Merge pull request #1605 from storytold/extract/shx-compiler

shx: extract CADCraft SHP to SHX compiler
This commit is contained in:
FredApps
2026-11-16 02:32:29 +01:00
committed by GitHub
10 changed files with 1316 additions and 0 deletions
Generated
+4
View File
@@ -2661,6 +2661,10 @@ dependencies = [
name = "craft-sheet"
version = "0.1.0"
[[package]]
name = "craft-shx"
version = "0.1.0"
[[package]]
name = "craft-silhouette-studio"
version = "0.1.0"
+1
View File
@@ -11,6 +11,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/craft-libs"
[workspace.dependencies]
craft-shx = { path = "crates/shx" }
craft-http-url = { path = "crates/http-url" }
craft-usd = { path = "crates/usd" }
craft-smime = { path = "crates/smime" }
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "craft-shx"
description = "Bounded SHP shape-source compiler for SHX shape, big-font and Unicode containers"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
+8
View File
@@ -0,0 +1,8 @@
# craft-shx
Compiles SHP shape source into SHX shapes, big-font and Unicode containers.
Extracted from CADCraft by Francesco BV (cadcraft52c1e6de); no font assets are bundled.
App font discovery, text layout and glyph interpretation are not part of this crate.
The original 8 MiB source and u16 record bounds remain; malformed double signs,
excess escape ranges and oversized Unicode font records are refused. Duplicate
shape detection is linear rather than a repeated whole-list scan.
+327
View File
@@ -0,0 +1,327 @@
//! Shape source (`.shp`) to a compiled SHX file, as COMPILE does.
//!
//! A source is a list of definitions: a header line `*number,defbytes,NAME` followed by its
//! specification bytes (on as many lines as needed, ending with 0). Numbers are decimal, or
//! hexadecimal after a leading `0` (`012`, `08cfb`); parentheses only group; `;` starts a
//! comment. A big font starts with `*BIGFONT nchars,nranges,first,last,…` and a Unicode font
//! with `*UNIFONT,6,name` followed by `above,below,modes,encoding,type,0`. Shape 0 is a text
//! font's record (`above,below,modes,0`).
//!
//! Operands are encoded by what they are: a subshape number takes two bytes in a Unicode font
//! (and after `7,0` in a big font), displacements and bulges are two's complement, and an arc's
//! direction byte (`-043`) keeps its sign in the high bit. `defbytes` is not checked: the
//! program's own length is written.
use super::ShxError;
const SHAPES_10: &[u8] = b"AutoCAD-86 shapes 1.0\r\n\x1a";
const BIGFONT: &[u8] = b"AutoCAD-86 bigfont 1.0\r\n\x1a";
const UNIFONT: &[u8] = b"AutoCAD-86 unifont 1.0\r\n\x1a";
/// Largest source compiled.
const MAX_SOURCE: usize = 8 << 20;
#[derive(Clone, Copy, PartialEq)]
enum Kind {
Shapes,
Big,
Uni,
}
struct Shape {
number: u16,
name: String,
program: Vec<u8>,
}
/// A number token: value (sign included).
fn number(tok: &str, line: usize) -> Result<i64, ShxError> {
let t: String = tok.chars().filter(|c| !matches!(c, '(' | ')') && !c.is_whitespace()).collect();
let (neg, digits) = match t.strip_prefix('-') {
Some(d) => (true, d),
None => (false, t.strip_prefix('+').unwrap_or(&t)),
};
let err = || ShxError::Source(line, format!("not a number: {tok:?}"));
let v = if digits.len() > 1 && digits.starts_with('0') {
i64::from_str_radix(digits.get(1..).unwrap_or_default(), 16).map_err(|_| err())?
} else {
digits.parse::<i64>().map_err(|_| err())?
};
if !(0..=0xFFFF).contains(&v) {
return Err(err());
}
Ok(if neg { -v } else { v })
}
/// The comma-separated numbers of a line (comment removed, blank fields skipped).
fn numbers(text: &str, line: usize) -> Result<Vec<i64>, ShxError> {
text.split(',').map(str::trim).filter(|t| !t.is_empty() && *t != "(" && *t != ")").map(|t| number(t, line)).collect()
}
/// The spec-byte encoder: walks the tokens as the reader walks the bytes.
struct Enc<'a> {
toks: &'a [i64],
i: usize,
out: Vec<u8>,
kind: Kind,
line: usize,
}
impl Enc<'_> {
fn next(&mut self) -> Result<i64, ShxError> {
let v = self.toks.get(self.i).copied().ok_or_else(|| ShxError::Source(self.line, "the shape ends inside a command".into()))?;
self.i += 1;
Ok(v)
}
fn byte(&mut self) -> Result<(), ShxError> {
let v = self.next()?;
let b = u8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a byte")))?;
self.out.push(b);
Ok(())
}
/// Two's complement −128..127.
fn signed(&mut self) -> Result<i64, ShxError> {
let v = self.next()?;
let b = i8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not −128..127")))?;
self.out.extend(b.to_le_bytes());
Ok(v)
}
/// Sign in the high bit (an arc's direction byte).
fn sign_magnitude(&mut self) -> Result<(), ShxError> {
let v = self.next()?;
let m = u8::try_from(v.unsigned_abs())
.ok()
.filter(|m| *m < 0x80)
.ok_or_else(|| ShxError::Source(self.line, format!("{v} is not an octant byte")))?;
self.out.push(if v < 0 { m | 0x80 } else { m });
Ok(())
}
fn word(&mut self) -> Result<(), ShxError> {
let v = self.next()?;
let w = u16::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a shape number")))?;
self.out.extend(w.to_be_bytes());
Ok(())
}
fn program(mut self) -> Result<Vec<u8>, ShxError> {
while self.i < self.toks.len() {
let code = self.next()?;
let c = u8::try_from(code).map_err(|_| ShxError::Source(self.line, format!("{code} is not a code")))?;
self.out.push(c);
match c {
0 => break,
3 | 4 => self.byte()?,
7 => match self.kind {
Kind::Uni => self.word()?,
Kind::Big => {
let first = self.toks.get(self.i).copied().unwrap_or(0);
if first == 0 {
self.byte()?;
self.word()?;
for _ in 0..4 {
self.byte()?;
}
} else {
self.byte()?;
}
}
Kind::Shapes => self.byte()?,
},
8 => {
self.signed()?;
self.signed()?;
}
9 => loop {
let (x, y) = (self.signed()?, self.signed()?);
if x == 0 && y == 0 {
break;
}
},
10 => {
self.byte()?;
self.sign_magnitude()?;
}
11 => {
for _ in 0..4 {
self.byte()?;
}
self.sign_magnitude()?;
}
12 => {
for _ in 0..3 {
self.signed()?;
}
}
13 => loop {
let (x, y) = (self.signed()?, self.signed()?);
if x == 0 && y == 0 {
break;
}
self.signed()?;
},
_ => {}
}
}
if self.out.last() != Some(&0) {
self.out.push(0);
}
Ok(self.out)
}
}
/// Compile shape source into an SHX file (a shape file or text font, a big font, or a Unicode
/// font, as its first definition says).
pub fn compile(source: &str) -> Result<Vec<u8>, ShxError> {
if source.len() > MAX_SOURCE {
return Err(ShxError::TooLarge);
}
let mut kind = Kind::Shapes;
let mut ranges: Vec<(u16, u16)> = Vec::new();
let mut uni_info: Option<(String, Vec<u8>)> = None;
// Definitions: header (number, name, line) and the numbers that follow it.
let mut defs: Vec<(i64, String, usize, Vec<i64>)> = Vec::new();
let mut uni_header_pending = false;
for (no, raw) in source.lines().enumerate() {
let line = no + 1;
let text = raw.split(';').next().unwrap_or_default().trim();
if text.is_empty() {
continue;
}
if let Some(head) = text.strip_prefix('*') {
let upper = head.trim_start().to_ascii_uppercase();
if let Some(rest) = upper.strip_prefix("BIGFONT") {
kind = Kind::Big;
let v = numbers(rest, line)?;
let n = usize::try_from(v.get(1).copied().unwrap_or(0)).unwrap_or(0);
// A big font has byte-valued lead ranges. Bound repeated headers too,
// so a tiny declaration cannot amplify into millions of ranges.
if n > 256 || ranges.len().saturating_add(n) > 256 {
return Err(ShxError::TooLarge);
}
for k in 0..n {
let lo = v.get(2 + 2 * k).copied().unwrap_or(0);
let hi = v.get(3 + 2 * k).copied().unwrap_or(lo);
let to = |x: i64| u16::try_from(x).map_err(|_| ShxError::Source(line, "bad escape range".into()));
ranges.push((to(lo)?, to(hi)?));
}
continue;
}
if upper.starts_with("UNIFONT") {
kind = Kind::Uni;
let name = head.splitn(3, ',').nth(2).unwrap_or_default().trim().to_string();
uni_info = Some((name, Vec::new()));
uni_header_pending = true;
continue;
}
uni_header_pending = false;
let mut parts = head.splitn(3, ',');
let num = number(parts.next().unwrap_or_default().trim(), line)?;
let _defbytes = parts.next();
let name = parts.next().unwrap_or_default().trim().to_string();
if defs.len() >= usize::from(u16::MAX) {
return Err(ShxError::TooLarge);
}
defs.push((num, name, line, Vec::new()));
continue;
}
let v = numbers(text, line)?;
if uni_header_pending {
if let Some((_, info)) = uni_info.as_mut() {
for x in v {
info.push(u8::try_from(x).map_err(|_| ShxError::Source(line, "bad font record".into()))?);
}
}
continue;
}
match defs.last_mut() {
Some(d) => d.3.extend(v),
None => return Err(ShxError::Source(line, "specification bytes before any *number,defbytes,NAME line".into())),
}
}
let mut shapes: Vec<Shape> = Vec::new();
let mut seen = std::collections::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 {
// The font record: plain bytes.
toks.iter().map(|x| u8::try_from(*x).map_err(|_| ShxError::Source(line, "bad font record".into()))).collect::<Result<Vec<u8>, _>>()?
} else {
Enc { toks: &toks, i: 0, out: Vec::new(), kind, line }.program()?
};
if !seen.insert(number) {
return Err(ShxError::Source(line, format!("shape {number} is defined twice")));
}
shapes.push(Shape { number, name, program });
}
if shapes.is_empty() {
return Err(ShxError::Empty);
}
shapes.sort_by_key(|s| s.number);
let record = |s: &Shape| -> Result<Vec<u8>, ShxError> {
let mut r: Vec<u8> = s.name.bytes().filter(|b| *b != 0).collect();
r.push(0);
r.extend(&s.program);
if r.len() > usize::from(u16::MAX) { Err(ShxError::TooLarge) } else { Ok(r) }
};
let count = u16::try_from(shapes.len()).map_err(|_| ShxError::TooLarge)?;
let len16 = |r: &[u8]| u16::try_from(r.len()).unwrap_or(u16::MAX);
let mut out = Vec::new();
match kind {
Kind::Shapes => {
out.extend(SHAPES_10);
out.extend(shapes.first().map_or(0, |s| s.number).to_le_bytes());
out.extend(shapes.last().map_or(0, |s| s.number).to_le_bytes());
out.extend(count.to_le_bytes());
let recs: Vec<Vec<u8>> = shapes.iter().map(record).collect::<Result<_, _>>()?;
for (s, r) in shapes.iter().zip(&recs) {
out.extend(s.number.to_le_bytes());
out.extend(len16(r).to_le_bytes());
}
for r in &recs {
out.extend(r);
}
out.extend(b"EOF");
}
Kind::Big => {
out.extend(BIGFONT);
let nranges = u16::try_from(ranges.len()).map_err(|_| ShxError::TooLarge)?;
out.extend(count.to_le_bytes());
out.extend(count.to_le_bytes());
out.extend(nranges.to_le_bytes());
for (lo, hi) in &ranges {
out.extend(lo.to_le_bytes());
out.extend(hi.to_le_bytes());
}
let recs: Vec<Vec<u8>> = shapes.iter().map(record).collect::<Result<_, _>>()?;
let mut off = out.len() + 8 * recs.len();
for (s, r) in shapes.iter().zip(&recs) {
out.extend(s.number.to_le_bytes());
out.extend(len16(r).to_le_bytes());
out.extend(u32::try_from(off).map_err(|_| ShxError::TooLarge)?.to_le_bytes());
off += r.len();
}
for r in &recs {
out.extend(r);
}
}
Kind::Uni => {
out.extend(UNIFONT);
let (name, info) = uni_info.unwrap_or_default();
out.extend((u32::from(count) + 1).to_le_bytes());
if name.len().saturating_add(1).saturating_add(info.len()) > usize::from(u16::MAX) {
return Err(ShxError::TooLarge);
}
let mut rec: Vec<u8> = name.bytes().filter(|b| *b != 0).collect();
rec.push(0);
rec.extend(&info);
out.extend(len16(&rec).to_le_bytes());
out.extend(&rec);
for s in &shapes {
let r = record(s)?;
out.extend(s.number.to_le_bytes());
out.extend(len16(&r).to_le_bytes());
out.extend(r);
}
}
}
Ok(out)
}
+28
View File
@@ -0,0 +1,28 @@
/// Why a font file can't be read or a shape source can't be compiled.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ShxError {
/// Not an SHX file (unknown signature).
NotShx,
/// The file ends inside its header or index.
Truncated,
/// The file is larger, or has more of something, than CADCraft reads.
TooLarge,
/// The file is well-formed but holds no shape.
Empty,
/// Shape source error: line and message.
Source(usize, String),
}
impl std::fmt::Display for ShxError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ShxError::NotShx => f.write_str("not an SHX shape or font file"),
ShxError::Truncated => f.write_str("the SHX file is truncated"),
ShxError::TooLarge => f.write_str("the SHX file is too large"),
ShxError::Empty => f.write_str("the SHX file has no shapes"),
ShxError::Source(line, msg) => write!(f, "line {line}: {msg}"),
}
}
}
impl std::error::Error for ShxError {}
+11
View File
@@ -0,0 +1,11 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
//! SHP source compilation to SHX containers, extracted from CADCraft.
//! Font discovery, glyph execution and text layout remain consumer responsibilities.
mod compile;
mod error;
pub mod parse;
pub mod program;
pub use compile::compile;
pub use error::ShxError;
pub use parse::{ParsedFont, Record, ShxKind};
+281
View File
@@ -0,0 +1,281 @@
//! Reading the compiled SHX containers (layouts in the module documentation). Every count and
//! offset comes from the file, so each is checked against its length; records that run past
//! the end are dropped and the rest kept.
use super::ShxError;
use std::collections::HashMap;
/// The SHX container kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShxKind {
Shapes,
BigFont,
Unifont,
}
/// Byte ranges of one shape name and pen program in [`ParsedFont::data`].
#[derive(Clone, Copy, Debug)]
pub struct Record {
pub name: (usize, usize),
pub program: (usize, usize),
}
/// Decoded container records and metrics; glyph execution remains a caller concern.
pub struct ParsedFont {
pub kind: ShxKind,
pub name: String,
pub header: bool,
pub above: f64,
pub below: f64,
pub dual: bool,
pub encoding: u8,
pub char_width: f64,
pub ranges: Vec<(u16, u16)>,
pub data: Vec<u8>,
pub records: HashMap<u16, Record>,
}
pub const SHAPES_10: &[u8] = b"AutoCAD-86 shapes 1.0\r\n\x1a";
pub const SHAPES_11: &[u8] = b"AutoCAD-86 shapes 1.1\r\n\x1a";
pub const BIGFONT: &[u8] = b"AutoCAD-86 bigfont 1.0\r\n\x1a";
pub const UNIFONT: &[u8] = b"AutoCAD-86 unifont 1.0\r\n\x1a";
/// Largest file read (the largest big fonts are a few megabytes).
pub const MAX_FILE_BYTES: usize = 32 << 20;
/// Most escape ranges in a big font (lead bytes: at most 256).
const MAX_RANGES: usize = 256;
/// A checked little-endian reader.
struct Rd<'a> {
b: &'a [u8],
pos: usize,
}
impl<'a> Rd<'a> {
fn take(&mut self, n: usize) -> Result<&'a [u8], ShxError> {
let end = self.pos.checked_add(n).ok_or(ShxError::Truncated)?;
let s = self.b.get(self.pos..end).ok_or(ShxError::Truncated)?;
self.pos = end;
Ok(s)
}
fn u16(&mut self) -> Result<u16, ShxError> {
match self.take(2)? {
[a, b] => Ok(u16::from_le_bytes([*a, *b])),
_ => Err(ShxError::Truncated),
}
}
fn u32(&mut self) -> Result<u32, ShxError> {
match self.take(4)? {
[a, b, c, d] => Ok(u32::from_le_bytes([*a, *b, *c, *d])),
_ => Err(ShxError::Truncated),
}
}
}
/// A font being read.
struct Font {
kind: ShxKind,
name: String,
header: bool,
above: f64,
below: f64,
dual: bool,
encoding: u8,
char_width: f64,
ranges: Vec<(u16, u16)>,
records: HashMap<u16, Record>,
}
impl Font {
fn new(kind: ShxKind) -> Font {
Font {
kind,
name: String::new(),
header: false,
above: 0.0,
below: 0.0,
dual: false,
encoding: 0,
char_width: 0.0,
ranges: Vec::new(),
records: HashMap::new(),
}
}
/// Add the record of shape `number` at `start..end` of `data`: a NUL-terminated name, then
/// the program. Shape 0 is the font record. A record without a name terminator is dropped;
/// the first record of a number wins.
fn record(&mut self, data: &[u8], number: u16, start: usize, end: usize) {
let Some(bytes) = data.get(start..end) else { return };
let Some(nul) = bytes.iter().position(|b| *b == 0) else { return };
let name = (start, start + nul);
let program = (start + nul + 1, end);
if number == 0 {
if !self.header {
self.font_record(data.get(program.0..program.1).unwrap_or_default(), data.get(name.0..name.1).unwrap_or_default());
}
return;
}
self.records.entry(number).or_insert(Record { name, program });
}
/// The font record: above, below, modes (and for a unifont encoding and embedding); an
/// extended big font's is character height, 0, modes, character width.
fn font_record(&mut self, info: &[u8], name: &[u8]) {
self.header = true;
self.name = name.iter().take(255).map(|c| char::from(*c)).collect();
let byte = |i: usize| info.get(i).copied().unwrap_or(0);
self.above = f64::from(byte(0));
self.below = f64::from(byte(1));
self.dual = byte(2) == 2;
if self.kind == ShxKind::Unifont {
self.encoding = byte(3);
}
if self.kind == ShxKind::BigFont && info.len() >= 5 && byte(1) == 0 {
// Extended: height, 0, modes, width, 0.
self.below = 0.0;
self.char_width = f64::from(byte(3));
}
}
fn finish(self, data: Vec<u8>) -> Result<ParsedFont, ShxError> {
if self.records.is_empty() {
return Err(ShxError::Empty);
}
Ok(ParsedFont {
kind: self.kind,
name: self.name,
header: self.header,
above: self.above,
below: self.below,
dual: self.dual,
encoding: self.encoding,
char_width: if self.char_width > 0.0 { self.char_width } else { self.above },
ranges: self.ranges,
data,
records: self.records,
})
}
}
pub fn parse(bytes: &[u8]) -> Result<ParsedFont, ShxError> {
if bytes.len() > MAX_FILE_BYTES {
return Err(ShxError::TooLarge);
}
if bytes.starts_with(SHAPES_10) || bytes.starts_with(SHAPES_11) {
shapes(bytes)
} else if bytes.starts_with(BIGFONT) {
bigfont(bytes)
} else if bytes.starts_with(UNIFONT) {
unifont(bytes)
} else {
Err(ShxError::NotShx)
}
}
fn shapes(bytes: &[u8]) -> Result<ParsedFont, ShxError> {
let mut r = Rd { b: bytes, pos: SHAPES_10.len() };
let _first = r.u16()?;
let _last = r.u16()?;
let count = usize::from(r.u16()?);
// The whole index must be there before anything is read from it.
let index = r.take(count.checked_mul(4).ok_or(ShxError::TooLarge)?)?;
let mut f = Font::new(ShxKind::Shapes);
let mut pos = r.pos;
for [a, b, c, d] in index.as_chunks::<4>().0 {
let (number, len) = (u16::from_le_bytes([*a, *b]), usize::from(u16::from_le_bytes([*c, *d])));
let Some(end) = pos.checked_add(len).filter(|e| *e <= bytes.len()) else { break };
f.record(bytes, number, pos, end);
pos = end;
}
f.finish(bytes.to_vec())
}
fn bigfont(bytes: &[u8]) -> Result<ParsedFont, ShxError> {
let mut r = Rd { b: bytes, pos: BIGFONT.len() };
let index_size = usize::from(r.u16()?);
let count = usize::from(r.u16()?);
let nranges = usize::from(r.u16()?);
if nranges > MAX_RANGES {
return Err(ShxError::TooLarge);
}
let mut f = Font::new(ShxKind::BigFont);
for _ in 0..nranges {
let (lo, hi) = (r.u16()?, r.u16()?);
f.ranges.push((lo.min(hi), lo.max(hi)));
}
// The index has `count` entries of 8 bytes; a file whose count doesn't fit but whose index
// size does is read by that.
let fits = |n: usize| n.checked_mul(8).and_then(|l| r.pos.checked_add(l)).is_some_and(|e| e <= bytes.len());
let n = if fits(count) {
count
} else if fits(index_size) {
index_size
} else {
return Err(ShxError::Truncated);
};
let index = r.take(n.checked_mul(8).ok_or(ShxError::TooLarge)?)?;
for [a, b, c, d, o0, o1, o2, o3] in index.as_chunks::<8>().0 {
let number = u16::from_le_bytes([*a, *b]);
let len = usize::from(u16::from_le_bytes([*c, *d]));
let Ok(off) = usize::try_from(u32::from_le_bytes([*o0, *o1, *o2, *o3])) else { continue };
if len == 0 {
continue;
}
let Some(end) = off.checked_add(len).filter(|e| *e <= bytes.len()) else { continue };
f.record(bytes, number, off, end);
}
f.finish(bytes.to_vec())
}
fn unifont(bytes: &[u8]) -> Result<ParsedFont, ShxError> {
let mut r = Rd { b: bytes, pos: UNIFONT.len() };
let count = r.u32()?;
let info_len = usize::from(r.u16()?);
let info = r.take(info_len)?;
let mut f = Font::new(ShxKind::Unifont);
let nul = info.iter().position(|b| *b == 0).unwrap_or(info.len());
f.font_record(info.get(nul.saturating_add(1)..).unwrap_or_default(), info.get(..nul).unwrap_or_default());
// `count` includes the font record; never trusted beyond the data that is there.
let mut left = count.saturating_sub(1);
while left > 0 {
left -= 1;
let Ok(number) = r.u16() else { break };
let Ok(len) = r.u16().map(usize::from) else { break };
let start = r.pos;
let Some(end) = start.checked_add(len).filter(|e| *e <= bytes.len()) else { break };
r.pos = end;
f.record(bytes, number, start, end);
}
f.finish(bytes.to_vec())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn reads_shapes_bigfont_and_unifont_records() {
for (source, kind, shape) in [
("*0,4,font\n6,2,2,0\n*65,4,A\n1,064,0\n", ShxKind::Shapes, 65),
("*BIGFONT 2,1,081,09F\n*0,4,big\n8,0,0,0\n*082A0,4,square\n1,080,0\n", ShxKind::BigFont, 0x82a0),
("*UNIFONT,6,uni\n6,2,0,0,0,0\n*00041,4,a\n1,064,0\n", ShxKind::Unifont, 65),
] {
let bytes = crate::compile(source).unwrap();
let font = parse(&bytes).unwrap();
assert_eq!(font.kind, kind);
assert!(font.header);
let record = font.records.get(&shape).unwrap();
assert_eq!(font.data.get(record.program.1 - 1), Some(&0));
}
}
#[test]
fn truncation_limits_and_unknown_signatures_are_errors() {
assert!(matches!(parse(b"not a font"), Err(ShxError::NotShx)));
assert!(matches!(parse(&vec![0; MAX_FILE_BYTES + 1]), Err(ShxError::TooLarge)));
let mut shapes = SHAPES_10.to_vec();
shapes.extend([1, 0, 255, 255, 255, 255]);
assert!(matches!(parse(&shapes), Err(ShxError::Truncated)));
let mut big = BIGFONT.to_vec();
big.extend([255, 255, 255, 255, 255, 255]);
assert!(matches!(parse(&big), Err(ShxError::TooLarge)));
}
}
+536
View File
@@ -0,0 +1,536 @@
//! The shape pen program: vector length/direction bytes and special codes 0–14, run into
//! polylines. Bounded everywhere: subshape depth, location stack, steps, points, coordinates.
//!
//! - A byte with a non-zero high nibble is a vector: length (high nibble) in one of 16
//! directions (low nibble, counter-clockwise from east in 22.5° steps; the off-axis ones
//! are half-unit or unit steps on the minor axis).
//! - 0 end, 1 pen down, 2 pen up, 3/4 divide/multiply vector lengths by the next byte,
//! 5/6 push/pop the location, 7 subshape (one byte; two bytes high first in a Unicode font;
//! `0`, a two-byte number, base point, width and height in an extended big font),
//! 8 one X-Y displacement, 9 displacements up to (0,0), 10 octant arc (radius,
//! ±0SC: sign = clockwise, S start octant, C octants, 0 = 8), 11 fractional arc (start
//! offset, end offset, high and low radius, ±0SC; offsets in 1/256 of 45° from the octant
//! boundaries), 12 bulge arc (dx, dy, bulge: ±127 = semicircle), 13 bulge arcs up to (0,0),
//! 14 the next command is for vertical text only (dual-orientation fonts).
//! - Displacements and bulges are two's complement bytes; the arc direction byte keeps its
//! sign in the high bit.
use std::f64::consts::{FRAC_PI_4, TAU};
use super::ShxKind;
use std::ops::{Add, Mul, Neg, Sub};
/// A point in SHX font units.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Point {
pub x: f64,
pub y: f64,
}
impl Point {
pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
pub const fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
fn len(self) -> f64 {
self.x.hypot(self.y)
}
fn len2(self) -> f64 {
self.x * self.x + self.y * self.y
}
}
impl Add for Point {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Self::new(self.x + rhs.x, self.y + rhs.y)
}
}
impl Sub for Point {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self::new(self.x - rhs.x, self.y - rhs.y)
}
}
impl Mul<f64> for Point {
type Output = Self;
fn mul(self, rhs: f64) -> Self {
Self::new(self.x * rhs, self.y * rhs)
}
}
impl Neg for Point {
type Output = Self;
fn neg(self) -> Self {
Self::new(-self.x, -self.y)
}
}
/// Font records and metrics the bounded shape interpreter needs.
pub trait Font {
fn kind(&self) -> ShxKind;
fn dual(&self) -> bool;
fn above(&self) -> f64;
fn char_width(&self) -> f64;
fn program(&self, number: u16) -> Option<&[u8]>;
}
/// Pen-down strokes and advance in font units.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Glyph {
pub strokes: Vec<Vec<Point>>,
pub advance: Point,
}
/// Subshape nesting (a cycle ends here).
const MAX_DEPTH: usize = 16;
/// Location stack (the format promises four).
const MAX_STACK: usize = 64;
/// Bytes run per glyph, subshapes included.
const MAX_STEPS: usize = 200_000;
/// Points per glyph.
const MAX_POINTS: usize = 50_000;
/// Coordinates in font units.
const MAX_COORD: f64 = 1.0e7;
/// Arc segments per full turn.
const ARC_STEPS: f64 = 64.0;
/// Why a program stops early: the glyph is then not drawn.
#[derive(Debug)]
pub struct Broken;
type Res = Result<(), Broken>;
struct Pen<'a> {
font: &'a dyn Font,
vertical: bool,
pos: Point,
down: bool,
/// Vector length factor (codes 3 and 4).
scale: f64,
/// Per-axis factor of an extended big font subshape.
axes: Point,
stack: Vec<Point>,
strokes: Vec<Vec<Point>>,
active: Vec<Point>,
steps: usize,
points: usize,
}
pub fn outline(font: &dyn Font, number: u16, vertical: bool) -> Result<Glyph, Broken> {
let mut pen = Pen {
font,
vertical,
pos: Point::ZERO,
down: true,
scale: 1.0,
axes: Point::new(1.0, 1.0),
stack: Vec::new(),
strokes: Vec::new(),
active: Vec::new(),
steps: 0,
points: 0,
};
pen.run(number, 0)?;
pen.flush();
Ok(Glyph { strokes: pen.strokes, advance: pen.pos })
}
/// The 16 vector directions (unit length on the major axis).
fn direction(d: u8) -> Point {
let (x, y) = match d & 15 {
0 => (1.0, 0.0),
1 => (1.0, 0.5),
2 => (1.0, 1.0),
3 => (0.5, 1.0),
4 => (0.0, 1.0),
5 => (-0.5, 1.0),
6 => (-1.0, 1.0),
7 => (-1.0, 0.5),
8 => (-1.0, 0.0),
9 => (-1.0, -0.5),
10 => (-1.0, -1.0),
11 => (-0.5, -1.0),
12 => (0.0, -1.0),
13 => (0.5, -1.0),
14 => (1.0, -1.0),
_ => (1.0, -0.5),
};
Point::new(x, y)
}
/// A two's complement operand byte.
fn signed(b: u8) -> f64 {
f64::from(i8::from_le_bytes([b]))
}
/// A program being read: its bytes and position.
struct Cur<'p> {
b: &'p [u8],
pos: usize,
}
impl Cur<'_> {
fn byte(&mut self) -> Result<u8, Broken> {
let v = self.b.get(self.pos).copied().ok_or(Broken)?;
self.pos += 1;
Ok(v)
}
}
impl Pen<'_> {
fn step(&mut self) -> Res {
self.steps += 1;
if self.steps > MAX_STEPS { Err(Broken) } else { Ok(()) }
}
fn flush(&mut self) {
if self.active.len() >= 2 {
self.strokes.push(std::mem::take(&mut self.active));
} else {
self.active.clear();
}
}
/// Move the pen by `d` font units (already scaled), drawing when the pen is down.
fn to(&mut self, target: Point) -> Res {
if !target.is_finite() || target.x.abs().max(target.y.abs()) > MAX_COORD {
return Err(Broken);
}
if self.down {
if self.active.is_empty() {
self.active.push(self.pos);
self.points += 1;
}
self.active.push(target);
self.points += 1;
if self.points > MAX_POINTS {
return Err(Broken);
}
} else {
self.flush();
}
self.pos = target;
Ok(())
}
/// A displacement in vector units (times the length factor and the subshape axes).
fn by(&mut self, d: Point) -> Res {
let k = d * self.scale;
self.to(self.pos + Point::new(k.x * self.axes.x, k.y * self.axes.y))
}
/// An arc of `radius` vector units from the pen, starting at angle `start` on its circle
/// and turning `sweep` radians (positive counter-clockwise).
fn arc(&mut self, radius: f64, start: f64, sweep: f64) -> Res {
let r = radius * self.scale;
if !(r.is_finite() && r > 0.0 && sweep.is_finite()) {
return Ok(());
}
let n = if self.down { (sweep.abs() / TAU * ARC_STEPS).ceil().clamp(1.0, ARC_STEPS) as usize } else { 1 };
let from = self.pos;
let s0 = Point::new(start.cos(), start.sin());
for i in 1..=n {
let a = start + sweep * i as f64 / n as f64;
let d = (Point::new(a.cos(), a.sin()) - s0) * r;
self.to(from + Point::new(d.x * self.axes.x, d.y * self.axes.y))?;
}
Ok(())
}
/// An arc to the displacement `d` with `bulge` (−127..127, ±127 a semicircle).
fn bulge(&mut self, d: Point, bulge: f64) -> Res {
let b = bulge.clamp(-127.0, 127.0) / 127.0;
if b == 0.0 || !self.down || d.len2() == 0.0 {
return self.by(d);
}
// Centre from the chord midpoint along its left normal; sweep 4·atan(b).
let centre = d * 0.5 + Point::new(-d.y, d.x) * ((1.0 - b * b) / (4.0 * b));
let rel = -centre;
self.arc(rel.len(), rel.y.atan2(rel.x), 4.0 * b.atan())
}
/// The octant byte `±0SC`: (clockwise, start octant, octants with 0 = 8).
fn octants(spec: u8) -> (f64, f64, f64) {
let sign = if spec & 0x80 != 0 { -1.0 } else { 1.0 };
let s = f64::from((spec >> 4) & 7);
let c = match spec & 7 {
0 => 8.0,
c => f64::from(c),
};
(sign, s, c)
}
/// The vector unit size of an extended big font's subshape cell.
fn cell(&self) -> Point {
let h = if self.font.above() > 0.0 { self.font.above() } else { 1.0 };
let w = if self.font.char_width() > 0.0 { self.font.char_width() } else { h };
Point::new(w, h)
}
fn run(&mut self, number: u16, depth: usize) -> Res {
if depth >= MAX_DEPTH {
return Err(Broken);
}
let program = self.font.program(number).ok_or(Broken)?;
let mut r = Cur { b: program, pos: 0 };
let mut skip = false;
while r.pos < r.b.len() {
self.step()?;
let code = r.byte()?;
// Code 14: in a dual-orientation font the next command is for vertical text only.
let exec = !skip;
skip = false;
match code {
0 => return Ok(()),
1 if exec => self.down = true,
2 if exec => {
self.down = false;
self.flush();
}
3 | 4 => {
let k = f64::from(r.byte()?);
if exec && k > 0.0 {
let s = if code == 3 { self.scale / k } else { self.scale * k };
if !(1e-9..=MAX_COORD).contains(&s) {
return Err(Broken);
}
self.scale = s;
}
}
5 if exec => {
if self.stack.len() >= MAX_STACK {
return Err(Broken);
}
self.stack.push(self.pos);
}
6 if exec => {
self.flush();
if let Some(p) = self.stack.pop() {
self.pos = p;
}
}
7 => self.subshape(&mut r, exec, depth)?,
8 | 9 | 12 | 13 => loop {
self.step()?;
let d = Point::new(signed(r.byte()?), signed(r.byte()?));
if matches!(code, 9 | 13) && d == Point::ZERO {
break;
}
let bulge = if matches!(code, 12 | 13) { signed(r.byte()?) } else { 0.0 };
if exec {
self.bulge(d, bulge)?;
}
if matches!(code, 8 | 12) {
break;
}
},
10 => {
let radius = f64::from(r.byte()?);
let (sign, s, c) = Self::octants(r.byte()?);
if exec {
self.arc(radius, s * FRAC_PI_4, sign * c * FRAC_PI_4)?;
}
}
11 => {
let start = f64::from(r.byte()?) / 256.0;
let end = match r.byte()? {
0 => 1.0,
e => f64::from(e) / 256.0,
};
let radius = f64::from(u16::from_be_bytes([r.byte()?, r.byte()?]));
let (sign, s, c) = Self::octants(r.byte()?);
if exec {
// From `start` past the first octant boundary to `end` past the last
// octant's.
self.arc(radius, (s + sign * start) * FRAC_PI_4, sign * (c - 1.0 + end - start) * FRAC_PI_4)?;
}
}
14 => skip = self.font.dual() && !self.vertical && exec,
1..=15 => {}
v => {
if exec {
self.by(direction(v) * f64::from(v >> 4))?;
}
}
}
}
Ok(())
}
/// Code 7 and its operands.
fn subshape(&mut self, r: &mut Cur, exec: bool, depth: usize) -> Res {
match self.font.kind() {
ShxKind::Unifont => {
let n = u16::from_be_bytes([r.byte()?, r.byte()?]);
if exec {
self.run(n, depth + 1)?;
}
}
ShxKind::BigFont => {
let first = r.byte()?;
if first != 0 {
if exec {
self.run(u16::from(first), depth + 1)?;
}
return Ok(());
}
// Extended: the primitive drawn in the box (x, y, width, height) of the cell.
let n = u16::from_be_bytes([r.byte()?, r.byte()?]);
let (x, y, w, h) = (f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?));
if !exec {
return Ok(());
}
let (pos, axes, down) = (self.pos, self.axes, self.down);
let cell = self.cell();
self.flush();
self.pos = pos + Point::new(x * axes.x, y * axes.y) * self.scale;
self.axes = Point::new(axes.x * w / cell.x, axes.y * h / cell.y);
let res = self.run(n, depth + 1);
self.flush();
self.axes = axes;
self.pos = pos;
self.down = down;
res?;
}
ShxKind::Shapes => {
let n = u16::from(r.byte()?);
if exec {
self.run(n, depth + 1)?;
}
}
}
Ok(())
}
}
impl Font for crate::ParsedFont {
fn kind(&self) -> ShxKind {
self.kind
}
fn dual(&self) -> bool {
self.dual
}
fn above(&self) -> f64 {
self.above
}
fn char_width(&self) -> f64 {
self.char_width
}
fn program(&self, number: u16) -> Option<&[u8]> {
let r = self.records.get(&number)?;
self.data.get(r.program.0..r.program.1)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn executes_shape_vectors_without_app_geometry_types() {
let bytes = crate::compile("*1,3,A\n1,010,0\n").unwrap();
let font = crate::parse::parse(&bytes).unwrap();
let glyph = outline(&font, 1, false).unwrap();
assert_eq!(glyph.strokes, vec![vec![Point::new(0.0, 0.0), Point::new(1.0, 0.0)]]);
assert_eq!(glyph.advance, Point::new(1.0, 0.0));
}
#[test]
fn recursive_shapes_stop_at_the_depth_bound() {
let bytes = crate::compile("*1,3,A\n7,1,0\n").unwrap();
let font = crate::parse::parse(&bytes).unwrap();
assert!(outline(&font, 1, false).is_err());
}
}
#[cfg(test)]
mod instruction_tests {
#![allow(clippy::unwrap_used)]
use super::*;
struct Fixture {
kind: ShxKind,
programs: Vec<Vec<u8>>,
}
impl Font for Fixture {
fn kind(&self) -> ShxKind {
self.kind
}
fn dual(&self) -> bool {
true
}
fn above(&self) -> f64 {
10.0
}
fn char_width(&self) -> f64 {
10.0
}
fn program(&self, number: u16) -> Option<&[u8]> {
self.programs.get(usize::from(number)).map(Vec::as_slice)
}
}
fn fixture(program: Vec<u8>) -> Fixture {
Fixture { kind: ShxKind::Shapes, programs: vec![program] }
}
#[test]
fn pen_state_scaling_and_location_stack_keep_separate_strokes() {
let font = fixture(vec![4, 4, 0x10, 5, 2, 8, 2, 3, 6, 1, 3, 2, 0x14, 0]);
let g = outline(&font, 0, false).unwrap();
assert_eq!(g.strokes, vec![vec![Point::ZERO, Point::new(4.0, 0.0)], vec![Point::new(4.0, 0.0), Point::new(4.0, 2.0)]]);
assert_eq!(g.advance, Point::new(4.0, 2.0));
}
#[test]
fn vertical_only_commands_consume_operands_without_affecting_horizontal_text() {
let font = fixture(vec![14, 8, 10, 20, 0x10, 0]);
assert_eq!(outline(&font, 0, false).unwrap().advance, Point::new(1.0, 0.0));
assert_eq!(outline(&font, 0, true).unwrap().advance, Point::new(11.0, 20.0));
}
#[test]
fn displacement_and_bulge_sequences_end_at_their_chord_endpoint() {
for (program, end_x) in
[(vec![9, 3, 4, 253, 252, 0, 0, 0], 0.0), (vec![12, 10, 0, 127, 0], 10.0), (vec![13, 10, 0, 129, 246, 0, 0, 0, 0, 0], 0.0)]
{
let g = outline(&fixture(program), 0, false).unwrap();
assert!(g.advance.y.abs() < 1e-10);
assert!((g.advance.x - end_x).abs() < 1e-10);
}
}
#[test]
fn full_octant_arcs_close_and_fractional_arcs_keep_radius() {
for program in [vec![10, 10, 0, 0], vec![10, 10, 128, 0], vec![11, 0, 0, 0, 10, 0, 0]] {
let g = outline(&fixture(program), 0, false).unwrap();
assert!(g.advance.len() < 1e-10);
assert_eq!(g.strokes[0].len(), 65);
}
}
#[test]
fn subshape_operands_follow_font_kind_and_bigfont_restores_parent_position() {
for kind in [ShxKind::Shapes, ShxKind::Unifont, ShxKind::BigFont] {
let call = match kind {
ShxKind::Unifont => vec![7, 0, 1, 0],
ShxKind::BigFont => vec![7, 0, 0, 1, 2, 3, 20, 30, 0],
_ => vec![7, 1, 0],
};
let font = Fixture { kind, programs: vec![call, vec![0x10, 0]] };
let g = outline(&font, 0, false).unwrap();
if kind == ShxKind::BigFont {
assert_eq!(g.advance, Point::ZERO);
assert_eq!(g.strokes[0], vec![Point::new(2.0, 3.0), Point::new(4.0, 3.0)]);
} else {
assert_eq!(g.advance, Point::new(1.0, 0.0));
}
}
}
#[test]
fn malformed_operands_and_resource_exhaustion_return_errors() {
for program in [vec![8, 1], vec![7, 99], vec![5; MAX_STACK + 1], vec![0x10; MAX_POINTS + 1], vec![4, 255, 4, 255, 4, 255]] {
assert!(outline(&fixture(program), 0, false).is_err());
}
assert!(outline(&fixture(vec![0]), 1, false).is_err());
}
}
+109
View File
@@ -0,0 +1,109 @@
use craft_shx::{ShxError, compile};
#[test]
fn fixed_shape_bytes() {
let b = compile("*65,2,A\n010,0\n").unwrap();
let mut expected = b"AutoCAD-86 shapes 1.0\r\n\x1a".to_vec();
expected.extend([65, 0, 65, 0, 1, 0, 65, 0, 4, 0, b'A', 0, 0x10, 0]);
expected.extend(b"EOF");
assert_eq!(b, expected);
}
#[test]
fn hostile_sources_are_refused() {
for src in [
"*1,2,X\n7\n",
"*1,2,X\n9,(1,1)\n",
"*99999,1,X\n0\n",
"*1,1,X\n300,0\n",
"010,0\n",
"*1,1,X\n1,0zz,0\n",
"*1,1,X\n0\n*1,1,Y\n0\n",
"*--9223372036854775808,1,X\n0",
"*BIGFONT 1,65535\n*1,1,X\n0",
] {
assert!(compile(src).is_err(), "{src:?}");
}
assert_eq!(compile(""), Err(ShxError::Empty));
assert_eq!(compile(&" ".repeat((8 << 20) + 1)), Err(ShxError::TooLarge));
let oversized_header = format!("*UNIFONT,6,{}\n10,2,0,0,0,0\n*65,1,A\n0", "n".repeat(65536));
assert_eq!(compile(&oversized_header), Err(ShxError::TooLarge));
}
#[test]
fn displacement_arc_and_subshape_operands_have_exact_bytes() {
let source = "; comment\n*+65,99,A\n3,2,4,3,7,66,8,-128,127,9,(1,-2),(0,0),\n10,12,-043,11,1,2,3,4,043,12,-1,2,-3,13,1,2,-3,0,0,0\n";
let bytes = compile(source).unwrap();
let program = [3, 2, 4, 3, 7, 66, 8, 128, 127, 9, 1, 254, 0, 0, 10, 12, 0xc3, 11, 1, 2, 3, 4, 0x43, 12, 255, 2, 253, 13, 1, 2, 253, 0, 0, 0];
let mut record = vec![b'A', 0];
record.extend(program);
record.extend(b"EOF");
assert!(bytes.ends_with(&record));
}
#[test]
fn bigfont_ranges_index_offsets_and_extended_calls_are_encoded() {
let bytes = compile("*BIGFONT 1,2,128,129,140,141\n*65,1,A\n7,66,7,0,01234,1,2,3,4,0\n").unwrap();
let signature = b"AutoCAD-86 bigfont 1.0\r\n\x1a";
let mut expected = signature.to_vec();
expected.extend([1, 0, 1, 0, 2, 0, 128, 0, 129, 0, 140, 0, 141, 0]);
let record = [b'A', 0, 7, 66, 7, 0, 0x12, 0x34, 1, 2, 3, 4, 0];
let offset = (expected.len() + 8) as u32;
expected.extend([65, 0, record.len() as u8, 0]);
expected.extend(offset.to_le_bytes());
expected.extend(record);
assert_eq!(bytes, expected);
}
#[test]
fn unicode_font_records_and_subshape_numbers_are_encoded() {
let bytes = compile("*UNIFONT,6,Example\n10,2,0\n0,0,0\n*65,9,A\n7,01234\n").unwrap();
let mut expected = b"AutoCAD-86 unifont 1.0\r\n\x1a".to_vec();
expected.extend(2u32.to_le_bytes());
expected.extend(14u16.to_le_bytes());
expected.extend(b"Example\0");
expected.extend([10, 2, 0, 0, 0, 0]);
expected.extend([65, 0, 6, 0, b'A', 0, 7, 0x12, 0x34, 0]);
assert_eq!(bytes, expected);
}
#[test]
fn font_records_sorting_names_and_implicit_end_are_preserved() {
let bytes = compile("*66,1,B\0name\n1\n*0,4,Font\n10,2,0,0\n*65,1,A\n2,0\n").unwrap();
let mut expected = b"AutoCAD-86 shapes 1.0\r\n\x1a".to_vec();
expected.extend([0, 0, 66, 0, 3, 0]);
let records: [(u16, &[u8]); 3] = [(0, b"Font\0\x0a\x02\0\0"), (65, b"A\0\x02\0"), (66, b"Bname\0\x01\0")];
for (number, record) in records {
expected.extend(number.to_le_bytes());
expected.extend((record.len() as u16).to_le_bytes());
}
for (_, record) in records {
expected.extend(record);
}
expected.extend(b"EOF");
assert_eq!(bytes, expected);
}
#[test]
fn invalid_typed_operands_report_source_lines() {
for body in ["8,128,0", "10,1,128", "11,1,2,3,4,-128", "7,-1", "3,-1", "256", "7,256"] {
assert!(matches!(compile(&format!("*65,1,A\n{body}")), Err(ShxError::Source(1, _))), "{body}");
}
for source in ["*UNIFONT,6,X\n256\n*65,1,A\n0", "*BIGFONT 1,1,-1,2\n*65,1,A\n0", "*0,1,F\n256", "*-1,1,A\n0"] {
assert!(matches!(compile(source), Err(ShxError::Source(_, _))), "{source}");
}
let large_record = format!("*65,1,{}\n0", "x".repeat(65535));
assert_eq!(compile(&large_record), Err(ShxError::TooLarge));
}
#[test]
fn errors_have_useful_display_messages() {
for (error, expected) in [
(ShxError::NotShx, "not an SHX shape or font file"),
(ShxError::Truncated, "the SHX file is truncated"),
(ShxError::TooLarge, "the SHX file is too large"),
(ShxError::Empty, "the SHX file has no shapes"),
(ShxError::Source(7, "bad operand".into()), "line 7: bad operand"),
] {
assert_eq!(error.to_string(), expected);
}
}