Skip to content

Commit

Permalink
feat: IDLBuilder.try_reserve_value_serializer_capacity (#586)
Browse files Browse the repository at this point in the history
  • Loading branch information
ericswanson-dfinity authored Dec 10, 2024
1 parent 7758917 commit 5ee6538
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
4 changes: 4 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@

# Changelog

## [Unreleased]

* Add `IDLBuilder.try_reserve_value_serializer_capacity()` to reserve capacity before serializing a large amount of data.

## 2024-05-03

### Candid 0.10.10
Expand Down
4 changes: 4 additions & 0 deletions rust/candid/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! `candid::Result<T> = Result<T, candid::Error>>`
use serde::{de, ser};
use std::collections::TryReserveError;
use std::{io, num::ParseIntError};
use thiserror::Error;

Expand All @@ -17,6 +18,9 @@ pub enum Error {
#[error("binary parser error: {}", .0.first().map_or_else(|| "io error".to_string(), |f| format!("{} at byte offset {}", f.message, f.pos/2)))]
Binread(Vec<Label>),

#[error(transparent)]
Reserve(#[from] TryReserveError),

#[error("Subtyping error: {0}")]
Subtype(String),

Expand Down
14 changes: 13 additions & 1 deletion rust/candid/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use super::types::value::IDLValue;
use super::types::{internal::Opcode, Field, Type, TypeEnv, TypeInner};
use byteorder::{LittleEndian, WriteBytesExt};
use leb128::write::{signed as sleb128_encode, unsigned as leb128_encode};
use std::collections::BTreeMap;
use std::collections::{BTreeMap, TryReserveError};
use std::io;
use std::vec::Vec;

Expand Down Expand Up @@ -71,6 +71,14 @@ impl IDLBuilder {
self.serialize(&mut vec)?;
Ok(vec)
}
/// If serializing a large amount of data, you can try to reserve the capacity of the
/// value serializer ahead of time to avoid reallocation.
pub fn try_reserve_value_serializer_capacity(
&mut self,
additional: usize,
) -> std::result::Result<(), TryReserveError> {
self.value_ser.try_reserve(additional)
}
}

/// A structure for serializing Rust values to IDL.
Expand Down Expand Up @@ -99,6 +107,10 @@ impl ValueSerializer {
self.value.write_all(bytes)?;
Ok(())
}
#[doc(hidden)]
pub fn try_reserve(&mut self, additional: usize) -> std::result::Result<(), TryReserveError> {
self.value.try_reserve(additional)
}
}

macro_rules! serialize_num {
Expand Down

0 comments on commit 5ee6538

Please sign in to comment.