upstream: https://github.com/mirage/mirage-crypto
at main 61 lines 1.8 kB view raw
1open OUnit2 2 3let prf, strf = Format.(fprintf, asprintf) 4let pp_map pp f ppf x = pp ppf (f x) 5let pp_diff pp ppf (a, b) = prf ppf "@[<v>want: %a@,have: %a@]" pp a pp b 6 7let of_hex ?(skip_ws = true) s = 8 let fold f acc str = 9 let st = ref acc in 10 String.iter (fun c -> st := f !st c) str; 11 !st 12 and digit c = 13 match c with 14 | '0' .. '9' -> int_of_char c - 0x30 15 | 'A' .. 'F' -> int_of_char c - 0x41 + 10 16 | 'a' .. 'f' -> int_of_char c - 0x61 + 10 17 | _ -> invalid_arg "bad character" 18 and is_space = function 19 | ' ' | '\012' | '\n' | '\r' | '\t' -> true 20 | _ -> false 21 in 22 let chars, leftover = 23 fold 24 (fun (chars, leftover) c -> 25 if skip_ws && is_space c then (chars, leftover) 26 else 27 let c = digit c in 28 match leftover with 29 | None -> (chars, Some (c lsl 4)) 30 | Some c' -> ((c' lor c) :: chars, None)) 31 ([], None) s 32 in 33 let chars = List.rev chars in 34 assert (leftover = None); 35 String.init (List.length chars) (fun i -> char_of_int (List.nth chars i)) 36 37let rec range a b = if a > b then [] else a :: range (succ a) b 38 39let rec times ~n f a = 40 if n > 0 then ( 41 ignore (f a); 42 times ~n:(pred n) f a) 43 44let pp_opt pp ppf = 45 Format.( 46 function 47 | Some x -> fprintf ppf "Some(%a)" pp x 48 | None -> fprintf ppf "None") 49 50let eq_opt eq a b = match (a, b) with Some x, Some y -> eq x y | _ -> false 51let pp_octets pp = pp (Ohex.pp_hexdump ()) 52 53let assert_oct_equal ?msg = 54 assert_equal ~cmp:String.equal ?msg ~pp_diff:(pp_octets pp_diff) 55 56let iter_list xs f = List.iter f xs 57let cases_of f = List.map @@ fun params -> test_case (f params) 58let any _ = true 59let vx = Ohex.decode 60let f1_eq ?msg f (a, b) _ = assert_oct_equal ?msg (f (vx a)) (vx b) 61let f2_eq ?msg f (a, b, c) = f1_eq ?msg (f (vx a)) (b, c)