dynarray.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #ifndef DYNARRAY_H
  2. #define DYNARRAY_H
  3. #include <stddef.h>
  4. /* simple dynamic array of pointers */
  5. typedef struct {
  6. int count;
  7. int capacity;
  8. void** items;
  9. } dynarray_t;
  10. #define DYNARRAY_INITIALIZER { 0, 0, NULL }
  11. void dynarray_init( dynarray_t *a );
  12. void dynarray_done( dynarray_t *a );
  13. void dynarray_append( dynarray_t *a, void* item );
  14. /* Used to iterate over a dynarray_t
  15. * _array :: pointer to the array
  16. * _item_type :: type of objects pointed to by the array
  17. * _item :: name of a local variable defined within the loop
  18. * with type '_item_type'
  19. * _stmnt :: C statement that will be executed in each iteration.
  20. *
  21. * You case use 'break' and 'continue' within _stmnt
  22. *
  23. * This macro is only intended for simple uses. I.e. do not add or
  24. * remove items from the array during iteration.
  25. */
  26. #define DYNARRAY_FOREACH_TYPE(_array,_item_type,_item,_stmnt) \
  27. do { \
  28. int _nn_##__LINE__ = 0; \
  29. for (;_nn_##__LINE__ < (_array)->count; ++ _nn_##__LINE__) { \
  30. _item_type _item = (_item_type)(_array)->items[_nn_##__LINE__]; \
  31. _stmnt; \
  32. } \
  33. } while (0)
  34. #define DYNARRAY_FOREACH(_array,_item,_stmnt) \
  35. DYNARRAY_FOREACH_TYPE(_array,void *,_item,_stmnt)
  36. /* Simple dynamic string arrays
  37. *
  38. * NOTE: A strlist_t owns the strings it references.
  39. */
  40. typedef dynarray_t strlist_t;
  41. #define STRLIST_INITIALIZER DYNARRAY_INITIALIZER
  42. /* Used to iterate over a strlist_t
  43. * _list :: pointer to strlist_t object
  44. * _string :: name of local variable name defined within the loop with
  45. * type 'char*'
  46. * _stmnt :: C statement executed in each iteration
  47. *
  48. * This macro is only intended for simple uses. Do not add or remove items
  49. * to/from the list during iteration.
  50. */
  51. #define STRLIST_FOREACH(_list,_string,_stmnt) \
  52. DYNARRAY_FOREACH_TYPE(_list,char *,_string,_stmnt)
  53. void strlist_init( strlist_t *list );
  54. /* note: strlist_done will free all the strings owned by the list */
  55. void strlist_done( strlist_t *list );
  56. /* append a new string made of the first 'slen' characters from 'str'
  57. * followed by a trailing zero.
  58. */
  59. void strlist_append_b( strlist_t *list, const void* str, size_t slen );
  60. /* append the copy of a given input string to a strlist_t */
  61. void strlist_append_dup( strlist_t *list, const char *str);
  62. /* sort the strings in a given list (using strcmp) */
  63. void strlist_sort( strlist_t *list );
  64. #endif /* DYNARRAY_H */