10000 Feat: Borsh deser using unsafe by prestwich · Pull Request #417 · recmo/uint · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Feat: Borsh deser using unsafe #417

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

Closed
wants to merge 12 commits into from
Closed
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- Support for borsh @ 1.5 ([#416])

## [1.12.4] - 2024-12-16

### Added
Expand Down
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ diesel = { version = "2.2", optional = true }
# sqlx
sqlx-core = { version = "0.8.2", optional = true }

# borsh
borsh = { version = "1.5", optional = true, default-features = false }
hex = "0.4"

[dev-dependencies]
ruint = { path = ".", features = ["arbitrary", "proptest"] }

Expand All @@ -108,6 +112,9 @@ postgres = "0.19"
proptest = "=1.5"
serde_json = "1.0"

# borsh
borsh = { version = "1.5", features = ["derive"] }

[features]
default = ["std"]
std = [
Expand Down Expand Up @@ -149,6 +156,7 @@ arbitrary = ["dep:arbitrary", "std"]
ark-ff = ["dep:ark-ff-03"]
ark-ff-04 = ["dep:ark-ff-04"]
bn-rs = ["dep:bn-rs", "std"]
borsh = ["alloc", "dep:borsh"]
bytemuck = ["dep:bytemuck"]
der = ["dep:der", "alloc"] # TODO: also have alloc free der impls.
diesel = ["dep:diesel", "std", "dep:thiserror"]
Expand Down
2 changes: 2 additions & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
"adcs",
"archs",
"BYTEA",
"borsh",
"clippy",
"codecov",
"conv",
"cpython",
"cset",
"divq",
"divrem",
"docsrs",
"Encodable",
"fastrlp",
"freethreaded",
Expand Down
127 changes: 127 additions & 0 deletions src/support/borsh.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
//! Support for the [`borsh`](https://crates.io/crates/borsh) crate.

#![cfg(feature = "borsh")]
#![cfg_attr(docsrs, doc(cfg(feature = "borsh")))]

use crate::{Bits, Uint};
use borsh::{io, BorshDeserialize, BorshSerialize};

impl<const BITS: usize, const LIMBS: usize> BorshDeserialize for Uint<BITS, LIMBS> {
#[inline]
fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
// This is a bit of an end-run around missing `generic_const_exprs`
// We cannot declare a `[u8; Self::BYTES]` or `[u8; LIMBS * 8]`,
// so we declare a `[u8; LIMBS]` and use unsafe to write to it.

// TODO: Replace the unsafety with `generic_const_exprs` when
// available
let mut limbs = [0u64; LIMBS];

// SAFETY: `limbs` is known to have identical memory layout and
// alignment to `[u8; LIMBS * 8]`, which is guaranteed to safely
// contain [u8; Self::BYTES]`, as `LIMBS * 8 >= Self::BYTES`.
// Reference:
// https://doc.rust-lang.org/reference/type-layout.html#array-layout
let target = unsafe {
core::slice::from_raw_parts_mut(limbs.as_mut_ptr().cast::<u8>(), Self::BYTES)
};
reader.read_exact(target)?;

// Using `Self::from_limbs(limbs)` would be incorrect here, as the
// inner u64s are encoded in LE, and the platform may be BE.
Self::try_from_le_slice(target).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
"value is too large for the type",
)
})
}
}

impl<const BITS: usize, const LIMBS: usize> BorshSerialize for Uint<BITS, LIMBS> {
#[inline]
fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
// TODO: non-allocating and remove the `alloc` feature requirement
let bytes = self.as_le_bytes_trimmed();
writer.write_all(&bytes)
}
}

impl<const BITS: usize, const LIMBS: usize> BorshDeserialize for Bits<BITS, LIMBS> {
#[inline]
fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
Uint::<BITS, LIMBS>::deserialize_reader(reader).map(Into::into)
}
}

impl<const BITS: usize, const LIMBS: usize> BorshSerialize for Bits<BITS, LIMBS> {
#[inline]
fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
self.as_uint().serialize(writer)
}
}
#[cfg(test)]
mod test {
use super::*;

#[derive(Debug, BorshDeserialize, BorshSerialize, PartialEq, Eq)]
struct Something {
is_it: bool,
value: Uint<256, 4>,
}

#[test]
fn test_uint() {
let something = Something {
is_it: true,
value: Uint::<256, 4>::from_limbs([1, 2, 3, 4]),
};
let mut buf = [0; 33];

something.serialize(&mut buf.as_mut_slice()).unwrap();
assert_eq!(buf, [
1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0
]);
assert_eq!(&something.value.to_le_bytes::<32>(), &buf[1..]);
assert_eq!(Something::try_from_slice(&mut &buf[..]).unwrap(), something);
}

#[derive(Debug, BorshDeserialize, BorshSerialize, PartialEq, Eq)]
struct AnotherThing {
is_it: bool,
value: Bits<256, 4>,
}

#[test]
fn test_bits() {
let another_thing = AnotherThing {
is_it: true,
value: Bits::<256, 4>::from_limbs([1, 2, 3, 4]),
};
let mut buf = [0; 33];

another_thing.serialize(&mut buf.as_mut_slice()).unwrap();

assert_eq!(buf, [
1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0
]);
assert_eq!(&another_thing.value.to_le_bytes::<32>(), &buf[1..]);
assert_eq!(
AnotherThing::try_from_slice(&mut &buf[..]).unwrap(),
another_thing
);
}

#[test]
fn deser_invalid_value() {
let buf = [0xff; 4];
let mut reader = &mut &buf[..];

let result = Uint::<31, 1>::deserialize_reader(&mut reader);
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert_eq!(err.to_string(), "value is too large for the type");
}
}
6D4E 1 change: 1 addition & 0 deletions src/support/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod arbitrary;
mod ark_ff;
mod ark_ff_04;
mod bn_rs;
mod borsh;
mod bytemuck;
mod der;
pub mod diesel;
Expand Down
Loading
0