-
Notifications
You must be signed in to change notification settings - Fork 409
Expand file tree
/
Copy pathblock_transposed.rs
More file actions
2210 lines (1950 loc) · 82.8 KB
/
block_transposed.rs
File metadata and controls
2210 lines (1950 loc) · 82.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
//! Block-transposed matrix types with configurable packing.
//!
//! This module provides block-transposed matrix types — [`BlockTransposed`] (owned),
//! [`BlockTransposedRef`] (shared view), and [`BlockTransposedMut`] (mutable view) —
//! where groups of `GROUP` rows are stored in transposed form to enable efficient SIMD
//! processing. An optional packing factor `PACK` interleaves adjacent columns within
//! each group, which can be used to feed SIMD instructions that operate on packed pairs
//! (e.g. `vpmaddwd` with `PACK = 2`).
//!
//! # Layout
//!
//! ## `PACK = 1` (standard block-transpose)
//!
//! Given a logical matrix with rows `a`, `b`, `c`, `d`, `e` (each with `K` columns)
//! and `GROUP = 3`:
//!
//! ```text
//! Group Size (3)
//! <---------->
//!
//! +----------+ ^
//! | a0 b0 c0 | |
//! | a1 b1 c1 | |
//! | a2 b2 c2 | | Block Size (K)
//! Block 0 | ... | |
//! (Full) | aK bK cK | |
//! +----------+ v
//! +----------+
//! | d0 e0 XX |
//! Block 1 | d1 e1 XX |
//! (Partial) | ... |
//! | dK eK XX |
//! +----------+
//! ```
//!
//! ## `PACK = 2` (super-packed)
//!
//! With `GROUP = 4`, `PACK = 2`, and a logical matrix with rows `a`, `b`, `c`, `d`,
//! `e`, `f` (each with **5** columns — odd, to show padding), adjacent column-pairs
//! are interleaved per row within each group panel:
//!
//! ```text
//! GROUP × PACK (4 × 2 = 8)
//! <----------------------------->
//!
//! +-----------------------------+ ^
//! | a0 a1 b0 b1 c0 c1 d0 d1 | | col-pair (0, 1)
//! | a2 a3 b2 b3 c2 c3 d2 d3 | | col-pair (2, 3)
//! Block 0 | a4 __ b4 __ c4 __ d4 __ | | col-pair (4, pad)
//! (Full) +-----------------------------+ v
//! +-----------------------------+
//! | e0 e1 f0 f1 XX XX XX XX | col-pair (0, 1)
//! Block 1 | e2 e3 f2 f3 XX XX XX XX | col-pair (2, 3)
//! (Partial) | e4 __ f4 __ XX XX XX XX | col-pair (4, pad)
//! +-----------------------------+
//!
//! __ = zero (column padding) XX = zero (row padding)
//! padded_ncols = 6 (5 rounded up to next multiple of PACK)
//! Block Size = padded_ncols / PACK = 3 physical rows per block
//! ```
//!
//! Each physical row of a block holds one column-pair across all `GROUP` rows.
//! For example, the first physical row stores columns `(0, 1)` for rows
//! `a, b, c, d` interleaved as `[a0, a1, b0, b1, c0, c1, d0, d1]`.
//!
//! Because `ncols = 5` is odd (not a multiple of `PACK = 2`), the last
//! column-pair `(4, pad)` is zero-padded: `[a4, 0, b4, 0, c4, 0, d4, 0]`.
//!
//! # Constraints
//!
//! - `GROUP > 0`
//! - `PACK > 0`
//! - `GROUP % PACK == 0`
use std::{alloc::Layout, marker::PhantomData, ptr::NonNull};
use diskann_utils::{
ReborrowMut,
strided::StridedView,
views::{MatrixView, MutMatrixView},
};
use super::matrix::{
Defaulted, LayoutError, Mat, MatMut, MatRef, NewMut, NewOwned, NewRef, Overflow, Repr, ReprMut,
ReprOwned, SliceError,
};
use crate::bits::{AsMutPtr, AsPtr, MutSlicePtr, SlicePtr};
use crate::utils;
/// Round `ncols` up to the next multiple of `PACK`.
#[inline]
fn padded_ncols<const PACK: usize>(ncols: usize) -> usize {
ncols.next_multiple_of(PACK)
}
/// Compute the total number of `T` elements required to store a block-transposed matrix
/// of `nrows x ncols` with group size `GROUP` and packing factor `PACK`.
///
/// This is the **unchecked** flavor — it assumes the caller has already validated that
/// the dimensions do not overflow (e.g. after construction). For use in the constructor,
/// prefer [`checked_compute_capacity`].
///
/// Compile-time constraints (`GROUP > 0`, `PACK > 0`, `GROUP % PACK == 0`) are enforced
/// by [`BlockTransposedRepr::_ASSERTIONS`]; this function does **not** duplicate them.
#[inline]
fn compute_capacity<const GROUP: usize, const PACK: usize>(nrows: usize, ncols: usize) -> usize {
nrows.next_multiple_of(GROUP) * padded_ncols::<PACK>(ncols)
}
/// Checked variant of [`compute_capacity`] that returns `None` if any intermediate
/// arithmetic overflows. Used by the constructor to reject impossibly large dimensions
/// before committing to an allocation.
#[inline]
fn checked_compute_capacity<const GROUP: usize, const PACK: usize>(
nrows: usize,
ncols: usize,
) -> Option<usize> {
nrows
.checked_next_multiple_of(GROUP)?
.checked_mul(ncols.checked_next_multiple_of(PACK)?)
}
/// Compute the linear index for the element at logical `(row, col)` in a block-transposed
/// layout with group size `GROUP`, packing factor `PACK`, and `ncols` logical columns.
#[inline]
fn linear_index<const GROUP: usize, const PACK: usize>(
row: usize,
col: usize,
ncols: usize,
) -> usize {
let pncols = padded_ncols::<PACK>(ncols);
let block = row / GROUP;
let row_in_block = row % GROUP;
block * GROUP * pncols + (col / PACK) * GROUP * PACK + row_in_block * PACK + (col % PACK)
}
/// Compute the offset from a row's base pointer (at col=0) to the element at `col`.
///
/// This is purely a function of the column index and the const layout parameters, not
/// of any particular matrix's dimensions.
#[inline]
fn col_offset<const GROUP: usize, const PACK: usize>(col: usize) -> usize {
(col / PACK) * GROUP * PACK + (col % PACK)
}
/// Internal layout descriptor for block-transposed matrices.
///
/// This is not part of the public API — use [`BlockTransposed`], [`BlockTransposedRef`],
/// or [`BlockTransposedMut`] instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct BlockTransposedRepr<T, const GROUP: usize, const PACK: usize = 1> {
nrows: usize,
ncols: usize,
_elem: PhantomData<T>,
}
impl<T: Copy, const GROUP: usize, const PACK: usize> BlockTransposedRepr<T, GROUP, PACK> {
// Compile-time assertions — evaluated whenever any method references this constant.
const _ASSERTIONS: () = {
assert!(GROUP > 0, "group size GROUP must be positive");
assert!(PACK > 0, "packing factor PACK must be positive");
assert!(
GROUP.is_multiple_of(PACK),
"GROUP must be divisible by PACK"
);
};
/// Create a new `BlockTransposedRepr` descriptor.
///
/// Successful construction requires that the total memory for the backing allocation
/// does not exceed `isize::MAX`.
pub fn new(nrows: usize, ncols: usize) -> Result<Self, Overflow> {
let () = Self::_ASSERTIONS;
let capacity = checked_compute_capacity::<GROUP, PACK>(nrows, ncols)
.ok_or_else(|| Overflow::for_type::<T>(nrows, ncols))?;
Overflow::check_byte_budget::<T>(capacity, nrows, ncols)?;
Ok(Self {
nrows,
ncols,
_elem: PhantomData,
})
}
// ── Query helpers ────────────────────────────────────────────────
/// The total number of `T` elements in the backing allocation (including padding).
#[inline]
fn storage_len(&self) -> usize {
compute_capacity::<GROUP, PACK>(self.nrows, self.ncols)
}
/// Number of logical rows.
#[inline]
fn nrows(&self) -> usize {
self.nrows
}
/// Number of logical columns (dimensionality).
#[inline]
pub fn ncols(&self) -> usize {
self.ncols
}
/// Number of physical (padded) columns — logical columns rounded up to
/// the next multiple of `PACK`.
#[inline]
pub fn padded_ncols(&self) -> usize {
padded_ncols::<PACK>(self.ncols)
}
/// Number of completely full blocks.
#[inline]
pub fn full_blocks(&self) -> usize {
self.nrows / GROUP
}
/// Total number of blocks including a possible partially-filled tail.
#[inline]
pub fn num_blocks(&self) -> usize {
self.nrows.div_ceil(GROUP)
}
/// Number of valid elements in the last block, or 0 if all blocks are full.
#[inline]
pub fn remainder(&self) -> usize {
self.nrows % GROUP
}
/// Total number of logical rows rounded up to the next multiple of `GROUP`.
///
/// This is the number of "available" row slots in the backing allocation,
/// including zero-padded rows in the last (possibly partial) block.
#[inline]
pub fn available_rows(&self) -> usize {
self.num_blocks() * GROUP
}
/// The stride (in elements) between the start of consecutive blocks.
#[inline]
fn block_stride(&self) -> usize {
GROUP * self.padded_ncols()
}
/// The linear offset of the start of `block`.
#[inline]
fn block_offset(&self, block: usize) -> usize {
block * self.block_stride()
}
/// Verify that `slice` has exactly `self.storage_len()` elements.
fn check_slice(&self, slice: &[T]) -> Result<(), SliceError> {
let cap = self.storage_len();
if slice.len() != cap {
Err(SliceError::LengthMismatch {
expected: cap,
found: slice.len(),
})
} else {
Ok(())
}
}
/// Helper: wrap a `Box<[T]>` into a [`Mat`] without any further checks.
///
/// # Safety
///
/// `b.len()` must equal `self.storage_len()`.
unsafe fn box_to_mat(self, b: Box<[T]>) -> Mat<Self> {
debug_assert_eq!(b.len(), self.storage_len(), "safety contract violated");
let ptr = utils::box_into_nonnull(b).cast::<u8>();
// SAFETY: `ptr` is properly aligned and compatible with our layout.
unsafe { Mat::from_raw_parts(self, ptr) }
}
}
// ════════════════════════════════════════════════════════════════════
// Row view types
// ════════════════════════════════════════════════════════════════════
/// An immutable view of a single logical row in a block-transposed matrix.
///
/// Because the elements of a logical row are strided (not contiguous), this struct
/// provides indexed access and iteration over the row's elements.
#[derive(Debug, Clone, Copy)]
pub struct Row<'a, T, const GROUP: usize, const PACK: usize = 1> {
/// Pointer to the element at `(row, col=0)` in the backing allocation.
base: SlicePtr<'a, T>,
ncols: usize,
}
impl<T: Copy, const GROUP: usize, const PACK: usize> Row<'_, T, GROUP, PACK> {
/// Number of elements (columns) in this row.
#[inline]
pub fn len(&self) -> usize {
self.ncols
}
/// Whether the row is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.ncols == 0
}
/// Get a reference to the element at column `col`, or `None` if out of bounds.
#[inline]
pub fn get(&self, col: usize) -> Option<&T> {
if col < self.ncols {
// SAFETY: bounds checked, offset computed from validated layout.
Some(unsafe { &*self.base.as_ptr().add(col_offset::<GROUP, PACK>(col)) })
} else {
None
}
}
/// Return an iterator over the elements of this row.
#[inline]
pub fn iter(&self) -> RowIter<'_, T, GROUP, PACK> {
RowIter {
base: self.base,
col: 0,
ncols: self.ncols,
}
}
}
impl<T: Copy, const GROUP: usize, const PACK: usize> std::ops::Index<usize>
for Row<'_, T, GROUP, PACK>
{
type Output = T;
#[inline]
#[allow(clippy::panic)] // Index is expected to panic on OOB
fn index(&self, col: usize) -> &Self::Output {
self.get(col)
.unwrap_or_else(|| panic!("column index {col} out of bounds (ncols = {})", self.ncols))
}
}
/// Iterator over the elements of a [`Row`].
#[derive(Debug, Clone)]
pub struct RowIter<'a, T, const GROUP: usize, const PACK: usize = 1> {
base: SlicePtr<'a, T>,
col: usize,
ncols: usize,
}
impl<T: Copy, const GROUP: usize, const PACK: usize> Iterator for RowIter<'_, T, GROUP, PACK> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.col >= self.ncols {
return None;
}
// SAFETY: col < ncols means the offset is within the backing allocation.
let val = unsafe { *self.base.as_ptr().add(col_offset::<GROUP, PACK>(self.col)) };
self.col += 1;
Some(val)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.ncols - self.col;
(remaining, Some(remaining))
}
}
impl<T: Copy, const GROUP: usize, const PACK: usize> ExactSizeIterator
for RowIter<'_, T, GROUP, PACK>
{
}
impl<T: Copy, const GROUP: usize, const PACK: usize> std::iter::FusedIterator
for RowIter<'_, T, GROUP, PACK>
{
}
/// A mutable view of a single logical row in a block-transposed matrix.
#[derive(Debug)]
pub struct RowMut<'a, T, const GROUP: usize, const PACK: usize = 1> {
base: MutSlicePtr<'a, T>,
ncols: usize,
}
impl<T: Copy, const GROUP: usize, const PACK: usize> RowMut<'_, T, GROUP, PACK> {
/// Number of elements (columns) in this row.
#[inline]
pub fn len(&self) -> usize {
self.ncols
}
/// Whether the row is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.ncols == 0
}
/// Get a reference to the element at column `col`, or `None` if out of bounds.
#[inline]
pub fn get(&self, col: usize) -> Option<&T> {
if col < self.ncols {
// SAFETY: bounds checked.
Some(unsafe { &*self.base.as_ptr().add(col_offset::<GROUP, PACK>(col)) })
} else {
None
}
}
/// Get a mutable reference to the element at column `col`, or `None` if out of bounds.
#[inline]
pub fn get_mut(&mut self, col: usize) -> Option<&mut T> {
if col < self.ncols {
// SAFETY: bounds checked.
Some(unsafe { &mut *self.base.as_mut_ptr().add(col_offset::<GROUP, PACK>(col)) })
} else {
None
}
}
/// Set the element at column `col`.
///
/// # Panics
///
/// Panics if `col >= self.len()`.
#[inline]
pub fn set(&mut self, col: usize, value: T) {
assert!(
col < self.ncols,
"column index {col} out of bounds (ncols = {})",
self.ncols
);
// SAFETY: bounds checked.
unsafe { *self.base.as_mut_ptr().add(col_offset::<GROUP, PACK>(col)) = value };
}
}
impl<T: Copy, const GROUP: usize, const PACK: usize> std::ops::Index<usize>
for RowMut<'_, T, GROUP, PACK>
{
type Output = T;
#[inline]
#[allow(clippy::panic)] // Index is expected to panic on OOB
fn index(&self, col: usize) -> &Self::Output {
self.get(col)
.unwrap_or_else(|| panic!("column index {col} out of bounds (ncols = {})", self.ncols))
}
}
impl<T: Copy, const GROUP: usize, const PACK: usize> std::ops::IndexMut<usize>
for RowMut<'_, T, GROUP, PACK>
{
#[inline]
#[allow(clippy::panic)] // IndexMut is expected to panic on OOB
fn index_mut(&mut self, col: usize) -> &mut Self::Output {
let ncols = self.ncols;
self.get_mut(col)
.unwrap_or_else(|| panic!("column index {col} out of bounds (ncols = {ncols})"))
}
}
// ════════════════════════════════════════════════════════════════════
// Repr / ReprMut / ReprOwned
// ════════════════════════════════════════════════════════════════════
// SAFETY: `get_row` produces a valid `Row` for valid indices. The layout
// reports the correct capacity for the block-transposed backing allocation.
unsafe impl<T: Copy, const GROUP: usize, const PACK: usize> Repr
for BlockTransposedRepr<T, GROUP, PACK>
{
type Row<'a>
= Row<'a, T, GROUP, PACK>
where
Self: 'a;
fn nrows(&self) -> usize {
self.nrows
}
fn layout(&self) -> Result<Layout, LayoutError> {
Ok(Layout::array::<T>(self.storage_len())?)
}
unsafe fn get_row<'a>(self, ptr: NonNull<u8>, i: usize) -> Self::Row<'a> {
debug_assert!(i < self.nrows);
// When ncols == 0 the backing allocation is zero-sized, so we must not
// compute any pointer offset. Return a dangling base instead.
if self.ncols == 0 {
return Row {
// SAFETY: The row is empty (ncols == 0) so the pointer will never be
// dereferenced. A dangling `NonNull` satisfies the non-null invariant.
base: unsafe { SlicePtr::new_unchecked(NonNull::dangling()) },
ncols: 0,
};
}
let base_ptr = ptr.as_ptr().cast::<T>();
let offset = linear_index::<GROUP, PACK>(i, 0, self.ncols);
// SAFETY: The caller asserts `i < self.nrows()`. The backing allocation has at
// least `self.storage_len()` elements, so the computed offset is in bounds.
let row_base = unsafe { base_ptr.add(offset) };
Row {
// SAFETY: `row_base` is derived from a `NonNull<u8>` with a valid offset,
// so it is non-null. The lifetime is tied to the caller's `'a`.
base: unsafe { SlicePtr::new_unchecked(NonNull::new_unchecked(row_base)) },
ncols: self.ncols,
}
}
}
// SAFETY: `get_row_mut` produces a valid `RowMut`. Disjoint row indices
// produce disjoint base pointers because each row within a block starts at a unique
// offset modulo GROUP.
unsafe impl<T: Copy, const GROUP: usize, const PACK: usize> ReprMut
for BlockTransposedRepr<T, GROUP, PACK>
{
type RowMut<'a>
= RowMut<'a, T, GROUP, PACK>
where
Self: 'a;
unsafe fn get_row_mut<'a>(self, ptr: NonNull<u8>, i: usize) -> Self::RowMut<'a> {
debug_assert!(i < self.nrows);
// When ncols == 0 the backing allocation is zero-sized, so we must not
// compute any pointer offset. Return a dangling base instead.
if self.ncols == 0 {
return RowMut {
// SAFETY: The row is empty (ncols == 0) so the pointer will never be
// dereferenced. A dangling `NonNull` satisfies the non-null invariant.
base: unsafe { MutSlicePtr::new_unchecked(NonNull::dangling()) },
ncols: 0,
};
}
let base_ptr = ptr.as_ptr().cast::<T>();
let offset = linear_index::<GROUP, PACK>(i, 0, self.ncols);
// SAFETY: `i < self.nrows` (debug-asserted) guarantees the offset is within
// the backing allocation. Same reasoning as `get_row`.
let row_base = unsafe { base_ptr.add(offset) };
RowMut {
// SAFETY: `row_base` is derived from a `NonNull<u8>` with a valid offset,
// so it is non-null. The lifetime is tied to the caller's `'a`.
base: unsafe { MutSlicePtr::new_unchecked(NonNull::new_unchecked(row_base)) },
ncols: self.ncols,
}
}
}
// SAFETY: Memory is deallocated by reconstructing the `Box<[T]>` that was created during
// `NewOwned`.
unsafe impl<T: Copy, const GROUP: usize, const PACK: usize> ReprOwned
for BlockTransposedRepr<T, GROUP, PACK>
{
unsafe fn drop(self, ptr: NonNull<u8>) {
// SAFETY: `ptr` was obtained from `Box::into_raw` with length `self.storage_len()`.
unsafe {
let slice_ptr =
std::ptr::slice_from_raw_parts_mut(ptr.cast::<T>().as_ptr(), self.storage_len());
let _ = Box::from_raw(slice_ptr);
}
}
}
// ════════════════════════════════════════════════════════════════════
// Constructors
// ════════════════════════════════════════════════════════════════════
// SAFETY: The returned `Mat` contains a `Box` with exactly `self.storage_len()` elements.
unsafe impl<T: Copy, const GROUP: usize, const PACK: usize> NewOwned<T>
for BlockTransposedRepr<T, GROUP, PACK>
{
type Error = crate::error::Infallible;
fn new_owned(self, value: T) -> Result<Mat<Self>, Self::Error> {
let b: Box<[T]> = vec![value; self.storage_len()].into_boxed_slice();
// SAFETY: By construction, `b.len() == self.storage_len()`.
Ok(unsafe { self.box_to_mat(b) })
}
}
// SAFETY: This safely re-uses `<Self as NewOwned<T>>`.
unsafe impl<T: Copy + Default, const GROUP: usize, const PACK: usize> NewOwned<Defaulted>
for BlockTransposedRepr<T, GROUP, PACK>
{
type Error = crate::error::Infallible;
fn new_owned(self, _: Defaulted) -> Result<Mat<Self>, Self::Error> {
self.new_owned(T::default())
}
}
// SAFETY: This checks slice length against storage_len.
unsafe impl<T: Copy, const GROUP: usize, const PACK: usize> NewRef<T>
for BlockTransposedRepr<T, GROUP, PACK>
{
type Error = SliceError;
fn new_ref(self, data: &[T]) -> Result<MatRef<'_, Self>, Self::Error> {
self.check_slice(data)?;
// SAFETY: `check_slice` verified the length.
Ok(unsafe { MatRef::from_raw_parts(self, utils::as_nonnull(data).cast::<u8>()) })
}
}
// SAFETY: This checks slice length against storage_len.
unsafe impl<T: Copy, const GROUP: usize, const PACK: usize> NewMut<T>
for BlockTransposedRepr<T, GROUP, PACK>
{
type Error = SliceError;
fn new_mut(self, data: &mut [T]) -> Result<MatMut<'_, Self>, Self::Error> {
self.check_slice(data)?;
// SAFETY: `check_slice` verified the length.
Ok(unsafe { MatMut::from_raw_parts(self, utils::as_nonnull_mut(data).cast::<u8>()) })
}
}
// ════════════════════════════════════════════════════════════════════
// Delegation macro
// ════════════════════════════════════════════════════════════════════
/// Generates a forwarding method that delegates to `self.as_view().$name(...)`.
///
/// The generated doc-comment links back to the canonical implementation on
/// [`BlockTransposedRef`], so documentation stays in sync automatically.
macro_rules! delegate_to_ref {
// Safe function.
($(#[$m:meta])* $vis:vis fn $name:ident(&self $(, $a:ident: $t:ty)*) $(-> $r:ty)?) => {
#[doc = concat!("See [`BlockTransposedRef::", stringify!($name), "`].")]
$(#[$m])*
#[inline]
$vis fn $name(&self $(, $a: $t)*) $(-> $r)? {
self.as_view().$name($($a),*)
}
};
// Unsafe function.
($(#[$m:meta])* unsafe $vis:vis fn $name:ident(&self $(, $a:ident: $t:ty)*) $(-> $r:ty)?) => {
#[doc = concat!("See [`BlockTransposedRef::", stringify!($name), "`].")]
$(#[$m])*
#[inline]
$vis unsafe fn $name(&self $(, $a: $t)*) $(-> $r)? {
// SAFETY: Caller upholds the safety contract of the delegated method.
unsafe { self.as_view().$name($($a),*) }
}
};
}
// ════════════════════════════════════════════════════════════════════
// Public wrapper types
// ════════════════════════════════════════════════════════════════════
/// An owning block-transposed matrix.
///
/// Wraps an owned allocation of `T` elements laid out in block-transposed order.
/// See the [module-level documentation](self) for layout details.
///
/// For shared and mutable views, see [`BlockTransposedRef`] and [`BlockTransposedMut`].
///
/// # Row Types
///
/// Because rows are not contiguous in memory, the row types are view structs:
///
/// - [`Row`] — a `Copy` handle supporting `Index<usize>` and `.iter()`.
/// - [`RowMut`] — a mutable handle supporting `IndexMut<usize>`.
#[derive(Debug)]
pub struct BlockTransposed<T: Copy, const GROUP: usize, const PACK: usize = 1> {
data: Mat<BlockTransposedRepr<T, GROUP, PACK>>,
}
/// A shared (immutable) view of a block-transposed matrix.
///
/// Created by [`BlockTransposed::as_view`].
#[derive(Debug, Clone, Copy)]
pub struct BlockTransposedRef<'a, T: Copy, const GROUP: usize, const PACK: usize = 1> {
data: MatRef<'a, BlockTransposedRepr<T, GROUP, PACK>>,
}
/// A mutable view of a block-transposed matrix.
///
/// Created by [`BlockTransposed::as_view_mut`].
pub struct BlockTransposedMut<'a, T: Copy, const GROUP: usize, const PACK: usize = 1> {
data: MatMut<'a, BlockTransposedRepr<T, GROUP, PACK>>,
}
// ── BlockTransposedRef (core read implementations) ───────────────
impl<'a, T: Copy, const GROUP: usize, const PACK: usize> BlockTransposedRef<'a, T, GROUP, PACK> {
/// Returns the number of logical rows.
#[inline]
pub fn nrows(&self) -> usize {
self.data.repr().nrows()
}
/// Returns the number of logical columns (dimensionality).
#[inline]
pub fn ncols(&self) -> usize {
self.data.repr().ncols()
}
/// Returns the number of physical (padded) columns.
#[inline]
pub fn padded_ncols(&self) -> usize {
self.data.repr().padded_ncols()
}
/// Group size (blocking factor `GROUP`).
pub const fn group_size(&self) -> usize {
GROUP
}
/// Group size (blocking factor `GROUP`) as a `const` function on the *type*.
pub const fn const_group_size() -> usize {
GROUP
}
/// Packing factor `PACK`.
pub const fn pack_size(&self) -> usize {
PACK
}
/// Number of completely full blocks.
#[inline]
pub fn full_blocks(&self) -> usize {
self.data.repr().full_blocks()
}
/// Total number of blocks including any partially-filled tail.
#[inline]
pub fn num_blocks(&self) -> usize {
self.data.repr().num_blocks()
}
/// Number of valid elements in the last partially-full block, or 0 if all
/// blocks are full.
#[inline]
pub fn remainder(&self) -> usize {
self.data.repr().remainder()
}
/// Total number of logical rows rounded up to the next multiple of `GROUP`.
///
/// This is the number of "available" row slots in the backing allocation,
/// including zero-padded rows in the last (possibly partial) block.
#[inline]
pub fn available_rows(&self) -> usize {
self.data.repr().available_rows()
}
/// Return a raw typed pointer to the start of the backing data.
#[inline]
pub fn as_ptr(&self) -> *const T {
self.data.as_raw_ptr().cast::<T>()
}
/// Return the backing data as a shared slice.
///
/// The returned slice has `storage_len()` elements — this includes all padding
/// for partial blocks and column-group alignment.
#[inline]
pub fn as_slice(&self) -> &'a [T] {
let len = self.data.repr().storage_len();
// SAFETY: The backing allocation has exactly `storage_len()` elements of type T.
unsafe { std::slice::from_raw_parts(self.as_ptr(), len) }
}
/// Return a pointer to the start of the given block.
///
/// The caller may assume that for the returned pointer `ptr`,
/// `[ptr, ptr + GROUP * padded_ncols)` points to valid memory, even for the
/// remainder block.
///
/// # Safety
///
/// `block` must be less than `self.num_blocks()`. No bounds check is
/// performed in release builds; callers must verify the index themselves
/// (e.g. by iterating `0..self.num_blocks()`).
#[inline]
pub unsafe fn block_ptr_unchecked(&self, block: usize) -> *const T {
debug_assert!(block < self.num_blocks());
// SAFETY: Caller asserts `block < self.num_blocks()`.
unsafe { self.as_ptr().add(self.data.repr().block_offset(block)) }
}
/// Return a view over a full block as a [`MatrixView`].
///
/// The returned view has `padded_ncols / PACK` rows and `GROUP * PACK`
/// columns. For `PACK == 1` this simplifies to `ncols` rows and `GROUP`
/// columns (the standard transposed interpretation).
///
/// # Panics
///
/// Panics if `block >= self.full_blocks()`.
#[allow(clippy::expect_used)]
pub fn block(&self, block: usize) -> MatrixView<'a, T> {
assert!(block < self.full_blocks());
let offset = self.data.repr().block_offset(block);
let stride = self.data.repr().block_stride();
// SAFETY: `block < full_blocks()` (asserted above) guarantees
// `offset + stride` is within the backing allocation.
let data: &[T] = unsafe { std::slice::from_raw_parts(self.as_ptr().add(offset), stride) };
MatrixView::try_from(data, self.padded_ncols() / PACK, GROUP * PACK)
.expect("base data should have been sized correctly")
}
/// Return a view over the remainder block, or `None` if there is no
/// remainder.
///
/// The returned view has the same dimensions as [`block()`](Self::block):
/// `padded_ncols / PACK` rows and `GROUP * PACK` columns.
#[allow(clippy::expect_used)]
pub fn remainder_block(&self) -> Option<MatrixView<'a, T>> {
if self.remainder() == 0 {
None
} else {
let offset = self.data.repr().block_offset(self.full_blocks());
let stride = self.data.repr().block_stride();
// SAFETY: The remainder block exists (`remainder() != 0`),
// so `offset + stride` is within the backing allocation.
let data: &[T] =
unsafe { std::slice::from_raw_parts(self.as_ptr().add(offset), stride) };
Some(
MatrixView::try_from(data, self.padded_ncols() / PACK, GROUP * PACK)
.expect("base data should have been sized correctly"),
)
}
}
/// Retrieve the value at the logical `(row, col)`.
///
/// # Panics
///
/// Panics if `row >= self.nrows()` or `col >= self.ncols()`.
#[inline]
pub fn get_element(&self, row: usize, col: usize) -> T {
assert!(
row < self.nrows(),
"row {row} out of bounds (nrows = {})",
self.nrows()
);
assert!(
col < self.ncols(),
"col {col} out of bounds (ncols = {})",
self.ncols()
);
let idx = linear_index::<GROUP, PACK>(row, col, self.ncols());
// SAFETY: bounds checked above.
unsafe { *self.as_ptr().add(idx) }
}
/// Get an immutable row view, or `None` if `i` is out of bounds.
#[inline]
pub fn get_row(&self, i: usize) -> Option<Row<'_, T, GROUP, PACK>> {
self.data.get_row(i)
}
}
// ── BlockTransposedMut ───────────────────────────────────────────
impl<'a, T: Copy, const GROUP: usize, const PACK: usize> BlockTransposedMut<'a, T, GROUP, PACK> {
/// Borrow as an immutable [`BlockTransposedRef`].
#[inline]
pub fn as_view(&self) -> BlockTransposedRef<'_, T, GROUP, PACK> {
BlockTransposedRef {
data: self.data.as_view(),
}
}
// ── Delegated read methods ───────────────────────────────────
delegate_to_ref!(pub fn nrows(&self) -> usize);
delegate_to_ref!(pub fn ncols(&self) -> usize);
delegate_to_ref!(pub fn padded_ncols(&self) -> usize);
delegate_to_ref!(pub fn full_blocks(&self) -> usize);
delegate_to_ref!(pub fn num_blocks(&self) -> usize);
delegate_to_ref!(pub fn remainder(&self) -> usize);
delegate_to_ref!(pub fn available_rows(&self) -> usize);
delegate_to_ref!(pub fn as_ptr(&self) -> *const T);
delegate_to_ref!(pub fn as_slice(&self) -> &[T]);
delegate_to_ref!(#[allow(clippy::missing_safety_doc)] unsafe pub fn block_ptr_unchecked(&self, block: usize) -> *const T);
delegate_to_ref!(#[allow(clippy::expect_used)] pub fn block(&self, block: usize) -> MatrixView<'_, T>);
delegate_to_ref!(#[allow(clippy::expect_used)] pub fn remainder_block(&self) -> Option<MatrixView<'_, T>>);
delegate_to_ref!(pub fn get_element(&self, row: usize, col: usize) -> T);
/// Group size (blocking factor `GROUP`).
pub const fn group_size(&self) -> usize {
GROUP
}
/// Group size as `const` function on the *type*.
pub const fn const_group_size() -> usize {
GROUP
}
/// Packing factor `PACK`.
pub const fn pack_size(&self) -> usize {
PACK
}
/// Get an immutable row view, or `None` if `i` is out of bounds.
#[inline]
pub fn get_row(&self, i: usize) -> Option<Row<'_, T, GROUP, PACK>> {
self.data.get_row(i)
}
// ── Mutable methods ──────────────────────────────────────────
//
// The `_inner` variants consume `self` by value so that the lifetime of
// the returned view is tied to `'a` (the underlying allocation), not to
// a temporary reborrow. Public `&mut self` methods reborrow into a
// short-lived `BlockTransposedMut` and then call the inner variant.
/// Return the backing data as a mutable slice.
///
/// The returned slice has `storage_len()` elements (including all padding).
#[inline]
pub fn as_mut_slice(&mut self) -> &mut [T] {
self.reborrow_mut().mut_slice_inner()
}
fn mut_slice_inner(mut self) -> &'a mut [T] {
let len = self.data.repr().storage_len();
// SAFETY: We own exclusive access through `self`.
unsafe { std::slice::from_raw_parts_mut(self.data.as_raw_mut_ptr().cast::<T>(), len) }
}
/// Return a mutable view over a full block.
///
/// # Panics
///
/// Panics if `block >= self.full_blocks()`.
#[allow(clippy::expect_used)]
pub fn block_mut(&mut self, block: usize) -> MutMatrixView<'_, T> {
self.reborrow_mut().block_mut_inner(block)
}
#[allow(clippy::expect_used)]
fn block_mut_inner(mut self, block: usize) -> MutMatrixView<'a, T> {
let repr = *self.data.repr();
assert!(block < repr.full_blocks());
let offset = repr.block_offset(block);
let stride = repr.block_stride();
let pncols = repr.padded_ncols();
// SAFETY: `block < full_blocks()`, so the range is within the allocation.
let data: &mut [T] = unsafe {
std::slice::from_raw_parts_mut(
self.data.as_raw_mut_ptr().cast::<T>().add(offset),
stride,
)
};
MutMatrixView::try_from(data, pncols / PACK, GROUP * PACK)
.expect("base data should have been sized correctly")
}
/// Return a mutable view over the remainder block, or `None` if there is no
/// remainder.
#[allow(clippy::expect_used)]
pub fn remainder_block_mut(&mut self) -> Option<MutMatrixView<'_, T>> {
self.reborrow_mut().remainder_block_mut_inner()
}
#[allow(clippy::expect_used)]
fn remainder_block_mut_inner(mut self) -> Option<MutMatrixView<'a, T>> {
let repr = *self.data.repr();
if repr.remainder() == 0 {
None
} else {
let offset = repr.block_offset(repr.full_blocks());
let stride = repr.block_stride();
let pncols = repr.padded_ncols();
// SAFETY: Remainder block exists, so the range is within the allocation.
let data: &mut [T] = unsafe {
std::slice::from_raw_parts_mut(
self.data.as_raw_mut_ptr().cast::<T>().add(offset),
stride,
)
};
Some(
MutMatrixView::try_from(data, pncols / PACK, GROUP * PACK)
.expect("base data should have been sized correctly"),
)
}
}
/// Get a mutable row view, or `None` if `i` is out of bounds.
#[inline]