feat: raise Invalid_argument for bad hex values

This commit is contained in:
Matt Bray 2022-03-24 17:35:20 +00:00
parent 0326a8a9a2
commit 1e96404502

View file

@ -152,9 +152,9 @@ module Util_ = struct
let n_of_c = function
| '0' .. '9' as c -> Char.code c - Char.code '0'
| 'a' .. 'f' as c -> 10 + Char.code c - Char.code 'a'
| _ -> failwith "invalid hex char"
| _ -> raise (Invalid_argument "invalid hex char")
in
assert (String.length s mod 2 = 0);
if (String.length s mod 2 <> 0) then raise (Invalid_argument "hex sequence must be of even length");
let res = Bytes.make (String.length s / 2) '\x00' in
for i=0 to String.length s/2-1 do
let n1 = n_of_c (String.get s (2*i)) in
@ -180,7 +180,7 @@ end = struct
type t = bytes
let to_bytes self = self
let create () : t = Collector.rand_bytes_16()
let of_bytes b = assert(Bytes.length b=16); b
let of_bytes b = if Bytes.length b=16 then b else raise (Invalid_argument "trace IDs must be 16 bytes in length")
let to_hex self = Util_.bytes_to_hex self
let of_hex s = of_bytes (Util_.bytes_of_hex s)
end
@ -198,7 +198,7 @@ end = struct
type t = bytes
let to_bytes self = self
let create () : t = Collector.rand_bytes_8()
let of_bytes b = assert(Bytes.length b=8); b
let of_bytes b = if Bytes.length b=8 then b else raise (Invalid_argument "span IDs must be 8 bytes in length")
let to_hex self = Util_.bytes_to_hex self
let of_hex s = of_bytes (Util_.bytes_of_hex s)
end
@ -620,7 +620,6 @@ module Trace_context = struct
let consume expected ~offset ~or_ =
let len = String.length expected in
let* str, offset = blit ~offset ~len ~or_ in
(* Printf.printf "got %S\n%!" str; *)
if str = expected then Ok offset else Error or_
in
let offset = 0 in
@ -630,14 +629,14 @@ module Trace_context = struct
let* trace_id =
match Trace_id.of_hex trace_id with
| trace_id -> Ok trace_id
| exception Failure _ -> Error "Expected hex-encoded trace-id"
| exception Invalid_argument _ -> Error "Expected hex-encoded trace-id"
in
let* offset = consume "-" ~offset ~or_:"Expected delimiter" in
let* parent_id, offset = blit ~offset ~len:16 ~or_:"Expected 16-digit parent-id" in
let* parent_id =
match Span_id.of_hex parent_id with
| parent_id -> Ok parent_id
| exception Failure _ -> Error "Expected hex-encoded parent-id"
| exception Invalid_argument _ -> Error "Expected hex-encoded parent-id"
in
let* offset = consume "-" ~offset ~or_:"Expected delimiter" in
let* _flags, _offset = blit ~offset ~len:2 ~or_:"Expected 2-digit flags" in