Skip to content

Commit fedd38c

Browse files
Add Hrp::{as_bytes, as_str}
1 parent 202b59f commit fedd38c

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/primitives/hrp.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use alloc::string::String;
1414
use core::cmp::Ordering;
1515
use core::fmt::{self, Write};
1616
use core::iter::FusedIterator;
17-
use core::slice;
17+
use core::{slice, str};
1818

1919
/// Maximum length of the human-readable part, as defined by BIP-173.
2020
const MAX_HRP_LEN: usize = 83;
@@ -148,6 +148,16 @@ impl Hrp {
148148
#[inline]
149149
pub fn to_lowercase(&self) -> String { self.lowercase_char_iter().collect() }
150150

151+
/// Returns this human-readable part as bytes.
152+
#[inline]
153+
pub fn as_bytes(&self) -> &[u8] { &self.buf[..self.size] }
154+
155+
/// Returns this human-readable part as str.
156+
#[inline]
157+
pub fn as_str(&self) -> &str {
158+
str::from_utf8(&self.buf[..self.size]).expect("we only store ASCII bytes")
159+
}
160+
151161
/// Creates a byte iterator over the ASCII byte values (ASCII characters) of this HRP.
152162
///
153163
/// If an uppercase HRP was parsed during object construction then this iterator will yield
@@ -512,4 +522,18 @@ mod tests {
512522
assert_eq!(TB, Hrp::parse_unchecked("tb"));
513523
assert_eq!(BCRT, Hrp::parse_unchecked("bcrt"));
514524
}
525+
526+
#[test]
527+
fn as_str() {
528+
let s = "arbitraryhrp";
529+
let hrp = Hrp::parse_unchecked(s);
530+
assert_eq!(hrp.as_str(), s);
531+
}
532+
533+
#[test]
534+
fn as_bytes() {
535+
let s = "arbitraryhrp";
536+
let hrp = Hrp::parse_unchecked(s);
537+
assert_eq!(hrp.as_bytes(), s.as_bytes());
538+
}
515539
}

0 commit comments

Comments
 (0)