glyphatar 0.2.0

Deterministic, mirror-symmetric SVG identicons built from simple shapes
Documentation
//! Deterministic SVG identicons ("glyph avatars").
//!
//! ```
//! let svg = glyphatar::svg(b"some public key bytes", 64);
//! assert!(svg.starts_with("<svg"));
//! ```
//!
//! # Stability
//!
//! The same input renders the same image within a major version. Any change
//! to the picture for a given input is a breaking change.

mod sha256;

use std::fmt::Write;

/// Cells per side. Columns `0..GRID/2` are mirrored onto the right half.
const GRID: usize = 5;
const HALF: usize = GRID.div_ceil(2);
/// Below this many filled cells (of `GRID * HALF`), regenerate.
const MIN_FILLED: usize = 5;

/// A corner of a cell, used to orient triangles and quarter circles.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Corner {
    TopLeft,
    TopRight,
    BottomRight,
    BottomLeft,
}

impl Corner {
    const ALL: [Corner; 4] = [
        Corner::TopLeft,
        Corner::TopRight,
        Corner::BottomRight,
        Corner::BottomLeft,
    ];

    fn mirrored(self) -> Corner {
        match self {
            Corner::TopLeft => Corner::TopRight,
            Corner::TopRight => Corner::TopLeft,
            Corner::BottomRight => Corner::BottomLeft,
            Corner::BottomLeft => Corner::BottomRight,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Shape {
    Empty,
    Square,
    Circle,
    Diamond,
    /// Right triangle whose right angle sits in the given corner.
    Triangle(Corner),
    /// Quarter disc of radius 1 centred on the given corner.
    Quarter(Corner),
}

impl Shape {
    fn mirrored(self) -> Shape {
        match self {
            Shape::Triangle(c) => Shape::Triangle(c.mirrored()),
            Shape::Quarter(c) => Shape::Quarter(c.mirrored()),
            s => s,
        }
    }

    /// Off-centre cells: 5 bits → shape, weighted out of 32.
    fn side(v: u32) -> Shape {
        match v {
            0..=10 => Shape::Empty,
            11..=15 => Shape::Square,
            16..=23 => Shape::Triangle(Corner::ALL[(v - 16) as usize / 2]),
            24..=27 => Shape::Quarter(Corner::ALL[(v - 24) as usize]),
            28..=29 => Shape::Circle,
            _ => Shape::Diamond,
        }
    }

    /// Centre-column cells must be left-right symmetric on their own.
    fn center(v: u32) -> Shape {
        match v {
            0..=11 => Shape::Empty,
            12..=21 => Shape::Square,
            22..=26 => Shape::Circle,
            _ => Shape::Diamond,
        }
    }

    /// Append an SVG path for this shape in the unit cell at (x, y).
    /// `{x0}.5` relies on x0 and y0 being integers.
    fn path(self, out: &mut String, x: usize, y: usize) {
        let (x0, y0, x1, y1) = (x, y, x + 1, y + 1);
        let _ = match self {
            Shape::Empty => Ok(()),
            Shape::Square => write!(out, "M{x0} {y0}h1v1h-1z"),
            Shape::Circle => write!(out, "M{x0}.1 {y0}.5a.4 .4 0 1 0 .8 0a.4 .4 0 1 0-.8 0z"),
            Shape::Diamond => write!(out, "M{x0}.5 {y0}L{x1} {y0}.5L{x0}.5 {y1}L{x0} {y0}.5z"),
            Shape::Triangle(c) => match c {
                Corner::TopLeft => write!(out, "M{x0} {y0}H{x1}L{x0} {y1}z"),
                Corner::TopRight => write!(out, "M{x0} {y0}H{x1}V{y1}z"),
                Corner::BottomRight => write!(out, "M{x1} {y0}V{y1}H{x0}z"),
                Corner::BottomLeft => write!(out, "M{x0} {y0}L{x1} {y1}H{x0}z"),
            },
            // Pie slices: two straight edges from the corner, arc between.
            Shape::Quarter(c) => match c {
                Corner::TopLeft => write!(out, "M{x0} {y0}H{x1}A1 1 0 0 1 {x0} {y1}z"),
                Corner::TopRight => write!(out, "M{x1} {y0}V{y1}A1 1 0 0 1 {x0} {y0}z"),
                Corner::BottomRight => write!(out, "M{x1} {y1}H{x0}A1 1 0 0 1 {x1} {y0}z"),
                Corner::BottomLeft => write!(out, "M{x0} {y1}V{y0}A1 1 0 0 1 {x1} {y1}z"),
            },
        };
    }
}

/// An OKLCH colour: perceptual lightness (0..1), chroma, and hue in degrees.
/// Unlike HSL, equal steps in hue look equally different, and every hue at
/// the same lightness looks equally bright.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Oklch {
    l: f64,
    c: f64,
    h: f64,
}

impl Oklch {
    /// Linear sRGB channels; out of `0..=1` when the colour is out of gamut.
    fn linear_srgb(self, c: f64) -> [f64; 3] {
        let (a, b) = (c * self.h.to_radians().cos(), c * self.h.to_radians().sin());
        let l_ = self.l + 0.3963377774 * a + 0.2158037573 * b;
        let m_ = self.l - 0.1055613458 * a - 0.0638541728 * b;
        let s_ = self.l - 0.0894841775 * a - 1.2914855480 * b;
        let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
        [
            4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
            -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
            -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
        ]
    }

    /// `#rrggbb`, which every SVG renderer understands (unlike CSS `oklch()`).
    /// Chroma is reduced as needed to fit in sRGB, keeping lightness and hue.
    fn hex(self) -> String {
        let in_gamut = |c| {
            self.linear_srgb(c)
                .iter()
                .all(|v| (-1e-9..=1.0 + 1e-9).contains(v))
        };
        let mut c = self.c;
        if !in_gamut(c) {
            let (mut lo, mut hi) = (0.0, self.c);
            for _ in 0..24 {
                let mid = (lo + hi) / 2.0;
                if in_gamut(mid) { lo = mid } else { hi = mid }
            }
            c = lo;
        }
        let [r, g, b] = self.linear_srgb(c).map(|v| {
            let v = v.clamp(0.0, 1.0);
            let v = if v <= 0.0031308 {
                12.92 * v
            } else {
                1.055 * v.powf(1.0 / 2.4) - 0.055
            };
            (v * 255.0).round() as u8
        });
        format!("#{r:02x}{g:02x}{b:02x}")
    }
}

/// A generated glyph, which can be rendered at any size.
#[derive(Clone, Debug, PartialEq)]
pub struct Glyphatar {
    /// `cells[row][col]`: the shape and whether it uses the secondary colour.
    cells: [[(Shape, bool); GRID]; GRID],
    primary: Oklch,
    secondary: Oklch,
}

/// Reads bits from a SHA-256 digest, low bits first.
struct Bits {
    bytes: [u8; 32],
    pos: usize,
}

impl Bits {
    fn take(&mut self, n: usize) -> u32 {
        let mut v = 0;
        for i in 0..n {
            let bit = self.bytes[self.pos / 8] >> (self.pos % 8) & 1;
            v |= (bit as u32) << i;
            self.pos += 1;
        }
        v
    }
}

impl Glyphatar {
    /// Derive a glyph from arbitrary bytes (a public key, user id, …).
    /// The input is hashed, so it can be any length.
    pub fn new(input: &[u8]) -> Glyphatar {
        let mut digest = sha256::digest(input);
        loop {
            if let Some(glyph) = Self::from_digest(digest) {
                return glyph;
            }
            // Too sparse: rehash deterministically and try again.
            digest = sha256::digest(&digest);
        }
    }

    /// Uses 9 + 3 + 2 + 15 * (5 + 2) = 119 of the 256 bits.
    fn from_digest(digest: [u8; 32]) -> Option<Glyphatar> {
        let mut bits = Bits {
            bytes: digest,
            pos: 0,
        };
        // Scale rather than `% 360`, which would favour the first 152 degrees.
        let h = bits.take(9) as f64 * 360.0 / 512.0;
        let c = 0.13 + 0.01 * bits.take(3) as f64; // 0.13..=0.20
        let offset = [0.0, 40.0, 320.0, 180.0][bits.take(2) as usize];
        let primary = Oklch { l: 0.67, c, h };
        let secondary = Oklch {
            l: 0.85,
            c,
            h: (h + offset) % 360.0,
        };

        let mut cells = [[(Shape::Empty, false); GRID]; GRID];
        let mut filled = 0;
        for row in cells.iter_mut() {
            for col in 0..HALF {
                let v = bits.take(5);
                let shape = if col == GRID / 2 {
                    Shape::center(v)
                } else {
                    Shape::side(v)
                };
                // One in four filled cells takes the secondary colour.
                let alt = bits.take(2) == 0;
                row[col] = (shape, alt);
                row[GRID - 1 - col] = (shape.mirrored(), alt);
                filled += (shape != Shape::Empty) as usize;
            }
        }
        (filled >= MIN_FILLED).then_some(Glyphatar {
            cells,
            primary,
            secondary,
        })
    }

    /// Render as an SVG `size` pixels square, with a transparent background
    /// and a half-cell margin.
    pub fn to_svg(&self, size: u32) -> String {
        self.render(size, None)
    }

    /// Like [`to_svg`](Self::to_svg), with a `<title>` for screen readers and
    /// hover tooltips. The title is XML-escaped.
    pub fn to_svg_with_title(&self, size: u32, title: &str) -> String {
        self.render(size, Some(title))
    }

    fn render(&self, size: u32, title: Option<&str>) -> String {
        let (mut fg, mut alt) = (String::new(), String::new());
        for (y, row) in self.cells.iter().enumerate() {
            for (x, &(shape, is_alt)) in row.iter().enumerate() {
                shape.path(if is_alt { &mut alt } else { &mut fg }, x, y);
            }
        }
        let mut svg = format!(
            r#"<svg xmlns="http://www.w3.org/2000/svg" role="img" width="{size}" height="{size}" viewBox="-0.5 -0.5 {v} {v}">"#,
            v = GRID + 1
        );
        if let Some(title) = title {
            svg.push_str("<title>");
            escape_into(&mut svg, title);
            svg.push_str("</title>");
        }
        for (d, color) in [(fg, self.primary), (alt, self.secondary)] {
            if !d.is_empty() {
                let _ = write!(svg, r#"<path fill="{}" d="{d}"/>"#, color.hex());
            }
        }
        svg.push_str("</svg>");
        svg
    }
}

fn escape_into(out: &mut String, s: &str) {
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            c => out.push(c),
        }
    }
}

/// Generate an SVG glyph for `input`, `size` pixels square.
pub fn svg(input: &[u8], size: u32) -> String {
    Glyphatar::new(input).to_svg(size)
}

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

