Skip to content

Commit 4f0b811

Browse files
committed
Add display function to Argument trait
This is an idea stolen from rust-lang/rust#120048. It's useful for the next commit.
1 parent 9073b72 commit 4f0b811

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

src/traits.rs

+39-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use core::fmt::Debug;
1+
use core::fmt::{Debug, Display, Formatter, Write};
22

33
/// The argument trait for types that can be parsed by
44
/// [`Options`][crate::Options].
@@ -116,6 +116,16 @@ pub trait Argument: Copy + Eq + Debug {
116116
/// [`parse_short_cluster`][Self::parse_short_cluster]. Returns the
117117
/// value that was consumed.
118118
fn consume_short_val(self) -> Self;
119+
120+
/// Returns an object implementing Display which can be used to format the
121+
/// Argument.
122+
///
123+
/// # Example
124+
///
125+
/// ```
126+
/// # use getargs::Argument;
127+
/// assert_eq!(b"abc".display().to_string(), "abc");
128+
fn display(self) -> impl Display;
119129
}
120130

121131
#[inline]
@@ -190,6 +200,29 @@ impl Argument for &str {
190200
fn consume_short_val(self) -> Self {
191201
self
192202
}
203+
204+
#[inline]
205+
fn display(self) -> impl Display {
206+
self
207+
}
208+
}
209+
210+
struct DisplaySliceU8<'a> {
211+
slice: &'a [u8],
212+
}
213+
214+
impl Display for DisplaySliceU8<'_> {
215+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
216+
f.write_str("")?;
217+
for chunk in self.slice.utf8_chunks() {
218+
f.write_str(chunk.valid())?;
219+
let invalid = chunk.invalid();
220+
if !invalid.is_empty() {
221+
f.write_char(char::REPLACEMENT_CHARACTER)?;
222+
}
223+
}
224+
Ok(())
225+
}
193226
}
194227

195228
impl Argument for &[u8] {
@@ -234,6 +267,11 @@ impl Argument for &[u8] {
234267
fn consume_short_val(self) -> Self {
235268
self
236269
}
270+
271+
#[inline]
272+
fn display(self) -> impl Display {
273+
DisplaySliceU8 { slice: self }
274+
}
237275
}
238276

239277
#[cfg(test)]

0 commit comments

Comments
 (0)