Skip to content

Commit

Permalink
Replace vec! from deserialization with static array
Browse files Browse the repository at this point in the history
  • Loading branch information
danlehmann committed Jul 23, 2024
1 parent d4f6c7c commit aeb986e
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
10 changes: 7 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ use core::ops::{
use serde::{Deserialize, Deserializer, Serialize, Serializer};

#[cfg(all(feature = "borsh", not(feature = "std")))]
use alloc::{collections::BTreeMap, string::ToString, vec};
use alloc::{collections::BTreeMap, string::ToString};

#[cfg(all(feature = "borsh", feature = "std"))]
use std::{collections::BTreeMap, string::ToString, vec};
use std::{collections::BTreeMap, string::ToString};

#[cfg(feature = "schemars")]
use schemars::JsonSchema;
Expand Down Expand Up @@ -1105,7 +1105,11 @@ where
Self: Number,
{
fn deserialize_reader<R: borsh::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
let mut buf = vec![0u8; core::mem::size_of::<T>()];
// Ideally, we'd want a buffer of size `BITS >> 3` or `size_of::<T>`, but that's not possible
// with arrays.
// So instead we'll do a 16 byte buffer which handles the largest arbitrary-ints possible -
// not ideal, but still pretty small and better than going through an allocator.
let mut buf = [0u8; 16];
reader.read(&mut buf)?;
let value = T::deserialize(&mut &buf[..])?;
if value >= Self::MIN.value() && value <= Self::MAX.value() {
Expand Down
4 changes: 1 addition & 3 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1914,9 +1914,7 @@ fn serde() {

#[cfg(feature = "borsh")]
mod borsh_tests {
use arbitrary_int::{
u1, u14, u15, u50, u6, u63, u65, u7, u72, u79, u80, u81, u9, Number, UInt,
};
use arbitrary_int::{u1, u14, u15, u6, u63, u65, u7, u72, u79, u80, u81, u9, Number, UInt};
use borsh::schema::BorshSchemaContainer;
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use std::fmt::Debug;
Expand Down

0 comments on commit aeb986e

Please sign in to comment.