Refactor and rename encoders

This commit is contained in:
Lena Hellström 2021-10-17 16:18:57 +02:00
parent 61c1e8a7cd
commit e232454936
28 changed files with 1122 additions and 1366 deletions

View File

@ -1,6 +1,6 @@
# Bincode-derive
The derive crate for bincode. Implements `bincode::Encodable` and `bincode::Decodable`.
The derive crate for bincode. Implements `bincode::Encode` and `bincode::Decode`.
This crate is roughly split into 2 parts:
@ -25,4 +25,4 @@ This is supported by the structs in `src/generate`. The most notable points of t
For additional derive testing, see the test cases in `../tests`
For testing purposes, all generated code is outputted to the current `target` folder, under file name `<struct/enum name>_Encodeable.rs` and `<struct/enum name>_Decodeable.rs`. This can help with debugging.
For testing purposes, all generated code is outputted to the current `target` folder, under file name `<struct/enum name>_Encode.rs` and `<struct/enum name>_Decode.rs`. This can help with debugging.

View File

@ -10,13 +10,13 @@ pub struct DeriveEnum {
}
impl DeriveEnum {
pub fn generate_encodable(self, generator: &mut Generator) -> Result<()> {
pub fn generate_encode(self, generator: &mut Generator) -> Result<()> {
let DeriveEnum { variants } = self;
generator
.impl_for("bincode::enc::Encodeable")
.impl_for("bincode::enc::Encode")
.generate_fn("encode")
.with_generic("E", ["bincode::enc::Encode"])
.with_generic("E", ["bincode::enc::Encoder"])
.with_self_arg(FnSelfArg::RefSelf)
.with_arg("mut encoder", "E")
.with_return_type("core::result::Result<(), bincode::error::EncodeError>")
@ -55,17 +55,20 @@ impl DeriveEnum {
// Note that the fields are available as locals because of the match destructuring above
// {
// encoder.encode_u32(n)?;
// bincode::enc::Encodeable::encode(a, &mut encoder)?;
// bincode::enc::Encodeable::encode(b, &mut encoder)?;
// bincode::enc::Encodeable::encode(c, &mut encoder)?;
// bincode::enc::Encode::encode(a, &mut encoder)?;
// bincode::enc::Encode::encode(b, &mut encoder)?;
// bincode::enc::Encode::encode(c, &mut encoder)?;
// }
match_body.group(Delimiter::Brace, |body| {
// variant index
body.push_parsed(format!("encoder.encode_u32({})?;", variant_index));
body.push_parsed(format!(
"<u32 as bincode::enc::Encode>::encode(&{}, &mut encoder)?;",
variant_index
));
// If we have any fields, encode them all one by one
for field_name in variant.fields.names() {
body.push_parsed(format!(
"bincode::enc::Encodeable::encode({}, &mut encoder)?;",
"bincode::enc::Encode::encode({}, &mut encoder)?;",
field_name.to_string_with_prefix(TUPLE_FIELD_PREFIX),
));
}
@ -78,21 +81,21 @@ impl DeriveEnum {
Ok(())
}
pub fn generate_decodable(self, generator: &mut Generator) -> Result<()> {
pub fn generate_decode(self, generator: &mut Generator) -> Result<()> {
let DeriveEnum { variants } = self;
let enum_name = generator.target_name().to_string();
if generator.has_lifetimes() {
// enum has a lifetime, implement BorrowDecodable
// enum has a lifetime, implement BorrowDecode
generator.impl_for_with_de_lifetime("bincode::de::BorrowDecodable<'__de>")
generator.impl_for_with_de_lifetime("bincode::de::BorrowDecode<'__de>")
.generate_fn("borrow_decode")
.with_generic("D", ["bincode::de::BorrowDecode<'__de>"])
.with_generic("D", ["bincode::de::BorrowDecoder<'__de>"])
.with_arg("mut decoder", "D")
.with_return_type("Result<Self, bincode::error::DecodeError>")
.body(|fn_builder| {
fn_builder
.push_parsed("let variant_index = bincode::de::Decode::decode_u32(&mut decoder)?;");
.push_parsed("let variant_index = <u32 as bincode::de::Decode>::decode(&mut decoder)?;");
fn_builder.push_parsed("match variant_index");
fn_builder.group(Delimiter::Brace, |variant_case| {
for (idx, variant) in variants.iter().enumerate() {
@ -117,7 +120,7 @@ impl DeriveEnum {
variant_body.ident(field.unwrap_ident().clone());
}
variant_body.punct(':');
variant_body.push_parsed("bincode::de::BorrowDecodable::borrow_decode(&mut decoder)?,");
variant_body.push_parsed("bincode::de::BorrowDecode::borrow_decode(&mut decoder)?,");
}
});
});
@ -133,16 +136,16 @@ impl DeriveEnum {
});
});
} else {
// enum has no lifetimes, implement Decodable
generator.impl_for("bincode::de::Decodable")
// enum has no lifetimes, implement Decode
generator.impl_for("bincode::de::Decode")
.generate_fn("decode")
.with_generic("D", ["bincode::de::Decode"])
.with_generic("D", ["bincode::de::Decoder"])
.with_arg("mut decoder", "D")
.with_return_type("Result<Self, bincode::error::DecodeError>")
.body(|fn_builder| {
fn_builder
.push_parsed("let variant_index = bincode::de::Decode::decode_u32(&mut decoder)?;");
.push_parsed("let variant_index = <u32 as bincode::de::Decode>::decode(&mut decoder)?;");
fn_builder.push_parsed("match variant_index");
fn_builder.group(Delimiter::Brace, |variant_case| {
for (idx, variant) in variants.iter().enumerate() {
@ -167,7 +170,7 @@ impl DeriveEnum {
variant_body.ident(field.unwrap_ident().clone());
}
variant_body.punct(':');
variant_body.push_parsed("bincode::de::Decodable::decode(&mut decoder)?,");
variant_body.push_parsed("bincode::de::Decode::decode(&mut decoder)?,");
}
});
});

View File

@ -8,20 +8,20 @@ pub struct DeriveStruct {
}
impl DeriveStruct {
pub fn generate_encodable(self, generator: &mut Generator) -> Result<()> {
pub fn generate_encode(self, generator: &mut Generator) -> Result<()> {
let DeriveStruct { fields } = self;
let mut impl_for = generator.impl_for("bincode::enc::Encodeable");
let mut impl_for = generator.impl_for("bincode::enc::Encode");
impl_for
.generate_fn("encode")
.with_generic("E", ["bincode::enc::Encode"])
.with_generic("E", ["bincode::enc::Encoder"])
.with_self_arg(crate::generate::FnSelfArg::RefSelf)
.with_arg("mut encoder", "E")
.with_return_type("Result<(), bincode::error::EncodeError>")
.body(|fn_body| {
for field in fields.names() {
fn_body.push_parsed(format!(
"bincode::enc::Encodeable::encode(&self.{}, &mut encoder)?;",
"bincode::enc::Encode::encode(&self.{}, &mut encoder)?;",
field.to_string()
));
}
@ -31,16 +31,16 @@ impl DeriveStruct {
Ok(())
}
pub fn generate_decodable(self, generator: &mut Generator) -> Result<()> {
pub fn generate_decode(self, generator: &mut Generator) -> Result<()> {
let DeriveStruct { fields } = self;
if generator.has_lifetimes() {
// struct has a lifetime, implement BorrowDecodable
// struct has a lifetime, implement BorrowDecode
generator
.impl_for_with_de_lifetime("bincode::de::BorrowDecodable<'__de>")
.impl_for_with_de_lifetime("bincode::de::BorrowDecode<'__de>")
.generate_fn("borrow_decode")
.with_generic("D", ["bincode::de::BorrowDecode<'__de>"])
.with_generic("D", ["bincode::de::BorrowDecoder<'__de>"])
.with_arg("mut decoder", "D")
.with_return_type("Result<Self, bincode::error::DecodeError>")
.body(|fn_body| {
@ -51,9 +51,9 @@ impl DeriveStruct {
ok_group.group(Delimiter::Brace, |struct_body| {
for field in fields.names() {
struct_body.push_parsed(format!(
"{}: bincode::de::BorrowDecodable::borrow_decode(&mut decoder)?,",
field.to_string()
));
"{}: bincode::de::BorrowDecode::borrow_decode(&mut decoder)?,",
field.to_string()
));
}
});
});
@ -61,12 +61,12 @@ impl DeriveStruct {
Ok(())
} else {
// struct has no lifetimes, implement Decodable
// struct has no lifetimes, implement Decode
let mut impl_for = generator.impl_for("bincode::de::Decodable");
let mut impl_for = generator.impl_for("bincode::de::Decode");
impl_for
.generate_fn("decode")
.with_generic("D", ["bincode::de::Decode"])
.with_generic("D", ["bincode::de::Decoder"])
.with_arg("mut decoder", "D")
.with_return_type("Result<Self, bincode::error::DecodeError>")
.body(|fn_body| {
@ -77,13 +77,13 @@ impl DeriveStruct {
ok_group.group(Delimiter::Brace, |struct_body| {
// Fields
// {
// a: bincode::de::Decodable::decode(&mut decoder)?,
// b: bincode::de::Decodable::decode(&mut decoder)?,
// a: bincode::de::Decode::decode(&mut decoder)?,
// b: bincode::de::Decode::decode(&mut decoder)?,
// ...
// }
for field in fields.names() {
struct_body.push_parsed(format!(
"{}: bincode::de::Decodable::decode(&mut decoder)?,",
"{}: bincode::de::Decode::decode(&mut decoder)?,",
field.to_string()
));
}

View File

@ -20,15 +20,15 @@ use prelude::TokenStream;
type Result<T = ()> = std::result::Result<T, Error>;
#[proc_macro_derive(Encodable)]
pub fn derive_encodable(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
#[proc_macro_derive(Encode)]
pub fn derive_encode(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
#[allow(clippy::useless_conversion)]
derive_encodable_inner(input.into())
derive_encode_inner(input.into())
.unwrap_or_else(|e| e.into_token_stream())
.into()
}
fn derive_encodable_inner(input: TokenStream) -> Result<TokenStream> {
fn derive_encode_inner(input: TokenStream) -> Result<TokenStream> {
let source = &mut input.into_iter().peekable();
let _attributes = parse::Attributes::try_take(source)?;
@ -45,31 +45,31 @@ fn derive_encodable_inner(input: TokenStream) -> Result<TokenStream> {
derive_struct::DeriveStruct {
fields: body.fields,
}
.generate_encodable(&mut generator)?;
.generate_encode(&mut generator)?;
}
parse::DataType::Enum => {
let body = parse::EnumBody::take(source)?;
derive_enum::DeriveEnum {
variants: body.variants,
}
.generate_encodable(&mut generator)?;
.generate_encode(&mut generator)?;
}
}
let stream = generator.take_stream();
dump_output(name, "Encodeable", &stream);
dump_output(name, "Encode", &stream);
Ok(stream)
}
#[proc_macro_derive(Decodable)]
pub fn derive_decodable(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
#[proc_macro_derive(Decode)]
pub fn derive_decode(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
#[allow(clippy::useless_conversion)]
derive_decodable_inner(input.into())
derive_decode_inner(input.into())
.unwrap_or_else(|e| e.into_token_stream())
.into()
}
fn derive_decodable_inner(input: TokenStream) -> Result<TokenStream> {
fn derive_decode_inner(input: TokenStream) -> Result<TokenStream> {
let source = &mut input.into_iter().peekable();
let _attributes = parse::Attributes::try_take(source)?;
@ -86,19 +86,19 @@ fn derive_decodable_inner(input: TokenStream) -> Result<TokenStream> {
derive_struct::DeriveStruct {
fields: body.fields,
}
.generate_decodable(&mut generator)?;
.generate_decode(&mut generator)?;
}
parse::DataType::Enum => {
let body = parse::EnumBody::take(source)?;
derive_enum::DeriveEnum {
variants: body.variants,
}
.generate_decodable(&mut generator)?;
.generate_decode(&mut generator)?;
}
}
let stream = generator.take_stream();
dump_output(name, "Decodeable", &stream);
dump_output(name, "Decode", &stream);
Ok(stream)
}

View File

@ -404,7 +404,7 @@ fn test_generic_constraints_try_take() {
let stream = &mut token_stream("");
assert!(GenericConstraints::try_take(stream).unwrap().is_none());
let stream = &mut token_stream("pub(crate) struct Test<T: Encodeable> {}");
let stream = &mut token_stream("pub(crate) struct Test<T: Encode> {}");
assert_eq!(Visibility::Pub, Visibility::try_take(stream).unwrap());
let (data_type, ident) = DataType::take(stream).unwrap();
assert_eq!(data_type, DataType::Struct);

View File

@ -57,7 +57,7 @@ Enums are encoded with their variant first, followed by optionally the variant f
Both named and unnamed fields are serialized with their values only, and therefor encode to the same value.
```rs
#[derive(bincode::Encodable)]
#[derive(bincode::Encode)]
pub enum SomeEnum {
A,
B(u32),

View File

@ -1,12 +1,9 @@
use super::{
read::{BorrowReader, Reader},
BorrowDecode, Decode,
sealed::Sealed,
BorrowDecoder, Decoder,
};
use crate::{
config::{Config, Endian, IntEncoding},
error::DecodeError,
};
use core::marker::PhantomData;
use crate::config::Config;
/// A Decoder that reads bytes from a given reader `R`.
///
@ -19,272 +16,44 @@ use core::marker::PhantomData;
/// ```
/// # let slice: &[u8] = &[0, 0, 0, 0];
/// # let some_reader = bincode::de::read::SliceReader::new(slice);
/// use bincode::de::{Decoder, Decodable};
/// use bincode::de::{DecoderImpl, Decode};
/// use bincode::config;
/// let mut decoder = Decoder::new(some_reader, config::Default);
/// // this u32 can be any Decodable
/// let mut decoder = DecoderImpl::new(some_reader, config::Default);
/// // this u32 can be any Decode
/// let value = u32::decode(&mut decoder).unwrap();
/// ```
pub struct Decoder<R, C: Config> {
pub struct DecoderImpl<R, C: Config> {
reader: R,
config: PhantomData<C>,
config: C,
}
impl<'de, R: Reader<'de>, C: Config> Decoder<R, C> {
impl<'de, R: Reader, C: Config> DecoderImpl<R, C> {
/// Construct a new Decoder
pub fn new(reader: R, _config: C) -> Decoder<R, C> {
Decoder {
reader,
config: PhantomData,
}
}
/// Consume the decoder and return the inner reader
pub fn into_reader(self) -> R {
self.reader
pub fn new(reader: R, config: C) -> DecoderImpl<R, C> {
DecoderImpl { reader, config }
}
}
impl<'a, 'de, R: BorrowReader<'de>, C: Config> BorrowDecode<'de> for &'a mut Decoder<R, C> {
fn decode_slice(&mut self, len: usize) -> Result<&'de [u8], DecodeError> {
self.reader.take_bytes(len)
impl<'a, R, C: Config> Sealed for &'a mut DecoderImpl<R, C> {}
impl<'a, 'de, R: BorrowReader<'de>, C: Config> BorrowDecoder<'de> for &'a mut DecoderImpl<R, C> {
type BR = R;
fn borrow_reader(&mut self) -> &mut Self::BR {
&mut self.reader
}
}
impl<'a, 'de, R: Reader<'de>, C: Config> Decode for &'a mut Decoder<R, C> {
fn decode_u8(&mut self) -> Result<u8, DecodeError> {
let mut bytes = [0u8; 1];
self.reader.read(&mut bytes)?;
Ok(bytes[0])
impl<'a, 'de, R: Reader, C: Config> Decoder for &'a mut DecoderImpl<R, C> {
type R = R;
type C = C;
fn reader(&mut self) -> &mut Self::R {
&mut self.reader
}
fn decode_u16(&mut self) -> Result<u16, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => crate::varint::varint_decode_u16(&mut self.reader, C::ENDIAN),
IntEncoding::Fixed => {
let mut bytes = [0u8; 2];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => u16::from_le_bytes(bytes),
Endian::Big => u16::from_be_bytes(bytes),
})
}
}
}
fn decode_u32(&mut self) -> Result<u32, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => crate::varint::varint_decode_u32(&mut self.reader, C::ENDIAN),
IntEncoding::Fixed => {
let mut bytes = [0u8; 4];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => u32::from_le_bytes(bytes),
Endian::Big => u32::from_be_bytes(bytes),
})
}
}
}
fn decode_u64(&mut self) -> Result<u64, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => crate::varint::varint_decode_u64(&mut self.reader, C::ENDIAN),
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => u64::from_le_bytes(bytes),
Endian::Big => u64::from_be_bytes(bytes),
})
}
}
}
fn decode_u128(&mut self) -> Result<u128, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => crate::varint::varint_decode_u128(&mut self.reader, C::ENDIAN),
IntEncoding::Fixed => {
let mut bytes = [0u8; 16];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => u128::from_le_bytes(bytes),
Endian::Big => u128::from_be_bytes(bytes),
})
}
}
}
fn decode_usize(&mut self) -> Result<usize, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_usize(&mut self.reader, C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => u64::from_le_bytes(bytes),
Endian::Big => u64::from_be_bytes(bytes),
} as usize)
}
}
}
fn decode_i8(&mut self) -> Result<i8, DecodeError> {
let mut bytes = [0u8; 1];
self.reader.read(&mut bytes)?;
Ok(bytes[0] as i8)
}
fn decode_i16(&mut self) -> Result<i16, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => crate::varint::varint_decode_i16(&mut self.reader, C::ENDIAN),
IntEncoding::Fixed => {
let mut bytes = [0u8; 2];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => i16::from_le_bytes(bytes),
Endian::Big => i16::from_be_bytes(bytes),
})
}
}
}
fn decode_i32(&mut self) -> Result<i32, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => crate::varint::varint_decode_i32(&mut self.reader, C::ENDIAN),
IntEncoding::Fixed => {
let mut bytes = [0u8; 4];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => i32::from_le_bytes(bytes),
Endian::Big => i32::from_be_bytes(bytes),
})
}
}
}
fn decode_i64(&mut self) -> Result<i64, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => crate::varint::varint_decode_i64(&mut self.reader, C::ENDIAN),
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => i64::from_le_bytes(bytes),
Endian::Big => i64::from_be_bytes(bytes),
})
}
}
}
fn decode_i128(&mut self) -> Result<i128, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => crate::varint::varint_decode_i128(&mut self.reader, C::ENDIAN),
IntEncoding::Fixed => {
let mut bytes = [0u8; 16];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => i128::from_le_bytes(bytes),
Endian::Big => i128::from_be_bytes(bytes),
})
}
}
}
fn decode_isize(&mut self) -> Result<isize, DecodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_isize(&mut self.reader, C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => i64::from_le_bytes(bytes),
Endian::Big => i64::from_be_bytes(bytes),
} as isize)
}
}
}
fn decode_f32(&mut self) -> Result<f32, DecodeError> {
let mut bytes = [0u8; 4];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => f32::from_le_bytes(bytes),
Endian::Big => f32::from_be_bytes(bytes),
})
}
fn decode_f64(&mut self) -> Result<f64, DecodeError> {
let mut bytes = [0u8; 8];
self.reader.read(&mut bytes)?;
Ok(match C::ENDIAN {
Endian::Little => f64::from_le_bytes(bytes),
Endian::Big => f64::from_be_bytes(bytes),
})
}
fn decode_array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
let mut array = [0u8; N];
if !C::SKIP_FIXED_ARRAY_LENGTH {
let length = self.decode_usize()?;
if length != N {
return Err(DecodeError::ArrayLengthMismatch {
found: length,
required: N,
});
}
}
self.reader.read(&mut array)?;
Ok(array)
}
fn decode_char(&mut self) -> Result<char, DecodeError> {
let mut array = [0u8; 4];
// Look at the first byte to see how many bytes must be read
self.reader.read(&mut array[..1])?;
let width = utf8_char_width(array[0]);
if width == 0 {
return Err(DecodeError::InvalidCharEncoding(array));
}
if width == 1 {
return Ok(array[0] as char);
}
// read the remaining pain
self.reader.read(&mut array[1..width])?;
let res = core::str::from_utf8(&array[..width])
.ok()
.and_then(|s| s.chars().next())
.ok_or(DecodeError::InvalidCharEncoding(array))?;
Ok(res)
fn config(&self) -> &Self::C {
&self.config
}
}
const UTF8_CHAR_WIDTH: [u8; 256] = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x1F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x3F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x5F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x7F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0x9F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0xBF
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, // 0xDF
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF
];
// This function is a copy of core::str::utf8_char_width
const fn utf8_char_width(b: u8) -> usize {
UTF8_CHAR_WIDTH[b as usize] as usize
}

