about summary refs log tree commit diff
path: root/markup/src/intra.rs
blob: e936e399c2d4ae5bcc5c35c466cb36d67d3541b9 (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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use core::range;
use std::fmt::Display;
use std::ops::RangeInclusive;

macro_rules! false_or_continue {
	($action:expr) => {
		if $action {
			continue;
		}
	};
}

pub fn process(raw: String) -> String {
	let mut chars = raw.chars();
	let mut ctx = Context::default();

	loop {
		let nch = match chars.next() {
			None => break,
			Some(ch) => ch,
		};

		false_or_continue!(escaped_char(&mut ctx, nch));

		match nch {
			'`' => ctx.toggle_code(),
			'*' => ctx.toggle_italics(),
			ch => ctx.push_char(ch),
		}
	}

	let out = ctx.done();
	let length = out.iter().fold(0, |acc, cs| acc + cs.len());
	let mut string = String::with_capacity(length);
	out.iter().for_each(|cs| string.push_str(&cs.to_string()));

	string
}

#[inline]
fn escaped_char(ctx: &mut Context, ch: char) -> bool {
	let escaped_chars = ['`', '*', '\\'];

	if ctx.escape_next {
		ctx.escape_next = false;

		if escaped_chars.contains(&ch) {
			ctx.push_char(ch);
			true
		} else {
			false
		}
	} else if ch == '\\' {
		ctx.escape_next = true;
		true
	} else {
		false
	}
}

struct ContextualizedString {
	state: State,
	text: String,
}

impl ContextualizedString {
	pub fn len(&self) -> usize {
		self.state.open().len() + self.text.len() + self.state.close().len()
	}
}

#[derive(Copy, Clone, Debug, PartialEq)]
struct State {
	code: bool,
	italics: bool,
	bold: bool,
}

struct Context {
	escape_next: bool,
	bold_flag: bool,

	text_state: State,
	current: String,

	output: Vec<ContextualizedString>,
}

impl Context {
	pub fn push_char(&mut self, ch: char) {
		if self.bold_flag {
			// Attemping to push with the bold flag set,
			// pop_current as italic, clear the italic flag,
			// and then push
			self.pop_current();
			self.text_state.italics = false;
		}

		self.current.push(ch);
	}

	pub fn toggle_code(&mut self) {
		self.pop_current();
		self.text_state.code = !self.text_state.code;
	}

	pub fn toggle_italics(&mut self) {
		if self.text_state.bold {
			if self.bold_flag {
				// We're bold and the flag is set! pop_current and disable bolding
				self.pop_current();
				self.text_state.bold = false;
				self.bold_flag = false;

				return;
			} else {
				// bold and flag not set, set flag and return
				self.bold_flag = true;
				return;
			}
		} else {
			if self.text_state.italics && self.current.is_empty() {
				// we're already italisized and nothing is in current,
				// this is a "**", a bold
				self.text_state.italics = false;
				self.text_state.bold = true;
				return;
			} else {
				// Passed all bold checks, pop_current() and set the italic flag
				self.pop_current();
				self.text_state.italics = !self.text_state.italics;
			}
		}
	}

	pub fn done(mut self) -> Vec<ContextualizedString> {
		self.pop_current();
		self.output
	}

	fn pop_current(&mut self) {
		if !self.current.is_empty() {
			let cs = ContextualizedString {
				state: self.text_state,
				text: self.take_current(),
			};

			self.output.push(cs);
		}
	}

	fn take_current(&mut self) -> String {
		self.current.split_off(0)
	}
}

macro_rules! mask_match_unreachable {
	() => {
		State::MASK_MAX_PP..=u8::MAX
	};
}

impl State {
	const MASK_MAX: u8 = 7;
	const MASK_MAX_PP: u8 = State::MASK_MAX + 1;

	pub fn mask(&self) -> u8 {
		// code 1, italics 2, bold 4
		self.code as u8 | ((self.italics as u8) << 1) | ((self.bold as u8) << 2)
	}

	pub fn open(&self) -> &'static str {
		match self.mask() {
			// Nothing
			0 => "",

			// Single
			1 => "<code>",
			2 => "<i>",
			4 => "<b>",

			// Double
			3 => "<i><code>",
			5 => "<b><code>",
			6 => "<b><i>",

			// Triple
			7 => "<b><i><code>",

			mask_match_unreachable!() => unreachable!(),
		}
	}

	pub fn close(&self) -> &'static str {
		match self.mask() {
			// Nothing
			0 => "",

			// Single
			1 => "</code>",
			2 => "</i>",
			4 => "</b>",

			// Double
			3 => "</code></i>",
			5 => "<code></b>",
			6 => "</i></b>",

			// Triple
			7 => "</code></i></b>",

			mask_match_unreachable!() => unreachable!(),
		}
	}
}

impl Display for ContextualizedString {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(
			f,
			"{}{}{}",
			self.state.open(),
			self.text,
			self.state.close()
		)
	}
}

// MARK: defaults

impl Default for Context {
	fn default() -> Self {
		Self {
			escape_next: false,
			bold_flag: false,

			text_state: State::default(),
			current: String::with_capacity(128),

			output: vec![],
		}
	}
}

impl Default for State {
	fn default() -> Self {
		Self {
			code: false,
			italics: false,
			bold: false,
		}
	}
}

// MARK: tests
#[cfg(test)]
mod test {
	use crate::intra::process;

	macro_rules! verify {
		($inp:literal -> $out:literal) => {{
			let actual = process($inp.to_string());
			if actual != $out {
				panic!("expected: \"{}\"\n  actual: \"{actual}\"", $out);
			}
		}};
	}

	#[test]
	fn parese_no_markup() {
		verify!("no markup" -> "no markup");
		verify!("no\nmarkup" -> "no\nmarkup")
	}

	#[test]
	fn parses_escapes() {
		verify!(r"italic \*" -> "italic *");
		verify!(r"code \`" -> "code `");
		verify!(r"escape \\" -> r"escape \");
		verify!(r"everything \\ \* \`" -> r"everything \ * `");
	}

	#[test]
	fn parses_code() {
		verify!("`struct foo{}`" -> "<code>struct foo{}</code>");
		verify!(r"`let code = '\`';`" -> "<code>let code = '`';</code>");
	}

	#[test]
	fn parses_italic() {
		verify!("*(aside)*" -> "<i>(aside)</i>");
		verify!(r"*(italics are \*)*" -> "<i>(italics are *)</i>");
		verify!("*italics**again*" -> "<i>italics</i><i>again</i>");
	}

	#[test]
	fn parses_bold() {
		verify!("**bold!**" -> "<b>bold!</b>");
		verify!("*italics***bold!**" -> "<i>italics</i><b>bold!</b>");
	}

	#[test]
	fn parses_code_italics() {
		verify!("*`italic code`*" -> "<i><code>italic code</code></i>");
		verify!("`*italic code*`" -> "<i><code>italic code</code></i>");

		verify!("`program *italics* more`"
			-> "<code>program </code>\
				<i><code>italics</code></i>\
				<code> more</code>");
	}
}