Skip to content

Commit

Permalink
chore: add Declaration-s to validate errors to simplify finding error
Browse files Browse the repository at this point in the history
  • Loading branch information
dj8yf0μl committed Sep 18, 2023
1 parent 75963a3 commit 7fca4e0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
16 changes: 10 additions & 6 deletions borsh/src/schema/container_ext/validate.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::is_zero_size;
use super::{BorshSchemaContainer, Declaration, Definition, Fields};
use crate::__private::maybestd::vec::Vec;
use crate::__private::maybestd::{string::ToString, vec::Vec};

impl BorshSchemaContainer {
/// Validates container for violation of any well-known rules with
Expand All @@ -25,13 +25,13 @@ impl BorshSchemaContainer {

/// Possible error when validating a [`BorshSchemaContainer`], generated for some type `T`,
/// for violation of any well-known rules with respect to `borsh` serialization.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SchemaContainerValidateError {
/// sequences of zero-sized types of dynamic length are forbidden by definition
/// see <https://github.com/near/borsh-rs/pull/202> and related ones
ZSTSequence,
ZSTSequence(Declaration),
/// Declared tag width is too large. Tags may be at most eight bytes.
TagTooWide,
TagTooWide(Declaration),
}

fn validate_impl<'a>(
Expand All @@ -58,7 +58,9 @@ fn validate_impl<'a>(
// or it uses `Definiotion::Enum` or `Definition::Sequence` to exit from recursion
// which make it non-zero size
if is_zero_size(elements, schema).unwrap_or(false) {
return Err(SchemaContainerValidateError::ZSTSequence);
return Err(SchemaContainerValidateError::ZSTSequence(
declaration.to_string(),
));
}
validate_impl(elements, schema, stack)?;
}
Expand All @@ -67,7 +69,9 @@ fn validate_impl<'a>(
variants,
} => {
if *tag_width > 8 {
return Err(SchemaContainerValidateError::TagTooWide);
return Err(SchemaContainerValidateError::TagTooWide(
declaration.to_string(),
));
}
for (_, variant) in variants {
validate_impl(variant, schema, stack)?;
Expand Down
8 changes: 6 additions & 2 deletions borsh/tests/test_schema_validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ fn validate_for_derived_types() {

#[test]
fn validate_for_zst_sequences() {
test_err::<Vec<Vec<()>>>(SchemaContainerValidateError::ZSTSequence);
test_err::<Vec<core::ops::RangeFull>>(SchemaContainerValidateError::ZSTSequence);
test_err::<Vec<Vec<()>>>(SchemaContainerValidateError::ZSTSequence(
"Vec<nil>".to_string(),
));
test_err::<Vec<core::ops::RangeFull>>(SchemaContainerValidateError::ZSTSequence(
"Vec<RangeFull>".to_string(),
));
}

0 comments on commit 7fca4e0

Please sign in to comment.