1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
use core::fmt;
use core::ops::Deref;

use arrayvec::ArrayString;

const MAX_DEC_LEN: usize = 8;
pub(crate) const MAX_ERR_LEN: usize = 256;
const MAX_INF_LEN: usize = 128;
pub(crate) const MAX_MIN_LEN: usize = 8;
const MAX_NAN_LEN: usize = 64;
const MAX_PLUS_LEN: usize = 8;
pub(crate) const MAX_SEP_LEN: usize = 8;

#[cfg(feature = "with-serde")]
use serde::{de, ser};

use crate::error::Error;

/// Simple wrapper type for a `&str` to make sure its length is less than the maximum for
/// a decimal (8 bytes).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct DecimalStr<'a>(&'a str);

impl<'a> DecimalStr<'a> {
    /// Constructs an [`DecimalStr`], ensuring that the length is less than the maximum for
    /// a decimal (8 bytes).
    ///
    /// # Errors
    ///
    /// Returns an error if the provided `&str`'s length is more than 8 bytes.
    ///
    /// [`DecimalStr`]: struct.DecimalStr.html
    pub fn new(s: &'a str) -> Result<DecimalStr<'a>, Error> {
        Self::_new(s)
    }
}

/// Simple wrapper type for a `&str` to make sure its length is less than the maximum for
/// an infinity symbol (128 bytes).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct InfinityStr<'a>(&'a str);

impl<'a> InfinityStr<'a> {
    /// Constructs an [`InfinityStr`], ensuring that the length is less than the maximum for
    /// an infinity symbol (128 bytes).
    ///
    /// # Errors
    ///
    /// Returns an error if the provided `&str`'s length is more than 128 bytes.
    ///
    /// [`InfinityStr`]: struct.InfinityStr.html
    pub fn new(s: &'a str) -> Result<InfinityStr<'a>, Error> {
        Self::_new(s)
    }
}

/// Simple wrapper type for a `&str` to make sure its length is less than the maximum for
/// a minus sign (8 bytes).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct MinusSignStr<'a>(&'a str);

impl<'a> MinusSignStr<'a> {
    /// Constructs a [`MinusSignStr`], ensuring that the length is less than the maximum for
    /// a minus sign (8 bytes).
    ///
    /// # Errors
    ///
    /// Returns an error if the provided `&str`'s length is more than 7 bytes.
    ///
    /// [`MinusSignStr`]: struct.MinusSignStr.html
    pub fn new(s: &'a str) -> Result<MinusSignStr<'a>, Error> {
        Self::_new(s)
    }
}

/// Simple wrapper type for a `&str` to make sure its length is less than the maximum for
/// a nan symbol (64 bytes).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct NanStr<'a>(&'a str);

impl<'a> NanStr<'a> {
    /// Constructs an [`NanStr`], ensuring that the length is less than the maximum for
    /// a nan symbol (64 bytes).
    ///
    /// # Errors
    ///
    /// Returns an error if the provided `&str`'s length is more than 64 bytes.
    ///
    /// [`NanStr`]: struct.NanStr.html
    pub fn new(s: &'a str) -> Result<NanStr<'a>, Error> {
        Self::_new(s)
    }
}

/// Simple wrapper type for a `&str` to make sure its length is less than the maximum for
/// a plus sign (8 bytes).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct PlusSignStr<'a>(&'a str);

impl<'a> PlusSignStr<'a> {
    /// Constructs an [`PlusSignStr`], ensuring that the length is less than the maximum for
    /// a plus sign (8 bytes).
    ///
    /// # Errors
    ///
    /// Returns an error if the provided `&str`'s length is more than 8 bytes.
    ///
    /// [`PlusSignStr`]: struct.PlusSignStr.html
    pub fn new(s: &'a str) -> Result<PlusSignStr<'a>, Error> {
        Self::_new(s)
    }
}

/// Simple wrapper type for a `&str` to make sure its length is less than the maximum for
/// a separator (8 bytes).
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SeparatorStr<'a>(&'a str);

impl<'a> SeparatorStr<'a> {
    /// Constructs an [`SeparatorStr`], ensuring that the length is less than the maximum for
    /// a separator (8 bytes).
    ///
    /// # Errors
    ///
    /// Returns an error if the provided `&str`'s length is more than 8 bytes.
    ///
    /// [`SeparatorStr`]: struct.SeparatorStr.html
    pub fn new(s: &'a str) -> Result<SeparatorStr<'a>, Error> {
        Self::_new(s)
    }
}

macro_rules! create_impls {
    ( $name:ident, $max_len:expr ) => {
        impl<'a> $name<'a> {
            #[inline(always)]
            /// Allows recovery of the initial / wrapped `&str`.
            pub fn into_str(self) -> &'a str {
                self.0
            }

            #[inline(always)]
            fn _new(s: &'a str) -> Result<$name<'a>, Error> {
                let len = s.len();
                if len > $max_len {
                    return Err(Error::capacity(len, $max_len));
                }
                Ok($name(s))
            }
        }

        impl<'a> AsRef<str> for $name<'a> {
            #[inline(always)]
            fn as_ref(&self) -> &str {
                self.0
            }
        }

        impl<'a> fmt::Debug for $name<'a> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{:?}", self.0)
            }
        }

