Skip to content

Commit

Permalink
chore: add MaxSizeError::ZSTSequenceNotArray
Browse files Browse the repository at this point in the history
to make `BorshSchema` more congruent with `BorshSerialize, BorshDeserialize`
  • Loading branch information
dj8yf0μl committed Sep 11, 2023
1 parent f237c55 commit 63ea369
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
8 changes: 7 additions & 1 deletion borsh/src/schema_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ pub enum MaxSizeError {
/// Some of the declared types were lacking definition making it impossible
/// to calculate the size.
MissingDefinition,

/// sequences of zero sized types of dynamic length are forbidden by definition
ZSTSequenceNotArray,
}

/// Returns the largest possible size of a serialised object based solely on its type.
Expand Down Expand Up @@ -187,6 +190,9 @@ fn max_serialized_size_impl<'a>(
}
}
Ok(Definition::Sequence { elements }) => {
if is_zero_size(elements, schema) {
return Err(MaxSizeError::ZSTSequenceNotArray);
}
// Assume that sequence has MAX_LEN elements since that’s the most
// it can have.
let sz = max_serialized_size_impl(MAX_LEN, elements, schema, stack)?;
Expand Down Expand Up @@ -286,7 +292,7 @@ mod tests {
test_ok::<String>(4 + MAX_LEN);

test_err::<Vec<Vec<u8>>>(MaxSizeError::Overflow);
test_ok::<Vec<Vec<()>>>(4 + MAX_LEN * 4);
test_err::<Vec<Vec<()>>>(MaxSizeError::ZSTSequenceNotArray);
test_ok::<[[[(); MAX_LEN]; MAX_LEN]; MAX_LEN]>(0);
}

Expand Down
16 changes: 16 additions & 0 deletions borsh/tests/test_zero_sized_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,22 @@ fn test_serialize_vec_of_zst() {
assert_eq!(res.unwrap_err().to_string(), ERROR_ZST_FORBIDDEN);
}

#[test]
fn test_serialize_vec_of_unit_type() {
let v = vec![(), (), ()];
let res = to_vec(&v);
assert_eq!(res.unwrap_err().to_string(), ERROR_ZST_FORBIDDEN);
}

#[test]
fn test_serialize_vec_of_vec_of_unit_type() {
let v: Vec<Vec<()>> = vec![vec![(), (), ()]];
let res = to_vec(&v);
assert_eq!(res.unwrap_err().to_string(), ERROR_ZST_FORBIDDEN);
}



#[test]
fn test_deserialize_vec_deque_of_zst() {
let v = [0u8, 0u8, 0u8, 64u8];
Expand Down

0 comments on commit 63ea369

Please sign in to comment.