Browse Source

fix indentation and simplify hex.decode_sequence

Laytan Laats 2 years ago
parent
commit
6e4fab19a2
1 changed files with 28 additions and 29 deletions
  1. 28 29
      core/encoding/hex/hex.odin

+ 28 - 29
core/encoding/hex/hex.odin

@@ -4,12 +4,12 @@ import "core:strings"
 
 
 encode :: proc(src: []byte, allocator := context.allocator) -> []byte #no_bounds_check {
 encode :: proc(src: []byte, allocator := context.allocator) -> []byte #no_bounds_check {
 	dst := make([]byte, len(src) * 2, allocator)
 	dst := make([]byte, len(src) * 2, allocator)
-    for i := 0; i < len(src); i += 1 {
+	for i := 0; i < len(src); i += 1 {
 		v := src[i]
 		v := src[i]
-        dst[i]   = HEXTABLE[v>>4]
-        dst[i+1] = HEXTABLE[v&0x0f]
-        i += 2
-    }
+		dst[i]   = HEXTABLE[v>>4]
+		dst[i+1] = HEXTABLE[v&0x0f]
+		i += 2
+	}
 
 
 	return dst
 	return dst
 }
 }
@@ -36,39 +36,38 @@ decode :: proc(src: []byte, allocator := context.allocator) -> (dst: []byte, ok:
 }
 }
 
 
 // Decodes the given sequence into one byte.
 // Decodes the given sequence into one byte.
-// Should be called with one rune worth of the source, eg: 0x23 -> '#'.
-decode_sequence :: proc(str: string) -> (byte, bool) {
-	no_prefix_str := strings.trim_prefix(str, "0x")
-	val: byte
-	for i := 0; i < len(no_prefix_str); i += 1 {
-		index := (len(no_prefix_str) - 1) - i // reverse the loop.
-
-		hd, ok := hex_digit(no_prefix_str[i])
-		if !ok {
-			return 0, false
-		}
-
-		val += u8(hd) << uint(4 * index)
+// Should be called with one byte worth of the source, eg: 0x23 -> '#'.
+decode_sequence :: proc(str: string) -> (res: byte, ok: bool) {
+	str := str
+	if strings.has_prefix(str, "0x") || strings.has_prefix(str, "0X") {
+		str = str[2:]
+	}
+
+	if len(str) != 2 {
+		return 0, false
 	}
 	}
 
 
-	return val, true
+	upper := hex_digit(str[0]) or_return
+	lower := hex_digit(str[1]) or_return
+
+	return upper << 4 | lower, true
 }
 }
 
 
 @(private)
 @(private)
 HEXTABLE := [16]byte {
 HEXTABLE := [16]byte {
-    '0', '1', '2', '3',
-    '4', '5', '6', '7',
-    '8', '9', 'a', 'b',
-    'c', 'd', 'e', 'f',
+	'0', '1', '2', '3',
+	'4', '5', '6', '7',
+	'8', '9', 'a', 'b',
+	'c', 'd', 'e', 'f',
 }
 }
 
 
 @(private)
 @(private)
 hex_digit :: proc(char: byte) -> (u8, bool) {
 hex_digit :: proc(char: byte) -> (u8, bool) {
-    switch char {
-    case '0' ..= '9': return char - '0', true
-    case 'a' ..= 'f': return char - 'a' + 10, true
-    case 'A' ..= 'F': return char - 'A' + 10, true
-    case:             return 0, false
-    }
+	switch char {
+	case '0' ..= '9': return char - '0', true
+	case 'a' ..= 'f': return char - 'a' + 10, true
+	case 'A' ..= 'F': return char - 'A' + 10, true
+	case:             return 0, false
+	}
 }
 }