Skip to content

Commit e0c3ff9

Browse files
committed
Fix for #313
1 parent 2da2123 commit e0c3ff9

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

‎source/mir/ndslice/slice.d‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,54 @@ auto sliced(size_t N, Iterator)(return scope Iterator iterator, size_t[N] length
299299
assert(slice[1, 2] == 12);
300300
}
301301

302+
/++
303+
Creates an n-dimensional slice-shell over an iterator having the exact elemnt count as that of the array.
304+
Params:
305+
iterator = An iterator, a pointer, or an array.
306+
lengths = A list of lengths for each dimension
307+
Returns:
308+
n-dimensional slice
309+
+/
310+
auto slicedExactly(size_t N, Iterator)(return scope Iterator iterator, size_t[N] lengths...)
311+
if (!__traits(isStaticArray, Iterator) && N
312+
&& !is(Iterator : Slice!(_Iterator, _N, kind), _Iterator, size_t _N, SliceKind kind))
313+
{
314+
alias C = ImplicitlyUnqual!(typeof(iterator));
315+
size_t[N] _lengths;
316+
foreach (i; Iota!N)
317+
_lengths[i] = lengths[i];
318+
ptrdiff_t[1] _strides = 0;
319+
static if (isDynamicArray!Iterator)
320+
{
321+
assert(lengthsProduct(_lengths) == iterator.length,
322+
"array length should be exactly equal to the product of constructed ndslice lengths");
323+
auto ptr = iterator.length ? &iterator[0] : null;
324+
return Slice!(typeof(C.init[0])*, N)(_lengths, ptr);
325+
}
326+
else
327+
{
328+
// break safety
329+
if (false)
330+
{
331+
++iterator;
332+
--iterator;
333+
iterator += 34;
334+
iterator -= 34;
335+
}
336+
import core.lifetime: move;
337+
return Slice!(C, N)(_lengths, iterator.move);
338+
}
339+
}
340+
341+
/// Test case for Issue 313 https://github.com/libmir/mir-algorithm/issues/313
342+
@safe pure nothrow @nogc unittest
343+
{
344+
int[6] values= [1, 2, 3, 4, 5, 6];
345+
auto arr = values[];
346+
auto s = arr.slicedExactly(2, 3);
347+
assert(s.elementCount == arr.length);
348+
}
349+
302350
/++
303351
Creates an 1-dimensional slice-shell over an array.
304352
Params:

0 commit comments

Comments
 (0)