From 425be4bef4018fceb621bba8d0dd26f0aab210af Mon Sep 17 00:00:00 2001 From: Emmanuel Gil Peyrot Date: Sun, 1 Sep 2024 12:30:18 +0200 Subject: [PATCH] tokio-xmpp: Improve highlight_xml() First switch to LazyLock from OnceLock, to simplify the code. Then concatenate the colour reset escape code instead of using format!(), since the vast majority of those strings have more capacity than their length it will avoid a reallocation in most cases. --- tokio-xmpp/src/xmlstream/mod.rs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/tokio-xmpp/src/xmlstream/mod.rs b/tokio-xmpp/src/xmlstream/mod.rs index f077fe11..aad992d3 100644 --- a/tokio-xmpp/src/xmlstream/mod.rs +++ b/tokio-xmpp/src/xmlstream/mod.rs @@ -62,7 +62,7 @@ use core::pin::Pin; use core::task::{Context, Poll}; use std::io; #[cfg(feature = "syntax-highlighting")] -use std::sync::OnceLock; +use std::sync::LazyLock; use futures::{ready, Sink, SinkExt, Stream}; @@ -85,25 +85,25 @@ pub use self::responder::{AcceptedStream, PendingFeaturesSend}; pub use self::xmpp::XmppStreamElement; #[cfg(feature = "syntax-highlighting")] -static PS: OnceLock = OnceLock::new(); +static PS: LazyLock = + LazyLock::new(syntect::parsing::SyntaxSet::load_defaults_newlines); + #[cfg(feature = "syntax-highlighting")] -static SYNTAX: OnceLock = OnceLock::new(); +static SYNTAX: LazyLock<&syntect::parsing::SyntaxReference> = + LazyLock::new(|| PS.find_syntax_by_extension("xml").unwrap()); + #[cfg(feature = "syntax-highlighting")] -static THEME: OnceLock = OnceLock::new(); +static THEME: LazyLock = LazyLock::new(|| { + syntect::highlighting::ThemeSet::load_defaults().themes["Solarized (dark)"].clone() +}); #[cfg(feature = "syntax-highlighting")] fn highlight_xml(xml: &str) -> String { - let ps = PS.get_or_init(syntect::parsing::SyntaxSet::load_defaults_newlines); - let mut h = syntect::easy::HighlightLines::new( - SYNTAX.get_or_init(|| ps.find_syntax_by_extension("xml").unwrap().clone()), - THEME.get_or_init(|| { - syntect::highlighting::ThemeSet::load_defaults().themes["Solarized (dark)"].clone() - }), - ); - - let ranges: Vec<_> = h.highlight_line(&xml, ps).unwrap(); - let escaped = syntect::util::as_24_bit_terminal_escaped(&ranges[..], false); - format!("{}\x1b[0m", escaped) + let mut h = syntect::easy::HighlightLines::new(&SYNTAX, &THEME); + let ranges: Vec<_> = h.highlight_line(&xml, &PS).unwrap(); + let mut escaped = syntect::util::as_24_bit_terminal_escaped(&ranges[..], false); + escaped += "\x1b[0m"; + escaped } struct LogXsoBuf<'x>(&'x [u8]);