Skip to content

Commit 6d82800

Browse files
committed
Introduce macro to create static UncasedStrs
Add a static_uncased_str macro, which can create `&'static UncasedStr`s from `&'static str`s. This won't be necessary once rust-lang/rust#53605 lands, but that's at least a few months away.
1 parent b654387 commit 6d82800

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/borrowed.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,3 +242,20 @@ impl Hash for UncasedStr {
242242
self.0.bytes().for_each(|b| hasher.write_u8(b.to_ascii_lowercase()));
243243
}
244244
}
245+
246+
/// Cost-free conversion from a `&'static str` to a `&'static UncasedStr`.
247+
///
248+
/// This macro can be used in the definition of a static or const variable,
249+
/// while [`UncasedStr::new`] cannot.
250+
///
251+
/// When it is possible to mark `UncasedStr::new` as a `const fn`
252+
/// (see [rust-lang/rust#53605]), this macro will be removed.
253+
///
254+
/// [rust-lang/rust#53605]: https://github.com/rust-lang/rust/issues/53605
255+
#[macro_export]
256+
macro_rules! static_uncased_str {
257+
($string:expr) => {{
258+
// This is safe for the same reason that `UncasedStr::new` is safe.
259+
unsafe { ::core::mem::transmute::<&'static str, &'static UncasedStr>($string) }
260+
}}
261+
}

src/tests.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#![allow(deprecated)]
22

3-
use crate::UncasedStr;
3+
use crate::{static_uncased_str, UncasedStr};
44

55
use core::hash::{Hash, Hasher, SipHasher};
66

@@ -58,3 +58,9 @@ fn test_case_cmp() {
5858
assert!(UncasedStr::new("aA") > UncasedStr::new("a"));
5959
assert!(UncasedStr::new("aA") > UncasedStr::new("A"));
6060
}
61+
62+
#[test]
63+
fn test_static() {
64+
const FOO: &UncasedStr = static_uncased_str!("FOO");
65+
assert_eq!(FOO, UncasedStr::new("foo"));
66+
}

0 commit comments

Comments
 (0)