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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 HAVE_STRINGS_H
  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 *this;
  25. if(!(this = calloc(1, sizeof(struct array_list)))) return NULL;
  26. this->size = ARRAY_LIST_DEFAULT_SIZE;
  27. this->length = 0;
  28. this->free_fn = free_fn;
  29. if(!(this->array = calloc(sizeof(void*), this->size))) {
  30. free(this);
  31. return NULL;
  32. }
  33. return this;
  34. }
  35. extern void
  36. array_list_free(struct array_list *this)
  37. {
  38. int i;
  39. for(i = 0; i < this->length; i++)
  40. if(this->array[i]) this->free_fn(this->array[i]);
  41. free(this->array);
  42. free(this);
  43. }
  44. void*
  45. array_list_get_idx(struct array_list *this, int i)
  46. {
  47. if(i >= this->length) return NULL;
  48. return this->array[i];
  49. }
  50. static int array_list_expand_internal(struct array_list *this, int max)
  51. {
  52. void *t;
  53. int new_size;
  54. if(max < this->size) return 0;
  55. new_size = max(this->size << 1, max);
  56. if(!(t = realloc(this->array, new_size*sizeof(void*)))) return -1;
  57. this->array = t;
  58. (void)memset(this->array + this->size, 0, (new_size-this->size)*sizeof(void*));
  59. this->size = new_size;
  60. return 0;
  61. }
  62. int
  63. array_list_put_idx(struct array_list *this, int idx, void *data)
  64. {
  65. if(array_list_expand_internal(this, idx)) return -1;
  66. if(this->array[idx]) this->free_fn(this->array[idx]);
  67. this->array[idx] = data;
  68. if(this->length <= idx) this->length = idx + 1;
  69. return 0;
  70. }
  71. int
  72. array_list_add(struct array_list *this, void *data)
  73. {
  74. return array_list_put_idx(this, this->length, data);
  75. }
  76. int
  77. array_list_length(struct array_list *this)
  78. {
  79. return this->length;
  80. }

No Description

Contributors (1)