Skip to content
This repository was archived by the owner on Nov 30, 2022. It is now read-only.

Commit 012d775

Browse files
committed
hex: use precision to set maximum width; use width for minimum
1 parent de89e4c commit 012d775

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

src/hex.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -136,31 +136,33 @@ impl<'a> ExactSizeIterator for HexIterator<'a> {
136136
/// Output hex into an object implementing `fmt::Write`, which is usually more
137137
/// efficient than going through a `String` using `ToHex`.
138138
pub fn format_hex(data: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
139+
let prec = f.precision().unwrap_or(2 * data.len());
139140
let width = f.width().unwrap_or(2 * data.len());
140141
for _ in (2 * data.len())..width {
141142
f.write_str("0")?;
142143
}
143-
for ch in data.into_iter().take(width / 2) {
144+
for ch in data.into_iter().take(prec / 2) {
144145
write!(f, "{:02x}", *ch)?;
145146
}
146-
if width < 2 * data.len() && width % 2 == 1 {
147-
write!(f, "{:x}", data[width / 2] / 16)?;
147+
if prec < 2 * data.len() && prec % 2 == 1 {
148+
write!(f, "{:x}", data[prec / 2] / 16)?;
148149
}
149150
Ok(())
150151
}
151152

152153
/// Output hex in reverse order; used for Sha256dHash whose standard hex encoding
153154
/// has the bytes reversed.
154155
pub fn format_hex_reverse(data: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
156+
let prec = f.precision().unwrap_or(2 * data.len());
155157
let width = f.width().unwrap_or(2 * data.len());
156158
for _ in (2 * data.len())..width {
157159
f.write_str("0")?;
158160
}
159-
for ch in data.iter().rev().take(width / 2) {
161+
for ch in data.iter().rev().take(prec / 2) {
160162
write!(f, "{:02x}", *ch)?;
161163
}
162-
if width < 2 * data.len() && width % 2 == 1 {
163-
write!(f, "{:x}", data[data.len() - 1 - width / 2] / 16)?;
164+
if prec < 2 * data.len() && prec % 2 == 1 {
165+
write!(f, "{:x}", data[data.len() - 1 - prec / 2] / 16)?;
164166
}
165167
Ok(())
166168
}
@@ -274,7 +276,7 @@ mod tests {
274276

275277
for i in 0..20 {
276278
assert_eq!(
277-
format!("{:width$x}", bytes, width = i),
279+
format!("{:.prec$x}", bytes, prec = i),
278280
&"0102030405060708090a"[0..i]
279281
);
280282
}
@@ -307,7 +309,7 @@ mod tests {
307309

308310
for i in 0..20 {
309311
assert_eq!(
310-
format!("{:width$x}", bytes, width = i),
312+
format!("{:.prec$x}", bytes, prec = i),
311313
&"0a090807060504030201"[0..i]
312314
);
313315
}

0 commit comments

Comments
 (0)