Skip to content

Commit

Permalink
assure of_bigarray can't create invalid cstructs
Browse files Browse the repository at this point in the history
breaks compatibility:
  * len and off can't point out outside of bigarray
  * if given, len is not clipped to size of the given bigarray
  • Loading branch information
pqwy committed Jul 21, 2014
1 parent 756750e commit 75f0ba1
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions lib/cstruct.ml
Expand Up @@ -29,18 +29,21 @@ type t = {
} with sexp

let of_bigarray ?(off=0) ?len buffer =
let dim = Bigarray.Array1.dim buffer in
let len =
match len with
|None -> Bigarray.Array1.dim buffer
|Some len -> min len (Bigarray.Array1.dim buffer)
in { buffer; off; len }
| None -> dim - off
| Some len -> len in
if off < 0 || len < 0 || off + len > dim then
raise (Invalid_argument "Cstruct.of_bigarray");
{ buffer; off; len }

let to_bigarray buffer =
Bigarray.Array1.sub buffer.buffer buffer.off buffer.len

let create len =
let ba = Bigarray.Array1.create Bigarray.char Bigarray.c_layout len in
of_bigarray ba
let buffer = Bigarray.(Array1.create char c_layout len) in
{ buffer ; len ; off = 0 }

let check_bounds t len =
Bigarray.Array1.dim t.buffer >= len
Expand Down

0 comments on commit 75f0ba1

Please sign in to comment.