Skip to content
Merged
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
6 changes: 1 addition & 5 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,12 @@ jobs:
fmt:
name: Rustfmt
runs-on: ubuntu-latest
strategy:
matrix:
rust:
- stable
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.rust }}
toolchain: nightly
override: true
- run: rustup component add rustfmt
- uses: actions-rs/cargo@v1
Expand Down
78 changes: 78 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
ignore = []

hard_tabs = false
tab_spaces = 4
newline_style = "Auto"
indent_style = "Block"

max_width = 100 # This is number of characters.
# `use_small_heuristics` is ignored if the granular width config values are explicitly set.
use_small_heuristics = "Max" # "Max" == All granular width settings same as `max_width`.
# # Granular width configuration settings. These are percentages of `max_width`.
# fn_call_width = 60
# attr_fn_like_width = 70
# struct_lit_width = 18
# struct_variant_width = 35
# array_width = 60
# chain_width = 60
# single_line_if_else_max_width = 50

wrap_comments = false
format_code_in_doc_comments = false
comment_width = 100 # Default 80
normalize_comments = false
normalize_doc_attributes = false
format_strings = false
format_macro_matchers = false
format_macro_bodies = true
hex_literal_case = "Preserve"
empty_item_single_line = true
struct_lit_single_line = true
fn_single_line = true # Default false
where_single_line = false
imports_indent = "Block"
imports_layout = "Mixed"
imports_granularity = "Module" # Default "Preserve"
group_imports = "StdExternalCrate" # Default "Preserve"
reorder_imports = true
reorder_modules = true
reorder_impl_items = false
type_punctuation_density = "Wide"
space_before_colon = false
space_after_colon = true
spaces_around_ranges = false
binop_separator = "Front"
remove_nested_parens = true
combine_control_expr = true
overflow_delimited_expr = false
struct_field_align_threshold = 0
enum_discrim_align_threshold = 0
match_arm_blocks = false # Default true
match_arm_leading_pipes = "Never"
force_multiline_blocks = false
fn_params_layout = "Tall"
brace_style = "SameLineWhere"
control_brace_style = "AlwaysSameLine"
trailing_semicolon = true
trailing_comma = "Vertical"
match_block_trailing_comma = false
blank_lines_upper_bound = 1
blank_lines_lower_bound = 0
edition = "2018"
version = "One"
inline_attribute_width = 0
format_generated_files = true
merge_derives = true
use_try_shorthand = false
use_field_init_shorthand = false
force_explicit_abi = true
condense_wildcard_suffixes = false
color = "Auto"
unstable_features = false
disable_all_formatting = false
skip_children = false
hide_parse_errors = false
error_on_line_overflow = false
error_on_unformatted = false
emit_mode = "Files"
make_backup = false
92 changes: 22 additions & 70 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,15 @@ extern crate alloc;
#[cfg(any(test, feature = "std"))]
extern crate core;

#[cfg(all(not(feature = "std"), not(test)))]
use alloc::{string::String, vec::Vec};

#[cfg(all(not(feature = "std"), not(test)))]
use alloc::borrow::Cow;
#[cfg(all(not(feature = "std"), not(test)))]
use alloc::{string::String, vec::Vec};
use core::convert::Infallible;
use core::{fmt, mem};
#[cfg(any(feature = "std", test))]
use std::borrow::Cow;

use core::{convert::Infallible, fmt, mem};

/// Integer in the range `0..32`
#[derive(PartialEq, Eq, Debug, Copy, Clone, Default, PartialOrd, Ord, Hash)]
#[allow(non_camel_case_types)]
Expand All @@ -89,26 +88,18 @@ impl u5 {
}

/// Returns a copy of the underlying `u8` value
pub fn to_u8(self) -> u8 {
self.0
}
pub fn to_u8(self) -> u8 { self.0 }

/// Get char representing this 5 bit value as defined in BIP173
pub fn to_char(self) -> char {
CHARSET[self.to_u8() as usize]
}
pub fn to_char(self) -> char { CHARSET[self.to_u8() as usize] }
}

impl From<u5> for u8 {
fn from(v: u5) -> u8 {
v.0
}
fn from(v: u5) -> u8 { v.0 }
}

impl AsRef<u8> for u5 {
fn as_ref(&self) -> &u8 {
&self.0
}
fn as_ref(&self) -> &u8 { &self.0 }
}

/// Interface to write `u5`s into a sink
Expand Down Expand Up @@ -148,11 +139,7 @@ impl<'a> Bech32Writer<'a> {
variant: Variant,
fmt: &'a mut fmt::Write,
) -> Result<Bech32Writer<'a>, fmt::Error> {
let mut writer = Bech32Writer {
formatter: fmt,
chk: 1,
variant,
};
let mut writer = Bech32Writer { formatter: fmt, chk: 1, variant };

