From de95bf52cb560e8d7e23134257d2e3c851e38fed Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 29 Aug 2023 09:01:25 +1000 Subject: [PATCH] Use checked_sub Recently we "if" guarded subtraction manually using `> 0`, we can better convey the meaning by using `checked_sub` and pattern match on the option. Refactor only, no logic changes. --- bitcoin/src/blockdata/witness.rs | 38 ++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/bitcoin/src/blockdata/witness.rs b/bitcoin/src/blockdata/witness.rs index 889eb472..9d7102cf 100644 --- a/bitcoin/src/blockdata/witness.rs +++ b/bitcoin/src/blockdata/witness.rs @@ -68,26 +68,30 @@ fn fmt_debug(w: &Witness, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> f.write_str("witnesses: [")?; let instructions = w.iter(); - if instructions.len() > 0 { - let last_instruction = instructions.len() - 1; - for (i, instruction) in instructions.enumerate() { - let bytes = instruction.iter(); - if bytes.len() > 0 { - let last_byte = bytes.len() - 1; - f.write_str("[")?; - for (j, byte) in bytes.enumerate() { - write!(f, "{:#04x}", byte)?; - f.write_str(comma_or_close(j, last_byte))?; + match instructions.len().checked_sub(1) { + Some(last_instruction) => { + for (i, instruction) in instructions.enumerate() { + let bytes = instruction.iter(); + match bytes.len().checked_sub(1) { + Some(last_byte) => { + f.write_str("[")?; + for (j, byte) in bytes.enumerate() { + write!(f, "{:#04x}", byte)?; + f.write_str(comma_or_close(j, last_byte))?; + } + } + None => { + // This is possible because the varint is not part of the instruction (see Iter). + write!(f, "[]")?; + } } - } else { - // This is possible because the varint is not part of the instruction (see Iter). - write!(f, "[]")?; + f.write_str(comma_or_close(i, last_instruction))?; } - f.write_str(comma_or_close(i, last_instruction))?; } - } else { - // Witnesses can be empty because the 0x00 var int is not stored in content. - write!(f, "]")?; + None => { + // Witnesses can be empty because the 0x00 var int is not stored in content. + write!(f, "]")?; + } } f.write_str(" }")