astr 0.1.1

A const lenght stack str
Documentation
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#![cfg_attr(not(feature = "std"), no_std)]
#![doc = include_str!("../README.md")]

use core::{array::TryFromSliceError, str::Utf8Error};

/// # astr
/// Build an AStr from a string literal.
///
/// ```rust
/// use astr::astr;
///
/// let s = astr!("iam a string");
/// assert_eq!(s, "iam a string");
/// ```
///
#[macro_export]
macro_rules! astr {
    ($input:expr) => {
        unsafe {
            const STR: &str = $input;
            const LEN: usize = STR.len();
            // this is safa because we know that the bytes are valid utf8
            $crate::AStr::<LEN>::from_utf8_array_unchecked_ref(&*STR.as_ptr().cast::<[u8; LEN]>())
        }
    };
}

/// A str with a copiletime length.
///
/// This is a wrapper around an array of bytes representing an utf-8 string.
///
/// use the `astr!` macro to create an AStr from a string literal.
///
/// ```rust
/// use astr::astr;
///
/// let s = astr!("iam a string");
/// assert_eq!(s, "iam a string");
/// ```
///
/// if you want to create an AStr from a string or string reference, use the `AStr::try_from`
///
/// ```rust
/// use astr::AStr;
///
/// let s = AStr::<11>::try_from("Hallo World").unwrap();
/// assert_eq!(s, "Hallo World");
/// ```
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct AStr<const LEN: usize>([u8; LEN]);

impl<const LEN: usize> std::hash::Hash for AStr<LEN> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.as_str().hash(state);
    }
}

#[derive(Debug, Clone)]
pub enum AStrError {
    Utf8(Utf8Error),
    Slice(TryFromSliceError),
}

impl From<Utf8Error> for AStrError {
    fn from(err: Utf8Error) -> Self {
        Self::Utf8(err)
    }
}

impl From<TryFromSliceError> for AStrError {
    fn from(err: TryFromSliceError) -> Self {
        Self::Slice(err)
    }
}

impl core::fmt::Display for AStrError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Utf8(err) => err.fmt(f),
            Self::Slice(err) => err.fmt(f),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for AStrError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Utf8(ref err) => Some(err),
            Self::Slice(ref err) => Some(err),
        }
    }
}

impl<const LEN: usize> AStr<LEN> {
    /// Create a new AStr from an array of bytes.
    /// # Safety
    /// The slice must be valid UTF-8.
    pub const unsafe fn from_utf8_array_unchecked(arr: [u8; LEN]) -> Self {
        *Self::from_utf8_array_unchecked_ref(&arr)
    }

    /// Create a new AStr from an array of bytes.
    /// # Safety
    /// The slice must be valid UTF-8.
    pub const unsafe fn from_utf8_array_unchecked_ref(arr: &[u8; LEN]) -> &Self {
        core::mem::transmute(arr)
    }

    /// Create a new AStr from an array of bytes.
    /// # Safety
    /// The slice must be valid UTF-8.
    pub unsafe fn from_utf8_array_unchecked_mut(arr: &mut [u8; LEN]) -> &mut Self {
        core::mem::transmute(arr)
    }

    /// Create a new AStr from a slice of bytes.
    pub fn from_utf8_array_ref(arr: &[u8; LEN]) -> Result<&Self, AStrError> {
        core::str::from_utf8(arr)?;
        Ok(unsafe { Self::from_utf8_array_unchecked_ref(arr) })
    }

    /// Create a new AStr from a slice of bytes.
    pub fn from_utf8_array_mut(arr: &mut [u8; LEN]) -> Result<&mut Self, AStrError> {
        core::str::from_utf8_mut(arr)?;
        Ok(unsafe { Self::from_utf8_array_unchecked_mut(arr) })
    }

    /// Create a new AStr from a slice of bytes.
    pub fn from_utf8(slice: &[u8]) -> Result<&Self, AStrError> {
        Ok(Self::from_utf8_array_ref(slice.try_into()?)?)
    }

