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

Making std optional. #260

Closed
wants to merge 3 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
22 changes: 21 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 11 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ license = "MIT"
members = ["ruint-macro"]

[features]
default = []
default = ["std"]
bench = ["dep:criterion", "proptest", "rand"]
dyn = ["dep:smallvec"]
generic_const_exprs = []
postgres = ["dep:postgres-types", "dep:bytes"]
sqlx = ["dep:sqlx-core"]
# no_std requires nightly rust due to use of #![feature(error_in_core)] (issue #103765)
std = ["thiserror/std", "proptest?/std", "proptest?/alloc", "primitive-types?/std", "rlp?/std"]

[[bench]]
name = "criterion"
Expand All @@ -39,19 +41,23 @@ fastrlp = { version = "0.3.1", optional = true }
num-bigint = { version = "0.4.3", optional = true }
parity-scale-codec = { version = "3.2.1", optional = true, features = [ "max-encoded-len" ] }
postgres-types = { version = "0.2.3", optional = true }
primitive-types = { version = "<1", optional = true }
proptest = { version = "1.0", optional = true }
primitive-types = { version = "<1", default-features = false, optional = true }
proptest = { version = "1.0", default-features = false, optional = true }
pyo3 = { version = "0.18.3", optional = true }
quickcheck = { version = "1.0", optional = true }
rand = { version = "0.8.5", optional = true }
rlp = { version = "0.5.1", optional = true }
rlp = { version = "0.5.1", default-features = false, optional = true }
ruint-macro = { version = "1.0.2", path = "./ruint-macro" }
serde = { version = "1.0", optional = true }
smallvec = { version = "1.8.0", optional = true, features = [ "union" ] } # for UintDyn
# HACK: (BLOCKED) sqlx requires a runtime to be specified.
# <https://github.com/launchbadge/sqlx/issues/1627>
sqlx-core = { version = "0.6", optional = true, features = [ "runtime-tokio-native-tls" ] }
thiserror = "1.0"
# thiserror does not support no-std, the PR to support it is
# https://github.com/dtolnay/thiserror/pull/211, but I don't think it will be
# merged until https://github.com/rust-lang/rust/issues/103765 is stabilized.
# So, the forked thiserror with no-std support is being used instead.
thiserror = { version = "1.0", default-features = false, package = "thiserror-core" }
valuable = { version = "0.1.0", optional = true }
zeroize = { version = "1.5", optional = true }

Expand Down
1 change: 1 addition & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Support for `#![no_std]` builds with the new `std` feature.
- Support `bn-rs`, `serde` and `uint!` for `Bits`

### Fixed
Expand Down
23 changes: 21 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ it in the stable version. There are a few more subtle issues that make this
less ideal than it appears. It also looks like it may take some time before
these nightly features are stabilized.

