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

feat: IDLBuilder.try_reserve_value_serializer_capacity #586

Merged
merged 3 commits into from
Dec 10, 2024
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: 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
Loading