summaryrefslogtreecommitdiffstats
path: root/src/helpers/toml.rs
blob: 5b562bfa99b019406255616469804c259c5b3dd9 (plain)
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
use std::{
    fs::{File, OpenOptions},
    io::{BufWriter, Read, Write},
    path::Path,
};

use crate::{data::Data, Result};

/// Attempts to deserialize a Data struct from a string
pub fn from_str(s: &str) -> Result<Data> {
    Ok(toml::from_str(s)?)
}

/// Attempts to deserialize a Data struct from a slice of bytes
pub fn from_slice(s: &[u8]) -> Result<Data> {
    Ok(toml::from_slice(s)?)
}

/// Attempts to deserialize a Data struct from something that implements
/// the std::io::Read trait
pub fn from_reader<R: Read>(mut r: R) -> Result<Data> {
    let mut buffer = Vec::new();
    r.read_to_end(&mut buffer)?;
    from_slice(&buffer)
}

/// Attempts to deserialize a Data struct from a file
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Data> {
    let path = path.as_ref();
    let file = File::open(path)?;
    Ok(from_reader(file)?)
}

/// Attempts to serialize a Data struct to a String
pub fn to_string(data: &Data) -> Result<String> {
    Ok(toml::to_string_pretty(data)?)
}

/// Attempts to serialize a Data struct to a Vec of bytes
pub fn to_vec(data: &Data) -> Result<Vec<u8>> {
    Ok(toml::to_vec(data)?)
}

/// Attempts to serialize a Data struct to something that implements the
/// std::io::Write trait
pub fn to_writer<W: Write>(data: &Data, writer: W) -> Result<()> {
    let mut buf_writer = BufWriter::new(writer);
    let vec = to_vec(data)?;
    buf_writer.write(&vec)?;
    Ok(())
}

/// Attempts to serialize a Data struct to a file
///
/// When opening the file, this will set the `.write(true)` and
/// `.truncate(true)` options, use the next method for more
/// fine-grained control
pub fn to_file<P: AsRef<Path>>(data: &Data, path: P) -> Result<()> {
    let mut options = OpenOptions::new();
    options.create(true).write(true).truncate(true);
    to_file_with_options(data, path, options)?;
    Ok(())
}

/// Attempts to serialize a Data struct to a file
pub fn to_file_with_options<P: AsRef<Path>>(
    data: &Data,
    path: P,
    options: OpenOptions,
) -> Result<()> {
    let path = path.as_ref();
    let file = options.open(path)?;
    to_writer(data, file)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{fs::OpenOptions, io::Cursor};
    use tempfile::{tempdir, NamedTempFile};

    const DOC: &'static str = indoc::indoc!(
        r#"
            base = "https://example.com"
            client_id = "adbc01234"
            client_secret = "0987dcba"
            redirect = "urn:ietf:wg:oauth:2.0:oob"
            token = "fedc5678"
    "#
    );

    #[test]
    fn test_from_str() {
        let desered = from_str(DOC).expect("Couldn't deserialize Data");
        assert_eq!(
            desered,
            Data {
                base: "https://example.com".into(),
                client_id: "adbc01234".into(),
                client_secret: "0987dcba".into(),
                redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
                token: "fedc5678".into(),
            }
        );
    }
    #[test]
    fn test_from_slice() {
        let doc = DOC.as_bytes();
        let desered = from_slice(&doc).expect("Couldn't deserialize Data");
        assert_eq!(
            desered,
            Data {
                base: "https://example.com".into(),
                client_id: "adbc01234".into(),
                client_secret: "0987dcba".into(),
                redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
                token: "fedc5678".into(),
            }
        );
    }
    #[test]
    fn test_from_reader() {
        let doc = DOC.as_bytes();
        let doc = Cursor::new(doc);
        let desered = from_reader(doc).expect("Couldn't deserialize Data");
        assert_eq!(
            desered,
            Data {
                base: "https://example.com".into(),
                client_id: "adbc01234".into(),
                client_secret: "0987dcba".into(),
                redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
                token: "fedc5678".into(),
            }
        );
    }
    #[test]
    fn test_from_file() {
        let mut datafile = NamedTempFile::new().expect("Couldn't create tempfile");
        write!(&mut datafile, "{}", DOC).expect("Couldn't write Data to file");
        let desered = from_file(datafile.path()).expect("Couldn't deserialize Data");
        assert_eq!(
            desered,
            Data {
                base: "https://example.com".into(),
                client_id: "adbc01234".into(),
                client_secret: "0987dcba".into(),
                redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
                token: "fedc5678".into(),
            }
        );
    }
    #[test]
    fn test_to_string() {
        let data = Data {
            base: "https://example.com".into(),
            client_id: "adbc01234".into(),
            client_secret: "0987dcba".into(),
            redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
            token: "fedc5678".into(),
        };
        let s = to_string(&data).expect("Couldn't serialize Data");
        let desered = from_str(&s).expect("Couldn't deserialize Data");
        assert_eq!(data, desered);
    }
    #[test]
    fn test_to_vec() {
        let data = Data {
            base: "https://example.com".into(),
            client_id: "adbc01234".into(),
            client_secret: "0987dcba".into(),
            redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
            token: "fedc5678".into(),
        };
        let v = to_vec(&data).expect("Couldn't write to vec");
        let desered = from_slice(&v).expect("Couldn't deserialize data");
        assert_eq!(data, desered);
    }
    #[test]
    fn test_to_writer() {
        let data = Data {
            base: "https://example.com".into(),
            client_id: "adbc01234".into(),
            client_secret: "0987dcba".into(),
            redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
            token: "fedc5678".into(),
        };
        let mut buffer = Vec::new();
        to_writer(&data, &mut buffer).expect("Couldn't write to writer");
        let reader = Cursor::new(buffer);
        let desered = from_reader(reader).expect("Couldn't deserialize Data");
        assert_eq!(data, desered);
    }
    #[test]
    fn test_to_file() {
        let data = Data {
            base: "https://example.com".into(),
            client_id: "adbc01234".into(),
            client_secret: "0987dcba".into(),
            redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
            token: "fedc5678".into(),
        };
        let tempdir = tempdir().expect("Couldn't create tempdir");
        let filename = tempdir.path().join("mastodon-data.toml");
        to_file(&data, &filename).expect("Couldn't write to file");
        let desered = from_file(&filename).expect("Couldn't deserialize Data");
        assert_eq!(data, desered);
    }
    #[test]
    fn test_to_file_with_options() {
        let data = Data {
            base: "https://example.com".into(),
            client_id: "adbc01234".into(),
            client_secret: "0987dcba".into(),
            redirect: "urn:ietf:wg:oauth:2.0:oob".into(),
            token: "fedc5678".into(),
        };
        let file = NamedTempFile::new().expect("Couldn't create tempfile");
        let mut options = OpenOptions::new();
        options.write(true).create(false).truncate(true);
        to_file_with_options(&data, file.path(), options).expect("Couldn't write to file");
        let desered = from_file(file.path()).expect("Couldn't deserialize Data");
        assert_eq!(data, desered);
    }
}