matrix-slice 1.1.0

Safe abstractions for two-dimensional slices.
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
//! Implements references to blocks of a matrix.
//!
//! Consider a reference to a slice (sometimes also just called slice). Typically, it is created by
//! unsizing a reference to an array through type coercion, such as sing `&[0, 1, 2]` in a
//! parameter to function that takes `&[u32]` which turns a reference `&[u32; 3]` to a slice
//! `&[u32]`. The length of the slice, controlling the number of elements and thus the provenance
//! of access that the reference allows, is stored in a tag alongside the pointer to its elements
//! and initialized from the known length of the array. Since this tag is a runtime value we can
//! manipulate it while upholding the invariants required by the type system.
//!
//! This is analogous to that but for blocks of a matrix. A block is a rectangular region of a
//! matrix where the matrix provides an underlying pitch (or stride) between rows and a total
//! number of elements and the block the number of rows and columns that are spanned, i.e. are
//! allowed to be accessed by (mutable) reference.
//!
//! ## Treatment of empty blocks
//!
//! A block may have zero rows or zero columns. In either case the block is empty and provides no
//! access to any elements yet will still return an empty slice for some operations that would
//! otherwise access multiple elements. The memory address of such a block is **not** necessarily
//! at its expected location but it will be in-bounds of the underlying matrix data.
//!
//! Consider the bottom right `2x2` block of a row-major `3x3` matrix.
//!
//! ```text
//! +---+---+---+
//! | x | x | x |
//! +---+---+---+
//! | x | 4 | 5 |
//! +---+---+---+
//! | x | 7 | 8 |
//! +---+---+---+
//! ```
//!
//! This block has a pitch of 3 but only spans 2 columns. If we would naively calculate the address
//! of its past-the-end element we would get an element below `7` which is out-of-bounds. Hence if
//! we split this at row 2, into itself and an empty `0x2` block, the latter block's data pointer
//! would be created with undefined behavior. Instead, we sacrifice the ability to 'locate' such
//! empty blocks and instead have them point at an arbitrary (empty) in-bounds slice within the
//! matrix. (Currently, that is the start of the block from which it was created).
#![no_std]
use core::{cell::Cell, fmt, marker::PhantomData, ops, ptr::NonNull};

/// The Readme of the crate and links to further documentation.
///
/// Note: This module only exists on `cfg(doc)` builds, do not refer to it.
///
#[cfg(doc)]
#[doc = include_str!("../Readme.md")]
pub mod docs {
    /// A discussion of the approach, alternatives, trade-offs and context.
    ///
    #[doc = include_str!("../docs/development_log.md")]
    pub const DEVELOPMENT_NOTES: () = ();

    /// Documentation of each released version.
    ///
    #[doc = include_str!("../Changes.md")]
    pub const CHANGELOG: () = ();
}

/// Create a block reference from a full matrix represented as an array of rows.
///
/// # Examples
///
/// ```
/// let data = &mut [
///    [0, 1, 2],
///    [3, 4, 5],
/// ];
///
/// let mut block = matrix_slice::from_array_rows(data);
///
/// assert_eq!(block.rows(), 2);
/// assert_eq!(block.cols(), 3);
///
/// assert_eq!(block[(1, 1)], 4);
/// ```
pub fn from_array_rows<'a, T, const N: usize>(data: &'a [[T; N]]) -> BlockRef<'a, T> {
    BlockRef {
        block: BlockSlice {
            rows: data.len(),
            cols: N,
            pitch: N,
        },
        data: NonNull::from_ref(data).cast(),
        lifetime: PhantomData,
    }
}

/// A reference to a block of a matrix with shared access to elements.
#[derive(Copy, Clone)]
pub struct BlockRef<'a, T> {
    data: NonNull<T>,
    block: BlockSlice,
    lifetime: PhantomData<&'a [T]>,
}

// SAFETY: See `&[T]`. The reference can be used to, potentially, get a `&T` for each element in
// the block and thus the block itself provides the exact same properties as `T`. The `BlockRef` is
// then `&[T]` itself and thus has properties of a reference to such a type. Refer to the
// reference: <https://doc.rust-lang.org/stable/std/primitive.reference.html>
//
// We have `&T: Sync` iff `T: Sync`
unsafe impl<T> Sync for BlockRef<'_, T> where T: Sync {}
// We have `&T: Send` iff `T: Sync`
unsafe impl<T> Send for BlockRef<'_, T> where T: Sync {}

const _: () = {
    // We can coerce a block to a shorter lifetime.
    fn _coerce_block<'a, 'b: 'a, T>(v: BlockRef<'b, T>) -> BlockRef<'a, T> {
        v
    }

    // We can coerce a reference to a block to a shorter lifetime.
    fn _coerce_covariant<'lt, 'a, 'b: 'a, T>(v: &'lt BlockRef<'b, T>) -> &'lt BlockRef<'a, T> {
        v
    }

    fn _coerce_covariant_fn<'lt, 'a, 'b: 'a, T>(v: fn(BlockRef<'a, T>)) -> fn(BlockRef<'b, T>) {
        v
    }

    fn _coerce_item_covariant<'lt, 'a, 'b: 'a, T>(v: BlockRef<'lt, &'b T>) -> BlockRef<'lt, &'a T> {
        v
    }
};

/// Creates an empty block reference, within a matrix of a dangling slice.
impl<T> Default for BlockRef<'_, T> {
    fn default() -> Self {
        from_array_rows::<T, 0>(&[])
    }
}

impl<'data, T> BlockRef<'data, T> {
    /// Create a new block reference from a raw slice and pitch.
    ///
    /// The resulting block refers to the whole matrix.
    ///
    /// # Panics
    ///
    /// Panics if the length of `data` is not a multiple of `pitch`.
    pub fn new(data: &'data [T], pitch: usize) -> Self {
        assert!(data.len().is_multiple_of(pitch));

        BlockRef {
            block: BlockSlice {
                rows: data.len() / pitch,
                cols: pitch,
                pitch,
            },
            data: NonNull::from_ref(data).cast(),
            lifetime: PhantomData,
        }
    }

    /// Number of rows in this block.
    pub fn rows(&self) -> usize {
        self.block.rows
    }

    /// Number of columns in this block.
    pub fn cols(&self) -> usize {
        self.block.cols
    }

