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

implement Packable for usize, isize, Vec<T>, Box<[T]> and String #17

Merged
merged 5 commits into from
Feb 8, 2022
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
1 change: 1 addition & 0 deletions packable/packable/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Derive `Error` for all the error types if the `std` feature is enabled;
- Implement `Packable` for `f32` and `f64`;
- Implement `Packable` for `usize`, `isize`, `Vec<T>`, `Box<[T]>` and `String` under the `usize` feature;

## 0.1.0 - 2022-01-13

Expand Down
1 change: 1 addition & 0 deletions packable/packable/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ homepage = "https://www.iota.org"
[features]
io = [ "std" ]
std = [ ]
usize = [ ]

[build-dependencies]
autocfg = { version = "1.0.1", default-features = false }
Expand Down
38 changes: 38 additions & 0 deletions packable/packable/src/packable/box.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,41 @@ impl<T: Packable> Packable for Box<T> {
Ok(Box::new(T::unpack::<_, VERIFY>(unpacker)?))
}
}

#[cfg(feature = "usize")]
impl<T: Packable> Packable for Box<[T]> {
type UnpackError =
crate::prefix::UnpackPrefixError<T::UnpackError, <usize as Packable>::UnpackError>;

#[inline(always)]
fn pack<P: Packer>(&self, packer: &mut P) -> Result<(), P::Error> {
// This cast is fine because we know `usize` is not larger than `64` bits.
(self.len() as u64).pack(packer)?;

for item in self.iter() {
item.pack(packer)?;
}

Ok(())
}

fn unpack<U: Unpacker, const VERIFY: bool>(
unpacker: &mut U,
) -> Result<Self, UnpackError<Self::UnpackError, U::Error>> {
use crate::error::UnpackErrorExt;

let len = u64::unpack::<_, VERIFY>(unpacker)
.infallible()?
.try_into()
.map_err(|err| UnpackError::Packable(Self::UnpackError::Prefix(err)))?;

let mut vec = alloc::vec::Vec::with_capacity(len);

for _ in 0..len {
let item = T::unpack::<_, VERIFY>(unpacker).coerce()?;
vec.push(item);
}

Ok(vec.into_boxed_slice())
}
}
4 changes: 4 additions & 0 deletions packable/packable/src/packable/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ mod r#box;
mod num;
#[cfg(feature = "primitive-types")]
mod primitive_types;
#[cfg(feature = "usize")]
mod string;
#[cfg(feature = "usize")]
mod vec;

