From ff58b5e81c432157a799445d1b7075ce47efa5a2 Mon Sep 17 00:00:00 2001 From: Eugen Wissner Date: Wed, 24 Oct 2018 08:14:15 +0200 Subject: [PATCH] Add algorithm.mutation.initializeAll --- source/tanya/algorithm/mutation.d | 52 +++++++++++++++++++++++++++++++ source/tanya/container/array.d | 2 +- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/source/tanya/algorithm/mutation.d b/source/tanya/algorithm/mutation.d index 550afdd..49539d1 100644 --- a/source/tanya/algorithm/mutation.d +++ b/source/tanya/algorithm/mutation.d @@ -509,3 +509,55 @@ if (isInputRange!Range && hasLvalueElements!Range uninitializedFill(actual[], 1); assert(equal(actual[], expected[])); } + +/** + * Initializes all elements of the $(D_PARAM range) assuming that they are + * uninitialized. + * + * Params: + * Range = Input range type + * range = Input range. + */ +void initializeAll(Range)(Range range) @trusted +if (isInputRange!Range && hasLvalueElements!Range) +{ + import tanya.memory.op : copy, fill; + alias T = ElementType!Range; + + static if (__VERSION__ >= 2083 + && isDynamicArray!Range + && __traits(isZeroInit, T)) + { + fill!0(range); + } + else + { + static immutable init = T.init; + for (; !range.empty; range.popFront()) + { + copy((&init)[0 .. 1], (&range.front)[0 .. 1]); + } + } +} + +/// +@nogc nothrow pure @safe unittest +{ + import tanya.algorithm.comparison : equal; + + int[2] actual = void; + const int[2] expected = [0, 0]; + + initializeAll(actual[]); + assert(equal(actual[], expected[])); +} + +@nogc nothrow pure @safe unittest +{ + static struct NonCopyable + { + @disable this(this); + } + NonCopyable[] nonCopyable; + initializeAll(nonCopyable); +} diff --git a/source/tanya/container/array.d b/source/tanya/container/array.d index 17082d1..57ea482 100644 --- a/source/tanya/container/array.d +++ b/source/tanya/container/array.d @@ -15,7 +15,7 @@ module tanya.container.array; import core.checkedint; -import std.algorithm.mutation : bringToFront, initializeAll; +import std.algorithm.mutation : bringToFront; import tanya.algorithm.comparison; import tanya.algorithm.mutation; import tanya.exception;