termosaic 0.2.2

Semantic, structured output for human, machine-text, and opaque-byte destinations
Documentation
use crate::{AnsiColor, Color, ColorDepth, Stream, Theme, TokenId, TokenStyle};

const ESC: &[u8] = b"\x1b[";
const RESET: &[u8] = b"\x1b[0m";

#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) struct StyleEncoding {
    prefix: [u8; 64],
    prefix_len: u8,
    reset_count: u8,
}

impl StyleEncoding {
    pub(crate) fn prefix(&self) -> &[u8] {
        &self.prefix[..usize::from(self.prefix_len)]
    }

    pub(crate) const fn reset_count(&self) -> u8 {
        self.reset_count
    }

    pub(crate) const fn suffix_len(&self) -> usize {
        RESET.len() * self.reset_count as usize
    }
}

pub(crate) fn render_text(
    theme: &Theme,
    token: &TokenId,
    text: &str,
    depth: ColorDepth,
    color_enabled: bool,
    stream: Stream,
) -> String {
    if !color_enabled || text.is_empty() {
        return text.to_owned();
    }
    let encoding = style_encoding(theme, token, depth, color_enabled, stream);
    if encoding.prefix_len == 0 {
        return text.to_owned();
    }
    let mut output =
        Vec::with_capacity(encoding.prefix().len() + text.len() + encoding.suffix_len());
    output.extend_from_slice(encoding.prefix());
    output.extend_from_slice(text.as_bytes());
    for _ in 0..encoding.reset_count() {
        output.extend_from_slice(RESET);
    }
    String::from_utf8(output).expect("ANSI rendering preserves UTF-8")
}

pub(crate) fn style_encoding(
    theme: &Theme,
    token: &TokenId,
    depth: ColorDepth,
    color_enabled: bool,
    _stream: Stream,
) -> StyleEncoding {
    let style = theme.resolve(token);
    style_encoding_for_style(style, depth, color_enabled, _stream)
}

pub(crate) fn style_encoding_for_style(
    style: TokenStyle,
    depth: ColorDepth,
    color_enabled: bool,
    _stream: Stream,
) -> StyleEncoding {
    if !color_enabled || style == TokenStyle::default() {
        return StyleEncoding {
            prefix: [0; 64],
            prefix_len: 0,
            reset_count: 0,
        };
    }

    let mut encoding = StyleEncoding {
        prefix: [0; 64],
        prefix_len: 0,
        reset_count: 1,
    };
    if let Some(foreground) = style.foreground {
        match foreground {
            Color::Ansi(color) => push_ansi_color(&mut encoding, color),
            Color::Rgb {
                red,
                green,
                blue,
                fallback,
            } => match depth {
                ColorDepth::TrueColor => {
                    push_color_values(&mut encoding, &[38, 2, red, green, blue])
                }
                ColorDepth::Ansi256 => {
                    push_color_values(&mut encoding, &[38, 5, quantize_ansi256(red, green, blue)])
                }
                ColorDepth::Ansi16 => push_ansi_color(&mut encoding, fallback),
            },
        }
    }
    if style.bold {
        push_sequence(&mut encoding, 1);
    }
    if style.dim {
        push_sequence(&mut encoding, 2);
    }
    if style.underline {
        push_sequence(&mut encoding, 4);
    }
    encoding
}

fn push_ansi_color(encoding: &mut StyleEncoding, color: AnsiColor) {
    let (normal, bright) = match color {
        AnsiColor::Black => (30, None),
        AnsiColor::Red => (31, None),
        AnsiColor::Green => (32, None),
        AnsiColor::Yellow => (33, None),
        AnsiColor::Blue => (34, None),
        AnsiColor::Magenta => (35, None),
        AnsiColor::Cyan => (36, None),
        AnsiColor::White => (37, None),
        AnsiColor::BrightBlack => (30, Some(90)),
        AnsiColor::BrightRed => (31, Some(91)),
        AnsiColor::BrightGreen => (32, Some(92)),
        AnsiColor::BrightYellow => (33, Some(93)),
        AnsiColor::BrightBlue => (34, Some(94)),
        AnsiColor::BrightMagenta => (35, Some(95)),
        AnsiColor::BrightCyan => (36, Some(96)),
        AnsiColor::BrightWhite => (37, Some(97)),
    };
    if let Some(bright) = bright {
        push_sequence(encoding, bright);
        encoding.reset_count = 2;
    }
    push_sequence(encoding, normal);
}

