1use std::borrow::Cow;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
52#[expect(
53 clippy::struct_excessive_bools,
54 reason = "one switch per kind of markdown, as in discord.js"
55)]
56pub struct EscapeOptions {
57 code_block: bool,
58 inline_code: bool,
59 bold: bool,
60 italic: bool,
61 underline: bool,
62 strikethrough: bool,
63 spoiler: bool,
64 code_block_content: bool,
65 inline_code_content: bool,
66 backslash: bool,
67 heading: bool,
68 bulleted_list: bool,
69 numbered_list: bool,
70 masked_link: bool,
71}
72
73impl Default for EscapeOptions {
74 fn default() -> Self {
75 Self::new()
76 }
77}
78
79macro_rules! setters {
81 ($($(#[$meta:meta])* $field:ident,)*) => {
82 $(
83 $(#[$meta])*
84 pub const fn $field(mut self, on: bool) -> Self {
85 self.$field = on;
86 self
87 }
88 )*
89 };
90}
91
92impl EscapeOptions {
93 #[must_use]
96 pub const fn new() -> Self {
97 Self {
98 code_block: true,
99 inline_code: true,
100 bold: true,
101 italic: true,
102 underline: true,
103 strikethrough: true,
104 spoiler: true,
105 code_block_content: true,
106 inline_code_content: true,
107 backslash: true,
108 heading: false,
109 bulleted_list: false,
110 numbered_list: false,
111 masked_link: false,
112 }
113 }
114
115 #[must_use]
119 pub const fn none() -> Self {
120 Self {
121 code_block: false,
122 inline_code: false,
123 bold: false,
124 italic: false,
125 underline: false,
126 strikethrough: false,
127 spoiler: false,
128 code_block_content: true,
129 inline_code_content: true,
130 backslash: false,
131 heading: false,
132 bulleted_list: false,
133 numbered_list: false,
134 masked_link: false,
135 }
136 }
137
138 setters! {
139 #[must_use]
141 code_block,
142 #[must_use]
144 inline_code,
145 #[must_use]
147 bold,
148 #[must_use]
150 italic,
151 #[must_use]
153 underline,
154 #[must_use]
156 strikethrough,
157 #[must_use]
159 spoiler,
160 #[must_use]
162 code_block_content,
163 #[must_use]
165 inline_code_content,
166 #[must_use]
168 backslash,
169 #[must_use]
171 heading,
172 #[must_use]
174 bulleted_list,
175 #[must_use]
177 numbered_list,
178 #[must_use]
180 masked_link,
181 }
182
183 #[must_use]
188 pub fn escape<'a>(&self, text: &'a str) -> Cow<'a, str> {
189 let mut scanner = Scanner {
190 options: *self,
191 bytes: text.as_bytes(),
192 text,
193 out: None,
194 copied: 0,
195 line: Line::NONE,
196 };
197 scanner.run();
198 scanner.finish()
199 }
200}
201
202#[must_use]
219pub fn escape_markdown(text: &str) -> Cow<'_, str> {
220 EscapeOptions::new().escape(text)
221}
222
223macro_rules! escapers {
225 ($($function:ident => $option:ident, $js:literal, $what:literal, $input:literal => $output:literal;)*) => {
226 $(
227 #[doc = concat!("Escapes only ", $what, " in `text` ([`EscapeOptions::", stringify!($option), "`]).")]
228 #[doc = concat!("discord.js counterpart: `", $js, "`.")]
230 #[doc = concat!("assert_eq!(djs_formatters::", stringify!($function), "(", $input, "), ", $output, ");")]
235 #[must_use]
237 pub fn $function(text: &str) -> Cow<'_, str> {
238 EscapeOptions::none().$option(true).escape(text)
239 }
240 )*
241 };
242}
243
244escapers! {
245 escape_code_block => code_block, "escapeCodeBlock", "runs of three or more backticks",
246 r#""```rust```""# => r#"r"\`\`\`rust\`\`\`""#;
247 escape_inline_code => inline_code, "escapeInlineCode", "runs of one or two backticks",
248 r#""`a` ``b``""# => r#"r"\`a\` \`\`b\`\`""#;
249 escape_bold => bold, "escapeBold", "`**`", r#""**a**""# => r#"r"\*\*a\*\*""#;
250 escape_italic => italic, "escapeItalic", "a single `*` or `_`",
251 r#""*a* _b_""# => r#"r"\*a\* \_b\_""#;
252 escape_underline => underline, "escapeUnderline", "`__`", r#""__a__""# => r#"r"\_\_a\_\_""#;
253 escape_strikethrough => strikethrough, "escapeStrikethrough", "`~~`",
254 r#""~~a~~ ~b""# => r#"r"\~\~a\~\~ ~b""#;
255 escape_spoiler => spoiler, "escapeSpoiler", "`||`", r#""||a||""# => r#"r"\|\|a\|\|""#;
256 escape_escape => backslash, "escapeEscape", "backslashes", r#"r"a\b""# => r#"r"a\\b""#;
257 escape_heading => heading, "escapeHeading", "headings at the start of a line",
258 r###""## Title""### => r###"r"\## Title""###;
259 escape_bulleted_list => bulleted_list, "escapeBulletedList",
260 "bullets at the start of a line", r#""- item""# => r#"r"\- item""#;
261 escape_numbered_list => numbered_list, "escapeNumberedList",
262 "numbered list items at the start of a line", r#""1. item""# => r#"r"1\. item""#;
263 escape_masked_link => masked_link, "escapeMaskedLink", "masked links",
264 r#""[a](https://b.c)""# => r#"r"\[a](https://b.c)""#;
265}
266
267const NONE: usize = usize::MAX;
269
270#[derive(Clone, Copy, Debug)]
272struct Line {
273 end: usize,
275 marks: [usize; 3],
278 link_middle: usize,
281}
282
283impl Line {
284 const NONE: Self = Self {
286 end: 0,
287 marks: [NONE; 3],
288 link_middle: NONE,
289 };
290}
291
292struct Scanner<'a> {
294 options: EscapeOptions,
295 text: &'a str,
296 bytes: &'a [u8],
297 out: Option<String>,
298 copied: usize,
299 line: Line,
300}
301
302const fn is_space(byte: u8) -> bool {
304 matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C)
305}
306
307const fn table(bytes: &[u8]) -> [bool; 256] {
309 let mut table = [false; 256];
310 let mut index = 0;
311 while index < bytes.len() {
312 table[bytes[index] as usize] = true;
313 index += 1;
314 }
315 table
316}
317
318static STOPS: [bool; 256] = table(b"<\\*_~|`[:");
321static LINE_STOPS: [bool; 256] = table(b"<\\*_~|`[:\n#-.");
323
324impl<'a> Scanner<'a> {
325 fn escape_at(&mut self, index: usize) {
328 let out = self
329 .out
330 .get_or_insert_with(|| String::with_capacity(self.text.len() + 16));
331 out.push_str(&self.text[self.copied..index]);
332 out.push('\\');
333 self.copied = index;
334 }
335
336 fn finish(self) -> Cow<'a, str> {
337 match self.out {
338 None => Cow::Borrowed(self.text),
339 Some(mut out) => {
340 out.push_str(&self.text[self.copied..]);
341 Cow::Owned(out)
342 }
343 }
344 }
345
346 fn run_length(&self, start: usize, byte: u8) -> usize {
348 self.bytes[start..]
349 .iter()
350 .position(|&other| other != byte)
351 .unwrap_or(self.bytes.len() - start)
352 }
353
354 fn is_mark(&self, index: usize) -> bool {
355 self.line.marks.contains(&index)
356 }
357
358 fn run(&mut self) {
359 let options = self.options;
360 let lines = options.heading
361 || options.bulleted_list
362 || options.numbered_list
363 || options.masked_link;
364 let stops = if lines { &LINE_STOPS } else { &STOPS };
365 let len = self.bytes.len();
366 let mut index = 0;
367 while index < len {
368 match self.bytes[index..]
369 .iter()
370 .position(|&byte| stops[usize::from(byte)])
371 {
372 Some(offset) => index += offset,
373 None => break,
374 }
375 if lines && index >= self.line.end {
376 self.load_line(index);
377 }
378 index = match self.bytes[index] {
379 b':' => self.link(index),
380 b'<' => self.token(index),
381 b'\\' => {
382 if self.options.backslash {
383 self.escape_at(index);
384 }
385 index + 1
386 }
387 b'*' => self.emphasis(index, b'*', self.options.bold),
388 b'_' => self.emphasis(index, b'_', self.options.underline),
389 b'~' => self.pairs(index, b'~', self.options.strikethrough),
390 b'|' => self.pairs(index, b'|', self.options.spoiler),
391 b'`' => self.backticks(index),
392 b'[' => {
393 let middle = self.line.link_middle;
394 if self.options.masked_link && middle != NONE && middle >= index + 2 {
395 self.escape_at(index);
396 }
397 index + 1
398 }
399 _ => {
400 if self.is_mark(index) {
401 self.escape_at(index);
402 }
403 index + 1
404 }
405 };
406 }
407 }
408
409 fn load_line(&mut self, index: usize) {
412 let bytes = self.bytes;
413 let previous_end = self.line.end.min(index);
414 let start = bytes[previous_end..index]
415 .iter()
416 .rposition(|&byte| byte == b'\n')
417 .map_or(previous_end, |offset| previous_end + offset + 1);
418 let end = bytes[index..]
419 .iter()
420 .position(|&byte| byte == b'\n')
421 .map_or(bytes.len(), |offset| index + offset + 1);
422 let content_end = if end > start && bytes[end - 1] == b'\n' {
423 end - 1
424 } else {
425 end
426 };
427 let line = &bytes[start..content_end];
428 let mut marks = [NONE; 3];
429 let options = self.options;
430 if options.bulleted_list || options.heading || options.numbered_list {
431 let spaces = line.iter().take_while(|&&byte| byte == b' ').count();
432 if options.bulleted_list
434 && matches!(line.get(spaces), Some(b'-' | b'*'))
435 && line.get(spaces + 1) == Some(&b' ')
436 {
437 marks[0] = start + spaces;
438 }
439 if options.heading {
441 let mut at = spaces;
442 if spaces <= 2
443 && matches!(line.get(at), Some(b'-' | b'*'))
444 && line.get(at + 1) == Some(&b' ')
445 {
446 at += 2;
447 at += line[at..].iter().take_while(|&&byte| byte == b' ').count();
448 }
449 let hashes = line[at..].iter().take_while(|&&byte| byte == b'#').count();
450 if (1..=3).contains(&hashes) && line.get(at + hashes) == Some(&b' ') {
451 marks[1] = start + at;
452 }
453 }
454 if options.numbered_list {
456 let digits = line[spaces..]
457 .iter()
458 .take_while(|byte| byte.is_ascii_digit())
459 .count();
460 if digits > 0 && line.get(spaces + digits) == Some(&b'.') {
461 marks[2] = start + spaces + digits;
462 }
463 }
464 }
465 let mut link_middle = NONE;
466 if options.masked_link
467 && let Some(close) = line.iter().rposition(|&byte| byte == b')')
468 && close >= 3
469 {
470 link_middle = line[..close - 1]
472 .windows(2)
473 .rposition(|pair| pair == b"](")
474 .map_or(NONE, |middle| start + middle);
475 }
476 self.line = Line {
477 end,
478 marks,
479 link_middle,
480 };
481 }
482
483 fn link(&self, index: usize) -> usize {
486 let bytes = self.bytes;
487 let is_link = bytes[index..].starts_with(b"://")
488 && bytes.get(index + 3).is_some_and(|&byte| !is_space(byte))
489 && ((index >= 5 && bytes[index - 5..index].eq_ignore_ascii_case(b"https"))
490 || (index >= 4 && bytes[index - 4..index].eq_ignore_ascii_case(b"http")));
491 if !is_link {
492 return index + 1;
493 }
494 let rest = &bytes[index + 3..];
495 index
496 + 3
497 + rest
498 .iter()
499 .position(|&byte| is_space(byte))
500 .unwrap_or(rest.len())
501 }
502
503 fn token(&self, index: usize) -> usize {
505 let rest = &self.bytes[index + 1..];
506 let Some(close) = rest
507 .iter()
508 .position(|&byte| matches!(byte, b'<' | b'>' | b'\n'))
509 else {
510 return index + 1;
511 };
512 if rest[close] != b'>' || close == 0 {
513 return index + 1;
514 }
515 let content = &rest[..close];
516 let protected = if content[0] == b'/' {
517 let digits = content
519 .iter()
520 .rev()
521 .take_while(|byte| byte.is_ascii_digit())
522 .count();
523 digits > 0 && content.len() > digits + 1 && content[content.len() - digits - 1] == b':'
524 } else {
525 !content.iter().any(|&byte| is_space(byte))
526 && (matches!(content[0], b'@' | b'#' | b'+')
527 || content.iter().any(|&byte| matches!(byte, b':' | b'@')))
528 };
529 if protected {
530 index + close + 2
531 } else {
532 index + 1
533 }
534 }
535
536 fn emphasis(&mut self, index: usize, byte: u8, pairs: bool) -> usize {
539 let length = self.run_length(index, byte);
540 let single = self.options.italic;
541 for offset in 0..length {
542 let escaped = match (pairs, single) {
543 (true, true) => true,
544 (true, false) => offset < length / 2 * 2,
545 (false, true) => length % 2 == 1 && offset == 0,
546 (false, false) => false,
547 };
548 if escaped || self.is_mark(index + offset) {
549 self.escape_at(index + offset);
550 }
551 }
552 index + length
553 }
554
555 fn pairs(&mut self, index: usize, byte: u8, on: bool) -> usize {
557 let length = self.run_length(index, byte);
558 if on {
559 for offset in 0..length / 2 * 2 {
560 self.escape_at(index + offset);
561 }
562 }
563 index + length
564 }
565
566 fn escape_all(&mut self, index: usize, count: usize) {
568 for offset in 0..count {
569 self.escape_at(index + offset);
570 }
571 }
572
573 fn backticks(&mut self, index: usize) -> usize {
575 let options = self.options;
576 if !options.code_block_content && self.bytes[index..].starts_with(b"```") {
579 let after = index + 3;
580 let close = self.bytes[after..]
581 .windows(3)
582 .position(|window| window == b"```")
583 .map(|offset| after + offset);
584 if options.code_block {
585 self.escape_all(index, 3);
586 }
587 let Some(close) = close else {
588 return after;
589 };
590 if options.code_block {
591 self.escape_all(close, 3);
592 }
593 return close + 3;
594 }
595 let length = self.run_length(index, b'`');
596 if length == 1 && !options.inline_code_content {
597 let close = self.single_backtick(index + 1);
598 if options.inline_code {
599 self.escape_at(index);
600 }
601 let Some(close) = close else {
602 return index + 1;
603 };
604 if options.inline_code {
605 self.escape_at(close);
606 }
607 return close + 1;
608 }
609 let on = if length >= 3 {
610 options.code_block
611 } else {
612 options.inline_code
613 };
614 if on {
615 self.escape_all(index, length);
616 }
617 index + length
618 }
619
620 fn single_backtick(&self, from: usize) -> Option<usize> {
623 let mut index = from;
624 while let Some(offset) = self.bytes[index..].iter().position(|&byte| byte == b'`') {
625 let start = index + offset;
626 let length = self.run_length(start, b'`');
627 if length == 1 {
628 return Some(start);
629 }
630 if length >= 3 && !self.options.code_block_content {
631 return None;
632 }
633 index = start + length;
634 }
635 None
636 }
637}