    /// Divide into two blocks at the given column.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &[
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    /// ];
    ///
    /// let block = matrix_slice::from_array_rows(data);
    /// let (left, right) = block.split_at_col(2);
    ///
    /// assert_eq!(left[(1, 0)], 3);
    /// assert_eq!(right[(1, 0)], 5);
    /// ```
    pub fn split_at_col(self, mid: usize) -> (BlockRef<'data, T>, BlockRef<'data, T>) {
        self.split_at_col_checked(mid).unwrap()
    }

    /// Divide into two blocks at the given column.
    ///
    /// See [`Self::split_at_col`] but returns `None` if out of bounds.
    pub fn split_at_col_checked(
        self,
        mid: usize,
    ) -> Option<(BlockRef<'data, T>, BlockRef<'data, T>)> {
        if let Some((lhs, rhs, offset)) = self.block.split_at_col(mid) {
            Some((
                BlockRef {
                    data: self.data,
                    block: lhs,
                    lifetime: self.lifetime,
                },
                BlockRef {
                    data: unsafe { self.data.add(offset) },
                    block: rhs,
                    lifetime: self.lifetime,
                },
            ))
        } else {
            None
        }
    }

    /// Divide into two blocks at the given row.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &[
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    /// ];
    ///
    /// let block = matrix_slice::from_array_rows(data);
    /// let (top, bot) = block.split_at_row(1);
    ///
    /// assert_eq!(top[(0, 2)], 2);
    /// assert_eq!(bot[(0, 2)], 5);
    /// ```
    pub fn split_at_row(self, mid: usize) -> (BlockRef<'data, T>, BlockRef<'data, T>) {
        self.split_at_row_checked(mid).unwrap()
    }

    /// Divide into two blocks at the given row.
    ///
    /// See [`Self::split_at_row`] but returns `None` if out of bounds.
    pub fn split_at_row_checked(
        self,
        mid: usize,
    ) -> Option<(BlockRef<'data, T>, BlockRef<'data, T>)> {
        if let Some((lhs, rhs, offset)) = self.block.split_at_row(mid) {
            Some((
                BlockRef {
                    data: self.data,
                    block: lhs,
                    lifetime: self.lifetime,
                },
                BlockRef {
                    data: unsafe { self.data.add(offset) },
                    block: rhs,
                    lifetime: self.lifetime,
                },
            ))
        } else {
            None
        }
    }

    /// Choose a single row and refer to its data.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &[
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    ///     [6, 7, 8],
    /// ];
    ///
    /// let block = matrix_slice::from_array_rows(data);
    /// let row = block.row(1);
    /// assert_eq!(row[0], 3);
    /// ```
    pub fn row(self, row: usize) -> VecRef<'data, T> {
        let (_, block, offset) = self.block.split_at_row(row).unwrap();
        assert!(block.rows >= 1);

        VecRef {
            block: VectorSlice {
                count: block.cols,
                pitch: 1,
            },
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        }
    }

    /// Choose a single column and refer to its data.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &[
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    ///     [6, 7, 8],
    /// ];
    ///
    /// let block = matrix_slice::from_array_rows(data);
    /// let row = block.col(1);
    /// assert_eq!(row[0], 1);
    /// ```
    pub fn col(self, col: usize) -> VecRef<'data, T> {
        let (_, block, offset) = self.block.split_at_col(col).unwrap();
        assert!(block.cols >= 1);

        VecRef {
            block: VectorSlice {
                count: block.rows,
                pitch: block.pitch,
            },
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        }
    }

    /// Choose a range of rows and contract the block to that.
    ///
    /// The argument type is flexible, allowing ranges (`1..3`), half open ranges (`2..` and `..2`)
    /// among others. See the [`MatrixIndex`] trait, which is sealed though as its details are not
    /// yet finalized.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &[
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    ///     [6, 7, 8],
    /// ];
    ///
    /// let block = matrix_slice::from_array_rows(data);
    ///
    /// let center = block.select_rows(1..2).unwrap();
    /// assert_eq!(center.rows(), 1);
    /// assert_eq!(center.cols(), 3);
    /// assert_eq!(center[(0, 1)], 4);
    /// ```
    pub fn select_rows<R>(self, range: R) -> Option<BlockRef<'data, T>>
    where
        R: MatrixIndex,
    {
        let (start, len) = range.into_start_and_len(self.block.rows)?;
        let (_, block, offset) = self.block.split_at_row(start)?;
        // Safety: ensures that the resulting block is more constrained, this property should be
        // ensured by our sealed `MatrixIndex` implementations.
        assert!(block.rows >= len);

        Some(BlockRef {
            block: BlockSlice { rows: len, ..block },
            // SAFETY: offset is in-bounds as per `split_at_row` contract.
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        })
    }

    /// Choose a range of columns and contract the block to that.
    ///
    /// The argument type is flexible, allowing ranges (`1..3`), half open ranges (`2..` and `..2`)
    /// among others. See the [`MatrixIndex`] trait, which is sealed though as its details are not
    /// yet finalized.
    pub fn select_cols<R>(self, range: R) -> Option<BlockRef<'data, T>>
    where
        R: MatrixIndex,
    {
        let (start, len) = range.into_start_and_len(self.block.rows)?;
        let (_, block, offset) = self.block.split_at_col(start)?;
        assert!(block.cols >= len);

        Some(BlockRef {
            block: BlockSlice { cols: len, ..block },
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        })
    }

    /// Choose a sub-block by its range of rows and columns.
    pub fn select(
        self,
        row_range: impl MatrixIndex,
        col_range: impl MatrixIndex,
    ) -> Option<BlockRef<'data, T>> {
        let block = self.select_rows(row_range)?;
        block.select_cols(col_range)
    }

    /// Extract a contiguous underlying slice of elements if the block is contiguous.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &[[0u32; 3]; 3];
    /// let block = matrix_slice::from_array_rows(data);
    ///
    /// let (block, _) = block.split_at_row(2);
    /// assert!(block.into_contiguous_slice().is_some());
    ///
    /// let (pre, post) = block.split_at_col(2);
    /// assert!(pre.into_contiguous_slice().is_none());
    /// assert!(post.into_contiguous_slice().is_none());
    ///
    /// let (same, _) = block.split_at_col(3);
    /// assert!(same.into_contiguous_slice().is_some());
    /// ```
    pub fn into_contiguous_slice(self) -> Option<&'data [T]> {
        if let Some(items) = self.block.contiguous_span() {
            Some(unsafe { core::slice::from_raw_parts(self.data.as_ptr().cast(), items) })
        } else {
            None
        }
    }

    /// Turn this into a slice of the first row, assuming it is at most one row.
    fn fake_contiguity(mut self) -> &'data [T] {
        self.block.fake_contiguity();
        self.into_contiguous_slice().unwrap()
    }

    /// Extract access as a slice of arrays if the block is contiguous.
    ///
    /// The caller must choose `N` matching the number of columns.
    pub fn into_array_rows_checked<const N: usize>(self) -> Option<&'data [[T; N]]> {
        if self.block.cols == self.block.pitch && self.block.cols == N {
            Some(unsafe { core::slice::from_raw_parts(self.data.as_ptr().cast(), self.block.rows) })
        } else {
            None
        }
    }

    /// Iterate over the rows of this block.
    pub fn iter_rows(self) -> IterRows<'data, T> {
        IterRows { block: self }
    }

    /// Create a reference to this block with a shorter lifetime.
    pub fn reborrow(&self) -> BlockRef<'_, T> {
        BlockRef {
            data: self.data,
            block: self.block,
            lifetime: PhantomData,
        }
    }
}

