devela 0.28.0

A development substrate of coherence.
Documentation
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
// devela::num::fin::ord::order::rowcol
//
//! Dense row-major and column-major ordinal encodings.
//!
//! Coordinates and dimensions use spatial axis order:
//! `[x, y, z, ...]` and `[width, height, depth, ...]`.
//!
//! Row-major order keeps the first axis contiguous.
//! Column-major order keeps the last axis contiguous.
//

use crate::{Order, is, unwrap, whilst};

/* row-major */

/// # Row-major ordinal encodings
///
/// The first coordinate axis changes fastest.
impl Order {
    /// Encodes 2D coordinates in row-major order.
    ///
    /// Does not validate coordinates or arithmetic overflow.
    #[must_use]
    #[inline]
    pub const fn row_major_from_2d(x: usize, y: usize, width: usize) -> usize {
        y * width + x
    }

    /// Encodes bounded 2D coordinates in row-major order.
    ///
    /// Returns `None` if the coordinates are out of bounds or the grid length
    /// cannot be represented by `usize`.
    #[must_use]
    pub const fn row_major_try_from_2d(
        x: usize,
        y: usize,
        width: usize,
        height: usize,
    ) -> Option<usize> {
        is! { x >= width || y >= height, return None }
        let _len = unwrap![some? width.checked_mul(height)];
        Some(Self::row_major_from_2d(x, y, width))
    }

    /// Decodes a row-major ordinal into 2D coordinates.
    ///
    /// Does not validate the ordinal. `width` must be nonzero.
    #[must_use]
    #[inline]
    pub const fn row_major_to_2d(i: usize, width: usize) -> (usize, usize) {
        (i % width, i / width)
    }

    /// Decodes a bounded row-major ordinal into 2D coordinates.
    ///
    /// Returns `None` if the grid is empty, its length overflows, or `i` is
    /// outside the grid.
    #[must_use]
    pub const fn row_major_try_to_2d(
        i: usize,
        width: usize,
        height: usize,
    ) -> Option<(usize, usize)> {
        is! { width == 0 || height == 0, return None }
        let len = unwrap![some? width.checked_mul(height)];
        is! { i >= len, return None }
        Some(Self::row_major_to_2d(i, width))
    }

    /// Encodes 3D coordinates in row-major order.
    ///
    /// Does not validate coordinates or arithmetic overflow.
    #[must_use]
    #[inline]
    pub const fn row_major_from_3d(
        x: usize,
        y: usize,
        z: usize,
        width: usize,
        height: usize,
    ) -> usize {
        (z * height + y) * width + x
    }

    /// Encodes bounded 3D coordinates in row-major order.
    ///
    /// Returns `None` if the coordinates are out of bounds or the grid length
    /// cannot be represented by `usize`.
    #[must_use]
    pub const fn row_major_try_from_3d(
        x: usize,
        y: usize,
        z: usize,
        width: usize,
        height: usize,
        depth: usize,
    ) -> Option<usize> {
        is! { x >= width || y >= height || z >= depth,return None }
        let area = unwrap![some? width.checked_mul(height)];
        let _len = unwrap![some? area.checked_mul(depth)];
        Some(Self::row_major_from_3d(x, y, z, width, height))
    }

    /// Decodes a row-major ordinal into 3D coordinates.
    ///
    /// Does not validate the ordinal. `width` and `height` must be nonzero.
    #[must_use]
    #[inline]
    pub const fn row_major_to_3d(i: usize, width: usize, height: usize) -> (usize, usize, usize) {
        let area = width * height;
        let z = i / area;
        let rem = i % area;
        let y = rem / width;
        let x = rem % width;
        (x, y, z)
    }

    /// Decodes a bounded row-major ordinal into 3D coordinates.
    #[must_use]
    pub const fn row_major_try_to_3d(
        i: usize,
        width: usize,
        height: usize,
        depth: usize,
    ) -> Option<(usize, usize, usize)> {
        is! { width == 0 || height == 0 || depth == 0, return None }
        let area = unwrap![some? width.checked_mul(height)];
        let len = unwrap![some? area.checked_mul(depth)];
        is! { i >= len, return None }
        Some(Self::row_major_to_3d(i, width, height))
    }
}

