2 * Array container for internal usage.
4 * Copyright: Copyright Martin Nowak 2013.
5 * License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
6 * Authors: Martin Nowak
8 module core.internal.container.array;
10 static import common = core.internal.container.common;
12 import core.exception : onOutOfMemoryErrorNoGC;
29 @property size_t length() const
34 @property void length(size_t nlength)
36 import core.checkedint : mulu;
38 bool overflow = false;
39 size_t reqsize = mulu(T.sizeof, nlength, overflow);
42 if (nlength < _length)
43 foreach (ref val; _ptr[nlength .. _length]) common.destroy(val);
44 _ptr = cast(T*)common.xrealloc(_ptr, reqsize);
45 if (nlength > _length)
46 foreach (ref val; _ptr[_length .. nlength]) common.initialize(val);
50 onOutOfMemoryErrorNoGC();
54 @property bool empty() const
59 @property ref inout(T) front() inout
60 in { assert(!empty); }
66 @property ref inout(T) back() inout
67 in { assert(!empty); }
70 return _ptr[_length - 1];
73 ref inout(T) opIndex(size_t idx) inout
74 in { assert(idx < length); }
80 inout(T)[] opSlice() inout
82 return _ptr[0 .. _length];
85 inout(T)[] opSlice(size_t a, size_t b) inout
86 in { assert(a < b && b <= length); }
92 alias length opDollar;
94 void insertBack()(auto ref T val)
96 import core.checkedint : addu;
98 bool overflow = false;
99 size_t newlength = addu(length, 1, overflow);
106 onOutOfMemoryErrorNoGC();
114 void remove(size_t idx)
115 in { assert(idx < length); }
118 foreach (i; idx .. length - 1)
123 void swap(ref Array other)
128 immutable len = _length;
129 _length = other._length;
135 assert(!_ptr == !_length);
149 assert(ary[] == [5]);
150 assert(ary[$-1] == 5);
155 assert(ary[] == [0, 1]);
156 assert(ary[0 .. 1] == [0]);
157 assert(ary[1 .. 2] == [1]);
158 assert(ary[$ - 2 .. $] == [0, 1]);
160 foreach (val; ary) assert(idx++ == val);
161 foreach_reverse (val; ary) assert(--idx == val);
162 foreach (i, val; ary) assert(i == val);
163 foreach_reverse (i, val; ary) assert(i == val);
167 assert(ary[] == [0, 2]);
178 static assert(!__traits(compiles, { Array!size_t ary2 = ary; }));
180 static assert(!__traits(compiles, ary = ary2));
181 static void foo(Array!size_t copy) {}
182 static assert(!__traits(compiles, foo(ary)));
186 assert(ary2[] == [0]);
188 assert(ary[] == [0]);
194 alias RC = common.RC!();
199 ary.insertBack(RC(&cnt));
201 ary.insertBack(RC(&cnt));
203 ary.back = ary.front;
213 import core.exception;
216 // Overflow ary.length.
217 auto ary = Array!size_t(cast(size_t*)0xdeadbeef, -1);
220 catch (OutOfMemoryError)
225 // Overflow requested memory size for common.xrealloc().
226 auto ary = Array!size_t(cast(size_t*)0xdeadbeef, -2);
229 catch (OutOfMemoryError)