Browse Source

Add comments and slight variable name change

master
Blink The Things 3 years ago
parent
commit
d76062674e
1 changed files with 21 additions and 12 deletions
  1. +21
    -12
      modhex.go

+ 21
- 12
modhex.go View File

@ -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.


Loading…
Cancel
Save