/* column-major */

/// # Column-major ordinal encodings
///
/// The last coordinate axis changes fastest.
impl Order {
    /// Encodes 2D coordinates in column-major order.
    ///
    /// Does not validate coordinates or arithmetic overflow.
    #[must_use]
    #[inline]
    pub const fn col_major_from_2d(x: usize, y: usize, height: usize) -> usize {
        x * height + y
    }

    /// Encodes bounded 2D coordinates in column-major order.
    #[must_use]
    pub const fn col_major_try_from_2d(
        x: usize,
        y: usize,
        width: usize,
        height: usize,
    ) -> Option<usize> {
        is! { x >= width || y >= height, return None }
        let _len = unwrap![some? width.checked_mul(height)];
        Some(Self::col_major_from_2d(x, y, height))
    }

    /// Decodes a column-major ordinal into 2D coordinates.
    ///
    /// Does not validate the ordinal. `height` must be nonzero.
    #[must_use]
    #[inline]
    pub const fn col_major_to_2d(i: usize, height: usize) -> (usize, usize) {
        (i / height, i % height)
    }

    /// Decodes a bounded column-major ordinal into 2D coordinates.
    #[must_use]
    pub const fn col_major_try_to_2d(
        i: usize,
        width: usize,
        height: usize,
    ) -> Option<(usize, usize)> {
        is! { width == 0 || height == 0, return None }
        let len = unwrap![some? width.checked_mul(height)];
        is! { i >= len, return None }
        Some(Self::col_major_to_2d(i, height))
    }

    /// Encodes 3D coordinates in column-major order.
    ///
    /// Does not validate coordinates or arithmetic overflow.
    #[must_use]
    #[inline]
    pub const fn col_major_from_3d(
        x: usize,
        y: usize,
        z: usize,
        height: usize,
        depth: usize,
    ) -> usize {
        (x * height + y) * depth + z
    }

    /// Encodes bounded 3D coordinates in column-major order.
    #[must_use]
    pub const fn col_major_try_from_3d(
        x: usize,
        y: usize,
        z: usize,
        width: usize,
        height: usize,
        depth: usize,
    ) -> Option<usize> {
        is! { x >= width || y >= height || z >= depth, return None }
        let area = unwrap![some? height.checked_mul(depth)];
        let _len = unwrap![some? width.checked_mul(area)];
        Some(Self::col_major_from_3d(x, y, z, height, depth))
    }

    /// Decodes a column-major ordinal into 3D coordinates.
    ///
    /// Does not validate the ordinal. `height` and `depth` must be nonzero.
    #[must_use]
    #[inline]
    pub const fn col_major_to_3d(i: usize, height: usize, depth: usize) -> (usize, usize, usize) {
        let area = height * depth;
        let x = i / area;
        let rem = i % area;
        let y = rem / depth;
        let z = rem % depth;
        (x, y, z)
    }

    /// Decodes a bounded column-major ordinal into 3D coordinates.
    #[must_use]
    pub const fn col_major_try_to_3d(
        i: usize,
        width: usize,
        height: usize,
        depth: usize,
    ) -> Option<(usize, usize, usize)> {
        is! { width == 0 || height == 0 || depth == 0, return None }
        let area = unwrap![some? height.checked_mul(depth)];
        let len = unwrap![some? width.checked_mul(area)];
        is! { i >= len, return None }
        Some(Self::col_major_to_3d(i, height, depth))
    }
}

/* N-dimensional */

/// # N-dimensional ordinal encodings
impl Order {
    /// Returns the number of coordinates in the grid.
    ///
    /// Returns `None` if the product overflows `usize`.
    ///
    /// An empty dimension makes the grid empty. A zero-dimensional grid has
    /// one coordinate, following the empty-product convention.
    #[must_use]
    pub const fn grid_volume<const N: usize>(dims: [usize; N]) -> Option<usize> {
        // The mathematical product is zero regardless of the other dimensions.
        whilst! { k in 0..N; {
            is! { dims[k] == 0, return Some(0) }
        }}
        let mut volume = 1_usize;
        whilst! { k in 0..N; {
            volume = unwrap![some? volume.checked_mul(dims[k])];
        }}
        Some(volume)
    }

