collection.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * collection.c
  3. *
  4. * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
  5. * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdio.h>
  27. #include "collection.h"
  28. void collection_init(struct collection *col)
  29. {
  30. col->list = malloc(sizeof(void *));
  31. memset(col->list, 0, sizeof(void *));
  32. col->capacity = 1;
  33. }
  34. void collection_free(struct collection *col)
  35. {
  36. free(col->list);
  37. col->list = NULL;
  38. col->capacity = 0;
  39. }
  40. void collection_add(struct collection *col, void *element)
  41. {
  42. int i;
  43. for(i=0; i<col->capacity; i++) {
  44. if(!col->list[i]) {
  45. col->list[i] = element;
  46. return;
  47. }
  48. }
  49. col->list = realloc(col->list, sizeof(void*) * col->capacity * 2);
  50. memset(&col->list[col->capacity], 0, sizeof(void *) * col->capacity);
  51. col->list[col->capacity] = element;
  52. col->capacity *= 2;
  53. }
  54. void collection_remove(struct collection *col, void *element)
  55. {
  56. int i;
  57. for(i=0; i<col->capacity; i++) {
  58. if(col->list[i] == element) {
  59. col->list[i] = NULL;
  60. return;
  61. }
  62. }
  63. fprintf(stderr, "%s: WARNING: element %p not present in collection %p (cap %d)", __func__, element, col, col->capacity);
  64. }
  65. int collection_count(struct collection *col)
  66. {
  67. int i, cnt = 0;
  68. for(i=0; i<col->capacity; i++) {
  69. if(col->list[i])
  70. cnt++;
  71. }
  72. return cnt;
  73. }