Add print_array_stats()
[eleutheria.git] / proplib / prop_expand.c
blobaeaa1316505102669e4e6cc6d038dcff7e030949
1 #include <err.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <prop/proplib.h>
6 #define INIT_CAPACITY 10
7 #define NUM_STRINGS 32
8 #define PRINT_STEP 5 /* Print stats every 5 steps */
10 /* Function prototypes */
11 void print_array_stats(const prop_array_t pa);
13 int
14 main(int argc, char *argv[])
16 prop_array_t pa;
17 prop_string_t ps;
18 unsigned int i;
20 /*
21 * Create array object with initial capacity set to
22 * ``INIT_CAPACITY''. The array will expand on demand
23 * if its count exceeds its capacity.
24 * This happens in prop_array_add() with ``EXPAND_STEP''
25 * step, as defined in libprop/prop_array.c file.
27 pa = prop_array_create_with_capacity(INIT_CAPACITY);
28 if (pa == NULL)
29 errx(EXIT_FAILURE, "prop_array_create_with_capacity()");
31 /* Create prop_string_t object */
32 ps = prop_string_create_cstring("foo");
33 if (ps == NULL) {
34 prop_object_release(pa);
35 errx(EXIT_FAILURE, "prop_string_create_cstring()");
39 * Add up to ``NUM_STRINGS'' references of prop_string_t
40 * object to array and watch if/how the latter expands on demand.
42 for (i = 0; i < NUM_STRINGS; i++) {
43 /* Print statistics every ``PRINT_STEP'' step */
44 if (i % PRINT_STEP == 0)
45 print_array_stats(pa);
47 /* Add object reference in array */
48 if (prop_array_add(pa, ps) == FALSE) {
49 prop_object_release(pa);
50 prop_object_release(ps);
51 errx(EXIT_FAILURE, "prop_array_add()");
56 * Remove references from array and note that
57 * if an expansion has happened before, array's
58 * capacity won't reduce to its initial value,
59 * i.e. ``INIT_CAPACITY''
61 for (i = 0; i < NUM_STRINGS; i++) {
62 /* Print statistics every ``PRINT_STEP'' step */
63 if (i % PRINT_STEP == 0)
64 print_array_stats(pa);
66 prop_array_remove(pa, NUM_STRINGS - i - 1);
69 /* Release objects */
70 prop_object_release(pa);
71 prop_object_release(ps);
73 print_array_stats(pa);
75 return EXIT_SUCCESS;
78 void print_array_stats(const prop_array_t pa)
80 printf("count = %u\tcapacity = %u\n",
81 prop_array_count(pa),
82 prop_array_capacity(pa));