impl<T> ops::Index<(usize, usize)> for BlockRef<'_, T> {
    type Output = T;

    fn index(&self, index: (usize, usize)) -> &Self::Output {
        let idx = self.block.in_bounds_offset(index.0, index.1);
        // SAFETY: Index is bounded by `total_span` which itself is a lower estimate of the
        // provenance of the pointer.
        unsafe { &*self.data.as_ptr().add(idx) }
    }
}

impl<T: fmt::Debug> fmt::Debug for BlockRef<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.reborrow().iter_rows()).finish()
    }
}

/// Create a mutable block reference from a full matrix represented as an array of rows.
///
/// # Examples
///
/// ```
/// let data = &mut [
///    [0, 1, 2],
///    [3, 4, 5],
/// ];
///
/// let mut block = matrix_slice::from_array_rows_mut(data);
///
/// assert_eq!(block.rows(), 2);
/// assert_eq!(block.cols(), 3);
///
/// block[(1, 1)] = 42;
///
/// assert_eq!(data[1][1], 42);
/// ```
pub fn from_array_rows_mut<'a, T, const N: usize>(data: &'a mut [[T; N]]) -> BlockMut<'a, T> {
    BlockMut {
        block: BlockSlice {
            rows: data.len(),
            cols: N,
            pitch: N,
        },
        data: NonNull::from_mut(data).cast(),
        lifetime: PhantomData,
    }
}

/// A reference to a block of a matrix with unique access to elements.
pub struct BlockMut<'a, T> {
    data: NonNull<T>,
    block: BlockSlice,
    lifetime: PhantomData<&'a mut [T]>,
}

// SAFETY: See `BlockRef` but with `&mut [T]`.
//
// We have `&mut T: Sync` iff `T: Sync`
unsafe impl<T> Sync for BlockMut<'_, T> where T: Sync {}
// We have `&mut T: Send` iff `T: Send`
unsafe impl<T> Send for BlockMut<'_, T> where T: Sync {}

/// ```compile_fail
/// use matrix_slice::BlockMut;
///
/// // This coercion must *not* be possible. The field `lifetime` ensures the right variance.
/// fn _coerce_item_not_covariant<'lt, 'a, 'b: 'a, T>(
///     v: BlockMut<'lt, &'b T>,
/// ) -> BlockMut<'lt, &'a T> {
///     v
/// //  ^ function was supposed to return data with lifetime `'b` but it is returning data with lifetime `'a`
/// }
///
/// ```compile_fail
/// use matrix_slice::BlockMut;
///
/// fn _copy_block(v: BlockMut<'_, u32>) -> [BlockMut<'_, u32>; 2] {
///    [v, v]
/// }
const _: () = {
    // We can coerce a block to a shorter lifetime.
    fn _coerce_block_mut<'a, 'b: 'a, T>(v: BlockMut<'b, T>) -> BlockMut<'a, T> {
        v
    }

    // We can coerce a reference to a block to a shorter lifetime.
    fn _coerce_covariant<'lt, 'a, 'b: 'a, T>(v: &'lt BlockMut<'b, T>) -> &'lt BlockMut<'a, T> {
        v
    }

    fn _coerce_covariant_fn<'lt, 'a, 'b: 'a, T>(v: fn(BlockMut<'a, T>)) -> fn(BlockMut<'b, T>) {
        v
    }
};

/// Creates an empty block reference, within a matrix of a dangling slice.
impl<T> Default for BlockMut<'_, T> {
    fn default() -> Self {
        from_array_rows_mut::<T, 0>(&mut [])
    }
}

impl<'data, T> BlockMut<'data, T> {
    /// Create a new block reference from a raw slice and pitch.
    ///
    /// The resulting block refers to the whole matrix.
    ///
    /// # Panics
    ///
    /// Panics if the length of `data` is not a multiple of `pitch`.
    pub fn new(data: &'data mut [T], pitch: usize) -> Self {
        assert!(data.len().is_multiple_of(pitch));

        BlockMut {
            block: BlockSlice {
                rows: data.len() / pitch,
                cols: pitch,
                pitch,
            },
            data: NonNull::from_mut(data).cast(),
            lifetime: PhantomData,
        }
    }

    /// Number of rows in this block.
    pub fn rows(&self) -> usize {
        self.block.rows
    }

    /// Number of columns in this block.
    pub fn cols(&self) -> usize {
        self.block.cols
    }

    /// Divide into two blocks at the given column.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &mut [
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    /// ];
    ///
    /// let block = matrix_slice::from_array_rows_mut(data);
    /// let (left, right) = block.split_at_col(2);
    ///
    /// assert_eq!(left[(1, 0)], 3);
    /// assert_eq!(right[(1, 0)], 5);
    /// ```
    pub fn split_at_col(self, mid: usize) -> (BlockMut<'data, T>, BlockMut<'data, T>) {
        self.split_at_col_checked(mid).unwrap()
    }

    /// Divide into two blocks at the given column.
    ///
    /// See [`Self::split_at_col`] but returns `None` if out of bounds.
    pub fn split_at_col_checked(
        self,
        mid: usize,
    ) -> Option<(BlockMut<'data, T>, BlockMut<'data, T>)> {
        if let Some((lhs, rhs, offset)) = self.block.split_at_col(mid) {
            Some((
                BlockMut {
                    data: self.data,
                    block: lhs,
                    lifetime: self.lifetime,
                },
                BlockMut {
                    data: unsafe { self.data.add(offset) },
                    block: rhs,
                    lifetime: self.lifetime,
                },
            ))
        } else {
            None
        }
    }

