diff --git a/crates/fonts/src/shx/compile.rs b/crates/fonts/src/shx/compile.rs index 3b31562dc..efc4cf57d 100644 --- a/crates/fonts/src/shx/compile.rs +++ b/crates/fonts/src/shx/compile.rs @@ -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, ShxError> { } } let mut shapes: Vec = 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, 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 }); diff --git a/crates/fonts/src/shx/tests.rs b/crates/fonts/src/shx/tests.rs index df0dd9aca..fa28fd73d 100644 --- a/crates/fonts/src/shx/tests.rs +++ b/crates/fonts/src/shx/tests.rs @@ -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