Skip to content
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
7 changes: 7 additions & 0 deletions Cargo.lock

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

16 changes: 16 additions & 0 deletions examples/generics/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "fortifier-example-generics"
description = "Fortifier generics example."
publish = false

authors.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
version.workspace = true

[dependencies]
fortifier.workspace = true

[lints]
workspace = true
60 changes: 60 additions & 0 deletions examples/generics/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use std::fmt::Debug;

use fortifier::{Validate, ValidationErrors};

#[derive(Validate)]
#[validate(custom(function = validate_min_max, error = BoundsMinMaxError<T>))]
struct Bounds<T>
where
T: Clone + Debug + PartialEq + PartialOrd,
{
min: Option<T>,
max: Option<T>,
}

#[derive(Debug, PartialEq)]
struct BoundsMinMaxError<T>
where
T: Debug + PartialEq,
{
min: T,
max: T,
}

fn validate_min_max<T>(value: &Bounds<T>) -> Result<(), BoundsMinMaxError<T>>
where
T: Clone + Debug + PartialEq + PartialOrd,
{
if let Some(min) = &value.min
&& let Some(max) = &value.max
&& min > max
{
Err(BoundsMinMaxError {
min: min.clone(),
max: max.clone(),
})
} else {
Ok(())
}
}

fn main() {
let bounds = Bounds {
min: Some(1),
max: Some(10),
};

assert_eq!(bounds.validate_sync(), Ok(()));

let bounds = Bounds {
min: Some(11),
max: Some(10),
};

assert_eq!(
bounds.validate_sync(),
Err(ValidationErrors::from_iter([BoundsValidationError::Root(
BoundsMinMaxError { min: 11, max: 10 }
)]))
);
}
5 changes: 3 additions & 2 deletions packages/fortifier-macros-tests/tests/validations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use trybuild::TestCases;
#[test]
fn validations() {
let t = TestCases::new();
t.pass("tests/validations/*/*_pass.rs");
t.compile_fail("tests/validations/*/*_fail.rs");
t.pass("tests/validations/*/root_generics_pass.rs");
// t.pass("tests/validations/*/*_pass.rs");
// t.compile_fail("tests/validations/*/*_fail.rs");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::fmt::Debug;

use fortifier::{Validate, ValidationErrors};
use serde::{Deserialize, Serialize};

#[derive(Validate)]
#[validate(custom(function = validate_min_max, error = BoundsMinMaxError<T>))]
struct Bounds<T>
where
T: Clone + Debug + PartialEq + PartialOrd,
{
min: Option<T>,
max: Option<T>,
}

#[derive(Debug, Deserialize, PartialEq, Serialize)]
struct BoundsMinMaxError<T>
where
T: Debug + PartialEq,
{
min: T,
max: T,
}

fn validate_min_max<T>(value: &Bounds<T>) -> Result<(), BoundsMinMaxError<T>>
where
T: Clone + Debug + PartialEq + PartialOrd,
{
if let Some(min) = &value.min
&& let Some(max) = &value.max
&& min > max
{
Err(BoundsMinMaxError {
min: min.clone(),
max: max.clone(),
})
} else {
Ok(())
}
}

fn main() {
let bounds = Bounds {
min: Some(1),
max: Some(10),
};

assert_eq!(bounds.validate_sync(), Ok(()));

let bounds = Bounds {
min: Some(11),
max: Some(10),
};

assert_eq!(
bounds.validate_sync(),
Err(ValidationErrors::from_iter([BoundsValidationError::Root(
BoundsMinMaxError { min: 11, max: 10 }
)]))
);
}
1 change: 1 addition & 0 deletions packages/fortifier-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! Fortifier macros.

mod attributes;
mod util;
mod validate;
mod validation;
mod validations;
Expand Down
23 changes: 23 additions & 0 deletions packages/fortifier-macros/src/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use convert_case::{Case, Casing};
use quote::format_ident;
use syn::{GenericArgument, Ident, PathArguments, TypePath};

pub fn upper_camel_ident(ident: &Ident) -> Ident {
let s = ident.to_string();

if s.starts_with("r#") {
format_ident!("{}", (&s[2..]).to_case(Case::UpperCamel))
} else {
format_ident!("{}", s.to_case(Case::UpperCamel))
}
}

pub fn generic_arguments(r#type: &TypePath) -> Vec<GenericArgument> {
if let Some(segment) = r#type.path.segments.last()
&& let PathArguments::AngleBracketed(arguments) = &segment.arguments
{
arguments.args.iter().cloned().collect()
} else {
vec![]
}
}
1 change: 1 addition & 0 deletions packages/fortifier-macros/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod r#enum;
mod error;
mod field;
mod fields;
mod generics;
mod r#struct;
mod r#type;
mod r#union;
Expand Down
31 changes: 7 additions & 24 deletions packages/fortifier-macros/src/validate/enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::{

pub struct ValidateEnum<'a> {
visibility: &'a Visibility,
generics: &'a Generics,
ident: &'a Ident,
error_ident: Ident,
variants: Vec<ValidateEnumVariant<'a>>,
Expand All @@ -22,6 +23,7 @@ impl<'a> ValidateEnum<'a> {
pub fn parse(input: &'a DeriveInput, data: &'a DataEnum) -> Result<Self> {
let mut result = ValidateEnum {
visibility: &input.vis,
generics: &input.generics,
ident: &input.ident,
error_ident: format_error_ident(&input.ident),
variants: Vec::with_capacity(data.variants.len()),
Expand All @@ -41,39 +43,20 @@ impl<'a> ValidateEnum<'a> {
}

pub fn error_type(&self, root_error_type: Option<&ErrorType>) -> Option<ErrorType> {
if self.variants.is_empty() {
return None;
}

let variant_error_types = self
.variants
.iter()
.flat_map(|variant| variant.error_type(root_error_type))
.collect::<Vec<_>>();

if variant_error_types.is_empty() {
return None;
}

let variant_idents = variant_error_types
.iter()
.map(|ErrorType { variant_ident, .. }| variant_ident);
let variant_types = variant_error_types
.iter()
.map(|ErrorType { r#type, .. }| r#type);
let variant_definitions = variant_error_types
.iter()
.flat_map(|ErrorType { definition, .. }| definition);
.collect();

Some(combined_error_type(
combined_error_type(
self.visibility,
self.generics,
self.ident,
&self.error_ident,
variant_idents,
variant_types,
variant_definitions,
variant_error_types,
None,
))
)
}

pub fn validations(
Expand Down
Loading
Loading