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
use std;
use std::marker::PhantomData;
use uuid::Uuid;

/// `Root` contains the content of a CouchDB server's root resource.
///
/// # Summary
///
/// * `Root` has public members instead of accessor methods because there are no
///   invariants restricting the data.
///
/// * `Root` implements `Deserialize`.
///
/// # Remarks
///
/// An application may obtain a CouchDB server's root resource by sending an
/// HTTP request to GET `/`.
///
/// # Compatibility
///
/// `Root` contains a dummy private member in order to prevent applications from
/// directly constructing a `Root` instance. This allows new fields to be added
/// to `Root` in future releases without it being a breaking change.
///
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq)]
pub struct Root {
    pub couchdb: String,
    pub uuid: Uuid,
    pub vendor: Vendor,
    pub version: Version,

    #[serde(default = "PhantomData::default")]
    _private_guard: PhantomData<()>,
}

/// `Vendor` contains information about a CouchDB server vendor.
///
/// # Summary
///
/// * `Vendor` has public members instead of accessor methods because there are
///   no invariants restricting the data.
///
/// * `Vendor` implements `Deserialize`.
///
/// # Remarks
///
/// `Vendor` is normally part of a [`Root`](struct.Root.html) instance.
///
/// # Compatibility
///
/// `Vendor` contains a dummy private member in order to prevent applications
/// from directly constructing a `Vendor` instance. This allows new fields to be
/// added to `Vendor` in future releases without it being a breaking change.
///
///
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq)]
pub struct Vendor {
    pub name: String,
    pub version: Version,

    #[serde(default = "PhantomData::default")]
    _private_guard: PhantomData<()>,
}

/// `Version` is a string specifying a version.
///
/// # Summary
///
/// * `Version` thinly wraps a string but may be parsed into its major, minor,
///   and patch numbers.
///
/// * `Version` implements `Deserialize`.
///
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq)]
pub struct Version(String);

impl std::fmt::Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        f.write_str(&self.0)
    }
}

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

impl From<Version> for String {
    fn from(v: Version) -> Self {
        v.0
    }
}

impl From<String> for Version {
    fn from(s: String) -> Self {
        Version(s)
    }
}

impl<'a> From<&'a str> for Version {
    fn from(s: &'a str) -> Self {
        Version(String::from(s))
    }
}

impl Version {
    /// Tries to obtain the major, minor, and patch numbers from the version
    /// string.
    pub fn triple(&self) -> Option<(u64, u64, u64)> {

        const BASE: u32 = 10;

        let parts = self.0
            .split(|c: char| !c.is_digit(BASE))
            .map(|s| {
                u64::from_str_radix(s, BASE).map(|x| Some(x)).unwrap_or(
                    None,
                )
            })
            .take(3)
            .collect::<Vec<_>>();

        if parts.len() < 3 || parts.iter().any(|&x| x.is_none()) {
            return None;
        }

        Some((parts[0].unwrap(), parts[1].unwrap(), parts[2].unwrap()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json;
    use std::marker::PhantomData;

    #[test]
    fn version_parses_triple() {
        assert_eq!(Version::from("1.6.1").triple(), Some((1, 6, 1)));

        // E.g., the Homebrew vendor appends an extra number onto their version.
        assert_eq!(Version::from("1.6.1_1").triple(), Some((1, 6, 1)));

        assert_eq!(Version::from("obviously_bad").triple(), None);
    }

    #[test]
    fn root_deserializes_ok() {

        let source = r#"{
            "couchdb": "Welcome",
            "uuid": "0762dcce5f0d7f6f79157f852186f149",
            "version": "1.6.1",
            "vendor": {
                "name": "Homebrew",
                "version": "1.6.1_9"
            }
        }"#;

        let expected = Root {
            couchdb: String::from("Welcome"),
            uuid: Uuid::parse_str("0762dcce5f0d7f6f79157f852186f149").unwrap(),
            vendor: Vendor {
                name: String::from("Homebrew"),
                version: Version::from("1.6.1_9"),
                _private_guard: PhantomData,
            },
            version: Version::from("1.6.1"),
            _private_guard: PhantomData,
        };

        let got: Root = serde_json::from_str(source).unwrap();
        assert_eq!(got, expected);
    }
}