Skip to content

Commit

Permalink
Merge pull request #153 from greyblake/try-new
Browse files Browse the repository at this point in the history
Deprecate fallible ::new() in favor of ::try_new()
  • Loading branch information
greyblake authored Jul 1, 2024
2 parents 391b702 + fdf490c commit 4ab24cc
Show file tree
Hide file tree
Showing 24 changed files with 372 additions and 409 deletions.
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
### v0.x.x - 2024-xx-xx

* Support newtypes with generics

* Support generics
* [DEPRECATION] Fallible constructor `::new()` is deprecated. Users should use `::try_new()` instead.
* [FIX] Use absolute path for `::core::result::Result` when generating code for `derive(TryFrom)`.

### v0.4.2 - 2024-04-07

Expand Down
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,22 @@ use nutype::nutype;
)]
pub struct Username(String);

// We can obtain a value of Username with `::new()`.
// We can obtain a value of Username with `::try_new()`.
// Note that Username holds a sanitized string
assert_eq!(
Username::new(" FooBar ").unwrap().into_inner(),
Username::try_new(" FooBar ").unwrap().into_inner(),
"foobar"
);

// It's impossible to obtain an invalid Username
// Note that we also got `UsernameError` enum generated implicitly
// based on the validation rules.
assert_eq!(
Username::new(" "),
Username::try_new(" "),
Err(UsernameError::NotEmptyViolated),
);
assert_eq!(
Username::new("TheUserNameIsVeryVeryLong"),
Username::try_new("TheUserNameIsVeryVeryLong"),
Err(UsernameError::LenCharMaxViolated),
);
```
Expand Down Expand Up @@ -229,12 +229,12 @@ pub struct GuestList(Vec<String>);

// Empty list is not allowed
assert_eq!(
GuestList::new(vec![]),
GuestList::try_new(vec![]),
Err(GuestListError::PredicateViolated)
);

// Create the list of our guests
let guest_list = GuestList::new(vec![
let guest_list = GuestList::try_new(vec![
"Seneca".to_string(),
"Marcus Aurelius".to_string(),
"Socrates".to_string(),
Expand Down
144 changes: 0 additions & 144 deletions WORKLOG.md

This file was deleted.

15 changes: 3 additions & 12 deletions dummy/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
use arbitrary::Arbitrary;
use nutype::nutype;

#[nutype(derive(Debug, Arbitrary))]
struct Wrapper<T>(Vec<T>);
#[nutype(validate(len_char_min = 5), default = "Anonymous", derive(Default))]
pub struct Name(String);

fn main() {
fn gen(bytes: &[u8]) -> Wrapper<bool> {
let mut u = arbitrary::Unstructured::new(bytes);
Wrapper::<bool>::arbitrary(&mut u).unwrap()
}
assert_eq!(gen(&[]).into_inner(), vec![]);
assert_eq!(gen(&[1]).into_inner(), vec![false]);
assert_eq!(gen(&[1, 3, 5]).into_inner(), vec![true, false]);
}
fn main() {}
4 changes: 2 additions & 2 deletions examples/any_generics/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ fn main() {
// NotEmpty
//
{
let v = NotEmpty::new(vec![1, 2, 3]).unwrap();
let v = NotEmpty::try_new(vec![1, 2, 3]).unwrap();
assert_eq!(v.into_inner(), vec![1, 2, 3]);

let err = NotEmpty::<i32>::new(vec![]).unwrap_err();
let err = NotEmpty::<i32>::try_new(vec![]).unwrap_err();
assert_eq!(err, NotEmptyError::PredicateViolated);
}

Expand Down
10 changes: 5 additions & 5 deletions examples/float_sortable/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn main() {
// which excluded NaN values.
let mut widths: Vec<Width> = raw_widths
.into_iter()
.map(|w| Width::new(w).unwrap())
.map(|w| Width::try_new(w).unwrap())
.collect();

// Now we can sort
Expand All @@ -27,10 +27,10 @@ fn main() {
assert_eq!(
widths,
vec![
Width::new(1.4).unwrap(),
Width::new(1.5).unwrap(),
Width::new(1.8).unwrap(),
Width::new(2.1).unwrap(),
Width::try_new(1.4).unwrap(),
Width::try_new(1.5).unwrap(),
Width::try_new(1.8).unwrap(),
Width::try_new(2.1).unwrap(),
],
)
}
13 changes: 8 additions & 5 deletions examples/integer_bounded/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@ struct Volume(i8);

fn main() {
// Too small
assert_eq!(Volume::new(-101), Err(VolumeError::GreaterOrEqualViolated),);
assert_eq!(
Volume::try_new(-101),
Err(VolumeError::GreaterOrEqualViolated),
);

// Too big
assert_eq!(Volume::new(101), Err(VolumeError::LessOrEqualViolated),);
assert_eq!(Volume::try_new(101), Err(VolumeError::LessOrEqualViolated),);

// Valid values
assert_eq!(Volume::new(-100).unwrap().into_inner(), -100);
assert_eq!(Volume::new(0).unwrap().into_inner(), 0);
assert_eq!(Volume::new(100).unwrap().into_inner(), 100);
assert_eq!(Volume::try_new(-100).unwrap().into_inner(), -100);
assert_eq!(Volume::try_new(0).unwrap().into_inner(), 0);
assert_eq!(Volume::try_new(100).unwrap().into_inner(), 100);
}
6 changes: 3 additions & 3 deletions examples/serde_complex/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ fn main() {
assert_eq!(
product,
Product {
name: Name::new("FlySniper").unwrap(),
image_url: ImageUrl::new("https://example.com/image.jpg").unwrap(),
price: Price::new(9.99).unwrap(),
name: Name::try_new("FlySniper").unwrap(),
image_url: ImageUrl::try_new("https://example.com/image.jpg").unwrap(),
price: Price::try_new(9.99).unwrap(),
}
)
}
Expand Down
6 changes: 3 additions & 3 deletions examples/string_bounded_len/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const MAX_NAME_LEN: usize = 4;
pub struct Name(String);

fn main() {
assert_eq!(Name::new("Bo"), Err(NameError::LenCharMinViolated));
assert_eq!(Name::new("Julia"), Err(NameError::LenCharMaxViolated));
assert_eq!(Name::new("Jojo").unwrap().as_ref(), "Jojo");
assert_eq!(Name::try_new("Bo"), Err(NameError::LenCharMinViolated));
assert_eq!(Name::try_new("Julia"), Err(NameError::LenCharMaxViolated));
assert_eq!(Name::try_new("Jojo").unwrap().as_ref(), "Jojo");
}
8 changes: 4 additions & 4 deletions examples/string_regex_email/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,19 @@ struct Email(String);

fn main() {
// Too short
assert_eq!(Email::new("a@b"), Err(EmailError::LenCharMinViolated));
assert_eq!(Email::try_new("a@b"), Err(EmailError::LenCharMinViolated));

// Too long
assert_eq!(
Email::new("[email protected]"),
Email::try_new("[email protected]"),
Err(EmailError::LenCharMaxViolated)
);

// Does not match the regex
assert_eq!(Email::new("foo@barcom"), Err(EmailError::RegexViolated));
assert_eq!(Email::try_new("foo@barcom"), Err(EmailError::RegexViolated));

// A valid email
let email: Email = Email::new("\t [email protected] \n").unwrap();
let email: Email = Email::try_new("\t [email protected] \n").unwrap();

// The underlying string that represents the email address is sanitized
assert_eq!(email.as_ref(), "[email protected]");
Expand Down
5 changes: 5 additions & 0 deletions nutype/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ categories = ["data-structures", "rust-patterns"]
[dependencies]
nutype_macros = { version = "0.4.2", path = "../nutype_macros" }

[dev-dependencies]
regex = "1.0"
lazy_static = "1.0"
once_cell = "1.0"

[features]
default = ["std"]

Expand Down
Loading

0 comments on commit 4ab24cc

Please sign in to comment.