1# hex - hexadecimal encoding.2#3# EncodeToString turns bytes into the string of their hexadecimal digits, two4# per byte, and DecodeString reads that string back.56# The digits as bytes: indexing a string gives a string, indexing bytes gives7# the number, which is what goes into the output.8digits = bytes("0123456789abcdef")910# value returns the number a hexadecimal digit stands for, or -1.11value = fn(c) {12 if c >= 48 && c <= 57 {13 return c - 4814 }15 if c >= 97 && c <= 102 {16 return c - 8717 }18 if c >= 65 && c <= 70 {19 return c - 5520 }21 return -122}2324# EncodedLen is how long the encoding of n bytes is.25EncodedLen = fn(n) { n * 2 }2627# DecodedLen is how many bytes n hexadecimal digits stand for.28DecodedLen = fn(n) { (n - n % 2) >> 1 }2930# EncodeToString returns the hexadecimal form of data, a string or bytes.31EncodeToString = fn(data) {32 if type(data) != "bytes" {33 if failed(data = bytes(string(data))) {34 return data35 }36 }3738 # A list of numbers turned into bytes at the end: bytes are read only,39 # and growing a string one digit at a time would copy it every time.40 out = []41 for i = 0; i < len(data); ++i {42 b = data[i]43 out = append(out, digits[b >> 4], digits[b & 0x0f])44 }45 return string(bytes(out))46}4748# DecodeString returns the bytes the hexadecimal string s stands for.49DecodeString = fn(s) {50 if type(s) != "bytes" {51 if failed(s = bytes(string(s))) {52 return s53 }54 }5556 if len(s) % 2 != 0 {57 return error("hex: odd length string")58 }5960 out = []61 for i = 0; i < len(s); i = i + 2 {62 hi = value(s[i])63 lo = value(s[i + 1])6465 if hi < 0 || lo < 0 {66 return error("hex: invalid byte at index {i}")67 }68 out = append(out, hi << 4 | lo)69 }70 return bytes(out)71}