    /// Divide into two blocks at the given row.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &mut [
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    /// ];
    ///
    /// let block = matrix_slice::from_array_rows_mut(data);
    /// let (top, bot) = block.split_at_row(1);
    ///
    /// assert_eq!(top[(0, 2)], 2);
    /// assert_eq!(bot[(0, 2)], 5);
    /// ```
    pub fn split_at_row(self, mid: usize) -> (BlockMut<'data, T>, BlockMut<'data, T>) {
        self.split_at_row_checked(mid).unwrap()
    }

    /// Divide into two blocks at the given row.
    ///
    /// See [`Self::split_at_row`] but returns `None` if out of bounds.
    pub fn split_at_row_checked(
        self,
        mid: usize,
    ) -> Option<(BlockMut<'data, T>, BlockMut<'data, T>)> {
        if let Some((lhs, rhs, offset)) = self.block.split_at_row(mid) {
            Some((
                BlockMut {
                    data: self.data,
                    block: lhs,
                    lifetime: self.lifetime,
                },
                BlockMut {
                    data: unsafe { self.data.add(offset) },
                    block: rhs,
                    lifetime: self.lifetime,
                },
            ))
        } else {
            None
        }
    }

    /// Choose a single row and refer to its data.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &mut [
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    ///     [6, 7, 8],
    /// ];
    ///
    /// let mut block = matrix_slice::from_array_rows_mut(data);
    /// let mut row = block.reborrow().row(1);
    /// row[0] = 0x42;
    /// assert_eq!(block[(1, 0)], 0x42);
    /// ```
    pub fn row(self, row: usize) -> VecMut<'data, T> {
        let (_, block, offset) = self.block.split_at_row(row).unwrap();
        assert!(block.rows >= 1);

        VecMut {
            block: VectorSlice {
                count: block.cols,
                pitch: 1,
            },
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        }
    }

    /// Choose a single column and refer to its data.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &mut [
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    ///     [6, 7, 8],
    /// ];
    ///
    /// let mut block = matrix_slice::from_array_rows_mut(data);
    /// let mut row = block.reborrow().col(1);
    /// row[0] = 0x42;
    /// assert_eq!(block[(0, 1)], 0x42);
    /// ```
    pub fn col(self, col: usize) -> VecMut<'data, T> {
        let (_, block, offset) = self.block.split_at_col(col).unwrap();
        assert!(block.cols >= 1);

        VecMut {
            block: VectorSlice {
                count: block.rows,
                pitch: block.pitch,
            },
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        }
    }

    /// Choose a range of rows and contract the block to that.
    ///
    /// The argument type is flexible, allowing ranges (`1..3`), half open ranges (`2..` and `..2`)
    /// among others. See the [`MatrixIndex`] trait, which is sealed though as its details are not
    /// yet finalized.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &mut [
    ///     [0, 1, 2],
    ///     [3, 4, 5],
    ///     [6, 7, 8],
    /// ];
    ///
    /// let block = matrix_slice::from_array_rows_mut(data);
    ///
    /// let center = block.select_rows(1..2).unwrap();
    /// assert_eq!(center.rows(), 1);
    /// assert_eq!(center.cols(), 3);
    /// assert_eq!(center[(0, 1)], 4);
    /// ```
    pub fn select_rows<R>(self, range: R) -> Option<BlockMut<'data, T>>
    where
        R: MatrixIndex,
    {
        let (start, len) = range.into_start_and_len(self.block.rows)?;
        let (_, block, offset) = self.block.split_at_row(start)?;
        assert!(block.rows >= len);

        Some(BlockMut {
            block: BlockSlice { rows: len, ..block },
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        })
    }

    /// Choose a range of columns and contract the block to that.
    ///
    /// The argument type is flexible, allowing ranges (`1..3`), half open ranges (`2..` and `..2`)
    /// among others. See the [`MatrixIndex`] trait, which is sealed though as its details are not
    /// yet finalized.
    pub fn select_cols<R>(self, range: R) -> Option<BlockMut<'data, T>>
    where
        R: MatrixIndex,
    {
        let (start, len) = range.into_start_and_len(self.block.rows)?;
        let (_, block, offset) = self.block.split_at_col(start)?;
        assert!(block.cols >= len);

        Some(BlockMut {
            block: BlockSlice { cols: len, ..block },
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        })
    }

    /// Choose a sub-block by its range of rows and columns.
    pub fn select(
        self,
        row_range: impl MatrixIndex,
        col_range: impl MatrixIndex,
    ) -> Option<BlockMut<'data, T>> {
        let block = self.select_rows(row_range)?;
        block.select_cols(col_range)
    }

    /// Extract a contiguous underlying slice of elements if the block is contiguous.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &mut [[0u32; 3]; 3];
    /// let mut block = matrix_slice::from_array_rows_mut(data);
    ///
    /// let (mut part, _) = block.reborrow().split_at_row(2);
    /// assert!(part.into_contiguous_slice().is_some());
    ///
    /// let (pre, post) = block.reborrow().split_at_col(2);
    /// assert!(pre.into_contiguous_slice().is_none());
    /// assert!(post.into_contiguous_slice().is_none());
    ///
    /// let (same, _) = block.reborrow().split_at_col(3);
    /// assert!(same.into_contiguous_slice().is_some());
    /// ```
    pub fn into_contiguous_slice(self) -> Option<&'data mut [T]> {
        if let Some(items) = self.block.contiguous_span() {
            Some(unsafe { core::slice::from_raw_parts_mut(self.data.as_ptr().cast(), items) })
        } else {
            None
        }
    }

    /// Turn this into a slice of the first row, assuming it is at most one row.
    fn fake_contiguity(mut self) -> &'data mut [T] {
        self.block.fake_contiguity();
        self.into_contiguous_slice().unwrap()
    }

    /// Extract access as a slice of arrays if the block is contiguous.
    ///
    /// The caller must choose `N` matching the number of columns.
    ///
    /// # Examples
    ///
    /// ```
    /// let data = &mut [[0u32; 3]; 3];
    /// let mut block = matrix_slice::from_array_rows_mut(data);
    ///
    /// // Turns this back into the same type as `data` had.
    /// assert!(block.reborrow().into_array_rows_checked::<3>().is_some());
    ///
    /// // Using an incorrect number of columns fails.
    /// assert!(block.reborrow().into_array_rows_checked::<2>().is_none());
    ///
    /// // Can still be used after splitting at rows.
    /// let (_, mut block) = block.split_at_row(2);
    /// assert!(block.reborrow().into_array_rows_checked::<3>().is_some());
    /// ```
    pub fn into_array_rows_checked<const N: usize>(self) -> Option<&'data mut [[T; N]]> {
        if self.block.cols == self.block.pitch && self.block.cols == N {
            Some(unsafe {
                core::slice::from_raw_parts_mut(self.data.as_ptr().cast(), self.block.rows)
            })
        } else {
            None
        }
    }

    /// Turn this unique reference into a shared reference.
    pub fn cast_const(self) -> BlockRef<'data, T> {
        // SAFETY: shared access can always be re-tagged from unique access.
        BlockRef {
            data: self.data,
            block: self.block,
            lifetime: PhantomData,
        }
    }

    /// Create a unique reference to this block with a shorter lifetime.
    pub fn reborrow(&mut self) -> BlockMut<'_, T> {
        // SAFETY: Unique access is created by deriving it from our current pointer so the
        // provenance is the same, and temporally it can not overlap access through the current
        // value due to the lifetime enforcing a borrow relationship.
        BlockMut {
            data: self.data,
            block: self.block,
            lifetime: PhantomData,
        }
    }

    /// Iterate over the rows of this block.
    pub fn iter_rows(self) -> IterRows<'data, T> {
        self.cast_const().iter_rows()
    }

    /// Iterate over the rows of this block.
    pub fn iter_rows_mut(self) -> IterRowsMut<'data, T> {
        IterRowsMut { block: self }
    }

    /// Modify the item type to a `Cell`, allowing interior mutability.
    ///
    /// This is the equivalent of [`Cell::from_mut`] over elements in this slice.
    pub fn as_cells(self) -> BlockMut<'data, Cell<T>> {
        // SAFETY: `Cell<T>` has the same layout as `T`.
        BlockMut {
            data: self.data.cast(),
            block: self.block,
            lifetime: PhantomData,
        }
    }
}

