diff --git a/common/CHANGELOG.md b/common/CHANGELOG.md index 497226d..3529d85 100644 --- a/common/CHANGELOG.md +++ b/common/CHANGELOG.md @@ -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 diff --git a/common/src/zalgo_string.rs b/common/src/zalgo_string.rs index 8a147f1..1e480a0 100644 --- a/common/src/zalgo_string.rs +++ b/common/src/zalgo_string.rs @@ -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(&self, index: I) -> &>::Output + where + I: SliceIndex, + { + 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. @@ -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();