Skip to content
Open
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
8 changes: 6 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ license = "Apache-2.0"
edition = "2018"

[dependencies]
thiserror = "1.0.37"
serde = { version = "1.0.145", features = ["derive"] }
serde = { version = "1.0.145", default-features = false, features = ["derive"] }
thiserror = { version = "2.0.18", default-features = false }

[features]
default = ["std"]
std = []

[dev-dependencies]
criterion = "0.3.6"
Expand Down
1 change: 0 additions & 1 deletion rust-toolchain

This file was deleted.

50 changes: 33 additions & 17 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
// SPDX-License-Identifier: Apache-2.0

use crate::error::{Error, Result};
use serde::de::{self, Deserialize, DeserializeOwned, DeserializeSeed, IntoDeserializer, Visitor};
use std::{convert::TryFrom, io::Read};
use core::convert::TryFrom;
#[cfg(feature = "std")]
use serde::de::DeserializeOwned;
use serde::de::{self, Deserialize, DeserializeSeed, IntoDeserializer, Visitor};

/// Deserializes a `&[u8]` into a type.
/// Deserializes into a type.
///
/// This function will attempt to interpret `bytes` as the BCS serialized form of `T` and
/// deserialize `T` from `bytes`.
Expand Down Expand Up @@ -85,8 +87,9 @@ where
Ok(t)
}

/// Deserialize a type from an implementation of [`Read`].
pub fn from_reader<T>(mut reader: impl Read) -> Result<T>
#[cfg(feature = "std")]
/// Deserialize a type from an implementation of [`std::io::Read`].
pub fn from_reader<T>(mut reader: impl std::io::Read) -> Result<T>
where
T: DeserializeOwned,
{
Expand All @@ -96,9 +99,10 @@ where
Ok(t)
}

#[cfg(feature = "std")]
/// Same as `from_reader_seed` but use `limit` as max container depth instead of MAX_CONTAINER_DEPTH`
/// Note that `limit` has to be lower than MAX_CONTAINER_DEPTH
pub fn from_reader_with_limit<T>(mut reader: impl Read, limit: usize) -> Result<T>
pub fn from_reader_with_limit<T>(mut reader: impl std::io::Read, limit: usize) -> Result<T>
where
T: DeserializeOwned,
{
Expand All @@ -111,8 +115,9 @@ where
Ok(t)
}

/// Deserialize a type from an implementation of [`Read`] using the provided seed
pub fn from_reader_seed<T, V>(seed: T, mut reader: impl Read) -> Result<V>
#[cfg(feature = "std")]
/// Deserialize a type from an implementation of [`std::io::Read`] using the provided seed
pub fn from_reader_seed<T, V>(seed: T, mut reader: impl std::io::Read) -> Result<V>
where
for<'a> T: DeserializeSeed<'a, Value = V>,
{
Expand All @@ -122,9 +127,14 @@ where
Ok(t)
}

