-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
See the relevant documentation on the trait for more info
- Loading branch information
1 parent
9f5fe65
commit 079560f
Showing
2 changed files
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,4 +16,5 @@ pub mod chars; | |
pub mod iter; | ||
pub mod punycode; | ||
pub mod rand; | ||
pub mod slice; | ||
pub mod time; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} | ||
} |