impl<'data, T> BlockMut<'data, Cell<T>> {
    /// Modify the item type from a `Cell` to its interior type.
    ///
    /// This is the equivalent of [`Cell::get_mut`] over elements in this slice.
    pub fn as_cell_items(self) -> BlockMut<'data, T> {
        // SAFETY: `Cell<T>` has the same layout as `T`.
        BlockMut {
            data: self.data.cast(),
            block: self.block,
            lifetime: PhantomData,
        }
    }
}

impl<T> ops::Index<(usize, usize)> for BlockMut<'_, T> {
    type Output = T;

    fn index(&self, index: (usize, usize)) -> &Self::Output {
        let idx = self.block.in_bounds_offset(index.0, index.1);
        // SAFETY: Index is bounded by `total_span` which itself is a lower estimate of the
        // provenance of the pointer.
        unsafe { &*self.data.as_ptr().add(idx) }
    }
}

impl<T> ops::IndexMut<(usize, usize)> for BlockMut<'_, T> {
    fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {
        let idx = self.block.in_bounds_offset(index.0, index.1);
        // SAFETY: Index is bounded by `total_span` which itself is a lower estimate of the
        // provenance of the pointer.
        unsafe { &mut *self.data.as_ptr().add(idx) }
    }
}

/// Represents the provenance of a pointer to a block of a matrix.
///
/// FIXME: before exposing this consider `PartialEq, … Ord` implications. These were added to
/// satisfy the `Pointee` trait requirements but really what does ordering mean? We have chosen the
/// field `pitch` to be last but that is super arbitrary.
///
/// We assume row major order here for the convention of _naming_ things. That is, when we say row
/// we mean a tightly packed slice of items. This implies that the item pitch is assumed to be `1`.
/// We have two major possible choices in representation a block-subset of a matrix: store the
/// dimensions of the block with a matrix row pitch or store the total size of the matrix and two
/// lengths.
///
/// The former of these allows us to represent both `0×N` and `M×0` blocks naturally, while the
/// latter allows one of them but provides a fast capacity that's pre-calculated. We choose the
/// former. In either case we need to store three `usize` values. Note that the total span of items
/// is *not* `rows * pitch` since the last row might be ragged.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct BlockSlice {
    rows: usize,
    cols: usize,
    pitch: usize,
}

const _: () = {
    // As per Rust 1.92's `Pointee` trait. Suspicious: `Ord`. See comment on `BlockSlice`.
    use core::{fmt, hash};

    fn _can_eventually_be_ptr_metadata<
        // Missing: `Freeze` which is unstable
        Metadata: fmt::Debug + Copy + Send + Sync + Ord + hash::Hash + Unpin,
    >() {
    }

    let _ = _can_eventually_be_ptr_metadata::<BlockSlice>;
};

impl BlockSlice {
    /// The number of elements if this block is contiguous (cols equals pitch).
    fn contiguous_span(&self) -> Option<usize> {
        if self.cols == self.pitch {
            Some(self.rows * self.cols)
        } else {
            None
        }
    }

    /// The number of elements spanned by this block (including those we are not allowed to
    /// access).
    fn total_span(&self) -> usize {
        if let Some(all_but_last) = self.rows.checked_sub(1) {
            all_but_last * self.pitch + self.cols
        } else {
            0
        }
    }

    /// The caller must ensure that this block has at most one row.
    fn fake_contiguity(&mut self) {
        debug_assert!(self.rows <= 1);
        debug_assert!(self.cols <= self.pitch);

        self.rows = self.rows.min(1);
        // SAFETY: Reducing the pitch when we have at most one row does not change the elements we
        // may refer to. The pitch always exceeds the number of columns.
        self.pitch = self.cols;
    }

    /// Split into two block descriptors.
    ///
    /// Returns `Some` with two valid blocks. The first block is in-bounds. Also returns an offset
    /// that is in-bounds of the current block and such that the elements valid for both blocks do
    /// not alias. The second block is in-bounds when interpreted as start at the offset.
    fn split_at_row(self, mid: usize) -> Option<(BlockSlice, BlockSlice, usize)> {
        let n = self.rows.checked_sub(mid)?;

        let lhs = BlockSlice {
            rows: mid,
            cols: self.cols,
            pitch: self.pitch,
        };

        let rhs = BlockSlice {
            rows: n,
            cols: self.cols,
            pitch: self.pitch,
        };

        // Careful: If we split a block after its last row (i.e. lhs and self are identical),
        // the naive offset of rows * pitch may point beyond the total span of elements covered
        // by ourselves. In this case the rhs does not cover any row so we assign it any
        // in-bounds offset.
        let offset = if n > 0 { mid * self.pitch } else { 0 };
        debug_assert!(offset <= self.total_span());

        Some((lhs, rhs, offset))
    }