    #[test]
    fn deterministic() {
        assert_eq!(svg(b"hello", 64), svg(b"hello", 64));
        assert_ne!(svg(b"hello", 64), svg(b"hellp", 64));
    }

    #[test]
    fn mirrored_and_dense_enough() {
        for i in 0u32..500 {
            let glyph = Glyphatar::new(&i.to_le_bytes());
            let mut filled = 0;
            for row in &glyph.cells {
                for col in 0..GRID {
                    let (s, a) = row[col];
                    assert_eq!((s.mirrored(), a), row[GRID - 1 - col]);
                    filled += (s != Shape::Empty) as usize;
                }
            }
            assert!(filled >= MIN_FILLED);
        }
    }

    #[test]
    fn mostly_distinct() {
        let glyphs: std::collections::HashSet<String> =
            (0u32..2000).map(|i| svg(&i.to_le_bytes(), 32)).collect();
        assert_eq!(glyphs.len(), 2000);
    }

    #[test]
    fn hex_colours() {
        let hex = |l, c, h| Oklch { l, c, h }.hex();
        assert_eq!(hex(1.0, 0.0, 0.0), "#ffffff");
        assert_eq!(hex(0.0, 0.0, 0.0), "#000000");
        // Pure sRGB red, from its published OKLCH coordinates.
        assert_eq!(hex(0.627955, 0.257683, 29.2339), "#ff0000");
        // Out of gamut: chroma is reduced instead of clipping a channel.
        let cyan = hex(0.62, 0.3, 200.0);
        assert_eq!(cyan, hex(0.62, 0.2, 200.0));
    }

