pub const GLYPH_W: usize = 5;
pub const GLYPH_H: usize = 7;
pub const CELL_DOTS: usize = 2;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bitmap {
pub width: usize,
pub height: usize,
pub dots: Vec<bool>,
}
impl Bitmap {
#[inline]
pub fn get(&self, x: usize, y: usize) -> bool {
x < self.width && y < self.height && self.dots[y * self.width + x]
}
pub fn ink(&self) -> usize {
self.dots.iter().filter(|d| **d).count()
}
pub fn ink_extent(&self) -> Option<(usize, usize, usize, usize)> {
let mut bounds: Option<(usize, usize, usize, usize)> = None;
for y in 0..self.height {
for x in 0..self.width {
if !self.get(x, y) {
continue;
}
bounds = Some(match bounds {
None => (x, y, x, y),
Some((x0, y0, x1, y1)) => {
(x0.min(x), y0.min(y), x1.max(x), y1.max(y))
}
});
}
}
bounds
}
}
const ON: char = '#';
#[cfg(test)]
const OFF: char = '.';
const INK: &[(char, [&str; GLYPH_H])] = &[
(
'0',
[
".###.", "#...#", "#..##", "#.#.#", "##..#", "#...#", ".###.",
],
),
(
'1',
[
"..#..", ".##..", "..#..", "..#..", "..#..", "..#..", ".###.",
],
),
(
'2',
[
".###.", "#...#", "....#", "...#.", "..#..", ".#...", "#####",
],
),
(
'3',
[
"#####", "...#.", "..#..", "...#.", "....#", "#...#", ".###.",
],
),
(
'4',
[
"...#.", "..##.", ".#.#.", "#..#.", "#####", "...#.", "...#.",
],
),
(
'5',
[
"#####", "#....", "####.", "....#", "....#", "#...#", ".###.",
],
),
(
'6',
[
"..##.", ".#...", "#....", "####.", "#...#", "#...#", ".###.",
],
),
(
'7',
[
"#####", "....#", "...#.", "..#..", ".#...", ".#...", ".#...",
],
),
(
'8',
[
".###.", "#...#", "#...#", ".###.", "#...#", "#...#", ".###.",
],
),
(
'9',
[
".###.", "#...#", "#...#", ".####", "....#", "...#.", ".##..",
],
),
(
SEPARATOR,
[OFF_STR, OFF_STR, ON_STR, OFF_STR, OFF_STR, ON_STR, OFF_STR],
),
];
const ON_STR: &str = "#";
const OFF_STR: &str = ".";
pub const DIGITS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
pub const SEPARATOR: char = ':';
pub fn cell_width(c: char) -> Option<usize> {
art(c).map(|rows| {
rows.iter()
.map(|row| row.chars().count())
.max()
.unwrap_or(0)
})
}
pub fn bitmap(c: char) -> Option<Bitmap> {
let rows = art(c)?;
let width = rows
.iter()
.map(|row| row.chars().count())
.max()
.unwrap_or(0)
* CELL_DOTS;
let height = GLYPH_H * CELL_DOTS;
let mut dots = vec![false; width * height];
for (cell_y, row) in rows.iter().enumerate() {
for (cell_x, ch) in row.chars().enumerate() {
if ch != ON {
continue;
}
let (x0, y0) = (cell_x * CELL_DOTS, cell_y * CELL_DOTS);
for dy in 0..CELL_DOTS {
for dx in 0..CELL_DOTS {
dots[(y0 + dy) * width + x0 + dx] = true;
}
}
}
}
Some(Bitmap {
width,
height,
dots,
})
}
fn art(c: char) -> Option<&'static [&'static str; GLYPH_H]> {
INK.iter()
.find(|(glyph, _)| *glyph == c)
.map(|(_, rows)| rows)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_font_is_the_digits_and_a_separator_and_nothing_else() {
let listed: Vec<char> = INK.iter().map(|(c, _)| *c).collect();
let mut expected: Vec<char> = DIGITS.to_vec();
expected.push(SEPARATOR);
expected.sort_unstable();
assert_eq!(
listed.len(),
expected.len(),
"the font has {} glyphs, expected {}",
listed.len(),
expected.len()
);
for c in expected {
assert!(
listed.contains(&c),
"{c:?} is missing from the font, or spelled differently"
);
}
assert_eq!(
listed.len(),
11,
"the font grew. It is eleven hand-authored glyphs on purpose, and a \
larger table needs a deliberate decision about reviewing it -- not a \
character added while fixing something else."
);
}
#[test]
fn every_row_of_every_glyph_is_the_same_width() {
const NARROWER: &[(char, usize)] = &[(SEPARATOR, 1)];
for (c, rows) in INK {
let widths: Vec<usize> =
rows.iter().map(|row| row.chars().count()).collect();
let first = widths[0];
for (y, width) in widths.iter().enumerate() {
assert_eq!(
*width, first,
"the {c:?} glyph's row {y} is {width} wide and its row 0 is \
{first}. `bitmap` takes the widest row, so the short row's \
missing cells are drawn as background and the glyph is \
quietly the wrong shape."
);
}
let expected = NARROWER
.iter()
.find(|(glyph, _)| *glyph == *c)
.map(|(_, width)| *width)
.unwrap_or(GLYPH_W);
assert_eq!(
first, expected,
"{c:?} is {first} source cells wide and the design grid is {GLYPH_W}"
);
assert!(
expected <= GLYPH_W,
"{c:?} is listed as narrower than the grid at {expected}, which is \
not narrower"
);
}
}
#[test]
fn the_art_uses_only_ink_and_background() {
for (c, rows) in INK {
for (y, row) in rows.iter().enumerate() {
for (x, ch) in row.chars().enumerate() {
assert!(
ch == ON || ch == OFF,
"the {c:?} glyph has {ch:?} at ({x}, {y}); only {ON:?} and \
{OFF:?} are meaningful"
);
}
}
}
}
#[test]
fn a_source_cell_expands_to_a_square_block_of_dots() {
let zero = bitmap('0').expect("0 is in the font");
assert_eq!(zero.width, GLYPH_W * CELL_DOTS);
assert_eq!(zero.height, GLYPH_H * CELL_DOTS);
for dot_x in 0..zero.width {
let in_source_block = (2..8).contains(&dot_x);
assert_eq!(
zero.get(dot_x, 0),
in_source_block,
"dot ({dot_x}, 0) is {} but three 2x2 blocks from column 2 say it \
should be {}",
zero.get(dot_x, 0),
in_source_block
);
assert_eq!(
zero.get(dot_x, 1),
in_source_block,
"dot ({dot_x}, 1) disagrees with ({dot_x}, 0): the block is not 2x2"
);
}
assert!(zero.get(0, 2), "source row 1 starts with ink");
assert!(!zero.get(2, 2), "source row 1 has a gap in the middle");
let inked_cells = INK
.iter()
.find(|(c, _)| *c == '0')
.map(|(_, rows)| {
rows.iter()
.map(|row| row.chars().filter(|ch| *ch == ON).count())
.sum::<usize>()
})
.expect("0 is in the font");
assert_eq!(
zero.ink(),
inked_cells * CELL_DOTS * CELL_DOTS,
"the rasterised zero has {} dots but its art has {inked_cells} inked \
source cells",
zero.ink()
);
}
#[test]
fn the_colon_is_centred_rather_than_sitting_at_the_extremes() {
let colon = bitmap(SEPARATOR).expect("the separator is in the font");
assert_eq!(
colon.width, CELL_DOTS,
"the colon is one source cell wide, so {} dots across",
CELL_DOTS
);
let raised: Vec<usize> = (0..colon.height)
.filter(|y| (0..colon.width).any(|x| colon.get(x, *y)))
.collect();
assert_eq!(
raised.len(),
2 * CELL_DOTS,
"a colon is two {CELL_DOTS}-dot blocks, got dot rows {raised:?}"
);
let blocks: Vec<&[usize]> = raised.chunks(CELL_DOTS).collect();
assert_eq!(blocks.len(), 2, "the colon is two blocks, got {blocks:?}");
for block in &blocks {
assert_eq!(
block.len(),
CELL_DOTS,
"the colon has a partial block at {block:?}"
);
let top = block[0];
assert!(
(0..colon.width).all(|x| colon.get(x, top)),
"the colon's block at dot row {top} is not {CELL_DOTS} dots wide"
);
}
let (first, second) = (blocks[0][0], blocks[1][0]);
assert!(first > 0, "the colon's first block starts on dot row 0");
assert!(
second + CELL_DOTS <= colon.height,
"the colon's second block runs past the last dot row"
);
assert!(
first < colon.height / 2 && second >= colon.height / 2,
"the colon's blocks start at dot rows {first} and {second}, which are \
both in one half of a {} row glyph",
colon.height
);
assert!(
second >= first + 2 * CELL_DOTS,
"the colon's blocks start at dot rows {first} and {second}, with \
nothing between them"
);
}
#[test]
fn no_glyph_is_empty() {
for c in DIGITS.iter().copied().chain([SEPARATOR]) {
let glyph = bitmap(c).expect("glyph is in the font");
assert!(glyph.ink() > 0, "{c:?} rasterises to nothing");
}
assert!(bitmap('x').is_none(), "'x' is not in the font");
assert!(bitmap(' ').is_none(), "a space is not in the font");
assert!(cell_width('x').is_none());
}
}