Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use error feature #10

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ serde = { version = "1", features = ["derive"] }
[features]
default = []
serde = ["dep:serde"]
use_error = []
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@ use non_empty_string::NonEmptyString;
let s = "A string with a length".to_owned();
assert!(NonEmptyString::new(s).is_ok());

// But constructing it from a non-zero-length String results in an `Err`, where we get the `String` back that we passed in.
// But constructing it from a zero-length String results in an `Err`.
let empty = "".to_owned();
let result = NonEmptyString::new(empty);
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "".to_owned())

```

Expand Down
72 changes: 68 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ use std::fmt::Display;
#[cfg(feature = "serde")]
mod serde_support;

#[cfg(feature = "use_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorEmptyString;

#[cfg(feature = "use_error")]
impl Display for ErrorEmptyString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Error: zero-value string")
}
}

#[cfg(feature = "use_error")]
impl std::error::Error for ErrorEmptyString {}

/// A simple String wrapper type, similar to NonZeroUsize and friends.
/// Guarantees that the String contained inside is not of length 0.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
Expand All @@ -24,14 +38,26 @@ pub struct NonEmptyString(String);

#[allow(clippy::len_without_is_empty)] // is_empty would always returns false so it seems a bit silly to have it.
impl NonEmptyString {
/// Attempts to create a new NonEmptyString.
#[cfg(not(feature = "use_error"))]
// Attempts to create a new NonEmptyString.
/// If the given `string` is empty, `Err` is returned, containing the original `String`, `Ok` otherwise.
pub fn new(string: String) -> Result<NonEmptyString, String> {
if string.is_empty() {
Err(string)
} else {
Ok(NonEmptyString(string))
return Err(string);
}

Ok(NonEmptyString(string))
}

#[cfg(feature = "use_error")]
/// Attempts to create a new NonEmptyString.
/// If the given `string` is empty, `Err` is returned, `Ok` otherwise.
pub fn new(string: String) -> Result<NonEmptyString, ErrorEmptyString> {
if string.is_empty() {
return Err(ErrorEmptyString);
}

Ok(NonEmptyString(string))
}

/// Returns a reference to the contained value.
Expand Down Expand Up @@ -128,6 +154,7 @@ impl AsRef<String> for NonEmptyString {
}
}

#[cfg(not(feature = "use_error"))]
impl<'s> TryFrom<&'s str> for NonEmptyString {
type Error = &'s str;

Expand All @@ -140,6 +167,7 @@ impl<'s> TryFrom<&'s str> for NonEmptyString {
}
}

#[cfg(not(feature = "use_error"))]
impl TryFrom<String> for NonEmptyString {
type Error = String;

Expand All @@ -148,6 +176,28 @@ impl TryFrom<String> for NonEmptyString {
}
}

#[cfg(feature = "use_error")]
impl<'s> TryFrom<&'s str> for NonEmptyString {
type Error = ErrorEmptyString;

fn try_from(value: &'s str) -> Result<Self, Self::Error> {
if value.is_empty() {
return Err(ErrorEmptyString);
}

Ok(NonEmptyString(value.to_owned()))
}
}

#[cfg(feature = "use_error")]
impl TryFrom<String> for NonEmptyString {
type Error = ErrorEmptyString;

fn try_from(value: String) -> Result<Self, Self::Error> {
NonEmptyString::new(value)
}
}

impl Display for NonEmptyString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f)
Expand All @@ -159,11 +209,25 @@ mod tests {
use super::*;

#[test]
#[cfg(not(feature = "use_error"))]
fn empty_string_returns_err() {
assert_eq!(NonEmptyString::new("".to_owned()), Err("".to_owned()));
}

#[test]
#[cfg(not(feature = "use_error"))]
fn non_empty_string_returns_ok() {
assert!(NonEmptyString::new("string".to_owned()).is_ok())
}

#[test]
#[cfg(feature = "use_error")]
fn empty_string_returns_err() {
assert_eq!(NonEmptyString::new("".to_owned()), Err(ErrorEmptyString));
}

#[test]
#[cfg(feature = "use_error")]
fn non_empty_string_returns_ok() {
assert!(NonEmptyString::new("string".to_owned()).is_ok())
}
Expand Down
3 changes: 2 additions & 1 deletion src/serde_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ impl<'de> Visitor<'de> for NonEmptyStringVisitor {
where
E: de::Error,
{
NonEmptyString::new(value).map_err(|e| de::Error::invalid_value(Unexpected::Str(&e), &self))
NonEmptyString::new(value)
.map_err(|_e| de::Error::invalid_value(Unexpected::Str(""), &self))
}
}

Expand Down