Skip to content

Commit

Permalink
Clean up no_std usage
Browse files Browse the repository at this point in the history
Previously the crate used negative reasoning to enable `std` which was
hard to understand, required the `prelude` module and wasn't really
needed because it's only needed when a crate wants to add `alloc`
feature-backwards compatibly and this crate always had the feature.

This cleans up usage to unconditionally use `#[no_std]` and then just
add `extern crate` on top as needed by activated features.
  • Loading branch information
Kixunil committed Jan 27, 2024
1 parent fce03ce commit 4565fa3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 28 deletions.
37 changes: 22 additions & 15 deletions units/src/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use internals::error::InputString;
use internals::write_err;

#[cfg(feature = "alloc")]
use crate::prelude::{String, ToString};
use alloc::string::{String, ToString};

/// A set of denominations in which amounts can be expressed.
///
Expand Down Expand Up @@ -1788,6 +1788,7 @@ mod verification {
#[cfg(test)]
mod tests {
use core::str::FromStr;

#[cfg(feature = "std")]
use std::panic;

Expand All @@ -1797,8 +1798,9 @@ mod tests {
use super::*;

#[test]
#[cfg(feature = "alloc")]
fn from_str_zero() {
let denoms = vec!["BTC", "mBTC", "uBTC", "nBTC", "pBTC", "bits", "sats", "msats"];
let denoms = ["BTC", "mBTC", "uBTC", "nBTC", "pBTC", "bits", "sats", "msats"];
for denom in denoms {
for v in &["0", "000"] {
let s = format!("{} {}", v, denom);
Expand Down Expand Up @@ -1935,7 +1937,9 @@ mod tests {
assert_eq!(p("-1.0x", btc), Err(E::InvalidCharacter('x')));
assert_eq!(p("0.0 ", btc), Err(ParseAmountError::InvalidCharacter(' ')));
assert_eq!(p("0.000.000", btc), Err(E::InvalidFormat));
#[cfg(feature = "alloc")]
let more_than_max = format!("1{}", Amount::MAX);
#[cfg(feature = "alloc")]
assert_eq!(p(&more_than_max, btc), Err(OutOfRangeError::too_big(false).into()));
assert_eq!(p("0.000000042", btc), Err(E::TooPrecise));
assert_eq!(p("999.0000000", msat), Err(E::TooPrecise));
Expand Down Expand Up @@ -2028,6 +2032,7 @@ mod tests {
($denom:ident; $($test_name:ident, $val:literal, $format_string:literal, $expected:literal);* $(;)?) => {
$(
#[test]
#[cfg(feature = "alloc")]
fn $test_name() {
assert_eq!(format!($format_string, Amount::from_sat($val).display_in(Denomination::$denom)), $expected);
assert_eq!(format!($format_string, SignedAmount::from_sat($val as i64).display_in(Denomination::$denom)), $expected);
Expand All @@ -2040,6 +2045,7 @@ mod tests {
($denom:ident, $denom_suffix:literal; $($test_name:ident, $val:literal, $format_string:literal, $expected:literal);* $(;)?) => {
$(
#[test]
#[cfg(feature = "alloc")]
fn $test_name() {
assert_eq!(format!($format_string, Amount::from_sat($val).display_in(Denomination::$denom).show_denomination()), concat!($expected, $denom_suffix));
assert_eq!(format!($format_string, SignedAmount::from_sat($val as i64).display_in(Denomination::$denom).show_denomination()), concat!($expected, $denom_suffix));
Expand Down Expand Up @@ -2273,6 +2279,7 @@ mod tests {
ok_scase("-5 satoshi", SignedAmount::from_sat(-5));
ok_case("0.10000000 BTC", Amount::from_sat(100_000_00));
ok_scase("-100 bits", SignedAmount::from_sat(-10_000));
#[cfg(feature = "alloc")]
ok_scase(&format!("{} SAT", i64::MIN), SignedAmount::from_sat(i64::MIN));
}

Expand Down Expand Up @@ -2448,7 +2455,7 @@ mod tests {
serde_json::from_str("{\"amt\": 1000000.000000001, \"samt\": 1}");
assert!(t.unwrap_err().to_string().contains(&ParseAmountError::TooPrecise.to_string()));
let t: Result<T, serde_json::Error> = serde_json::from_str("{\"amt\": -1, \"samt\": 1}");
assert!(dbg!(t.unwrap_err().to_string()).contains(&OutOfRangeError::negative().to_string()));
assert!(t.unwrap_err().to_string().contains(&OutOfRangeError::negative().to_string()));
}

#[cfg(feature = "serde")]
Expand Down Expand Up @@ -2537,14 +2544,14 @@ mod tests {

#[test]
fn sum_amounts() {
assert_eq!(Amount::from_sat(0), vec![].into_iter().sum::<Amount>());
assert_eq!(SignedAmount::from_sat(0), vec![].into_iter().sum::<SignedAmount>());
assert_eq!(Amount::from_sat(0), [].into_iter().sum::<Amount>());
assert_eq!(SignedAmount::from_sat(0), [].into_iter().sum::<SignedAmount>());

let amounts = vec![Amount::from_sat(42), Amount::from_sat(1337), Amount::from_sat(21)];
let amounts = [Amount::from_sat(42), Amount::from_sat(1337), Amount::from_sat(21)];
let sum = amounts.into_iter().sum::<Amount>();
assert_eq!(Amount::from_sat(1400), sum);

let amounts = vec![
let amounts = [
SignedAmount::from_sat(-42),
SignedAmount::from_sat(1337),
SignedAmount::from_sat(21),
Expand All @@ -2555,35 +2562,35 @@ mod tests {

#[test]
fn checked_sum_amounts() {
assert_eq!(Some(Amount::from_sat(0)), vec![].into_iter().checked_sum());
assert_eq!(Some(SignedAmount::from_sat(0)), vec![].into_iter().checked_sum());
assert_eq!(Some(Amount::from_sat(0)), [].into_iter().checked_sum());
assert_eq!(Some(SignedAmount::from_sat(0)), [].into_iter().checked_sum());

let amounts = vec![Amount::from_sat(42), Amount::from_sat(1337), Amount::from_sat(21)];
let amounts = [Amount::from_sat(42), Amount::from_sat(1337), Amount::from_sat(21)];
let sum = amounts.into_iter().checked_sum();
assert_eq!(Some(Amount::from_sat(1400)), sum);

let amounts =
vec![Amount::from_sat(u64::MAX), Amount::from_sat(1337), Amount::from_sat(21)];
[Amount::from_sat(u64::MAX), Amount::from_sat(1337), Amount::from_sat(21)];
let sum = amounts.into_iter().checked_sum();
assert_eq!(None, sum);

let amounts = vec![
let amounts = [
SignedAmount::from_sat(i64::MIN),
SignedAmount::from_sat(-1),
SignedAmount::from_sat(21),
];
let sum = amounts.into_iter().checked_sum();
assert_eq!(None, sum);

let amounts = vec![
let amounts = [
SignedAmount::from_sat(i64::MAX),
SignedAmount::from_sat(1),
SignedAmount::from_sat(21),
];
let sum = amounts.into_iter().checked_sum();
assert_eq!(None, sum);

let amounts = vec![
let amounts = [
SignedAmount::from_sat(42),
SignedAmount::from_sat(3301),
SignedAmount::from_sat(21),
Expand All @@ -2595,7 +2602,7 @@ mod tests {
#[test]
fn denomination_string_acceptable_forms() {
// Non-exhaustive list of valid forms.
let valid = vec![
let valid = [
"BTC", "btc", "mBTC", "mbtc", "uBTC", "ubtc", "SATOSHI", "satoshi", "SATOSHIS",
"satoshis", "SAT", "sat", "SATS", "sats", "bit", "bits", "nBTC", "pBTC",
];
Expand Down
20 changes: 7 additions & 13 deletions units/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,29 @@
//!
//! This library provides basic types used by the Rust Bitcoin ecosystem.

#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
// Experimental features we need.
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
// Coding conventions
#![warn(missing_docs)]
// Exclude clippy lints we don't think are valuable
#![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134

#![no_std]

// Disable 16-bit support at least for now as we can't guarantee it yet.
#[cfg(target_pointer_width = "16")]
compile_error!(
"rust-bitcoin currently only supports architectures with pointers wider than 16 bits, let us
know if you want 16-bit support. Note that we do NOT guarantee that we will implement it!"
);

#[cfg(all(feature = "alloc", not(feature = "std")))]
#[cfg(feature = "alloc")]
#[allow(unused_imports)] // broken lint
#[macro_use]
extern crate alloc;

#[cfg(not(feature = "std"))]
extern crate core;
#[cfg(feature = "std")]
extern crate std;

/// A generic serialization/deserialization framework.
#[cfg(feature = "serde")]
Expand All @@ -33,12 +36,3 @@ pub mod amount;

#[doc(inline)]
pub use self::amount::{Amount, ParseAmountError, SignedAmount};

#[rustfmt::skip]
mod prelude {
#[cfg(all(feature = "alloc", not(feature = "std"), not(test)))]
pub use alloc::string::{String, ToString};

#[cfg(any(feature = "std", test))]
pub use std::string::{String, ToString};
}

0 comments on commit 4565fa3

Please sign in to comment.