From 6ea9f53498749703606f6f8d019fe0bc9080ea30 Mon Sep 17 00:00:00 2001 From: platlas Date: Mon, 29 Jan 2024 17:36:01 +0100 Subject: [PATCH] Replace panic with error return in `BezPath::from_svg` (#329) * Replace panic with error return in `BezPath::from_svg` --- src/svg.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/svg.rs b/src/svg.rs index ecdb1901..016a0660 100644 --- a/src/svg.rs +++ b/src/svg.rs @@ -102,6 +102,10 @@ impl BezPath { let mut implicit_moveto = None; while let Some(c) = lexer.get_cmd(last_cmd) { if c != b'm' && c != b'M' { + if path.elements().is_empty() { + return Err(SvgParseError::UninitializedPath); + } + if let Some(pt) = implicit_moveto.take() { path.move_to(pt); } @@ -242,6 +246,8 @@ pub enum SvgParseError { UnexpectedEof, /// Encountered an unknown command letter. UnknownCommand(char), + /// Encountered a command that precedes expected 'moveto' command. + UninitializedPath, } impl Display for SvgParseError { @@ -250,6 +256,9 @@ impl Display for SvgParseError { SvgParseError::Wrong => write!(f, "Unable to parse a number"), SvgParseError::UnexpectedEof => write!(f, "Unexpected EOF"), SvgParseError::UnknownCommand(letter) => write!(f, "Unknown command, \"{letter}\""), + SvgParseError::UninitializedPath => { + write!(f, "Unititialized path (missing moveto command)") + } } } } @@ -517,6 +526,12 @@ mod tests { assert_eq!(path.perimeter(1e-6).round(), 168.0); } + #[test] + fn test_parse_svg_uninitialized() { + let path = BezPath::from_svg("L10 10 100 0 0 100"); + assert!(path.is_err()); + } + #[test] fn test_write_svg_single() { let segments = [CubicBez::new(