SHX fonts: shape source finds a repeated shape number with a set, not a scan

Each definition was compared with every one before it: 65,535 shapes (an 821 KB source)
took 2.8 s to compile. The error still names the line of the repeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mo
2026-11-04 23:53:42 -05:00
co-authored by Claude Opus 5.5
parent b439879181
commit bb91014ebd
2 changed files with 13 additions and 1 deletions
+4 -1
View File
@@ -12,6 +12,8 @@
//! direction byte (`-043`) keeps its sign in the high bit. `defbytes` is not checked: the
//! program's own length is written.
use std::collections::HashSet;
use super::ShxError;
use super::parse::{BIGFONT, SHAPES_10, UNIFONT};
@@ -228,6 +230,7 @@ pub fn compile(source: &str) -> Result<Vec<u8>, ShxError> {
}
}
let mut shapes: Vec<Shape> = Vec::new();
let mut seen = HashSet::new();
for (num, name, line, toks) in defs {
let number = u16::try_from(num).map_err(|_| ShxError::Source(line, format!("shape number {num} out of range")))?;
let program = if number == 0 {
@@ -236,7 +239,7 @@ pub fn compile(source: &str) -> Result<Vec<u8>, ShxError> {
} else {
Enc { toks: &toks, i: 0, out: Vec::new(), kind, line }.program()?
};
if shapes.iter().any(|s| s.number == number) {
if !seen.insert(number) {
return Err(ShxError::Source(line, format!("shape {number} is defined twice")));
}
shapes.push(Shape { number, name, program });
+9
View File
@@ -373,6 +373,15 @@ fn a_name_is_looked_for_in_its_first_kilobyte_only() {
assert_eq!(ShxFont::parse(&big).err(), Some(ShxError::Empty));
}
#[test]
fn all_65535_shape_numbers_compile_and_a_repeat_is_found() {
// Hostile: each of 65,535 definitions was compared with all before it, 2.8 s for an 821 KB
// source.
let src: String = (1..=65535u32).map(|n| format!("*{n},1,X\n0\n")).collect();
assert_eq!(ShxFont::parse(&compile(&src).unwrap()).unwrap().shape_count(), 65535);
assert_eq!(compile("*1,1,X\n0\n*2,1,Y\n0\n*1,1,Z\n0\n").err(), Some(ShxError::Source(5, "shape 1 is defined twice".into())));
}
#[test]
fn a_doubled_minus_sign_is_not_a_number() {
// Hostile: the digits after the sign were themselves negative, down to i64::MIN; as a big