    /// Computes row-major strides.
    ///
    /// The returned first stride is `1`.
    ///
    /// For `[width, height, depth]`, this returns
    /// `[1, width, width * height]`.
    #[must_use]
    pub const fn row_major_strides<const N: usize>(dims: [usize; N]) -> Option<[usize; N]> {
        let mut strides = [1_usize; N];
        whilst! { k in 1..N; {
            strides[k] = unwrap![some? strides[k - 1].checked_mul(dims[k - 1])];
        }}
        Some(strides)
    }

    /// Computes column-major strides.
    ///
    /// The returned last stride is `1`.
    ///
    /// For `[width, height, depth]`, this returns
    /// `[height * depth, depth, 1]`.
    #[must_use]
    pub const fn col_major_strides<const N: usize>(dims: [usize; N]) -> Option<[usize; N]> {
        let mut strides = [1_usize; N];
        whilst! { k in rev 1..N; {
            strides[k - 1] = unwrap![some? strides[k].checked_mul(dims[k])];
        }}
        Some(strides)
    }

    /// Encodes N-dimensional coordinates in row-major order.
    ///
    /// Does not validate coordinates, dimensions, or arithmetic overflow.
    #[must_use]
    pub const fn row_major_from<const N: usize>(coords: [usize; N], dims: [usize; N]) -> usize {
        let mut i = 0;
        whilst! { k in rev 0..N; {
            i = i * dims[k] + coords[k];
        }}
        i
    }

    /// Encodes bounded N-dimensional coordinates in row-major order.
    #[must_use]
    pub const fn row_major_try_from<const N: usize>(
        coords: [usize; N],
        dims: [usize; N],
    ) -> Option<usize> {
        whilst! { k in 0..N; {
            is! { coords[k] >= dims[k], return None }
        }}
        let _volume = unwrap![some? Self::grid_volume(dims)];
        Some(Self::row_major_from(coords, dims))
    }

    /// Decodes a row-major ordinal into N-dimensional coordinates.
    ///
    /// Does not validate the ordinal. Every dimension must be nonzero.
    #[must_use]
    pub const fn row_major_to<const N: usize>(mut i: usize, dims: [usize; N]) -> [usize; N] {
        let mut coords = [0; N];
        whilst! { k in 0..N; {
            coords[k] = i % dims[k];
            i /= dims[k];
        }}
        coords
    }

    /// Decodes a bounded row-major ordinal into N-dimensional coordinates.
    #[must_use]
    pub const fn row_major_try_to<const N: usize>(
        i: usize,
        dims: [usize; N],
    ) -> Option<[usize; N]> {
        let volume = unwrap![some? Self::grid_volume(dims)];
        is! { i >= volume, return None }
        Some(Self::row_major_to(i, dims))
    }

    /// Encodes N-dimensional coordinates in column-major order.
    ///
    /// Does not validate coordinates, dimensions, or arithmetic overflow.
    #[must_use]
    pub const fn col_major_from<const N: usize>(coords: [usize; N], dims: [usize; N]) -> usize {
        let mut i = 0;
        whilst! { k in 0..N; {
            i = i * dims[k] + coords[k];
        }}
        i
    }

    /// Encodes bounded N-dimensional coordinates in column-major order.
    #[must_use]
    pub const fn col_major_try_from<const N: usize>(
        coords: [usize; N],
        dims: [usize; N],
    ) -> Option<usize> {
        whilst! { k in 0..N; {
            if coords[k] >= dims[k] {
                return None;
            }
        }}
        let _volume = unwrap![some? Self::grid_volume(dims)];
        Some(Self::col_major_from(coords, dims))
    }