    fn split_at_col(self, mid: usize) -> Option<(BlockSlice, BlockSlice, usize)> {
        let n = self.cols.checked_sub(mid)?;

        let lhs = BlockSlice {
            rows: self.rows,
            cols: mid,
            pitch: self.pitch,
        };

        let rhs = BlockSlice {
            rows: self.rows,
            cols: n,
            pitch: self.pitch,
        };

        // If we have no rows at all then this block does not cover any elements so we must
        // pick an offset of 0 to guarantee in-bounds access. The good news is that this case
        // also implies that the other side is empty so its offset does not matter.
        let offset = if self.rows > 0 { mid } else { 0 };
        debug_assert!(offset <= self.total_span());

        Some((lhs, rhs, offset))
    }

    /// Return the absolute position of the element, if in bounds. Otherwise, panic.
    fn in_bounds_offset(&self, row: usize, col: usize) -> usize {
        assert!(row < self.rows);
        assert!(col < self.cols);
        let idx = row * self.pitch + col;
        debug_assert!(idx < self.total_span());
        idx
    }
}

/// Represents the provenance of a pointer to a single column/row of a matrix.
///
/// FIXME: before exposing this consider `PartialEq, … Ord` implications. These were added to
/// satisfy the `Pointee` trait requirements but really what does ordering mean? We have chosen the
/// field `pitch` to be last but that is super arbitrary.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct VectorSlice {
    count: usize,
    pitch: usize,
}

const _: () = {
    // As per Rust 1.92's `Pointee` trait. Suspicious: `Ord`. See comment on `VectorSlice`.
    use core::{fmt, hash};

    fn _can_eventually_be_ptr_metadata<
        // Missing: `Freeze` which is unstable
        Metadata: fmt::Debug + Copy + Send + Sync + Ord + hash::Hash + Unpin,
    >() {
    }

    let _ = _can_eventually_be_ptr_metadata::<VectorSlice>;
};

impl VectorSlice {
    /// Split into two vector descriptors.
    ///
    /// Returns `Some` with two valid slice. The first slice is in-bounds. Also returns an offset
    /// that is in-bounds of the current slice and such that the elements valid for both blocks do
    /// not alias. The second block is in-bounds when interpreted as start at the offset.
    fn split_at(self, mid: usize) -> Option<(VectorSlice, VectorSlice, usize)> {
        let right_count = self.count.checked_sub(mid)?;

        let left = VectorSlice {
            count: mid,
            pitch: self.pitch,
        };

        let right = VectorSlice {
            count: right_count,
            pitch: self.pitch,
        };

        let offset = mid * self.pitch;
        Some((left, right, offset))
    }

    /// Return the absolute position of the element, if in bounds. Otherwise, panic.
    fn in_bounds_offset(&self, index: usize) -> usize {
        assert!(index < self.count);
        index * self.pitch
    }
}

/// Iterate over the rows of a block in a matrix.
///
/// We assume row-major matrices here, a row is a contiguous slice of items.
pub struct IterRows<'a, T> {
    block: BlockRef<'a, T>,
}

impl<'data, T> Iterator for IterRows<'data, T> {
    type Item = &'data [T];

    fn next(&mut self) -> Option<Self::Item> {
        if self.block.rows() == 0 {
            None
        } else {
            // FIXME: add `split_off_rows` instead.
            let (row, rest) = core::mem::take(&mut self.block).split_at_row(1);
            self.block = rest;
            // One row as it was created from `split_at_row(1)`.
            Some(row.fake_contiguity())
        }
    }
}

/// Iterate over mutable rows of a block in a matrix.
///
/// We assume row-major matrices here, a row is a contiguous slice of items.
pub struct IterRowsMut<'a, T> {
    block: BlockMut<'a, T>,
}

impl<'data, T> Iterator for IterRowsMut<'data, T> {
    type Item = &'data mut [T];

    fn next(&mut self) -> Option<Self::Item> {
        if self.block.rows() == 0 {
            None
        } else {
            // FIXME: add `split_off_rows` instead.
            let (row, rest) = core::mem::take(&mut self.block).split_at_row(1);
            self.block = rest;
            // One row as it was created from `split_at_row(1)`.
            Some(row.fake_contiguity())
        }
    }
}

pub trait MatrixIndex: sealed::Sealed {}

impl MatrixIndex for ops::Range<usize> {}
impl MatrixIndex for ops::RangeInclusive<usize> {}
impl MatrixIndex for ops::RangeFrom<usize> {}
impl MatrixIndex for ops::RangeTo<usize> {}
impl MatrixIndex for ops::RangeToInclusive<usize> {}
impl MatrixIndex for ops::RangeFull {}

mod sealed {
    use core::ops;

    pub trait Sealed {
        fn into_start_and_len(self, dim: usize) -> Option<(usize, usize)>;
    }

    impl Sealed for ops::Range<usize> {
        fn into_start_and_len(self, dim: usize) -> Option<(usize, usize)> {
            if self.start <= self.end && self.end <= dim {
                Some((self.start, self.end - self.start))
            } else {
                None
            }
        }
    }

    impl Sealed for ops::RangeInclusive<usize> {
        fn into_start_and_len(self, dim: usize) -> Option<(usize, usize)> {
            let start = *self.start();
            let end = *self.end();
            if start <= end && end < dim {
                Some((start, end - start + 1))
            } else {
                None
            }
        }
    }

    impl Sealed for ops::RangeFrom<usize> {
        fn into_start_and_len(self, dim: usize) -> Option<(usize, usize)> {
            if self.start <= dim {
                Some((self.start, dim - self.start))
            } else {
                None
            }
        }
    }

    impl Sealed for ops::RangeTo<usize> {
        fn into_start_and_len(self, dim: usize) -> Option<(usize, usize)> {
            if self.end <= dim {
                Some((0, self.end))
            } else {
                None
            }
        }
    }

