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
use std::str::Chars;
use std::iter::Iterator;
use std::cmp::{ PartialEq, Eq, max };
use std::ascii::AsciiExt;

/// Analogous to PartialEq, but with _ascii_ case insensitive equality
pub trait AsciiCaseInsensitiveEq<Rhs: ?Sized> {

    /// compares this instance with other with a ascii case insensitive comparsion algorithm
    ///
    /// Note that this is _ascii_ case insensitivity. Which means this will not work
    /// well/as expected if the content contain non ascii characters.
    /// E.g. the upercase of `"ß"` was `"SS"` but by know there is also a
    /// "ẞ" used in all caps writing.
    fn eq_ignore_ascii_case(&self, other: &Rhs) -> bool;
}

/// A iterator over chars of the content represented by the quoted strings (PartialEq<&str>)
///
/// It will on the fly (without extra allocation)
/// remove the surrounding quotes and unquote quoted-pairs
///
/// It implements Eq, and PartialEq with str, &str and itself. This
/// enables to compare a quoted string with a string representing the
/// content of a quoted string.
///
/// # Example
///
/// ```
/// # use quoted_string::ContentChars;
/// use quoted_string::AsciiCaseInsensitiveEq;
///
/// let quoted_string = r#""ab\"\ c""#;
/// let cc = ContentChars::from_string_unchecked(quoted_string);
/// assert_eq!(cc, "ab\" c");
/// assert!(cc.eq_ignore_ascii_case("AB\" c"));
/// assert_eq!(cc.collect::<Vec<_>>().as_slice(), &[ 'a', 'b', '"', ' ', 'c' ] );
///
/// ```
#[derive(Debug, Clone)]
pub struct ContentChars<'a> {
    inner: Chars<'a>
}

impl<'s> ContentChars<'s> {

    /// Crates a `ContentChars` iterator from a &str slice,
    /// assuming it represents a valid quoted-string
    ///
    /// It can be used on both with a complete quoted
    /// string and one from which the surrounding double
    /// quotes where stripped.
    ///
    /// This function relies on quoted to be valid, if it isn't
    /// it will not panic, but might not yield the expected result
    /// as there is no clear way how to handle invalid input.
    pub fn from_string_unchecked(quoted: &'s str) -> Self {
        let inner =
            if quoted.chars().next().map(|ch| ch == '"').unwrap_or(false) {
                // do not panic on invalid input "\"" is seen as "\"\""
                quoted[1..max(1, quoted.len()-1)].chars()
            } else {
                quoted.chars()
            };

        ContentChars{ inner }
    }
}


impl<'a> Iterator for ContentChars<'a> {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
            .map(|ch| {
                if ch == '\\' {
                    // do not panic on invalid input "\"\\\"" is seen as "\"\\\\\""
                    self.inner.next().unwrap_or('\\')
                } else {
                    ch
                }
            })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}


impl<'a> PartialEq<str> for ContentChars<'a> {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        iter_eq(self.clone(), other.chars())
    }
}

impl<'a, 'b> PartialEq<ContentChars<'b>> for &'a str {
    #[inline]
    fn eq(&self, other: &ContentChars<'b>) -> bool {
        iter_eq(self.chars(), other.clone())
    }
}

impl<'a, 'b> PartialEq<&'b str> for ContentChars<'a> {
    #[inline]
    fn eq(&self, other: &&'b str) -> bool {
        iter_eq(self.clone(), other.chars())
    }
}

impl<'a, 'b> PartialEq<ContentChars<'b>> for ContentChars<'a> {
    #[inline]
    fn eq(&self, other: &ContentChars<'b>) -> bool {
        iter_eq(self.clone(), other.clone())
    }
}

impl<'a> Eq for ContentChars<'a> {}



impl<'a> AsciiCaseInsensitiveEq<str> for ContentChars<'a> {
    #[inline]
    fn eq_ignore_ascii_case(&self, other: &str) -> bool {
        iter_eq_ascii_case_insensitive(self.clone(), other.chars())
    }
}

impl<'a, 'b> AsciiCaseInsensitiveEq<ContentChars<'b>> for ContentChars<'a> {
    #[inline]
    fn eq_ignore_ascii_case(&self, other: &ContentChars<'b>) -> bool {
        iter_eq_ascii_case_insensitive(self.clone(), other.clone())
    }
}

impl<'a, 'b> AsciiCaseInsensitiveEq<ContentChars<'b>> for &'a str {
    #[inline]
    fn eq_ignore_ascii_case(&self, other: &ContentChars<'b>) -> bool {
        iter_eq_ascii_case_insensitive(self.chars(), other.clone())
    }
}



impl<'a, 'b> AsciiCaseInsensitiveEq<&'b str> for ContentChars<'a>  {
    #[inline]
    fn eq_ignore_ascii_case(&self, other: &&'b str) -> bool {
        iter_eq_ascii_case_insensitive(self.clone(), other.chars())
    }
}

fn iter_eq<I1, I2>(mut left: I1, mut right: I2) -> bool
    where I1: Iterator<Item=char>,
          I2: Iterator<Item=char>
{
    loop {
        match (left.next(), right.next()) {
            (None, None) => break,
            (Some(x), Some(y)) if x == y => (),
            _ => return false
        }
    }
    true
}

fn iter_eq_ascii_case_insensitive<I1, I2>(mut left: I1, mut right: I2) -> bool
    where I1: Iterator<Item=char>,
          I2: Iterator<Item=char>
{
    loop {
        match (left.next(), right.next()) {
            (None, None) => break,
            (Some(x), Some(y)) if x.eq_ignore_ascii_case(&y) => (),
            _ => return false
        }
    }
    true
}

#[cfg(test)]
mod test {
    use super::{ContentChars, AsciiCaseInsensitiveEq};

    #[test]
    fn no_quotation() {
        let res = ContentChars::from_string_unchecked("abcdef");
        assert_eq!(res.collect::<Vec<_>>().as_slice(), &[
            'a', 'b', 'c' ,'d', 'e', 'f'
        ])
    }

    #[test]
    fn unnecessary_quoted() {
        let res = ContentChars::from_string_unchecked("\"abcdef\"");
        assert_eq!(res.collect::<Vec<_>>().as_slice(), &[
            'a', 'b', 'c' ,'d', 'e', 'f'
        ])
    }

    #[test]
    fn quoted() {
        let res = ContentChars::from_string_unchecked("\"abc def\"");
        assert_eq!(res.collect::<Vec<_>>().as_slice(), &[
            'a', 'b', 'c', ' ', 'd', 'e', 'f'
        ])
    }

    #[test]
    fn with_quoted_pair() {
        let res = ContentChars::from_string_unchecked(r#""abc\" \def""#);
        assert_eq!(res.collect::<Vec<_>>().as_slice(), &[
            'a', 'b', 'c', '"', ' ', 'd', 'e', 'f'
        ])
    }

    #[test]
    fn missing_double_quoted() {
        let res = ContentChars::from_string_unchecked(r#"abc\" \def"#);
        assert_eq!(res.collect::<Vec<_>>().as_slice(), &[
            'a', 'b', 'c', '"', ' ', 'd', 'e', 'f'
        ])
    }

    #[test]
    fn ascii_case_insensitive_eq() {
        let left = ContentChars::from_string_unchecked(r#""abc""#);
        let right = ContentChars::from_string_unchecked(r#""aBc""#);
        assert!(left.eq_ignore_ascii_case(&right))
    }
}