1use std::sync::atomic::{AtomicBool, Ordering};
5
6use crate::style::Color;
7
8#[derive(Clone, Debug, Default, PartialEq)]
12pub struct Span {
13 pub text: String,
15 pub bold: bool,
17 pub italic: bool,
19 pub underline: bool,
21 pub strikethrough: bool,
23 pub color: Option<Color>,
25 pub link: Option<String>,
28}
29
30impl Span {
31 pub fn new(text: impl Into<String>) -> Span {
33 Span {
34 text: text.into(),
35 ..Span::default()
36 }
37 }
38
39 pub fn bold(mut self) -> Span {
41 self.bold = true;
42 self
43 }
44
45 pub fn italic(mut self) -> Span {
47 self.italic = true;
48 self
49 }
50
51 pub fn underline(mut self) -> Span {
53 self.underline = true;
54 self
55 }
56
57 pub fn strikethrough(mut self) -> Span {
59 self.strikethrough = true;
60 self
61 }
62
63 pub fn color(mut self, color: Color) -> Span {
65 self.color = Some(color);
66 self
67 }
68
69 pub fn link(mut self, url: impl Into<String>) -> Span {
71 self.link = Some(url.into());
72 self
73 }
74}
75
76pub const MARKUP_CAP: usize = 64 * 1024;
78
79pub fn parse_markup(body: &str) -> Vec<Span> {
93 static CUT_LOGGED: AtomicBool = AtomicBool::new(false);
94 let mut body = body;
95 if body.len() > MARKUP_CAP {
96 let mut end = MARKUP_CAP;
97 while !body.is_char_boundary(end) {
98 end -= 1;
99 }
100 if !CUT_LOGGED.swap(true, Ordering::Relaxed) {
101 tracing::warn!(
102 bytes = body.len(),
103 "a markup body is over 64 KiB, so only its first 64 KiB are shown"
104 );
105 }
106 body = &body[..end];
107 }
108 let mut out = Markup::default();
109 let mut rest = body;
110 while let Some(at) = rest.find(['<', '&']) {
111 out.text(&rest[..at]);
112 rest = &rest[at..];
113 let used = if rest.starts_with('&') {
114 entity(rest).map(|(ch, len)| {
115 out.push(ch.encode_utf8(&mut [0; 4]));
116 len
117 })
118 } else {
119 tag(rest).map(|(tag, len)| {
120 out.tag(tag);
121 len
122 })
123 };
124 let used = used.unwrap_or_else(|| {
126 out.push(&rest[..1]);
127 1
128 });
129 rest = &rest[used..];
130 }
131 out.text(rest);
132 out.spans
133}
134
135#[derive(Default)]
139struct Markup {
140 spans: Vec<Span>,
141 open: Vec<usize>,
143 at: [Vec<usize>; 4],
145 links: Vec<(usize, Option<String>)>,
147 opened: usize,
149 last: Option<(bool, bool, bool, Option<usize>)>,
152}
153
154const B: usize = 0;
155const I: usize = 1;
156const U: usize = 2;
157const A: usize = 3;
158
159impl Markup {
160 fn text(&mut self, text: &str) {
162 if !text.is_empty() {
163 self.push(text);
164 }
165 }
166
167 fn push(&mut self, text: &str) {
170 let open = |kind: usize| !self.at[kind].is_empty();
171 let (number, link) = match self.links.last() {
172 Some((number, Some(link))) => (Some(*number), Some(link)),
173 _ => (None, None),
174 };
175 let style = (open(B), open(I), open(U) || link.is_some(), number);
176 let same = match (self.last, self.spans.last()) {
177 (Some(last), _) if last == style => true,
178 (Some((bold, italic, underline, _)), Some(span)) => {
180 (bold, italic, underline) == (style.0, style.1, style.2) && span.link.as_ref() == link
181 }
182 _ => false,
183 };
184 if let (true, Some(last)) = (same, self.spans.last_mut()) {
185 last.text.push_str(text);
186 } else {
187 self.spans.push(Span {
188 text: text.to_owned(),
189 bold: style.0,
190 italic: style.1,
191 underline: style.2,
192 strikethrough: false,
193 color: None,
194 link: link.cloned(),
195 });
196 }
197 self.last = Some(style);
198 }
199
200 fn tag(&mut self, tag: Tag) {
201 match tag {
202 Tag::Open(kind, link) => {
203 self.at[kind].push(self.open.len());
204 self.open.push(kind);
205 if kind == A {
206 self.links.push((self.opened, link));
207 self.opened += 1;
208 }
209 }
210 Tag::Close(kind) => {
212 let Some(&from) = self.at[kind].last() else {
213 return;
214 };
215 while self.open.len() > from {
216 let closed = self.open.pop().expect("open holds the tag closed");
217 self.at[closed].pop();
218 if closed == A {
219 self.links.pop();
220 }
221 }
222 }
223 Tag::Image(alt) => self.text(&alt),
224 Tag::Unknown => {}
225 }
226 }
227}
228
229enum Tag {
230 Open(usize, Option<String>),
232 Close(usize),
233 Image(String),
234 Unknown,
235}
236
237fn tag(text: &str) -> Option<(Tag, usize)> {
240 let bytes = text.as_bytes();
241 let mut at = 1;
242 let close = bytes.get(at) == Some(&b'/');
243 if close {
244 at += 1;
245 }
246 let name_start = at;
247 if !bytes.get(at)?.is_ascii_alphabetic() {
248 return None;
249 }
250 while bytes.get(at).is_some_and(u8::is_ascii_alphanumeric) {
251 at += 1;
252 }
253 let name = text[name_start..at].to_ascii_lowercase();
254 let mut attributes = Vec::new();
255 let mut empty = false;
256 loop {
257 while bytes.get(at).is_some_and(u8::is_ascii_whitespace) {
258 at += 1;
259 }
260 match bytes.get(at)? {
261 b'>' => {
262 at += 1;
263 break;
264 }
265 b'/' if bytes.get(at + 1) == Some(&b'>') => {
266 at += 2;
267 empty = true;
268 break;
269 }
270 _ if !bytes[at - 1].is_ascii_whitespace() => return None,
272 _ => {
273 let (attribute, len) = attribute(&text[at..])?;
274 attributes.push(attribute);
275 at += len;
276 }
277 }
278 }
279 let value = |key: &str| {
280 attributes
281 .iter()
282 .find(|(name, _)| name.eq_ignore_ascii_case(key))
283 .map(|(_, value)| value.clone())
284 };
285 let tag = match (close, name.as_str()) {
286 (false, "img") => Tag::Image(value("alt").unwrap_or_default()),
287 _ if empty => Tag::Unknown,
289 (false, "a") => Tag::Open(A, value("href").filter(|href| safe_link(href))),
290 (false, "b") => Tag::Open(B, None),
291 (false, "i") => Tag::Open(I, None),
292 (false, "u") => Tag::Open(U, None),
293 (true, "a") => Tag::Close(A),
294 (true, "b") => Tag::Close(B),
295 (true, "i") => Tag::Close(I),
296 (true, "u") => Tag::Close(U),
297 _ => Tag::Unknown,
298 };
299 Some((tag, at))
300}
301
302fn attribute(text: &str) -> Option<((String, String), usize)> {
306 let name_len = text
307 .find(|ch: char| ch.is_ascii_whitespace() || matches!(ch, '=' | '>' | '/' | '<' | '"' | '\''))
308 .unwrap_or(text.len());
309 if name_len == 0 {
310 return None;
311 }
312 let name = text[..name_len].to_owned();
313 let rest = &text[name_len..];
314 let Some(rest) = rest.strip_prefix('=') else {
315 return Some(((name, String::new()), name_len));
316 };
317 let (raw, len) = match rest.chars().next()? {
318 quote @ ('"' | '\'') => {
319 let end = rest[1..].find([quote, '<'])? + 1;
320 if !rest[end..].starts_with(quote) {
321 return None;
322 }
323 (&rest[1..end], end + 1)
324 }
325 _ => {
326 let end = rest
327 .find(|ch: char| ch.is_ascii_whitespace() || matches!(ch, '>' | '<' | '"' | '\''))
328 .unwrap_or(rest.len());
329 (&rest[..end], end)
330 }
331 };
332 if rest[len..].is_empty() {
333 return None;
334 }
335 Some(((name, decode(raw)), name_len + 1 + len))
336}
337
338fn decode(text: &str) -> String {
340 let mut out = String::with_capacity(text.len());
341 let mut rest = text;
342 while let Some(at) = rest.find('&') {
343 out.push_str(&rest[..at]);
344 rest = &rest[at..];
345 match entity(rest) {
346 Some((ch, len)) => {
347 out.push(ch);
348 rest = &rest[len..];
349 }
350 None => {
351 out.push('&');
352 rest = &rest[1..];
353 }
354 }
355 }
356 out.push_str(rest);
357 out
358}
359
360fn entity(text: &str) -> Option<(char, usize)> {
363 let end = text.bytes().take(12).position(|byte| byte == b';')?;
366 let ch = match &text[1..end] {
367 "amp" => '&',
368 "lt" => '<',
369 "gt" => '>',
370 "quot" => '"',
371 "apos" => '\'',
372 name => {
373 let number = name.strip_prefix('#')?;
374 let (digits, radix) = match number.strip_prefix(['x', 'X']) {
375 Some(hex) => (hex, 16),
376 None => (number, 10),
377 };
378 if !digits.chars().all(|ch| ch.is_digit(radix)) {
380 return None;
381 }
382 let code = u32::from_str_radix(digits, radix).ok()?;
383 char::from_u32(code).filter(|&ch| ch != '\0')?
385 }
386 };
387 Some((ch, end + 1))
388}
389
390fn safe_link(href: &str) -> bool {
393 ["http:", "https:", "mailto:"].iter().any(|scheme| {
394 href
395 .get(..scheme.len())
396 .is_some_and(|start| start.eq_ignore_ascii_case(scheme))
397 })
398}