You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

arraylist.c 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * $Id: arraylist.c,v 1.4 2006/01/26 02:16:28 mclark Exp $
  3. *
  4. * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
  5. * Michael Clark <michael@metaparadigm.com>
  6. *
  7. * This library is free software; you can redistribute it and/or modify
  8. * it under the terms of the MIT license. See COPYING for details.
  9. *
  10. */
  11. #include "config.h"
  12. #if STDC_HEADERS
  13. # include <stdlib.h>
  14. # include <string.h>
  15. #endif /* STDC_HEADERS */
  16. #if defined HAVE_STRINGS_H && !defined _STRING_H && !defined __USE_BSD
  17. # include <strings.h>
  18. #endif /* HAVE_STRINGS_H */
  19. #include "bits.h"
  20. #include "arraylist.h"
  21. struct array_list*
  22. array_list_new(array_list_free_fn *free_fn)
  23. {
  24. struct array_list *arr;
  25. arr = (struct array_list*)calloc(1, sizeof(struct array_list));
  26. if(!arr) return NULL;
  27. arr->size = ARRAY_LIST_DEFAULT_SIZE;
  28. arr->length = 0;
  29. arr->free_fn = free_fn;
  30. if(!(arr->array = (void**)calloc(sizeof(void*), arr->size))) {
  31. free(arr);
  32. return NULL;
  33. }
  34. return arr;
  35. }
  36. extern void
  37. array_list_free(struct array_list *arr)
  38. {
  39. int i;
  40. for(i = 0; i < arr->length; i++)
  41. if(arr->array[i]) arr->free_fn(arr->array[i]);
  42. free(arr->array);
  43. free(arr);
  44. }
  45. void*
  46. array_list_get_idx(struct array_list *arr, int i)
  47. {
  48. if(i >= arr->length) return NULL;
  49. return arr->array[i];
  50. }
  51. static int array_list_expand_internal(struct array_list *arr, int max)
  52. {
  53. void *t;
  54. int new_size;
  55. if(max < arr->size) return 0;
  56. new_size = json_max(arr->size << 1, max);
  57. if(!(t = realloc(arr->array, new_size*sizeof(void*)))) return -1;
  58. arr->array = (void**)t;
  59. (void)memset(arr->array + arr->size, 0, (new_size-arr->size)*sizeof(void*));
  60. arr->size = new_size;
  61. return 0;
  62. }
  63. int
  64. array_list_put_idx(struct array_list *arr, int idx, void *data)
  65. {
  66. if(array_list_expand_internal(arr, idx)) return -1;
  67. if(arr->array[idx]) arr->free_fn(arr->array[idx]);
  68. arr->array[idx] = data;
  69. if(arr->length <= idx) arr->length = idx + 1;
  70. return 0;
  71. }
  72. int
  73. array_list_add(struct array_list *arr, void *data)
  74. {
  75. return array_list_put_idx(arr, arr->length, data);
  76. }
  77. int
  78. array_list_length(struct array_list *arr)
  79. {
  80. return arr->length;
  81. }