Skip to content

Commit

Permalink
Add encode_display for easier formatting (#119)
Browse files Browse the repository at this point in the history
Fixes #118
  • Loading branch information
ia0 authored Jan 7, 2025
1 parent 96fda52 commit 022e711
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1377,6 +1377,22 @@ impl Encoding {
Ok(())
}

/// Returns an object to display the encoding of `input`
///
/// # Examples
///
/// ```rust
/// use data_encoding::BASE64;
/// assert_eq!(
/// format!("Payload: {}", BASE64.encode_display(b"Hello world")),
/// "Payload: SGVsbG8gd29ybGQ=",
/// );
/// ```
#[must_use]
pub fn encode_display<'a>(&'a self, input: &'a [u8]) -> Display<'a> {
Display { encoding: self, input }
}

/// Returns encoded `input`
///
/// # Examples
Expand Down Expand Up @@ -1678,6 +1694,19 @@ impl<'a> Encoder<'a> {
pub fn finalize(self) {}
}

/// Wraps an encoding and input for display purposes.
#[derive(Debug)]
pub struct Display<'a> {
encoding: &'a Encoding,
input: &'a [u8],
}

impl core::fmt::Display for Display<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.encoding.encode_write(self.input, f)
}
}

#[derive(Debug, Copy, Clone)]
#[cfg(feature = "alloc")]
enum SpecificationErrorImpl {
Expand Down

0 comments on commit 022e711

Please sign in to comment.