hex.odin 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package encoding_hex
  2. import "core:io"
  3. import "core:strings"
  4. encode :: proc(src: []byte, allocator := context.allocator, loc := #caller_location) -> []byte #no_bounds_check {
  5. dst := make([]byte, len(src) * 2, allocator, loc)
  6. for i, j := 0, 0; i < len(src); i += 1 {
  7. v := src[i]
  8. dst[j] = HEXTABLE[v>>4]
  9. dst[j+1] = HEXTABLE[v&0x0f]
  10. j += 2
  11. }
  12. return dst
  13. }
  14. encode_into_writer :: proc(dst: io.Writer, src: []byte) -> io.Error {
  15. for v in src {
  16. io.write(dst, {HEXTABLE[v>>4], HEXTABLE[v&0x0f]}) or_return
  17. }
  18. return nil
  19. }
  20. decode :: proc(src: []byte, allocator := context.allocator, loc := #caller_location) -> (dst: []byte, ok: bool) #no_bounds_check {
  21. if len(src) % 2 == 1 {
  22. return
  23. }
  24. dst = make([]byte, len(src) / 2, allocator, loc)
  25. for i, j := 0, 1; j < len(src); j += 2 {
  26. p := src[j-1]
  27. q := src[j]
  28. a := hex_digit(p) or_return
  29. b := hex_digit(q) or_return
  30. dst[i] = (a << 4) | b
  31. i += 1
  32. }
  33. return dst, true
  34. }
  35. // Decodes the given sequence into one byte.
  36. // Should be called with one byte worth of the source, eg: 0x23 -> '#'.
  37. decode_sequence :: proc(str: string) -> (res: byte, ok: bool) {
  38. str := str
  39. if strings.has_prefix(str, "0x") || strings.has_prefix(str, "0X") {
  40. str = str[2:]
  41. }
  42. if len(str) != 2 {
  43. return 0, false
  44. }
  45. upper := hex_digit(str[0]) or_return
  46. lower := hex_digit(str[1]) or_return
  47. return upper << 4 | lower, true
  48. }
  49. @(private)
  50. HEXTABLE := [16]byte {
  51. '0', '1', '2', '3',
  52. '4', '5', '6', '7',
  53. '8', '9', 'a', 'b',
  54. 'c', 'd', 'e', 'f',
  55. }
  56. @(private)
  57. hex_digit :: proc(char: byte) -> (u8, bool) {
  58. switch char {
  59. case '0' ..= '9': return char - '0', true
  60. case 'a' ..= 'f': return char - 'a' + 10, true
  61. case 'A' ..= 'F': return char - 'A' + 10, true
  62. case: return 0, false
  63. }
  64. }