writer.formatter.write_str(hrp)?;
writer.formatter.write_char(SEP)?;
Expand Down Expand Up @@ -196,8 +183,7 @@ impl<'a> Bech32Writer<'a> {
let plm: u32 = self.chk ^ self.variant.constant();

for p in 0..CHECKSUM_LENGTH {
self.formatter
.write_char(u5(((plm >> (5 * (5 - p))) & 0x1f) as u8).to_char())?;
self.formatter.write_char(u5(((plm >> (5 * (5 - p))) & 0x1f) as u8).to_char())?;
}

Ok(())
Expand All @@ -216,8 +202,7 @@ impl<'a> WriteBase32 for Bech32Writer<'a> {

impl<'a> Drop for Bech32Writer<'a> {
fn drop(&mut self) {
self.write_checksum()
.expect("Unhandled error writing the checksum on drop.")
self.write_checksum().expect("Unhandled error writing the checksum on drop.")
}
}

Expand Down Expand Up @@ -250,9 +235,7 @@ impl FromBase32 for Vec<u8> {

/// Convert base32 to base256, removes null-padding if present, returns
/// `Err(Error::InvalidPadding)` if padding bits are unequal `0`
fn from_base32(b32: &[u5]) -> Result<Self, Self::Err> {
convert_bits(b32, 5, 8, false)
}
fn from_base32(b32: &[u5]) -> Result<Self, Self::Err> { convert_bits(b32, 5, 8, false) }
}

/// A trait for converting a value to a type `T` that represents a `u5` slice.
Expand Down Expand Up @@ -344,10 +327,7 @@ impl<T: AsRef<[u8]>> CheckBase32<Vec<u5>> for T {
type Err = Error;

fn check_base32(self) -> Result<Vec<u5>, Self::Err> {
self.as_ref()
.iter()
.map(|x| u5::try_from_u8(*x))
.collect::<Result<Vec<u5>, Error>>()
self.as_ref().iter().map(|x| u5::try_from_u8(*x)).collect::<Result<Vec<u5>, Error>>()
}
}

Expand Down Expand Up @@ -534,9 +514,7 @@ pub fn decode(s: &str) -> Result<(String, Vec<u5>, Variant), Error> {
/// Decode a bech32 string into the raw HRP and the data bytes, assuming no checksum.
///
/// Returns the HRP in lowercase and the data.
pub fn decode_without_checksum(s: &str) -> Result<(String, Vec<u5>), Error> {
split_and_decode(s)
}
pub fn decode_without_checksum(s: &str) -> Result<(String, Vec<u5>), Error> { split_and_decode(s) }

/// Decode a bech32 string into the raw HRP and the `u5` data.
fn split_and_decode(s: &str) -> Result<(String, Vec<u5>), Error> {
Expand Down Expand Up @@ -651,13 +629,7 @@ const CHARSET_REV: [i8; 128] = [
];

/// Generator coefficients
const GEN: [u32; 5] = [
0x3b6a_57b2,
0x2650_8e6d,
0x1ea1_19fa,
0x3d42_33dd,
0x2a14_62b3,
];
const GEN: [u32; 5] = [0x3b6a_57b2, 0x2650_8e6d, 0x1ea1_19fa, 0x3d42_33dd, 0x2a14_62b3];

/// Error types for Bech32 encoding / decoding.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
Expand Down Expand Up @@ -865,13 +837,7 @@ mod tests {
(vec![0x01], 8, 8, true, vec![0x01]),
(vec![0x01], 8, 4, true, vec![0x00, 0x01]),
(vec![0x01], 8, 2, true, vec![0x00, 0x00, 0x00, 0x01]),
(
vec![0x01],
8,
1,
true,
vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01],
),
(vec![0x01], 8, 1, true, vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]),
(vec![0xff], 8, 5, true, vec![0x1f, 0x1c]),
(vec![0x1f, 0x1c], 5, 8, false, vec![0xff]),
];
Expand Down Expand Up @@ -921,30 +887,20 @@ mod tests {
assert!([0u8, 1, 2, 30, 31, 255].check_base32().is_err());

assert!([1u8, 2, 3, 4].check_base32().is_ok());
assert_eq!(
[30u8, 31, 35, 20].check_base32(),
Err(Error::InvalidData(35))
);
assert_eq!([30u8, 31, 35, 20].check_base32(), Err(Error::InvalidData(35)));
}

#[test]
fn test_encode() {
assert_eq!(
encode(
"",
vec![1u8, 2, 3, 4].check_base32().unwrap(),
Variant::Bech32
),
encode("", vec![1u8, 2, 3, 4].check_base32().unwrap(), Variant::Bech32),
Err(Error::InvalidLength)
);
}

#[test]
fn from_base32() {
assert_eq!(
Vec::from_base32(&[0x1f, 0x1c].check_base32().unwrap()),
Ok(vec![0xff])
);
assert_eq!(Vec::from_base32(&[0x1f, 0x1c].check_base32().unwrap()), Ok(vec![0xff]));
assert_eq!(
Vec::from_base32(&[0x1f, 0x1f].check_base32().unwrap()),
Err(Error::InvalidPadding)
Expand All @@ -966,9 +922,8 @@ mod tests {
}
}

let expected_rev_charset = (0u8..128)
.map(|i| get_char_value(i as char))
.collect::<Vec<_>>();
let expected_rev_charset =
(0u8..128).map(|i| get_char_value(i as char)).collect::<Vec<_>>();

assert_eq!(&(CHARSET_REV[..]), expected_rev_charset.as_slice());
}
Expand Down Expand Up @@ -1003,10 +958,7 @@ mod tests {

let encoded_str = encode_without_checksum(hrp, data).unwrap();

assert_eq!(
encoded_str,
written_str[..written_str.len() - CHECKSUM_LENGTH]
);
assert_eq!(encoded_str, written_str[..written_str.len() - CHECKSUM_LENGTH]);
}

#[test]
Expand Down