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
use core::fmt;
use std::{
    borrow::Cow,
    ops::{Add, AddAssign, Deref},
};

mod error;
pub use error::Error;

/// An identifier wrapper for SQLite identifiers.  This checks validity and
/// wraps the identifier in quotes with escapes for protection.
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct Identifier<'a> {
    inner: Cow<'a, str>,
    quoted: String,
}

impl<'a> TryFrom<Cow<'a, str>> for Identifier<'a> {
    type Error = Error;

    fn try_from(value: Cow<'a, str>) -> Result<Self, Self::Error> {
        if value.find('\0').is_some() {
            return Err(Error::NullCharacter);
        }
        let len = 2 + value.chars().filter(|&c| c == '"').count() + value.len();
        let mut quoted = String::new();
        quoted.reserve_exact(len);
        {
            quoted.push('"');
            let mut value: &str = &value;
            loop {
                match value.find('"') {
                    Some(index) => {
                        quoted.push_str(&value[..=index]);
                        quoted.push('"');

                        value = &value[index + 1..];
                    }
                    None => {
                        quoted.push_str(value);
                        break;
                    }
                }
            }
            quoted.push('"');
        }
        Ok(Identifier {
            inner: value,
            quoted,
        })
    }
}

impl<'a> TryFrom<&'a str> for Identifier<'a> {
    type Error = Error;

    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        Identifier::try_from(Cow::Borrowed(value))
    }
}

impl TryFrom<String> for Identifier<'static> {
    type Error = Error;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Identifier::try_from(Cow::Owned(value))
    }
}

impl<'a> From<Identifier<'a>> for Cow<'a, str> {
    fn from(value: Identifier<'a>) -> Self {
        value.inner
    }
}

impl<'a> Deref for Identifier<'a> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a, T> AsRef<T> for Identifier<'a>
where
    T: ?Sized,
    <Identifier<'a> as Deref>::Target: AsRef<T>,
{
    fn as_ref(&self) -> &T {
        self.deref().as_ref()
    }
}
impl<'a, 'b> Add<&Identifier<'b>> for Identifier<'a> {
    type Output = Identifier<'a>;

    fn add(mut self, rhs: &Identifier) -> Self::Output {
        self += rhs;
        self
    }
}

impl<'a, 'b> AddAssign<&Identifier<'b>> for Identifier<'a> {
    fn add_assign(&mut self, rhs: &Identifier) {
        let mut inner = self.inner.to_mut();
        inner.reserve_exact(rhs.inner.len());
        *inner += &rhs.inner;

        // Don't need rhs's quotation marks.
        self.quoted.reserve_exact(rhs.quoted.len() - 2);
        self.quoted.pop();
        self.quoted += &rhs.quoted[1..];
    }
}

impl<'a> fmt::Display for Identifier<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.quoted.fmt(f)
    }
}

#[cfg(test)]
mod test {
    use super::Identifier;

    #[test]
    fn tests() {
        assert_eq!(
            Identifier::try_from("main").unwrap().to_string(),
            String::from("\"main\""),
        );
        assert_eq!(
            Identifier::try_from(String::from("ma\"in"))
                .unwrap()
                .to_string(),
            String::from("\"ma\"\"in\""),
        );
        assert_eq!(
            Identifier::try_from(String::from("\"main"))
                .unwrap()
                .to_string(),
            String::from("\"\"\"main\""),
        );
        assert_eq!(
            Identifier::try_from(String::from("main\""))
                .unwrap()
                .to_string(),
            String::from("\"main\"\"\""),
        );
        assert!(Identifier::try_from(String::from("ma\0in")).is_err());
    }

    #[test]
    fn test_add() {
        assert_eq!(
            (Identifier::try_from(String::from("main")).unwrap()
                + &String::from("_after").try_into().unwrap())
                .to_string(),
            "\"main_after\"",
        );
    }
}