Skip to content

Commit 7536937

Browse files
committed
Add "alloc" feature
We would like users to be able to use parts of this library in a `no_std` environment without an allocator. To achieve this add an "alloc" feature and feature gate any code that requires allocation behind "alloc"/"std". Update the CI test job to run the test with each feature on its own.
1 parent c6d2dc3 commit 7536937

File tree

3 files changed

+34
-10
lines changed

3 files changed

+34
-10
lines changed

.github/workflows/rust.yml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
on: [pull_request]
23

34
name: Continuous Integration
@@ -22,7 +23,11 @@ jobs:
2223
- uses: actions-rs/cargo@v1
2324
with:
2425
command: test
25-
args: --verbose --features strict
26+
args: --verbose --no-default-features --features strict alloc
27+
- uses: actions-rs/cargo@v1
28+
with:
29+
command: test
30+
args: --verbose --no-default-features --features strict std
2631

2732
fmt:
2833
name: Rustfmt

Cargo.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ edition = "2018"
1212

1313
[features]
1414
default = ["std"]
15-
std = []
15+
std = ["alloc"]
16+
alloc = []
17+
1618
# Only for CI to make all warnings errors, do not activate otherwise (may break forward compatibility)
1719
strict = []
1820

src/lib.rs

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,21 +54,19 @@ assert_eq!(variant, Variant::Bech32);
5454
#![deny(non_camel_case_types)]
5555
#![deny(non_snake_case)]
5656
#![deny(unused_mut)]
57+
5758
#![cfg_attr(feature = "strict", deny(warnings))]
5859
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
5960

60-
#[cfg(all(not(feature = "std"), not(test)))]
61+
#[cfg(feature = "alloc")]
6162
extern crate alloc;
6263

63-
#[cfg(any(test, feature = "std"))]
64-
extern crate core;
65-
66-
#[cfg(all(not(feature = "std"), not(test)))]
64+
#[cfg(all(feature = "alloc", not(feature = "std")))]
6765
use alloc::{string::String, vec::Vec};
6866

69-
#[cfg(all(not(feature = "std"), not(test)))]
67+
#[cfg(all(feature = "alloc", not(feature = "std")))]
7068
use alloc::borrow::Cow;
71-
#[cfg(any(feature = "std", test))]
69+
#[cfg(feature = "std")]
7270
use std::borrow::Cow;
7371

7472
use core::{fmt, mem};
@@ -228,6 +226,7 @@ pub trait FromBase32: Sized {
228226
fn from_base32(b32: &[u5]) -> Result<Self, Self::Err>;
229227
}
230228

229+
#[cfg(feature = "alloc")]
231230
impl WriteBase32 for Vec<u5> {
232231
type Err = ();
233232

@@ -242,6 +241,7 @@ impl WriteBase32 for Vec<u5> {
242241
}
243242
}
244243

