>From 4619425201df9693793c38e0236114ea15319f91 Mon Sep 17 00:00:00 2001
From: Dmitri Pal <dpal@redhat.com>
Date: Sat, 24 Oct 2009 21:37:08 -0400
Subject: [PATCH] [REF ARRAY] Adding a dynamic array object with reference count

For now it is a specific object used by ELAPI.
It can be made more generic in future.
But this is not the goal for now.
For now it will serve a specific purpose in ELAPI
and will help with easier access to sink chains when
the events are processed asynchroniously.

In future it can be enhanced. The following functions
might be added:
* Update array element
* Remove array element
* Insert array element
Then it can become a separate interface and be moved
under common. We will see.
---
 common/elapi/refarray/Makefile.am     |   36 ++++
 common/elapi/refarray/configure.ac    |   27 +++
 common/elapi/refarray/ref_array.c     |  311 +++++++++++++++++++++++++++++++++
 common/elapi/refarray/ref_array.h     |   68 +++++++
 common/elapi/refarray/ref_array.pc.in |   11 ++
 common/elapi/refarray/ref_array_ut.c  |  228 ++++++++++++++++++++++++
 6 files changed, 681 insertions(+), 0 deletions(-)
 create mode 100644 common/elapi/refarray/Makefile.am
 create mode 100644 common/elapi/refarray/configure.ac
 create mode 100644 common/elapi/refarray/m4/.dir
 create mode 100644 common/elapi/refarray/ref_array.c
 create mode 100644 common/elapi/refarray/ref_array.h
 create mode 100644 common/elapi/refarray/ref_array.pc.in
 create mode 100644 common/elapi/refarray/ref_array_ut.c

