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

uint: optimize FromStr, make it no_std-compatible #468

Merged
merged 7 commits into from
Dec 9, 2020
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
4 changes: 2 additions & 2 deletions uint/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ byteorder = { version = "1.3.2", default-features = false }
crunchy = { version = "0.2.2", default-features = false }
qc = { package = "quickcheck", version = "0.9.0", optional = true }
rand = { version = "0.7.2", default-features = false, optional = true }
rustc-hex = { version = "2.0.1", default-features = false }
hex = { version = "0.4", default-features = false }
static_assertions = "1.0.0"
arbitrary = { version = "0.4", optional = true }

[features]
default = ["std"]
std = ["byteorder/std", "rustc-hex/std", "crunchy/std"]
std = ["byteorder/std", "crunchy/std", "hex/std"]
quickcheck = ["qc", "rand"]

[[example]]
Expand Down
11 changes: 11 additions & 0 deletions uint/benches/bigint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ criterion_group!(
u128_mul,
u128_div,
from_fixed_array,
from_str,
);
criterion_main!(bigint);

Expand Down Expand Up @@ -642,3 +643,13 @@ fn from_fixed_array(c: &mut Criterion) {
})
});
}

fn from_str(c: &mut Criterion) {
c.bench_function("from_str", move |b| {
b.iter(|| {
black_box(U512::from_str(black_box("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")).unwrap());
black_box(U512::from_str(black_box("0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")).unwrap());
black_box(U512::from_str(black_box("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")).unwrap());
})
});
}
2 changes: 1 addition & 1 deletion uint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub use byteorder;
pub use core as core_;

#[doc(hidden)]
pub use rustc_hex;
pub use hex;

#[cfg(feature = "quickcheck")]
#[doc(hidden)]
Expand Down
89 changes: 58 additions & 31 deletions uint/src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
//! implementations for even more speed, hidden behind the `x64_arithmetic`
//! feature flag.

use core::fmt;

/// Conversion from decimal string error
#[derive(Debug, PartialEq)]
pub enum FromDecStrErr {
Expand All @@ -38,9 +40,8 @@ pub enum FromDecStrErr {
InvalidLength,
}

#[cfg(feature = "std")]
impl std::fmt::Display for FromDecStrErr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl fmt::Display for FromDecStrErr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
Expand All @@ -55,6 +56,31 @@ impl std::fmt::Display for FromDecStrErr {
#[cfg(feature = "std")]
impl std::error::Error for FromDecStrErr {}

#[derive(Debug)]
pub struct FromHexError {
inner: hex::FromHexError,
}

impl fmt::Display for FromHexError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inner)
}
}

#[cfg(feature = "std")]
impl std::error::Error for FromHexError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.inner)
}
}

#[doc(hidden)]
impl From<hex::FromHexError> for FromHexError {
fn from(inner: hex::FromHexError) -> Self {
Self { inner }
}
}

#[macro_export]
#[doc(hidden)]
macro_rules! impl_map_from {
Expand Down Expand Up @@ -1550,31 +1576,34 @@ macro_rules! construct_uint {
}
}

$crate::impl_std_for_uint!($name, $n_words);
// `$n_words * 8` because macro expects bytes and
// uints use 64 bit (8 byte) words
$crate::impl_quickcheck_arbitrary_for_uint!($name, ($n_words * 8));
$crate::impl_arbitrary_for_uint!($name, ($n_words * 8));
}
}

#[cfg(feature = "std")]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_uint {
($name: ident, $n_words: tt) => {
impl $crate::core_::str::FromStr for $name {
type Err = $crate::rustc_hex::FromHexError;
type Err = $crate::FromHexError;

fn from_str(value: &str) -> $crate::core_::result::Result<$name, Self::Err> {
use $crate::rustc_hex::FromHex;
let bytes: Vec<u8> = match value.len() % 2 == 0 {
true => value.from_hex()?,
false => ("0".to_owned() + value).from_hex()?,
};
const BYTES_LEN: usize = $n_words * 8;
const MAX_ENCODED_LEN: usize = BYTES_LEN * 2;

let mut bytes = [0_u8; BYTES_LEN];

let encoded = value.as_bytes();

if $n_words * 8 < bytes.len() {
return Err(Self::Err::InvalidHexLength);
if encoded.len() > MAX_ENCODED_LEN {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find this code hard to read, it could maybe be possible to refactor to avoid repeating let out = &mut bytes[BYTES_LEN - encoded.len() / 2..]; and $crate::hex::decode_to_slice(encoded, out).map_err(Self::Err::from)?; twice.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure it's possible because owning buffers are of different types (value: &str vs s: [u8; MAX_ENCODED_LEN]), different lengths and borrowing is involved here.

return Err($crate::hex::FromHexError::InvalidStringLength.into());
}

if encoded.len() % 2 == 0 {
let out = &mut bytes[BYTES_LEN - encoded.len() / 2..];

$crate::hex::decode_to_slice(encoded, out).map_err(Self::Err::from)?;
} else {
// Prepend '0' by overlaying our value on a scratch buffer filled with '0' characters.
let mut s = [b'0'; MAX_ENCODED_LEN];
s[MAX_ENCODED_LEN - encoded.len()..].copy_from_slice(encoded);
let encoded = &s[MAX_ENCODED_LEN - encoded.len() - 1..];
niklasad1 marked this conversation as resolved.
Show resolved Hide resolved

let out = &mut bytes[BYTES_LEN - encoded.len() / 2..];

$crate::hex::decode_to_slice(encoded, out).map_err(Self::Err::from)?;
}

let bytes_ref: &[u8] = &bytes;
Expand All @@ -1587,14 +1616,12 @@ macro_rules! impl_std_for_uint {
s.parse().unwrap()
}
}
};
}

#[cfg(not(feature = "std"))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_uint {
($name: ident, $n_words: tt) => {};
// `$n_words * 8` because macro expects bytes and
// uints use 64 bit (8 byte) words
$crate::impl_quickcheck_arbitrary_for_uint!($name, ($n_words * 8));
$crate::impl_arbitrary_for_uint!($name, ($n_words * 8));
}
}

#[cfg(feature = "quickcheck")]
Expand Down
4 changes: 4 additions & 0 deletions uint/tests/uint_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ fn uint256_from() {
// test initializtion from string
let sa = U256::from_str("0a").unwrap();
assert_eq!(e, sa);
assert_eq!(U256([0, 0, 0, 0]), U256::from_str("").unwrap());
assert_eq!(U256([0x1, 0, 0, 0]), U256::from_str("1").unwrap());
assert_eq!(U256([0x101, 0, 0, 0]), U256::from_str("101").unwrap());
assert_eq!(U256([0x1010, 0, 0, 0]), U256::from_str("1010").unwrap());
assert_eq!(U256([0x12f0, 0, 0, 0]), U256::from_str("12f0").unwrap());
assert_eq!(U256([0x12f0, 0, 0, 0]), U256::from_str("0000000012f0").unwrap());
Expand All @@ -145,6 +148,7 @@ fn uint256_from() {

// This string contains more bits than what fits in a U256.
assert!(U256::from_str("000000000000000000000000000000000000000000000000000000000000000000").is_err());
assert!(U256::from_str("100000000000000000000000000000000000000000000000000000000000000000").is_err());
}

#[test]
Expand Down