    /// Create a new AStr from a slice of bytes.
    pub fn from_utf8_mut(slice: &mut [u8]) -> Result<&mut Self, AStrError> {
        Ok(Self::from_utf8_array_mut(slice.try_into()?)?)
    }

    /// Create a new AStr from a str
    pub fn from_str_ref(str: &str) -> Result<&Self, AStrError> {
        let arr = str.as_bytes().try_into()?;
        Ok(unsafe { Self::from_utf8_array_unchecked_ref(arr) })
    }

    /// Create a new AStr from a str
    pub fn from_str_mut(str: &mut str) -> Result<&mut Self, AStrError> {
        Ok(unsafe {
            let arr = str.as_bytes_mut().try_into()?;
            Self::from_utf8_array_unchecked_mut(arr)
        })
    }

    /// get byte representation of the AStr
    pub const fn as_bytes_array(&self) -> &[u8; LEN] {
        &self.0
    }

    /// get mutable byte representation of the AStr
    /// # Safety
    /// Invariant: the byte array must be valid UTF-8.
    pub unsafe fn as_bytes_array_mut(&mut self) -> &mut [u8; LEN] {
        &mut self.0
    }

    /// get byte representation of the AStr
    pub const fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// get mutable byte representation of the AStr
    /// # Safety
    /// Invariant: the byte array must be valid UTF-8.
    pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }

    /// get str representation of the AStr
    pub const fn as_str(&self) -> &str {
        unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
    }

    /// get mutable str representation of the AStr
    pub fn as_str_mut(&mut self) -> &mut str {
        unsafe { core::str::from_utf8_unchecked_mut(self.as_bytes_mut()) }
    }
}

impl<const LEN: usize> AsRef<str> for AStr<LEN> {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<const LEN: usize> AsMut<str> for AStr<LEN> {
    fn as_mut(&mut self) -> &mut str {
        self.as_str_mut()
    }
}

impl<const LEN: usize> core::borrow::Borrow<str> for AStr<LEN> {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl<const LEN: usize> core::borrow::BorrowMut<str> for AStr<LEN> {
    fn borrow_mut(&mut self) -> &mut str {
        self.as_str_mut()
    }
}

impl<const LEN: usize> AsRef<[u8]> for AStr<LEN> {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

// Should be Unsize<str> but that's unstable
impl<const LEN: usize> core::ops::Deref for AStr<LEN> {
    type Target = str;
    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl<const LEN: usize> core::ops::DerefMut for AStr<LEN> {
    fn deref_mut(&mut self) -> &mut str {
        self.as_str_mut()
    }
}

impl<const LEN: usize> core::fmt::Debug for AStr<LEN> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.as_str().fmt(f)
    }
}

impl<const LEN: usize> core::fmt::Display for AStr<LEN> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.as_str().fmt(f)
    }
}

impl<'a, const LEN: usize> TryFrom<&'a str> for &'a AStr<LEN> {
    type Error = AStrError;

    fn try_from(str: &'a str) -> Result<Self, Self::Error> {
        AStr::from_str_ref(str)
    }
}

impl<'a, const LEN: usize> TryFrom<&'a mut str> for &'a mut AStr<LEN> {
    type Error = AStrError;

    fn try_from(str: &'a mut str) -> Result<Self, Self::Error> {
        AStr::from_str_mut(str)
    }
}

impl<const LEN: usize> TryFrom<&'_ str> for AStr<LEN> {
    type Error = AStrError;

    fn try_from(str: &'_ str) -> Result<Self, Self::Error> {
        Ok(*AStr::from_str_ref(str)?)
    }
}

impl<const LEN: usize> core::str::FromStr for AStr<LEN> {
    type Err = AStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        AStr::try_from(s)
    }
}

impl<const LEN: usize> PartialEq<str> for AStr<LEN> {
    fn eq(&self, other: &str) -> bool {
        self.as_str().eq(other)
    }
}

impl<const LEN: usize> PartialEq<AStr<LEN>> for &AStr<LEN> {
    fn eq(&self, other: &AStr<LEN>) -> bool {
        AStr::<LEN>::eq(self, other)
    }
}

