Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Added unty dependency and added type checks #667

Merged
merged 4 commits into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 70 additions & 69 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,69 +1,70 @@
[workspace]
members = ["derive", "compatibility"]

[package]
name = "bincode"
version = "2.0.0-rc.3" # remember to update html_root_url and bincode_derive
authors = [
"Ty Overby <[email protected]>",
"Zoey Riordan <[email protected]>",
"Victor Koenders <[email protected]>",
]
exclude = ["logo.svg", "examples/*", ".gitignore", ".github/"]

publish = true

repository = "https://github.com/bincode-org/bincode"
documentation = "https://docs.rs/bincode"
readme = "./readme.md"
categories = ["encoding", "network-programming"]
keywords = ["binary", "encode", "decode", "serialize", "deserialize"]

license = "MIT"
description = "A binary serialization / deserialization strategy for transforming structs into bytes and vice versa!"

edition = "2021"

[features]
default = ["std", "derive"]
std = ["alloc", "serde?/std"]
alloc = ["serde?/alloc"]
derive = ["bincode_derive"]

[dependencies]
bincode_derive = { path = "derive", version = "2.0.0-rc.3", optional = true }
serde = { version = "1.0", default-features = false, optional = true }

# Used for tests
[dev-dependencies]
serde_derive = "1.0"
serde_json = { version = "1.0", default-features = false }
tempfile = "3.2"
criterion = "0.5"
rand = "0.8"
uuid = { version = "1.1", features = ["serde"] }
chrono = { version = "0.4", features = ["serde"] }
glam = { version = "0.24", features = ["serde"] }
bincode_1 = { version = "1.3", package = "bincode" }
serde = { version = "1.0", features = ["derive"] }

[[bench]]
name = "varint"
harness = false

[[bench]]
name = "inline"
harness = false

[[bench]]
name = "string"
harness = false

[profile.bench]
codegen-units = 1
debug = 1
lto = true

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[workspace]
members = ["derive", "compatibility"]

[package]
name = "bincode"
version = "2.0.0-rc.3" # remember to update html_root_url and bincode_derive
authors = [
"Ty Overby <[email protected]>",
"Zoey Riordan <[email protected]>",
"Victor Koenders <[email protected]>",
]
exclude = ["logo.svg", "examples/*", ".gitignore", ".github/"]

publish = true

repository = "https://github.com/bincode-org/bincode"
documentation = "https://docs.rs/bincode"
readme = "./readme.md"
categories = ["encoding", "network-programming"]
keywords = ["binary", "encode", "decode", "serialize", "deserialize"]

license = "MIT"
description = "A binary serialization / deserialization strategy for transforming structs into bytes and vice versa!"

edition = "2021"

[features]
default = ["std", "derive"]
std = ["alloc", "serde?/std"]
alloc = ["serde?/alloc"]
derive = ["bincode_derive"]

[dependencies]
bincode_derive = { path = "derive", version = "2.0.0-rc.3", optional = true }
serde = { version = "1.0", default-features = false, optional = true }
unty = "0.0.3"

# Used for tests
[dev-dependencies]
serde_derive = "1.0"
serde_json = { version = "1.0", default-features = false }
tempfile = "3.2"
criterion = "0.5"
rand = "0.8"
uuid = { version = "1.1", features = ["serde"] }
chrono = { version = "0.4", features = ["serde"] }
glam = { version = "0.24", features = ["serde"] }
bincode_1 = { version = "1.3", package = "bincode" }
serde = { version = "1.0", features = ["derive"] }

[[bench]]
name = "varint"
harness = false

[[bench]]
name = "inline"
harness = false

[[bench]]
name = "string"
harness = false

[profile.bench]
codegen-units = 1
debug = 1
lto = true

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
100 changes: 40 additions & 60 deletions src/de/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,65 +441,61 @@ impl<'a, 'de: 'a> BorrowDecode<'de> for &'a str {

impl<T, const N: usize> Decode for [T; N]
where
T: Decode + Sized,
T: Decode,
{
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
decoder.claim_bytes_read(core::mem::size_of::<[T; N]>())?;

// TODO: we can't limit `T: 'static` because that would break other things
// but we want to have this optimization
// This will be another contendor for specialization implementation
// if TypeId::of::<u8>() == TypeId::of::<T>() {
// let mut buf = [0u8; N];
// decoder.reader().read(&mut buf)?;
// let ptr = &mut buf as *mut _ as *mut [T; N];

// // Safety: we know that T is a u8, so it is perfectly safe to
// // translate an array of u8 into an array of T
// let res = unsafe { ptr.read() };
// Ok(res)
// }
let result = super::impl_core::collect_into_array(&mut (0..N).map(|_| {
// See the documentation on `unclaim_bytes_read` as to why we're doing this here
decoder.unclaim_bytes_read(core::mem::size_of::<T>());
T::decode(decoder)
}));
if unty::type_equal::<T, u8>() {
let mut buf = [0u8; N];
decoder.reader().read(&mut buf)?;
let ptr = &mut buf as *mut _ as *mut [T; N];

// result is only None if N does not match the values of `(0..N)`, which it always should
// So this unwrap should never occur
result.unwrap()
// Safety: we know that T is a u8, so it is perfectly safe to
VictorKoenders marked this conversation as resolved.
Show resolved Hide resolved
// translate an array of u8 into an array of T
let res = unsafe { ptr.read() };
Ok(res)
} else {
let result = super::impl_core::collect_into_array(&mut (0..N).map(|_| {
// See the documentation on `unclaim_bytes_read` as to why we're doing this here
decoder.unclaim_bytes_read(core::mem::size_of::<T>());
T::decode(decoder)
}));

// result is only None if N does not match the values of `(0..N)`, which it always should
// So this unwrap should never occur
result.unwrap()
}
}
}