View File

@ -1,32 +1,32 @@
use super::{Decodable, Decode};
use super::{Decode, Decoder};
use crate::error::DecodeError;
impl<A> Decodable for (A,)
impl<A> Decode for (A,)
where
A: Decodable,
A: Decode,
{
fn decode<_D: Decode>(mut decoder: _D) -> Result<Self, DecodeError> {
fn decode<_D: Decoder>(mut decoder: _D) -> Result<Self, DecodeError> {
Ok((A::decode(&mut decoder)?,))
}
}
impl<A, B> Decodable for (A, B)
impl<A, B> Decode for (A, B)
where
A: Decodable,
B: Decodable,
A: Decode,
B: Decode,
{
fn decode<_D: Decode>(mut decoder: _D) -> Result<Self, DecodeError> {
fn decode<_D: Decoder>(mut decoder: _D) -> Result<Self, DecodeError> {
Ok((A::decode(&mut decoder)?, B::decode(&mut decoder)?))
}
}
impl<A, B, C> Decodable for (A, B, C)
impl<A, B, C> Decode for (A, B, C)
where
A: Decodable,
B: Decodable,
C: Decodable,
A: Decode,
B: Decode,
C: Decode,
{
fn decode<_D: Decode>(mut decoder: _D) -> Result<Self, DecodeError> {
fn decode<_D: Decoder>(mut decoder: _D) -> Result<Self, DecodeError> {
Ok((
A::decode(&mut decoder)?,
B::decode(&mut decoder)?,
@ -35,14 +35,14 @@ where
}
}
impl<A, B, C, D> Decodable for (A, B, C, D)
impl<A, B, C, D> Decode for (A, B, C, D)
where
A: Decodable,
B: Decodable,
C: Decodable,
D: Decodable,
A: Decode,
B: Decode,
C: Decode,
D: Decode,
{
fn decode<_D: Decode>(mut decoder: _D) -> Result<Self, DecodeError> {
fn decode<_D: Decoder>(mut decoder: _D) -> Result<Self, DecodeError> {
Ok((
A::decode(&mut decoder)?,
B::decode(&mut decoder)?,
@ -52,15 +52,15 @@ where
}
}
impl<A, B, C, D, E> Decodable for (A, B, C, D, E)
impl<A, B, C, D, E> Decode for (A, B, C, D, E)
where
A: Decodable,
B: Decodable,
C: Decodable,
D: Decodable,
E: Decodable,
A: Decode,
B: Decode,
C: Decode,
D: Decode,
E: Decode,
{
fn decode<_D: Decode>(mut decoder: _D) -> Result<Self, DecodeError> {
fn decode<_D: Decoder>(mut decoder: _D) -> Result<Self, DecodeError> {
Ok((
A::decode(&mut decoder)?,
B::decode(&mut decoder)?,
@ -71,16 +71,16 @@ where
}
}
impl<A, B, C, D, E, F> Decodable for (A, B, C, D, E, F)
impl<A, B, C, D, E, F> Decode for (A, B, C, D, E, F)
where
A: Decodable,
B: Decodable,
C: Decodable,
D: Decodable,
E: Decodable,
F: Decodable,
A: Decode,
B: Decode,
C: Decode,
D: Decode,
E: Decode,
F: Decode,
{
fn decode<_D: Decode>(mut decoder: _D) -> Result<Self, DecodeError> {
fn decode<_D: Decoder>(mut decoder: _D) -> Result<Self, DecodeError> {
Ok((
A::decode(&mut decoder)?,
B::decode(&mut decoder)?,
@ -92,17 +92,17 @@ where
}
}
impl<A, B, C, D, E, F, G> Decodable for (A, B, C, D, E, F, G)
impl<A, B, C, D, E, F, G> Decode for (A, B, C, D, E, F, G)
where
A: Decodable,
B: Decodable,
C: Decodable,
D: Decodable,
E: Decodable,
F: Decodable,
G: Decodable,
A: Decode,
B: Decode,
C: Decode,
D: Decode,
E: Decode,
F: Decode,
G: Decode,
{
fn decode<_D: Decode>(mut decoder: _D) -> Result<Self, DecodeError> {
fn decode<_D: Decoder>(mut decoder: _D) -> Result<Self, DecodeError> {
Ok((
A::decode(&mut decoder)?,
B::decode(&mut decoder)?,
@ -115,18 +115,18 @@ where
}
}
impl<A, B, C, D, E, F, G, H> Decodable for (A, B, C, D, E, F, G, H)
impl<A, B, C, D, E, F, G, H> Decode for (A, B, C, D, E, F, G, H)
where
A: Decodable,
B: Decodable,
C: Decodable,
D: Decodable,
E: Decodable,
F: Decodable,
G: Decodable,
H: Decodable,
A: Decode,
B: Decode,
C: Decode,
D: Decode,
E: Decode,
F: Decode,
G: Decode,
H: Decode,
{
fn decode<_D: Decode>(mut decoder: _D) -> Result<Self, DecodeError> {
fn decode<_D: Decoder>(mut decoder: _D) -> Result<Self, DecodeError> {
Ok((
A::decode(&mut decoder)?,
B::decode(&mut decoder)?,

View File

@ -1,5 +1,11 @@
use super::{BorrowDecodable, BorrowDecode, Decodable, Decode};
use crate::error::{DecodeError, IntegerType};
use super::{
read::{BorrowReader, Reader},
BorrowDecode, BorrowDecoder, Decode, Decoder,
};
use crate::{
config::{Endian, IntEncoding, InternalConfig},
error::{DecodeError, IntegerType},
};
use core::{
cell::{Cell, RefCell},
num::{
@ -10,9 +16,9 @@ use core::{
time::Duration,
};
impl Decodable for bool {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
match decoder.decode_u8()? {
impl Decode for bool {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
match u8::decode(decoder)? {
0 => Ok(false),
1 => Ok(true),
x => Err(DecodeError::InvalidBooleanValue(x)),
@ -20,223 +26,387 @@ impl Decodable for bool {
}
}
impl Decodable for u8 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_u8()
impl Decode for u8 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let mut bytes = [0u8; 1];
decoder.reader().read(&mut bytes)?;
Ok(bytes[0])
}
}
impl Decodable for NonZeroU8 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroU8::new(decoder.decode_u8()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroU8 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroU8::new(u8::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::U8,
})
}
}
impl Decodable for u16 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_u16()
impl Decode for u16 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_u16(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 2];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => u16::from_le_bytes(bytes),
Endian::Big => u16::from_be_bytes(bytes),
})
}
}
}
}
impl Decodable for NonZeroU16 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroU16::new(decoder.decode_u16()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroU16 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroU16::new(u16::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::U16,
})
}
}
impl Decodable for u32 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_u32()
impl Decode for u32 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_u32(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 4];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => u32::from_le_bytes(bytes),
Endian::Big => u32::from_be_bytes(bytes),
})
}
}
}
}
impl Decodable for NonZeroU32 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroU32::new(decoder.decode_u32()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroU32 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroU32::new(u32::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::U32,
})
}
}
impl Decodable for u64 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_u64()
impl Decode for u64 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_u64(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => u64::from_le_bytes(bytes),
Endian::Big => u64::from_be_bytes(bytes),
})
}
}
}
}
impl Decodable for NonZeroU64 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroU64::new(decoder.decode_u64()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroU64 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroU64::new(u64::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::U64,
})
}
}
impl Decodable for u128 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_u128()
impl Decode for u128 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_u128(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 16];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => u128::from_le_bytes(bytes),
Endian::Big => u128::from_be_bytes(bytes),
})
}
}
}
}
impl Decodable for NonZeroU128 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroU128::new(decoder.decode_u128()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroU128 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroU128::new(u128::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::U128,
})
}
}
impl Decodable for usize {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_usize()
impl Decode for usize {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_usize(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => u64::from_le_bytes(bytes),
Endian::Big => u64::from_be_bytes(bytes),
} as usize)
}
}
}
}
impl Decodable for NonZeroUsize {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroUsize::new(decoder.decode_usize()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroUsize {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroUsize::new(usize::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::Usize,
})
}
}
impl Decodable for i8 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_i8()
impl Decode for i8 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let mut bytes = [0u8; 1];
decoder.reader().read(&mut bytes)?;
Ok(bytes[0] as i8)
}
}
impl Decodable for NonZeroI8 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroI8::new(decoder.decode_i8()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroI8 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroI8::new(i8::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::I8,
})
}
}
impl Decodable for i16 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_i16()
impl Decode for i16 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_i16(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 2];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => i16::from_le_bytes(bytes),
Endian::Big => i16::from_be_bytes(bytes),
})
}
}
}
}
impl Decodable for NonZeroI16 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroI16::new(decoder.decode_i16()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroI16 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroI16::new(i16::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::I16,
})
}
}
impl Decodable for i32 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_i32()
impl Decode for i32 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_i32(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 4];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => i32::from_le_bytes(bytes),
Endian::Big => i32::from_be_bytes(bytes),
})
}
}
}
}
impl Decodable for NonZeroI32 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroI32::new(decoder.decode_i32()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroI32 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroI32::new(i32::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::I32,
})
}
}
impl Decodable for i64 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_i64()
impl Decode for i64 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_i64(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => i64::from_le_bytes(bytes),
Endian::Big => i64::from_be_bytes(bytes),
})
}
}
}
}
impl Decodable for NonZeroI64 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroI64::new(decoder.decode_i64()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroI64 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroI64::new(i64::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::I64,
})
}
}
impl Decodable for i128 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_i128()
impl Decode for i128 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_i128(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 16];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => i128::from_le_bytes(bytes),
Endian::Big => i128::from_be_bytes(bytes),
})
}
}
}
}
impl Decodable for NonZeroI128 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroI128::new(decoder.decode_i128()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroI128 {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroI128::new(i128::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::I128,
})
}
}
impl Decodable for isize {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_isize()
impl Decode for isize {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match D::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_decode_isize(decoder.reader(), D::C::ENDIAN)
}
IntEncoding::Fixed => {
let mut bytes = [0u8; 8];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => i64::from_le_bytes(bytes),
Endian::Big => i64::from_be_bytes(bytes),
} as isize)
}
}
}
}
impl Decodable for NonZeroIsize {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
NonZeroIsize::new(decoder.decode_isize()?).ok_or(DecodeError::NonZeroTypeIsZero {
impl Decode for NonZeroIsize {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
NonZeroIsize::new(isize::decode(decoder)?).ok_or(DecodeError::NonZeroTypeIsZero {
non_zero_type: IntegerType::Isize,
})
}
}
impl Decodable for f32 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_f32()
impl Decode for f32 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let mut bytes = [0u8; 4];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => f32::from_le_bytes(bytes),
Endian::Big => f32::from_be_bytes(bytes),
})
}
}
impl Decodable for f64 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_f64()
impl Decode for f64 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let mut bytes = [0u8; 8];
decoder.reader().read(&mut bytes)?;
Ok(match D::C::ENDIAN {
Endian::Little => f64::from_le_bytes(bytes),
Endian::Big => f64::from_be_bytes(bytes),
})
}
}
impl Decodable for char {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_char()
impl Decode for char {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let mut array = [0u8; 4];
// Look at the first byte to see how many bytes must be read
decoder.reader().read(&mut array[..1])?;
let width = utf8_char_width(array[0]);
if width == 0 {
return Err(DecodeError::InvalidCharEncoding(array));
}
if width == 1 {
return Ok(array[0] as char);
}
// read the remaining pain
decoder.reader().read(&mut array[1..width])?;
let res = core::str::from_utf8(&array[..width])
.ok()
.and_then(|s| s.chars().next())
.ok_or(DecodeError::InvalidCharEncoding(array))?;
Ok(res)
}
}
impl<'a, 'de: 'a> BorrowDecodable<'de> for &'a [u8] {
fn borrow_decode<D: BorrowDecode<'de>>(mut decoder: D) -> Result<Self, DecodeError> {
impl<'a, 'de: 'a> BorrowDecode<'de> for &'a [u8] {
fn borrow_decode<D: BorrowDecoder<'de>>(mut decoder: D) -> Result<Self, DecodeError> {
let len = usize::decode(&mut decoder)?;
decoder.decode_slice(len)
decoder.borrow_reader().take_bytes(len)
}
}
impl<'a, 'de: 'a> BorrowDecodable<'de> for &'a str {
fn borrow_decode<D: BorrowDecode<'de>>(decoder: D) -> Result<Self, DecodeError> {
let slice: &[u8] = BorrowDecodable::borrow_decode(decoder)?;
impl<'a, 'de: 'a> BorrowDecode<'de> for &'a str {
fn borrow_decode<D: BorrowDecoder<'de>>(decoder: D) -> Result<Self, DecodeError> {
let slice: &[u8] = BorrowDecode::borrow_decode(decoder)?;
core::str::from_utf8(slice).map_err(DecodeError::Utf8)
}
}
impl<const N: usize> Decodable for [u8; N] {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
decoder.decode_array()
impl<const N: usize> Decode for [u8; N] {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let mut array = [0u8; N];
if !D::C::SKIP_FIXED_ARRAY_LENGTH {
let length = usize::decode(&mut decoder)?;
if length != N {
return Err(DecodeError::ArrayLengthMismatch {
found: length,
required: N,
});
}
}
decoder.reader().read(&mut array)?;
Ok(array)
}
}
impl<T> Decodable for core::marker::PhantomData<T> {
fn decode<D: Decode>(_: D) -> Result<Self, DecodeError> {
impl<T> Decode for core::marker::PhantomData<T> {
fn decode<D: Decoder>(_: D) -> Result<Self, DecodeError> {
Ok(core::marker::PhantomData)
}
}
impl<T> Decodable for Option<T>
impl<T> Decode for Option<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let is_some = u8::decode(&mut decoder)?;
match is_some {
0 => Ok(None),
@ -254,12 +424,12 @@ where
}
}
impl<T, U> Decodable for Result<T, U>
impl<T, U> Decode for Result<T, U>
where
T: Decodable,
U: Decodable,
T: Decode,
U: Decode,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let is_ok = u8::decode(&mut decoder)?;
match is_ok {
0 => {
@ -280,61 +450,61 @@ where
}
}
impl<T> Decodable for Cell<T>
impl<T> Decode for Cell<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let t = T::decode(decoder)?;
Ok(Cell::new(t))
}
}
impl<T> Decodable for RefCell<T>
impl<T> Decode for RefCell<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let t = T::decode(decoder)?;
Ok(RefCell::new(t))
}
}
impl Decodable for Duration {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
let secs = Decodable::decode(&mut decoder)?;
let nanos = Decodable::decode(&mut decoder)?;
impl Decode for Duration {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let secs = Decode::decode(&mut decoder)?;
let nanos = Decode::decode(&mut decoder)?;
Ok(Duration::new(secs, nanos))
}
}
impl<T> Decodable for Range<T>
impl<T> Decode for Range<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let min = T::decode(&mut decoder)?;
let max = T::decode(&mut decoder)?;
Ok(min..max)
}
}
impl<T> Decodable for RangeInclusive<T>
impl<T> Decode for RangeInclusive<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let min = T::decode(&mut decoder)?;
let max = T::decode(&mut decoder)?;
Ok(RangeInclusive::new(min, max))
}
}
impl<T> Decodable for Bound<T>
impl<T> Decode for Bound<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match u32::decode(&mut decoder)? {
0 => Ok(Bound::Unbounded),
1 => Ok(Bound::Included(T::decode(decoder)?)),
@ -349,80 +519,26 @@ where
}
}
impl<'a, 'de, T> Decode for &'a mut T
where
T: Decode,
{
fn decode_u8(&mut self) -> Result<u8, DecodeError> {
T::decode_u8(self)
}
const UTF8_CHAR_WIDTH: [u8; 256] = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x1F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x3F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x5F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x7F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0x9F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, // 0xBF
0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, // 0xDF
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEF
4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xFF
];
fn decode_u16(&mut self) -> Result<u16, DecodeError> {
T::decode_u16(self)
}
fn decode_u32(&mut self) -> Result<u32, DecodeError> {
T::decode_u32(self)
}
fn decode_u64(&mut self) -> Result<u64, DecodeError> {
T::decode_u64(self)
}
fn decode_u128(&mut self) -> Result<u128, DecodeError> {
T::decode_u128(self)
}
fn decode_usize(&mut self) -> Result<usize, DecodeError> {
T::decode_usize(self)
}
fn decode_i8(&mut self) -> Result<i8, DecodeError> {
T::decode_i8(self)
}
fn decode_i16(&mut self) -> Result<i16, DecodeError> {
T::decode_i16(self)
}
fn decode_i32(&mut self) -> Result<i32, DecodeError> {
T::decode_i32(self)
}
fn decode_i64(&mut self) -> Result<i64, DecodeError> {
T::decode_i64(self)
}
fn decode_i128(&mut self) -> Result<i128, DecodeError> {
T::decode_i128(self)
}
fn decode_isize(&mut self) -> Result<isize, DecodeError> {
T::decode_isize(self)
}
fn decode_f32(&mut self) -> Result<f32, DecodeError> {
T::decode_f32(self)
}
fn decode_f64(&mut self) -> Result<f64, DecodeError> {
T::decode_f64(self)
}
fn decode_array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
T::decode_array::<N>(self)
}
fn decode_char(&mut self) -> Result<char, DecodeError> {
T::decode_char(self)
}
}
impl<'a, 'de, T> BorrowDecode<'de> for &'a mut T
where
T: BorrowDecode<'de>,
{
fn decode_slice(&mut self, len: usize) -> Result<&'de [u8], DecodeError> {
T::decode_slice(self, len)
}
// This function is a copy of core::str::utf8_char_width
const fn utf8_char_width(b: u8) -> usize {
UTF8_CHAR_WIDTH[b as usize] as usize
}

