Various modules solving daily C developer tasks
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

133 lines
2.2 KiB

  1. /******************************************************************************
  2. *
  3. * Copyright (c) 2017-2019 by Löwenware Ltd
  4. * Please, refer LICENSE file for legal information
  5. *
  6. ******************************************************************************/
  7. /**
  8. * @file list.c
  9. * @author Ilja Kartašov <ik@lowenware.com>
  10. * @brief cStuff list module
  11. *
  12. * @see https://lowenware.com/
  13. */
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include "list.h"
  17. CStuffRetcode
  18. cstuff_list_init(CStuffList self, int size)
  19. {
  20. if (!(self->items = calloc(size, sizeof (void *))))
  21. return CSTUFF_MALLOC_ERROR;
  22. self->length = 0;
  23. self->size = size;
  24. return CSTUFF_SUCCESS;
  25. }
  26. void
  27. cstuff_list_release(CStuffList self, CStuffListFree item_free)
  28. {
  29. if (self->items) {
  30. if (item_free) {
  31. int i;
  32. for (i = 0; i < self->length; i++) {
  33. void *ptr = self->items[i];
  34. if (ptr) {
  35. item_free(ptr);
  36. }
  37. }
  38. }
  39. free(self->items);
  40. }
  41. }
  42. int
  43. cstuff_list_append(CStuffList self, void *item)
  44. {
  45. void **items;
  46. int size = self->length + 1;
  47. if (size > self->size) {
  48. if (!(items = realloc(self->items, size * sizeof (void*))))
  49. return -1;
  50. self->items = items;
  51. self->size = size;
  52. }
  53. self->items[self->length] = item;
  54. return self->length++;
  55. }
  56. int
  57. cstuff_list_insert(CStuffList self, void *item, int index)
  58. {
  59. int r;
  60. if ((r = cstuff_list_append(self, item)) == -1)
  61. return -1;
  62. if (index >= r || index < 0)
  63. return r;
  64. memmove(&self->items[index + 1], &self->items[index],
  65. (self->length - index - 1) * sizeof (void*));
  66. self->items[index] = item;
  67. return index;
  68. }
  69. void *
  70. cstuff_list_remove(CStuffList self, int index)
  71. {
  72. void *result;
  73. int i;
  74. if (index < self->length) {
  75. result = self->items[index];
  76. self->length--;
  77. for (i = index; i < self->length; i++) {
  78. self->items[i] = self->items[i + 1];
  79. }
  80. } else {
  81. result = NULL;
  82. }
  83. return result;
  84. }
  85. void
  86. cstuff_list_remove_item(CStuffList self, void *item)
  87. {
  88. int i;
  89. for (i = 0; i < self->length; i++) {
  90. if (self->items[i] == item) {
  91. cstuff_list_remove(self, i);
  92. break;
  93. }
  94. }
  95. }
  96. void
  97. cstuff_list_set_item(CStuffList self, int index, void *value)
  98. {
  99. if (self->size > index) {
  100. self->items[index] = value;
  101. if (index >= self->length)
  102. self->length = index + 1;
  103. }
  104. }