244+
#[cfg(feature = "alloc")]
245245
impl FromBase32 for Vec<u8> {
246246
type Err = Error;
247247

@@ -253,6 +253,7 @@ impl FromBase32 for Vec<u8> {
253253
}
254254

255255
/// A trait for converting a value to a type `T` that represents a `u5` slice.
256+
#[cfg(feature = "alloc")]
256257
pub trait ToBase32 {
257258
/// Convert `Self` to base32 vector
258259
fn to_base32(&self) -> Vec<u5> {
@@ -267,11 +268,13 @@ pub trait ToBase32 {
267268
}
268269

269270
/// Interface to calculate the length of the base32 representation before actually serializing
271+
#[cfg(feature = "alloc")]
270272
pub trait Base32Len: ToBase32 {
271273
/// Calculate the base32 serialized length
272274
fn base32_len(&self) -> usize;
273275
}
274276

277+
#[cfg(feature = "alloc")]
275278
impl<T: AsRef<[u8]>> ToBase32 for T {
276279
fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
277280
// Amount of bits left over from last round, stored in buffer.
@@ -316,6 +319,7 @@ impl<T: AsRef<[u8]>> ToBase32 for T {
316319
}
317320
}
318321

322+
#[cfg(feature = "alloc")]
319323
impl<T: AsRef<[u8]>> Base32Len for T {
320324
fn base32_len(&self) -> usize {
321325
let bits = self.as_ref().len() * 8;
@@ -337,6 +341,7 @@ pub trait CheckBase32<T: AsRef<[u5]>> {
337341
fn check_base32(self) -> Result<T, Self::Err>;
338342
}
339343

344+
#[cfg(feature = "alloc")]
340345
impl<T: AsRef<[u8]>> CheckBase32<Vec<u5>> for T {
341346
type Err = Error;
342347

@@ -349,6 +354,7 @@ impl<T: AsRef<[u8]>> CheckBase32<Vec<u5>> for T {
349354
}
350355

351356
#[derive(Clone, Copy, PartialEq, Eq)]
357+
#[cfg(feature = "alloc")]
352358
enum Case {
353359
Upper,
354360
Lower,
@@ -361,6 +367,7 @@ enum Case {
361367
/// * **MixedCase**: If the HRP contains both uppercase and lowercase characters.
362368
/// * **InvalidChar**: If the HRP contains any non-ASCII characters (outside 33..=126).
363369
/// * **InvalidLength**: If the HRP is outside 1..83 characters long.
370+
#[cfg(feature = "alloc")]
364371
fn check_hrp(hrp: &str) -> Result<Case, Error> {
365372
if hrp.is_empty() || hrp.len() > 83 {
366373
return Err(Error::InvalidLength);
@@ -400,6 +407,7 @@ fn check_hrp(hrp: &str) -> Result<Case, Error> {
400407
/// * If [check_hrp] returns an error for the given HRP.
401408
/// # Deviations from standard
402409
/// * No length limits are enforced for the data part
410+
#[cfg(feature = "alloc")]
403411
pub fn encode_to_fmt<T: AsRef<[u5]>>(
404412
fmt: &mut fmt::Write,
405413
hrp: &str,
@@ -436,6 +444,7 @@ const BECH32M_CONST: u32 = 0x2bc8_30a3;
436444

437445
impl Variant {
438446
// Produce the variant based on the remainder of the polymod operation
447+
#[cfg(feature = "alloc")]
439448
fn from_remainder(c: u32) -> Option<Self> {
440449
match c {
441450
BECH32_CONST => Some(Variant::Bech32),
@@ -458,6 +467,7 @@ impl Variant {
458467
/// * If [check_hrp] returns an error for the given HRP.
459468
/// # Deviations from standard
460469
/// * No length limits are enforced for the data part
470+
#[cfg(feature = "alloc")]
461471
pub fn encode<T: AsRef<[u5]>>(hrp: &str, data: T, variant: Variant) -> Result<String, Error> {
462472
let mut buf = String::new();
463473
encode_to_fmt(&mut buf, hrp, data, variant)?.unwrap();
@@ -467,6 +477,7 @@ pub fn encode<T: AsRef<[u5]>>(hrp: &str, data: T, variant: Variant) -> Result<St
467477
/// Decode a bech32 string into the raw HRP and the data bytes.
468478
///
469479
/// Returns the HRP in lowercase..
480+
#[cfg(feature = "alloc")]
470481
pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
471482
// Ensure overall length is within bounds
472483
if s.len() < 8 {
@@ -541,12 +552,14 @@ pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
541552
}
542553
}
543554

555+
#[cfg(feature = "alloc")]
544556
fn verify_checksum(hrp: &[u8], data: &[u5]) -> Option<Variant> {
545557
let mut exp = hrp_expand(hrp);
546558
exp.extend_from_slice(data);
547559
Variant::from_remainder(polymod(&exp))
548560
}
549561

562+
#[cfg(feature = "alloc")]
550563
fn hrp_expand(hrp: &[u8]) -> Vec<u5> {
551564
let mut v: Vec<u5> = Vec::new();
552565
for b in hrp {
@@ -559,6 +572,7 @@ fn hrp_expand(hrp: &[u8]) -> Vec<u5> {
559572
v
560573
}
561574

575+
#[cfg(feature = "alloc")]
562576
fn polymod(values: &[u5]) -> u32 {
563577
let mut chk: u32 = 1;
564578
let mut b: u8;
@@ -587,6 +601,7 @@ const CHARSET: [char; 32] = [
587601
];
588602

589603
/// Reverse character set. Maps ASCII byte -> CHARSET index on [0,31]
604+
#[cfg(feature = "alloc")]
590605
const CHARSET_REV: [i8; 128] = [
591606
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
592607
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
@@ -638,7 +653,7 @@ impl fmt::Display for Error {
638653
}
639654
}
640655

641-
#[cfg(any(feature = "std", test))]
656+
#[cfg(feature = "std")]
642657
impl std::error::Error for Error {
643658
fn description(&self) -> &str {
644659
match *self {
@@ -670,6 +685,7 @@ impl std::error::Error for Error {
670685
/// let base5 = convert_bits(&[0xff], 8, 5, true);
671686
/// assert_eq!(base5.unwrap(), vec![0x1f, 0x1c]);
672687
/// ```
688+
#[cfg(feature = "alloc")]
673689
pub fn convert_bits<T>(data: &[T], from: u32, to: u32, pad: bool) -> Result<Vec<u8>, Error>
674690
where
675691
T: Into<u8> + Copy,
@@ -705,6 +721,7 @@ where
705721
}
706722

707723
#[cfg(test)]
724+
#[cfg(feature = "alloc")] // Note, all the unit tests currently require an allocator.
708725
mod tests {
709726
use super::*;
710727

0 commit comments

Comments
 (0)