ArrayList.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #define ArrayList_NOCREATE
  16. #include "util/ArrayList.h"
  17. #include "util/Bits.h"
  18. #include <stddef.h>
  19. struct ArrayList_pvt
  20. {
  21. /** AckTung: The fields in ArrayList.h (struct ArrayList_NAME) must be reflected here first. */
  22. int length;
  23. int capacity;
  24. void** elements;
  25. struct Allocator* alloc;
  26. Identity
  27. };
  28. void* ArrayList_new(struct Allocator* alloc, int initialCapacity)
  29. {
  30. struct ArrayList_pvt* l = Allocator_calloc(alloc, sizeof(struct ArrayList_pvt), 1);
  31. l->elements = Allocator_calloc(alloc, sizeof(char*), initialCapacity);
  32. l->capacity = initialCapacity;
  33. l->alloc = alloc;
  34. Identity_set(l);
  35. return l;
  36. }
  37. void* ArrayList_get(void* vlist, int number)
  38. {
  39. struct ArrayList_pvt* list = Identity_check((struct ArrayList_pvt*) vlist);
  40. if (number >= list->length || number < 0) { return NULL; }
  41. return list->elements[number];
  42. }
  43. void* ArrayList_shift(void* vlist)
  44. {
  45. struct ArrayList_pvt* list = Identity_check((struct ArrayList_pvt*) vlist);
  46. if (!list->length) { return NULL; }
  47. void* out = list->elements[0];
  48. list->length--;
  49. if (list->length) {
  50. Bits_memmove(list->elements, &list->elements[1], sizeof(char*) * list->length);
  51. }
  52. return out;
  53. }
  54. int ArrayList_put(void* vlist, int number, void* val)
  55. {
  56. struct ArrayList_pvt* list = Identity_check((struct ArrayList_pvt*) vlist);
  57. Assert_true(number >= 0 && number <= list->length);
  58. if (number >= list->capacity) {
  59. int capacity = list->capacity * 2;
  60. list->elements = Allocator_realloc(list->alloc, list->elements, capacity * sizeof(char*));
  61. for (int i = list->capacity; i < capacity; i++) {
  62. list->elements[i] = NULL;
  63. }
  64. list->capacity = capacity;
  65. }
  66. list->elements[number] = val;
  67. if (number == list->length) { list->length++; }
  68. return number;
  69. }