|
|
|
adx_util - Array Descriptor (ADX) UtilitiesThe ADX_UTIL package provides functions for creating and manipulating dynamically sized arrays of arbitrary, homogeneous (fixed-size) elements.
This package was inspired by my MDX_UTIL memory region descriptor package, which, in fact, did include the ability to treat a memory region as an array. However, the mechanisms for working with memory regions as arrays were awkward for the application using the package. Hopefully, ADX_UTIL improves on that front.
The following example reads a complete text file into an array of
SDX_UTIL string descriptors, one element per
line, a convenient framework for a simple text editor. Note
that the array is composed of pointers (StringDx) to string
descriptors (_StringDx), not an array of string descriptors
themselves.
#include "adx_util.h" -- Array Descriptor utilities.
#include "sdx_util.h" -- String Descriptor utilities.
FILE *file ;
ssize_t count ;
ArrayDx adx ;
StringDx *element41, sdx ;
adxCreate (0, sizeof (StringDx), NULL, 0, AdxDynamic, &adx) ;
file = fopen ("example.txt", "r") ;
for ( ; ; ) { -- Break on EOF or error.
sdxCreate (NULL, -1, SdxDynamic, &sdx) ;
if (sdxReadLine (file, sdx, &count) || (count < 1)) break ;
adxAdd (adx, (const void *) &sdx, 1, -1) ;
}
fclose (file) ;
Then, access line 20. Note the distinction between line numbers, 1..N, and their corresponding array indices, 0..N-1 — hence all the little "-1"s in the few lines of code below; e.g., line 20 is at index 20-1 = 19.
printf ("Line 20: \"%s\"\n",
sdxStringZ (*((StringDx) adxGet (adx, 20-1)))) ;
Next, insert a line between line 30 and line 31.
sdxCreate ("I'm the new line 31!!!", -1, SdxVolatile, &sdx) ;
adxAdd (adx, (const void *) &sdx, 1, 31-1) ;
Now, delete lines 41-45. Since the elements have dynamically allocated resources of their own, it is necessary to destroy or save the elements being deleted before actually deleting them from the array.
element41 = (StringDx *) adxGet (adx, 41-1) ;
-- Destroy descriptors being deleted
for (i = 0 ; i < 5 ; i++) { -- (or save them in cut/undo buffer).
sdxDestroy (element41[i]) ;
}
adxDelete (adx, 5, 41-1) ; -- Delete the 5 elements.
adxAdd() - adds one or more elements to a described array.adxCopy() - copy the contents of one array descriptor to another.adxCount() - gets the number of elements in a described array.adxCreate() - creates an array descriptor.adxDelete() - deletes one or more elements from a described array.adxDestroy() - destroys an array descriptor.adxDuplicate() - duplicates an array descriptor.adxElementSize() - gets the size in bytes of a described array's elements.adxErase() - erases the contents of an array descriptor.adxGet() - gets the address of an element in a described array.adxIncrement() - sets or gets the block size used to expand an array.adxOwn() - takes ownership of a described array.adx_util.c
adx_util.h
(See libgpl
for the complete source, including support routines and build files.)