refinement_types/
type_str.rs

1//! Type-level strings.
2
3use crate::static_str::StaticStr;
4
5/// Represents type-level strings.
6pub trait TypeStr {
7    /// The string value.
8    const VALUE: StaticStr;
9}
10
11#[doc(hidden)]
12pub mod import {
13    pub use core::fmt;
14}
15
16/// Lifts static strings to type-level strings.
17///
18/// # Examples
19///
20/// ```
21/// use refinement_types::type_str;
22///
23/// type_str!(HelloWorld = "Hello, world!");
24/// ```
25///
26/// Is equivalent to:
27///
28/// ```
29/// use core::fmt;
30///
31/// use refinement_types::{StaticStr, TypeStr};
32///
33/// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
34/// struct HelloWorld;
35///
36/// impl TypeStr for HelloWorld {
37///     const VALUE: StaticStr = "Hello, world!";
38/// }
39///
40/// impl fmt::Display for HelloWorld {
41///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
42///         formatter.write_str(Self::VALUE)
43///     }
44/// }
45/// ```
46#[macro_export]
47macro_rules! type_str {
48    ($vis: vis $name: ident = $value: expr $(=> $doc: expr)?) => {
49        $(
50            #[doc = $doc]
51        )?
52        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
53        $vis struct $name;
54
55        impl $crate::type_str::TypeStr for $name {
56            const VALUE: $crate::static_str::StaticStr = $value;
57        }
58
59        impl $crate::type_str::import::fmt::Display for $name {
60            fn fmt(
61                &self, formatter: &mut $crate::type_str::import::fmt::Formatter<'_>
62            ) -> $crate::type_str::import::fmt::Result {
63                use $crate::type_str::TypeStr;
64
65                formatter.write_str(Self::VALUE)
66            }
67        }
68    };
69}