aboutsummaryrefslogtreecommitdiff
path: root/src/api/encoding.rs
blob: 63c5dee2fd69a0c7d9bc759088e6ede5135397f8 (plain) (blame)
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
//! Module containing various helpers for encoding

/// Escape &str for xml inclusion
pub fn xml_escape(s: &str) -> String {
	s.replace("<", "&lt;")
		.replace(">", "&gt;")
		.replace("\"", "&quot;")
}

/// Encode &str for use in a URI
pub fn uri_encode(string: &str, encode_slash: bool) -> String {
	let mut result = String::with_capacity(string.len() * 2);
	for c in string.chars() {
		match c {
			'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '-' | '~' | '.' => result.push(c),
			'/' if encode_slash => result.push_str("%2F"),
			'/' if !encode_slash => result.push('/'),
			_ => {
				result.push_str(
					&format!("{}", c)
						.bytes()
						.map(|b| format!("%{:02X}", b))
						.collect::<String>(),
				);
			}
		}
	}
	result
}

/// Encode &str either as an uri, or a valid string for xml inclusion
pub fn xml_encode_key(k: &str, urlencode: bool) -> String {
	if urlencode {
		uri_encode(k, true)
	} else {
		xml_escape(k)
	}
}