From d76062674e7e0672b944157caba176d92629d920 Mon Sep 17 00:00:00 2001 From: blinkthethings Date: Fri, 25 Dec 2020 09:27:22 -0500 Subject: [PATCH] Add comments and slight variable name change --- modhex.go | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/modhex.go b/modhex.go index 198ceba..0cda637 100644 --- a/modhex.go +++ b/modhex.go @@ -86,31 +86,40 @@ func (e InvalidByteError) Error() string { // even length. If the input is malformed, Decode returns the number of bytes // decoded before the error. func Decode(dst, src []byte) (int, error) { - i, j := 0, 1 - for ; j < len(src); j += 2 { - a, ok := modhexMap[src[j-1]] + // decode the src bytes two at a time + n, i := 0, 1 + for ; i < len(src); i += 2 { + + // try to decode the upper nibble + a, ok := modhexMap[src[i-1]] if !ok { - return i, InvalidByteError(src[j-1]) + return n, InvalidByteError(src[i-1]) } - b, ok := modhexMap[src[j]] + // try to decode the lower nibble + b, ok := modhexMap[src[i]] if !ok { - return i, InvalidByteError(src[j]) + return n, InvalidByteError(src[i]) } - dst[i] = (a << 4) | b - i++ + // store the decoded value into dst + dst[n] = (a << 4) | b + n++ } + // check for an odd length input if len(src)%2 == 1 { - if _, ok := modhexMap[src[j-1]]; !ok { - return i, InvalidByteError(src[j-1]) + // first check for an invalid byte + if _, ok := modhexMap[src[i-1]]; !ok { + return n, InvalidByteError(src[i-1]) } - return i, ErrLength + // report the number of bytes written and the length error + return n, ErrLength } - return i, nil + // return the number of bytes written to dst + return n, nil } // DecodeString returns the bytes represented by the modhex string s.