/src/rt/util/array_list.h

http://github.com/jruderman/rust · C Header · 114 lines · 92 code · 14 blank · 8 comment · 12 complexity · 5b362ef526df92c1cda361f86cfaa236 MD5 · raw file

  1. // -*- c++ -*-
  2. #ifndef ARRAY_LIST_H
  3. #define ARRAY_LIST_H
  4. #include <inttypes.h>
  5. #include <stddef.h>
  6. /**
  7. * A simple, resizable array list.
  8. */
  9. template<typename T> class array_list {
  10. static const size_t INITIAL_CAPACITY = 8;
  11. size_t _size;
  12. T * _data;
  13. size_t _capacity;
  14. public:
  15. array_list();
  16. ~array_list();
  17. size_t size();
  18. int32_t append(T value);
  19. int32_t push(T value);
  20. bool pop(T *value);
  21. bool replace(T old_value, T new_value);
  22. int32_t index_of(T value);
  23. bool is_empty();
  24. T* data();
  25. T & operator[](size_t index);
  26. };
  27. template<typename T>
  28. array_list<T>::array_list() {
  29. _size = 0;
  30. _capacity = INITIAL_CAPACITY;
  31. _data = (T *) malloc(sizeof(T) * _capacity);
  32. }
  33. template<typename T>
  34. array_list<T>::~array_list() {
  35. free(_data);
  36. }
  37. template<typename T> size_t
  38. array_list<T>::size() {
  39. return _size;
  40. }
  41. template<typename T> int32_t
  42. array_list<T>::append(T value) {
  43. return push(value);
  44. }
  45. template<typename T> int32_t
  46. array_list<T>::push(T value) {
  47. if (_size == _capacity) {
  48. _capacity = _capacity * 2;
  49. _data = (T *) realloc(_data, _capacity * sizeof(T));
  50. }
  51. _data[_size ++] = value;
  52. return _size - 1;
  53. }
  54. template<typename T> bool
  55. array_list<T>::pop(T *value) {
  56. if (_size == 0) {
  57. return false;
  58. }
  59. if (value != NULL) {
  60. *value = _data[-- _size];
  61. } else {
  62. -- _size;
  63. }
  64. return true;
  65. }
  66. /**
  67. * Replaces the old_value in the list with the new_value.
  68. * Returns the true if the replacement succeeded, or false otherwise.
  69. */
  70. template<typename T> bool
  71. array_list<T>::replace(T old_value, T new_value) {
  72. int index = index_of(old_value);
  73. if (index < 0) {
  74. return false;
  75. }
  76. _data[index] = new_value;
  77. return true;
  78. }
  79. template<typename T> int32_t
  80. array_list<T>::index_of(T value) {
  81. for (size_t i = 0; i < _size; i++) {
  82. if (_data[i] == value) {
  83. return i;
  84. }
  85. }
  86. return -1;
  87. }
  88. template<typename T> T &
  89. array_list<T>::operator[](size_t index) {
  90. return _data[index];
  91. }
  92. template<typename T> bool
  93. array_list<T>::is_empty() {
  94. return _size == 0;
  95. }
  96. template<typename T> T*
  97. array_list<T>::data() {
  98. return _data;
  99. }
  100. #endif /* ARRAY_LIST_H */