Skip to content

Commit

Permalink
Add a dedicated error for parsing Version from empty string
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Mar 12, 2023
1 parent cc2cfed commit d92a4d8
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 4 deletions.
2 changes: 2 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 4 additions & 0 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ impl FromStr for Version {
type Err = Error;

fn from_str(text: &str) -> Result<Self, Self::Err> {
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)?;
Expand Down
5 changes: 1 addition & 4 deletions tests/test_version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit d92a4d8

Please sign in to comment.