From d13a241f9056b3cf7240e1a766ece84e9b43ea07 Mon Sep 17 00:00:00 2001 From: DoumanAsh Date: Sat, 19 Oct 2024 09:17:01 +0900 Subject: [PATCH] Add const fn options for case conversion --- src/lib.rs | 38 ++++++++++++++++++++++++++++++++++++++ tests/push.rs | 6 ++++++ 2 files changed, 44 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 7ef9673..9d583f6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -186,6 +186,7 @@ impl StrBuf { } #[inline] + #[allow(clippy::missing_transmute_annotations)] ///Returns slice to already written data. pub const fn as_slice(&self) -> &[u8] { //Layout is: (, ) @@ -344,6 +345,24 @@ impl StrBuf { } } + #[inline(always)] + ///Modifies this string to convert all its characters into ASCII lower case equivalent + pub const fn into_ascii_lowercase(mut self) -> Self { + let len = self.len(); + let mut idx = 0; + loop { + if idx >= len { + break; + } + + self.inner[idx] = unsafe { + mem::MaybeUninit::new(self.inner[idx].assume_init().to_ascii_lowercase()) + }; + idx = idx.saturating_add(1); + } + self + } + #[inline(always)] ///Converts this string to its ASCII lower case equivalent in-place. pub fn make_ascii_lowercase(&mut self) { @@ -352,6 +371,25 @@ impl StrBuf { } } + + #[inline(always)] + ///Modifies this string to convert all its characters into ASCII upper case equivalent + pub const fn into_ascii_uppercase(mut self) -> Self { + let len = self.len(); + let mut idx = 0; + loop { + if idx >= len { + break; + } + + self.inner[idx] = unsafe { + mem::MaybeUninit::new(self.inner[idx].assume_init().to_ascii_uppercase()) + }; + idx = idx.saturating_add(1); + } + self + } + #[inline(always)] ///Converts this string to its ASCII upper case equivalent in-place. pub fn make_ascii_uppercase(&mut self) { diff --git a/tests/push.rs b/tests/push.rs index 4b101c8..c7bfede 100644 --- a/tests/push.rs +++ b/tests/push.rs @@ -6,10 +6,16 @@ type SmolStr = StrBuf<5>; fn should_correctly_convert_ascii_case() { let mut buf = SmolStr::new(); assert_eq!(buf.push_str("ロri"), "ロri".len()); + + let buf_copy = buf.clone().into_ascii_uppercase(); buf.make_ascii_uppercase(); assert_eq!(buf, "ロRI"); + assert_eq!(buf_copy, "ロRI"); + + let buf_copy = buf.clone().into_ascii_lowercase(); buf.make_ascii_lowercase(); assert_eq!(buf, "ロri"); + assert_eq!(buf_copy, "ロri"); } #[test]