Skip to content

Commit

Permalink
Merge #116: Do random improvements
Browse files Browse the repository at this point in the history
30e7e48 Clean up comments in private error module (Tobin C. Harding)
7ea5793 embedded: Run formatter (Tobin C. Harding)
db157f9 Improve rustdoc (Tobin C. Harding)
e4f16cf Implement error traits for gf32::Error (Tobin C. Harding)
a2209d5 Remove crate level examples (Tobin C. Harding)
fdea41f Remove incorrect todo (Tobin C. Harding)
2fa4fc5 Add formatter to git pre-commit hook (Tobin C. Harding)

Pull request description:

  Pull all the unrelated random improvements out of #113 so that we can review/merge them more easily. Nothing controversial here except perhaps commit: `a2209d5 Remove crate level examples`. Note also that commit: `1a746b7 Clean up comments in private error module` is new.

ACKs for top commit:
  apoelstra:
    ACK 30e7e48

Tree-SHA512: 896a025d29659c7305a2fb1d524915fe628dfdb97158381216e50d203730955b4c6aa350dcf26c8a70b18e39cb61e024646ea1303f4bd20a5015b71a464397f4
  • Loading branch information
apoelstra committed Jul 12, 2023
2 parents 2495b06 + 30e7e48 commit f8ebe75
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 52 deletions.
9 changes: 3 additions & 6 deletions embedded/no-allocator/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@
#![no_main]
#![no_std]

use panic_halt as _;

use arrayvec::{ArrayString, ArrayVec};
use bech32::{self, u5, ComboError, FromBase32, ToBase32, Variant, Hrp};
use bech32::{self, u5, ComboError, FromBase32, Hrp, ToBase32, Variant};
use cortex_m_rt::entry;
use cortex_m_semihosting::{debug, hprintln};
use panic_halt as _;

// Note: `#[global_allocator]` is NOT set.