Also, on nightly you may disable the `std` feature for `#![no_std]` support.
Nightly is required until the stabilization of `error_in_core` (Rust issue
[#103765][r103765]), moving the standard `Error` trait to `core`.

[r103765]: https://github.com/rust-lang/rust/issues/103765

## Examples

```rust
Expand Down Expand Up @@ -112,8 +118,21 @@ Note that since `B` is a valid hexadecimal digit there can be ambiguity. To less

## Feature flags

There is support for a number of crates. These are enabled by setting the identically
named feature flag.
The only feature enabled by default is `std`. Disabling it is only supported on
nightly, and removes the dependency on the `std` crate, allowing this crate to
be used on `#![no_std]` projects. Due to limited support for floating point
operations in `core` (see Rust issue [#50145][r50145]), without `std` the
following functionalities are disabled:
* module `log`
* module `pow`
* module `root`
* trait implementation `From<f32>`
* trait implementation `From<f64>`

[r50145]: https://github.com/rust-lang/rust/issues/50145

There is optional support for a number of crates. These are enabled by setting
the identically named feature flag.

* `unstable` Enable sem-ver unstable features.
* [`rand`](https://docs.rs/rand): Implements sampling from the [`Standard`](https://docs.rs/rand/latest/rand/distributions/struct.Standard.html) distribution, i.e. [`rng.gen()`](https://docs.rs/rand/latest/rand/trait.Rng.html#method.gen).
Expand Down
3 changes: 2 additions & 1 deletion src/algorithms/div/knuth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,12 @@ mod tests {
add::{cmp, sbb_n},
addmul,
};
use alloc::{vec, vec::Vec};
use core::cmp::Ordering;
use proptest::{
collection, num, proptest,
strategy::{Just, Strategy},
};
use std::cmp::Ordering;

// Basic test without exceptional paths
#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/algorithms/div/reciprocal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//! [new]: https://gmplib.org/list-archives/gmp-devel/2019-October/005590.html
#![allow(dead_code, clippy::cast_possible_truncation, clippy::cast_lossless)]

use std::num::Wrapping;
use core::num::Wrapping;

pub use self::{reciprocal_2_mg10 as reciprocal_2, reciprocal_mg10 as reciprocal};

Expand Down
1 change: 1 addition & 0 deletions src/algorithms/div/small.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ pub fn div_3x2_mg10(u21: u128, u0: u64, d: u128, v: u64) -> (u64, u128) {
mod tests {
use super::*;
use crate::algorithms::addmul;
use alloc::{format, vec};
use proptest::{
collection,
num::{u128, u64},
Expand Down
2 changes: 1 addition & 1 deletion src/algorithms/gcd/matrix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,12 +333,12 @@ impl Matrix {
mod tests {
use super::*;
use crate::{const_for, nlimbs};
use alloc::str::FromStr;
use core::{
cmp::{max, min},
mem::swap,
};
use proptest::{proptest, test_runner::Config};
use std::str::FromStr;

fn gcd(mut a: u128, mut b: u128) -> u128 {
while b != 0 {
Expand Down
2 changes: 1 addition & 1 deletion src/algorithms/gcd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ mod tests {

#[test]
fn test_gcd_one() {
use std::str::FromStr;
use alloc::str::FromStr;
const BITS: usize = 129;
const LIMBS: usize = nlimbs(BITS);
type U = Uint<BITS, LIMBS>;
Expand Down
1 change: 1 addition & 0 deletions src/algorithms/mul.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ pub fn submul_nx1(lhs: &mut [u64], a: &[u64], b: u64) -> u64 {
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use proptest::{collection, num::u64, proptest};

#[test]
Expand Down
1 change: 1 addition & 0 deletions src/algorithms/mul_redc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::addmul;
use alloc::vec;
use core::iter::zip;

/// See Handbook of Applied Cryptography, Algorithm 14.32, p. 601.
Expand Down
1 change: 1 addition & 0 deletions src/base_convert.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::Uint;
use alloc::vec::Vec;
use thiserror::Error;

/// Error for [`from_base_le`][Uint::from_base_le] and
Expand Down
2 changes: 1 addition & 1 deletion src/bit_arr.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::{ParseError, Uint};
use alloc::{borrow::Cow, vec::Vec};
use core::ops::{
BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index, Not, Shl, ShlAssign,
Shr, ShrAssign,
};
use derive_more::{From, FromStr, Into};
use std::borrow::Cow;

/// A newtype wrapper around [`Uint`] that restricts operations to those
/// relevant for bit arrays.
Expand Down
2 changes: 1 addition & 1 deletion src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use crate::{
utils::{trim_end_slice, trim_end_vec},
Uint,
};
use alloc::{borrow::Cow, vec::Vec};
use core::{
mem::size_of_val,
ptr::{addr_of, addr_of_mut},
slice,
};
use std::borrow::Cow;

// OPT: *_to_smallvec to avoid allocation.

Expand Down
1 change: 1 addition & 0 deletions src/div.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ impl_bin_op!(Rem, rem, RemAssign, rem_assign, wrapping_rem);
pub mod tests {
use super::*;
use crate::{const_for, nlimbs};
use alloc::format;
use proptest::{prop_assume, proptest};

#[test]
Expand Down
6 changes: 6 additions & 0 deletions src/from.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,7 @@ impl_from_signed_int!(i64, u64);
impl_from_signed_int!(i128, u128);
impl_from_signed_int!(isize, usize);

#[cfg(feature = "std")]
impl<const BITS: usize, const LIMBS: usize> TryFrom<f64> for Uint<BITS, LIMBS> {
type Error = ToUintError<Self>;

Expand Down Expand Up @@ -483,6 +484,7 @@ impl<const BITS: usize, const LIMBS: usize> TryFrom<f64> for Uint<BITS, LIMBS> {
}
}

#[cfg(feature = "std")]
impl<const BITS: usize, const LIMBS: usize> TryFrom<f32> for Uint<BITS, LIMBS> {
type Error = ToUintError<Self>;

Expand Down Expand Up @@ -601,12 +603,14 @@ impl<const BITS: usize, const LIMBS: usize> TryFrom<&Uint<BITS, LIMBS>> for u128
// Convert Uint to floating point
//

#[cfg(feature = "std")]
impl<const BITS: usize, const LIMBS: usize> From<Uint<BITS, LIMBS>> for f32 {
fn from(value: Uint<BITS, LIMBS>) -> Self {
Self::from(&value)
}
}

#[cfg(feature = "std")]
impl<const BITS: usize, const LIMBS: usize> From<&Uint<BITS, LIMBS>> for f32 {
/// Approximate single precision float.
///
Expand All @@ -618,12 +622,14 @@ impl<const BITS: usize, const LIMBS: usize> From<&Uint<BITS, LIMBS>> for f32 {
}
}

#[cfg(feature = "std")]
impl<const BITS: usize, const LIMBS: usize> From<Uint<BITS, LIMBS>> for f64 {
fn from(value: Uint<BITS, LIMBS>) -> Self {
Self::from(&value)
}
}

#[cfg(feature = "std")]
impl<const BITS: usize, const LIMBS: usize> From<&Uint<BITS, LIMBS>> for f64 {
/// Approximate double precision float.
///
Expand Down
14 changes: 11 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![cfg_attr(not(feature = "std"), no_std, feature(error_in_core))]
#![doc = include_str!("../Readme.md")]
#![doc(issue_tracker_base_url = "https://github.com/recmo/uint/issues/")]
#![warn(clippy::all, clippy::pedantic, clippy::cargo, clippy::nursery)]
Expand Down Expand Up @@ -26,6 +27,8 @@
// Nightly only feature flag to enable the `unlikely` compiler hint.
#![cfg_attr(has_core_intrinsics, feature(core_intrinsics))]

extern crate alloc;

// Workaround for proc-macro `uint!` in this crate.
// See <https://github.com/rust-lang/rust/pull/55275>
extern crate self as ruint;
Expand All @@ -42,16 +45,21 @@ mod const_for;
mod div;
mod from;
mod gcd;
mod log;
mod modular;
mod mul;
mod pow;
mod root;
mod special;
mod string;
mod support;
mod uint_dyn;
mod utils;
// The following math operations are disable due to lack of some floating point
// functions in core. See issue https://github.com/rust-lang/rust/issues/50145
#[cfg(feature = "std")]
mod log;
#[cfg(feature = "std")]
mod pow;
#[cfg(feature = "std")]
mod root;

#[cfg(all(feature = "dyn", feature = "unstable"))]
#[doc(inline)]
Expand Down
3 changes: 2 additions & 1 deletion src/modular.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{algorithms, nlimbs, Uint};
use alloc::vec;

// FEATURE: sub_mod, neg_mod, inv_mod, div_mod, root_mod
// See <https://en.wikipedia.org/wiki/Cipolla's_algorithm>
Expand Down Expand Up @@ -169,6 +170,7 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
mod tests {
use super::*;
use crate::{aliases::U64, const_for, nlimbs};
use alloc::format;
use core::cmp::min;
use proptest::{prop_assume, proptest, test_runner::Config};

Expand Down Expand Up @@ -289,7 +291,6 @@ mod tests {
// TODO: Test for larger (>= m) values of a, b.

let expected = a.mul_mod(b, m).mul_mod(r, m);

assert_eq!(ar.mul_redc(br, m, inv), expected);
}
});
Expand Down
2 changes: 1 addition & 1 deletion src/pow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,8 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
mod tests {
use super::*;
use crate::{const_for, nlimbs};
use core::iter::repeat;
use proptest::proptest;
use std::iter::repeat;

#[test]
fn test_pow2_shl() {
Expand Down
7 changes: 4 additions & 3 deletions src/string.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::{base_convert::BaseConvertError, utils::rem_up, Uint};
use core::fmt::{
Binary, Debug, Display, Formatter, LowerHex, Octal, Result as FmtResult, UpperHex,
use core::{
fmt::{Binary, Debug, Display, Formatter, LowerHex, Octal, Result as FmtResult, UpperHex},
str::FromStr,
};
use std::str::FromStr;
use thiserror::Error;

// FEATURE: Respect width parameter in formatters.
Expand Down Expand Up @@ -186,6 +186,7 @@ impl<const BITS: usize, const LIMBS: usize> FromStr for Uint<BITS, LIMBS> {
#[cfg(test)]
mod tests {
use super::*;
use alloc::{format, string::ToString};
use proptest::proptest;

#[allow(clippy::unreadable_literal)]
Expand Down
3 changes: 2 additions & 1 deletion src/support/arbitrary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ impl<'a, const BITS: usize, const LIMBS: usize> Arbitrary<'a> for Uint<BITS, LIM
mod tests {
use super::*;
use crate::{const_for, nlimbs};
use std::iter::repeat;
use alloc::vec::Vec;
use core::iter::repeat;

#[test]
fn test_arbitrary() {
Expand Down
2 changes: 1 addition & 1 deletion src/support/rlp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
#![cfg_attr(has_doc_cfg, doc(cfg(feature = "rlp")))]

use crate::{Bits, Uint};
use core::cmp::Ordering;
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
use std::cmp::Ordering;

/// Allows a [`Uint`] to be serialized as RLP.
///
Expand Down
2 changes: 2 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use alloc::vec::Vec;

/// Like `a % b` but returns `b` instead of `0`.
#[must_use]
pub const fn rem_up(a: usize, b: usize) -> usize {
Expand Down