View File

@ -1,81 +1,95 @@
//! Decoder-based structs and traits.
use crate::error::DecodeError;
use crate::{config::Config, error::DecodeError};
mod decoder;
mod impl_tuples;
mod impls;
pub mod read;
pub use self::decoder::Decoder;
pub use self::decoder::DecoderImpl;
use self::read::{BorrowReader, Reader};
/// Trait that makes a type able to be decoded, akin to serde's `DeserializeOwned` trait.
///
/// This trait should be implemented for types which do not have references to data in the reader. For types that contain e.g. `&str` and `&[u8]`, implement [BorrowDecodable] instead.
/// This trait should be implemented for types which do not have references to data in the reader. For types that contain e.g. `&str` and `&[u8]`, implement [BorrowDecode] instead.
///
/// Whenever you implement `Decodable` for your type, the base trait `BorrowDecodable` is automatically implemented.
pub trait Decodable: for<'de> BorrowDecodable<'de> {
/// Whenever you implement `Decode` for your type, the base trait `BorrowDecode` is automatically implemented.
pub trait Decode: for<'de> BorrowDecode<'de> {
/// Attempt to decode this type with the given [Decode].
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError>;
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError>;
}
/// Trait that makes a type able to be decoded, akin to serde's `Deserialize` trait.
///
/// This trait should be implemented for types that contain borrowed data, like `&str` and `&[u8]`. If your type does not have borrowed data, consider implementing [Decodable] instead.
pub trait BorrowDecodable<'de>: Sized {
/// This trait should be implemented for types that contain borrowed data, like `&str` and `&[u8]`. If your type does not have borrowed data, consider implementing [Decode] instead.
pub trait BorrowDecode<'de>: Sized {
/// Attempt to decode this type with the given [BorrowDecode].
fn borrow_decode<D: BorrowDecode<'de>>(decoder: D) -> Result<Self, DecodeError>;
fn borrow_decode<D: BorrowDecoder<'de>>(decoder: D) -> Result<Self, DecodeError>;
}
impl<'de, T: Decodable> BorrowDecodable<'de> for T {
fn borrow_decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
Decodable::decode(decoder)
impl<'de, T: Decode> BorrowDecode<'de> for T {
fn borrow_decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
Decode::decode(decoder)
}
}
/// Any source that can decode basic types. This type is most notably implemented for [Decoder].
pub trait Decode {
/// Attempt to decode a `u8`
fn decode_u8(&mut self) -> Result<u8, DecodeError>;
/// Attempt to decode a `u16`
fn decode_u16(&mut self) -> Result<u16, DecodeError>;
/// Attempt to decode a `u32`
fn decode_u32(&mut self) -> Result<u32, DecodeError>;
/// Attempt to decode a `u64`
fn decode_u64(&mut self) -> Result<u64, DecodeError>;
/// Attempt to decode a `u128`
fn decode_u128(&mut self) -> Result<u128, DecodeError>;
/// Attempt to decode a `usize`
fn decode_usize(&mut self) -> Result<usize, DecodeError>;
pub trait Decoder: sealed::Sealed {
/// The concrete [Reader] type
type R: Reader;
/// Attempt to decode a `i8`
fn decode_i8(&mut self) -> Result<i8, DecodeError>;
/// Attempt to decode a `i16`
fn decode_i16(&mut self) -> Result<i16, DecodeError>;
/// Attempt to decode a `i32`
fn decode_i32(&mut self) -> Result<i32, DecodeError>;
/// Attempt to decode a `i64`
fn decode_i64(&mut self) -> Result<i64, DecodeError>;
/// Attempt to decode a `i128`
fn decode_i128(&mut self) -> Result<i128, DecodeError>;
/// Attempt to decode a `isize`
fn decode_isize(&mut self) -> Result<isize, DecodeError>;
/// The concrete [Config] type
type C: Config;
/// Attempt to decode a `f32`
fn decode_f32(&mut self) -> Result<f32, DecodeError>;
/// Attempt to decode a `f64`
fn decode_f64(&mut self) -> Result<f64, DecodeError>;
/// Attempt to decode an array of `N` entries.
fn decode_array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError>;
/// Returns a mutable reference to the reader
fn reader(&mut self) -> &mut Self::R;
/// Attempt to decode a `char`
fn decode_char(&mut self) -> Result<char, DecodeError>;
/// Returns a mutable reference to the config
fn config(&self) -> &Self::C;
}
/// Any source that can decode basic types. This type is most notably implemented for [Decoder].
///
/// This is an extension of [Decode] that can also return borrowed data.
pub trait BorrowDecode<'de>: Decode {
/// Decode `len` bytes, returning the slice as borrowed data.
fn decode_slice(&mut self, len: usize) -> Result<&'de [u8], DecodeError>;
pub trait BorrowDecoder<'de>: Decoder {
/// The concrete [BorrowReader] type
type BR: BorrowReader<'de>;
/// Rerturns a mutable reference to the borrow reader
fn borrow_reader(&mut self) -> &mut Self::BR;
}
impl<'a, 'de, T> Decoder for &'a mut T
where
T: Decoder,
{
type R = T::R;
type C = T::C;
fn reader(&mut self) -> &mut Self::R {
T::reader(self)
}
fn config(&self) -> &Self::C {
T::config(self)
}
}
impl<'a, 'de, T> BorrowDecoder<'de> for &'a mut T
where
T: BorrowDecoder<'de>,
{
type BR = T::BR;
fn borrow_reader(&mut self) -> &mut Self::BR {
T::borrow_reader(self)
}
}
pub(crate) mod sealed {
pub trait Sealed {}
impl<'a, T> Sealed for &'a mut T where T: Sealed {}
}