use crate::{
error::{UnexpectedEOF, UnpackError},
Expand Down
41 changes: 41 additions & 0 deletions packable/packable/src/packable/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,46 @@ impl_packable_for_num!(i32);
impl_packable_for_num!(i64);
#[cfg(has_i128)]
impl_packable_for_num!(i128);

impl_packable_for_num!(f32);
impl_packable_for_num!(f64);

#[cfg(feature = "usize")]
impl Packable for usize {
type UnpackError = core::num::TryFromIntError;

fn pack<P: Packer>(&self, packer: &mut P) -> Result<(), P::Error> {
const _: () = {
if core::mem::size_of::<usize>() > core::mem::size_of::<u64>() {
panic!("The \"usize\" feature cannot be used for targets with a pointer size larger than 64 bits.");
}
};

(*self as u64).pack(packer)
}

fn unpack<U: Unpacker, const VERIFY: bool>(
unpacker: &mut U,
) -> Result<Self, UnpackError<Self::UnpackError, U::Error>> {
use crate::error::UnpackErrorExt;
Self::try_from(u64::unpack::<_, VERIFY>(unpacker).infallible()?)
.map_err(UnpackError::Packable)
}
}

#[cfg(feature = "usize")]
impl Packable for isize {
type UnpackError = core::num::TryFromIntError;

fn pack<P: Packer>(&self, packer: &mut P) -> Result<(), P::Error> {
(*self as i64).pack(packer)
}

fn unpack<U: Unpacker, const VERIFY: bool>(
unpacker: &mut U,
) -> Result<Self, UnpackError<Self::UnpackError, U::Error>> {
use crate::error::UnpackErrorExt;
Self::try_from(i64::unpack::<_, VERIFY>(unpacker).infallible()?)
.map_err(UnpackError::Packable)
}
}
42 changes: 42 additions & 0 deletions packable/packable/src/packable/string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2021-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

extern crate alloc;

use crate::{
error::{UnpackError, UnpackErrorExt},
packer::Packer,
prefix::UnpackPrefixError,
unpacker::Unpacker,
Packable,
};

use alloc::{
string::{FromUtf8Error, String},
vec::Vec,
};

impl Packable for String {
type UnpackError = UnpackPrefixError<FromUtf8Error, <usize as Packable>::UnpackError>;

fn pack<P: Packer>(&self, packer: &mut P) -> Result<(), P::Error> {
let bytes = self.as_bytes();
// This cast is fine because we know `usize` is not larger than `64` bits.
(bytes.len() as u64).pack(packer)?;

for item in bytes.iter() {
item.pack(packer)?;
}

Ok(())
}

fn unpack<U: Unpacker, const VERIFY: bool>(
unpacker: &mut U,
) -> Result<Self, UnpackError<Self::UnpackError, U::Error>> {
let bytes = Vec::<u8>::unpack::<_, VERIFY>(unpacker)
.map_packable_err(|err| UnpackPrefixError::Prefix(err.into_prefix()))?;

String::from_utf8(bytes).map_err(UnpackError::from_packable)
}
}
50 changes: 50 additions & 0 deletions packable/packable/src/packable/vec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright 2021-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

extern crate alloc;

use crate::{
error::{UnpackError, UnpackErrorExt},
packer::Packer,
prefix::UnpackPrefixError,
unpacker::Unpacker,
Packable,
};

use alloc::vec::Vec;

impl<T> Packable for Vec<T>
where
T: Packable,
{
type UnpackError = UnpackPrefixError<T::UnpackError, <usize as Packable>::UnpackError>;

fn pack<P: Packer>(&self, packer: &mut P) -> Result<(), P::Error> {
// This cast is fine because we know `usize` is not larger than `64` bits.
(self.len() as u64).pack(packer)?;

for item in self.iter() {
item.pack(packer)?;
}

Ok(())
}

fn unpack<U: Unpacker, const VERIFY: bool>(
unpacker: &mut U,
) -> Result<Self, UnpackError<Self::UnpackError, U::Error>> {
let len = u64::unpack::<_, VERIFY>(unpacker)
.infallible()?
.try_into()
.map_err(|err| UnpackError::Packable(UnpackPrefixError::Prefix(err)))?;

let mut vec = Vec::with_capacity(len);

for _ in 0..len {
let item = T::unpack::<_, VERIFY>(unpacker).coerce()?;
vec.push(item);
}

Ok(vec)
}
}
16 changes: 16 additions & 0 deletions packable/packable/tests/boxed_slice.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright 2021-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

mod common;

#[test]
fn packable_boxed_slice() {
assert_eq!(
common::generic_test(&vec![Some(0u32), None].into_boxed_slice())
.0
.len(),
core::mem::size_of::<u64>()
+ (core::mem::size_of::<u8>() + core::mem::size_of::<u32>())
+ core::mem::size_of::<u8>()
);
}
4 changes: 4 additions & 0 deletions packable/packable/tests/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ impl_packable_test_for_num!(packable_i32, i32, 0x6F7BD423);
impl_packable_test_for_num!(packable_u32, u32, 0x6F7BD423);
impl_packable_test_for_num!(packable_i64, i64, 0x6F7BD423100423DB);
impl_packable_test_for_num!(packable_u64, u64, 0x6F7BD423100423DB);
#[cfg(feature = "usize")]
impl_packable_test_for_num!(packable_isize, isize, 0x6F7BD423);
#[cfg(feature = "usize")]
impl_packable_test_for_num!(packable_usize, usize, 0x6F7BD423);
#[cfg(has_i128)]
impl_packable_test_for_num!(packable_i128, i128, 0x6F7BD423100423DBFF127B91CA0AB123);
#[cfg(has_u128)]
Expand Down
12 changes: 12 additions & 0 deletions packable/packable/tests/string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright 2021-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

mod common;

#[test]
fn packable_string() {
assert_eq!(
common::generic_test(&"yellow submarine".to_owned()).0.len(),
core::mem::size_of::<u64>() + 16 * core::mem::size_of::<u8>()
);
}
14 changes: 14 additions & 0 deletions packable/packable/tests/vec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright 2021-2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

mod common;

#[test]
fn packable_vec() {
assert_eq!(
common::generic_test(&vec![Some(0u32), None]).0.len(),
core::mem::size_of::<u64>()
+ (core::mem::size_of::<u8>() + core::mem::size_of::<u32>())
+ core::mem::size_of::<u8>()
);
}