    impl Sealed for ops::RangeToInclusive<usize> {
        fn into_start_and_len(self, dim: usize) -> Option<(usize, usize)> {
            if self.end < dim {
                Some((0, self.end + 1))
            } else {
                None
            }
        }
    }

    impl Sealed for ops::RangeFull {
        fn into_start_and_len(self, dim: usize) -> Option<(usize, usize)> {
            Some((0, dim))
        }
    }
}

/// A reference to a single column/row of a matrix.
///
/// This is similar to `&[T]` but with a pitch potentially different from `1` between its elements,
/// i.e. there is no guarantee of contiguity. As a consequence this does not have a simple
/// past-the-end pointer like a slice would have. For an empty slice the only guaranteed-valid
/// pointer is the base pointer itself while for larger slices the last guaranteed-valid pointer is
/// one-past the last element, _not_ one additional pitch.
///
/// Created from its constructors or a block reference via the [`BlockRef::col`] and
/// [`BlockRef::row`] methods.
#[derive(Copy, Clone)]
pub struct VecRef<'a, T> {
    data: NonNull<T>,
    block: VectorSlice,
    lifetime: PhantomData<&'a [T]>,
}

// SAFETY: See `&[T]`. The reference can be used to, potentially, get a `&T` for each element in
// the block and thus the block itself provides the exact same properties as `T`. The `VecRef` is
// then `&[T]` itself and thus has properties of a reference to such a type. Refer to the
// reference: <https://doc.rust-lang.org/stable/std/primitive.reference.html>
//
// We have `&T: Sync` iff `T: Sync`
unsafe impl<T> Sync for VecRef<'_, T> where T: Sync {}
// We have `&T: Send` iff `T: Sync`
unsafe impl<T> Send for VecRef<'_, T> where T: Sync {}

impl<'data, T> VecRef<'data, T> {
    /// Create a new vector reference from a raw slice and pitch.
    ///
    /// The resulting block refers to the first column of the matrix.
    ///
    /// # Panics
    ///
    /// Panics if the pitch is zero.
    pub fn new(data: &'data [T], pitch: usize) -> Self {
        assert_ne!(pitch, 0);

        VecRef {
            // Safety: construction implies `count * pitch <= data.len()`.
            block: VectorSlice {
                count: data.len() / pitch,
                pitch,
            },
            data: NonNull::from(data).cast(),
            lifetime: PhantomData,
        }
    }

    /// Create a new vector reference from a raw slice with pitch `1`.
    pub fn from_slice(data: &'data [T]) -> Self {
        VecRef {
            block: VectorSlice {
                count: data.len(),
                pitch: 1,
            },
            data: NonNull::from(data).cast(),
            lifetime: PhantomData,
        }
    }

    /// Number of elements in this vector.
    pub fn len(&self) -> usize {
        self.block.count
    }

    /// Whether this vector is empty.
    pub fn is_empty(&self) -> bool {
        self.block.count == 0
    }

    /// Divide into two vectors at the given element.
    ///
    /// # Examples
    ///
    /// ```
    /// use matrix_slice::VecRef;
    ///
    /// let data = &[0, 1, 2, 3, 4, 5];
    ///
    /// let block = VecRef::new(data, 1);
    /// let (left, right) = block.split_at(2);
    ///
    /// assert_eq!(left[1], 1);
    /// assert_eq!(right[3], 5);
    /// ```
    pub fn split_at(self, mid: usize) -> (VecRef<'data, T>, VecRef<'data, T>) {
        self.split_at_checked(mid).unwrap()
    }

    /// Divide into two vectors at the given element.
    ///
    /// See [`Self::split_at`] but returns `None` if out of bounds.
    pub fn split_at_checked(self, mid: usize) -> Option<(VecRef<'data, T>, VecRef<'data, T>)> {
        if let Some((lhs, rhs, offset)) = self.block.split_at(mid) {
            Some((
                VecRef {
                    data: self.data,
                    block: lhs,
                    lifetime: self.lifetime,
                },
                VecRef {
                    data: unsafe { self.data.add(offset) },
                    block: rhs,
                    lifetime: self.lifetime,
                },
            ))
        } else {
            None
        }
    }

    /// Choose a range of elements and contract the vector to that.
    pub fn select<R>(self, range: R) -> Option<VecRef<'data, T>>
    where
        R: MatrixIndex,
    {
        let (start, len) = range.into_start_and_len(self.block.count)?;
        let (_, block, offset) = self.block.split_at(start)?;
        // Safety: ensures that the resulting block is more constrained, this property should be
        // ensured by our sealed `MatrixIndex` implementations.
        assert!(block.count >= len);

        Some(VecRef {
            block: VectorSlice {
                count: len,
                ..block
            },
            // SAFETY: offset is in-bounds as per `split_at` contract.
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        })
    }
}

impl<T> ops::Index<usize> for VecRef<'_, T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        let idx = self.block.in_bounds_offset(index);
        // SAFETY: Index is bounded by `total_span` which itself is a lower estimate of the
        // provenance of the pointer.
        unsafe { &*self.data.as_ptr().add(idx) }
    }
}

/// A reference to a single column/row of a matrix.
///
/// This is similar to `&[T]` but with a pitch potentially different from `1` between its elements,
/// i.e. there is no guarantee of contiguity. As a consequence this does not have a simple
/// past-the-end pointer like a slice would have. For an empty slice the only guaranteed-valid
/// pointer is the base pointer itself while for larger slices the last guaranteed-valid pointer is
/// one-past the last element, _not_ one additional pitch.
///
/// Created from its constructors or a block reference via the [`BlockMut::col`] and
/// [`BlockMut::row`] methods.
pub struct VecMut<'a, T> {
    data: NonNull<T>,
    block: VectorSlice,
    lifetime: PhantomData<&'a mut [T]>,
}

// SAFETY: See `VecRef` but with `&mut [T]`.
//
// We have `&mut T: Sync` iff `T: Sync`
unsafe impl<T> Sync for VecMut<'_, T> where T: Sync {}
// We have `&mut T: Send` iff `T: Send`
unsafe impl<T> Send for VecMut<'_, T> where T: Sync {}

impl<'data, T> VecMut<'data, T> {
    /// Create a new vector reference from a raw slice and pitch.
    ///
    /// The resulting block refers to the first column of the matrix.
    pub fn new(data: &'data mut [T], pitch: usize) -> Self {
        VecMut {
            // Safety: construction implies `count * pitch <= data.len()`.
            block: VectorSlice {
                count: data.len() / pitch,
                pitch,
            },
            data: NonNull::from(data).cast(),
            lifetime: PhantomData,
        }
    }

