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::util::error::Error;
8
9/// Codec for plain text content.
10pub struct PlainText;
11
12impl PlainText {
13 pub fn decode(s: &str) -> Result<Option<String>, Error> {
14 Ok(match s {
15 "" => None,
16 text => Some(text.to_owned()),
17 })
18 }
19
20 pub fn encode(string: &Option<String>) -> Option<String> {
21 string.as_ref().map(ToOwned::to_owned)
22 }
23}
24
25/// Codec for trimmed plain text content.
26pub struct TrimmedPlainText;
27
28impl TrimmedPlainText {
29 pub fn decode(s: &str) -> Result<String, Error> {
30 Ok(match s.trim() {
31 "" => return Err(Error::ParseError("URI missing in uri.")),
32 text => text.to_owned(),
33 })
34 }
35
36 pub fn encode(string: &str) -> Option<String> {
37 Some(string.to_owned())
38 }
39}
40
41/// Codec wrapping base64 encode/decode.
42pub struct Base64;
43
44impl Base64 {
45 pub fn decode(s: &str) -> Result<Vec<u8>, Error> {
46 Ok(base64::decode(s)?)
47 }
48
49 pub fn encode(b: &[u8]) -> Option<String> {
50 Some(base64::encode(b))
51 }
52}
53
54/// Codec wrapping base64 encode/decode, while ignoring whitespace characters.
55pub struct WhitespaceAwareBase64;
56
57impl WhitespaceAwareBase64 {
58 pub fn decode(s: &str) -> Result<Vec<u8>, Error> {
59 let s: String = s.chars().filter(|ch| *ch != ' ' && *ch != '\n' && *ch != '\t').collect();
60 Ok(base64::decode(&s)?)
61 }
62
63 pub fn encode(b: &[u8]) -> Option<String> {
64 Some(base64::encode(b))
65 }
66}
67
68/// Codec for colon-separated bytes of uppercase hexadecimal.
69pub struct ColonSeparatedHex;
70
71impl ColonSeparatedHex {
72 pub fn decode(s: &str) -> Result<Vec<u8>, Error> {
73 let mut bytes = vec![];
74 for i in 0..(1 + s.len()) / 3 {
75 let byte = u8::from_str_radix(&s[3 * i..3 * i + 2], 16)?;
76 if 3 * i + 2 < s.len() {
77 assert_eq!(&s[3 * i + 2..3 * i + 3], ":");
78 }
79 bytes.push(byte);
80 }
81 Ok(bytes)
82 }
83
84 pub fn encode(b: &[u8]) -> Option<String> {
85 let mut bytes = vec![];
86 for byte in b {
87 bytes.push(format!("{:02X}", byte));
88 }
89 Some(bytes.join(":"))
90 }
91}