impl<'de, T, const N: usize> BorrowDecode<'de> for [T; N]
where
T: BorrowDecode<'de> + Sized,
T: BorrowDecode<'de>,
{
fn borrow_decode<D: BorrowDecoder<'de>>(decoder: &mut D) -> Result<Self, DecodeError> {
decoder.claim_bytes_read(core::mem::size_of::<[T; N]>())?;

// TODO: we can't limit `T: 'static` because that would break other things
// but we want to have this optimization
// This will be another contendor for specialization implementation
// if TypeId::of::<u8>() == TypeId::of::<T>() {
// let mut buf = [0u8; N];
// decoder.reader().read(&mut buf)?;
// let ptr = &mut buf as *mut _ as *mut [T; N];
if unty::type_equal::<T, u8>() {
let mut buf = [0u8; N];
decoder.reader().read(&mut buf)?;
let ptr = &mut buf as *mut _ as *mut [T; N];

// // Safety: we know that T is a u8, so it is perfectly safe to
// // translate an array of u8 into an array of T
// let res = unsafe { ptr.read() };
// Ok(res)
// }
let result = super::impl_core::collect_into_array(&mut (0..N).map(|_| {
// See the documentation on `unclaim_bytes_read` as to why we're doing this here
decoder.unclaim_bytes_read(core::mem::size_of::<T>());
T::borrow_decode(decoder)
}));

// result is only None if N does not match the values of `(0..N)`, which it always should
// So this unwrap should never occur
result.unwrap()
// Safety: we know that T is a u8, so it is perfectly safe to
// translate an array of u8 into an array of T
let res = unsafe { ptr.read() };
Ok(res)
} else {
let result = super::impl_core::collect_into_array(&mut (0..N).map(|_| {
// See the documentation on `unclaim_bytes_read` as to why we're doing this here
decoder.unclaim_bytes_read(core::mem::size_of::<T>());
T::borrow_decode(decoder)
}));

// result is only None if N does not match the values of `(0..N)`, which it always should
// So this unwrap should never occur
result.unwrap()
}
}
}

Expand Down Expand Up @@ -547,22 +543,6 @@ where
}
}

// BlockedTODO: https://github.com/rust-lang/rust/issues/37653
//
// We'll want to implement BorrowDecode for both Option<&[u8]> and Option<&[T: Encode]>,
// but those implementations overlap because &'a [u8] also implements BorrowDecode
// impl<'a, 'de: 'a> BorrowDecode<'de> for Option<&'a [u8]> {
// fn borrow_decode<D: BorrowDecoder<'de>>(decoder: &mut D) -> Result<Self, DecodeError> {
// match super::decode_option_variant(decoder, core::any::type_name::<Option<&[u8]>>())? {
// Some(_) => {
// let val = BorrowDecode::borrow_decode(decoder)?;
// Ok(Some(val))
// }
// None => Ok(None),
// }
// }
// }

impl<T, U> Decode for Result<T, U>
where
T: Decode,
Expand Down
28 changes: 13 additions & 15 deletions src/enc/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,24 +280,15 @@ impl Encode for char {
}
}

// BlockedTODO: https://github.com/rust-lang/rust/issues/37653
//
// We'll want to implement encoding for both &[u8] and &[T: Encode],
// but those implementations overlap because u8 also implements Encode
// impl Encode for &'_ [u8] {
// fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
// encoder.writer().write(*self)
// }
// }

impl<T> Encode for [T]
where
T: Encode + 'static,
T: Encode,
{
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
super::encode_slice_len(encoder, self.len())?;

if core::any::TypeId::of::<T>() == core::any::TypeId::of::<u8>() {
if unty::type_equal::<T, u8>() {
// Safety: T = u8
let t: &[u8] = unsafe { core::mem::transmute(self) };
encoder.writer().write(t)?;
return Ok(());
Expand Down Expand Up @@ -355,10 +346,17 @@ where
T: Encode,
{
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
for item in self.iter() {
item.encode(encoder)?;
if unty::type_equal::<T, u8>() {
// Safety: this is &[u8; N]
let array_slice: &[u8] =
unsafe { core::slice::from_raw_parts(self.as_ptr().cast(), N) };
encoder.writer().write(array_slice)
} else {
for item in self.iter() {
item.encode(encoder)?;
}
Ok(())
}
Ok(())
}
}

Expand Down
Loading
Loading