Skip to content

Commit

Permalink
sl-std: add SubsliceOffset trait
Browse files Browse the repository at this point in the history
See the relevant documentation on the trait for more info
  • Loading branch information
simonwuelker committed Sep 20, 2023
1 parent 9f5fe65 commit 079560f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions sl-std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ pub mod chars;
pub mod iter;
pub mod punycode;
pub mod rand;
pub mod slice;
pub mod time;
27 changes: 27 additions & 0 deletions sl-std/src/slice.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pub trait SubsliceOffset {
/// Returns the byte offset of an inner slice relative to an enclosing outer slice.
///
/// Examples
///
/// ```
/// let string = "a\nb\nc";
/// let lines: Vec<&str> = string.lines().collect();
/// assert!(string.subslice_offset(lines[0]) == Some(0)); // &"a"
/// assert!(string.subslice_offset(lines[1]) == Some(2)); // &"b"
/// assert!(string.subslice_offset(lines[2]) == Some(4)); // &"c"
/// assert!(string.subslice_offset("other!") == None);
/// ```
fn subslice_offset(&self, inner: &Self) -> Option<usize>;
}

impl SubsliceOffset for str {
fn subslice_offset(&self, inner: &str) -> Option<usize> {
let outer = self.as_ptr() as usize;
let inner = inner.as_ptr() as usize;
if (outer..outer + self.len()).contains(&inner) {
Some(inner.wrapping_sub(outer))
} else {
None
}
}
}

0 comments on commit 079560f

Please sign in to comment.