From 8ba6ccbba2bcee6eba9624c7b40af20494cb37c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20W=C3=BClker?= Date: Tue, 23 Jul 2024 20:50:17 +0200 Subject: [PATCH] sl-std: Add utility ascii! macro This macro is used to construct ascii strings with ease --- crates/sl-std/src/ascii/mod.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/sl-std/src/ascii/mod.rs b/crates/sl-std/src/ascii/mod.rs index 082f763b..989616d2 100644 --- a/crates/sl-std/src/ascii/mod.rs +++ b/crates/sl-std/src/ascii/mod.rs @@ -48,3 +48,30 @@ impl AsciiCharExt for Char { } } } + +/// Allows for easy definition of ascii-strings +/// +/// Since rust does not allow us to define our own string literals, the use of a macro +/// is necessary. If the provided literal contains non-ascii data then the invocation will +/// panic at compile-time. +/// +/// # Example +/// ``` +/// # #![feature(ascii_char)] +/// # use sl_std::ascii; +/// +/// let foo: &ascii::Str = ascii!("foo"); +/// assert_eq!(foo.as_str(), "foo"); +/// +/// ``` +#[macro_export] +macro_rules! ascii { + ($s: expr) => { + const { + match $s.as_bytes().as_ascii() { + Some(ascii) => $crate::ascii::Str::from_ascii_chars(ascii), + None => panic!("string literal is not ascii"), + } + } + }; +}