Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add get_unchecked to ZalgoString #31

Merged
merged 4 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion common/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ This document contains all changes to the crate since version 0.9.4.
## 0.10.4

- Implement the `Index` trait for the different range types for `ZalgoString`.
- Add the `get` function to `ZalgoString` that works the same as `String::get`.
- Add the `get` and `get_unchecked` functions to `ZalgoString` that work the same as `str::get` and `str::get_unchecked`.

## 0.10.3

Expand Down
37 changes: 37 additions & 0 deletions common/src/zalgo_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,35 @@ impl ZalgoString {
self.0.get(index)
}

/// Returns an unchecked subslice of `self`.
///
/// This is the unchecked alternative to indexing a `ZalgoString`.
///
/// # Safety
///
/// This function has the same safety requirements as [`str::get_unchecked`]:
/// - The starting index must not exceed the ending index;
/// - Indexes must be within bounds of the original slice;
/// - Indexes must lie on UTF-8 sequence boundaries.
///
/// # Example
///
/// ```
/// # use zalgo_codec_common::{Error, ZalgoString};
/// let zs = ZalgoString::new("Zalgo")?;
/// unsafe {
/// assert_eq!(zs.get_unchecked(..3), "E\u{33a}");
/// }
/// # Ok::<(), Error>(())
/// ```
#[inline]
pub unsafe fn get_unchecked<I>(&self, index: I) -> &<I as SliceIndex<str>>::Output
where
I: SliceIndex<str>,
{
self.0.get_unchecked(index)
}

/// Returns an iterator over the encoded characters of the `ZalgoString`.
///
/// The first character is an "E", the others are unicode combining characters.
Expand Down Expand Up @@ -844,6 +873,14 @@ mod test {
assert!(zs.get(0..42).is_none());
}

#[test]
fn test_get_unchecked() {
let zs = ZalgoString::new("Zalgo").unwrap();
unsafe {
assert_eq!(zs.get_unchecked(..3), "E\u{33a}");
}
}

#[test]
fn test_indexing() {
let zs = ZalgoString::new("Zalgo").unwrap();
Expand Down