Skip to content

Commit 67fc122

Browse files
slice: utility 'enforce_embedding' (#780)
Summary: Pull Request resolved: #780 as discussed in D79287947, this diff provides a dedicated function to enforce that a supposed 'view' slice is physically contained by a base slice. Reviewed By: pzhan9 Differential Revision: D79751839 fbshipit-source-id: 99f72ebfc9830f10efe321f3213aeadcaa8a58c8
1 parent b48988a commit 67fc122

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

ndslice/src/slice.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,17 @@ impl Slice {
654654
strides: self.strides.clone(),
655655
})
656656
}
657+
658+
/// Ensures that every storage offset used by `other` is valid in
659+
/// `self`.
660+
///
661+
/// That is, for all p ∈ other:
662+
/// `self.coordinates(other.location(p))` is defined.
663+
pub fn enforce_embedding(&self, other: &Slice) -> Result<(), SliceError> {
664+
other
665+
.iter()
666+
.try_for_each(|loc| self.coordinates(loc).map(|_| ()))
667+
}
657668
}
658669

659670
impl std::fmt::Display for Slice {
@@ -1075,4 +1086,20 @@ mod tests {
10751086
assert_eq!(c.get(c.index(loc).unwrap()).unwrap(), loc);
10761087
}
10771088
}
1089+
1090+
#[test]
1091+
fn embedding_succeeds_for_contained_view() {
1092+
let base = Slice::new(0, vec![4, 4], vec![4, 1]).unwrap(); // 4×4 matrix, row-major
1093+
let view = Slice::new(5, vec![2, 2], vec![4, 1]).unwrap(); // a 2×2 submatrix starting at (1,1)
1094+
1095+
assert!(base.enforce_embedding(&view).is_ok());
1096+
}
1097+
1098+
#[test]
1099+
fn embedding_fails_for_out_of_bounds_view() {
1100+
let base = Slice::new(0, vec![4, 4], vec![4, 1]).unwrap(); // 4×4 matrix
1101+
let view = Slice::new(14, vec![2, 2], vec![4, 1]).unwrap(); // starts at (3,2), accesses (4,3)
1102+
1103+
assert!(base.enforce_embedding(&view).is_err());
1104+
}
10781105
}

0 commit comments

Comments
 (0)