impl<const LEN: usize> PartialEq<&'_ str> for AStr<LEN> {
    fn eq(&self, other: &&'_ str) -> bool {
        self.eq(*other)
    }
}

impl<const LEN: usize> PartialEq<AStr<LEN>> for str {
    fn eq(&self, other: &AStr<LEN>) -> bool {
        self.eq(other.as_str())
    }
}

impl<const LEN: usize> PartialEq<AStr<LEN>> for &'_ str {
    fn eq(&self, other: &AStr<LEN>) -> bool {
        (*self).eq(other)
    }
}

impl<I: core::slice::SliceIndex<str>, const LEN: usize> core::ops::Index<I> for AStr<LEN> {
    type Output = I::Output;

    fn index(&self, index: I) -> &Self::Output {
        self.as_str().index(index)
    }
}

impl<I: core::slice::SliceIndex<str>, const LEN: usize> core::ops::IndexMut<I> for AStr<LEN> {
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        self.as_str_mut().index_mut(index)
    }
}

#[cfg(feature = "std")]
impl<const LEN: usize> AsRef<std::ffi::OsStr> for AStr<LEN> {
    fn as_ref(&self) -> &std::ffi::OsStr {
        self.as_str().as_ref()
    }
}

#[cfg(feature = "std")]
impl<const LEN: usize> AsRef<std::path::Path> for AStr<LEN> {
    fn as_ref(&self) -> &std::path::Path {
        self.as_str().as_ref()
    }
}

#[cfg(feature = "std")]
impl<const LEN: usize> From<AStr<LEN>> for String {
    fn from(s: AStr<LEN>) -> Self {
        s.as_str().into()
    }
}

#[cfg(feature = "std")]
impl<const LEN: usize> TryFrom<String> for AStr<LEN> {
    type Error = AStrError;

    fn try_from(str: String) -> Result<Self, Self::Error> {
        Ok(*AStr::from_str_ref(&str)?)
    }
}

impl Default for AStr<0> {
    fn default() -> Self {
        AStr([])
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use super::AStr;
    use serde::{
        de::{self, Visitor},
        Deserialize, Deserializer, Serialize, Serializer,
    };

    impl<const LEN: usize> Serialize for AStr<LEN> {
        fn serialize<S: Serializer>(&'_ self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.serialize_str(self.as_str())
        }
    }

    struct AStrVisitor<const LEN: usize>;

    impl<'de, const LEN: usize> Visitor<'de> for AStrVisitor<LEN> {
        type Value = AStr<LEN>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(formatter, "a string of length {}", LEN)
        }

        #[inline]
        fn visit_str<E: de::Error>(self, s: &'_ str) -> Result<Self::Value, E> {
            AStr::try_from(s).map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))
        }
    }

    impl<'de, const LEN: usize> Deserialize<'de> for AStr<LEN> {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_str(AStrVisitor::<LEN>)
        }
    }
}
#[cfg(test)]
mod tests {
    use super::{astr, AStr};

    #[test]
    fn test_const() {
        const TEST_STR: AStr<4> = *astr!("test");
        assert_eq!(TEST_STR.as_str(), "test");
    }

    #[test]
    fn test_a() {
        let s = astr!("hello");

        assert_eq!(s.len(), 5);
        assert_eq!(s, "hello");
    }

    #[test]
    fn test_index() {
        let s = astr!("hello world");

        assert_eq!(&s[0..5], "hello");
    }

    #[test]
    fn test_to_string() {
        let s = *astr!("hello");

        assert_eq!(s.to_string(), "hello");
    }

    #[test]
    fn test_from_string() {
        const S: &str = "hello";
        let s = *astr!(S);

        assert_eq!(s.to_string(), "hello");
    }

    #[test]
    fn test_cstr() {
        let s = *astr!("hello\0");
        let str = s.as_str();
        let cstr = std::ffi::CStr::from_bytes_with_nul(str.as_bytes()).unwrap();
        assert_eq!(cstr.to_str().unwrap(), "hello");
    }
}