Browse Source

Add a few more comments

master
Blink The Things 3 years ago
parent
commit
e56da53b05
2 changed files with 36 additions and 11 deletions
  1. +2
    -0
      .vscode/settings.json
  2. +34
    -11
      modhex.go

+ 2
- 0
.vscode/settings.json View File

@ -0,0 +1,2 @@
{
}

+ 34
- 11
modhex.go View File

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

Loading…
Cancel
Save