Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save davidabram/627d06a0e1daefcac55f90435b445afe to your computer and use it in GitHub Desktop.

Select an option

Save davidabram/627d06a0e1daefcac55f90435b445afe to your computer and use it in GitHub Desktop.
phantom.ml
type mutable_
type immutable
type 'perm byte_buf = {
raw : bytes;
}
let create_mutable size : mutable_ byte_buf =
{ raw = Bytes.create size }
let get (type p) (buf : p byte_buf) (i : int) : char =
Bytes.get buf.raw i
let set (buf : mutable_ byte_buf) (i : int) (c : char) : unit =
Bytes.set buf.raw i c
let freeze (buf : mutable_ byte_buf) : immutable byte_buf =
{ raw = Bytes.copy buf.raw }
let unsafe_thaw (buf : immutable byte_buf) : mutable_ byte_buf =
{ raw = Bytes.copy buf.raw }
let print_first_char (type p) (buf : p byte_buf) : unit =
let c = get buf 0 in
Printf.printf "First char: %c\n" c
let overwrite_with_x (buf : mutable_ byte_buf) : unit =
for i = 0 to Bytes.length buf.raw - 1 do
set buf i 'x'
done
let to_upper_copy (buf : immutable byte_buf) : immutable byte_buf =
let copy = unsafe_thaw buf in
for i = 0 to Bytes.length copy.raw - 1 do
let c = get copy i in
set copy i (Char.uppercase_ascii c)
done;
freeze copy
let () =
let m = create_mutable 5 in
set m 0 'a';
print_first_char m;
overwrite_with_x m;
print_first_char m;
let i = freeze m in
print_first_char i;
let i_upper = to_upper_copy i in
print_first_char i_upper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment