mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
dxf: add shared .lin and .pat text parsers (#2434)
This commit is contained in:
@@ -12,6 +12,7 @@
|
||||
use std::io::Write as _;
|
||||
|
||||
pub mod drawing;
|
||||
pub mod lin_pat;
|
||||
pub mod model;
|
||||
pub mod mtext;
|
||||
pub mod mtext_tokens;
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
//! Readers for AutoCAD-compatible linetype (`.lin`) and hatch pattern (`.pat`) text files.
|
||||
//!
|
||||
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
|
||||
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
|
||||
//! a pattern), with `;` starting a comment. Everything here treats the text as hostile: lines,
|
||||
//! definitions, dashes, families and warnings are capped, numbers must be finite and reasonable,
|
||||
//! and nothing panics. Problems become warnings and the definitions that can be read are kept.
|
||||
|
||||
/// Longest line read; longer lines are skipped with a warning.
|
||||
pub const MAX_LINE_CHARS: usize = 4096;
|
||||
/// Most definitions (linetypes or patterns) read from one file.
|
||||
pub const MAX_DEFINITIONS: usize = 4096;
|
||||
/// Most elements in one linetype.
|
||||
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
|
||||
/// Most line families in one hatch pattern.
|
||||
pub const MAX_PATTERN_FAMILIES: usize = 1024;
|
||||
/// Most dashes in one pattern line family.
|
||||
pub const MAX_PATTERN_DASHES: usize = 256;
|
||||
/// Largest magnitude accepted for a length, offset or scale.
|
||||
pub const MAX_VALUE: f64 = 1.0e6;
|
||||
/// Longest name or description kept.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
/// Most warnings collected; the rest are counted in a last line.
|
||||
const MAX_WARNINGS: usize = 100;
|
||||
|
||||
/// One element of a linetype parsed from a `.lin` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LinDashElement {
|
||||
/// Dash (`> 0`), gap (`< 0`), or dot (`0`) length in drawing units.
|
||||
pub length: f64,
|
||||
/// Embedded text string, if any.
|
||||
pub text: Option<String>,
|
||||
/// Text style name for embedded text, if any.
|
||||
pub style: Option<String>,
|
||||
/// Text scale factor (`S=`, default `1.0`).
|
||||
pub scale: f64,
|
||||
/// Text rotation in radians (`R=`, `A=`, or `U=`, default `0.0`).
|
||||
pub rotation: f64,
|
||||
/// Text X/Y offset (`X=`, `Y=`, default `[0.0, 0.0]`).
|
||||
pub offset: [f64; 2],
|
||||
/// Whether rotation is absolute (`A=`) rather than relative to the line (`R=` or `U=`).
|
||||
pub absolute: bool,
|
||||
}
|
||||
|
||||
impl LinDashElement {
|
||||
/// A simple dash, gap, or dot element with no embedded text.
|
||||
#[must_use]
|
||||
pub fn dash(length: f64) -> Self {
|
||||
Self { length, text: None, style: None, scale: 1.0, rotation: 0.0, offset: [0.0, 0.0], absolute: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// A linetype definition parsed from a `.lin` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LinDefinition {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub pattern: Vec<LinDashElement>,
|
||||
}
|
||||
|
||||
/// One line family of a hatch pattern parsed from a `.pat` file.
|
||||
///
|
||||
/// Values are in pattern-definition coordinates as written: `angle` in degrees, `origin` as
|
||||
/// `[x, y]`, `delta` as `[delta_x, delta_y]` along/perpendicular to the line direction, and
|
||||
/// `dashes` as dash (`> 0`), gap (`< 0`), and dot (`0`) lengths.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PatLineFamily {
|
||||
pub angle: f64,
|
||||
pub origin: [f64; 2],
|
||||
pub delta: [f64; 2],
|
||||
pub dashes: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A hatch pattern definition parsed from a `.pat` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PatDefinition {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub lines: Vec<PatLineFamily>,
|
||||
}
|
||||
|
||||
/// What a file held: the definitions that could be read, and why anything else was skipped.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Parsed<T> {
|
||||
pub items: Vec<T>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T> Default for Parsed<T> {
|
||||
fn default() -> Self {
|
||||
Self { items: Vec::new(), warnings: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Parsed<T> {
|
||||
fn warn(&mut self, line: usize, msg: impl Into<String>) {
|
||||
match self.warnings.len() {
|
||||
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
|
||||
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
|
||||
fn header(rest: &str) -> std::result::Result<(String, String), String> {
|
||||
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("a definition without a name".into());
|
||||
}
|
||||
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
|
||||
return Err("a definition name that is too long or has control characters".into());
|
||||
}
|
||||
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
|
||||
Ok((name.to_string(), desc))
|
||||
}
|
||||
|
||||
/// A finite number within ±[`MAX_VALUE`].
|
||||
fn number(t: &str) -> Option<f64> {
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
|
||||
}
|
||||
|
||||
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
|
||||
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
|
||||
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
|
||||
}
|
||||
|
||||
// ---------- LIN ----------
|
||||
|
||||
/// Read the linetypes of a `.lin` file.
|
||||
///
|
||||
/// Simple linetypes and complex ones with embedded text
|
||||
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
|
||||
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
|
||||
/// Lengths are in drawing units as written: a user's file is never rescaled.
|
||||
#[must_use]
|
||||
pub fn parse_lin(text: &str) -> Parsed<LinDefinition> {
|
||||
let mut out = Parsed::default();
|
||||
// The definition being read: name, description, header line.
|
||||
let mut pending: Option<(String, String, usize)> = None;
|
||||
for (no, line) in lines(text) {
|
||||
if line.is_empty() || line.starts_with(';') {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
if let Some((name, _, at)) = pending.take() {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
match header(rest) {
|
||||
Ok((name, desc)) => pending = Some((name, desc, no)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((name, description, _)) = pending.take() else {
|
||||
out.warn(no, "pattern line without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
|
||||
break;
|
||||
}
|
||||
if out.items.iter().any(|l: &LinDefinition| l.name.eq_ignore_ascii_case(&name)) {
|
||||
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
|
||||
continue;
|
||||
}
|
||||
match lin_pattern(line, no, &name, &mut out) {
|
||||
Ok(pattern) => out.items.push(LinDefinition { name, description, pattern }),
|
||||
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
|
||||
}
|
||||
}
|
||||
if let Some((name, _, at)) = pending {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a pattern line at commas outside `[…]` and `"…"`.
|
||||
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
|
||||
let mut out = Vec::new();
|
||||
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
|
||||
for (i, c) in line.char_indices() {
|
||||
match c {
|
||||
'"' => quoted = !quoted,
|
||||
'[' if !quoted => depth = depth.saturating_add(1),
|
||||
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
|
||||
',' if !quoted && depth == 0 => {
|
||||
out.push(line.get(start..i).unwrap_or("").trim());
|
||||
start = i.saturating_add(1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
}
|
||||
if quoted || depth != 0 {
|
||||
return Err("an unclosed [ or \"".into());
|
||||
}
|
||||
out.push(line.get(start..).unwrap_or("").trim());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The elements of a pattern line `A,dash,gap,[…],…`.
|
||||
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<LinDefinition>) -> std::result::Result<Vec<LinDashElement>, String> {
|
||||
let mut fields = lin_fields(line)?;
|
||||
// The alignment field ("A") comes first; a line of plain numbers is read as well.
|
||||
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
|
||||
fields.remove(0);
|
||||
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
|
||||
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
|
||||
}
|
||||
let mut pattern: Vec<LinDashElement> = Vec::new();
|
||||
for f in fields.into_iter().filter(|f| !f.is_empty()) {
|
||||
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
let Some(inner) = f.strip_prefix('[') else {
|
||||
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
|
||||
pattern.push(LinDashElement::dash(len));
|
||||
continue;
|
||||
};
|
||||
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
|
||||
match lin_text(inner)? {
|
||||
Some(text) => {
|
||||
// The text sits at the end of the element before it (a zero-length one if none).
|
||||
if pattern.last().is_none_or(|e| e.text.is_some()) {
|
||||
pattern.push(LinDashElement::dash(0.0));
|
||||
}
|
||||
if let Some(last) = pattern.last_mut() {
|
||||
*last = LinDashElement { length: last.length, ..text };
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let shape = inner.split(',').next().unwrap_or("").trim();
|
||||
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which is not supported here; left out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if pattern.is_empty() {
|
||||
return Err("no dashes".into());
|
||||
}
|
||||
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
|
||||
return Err("every element has zero length".into());
|
||||
}
|
||||
Ok(pattern)
|
||||
}
|
||||
|
||||
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
|
||||
fn lin_text(inner: &str) -> std::result::Result<Option<LinDashElement>, String> {
|
||||
let inner = inner.trim();
|
||||
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
|
||||
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
|
||||
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
|
||||
return Err("embedded text that is too long or has control characters".into());
|
||||
}
|
||||
let mut parts = rest.split(',').map(str::trim);
|
||||
if !parts.next().unwrap_or("").is_empty() {
|
||||
return Err("text element: expected a comma after the text".into());
|
||||
}
|
||||
let style = parts.next().unwrap_or("").trim();
|
||||
if style.is_empty() || style.contains('=') {
|
||||
return Err("text element: the text style is missing".into());
|
||||
}
|
||||
let mut e = LinDashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..LinDashElement::dash(0.0) };
|
||||
for kv in parts.filter(|p| !p.is_empty()) {
|
||||
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
|
||||
match k.trim().to_ascii_uppercase().as_str() {
|
||||
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
|
||||
"X" => e.offset[0] = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
|
||||
"Y" => e.offset[1] = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
|
||||
// Upright text keeps a rotation relative to the line, like R.
|
||||
k @ ("R" | "A" | "U") => {
|
||||
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
|
||||
e.absolute = k == "A";
|
||||
}
|
||||
other => return Err(format!("text element: unknown option `{other}`")),
|
||||
}
|
||||
}
|
||||
Ok(Some(e))
|
||||
}
|
||||
|
||||
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
|
||||
fn angle(t: &str) -> Option<f64> {
|
||||
let t = t.trim().to_ascii_lowercase();
|
||||
let (num, unit) = match t.char_indices().last() {
|
||||
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
|
||||
_ => (t.as_str(), 'd'),
|
||||
};
|
||||
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
|
||||
Some(match unit {
|
||||
'r' => v,
|
||||
'g' => v * std::f64::consts::PI / 200.0,
|
||||
_ => v.to_radians(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- PAT ----------
|
||||
|
||||
/// Read the hatch patterns of a `.pat` file.
|
||||
///
|
||||
/// Values are used as written (an inch file for inch drawings, a millimetre file for metric ones).
|
||||
#[must_use]
|
||||
pub fn parse_pat(text: &str) -> Parsed<PatDefinition> {
|
||||
let mut out: Parsed<PatDefinition> = Parsed::default();
|
||||
// The pattern being read, its header line, and whether it already failed.
|
||||
let mut cur: Option<(PatDefinition, usize, bool)> = None;
|
||||
for (no, line) in lines(text) {
|
||||
// A comment runs to the end of the line.
|
||||
let line = line.split(';').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
finish_pat(cur.take(), &mut out);
|
||||
match header(rest) {
|
||||
Ok((name, description)) => cur = Some((PatDefinition { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((p, _, failed)) = cur.as_mut() else {
|
||||
out.warn(no, "line family without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if *failed {
|
||||
continue;
|
||||
}
|
||||
if p.lines.len() >= MAX_PATTERN_FAMILIES {
|
||||
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
|
||||
*failed = true;
|
||||
continue;
|
||||
}
|
||||
match pat_family(line) {
|
||||
Ok(l) => p.lines.push(l),
|
||||
Err(e) => {
|
||||
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
|
||||
*failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
finish_pat(cur, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn finish_pat(cur: Option<(PatDefinition, usize, bool)>, out: &mut Parsed<PatDefinition>) {
|
||||
let Some((p, at, failed)) = cur else { return };
|
||||
if failed {
|
||||
return;
|
||||
}
|
||||
if p.lines.is_empty() {
|
||||
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
|
||||
} else if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
|
||||
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
|
||||
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
|
||||
} else {
|
||||
out.items.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
|
||||
fn pat_family(line: &str) -> std::result::Result<PatLineFamily, String> {
|
||||
let mut v = Vec::new();
|
||||
for f in line.split(',') {
|
||||
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
|
||||
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
|
||||
}
|
||||
let f = f.trim();
|
||||
if f.is_empty() && v.len() >= 5 {
|
||||
continue;
|
||||
}
|
||||
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
|
||||
}
|
||||
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
|
||||
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
|
||||
};
|
||||
if dy.abs() < 1e-9 {
|
||||
return Err("a line family with zero spacing (delta-y)".into());
|
||||
}
|
||||
Ok(PatLineFamily { angle, origin: [x, y], delta: [dx, dy], dashes: v.get(5..).unwrap_or(&[]).to_vec() })
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Tests for `.lin` and `.pat` text resource parsing.
|
||||
|
||||
use craft_dxf::lin_pat::{MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, parse_lin, parse_pat};
|
||||
|
||||
const LIN: &str = "\
|
||||
;; my own linetypes
|
||||
*MYDASH,My dash __ __ __
|
||||
A,.5,-.25
|
||||
|
||||
*MYDOTS
|
||||
A,0,-.1,0,-.2
|
||||
*MYTEXT,Text line --MY--MY--
|
||||
A,.5,-.2,[\"MY\",STANDARD,S=.1,R=0.0,X=-0.1,Y=-.05],-.2
|
||||
*MYSHAPE,Shape line
|
||||
A,.25,-.1,[MYBOX,myshapes.shx,S=.1],-.1,1
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn simple_and_text_linetypes_are_read() {
|
||||
let r = parse_lin(LIN);
|
||||
let names: Vec<&str> = r.items.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["MYDASH", "MYDOTS", "MYTEXT", "MYSHAPE"]);
|
||||
let dash = &r.items[0];
|
||||
assert_eq!(dash.description, "My dash __ __ __");
|
||||
assert_eq!(dash.pattern.iter().map(|e| e.length).collect::<Vec<_>>(), [0.5, -0.25]);
|
||||
assert_eq!(r.items[1].description, "");
|
||||
assert_eq!(r.items[1].pattern.len(), 4);
|
||||
|
||||
// The text belongs to the gap before it: drawn at that gap's end.
|
||||
let text = &r.items[2].pattern;
|
||||
assert_eq!(text.len(), 3);
|
||||
assert_eq!(text[1].length, -0.2);
|
||||
assert_eq!(text[1].text.as_deref(), Some("MY"));
|
||||
assert_eq!(text[1].style.as_deref(), Some("STANDARD"));
|
||||
assert!((text[1].scale - 0.1).abs() < 1e-12);
|
||||
assert!((text[1].offset[0] + 0.1).abs() < 1e-12 && (text[1].offset[1] + 0.05).abs() < 1e-12);
|
||||
assert!(!text[1].absolute);
|
||||
assert!(text[2].text.is_none());
|
||||
|
||||
// Shapes need SHX files: left out with a note, the dashes kept.
|
||||
let shape = &r.items[3].pattern;
|
||||
assert_eq!(shape.iter().map(|e| e.length).collect::<Vec<_>>(), [0.25, -0.1, -0.1, 1.0]);
|
||||
assert!(shape.iter().all(|e| e.text.is_none()));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("MYBOX")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_rotation_units_and_absolute_angles() {
|
||||
let r = parse_lin("*R1\nA,1,[\"x\",S1,A=90,S=1],-1\n*R2\nA,1,[\"x\",S1,R=1.5r],-1\n*R3\nA,1,[\"a,b]\",S1,U=100g],-1\n");
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let rot = |i: usize| r.items[i].pattern[0].rotation;
|
||||
assert!((rot(0) - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && r.items[0].pattern[0].absolute);
|
||||
assert!((rot(1) - 1.5).abs() < 1e-12);
|
||||
assert!((rot(2) - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
|
||||
// Commas and brackets inside the quoted text are text.
|
||||
assert_eq!(r.items[2].pattern[0].text.as_deref(), Some("a,b]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_linetypes_are_skipped_with_warnings() {
|
||||
let text = "\
|
||||
*NOPATTERN
|
||||
*BADNUM
|
||||
A,.5,abc
|
||||
*BADALIGN
|
||||
B,.5,-.5
|
||||
*UNCLOSED
|
||||
A,.5,[\"x\",S1
|
||||
*
|
||||
A,1,-1
|
||||
A,1,-1
|
||||
*GOOD
|
||||
A,1,-1
|
||||
*GOOD
|
||||
A,2,-2
|
||||
*ZERO
|
||||
A,0,0
|
||||
*NOSTYLE
|
||||
A,1,[\"x\"],-1
|
||||
";
|
||||
let r = parse_lin(text);
|
||||
assert_eq!(r.items.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["GOOD"]);
|
||||
assert_eq!(r.items[0].pattern[0].length, 1.0, "the first definition is kept");
|
||||
for what in ["NOPATTERN", "BADNUM", "BADALIGN", "UNCLOSED", "without a name", "without a *NAME", "defined twice", "ZERO", "NOSTYLE"] {
|
||||
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_linetype_files_never_panic_and_stay_capped() {
|
||||
let long_line = format!("*LONG\nA,{}", vec!["1"; 5000].join(","));
|
||||
let many = format!("*MANY\nA,{}", vec!["1,-1"; MAX_LINETYPE_ELEMENTS].join(","));
|
||||
let defs: String = (0..5000).map(|i| format!("*L{i}\nA,1,-1\n")).collect();
|
||||
let huge = "*HUGE\nA,1e300,-1\n*NAN\nA,NaN,-1\n*INF\nA,inf,-1\n";
|
||||
for text in [long_line.as_str(), many.as_str(), defs.as_str(), huge, "", "\u{feff}", "]]][[[\"", "*\u{0}\nA,1", "A,1,-1\n*X,", "*X\nA,[[[[\"]]]"]
|
||||
{
|
||||
let r = parse_lin(text);
|
||||
assert!(r.items.len() <= 4096);
|
||||
assert!(r.items.iter().all(|l| l.pattern.len() <= MAX_LINETYPE_ELEMENTS && l.pattern.iter().all(|e| e.length.is_finite())));
|
||||
assert!(r.warnings.len() <= 101);
|
||||
}
|
||||
assert!(parse_lin(huge).items.is_empty());
|
||||
assert_eq!(parse_lin(&defs).items.len(), 4096);
|
||||
}
|
||||
|
||||
const PAT: &str = "\
|
||||
; my own patterns
|
||||
*MYGRID, My grid
|
||||
0, 0,0, 0,.5
|
||||
90, 0,0, 0,.5
|
||||
*MYBRICK,My brick ; trailing comment
|
||||
0, 0,0, 0,.25
|
||||
90, 0,0, .25,.25, .25,-.25
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn hatch_patterns_are_read() {
|
||||
let r = parse_pat(PAT);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(r.items.len(), 2);
|
||||
let grid = &r.items[0];
|
||||
assert_eq!((grid.name.as_str(), grid.description.as_str()), ("MYGRID", "My grid"));
|
||||
assert_eq!(grid.lines.len(), 2);
|
||||
assert_eq!(grid.lines[1].angle, 90.0);
|
||||
assert_eq!(grid.lines[1].delta, [0.0, 0.5]);
|
||||
let brick = &r.items[1];
|
||||
assert_eq!(brick.description, "My brick");
|
||||
assert_eq!(brick.lines[1].origin, [0.0, 0.0]);
|
||||
assert_eq!(brick.lines[1].dashes, [0.25, -0.25]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowercase_pattern_names_are_upper_cased() {
|
||||
let r = parse_pat("*mypat\n45,0,0,0,.125\n");
|
||||
assert_eq!(r.items[0].name, "MYPAT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_patterns_are_skipped_with_warnings() {
|
||||
let text = "\
|
||||
0,0,0,0,1
|
||||
*EMPTY
|
||||
*SHORT
|
||||
0,0,0
|
||||
*ZEROGAP
|
||||
0,0,0,1,0
|
||||
*BADNUM
|
||||
0,0,0,0,x
|
||||
*OK
|
||||
0,0,0,0,1
|
||||
*OK
|
||||
45,0,0,0,1
|
||||
";
|
||||
let r = parse_pat(text);
|
||||
assert_eq!(r.items.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["OK"]);
|
||||
assert_eq!(r.items[0].lines[0].angle, 0.0, "the first definition is kept");
|
||||
for what in ["without a *NAME", "EMPTY", "SHORT", "ZEROGAP", "BADNUM", "defined twice"] {
|
||||
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_pattern_files_never_panic_and_stay_capped() {
|
||||
let families = format!("*FAM\n{}", "0,0,0,0,1\n".repeat(MAX_PATTERN_FAMILIES + 5));
|
||||
let dashes = format!("*DASH\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES + 1].join(","));
|
||||
let ok_dashes = format!("*DASHOK\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES].join(","));
|
||||
let defs: String = (0..5000).map(|i| format!("*P{i}\n0,0,0,0,1\n")).collect();
|
||||
let big = "*BIG\n1e300,0,0,0,1\n*NAN\nNaN,0,0,0,1\n";
|
||||
for text in [families.as_str(), dashes.as_str(), ok_dashes.as_str(), defs.as_str(), big, "", "*", "***\n,,,,,", "*X\n,,,,,,,,,,"] {
|
||||
let r = parse_pat(text);
|
||||
assert!(r.items.len() <= 4096);
|
||||
assert!(r.items.iter().all(|p| p.lines.len() <= MAX_PATTERN_FAMILIES && p.lines.iter().all(|l| l.dashes.len() <= MAX_PATTERN_DASHES)));
|
||||
assert!(r.warnings.len() <= 101);
|
||||
}
|
||||
assert!(parse_pat(&families).items.is_empty());
|
||||
assert!(parse_pat(&dashes).items.is_empty());
|
||||
assert_eq!(parse_pat(&ok_dashes).items.len(), 1);
|
||||
assert!(parse_pat(big).items.is_empty());
|
||||
assert_eq!(parse_pat(&defs).items.len(), 4096);
|
||||
}
|
||||
Reference in New Issue
Block a user