Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore!: deprecate try_to_vec method from BorshSerialize #206

Merged
merged 1 commit into from
Aug 29, 2023
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ strict [specification](https://github.com/near/borsh#specification).
## Example

```rust
use borsh::{BorshSerialize, BorshDeserialize, from_slice};
use borsh::{BorshSerialize, BorshDeserialize, from_slice, to_vec};

#[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug)]
struct A {
Expand All @@ -33,7 +33,7 @@ fn test_simple_struct() {
x: 3301,
y: "liber primus".to_string(),
};
let encoded_a = a.try_to_vec().unwrap();
let encoded_a = to_vec(&a).unwrap();
let decoded_a = from_slice::<A>(&encoded_a).unwrap();
assert_eq!(a, decoded_a);
}
Expand Down
8 changes: 4 additions & 4 deletions benchmarks/benches/bench.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use benchmarks::{Account, Block, BlockHeader, Generate, SignedTransaction};
use borsh::{from_slice, BorshDeserialize, BorshSerialize};
use borsh::{from_slice, to_vec, BorshDeserialize, BorshSerialize};
use rand::SeedableRng;
use serde::{Deserialize as SerdeDeserialize, Serialize as SerdeSerialize};
use speedy::Endianness;
Expand All @@ -22,7 +22,7 @@ where
let mut group = c.benchmark_group(group_name);

let objects: Vec<_> = (0..num_samples).map(|_| T::generate(&mut rng)).collect();
let borsh_datas: Vec<Vec<u8>> = objects.iter().map(|t| t.try_to_vec().unwrap()).collect();
let borsh_datas: Vec<Vec<u8>> = objects.iter().map(|t| to_vec(t).unwrap()).collect();
let borsh_sizes: Vec<_> = borsh_datas.iter().map(|d| d.len()).collect();

for i in 0..objects.len() {
Expand Down Expand Up @@ -50,7 +50,7 @@ where
BenchmarkId::new("borsh", benchmark_param_display.clone()),
obj,
|b, d| {
b.iter(|| d.try_to_vec().unwrap());
b.iter(|| to_vec(d).unwrap());
},
);
group.bench_with_input(
Expand Down Expand Up @@ -87,7 +87,7 @@ where
.iter()
.map(|t| bincode::serialize(t).unwrap())
.collect();
let borsh_datas: Vec<Vec<u8>> = objects.iter().map(|t| t.try_to_vec().unwrap()).collect();
let borsh_datas: Vec<Vec<u8>> = objects.iter().map(|t| to_vec(t).unwrap()).collect();
let speedy_datas: Vec<Vec<u8>> = objects
.iter()
.map(|t| t.write_to_vec(Endianness::LittleEndian).unwrap())
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/benches/maps_sets_inner_de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{
};

use benchmarks::{Generate, PublicKey};
use borsh::{from_slice, BorshDeserialize, BorshSerialize};
use borsh::{from_slice, to_vec, BorshDeserialize, BorshSerialize};
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use rand::SeedableRng;

Expand All @@ -21,7 +21,7 @@ where

let collection: U = (0..num_samples).map(|_| T::generate(&mut rng)).collect();

let serialized: Vec<u8> = collection.try_to_vec().unwrap();
let serialized: Vec<u8> = to_vec(&collection).unwrap();

group.bench_with_input(BenchmarkId::new("borsh_de", ""), &serialized, |b, d| {
b.iter(|| from_slice::<U>(d).unwrap());
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/benches/maps_sets_inner_ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
iter::FromIterator,
};

use borsh::BorshSerialize;
use borsh::{to_vec, BorshSerialize};

use benchmarks::Generate;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
Expand All @@ -23,7 +23,7 @@ where
let collection: U = (0..num_samples).map(|_| T::generate(&mut rng)).collect();

group.bench_with_input(BenchmarkId::new("borsh_ser", ""), &collection, |b, d| {
b.iter(|| d.try_to_vec().unwrap());
b.iter(|| to_vec(d).unwrap());
});
}

Expand Down
8 changes: 4 additions & 4 deletions borsh/src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -871,7 +871,7 @@ impl<T: ?Sized> BorshDeserialize for PhantomData<T> {
/// Deserializes an object from a slice of bytes.
/// # Example
/// ```
/// use borsh::{BorshDeserialize, BorshSerialize, from_slice};
/// use borsh::{BorshDeserialize, BorshSerialize, from_slice, to_vec};
///
/// /// derive is only available if borsh is built with `features = ["derive"]`
/// # #[cfg(feature = "derive")]
Expand All @@ -884,7 +884,7 @@ impl<T: ?Sized> BorshDeserialize for PhantomData<T> {
/// # #[cfg(feature = "derive")]
/// let original = MyStruct { a: 10, b: vec![1, 2, 3] };
/// # #[cfg(feature = "derive")]
/// let encoded = original.try_to_vec().unwrap();
/// let encoded = to_vec(&original).unwrap();
/// # #[cfg(feature = "derive")]
/// let decoded = from_slice::<MyStruct>(&encoded).unwrap();
/// # #[cfg(feature = "derive")]
Expand All @@ -911,7 +911,7 @@ pub fn from_slice<T: BorshDeserialize>(v: &[u8]) -> Result<T> {
/// Deserializes an object from a reader.
/// # Example
/// ```
/// use borsh::{BorshDeserialize, BorshSerialize, from_reader};
/// use borsh::{BorshDeserialize, BorshSerialize, from_reader, to_vec};
///
/// /// derive is only available if borsh is built with `features = ["derive"]`
/// # #[cfg(feature = "derive")]
Expand All @@ -924,7 +924,7 @@ pub fn from_slice<T: BorshDeserialize>(v: &[u8]) -> Result<T> {
/// # #[cfg(feature = "derive")]
/// let original = MyStruct { a: 10, b: vec![1, 2, 3] };
/// # #[cfg(feature = "derive")]
/// let encoded = original.try_to_vec().unwrap();
/// let encoded = to_vec(&original).unwrap();
/// # #[cfg(feature = "derive")]
/// let decoded = from_reader::<_, MyStruct>(&mut encoded.as_slice()).unwrap();
/// # #[cfg(feature = "derive")]
Expand Down
7 changes: 3 additions & 4 deletions borsh/src/generate_schema_schema.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
//! Generate `BorshSchemaCointainer` for `BorshSchemaContainer` and save it into a file.

#![cfg_attr(not(feature = "std"), no_std)]
use borsh::{schema_container_of, BorshSerialize};
use borsh::schema_container_of;
use std::fs::File;
use std::io::Write;

fn main() {
let container = schema_container_of::<borsh::schema::BorshSchemaContainer>();

println!("{:#?}", container);
let data = container
.try_to_vec()
.expect("Failed to serialize BorshSchemaContainer");

let data = borsh::to_vec(&container).expect("Failed to serialize BorshSchemaContainer");
let mut file = File::create("schema_schema.dat").expect("Failed to create file");
file.write_all(&data).expect("Failed to write file");
}
2 changes: 1 addition & 1 deletion borsh/src/schema_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub fn try_from_slice_with_schema<T: BorshDeserialize + BorshSchema>(v: &[u8]) -
/// bytes in Borsh format.
pub fn try_to_vec_with_schema<T: BorshSerialize + BorshSchema>(value: &T) -> Result<Vec<u8>> {
let schema = schema_container_of::<T>();
let mut res = schema.try_to_vec()?;
let mut res = crate::to_vec(&schema)?;
value.serialize(&mut res)?;
Ok(res)
}
Expand Down
6 changes: 5 additions & 1 deletion borsh/src/ser/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ use crate::__private::maybestd::{
vec::Vec,
};

pub(super) const DEFAULT_SERIALIZER_CAPACITY: usize = 1024;

/// Serialize an object into a vector of bytes.
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
where
T: BorshSerialize + ?Sized,
{
value.try_to_vec()
let mut result = Vec::with_capacity(DEFAULT_SERIALIZER_CAPACITY);
value.serialize(&mut result)?;
Ok(result)
}

/// Serializes an object directly into a `Writer`.
Expand Down
5 changes: 2 additions & 3 deletions borsh/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ use crate::__private::maybestd::{rc::Rc, sync::Arc};

pub(crate) mod helpers;

const DEFAULT_SERIALIZER_CAPACITY: usize = 1024;

/// A data-structure that can be serialized into binary format by NBOR.
///
/// ```
Expand Down Expand Up @@ -57,8 +55,9 @@ pub trait BorshSerialize {
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()>;

/// Serialize this instance into a vector of bytes.
#[deprecated = "use `borsh::to_vec(&object)` instead"]
fn try_to_vec(&self) -> Result<Vec<u8>> {
let mut result = Vec::with_capacity(DEFAULT_SERIALIZER_CAPACITY);
let mut result = Vec::with_capacity(helpers::DEFAULT_SERIALIZER_CAPACITY);
self.serialize(&mut result)?;
Ok(result)
}
Expand Down
5 changes: 3 additions & 2 deletions borsh/tests/common_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ macro_rules! set_insert_deser_assert_macro [
$($set.insert($key));*
;

let $data = $set.try_to_vec().unwrap();
let $data = borsh::to_vec(&$set).unwrap();
#[cfg(feature = "std")]
insta::assert_debug_snapshot!($data);
]
Expand All @@ -17,7 +17,8 @@ macro_rules! map_insert_deser_assert_macro [
[$map: ident, $data: ident, $($key: expr => $value: expr),*] => [
$($map.insert($key, $value));*
;
let $data = $map.try_to_vec().unwrap();

let $data = borsh::to_vec(&$map).unwrap();
#[cfg(feature = "std")]
insta::assert_debug_snapshot!($data);
]
Expand Down
10 changes: 5 additions & 5 deletions borsh/tests/test_arrays.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::float_cmp)]

use borsh::{from_slice, to_vec};
#[cfg(feature = "derive")]
use borsh::BorshDeserialize;
use borsh::{from_slice, BorshSerialize};
use borsh::{BorshDeserialize, BorshSerialize};

#[cfg(not(feature = "std"))]
extern crate alloc;
Expand All @@ -12,7 +12,7 @@ use alloc::string::{String, ToString};

macro_rules! test_array {
($v: expr, $t: ty, $len: expr) => {
let buf = $v.try_to_vec().unwrap();
let buf = borsh::to_vec(&$v).unwrap();
#[cfg(feature = "std")]
insta::assert_debug_snapshot!(buf);
let actual_v: [$t; $len] = from_slice(&buf).expect("failed to deserialize");
Expand Down Expand Up @@ -63,7 +63,7 @@ struct CustomStruct(u8);
#[test]
fn test_custom_struct_array() {
let arr = [CustomStruct(0), CustomStruct(1), CustomStruct(2)];
let serialized = arr.try_to_vec().unwrap();
let serialized = to_vec(&arr).unwrap();
#[cfg(feature = "std")]
insta::assert_debug_snapshot!(serialized);
let deserialized: [CustomStruct; 3] = from_slice(&serialized).unwrap();
Expand All @@ -73,7 +73,7 @@ fn test_custom_struct_array() {
#[test]
fn test_string_array() {
let arr = ["0".to_string(), "1".to_string(), "2".to_string()];
let serialized = arr.try_to_vec().unwrap();
let serialized = to_vec(&arr).unwrap();
#[cfg(feature = "std")]
insta::assert_debug_snapshot!(serialized);
let deserialized: [String; 3] = from_slice(&serialized).unwrap();
Expand Down
4 changes: 2 additions & 2 deletions borsh/tests/test_bson_object_ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#![allow(clippy::float_cmp)]
#![cfg(feature = "derive")]

use borsh::{from_slice, BorshDeserialize, BorshSerialize};
use borsh::{from_slice, to_vec, BorshDeserialize, BorshSerialize};
use bson::oid::ObjectId;

#[derive(BorshDeserialize, BorshSerialize, PartialEq, Debug)]
Expand All @@ -15,7 +15,7 @@ fn test_object_id() {
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
33,
);
let serialized = obj.try_to_vec().unwrap();
let serialized = to_vec(&obj).unwrap();
#[cfg(feature = "std")]
insta::assert_debug_snapshot!(serialized);
let deserialized: StructWithObjectId = from_slice(&serialized).unwrap();
Expand Down
10 changes: 5 additions & 5 deletions borsh/tests/test_custom_reader.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg(feature = "derive")]
use borsh::{from_reader, BorshDeserialize, BorshSerialize};
use borsh::{from_reader, to_vec, BorshDeserialize, BorshSerialize};

#[cfg(not(feature = "std"))]
extern crate alloc;
Expand Down Expand Up @@ -33,7 +33,7 @@ fn test_custom_reader() {
item2: "foo".into(),
item3: 1.2345,
};
let bytes = s.try_to_vec().unwrap();
let bytes = to_vec(&s).unwrap();
let mut reader = CustomReader {
data: bytes,
read_index: 0,
Expand All @@ -51,7 +51,7 @@ fn test_custom_reader_with_insufficient_data() {
item2: "foo".into(),
item3: 1.2345,
};
let mut bytes = s.try_to_vec().unwrap();
let mut bytes = to_vec(&s).unwrap();
bytes.pop().unwrap();
let mut reader = CustomReader {
data: bytes,
Expand All @@ -72,7 +72,7 @@ fn test_custom_reader_with_too_much_data() {
item2: "foo".into(),
item3: 1.2345,
};
let mut bytes = s.try_to_vec().unwrap();
let mut bytes = to_vec(&s).unwrap();
bytes.push(1);
let mut reader = CustomReader {
data: bytes,
Expand Down Expand Up @@ -107,7 +107,7 @@ fn test_custom_reader_that_doesnt_fill_slices() {
item2: "foo".into(),
item3: 1.2345,
};
let bytes = s.try_to_vec().unwrap();
let bytes = to_vec(&s).unwrap();
let mut reader = CustomReaderThatDoesntFillSlices {
data: bytes,
read_index: 0,
Expand Down
20 changes: 10 additions & 10 deletions borsh/tests/test_enum_discriminants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::vec;

use borsh::{from_slice, BorshDeserialize, BorshSerialize};
use borsh::{from_slice, to_vec, BorshDeserialize, BorshSerialize};
// sequence, no unit enums
#[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Clone, Copy, Debug)]
#[borsh(use_discriminant = true)]
Expand Down Expand Up @@ -39,7 +39,7 @@ fn test_discriminant_serde_no_unit_type() {
let expected_discriminants = [0u8, 20, 21, 10, 22, 11];

for (ind, value) in values.iter().enumerate() {
let data = value.try_to_vec().unwrap();
let data = to_vec(value).unwrap();
assert_eq!(data[0], expected_discriminants[ind]);
assert_eq!(from_slice::<XY>(&data).unwrap(), values[ind]);
}
Expand All @@ -58,7 +58,7 @@ fn test_discriminant_serde_no_unit_type_no_use_discriminant() {
let expected_discriminants = [0u8, 1, 2, 3, 4, 5];

for (ind, value) in values.iter().enumerate() {
let data = value.try_to_vec().unwrap();
let data = to_vec(value).unwrap();
assert_eq!(data[0], expected_discriminants[ind]);
assert_eq!(from_slice::<XYNoDiscriminant>(&data).unwrap(), values[ind]);
}
Expand All @@ -84,17 +84,17 @@ enum MyEnumNoDiscriminant {
#[test]
fn test_discriminant_minimal_true() {
assert_eq!(MyDiscriminantEnum::A as u8, 20);
assert_eq!(MyDiscriminantEnum::A.try_to_vec().unwrap(), vec![20]);
assert_eq!(to_vec(&MyDiscriminantEnum::A).unwrap(), vec![20]);
}

#[test]
fn test_discriminant_minimal_false() {
assert_eq!(MyDiscriminantEnumFalse::A as u8, 20);
assert_eq!(
MyEnumNoDiscriminant::A.try_to_vec().unwrap(),
MyDiscriminantEnumFalse::A.try_to_vec().unwrap(),
to_vec(&MyEnumNoDiscriminant::A).unwrap(),
to_vec(&MyDiscriminantEnumFalse::A).unwrap(),
);
assert_eq!(MyDiscriminantEnumFalse::A.try_to_vec().unwrap(), vec![0]);
assert_eq!(to_vec(&MyDiscriminantEnumFalse::A).unwrap(), vec![0]);
}

// sequence
Expand All @@ -121,7 +121,7 @@ fn test_discriminant_serde_no_use_discriminant() {
];
let expected_discriminants = [0u8, 1, 2, 3, 4, 5];
for (index, value) in values.iter().enumerate() {
let data = value.try_to_vec().unwrap();
let data = to_vec(value).unwrap();
assert_eq!(data[0], expected_discriminants[index]);
assert_eq!(from_slice::<XNoDiscriminant>(&data).unwrap(), values[index]);
}
Expand Down Expand Up @@ -155,7 +155,7 @@ enum X {
fn test_discriminant_serialization() {
let values = vec![X::A, X::B, X::C, X::D, X::E, X::F];
for value in values {
assert_eq!(value.try_to_vec().unwrap(), [value as u8]);
assert_eq!(to_vec(&value).unwrap(), [value as u8]);
}
}

Expand All @@ -178,7 +178,7 @@ fn test_discriminant_serde() {
let values = vec![X::A, X::B, X::C, X::D, X::E, X::F];
let expected_discriminants = [0u8, 20, 21, 22, 10, 11];
for (index, value) in values.iter().enumerate() {
let data = value.try_to_vec().unwrap();
let data = to_vec(value).unwrap();
assert_eq!(data[0], expected_discriminants[index]);
assert_eq!(from_slice::<X>(&data).unwrap(), values[index]);
}
Expand Down
Loading
Loading