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
use std::borrow::Borrow;
use std::borrow::ToOwned;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::fmt::Write;
use std::ops::Deref;

use pest::iterators::Pair;
use opaque_typedef::OpaqueTypedefUnsized;

use crate::error::Error;
use crate::parser::FromPair;
use crate::parser::QuickFind;
use crate::parser::Rule;
use crate::share::Share;
use crate::share::Cow;
use crate::share::Redeem;
use super::escape;
use super::unescape;

/// A string enclosed by quotes, used for definitions.
///
/// This type is mostly just a wrapper for `String` that patches `FromStr` and
/// `Display` so that it can read and write quoted strings in OBO documents.
///
/// # Usage
/// Use `FromStr` to parse the serialized representation of a `QuotedString`,
/// and `QuotedString::new` to create a quoted string with its content set
/// from an `Into<String>` implementor.
///
/// To get the the unescaped `String`, use `QuotedString::into_string`, or
/// use `ToString::to_string` to obtained a serialized (escaped) version of
/// the quoted string.
///
/// # Example
/// ```rust
/// # extern crate fastobo;
/// # use fastobo::ast::QuotedString;
/// let s = QuotedString::new("Hello, world!");
/// assert_eq!(s.as_str(), "Hello, world!");
/// assert_eq!(s.to_string(), "\"Hello, world!\"");
/// ```
#[derive(Clone, Debug, Eq, Hash, Ord, OpaqueTypedef, PartialEq, PartialOrd)]
#[opaque_typedef(derive(AsRefInner, AsRefSelf, FromInner, IntoInner))]
pub struct QuotedString {
    value: String,
}

impl QuotedString {
    /// Create a new `QuotedString` from an unescaped string.
    pub fn new<S>(s: S) -> Self
    where
        S: Into<String>
    {
        QuotedString { value: s.into() }
    }

    /// Extracts a string slice containing the `QuotedString` value.
    pub fn as_str(&self) -> &str {
        &self.value
    }

    /// Retrieve the underlying unescaped string from the `QuotedString`.
    pub fn into_string(self) -> String {
        self.value
    }
}

impl AsRef<str> for QuotedString {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl AsRef<QuotedStr> for QuotedString {
    fn as_ref(&self) -> &QuotedStr {
        self.share()
    }
}

impl Borrow<QuotedStr> for QuotedString {
    fn borrow(&self) -> &QuotedStr {
        QuotedStr::new(self.as_ref())
    }
}

impl Deref for QuotedString {
    type Target = QuotedStr;
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl Display for QuotedString {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        let s: &QuotedStr = self.borrow();
        s.fmt(f)
    }
}

impl From<&str> for QuotedString {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

impl<'i> FromPair<'i> for QuotedString {
    const RULE: Rule = Rule::QuotedString;
    unsafe fn from_pair_unchecked(pair: Pair<Rule>) -> Result<Self, Error> {
        let s = pair.as_str();
        let escaped = s.quickcount(b'\\');
        let mut local = String::with_capacity(s.len() + escaped);
        unescape(&mut local, s.get_unchecked(1..s.len() - 1))
            .expect("String as fmt::Write cannot fail");
        Ok(QuotedString::new(local))
    }
}
impl_fromstr!(QuotedString);

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

impl PartialEq<String> for QuotedString {
    fn eq(&self, other: &String) -> bool {
        self.value == other.as_str()
    }
}

impl<'a> Share<'a, &'a QuotedStr> for QuotedString {
    fn share(&'a self) -> &'a QuotedStr {
        QuotedStr::new(&self.value)
    }
}

/// A borrowed `QuotedString`.
#[derive(Debug, Eq, Hash, OpaqueTypedefUnsized, Ord, PartialEq, PartialOrd)]
#[opaque_typedef(derive(Deref, AsRef(Inner, Self)))]
#[repr(transparent)]
pub struct QuotedStr(str);

impl QuotedStr {
    /// Create a new `QuotedStr`.
    pub fn new(s: &str) -> &Self {
        // Using `unchecked` because there is no validation needed.
        unsafe { QuotedStr::from_inner_unchecked(s) }
    }
}

impl<'a> Display for QuotedStr {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.write_char('"')
            .and(escape(f, &self.0))
            .and(f.write_char('"'))
    }
}

impl<'i> FromPair<'i> for Cow<'i, &'i QuotedStr> {
    const RULE: Rule = Rule::QuotedString;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self, Error> {
        if pair.as_str().quickfind(b'\\').is_some() {
            QuotedString::from_pair_unchecked(pair).map(Cow::Owned)
        } else {
            Ok(Cow::Borrowed(QuotedStr::new(pair.as_str())))
        }
    }
}
impl_fromslice!('i, Cow<'i, &'i QuotedStr>);

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

impl PartialEq<String> for QuotedStr {
    fn eq(&self, other: &String) -> bool {
        &self.0 == other.as_str()
    }
}

impl<'a> Redeem<'a> for &'a QuotedStr {
    type Owned = QuotedString;
    fn redeem(&self) -> QuotedString {
        QuotedString::new(self.0.to_owned())
    }
}

impl ToOwned for QuotedStr {
    type Owned = QuotedString;
    fn to_owned(&self) -> QuotedString {
        QuotedString::new(self.0.to_owned())
    }
}

#[cfg(test)]
mod tests {

    use std::str::FromStr;
    use std::string::ToString;
    use pretty_assertions::assert_eq;
    use super::*;

    #[test]
    fn from_str() {
        let actual = QuotedString::from_str("\"something in quotes\"");
        let expected = QuotedString::new(String::from("something in quotes"));
        assert_eq!(expected, actual.unwrap());

        let actual = QuotedString::from_str("\"something in \\\"escaped\\\" quotes\"");
        let expected = QuotedString::new(String::from("something in \"escaped\" quotes"));
        assert_eq!(expected, actual.unwrap());
    }
}