src/misc/smallvec.h
changeset 9335 4f1e59a9aed4
parent 9111 48ce04029fe4
child 9348 dc680f675138
equal deleted inserted replaced
9334:28ac6c8e0795 9335:4f1e59a9aed4
     1 /* $Id$ */
     1 /* $Id$ */
     2 
     2 
     3 /** @file smallvec.h Simple vector class that allows allocating an item without the need to copy data needlessly. */
     3 /** @file smallvec.h Simple vector class that allows allocating an item without the need to copy this->data needlessly. */
     4 
     4 
     5 #ifndef SMALLVEC_H
     5 #ifndef SMALLVEC_H
     6 #define SMALLVEC_H
     6 #define SMALLVEC_H
     7 
     7 
     8 template <typename T, uint S> struct SmallVector {
     8 template <typename T, uint S>
       
     9 struct SmallVector {
     9 	T *data;
    10 	T *data;
    10 	uint items;
    11 	uint items;
    11 	uint capacity;
    12 	uint capacity;
    12 
    13 
    13 	SmallVector() : data(NULL), items(0), capacity(0) { }
    14 	SmallVector() : data(NULL), items(0), capacity(0) { }
    14 
    15 
    15 	~SmallVector()
    16 	~SmallVector()
    16 	{
    17 	{
    17 		free(data);
    18 		free(this->data);
    18 	}
    19 	}
    19 
    20 
    20 	/**
    21 	/**
    21 	 * Append an item and return it.
    22 	 * Append an item and return it.
    22 	 */
    23 	 */
    23 	T *Append()
    24 	T *Append()
    24 	{
    25 	{
    25 		if (items == capacity) {
    26 		if (this->items == this->capacity) {
    26 			capacity += S;
    27 			this->capacity += S;
    27 			data = ReallocT(data, capacity);
    28 			this->data = ReallocT(this->data, this->capacity);
    28 		}
    29 		}
    29 
    30 
    30 		return &data[items++];
    31 		return &this->data[this->items++];
    31 	}
    32 	}
    32 
    33 
    33 	const T *Begin() const
    34 	const T *Begin() const
    34 	{
    35 	{
    35 		return data;
    36 		return this->data;
    36 	}
    37 	}
    37 
    38 
    38 	T *Begin()
    39 	T *Begin()
    39 	{
    40 	{
    40 		return data;
    41 		return this->data;
    41 	}
    42 	}
    42 
    43 
    43 	const T *End() const
    44 	const T *End() const
    44 	{
    45 	{
    45 		return &data[items];
    46 		return &this->data[this->items];
    46 	}
    47 	}
    47 
    48 
    48 	T *End()
    49 	T *End()
    49 	{
    50 	{
    50 		return &data[items];
    51 		return &this->data[this->items];
    51 	}
    52 	}
    52 
    53 
    53 	const T *Get(size_t index) const
    54 	const T *Get(uint index) const
    54 	{
    55 	{
    55 		return &data[index];
    56 		return &this->data[index];
    56 	}
    57 	}
    57 
    58 
    58 	T *Get(size_t index)
    59 	T *Get(uint index)
    59 	{
    60 	{
    60 		return &data[index];
    61 		return &this->data[index];
    61 	}
    62 	}
    62 };
    63 };
    63 
    64 
    64 #endif /* SMALLVEC_H */
    65 #endif /* SMALLVEC_H */