fn push_color_values(encoding: &mut StyleEncoding, values: &[u8]) {
    push_bytes(encoding, ESC);
    for (index, value) in values.iter().copied().enumerate() {
        if index != 0 {
            push_bytes(encoding, b";");
        }
        push_decimal(encoding, value);
    }
    push_bytes(encoding, b"m");
}

fn push_sequence(encoding: &mut StyleEncoding, value: u8) {
    push_bytes(encoding, ESC);
    push_decimal(encoding, value);
    push_bytes(encoding, b"m");
}

fn push_decimal(encoding: &mut StyleEncoding, value: u8) {
    let hundreds = value / 100;
    let tens = (value / 10) % 10;
    let ones = value % 10;
    if hundreds != 0 {
        push_bytes(encoding, &[b'0' + hundreds]);
        push_bytes(encoding, &[b'0' + tens]);
    } else if tens != 0 {
        push_bytes(encoding, &[b'0' + tens]);
    }
    push_bytes(encoding, &[b'0' + ones]);
}

fn push_bytes(encoding: &mut StyleEncoding, bytes: &[u8]) {
    let start = usize::from(encoding.prefix_len);
    let end = start + bytes.len();
    encoding.prefix[start..end].copy_from_slice(bytes);
    encoding.prefix_len = u8::try_from(end).expect("style prefix fits fixed encoder");
}

/// Deterministically quantize RGB into xterm indices 16 through 255.
pub(crate) fn quantize_ansi256(red: u8, green: u8, blue: u8) -> u8 {
    const CUBE: [u8; 6] = [0, 95, 135, 175, 215, 255];
    let mut best_index = 16u8;
    let mut best_distance = u64::MAX;

    for (r_index, &candidate_red) in CUBE.iter().enumerate() {
        for (g_index, &candidate_green) in CUBE.iter().enumerate() {
            for (b_index, &candidate_blue) in CUBE.iter().enumerate() {
                let index = 16 + 36 * r_index as u8 + 6 * g_index as u8 + b_index as u8;
                choose_candidate(
                    red,
                    green,
                    blue,
                    candidate_red,
                    candidate_green,
                    candidate_blue,
                    index,
                    &mut best_index,
                    &mut best_distance,
                );
            }
        }
    }

    for gray_index in 0u8..=23 {
        let value = 8 + 10 * gray_index;
        choose_candidate(
            red,
            green,
            blue,
            value,
            value,
            value,
            232 + gray_index,
            &mut best_index,
            &mut best_distance,
        );
    }
    best_index
}

#[allow(clippy::too_many_arguments)]
fn choose_candidate(
    red: u8,
    green: u8,
    blue: u8,
    candidate_red: u8,
    candidate_green: u8,
    candidate_blue: u8,
    candidate_index: u8,
    best_index: &mut u8,
    best_distance: &mut u64,
) {
    let distance = red_mean_distance(
        red,
        green,
        blue,
        candidate_red,
        candidate_green,
        candidate_blue,
    );
    if distance < *best_distance || (distance == *best_distance && candidate_index < *best_index) {
        *best_distance = distance;
        *best_index = candidate_index;
    }
}

