From e56da53b051c159fb7ef07bb9a842880fb2a3e5d Mon Sep 17 00:00:00 2001 From: blinkthethings Date: Thu, 24 Dec 2020 21:01:13 -0500 Subject: [PATCH] Add a few more comments --- .vscode/settings.json | 2 ++ modhex.go | 45 ++++++++++++++++++++++++++++++++----------- 2 files changed, 36 insertions(+), 11 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..7a73a41 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/modhex.go b/modhex.go index 9247210..e92e719 100644 --- a/modhex.go +++ b/modhex.go @@ -23,24 +23,29 @@ func EncodedLen(n int) int { return n * 2 } -// Encode encodes src into EncodedLen(len(src)) -// bytes of dst. It returns the number of bytes -// written to dst, but this is always EncodedLen(len(src)). +// Encode encodes src into EncodedLen(len(src)) bytes of dst. +// It returns the number of bytes written to dst, but this is +// always EncodedLen(len(src)). // Encode implements modhex encoding. func Encode(dst, src []byte) int { - j := 0 + i := 0 for _, v := range src { - dst[j] = modhexTable[v>>4] - dst[j+1] = modhexTable[v&0x0f] - j += 2 + dst[i] = modhexTable[v>>4] + dst[i+1] = modhexTable[v&0x0f] + i += 2 } return len(src) * 2 } // EncodeToString returns the modhex encoding of src. func EncodeToString(src []byte) string { + // make a new slice to hold the encoded bytes dst := make([]byte, EncodedLen(len(src))) + + // encode it! Encode(dst, src) + + // return the encoded bytes as a string return string(dst) } @@ -50,8 +55,13 @@ func DecodedLen(n int) int { return n / 2 } -// Decode decodes src into DecodedLen(len(src)) bytes, -// returning the actual number of bytes written to dst. +// Decode decodes src into DecodedLen(len(src)) bytes, returning +// the actual number of bytes written to dst. +// +// Decode expects that src contains only modhex characters and that +// src has an 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 { @@ -81,8 +91,21 @@ func Decode(dst, src []byte) (int, error) { } // DecodeString returns the bytes represesented by the modhex string s. +// +// Decode expects that s contains only modhex characters and that s +// has an even length. +// If the input is malformed, Decode returns the number +// of bytes decoded before the error. func DecodeString(s string) ([]byte, error) { + // convert the input string to an array of bytes src := []byte(s) - n, err := Decode(src, src) - return src[:n], err + + // make a new slice to hold the decoded bytes + dst := make([]byte, DecodedLen(len(src))) + + // decode it! + n, err := Decode(dst, src) + + // return the decoded bytes along with any errors that may have occured + return dst[:n], err }