Skip to content

Commit a6a37d8

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 995cb7c commit a6a37d8

File tree

3 files changed

+37
-6
lines changed

3 files changed

+37
-6
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: 28 additions & 4 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);
@@ -400,6 +410,7 @@ fn check_hrp(hrp: &str) -> Result<Case, Error> {
400410
/// * If [check_hrp] returns an error for the given HRP.
401411
/// # Deviations from standard
402412
/// * No length limits are enforced for the data part
413+
#[cfg(feature = "alloc")]
403414
pub fn encode_to_fmt<T: AsRef<[u5]>>(
404415
fmt: &mut fmt::Write,
405416
hrp: &str,
@@ -429,6 +440,7 @@ pub fn encode_to_fmt<T: AsRef<[u5]>>(
429440
/// * If [check_hrp] returns an error for the given HRP.
430441
/// # Deviations from standard
431442
/// * No length limits are enforced for the data part
443+
#[cfg(feature = "alloc")]
432444
pub fn encode_without_checksum_to_fmt<T: AsRef<[u5]>>(
433445
fmt: &mut fmt::Write,
434446
hrp: &str,
@@ -467,6 +479,7 @@ const BECH32M_CONST: u32 = 0x2bc8_30a3;
467479

468480
impl Variant {
469481
// Produce the variant based on the remainder of the polymod operation
482+
#[cfg(feature = "alloc")]
470483
fn from_remainder(c: u32) -> Option<Self> {
471484
match c {
472485
BECH32_CONST => Some(Variant::Bech32),
@@ -489,6 +502,7 @@ impl Variant {
489502
/// * If [check_hrp] returns an error for the given HRP.
490503
/// # Deviations from standard
491504
/// * No length limits are enforced for the data part
505+
#[cfg(feature = "alloc")]
492506
pub fn encode<T: AsRef<[u5]>>(hrp: &str, data: T, variant: Variant) -> Result<String, Error> {
493507
let mut buf = String::new();
494508
encode_to_fmt(&mut buf, hrp, data, variant)?.unwrap();
@@ -501,6 +515,7 @@ pub fn encode<T: AsRef<[u5]>>(hrp: &str, data: T, variant: Variant) -> Result<St
501515
/// * If [check_hrp] returns an error for the given HRP.
502516
/// # Deviations from standard
503517
/// * No length limits are enforced for the data part
518+
#[cfg(feature = "alloc")]
504519
pub fn encode_without_checksum<T: AsRef<[u5]>>(hrp: &str, data: T) -> Result<String, Error> {
505520
let mut buf = String::new();
506521
encode_without_checksum_to_fmt(&mut buf, hrp, data)?.unwrap();
@@ -510,6 +525,7 @@ pub fn encode_without_checksum<T: AsRef<[u5]>>(hrp: &str, data: T) -> Result<Str
510525
/// Decode a bech32 string into the raw HRP and the data bytes.
511526
///
512527
/// Returns the HRP in lowercase, the data with the checksum removed, and the encoding.
528+
#[cfg(feature = "alloc")]
513529
pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
514530
let (hrp_lower, mut data) = split_and_decode(s)?;
515531
if data.len() < CHECKSUM_LENGTH {
@@ -531,11 +547,13 @@ pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
531547
/// Decode a bech32 string into the raw HRP and the data bytes, assuming no checksum.
532548
///
533549
/// Returns the HRP in lowercase and the data.
550+
#[cfg(feature = "alloc")]
534551
pub fn decode_without_checksum(s: &str) -> Result<(String, Vec<u5>), Error> {
535552
split_and_decode(s)
536553
}
537554

538555
/// Decode a bech32 string into the raw HRP and the `u5` data.
556+
#[cfg(feature = "alloc")]
539557
fn split_and_decode(s: &str) -> Result<(String, Vec<u5>), Error> {
540558
// Split at separator and check for two pieces
541559
let (raw_hrp, raw_data) = match s.rfind(SEP) {
@@ -592,12 +610,14 @@ fn split_and_decode(s: &str) -> Result<(String, Vec<u5>), Error> {
592610
Ok((hrp_lower, data))
593611
}
594612

613+
#[cfg(feature = "alloc")]
595614
fn verify_checksum(hrp: &[u8], data: &[u5]) -> Option<Variant> {
596615
let mut exp = hrp_expand(hrp);
597616
exp.extend_from_slice(data);
598617
Variant::from_remainder(polymod(&exp))
599618
}
600619

620+
#[cfg(feature = "alloc")]
601621
fn hrp_expand(hrp: &[u8]) -> Vec<u5> {
602622
let mut v: Vec<u5> = Vec::new();
603623
for b in hrp {
@@ -610,6 +630,7 @@ fn hrp_expand(hrp: &[u8]) -> Vec<u5> {
610630
v
611631
}
612632

633+
#[cfg(feature = "alloc")]
613634
fn polymod(values: &[u5]) -> u32 {
614635
let mut chk: u32 = 1;
615636
let mut b: u8;
@@ -638,6 +659,7 @@ const CHARSET: [char; 32] = [
638659
];
639660

640661
/// Reverse character set. Maps ASCII byte -> CHARSET index on [0,31]
662+
#[cfg(feature = "alloc")]
641663
const CHARSET_REV: [i8; 128] = [
642664
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
643665
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
@@ -718,6 +740,7 @@ impl std::error::Error for Error {
718740
/// let base5 = convert_bits(&[0xff], 8, 5, true);
719741
/// assert_eq!(base5.unwrap(), vec![0x1f, 0x1c]);
720742
/// ```
743+
#[cfg(feature = "alloc")]
721744
pub fn convert_bits<T>(data: &[T], from: u32, to: u32, pad: bool) -> Result<Vec<u8>, Error>
722745
where
723746
T: Into<u8> + Copy,
@@ -753,6 +776,7 @@ where
753776
}
754777

755778
#[cfg(test)]
779+
#[cfg(feature = "alloc")] // Note, all the unit tests currently require an allocator.
756780
mod tests {
757781
use super::*;
758782

0 commit comments

Comments
 (0)