Skip to content

Commit

Permalink
u32::MAX limit for borsh
Browse files Browse the repository at this point in the history
  • Loading branch information
dzmitry-lahoda committed Jan 22, 2025
1 parent 667c0d1 commit efb92f1
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion src/bounded_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -445,8 +445,41 @@ mod borsh_impl {
use alloc::collections::btree_map::{BTreeMap, Entry};
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};

// we panic of U is bigger then it should be

impl<T, const L: usize, const U: usize> super::BoundedVec<T, L, U>
where
Self: BorshSerialize,
{
/// Internal const assert.
const fn __assert_borsh_ser_upper_limit_under_u32_max() {
assert!(U <= u32::MAX as usize)
}
}

impl<T, const L: usize, const U: usize> super::BoundedVec<T, L, U>
where
Self: BorshDeserialize,
{
/// Internal const assert
const fn __assert_borsh_de_upper_limit_under_u32_max() {
assert!(U <= u32::MAX as usize)
}
}

impl<T, const L: usize, const U: usize> super::BoundedVec<T, L, U>
where
Self: BorshSchema,
{
/// Internal const assert
const fn __assert_borsh_schema_upper_limit_under_u32_max() {
assert!(U <= u32::MAX as usize)
}
}

impl<T: BorshSerialize, const L: usize, const U: usize> BorshSerialize for BoundedVec<T, L, U> {
fn serialize<W: borsh::io::Write>(&self, writer: &mut W) -> borsh::io::Result<()> {
Self::__assert_borsh_ser_upper_limit_under_u32_max();
if U <= u8::MAX as usize {
(self.len() as u8).serialize(writer)?;
} else if U <= u16::MAX as usize {
Expand All @@ -470,6 +503,7 @@ mod borsh_impl {

impl<T: BorshDeserialize, const L: usize, const U: usize> BorshDeserialize for BoundedVec<T, L, U> {
fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
Self::__assert_borsh_de_upper_limit_under_u32_max();
let len = if U <= u8::MAX as usize {
u8::deserialize_reader(reader)? as usize
} else if U <= u16::MAX as usize {
Expand Down Expand Up @@ -514,6 +548,7 @@ mod borsh_impl {
fn add_definitions_recursively(
definitions: &mut BTreeMap<borsh::schema::Declaration, borsh::schema::Definition>,
) {
Self::__assert_borsh_schema_upper_limit_under_u32_max();
use borsh::schema::Definition;
let len_width = if U <= u8::MAX as usize {
1
Expand Down Expand Up @@ -556,7 +591,7 @@ mod borsh_impl {
use super::*;
#[test]
#[allow(clippy::expect_used)]
fn enddec() {
fn encdec() {
let data: BoundedVec<u8, 2, 8> = vec![1u8, 2].try_into().expect("borsh works");
let buf = &mut Vec::new();
data.serialize(buf).expect("borsh works");
Expand Down

0 comments on commit efb92f1

Please sign in to comment.