use std::borrow::Cow;
use std::cell::Cell;
use crate::Script;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FormattingFallback {
#[default]
None,
Html,
}
impl FormattingFallback {
pub fn as_str(self) -> &'static str {
match self {
FormattingFallback::None => "none",
FormattingFallback::Html => "html",
}
}
}
impl std::fmt::Display for FormattingFallback {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for FormattingFallback {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_ascii_lowercase().as_str() {
"none" => Ok(FormattingFallback::None),
"html" => Ok(FormattingFallback::Html),
other => Err(format!(
"unknown formatting fallback {other:?} (expected none | html)"
)),
}
}
}
const MARKS: [(char, &str); 6] = [
('\u{FDD0}', "<u>"),
('\u{FDD1}', "</u>"),
('\u{FDD2}', "<sub>"),
('\u{FDD3}', "</sub>"),
('\u{FDD4}', "<sup>"),
('\u{FDD5}', "</sup>"),
];
fn is_mark(c: char) -> bool {
('\u{FDD0}'..='\u{FDD5}').contains(&c)
}
thread_local! {
static ACTIVE: Cell<bool> = const { Cell::new(false) };
}
static EVER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn with_fallback<R>(on: bool, f: impl FnOnce() -> R) -> R {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
ACTIVE.with(|a| a.set(self.0));
}
}
let _restore = Restore(ACTIVE.with(|a| a.replace(on)));
f()
}
pub fn active() -> bool {
ACTIVE.with(Cell::get)
}
fn wrap(text: String, open: char, close: char) -> String {
if text.is_empty() {
return text;
}
EVER.store(true, std::sync::atomic::Ordering::Relaxed);
let mut s = String::with_capacity(text.len() + 6);
s.push(open);
s.push_str(&text);
s.push(close);
s
}
pub fn underline(text: String, on: bool) -> String {
if on && active() {
wrap(text, '\u{FDD0}', '\u{FDD1}')
} else {
text
}
}
pub fn script(text: String, script: Script) -> String {
if !active() {
return text;
}
match script {
Script::Sub => wrap(text, '\u{FDD2}', '\u{FDD3}'),
Script::Super => wrap(text, '\u{FDD4}', '\u{FDD5}'),
Script::Baseline => text,
}
}
pub fn render(text: &str, mode: FormattingFallback) -> Cow<'_, str> {
if !text.contains(is_mark) {
return Cow::Borrowed(text);
}
match mode {
FormattingFallback::None => strip(text),
FormattingFallback::Html => {
let mut s = String::with_capacity(text.len() + 16);
for c in text.chars() {
match MARKS.iter().find(|(m, _)| *m == c) {
Some((_, tag)) => s.push_str(tag),
None => s.push(c),
}
}
Cow::Owned(s)
}
}
}
pub fn strip(text: &str) -> Cow<'_, str> {
if text.contains(is_mark) {
Cow::Owned(text.chars().filter(|&c| !is_mark(c)).collect())
} else {
Cow::Borrowed(text)
}
}
pub fn strip_owned(text: String) -> String {
match strip(&text) {
Cow::Borrowed(_) => text,
Cow::Owned(s) => s,
}
}
pub(crate) fn any_marks() -> bool {
EVER.load(std::sync::atomic::Ordering::Relaxed)
}
pub(crate) struct MarkFilter<W> {
inner: W,
pending: Vec<u8>,
}
impl<W: std::io::Write> MarkFilter<W> {
pub(crate) fn new(inner: W) -> Self {
MarkFilter {
inner,
pending: Vec::new(),
}
}
}
impl<W: std::io::Write> std::io::Write for MarkFilter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let mut data = std::mem::take(&mut self.pending);
data.extend_from_slice(buf);
let mut out = Vec::with_capacity(data.len());
let mut i = 0;
while i < data.len() {
if data[i] == 0xEF {
if data.len() - i < 3 {
self.pending = data[i..].to_vec();
break;
}
if data[i + 1] == 0xB7 && (0x90..=0x95).contains(&data[i + 2]) {
i += 3;
continue;
}
}
out.push(data[i]);
i += 1;
}
self.inner.write_all(&out)?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
if !self.pending.is_empty() {
let rest = std::mem::take(&mut self.pending);
self.inner.write_all(&rest)?;
}
self.inner.flush()
}
}
pub fn strip_value(v: &mut serde_json::Value) {
match v {
serde_json::Value::String(s) => {
if s.contains(is_mark) {
*s = strip(s).into_owned();
}
}
serde_json::Value::Array(a) => a.iter_mut().for_each(strip_value),
serde_json::Value::Object(o) => o.values_mut().for_each(strip_value),
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn marks_only_under_the_fallback() {
assert_eq!(underline("x".into(), true), "x");
assert_eq!(script("2".into(), Script::Sub), "2");
with_fallback(true, || {
let u = underline("<tag>".into(), true);
let sub = script("2".into(), Script::Sub);
let sup = script("2".into(), Script::Super);
let text = format!("H{sub}O, mc{sup}, {u}");
assert_eq!(
render(&text, FormattingFallback::Html),
"H<sub>2</sub>O, mc<sup>2</sup>, <u><tag></u>"
);
assert_eq!(
render(&text, FormattingFallback::None),
"H2O, mc2, <tag>"
);
assert_eq!(strip(&text), "H2O, mc2, <tag>");
assert_eq!(underline("x".into(), false), "x");
});
assert!(!active());
}
#[test]
fn parses_the_wire_values() {
assert_eq!("HTML".parse(), Ok(FormattingFallback::Html));
assert_eq!("none".parse(), Ok(FormattingFallback::None));
assert!("tags".parse::<FormattingFallback>().is_err());
}
}