        impl<'a> fmt::Display for $name<'a> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.0)
            }
        }
    };
}

create_impls!(DecimalStr, MAX_DEC_LEN);
create_impls!(InfinityStr, MAX_INF_LEN);
create_impls!(MinusSignStr, MAX_MIN_LEN);
create_impls!(NanStr, MAX_NAN_LEN);
create_impls!(PlusSignStr, MAX_PLUS_LEN);
create_impls!(SeparatorStr, MAX_SEP_LEN);

macro_rules! create_string {
    ( $name:ident, $visitor:ident, $max_len:expr ) => {
        #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
        pub(crate) struct $name(ArrayString<$max_len>);

        impl $name {
            #[allow(dead_code)]
            pub(crate) fn new<S>(s: S) -> Result<Self, Error>
            where
                S: AsRef<str>,
            {
                let s = s.as_ref();
                let a = ArrayString::from(s).map_err(|_| Error::capacity(s.len(), $max_len))?;
                Ok($name(a))
            }

            #[allow(dead_code)]
            pub(crate) fn truncated<S>(s: S) -> Self
            where
                S: AsRef<str>,
            {
                let s = s.as_ref();
                let s = if s.len() > $max_len {
                    &s[0..$max_len]
                } else {
                    s
                };
                $name(ArrayString::from(s).unwrap())
            }

            #[allow(dead_code)]
            #[inline(always)]
            pub(crate) fn capacity() -> usize {
                $max_len
            }
        }

        impl Deref for $name {
            type Target = str;

            #[inline(always)]
            fn deref(&self) -> &str {
                self.0.deref()
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.0)
            }
        }

        impl From<$name> for ArrayString<$max_len> {
            fn from(s: $name) -> Self {
                s.0
            }
        }

        #[cfg(feature = "with-serde")]
        impl ser::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: ser::Serializer,
            {
                serializer.serialize_str(self.0.as_str())
            }
        }

        #[cfg(feature = "with-serde")]
        struct $visitor;

        #[cfg(feature = "with-serde")]
        impl<'de> de::Visitor<'de> for $visitor {
            type Value = $name;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(formatter, "a string containing at most {} bytes", $max_len)
            }

            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                $name::new(s).map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))
            }
        }

        #[cfg(feature = "with-serde")]
        impl<'de> de::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: de::Deserializer<'de>,
            {
                deserializer.deserialize_str($visitor)
            }
        }
    };
}

create_string!(DecString, DecVisitor, MAX_DEC_LEN);
create_string!(ErrString, ErrVisitor, MAX_ERR_LEN);
create_string!(InfString, InfVisitor, MAX_INF_LEN);
create_string!(MinString, MinVisitor, MAX_MIN_LEN);
create_string!(NanString, NanVisitor, MAX_NAN_LEN);
create_string!(PlusString, PlusVisitor, MAX_PLUS_LEN);
create_string!(SepString, SepVisitor, MAX_SEP_LEN);