fn red_mean_distance(
    red: u8,
    green: u8,
    blue: u8,
    candidate_red: u8,
    candidate_green: u8,
    candidate_blue: u8,
) -> u64 {
    let red_mean = (u64::from(red) + u64::from(candidate_red)) / 2;
    let delta_red = i64::from(red) - i64::from(candidate_red);
    let delta_green = i64::from(green) - i64::from(candidate_green);
    let delta_blue = i64::from(blue) - i64::from(candidate_blue);
    let red_squared = delta_red.unsigned_abs().pow(2);
    let green_squared = delta_green.unsigned_abs().pow(2);
    let blue_squared = delta_blue.unsigned_abs().pow(2);
    (((512 + red_mean) * red_squared) >> 8)
        + 4 * green_squared
        + (((767 - red_mean) * blue_squared) >> 8)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rgb_quantization_matches_independent_reference_boundaries() {
        let fixture = include_str!("../tests/fixtures/console-color-quantization.toml");
        let mut red = None;
        let mut green = None;
        let mut blue = None;
        let mut cases = Vec::new();
        for line in fixture.lines() {
            let Some((key, value)) = line.split_once(" = ") else {
                continue;
            };
            let parsed = value.parse::<u8>();
            match (key, parsed) {
                ("red", Ok(value)) => red = Some(value),
                ("green", Ok(value)) => green = Some(value),
                ("blue", Ok(value)) => blue = Some(value),
                ("expected_index", Ok(expected)) => {
                    if let (Some(red), Some(green), Some(blue)) = (red, green, blue) {
                        cases.push((red, green, blue, expected));
                    }
                    red = None;
                    green = None;
                    blue = None;
                }
                _ => {}
            }
        }
        assert_eq!(cases.len(), 9, "fixture case count changed");
        for (red, green, blue, expected) in cases {
            assert_eq!(
                quantize_ansi256(red, green, blue),
                expected,
                "vector ({red}, {green}, {blue})"
            );
            assert_eq!(expected, reference_quantize(red, green, blue));
        }
    }

    #[test]
    fn pinned_rgb_index_and_direct_ansi_color_are_depth_invariant() {
        assert_eq!(quantize_ansi256(255, 85, 85), 203);

        let token = TokenId::from_static("status.error.test");
        let theme = Theme::inheriting("ansi-depth-test", &crate::themes::default())
            .rule(
                token.clone(),
                TokenStyle {
                    foreground: Some(Color::Ansi(AnsiColor::BrightCyan)),
                    bold: true,
                    dim: false,
                    underline: false,
                },
            )
            .and_then(crate::ThemeBuilder::build)
            .expect("valid test theme");
        let rendered = [
            ColorDepth::Ansi16,
            ColorDepth::Ansi256,
            ColorDepth::TrueColor,
        ]
        .map(|depth| render_text(&theme, &token, "value", depth, true, Stream::Stdout));
        assert_eq!(rendered[0], rendered[1]);
        assert_eq!(rendered[1], rendered[2]);
        assert!(!rendered[0].contains("38;5;") && !rendered[0].contains("38;2;"));
    }

    fn reference_quantize(red: u8, green: u8, blue: u8) -> u8 {
        let cube = [0u8, 95, 135, 175, 215, 255];
        let mut candidates = Vec::new();
        for (r, &candidate_red) in cube.iter().enumerate() {
            for (g, &candidate_green) in cube.iter().enumerate() {
                for (b, &candidate_blue) in cube.iter().enumerate() {
                    candidates.push((
                        16 + 36 * r as u8 + 6 * g as u8 + b as u8,
                        candidate_red,
                        candidate_green,
                        candidate_blue,
                    ));
                }
            }
        }
        candidates.extend((0u8..=23).map(|index| {
            let value = 8 + 10 * index;
            (232 + index, value, value, value)
        }));
        candidates
            .into_iter()
            .map(|(index, candidate_red, candidate_green, candidate_blue)| {
                let red_mean = (u64::from(red) + u64::from(candidate_red)) / 2;
                let dr = (i64::from(red) - i64::from(candidate_red)).unsigned_abs();
                let dg = (i64::from(green) - i64::from(candidate_green)).unsigned_abs();
                let db = (i64::from(blue) - i64::from(candidate_blue)).unsigned_abs();
                let distance = (((512 + red_mean) * dr * dr) >> 8)
                    + 4 * dg * dg
                    + (((767 - red_mean) * db * db) >> 8);
                (distance, index)
            })
            .min()
            .map_or(16, |(_, index)| index)
    }
}