mirror of
https://github.com/odin-lang/Odin.git
synced 2026-08-18 03:12:10 +00:00
Add non-allocating hex.decode_into_buffer
Also minor fixes to documentation of hex.decode(). Adds tests of the new procedure with buffers the correct size, larger, and too small.
This commit is contained in:
@@ -95,12 +95,12 @@ Decodes a hex sequence into a byte slice
|
||||
*Allocates Using Provided Allocator*
|
||||
|
||||
Inputs:
|
||||
- dst: The hex sequence decoded into bytes
|
||||
- src: The `[]byte` to be hex-decoded
|
||||
- allocator: (default: context.allocator)
|
||||
- loc: The caller location for debugging purposes (default: #caller_location)
|
||||
|
||||
Returns:
|
||||
- dst: The hex sequence decoded into bytes
|
||||
- ok: A bool, `true` if decoding succeeded, `false` otherwise
|
||||
*/
|
||||
decode :: proc(src: []byte, allocator := context.allocator, loc := #caller_location) -> (dst: []byte, ok: bool) {
|
||||
@@ -123,6 +123,40 @@ decode :: proc(src: []byte, allocator := context.allocator, loc := #caller_locat
|
||||
return dst, true
|
||||
}
|
||||
|
||||
/*
|
||||
Decodes a hex sequence into a byte slice
|
||||
|
||||
Inputs:
|
||||
- src: The `[]byte` to be hex-decoded
|
||||
- buf: A buffer large enough to hold the decoded sequence
|
||||
|
||||
Returns:
|
||||
- dst: The hex sequence decoded into bytes
|
||||
- ok: A bool, `true` if decoding succeeded, `false` otherwise
|
||||
*/
|
||||
decode_into_buffer :: proc(src: []byte, buf: []byte) -> (dst: []byte, ok: bool) #optional_ok {
|
||||
if len(src) % 2 == 1 {
|
||||
return
|
||||
}
|
||||
dst_len := len(src) / 2
|
||||
if len(buf) < dst_len {
|
||||
return
|
||||
}
|
||||
|
||||
#no_bounds_check for i, j := 0, 1; j < len(src); j += 2 {
|
||||
p := src[j-1]
|
||||
q := src[j]
|
||||
|
||||
a := hex_digit(p) or_return
|
||||
b := hex_digit(q) or_return
|
||||
|
||||
buf[i] = (a << 4) | b
|
||||
i += 1
|
||||
}
|
||||
|
||||
return buf[:dst_len], true
|
||||
}
|
||||
|
||||
/*
|
||||
Decodes the first byte in a hex sequence to a byte
|
||||
|
||||
@@ -173,4 +207,4 @@ hex_digit :: proc(char: byte) -> (u8, bool) {
|
||||
case 'A' ..= 'F': return char - 'A' + 10, true
|
||||
case: return 0, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user