forked from libmir/mir-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslice.d
More file actions
4176 lines (3613 loc) · 118 KB
/
slice.d
File metadata and controls
4176 lines (3613 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/++
This is a submodule of $(MREF mir, ndslice).
Safety_note:
User-defined iterators should care about their safety except bounds checks.
Bounds are checked in ndslice code.
License: $(HTTP www.apache.org/licenses/LICENSE-2.0, Apache-2.0)
Copyright: 2020 Ilia Ki, Kaleidic Associates Advisory Limited, Symmetry Investments
Authors: Ilia Ki
$(BOOKTABLE $(H2 Definitions),
$(TR $(TH Name) $(TH Description))
$(T2 Slice, N-dimensional slice.)
$(T2 SliceKind, SliceKind of $(LREF Slice) enumeration.)
$(T2 Universal, Alias for $(LREF .SliceKind.universal).)
$(T2 Canonical, Alias for $(LREF .SliceKind.canonical).)
$(T2 Contiguous, Alias for $(LREF .SliceKind.contiguous).)
$(T2 sliced, Creates a slice on top of an iterator, a pointer, or an array's pointer.)
$(T2 slicedField, Creates a slice on top of a field, a random access range, or an array.)
$(T2 slicedNdField, Creates a slice on top of an ndField.)
$(T2 kindOf, Extracts $(LREF SliceKind).)
$(T2 isSlice, Checks if the type is `Slice` instance.)
$(T2 Structure, A tuple of lengths and strides.)
)
Macros:
SUBREF = $(REF_ALTTEXT $(TT $2), $2, mir, ndslice, $1)$(NBSP)
T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
T4=$(TR $(TDNW $(LREF $1)) $(TD $2) $(TD $3) $(TD $4))
STD = $(TD $(SMALL $0))
+/
module mir.ndslice.slice;
import mir.internal.utility : Iota;
import mir.math.common : fmamath;
import mir.ndslice.concatenation;
import mir.ndslice.field;
import mir.ndslice.internal;
import mir.ndslice.iterator;
import mir.ndslice.traits: isIterator;
import mir.primitives;
import mir.qualifier;
import mir.utility;
import std.meta;
import std.traits;
///
public import mir.primitives: DeepElementType;
/++
Checks if type T has asSlice property and its returns a slices.
Aliases itself to a dimension count
+/
template hasAsSlice(T)
{
static if (__traits(hasMember, T, "asSlice"))
enum size_t hasAsSlice = typeof(T.init.asSlice).N;
else
enum size_t hasAsSlice = 0;
}
///
version(mir_ndslice_test) unittest
{
import mir.series;
static assert(!hasAsSlice!(int[]));
static assert(hasAsSlice!(SeriesMap!(int, string)) == 1);
}
/++
Check if $(LREF toConst) function can be called with type T.
+/
enum isConvertibleToSlice(T) = isSlice!T || isDynamicArray!T || hasAsSlice!T;
///
version(mir_ndslice_test) unittest
{
import mir.series: SeriesMap;
static assert(isConvertibleToSlice!(immutable int[]));
static assert(isConvertibleToSlice!(string[]));
static assert(isConvertibleToSlice!(SeriesMap!(string, int)));
static assert(isConvertibleToSlice!(Slice!(int*)));
}
/++
Reurns:
Ndslice view in the same data.
See_also: $(LREF isConvertibleToSlice).
+/
auto toSlice(Iterator, size_t N, SliceKind kind)(Slice!(Iterator, N, kind) val)
{
import core.lifetime: move;
return val.move;
}
/// ditto
auto toSlice(Iterator, size_t N, SliceKind kind)(const Slice!(Iterator, N, kind) val)
{
return val[];
}
/// ditto
auto toSlice(Iterator, size_t N, SliceKind kind)(immutable Slice!(Iterator, N, kind) val)
{
return val[];
}
/// ditto
auto toSlice(T)(T[] val)
{
return val.sliced;
}
/// ditto
auto toSlice(T)(T val)
if (hasAsSlice!T || __traits(hasMember, T, "moveToSlice"))
{
static if (__traits(hasMember, T, "moveToSlice"))
return val.moveToSlice;
else
return val.asSlice;
}
/// ditto
auto toSlice(T)(ref T val)
if (hasAsSlice!T)
{
return val.asSlice;
}
///
template toSlices(args...)
{
static if (args.length)
{
alias arg = args[0];
alias Arg = typeof(arg);
static if (isMutable!Arg && isSlice!Arg)
alias slc = arg;
else
@fmamath @property auto ref slc()()
{
return toSlice(arg);
}
alias toSlices = AliasSeq!(slc, toSlices!(args[1..$]));
}
else
alias toSlices = AliasSeq!();
}
/++
Checks if the type is `Slice` instance.
+/
enum isSlice(T) = is(T : Slice!(Iterator, N, kind), Iterator, size_t N, SliceKind kind);
///
@safe pure nothrow @nogc
version(mir_ndslice_test) unittest
{
alias A = uint[];
alias S = Slice!(int*);
static assert(isSlice!S);
static assert(!isSlice!A);
}
/++
SliceKind of $(LREF Slice).
See_also:
$(SUBREF topology, universal),
$(SUBREF topology, canonical),
$(SUBREF topology, assumeCanonical),
$(SUBREF topology, assumeContiguous).
+/
enum mir_slice_kind
{
/// A slice has strides for all dimensions.
universal,
/// A slice has >=2 dimensions and row dimension is contiguous.
canonical,
/// A slice is a flat contiguous data without strides.
contiguous,
}
/// ditto
alias SliceKind = mir_slice_kind;
/++
Alias for $(LREF .SliceKind.universal).
See_also:
Internal Binary Representation section in $(LREF Slice).
+/
alias Universal = SliceKind.universal;
/++
Alias for $(LREF .SliceKind.canonical).
See_also:
Internal Binary Representation section in $(LREF Slice).
+/
alias Canonical = SliceKind.canonical;
/++
Alias for $(LREF .SliceKind.contiguous).
See_also:
Internal Binary Representation section in $(LREF Slice).
+/
alias Contiguous = SliceKind.contiguous;
/// Extracts $(LREF SliceKind).
enum kindOf(T : Slice!(Iterator, N, kind), Iterator, size_t N, SliceKind kind) = kind;
///
@safe pure nothrow @nogc
version(mir_ndslice_test) unittest
{
static assert(kindOf!(Slice!(int*, 1, Universal)) == Universal);
}
/// Extracts iterator type from a $(LREF Slice).
alias IteratorOf(T : Slice!(Iterator, N, kind), Iterator, size_t N, SliceKind kind) = Iterator;
private template SkipDimension(size_t dimension, size_t index)
{
static if (index < dimension)
enum SkipDimension = index;
else
static if (index == dimension)
static assert (0, "SkipInex: wrong index");
else
enum SkipDimension = index - 1;
}
/++
Creates an n-dimensional slice-shell over an iterator.
Params:
iterator = An iterator, a pointer, or an array.
lengths = A list of lengths for each dimension
Returns:
n-dimensional slice
+/
auto sliced(size_t N, Iterator)(return scope Iterator iterator, size_t[N] lengths...)
if (!__traits(isStaticArray, Iterator) && N
&& !is(Iterator : Slice!(_Iterator, _N, kind), _Iterator, size_t _N, SliceKind kind))
{
alias C = ImplicitlyUnqual!(typeof(iterator));
size_t[N] _lengths;
foreach (i; Iota!N)
_lengths[i] = lengths[i];
ptrdiff_t[1] _strides = 0;
static if (isDynamicArray!Iterator)
{
assert(lengthsProduct(_lengths) <= iterator.length,
"array length should be greater or equal to the product of constructed ndslice lengths");
auto ptr = iterator.length ? &iterator[0] : null;
return Slice!(typeof(C.init[0])*, N)(_lengths, ptr);
}
else
{
// break safety
if (false)
{
++iterator;
--iterator;
iterator += 34;
iterator -= 34;
}
import core.lifetime: move;
return Slice!(C, N)(_lengths, iterator.move);
}
}
/// Random access range primitives for slices over user defined types
@safe pure nothrow @nogc version(mir_ndslice_test) unittest
{
struct MyIota
{
//`[index]` operator overloading
auto opIndex(size_t index) @safe nothrow
{
return index;
}
auto lightConst()() const @property { return MyIota(); }
auto lightImmutable()() immutable @property { return MyIota(); }
}
import mir.ndslice.iterator: FieldIterator;
alias Iterator = FieldIterator!MyIota;
alias S = Slice!(Iterator, 2);
import std.range.primitives;
static assert(hasLength!S);
static assert(hasSlicing!S);
static assert(isRandomAccessRange!S);
auto slice = Iterator().sliced(20, 10);
assert(slice[1, 2] == 12);
auto sCopy = slice.save;
assert(slice[1, 2] == 12);
}
/++
Creates an 1-dimensional slice-shell over an array.
Params:
array = An array.
Returns:
1-dimensional slice
+/
Slice!(T*) sliced(T)(T[] array) @trusted
{
version(LDC) pragma(inline, true);
return Slice!(T*)([array.length], array.ptr);
}
/// Creates a slice from an array.
@safe pure nothrow version(mir_ndslice_test) unittest
{
auto slice = new int[10].sliced;
assert(slice.length == 10);
static assert(is(typeof(slice) == Slice!(int*)));
}
/++
Creates an n-dimensional slice-shell over the 1-dimensional input slice.
Params:
slice = slice
lengths = A list of lengths for each dimension.
Returns:
n-dimensional slice
+/
Slice!(Iterator, N, kind)
sliced
(Iterator, size_t N, SliceKind kind)
(Slice!(Iterator, 1, kind) slice, size_t[N] lengths...)
if (N)
{
auto structure = typeof(return)._Structure.init;
structure[0] = lengths;
static if (kind != Contiguous)
{
import mir.ndslice.topology: iota;
structure[1] = structure[0].iota.strides;
}
import core.lifetime: move;
return typeof(return)(structure, slice._iterator.move);
}
///
@safe pure nothrow version(mir_ndslice_test) unittest
{
import mir.ndslice.topology : iota;
auto data = new int[24];
foreach (i, ref e; data)
e = cast(int)i;
auto a = data[0..10].sliced(10)[0..6].sliced(2, 3);
auto b = iota!int(10)[0..6].sliced(2, 3);
assert(a == b);
a[] += b;
foreach (i, e; data[0..6])
assert(e == 2*i);
foreach (i, e; data[6..$])
assert(e == i+6);
}
/++
Creates an n-dimensional slice-shell over a field.
Params:
field = A field. The length of the
array should be equal to or less then the product of
lengths.
lengths = A list of lengths for each dimension.
Returns:
n-dimensional slice
+/
Slice!(FieldIterator!Field, N)
slicedField(Field, size_t N)(Field field, size_t[N] lengths...)
if (N)
{
static if (hasLength!Field)
assert(lengths.lengthsProduct <= field.length, "Length product should be less or equal to the field length.");
return FieldIterator!Field(0, field).sliced(lengths);
}
///ditto
auto slicedField(Field)(Field field)
if(hasLength!Field)
{
return .slicedField(field, field.length);
}
/// Creates an 1-dimensional slice over a field, array, or random access range.
@safe @nogc pure nothrow version(mir_ndslice_test) unittest
{
import mir.ndslice.topology : iota;
auto slice = 10.iota.slicedField;
assert(slice.length == 10);
}
/++
Creates an n-dimensional slice-shell over an ndField.
Params:
field = A ndField. Lengths should fit into field's shape.
lengths = A list of lengths for each dimension.
Returns:
n-dimensional slice
See_also: $(SUBREF concatenation, concatenation) examples.
+/
Slice!(IndexIterator!(FieldIterator!(ndIotaField!N), ndField), N)
slicedNdField(ndField, size_t N)(ndField field, size_t[N] lengths...)
if (N)
{
static if(hasShape!ndField)
{
auto shape = field.shape;
foreach (i; 0 .. N)
assert(lengths[i] <= shape[i], "Lengths should fit into ndfield's shape.");
}
import mir.ndslice.topology: indexed, ndiota;
return indexed(field, ndiota(lengths));
}
///ditto
auto slicedNdField(ndField)(ndField field)
if(hasShape!ndField)
{
return .slicedNdField(field, field.shape);
}
/++
Combination of coordinate(s) and value.
+/
struct CoordinateValue(T, size_t N = 1)
{
///
size_t[N] index;
///
T value;
///
int opCmp()(scope auto ref const typeof(this) rht) const
{
return cmpCoo(this.index, rht.index);
}
}
private int cmpCoo(size_t N)(scope const auto ref size_t[N] a, scope const auto ref size_t[N] b)
{
foreach (i; Iota!(0, N))
if (a[i] != b[i])
return a[i] > b[i] ? 1 : -1;
return 0;
}
/++
Presents $(LREF .Slice.structure).
+/
struct Structure(size_t N)
{
///
size_t[N] lengths;
///
sizediff_t[N] strides;
}
package(mir) alias LightConstOfLightScopeOf(Iterator) = LightConstOf!(LightScopeOf!Iterator);
package(mir) alias LightImmutableOfLightConstOf(Iterator) = LightImmutableOf!(LightScopeOf!Iterator);
package(mir) alias ImmutableOfUnqualOfPointerTarget(Iterator) = immutable(Unqual!(PointerTarget!Iterator))*;
package(mir) alias ConstOfUnqualOfPointerTarget(Iterator) = const(Unqual!(PointerTarget!Iterator))*;
package(mir) template allLightScope(args...)
{
static if (args.length)
{
alias Arg = typeof(args[0]);
static if(!isDynamicArray!Arg)
{
static if(!is(LightScopeOf!Arg == Arg))
@fmamath @property auto allLightScopeMod()()
{
import mir.qualifier: lightScope;
return args[0].lightScope;
}
else alias allLightScopeMod = args[0];
}
else alias allLightScopeMod = args[0];
alias allLightScope = AliasSeq!(allLightScopeMod, allLightScope!(args[1..$]));
}
else
alias allLightScope = AliasSeq!();
}
/++
Presents an n-dimensional view over a range.
$(H3 Definitions)
In order to change data in a slice using
overloaded operators such as `=`, `+=`, `++`,
a syntactic structure of type
`<slice to change>[<index and interval sequence...>]` must be used.
It is worth noting that just like for regular arrays, operations `a = b`
and `a[] = b` have different meanings.
In the first case, after the operation is carried out, `a` simply points at the same data as `b`
does, and the data which `a` previously pointed at remains unmodified.
Here, `а` and `b` must be of the same type.
In the second case, `a` points at the same data as before,
but the data itself will be changed. In this instance, the number of dimensions of `b`
may be less than the number of dimensions of `а`; and `b` can be a Slice,
a regular multidimensional array, or simply a value (e.g. a number).
In the following table you will find the definitions you might come across
in comments on operator overloading.
$(BOOKTABLE
$(TR $(TH Operator Overloading) $(TH Examples at `N == 3`))
$(TR $(TD An $(B interval) is a part of a sequence of type `i .. j`.)
$(STD `2..$-3`, `0..4`))
$(TR $(TD An $(B index) is a part of a sequence of type `i`.)
$(STD `3`, `$-1`))
$(TR $(TD A $(B partially defined slice) is a sequence composed of
$(B intervals) and $(B indices) with an overall length strictly less than `N`.)
$(STD `[3]`, `[0..$]`, `[3, 3]`, `[0..$,0..3]`, `[0..$,2]`))
$(TR $(TD A $(B fully defined index) is a sequence
composed only of $(B indices) with an overall length equal to `N`.)
$(STD `[2,3,1]`))
$(TR $(TD A $(B fully defined slice) is an empty sequence
or a sequence composed of $(B indices) and at least one
$(B interval) with an overall length equal to `N`.)
$(STD `[]`, `[3..$,0..3,0..$-1]`, `[2,0..$,1]`))
$(TR $(TD An $(B indexed slice) is syntax sugar for $(SUBREF topology, indexed) and $(SUBREF topology, cartesian).)
$(STD `[anNdslice]`, `[$.iota, anNdsliceForCartesian1, $.iota]`))
)
See_also:
$(SUBREF topology, iota).
$(H3 Internal Binary Representation)
Multidimensional Slice is a structure that consists of lengths, strides, and a iterator (pointer).
$(SUBREF topology, FieldIterator) shell is used to wrap fields and random access ranges.
FieldIterator contains a shift of the current initial element of a multidimensional slice
and the field itself.
With the exception of $(MREF mir,ndslice,allocation) module, no functions in this
package move or copy data. The operations are only carried out on lengths, strides,
and pointers. If a slice is defined over a range, only the shift of the initial element
changes instead of the range.
Mir n-dimensional Slices can be one of the three kinds.
$(H4 Contiguous slice)
Contiguous in memory (or in a user-defined iterator's field) row-major tensor that doesn't store strides because they can be computed on the fly using lengths.
The row stride is always equaled 1.
$(H4 Canonical slice)
Canonical slice as contiguous in memory (or in a user-defined iterator's field) rows of a row-major tensor, it doesn't store the stride for row dimension because it is always equaled 1.
BLAS/LAPACK matrices are Canonical but originally have column-major order.
In the same time you can use 2D Canonical Slices with LAPACK assuming that rows are columns and columns are rows.
$(H4 Universal slice)
A row-major tensor that stores the strides for all dimensions.
NumPy strides are Universal.
$(H4 Internal Representation for Universal Slices)
Type definition
-------
Slice!(Iterator, N, Universal)
-------
Schema
-------
Slice!(Iterator, N, Universal)
size_t[N] _lengths
sizediff_t[N] _strides
Iterator _iterator
-------
$(H5 Example)
Definitions
-------
import mir.ndslice;
auto a = new double[24];
Slice!(double*, 3, Universal) s = a.sliced(2, 3, 4).universal;
Slice!(double*, 3, Universal) t = s.transposed!(1, 2, 0);
Slice!(double*, 3, Universal) r = t.reversed!1;
-------
Representation
-------
s________________________
lengths[0] ::= 2
lengths[1] ::= 3
lengths[2] ::= 4
strides[0] ::= 12
strides[1] ::= 4
strides[2] ::= 1
iterator ::= &a[0]
t____transposed!(1, 2, 0)
lengths[0] ::= 3
lengths[1] ::= 4
lengths[2] ::= 2
strides[0] ::= 4
strides[1] ::= 1
strides[2] ::= 12
iterator ::= &a[0]
r______________reversed!1
lengths[0] ::= 2
lengths[1] ::= 3
lengths[2] ::= 4
strides[0] ::= 12
strides[1] ::= -4
strides[2] ::= 1
iterator ::= &a[8] // (old_strides[1] * (lengths[1] - 1)) = 8
-------
$(H4 Internal Representation for Canonical Slices)
Type definition
-------
Slice!(Iterator, N, Canonical)
-------
Schema
-------
Slice!(Iterator, N, Canonical)
size_t[N] _lengths
sizediff_t[N-1] _strides
Iterator _iterator
-------
$(H4 Internal Representation for Contiguous Slices)
Type definition
-------
Slice!(Iterator, N)
-------
Schema
-------
Slice!(Iterator, N, Contiguous)
size_t[N] _lengths
sizediff_t[0] _strides
Iterator _iterator
-------
+/
struct mir_slice(Iterator_, size_t N_ = 1, SliceKind kind_ = Contiguous, Labels_...)
if (0 < N_ && N_ < 255 && !(kind_ == Canonical && N_ == 1) && Labels_.length <= N_ && isIterator!Iterator_)
{
@fmamath:
/// $(LREF SliceKind)
enum SliceKind kind = kind_;
/// Dimensions count
enum size_t N = N_;
/// Strides count
enum size_t S = kind == Universal ? N : kind == Canonical ? N - 1 : 0;
/// Labels count.
enum size_t L = Labels_.length;
/// Data iterator type
alias Iterator = Iterator_;
/// This type
alias This = Slice!(Iterator, N, kind);
/// Data element type
alias DeepElement = typeof(Iterator.init[size_t.init]);
///
alias serdeKeysProxy = Unqual!DeepElement;
/// Label Iterators types
alias Labels = Labels_;
///
template Element(size_t dimension)
if (dimension < N)
{
static if (N == 1)
alias Element = DeepElement;
else
{
static if (kind == Universal || dimension == N - 1)
alias Element = mir_slice!(Iterator, N - 1, Universal);
else
static if (N == 2 || kind == Contiguous && dimension == 0)
alias Element = mir_slice!(Iterator, N - 1);
else
alias Element = mir_slice!(Iterator, N - 1, Canonical);
}
}
package(mir):
enum doUnittest = is(Iterator == int*) && (N == 1 || N == 2) && kind == Contiguous;
enum hasAccessByRef = __traits(compiles, &_iterator[0]);
enum PureIndexLength(Slices...) = Filter!(isIndex, Slices).length;
enum isPureSlice(Slices...) =
Slices.length == 0
|| Slices.length <= N
&& PureIndexLength!Slices < N
&& Filter!(isIndex, Slices).length < Slices.length
&& allSatisfy!(templateOr!(isIndex, is_Slice), Slices);
enum isFullPureSlice(Slices...) =
Slices.length == 0
|| Slices.length == N
&& PureIndexLength!Slices < N
&& allSatisfy!(templateOr!(isIndex, is_Slice), Slices);
enum isIndexedSlice(Slices...) =
Slices.length
&& Slices.length <= N
&& allSatisfy!(isSlice, Slices)
&& anySatisfy!(templateNot!is_Slice, Slices);
static if (S)
{
///
public alias _Structure = AliasSeq!(size_t[N], ptrdiff_t[S]);
///
public _Structure _structure;
///
public alias _lengths = _structure[0];
///
public alias _strides = _structure[1];
}
else
{
///
public alias _Structure = AliasSeq!(size_t[N]);
///
public _Structure _structure;
///
public alias _lengths = _structure[0];
///
public enum ptrdiff_t[S] _strides = ptrdiff_t[S].init;
}
/// Data Iterator
public Iterator _iterator;
/// Labels iterators
public Labels _labels;
sizediff_t backIndex(size_t dimension = 0)() @safe @property scope const
if (dimension < N)
{
return _stride!dimension * (_lengths[dimension] - 1);
}
size_t indexStride(size_t I)(size_t[I] _indices) @safe scope const
{
static if (_indices.length)
{
static if (kind == Contiguous)
{
enum E = I - 1;
assert(_indices[E] < _lengths[E], indexError!(DeepElement, E, N));
ptrdiff_t ball = this._stride!E;
ptrdiff_t stride = _indices[E] * ball;
foreach_reverse (i; Iota!E) //static
{
ball *= _lengths[i + 1];
assert(_indices[i] < _lengths[i], indexError!(DeepElement, i, N));
stride += ball * _indices[i];
}
}
else
static if (kind == Canonical)
{
enum E = I - 1;
assert(_indices[E] < _lengths[E], indexError!(DeepElement, E, N));
static if (I == N)
size_t stride = _indices[E];
else
size_t stride = _strides[E] * _indices[E];
foreach_reverse (i; Iota!E) //static
{
assert(_indices[i] < _lengths[i], indexError!(DeepElement, i, N));
stride += _strides[i] * _indices[i];
}
}
else
{
enum E = I - 1;
assert(_indices[E] < _lengths[E], indexError!(DeepElement, E, N));
size_t stride = _strides[E] * _indices[E];
foreach_reverse (i; Iota!E) //static
{
assert(_indices[i] < _lengths[i], indexError!(DeepElement, i, N));
stride += _strides[i] * _indices[i];
}
}
return stride;
}
else
{
return 0;
}
}
public:
// static if (S == 0)
// {
/// Defined for Contiguous Slice only
// this()(size_t[N] lengths, in ptrdiff_t[] empty, Iterator iterator, Labels labels)
// {
// version(LDC) pragma(inline, true);
// assert(empty.length == 0);
// this._lengths = lengths;
// this._iterator = iterator;
// }
// /// ditto
// this()(size_t[N] lengths, Iterator iterator, Labels labels)
// {
// version(LDC) pragma(inline, true);
// this._lengths = lengths;
// this._iterator = iterator;
// }
// /// ditto
// this()(size_t[N] lengths, in ptrdiff_t[] empty, Iterator iterator, Labels labels)
// {
// version(LDC) pragma(inline, true);
// assert(empty.length == 0);
// this._lengths = lengths;
// this._iterator = iterator;
// }
// /// ditto
// this()(size_t[N] lengths, Iterator iterator, Labels labels)
// {
// version(LDC) pragma(inline, true);
// this._lengths = lengths;
// this._iterator = iterator;
// }
// }
// version(LDC)
// private enum classicConstructor = true;
// else
// private enum classicConstructor = S > 0;
// static if (classicConstructor)
// {
/// Defined for Canonical and Universal Slices (DMD, GDC, LDC) and for Contiguous Slices (LDC)
// this()(size_t[N] lengths, ptrdiff_t[S] strides, Iterator iterator, Labels labels)
// {
// version(LDC) pragma(inline, true);
// this._lengths = lengths;
// this._strides = strides;
// this._iterator = iterator;
// this._labels = labels;
// }
// /// ditto
// this()(size_t[N] lengths, ptrdiff_t[S] strides, ref Iterator iterator, Labels labels)
// {
// version(LDC) pragma(inline, true);
// this._lengths = lengths;
// this._strides = strides;
// this._iterator = iterator;
// this._labels = labels;
// }
// }
// /// Construct from null
// this()(typeof(null))
// {
// version(LDC) pragma(inline, true);
// }
// static if (doUnittest)
// ///
// @safe pure version(mir_ndslice_test) unittest
// {
// import mir.ndslice.slice;
// alias Array = Slice!(double*);
// Array a = null;
// auto b = Array(null);
// assert(a.empty);
// assert(b.empty);
// auto fun(Array a = null)
// {
// }
// }
static if (doUnittest)
/// Creates a 2-dimentional slice with custom strides.
nothrow pure
version(mir_ndslice_test) unittest
{
uint[8] array = [1, 2, 3, 4, 5, 6, 7, 8];
auto slice = Slice!(uint*, 2, Universal)([2, 2], [4, 1], array.ptr);
assert(&slice[0, 0] == &array[0]);
assert(&slice[0, 1] == &array[1]);
assert(&slice[1, 0] == &array[4]);
assert(&slice[1, 1] == &array[5]);
assert(slice == [[1, 2], [5, 6]]);
array[2] = 42;
assert(slice == [[1, 2], [5, 6]]);
array[1] = 99;
assert(slice == [[1, 99], [5, 6]]);
}
/++
Returns: View with stripped out reference counted context.
The lifetime of the result mustn't be longer then the lifetime of the original slice.
+/
auto lightScope()() return scope @property
{
auto ret = Slice!(LightScopeOf!Iterator, N, kind, staticMap!(LightScopeOf, Labels))
(_structure, .lightScope(_iterator));
foreach(i; Iota!L)
ret._labels[i] = .lightScope(_labels[i]);
return ret;
}
/// ditto
auto lightScope()() @trusted return scope const @property
{
auto ret = Slice!(LightConstOf!(LightScopeOf!Iterator), N, kind, staticMap!(LightConstOfLightScopeOf, Labels))
(_structure, .lightScope(_iterator));
foreach(i; Iota!L)
ret._labels[i] = .lightScope(_labels[i]);
return ret;
}
/// ditto
auto lightScope()() return scope immutable @property
{
auto ret = Slice!(LightImmutableOf!(LightScopeOf!Iterator), N, kind, staticMap!(LightImmutableOfLightConstOf, Labels))
(_structure, .lightScope(_iterator));
foreach(i; Iota!L)
ret._labels[i] = .lightScope(_labels[i]);
return ret;
}
/// Returns: Mutable slice over immutable data.
Slice!(LightImmutableOf!Iterator, N, kind, staticMap!(LightImmutableOf, Labels)) lightImmutable()() return scope immutable @property
{
auto ret = typeof(return)(_structure, .lightImmutable(_iterator));
foreach(i; Iota!L)
ret._labels[i] = .lightImmutable(_labels[i]);
return ret;
}
static if (doUnittest)
///
@safe pure nothrow
version(mir_ndslice_test) unittest {
import mir.algorithm.iteration: equal;
immutable Slice!(int*, 1) x = [1, 2].sliced;
auto y = x.lightImmutable;
// this._iterator is copied to the new slice (i.e. both point to the same underlying data)
assert(x._iterator == y._iterator);
assert(x[0] == 1);
assert(x[1] == 2);
assert(y[0] == 1);
assert(y[1] == 2);
// Outer immutable is moved to iteration type
static assert(is(typeof(y) == Slice!(immutable(int)*, 1)));