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::cmp::Ordering;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::fmt::Write;

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

use crate::share::Share;
use crate::share::Cow;
use crate::share::Redeem;
use crate::error::Error;
use crate::error::Result;
use crate::parser::FromPair;
use crate::parser::Rule;
use super::IdPrefix;
use super::IdentPrefix;
use super::IdLocal;
use super::IdentLocal;

/// An identifier with a prefix.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq)]
pub struct PrefixedIdent {
    prefix: IdentPrefix,
    local: IdentLocal,
}

impl PrefixedIdent {
    /// Create a new `PrefixedIdent` from a prefix and a local identifier.
    ///
    /// Thanks to conversion traits, the `prefix` and `local` arguments can be
    /// passed either as strings or `ast` structures:
    ///
    /// ```rust
    /// # extern crate fastobo;
    /// # use fastobo::ast::*;
    /// let id1 = PrefixedIdent::new("MS", "1000031");
    /// let id2 = PrefixedIdent::new(IdentPrefix::new("MS"), IdentLocal::new("1000031"));
    /// assert_eq!(id1, id2);
    /// ```
    ///
    /// # Example
    ///
    pub fn new<P, L>(prefix: P, local: L) -> Self
    where
        P: Into<IdentPrefix>,
        L: Into<IdentLocal>
    {
        Self {
            prefix: prefix.into(),
            local: local.into()
        }
    }

    /// Check if the prefixed identifier is canonical or not.
    ///
    /// # Example
    /// ```rust
    /// # extern crate fastobo;
    /// # use fastobo::ast::*;
    /// # use std::str::FromStr;
    /// let canonical_id = PrefixedIdent::from_str("GO:0046154").unwrap();
    /// assert!(canonical_id.is_canonical());
    ///
    /// let noncanonical_id = PrefixedIdent::from_str("PATO:something").unwrap();
    /// assert!(!noncanonical_id.is_canonical());
    pub fn is_canonical(&self) -> bool {
        self.prefix.is_canonical() && self.local.is_canonical()
    }

    // /// The prefix of the prefixed identifier.
    // pub fn prefix(&self) -> IdPrefix<'_> {
    //     self.prefix.share()
    // }
    //
    // /// The local part of the prefixed identifier.
    // pub fn local(&self) -> IdLocal<'_> {
    //     self.local.share()
    // }

    /// Get a reference to the prefix of the `PrefixedIdent`.
    pub fn prefix(&self) -> &IdentPrefix {
        &self.prefix
    }

    /// Get a mutable reference to the prefix of the `PrefixedIdent`.
    pub fn prefix_mut(&mut self) -> &mut IdentPrefix {
        &mut self.prefix
    }

    /// Get a reference to the local component of the `PrefixedIdent`.
    pub fn local(&self) -> &IdentLocal {
        &self.local
    }

    /// Get a mutable reference to the local component of the `PrefixedIdent`.
    pub fn local_mut(&mut self) -> &mut IdentLocal {
        &mut self.local
    }
}

impl Display for PrefixedIdent {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        self.share().fmt(f)
    }
}

impl<'i> FromPair<'i> for PrefixedIdent {
    const RULE: Rule = Rule::PrefixedId;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self> {
        let mut inners = pair.into_inner();
        let prefix = IdentPrefix::from_pair_unchecked(inners.next().unwrap())?;
        let local = IdentLocal::from_pair_unchecked(inners.next().unwrap())?;
        Ok(Self::new(prefix, local))
    }
}
impl_fromstr!(PrefixedIdent);

impl PartialOrd for PrefixedIdent {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match self.prefix.partial_cmp(&other.prefix) {
            None => None,
            Some(Ordering::Equal) => self.local.partial_cmp(&other.local),
            Some(ord) => Some(ord),
        }
    }
}

impl<'a> Share<'a, PrefixedId<'a>> for PrefixedIdent {
    fn share(&'a self) -> PrefixedId<'a> {
        PrefixedId::new(
            self.prefix.share(),
            self.local.share(),
        )
    }
}

/// A borrowed `PrefixedIdent`.
#[derive(Clone, Debug, Hash)]
pub struct PrefixedId<'a> {
    prefix: Cow<'a, IdPrefix<'a>>,
    local: Cow<'a, IdLocal<'a>>,
}

impl<'a> PrefixedId<'a> {
    /// Create a new `PrefixedId` from references.
    pub fn new(prefix: IdPrefix<'a>, local: IdLocal<'a>) -> Self {
        Self {
            prefix: Cow::Borrowed(prefix),
            local: Cow::Borrowed(local),
        }
    }

    /// Get a reference to the prefix of the `PrefixedId`.
    pub fn prefix(&'a self) -> IdPrefix<'a> {
        self.prefix.share()
    }

    /// Get a reference to the local component of the `PrefixedId`.
    pub fn local(&'a self) -> IdLocal<'a> {
        self.local.share()
    }
}

impl<'a> Display for PrefixedId<'a> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        self.prefix
            .fmt(f)
            .and(f.write_char(':'))
            .and(self.local.fmt(f))
    }
}

impl<'i> FromPair<'i> for Cow<'i, PrefixedId<'i>> {
    const RULE: Rule = Rule::PrefixedId;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self> {
        let mut inners = pair.into_inner();
        let prefix = Cow::<IdPrefix>::from_pair_unchecked(inners.next().unwrap())?;
        let local = Cow::<IdLocal>::from_pair_unchecked(inners.next().unwrap())?;
        Ok(Cow::Borrowed(PrefixedId { prefix, local }))
    }
}
impl_fromslice!('i, Cow<'i, PrefixedId<'i>>);

impl<'a> Redeem<'a> for PrefixedId<'a> {
    type Owned = PrefixedIdent;
    fn redeem(&'a self) -> PrefixedIdent {
        PrefixedIdent::new(self.prefix.redeem(), self.local.redeem())
    }
}

#[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 = PrefixedIdent::from_str("GO:0046154").unwrap();
        let expected = PrefixedIdent::new(IdentPrefix::new(String::from("GO")), IdentLocal::new(String::from("0046154")));
        self::assert_eq!(actual, expected);

        let actual = PrefixedIdent::from_str("PSI:MS").unwrap();
        let expected = PrefixedIdent::new(IdentPrefix::new(String::from("PSI")), IdentLocal::new(String::from("MS")));
        self::assert_eq!(actual, expected);

        let actual = PrefixedIdent::from_str("CAS:22325-47-9").unwrap();
        let expected = PrefixedIdent::new(IdentPrefix::new(String::from("CAS")), IdentLocal::new(String::from("22325-47-9")));
        self::assert_eq!(actual, expected);

        let actual = PrefixedIdent::from_str("Wikipedia:https\\://en.wikipedia.org/wiki/Gas").unwrap();
        let expected = PrefixedIdent::new(
            IdentPrefix::new(String::from("Wikipedia")),
            IdentLocal::new(String::from("https://en.wikipedia.org/wiki/Gas")),
        );
        self::assert_eq!(actual, expected);

        assert!(PrefixedIdent::from_str("[Term]").is_err());
        assert!(PrefixedIdent::from_str("").is_err());
        assert!(PrefixedIdent::from_str("Some\nthing:spanning").is_err());
        assert!(PrefixedIdent::from_str("GO:0046154 remaining").is_err());
    }

    #[test]
    fn to_string() {
        let id = PrefixedIdent::new(IdentPrefix::new(String::from("GO")), IdentLocal::new(String::from("0046154")));
        self::assert_eq!(id.to_string(), "GO:0046154")
    }
}