summaryrefslogtreecommitdiffstats
path: root/vendor/tinystr/src/tinystrauto.rs
blob: 9e2387cc13fa63bfe06628961bdbff40e7ca40c5 (plain)
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
use std::fmt;
use std::ops::Deref;
use std::str::FromStr;

use crate::helpers::String;
use crate::Error;
use crate::TinyStr16;

/// An ASCII string that is tiny when <= 16 chars and a String otherwise.
///
/// # Examples
///
/// ```
/// use tinystr::TinyStrAuto;
///
/// let s1: TinyStrAuto = "Testing".parse()
///     .expect("Failed to parse.");
///
/// assert_eq!(s1, "Testing");
/// ```
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub enum TinyStrAuto {
    /// Up to 16 characters stored on the stack.
    Tiny(TinyStr16),
    /// 17 or more characters stored on the heap.
    Heap(String),
}

impl fmt::Display for TinyStrAuto {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.deref().fmt(f)
    }
}

impl Deref for TinyStrAuto {
    type Target = str;

    fn deref(&self) -> &str {
        use TinyStrAuto::*;
        match self {
            Tiny(value) => value.deref(),
            Heap(value) => value.deref(),
        }
    }
}

impl PartialEq<&str> for TinyStrAuto {
    fn eq(&self, other: &&str) -> bool {
        self.deref() == *other
    }
}

impl FromStr for TinyStrAuto {
    type Err = Error;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        if text.len() <= 16 {
            match TinyStr16::from_str(text) {
                Ok(result) => Ok(TinyStrAuto::Tiny(result)),
                Err(err) => Err(err),
            }
        } else {
            if !text.is_ascii() {
                return Err(Error::NonAscii);
            }
            match String::from_str(text) {
                Ok(result) => Ok(TinyStrAuto::Heap(result)),
                Err(_) => unreachable!(),
            }
        }
    }
}