    #[test]
    fn title_is_escaped() {
        let s = Glyphatar::new(b"x").to_svg_with_title(32, "<a & b>");
        assert!(s.contains("<title>&lt;a &amp; b&gt;</title>"));
    }

    /// Output must not change within a major version. If this fails, the
    /// change is breaking: bump the major version and update the expectations.
    #[test]
    fn output_is_stable() {
        assert_eq!(svg(b"hello", 64), HELLO);
        let mut all = String::new();
        for i in 0u32..1000 {
            all.push_str(&svg(&i.to_le_bytes(), 64));
        }
        let digest: String = sha256::digest(all.as_bytes())
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        assert_eq!(digest, ALL_1000);
    }

    const HELLO: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" role="img" width="64" height="64" viewBox="-0.5 -0.5 6 6"><path fill="#de715e" d="M0 0L1 1H0zM1 0H2V1zM2.5 0L3 0.5L2.5 1L2 0.5zM3 0H4L3 1zM5 0V1H4zM1 1h1v1h-1zM2 1h1v1h-1zM3 1h1v1h-1zM1 2h1v1h-1zM3 2h1v1h-1zM0.5 3L1 3.5L0.5 4L0 3.5zM4.5 3L5 3.5L4.5 4L4 3.5zM0 4H1L0 5zM1.1 4.5a.4 .4 0 1 0 .8 0a.4 .4 0 1 0-.8 0zM3.1 4.5a.4 .4 0 1 0 .8 0a.4 .4 0 1 0-.8 0zM4 4H5V5z"/><path fill="#41e5ff" d="M0 1h1v1h-1zM4 1h1v1h-1zM0 2h1v1h-1zM4 2h1v1h-1z"/></svg>"##;
    const ALL_1000: &str = "0e955e510fa90849ce97da9443d0c0c29ec4bc10ac92c789a869b46e2f424106";
}