cnet's support functions
- NAME
- Vector support functions.
- SYNOPSIS
#include <cnet.h>
#include <cnetsupport.h>
typedef void * VECTOR;
extern VECTOR vector_new(void);
extern void vector_free(VECTOR q);
extern void vector_append(VECTOR v, void *item, size_t len);
extern void vector_replace(VECTOR v, int position, void *item, size_t len);
extern void *vector_remove(VECTOR v, int position, size_t *len);
extern void *vector_peek(VECTOR v, int position, size_t *len);
extern int vector_nitems(VECTOR v);
- DESCRIPTION
-
It is a very common requirement of network protocols to manage a vector
of heterogenous-sized items.
These functions support the maintenance of vectors of arbitrary data.
Each data item may be of a different datatype and a different size and, thus,
these functions should not be used in preference to a standard array in C.
A cnet node may have an unlimited number of such vectors.
A new vector is firstly allocated by calling vector_new,
and should eventually be deallocated with a call to vector_free.
The opaque value returned by vector_new should be passed to all
other functions, to identify which vector is being used.
Items, of any datatype and length,
may be appended to a vector with vector_append.
The functions do not know what they are storing,
and so you must also provide the length, in bytes, of each appended item.
A copy is made of all items appended to a vector.
The number of items in a vector may be determined at any time
by calling vector_nitems.
The first item in a vector is in position 0.
An existing item in a vector may be replaced by a new item
by calling vector_replace and providing the new length.
Removing an item from a vector returns a pointer to the
previously allocated copy, which you should use and, eventually, free.
All remaining items in the vector "slide-down" by one position to fill the
hole created by the removal.
Peeking at any item of a vector does not remove the item.
- EXAMPLE
- A typical use of these functions is:
VECTOR myv;
MYTYPE1 mydata1, *myptr1;
MYTYPE2 mydata2, *myptr2;
size_t len;
int n;
myv = vector_new();
vector_append(myv, &mydata1, sizeof(mydata1));
.....
vector_append(myv, &mydata2, sizeof(mydata2));
.....
n = vector_nitems(myv);
while(n > 0) {
(void)vector_peek(myv, 0, &len);
if(len == sizeof(mydata1)) {
myptr1 = vector_remove(myv, 0, &len);
.....
free(myptr1);
}
else {
myptr2 = vector_remove(myv, 0, &len);
.....
free(myptr2);
}
--n;
}
.....
vector_free(myv);
|