Skip to content

Commit

Permalink
perf: faster WithIndices
Browse files Browse the repository at this point in the history
  • Loading branch information
h-a-n-a committed Dec 16, 2024
1 parent 82a1d75 commit 5ca265b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1260,6 +1260,10 @@ pub trait SourceText<'a>: Default + Clone + ToString {
/// Returns a slice of the text specified by the byte range.
fn byte_slice(&self, range: Range<usize>) -> Self;

/// Returns a slice of the text specified by the byte range without bounds checking.
#[allow(unsafe_code)]
unsafe fn byte_slice_unchecked(&self, range: Range<usize>) -> Self;

/// Returns true if the text is empty.
fn is_empty(&self) -> bool;

Expand Down Expand Up @@ -1293,6 +1297,11 @@ impl<'a> SourceText<'a> for Rope<'a> {
self.byte_slice(range)
}

#[allow(unsafe_code)]
unsafe fn byte_slice_unchecked(&self, range: Range<usize>) -> Self {
self.byte_slice_unchecked(range)
}

#[inline]
fn is_empty(&self) -> bool {
self.is_empty()
Expand Down Expand Up @@ -1330,6 +1339,11 @@ impl<'a> SourceText<'a> for &'a str {
self.get(range).unwrap_or_default()
}

#[allow(unsafe_code)]
unsafe fn byte_slice_unchecked(&self, range: Range<usize>) -> Self {
self.get_unchecked(range)
}

#[inline]
fn is_empty(&self) -> bool {
(*self).is_empty()
Expand Down
9 changes: 8 additions & 1 deletion src/with_indices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,14 @@ where
let str_len = self.line.len();
let start = *indices_indexes.get(start_index).unwrap_or(&str_len);
let end = *indices_indexes.get(end_index).unwrap_or(&str_len);
self.line.byte_slice(start..end)

#[allow(unsafe_code)]
unsafe {
// SAFETY: Since `indices` iterates over the `CharIndices` of `self`, we can guarantee
// that the indices obtained from it will always be within the bounds of `self` and they
// will always lie on UTF-8 sequence boundaries.
self.line.byte_slice_unchecked(start..end)
}
}
}

Expand Down

0 comments on commit 5ca265b

Please sign in to comment.