Skip to main content

non_empty_str/
macros.rs

1//! Macros for creating non-empty strings.
2
3/// Constructs [`NonEmptyStr`] from the given string, panicking if it is empty,
4/// and then converts it into [`NonEmptyString`].
5///
6/// # Examples
7///
8/// Simple usage:
9///
10/// ```
11/// use non_empty_str::non_empty_string;
12///
13/// let nekit = non_empty_string!("nekit");
14/// ```
15///
16/// Expands to:
17///
18/// ```
19/// use non_empty_str::non_empty_str;
20///
21/// let nekit = non_empty_str!("nekit").to_non_empty_string();
22/// ```
23///
24/// See [`non_empty_str!`] for more details.
25///
26/// Panicking if the string is empty:
27///
28/// ```should_panic
29/// use non_empty_str::non_empty_string;
30///
31/// let never = non_empty_string!("");
32/// ```
33///
34/// [`NonEmptyStr`]: crate::str::NonEmptyStr
35/// [`NonEmptyString`]: crate::string::NonEmptyString
36/// [`non_empty_str!`]: crate::non_empty_str
37#[macro_export]
38#[cfg(any(feature = "std", feature = "alloc"))]
39macro_rules! non_empty_string {
40    ($string: expr) => {
41        $crate::non_empty_str!($string).to_non_empty_string()
42    };
43}
44
45/// Constructs [`NonEmptyStr`] from the given string, panicking if it is empty.
46///
47/// # Examples
48///
49/// Simple usage:
50///
51/// ```
52/// use non_empty_str::non_empty_str;
53///
54/// let nekit = non_empty_str!("nekit");
55/// ```
56///
57/// Panicking if the string is empty:
58///
59/// ```should_panic
60/// use non_empty_str::non_empty_str;
61///
62/// let never = non_empty_str!("");
63/// ```
64///
65/// Compilation failure when in `const` contexts:
66///
67/// ```compile_fail
68/// use non_empty_str::non_empty_str;
69///
70/// let never = const { non_empty_str!("") };
71/// ```
72///
73/// [`NonEmptyStr`]: crate::str::NonEmptyStr
74#[macro_export]
75macro_rules! non_empty_str {
76    ($string: expr) => {
77        $crate::str::NonEmptyStr::from_str($string).expect($crate::str::EMPTY_STR)
78    };
79}
80
81/// Similar to [`non_empty_str!`] but for `const` contexts.
82///
83/// Note that the provided expression must be const-evaluatable, else the compilation will fail.
84///
85/// # Examples
86///
87/// ```
88/// use non_empty_str::const_non_empty_str;
89///
90/// let message = const_non_empty_str!("Hello, world!");
91/// ```
92///
93/// Failing compilation on empty strings:
94///
95/// ```compile_fail
96/// use non_empty_str::const_non_empty_str;
97///
98/// let never = const_non_empty_str!("");
99/// ```
100///
101/// [`non_empty_str!`]: crate::non_empty_str
102#[macro_export]
103macro_rules! const_non_empty_str {
104    ($string: expr) => {
105        const { $crate::non_empty_str!($string) }
106    };
107}