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
2 changes: 1 addition & 1 deletion crates/serde_valid/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Serde Valid support standard validation based JSON Schema.
| Array | `#[validate(max_items = 5)]` | [`ValidateMaxItems`] | [maxItems](https://json-schema.org/understanding-json-schema/reference/array#length) |
| Array | `#[validate(min_items = 5)]` | [`ValidateMinItems`] | [minItems](https://json-schema.org/understanding-json-schema/reference/array#length) |
| Array | `#[validate(unique_items)]` | [`ValidateUniqueItems`] | [uniqueItems](https://json-schema.org/understanding-json-schema/reference/array#uniqueItems) |
| Generic | `#[validate(enumerate = [5, 10, 15])]` | [`ValidateEnumerate`] | [enum](https://json-schema.org/understanding-json-schema/reference/enum) |
| Generic | `#[validate(r#enum = [5, 10, 15])]` | [`ValidateEnum`] | [enum](https://json-schema.org/understanding-json-schema/reference/enum) |

In addition, [serde_valid::utils][module@crate::utils] provides a type of validation not described in the JSON schema specification.

Expand Down
4 changes: 2 additions & 2 deletions crates/serde_valid/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ struct_error_params!(
struct_error_params!(
#[derive(Debug, Clone)]
#[default_message = "The value must be in [{:}]."]
pub struct EnumerateError {
pub enumerate: Vec<Literal>,
pub struct EnumError {
pub candidates: Vec<Literal>,
}
);
2 changes: 1 addition & 1 deletion crates/serde_valid/src/features/fluent/localize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl Localize for crate::validation::Error {
Self::UniqueItems(message) => message.localize(bundle),
Self::MinProperties(message) => message.localize(bundle),
Self::MaxProperties(message) => message.localize(bundle),
Self::Enumerate(message) => message.localize(bundle),
Self::Enum(message) => message.localize(bundle),
Self::Custom(message) => LocalizedError::String(message.to_string()),
Self::Items(message) => LocalizedError::Items(message.localize(bundle)),
Self::Properties(message) => LocalizedError::Properties(message.localize(bundle)),
Expand Down
2 changes: 1 addition & 1 deletion crates/serde_valid/src/features/fluent/try_localize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ impl TryLocalize for crate::validation::Error {
Self::UniqueItems(message) => message.try_localize(bundle),
Self::MinProperties(message) => message.try_localize(bundle),
Self::MaxProperties(message) => message.try_localize(bundle),
Self::Enumerate(message) => message.try_localize(bundle),
Self::Enum(message) => message.try_localize(bundle),
Self::Custom(message) => Ok(LocalizedError::String(message.to_string())),
Self::Items(message) => Ok(LocalizedError::Items(message.try_localize(bundle)?)),
Self::Properties(message) => {
Expand Down
10 changes: 5 additions & 5 deletions crates/serde_valid/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
//! | Array | `#[validate(max_items = 5)]` | [`ValidateMaxItems`] | [maxItems](https://json-schema.org/understanding-json-schema/reference/array#length) |
//! | Array | `#[validate(min_items = 5)]` | [`ValidateMinItems`] | [minItems](https://json-schema.org/understanding-json-schema/reference/array#length) |
//! | Array | `#[validate(unique_items)]` | [`ValidateUniqueItems`] | [uniqueItems](https://json-schema.org/understanding-json-schema/reference/array#uniqueItems) |
//! | Generic | `#[validate(enumerate = [5, 10, 15])]` | [`ValidateEnumerate`] | [enum](https://json-schema.org/understanding-json-schema/reference/enum) |
//! | Generic | `#[validate(r#enum = [5, 10, 15])]` | [`ValidateEnum`] | [enum](https://json-schema.org/understanding-json-schema/reference/enum) |
//!
//! In addition, [serde_valid::utils][module@crate::utils] provides a type of validation not described in the JSON schema specification.
//!
Expand Down Expand Up @@ -579,16 +579,16 @@ pub mod utils;
pub mod validation;

pub use error::{
EnumerateError, Error, ExclusiveMaximumError, ExclusiveMinimumError, MaxItemsError,
MaxLengthError, MaxPropertiesError, MaximumError, MinItemsError, MinLengthError,
MinPropertiesError, MinimumError, MultipleOfError, PatternError, UniqueItemsError,
EnumError, Error, ExclusiveMaximumError, ExclusiveMinimumError, MaxItemsError, MaxLengthError,
MaxPropertiesError, MaximumError, MinItemsError, MinLengthError, MinPropertiesError,
MinimumError, MultipleOfError, PatternError, UniqueItemsError,
};
#[allow(unused_imports)]
pub use features::*;
use indexmap::IndexMap;
use std::{borrow::Cow, collections::HashMap};
pub use validation::{
ValidateEnumerate, ValidateExclusiveMaximum, ValidateExclusiveMinimum, ValidateMaxItems,
ValidateEnum, ValidateExclusiveMaximum, ValidateExclusiveMinimum, ValidateMaxItems,
ValidateMaxLength, ValidateMaxProperties, ValidateMaximum, ValidateMinItems, ValidateMinLength,
ValidateMinProperties, ValidateMinimum, ValidateMultipleOf, ValidatePattern,
ValidateUniqueItems,
Expand Down
14 changes: 5 additions & 9 deletions crates/serde_valid/src/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ mod object;
mod string;

use crate::{
EnumerateError, ExclusiveMaximumError, ExclusiveMinimumError, MaxLengthError,
MaxPropertiesError, MaximumError, MinLengthError, MinPropertiesError, MinimumError,
MultipleOfError, PatternError,
EnumError, ExclusiveMaximumError, ExclusiveMinimumError, MaxLengthError, MaxPropertiesError,
MaximumError, MinLengthError, MinPropertiesError, MinimumError, MultipleOfError, PatternError,
};
pub use composited::Composited;

Expand All @@ -19,7 +18,7 @@ pub use error::{
ArrayErrors, Error, Errors, IntoError, ItemErrorsMap, ItemVecErrorsMap, ObjectErrors,
PropertyErrorsMap, PropertyVecErrorsMap, VecErrors,
};
pub use generic::ValidateEnumerate;
pub use generic::ValidateEnum;
use indexmap::IndexMap;
pub use numeric::{
ValidateExclusiveMaximum, ValidateExclusiveMinimum, ValidateMaximum, ValidateMinimum,
Expand Down Expand Up @@ -417,10 +416,7 @@ impl_composited_validation_1args!(

// Generic
impl_composited_validation_1args!(
pub trait ValidateCompositedEnumerate<T> {
fn validate_composited_enumerate(
&self,
enumerate: T,
) -> Result<(), Composited<EnumerateError>>;
pub trait ValidateCompositedEnum<T> {
fn validate_composited_enum(&self, candidates: T) -> Result<(), Composited<EnumError>>;
}
);
4 changes: 2 additions & 2 deletions crates/serde_valid/src/validation/composited.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::validation::error::IntoError;

use crate::error::{
EnumerateError, ExclusiveMaximumError, ExclusiveMinimumError, MaxItemsError, MaxLengthError,
EnumError, ExclusiveMaximumError, ExclusiveMinimumError, MaxItemsError, MaxLengthError,
MaxPropertiesError, MaximumError, MinItemsError, MinLengthError, MinPropertiesError,
MinimumError, MultipleOfError, PatternError, UniqueItemsError,
};
Expand Down Expand Up @@ -55,7 +55,7 @@ macro_rules! impl_into_error {
}

// Global
impl_into_error!(Enumerate);
impl_into_error!(Enum);

// Numeric
impl_into_error!(Maximum);
Expand Down
4 changes: 2 additions & 2 deletions crates/serde_valid/src/validation/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ mod object_errors;
use std::borrow::Cow;

pub use crate::error::{
EnumerateError, ExclusiveMaximumError, ExclusiveMinimumError, MaxItemsError, MaxLengthError,
EnumError, ExclusiveMaximumError, ExclusiveMinimumError, MaxItemsError, MaxLengthError,
MaxPropertiesError, MaximumError, MinItemsError, MinLengthError, MinPropertiesError,
MinimumError, MultipleOfError, PatternError, UniqueItemsError,
};
Expand Down Expand Up @@ -77,7 +77,7 @@ pub enum Error {

#[error("{0}")]
#[serde(serialize_with = "serialize_error_message")]
Enumerate(Message<EnumerateError>),
Enum(Message<EnumError>),

#[error("{0}")]
#[serde(serialize_with = "serialize_error_message")]
Expand Down
4 changes: 2 additions & 2 deletions crates/serde_valid/src/validation/generic.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
mod enumerate;
pub use enumerate::ValidateEnumerate;
mod r#enum;
pub use r#enum::ValidateEnum;
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
use crate::validation::ValidateCompositedEnumerate;
use crate::EnumerateError;
use crate::validation::ValidateCompositedEnum;
use crate::EnumError;

/// Enumerate validation.
///
/// See <https://json-schema.org/understanding-json-schema/reference/generic.html#enumerated-values>
///
/// Note: `#[validate(enumerate = ...)]` is deprecated; use `#[validate(r#enum = ...)]`.
///
/// ```rust
/// use serde_json::json;
/// use serde_valid::{Validate, ValidateEnumerate};
/// use serde_valid::{Validate, ValidateEnum};
///
/// struct MyType(String);
///
/// impl ValidateEnumerate<&'static str> for MyType {
/// fn validate_enumerate(
/// impl ValidateEnum<&'static str> for MyType {
/// fn validate_enum(
/// &self,
/// enumerate: &[&'static str],
/// ) -> Result<(), serde_valid::EnumerateError> {
/// self.0.validate_enumerate(enumerate)
/// candidates: &[&'static str],
/// ) -> Result<(), serde_valid::EnumError> {
/// self.0.validate_enum(candidates)
/// }
/// }
///
/// #[derive(Validate)]
/// struct TestStruct {
/// #[validate(enumerate = ["1", "2", "3"])]
/// #[validate(r#enum = ["1", "2", "3"])]
/// val: MyType,
/// }
///
Expand All @@ -43,31 +45,31 @@ use crate::EnumerateError;
/// .to_string()
/// );
/// ```
pub trait ValidateEnumerate<T> {
fn validate_enumerate(&self, enumerate: &[T]) -> Result<(), EnumerateError>;
pub trait ValidateEnum<T> {
fn validate_enum(&self, candidates: &[T]) -> Result<(), EnumError>;
}

macro_rules! impl_validate_generic_enumerate_literal {
($type:ty) => {
impl ValidateEnumerate<$type> for $type {
fn validate_enumerate(&self, enumerate: &[$type]) -> Result<(), EnumerateError> {
if enumerate.iter().any(|candidate| candidate == self) {
impl ValidateEnum<$type> for $type {
fn validate_enum(&self, candidates: &[$type]) -> Result<(), EnumError> {
if candidates.iter().any(|candidate| candidate == self) {
Ok(())
} else {
Err(EnumerateError::new(enumerate))
Err(EnumError::new(candidates))
}
}
}

impl<T> ValidateCompositedEnumerate<&[$type]> for T
impl<T> ValidateCompositedEnum<&[$type]> for T
where
T: ValidateEnumerate<$type>,
T: ValidateEnum<$type>,
{
fn validate_composited_enumerate(
fn validate_composited_enum(
&self,
limit: &[$type],
) -> Result<(), crate::validation::Composited<EnumerateError>> {
self.validate_enumerate(limit)
) -> Result<(), crate::validation::Composited<EnumError>> {
self.validate_enum(limit)
.map_err(|error| crate::validation::Composited::Single(error))
}
}
Expand Down Expand Up @@ -108,12 +110,12 @@ impl_validate_generic_enumerate_literal!(char);

macro_rules! impl_validate_generic_enumerate_str {
($type:ty) => {
impl ValidateEnumerate<&'static str> for $type {
fn validate_enumerate(&self, enumerate: &[&'static str]) -> Result<(), EnumerateError> {
if enumerate.iter().any(|candidate| candidate == self) {
impl ValidateEnum<&'static str> for $type {
fn validate_enum(&self, candidates: &[&'static str]) -> Result<(), EnumError> {
if candidates.iter().any(|candidate| candidate == self) {
Ok(())
} else {
Err(EnumerateError::new(enumerate))
Err(EnumError::new(candidates))
}
}
}
Expand All @@ -128,15 +130,15 @@ impl_validate_generic_enumerate_str!(std::ffi::OsString);

macro_rules! impl_validate_generic_enumerate_path {
($type:ty) => {
impl ValidateEnumerate<&'static str> for $type {
fn validate_enumerate(&self, enumerate: &[&'static str]) -> Result<(), EnumerateError> {
if enumerate
impl ValidateEnum<&'static str> for $type {
fn validate_enum(&self, candidates: &[&'static str]) -> Result<(), EnumError> {
if candidates
.iter()
.any(|candidate| &std::path::Path::new(candidate) == self)
{
Ok(())
} else {
Err(EnumerateError::new(enumerate))
Err(EnumError::new(candidates))
}
}
}
Expand All @@ -146,15 +148,15 @@ macro_rules! impl_validate_generic_enumerate_path {
impl_validate_generic_enumerate_path!(&std::path::Path);
impl_validate_generic_enumerate_path!(std::path::PathBuf);

impl<T> ValidateCompositedEnumerate<&[&'static str]> for T
impl<T> ValidateCompositedEnum<&[&'static str]> for T
where
T: ValidateEnumerate<&'static str>,
T: ValidateEnum<&'static str>,
{
fn validate_composited_enumerate(
fn validate_composited_enum(
&self,
limit: &[&'static str],
) -> Result<(), crate::validation::Composited<EnumerateError>> {
self.validate_enumerate(limit)
) -> Result<(), crate::validation::Composited<EnumError>> {
self.validate_enum(limit)
.map_err(crate::validation::Composited::Single)
}
}
Expand All @@ -165,72 +167,60 @@ mod tests {

#[test]
fn test_validate_integer_vec_type_is_true() {
assert!(ValidateEnumerate::validate_enumerate(&1, &[1, 2, 3]).is_ok());
assert!(ValidateEnum::validate_enum(&1, &[1, 2, 3]).is_ok());
}

#[test]
fn test_validate_integer_vec_type_is_false() {
assert!(ValidateEnumerate::validate_enumerate(&1, &[2, 3, 4]).is_err());
assert!(ValidateEnum::validate_enum(&1, &[2, 3, 4]).is_err());
}

#[test]
fn test_validate_float_type_is_true() {
assert!(ValidateEnumerate::validate_enumerate(&0.9, &[0.9, 2.3, -3.0]).is_ok());
assert!(ValidateEnum::validate_enum(&0.9, &[0.9, 2.3, -3.0]).is_ok());
}

#[test]
fn test_validate_float_type_is_false() {
assert!(ValidateEnumerate::validate_enumerate(&0.9, &[0.8, 2.3, -3.0]).is_err());
assert!(ValidateEnum::validate_enum(&0.9, &[0.8, 2.3, -3.0]).is_err());
}

#[test]
fn test_validate_unsigned_int_type() {
assert!(ValidateEnumerate::validate_enumerate(&1, &[-1, 0, 1, 2, 3]).is_ok());
assert!(ValidateEnum::validate_enum(&1, &[-1, 0, 1, 2, 3]).is_ok());
}

#[test]
fn test_validate_str_type() {
assert!(ValidateEnumerate::validate_enumerate(&'a', &['a', 'b', 'c']).is_ok());
assert!(ValidateEnum::validate_enum(&'a', &['a', 'b', 'c']).is_ok());
}

#[test]
fn test_validate_string_type() {
assert!(ValidateEnumerate::validate_enumerate(&'a', &['a', 'b', 'c']).is_ok());
assert!(ValidateEnum::validate_enum(&'a', &['a', 'b', 'c']).is_ok());
}

#[test]
fn test_validate_os_str_type() {
assert!(ValidateEnumerate::validate_enumerate(
&std::ffi::OsStr::new("a"),
&["a", "b", "c"]
)
.is_ok());
assert!(ValidateEnum::validate_enum(&std::ffi::OsStr::new("a"), &["a", "b", "c"]).is_ok());
}

#[test]
fn test_validate_os_string_type() {
assert!(ValidateEnumerate::validate_enumerate(
&std::ffi::OsString::from("a"),
&["a", "b", "c"]
)
.is_ok());
assert!(
ValidateEnum::validate_enum(&std::ffi::OsString::from("a"), &["a", "b", "c"]).is_ok()
);
}

#[test]
fn test_validate_path_type() {
assert!(ValidateEnumerate::validate_enumerate(
&std::path::Path::new("a"),
&["a", "b", "c"]
)
.is_ok());
assert!(ValidateEnum::validate_enum(&std::path::Path::new("a"), &["a", "b", "c"]).is_ok());
}

#[test]
fn test_validate_path_buf_type() {
assert!(ValidateEnumerate::validate_enumerate(
&std::path::PathBuf::from("a"),
&["a", "b", "c"]
)
.is_ok());
assert!(
ValidateEnum::validate_enum(&std::path::PathBuf::from("a"), &["a", "b", "c"]).is_ok()
);
}
}
Loading
Loading