about summary refs log tree commit diff
path: root/wikarden/src/lib.rs
blob: 6827793a48e5bc913e852080a8f213d969ab6bb7 (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
pub mod error;

pub(crate) mod fs;

mod git;
mod journal;
mod settings;
mod table;
mod wikarden;

pub use error::WikError;
pub use journal::JournalName;
pub use settings::Settings;
pub use table::SectionData;
pub use wikarden::{PathType, Source, Wikarden};

use crate::fs::{Open, WikFile, WikPath};

pub(crate) fn quotes_encode(raw: &str) -> String {
	let mut ret = String::with_capacity(raw.len() + 4);
	ret.push('"');

	for ch in raw.chars() {
		match ch {
			'"' => {
				ret.push('\\');
				ret.push('"');
			}
			'\\' => {
				ret.push('\\');
				ret.push('\\');
			}
			ch => ret.push(ch),
		}
	}

	ret.push('"');
	ret
}

pub(crate) fn quotes_decode(raw: &str) -> Option<(String, &str)> {
	let raw = match raw.chars().next() {
		Some('"') => &raw[1..],
		_ => return None,
	};

	let mut ret = String::with_capacity(raw.len() / 2);
	let mut escaping = false;
	for (idx, ch) in raw.chars().enumerate() {
		match ch {
			'\\' if !escaping => escaping = true,
			'\\' if escaping => {
				ret.push('\\');
				escaping = false;
			}
			'"' if !escaping => return Some((ret, &raw[idx + 1..])),
			'"' if escaping => {
				ret.push('"');
				escaping = false;
			}
			ch if !escaping => ret.push(ch),
			ch if escaping => {
				ret.push('\\');
				ret.push(ch);
				escaping = false;
			}
			_ => unreachable!(),
		}
	}

	None
}

#[cfg(test)]
mod test {
	#[test]
	pub fn test_quotes_encode() {
		macro_rules! enc {
			($encode:literal -> $expected:literal) => {
				let actual = crate::quotes_encode($encode);
				if actual != $expected {
					panic!(
						"quotes_encode failed!\nexpected: '{}'\n  actual: '{}'",
						$expected, actual
					);
				}
			};
		}

		enc!("encode" -> r#""encode""#);
		enc!("encode\\" -> r#""encode\\""#);
		enc!("encode \"" -> r#""encode \"""#);
	}

	#[test]
	pub fn test_quotes_decode() {
		macro_rules! dec {
			($encode:literal -> $expected:expr) => {
				let actual = crate::quotes_decode($encode).unwrap();
				if actual != $expected {
					panic!(
						"quotes_encode failed!\nexpected: '{:?}'\n  actual: '{:?}'",
						$expected, actual
					);
				}
			};
		}

		dec!(r#""decode""# -> (String::from("decode"), ""));
		dec!(r#""escape \\""# -> (String::from("escape \\"), ""));
		dec!(r#""quote \"""# -> (String::from("quote \""), ""));
		dec!(r#""more after" some"# -> (String::from("more after"), " some"));
	}
}