helpers.rs

 1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
 2//
 3// This Source Code Form is subject to the terms of the Mozilla Public
 4// License, v. 2.0. If a copy of the MPL was not distributed with this
 5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
 6
 7use crate::error::Error;
 8use base64;
 9
10/// Codec for plain text content.
11pub struct PlainText;
12
13impl PlainText {
14    pub fn decode(s: &str) -> Result<Option<String>, Error> {
15        Ok(match s {
16            "" => None,
17            text => Some(text.to_owned()),
18        })
19    }
20
21    pub fn encode(string: &Option<String>) -> Option<String> {
22        string.as_ref().map(|text| text.to_owned())
23    }
24}
25
26/// Codec for trimmed plain text content.
27pub struct TrimmedPlainText;
28
29impl TrimmedPlainText {
30    pub fn decode(s: &str) -> Result<String, Error> {
31        Ok(match s.trim() {
32            "" => return Err(Error::ParseError("URI missing in uri.")),
33            text => text.to_owned(),
34        })
35    }
36
37    pub fn encode(string: &String) -> String {
38        string.to_owned()
39    }
40}
41
42/// Codec wrapping base64 encode/decode
43pub struct Base64;
44
45impl Base64 {
46    pub fn decode(s: &str) -> Result<Vec<u8>, Error> {
47        Ok(base64::decode(s)?)
48    }
49
50    pub fn encode(b: &Vec<u8>) -> Option<String> {
51        Some(base64::encode(b))
52    }
53}