#!/usr/bin/env dub
/+ dub.sdl:
name "images_mir_slice_views"
dependency "sparkles:base" path="../../../../.."
dependency "mir-algorithm" version="==3.22.4"
dflags "-preview=in" "-preview=dip1000"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
/**
* mir `Slice` as an image view: one interleaved RGBA8 buffer seen as a 2-D
* slice of a pixel struct, as a 3-D slice of bytes, through a crop and through
* a transpose, none of which copies a pixel.
*
* The storage is a `sparkles.base.buffer.UniqueBuffer`, so the experiment also
* shows how a `Slice` borrows memory a Sparkles owner holds, and what dip1000
* says about that borrow.
*
* Backs ./slice-experiment.md (sections "Views over one buffer" and
* "Borrowing a UniqueBuffer").
*
* Run with: `dub run --single slice-views.d`
*/
module (module) images_mir_slice_viewsmir Slice as an image view: one interleaved RGBA8 buffer seen as a 2-D
slice of a pixel struct, as a 3-D slice of bytes, through a crop and through
a transpose, none of which copies a pixel.
The storage is a sparkles.base.buffer.UniqueBuffer, so the experiment also
shows how a Slice borrows memory a Sparkles owner holds, and what dip1000
says about that borrow.
Backs ./slice-experiment.md (sections "Views over one buffer" and
"Borrowing a UniqueBuffer").
Run with: dub run --single slice-views.d
images_mir_slice_views;
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) images_mir_slice_views.writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Equivalent to writef(fmt, args, '\n').
writefln, (alias template) images_mir_slice_views.writeln = std.stdio.writeln(T...)(T args)Equivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln;
import (package) mirmir.(package) mir.ndslicendslice.(module) mir.ndslice.dynamicThis is a submodule of mir.ndslice.
Operators only change strides and lengths of a slice.
The range of a slice remains unmodified.
All operators return slice as the type of the argument, maybe except slice kind.
Function Name Description transposed Permutes dimensions.
iota(3, 4, 5, 6, 7).transposed!(4, 0, 1).shape returns [7, 3, 4, 5, 6]. |
| swapped | Swaps dimensions
iota(3, 4, 5).swapped!(1, 2).shape returns [3, 5, 4]. |
| everted | Reverses the order of dimensions
iota(3, 4, 5).everted.shape returns [5, 4, 3]. |
See also evertPack .
Function Name Description strided Multiplies the stride of a selected dimension by a factor.
iota(13, 40).strided!(0, 1)(2, 5).shape equals to [7, 8]. |
| reversed | Reverses the direction of iteration for selected dimensions.
slice.reversed!0 returns the slice with reversed direction of iteration for top level dimension. |
| allReversed | Reverses the direction of iteration for all dimensions.
iota(4, 5).allReversed equals to 20.iota.retro.sliced(4, 5). |
Function Name Description
| rotated | Rotates two selected dimensions by k*90 degrees.
iota(2, 3).rotated equals to [[2, 5], [1, 4], [0, 3]]. |
| dropToHypercube | Returns maximal multidimensional cube of a slice. |
| normalizeStructure | Reverses iteration order for dimensions with negative strides, they become not negative; and sorts dimensions according to the strides, dimensions with larger strides are going first. |
Bifacial operators
Some operators are bifacial,
i.e. they have two versions: one with template parameters, and another one
with function parameters. Versions with template parameters are preferable
because they allow compile time checks and can be optimized better.
Function Name Variadic Template Function swapped No slice.swapped!(2, 3) slice.swapped(2, 3) rotated No slice.rotated!(2, 3)(-1) slice.rotated(2, 3, -1) strided Yes/No slice.strided!(1, 2)(20, 40) slice.strided(1, 20).strided(2, 40) transposed Yes slice.transposed!(1, 4, 3) slice.transposed(1, 4, 3) reversed Yes slice.reversed!(0, 2) slice.reversed(0, 2)
Bifacial interface of drop, dropBack
dropExactly, and dropBackExactly
is identical to that of strided.
Bifacial interface of dropOne and dropBackOne
is identical to that of reversed.
dynamic : (alias template) images_mir_slice_views.transposed = mir.ndslice.dynamic.transposed(Dimensions...) if (Dimensions.length)N-dimensional transpose operator.
Brings selected dimensions to the first position.
transposed;
import (package) mirmir.(package) mir.ndslicendslice.(module) mir.ndslice.sliceThis is a submodule of mir.ndslice.
Safety note
User-defined iterators should care about their safety except bounds checks.
Bounds are checked in ndslice code.
slice : Canonical, Contiguous, Slice, (enum) mir.ndslice.slice.mir_slice_kindSliceKind of Slice.
SliceKind, (alias template) images_mir_slice_views.sliced = mir.ndslice.slice.sliced(ulong 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))Creates an n-dimensional slice-shell over an iterator.
sliced, Universal;
import (package) mirmir.(package) mir.ndslicendslice.(module) mir.ndslice.topologyThis is a submodule of mir.ndslice.
Selectors create new views and iteration patterns over the same data, without copying.
Function Name Description
| cycle | Cycle repeates 1-dimensional field/range/array/slice in a fixed length 1-dimensional slice |
| iota | Contiguous Slice with initial flattened (contiguous) index. |
| linspace | Evenly spaced numbers over a specified interval. |
| magic | Magic square. |
| ndiota | Contiguous Slice with initial multidimensional index. |
| repeat | Slice with identical values |
Function Name Description
| blocks | n-dimensional slice composed of n-dimensional non-overlapping blocks. If the slice has two dimensions, it is a block matrix. |
| diagonal | 1-dimensional slice composed of diagonal elements |
| dropBorders | Drops borders for all dimensions. |
| reshape | New slice view with changed dimensions |
| squeeze | New slice view of an n-dimensional slice with dimension removed |
| unsqueeze | New slice view of an n-dimensional slice with a dimension added |
| windows | n-dimensional slice of n-dimensional overlapping windows. If the slice has two dimensions, it is a sliding window. |
Function Name Description
| alongDim | Returns a slice that can be iterated along dimension. |
| byDim | Returns a slice that can be iterated by dimension. |
| pack | Returns slice of slices. |
| ipack | Returns slice of slices. |
| unpack | Merges two hight dimension packs. See also fuse . |
| evertPack | Reverses dimension packs. |
Function Name Description
| asKindOf | Converts a slice to a user provied kind SliceKind . |
| universal | Converts a slice to universal SliceKind . |
| canonical | Converts a slice to canonical SliceKind . |
| assumeCanonical | Converts a slice to canonical SliceKind . Does only assert checks. |
| assumeContiguous | Converts a slice to contiguous SliceKind . Does only assert checks. |
| assumeHypercube | Helps the compiler to use optimisations related to the shape form. Does only assert checks. |
| assumeSameShape | Helps the compiler to use optimisations related to the shape form. Does only assert checks. |
Function Name Description
| cartesian | Cartesian product. |
| kronecker | Kronecker product. |
Function Name Description
| as | Convenience function that creates a lazy view, where each element of the original slice is converted to a type T. |
| bitpack | Bitpack slice over an unsigned integral slice. |
| bitwise | Bitwise slice over an unsigned integral slice. |
| bytegroup | Groups existing slice into fixed length chunks and uses them as data store for destination type. |
| cached | Random access cache. It is usefull in combiation with map and vmap. |
| cachedGC | Random access cache auto-allocated in GC heap. It is usefull in combiation with map and vmap. |
| diff | Differences between vector elements. |
| flattened | Contiguous 1-dimensional slice of all elements of a slice. |
| map | Multidimensional functional map. |
| member | Field (element's member) projection. |
| orthogonalReduceField | Functional deep-element wise reduce of a slice composed of fields or iterators. |
| pairwise | Pairwise map for vectors. |
| pairwiseMapSubSlices | Maps pairwise index pairs to subslices. |
| retro | Reverses order of iteration for all dimensions. |
| slide | Lazy convolution for tensors. |
| slideAlong | Lazy convolution for tensors. |
| stairs | Two functions to pack, unpack, and iterate triangular and symmetric matrix storage. |
| stride | Strides 1-dimensional slice. |
| subSlices | Maps index pairs to subslices. |
| triplets | Constructs a lazy view of triplets with left, center, and right members. The topology is usefull for Math and Physics. |
| unzip | Selects a slice from a zipped slice. |
| withNeighboursSum | Zip view of elements packed with sum of their neighbours. |
| zip | Zips slices into a slice of refTuples. |
Subspace selectors serve to generalize and combine other selectors easily.
For a slice of Slice!(Iterator, N, kind) type slice.pack!K creates a slice of
slices of Slice!(kind, [N - K, K], Iterator) type by packing
the last K dimensions of the top dimension pack,
and the type of element of flattened is Slice!(Iterator, K).
Another way to use pack is transposition of dimension packs using
evertPack.
Examples of use of subspace selectors are available for selectors,
Slice.shape , and Slice.elementCount .
Sponsors
Part of this work has been sponsored by Symmetry Investments and Kaleidic Associates.
topology : (alias template) images_mir_slice_views.flattened = mir.ndslice.topology.flattened(Iterator, ulong N, mir_slice_kind kind)(Slice!(Iterator, N, kind) slice) if (N != 1 && (kind != Contiguous))A contiguous 1-dimensional slice of all elements of a slice.
flattened iterates existing data.
The order of elements is preserved.
flattened can be generalized with other selectors.
flattened, (alias template) images_mir_slice_views.member = mir.ndslice.topology.member(string name) if (name.length)Field (element's member) projection.
member;
import (package) sparklessparkles.(package) sparkles.basebase.(module) sparkles.base.bufferA @nogc container with Small Buffer Optimization (SBO).
Provides an append-only buffer that stores small amounts of data inline
(avoiding heap allocation) and automatically switches to heap storage
when capacity is exceeded.
Primary use case: appending elements in a temporary scope where GC
allocation is not desired.
buffer : (alias template) images_mir_slice_views.UniqueBuffer = sparkles.base.buffer.UniqueBuffer(T, ulong N = max(size_t(1), (T[]).sizeof / T.sizeof))Small-buffer optimization with a sole owner: inline while the elements fit, heap
when they do not, and copying is disabled.
Disabling copies is what removes the reference count from the grow path — there
is no second owner to consult. Hand a finished one to the shared world with
toShared, which consumes it and transfers any heap block without reallocating.
UniqueBuffer;
/// The pixel: four 8-bit samples, straight alpha, in memory order.
struct (struct) images_mir_slice_views.Rgba8The pixel: four 8-bit samples, straight alpha, in memory order.
Rgba8
{
ubyte (field) ubyte images_mir_slice_views.Rgba8.rr, (field) ubyte images_mir_slice_views.Rgba8.gg, (field) ubyte images_mir_slice_views.Rgba8.bb, (field) ubyte images_mir_slice_views.Rgba8.aa;
}
static assert((struct) images_mir_slice_views.Rgba8The pixel: four 8-bit samples, straight alpha, in memory order.
Rgba8.(constant) ulong images_mir_slice_views.Rgba8.sizeof = 4LUsizeof == 4 && (struct) images_mir_slice_views.Rgba8The pixel: four 8-bit samples, straight alpha, in memory order.
Rgba8.alignof == 1);
enum (alias) object.size_t = ulongsize_t (constant) ulong images_mir_slice_views.width = 6LUwidth = 6;
enum (alias) object.size_t = ulongsize_t (constant) ulong images_mir_slice_views.height = 4LUheight = 4;
/// A deterministic test pattern: every sample depends on (x, y).
(struct) images_mir_slice_views.Rgba8The pixel: four 8-bit samples, straight alpha, in memory order.
Rgba8 images_mir_slice_views.Rgba8 images_mir_slice_views.pattern(ulong y, ulong x) pure nothrow @nogc @safeA deterministic test pattern: every sample depends on (x, y).
pattern((alias) object.size_t = ulongsize_t (parameter) ulong yy, (alias) object.size_t = ulongsize_t (parameter) ulong xx) @safe pure nothrow @nogc
=> (struct) images_mir_slice_views.Rgba8The pixel: four 8-bit samples, straight alpha, in memory order.
Rgba8(cast(ubyte) ((parameter) ulong xx * 40), cast(ubyte) ((parameter) ulong yy * 60), cast(ubyte) ((parameter) ulong xx + (parameter) ulong yy * (constant) ulong images_mir_slice_views.width = 6LUwidth), cast(ubyte) (255 - (parameter) ulong xx * 20));
/// FNV-1a over every sample a byte slice of any dimension and kind visits, in
/// row-major order. Generic over the slice, so attributes are inferred.
uint uint images_mir_slice_views.fnv1a!(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous))(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) bytes) pure nothrow @nogc @safeFNV-1a over every sample a byte slice of any dimension and kind visits, in
row-major order. Generic over the slice, so attributes are inferred.
fnv1a(S)((alias) S = mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous)S (parameter) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) bytesbytes)
{
uint (local variable) uint hh = 2_166_136_261;
foreach ((local variable) ubyte bb; (parameter) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) bytesbytes.mir.ndslice.slice.Slice!(ubyte*, 1LU, mir_slice_kind.contiguous) mir.ndslice.topology.flattened!(ubyte*, 3LU)(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) slice) pure nothrow @nogc @safeA contiguous 1-dimensional slice of all elements of a slice.
flattened iterates existing data.
The order of elements is preserved.
flattened can be generalized with other selectors.
flattened)
{
(local variable) uint hh ^= (local variable) ubyte bb;
(local variable) uint hh *= 16_777_619;
}
return (local variable) uint hh;
}
/// Fills an RGBA image view in place: the function sees only a `Slice`, never
/// the owner. `@safe pure nothrow @nogc` holds for any contiguous view.
void void images_mir_slice_views.fill(mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) img) pure nothrow @nogc @safeFills an RGBA image view in place: the function sees only a Slice, never
the owner. @safe pure nothrow @nogc holds for any contiguous view.
fill(Slice!(Rgba8*, 2) (parameter) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg) @safe pure nothrow @nogc
{
foreach ((local variable) ulong yy; 0 .. (parameter) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg.ulong mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.contiguous).mir_slice.length!0LU() const pure nothrow @nogc @property scope @safeMultidimensional length property.
length!0)
foreach ((local variable) ulong xx; 0 .. (parameter) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg.ulong mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.contiguous).mir_slice.length!1LU() const pure nothrow @nogc @property scope @safeMultidimensional length property.
length!1)
(parameter) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg[(local variable) ulong yy, (local variable) ulong xx] = images_mir_slice_views.Rgba8 mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.contiguous).mir_slice.opIndexAssign!()(images_mir_slice_views.Rgba8 value, ulong[2] _indices...) pure nothrow @nogc ref return scope @trustedAssignment of a value (e.g. a number) to a fully defined index.
pattern(images_mir_slice_views.Rgba8 mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.contiguous).mir_slice.opIndexAssign!()(images_mir_slice_views.Rgba8 value, ulong[2] _indices...) pure nothrow @nogc ref return scope @trustedAssignment of a value (e.g. a number) to a fully defined index.
y, (local variable) ulong xx);
}
/// Sum of the red channel through a `member` projection, for a view of any
/// kind: the same code runs on the full image, a crop and a transpose.
(alias) object.size_t = ulongsize_t ulong images_mir_slice_views.redSum!(images_mir_slice_views.Rgba8*, mir_slice_kind.canonical)(mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) img) pure nothrow @nogc @safeSum of the red channel through a member projection, for a view of any
kind: the same code runs on the full image, a crop and a transpose.
redSum(Iterator, SliceKind kind)(Slice!(Iterator, 2, (constant) mir.ndslice.slice.mir_slice_kind images_mir_slice_views.kind = mir_slice_kind.canonicalkind) (parameter) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) imgimg)
{
(alias) object.size_t = ulongsize_t (local variable) ulong ss;
foreach ((local variable) ubyte vv; (parameter) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) imgimg.mir.ndslice.slice.Slice!(MemberIterator!(Rgba8*, "r"), 2LU, mir_slice_kind.canonical) mir.ndslice.topology.member!"r".member!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.canonical)(mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) slice) pure nothrow @nogc @safeField (element's member) projection.
Examples
// struct, union or class
struct S
{
// Property support
// Getter always must be defined.
double _x;
double x() @property
{
return x;
}
void x(double x) @property
{
_x = x;
}
/// Field support
double y;
/// Zero argument function support
double f()
{
return _x * 2;
}
}
import mir.ndslice.allocation: slice;
import mir.ndslice.topology: iota;
auto matrix = slice!S(2, 3);
matrix.member!"x"[] = [2, 3].iota;
matrix.member!"y"[] = matrix.member!"f";
assert(matrix.member!"y" == [2, 3].iota * 2);
member!"r".mir.ndslice.slice.Slice!(FlattenedIterator!(MemberIterator!(Rgba8*, "r"), 2LU, mir_slice_kind.canonical), 1LU, mir_slice_kind.contiguous) mir.ndslice.topology.flattened!(mir.ndslice.iterator.MemberIterator!(Rgba8*, "r"), 2LU, mir_slice_kind.canonical)(mir.ndslice.slice.Slice!(MemberIterator!(Rgba8*, "r"), 2LU, mir_slice_kind.canonical) slice) pure nothrow @nogc @safeA contiguous 1-dimensional slice of all elements of a slice.
flattened iterates existing data.
The order of elements is preserved.
flattened can be generalized with other selectors.
flattened)
(local variable) ulong ss += (local variable) ubyte vv;
return (local variable) ulong ss;
}
void void D main() @safemain() @safe
{
// The owner: a move-only Sparkles buffer, inline up to 64 bytes, on the
// heap above (96 bytes here).
(alias) sparkles.base.buffer.UniqueBuffer!(ubyte, 64LU) = sparkles.base.buffer.Buffer!(ubyte, 64LU, cast(Storage)cast(ubyte)7u)Small-buffer optimization with a sole owner: inline while the elements fit, heap
when they do not, and copying is disabled.
Disabling copies is what removes the reference count from the grow path — there
is no second owner to consult. Hand a finished one to the shared world with
toShared, which consumes it and transfers any heap block without reallocating.
UniqueBuffer!(ubyte, 64) (local variable) sparkles.base.buffer.Buffer!(ubyte, 64LU, cast(Storage)cast(ubyte)7u) storagestorage;
(local variable) sparkles.base.buffer.Buffer!(ubyte, 64LU, cast(Storage)cast(ubyte)7u) storagestorage.void sparkles.base.buffer.Buffer!(ubyte, 64LU, cast(Storage)cast(ubyte)7u).length(ulong newLength) pure nothrow @nogc @property @trustedSets the element count. Growing appends T.init-filled elements (one
storage growth); shrinking drops elements from the back and keeps the
storage, whichever it is (BUF13) — a buffer that has spilled to the
heap stays there until clear or the destructor, so a shrink costs
neither a copy back into the inline slots nor a free.
Output range interface: appends a single element.
length = (constant) ulong images_mir_slice_views.width = 6LUwidth * (constant) ulong images_mir_slice_views.height = 4LUheight * (struct) images_mir_slice_views.Rgba8The pixel: four 8-bit samples, straight alpha, in memory order.
Rgba8.(constant) ulong images_mir_slice_views.Rgba8.sizeof = 4LUsizeof;
// Borrow its bytes. `opSlice` is `return scope`, so `bytes` cannot
// outlive `storage` under dip1000.
ubyte[] (local variable) ubyte[] bytesbytes = (local variable) sparkles.base.buffer.Buffer!(ubyte, 64LU, cast(Storage)cast(ubyte)7u) storagestorage[];
// 1. The same memory as a 2-D slice of pixels and as a 3-D slice of bytes.
// `cast(Rgba8[])` of a `ubyte[]` is `@safe`: neither type has
// indirections, and the length is checked at run time.
auto (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg = (cast((struct) images_mir_slice_views.Rgba8The pixel: four 8-bit samples, straight alpha, in memory order.
Rgba8[]) (local variable) ubyte[] bytesbytes).mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) mir.ndslice.slice.sliced!(2LU, images_mir_slice_views.Rgba8[])(return scope images_mir_slice_views.Rgba8[] iterator, ulong[2] lengths...) pure nothrow @nogc @safeCreates an n-dimensional slice-shell over an iterator.
Examples
Random access range primitives for slices over user defined types
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);
sliced((constant) ulong images_mir_slice_views.height = 4LUheight, (constant) ulong images_mir_slice_views.width = 6LUwidth);
auto (local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) img3img3 = (local variable) ubyte[] bytesbytes.mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) mir.ndslice.slice.sliced!(3LU, ubyte[])(return scope ubyte[] iterator, ulong[3] lengths...) pure nothrow @nogc @safeCreates an n-dimensional slice-shell over an iterator.
Examples
Random access range primitives for slices over user defined types
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);
sliced((constant) ulong images_mir_slice_views.height = 4LUheight, (constant) ulong images_mir_slice_views.width = 6LUwidth, 4);
static assert(is(typeof((local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg) == Slice!(Rgba8*, 2, Contiguous)));
static assert(is(typeof((local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) img3img3) == Slice!(ubyte*, 3, Contiguous)));
void images_mir_slice_views.fill(mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) img) pure nothrow @nogc @safeFills an RGBA image view in place: the function sees only a Slice, never
the owner. @safe pure nothrow @nogc holds for any contiguous view.
fill((local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg);
void std.stdio.writefln!(char, ulong[2], ulong[3])(in char[] fmt, ulong[2] __param_1, ulong[3] __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln("img lengths %s, img3 lengths %s", (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg.ulong[2] mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.contiguous).mir_slice.shape!()() const pure nothrow @nogc @property scope @trustedshape, (local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) img3img3.ulong[3] mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous).mir_slice.shape!()() const pure nothrow @nogc @property scope @trustedshape);
void std.stdio.writefln!(char, images_mir_slice_views.Rgba8)(in char[] fmt, images_mir_slice_views.Rgba8 __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("img[2, 3] = %s", (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg[2, 3]);
void std.stdio.writefln!(char, mir.ndslice.slice.Slice!(ubyte*, 1LU, mir_slice_kind.contiguous))(in char[] fmt, mir.ndslice.slice.Slice!(ubyte*, 1LU, mir_slice_kind.contiguous) __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("img3[2, 3] = %s", (local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) img3img3[2, 3]);
void std.stdio.writefln!(char, uint)(in char[] fmt, uint __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("fnv1a(img3) = %08x", uint images_mir_slice_views.fnv1a!(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous))(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) bytes) pure nothrow @nogc @safeFNV-1a over every sample a byte slice of any dimension and kind visits, in
row-major order. Generic over the slice, so attributes are inferred.
fnv1a((local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) img3img3));
// 2. A crop: rows 1..3, columns 2..5. Slicing the last dimension too makes
// the view Canonical (a row stride, unit column stride).
auto (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) cropcrop = (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg[1 .. 3, 2 .. 5];
static assert(is(typeof((local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) cropcrop) == Slice!(Rgba8*, 2, Canonical)));
void std.stdio.writefln!(char, ulong[2], long[2])(in char[] fmt, ulong[2] __param_1, long[2] __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln("crop lengths %s strides %s", (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) cropcrop.ulong[2] mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.canonical).mir_slice.shape!()() const pure nothrow @nogc @property scope @trustedshape, (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) cropcrop.long[2] mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.canonical).mir_slice.strides!()() const pure nothrow @nogc @property scope @trustedstrides);
// 3. A transpose: Universal, every stride stored, still no copy.
auto (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.universal) trtr = (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg.mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.universal) mir.ndslice.dynamic.transposed!(images_mir_slice_views.Rgba8*, mir_slice_kind.contiguous)(mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) slice) pure nothrow @nogc @safeN-dimensional transpose operator.
Brings selected dimensions to the first position.
Examples
Template
import mir.ndslice.slice;
import mir.ndslice.topology: iota;
assert(iota(3, 4, 5, 6, 7)
.transposed!(3, 1, 0)
.shape == cast(size_t[5])[6, 4, 3, 5, 7]);
assert(iota(3, 4, 5, 6, 7)
.transposed!(4, 1, 0)
.shape == cast(size_t[5])[7, 4, 3, 5, 6]);
Function
import mir.ndslice.slice;
import mir.ndslice.topology: iota;
assert(iota(3, 4, 5, 6, 7)
.transposed(3, 1, 0)
.shape == cast(size_t[5])[6, 4, 3, 5, 7]);
assert(iota(3, 4, 5, 6, 7)
.transposed(4, 1, 0)
.shape == cast(size_t[5])[7, 4, 3, 5, 6]);
Single-argument function
import mir.ndslice.slice;
import mir.ndslice.topology: iota;
assert(iota(3, 4, 5, 6, 7)
.transposed(3)
.shape == cast(size_t[5])[6, 3, 4, 5, 7]);
assert(iota(3, 4, 5, 6, 7)
.transposed(4)
.shape == cast(size_t[5])[7, 3, 4, 5, 6]);
2-dimensional transpose
import mir.ndslice.slice;
import mir.ndslice.topology: iota;
assert(iota(3, 4)
.transposed
.shape == cast(size_t[2])[4, 3]);
transposed;
static assert(is(typeof((local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.universal) trtr) == Slice!(Rgba8*, 2, Universal)));
void std.stdio.writefln!(char, ulong[2], long[2])(in char[] fmt, ulong[2] __param_1, long[2] __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln("tr lengths %s strides %s", (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.universal) trtr.ulong[2] mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.universal).mir_slice.shape!()() const pure nothrow @nogc @property scope @trustedshape, (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.universal) trtr.long[2] mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.universal).mir_slice.strides!()() const pure nothrow @nogc @property scope @trustedstrides);
void std.stdio.writefln!(char, bool)(in char[] fmt, bool __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("tr[3, 2] == img[2, 3]: %s", (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.universal) trtr[3, 2] == (local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg[2, 3]);
// One generic function over all three kinds.
void std.stdio.writefln!(char, ulong, ulong, ulong)(in char[] fmt, ulong __param_1, ulong __param_2, ulong __param_3) @safeEquivalent to writef(fmt, args, '\n').
writefln("redSum img %s crop %s tr %s", ulong images_mir_slice_views.redSum!(images_mir_slice_views.Rgba8*, mir_slice_kind.contiguous)(mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) img) pure nothrow @nogc @safeSum of the red channel through a member projection, for a view of any
kind: the same code runs on the full image, a crop and a transpose.
redSum((local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.contiguous) imgimg), ulong images_mir_slice_views.redSum!(images_mir_slice_views.Rgba8*, mir_slice_kind.canonical)(mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) img) pure nothrow @nogc @safeSum of the red channel through a member projection, for a view of any
kind: the same code runs on the full image, a crop and a transpose.
redSum((local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) cropcrop), ulong images_mir_slice_views.redSum!(images_mir_slice_views.Rgba8*, mir_slice_kind.universal)(mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.universal) img) pure nothrow @nogc @safeSum of the red channel through a member projection, for a view of any
kind: the same code runs on the full image, a crop and a transpose.
redSum((local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.universal) trtr));
// 4. Writing through the crop changes the owner's bytes: a view, not a copy.
(local variable) mir.ndslice.slice.Slice!(Rgba8*, 2LU, mir_slice_kind.canonical) cropcrop[] = void mir.ndslice.slice.Slice!(images_mir_slice_views.Rgba8*, 2LU, mir_slice_kind.canonical).mir_slice.opIndexAssign!(images_mir_slice_views.Rgba8)(images_mir_slice_views.Rgba8 value) pure nothrow @nogc scope @safeAssignment of a value (e.g. a number) to a fully defined slice.
Rgba8(1, 2, 3, 4);
void std.stdio.writefln!(char, ulong, ulong, ubyte[])(in char[] fmt, ulong __param_1, ulong __param_2, ubyte[] __param_3) @safeEquivalent to writef(fmt, args, '\n').
writefln("after crop[] = (1,2,3,4): bytes[%s .. %s] = %s",
(1 * (constant) ulong images_mir_slice_views.width = 6LUwidth + 2) * 4, (1 * (constant) ulong images_mir_slice_views.width = 6LUwidth + 2) * 4 + 4,
(local variable) ubyte[] bytesbytes[(1 * (constant) ulong images_mir_slice_views.width = 6LUwidth + 2) * 4 .. (1 * (constant) ulong images_mir_slice_views.width = 6LUwidth + 2) * 4 + 4]);
void std.stdio.writefln!(char, uint)(in char[] fmt, uint __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("fnv1a(img3) = %08x", uint images_mir_slice_views.fnv1a!(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous))(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) bytes) pure nothrow @nogc @safeFNV-1a over every sample a byte slice of any dimension and kind visits, in
row-major order. Generic over the slice, so attributes are inferred.
fnv1a((local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) img3img3));
// 5. A 3-D byte view of the crop: the cropped pixel view cast to bytes is
// not expressible as a safe array cast (the crop is not one array), so
// the byte view comes from slicing the 3-D view the same way.
auto (local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical) crop3crop3 = (local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) img3img3[1 .. 3, 2 .. 5];
static assert(is(typeof((local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical) crop3crop3) == Slice!(ubyte*, 3, Canonical)));
void std.stdio.writefln!(char, ulong[3], long[3], uint)(in char[] fmt, ulong[3] __param_1, long[3] __param_2, uint __param_3) @safeEquivalent to writef(fmt, args, '\n').
writefln("crop3 lengths %s strides %s fnv1a %08x", (local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical) crop3crop3.ulong[3] mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical).mir_slice.shape!()() const pure nothrow @nogc @property scope @trustedshape, (local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical) crop3crop3.long[3] mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical).mir_slice.strides!()() const pure nothrow @nogc @property scope @trustedstrides, uint images_mir_slice_views.fnv1a!(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical))(mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical) bytes) pure nothrow @nogc @safeFNV-1a over every sample a byte slice of any dimension and kind visits, in
row-major order. Generic over the slice, so attributes are inferred.
fnv1a((local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.canonical) crop3crop3));
// 6. One channel as its own 2-D view (stride 4 bytes), via the 3-D slice.
auto (local variable) mir.ndslice.slice.Slice!(ubyte*, 2LU, mir_slice_kind.universal) alphaalpha = (local variable) mir.ndslice.slice.Slice!(ubyte*, 3LU, mir_slice_kind.contiguous) img3img3[0 .. $, 0 .. $, 3];
static assert(is(typeof((local variable) mir.ndslice.slice.Slice!(ubyte*, 2LU, mir_slice_kind.universal) alphaalpha) == Slice!(ubyte*, 2, Universal)));
void std.stdio.writefln!(char, ulong[2], long[2], mir.ndslice.slice.Slice!(ubyte*, 1LU, mir_slice_kind.universal))(in char[] fmt, ulong[2] __param_1, long[2] __param_2, mir.ndslice.slice.Slice!(ubyte*, 1LU, mir_slice_kind.universal) __param_3) @safeEquivalent to writef(fmt, args, '\n').
writefln("alpha lengths %s strides %s row 0 %s", (local variable) mir.ndslice.slice.Slice!(ubyte*, 2LU, mir_slice_kind.universal) alphaalpha.ulong[2] mir.ndslice.slice.Slice!(ubyte*, 2LU, mir_slice_kind.universal).mir_slice.shape!()() const pure nothrow @nogc @property scope @trustedshape, (local variable) mir.ndslice.slice.Slice!(ubyte*, 2LU, mir_slice_kind.universal) alphaalpha.long[2] mir.ndslice.slice.Slice!(ubyte*, 2LU, mir_slice_kind.universal).mir_slice.strides!()() const pure nothrow @nogc @property scope @trustedstrides, (local variable) mir.ndslice.slice.Slice!(ubyte*, 2LU, mir_slice_kind.universal) alphaalpha[0]);
}