spleen_font/lib.rs
1//! # `spleen-font` — tiny `no_std` PSF-2 bitmap‐font reader
2//!
3//! This crate ships the six **Spleen** fixed-width fonts and gives you a
4//! panic-free, heap-free API to render them on any framebuffer.
5//!
6//! ```text
7//! glyph lookup row iterator bit iterator
8//! ┌──────────────┐ ┌────────────────┐ ┌──────────────────┐
9//! UTF-8 ──► `PSF2Font` ──────► `Glyph<'_>` ───────► `GlyphRow<'_>` ─────► bool
10//! │ (cache) │ │ one scan-line │ │ one pixel (fg/bg)│
11//! └──────────────┘ └────────────────┘ └──────────────────┘
12//! ```
13//!
14//! ## Features
15//!
16//! * **`no_std`**, zero allocations – suitable for kernels and bootloaders.
17//! * Constant-time glyph lookup for ASCII and cached Unicode.
18//! * < 2 KiB RAM: 64-entry ring cache + iterator state.
19//! * Exposes only data; pixel drawing/framebuffer manipulation is left to the user.
20//!
21//! ## Quick start
22//! This example assumes that you have a framebuffer and a function to set pixels.
23//!
24//! ```rust
25//! fn main() {
26//! // only compiled & run when `s8x16` is enabled
27//! #[cfg(feature = "s8x16")] {
28//! use spleen_font::{PSF2Font, FONT_8X16};
29//! fn set_pixel(_: &mut [u8], _: usize, _: usize, _: bool) { }
30//!
31//! let mut font = PSF2Font::new(FONT_8X16).unwrap();
32//! let mut framebuffer = [0u8; 1024];
33//!
34//! if let Some(glyph) = font.glyph_for_utf8("é".as_bytes()) {
35//! for (row_y, row) in glyph.enumerate() {
36//! for (col_x, on) in row.enumerate() {
37//! set_pixel(&mut framebuffer, col_x, row_y, on);
38//! }
39//! }
40//! }
41//! }
42//! }
43//! ```
44//!
45//! To test this example, run:
46//!
47//! ```text
48//! cargo test --doc --features s8x16
49//! ```
50//!
51//! ## Feature gates
52//!
53//! To reduce the overall footprint, each of the six fonts is gated behind a feature. Note that while this does not reduce the size of the crate on crates.io, it does reduce the size of the compiled binary - only the blob for the selected font you enable will be included in the final binary.
54//!
55//! Feature | Enables constant | Size (KiB)
56//! |---------|-----------|--------------------|
57//! s5x8 | FONT_5X8 | 2 KiB
58//! s6x12 | FONT_6X12 | 6 KiB
59//! s8x16 | FONT_8X16 | 4 KiB
60//! s12x24 | FONT_12X24 | 12 KiB
61//! s16x32 | FONT_16X32 | 32 KiB
62//! s32x64 | FONT_32X64 | 128 KiB
63//! all | all of the above | 184 KiB
64//!
65//! Each entry is a raw byte slice **`&[u8]`** where the slice is the raw PSF-2 file embedded via `include_bytes!`.
66//!
67//! By default, no font is enabled. Enabling a font in your Cargo.toml should look like this:
68//!
69//! ```toml
70//! [dependencies]
71//! spleen-font = { version = "0.1", features = ["s8x16"] }
72//! ```
73//!
74//! ## Re-exports
75//!
76//! * [`PSF2Font`] — loader + glyph/Unicode lookup.
77//! * [`Glyph`] / [`GlyphRow`] — iterators over rows and pixels.
78//!
79//! ## Bundled fonts
80//!
81//! | variant | size (px) | index in [`FONTS`] |
82//! |---------|-----------|--------------------|
83//! | `S5x8` | 5 × 8 | 0 |
84//! | `S6x12` | 6 × 12| 1 |
85//! | `S8x16` | 8 × 16| 2 |
86//! | `S12x24`| 12 × 24| 3 |
87//! | `S16x32`| 16 × 32| 4 |
88//! | `S32x64`| 32 × 64| 5 |
89//!
90//! Each entry is a tuple **`(&[u8], Size)`** where the slice is the raw PSF-2
91//! file embedded via `include_bytes!`.
92//!
93//! ---
94//!
95//! *Spleen font Copyright (c) 2018-2024, Frederic Cambus, BSD2 License*
96//!
97//! **.psfu files obtained from https://github.com/fcambus/spleen*
98
99#![no_std]
100
101mod cache;
102pub mod glyph;
103pub mod psf;
104
105pub use glyph::{Glyph, GlyphRow};
106pub use psf::{PSF2Font, PSF2Header, PSF2_MAGIC};
107
108/// Logical name for each embedded Spleen size.
109pub enum Size {
110 S5x8,
111 S6x12,
112 S8x16,
113 S12x24,
114 S16x32,
115 S32x64,
116}
117
118#[cfg(feature = "s5x8")]
119pub const FONT_5X8: &[u8] = include_bytes!("../fonts/spleen-5x8.psfu");
120#[cfg(feature = "s6x12")]
121pub const FONT_6X12: &[u8] = include_bytes!("../fonts/spleen-6x12.psfu");
122#[cfg(feature = "s8x16")]
123pub const FONT_8X16: &[u8] = include_bytes!("../fonts/spleen-8x16.psfu");
124#[cfg(feature = "s12x24")]
125pub const FONT_12X24: &[u8] = include_bytes!("../fonts/spleen-12x24.psfu");
126#[cfg(feature = "s16x32")]
127pub const FONT_16X32: &[u8] = include_bytes!("../fonts/spleen-16x32.psfu");
128#[cfg(feature = "s32x64")]
129pub const FONT_32X64: &[u8] = include_bytes!("../fonts/spleen-32x64.psfu");
130
131#[cfg(feature = "all")]
132pub static FONTS: &[(&[u8], Size)] = &[
133 (include_bytes!("../fonts/spleen-5x8.psfu"), Size::S5x8),
134 (include_bytes!("../fonts/spleen-6x12.psfu"), Size::S6x12),
135 (include_bytes!("../fonts/spleen-8x16.psfu"), Size::S8x16),
136 (include_bytes!("../fonts/spleen-12x24.psfu"), Size::S12x24),
137 (include_bytes!("../fonts/spleen-16x32.psfu"), Size::S16x32),
138 (include_bytes!("../fonts/spleen-32x64.psfu"), Size::S32x64),
139];
140
141#[cfg(test)]
142pub static FONTS: &[(&[u8], Size)] = &[
143 (include_bytes!("../fonts/spleen-5x8.psfu"), Size::S5x8),
144 (include_bytes!("../fonts/spleen-6x12.psfu"), Size::S6x12),
145 (include_bytes!("../fonts/spleen-8x16.psfu"), Size::S8x16),
146 (include_bytes!("../fonts/spleen-12x24.psfu"), Size::S12x24),
147 (include_bytes!("../fonts/spleen-16x32.psfu"), Size::S16x32),
148 (include_bytes!("../fonts/spleen-32x64.psfu"), Size::S32x64),
149];
150
151#[cfg(test)]
152extern crate std;
153
154#[cfg(test)]
155use std::vec::Vec;
156
157#[cfg(test)]
158mod test {
159 use super::*;
160
161 #[test]
162 fn header_round_trip() {
163 let (blob, _) = FONTS[1]; // 8×16 face
164 let hdr = PSF2Header::from_bytes(&blob[..32]).unwrap();
165
166 assert_eq!(hdr.magic, PSF2_MAGIC);
167 assert_eq!(hdr.version, 0);
168 assert_eq!(hdr.header_size, 32);
169 assert!(hdr.width > 0 && hdr.height > 0);
170 assert_eq!(hdr.bytes_per_glyph, ((hdr.width + 7) >> 3) * hdr.height);
171 }
172
173 #[test]
174 fn header_rejects_invalid_magic() {
175 let mut bad = FONTS[0].0.to_vec();
176 bad[0] = 0; // corrupt magic
177 assert!(PSF2Header::from_bytes(&bad).is_err());
178 }
179
180 #[test]
181 fn open_font_and_first_last_glyph() {
182 let (blob, _) = FONTS[1]; // 6×12
183 let font = PSF2Font::new(blob).unwrap();
184
185 // First glyph should be 0 and not empty.
186 assert!(!font.glyph_by_idx(0).unwrap().is_empty());
187
188 // Last glyph index = num_glyphs - 1
189 let last = font.glyph_by_idx(font.num_glyphs - 1).unwrap();
190 assert_eq!(last.len(), font.bytes_per_glyph as usize);
191
192 // Out-of-range must be None (overflow-safe)
193 assert!(font.glyph_by_idx(font.num_glyphs).is_none());
194 }
195
196 // ASCII fast path and cache hit
197 #[test]
198 fn ascii_fast_then_cached() {
199 let (blob, _) = FONTS[2]; // 8×16
200 let mut font = PSF2Font::new(blob).unwrap();
201
202 // first call -> cold (fills cache)
203 let g1 = font.get_glyph_data(&[b'A']).unwrap();
204 // second call -> cache hit
205 let g2 = font.get_glyph_data(&[b'A']).unwrap();
206 assert!(core::ptr::eq(g1.as_ptr(), g2.as_ptr()));
207 }
208
209 // Unicode lookup (é) & iterator correctness
210 #[test]
211 fn unicode_lookup_and_iter() {
212 let (blob, _) = FONTS[0]; // 5x8
213 let mut font = PSF2Font::new(blob).unwrap();
214 let mut tmp = [0; 2];
215 let utf8 = 'é'.encode_utf8(&mut tmp);
216
217 let glyph = font.glyph_for_utf8(utf8.as_bytes()).expect("é present");
218
219 // Glyph MUST yield exactly height rows
220 assert_eq!(glyph.len(), font.height as usize);
221
222 // Every row must yield exactly width bits
223 for row in glyph.clone() {
224 assert_eq!(row.len(), font.width as usize);
225 }
226
227 // Forward → collect() then reverse → collect_rev() must match
228 let forward: Vec<bool> = glyph.clone().flat_map(|r| r).collect();
229 let reverse: Vec<bool> = glyph.rev().flat_map(|r| r).collect();
230 let mut rev2 = reverse.clone();
231 rev2.reverse();
232 assert_eq!(forward, rev2);
233 }
234}