From 507b03831fe75397e58290126d73c78a90ef4d2c Mon Sep 17 00:00:00 2001 From: Denis Shelomovskij Date: Tue, 6 Nov 2012 13:10:31 +0400 Subject: [PATCH] Add `std.array.asFlatStaticArray` --- std/array.d | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/std/array.d b/std/array.d index eeb9f8f6803..b3fd84747d7 100644 --- a/std/array.d +++ b/std/array.d @@ -672,6 +672,80 @@ unittest assert(overlap(c, d.idup).empty); } + +/** +Represents value as a flat (single-dimention) static array. +Considers $(D T) to be an $(D n)-dimensional static array type. + +Example: +--- +int i; +static assert(is(typeof(asFlatStaticArray(i)) == int[1])); +asFlatStaticArray(i) = 5; +assert(i == 5); + +int[1][2][3] mdimSArr; +static assert(is(typeof(asFlatStaticArray(mdimSArr)) == int[6])); +asFlatStaticArray(mdimSArr) = [1, 2, 3, 4, 5, 6]; +assert(mdimSArr == [[[1], [2]], [[3], [4]], [[5], [6]]]); + +static assert(is(typeof(asFlatStaticArray!2(mdimSArr)) == int[1][6])); +assert(asFlatStaticArray!2(mdimSArr) == [[1], [2], [3], [4], [5], [6]]); +--- +*/ +package ref asFlatStaticArray(T, size_t n = staticArrayDimensions!T)(ref T t) +{ + return *(cast(MultidimStaticArrayElementType!(T, n) + [multidimStaticArrayElementCount!(T, n)]*) &t); +} + +/// ditto +package ref asFlatStaticArray(size_t n, T)(ref T t) +{ + return asFlatStaticArray!(T, n)(t); +} + +unittest +{ + int i; + static assert(is(typeof(asFlatStaticArray(i)) == int[1])); + asFlatStaticArray(i) = 5; + assert(i == 5); + + int[1][2][3] mdimSArr; + static assert(is(typeof(asFlatStaticArray(mdimSArr)) == int[6])); + asFlatStaticArray(mdimSArr) = [1, 2, 3, 4, 5, 6]; + assert(mdimSArr == [[[1], [2]], [[3], [4]], [[5], [6]]]); + + static assert(is(typeof(asFlatStaticArray!2(mdimSArr)) == int[1][6])); + assert(asFlatStaticArray!2(mdimSArr) == [[1], [2], [3], [4], [5], [6]]); +} + +unittest +{ + static void test(T, U, El, V, W)(U valInit, El[] sarrFrom, V arrAssign, W valNew) + { + T t = valInit; + auto p = &asFlatStaticArray(t); + assert(cast(void*) p == &t); + static assert((*p).sizeof == T.sizeof); + assert(*p == sarrFrom); + *p = arrAssign; + assert(t == valNew); + } + + test!int(3, [3], 4 , 4); + test!int(3, [3], [4], 4); + + test!(int[0])(null, [], null, []); + test!(int[0])( 3, [], null, []); + test!(int[0])( 3, [], 4, []); + + test!(int[2])([3, 4], [3, 4], [5, 6], [5, 6]); + test!(int[2])(3, [3, 3], 1, [1, 1]); +} + + /+ Commented out until the insert which has been deprecated has been removed. I'd love to just remove it in favor of insertInPlace, but then code would then