|
1 |
| -use core::fmt::Debug; |
| 1 | +use core::fmt::{Debug, Display, Formatter, Write}; |
2 | 2 |
|
3 | 3 | /// The argument trait for types that can be parsed by
|
4 | 4 | /// [`Options`][crate::Options].
|
@@ -116,6 +116,16 @@ pub trait Argument: Copy + Eq + Debug {
|
116 | 116 | /// [`parse_short_cluster`][Self::parse_short_cluster]. Returns the
|
117 | 117 | /// value that was consumed.
|
118 | 118 | 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; |
119 | 129 | }
|
120 | 130 |
|
121 | 131 | #[inline]
|
@@ -190,6 +200,29 @@ impl Argument for &str {
|
190 | 200 | fn consume_short_val(self) -> Self {
|
191 | 201 | self
|
192 | 202 | }
|
| 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 | + } |
193 | 226 | }
|
194 | 227 |
|
195 | 228 | impl Argument for &[u8] {
|
@@ -234,6 +267,11 @@ impl Argument for &[u8] {
|
234 | 267 | fn consume_short_val(self) -> Self {
|
235 | 268 | self
|
236 | 269 | }
|
| 270 | + |
| 271 | + #[inline] |
| 272 | + fn display(self) -> impl Display { |
| 273 | + DisplaySliceU8 { slice: self } |
| 274 | + } |
237 | 275 | }
|
238 | 276 |
|
239 | 277 | #[cfg(test)]
|
|
0 commit comments