Expand All @@ -26,9 +25,7 @@ fn main() -> ! {

let hrp = Hrp::parse("bech32").unwrap();

bech32::encode_to_fmt_anycase(&mut encoded, hrp, &base32, Variant::Bech32)
.unwrap()
.unwrap();
bech32::encode_to_fmt_anycase(&mut encoded, hrp, &base32, Variant::Bech32).unwrap().unwrap();
test(&*encoded == "bech321qqqsyrhqy2a");

hprintln!("{}", encoded).unwrap();
Expand Down
19 changes: 7 additions & 12 deletions embedded/with-allocator/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@
#![no_std]

extern crate alloc;
use panic_halt as _;

use self::alloc::string::ToString;
use self::alloc::vec;
use self::alloc::vec::Vec;
use core::alloc::Layout;

use alloc_cortex_m::CortexMHeap;
use bech32::{self, FromBase32, ToBase32, Variant, Hrp};
use bech32::{self, FromBase32, Hrp, ToBase32, Variant};
use cortex_m::asm;
use cortex_m_rt::entry;
use cortex_m_semihosting::{debug, hprintln};
use panic_halt as _;

use self::alloc::string::ToString;
use self::alloc::vec;
use self::alloc::vec::Vec;

#[global_allocator]
static ALLOCATOR: CortexMHeap = CortexMHeap::empty();
Expand All @@ -27,12 +27,7 @@ fn main() -> ! {
unsafe { ALLOCATOR.init(cortex_m_rt::heap_start() as usize, HEAP_SIZE) }

let hrp = Hrp::parse("bech32").unwrap();
let encoded = bech32::encode(
hrp,
vec![0x00, 0x01, 0x02].to_base32(),
Variant::Bech32,
)
.unwrap();
let encoded = bech32::encode(hrp, vec![0x00, 0x01, 0x02].to_base32(), Variant::Bech32).unwrap();
test(encoded == "bech321qqqsyrhqy2a".to_string());

hprintln!("{}", encoded).unwrap();
Expand Down
3 changes: 3 additions & 0 deletions githooks/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,6 @@ git diff-index --check --cached $against -- || exit 1

# Check that code lints cleanly.
cargo clippy --all-features -- -D warnings || exit 1

# Check that there are no formatting issues.
cargo +nightly fmt --check || exit 1
8 changes: 0 additions & 8 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
// Written by the Rust Bitcoin developers.
// SPDX-License-Identifier: CC0-1.0

// TODO: We can get this from `bitcoin-internals` crate once that is released.

//! # Error
//!
//! Error handling macros and helpers.
//!
/// Formats error.
///
/// If `std` feature is OFF appends error source (delimited by `: `). We do this because
Expand Down
27 changes: 3 additions & 24 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,6 @@
//!
//! The original description in [BIP-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
//! has more details. See also [BIP-0350](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki).
//!
#![cfg_attr(
feature = "std",
doc = "
# Examples
```
use bech32::{self, FromBase32, ToBase32, Variant, Hrp};
let hrp = Hrp::parse(\"bech32\").expect(\"bech32 is valid\");
let encoded = bech32::encode(hrp, vec![0x00, 0x01, 0x02].to_base32(), Variant::Bech32).unwrap();
assert_eq!(encoded, \"bech321qqqsyrhqy2a\".to_string());
let (hrp, data, variant) = bech32::decode(&encoded).unwrap();
assert_eq!(hrp.to_string(), \"bech32\");
assert_eq!(Vec::<u8>::from_base32(&data).unwrap(), vec![0x00, 0x01, 0x02]);
assert_eq!(variant, Variant::Bech32);
```
"
)]
//!
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
// Experimental features we need.
Expand Down Expand Up @@ -452,9 +434,8 @@ pub fn encode_to_fmt_anycase<T: AsRef<[u5]>>(
///
/// This method is intended for implementing traits from [`std::fmt`].
///
/// # Errors
/// # Deviations from standard.
///
/// * Deviations from standard.
/// * No length limits are enforced for the data part.
pub fn encode_without_checksum_to_fmt<T: AsRef<[u5]>>(
fmt: &mut dyn fmt::Write,
Expand Down Expand Up @@ -502,9 +483,8 @@ impl Variant {

/// Encodes a bech32 payload to string.
///
/// # Errors
/// # Deviations from standard.
///
/// * Deviations from standard.
/// * No length limits are enforced for the data part.
#[cfg(feature = "alloc")]
pub fn encode<T: AsRef<[u5]>>(hrp: Hrp, data: T, variant: Variant) -> Result<String, Error> {
Expand All @@ -515,9 +495,8 @@ pub fn encode<T: AsRef<[u5]>>(hrp: Hrp, data: T, variant: Variant) -> Result<Str

/// Encodes a bech32 payload to string without the checksum.
///
/// # Errors
/// # Deviations from standard.
///
/// * Deviations from standard.
/// * No length limits are enforced for the data part.
#[cfg(feature = "alloc")]
pub fn encode_without_checksum<T: AsRef<[u5]>>(hrp: Hrp, data: T) -> Result<String, Error> {
Expand Down
21 changes: 19 additions & 2 deletions src/primitives/gf32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ use core::{fmt, num, ops};
#[cfg(all(test, mutate))]
use mutagen::mutate;

use crate::write_err;

/// Logarithm table of each bech32 element, as a power of alpha = Z.
///
/// Includes Q as 0 but this is false; you need to exclude Q because it has no discrete log. If we
Expand Down Expand Up @@ -317,12 +319,27 @@ pub enum Error {
}

impl fmt::Display for Error {
fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { todo!() }
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use Error::*;

match *self {
NotAByte(ref e) => write_err!(f, "invalid field element"; e),
InvalidByte(ref b) => write!(f, "invalid byte in field element: {:#04x}", b),
InvalidChar(ref c) => write!(f, "invalid char in field element: {}", c),
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { todo!() }
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use Error::*;

match *self {
NotAByte(ref e) => Some(e),
InvalidByte(_) | InvalidChar(_) => None,
}
}
}

impl From<num::TryFromIntError> for Error {
Expand Down

0 comments on commit f8ebe75

Please sign in to comment.