    /// Create a new vector reference from a raw slice with pitch `1`.
    pub fn from_slice(data: &'data mut [T]) -> Self {
        VecMut {
            block: VectorSlice {
                count: data.len(),
                pitch: 1,
            },
            data: NonNull::from(data).cast(),
            lifetime: PhantomData,
        }
    }

    /// Number of elements in this vector.
    pub fn len(&self) -> usize {
        self.block.count
    }

    /// Whether this vector is empty.
    pub fn is_empty(&self) -> bool {
        self.block.count == 0
    }

    /// Divide into two vectors at the given element.
    ///
    /// # Examples
    ///
    /// ```
    /// use matrix_slice::VecMut;
    ///
    /// let data = &mut [0, 1, 2, 3, 4, 5];
    ///
    /// let block = VecMut::new(data, 1);
    /// let (left, right) = block.split_at(2);
    ///
    /// assert_eq!(left[1], 1);
    /// assert_eq!(right[3], 5);
    /// ```
    pub fn split_at(self, mid: usize) -> (VecMut<'data, T>, VecMut<'data, T>) {
        self.split_at_checked(mid).unwrap()
    }

    /// Divide into two vectors at the given element.
    ///
    /// See [`Self::split_at`] but returns `None` if out of bounds.
    pub fn split_at_checked(self, mid: usize) -> Option<(VecMut<'data, T>, VecMut<'data, T>)> {
        if let Some((lhs, rhs, offset)) = self.block.split_at(mid) {
            Some((
                VecMut {
                    data: self.data,
                    block: lhs,
                    lifetime: self.lifetime,
                },
                VecMut {
                    data: unsafe { self.data.add(offset) },
                    block: rhs,
                    lifetime: self.lifetime,
                },
            ))
        } else {
            None
        }
    }

    /// Choose a range of elements and contract the vector to that.
    pub fn select<R>(self, range: R) -> Option<VecMut<'data, T>>
    where
        R: MatrixIndex,
    {
        let (start, len) = range.into_start_and_len(self.block.count)?;
        let (_, block, offset) = self.block.split_at(start)?;
        // Safety: ensures that the resulting block is more constrained, this property should be
        // ensured by our sealed `MatrixIndex` implementations.
        assert!(block.count >= len);

        Some(VecMut {
            block: VectorSlice {
                count: len,
                ..block
            },
            // SAFETY: offset is in-bounds as per `split_at` contract.
            data: unsafe { self.data.add(offset) },
            lifetime: self.lifetime,
        })
    }

    /// Turn this unique reference into a shared reference.
    pub fn cast_const(self) -> VecRef<'data, T> {
        // SAFETY: shared access can always be re-tagged from unique access.
        VecRef {
            data: self.data,
            block: self.block,
            lifetime: PhantomData,
        }
    }

    /// Create a unique reference to this block with a shorter lifetime.
    pub fn reborrow(&mut self) -> VecMut<'_, T> {
        // SAFETY: Unique access is created by deriving it from our current pointer so the
        // provenance is the same, and temporally it can not overlap access through the current
        // value due to the lifetime enforcing a borrow relationship.
        VecMut {
            data: self.data,
            block: self.block,
            lifetime: PhantomData,
        }
    }

    /// Modify the item type to a `Cell`, allowing interior mutability.
    ///
    /// This is the equivalent of [`Cell::from_mut`] over elements in this slice.
    pub fn as_cells(self) -> VecMut<'data, Cell<T>> {
        // SAFETY: `Cell<T>` has the same layout as `T`.
        VecMut {
            data: self.data.cast(),
            block: self.block,
            lifetime: PhantomData,
        }
    }
}

impl<'data, T> VecMut<'data, Cell<T>> {
    /// Modify the item type from a `Cell` to its interior type.
    ///
    /// This is the equivalent of [`Cell::get_mut`] over elements in this slice.
    pub fn as_cell_items(self) -> VecMut<'data, T> {
        // SAFETY: `Cell<T>` has the same layout as `T`.
        VecMut {
            data: self.data.cast(),
            block: self.block,
            lifetime: PhantomData,
        }
    }
}

impl<T> ops::Index<usize> for VecMut<'_, T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        let idx = self.block.in_bounds_offset(index);
        // SAFETY: Index is bounded by `total_span` which itself is a lower estimate of the
        // provenance of the pointer.
        unsafe { &*self.data.as_ptr().add(idx) }
    }
}

impl<T> ops::IndexMut<usize> for VecMut<'_, T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        let idx = self.block.in_bounds_offset(index);
        // SAFETY: Index is bounded by `total_span` which itself is a lower estimate of the
        // provenance of the pointer. By construction the `VecMut` has exclusive access to all
        // elements reachable as multiples of its pitch. We access exactly one of them here.
        unsafe { &mut *self.data.as_ptr().add(idx) }
    }
}

/// Tests should also be ran under MIRI.
#[cfg(test)]
mod tests {
    // Verify that splitting as in the example works.
    #[test]
    fn well_defined_split() {
        let data = &[[0u32; 3]; 3];
        let block = super::from_array_rows(data);
        let (_, block) = block.split_at_row(1);
        let (_, block) = block.split_at_col(1);

        block.split_at_row_checked(2).unwrap();
    }
    #[test]
    fn well_defined_split_mut() {
        let data = &mut [[0u32; 3]; 3];
        let block = super::from_array_rows_mut(data);
        let (_, block) = block.split_at_row(1);
        let (_, block) = block.split_at_col(1);

        block.split_at_row_checked(2).unwrap();
    }

    /// Check our pointer derivation does not cause retagging that would cause any block to lose
    /// provenance over its items. Access individual rows (derived slices) from an overlapping split
    /// concurrently.
    #[test]
    fn soundness_interleaved_block_access() {
        let data = &mut [[0u32; 4]; 4];
        let block = super::from_array_rows_mut(data);

        let (mut lhs, rhs) = block.split_at_col(2);

        for (left, right) in lhs.reborrow().iter_rows_mut().zip(rhs.iter_rows_mut()) {
            left[0] = right[0];
            left[1] = right[1];
            right.fill(1);
        }

        // Check that this pointer is still valid.
        for row in lhs.iter_rows_mut() {
            row.fill(2);
        }

        for row in data.iter() {
            assert_eq!(row, &[2, 2, 1, 1]);
        }
    }
}