//! 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 HSL colour (hue in degrees, saturation and lightness in percent).
#[derive(Clone, Copy, Debug, PartialEq)]
struct Hsl {
h: u16,
s: u8,
l: u8,
}
impl Hsl {
/// `#rrggbb`, which every SVG renderer understands (unlike CSS `hsl()`).
fn hex(self) -> String {
let (h, s, l) = (self.h as f64, self.s as f64 / 100.0, self.l as f64 / 100.0);
let a = s * l.min(1.0 - l);
let channel = |n: f64| {
let k = (n + h / 30.0) % 12.0;
let v = l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0);
(v * 255.0).round() as u8
};
format!(
"#{:02x}{:02x}{:02x}",
channel(0.0),
channel(8.0),
channel(4.0)
)
}
}
/// 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: Hsl,
secondary: Hsl,
}
/// 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,
};
let h = (bits.take(9) % 360) as u16;
let s = 50 + 4 * bits.take(3) as u8; // 50..=78
let offset = [0, 40, 320, 180][bits.take(2) as usize];
let primary = Hsl { h, s, l: 48 };
let secondary = Hsl {
h: (h + offset) % 360,
s,
l: 74,
};
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("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
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() {
assert_eq!(
Hsl {
h: 0,
s: 100,
l: 50
}
.hex(),
"#ff0000"
);
assert_eq!(
Hsl {
h: 120,
s: 100,
l: 50
}
.hex(),
"#00ff00"
);
assert_eq!(
Hsl {
h: 240,
s: 100,
l: 25
}
.hex(),
"#000080"
);
assert_eq!(Hsl { h: 0, s: 0, l: 100 }.hex(), "#ffffff");
}
#[test]
fn title_is_escaped() {
let s = Glyphatar::new(b"x").to_svg_with_title(32, "<a & b>");
assert!(s.contains("<title><a & b></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="#bc9938" 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="#99ace1" d="M0 1h1v1h-1zM4 1h1v1h-1zM0 2h1v1h-1zM4 2h1v1h-1z"/></svg>"##;
const ALL_1000: &str = "35afb8e612ec21ad1cbc203c7fe93ed45b192b0081ab5d08d7f3a7620cfcb648";
}