diff --git a/common/elapi/refarray/Makefile.am b/common/elapi/refarray/Makefile.am
new file mode 100644
index 0000000..36926fa
--- /dev/null
+++ b/common/elapi/refarray/Makefile.am
@@ -0,0 +1,36 @@
+TRACE_LEVEL=@TRACE_VAR@
+
+topdir=$(srcdir)/../..
+
+AM_CFLAGS =
+
+if HAVE_GCC
+    AM_CFLAGS += \
+        -Wall -Wshadow -Wstrict-prototypes -Wpointer-arith -Wcast-qual \
+        -Wcast-align -Wwrite-strings
+endif
+
+AM_CPPFLAGS = -I$(topdir)/trace -I$(topdir)/elapi/refarray $(TRACE_LEVEL)
+
+ACLOCAL_AMFLAGS = -I m4
+
+# Set up the pkg-config file
+pkgconfigdir = $(libdir)/pkgconfig
+dist_noinst_DATA = \
+    ref_array.pc \
+    m4
+
+# Build library
+noinst_LTLIBRARIES = libref_array.la
+libref_array_la_SOURCES = \
+    ref_array.c \
+    ref_array.h
+
+# Build unit test
+check_PROGRAMS = ref_array_ut
+ref_array_ut_SOURCES = ref_array_ut.c
+ref_array_ut_LDADD = libref_array.la
+
+TESTS = ref_array_ut
+
+tests: all $(check_PROGRAMS)
diff --git a/common/elapi/refarray/configure.ac b/common/elapi/refarray/configure.ac
new file mode 100644
index 0000000..ba10daf
--- /dev/null
+++ b/common/elapi/refarray/configure.ac
@@ -0,0 +1,27 @@
+AC_INIT([refarray],[0.0.1],[sssd-devel@lists.fedorahosted.org])
+AC_CONFIG_SRCDIR([ref_array.c])
+AC_CONFIG_AUX_DIR([build])
+AM_INIT_AUTOMAKE([-Wall -Werror foreign])
+AC_PROG_CC
+AC_PROG_LIBTOOL
+AC_CONFIG_MACRO_DIR([m4])
+AC_PROG_INSTALL
+
+AM_CONDITIONAL([HAVE_GCC], [test "$ac_cv_prog_gcc" = yes])
+
+m4_pattern_allow([AM_SILENT_RULES])
+AM_SILENT_RULES
+
+AC_CONFIG_HEADERS([config.h])
+
+# Enable trace build
+AC_ARG_ENABLE([trace],
+              [AS_HELP_STRING([--enable-trace[=LEVEL]],[build with low level tracing enabled])],
+              [trace_level="$enableval"],
+              [trace_level="0"])
+
+AS_IF([test ["$trace_level" -gt "0"] -a ["$trace_level" -lt "8"] ],[AC_SUBST([TRACE_VAR],["-DTRACE_LEVEL=$trace_level"])])
+
+AC_CONFIG_FILES([Makefile ref_array.pc])
+
+AC_OUTPUT
diff --git a/common/elapi/refarray/m4/.dir b/common/elapi/refarray/m4/.dir
new file mode 100644
index 0000000..e69de29
diff --git a/common/elapi/refarray/ref_array.c b/common/elapi/refarray/ref_array.c
new file mode 100644
index 0000000..987a83a
--- /dev/null
+++ b/common/elapi/refarray/ref_array.c
@@ -0,0 +1,311 @@
+/*
+    REF ARRAY
+
+    Implementation of the dynamic array with reference count.
+
+    Copyright (C) Dmitri Pal <dpal@redhat.com> 2009
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 3 of the License, or
+    (at your option) any later version.
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#define _GNU_SOURCE
+#include <errno.h>  /* for errors */
+#include <stdint.h>
+#include <malloc.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "ref_array.h"
+#include "config.h"
+#include "trace.h"
+
+/* The structure used in referenced array */
+struct ref_array {
+    void *storage;      /* The storage buffer */
+    size_t elsize;      /* Size of one element in the buffer */
+    uint32_t size;      /* Size of the storage in items */
+    uint32_t grow_by;   /* What increment use to reallocate memory */
+    uint32_t len;       /* Number of the elements in the array */
+    uint32_t refcount;  /* Reference count */
+};
+
+/****************************************************/
+/* INTERNAL FUNCTIONS                               */
+/****************************************************/
+static int ref_array_grow(struct ref_array *ra)
+{
+    int error = EOK;
+    void *newbuf = NULL;
+
+    TRACE_FLOW_STRING("ref_array_grow", "Entry");
+
+    TRACE_INFO_NUMBER("Current length: ", ra->len);
+    TRACE_INFO_NUMBER("Current size: ", ra->size);
+
+    /* Grow buffer if needed */
+    newbuf = realloc(ra->storage, (ra->size + ra->grow_by) * ra->elsize);
+    if (newbuf == NULL) {
+        TRACE_ERROR_NUMBER("Failed to allocate memory.", ENOMEM);
+        return ENOMEM;
+    }
+
+    ra->storage = newbuf;
+    ra->size += ra->grow_by;
+
+    TRACE_INFO_NUMBER("Final size: ", ra->size);
+    TRACE_FLOW_NUMBER("elapi_grow_data. Exit. Returning", error);
+    return error;
+
+}
+
+
+/****************************************************/
+/* PUBLIC FUNCTIONS                                 */
+/****************************************************/
+
+/* Create referenced array */
+int ref_array_create(struct ref_array **ra,
+                     size_t elemsz,
+                     uint32_t grow_by)
+{
+    struct ref_array *new_ra = NULL;
+
+    TRACE_FLOW_STRING("ref_array_create", "Entry");
+
+    if (!ra) {
+        TRACE_ERROR_NUMBER("Uninitialized argument.", EINVAL);
+        return EINVAL;
+    }
+
+    new_ra = (struct ref_array *)malloc(sizeof(struct ref_array));
+
+    if (!new_ra) {
+        TRACE_ERROR_NUMBER("Failed to allocate memory.", ENOMEM);
+        return ENOMEM;
+    }
+
+    new_ra->storage = NULL;
+    new_ra->elsize = elemsz;
+    new_ra->size = 0;
+    new_ra->grow_by = grow_by;
+    new_ra->len = 0;
+    new_ra->refcount = 1;
+
+    *ra = new_ra;
+
+    TRACE_FLOW_STRING("ref_array_create", "Exit");
+    return EOK;
+}
+
+/* Get new reference to an array */
+struct ref_array *ref_array_getref(struct ref_array *ra)
+{
+    TRACE_FLOW_STRING("ref_array_getref", "Entry");
+
+    /* Check if array is not NULL */
+    if (ra) {
+        TRACE_INFO_NUMBER("Increasing reference count. Current: ", ra->refcount);
+        /* Increase reference count */
+        ra->refcount++;
+        TRACE_INFO_NUMBER("Increased reference count. New: ", ra->refcount);
+
+    }
+    else {
+        TRACE_ERROR_STRING("Uninitialized array.", "Returning NULL");
+    }
+
+    TRACE_FLOW_STRING("ref_array_getref", "Exit");
+    return ra;
+}
+
+/* Delete the array */
+void ref_array_destroy(struct ref_array *ra)
+{
+    TRACE_FLOW_STRING("ref_array_destroy", "Entry");
+
+    /* Check if array is not NULL */
+    if (ra) {
+        TRACE_INFO_NUMBER("Current reference count: ", ra->refcount);
+        if (ra->refcount) {
+            /* Decrease reference count */
+            ra->refcount--;
+            if (ra->refcount == 0) {
+                TRACE_INFO_NUMBER("It is time to delete array. Count:", ra->refcount);
+                free(ra->storage);
+                free(ra);
+            }
+        }
+        else {
+            /* Should never be here */
+            TRACE_ERROR_STRING("Reference count is 0.", "Coding error???");
+        }
+    }
+    else {
+        TRACE_ERROR_STRING("Uninitialized array.", "Coding error???");
+    }
+
+    TRACE_FLOW_STRING("ref_array_destroy", "Exit");
+}
+
+/* Add new element to the array */
+int ref_array_append(struct ref_array *ra, void *element)
+{
+    int error = EOK;
+
+    TRACE_FLOW_STRING("ref_array_append", "Entry");
+    if ((!ra) || (!element)) {
+        TRACE_ERROR_NUMBER("Uninitialized argument.", EINVAL);
+        return EINVAL;
+    }
+
+    /* Do we have enough room for a new element? */
+    if (ra->size == ra->len) {
+        error = ref_array_grow(ra);
+        if (error) {
+            TRACE_ERROR_NUMBER("Failed to grow array.", error);
+            return EINVAL;
+        }
+    }
+
+    /* Copy element */
+    memcpy((unsigned char *)(ra->storage) + ra->len * ra->elsize,
+           element,
+           ra->elsize);
+
+    ra->len++;
+
+    TRACE_FLOW_STRING("ref_array_append", "Exit");
+    return error;
+}
+
+/* Get element */
+void *ref_array_get(struct ref_array *ra, uint32_t idx, void *acptr)
+{
+    TRACE_FLOW_STRING("ref_array_get", "Entry");
+
+    if (!ra) {
+        TRACE_ERROR_STRING("Uninitialized argument.", "");
+        return NULL;
+    }
+
+    if (idx >= ra->len) {
+        TRACE_ERROR_NUMBER("Invalid idx.", idx);
+        return NULL;
+    }
+
+    TRACE_INFO_NUMBER("Index: ", idx);
+
+    if (acptr) {
+
+        TRACE_INFO_STRING("Copying data.", "");
+        memcpy(acptr,
+               (unsigned char *)(ra->storage) + idx * ra->elsize,
+               ra->elsize);
+
+    }
+
+    TRACE_FLOW_STRING("ref_array_get retuning internal storage", "Exit");
+    return (unsigned char *)(ra->storage) + idx * ra->elsize;
+}
+
+/* Move to next */
+void *ref_array_next(struct ref_array *ra, uint32_t *idx, void *acptr)
+{
+    TRACE_FLOW_STRING("ref_array_next", "Entry");
+
+    if ((!ra) || (!idx)) {
+        TRACE_ERROR_STRING("Uninitialized argument.", "");
+        return NULL;
+    }
+
+    if ((*idx) >= (ra->len - 1)) {
+        TRACE_ERROR_NUMBER("Invalid idx.", idx);
+        return NULL;
+    }
+
+    (*idx)++;
+
+    if (acptr) {
+
+        memcpy(acptr,
+               (unsigned char *)(ra->storage) + (*idx) * ra->elsize,
+               ra->elsize);
+
+    }
+
+    TRACE_FLOW_STRING("ref_array_next retuning internal storage", "Exit");
+    return (unsigned char *)(ra->storage) + (*idx) * ra->elsize;
+}
+
+/* Move to previous */
+void *ref_array_prev(struct ref_array *ra, uint32_t *idx, void *acptr)
+{
+    TRACE_FLOW_STRING("ref_array_prev", "Entry");
+
+    if ((!ra) || (!idx)) {
+        TRACE_ERROR_STRING("Uninitialized argument.", "");
+        return NULL;
+    }
+
+    if (((*idx) >= ra->len) || (*idx == 0)) {
+        TRACE_ERROR_NUMBER("Invalid idx.", idx);
+        return NULL;
+    }
+
+    (*idx)--;
+
+    if (acptr) {
+
+        memcpy(acptr,
+               (unsigned char *)(ra->storage) + (*idx) * ra->elsize,
+               ra->elsize);
+
+    }
+
+    TRACE_FLOW_STRING("ref_array_prev retuning internal storage", "Exit");
+    return (unsigned char *)(ra->storage) + (*idx) * ra->elsize;
+}
+
+/* Get length */
+uint32_t ref_array_len(struct ref_array *ra)
+{
+    TRACE_FLOW_STRING("ref_array_len", "Entry");
+
+    if (!ra) {
+        TRACE_ERROR_STRING("Uninitialized argument.", "");
+        return 0;
+    }
+
+    TRACE_FLOW_STRING("ref_array_len", "Exit");
+    return ra->len;
+}
+
+/* Gedug function */
+void ref_array_debug(struct ref_array *ra)
+{
+    int i,j;
+
+    printf("\nARRAY DUMP START\n");
+    printf("Length = %d\n", ra->len);
+    printf("Size = %d\n", ra->size);
+    printf("Element = %d\n", ra->elsize);
+    printf("Grow by = %d\n", ra->grow_by);
+    printf("Count = %d\n", ra->refcount);
+    printf("ARRAY:\n");
+    for (i = 0; i < ra->len; i++)  {
+        for (j = 0; j < ra->elsize; j++) {
+            printf("%x", *((unsigned char *)(ra->storage) + i * ra->elsize + j));
+        }
+        printf("\n%s\n", *((char **)((unsigned char *)(ra->storage) + i * ra->elsize)));
+    }
+    printf("\nARRAY DUMP END\n\n");
+}
diff --git a/common/elapi/refarray/ref_array.h b/common/elapi/refarray/ref_array.h
new file mode 100644
index 0000000..d9efce5
--- /dev/null
+++ b/common/elapi/refarray/ref_array.h
@@ -0,0 +1,68 @@
+/*
+    REF ARRAY
+
+    Header file for of the dynamic array with reference count.
+
+    Copyright (C) Dmitri Pal <dpal@redhat.com> 2009
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 3 of the License, or
+    (at your option) any later version.
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef REF_ARRAY_H
+#define REF_ARRAY_H
+
+#include <stdint.h>
+#include <stdlib.h>
+
+struct ref_array;
+
+#ifndef EOK
+#define EOK 0
+#endif
+
+/*************************************/
+/* Interface to the referenced array */
+/*************************************/
+
+/* Create referenced array */
+int ref_array_create(struct ref_array **ra,
+                     size_t elem,
+                     uint32_t grow_by);
+
+/* Get new reference to an array */
+struct ref_array *ref_array_getref(struct ref_array *ra);
+
+/* Delete the array */
+void ref_array_destroy(struct ref_array *ra);
+
+/* Add new element to the array */
+int ref_array_append(struct ref_array *ra, void *element);
+
+/* Get element */
+void *ref_array_get(struct ref_array *ra, uint32_t idx, void *acptr);
+
+/* Move to next */
+void *ref_array_next(struct ref_array *ra, uint32_t *idx, void *acptr);
+
+/* Move to previous */
+void *ref_array_prev(struct ref_array *ra, uint32_t *idx, void *acptr);
+
+/* Get array length */
+uint32_t ref_array_len(struct ref_array *ra);
+
+/* In future in might make sense to add entry points
+ * to insert and delete elements from the array.
+ * Current use cases do not require this kind of
+ * functionality so it is left out of the implementation
+ */
+
+#endif
diff --git a/common/elapi/refarray/ref_array.pc.in b/common/elapi/refarray/ref_array.pc.in
new file mode 100644
index 0000000..1fc06f7
--- /dev/null
+++ b/common/elapi/refarray/ref_array.pc.in
@@ -0,0 +1,11 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: @PACKAGE_NAME@
+Description: Reference library
+Version: @PACKAGE_VERSION@
+Libs: -L${libdir} -lref_array
+Cflags: -I${includedir}
+URL: http://fedorahosted.org/sssd/
diff --git a/common/elapi/refarray/ref_array_ut.c b/common/elapi/refarray/ref_array_ut.c
new file mode 100644
index 0000000..304eddb
--- /dev/null
+++ b/common/elapi/refarray/ref_array_ut.c
@@ -0,0 +1,228 @@
+/*
+    REF ARRAY
+
+    Implementation of the dynamic array with reference count.
+
+    Copyright (C) Dmitri Pal <dpal@redhat.com> 2009
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 3 of the License, or
+    (at your option) any later version.
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#define _GNU_SOURCE
+#include <errno.h>  /* for errors */
+#include <stdint.h>
+#include <stdio.h>
+
+#include "ref_array.h"
+#include "config.h"
+#define TRACE_HOME
+#include "trace.h"
+
+extern void ref_array_debug(struct ref_array *ra);
+
+typedef int (*test_fn)(void);
+
+/* Basic test */
+int ref_array_basic_test(void)
+{
+    const char *line1 = "line1";
+    const char *line2 = "line2";
+    const char *line3 = "line3";
+    const char *line4 = "line4";
+    const char *line5 = "line5";
+    const char *line6 = "line6";
+    uint32_t i;
+    struct ref_array *ra;
+    struct ref_array *ra2;
+    int error = EOK;
+    uint32_t len;
+    char *ret;
+    void *ptr;
+
+    error = ref_array_create(&ra, sizeof(char *), 1);
+    if (error) {
+        printf("Failed to create array %d\n", error);
+        return error;
+    }
+
+    ref_array_debug(ra);
+
+    error = ref_array_append(ra, &line1);
+    if (error) {
+        ref_array_destroy(ra);
+        printf("Failed to append to array line 1 %d\n", error);
+        return error;
+    }
+
+    ref_array_debug(ra);
+
+    error = ref_array_append(ra, &line2);
+    if (error) {
+        ref_array_destroy(ra);
+        printf("Failed to append to array line 2 %d\n", error);
+        return error;
+    }
+
+    ref_array_debug(ra);
+
+    error = ref_array_append(ra, &line3);
+    if (error) {
+        ref_array_destroy(ra);
+        printf("Failed to append to array line 3 %d\n", error);
+        return error;
+    }
+
+    ref_array_debug(ra);
+
+    error = ref_array_append(ra, &line4);
+    if (error) {
+        ref_array_destroy(ra);
+        printf("Failed to append to array line 4 %d\n", error);
+        return error;
+    }
+
+    ref_array_debug(ra);
+
+    error = ref_array_append(ra, &line5);
+    if (error) {
+        ref_array_destroy(ra);
+        printf("Failed to append to array line 5 %d\n", error);
+        return error;
+    }
+
+    ref_array_debug(ra);
+
+    error = ref_array_append(ra, &line6);
+    if (error) {
+        ref_array_destroy(ra);
+        printf("Failed to append to array line 6 %d\n", error);
+        return error;
+    }
+
+    ref_array_debug(ra);
+
+    printf("\n\nTest 1 - Printing lines.\n\n");
+
+    len = ref_array_len(ra);
+    for (i = 0; i < len; i++) {
+        ref_array_get(ra, i, &ret);
+        printf("%s\n", ret);
+    }
+
+    printf("\n\nTest 2 - Creating reference and then printing lines.\n\n");
+
+    ra2 = ref_array_getref(ra);
+    ref_array_destroy(ra);
+
+    for (i = 0; i < len; i++) {
+        ret = *((char **)ref_array_get(ra2, i, NULL));
+        printf("%s\n", ret);
+    }
+
+    printf("\n\nTest 3 - Get elements with copying.\n\n");
+
+    for (i = 0; i < len; i++) {
+        ref_array_get(ra2, i, &ret);
+        printf("%s\n", ret);
+    }
+
+    printf("\n\nTest 4 - Get elements with copying and assignement.\n\n");
+
+    for (i = 0; i < len; i++) {
+        ret = *((char **)ref_array_get(ra2, i, &ret));
+        printf("%s\n", ret);
+    }
+
+    printf("\n\nTest 5 - While loop up.\n\n");
+
+    i = 0;
+    for (;;) {
+        ptr = ref_array_get(ra2, i, &ret);
+        if (ptr) {
+            printf("%s\n", ret);
+            i++;
+        }
+        else break;
+    }
+
+    printf("\n\nTest 6 - While loop down.\n\n");
+
+    i = len - 1;
+    for (;;) {
+        ptr = ref_array_get(ra2, i, &ret);
+        if (ptr) {
+            printf("%s\n", ret);
+            i--;
+        }
+        else break;
+    }
+
+    printf("\n\nTest 7 - Get first and then advance.\n\n");
+
+    i = 0;
+    ptr = ref_array_get(ra2, i, &ret);
+    if (ptr) {
+        printf("%s\n", ret);
+    }
+    else {
+        printf("Failed to get value.\n");
+        return EINVAL;
+    }
+
+    while ((ptr = ref_array_next(ra2, &i, &ret)) != NULL) {
+        printf("%s\n", ret);
+    }
+
+    printf("\n\nTest 8 - Get last and then move back.\n\n");
+
+    i = len - 1;
+    ptr = ref_array_get(ra2, i, &ret);
+    if (ptr) {
+        printf("%s\n", ret);
+    }
+    else {
+        printf("Failed to get value.\n");
+        return EINVAL;
+    }
+
+    while ((ptr = ref_array_prev(ra2, &i, &ret)) != NULL) {
+        printf("%s\n", ret);
+    }
+
+    printf("\n\nDone!!!\n\n");
+
+    ref_array_destroy(ra2);
+    return EOK;
+}
+
+/* Main function of the unit test */
+int main(int argc, char *argv[])
+{
+    int error = 0;
+    test_fn tests[] = { ref_array_basic_test,
+                        NULL };
+    test_fn t;
+    int i = 0;
+
+    printf("Start\n");
+
+    while ((t = tests[i++])) {
+        error = t();
+        if (error) {
+            printf("Failed!\n");
+            return error;
+        }
+    }
+
+    printf("Success!\n");
+    return 0;
+}
-- 
1.5.5.6

