Skip to content

Commit

Permalink
Introduce macro to create static UncasedStrs
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
benesch committed Jun 18, 2021
1 parent b654387 commit 6d82800
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/borrowed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,20 @@ impl Hash for UncasedStr {
self.0.bytes().for_each(|b| hasher.write_u8(b.to_ascii_lowercase()));
}
}

/// Cost-free conversion from a `&'static str` to a `&'static UncasedStr`.
///
/// This macro can be used in the definition of a static or const variable,
/// while [`UncasedStr::new`] cannot.
///
/// When it is possible to mark `UncasedStr::new` as a `const fn`
/// (see [rust-lang/rust#53605]), this macro will be removed.
///
/// [rust-lang/rust#53605]: https://github.com/rust-lang/rust/issues/53605
#[macro_export]
macro_rules! static_uncased_str {
($string:expr) => {{
// This is safe for the same reason that `UncasedStr::new` is safe.
unsafe { ::core::mem::transmute::<&'static str, &'static UncasedStr>($string) }
}}
}
8 changes: 7 additions & 1 deletion src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![allow(deprecated)]

use crate::UncasedStr;
use crate::{static_uncased_str, UncasedStr};

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

Expand Down Expand Up @@ -58,3 +58,9 @@ fn test_case_cmp() {
assert!(UncasedStr::new("aA") > UncasedStr::new("a"));
assert!(UncasedStr::new("aA") > UncasedStr::new("A"));
}

#[test]
fn test_static() {
const FOO: &UncasedStr = static_uncased_str!("FOO");
assert_eq!(FOO, UncasedStr::new("foo"));
}

0 comments on commit 6d82800

Please sign in to comment.