1use std::borrow::Cow;
22use std::cell::Cell;
23
24use crate::Script;
25
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
28pub enum FormattingFallback {
29 #[default]
31 None,
32 Html,
34}
35
36impl FormattingFallback {
37 pub fn as_str(self) -> &'static str {
39 match self {
40 FormattingFallback::None => "none",
41 FormattingFallback::Html => "html",
42 }
43 }
44}
45
46impl std::fmt::Display for FormattingFallback {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 f.write_str(self.as_str())
49 }
50}
51
52impl std::str::FromStr for FormattingFallback {
53 type Err = String;
54
55 fn from_str(s: &str) -> Result<Self, Self::Err> {
56 match s.trim().to_ascii_lowercase().as_str() {
57 "none" => Ok(FormattingFallback::None),
58 "html" => Ok(FormattingFallback::Html),
59 other => Err(format!(
60 "unknown formatting fallback {other:?} (expected none | html)"
61 )),
62 }
63 }
64}
65
66const MARKS: [(char, &str); 6] = [
68 ('\u{FDD0}', "<u>"),
69 ('\u{FDD1}', "</u>"),
70 ('\u{FDD2}', "<sub>"),
71 ('\u{FDD3}', "</sub>"),
72 ('\u{FDD4}', "<sup>"),
73 ('\u{FDD5}', "</sup>"),
74];
75
76fn is_mark(c: char) -> bool {
77 ('\u{FDD0}'..='\u{FDD5}').contains(&c)
78}
79
80thread_local! {
81 static ACTIVE: Cell<bool> = const { Cell::new(false) };
82}
83
84static EVER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
86
87pub fn with_fallback<R>(on: bool, f: impl FnOnce() -> R) -> R {
90 struct Restore(bool);
91 impl Drop for Restore {
92 fn drop(&mut self) {
93 ACTIVE.with(|a| a.set(self.0));
94 }
95 }
96 let _restore = Restore(ACTIVE.with(|a| a.replace(on)));
97 f()
98}
99
100pub fn active() -> bool {
102 ACTIVE.with(Cell::get)
103}
104
105fn wrap(text: String, open: char, close: char) -> String {
106 if text.is_empty() {
107 return text;
108 }
109 EVER.store(true, std::sync::atomic::Ordering::Relaxed);
110 let mut s = String::with_capacity(text.len() + 6);
111 s.push(open);
112 s.push_str(&text);
113 s.push(close);
114 s
115}
116
117pub fn underline(text: String, on: bool) -> String {
121 if on && active() {
122 wrap(text, '\u{FDD0}', '\u{FDD1}')
123 } else {
124 text
125 }
126}
127
128pub fn script(text: String, script: Script) -> String {
132 if !active() {
133 return text;
134 }
135 match script {
136 Script::Sub => wrap(text, '\u{FDD2}', '\u{FDD3}'),
137 Script::Super => wrap(text, '\u{FDD4}', '\u{FDD5}'),
138 Script::Baseline => text,
139 }
140}
141
142pub fn render(text: &str, mode: FormattingFallback) -> Cow<'_, str> {
145 if !text.contains(is_mark) {
146 return Cow::Borrowed(text);
147 }
148 match mode {
149 FormattingFallback::None => strip(text),
150 FormattingFallback::Html => {
151 let mut s = String::with_capacity(text.len() + 16);
152 for c in text.chars() {
153 match MARKS.iter().find(|(m, _)| *m == c) {
154 Some((_, tag)) => s.push_str(tag),
155 None => s.push(c),
156 }
157 }
158 Cow::Owned(s)
159 }
160 }
161}
162
163pub fn strip(text: &str) -> Cow<'_, str> {
165 if text.contains(is_mark) {
166 Cow::Owned(text.chars().filter(|&c| !is_mark(c)).collect())
167 } else {
168 Cow::Borrowed(text)
169 }
170}
171
172pub fn strip_owned(text: String) -> String {
174 match strip(&text) {
175 Cow::Borrowed(_) => text,
176 Cow::Owned(s) => s,
177 }
178}
179
180pub(crate) fn any_marks() -> bool {
183 EVER.load(std::sync::atomic::Ordering::Relaxed)
184}
185
186pub(crate) struct MarkFilter<W> {
190 inner: W,
191 pending: Vec<u8>,
192}
193
194impl<W: std::io::Write> MarkFilter<W> {
195 pub(crate) fn new(inner: W) -> Self {
196 MarkFilter {
197 inner,
198 pending: Vec::new(),
199 }
200 }
201}
202
203impl<W: std::io::Write> std::io::Write for MarkFilter<W> {
204 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
205 let mut data = std::mem::take(&mut self.pending);
206 data.extend_from_slice(buf);
207 let mut out = Vec::with_capacity(data.len());
208 let mut i = 0;
209 while i < data.len() {
210 if data[i] == 0xEF {
211 if data.len() - i < 3 {
213 self.pending = data[i..].to_vec();
214 break;
215 }
216 if data[i + 1] == 0xB7 && (0x90..=0x95).contains(&data[i + 2]) {
217 i += 3;
218 continue;
219 }
220 }
221 out.push(data[i]);
222 i += 1;
223 }
224 self.inner.write_all(&out)?;
225 Ok(buf.len())
226 }
227
228 fn flush(&mut self) -> std::io::Result<()> {
229 if !self.pending.is_empty() {
230 let rest = std::mem::take(&mut self.pending);
231 self.inner.write_all(&rest)?;
232 }
233 self.inner.flush()
234 }
235}
236
237pub fn strip_value(v: &mut serde_json::Value) {
239 match v {
240 serde_json::Value::String(s) => {
241 if s.contains(is_mark) {
242 *s = strip(s).into_owned();
243 }
244 }
245 serde_json::Value::Array(a) => a.iter_mut().for_each(strip_value),
246 serde_json::Value::Object(o) => o.values_mut().for_each(strip_value),
247 _ => {}
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 #[test]
256 fn marks_only_under_the_fallback() {
257 assert_eq!(underline("x".into(), true), "x");
258 assert_eq!(script("2".into(), Script::Sub), "2");
259 with_fallback(true, || {
260 let u = underline("<tag>".into(), true);
261 let sub = script("2".into(), Script::Sub);
262 let sup = script("2".into(), Script::Super);
263 let text = format!("H{sub}O, mc{sup}, {u}");
264 assert_eq!(
265 render(&text, FormattingFallback::Html),
266 "H<sub>2</sub>O, mc<sup>2</sup>, <u><tag></u>"
267 );
268 assert_eq!(
269 render(&text, FormattingFallback::None),
270 "H2O, mc2, <tag>"
271 );
272 assert_eq!(strip(&text), "H2O, mc2, <tag>");
273 assert_eq!(underline("x".into(), false), "x");
275 });
276 assert!(!active());
277 }
278
279 #[test]
280 fn parses_the_wire_values() {
281 assert_eq!("HTML".parse(), Ok(FormattingFallback::Html));
282 assert_eq!("none".parse(), Ok(FormattingFallback::None));
283 assert!("tags".parse::<FormattingFallback>().is_err());
284 }
285}