#[cfg(feature = "std")]
/// Same as `from_reader_seed` but use `limit` as max container depth instead of MAX_CONTAINER_DEPTH`
/// Note that `limit` has to be lower than MAX_CONTAINER_DEPTH
pub fn from_reader_seed_with_limit<T, V>(seed: T, mut reader: impl Read, limit: usize) -> Result<V>
pub fn from_reader_seed_with_limit<T, V>(
seed: T,
mut reader: impl std::io::Read,
limit: usize,
) -> Result<V>
where
for<'a> T: DeserializeSeed<'a, Value = V>,
{
Expand All @@ -143,7 +153,8 @@ struct Deserializer<R> {
max_remaining_depth: usize,
}

impl<'de, R: Read> Deserializer<TeeReader<'de, R>> {
#[cfg(feature = "std")]
impl<'de, R: std::io::Read> Deserializer<TeeReader<'de, R>> {
fn from_reader(input: &'de mut R, max_remaining_depth: usize) -> Self {
Deserializer {
input: TeeReader::new(input),
Expand All @@ -163,14 +174,16 @@ impl<'de> Deserializer<&'de [u8]> {
}
}

/// A reader that can optionally capture all bytes from an underlying [`Read`]er
#[cfg(feature = "std")]
/// A reader that can optionally capture all bytes from an underlying [`std::io::Read`]er
struct TeeReader<'de, R> {
/// the underlying reader
reader: &'de mut R,
/// If non-empty, all bytes read from the underlying reader will be captured in the last entry here.
captured_keys: Vec<Vec<u8>>,
}

#[cfg(feature = "std")]
impl<'de, R> TeeReader<'de, R> {
/// Wraps the provided reader in a new [`TeeReader`].
pub fn new(reader: &'de mut R) -> Self {
Expand All @@ -181,7 +194,8 @@ impl<'de, R> TeeReader<'de, R> {
}
}

impl<'de, R: Read> Read for TeeReader<'de, R> {
#[cfg(feature = "std")]
impl<'de, R: std::io::Read> std::io::Read for TeeReader<'de, R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let bytes_read = self.reader.read(buf)?;
if let Some(buffer) = self.captured_keys.last_mut() {
Expand Down Expand Up @@ -289,7 +303,8 @@ trait BcsDeserializer<'de> {
}
}

impl<'de, R: Read> Deserializer<TeeReader<'de, R>> {
#[cfg(feature = "std")]
impl<'de, R: std::io::Read> Deserializer<TeeReader<'de, R>> {
fn parse_vec(&mut self) -> Result<Vec<u8>> {
let len = self.parse_length()?;
let mut output = vec![0; len];
Expand All @@ -303,11 +318,12 @@ impl<'de, R: Read> Deserializer<TeeReader<'de, R>> {
}
}

impl<'de, R: Read> BcsDeserializer<'de> for Deserializer<TeeReader<'de, R>> {
#[cfg(feature = "std")]
impl<'de, R: std::io::Read> BcsDeserializer<'de> for Deserializer<TeeReader<'de, R>> {
type MaybeBorrowedBytes = Vec<u8>;

fn fill_slice(&mut self, slice: &mut [u8]) -> Result<()> {
Ok(self.input.read_exact(slice)?)
Ok(std::io::Read::read_exact(&mut self.input, slice)?)
}

fn parse_and_visit_str<V>(&mut self, visitor: V) -> Result<V::Value>
Expand Down Expand Up @@ -339,7 +355,7 @@ impl<'de, R: Read> BcsDeserializer<'de> for Deserializer<TeeReader<'de, R>> {

fn end(&mut self) -> Result<()> {
let mut byte = [0u8; 1];
match self.input.read_exact(&mut byte) {
match std::io::Read::read_exact(&mut self.input, &mut byte) {
Ok(_) => Err(Error::RemainingInput),
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(()),
Err(e) => Err(e.into()),
Expand Down Expand Up @@ -410,7 +426,7 @@ impl<'de> Deserializer<&'de [u8]> {

fn parse_string(&mut self) -> Result<&'de str> {
let slice = self.parse_bytes()?;
std::str::from_utf8(slice).map_err(|_| Error::Utf8)
core::str::from_utf8(slice).map_err(|_| Error::Utf8)
}
}

Expand Down
8 changes: 5 additions & 3 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use alloc::string::{String, ToString};
use core::fmt;
use serde::{de, ser};
use std::{fmt, io::ErrorKind};
use thiserror::Error;

pub type Result<T, E = Error> = std::result::Result<T, E>;
pub type Result<T, E = Error> = core::result::Result<T, E>;

#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum Error {
Expand Down Expand Up @@ -43,9 +44,10 @@ pub enum Error {
IntegerOverflowDuringUleb128Decoding,
}

#[cfg(feature = "std")]
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
if err.kind() == ErrorKind::UnexpectedEof {
if err.kind() == std::io::ErrorKind::UnexpectedEof {
Error::Eof
} else {
Error::Io(err.to_string())
Expand Down
19 changes: 13 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

#![forbid(unsafe_code)]
#![cfg_attr(not(feature = "std"), no_std)]

//! # Binary Canonical Serialization (BCS)
//!
Expand Down Expand Up @@ -303,9 +304,13 @@
//! # Ok(())}
//! ```

extern crate alloc;

mod de;
mod error;
mod ser;

#[cfg(feature = "std")]
pub mod test_helpers;

/// Variable length sequences in BCS are limited to max length of 2^31 - 1.
Expand All @@ -314,12 +319,14 @@ pub const MAX_SEQUENCE_LENGTH: usize = (1 << 31) - 1;
/// Maximal allowed depth of BCS data, counting only structs and enums.
pub const MAX_CONTAINER_DEPTH: usize = 500;

pub use de::{
from_bytes, from_bytes_seed, from_bytes_seed_with_limit, from_bytes_with_limit, from_reader,
from_reader_seed, from_reader_seed_with_limit, from_reader_with_limit,
};
pub use de::{from_bytes, from_bytes_seed, from_bytes_seed_with_limit, from_bytes_with_limit};
#[cfg(feature = "std")]
pub use de::{from_reader, from_reader_seed, from_reader_seed_with_limit, from_reader_with_limit};
pub use error::{Error, Result};
pub use ser::{
is_human_readable, serialize_into, serialize_into_with_limit, serialized_size,
serialized_size_with_limit, to_bytes, to_bytes_with_limit,
is_human_readable, serialize_into_with_limit, serialized_size, serialized_size_with_limit,
to_bytes, to_bytes_with_limit,
};

#[cfg(feature = "std")]
pub use ser::serialize_into;
Loading