experimental hashing with oxcaml
1(** Fast SHA256 hashing library with zero-copy C bindings. *)
2
3module Raw = struct
4 (** The SHA256 context type wrapping the C SHA256_CTX structure. *)
5 type t
6
7 (** External C functions *)
8 external create : unit -> t = "oxsha_create"
9
10 external update :
11 t ->
12 (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t ->
13 unit
14 = "oxsha_update"
15
16 external final : t -> bytes = "oxsha_final"
17
18 (** Convenience function: update with bytes *)
19 let update_bytes ctx data =
20 let len = Bytes.length data in
21 let ba = Bigarray.Array1.create Bigarray.char Bigarray.c_layout len in
22 for i = 0 to len - 1 do
23 Bigarray.Array1.unsafe_set ba i (Bytes.unsafe_get data i)
24 done;
25 update ctx ba
26
27 (** Convenience function: update with string *)
28 let update_string ctx data =
29 let len = String.length data in
30 let ba = Bigarray.Array1.create Bigarray.char Bigarray.c_layout len in
31 for i = 0 to len - 1 do
32 Bigarray.Array1.unsafe_set ba i (String.unsafe_get data i)
33 done;
34 update ctx ba
35
36 (** One-shot hash function for bigarrays *)
37 let hash data =
38 let ctx = create () in
39 update ctx data;
40 final ctx
41
42 (** One-shot hash function for bytes *)
43 let hash_bytes data =
44 let ctx = create () in
45 update_bytes ctx data;
46 final ctx
47
48 (** One-shot hash function for strings *)
49 let hash_string data =
50 let ctx = create () in
51 update_string ctx data;
52 final ctx
53end
54
55(** Re-export Raw module contents at top level *)
56include Raw