You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
1.9 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. // Package modhex implements modhex encoding and decoding.
  2. package modhex
  3. import (
  4. "errors"
  5. "fmt"
  6. )
  7. const modhexTable = "cbdefghijklnrtuv"
  8. var modhexMap map[byte]byte
  9. func init() {
  10. modhexMap = make(map[byte]byte)
  11. for i, v := range []byte(modhexTable) {
  12. modhexMap[v] = byte(i)
  13. }
  14. }
  15. // EncodedLen returns the length of an encoding of n source bytes.
  16. // Specifically, it returns n * 2.
  17. func EncodedLen(n int) int {
  18. return n * 2
  19. }
  20. // Encode encodes src into EncodedLen(len(src))
  21. // bytes of dst. It returns the number of bytes
  22. // written to dst, but this is always EncodedLen(len(src)).
  23. // Encode implements modhex encoding.
  24. func Encode(dst, src []byte) int {
  25. j := 0
  26. for _, v := range src {
  27. dst[j] = modhexTable[v>>4]
  28. dst[j+1] = modhexTable[v&0x0f]
  29. j += 2
  30. }
  31. return len(src) * 2
  32. }
  33. // EncodeToString returns the modhex encoding of src.
  34. func EncodeToString(src []byte) string {
  35. dst := make([]byte, EncodedLen(len(src)))
  36. Encode(dst, src)
  37. return string(dst)
  38. }
  39. // DecodedLen returns the length of a decoding of n source bytes.
  40. // Specifically, it returns n / 2.
  41. func DecodedLen(n int) int {
  42. return n / 2
  43. }
  44. // Decode decodes src into DecodedLen(len(src)) bytes,
  45. // returning the actual number of bytes written to dst.
  46. func Decode(dst, src []byte) (int, error) {
  47. i, j := 0, 1
  48. for ; j < len(src); j += 2 {
  49. a, ok := modhexMap[src[j-1]]
  50. if !ok {
  51. return i, fmt.Errorf("modhex: invalid byte: %#U", rune(src[j-1]))
  52. }
  53. b, ok := modhexMap[src[j]]
  54. if !ok {
  55. return i, fmt.Errorf("modhex: invalid byte: %#U", rune(src[j]))
  56. }
  57. dst[i] = (a << 4) | b
  58. i++
  59. }
  60. if len(src)%2 == 1 {
  61. if _, ok := modhexMap[src[j-1]]; !ok {
  62. return i, fmt.Errorf("modhex: invalid byte: %#U", rune(src[j-1]))
  63. }
  64. return i, errors.New("modhex: odd length modhex string")
  65. }
  66. return i, nil
  67. }
  68. // DecodeString returns the bytes represesented by the modhex string s.
  69. func DecodeString(s string) ([]byte, error) {
  70. src := []byte(s)
  71. n, err := Decode(src, src)
  72. return src[:n], err
  73. }