PageRenderTime 35ms CodeModel.GetById 22ms app.highlight 9ms RepoModel.GetById 2ms app.codeStats 0ms

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