Skip to content

Commit 022e711

Browse files
authored
Add encode_display for easier formatting (#119)
Fixes #118
1 parent 96fda52 commit 022e711

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

lib/src/lib.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1377,6 +1377,22 @@ impl Encoding {
13771377
Ok(())
13781378
}
13791379

1380+
/// Returns an object to display the encoding of `input`
1381+
///
1382+
/// # Examples
1383+
///
1384+
/// ```rust
1385+
/// use data_encoding::BASE64;
1386+
/// assert_eq!(
1387+
/// format!("Payload: {}", BASE64.encode_display(b"Hello world")),
1388+
/// "Payload: SGVsbG8gd29ybGQ=",
1389+
/// );
1390+
/// ```
1391+
#[must_use]
1392+
pub fn encode_display<'a>(&'a self, input: &'a [u8]) -> Display<'a> {
1393+
Display { encoding: self, input }
1394+
}
1395+
13801396
/// Returns encoded `input`
13811397
///
13821398
/// # Examples
@@ -1678,6 +1694,19 @@ impl<'a> Encoder<'a> {
16781694
pub fn finalize(self) {}
16791695
}
16801696

1697+
/// Wraps an encoding and input for display purposes.
1698+
#[derive(Debug)]
1699+
pub struct Display<'a> {
1700+
encoding: &'a Encoding,
1701+
input: &'a [u8],
1702+
}
1703+
1704+
impl core::fmt::Display for Display<'_> {
1705+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1706+
self.encoding.encode_write(self.input, f)
1707+
}
1708+
}
1709+
16811710
#[derive(Debug, Copy, Clone)]
16821711
#[cfg(feature = "alloc")]
16831712
enum SpecificationErrorImpl {

0 commit comments

Comments
 (0)