comparison src/basic/SmallArray.d @ 206:d3c148ca429b

Major moving of files. all src now goes into src, all docs in docs.
author Anders Johnsen <skabet@gmail.com>
date Tue, 12 Aug 2008 18:14:56 +0200
parents
children e0551773a005
comparison
equal deleted inserted replaced
205:8387cbaa85ab 206:d3c148ca429b
1 module basic.SmallArray;
2
3 /**
4 This struct acts like a normal dynamic array, with one difference.
5 A size is given, which is how many elements are preallocated on the stack.
6
7 Example:
8 --------
9 SmallArray!(float, 4) array;
10 array ~= 1.0;
11 array ~= 2.0;
12 array ~= 3.0;
13 float[] three_floats = array[0 .. 3];
14 // The slice gives a reference to the stack, remember to .dup
15 array ~= 4.0;
16 // not using the heap yet, but after the next line all values will have been
17 // copied to the heap.
18 array ~= 5.0;
19 --------
20
21 Compared to a normal dynamic array there is 8 bytes overhead (on 32 bit cpus)
22 and ofcourse size * T.sizeof bytes for the stack allocated array.
23 */
24 struct SmallArray(T, ubyte size = 8)
25 {
26 T[] opSlice(size_t low, size_t high)
27 {
28 assert(high <= len && low <= high, "Array index out of range");
29 return ptr[low .. high];
30 }
31
32 T[] opSlice()
33 {
34 return ptr[0 .. len];
35 }
36 alias opSlice unsafe;
37
38 T[] safe()
39 {
40 if (len <= size)
41 return static_array[0 .. len].dup;
42 return array[0 .. len];
43 }
44
45 T[] opSliceAssign(T val, size_t low, size_t high)
46 {
47 assert(high <= len && low <= high, "Array index out of range");
48 return ptr[low .. high] = val;
49 }
50
51 T[] opSliceAssign(T val)
52 {
53 return ptr[0 .. len] = val;
54 }
55
56 T opIndex(size_t index)
57 {
58 assert(index < len, "Array index out of range");
59 return ptr[index];
60 }
61
62 T opIndexAssign(T val, size_t index)
63 {
64 assert(index < len, "Array index out of range");
65 return ptr[index] = val;
66 }
67
68 void opCatAssign(T val)
69 {
70 if (len < size)
71 static_array[len] = val;
72 else if (len == size)
73 {
74 T[] tmp = static_array[].dup;
75 array = tmp;
76 array ~= val;
77 }
78 else
79 array ~= val;
80
81 ++len;
82 if (len <= size)
83 ptr = static_array.ptr;
84 else
85 ptr = array.ptr;
86 }
87
88 size_t length() { return len; }
89
90 static SmallArray opCall()
91 {
92 SmallArray array;
93 array.ptr = array.static_array.ptr;
94 return array;
95 }
96
97 private:
98 T* ptr;
99 size_t len;
100 union
101 {
102 T[] array;
103 T[size] static_array;
104 }
105 }
106