Skip to content

Commit

Permalink
[ndslice] allow init elem for slice()
Browse files Browse the repository at this point in the history
  • Loading branch information
wilzbach committed May 1, 2016
1 parent d69cab1 commit 30f6319
Showing 1 changed file with 41 additions and 6 deletions.
47 changes: 41 additions & 6 deletions std/experimental/ndslice/slice.d
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,26 @@ slice(T,
return new T[len].sliced!replaceArrayWithPointer(lengths);
}

/// ditto
auto slice(T,
Flag!`replaceArrayWithPointer` replaceArrayWithPointer = Yes.replaceArrayWithPointer,
size_t N)(auto ref in size_t[N] lengths, auto ref T init)
{
immutable len = lengthsProduct(lengths);
static if (!hasElaborateAssign!(T[]))
{
import std.array : uninitializedArray;
auto arr = uninitializedArray!(T[])(len);
}
else
{
auto arr = new T[len];
}
arr[] = init;
auto ret = arr.sliced!replaceArrayWithPointer(lengths);
return ret;
}

/// ditto
auto slice(
Flag!`replaceArrayWithPointer` replaceArrayWithPointer = Yes.replaceArrayWithPointer,
Expand All @@ -579,14 +599,29 @@ auto slice(
///
pure nothrow unittest
{
auto slice = slice!int(5, 6, 7);
assert(slice.length == 5);
assert(slice.elementsCount == 5 * 6 * 7);
static assert(is(typeof(slice) == Slice!(3, int*)));
auto tensor = slice!int(5, 6, 7);
assert(tensor.length == 5);
assert(tensor.elementsCount == 5 * 6 * 7);
static assert(is(typeof(tensor) == Slice!(3, int*)));

// creates duplicate using `slice`
auto dup = .slice(slice);
assert(dup == slice);
auto dup = tensor.slice;
assert(dup == tensor);
}

///
pure nothrow unittest
{
auto tensor = slice([2, 3], 5);
assert(tensor.elementsCount == 2 * 3);
assert(tensor[1, 1] == 5);
}

pure nothrow unittest
{
import std.experimental.ndslice.selection: iotaSlice;
auto tensor = iotaSlice(2, 3).slice;
assert(tensor == [[0, 1, 2], [3, 4, 5]]);
}

/++
Expand Down

0 comments on commit 30f6319

Please sign in to comment.