View File

@ -6,21 +6,21 @@
//!
//! [BorrowReader] is an extension of `Reader` that also allows returning borrowed data. A `BorrowReader` allows reading `&str` and `&[u8]`.
//!
//! Specifically the `Reader` trait is used by [Decodable] and the `BorrowReader` trait is used by `[BorrowDecodable]`.
//! Specifically the `Reader` trait is used by [Decode] and the `BorrowReader` trait is used by `[BorrowDecode]`.
//!
//! [Decodable]: ../trait.Decodable.html
//! [BorrowDecodable]: ../trait.BorrowDecodable.html
//! [Decode]: ../trait.Decode.html
//! [BorrowDecode]: ../trait.BorrowDecode.html
use crate::error::DecodeError;
/// A reader for owned data. See the module documentation for more information.
pub trait Reader<'storage> {
pub trait Reader {
/// Fill the given `bytes` argument with values. Exactly the length of the given slice must be filled, or else an error must be returned.
fn read(&mut self, bytes: &mut [u8]) -> Result<(), DecodeError>;
}
/// A reader for borrowed data. Implementors of this must also implement the [Reader] trait. See the module documentation for more information.
pub trait BorrowReader<'storage>: Reader<'storage> {
pub trait BorrowReader<'storage>: Reader {
/// Read exactly `length` bytes and return a slice to this data. If not enough bytes could be read, an error should be returned.
///
/// *note*: Exactly `length` bytes must be returned. If less bytes are returned, bincode may panic. If more bytes are returned, the excess bytes may be discarded.
@ -49,7 +49,7 @@ impl<'storage> SliceReader<'storage> {
}
}
impl<'storage> Reader<'storage> for SliceReader<'storage> {
impl<'storage> Reader for SliceReader<'storage> {
#[inline(always)]
fn read(&mut self, bytes: &mut [u8]) -> Result<(), DecodeError> {
if bytes.len() > self.slice.len() {

View File

@ -1,11 +1,7 @@
//! Contains
use super::{write::Writer, Encode};
use crate::{
config::{Config, Endian, IntEncoding},
error::EncodeError,
};
use core::marker::PhantomData;
use super::{sealed::Sealed, write::Writer, Encoder};
use crate::config::Config;
/// An Encoder that writes bytes into a given writer `W`.
///
@ -16,28 +12,25 @@ use core::marker::PhantomData;
/// is used to write integers to the writer.
///
/// ```
/// # use bincode::enc::{write::SliceWriter, Encoder, Encodeable};
/// # use bincode::enc::{write::SliceWriter, EncoderImpl, Encode};
/// # use bincode::config::{self, Config};
/// # let config = config::Default.with_fixed_int_encoding().with_big_endian();
/// let slice: &mut [u8] = &mut [0, 0, 0, 0];
/// let mut encoder = Encoder::new(SliceWriter::new(slice), config);
/// let mut encoder = EncoderImpl::new(SliceWriter::new(slice), config);
/// // this u32 can be any Encodable
/// 5u32.encode(&mut encoder).unwrap();
/// assert_eq!(encoder.into_writer().bytes_written(), 4);
/// assert_eq!(slice, [0, 0, 0, 5]);
/// ```
pub struct Encoder<W: Writer, C: Config> {
pub struct EncoderImpl<W: Writer, C: Config> {
writer: W,
config: PhantomData<C>,
config: C,
}
impl<W: Writer, C: Config> Encoder<W, C> {
impl<W: Writer, C: Config> EncoderImpl<W, C> {
/// Create a new Encoder
pub fn new(writer: W, _config: C) -> Encoder<W, C> {
Encoder {
writer,
config: PhantomData,
}
pub fn new(writer: W, config: C) -> EncoderImpl<W, C> {
EncoderImpl { writer, config }
}
/// Return the underlying writer
@ -46,196 +39,18 @@ impl<W: Writer, C: Config> Encoder<W, C> {
}
}
impl<'a, W: Writer, C: Config> Encode for &'a mut Encoder<W, C> {
fn encode_u8(&mut self, val: u8) -> Result<(), EncodeError> {
self.writer.write(&[val])
impl<'a, W: Writer, C: Config> Encoder for &'a mut EncoderImpl<W, C> {
type W = W;
type C = C;
fn writer(&mut self) -> &mut Self::W {
&mut self.writer
}
fn encode_u16(&mut self, val: u16) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_u16(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_u32(&mut self, val: u32) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_u32(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_u64(&mut self, val: u64) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_u64(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_u128(&mut self, val: u128) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_u128(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_usize(&mut self, val: usize) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_usize(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_i8(&mut self, val: i8) -> Result<(), EncodeError> {
self.writer.write(&[val as u8])
}
fn encode_i16(&mut self, val: i16) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_i16(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_i32(&mut self, val: i32) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_i32(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_i64(&mut self, val: i64) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_i64(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_i128(&mut self, val: i128) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_i128(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_isize(&mut self, val: isize) -> Result<(), EncodeError> {
match C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_isize(&mut self.writer, C::ENDIAN, val)
}
IntEncoding::Fixed => match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
},
}
}
fn encode_f32(&mut self, val: f32) -> Result<(), EncodeError> {
match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
}
}
fn encode_f64(&mut self, val: f64) -> Result<(), EncodeError> {
match C::ENDIAN {
Endian::Big => self.writer.write(&val.to_be_bytes()),
Endian::Little => self.writer.write(&val.to_le_bytes()),
}
}
fn encode_slice(&mut self, val: &[u8]) -> Result<(), EncodeError> {
self.encode_usize(val.len())?;
self.writer.write(val)
}
fn encode_array<const N: usize>(&mut self, val: [u8; N]) -> Result<(), EncodeError> {
if !C::SKIP_FIXED_ARRAY_LENGTH {
self.encode_usize(N)?;
}
self.writer.write(&val)
}
fn encode_char(&mut self, val: char) -> Result<(), EncodeError> {
encode_utf8(&mut self.writer, val)
fn config(&self) -> &Self::C {
&self.config
}
}
const TAG_CONT: u8 = 0b1000_0000;
const TAG_TWO_B: u8 = 0b1100_0000;
const TAG_THREE_B: u8 = 0b1110_0000;
const TAG_FOUR_B: u8 = 0b1111_0000;
const MAX_ONE_B: u32 = 0x80;
const MAX_TWO_B: u32 = 0x800;
const MAX_THREE_B: u32 = 0x10000;
fn encode_utf8(writer: &mut impl Writer, c: char) -> Result<(), EncodeError> {
let code = c as u32;
if code < MAX_ONE_B {
writer.write(&[c as u8])
} else if code < MAX_TWO_B {
let mut buf = [0u8; 2];
buf[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
buf[1] = (code & 0x3F) as u8 | TAG_CONT;
writer.write(&buf)
} else if code < MAX_THREE_B {
let mut buf = [0u8; 3];
buf[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
buf[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
buf[2] = (code & 0x3F) as u8 | TAG_CONT;
writer.write(&buf)
} else {
let mut buf = [0u8; 4];
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
writer.write(&buf)
}
}
impl<'a, W: Writer, C: Config> Sealed for &'a mut EncoderImpl<W, C> {}

View File

@ -1,35 +1,35 @@
use super::{Encode, Encodeable};
use super::{Encode, Encoder};
use crate::error::EncodeError;
impl<A> Encodeable for (A,)
impl<A> Encode for (A,)
where
A: Encodeable,
A: Encode,
{
fn encode<_E: Encode>(&self, mut encoder: _E) -> Result<(), EncodeError> {
fn encode<_E: Encoder>(&self, mut encoder: _E) -> Result<(), EncodeError> {
self.0.encode(&mut encoder)?;
Ok(())
}
}
impl<A, B> Encodeable for (A, B)
impl<A, B> Encode for (A, B)
where
A: Encodeable,
B: Encodeable,
A: Encode,
B: Encode,
{
fn encode<_E: Encode>(&self, mut encoder: _E) -> Result<(), EncodeError> {
fn encode<_E: Encoder>(&self, mut encoder: _E) -> Result<(), EncodeError> {
self.0.encode(&mut encoder)?;
self.1.encode(&mut encoder)?;
Ok(())
}
}
impl<A, B, C> Encodeable for (A, B, C)
impl<A, B, C> Encode for (A, B, C)
where
A: Encodeable,
B: Encodeable,
C: Encodeable,
A: Encode,
B: Encode,
C: Encode,
{
fn encode<_E: Encode>(&self, mut encoder: _E) -> Result<(), EncodeError> {
fn encode<_E: Encoder>(&self, mut encoder: _E) -> Result<(), EncodeError> {
self.0.encode(&mut encoder)?;
self.1.encode(&mut encoder)?;
self.2.encode(&mut encoder)?;
@ -37,14 +37,14 @@ where
}
}
impl<A, B, C, D> Encodeable for (A, B, C, D)
impl<A, B, C, D> Encode for (A, B, C, D)
where
A: Encodeable,
B: Encodeable,
C: Encodeable,
D: Encodeable,
A: Encode,
B: Encode,
C: Encode,
D: Encode,
{
fn encode<_E: Encode>(&self, mut encoder: _E) -> Result<(), EncodeError> {
fn encode<_E: Encoder>(&self, mut encoder: _E) -> Result<(), EncodeError> {
self.0.encode(&mut encoder)?;
self.1.encode(&mut encoder)?;
self.2.encode(&mut encoder)?;
@ -53,15 +53,15 @@ where
}
}
impl<A, B, C, D, E> Encodeable for (A, B, C, D, E)
impl<A, B, C, D, E> Encode for (A, B, C, D, E)
where
A: Encodeable,
B: Encodeable,
C: Encodeable,
D: Encodeable,
E: Encodeable,
A: Encode,
B: Encode,
C: Encode,
D: Encode,
E: Encode,
{
fn encode<_E: Encode>(&self, mut encoder: _E) -> Result<(), EncodeError> {
fn encode<_E: Encoder>(&self, mut encoder: _E) -> Result<(), EncodeError> {
self.0.encode(&mut encoder)?;
self.1.encode(&mut encoder)?;
self.2.encode(&mut encoder)?;
@ -71,16 +71,16 @@ where
}
}
impl<A, B, C, D, E, F> Encodeable for (A, B, C, D, E, F)
impl<A, B, C, D, E, F> Encode for (A, B, C, D, E, F)
where
A: Encodeable,
B: Encodeable,
C: Encodeable,
D: Encodeable,
E: Encodeable,
F: Encodeable,
A: Encode,
B: Encode,
C: Encode,
D: Encode,
E: Encode,
F: Encode,
{
fn encode<_E: Encode>(&self, mut encoder: _E) -> Result<(), EncodeError> {
fn encode<_E: Encoder>(&self, mut encoder: _E) -> Result<(), EncodeError> {
self.0.encode(&mut encoder)?;
self.1.encode(&mut encoder)?;
self.2.encode(&mut encoder)?;
@ -91,17 +91,17 @@ where
}
}
impl<A, B, C, D, E, F, G> Encodeable for (A, B, C, D, E, F, G)
impl<A, B, C, D, E, F, G> Encode for (A, B, C, D, E, F, G)
where
A: Encodeable,
B: Encodeable,
C: Encodeable,
D: Encodeable,
E: Encodeable,
F: Encodeable,
G: Encodeable,
A: Encode,
B: Encode,
C: Encode,
D: Encode,
E: Encode,
F: Encode,
G: Encode,
{
fn encode<_E: Encode>(&self, mut encoder: _E) -> Result<(), EncodeError> {
fn encode<_E: Encoder>(&self, mut encoder: _E) -> Result<(), EncodeError> {
self.0.encode(&mut encoder)?;
self.1.encode(&mut encoder)?;
self.2.encode(&mut encoder)?;
@ -113,18 +113,18 @@ where
}
}
impl<A, B, C, D, E, F, G, H> Encodeable for (A, B, C, D, E, F, G, H)
impl<A, B, C, D, E, F, G, H> Encode for (A, B, C, D, E, F, G, H)
where
A: Encodeable,
B: Encodeable,
C: Encodeable,
D: Encodeable,
E: Encodeable,
F: Encodeable,
G: Encodeable,
H: Encodeable,
A: Encode,
B: Encode,
C: Encode,
D: Encode,
E: Encode,
F: Encode,
G: Encode,
H: Encode,
{
fn encode<_E: Encode>(&self, mut encoder: _E) -> Result<(), EncodeError> {
fn encode<_E: Encoder>(&self, mut encoder: _E) -> Result<(), EncodeError> {
self.0.encode(&mut encoder)?;
self.1.encode(&mut encoder)?;
self.2.encode(&mut encoder)?;

View File

@ -1,5 +1,8 @@
use super::{Encode, Encodeable};
use crate::error::EncodeError;
use super::{write::Writer, Encode, Encoder};
use crate::{
config::{Endian, IntEncoding, InternalConfig},
error::EncodeError,
};
use core::{
cell::{Cell, RefCell},
num::{
@ -10,192 +13,313 @@ use core::{
time::Duration,
};
impl Encodeable for bool {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_u8(if *self { 1 } else { 0 })
impl Encode for bool {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
if *self { 1u8 } else { 0u8 }.encode(encoder)
}
}
impl Encodeable for u8 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_u8(*self)
impl Encode for u8 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.writer().write(&[*self])
}
}
impl Encodeable for NonZeroU8 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroU8 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for u16 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_u16(*self)
impl Encode for u16 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_u16(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroU16 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroU16 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for u32 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_u32(*self)
impl Encode for u32 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_u32(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroU32 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroU32 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for u64 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_u64(*self)
impl Encode for u64 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_u64(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroU64 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroU64 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for u128 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_u128(*self)
impl Encode for u128 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_u128(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroU128 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroU128 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for usize {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_usize(*self)
impl Encode for usize {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_usize(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroUsize {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroUsize {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for i8 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_i8(*self)
impl Encode for i8 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.writer().write(&[*self as u8])
}
}
impl Encodeable for NonZeroI8 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroI8 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for i16 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_i16(*self)
impl Encode for i16 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_i16(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroI16 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroI16 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for i32 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_i32(*self)
impl Encode for i32 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_i32(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroI32 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroI32 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for i64 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_i64(*self)
impl Encode for i64 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_i64(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroI64 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroI64 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for i128 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_i128(*self)
impl Encode for i128 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_i128(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroI128 {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroI128 {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for isize {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_isize(*self)
impl Encode for isize {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::INT_ENCODING {
IntEncoding::Variable => {
crate::varint::varint_encode_isize(encoder.writer(), E::C::ENDIAN, *self)
}
IntEncoding::Fixed => match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
},
}
}
}
impl Encodeable for NonZeroIsize {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for NonZeroIsize {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.get().encode(encoder)
}
}
impl Encodeable for f32 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_f32(*self)
impl Encode for f32 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
}
}
}
impl Encodeable for f64 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_f64(*self)
impl Encode for f64 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match E::C::ENDIAN {
Endian::Big => encoder.writer().write(&self.to_be_bytes()),
Endian::Little => encoder.writer().write(&self.to_le_bytes()),
}
}
}
impl Encodeable for char {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_char(*self)
impl Encode for char {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
encode_utf8(encoder.writer(), *self)
}
}
impl Encodeable for &'_ [u8] {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_slice(*self)
impl Encode for &'_ [u8] {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.len().encode(&mut encoder)?;
encoder.writer().write(self)
}
}
const TAG_CONT: u8 = 0b1000_0000;
const TAG_TWO_B: u8 = 0b1100_0000;
const TAG_THREE_B: u8 = 0b1110_0000;
const TAG_FOUR_B: u8 = 0b1111_0000;
const MAX_ONE_B: u32 = 0x80;
const MAX_TWO_B: u32 = 0x800;
const MAX_THREE_B: u32 = 0x10000;
fn encode_utf8(writer: &mut impl Writer, c: char) -> Result<(), EncodeError> {
let code = c as u32;
if code < MAX_ONE_B {
writer.write(&[c as u8])
} else if code < MAX_TWO_B {
let mut buf = [0u8; 2];
buf[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
buf[1] = (code & 0x3F) as u8 | TAG_CONT;
writer.write(&buf)
} else if code < MAX_THREE_B {
let mut buf = [0u8; 3];
buf[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
buf[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
buf[2] = (code & 0x3F) as u8 | TAG_CONT;
writer.write(&buf)
} else {
let mut buf = [0u8; 4];
buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT;
buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT;
buf[3] = (code & 0x3F) as u8 | TAG_CONT;
writer.write(&buf)
}
}
// BlockedTODO: https://github.com/rust-lang/rust/issues/37653
//
// We'll want to implement encoding for both &[u8] and &[T: Encodeable],
// We'll want to implement encoding for both &[u8] and &[T: Encode],
// but those implementations overlap because u8 also implements Encodeabl
//
// default impl Encodeable for &'_ [u8] {
// default impl Encode for &'_ [u8] {
// fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
// encoder.encode_slice(*self)
// }
// }
//
// impl<T: Encodeable> Encodeable for &'_ [T] {
// impl<T: Encode> Encode for &'_ [T] {
// fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
// self.len().encode(&mut encoder)?;
// for item in self.iter() {
@ -205,23 +329,26 @@ impl Encodeable for &'_ [u8] {
// }
// }
impl Encodeable for &'_ str {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_slice(self.as_bytes())
impl Encode for &'_ str {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.as_bytes().encode(encoder)
}
}
impl<const N: usize> Encodeable for [u8; N] {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
encoder.encode_array(*self)
impl<const N: usize> Encode for [u8; N] {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
if !E::C::SKIP_FIXED_ARRAY_LENGTH {
N.encode(&mut encoder)?;
}
encoder.writer().write(self)
}
}
impl<T> Encodeable for Option<T>
impl<T> Encode for Option<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
if let Some(val) = self {
1u8.encode(&mut encoder)?;
val.encode(encoder)
@ -231,12 +358,12 @@ where
}
}
impl<T, U> Encodeable for Result<T, U>
impl<T, U> Encode for Result<T, U>
where
T: Encodeable,
U: Encodeable,
T: Encode,
U: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match self {
Ok(val) => {
0u8.encode(&mut encoder)?;
@ -250,20 +377,20 @@ where
}
}
impl<T> Encodeable for Cell<T>
impl<T> Encode for Cell<T>
where
T: Encodeable + Copy,
T: Encode + Copy,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
T::encode(&self.get(), encoder)
}
}
impl<T> Encodeable for RefCell<T>
impl<T> Encode for RefCell<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
let borrow_guard = self
.try_borrow()
.map_err(|e| EncodeError::RefCellAlreadyBorrowed {
@ -274,41 +401,41 @@ where
}
}
impl Encodeable for Duration {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
impl Encode for Duration {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.as_secs().encode(&mut encoder)?;
self.subsec_nanos().encode(&mut encoder)?;
Ok(())
}
}
impl<T> Encodeable for Range<T>
impl<T> Encode for Range<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.start.encode(&mut encoder)?;
self.end.encode(&mut encoder)?;
Ok(())
}
}
impl<T> Encodeable for RangeInclusive<T>
impl<T> Encode for RangeInclusive<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.start().encode(&mut encoder)?;
self.end().encode(&mut encoder)?;
Ok(())
}
}
impl<T> Encodeable for Bound<T>
impl<T> Encode for Bound<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match self {
Self::Unbounded => {
0u32.encode(encoder)?;
@ -326,71 +453,11 @@ where
}
}
impl<'a, T> Encodeable for &'a T
where
T: Encodeable,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
T::encode(self, encoder)
}
}
impl<'a, T> Encode for &'a mut T
impl<'a, T> Encode for &'a T
where
T: Encode,
{
fn encode_u8(&mut self, val: u8) -> Result<(), EncodeError> {
T::encode_u8(self, val)
}
fn encode_u16(&mut self, val: u16) -> Result<(), EncodeError> {
T::encode_u16(self, val)
}
fn encode_u32(&mut self, val: u32) -> Result<(), EncodeError> {
T::encode_u32(self, val)
}
fn encode_u64(&mut self, val: u64) -> Result<(), EncodeError> {
T::encode_u64(self, val)
}
fn encode_u128(&mut self, val: u128) -> Result<(), EncodeError> {
T::encode_u128(self, val)
}
fn encode_usize(&mut self, val: usize) -> Result<(), EncodeError> {
T::encode_usize(self, val)
}
fn encode_i8(&mut self, val: i8) -> Result<(), EncodeError> {
T::encode_i8(self, val)
}
fn encode_i16(&mut self, val: i16) -> Result<(), EncodeError> {
T::encode_i16(self, val)
}
fn encode_i32(&mut self, val: i32) -> Result<(), EncodeError> {
T::encode_i32(self, val)
}
fn encode_i64(&mut self, val: i64) -> Result<(), EncodeError> {
T::encode_i64(self, val)
}
fn encode_i128(&mut self, val: i128) -> Result<(), EncodeError> {
T::encode_i128(self, val)
}
fn encode_isize(&mut self, val: isize) -> Result<(), EncodeError> {
T::encode_isize(self, val)
}
fn encode_f32(&mut self, val: f32) -> Result<(), EncodeError> {
T::encode_f32(self, val)
}
fn encode_f64(&mut self, val: f64) -> Result<(), EncodeError> {
T::encode_f64(self, val)
}
fn encode_slice(&mut self, val: &[u8]) -> Result<(), EncodeError> {
T::encode_slice(self, val)
}
fn encode_array<const N: usize>(&mut self, val: [u8; N]) -> Result<(), EncodeError> {
T::encode_array(self, val)
}
fn encode_char(&mut self, val: char) -> Result<(), EncodeError> {
T::encode_char(self, val)
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
T::encode(self, encoder)
}
}

View File

@ -4,57 +4,55 @@ mod encoder;
mod impl_tuples;
mod impls;
use crate::error::EncodeError;
use crate::{config::Config, error::EncodeError};
pub mod write;
pub use self::encoder::Encoder;
pub use self::encoder::EncoderImpl;
use self::write::Writer;
/// Any source that can encode types. This type is most notably implemented for [Encoder].
///
/// [Encoder]: ../struct.Encoder.html
pub trait Encodeable {
pub trait Encode {
/// Encode a given type.
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError>;
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError>;
}
/// Helper trait to encode basic types into.
pub trait Encode {
/// Encode an `u8`
fn encode_u8(&mut self, val: u8) -> Result<(), EncodeError>;
/// Encode an `u16`
fn encode_u16(&mut self, val: u16) -> Result<(), EncodeError>;
/// Encode an `u32`
fn encode_u32(&mut self, val: u32) -> Result<(), EncodeError>;
/// Encode an `u64`
fn encode_u64(&mut self, val: u64) -> Result<(), EncodeError>;
/// Encode an `u128`
fn encode_u128(&mut self, val: u128) -> Result<(), EncodeError>;
/// Encode an `usize`
fn encode_usize(&mut self, val: usize) -> Result<(), EncodeError>;
pub trait Encoder: sealed::Sealed {
/// The concrete [Writer] type
type W: Writer;
/// Encode an `i8`
fn encode_i8(&mut self, val: i8) -> Result<(), EncodeError>;
/// Encode an `i16`
fn encode_i16(&mut self, val: i16) -> Result<(), EncodeError>;
/// Encode an `i32`
fn encode_i32(&mut self, val: i32) -> Result<(), EncodeError>;
/// Encode an `i64`
fn encode_i64(&mut self, val: i64) -> Result<(), EncodeError>;
/// Encode an `i128`
fn encode_i128(&mut self, val: i128) -> Result<(), EncodeError>;
/// Encode an `isize`
fn encode_isize(&mut self, val: isize) -> Result<(), EncodeError>;
/// The concrete [Config] type
type C: Config;
/// Encode an `f32`
fn encode_f32(&mut self, val: f32) -> Result<(), EncodeError>;
/// Encode an `f64`
fn encode_f64(&mut self, val: f64) -> Result<(), EncodeError>;
/// Encode a slice. Exactly `val.len()` bytes must be encoded, else an error should be thrown.
fn encode_slice(&mut self, val: &[u8]) -> Result<(), EncodeError>;
/// Encode an array. Exactly `N` bytes must be encoded, else an error should be thrown.
fn encode_array<const N: usize>(&mut self, val: [u8; N]) -> Result<(), EncodeError>;
/// Returns a mutable reference to the writer
fn writer(&mut self) -> &mut Self::W;
/// Encode a single utf8 char
fn encode_char(&mut self, val: char) -> Result<(), EncodeError>;
/// Returns a reference to the config
fn config(&self) -> &Self::C;
}
impl<'a, 'de, T> Encoder for &'a mut T
where
T: Encoder,
{
type W = T::W;
type C = T::C;
fn writer(&mut self) -> &mut Self::W {
T::writer(self)
}
fn config(&self) -> &Self::C {
T::config(self)
}
}
pub(crate) mod sealed {
pub trait Sealed {}
impl<'a, T> Sealed for &'a mut T where T: Sealed {}
}

View File

@ -4,9 +4,9 @@
use crate::error::EncodeError;
/// Trait that indicates that a struct can be used as a destination to encode data too. This is used by [Encodeable]
/// Trait that indicates that a struct can be used as a destination to encode data too. This is used by [Encode]
///
/// [Encodeable]: ../trait.Encodeable.html
/// [Encode]: ../trait.Encode.html
pub trait Writer {
/// Write `bytes` to the underlying writer. Exactly `bytes.len()` bytes must be written, or else an error should be returned.
fn write(&mut self, bytes: &[u8]) -> Result<(), EncodeError>;

View File

@ -1,137 +1,137 @@
use crate::{de::Decodable, enc::Encodeable};
use crate::{de::Decode, enc::Encode};
use core::sync::atomic::{
AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32,
AtomicU64, AtomicU8, AtomicUsize, Ordering,
};
impl Encodeable for AtomicBool {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicBool {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicBool {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicBool::new(Decodable::decode(decoder)?))
impl Decode for AtomicBool {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicBool::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicU8 {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicU8 {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicU8 {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicU8::new(Decodable::decode(decoder)?))
impl Decode for AtomicU8 {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicU8::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicU16 {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicU16 {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicU16 {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicU16::new(Decodable::decode(decoder)?))
impl Decode for AtomicU16 {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicU16::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicU32 {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicU32 {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicU32 {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicU32::new(Decodable::decode(decoder)?))
impl Decode for AtomicU32 {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicU32::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicU64 {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicU64 {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicU64 {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicU64::new(Decodable::decode(decoder)?))
impl Decode for AtomicU64 {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicU64::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicUsize {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicUsize {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicUsize {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicUsize::new(Decodable::decode(decoder)?))
impl Decode for AtomicUsize {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicUsize::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicI8 {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicI8 {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicI8 {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicI8::new(Decodable::decode(decoder)?))
impl Decode for AtomicI8 {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicI8::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicI16 {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicI16 {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicI16 {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicI16::new(Decodable::decode(decoder)?))
impl Decode for AtomicI16 {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicI16::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicI32 {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicI32 {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicI32 {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicI32::new(Decodable::decode(decoder)?))
impl Decode for AtomicI32 {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicI32::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicI64 {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicI64 {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicI64 {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicI64::new(Decodable::decode(decoder)?))
impl Decode for AtomicI64 {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicI64::new(Decode::decode(decoder)?))
}
}
impl Encodeable for AtomicIsize {
fn encode<E: crate::enc::Encode>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
impl Encode for AtomicIsize {
fn encode<E: crate::enc::Encoder>(&self, encoder: E) -> Result<(), crate::error::EncodeError> {
self.load(Ordering::SeqCst).encode(encoder)
}
}
impl Decodable for AtomicIsize {
fn decode<D: crate::de::Decode>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicIsize::new(Decodable::decode(decoder)?))
impl Decode for AtomicIsize {
fn decode<D: crate::de::Decoder>(decoder: D) -> Result<Self, crate::error::DecodeError> {
Ok(AtomicIsize::new(Decode::decode(decoder)?))
}
}

View File

@ -1,2 +1,2 @@
#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
pub use bincode_derive::{Decodable, Encodable};
pub use bincode_derive::{Decode, Encode};

View File

@ -1,7 +1,7 @@
use crate::{
config,
de::{Decodable, Decode},
enc::{self, Encode, Encodeable},
de::{Decode, Decoder},
enc::{self, Encode, Encoder},
error::{DecodeError, EncodeError},
Config,
};
@ -21,27 +21,27 @@ impl enc::write::Writer for VecWriter {
/// Encode the given value into a `Vec<u8>`.
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn encode_to_vec<E: enc::Encodeable>(val: E) -> Result<Vec<u8>, EncodeError> {
pub fn encode_to_vec<E: enc::Encode>(val: E) -> Result<Vec<u8>, EncodeError> {
encode_to_vec_with_config(val, config::Default)
}
/// Encode the given value into a `Vec<u8>` with the given `Config`. See the [config] module for more information.
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn encode_to_vec_with_config<E: enc::Encodeable, C: Config>(
pub fn encode_to_vec_with_config<E: enc::Encode, C: Config>(
val: E,
config: C,
) -> Result<Vec<u8>, EncodeError> {
let writer = VecWriter::default();
let mut encoder = enc::Encoder::<_, C>::new(writer, config);
let mut encoder = enc::EncoderImpl::<_, C>::new(writer, config);
val.encode(&mut encoder)?;
Ok(encoder.into_writer().inner)
}
impl<T> Decodable for BinaryHeap<T>
impl<T> Decode for BinaryHeap<T>
where
T: Decodable + Ord,
T: Decode + Ord,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let len = usize::decode(&mut decoder)?;
let mut map = BinaryHeap::with_capacity(len);
for _ in 0..len {
@ -52,11 +52,11 @@ where
}
}
impl<T> Encodeable for BinaryHeap<T>
impl<T> Encode for BinaryHeap<T>
where
T: Encodeable + Ord,
T: Encode + Ord,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.len().encode(&mut encoder)?;
for val in self.iter() {
val.encode(&mut encoder)?;
@ -65,12 +65,12 @@ where
}
}
impl<K, V> Decodable for BTreeMap<K, V>
impl<K, V> Decode for BTreeMap<K, V>
where
K: Decodable + Ord,
V: Decodable,
K: Decode + Ord,
V: Decode,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let len = usize::decode(&mut decoder)?;
let mut map = BTreeMap::new();
for _ in 0..len {
@ -82,12 +82,12 @@ where
}
}
impl<K, V> Encodeable for BTreeMap<K, V>
impl<K, V> Encode for BTreeMap<K, V>
where
K: Encodeable + Ord,
V: Encodeable,
K: Encode + Ord,
V: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.len().encode(&mut encoder)?;
for (key, val) in self.iter() {
key.encode(&mut encoder)?;
@ -97,11 +97,11 @@ where
}
}
impl<T> Decodable for BTreeSet<T>
impl<T> Decode for BTreeSet<T>
where
T: Decodable + Ord,
T: Decode + Ord,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let len = usize::decode(&mut decoder)?;
let mut map = BTreeSet::new();
for _ in 0..len {
@ -112,11 +112,11 @@ where
}
}
impl<T> Encodeable for BTreeSet<T>
impl<T> Encode for BTreeSet<T>
where
T: Encodeable + Ord,
T: Encode + Ord,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.len().encode(&mut encoder)?;
for item in self.iter() {
item.encode(&mut encoder)?;
@ -125,11 +125,11 @@ where
}
}
impl<T> Decodable for VecDeque<T>
impl<T> Decode for VecDeque<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let len = usize::decode(&mut decoder)?;
let mut map = VecDeque::with_capacity(len);
for _ in 0..len {
@ -140,11 +140,11 @@ where
}
}
impl<T> Encodeable for VecDeque<T>
impl<T> Encode for VecDeque<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.len().encode(&mut encoder)?;
for item in self.iter() {
item.encode(&mut encoder)?;
@ -153,11 +153,11 @@ where
}
}
impl<T> Decodable for Vec<T>
impl<T> Decode for Vec<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let len = usize::decode(&mut decoder)?;
let mut vec = Vec::with_capacity(len);
for _ in 0..len {
@ -167,11 +167,11 @@ where
}
}
impl<T> Encodeable for Vec<T>
impl<T> Encode for Vec<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.len().encode(&mut encoder)?;
for item in self.iter() {
item.encode(&mut encoder)?;
@ -180,53 +180,53 @@ where
}
}
impl Decodable for String {
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
impl Decode for String {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let bytes = Vec::<u8>::decode(decoder)?;
String::from_utf8(bytes).map_err(|e| DecodeError::Utf8(e.utf8_error()))
}
}
impl Encodeable for String {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for String {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.as_bytes().encode(encoder)
}
}
impl<T> Decodable for Box<T>
impl<T> Decode for Box<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let t = T::decode(decoder)?;
Ok(Box::new(t))
}
}
impl<T> Encodeable for Box<T>
impl<T> Encode for Box<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
T::encode(self, encoder)
}
}
impl<T> Decodable for Box<[T]>
impl<T> Decode for Box<[T]>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let vec = Vec::decode(decoder)?;
Ok(vec.into_boxed_slice())
}
}
impl<T> Encodeable for Box<[T]>
impl<T> Encode for Box<[T]>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.len().encode(&mut encoder)?;
for item in self.iter() {
item.encode(&mut encoder)?;
@ -235,61 +235,61 @@ where
}
}
impl<'cow, T> Decodable for Cow<'cow, T>
impl<'cow, T> Decode for Cow<'cow, T>
where
T: Decodable + Clone,
T: Decode + Clone,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let t = T::decode(decoder)?;
Ok(Cow::Owned(t))
}
}
impl<'cow, T> Encodeable for Cow<'cow, T>
impl<'cow, T> Encode for Cow<'cow, T>
where
T: Encodeable + Clone,
T: Encode + Clone,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.as_ref().encode(encoder)
}
}
impl<T> Decodable for Rc<T>
impl<T> Decode for Rc<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let t = T::decode(decoder)?;
Ok(Rc::new(t))
}
}
impl<T> Encodeable for Rc<T>
impl<T> Encode for Rc<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
T::encode(self, encoder)
}
}
#[cfg(feature = "atomic")]
impl<T> Decodable for Arc<T>
impl<T> Decode for Arc<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let t = T::decode(decoder)?;
Ok(Arc::new(t))
}
}
#[cfg(feature = "atomic")]
impl<T> Encodeable for Arc<T>
impl<T> Encode for Arc<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
T::encode(self, encoder)
}
}

View File

@ -1,7 +1,7 @@
use crate::{
config::{self, Config},
de::{read::Reader, BorrowDecodable, BorrowDecode, Decodable, Decode, Decoder},
enc::{write::Writer, Encode, Encodeable, Encoder},
de::{read::Reader, BorrowDecode, BorrowDecoder, Decode, Decoder, DecoderImpl},
enc::{write::Writer, Encode, Encoder, EncoderImpl},
error::{DecodeError, EncodeError},
};
use core::time::Duration;
@ -15,7 +15,7 @@ use std::{
/// Decode type `D` from the given reader. The reader can be any type that implements `std::io::Read`, e.g. `std::fs::File`.
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn decode_from<D: Decodable, R: std::io::Read>(src: &mut R) -> Result<D, DecodeError> {
pub fn decode_from<D: Decode, R: std::io::Read>(src: &mut R) -> Result<D, DecodeError> {
decode_from_with_config(src, config::Default)
}
@ -23,15 +23,15 @@ pub fn decode_from<D: Decodable, R: std::io::Read>(src: &mut R) -> Result<D, Dec
///
/// See the [config] module for more information about config options.
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn decode_from_with_config<D: Decodable, C: Config, R: std::io::Read>(
pub fn decode_from_with_config<D: Decode, C: Config, R: std::io::Read>(
src: &mut R,
_config: C,
) -> Result<D, DecodeError> {
let mut decoder = Decoder::<_, C>::new(src, _config);
let mut decoder = DecoderImpl::<_, C>::new(src, _config);
D::decode(&mut decoder)
}
impl<'storage, R: std::io::Read> Reader<'storage> for R {
impl<'storage, R: std::io::Read> Reader for R {
#[inline(always)]
fn read(&mut self, bytes: &mut [u8]) -> Result<(), DecodeError> {
match self.read_exact(bytes) {
@ -43,7 +43,7 @@ impl<'storage, R: std::io::Read> Reader<'storage> for R {
/// Encode the given value into any type that implements `std::io::Write`, e.g. `std::fs::File`.
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn encode_into_write<E: Encodeable, W: std::io::Write>(
pub fn encode_into_write<E: Encode, W: std::io::Write>(
val: E,
dst: &mut W,
) -> Result<usize, EncodeError> {
@ -52,7 +52,7 @@ pub fn encode_into_write<E: Encodeable, W: std::io::Write>(
/// Encode the given value into any type that implements `std::io::Write`, e.g. `std::fs::File`, with the given `Config`. See the [config] module for more information.
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub fn encode_into_write_with_config<E: Encodeable, C: Config, W: std::io::Write>(
pub fn encode_into_write_with_config<E: Encode, C: Config, W: std::io::Write>(
val: E,
dst: &mut W,
config: C,
@ -61,7 +61,7 @@ pub fn encode_into_write_with_config<E: Encodeable, C: Config, W: std::io::Write
writer: dst,
bytes_written: 0,
};
let mut encoder = Encoder::<_, C>::new(writer, config);
let mut encoder = EncoderImpl::<_, C>::new(writer, config);
val.encode(&mut encoder)?;
Ok(encoder.into_writer().bytes_written)
}
@ -84,27 +84,27 @@ impl<'storage, W: std::io::Write> Writer for IoWriter<'storage, W> {
}
}
impl<'a> Encodeable for &'a CStr {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl<'a> Encode for &'a CStr {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.to_bytes_with_nul().encode(encoder)
}
}
impl<'de> BorrowDecodable<'de> for &'de CStr {
fn borrow_decode<D: BorrowDecode<'de>>(decoder: D) -> Result<Self, DecodeError> {
impl<'de> BorrowDecode<'de> for &'de CStr {
fn borrow_decode<D: BorrowDecoder<'de>>(decoder: D) -> Result<Self, DecodeError> {
let bytes = <&[u8]>::borrow_decode(decoder)?;
CStr::from_bytes_with_nul(bytes).map_err(|e| DecodeError::CStrNulError { inner: e })
}
}
impl Encodeable for CString {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for CString {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.as_bytes_with_nul().encode(encoder)
}
}
impl Decodable for CString {
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
impl Decode for CString {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
// BlockedTODO: https://github.com/rust-lang/rust/issues/73179
// use `from_vec_with_nul` instead, combined with:
// let bytes = std::vec::Vec::<u8>::decode(decoder)?;
@ -117,11 +117,11 @@ impl Decodable for CString {
}
}
impl<T> Encodeable for Mutex<T>
impl<T> Encode for Mutex<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
let t = self.lock().map_err(|_| EncodeError::LockFailed {
type_name: core::any::type_name::<Mutex<T>>(),
})?;
@ -129,21 +129,21 @@ where
}
}
impl<T> Decodable for Mutex<T>
impl<T> Decode for Mutex<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let t = T::decode(decoder)?;
Ok(Mutex::new(t))
}
}
impl<T> Encodeable for RwLock<T>
impl<T> Encode for RwLock<T>
where
T: Encodeable,
T: Encode,
{
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
let t = self.read().map_err(|_| EncodeError::LockFailed {
type_name: core::any::type_name::<Mutex<T>>(),
})?;
@ -151,18 +151,18 @@ where
}
}
impl<T> Decodable for RwLock<T>
impl<T> Decode for RwLock<T>
where
T: Decodable,
T: Decode,
{
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let t = T::decode(decoder)?;
Ok(RwLock::new(t))
}
}
impl Encodeable for SystemTime {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for SystemTime {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
let duration = self.duration_since(SystemTime::UNIX_EPOCH).map_err(|e| {
EncodeError::InvalidSystemTime {
inner: e,
@ -173,15 +173,15 @@ impl Encodeable for SystemTime {
}
}
impl Decodable for SystemTime {
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
impl Decode for SystemTime {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let duration = Duration::decode(decoder)?;
Ok(SystemTime::UNIX_EPOCH + duration)
}
}
impl Encodeable for &'_ Path {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for &'_ Path {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
match self.to_str() {
Some(str) => str.encode(encoder),
None => Err(EncodeError::Other("Path contains invalid UTF-8 characters")),
@ -189,28 +189,28 @@ impl Encodeable for &'_ Path {
}
}
impl<'de> BorrowDecodable<'de> for &'de Path {
fn borrow_decode<D: BorrowDecode<'de>>(decoder: D) -> Result<Self, DecodeError> {
impl<'de> BorrowDecode<'de> for &'de Path {
fn borrow_decode<D: BorrowDecoder<'de>>(decoder: D) -> Result<Self, DecodeError> {
let str = <&'de str>::borrow_decode(decoder)?;
Ok(Path::new(str))
}
}
impl Encodeable for PathBuf {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for PathBuf {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.as_path().encode(encoder)
}
}
impl Decodable for PathBuf {
fn decode<D: Decode>(decoder: D) -> Result<Self, DecodeError> {
impl Decode for PathBuf {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let string = std::string::String::decode(decoder)?;
Ok(string.into())
}
}
impl Encodeable for IpAddr {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
impl Encode for IpAddr {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match self {
IpAddr::V4(v4) => {
0u32.encode(&mut encoder)?;
@ -224,8 +224,8 @@ impl Encodeable for IpAddr {
}
}
impl Decodable for IpAddr {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
impl Decode for IpAddr {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match u32::decode(&mut decoder)? {
0 => Ok(IpAddr::V4(Ipv4Addr::decode(decoder)?)),
1 => Ok(IpAddr::V6(Ipv6Addr::decode(decoder)?)),
@ -239,32 +239,32 @@ impl Decodable for IpAddr {
}
}
impl Encodeable for Ipv4Addr {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for Ipv4Addr {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.octets().encode(encoder)
}
}
impl Decodable for Ipv4Addr {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
Ok(Self::from(decoder.decode_array::<4>()?))
impl Decode for Ipv4Addr {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
Ok(Self::from(<[u8; 4]>::decode(decoder)?))
}
}
impl Encodeable for Ipv6Addr {
fn encode<E: Encode>(&self, encoder: E) -> Result<(), EncodeError> {
impl Encode for Ipv6Addr {
fn encode<E: Encoder>(&self, encoder: E) -> Result<(), EncodeError> {
self.octets().encode(encoder)
}
}
impl Decodable for Ipv6Addr {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
Ok(Self::from(decoder.decode_array::<16>()?))
impl Decode for Ipv6Addr {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
Ok(Self::from(<[u8; 16]>::decode(decoder)?))
}
}
impl Encodeable for SocketAddr {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
impl Encode for SocketAddr {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
match self {
SocketAddr::V4(v4) => {
0u32.encode(&mut encoder)?;
@ -278,8 +278,8 @@ impl Encodeable for SocketAddr {
}
}
impl Decodable for SocketAddr {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
impl Decode for SocketAddr {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
match u32::decode(&mut decoder)? {
0 => Ok(SocketAddr::V4(SocketAddrV4::decode(decoder)?)),
1 => Ok(SocketAddr::V6(SocketAddrV6::decode(decoder)?)),
@ -293,30 +293,30 @@ impl Decodable for SocketAddr {
}
}
impl Encodeable for SocketAddrV4 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
impl Encode for SocketAddrV4 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.ip().encode(&mut encoder)?;
self.port().encode(encoder)
}
}
impl Decodable for SocketAddrV4 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
impl Decode for SocketAddrV4 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let ip = Ipv4Addr::decode(&mut decoder)?;
let port = u16::decode(decoder)?;
Ok(Self::new(ip, port))
}
}
impl Encodeable for SocketAddrV6 {
fn encode<E: Encode>(&self, mut encoder: E) -> Result<(), EncodeError> {
impl Encode for SocketAddrV6 {
fn encode<E: Encoder>(&self, mut encoder: E) -> Result<(), EncodeError> {
self.ip().encode(&mut encoder)?;
self.port().encode(encoder)
}
}
impl Decodable for SocketAddrV6 {
fn decode<D: Decode>(mut decoder: D) -> Result<Self, DecodeError> {
impl Decode for SocketAddrV6 {
fn decode<D: Decoder>(mut decoder: D) -> Result<Self, DecodeError> {
let ip = Ipv6Addr::decode(&mut decoder)?;
let port = u16::decode(decoder)?;
Ok(Self::new(ip, port, 0, 0))

View File

@ -13,12 +13,12 @@
//!
//! # Features
//!
//! |Name |Default?|Supported types for Encodeable/Decodeable|Enabled methods |Other|
//! |Name |Default?|Supported types for Encode/Decode|Enabled methods |Other|
//! |------|--------|-----------------------------------------|-----------------------------------------------------------------|-----|
//! |std | Yes ||`decode_from[_with_config]` and `encode_into_write[_with_config]`|
//! |alloc | Yes |All common containers in alloc, like `Vec`, `String`, `Box`|`encode_to_vec[_with_config]`|
//! |atomic| Yes |All `Atomic*` integer types, e.g. `AtomicUsize`, and `AtomicBool`||
//! |derive| Yes |||Enables the `Encodeable` and `Decodeable` derive macro|
//! |derive| Yes |||Enables the `Encode` and `Decode` derive macro|
//! |serde | No ||`serde_decode_from[_with_config]`, `serde_encode_into[_with_config]`|Also enables `_to_vec` when `alloc` is enabled|
#![doc(html_root_url = "https://docs.rs/bincode/2.0.0-dev")]
@ -48,7 +48,7 @@ use config::Config;
/// Will take the [Default] configuration. See the [config] module for more information.
///
/// [Default]: config/struct.Default.html
pub fn encode_into_slice<E: enc::Encodeable>(
pub fn encode_into_slice<E: enc::Encode>(
val: E,
dst: &mut [u8],
) -> Result<usize, error::EncodeError> {
@ -58,13 +58,13 @@ pub fn encode_into_slice<E: enc::Encodeable>(
/// Encode the given value into the given slice. Returns the amount of bytes that have been written.
///
/// See the [config] module for more information on configurations.
pub fn encode_into_slice_with_config<E: enc::Encodeable, C: Config>(
pub fn encode_into_slice_with_config<E: enc::Encode, C: Config>(
val: E,
dst: &mut [u8],
config: C,
) -> Result<usize, error::EncodeError> {
let writer = enc::write::SliceWriter::new(dst);
let mut encoder = enc::Encoder::<_, C>::new(writer, config);
let mut encoder = enc::EncoderImpl::<_, C>::new(writer, config);
val.encode(&mut encoder)?;
Ok(encoder.into_writer().bytes_written())
}
@ -74,7 +74,7 @@ pub fn encode_into_slice_with_config<E: enc::Encodeable, C: Config>(
/// Will take the [Default] configuration. See the [config] module for more information.
///
/// [Default]: config/struct.Default.html
pub fn decode<'__de, D: de::BorrowDecodable<'__de>>(
pub fn decode<'__de, D: de::BorrowDecode<'__de>>(
src: &'__de [u8],
) -> Result<D, error::DecodeError> {
decode_with_config(src, config::Default)
@ -83,11 +83,11 @@ pub fn decode<'__de, D: de::BorrowDecodable<'__de>>(
/// Attempt to decode a given type `D` from the given slice.
///
/// See the [config] module for more information on configurations.
pub fn decode_with_config<'__de, D: de::BorrowDecodable<'__de>, C: Config>(
pub fn decode_with_config<'__de, D: de::BorrowDecode<'__de>, C: Config>(
src: &'__de [u8],
_config: C,
) -> Result<D, error::DecodeError> {
let reader = de::read::SliceReader::new(src);
let mut decoder = de::Decoder::<_, C>::new(reader, _config);
let mut decoder = de::DecoderImpl::<_, C>::new(reader, _config);
D::borrow_decode(&mut decoder)
}

View File

@ -1,9 +1,6 @@
use crate::{config::Endian, de::read::Reader, error::DecodeError};
pub fn varint_decode_i16<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<i16, DecodeError> {
pub fn varint_decode_i16<R: Reader>(read: &mut R, endian: Endian) -> Result<i16, DecodeError> {
let n = super::varint_decode_u16(read, endian)?;
Ok(if n % 2 == 0 {
// positive number
@ -19,10 +16,7 @@ pub fn varint_decode_i16<'a, R: Reader<'a>>(
})
}
pub fn varint_decode_i32<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<i32, DecodeError> {
pub fn varint_decode_i32<R: Reader>(read: &mut R, endian: Endian) -> Result<i32, DecodeError> {
let n = super::varint_decode_u32(read, endian)?;
Ok(if n % 2 == 0 {
// positive number
@ -38,10 +32,7 @@ pub fn varint_decode_i32<'a, R: Reader<'a>>(
})
}
pub fn varint_decode_i64<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<i64, DecodeError> {
pub fn varint_decode_i64<R: Reader>(read: &mut R, endian: Endian) -> Result<i64, DecodeError> {
let n = super::varint_decode_u64(read, endian)?;
Ok(if n % 2 == 0 {
// positive number
@ -57,10 +48,7 @@ pub fn varint_decode_i64<'a, R: Reader<'a>>(
})
}
pub fn varint_decode_i128<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<i128, DecodeError> {
pub fn varint_decode_i128<R: Reader>(read: &mut R, endian: Endian) -> Result<i128, DecodeError> {
let n = super::varint_decode_u128(read, endian)?;
Ok(if n % 2 == 0 {
// positive number
@ -76,9 +64,6 @@ pub fn varint_decode_i128<'a, R: Reader<'a>>(
})
}
pub fn varint_decode_isize<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<isize, DecodeError> {
pub fn varint_decode_isize<R: Reader>(read: &mut R, endian: Endian) -> Result<isize, DecodeError> {
varint_decode_i64(read, endian).map(|v| v as isize)
}

View File

@ -5,10 +5,7 @@ use crate::{
error::{DecodeError, IntegerType},
};
pub fn varint_decode_u16<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<u16, DecodeError> {
pub fn varint_decode_u16<R: Reader>(read: &mut R, endian: Endian) -> Result<u16, DecodeError> {
let mut byte = [0u8; 1];
read.read(&mut byte)?;
match byte[0] {
@ -36,10 +33,7 @@ pub fn varint_decode_u16<'a, R: Reader<'a>>(
}
}
pub fn varint_decode_u32<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<u32, DecodeError> {
pub fn varint_decode_u32<R: Reader>(read: &mut R, endian: Endian) -> Result<u32, DecodeError> {
let mut byte = [0u8; 1];
read.read(&mut byte)?;
match byte[0] {
@ -71,10 +65,7 @@ pub fn varint_decode_u32<'a, R: Reader<'a>>(
}
}
pub fn varint_decode_u64<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<u64, DecodeError> {
pub fn varint_decode_u64<R: Reader>(read: &mut R, endian: Endian) -> Result<u64, DecodeError> {
let mut byte = [0u8; 1];
read.read(&mut byte)?;
match byte[0] {
@ -110,10 +101,7 @@ pub fn varint_decode_u64<'a, R: Reader<'a>>(
}
}
pub fn varint_decode_usize<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<usize, DecodeError> {
pub fn varint_decode_usize<R: Reader>(read: &mut R, endian: Endian) -> Result<usize, DecodeError> {
let mut byte = [0u8; 1];
read.read(&mut byte)?;
match byte[0] {
@ -149,10 +137,7 @@ pub fn varint_decode_usize<'a, R: Reader<'a>>(
}
}
pub fn varint_decode_u128<'a, R: Reader<'a>>(
read: &mut R,
endian: Endian,
) -> Result<u128, DecodeError> {
pub fn varint_decode_u128<R: Reader>(read: &mut R, endian: Endian) -> Result<u128, DecodeError> {
let mut byte = [0u8; 1];
read.read(&mut byte)?;
match byte[0] {

View File

@ -15,8 +15,8 @@ struct Foo {
pub b: u32,
}
impl bincode::enc::Encodeable for Foo {
fn encode<E: bincode::enc::Encode>(
impl bincode::enc::Encode for Foo {
fn encode<E: bincode::enc::Encoder>(
&self,
mut encoder: E,
) -> Result<(), bincode::error::EncodeError> {
@ -26,11 +26,13 @@ impl bincode::enc::Encodeable for Foo {
}
}
impl bincode::de::Decodable for Foo {
fn decode<D: bincode::de::Decode>(mut decoder: D) -> Result<Self, bincode::error::DecodeError> {
impl bincode::de::Decode for Foo {
fn decode<D: bincode::de::Decoder>(
mut decoder: D,
) -> Result<Self, bincode::error::DecodeError> {
Ok(Self {
a: bincode::de::Decodable::decode(&mut decoder)?,
b: bincode::de::Decodable::decode(&mut decoder)?,
a: bincode::de::Decode::decode(&mut decoder)?,
b: bincode::de::Decode::decode(&mut decoder)?,
})
}
}

View File

@ -1,39 +1,39 @@
#![cfg(feature = "derive")]
use bincode::{de::Decodable, enc::Encodeable};
use bincode::{de::Decode, enc::Encode};
#[derive(bincode::Encodable, PartialEq, Debug)]
pub(crate) struct Test<T: Encodeable> {
#[derive(bincode::Encode, PartialEq, Debug)]
pub(crate) struct Test<T: Encode> {
a: T,
b: u32,
c: u8,
}
#[derive(bincode::Decodable, PartialEq, Debug, Eq)]
pub struct Test2<T: Decodable> {
#[derive(bincode::Decode, PartialEq, Debug, Eq)]
pub struct Test2<T: Decode> {
a: T,
b: u32,
c: u32,
}
#[derive(bincode::Decodable, PartialEq, Debug, Eq)]
#[derive(bincode::Decode, PartialEq, Debug, Eq)]
pub struct Test3<'a> {
a: &'a str,
b: u32,
c: u32,
}
#[derive(bincode::Encodable, bincode::Decodable, PartialEq, Debug, Eq)]
#[derive(bincode::Encode, bincode::Decode, PartialEq, Debug, Eq)]
pub struct TestTupleStruct(u32, u32, u32);
#[derive(bincode::Encodable, bincode::Decodable, PartialEq, Debug, Eq)]
#[derive(bincode::Encode, bincode::Decode, PartialEq, Debug, Eq)]
pub enum TestEnum {
Foo,
Bar { name: u32 },
Baz(u32, u32, u32),
}
#[derive(bincode::Encodable, bincode::Decodable, PartialEq, Debug, Eq)]
#[derive(bincode::Encode, bincode::Decode, PartialEq, Debug, Eq)]
pub enum TestEnum2<'a> {
Foo,
Bar { name: &'a str },
@ -41,7 +41,7 @@ pub enum TestEnum2<'a> {
}
#[test]
fn test_encodable() {
fn test_encode() {
let start = Test {
a: 5i32,
b: 10u32,
@ -55,7 +55,7 @@ fn test_encodable() {
#[cfg(feature = "std")]
#[test]
fn test_decodable() {
fn test_decode() {
let start = Test2 {
a: 5u32,
b: 10u32,
@ -67,7 +67,7 @@ fn test_decodable() {
}
#[test]
fn test_encodable_tuple() {
fn test_encode_tuple() {
let start = TestTupleStruct(5, 10, 1024);
let mut slice = [0u8; 1024];
let bytes_written = bincode::encode_into_slice(start, &mut slice).unwrap();
@ -76,7 +76,7 @@ fn test_encodable_tuple() {
}
#[test]
fn test_decodable_tuple() {
fn test_decode_tuple() {
let start = TestTupleStruct(5, 10, 1024);
let mut slice = [5, 10, 251, 0, 4];
let result: TestTupleStruct = bincode::decode(&mut slice).unwrap();
@ -84,7 +84,7 @@ fn test_decodable_tuple() {
}
#[test]
fn test_encodable_enum_struct_variant() {
fn test_encode_enum_struct_variant() {
let start = TestEnum::Bar { name: 5u32 };
let mut slice = [0u8; 1024];
let bytes_written = bincode::encode_into_slice(start, &mut slice).unwrap();
@ -93,7 +93,7 @@ fn test_encodable_enum_struct_variant() {
}
#[test]
fn test_decodable_enum_struct_variant() {
fn test_decode_enum_struct_variant() {
let start = TestEnum::Bar { name: 5u32 };
let mut slice = [1, 5];
let result: TestEnum = bincode::decode(&mut slice).unwrap();
@ -101,7 +101,7 @@ fn test_decodable_enum_struct_variant() {
}
#[test]
fn test_encodable_enum_tuple_variant() {
fn test_encode_enum_tuple_variant() {
let start = TestEnum::Baz(5, 10, 1024);
let mut slice = [0u8; 1024];
let bytes_written = bincode::encode_into_slice(start, &mut slice).unwrap();
@ -110,7 +110,7 @@ fn test_encodable_enum_tuple_variant() {
}
#[test]
fn test_decodable_enum_unit_variant() {
fn test_decode_enum_unit_variant() {
let start = TestEnum::Foo;
let mut slice = [0];
let result: TestEnum = bincode::decode(&mut slice).unwrap();
@ -118,7 +118,7 @@ fn test_decodable_enum_unit_variant() {
}
#[test]
fn test_encodable_enum_unit_variant() {
fn test_encode_enum_unit_variant() {
let start = TestEnum::Foo;
let mut slice = [0u8; 1024];
let bytes_written = bincode::encode_into_slice(start, &mut slice).unwrap();
@ -127,7 +127,7 @@ fn test_encodable_enum_unit_variant() {
}
#[test]
fn test_decodable_enum_tuple_variant() {
fn test_decode_enum_tuple_variant() {
let start = TestEnum::Baz(5, 10, 1024);
let mut slice = [2, 5, 10, 251, 0, 4];
let result: TestEnum = bincode::decode(&mut slice).unwrap();

View File

@ -2,7 +2,7 @@
use serde_derive::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, bincode::Encodable, bincode::Decodable)]
#[derive(Serialize, Deserialize, bincode::Encode, bincode::Decode)]
pub struct SerdeRoundtrip {
pub a: u32,
#[serde(skip)]

View File

@ -18,8 +18,8 @@ struct Foo {
pub b: u32,
}
impl bincode::enc::Encodeable for Foo {
fn encode<E: bincode::enc::Encode>(
impl bincode::enc::Encode for Foo {
fn encode<E: bincode::enc::Encoder>(
&self,
mut encoder: E,
) -> Result<(), bincode::error::EncodeError> {
@ -29,11 +29,13 @@ impl bincode::enc::Encodeable for Foo {
}
}
impl bincode::de::Decodable for Foo {
fn decode<D: bincode::de::Decode>(mut decoder: D) -> Result<Self, bincode::error::DecodeError> {
impl bincode::de::Decode for Foo {
fn decode<D: bincode::de::Decoder>(
mut decoder: D,
) -> Result<Self, bincode::error::DecodeError> {
Ok(Self {
a: bincode::de::Decodable::decode(&mut decoder)?,
b: bincode::de::Decodable::decode(&mut decoder)?,
a: bincode::de::Decode::decode(&mut decoder)?,
b: bincode::de::Decode::decode(&mut decoder)?,
})
}
}

View File

@ -3,7 +3,7 @@ use core::fmt::Debug;
fn the_same_with_config<V, C, CMP>(element: &V, config: C, cmp: CMP)
where
V: bincode::enc::Encodeable + bincode::de::Decodable + Debug + 'static,
V: bincode::enc::Encode + bincode::de::Decode + Debug + 'static,
C: Config,
CMP: Fn(&V, &V) -> bool,
{
@ -28,7 +28,7 @@ where
pub fn the_same_with_comparer<V, CMP>(element: V, cmp: CMP)
where
V: bincode::enc::Encodeable + bincode::de::Decodable + Debug + 'static,
V: bincode::enc::Encode + bincode::de::Decode + Debug + 'static,
CMP: Fn(&V, &V) -> bool,
{
// A matrix of each different config option possible
@ -101,7 +101,7 @@ where
#[allow(dead_code)] // This is not used in every test
pub fn the_same<V>(element: V)
where
V: bincode::enc::Encodeable + bincode::de::Decodable + PartialEq + Debug + 'static,
V: bincode::enc::Encode + bincode::de::Decode + PartialEq + Debug + 'static,
{
the_same_with_comparer(element, |a, b| a == b);
}