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

feat: inner option support #70

Merged
merged 4 commits into from
Sep 21, 2023
Merged
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
37 changes: 37 additions & 0 deletions garde/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ A Rust validation library
- [Inner type validation](#inner-type-validation)
- [Handling Option](#handling-option)
- [Custom validation](#custom-validation)
- [Custom validation with containers](#custom-validation-with-containers)
- [Context/Self access](#contextself-access)
- [Implementing rules](#implementing-rules)
- [Implementing `Validate`](#implementing-validate)
Expand Down Expand Up @@ -202,6 +203,42 @@ user.validate(&ctx)?;
The validator function may accept the value as a reference to any type which it derefs to.
In the above example, it is possible to use `&str`, because `password` is a `String`, and `String` derefs to `&str`.

### Custom validation with containers

When working with custom validators, if the type is a container such as `Vec<T>` or `Option<T>`, the validation function will get a reference to that container instead of the underlying data. This is in contrast with built-in validators that are able to extract the type from some container types such as `Option<T>`.
To validate the underlying data of a container when using a custom validator, use the `inner` modifier:

```rust,ignore
#[derive(garde::Validate)]
#[garde(context(PasswordContext))]
struct User {
#[garde(inner(custom(is_strong_password)))] // wrap the rule in `inner`
password: Option<String>, // this field will only be validated if it is the `Some` variant
}

struct PasswordContext {
min_entropy: f32,
entropy: cracken::password_entropy::EntropyEstimator,
}

fn is_strong_password(value: &str, context: &PasswordContext) -> garde::Result {
let bits = context.entropy.estimate_password_entropy(value.as_bytes())
.map(|e| e.mask_entropy)
.unwrap_or(0.0);
if bits < context.min_entropy {
return Err(garde::Error::new("password is not strong enough"));
}
Ok(())
}

let ctx = PasswordContext { /* ... */ };
let user = User { /* ... */ };
user.validate(&ctx)?;
```

The above type will always pass validation if the `password` field is `None`.
This allows you to use the same validation function for `T` as you do for `Option<T>` or `Vec<T>`.

### Context/Self access

It's generally possible to also access the context and `self`, because they are in scope in the output of the proc macro:
Expand Down
13 changes: 13 additions & 0 deletions garde/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,21 @@ pub struct Path {
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Kind {
None,
Key,
Index,
}

#[doc(hidden)]
#[derive(Default)]
pub struct NoKey(());

impl std::fmt::Display for NoKey {
fn fmt(&self, _: &mut std::fmt::Formatter) -> std::fmt::Result {
Ok(())
}
}

pub trait PathComponentKind: std::fmt::Display + ToCompactString + private::Sealed {
fn component_kind() -> Kind;
}
Expand All @@ -116,6 +127,7 @@ impl_path_component_kind!(@'a; &'a str => Key);
impl_path_component_kind!(@'a; Cow<'a, str> => Key);
impl_path_component_kind!(String => Key);
impl_path_component_kind!(CompactString => Key);
impl_path_component_kind!(NoKey => None);

impl<'a, T: PathComponentKind> private::Sealed for &'a T {}
impl<'a, T: PathComponentKind> PathComponentKind for &'a T {
Expand Down Expand Up @@ -204,6 +216,7 @@ impl std::fmt::Display for Path {
}
if let Some((kind, _)) = components.peek() {
match kind {
Kind::None => {}
Kind::Key => f.write_str(".")?,
Kind::Index => f.write_str("[")?,
}
Expand Down
17 changes: 16 additions & 1 deletion garde/src/rules/inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
//!
//! The entrypoint is the [`Inner`] trait. Implementing this trait for a type allows that type to be used with the `#[garde(inner(..))]` rule.

use crate::error::{NoKey, PathComponentKind};

pub fn apply<T, U, K, F>(field: &T, f: F)
where
T: Inner<U, Key = K>,
Expand All @@ -19,7 +21,7 @@ where
}

pub trait Inner<T> {
type Key;
type Key: PathComponentKind;

fn validate_inner<F>(&self, f: F)
where
Expand Down Expand Up @@ -60,3 +62,16 @@ impl<'a, T> Inner<T> for &'a [T] {
}
}
}

impl<T> Inner<T> for Option<T> {
type Key = NoKey;

fn validate_inner<F>(&self, mut f: F)
where
F: FnMut(&T, &Self::Key),
{
if let Some(item) = self {
f(item, &NoKey::default())
}
}
}
93 changes: 93 additions & 0 deletions garde/tests/rules/inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,96 @@ fn alphanumeric_invalid() {
&()
)
}

#[derive(Debug, garde::Validate)]
struct NotNestedOption<'a> {
#[garde(inner(alphanumeric))]
inner: Option<&'a str>,
}

#[derive(Debug, garde::Validate)]
struct NestedSliceInsideOption<'a> {
#[garde(inner(inner(alphanumeric)))]
inner: Option<&'a [&'a str]>,
}

#[derive(Debug, garde::Validate)]
struct DoubleNestedSliceInsideOption<'a> {
#[garde(inner(inner(inner(alphanumeric))))]
inner: Option<&'a [&'a [&'a str]]>,
}

#[derive(Debug, garde::Validate)]
struct OptionInsideSlice<'a> {
#[garde(inner(inner(alphanumeric)))]
inner: &'a [Option<&'a str>],
}

#[test]
fn alphanumeric_some_valid() {
util::check_ok(
&[NotNestedOption {
inner: Some("abcd0123"),
}],
&(),
);
util::check_ok(
&[NestedSliceInsideOption {
inner: Some(&["abcd0123"]),
}],
&(),
);
util::check_ok(
&[DoubleNestedSliceInsideOption {
inner: Some(&[&["abcd0123"]]),
}],
&(),
);
util::check_ok(
&[OptionInsideSlice {
inner: &[Some("abcd0123")],
}],
&(),
)
}

#[test]
fn alphanumeric_some_invalid() {
util::check_fail!(
&[NotNestedOption {
inner: Some("!!!!"),
}],
&(),
);
util::check_fail!(
&[NestedSliceInsideOption {
inner: Some(&["!!!!"]),
}],
&(),
);
util::check_fail!(
&[DoubleNestedSliceInsideOption {
inner: Some(&[&["!!!!"]]),
}],
&(),
);
util::check_fail!(
&[OptionInsideSlice {
inner: &[Some("!!!!")],
}],
&(),
)
}

#[test]
fn alphanumeric_none_valid() {
util::check_ok(&[NotNestedOption { inner: None }], &());
util::check_ok(&[NestedSliceInsideOption { inner: None }], &());
util::check_ok(&[DoubleNestedSliceInsideOption { inner: None }], &());
util::check_ok(
&[OptionInsideSlice {
inner: &[None, None],
}],
&(),
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
source: garde/tests/./rules/inner.rs
assertion_line: 90
expression: snapshot
---
NestedSliceInsideOption {
inner: Some(
[
"!!!!",
],
),
}
inner[0]: not alphanumeric


Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
source: garde/tests/./rules/inner.rs
assertion_line: 96
expression: snapshot
---
DoubleNestedSliceInsideOption {
inner: Some(
[
[
"!!!!",
],
],
),
}
inner[0][0]: not alphanumeric


Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
source: garde/tests/./rules/inner.rs
assertion_line: 102
expression: snapshot
---
OptionInsideSlice {
inner: [
Some(
"!!!!",
),
],
}
inner[0]: not alphanumeric


Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
source: garde/tests/./rules/inner.rs
assertion_line: 84
expression: snapshot
---
NotNestedOption {
inner: Some(
"!!!!",
),
}
inner: not alphanumeric