Appending static arrays

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 17 13:01:41 PDT 2017


OK, here's an actual, compilable, runnable version:

	import std.algorithm : sum;
	import std.meta : allSatisfy, staticMap;
	import std.range : only;
	import std.traits : CommonType, isStaticArray;

	alias Elem(A : E[n], E, size_t n) = E;
	enum Length(A) = A.length;
	enum sumLengths(A...) = sum(only(0, staticMap!(Length, A)));

	CommonType!(staticMap!(Elem, A))[sumLengths!A] append(A...)(A arrays)
		if (allSatisfy!(isStaticArray, A))
	{
		typeof(return) result = void;
		foreach (i, a; arrays) {
			enum offset = sumLengths!(A[0 .. i]);
			result[offset .. offset + a.length] = a[];
		}
		return result;
	}

	@nogc unittest {
		int[2] a = [ 1, 2 ];
		int[3] b = [ 3, 4, 5 ];
		int[4] c = [ 6, 7, 8, 9 ];

		auto d = append(a, b, c);
		assert(is(typeof(d) == int[9]));
		assert(d == [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]);
	}


T

-- 
Be in denial for long enough, and one day you'll deny yourself of things you wish you hadn't.


More information about the Digitalmars-d-learn mailing list