From d92a4d8ff7d1a90caf9fcac9bf120c360455d8d9 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sun, 12 Mar 2023 10:58:56 -0700 Subject: [PATCH] Add a dedicated error for parsing Version from empty string --- src/error.rs | 2 ++ src/parse.rs | 4 ++++ tests/test_version.rs | 5 +---- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/error.rs b/src/error.rs index a514e3f1..93b05ee8 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,6 +2,7 @@ use crate::parse::Error; use core::fmt::{self, Debug, Display}; pub(crate) enum ErrorKind { + Empty, UnexpectedEnd(Position), UnexpectedChar(Position, char), UnexpectedCharAfter(Position, char), @@ -31,6 +32,7 @@ impl std::error::Error for Error {} impl Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match &self.kind { + ErrorKind::Empty => formatter.write_str("empty string, expected a semver version"), ErrorKind::UnexpectedEnd(pos) => { write!(formatter, "unexpected end of input while parsing {}", pos) } diff --git a/src/parse.rs b/src/parse.rs index 6a8f6ffb..e92d87ab 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -26,6 +26,10 @@ impl FromStr for Version { type Err = Error; fn from_str(text: &str) -> Result { + if text.is_empty() { + return Err(Error::new(ErrorKind::Empty)); + } + let mut pos = Position::Major; let (major, text) = numeric_identifier(text, pos)?; let text = dot(text, pos)?; diff --git a/tests/test_version.rs b/tests/test_version.rs index 93a528c1..de3628fa 100644 --- a/tests/test_version.rs +++ b/tests/test_version.rs @@ -12,10 +12,7 @@ use semver::{BuildMetadata, Prerelease, Version}; #[test] fn test_parse() { let err = version_err(""); - assert_to_string( - err, - "unexpected end of input while parsing major version number", - ); + assert_to_string(err, "empty string, expected a semver version"); let err = version_err(" "); assert_to_string(