    /// Decodes a column-major ordinal into N-dimensional coordinates.
    ///
    /// Does not validate the ordinal. Every dimension must be nonzero.
    #[must_use]
    pub const fn col_major_to<const N: usize>(mut i: usize, dims: [usize; N]) -> [usize; N] {
        let mut coords = [0; N];
        whilst! { k in rev 0..N; {
            coords[k] = i % dims[k];
            i /= dims[k];
        }}
        coords
    }

    /// Decodes a bounded column-major ordinal into N-dimensional coordinates.
    #[must_use]
    pub const fn col_major_try_to<const N: usize>(
        i: usize,
        dims: [usize; N],
    ) -> Option<[usize; N]> {
        let volume = unwrap![some? Self::grid_volume(dims)];
        is! { i >= volume, return None }
        Some(Self::col_major_to(i, dims))
    }
}

#[cfg(test)]
mod tests {
    use crate::Order;
    #[test]
    fn row_major_2d_roundtrip() {
        let (width, height) = (4, 3);
        for y in 0..height {
            for x in 0..width {
                let i = Order::row_major_from_2d(x, y, width);
                assert_eq!(Order::row_major_to_2d(i, width), (x, y));
                assert_eq!(Order::row_major_try_from_2d(x, y, width, height), Some(i),);
                assert_eq!(Order::row_major_try_to_2d(i, width, height), Some((x, y)),);
            }
        }
    }
    #[test]
    fn col_major_2d_roundtrip() {
        let (width, height) = (4, 3);
        for x in 0..width {
            for y in 0..height {
                let i = Order::col_major_from_2d(x, y, height);
                assert_eq!(Order::col_major_to_2d(i, height), (x, y));
                assert_eq!(Order::col_major_try_from_2d(x, y, width, height), Some(i),);
                assert_eq!(Order::col_major_try_to_2d(i, width, height), Some((x, y)),);
            }
        }
    }
    #[test]
    fn major_3d_roundtrip() {
        let (width, height, depth) = (4, 3, 2);
        let len = width * height * depth;
        for i in 0..len {
            let row = Order::row_major_to_3d(i, width, height);
            assert_eq!(Order::row_major_from_3d(row.0, row.1, row.2, width, height), i,);
            let col = Order::col_major_to_3d(i, height, depth);
            assert_eq!(Order::col_major_from_3d(col.0, col.1, col.2, height, depth), i,);
        }
        assert_eq!(Order::row_major_try_from_3d(2, 1, 1, width, height, depth), Some(18),);
        assert_eq!(Order::col_major_try_from_3d(2, 1, 1, width, height, depth), Some(15),);
    }
    #[test]
    fn generic_matches_fixed() {
        let dims = [4, 3, 2];
        assert_eq!(Order::row_major_strides(dims), Some([1, 4, 12]),);
        assert_eq!(Order::col_major_strides(dims), Some([6, 2, 1]),);
        assert_eq!(Order::row_major_from([2, 1, 1], dims), Order::row_major_from_3d(2, 1, 1, 4, 3),);
        assert_eq!(Order::col_major_from([2, 1, 1], dims), Order::col_major_from_3d(2, 1, 1, 3, 2),);
        for i in 0..24 {
            let row = Order::row_major_to(i, dims);
            let col = Order::col_major_to(i, dims);
            assert_eq!(Order::row_major_from(row, dims), i);
            assert_eq!(Order::col_major_from(col, dims), i);
        }
    }
    #[test]
    fn checked_boundaries() {
        assert_eq!(Order::row_major_try_from_2d(4, 0, 4, 3), None);
        assert_eq!(Order::row_major_try_to_2d(12, 4, 3), None);
        assert_eq!(Order::col_major_try_to_2d(0, 4, 0), None);
        assert_eq!(Order::grid_volume([usize::MAX, 2]), None);
        assert_eq!(Order::grid_volume([usize::MAX, 2, 0]), Some(0),);
        assert_eq!(Order::row_major_try_from([], []), Some(0));
        assert_eq!(Order::row_major_try_to(0, []), Some([]));
        assert_eq!(Order::row_major_try_to(1, []), None);
    }
}