Skip to content

Commit 4a5164d

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 6087ff2 commit 4a5164d

File tree

3 files changed

+38
-7
lines changed

3 files changed

+38
-7
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: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,18 +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(all(not(feature = "std"), not(test)))]
64+
#[cfg(all(feature = "alloc", not(feature = "std")))]
6465
use alloc::{string::String, vec::Vec};
6566

66-
#[cfg(all(not(feature = "std"), not(test)))]
67+
#[cfg(all(feature = "alloc", not(feature = "std")))]
6768
use alloc::borrow::Cow;
68-
#[cfg(any(feature = "std", test))]
69+
#[cfg(feature = "std")]
6970
use std::borrow::Cow;
7071

7172
use core::{fmt, mem};
@@ -228,6 +229,7 @@ pub trait FromBase32: Sized {
228229
fn from_base32(b32: &[u5]) -> Result<Self, Self::Err>;
229230
}
230231

232+
#[cfg(feature = "alloc")]
231233
impl WriteBase32 for Vec<u5> {
232234
type Err = ();
233235

@@ -242,6 +244,7 @@ impl WriteBase32 for Vec<u5> {
242244
}
243245
}
244246

247+
#[cfg(feature = "alloc")]
245248
impl FromBase32 for Vec<u8> {
246249
type Err = Error;
247250

@@ -253,6 +256,7 @@ impl FromBase32 for Vec<u8> {
253256
}
254257

255258
/// A trait for converting a value to a type `T` that represents a `u5` slice.
259+
#[cfg(feature = "alloc")]
256260
pub trait ToBase32 {
257261
/// Convert `Self` to base32 vector
258262
fn to_base32(&self) -> Vec<u5> {
@@ -267,11 +271,13 @@ pub trait ToBase32 {
267271
}
268272

269273
/// Interface to calculate the length of the base32 representation before actually serializing
274+
#[cfg(feature = "alloc")]
270275
pub trait Base32Len: ToBase32 {
271276
/// Calculate the base32 serialized length
272277
fn base32_len(&self) -> usize;
273278
}
274279

280+
#[cfg(feature = "alloc")]
275281
impl<T: AsRef<[u8]>> ToBase32 for T {
276282
fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
277283
// Amount of bits left over from last round, stored in buffer.
@@ -316,6 +322,7 @@ impl<T: AsRef<[u8]>> ToBase32 for T {
316322
}
317323
}
318324

325+
#[cfg(feature = "alloc")]
319326
impl<T: AsRef<[u8]>> Base32Len for T {
320327
fn base32_len(&self) -> usize {
321328
let bits = self.as_ref().len() * 8;
@@ -337,6 +344,7 @@ pub trait CheckBase32<T: AsRef<[u5]>> {
337344
fn check_base32(self) -> Result<T, Self::Err>;
338345
}
339346

347+
#[cfg(feature = "alloc")]
340348
impl<T: AsRef<[u8]>> CheckBase32<Vec<u5>> for T {
341349
type Err = Error;
342350

@@ -349,6 +357,7 @@ impl<T: AsRef<[u8]>> CheckBase32<Vec<u5>> for T {
349357
}
350358

351359
#[derive(Clone, Copy, PartialEq, Eq)]
360+
#[cfg(feature = "alloc")]
352361
enum Case {
353362
Upper,
354363
Lower,
@@ -361,6 +370,7 @@ enum Case {
361370
/// * **MixedCase**: If the HRP contains both uppercase and lowercase characters.
362371
/// * **InvalidChar**: If the HRP contains any non-ASCII characters (outside 33..=126).
363372
/// * **InvalidLength**: If the HRP is outside 1..83 characters long.
373+
#[cfg(feature = "alloc")]
364374
fn check_hrp(hrp: &str) -> Result<Case, Error> {
365375
if hrp.is_empty() || hrp.len() > 83 {
366376
return Err(Error::InvalidLength);
@@ -401,6 +411,7 @@ fn check_hrp(hrp: &str) -> Result<Case, Error> {
401411
/// * If `fmt` fails on write
402412
/// # Deviations from standard
403413
/// * No length limits are enforced for the data part
414+
#[cfg(feature = "alloc")]
404415
pub fn encode_to_fmt<T: AsRef<[u5]>>(
405416
fmt: &mut fmt::Write,
406417
hrp: &str,
@@ -427,6 +438,7 @@ pub fn encode_to_fmt<T: AsRef<[u5]>>(
427438
/// * If `fmt` fails on write
428439
/// # Deviations from standard
429440
/// * No length limits are enforced for the data part
441+
#[cfg(feature = "alloc")]
430442
pub fn encode_without_checksum_to_fmt<T: AsRef<[u5]>>(
431443
fmt: &mut fmt::Write,
432444
hrp: &str,
@@ -459,6 +471,7 @@ const BECH32M_CONST: u32 = 0x2bc8_30a3;
459471

460472
impl Variant {
461473
// Produce the variant based on the remainder of the polymod operation
474+
#[cfg(feature = "alloc")]
462475
fn from_remainder(c: u32) -> Option<Self> {
463476
match c {
464477
BECH32_CONST => Some(Variant::Bech32),
@@ -481,6 +494,7 @@ impl Variant {
481494
/// * If [check_hrp] returns an error for the given HRP.
482495
/// # Deviations from standard
483496
/// * No length limits are enforced for the data part
497+
#[cfg(feature = "alloc")]
484498
pub fn encode<T: AsRef<[u5]>>(hrp: &str, data: T, variant: Variant) -> Result<String, Error> {
485499
let mut buf = String::new();
486500
encode_to_fmt(&mut buf, hrp, data, variant)?;
@@ -493,6 +507,7 @@ pub fn encode<T: AsRef<[u5]>>(hrp: &str, data: T, variant: Variant) -> Result<St
493507
/// * If [check_hrp] returns an error for the given HRP.
494508
/// # Deviations from standard
495509
/// * No length limits are enforced for the data part
510+
#[cfg(feature = "alloc")]
496511
pub fn encode_without_checksum<T: AsRef<[u5]>>(hrp: &str, data: T) -> Result<String, Error> {
497512
let mut buf = String::new();
498513
encode_without_checksum_to_fmt(&mut buf, hrp, data)?;
@@ -502,6 +517,7 @@ pub fn encode_without_checksum<T: AsRef<[u5]>>(hrp: &str, data: T) -> Result<Str
502517
/// Decode a bech32 string into the raw HRP and the data bytes.
503518
///
504519
/// Returns the HRP in lowercase, the data with the checksum removed, and the encoding.
520+
#[cfg(feature = "alloc")]
505521
pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
506522
let (hrp_lower, mut data) = split_and_decode(s)?;
507523
if data.len() < CHECKSUM_LENGTH {
@@ -523,11 +539,13 @@ pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
523539
/// Decode a bech32 string into the raw HRP and the data bytes, assuming no checksum.
524540
///
525541
/// Returns the HRP in lowercase and the data.
542+
#[cfg(feature = "alloc")]
526543
pub fn decode_without_checksum(s: &str) -> Result<(String, Vec<u5>), Error> {
527544
split_and_decode(s)
528545
}
529546

530547
/// Decode a bech32 string into the raw HRP and the `u5` data.
548+
#[cfg(feature = "alloc")]
531549
fn split_and_decode(s: &str) -> Result<(String, Vec<u5>), Error> {
532550
// Split at separator and check for two pieces
533551
let (raw_hrp, raw_data) = match s.rfind(SEP) {
@@ -584,12 +602,14 @@ fn split_and_decode(s: &str) -> Result<(String, Vec<u5>), Error> {
584602
Ok((hrp_lower, data))
585603
}
586604

605+
#[cfg(feature = "alloc")]
587606
fn verify_checksum(hrp: &[u8], data: &[u5]) -> Option<Variant> {
588607
let mut exp = hrp_expand(hrp);
589608
exp.extend_from_slice(data);
590609
Variant::from_remainder(polymod(&exp))
591610
}
592611

612+
#[cfg(feature = "alloc")]
593613
fn hrp_expand(hrp: &[u8]) -> Vec<u5> {
594614
let mut v: Vec<u5> = Vec::new();
595615
for b in hrp {
@@ -602,6 +622,7 @@ fn hrp_expand(hrp: &[u8]) -> Vec<u5> {
602622
v
603623
}
604624

625+
#[cfg(feature = "alloc")]
605626
fn polymod(values: &[u5]) -> u32 {
606627
let mut chk: u32 = 1;
607628
let mut b: u8;
@@ -630,6 +651,7 @@ const CHARSET: [char; 32] = [
630651
];
631652

632653
/// Reverse character set. Maps ASCII byte -> CHARSET index on [0,31]
654+
#[cfg(feature = "alloc")]
633655
const CHARSET_REV: [i8; 128] = [
634656
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
635657
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
@@ -690,7 +712,7 @@ impl fmt::Display for Error {
690712
}
691713
}
692714

693-
#[cfg(any(feature = "std", test))]
715+
#[cfg(feature = "std")]
694716
impl std::error::Error for Error {
695717
fn description(&self) -> &str {
696718
match *self {
@@ -723,6 +745,7 @@ impl std::error::Error for Error {
723745
/// let base5 = convert_bits(&[0xff], 8, 5, true);
724746
/// assert_eq!(base5.unwrap(), vec![0x1f, 0x1c]);
725747
/// ```
748+
#[cfg(feature = "alloc")]
726749
pub fn convert_bits<T>(data: &[T], from: u32, to: u32, pad: bool) -> Result<Vec<u8>, Error>
727750
where
728751
T: Into<u8> + Copy,
@@ -758,6 +781,7 @@ where
758781
}
759782

760783
#[cfg(test)]
784+
#[cfg(feature = "alloc")] // Note, all the unit tests currently require an allocator.
761785
mod tests {
762786
use super::*;
763787

0 commit comments

Comments
 (0)