baxissimo
Joined: 23 Oct 2006 Posts: 241 Location: Tokyo, Japan
|
Posted: Tue Oct 02, 2007 9:08 pm Post subject: insert for cashew.utils.Array? |
|
|
I think I sent you an implementation of insert before, but it doesn't seem to have made it into Cashew. Here it is again (or maybe for the first time?):
Code: |
/***********************************************************************************
* Insert item x into an array at (just before) index.
*/
void insert (T) (ref T[] haystack, size_t index, T x)
in {
assert(index < haystack.length+1, ".insert() called with index greater than array length");
}
body {
if (index == haystack.length) {
haystack ~= x;
}
else {
haystack.length = haystack.length+1;
memmove(&haystack[index+1], &haystack[index],
T.sizeof * (haystack.length - index - 1));
haystack[index] = x;
}
}
unittest {
int[] foo = [0, 1, 2, 3, 4, 5];
foo.insert(3_U, 3);
assert(foo == [0, 1, 2, 3,3, 4, 5]);
foo.insert(7_U, 9);
assert(foo == [0, 1, 2, 3,3, 4, 5, 9]);
}
|
|
|