Dataset Viewer
package_name
stringlengths 2
45
| version
stringclasses 292
values | license
stringclasses 49
values | homepage
stringclasses 344
values | dev_repo
stringclasses 342
values | file_type
stringclasses 6
values | file_path
stringlengths 6
151
| file_content
stringlengths 0
9.28M
|
|---|---|---|---|---|---|---|---|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
opam
|
base64-3.5.2/base64.opam
|
version: "3.5.2"
opam-version: "2.0"
maintainer: "[email protected]"
authors: [ "Thomas Gazagnaire"
"Anil Madhavapeddy" "Calascibetta Romain"
"Peter Zotov" ]
license: "ISC"
homepage: "https://github.com/mirage/ocaml-base64"
doc: "https://mirage.github.io/ocaml-base64/"
bug-reports: "https://github.com/mirage/ocaml-base64/issues"
dev-repo: "git+https://github.com/mirage/ocaml-base64.git"
synopsis: "Base64 encoding for OCaml"
description: """
Base64 is a group of similar binary-to-text encoding schemes that represent
binary data in an ASCII string format by translating it into a radix-64
representation. It is specified in RFC 4648.
"""
depends: [
"ocaml" {>= "4.07.0"}
"dune" {>= "2.3"}
"fmt" {with-test & >= "0.8.7"}
"bos" {with-test}
"rresult" {with-test}
"alcotest" {with-test}
]
build: [
["dune" "subst"] {dev}
["dune" "build" "-p" name "-j" jobs]
["dune" "runtest" "-p" name "-j" jobs] {with-test}
]
x-maintenance-intent: [ "(latest)" ]
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
ml
|
base64-3.5.2/bench/benchmarks.ml
|
module Old_version = struct
let default_alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
let uri_safe_alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
let padding = '='
let of_char ?(alphabet = default_alphabet) x =
if x = padding then 0 else String.index alphabet x
let to_char ?(alphabet = default_alphabet) x = alphabet.[x]
let decode ?alphabet input =
let length = String.length input in
let input =
if length mod 4 = 0
then input
else input ^ String.make (4 - (length mod 4)) padding in
let length = String.length input in
let words = length / 4 in
let padding =
match length with
| 0 -> 0
| _ when input.[length - 2] = padding -> 2
| _ when input.[length - 1] = padding -> 1
| _ -> 0 in
let output = Bytes.make ((words * 3) - padding) '\000' in
for i = 0 to words - 1 do
let a = of_char ?alphabet input.[(4 * i) + 0]
and b = of_char ?alphabet input.[(4 * i) + 1]
and c = of_char ?alphabet input.[(4 * i) + 2]
and d = of_char ?alphabet input.[(4 * i) + 3] in
let n = (a lsl 18) lor (b lsl 12) lor (c lsl 6) lor d in
let x = (n lsr 16) land 255
and y = (n lsr 8) land 255
and z = n land 255 in
Bytes.set output ((3 * i) + 0) (char_of_int x) ;
if i <> words - 1 || padding < 2
then Bytes.set output ((3 * i) + 1) (char_of_int y) ;
if i <> words - 1 || padding < 1
then Bytes.set output ((3 * i) + 2) (char_of_int z)
done ;
Bytes.unsafe_to_string output
let decode_opt ?alphabet input =
try Some (decode ?alphabet input) with Not_found -> None
let encode ?(pad = true) ?alphabet input =
let length = String.length input in
let words = (length + 2) / 3 (* rounded up *) in
let padding_len = if length mod 3 = 0 then 0 else 3 - (length mod 3) in
let output = Bytes.make (words * 4) '\000' in
let get i = if i >= length then 0 else int_of_char input.[i] in
for i = 0 to words - 1 do
let x = get ((3 * i) + 0)
and y = get ((3 * i) + 1)
and z = get ((3 * i) + 2) in
let n = (x lsl 16) lor (y lsl 8) lor z in
let a = (n lsr 18) land 63
and b = (n lsr 12) land 63
and c = (n lsr 6) land 63
and d = n land 63 in
Bytes.set output ((4 * i) + 0) (to_char ?alphabet a) ;
Bytes.set output ((4 * i) + 1) (to_char ?alphabet b) ;
Bytes.set output ((4 * i) + 2) (to_char ?alphabet c) ;
Bytes.set output ((4 * i) + 3) (to_char ?alphabet d)
done ;
for i = 1 to padding_len do
Bytes.set output (Bytes.length output - i) padding
done ;
if pad
then Bytes.unsafe_to_string output
else Bytes.sub_string output 0 (Bytes.length output - padding_len)
end
let random len =
let ic = open_in "/dev/urandom" in
let rs = Bytes.create len in
really_input ic rs 0 len ;
close_in ic ;
Bytes.unsafe_to_string rs
open Core
open Core_bench
let b64_encode_and_decode len =
let input = random len in
Staged.stage @@ fun () ->
let encoded = Base64.encode_exn input in
let _decoded = Base64.decode_exn encoded in
()
let old_encode_and_decode len =
let input = random len in
Staged.stage @@ fun () ->
let encoded = Old_version.encode input in
let _decoded = Old_version.decode encoded in
()
let args = [ 0; 10; 50; 100; 500; 1000; 2500; 5000 ]
let test_b64 =
Bench.Test.create_indexed ~name:"Base64" ~args b64_encode_and_decode
let test_old = Bench.Test.create_indexed ~name:"Old" ~args old_encode_and_decode
let command = Bench.make_command [ test_b64; test_old ]
let () = Command.run command
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
dune
|
base64-3.5.2/bench/dune
|
(executable
(name benchmarks)
(enabled_if
(= %{profile} benchmark))
(libraries base64 core_bench))
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
ml
|
base64-3.5.2/config/config.ml
|
let parse s = Scanf.sscanf s "%d.%d" (fun major minor -> (major, minor))
let () =
let version = parse Sys.ocaml_version in
if version >= (4, 7)
then print_string "unsafe_stable.ml"
else print_string "unsafe_pre407.ml"
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
dune
|
base64-3.5.2/config/dune
|
(executable
(name config))
(rule
(with-stdout-to
which-unsafe-file
(run ./config.exe)))
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
dune
|
base64-3.5.2/fuzz/dune
|
(executable
(name fuzz_rfc2045)
(enabled_if
(= %{profile} fuzz))
(modules fuzz_rfc2045)
(libraries astring crowbar fmt base64.rfc2045))
(executable
(name fuzz_rfc4648)
(enabled_if
(= %{profile} fuzz))
(modules fuzz_rfc4648)
(libraries astring crowbar fmt base64))
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
ml
|
base64-3.5.2/fuzz/fuzz_rfc2045.ml
|
open Crowbar
exception Encode_error of string
exception Decode_error of string
(** Pretty printers *)
let register_printer () =
Printexc.register_printer (function
| Encode_error err -> Some (Fmt.str "(Encoding error: %s)" err)
| Decode_error err -> Some (Fmt.str "(Decoding error: %s)" err)
| _ -> None)
let pp_chr =
let escaped = function ' ' .. '~' as c -> String.make 1 c | _ -> "." in
Fmt.using escaped Fmt.string
let pp_scalar :
type buffer.
get:(buffer -> int -> char) -> length:(buffer -> int) -> buffer Fmt.t =
fun ~get ~length ppf b ->
let l = length b in
for i = 0 to l / 16 do
Fmt.pf ppf "%08x: " (i * 16) ;
let j = ref 0 in
while !j < 16 do
if (i * 16) + !j < l
then Fmt.pf ppf "%02x" (Char.code @@ get b ((i * 16) + !j))
else Fmt.pf ppf " " ;
if !j mod 2 <> 0 then Fmt.pf ppf " " ;
incr j
done ;
Fmt.pf ppf " " ;
j := 0 ;
while !j < 16 do
if (i * 16) + !j < l
then Fmt.pf ppf "%a" pp_chr (get b ((i * 16) + !j))
else Fmt.pf ppf " " ;
incr j
done ;
Fmt.pf ppf "@\n"
done
let pp = pp_scalar ~get:String.get ~length:String.length
(** Encoding and decoding *)
let check_encode str =
let subs = Astring.String.cuts ~sep:"\r\n" str in
let check str =
if String.length str > 78
then raise (Encode_error "too long string returned") in
List.iter check subs ;
str
let encode input =
let buf = Buffer.create 80 in
let encoder = Base64_rfc2045.encoder (`Buffer buf) in
String.iter
(fun c ->
let ret = Base64_rfc2045.encode encoder (`Char c) in
match ret with `Ok -> () | _ -> assert false)
(* XXX(dinosaure): [`Partial] can never occur. *)
input ;
let encode = Base64_rfc2045.encode encoder `End in
match encode with
| `Ok -> Buffer.contents buf |> check_encode
| _ -> (* XXX(dinosaure): [`Partial] can never occur. *) assert false
let decode input =
let decoder = Base64_rfc2045.decoder (`String input) in
let rec go acc =
if Base64_rfc2045.decoder_dangerous decoder
then raise (Decode_error "Dangerous input") ;
match Base64_rfc2045.decode decoder with
| `End -> List.rev acc
| `Flush output -> go (output :: acc)
| `Malformed _ -> raise (Decode_error "Malformed")
| `Wrong_padding -> raise (Decode_error "Wrong padding")
| _ -> (* XXX(dinosaure): [`Await] can never occur. *) assert false in
String.concat "" (go [])
(** String generators *)
let bytes_fixed_range : string gen = dynamic_bind (range 78) bytes_fixed
let char_from_alpha alpha : string gen =
map [ range (String.length alpha) ] (fun i -> alpha.[i] |> String.make 1)
let string_from_alpha n =
let acc = const "" in
let alpha = Base64_rfc2045.default_alphabet in
let rec add_char_from_alpha alpha acc = function
| 0 -> acc
| n ->
add_char_from_alpha alpha
(concat_gen_list (const "") [ acc; char_from_alpha alpha ])
(n - 1) in
add_char_from_alpha alpha acc n
let random_string_from_alpha n = dynamic_bind (range n) string_from_alpha
let bytes_fixed_range_from_alpha : string gen =
dynamic_bind (range 78) bytes_fixed
let set_canonic str =
let l = String.length str in
let to_drop = l * 6 mod 8 in
if to_drop = 6
(* XXX(clecat): Case when we need to drop 6 bits which means a whole letter *)
then String.sub str 0 (l - 1)
else if to_drop <> 0
(* XXX(clecat): Case when we need to drop 2 or 4 bits: we apply a mask droping the bits *)
then (
let buf = Bytes.of_string str in
let value =
String.index Base64_rfc2045.default_alphabet (Bytes.get buf (l - 1)) in
let canonic =
Base64_rfc2045.default_alphabet.[value land lnot ((1 lsl to_drop) - 1)]
in
Bytes.set buf (l - 1) canonic ;
Bytes.unsafe_to_string buf)
else str
let add_padding str =
let str = set_canonic str in
let str = str ^ "===" in
String.sub str 0 (String.length str / 4 * 4)
(** Tests *)
let e2d inputs =
let input = String.concat "\r\n" inputs in
let encode = encode input in
let decode = decode encode in
check_eq ~pp ~cmp:String.compare ~eq:String.equal input decode
let d2e inputs end_input =
let end_input = add_padding end_input in
let inputs = inputs @ [ end_input ] in
let input =
List.fold_left
(fun acc s -> if String.length s <> 0 then acc ^ "\r\n" ^ s else acc)
(List.hd inputs) (List.tl inputs) in
let decode = decode input in
let encode = encode decode in
check_eq ~pp ~cmp:String.compare ~eq:String.equal input encode
let () =
register_printer () ;
add_test ~name:"rfc2045: encode -> decode" [ list bytes_fixed_range ] e2d ;
add_test ~name:"rfc2045: decode -> encode"
[ list (string_from_alpha 76); random_string_from_alpha 76 ]
d2e
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
ml
|
base64-3.5.2/fuzz/fuzz_rfc4648.ml
|
open Crowbar
let pp_chr =
let escaped = function ' ' .. '~' as c -> String.make 1 c | _ -> "." in
Fmt.using escaped Fmt.string
let pp_scalar :
type buffer.
get:(buffer -> int -> char) -> length:(buffer -> int) -> buffer Fmt.t =
fun ~get ~length ppf b ->
let l = length b in
for i = 0 to l / 16 do
Fmt.pf ppf "%08x: " (i * 16) ;
let j = ref 0 in
while !j < 16 do
if (i * 16) + !j < l
then Fmt.pf ppf "%02x" (Char.code @@ get b ((i * 16) + !j))
else Fmt.pf ppf " " ;
if !j mod 2 <> 0 then Fmt.pf ppf " " ;
incr j
done ;
Fmt.pf ppf " " ;
j := 0 ;
while !j < 16 do
if (i * 16) + !j < l
then Fmt.pf ppf "%a" pp_chr (get b ((i * 16) + !j))
else Fmt.pf ppf " " ;
incr j
done ;
Fmt.pf ppf "@\n"
done
let pp = pp_scalar ~get:String.get ~length:String.length
let ( <.> ) f g x = f (g x)
let char_from_alphabet alphabet : string gen =
map [ range 64 ] (String.make 1 <.> String.get (Base64.alphabet alphabet))
let random_string_from_alphabet alphabet len : string gen =
let rec add_char_from_alphabet acc = function
| 0 -> acc
| n ->
add_char_from_alphabet
(concat_gen_list (const "") [ acc; char_from_alphabet alphabet ])
(n - 1) in
add_char_from_alphabet (const "") len
let random_string_from_alphabet ~max alphabet =
dynamic_bind (range max) @@ fun real_len ->
dynamic_bind (random_string_from_alphabet alphabet real_len) @@ fun input ->
if real_len <= 1
then const (input, 0, real_len)
else
dynamic_bind (range (real_len / 2)) @@ fun off ->
map [ range (real_len - off) ] (fun len -> (input, off, len))
let encode_and_decode (input, off, len) =
match Base64.encode ~pad:true ~off ~len input with
| Error (`Msg err) -> fail err
| Ok result ->
match Base64.decode ~pad:true result with
| Error (`Msg err) -> fail err
| Ok result ->
check_eq ~pp ~cmp:String.compare ~eq:String.equal result
(String.sub input off len)
let decode_and_encode (input, off, len) =
match Base64.decode ~pad:true ~off ~len input with
| Error (`Msg err) -> fail err
| Ok result ->
match Base64.encode ~pad:true result with
| Error (`Msg err) -> fail err
| Ok result ->
check_eq ~pp:Fmt.string ~cmp:String.compare ~eq:String.equal result
(String.sub input off len)
let ( // ) x y =
if y < 1 then raise Division_by_zero ;
if x > 0 then 1 + ((x - 1) / y) else 0
[@@inline]
let canonic alphabet =
let dmap = Array.make 256 (-1) in
String.iteri (fun i x -> dmap.(Char.code x) <- i) (Base64.alphabet alphabet) ;
fun (input, off, len) ->
let real_len = String.length input in
let input_len = len in
let normalized_len = input_len // 4 * 4 in
if normalized_len = input_len
then (input, off, input_len)
else if normalized_len - input_len = 3
then (input, off, input_len - 1)
else
let remainder_len = normalized_len - input_len in
let last = input.[off + input_len - 1] in
let output = Bytes.make (max real_len (off + normalized_len)) '=' in
Bytes.blit_string input 0 output 0 (off + input_len) ;
if off + normalized_len < real_len
then
Bytes.blit_string input (off + normalized_len) output
(off + normalized_len)
(real_len - (off + normalized_len)) ;
let mask =
match remainder_len with 1 -> 0x3c | 2 -> 0x30 | _ -> assert false in
let decoded = dmap.(Char.code last) in
let canonic = decoded land mask in
let encoded = (Base64.alphabet alphabet).[canonic] in
Bytes.set output (off + input_len - 1) encoded ;
(Bytes.unsafe_to_string output, off, normalized_len)
let isomorphism0 (input, off, len) =
(* x0 = decode(input) && x1 = decode(encode(x0)) && x0 = x1 *)
match Base64.decode ~pad:false ~off ~len input with
| Error (`Msg err) -> fail err
| Ok result0 -> (
let result1 = Base64.encode_exn result0 in
match Base64.decode ~pad:true result1 with
| Error (`Msg err) -> fail err
| Ok result2 ->
check_eq ~pp ~cmp:String.compare ~eq:String.equal result0 result2)
let isomorphism1 (input, off, len) =
let result0 = Base64.encode_exn ~off ~len input in
match Base64.decode ~pad:true result0 with
| Error (`Msg err) -> fail err
| Ok result1 ->
let result2 = Base64.encode_exn result1 in
check_eq ~pp:Fmt.string ~cmp:String.compare ~eq:String.equal result0
result2
let bytes_and_range : (string * int * int) gen =
dynamic_bind bytes @@ fun t ->
let real_length = String.length t in
if real_length <= 1
then const (t, 0, real_length)
else
dynamic_bind (range (real_length / 2)) @@ fun off ->
map [ range (real_length - off) ] (fun len -> (t, off, len))
let range_of_max max : (int * int) gen =
dynamic_bind (range (max / 2)) @@ fun off ->
map [ range (max - off) ] (fun len -> (off, len))
let failf fmt = Fmt.kstr fail fmt
let no_exception pad off len input =
try
let _ =
Base64.decode ?pad ?off ?len ~alphabet:Base64.default_alphabet input in
()
with exn -> failf "decode fails with: %s." (Printexc.to_string exn)
let () =
add_test ~name:"rfc4648: encode -> decode" [ bytes_and_range ]
encode_and_decode ;
add_test ~name:"rfc4648: decode -> encode"
[ random_string_from_alphabet ~max:1000 Base64.default_alphabet ]
(decode_and_encode <.> canonic Base64.default_alphabet) ;
add_test ~name:"rfc4648: x = decode(encode(x))"
[ random_string_from_alphabet ~max:1000 Base64.default_alphabet ]
isomorphism0 ;
add_test ~name:"rfc4648: x = encode(decode(x))" [ bytes_and_range ]
isomorphism1 ;
add_test ~name:"rfc4648: no exception leak"
[ option bool; option int; option int; bytes ]
no_exception
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
ml
|
base64-3.5.2/src/base64.ml
|
(*
* Copyright (c) 2006-2009 Citrix Systems Inc.
* Copyright (c) 2010 Thomas Gazagnaire <[email protected]>
* Copyright (c) 2014-2016 Anil Madhavapeddy <[email protected]>
* Copyright (c) 2016 David Kaloper Meršinjak
* Copyright (c) 2018 Romain Calascibetta <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
type alphabet = { emap : int array; dmap : int array }
type sub = string * int * int
let ( // ) x y =
if y < 1 then raise Division_by_zero ;
if x > 0 then 1 + ((x - 1) / y) else 0
[@@inline]
let unsafe_get_uint8 t off = Char.code (String.unsafe_get t off)
let unsafe_set_uint8 t off v = Bytes.unsafe_set t off (Char.chr v)
external unsafe_set_uint16 : bytes -> int -> int -> unit = "%caml_bytes_set16u"
[@@noalloc]
external unsafe_get_uint16 : string -> int -> int = "%caml_string_get16u"
[@@noalloc]
external swap16 : int -> int = "%bswap16" [@@noalloc]
let none = -1
(* We mostly want to have an optional array for [dmap] (e.g. [int option
array]). So we consider the [none] value as [-1]. *)
let make_alphabet alphabet =
if String.length alphabet <> 64
then invalid_arg "Length of alphabet must be 64" ;
if String.contains alphabet '='
then invalid_arg "Alphabet can not contain padding character" ;
let emap =
Array.init (String.length alphabet) (fun i -> Char.code alphabet.[i]) in
let dmap = Array.make 256 none in
String.iteri (fun idx chr -> dmap.(Char.code chr) <- idx) alphabet ;
{ emap; dmap }
let length_alphabet { emap; _ } = Array.length emap
let alphabet { emap; _ } =
String.init (Array.length emap) (fun i -> Char.chr emap.(i))
let default_alphabet =
make_alphabet
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
let uri_safe_alphabet =
make_alphabet
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
let unsafe_set_be_uint16 =
if Sys.big_endian
then fun t off v -> unsafe_set_uint16 t off v
else fun t off v -> unsafe_set_uint16 t off (swap16 v)
(* We make this exception to ensure to keep a control about which exception we
can raise and avoid appearance of unknown exceptions like an ex-nihilo
magic rabbit (or magic money?). *)
exception Out_of_bounds
exception Too_much_input
let get_uint8 t off =
if off < 0 || off >= String.length t then raise Out_of_bounds ;
unsafe_get_uint8 t off
let padding = int_of_char '='
let error_msgf fmt = Format.ksprintf (fun err -> Error (`Msg err)) fmt
let encode_sub pad { emap; _ } ?(off = 0) ?len input =
let len =
match len with Some len -> len | None -> String.length input - off in
if len < 0 || off < 0 || off > String.length input - len
then error_msgf "Invalid bounds"
else
let n = len in
let n' = n // 3 * 4 in
let res = Bytes.create n' in
let emap i = Array.unsafe_get emap i in
let emit b1 b2 b3 i =
unsafe_set_be_uint16 res i
((emap ((b1 lsr 2) land 0x3f) lsl 8)
lor emap ((b1 lsl 4) lor (b2 lsr 4) land 0x3f)) ;
unsafe_set_be_uint16 res (i + 2)
((emap ((b2 lsl 2) lor (b3 lsr 6) land 0x3f) lsl 8)
lor emap (b3 land 0x3f)) in
let rec enc j i =
if i = n
then ()
else if i = n - 1
then emit (unsafe_get_uint8 input (off + i)) 0 0 j
else if i = n - 2
then
emit
(unsafe_get_uint8 input (off + i))
(unsafe_get_uint8 input (off + i + 1))
0 j
else (
emit
(unsafe_get_uint8 input (off + i))
(unsafe_get_uint8 input (off + i + 1))
(unsafe_get_uint8 input (off + i + 2))
j ;
enc (j + 4) (i + 3)) in
let rec unsafe_fix = function
| 0 -> ()
| i ->
unsafe_set_uint8 res (n' - i) padding ;
unsafe_fix (i - 1) in
enc 0 0 ;
let pad_to_write = (3 - (n mod 3)) mod 3 in
if pad
then (
unsafe_fix pad_to_write ;
Ok (Bytes.unsafe_to_string res, 0, n'))
else Ok (Bytes.unsafe_to_string res, 0, n' - pad_to_write)
(* [pad = false], we don't want to write them. *)
let encode ?(pad = true) ?(alphabet = default_alphabet) ?off ?len input =
match encode_sub pad alphabet ?off ?len input with
| Ok (res, off, len) -> Ok (String.sub res off len)
| Error _ as err -> err
let encode_string ?pad ?alphabet input =
match encode ?pad ?alphabet input with
| Ok res -> res
| Error _ -> assert false
let encode_sub ?(pad = true) ?(alphabet = default_alphabet) ?off ?len input =
encode_sub pad alphabet ?off ?len input
let encode_exn ?pad ?alphabet ?off ?len input =
match encode ?pad ?alphabet ?off ?len input with
| Ok v -> v
| Error (`Msg err) -> invalid_arg err
let decode_sub ?(pad = true) { dmap; _ } ?(off = 0) ?len input =
let len =
match len with Some len -> len | None -> String.length input - off in
if len < 0 || off < 0 || off > String.length input - len
then error_msgf "Invalid bounds"
else
let n = len // 4 * 4 in
let n' = n // 4 * 3 in
let res = Bytes.create n' in
let invalid_pad_overflow = pad in
let get_uint8_or_padding =
if pad
then (fun t i ->
if i >= len then raise Out_of_bounds ;
get_uint8 t (off + i))
else
fun t i ->
try if i < len then get_uint8 t (off + i) else padding
with Out_of_bounds -> padding in
let set_be_uint16 t off v =
(* can not write 2 bytes. *)
if off < 0 || off + 1 > Bytes.length t
then () (* can not write 1 byte but can write 1 byte *)
else if off < 0 || off + 2 > Bytes.length t
then unsafe_set_uint8 t off (v lsr 8) (* can write 2 bytes. *)
else unsafe_set_be_uint16 t off v in
let set_uint8 t off v =
if off < 0 || off >= Bytes.length t then () else unsafe_set_uint8 t off v
in
let emit a b c d j =
let x = (a lsl 18) lor (b lsl 12) lor (c lsl 6) lor d in
set_be_uint16 res j (x lsr 8) ;
set_uint8 res (j + 2) (x land 0xff) in
let dmap i =
let x = Array.unsafe_get dmap i in
if x = none then raise Not_found ;
x in
let only_padding pad idx =
(* because we round length of [res] to the upper bound of how many
characters we should have from [input], we got at this stage only padding
characters and we need to delete them, so for each [====], we delete 3
bytes. *)
let pad = ref (pad + 3) in
let idx = ref idx in
while !idx + 4 < len do
(* use [unsafe_get_uint16] instead [unsafe_get_uint32] to avoid allocation
of [int32]. Of course, [3d3d3d3d] is [====]. *)
if unsafe_get_uint16 input (off + !idx) <> 0x3d3d
|| unsafe_get_uint16 input (off + !idx + 2) <> 0x3d3d
then raise Not_found ;
(* We got something bad, should be a valid character according to
[alphabet] but outside the scope. *)
idx := !idx + 4 ;
pad := !pad + 3
done ;
while !idx < len do
if unsafe_get_uint8 input (off + !idx) <> padding then raise Not_found ;
incr idx
done ;
!pad in
let rec dec j i =
if i = n
then 0
else
let d, pad =
let x = get_uint8_or_padding input (i + 3) in
try (dmap x, 0) with Not_found when x = padding -> (0, 1) in
(* [Not_found] iff [x ∉ alphabet and x <> '='] can leak. *)
let c, pad =
let x = get_uint8_or_padding input (i + 2) in
try (dmap x, pad)
with Not_found when x = padding && pad = 1 -> (0, 2) in
(* [Not_found] iff [x ∉ alphabet and x <> '='] can leak. *)
let b, pad =
let x = get_uint8_or_padding input (i + 1) in
try (dmap x, pad)
with Not_found when x = padding && pad = 2 -> (0, 3) in
(* [Not_found] iff [x ∉ alphabet and x <> '='] can leak. *)
let a, pad =
let x = get_uint8_or_padding input i in
try (dmap x, pad)
with Not_found when x = padding && pad = 3 -> (0, 4) in
(* [Not_found] iff [x ∉ alphabet and x <> '='] can leak. *)
emit a b c d j ;
if i + 4 = n (* end of input in anyway *)
then
match pad with
| 0 -> 0
| 4 ->
(* assert (invalid_pad_overflow = false) ; *)
3
(* [get_uint8] lies and if we get [4], that mean we got one or more (at
most 4) padding character. In this situation, because we round length
of [res] (see [n // 4]), we need to delete 3 bytes. *)
| pad -> pad
else
match pad with
| 0 -> dec (j + 3) (i + 4)
| 4 ->
(* assert (invalid_pad_overflow = false) ; *)
only_padding 3 (i + 4)
(* Same situation than above but we should get only more padding
characters then. *)
| pad ->
if invalid_pad_overflow = true then raise Too_much_input ;
only_padding pad (i + 4) in
match dec 0 0 with
| 0 -> Ok (Bytes.unsafe_to_string res, 0, n')
| pad -> Ok (Bytes.unsafe_to_string res, 0, n' - pad)
| exception Out_of_bounds ->
error_msgf "Wrong padding"
(* appear only when [pad = true] and when length of input is not a multiple of 4. *)
| exception Not_found ->
(* appear when one character of [input] ∉ [alphabet] and this character <> '=' *)
error_msgf "Malformed input"
| exception Too_much_input -> error_msgf "Too much input"
let decode ?pad ?(alphabet = default_alphabet) ?off ?len input =
match decode_sub ?pad alphabet ?off ?len input with
| Ok (res, off, len) -> Ok (String.sub res off len)
| Error _ as err -> err
let decode_sub ?pad ?(alphabet = default_alphabet) ?off ?len input =
decode_sub ?pad alphabet ?off ?len input
let decode_exn ?pad ?alphabet ?off ?len input =
match decode ?pad ?alphabet ?off ?len input with
| Ok res -> res
| Error (`Msg err) -> invalid_arg err
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
mli
|
base64-3.5.2/src/base64.mli
|
(*
* Copyright (c) 2006-2009 Citrix Systems Inc.
* Copyright (c) 2010 Thomas Gazagnaire <[email protected]>
* Copyright (c) 2014-2016 Anil Madhavapeddy <[email protected]>
* Copyright (c) 2018 Romain Calascibetta <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
(** Base64 RFC4648 implementation.
Base64 is a group of similar binary-to-text encoding schemes that represent
binary data in an ASCII string format by translating it into a radix-64
representation. It is specified in RFC 4648.
{e Release v3.5.2 - https://github.com/mirage/ocaml-base64} *)
type alphabet
(** Type of alphabet. *)
type sub = string * int * int
(** Type of sub-string: [str, off, len]. *)
val default_alphabet : alphabet
(** A 64-character alphabet specifying the regular Base64 alphabet. *)
val uri_safe_alphabet : alphabet
(** A 64-character alphabet specifying the URI- and filename-safe Base64
alphabet. *)
val make_alphabet : string -> alphabet
(** Make a new alphabet. *)
val length_alphabet : alphabet -> int
(** Returns length of the alphabet, should be 64. *)
val alphabet : alphabet -> string
(** Returns the alphabet. *)
val decode_exn :
?pad:bool -> ?alphabet:alphabet -> ?off:int -> ?len:int -> string -> string
(** [decode_exn ?off ?len s] decodes [len] bytes (defaults to
[String.length s - off]) of the string [s] starting from [off] (defaults to
[0]) that is encoded in Base64 format. Will leave trailing NULLs on the
string, padding it out to a multiple of 3 characters. [alphabet] defaults to
{!default_alphabet}. [pad = true] specifies to check if [s] is padded or
not, otherwise, it raises an exception.
Decoder can fail when character of [s] is not a part of [alphabet] or is not
[padding] character. If input is not padded correctly, decoder does the
best-effort but it does not ensure [decode_exn (encode ~pad:false x) = x].
@raise if Invalid_argument [s] is not a valid Base64 string. *)
val decode_sub :
?pad:bool ->
?alphabet:alphabet ->
?off:int ->
?len:int ->
string ->
(sub, [> `Msg of string ]) result
(** Same as {!decode_exn} but it returns a result type instead to raise an
exception. Then, it returns a {!sub} string. Decoded input [(str, off, len)]
will starting to [off] and will have [len] bytes - by this way, we ensure to
allocate only one time result. *)
val decode :
?pad:bool ->
?alphabet:alphabet ->
?off:int ->
?len:int ->
string ->
(string, [> `Msg of string ]) result
(** Same as {!decode_exn}, but returns an explicit error message {!result} if it
fails. *)
val encode :
?pad:bool ->
?alphabet:alphabet ->
?off:int ->
?len:int ->
string ->
(string, [> `Msg of string ]) result
(** [encode s] encodes the string [s] into base64. If [pad] is false, no
trailing padding is added. [pad] defaults to [true], and [alphabet] to
{!default_alphabet}.
[encode] fails when [off] and [len] do not designate a valid range of [s]. *)
val encode_string : ?pad:bool -> ?alphabet:alphabet -> string -> string
(** [encode_string s] encodes the string [s] into base64. If [pad] is false, no
trailing padding is added. [pad] defaults to [true], and [alphabet] to
{!default_alphabet}. *)
val encode_sub :
?pad:bool ->
?alphabet:alphabet ->
?off:int ->
?len:int ->
string ->
(sub, [> `Msg of string ]) result
(** Same as {!encode} but return a {!sub}-string instead a plain result. By this
way, we ensure to allocate only one time result. *)
val encode_exn :
?pad:bool -> ?alphabet:alphabet -> ?off:int -> ?len:int -> string -> string
(** Same as {!encode} but raises an invalid argument exception if we retrieve an
error. *)
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
ml
|
base64-3.5.2/src/base64_rfc2045.ml
|
(*
* Copyright (c) 2018 Romain Calascibetta <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
let default_alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
let io_buffer_size = 65536
let invalid_arg fmt = Format.ksprintf (fun s -> invalid_arg s) fmt
let invalid_bounds off len =
invalid_arg "Invalid bounds (off: %d, len: %d)" off len
let malformed chr = `Malformed (String.make 1 chr)
let unsafe_byte source off pos = Bytes.unsafe_get source (off + pos)
let unsafe_blit = Bytes.unsafe_blit
let unsafe_chr = Char.unsafe_chr
let unsafe_set_chr source off chr = Bytes.unsafe_set source off chr
type state = { quantum : int; size : int; buffer : Bytes.t }
let continue state (quantum, size) = `Continue { state with quantum; size }
let flush state = `Flush { state with quantum = 0; size = 0 }
let table =
"\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\062\255\255\255\063\052\053\054\055\056\057\058\059\060\061\255\255\255\255\255\255\255\000\001\002\003\004\005\006\007\008\009\010\011\012\013\014\015\016\017\018\019\020\021\022\023\024\025\255\255\255\255\255\255\026\027\028\029\030\031\032\033\034\035\036\037\038\039\040\041\042\043\044\045\046\047\048\049\050\051\255\255\255\255\255"
let r_repr ({ quantum; size; _ } as state) chr =
(* assert (0 <= off && 0 <= len && off + len <= String.length source); *)
(* assert (len >= 1); *)
let code = Char.code table.[Char.code chr] in
match size with
| 0 -> continue state (code, 1)
| 1 -> continue state ((quantum lsl 6) lor code, 2)
| 2 -> continue state ((quantum lsl 6) lor code, 3)
| 3 ->
unsafe_set_chr state.buffer 0 (unsafe_chr ((quantum lsr 10) land 255)) ;
unsafe_set_chr state.buffer 1 (unsafe_chr ((quantum lsr 2) land 255)) ;
unsafe_set_chr state.buffer 2
(unsafe_chr ((quantum lsl 6) lor code land 255)) ;
flush state
| _ -> malformed chr
type src = [ `Channel of in_channel | `String of string | `Manual ]
type decode =
[ `Await | `End | `Wrong_padding | `Malformed of string | `Flush of string ]
type input =
[ `Line_break | `Wsp | `Padding | `Malformed of string | `Flush of state ]
type decoder = {
src : src;
mutable i : Bytes.t;
mutable i_off : int;
mutable i_pos : int;
mutable i_len : int;
mutable s : state;
mutable padding : int;
mutable unsafe : bool;
mutable byte_count : int;
mutable limit_count : int;
mutable pp : decoder -> input -> decode;
mutable k : decoder -> decode;
}
let i_rem decoder = decoder.i_len - decoder.i_pos + 1
let end_of_input decoder =
decoder.i <- Bytes.empty ;
decoder.i_off <- 0 ;
decoder.i_pos <- 0 ;
decoder.i_len <- min_int
let src decoder source off len =
if off < 0 || len < 0 || off + len > Bytes.length source
then invalid_bounds off len
else if len = 0
then end_of_input decoder
else (
decoder.i <- source ;
decoder.i_off <- off ;
decoder.i_pos <- 0 ;
decoder.i_len <- len - 1)
let refill k decoder =
match decoder.src with
| `Manual ->
decoder.k <- k ;
`Await
| `String _ ->
end_of_input decoder ;
k decoder
| `Channel ic ->
let len = input ic decoder.i 0 (Bytes.length decoder.i) in
src decoder decoder.i 0 len ;
k decoder
let dangerous decoder v = decoder.unsafe <- v
let reset decoder = decoder.limit_count <- 0
let ret k v byte_count decoder =
decoder.k <- k ;
decoder.byte_count <- decoder.byte_count + byte_count ;
decoder.limit_count <- decoder.limit_count + byte_count ;
if decoder.limit_count > 78 then dangerous decoder true ;
decoder.pp decoder v
type flush_and_malformed = [ `Flush of state | `Malformed of string ]
let padding { size; _ } padding =
match (size, padding) with
| 0, 0 -> true
| 1, _ -> false
| 2, 2 -> true
| 3, 1 -> true
| _ -> false
let t_flush { quantum; size; buffer } =
match size with
| 0 | 1 -> `Flush { quantum; size; buffer = Bytes.empty }
| 2 ->
let quantum = quantum lsr 4 in
`Flush
{ quantum; size; buffer = Bytes.make 1 (unsafe_chr (quantum land 255)) }
| 3 ->
let quantum = quantum lsr 2 in
unsafe_set_chr buffer 0 (unsafe_chr ((quantum lsr 8) land 255)) ;
unsafe_set_chr buffer 1 (unsafe_chr (quantum land 255)) ;
`Flush { quantum; size; buffer = Bytes.sub buffer 0 2 }
| _ -> assert false
(* this branch is impossible, size can only ever be in the range [0..3]. *)
let wrong_padding decoder =
let k _ = `End in
decoder.k <- k ;
`Wrong_padding
let rec t_decode_base64 chr decoder =
if decoder.padding = 0
then
let rec go pos = function
| `Continue state ->
if decoder.i_len - (decoder.i_pos + pos) + 1 > 0
then (
match unsafe_byte decoder.i decoder.i_off (decoder.i_pos + pos) with
| ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '+' | '/') as chr ->
go (succ pos) (r_repr state chr)
| '=' ->
decoder.padding <- decoder.padding + 1 ;
decoder.i_pos <- decoder.i_pos + pos + 1 ;
decoder.s <- state ;
ret decode_base64 `Padding (pos + 1) decoder
| ' ' | '\t' ->
decoder.i_pos <- decoder.i_pos + pos + 1 ;
decoder.s <- state ;
ret decode_base64 `Wsp (pos + 1) decoder
| '\r' ->
decoder.i_pos <- decoder.i_pos + pos + 1 ;
decoder.s <- state ;
decode_base64_lf_after_cr decoder
| chr ->
decoder.i_pos <- decoder.i_pos + pos + 1 ;
decoder.s <- state ;
ret decode_base64 (malformed chr) (pos + 1) decoder)
else (
decoder.i_pos <- decoder.i_pos + pos ;
decoder.byte_count <- decoder.byte_count + pos ;
decoder.limit_count <- decoder.limit_count + pos ;
decoder.s <- state ;
refill decode_base64 decoder)
| #flush_and_malformed as v ->
decoder.i_pos <- decoder.i_pos + pos ;
ret decode_base64 v pos decoder in
go 1 (r_repr decoder.s chr)
else (
decoder.i_pos <- decoder.i_pos + 1 ;
ret decode_base64 (malformed chr) 1 decoder)
and decode_base64_lf_after_cr decoder =
let rem = i_rem decoder in
if rem < 0
then ret decode_base64 (malformed '\r') 1 decoder
else if rem = 0
then refill decode_base64_lf_after_cr decoder
else
match unsafe_byte decoder.i decoder.i_off decoder.i_pos with
| '\n' ->
decoder.i_pos <- decoder.i_pos + 1 ;
ret decode_base64 `Line_break 2 decoder
| _ -> ret decode_base64 (malformed '\r') 1 decoder
and decode_base64 decoder =
let rem = i_rem decoder in
if rem <= 0
then
if rem < 0
then
ret
(fun decoder ->
if padding decoder.s decoder.padding
then `End
else wrong_padding decoder)
(t_flush decoder.s) 0 decoder
else refill decode_base64 decoder
else
match unsafe_byte decoder.i decoder.i_off decoder.i_pos with
| ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '+' | '/') as chr ->
t_decode_base64 chr decoder
| '=' ->
decoder.padding <- decoder.padding + 1 ;
decoder.i_pos <- decoder.i_pos + 1 ;
ret decode_base64 `Padding 1 decoder
| ' ' | '\t' ->
decoder.i_pos <- decoder.i_pos + 1 ;
ret decode_base64 `Wsp 1 decoder
| '\r' ->
decoder.i_pos <- decoder.i_pos + 1 ;
decode_base64_lf_after_cr decoder
| chr ->
decoder.i_pos <- decoder.i_pos + 1 ;
ret decode_base64 (malformed chr) 1 decoder
let pp_base64 decoder = function
| `Line_break ->
reset decoder ;
decoder.k decoder
| `Wsp | `Padding -> decoder.k decoder
| `Flush state ->
decoder.s <- state ;
`Flush (Bytes.to_string state.buffer)
| `Malformed _ as v -> v
let decoder src =
let pp = pp_base64 in
let k = decode_base64 in
let i, i_off, i_pos, i_len =
match src with
| `Manual -> (Bytes.empty, 0, 1, 0)
| `Channel _ -> (Bytes.create io_buffer_size, 0, 1, 0)
| `String s -> (Bytes.unsafe_of_string s, 0, 0, String.length s - 1) in
{
src;
i_off;
i_pos;
i_len;
i;
s = { quantum = 0; size = 0; buffer = Bytes.create 3 };
padding = 0;
unsafe = false;
byte_count = 0;
limit_count = 0;
pp;
k;
}
let decode decoder = decoder.k decoder
let decoder_byte_count decoder = decoder.byte_count
let decoder_src decoder = decoder.src
let decoder_dangerous decoder = decoder.unsafe
(* / *)
let invalid_encode () = invalid_arg "Expected `Await encode"
type dst = [ `Channel of out_channel | `Buffer of Buffer.t | `Manual ]
type encode = [ `Await | `End | `Char of char ]
type encoder = {
dst : dst;
mutable o : Bytes.t;
mutable o_off : int;
mutable o_pos : int;
mutable o_len : int;
mutable c_col : int;
i : Bytes.t;
mutable s : int;
t : Bytes.t;
mutable t_pos : int;
mutable t_len : int;
mutable k : encoder -> encode -> [ `Ok | `Partial ];
}
let o_rem encoder = encoder.o_len - encoder.o_pos + 1
let dst encoder source off len =
if off < 0 || len < 0 || off + len > Bytes.length source
then invalid_bounds off len ;
encoder.o <- source ;
encoder.o_off <- off ;
encoder.o_pos <- 0 ;
encoder.o_len <- len - 1
let dst_rem = o_rem
let partial k encoder = function
| `Await -> k encoder
| `Char _ | `End -> invalid_encode ()
let flush k encoder =
match encoder.dst with
| `Manual ->
encoder.k <- partial k ;
`Partial
| `Channel oc ->
output oc encoder.o encoder.o_off encoder.o_pos ;
encoder.o_pos <- 0 ;
k encoder
| `Buffer b ->
let o = Bytes.unsafe_to_string encoder.o in
Buffer.add_substring b o encoder.o_off encoder.o_pos ;
encoder.o_pos <- 0 ;
k encoder
let t_range encoder len =
encoder.t_pos <- 0 ;
encoder.t_len <- len
let rec t_flush k encoder =
let blit encoder len =
unsafe_blit encoder.t encoder.t_pos encoder.o encoder.o_pos len ;
encoder.o_pos <- encoder.o_pos + len ;
encoder.t_pos <- encoder.t_pos + len in
let rem = o_rem encoder in
let len = encoder.t_len - encoder.t_pos + 1 in
if rem < len
then (
blit encoder rem ;
flush (t_flush k) encoder)
else (
blit encoder len ;
k encoder)
let rec encode_line_break k encoder =
let rem = o_rem encoder in
let s, j, k =
if rem < 2
then (
t_range encoder 2 ;
(encoder.t, 0, t_flush k))
else
let j = encoder.o_pos in
encoder.o_pos <- encoder.o_pos + 2 ;
(encoder.o, encoder.o_off + j, k) in
unsafe_set_chr s j '\r' ;
unsafe_set_chr s (j + 1) '\n' ;
encoder.c_col <- 0 ;
k encoder
and encode_char chr k (encoder : encoder) =
if encoder.s >= 2
then (
let a, b, c = (unsafe_byte encoder.i 0 0, unsafe_byte encoder.i 0 1, chr) in
encoder.s <- 0 ;
let quantum = (Char.code a lsl 16) + (Char.code b lsl 8) + Char.code c in
let a = quantum lsr 18 in
let b = (quantum lsr 12) land 63 in
let c = (quantum lsr 6) land 63 in
let d = quantum land 63 in
let rem = o_rem encoder in
let s, j, k =
if rem < 4
then (
t_range encoder 4 ;
(encoder.t, 0, t_flush (k 4)))
else
let j = encoder.o_pos in
encoder.o_pos <- encoder.o_pos + 4 ;
(encoder.o, encoder.o_off + j, k 4) in
unsafe_set_chr s j default_alphabet.[a] ;
unsafe_set_chr s (j + 1) default_alphabet.[b] ;
unsafe_set_chr s (j + 2) default_alphabet.[c] ;
unsafe_set_chr s (j + 3) default_alphabet.[d] ;
flush k encoder)
else (
unsafe_set_chr encoder.i encoder.s chr ;
encoder.s <- encoder.s + 1 ;
k 0 encoder)
and encode_trailing k encoder =
match encoder.s with
| 2 ->
let b, c = (unsafe_byte encoder.i 0 0, unsafe_byte encoder.i 0 1) in
encoder.s <- 0 ;
let quantum = (Char.code b lsl 10) + (Char.code c lsl 2) in
let b = (quantum lsr 12) land 63 in
let c = (quantum lsr 6) land 63 in
let d = quantum land 63 in
let rem = o_rem encoder in
let s, j, k =
if rem < 4
then (
t_range encoder 4 ;
(encoder.t, 0, t_flush (k 4)))
else
let j = encoder.o_pos in
encoder.o_pos <- encoder.o_pos + 4 ;
(encoder.o, encoder.o_off + j, k 4) in
unsafe_set_chr s j default_alphabet.[b] ;
unsafe_set_chr s (j + 1) default_alphabet.[c] ;
unsafe_set_chr s (j + 2) default_alphabet.[d] ;
unsafe_set_chr s (j + 3) '=' ;
flush k encoder
| 1 ->
let c = unsafe_byte encoder.i 0 0 in
encoder.s <- 0 ;
let quantum = Char.code c lsl 4 in
let c = (quantum lsr 6) land 63 in
let d = quantum land 63 in
let rem = o_rem encoder in
let s, j, k =
if rem < 4
then (
t_range encoder 4 ;
(encoder.t, 0, t_flush (k 4)))
else
let j = encoder.o_pos in
encoder.o_pos <- encoder.o_pos + 4 ;
(encoder.o, encoder.o_off + j, k 4) in
unsafe_set_chr s j default_alphabet.[c] ;
unsafe_set_chr s (j + 1) default_alphabet.[d] ;
unsafe_set_chr s (j + 2) '=' ;
unsafe_set_chr s (j + 3) '=' ;
flush k encoder
| 0 -> k 0 encoder
| _ -> assert false
and encode_base64 encoder v =
let k col_count encoder =
encoder.c_col <- encoder.c_col + col_count ;
encoder.k <- encode_base64 ;
`Ok in
match v with
| `Await -> k 0 encoder
| `End ->
if encoder.c_col = 76
then encode_line_break (fun encoder -> encode_base64 encoder v) encoder
else encode_trailing k encoder
| `Char chr ->
let rem = o_rem encoder in
if rem < 1
then flush (fun encoder -> encode_base64 encoder v) encoder
else if encoder.c_col = 76
then encode_line_break (fun encoder -> encode_base64 encoder v) encoder
else encode_char chr k encoder
let encoder dst =
let o, o_off, o_pos, o_len =
match dst with
| `Manual -> (Bytes.empty, 1, 0, 0)
| `Buffer _ | `Channel _ ->
(Bytes.create io_buffer_size, 0, 0, io_buffer_size - 1) in
{
dst;
o_off;
o_pos;
o_len;
o;
t = Bytes.create 4;
t_pos = 1;
t_len = 0;
c_col = 0;
i = Bytes.create 3;
s = 0;
k = encode_base64;
}
let encode encoder = encoder.k encoder
let encoder_dst encoder = encoder.dst
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
mli
|
base64-3.5.2/src/base64_rfc2045.mli
|
(*
* Copyright (c) 2014-2016 Anil Madhavapeddy <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
(** Decode *)
val default_alphabet : string
(** A 64-character string specifying the regular Base64 alphabet. *)
type decoder
(** The type for decoders. *)
type src = [ `Manual | `Channel of in_channel | `String of string ]
(** The type for input sources. With a [`Manual] source the client must provide
input with {!src}. *)
type decode =
[ `Await | `End | `Flush of string | `Malformed of string | `Wrong_padding ]
val src : decoder -> Bytes.t -> int -> int -> unit
(** [src d s j l] provides [d] with [l] bytes to read, starting at [j] in [s].
This byte range is read by calls to {!decode} with [d] until [`Await] is
returned. To signal the end of input, call the function with [l = 0]. *)
val decoder : src -> decoder
(** [decoder src] is a decoder that inputs from [src]. *)
val decode : decoder -> decode
(** [decode d] is:
- [`Await] if [d] has a [`Manual] input source and awaits for more input.
The client must use {!src} to provide it.
- [`End] if the end of input was reached
- [`Malformed bytes] if the [bytes] sequence is malformed according to the
decoded base64 encoding scheme. If you are interested in a best-effort
decoding, you can still continue to decode after an error until the decode
synchronizes again on valid bytes.
- [`Flush data] if a [data] sequence value was decoded.
- [`Wrong_padding] if decoder retrieve a wrong padding at the end of the
input.
{b Note}. Repeated invocation always eventually returns [`End], even in case
of errors. *)
val decoder_byte_count : decoder -> int
(** [decoder_byte_count d] is the number of characters already decoded on [d]
(included malformed ones). This is the last {!decode}'s end output offset
counting from beginning of the stream. *)
val decoder_src : decoder -> src
(** [decoder_src d] is [d]'s input source. *)
val decoder_dangerous : decoder -> bool
(** [decoder_dangerous d] returns [true] if encoded input does not respect the
80-columns rule. If your are interested in a best-effort decoding you can
still continue to decode even if [decoder_dangerous d] returns [true].
Nothing grow automatically internally in this state. *)
type dst = [ `Channel of out_channel | `Buffer of Buffer.t | `Manual ]
(** The type for output destinations. With a [`Manual] destination the client
must provide output storage with {!dst}. *)
type encode = [ `Await | `End | `Char of char ]
type encoder
(** The type for Base64 (RFC2045) encoder. *)
val encoder : dst -> encoder
(** [encoder dst] is an encoder for Base64 (RFC2045) that outputs to [dst]. *)
val encode : encoder -> encode -> [ `Ok | `Partial ]
(** [encode e v]: is
- [`Partial] iff [e] has a [`Manual] destination and needs more output
storage. The client must use {!dst} to provide a new buffer and then call
{!encode} with [`Await] until [`Ok] is returned.
- [`Ok] when the encoder is ready to encode a new [`Char] or [`End]
For [`Manual] destination, encoding [`End] always return [`Partial], the
client should continue as usual with [`Await] until [`Ok] is returned at
which point {!dst_rem} [encoder] is guaranteed to be the size of the last
provided buffer (i.e. nothing was written).
{b Raises.} [Invalid_argument] if a [`Char] or [`End] is encoded after a
[`Partial] encode. *)
val encoder_dst : encoder -> dst
(** [encoder_dst encoder] is [encoder]'s output destination. *)
val dst : encoder -> Bytes.t -> int -> int -> unit
(** [dst e s j l] provides [e] with [l] bytes to write, starting at [j] in [s].
This byte range is written by calls to {!encode} with [e] until [`Partial]
is returned. Use {!dst_rem} to know the remaining number of non-written free
bytes in [s]. *)
val dst_rem : encoder -> int
(** [dst_rem e] is the remaining number of non-written, free bytes in the last
buffer provided with {!dst}. *)
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
dune
|
base64-3.5.2/src/dune
|
(library
(name base64)
(modules base64)
(public_name base64))
(library
(name base64_rfc2045)
(modules base64_rfc2045)
(public_name base64.rfc2045))
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
dune
|
base64-3.5.2/test/dune
|
(executable
(modes byte exe)
(name test)
(libraries base64 base64.rfc2045 rresult alcotest bos))
(rule
(alias runtest)
(deps
(:exe test.exe))
(action
(run %{exe} --color=always)))
|
base64
|
3.5.2
|
ISC
|
https://github.com/mirage/ocaml-base64
|
git+https://github.com/mirage/ocaml-base64.git
|
ml
|
base64-3.5.2/test/test.ml
|
(*
* Copyright (c) 2016 Anil Madhavapeddy <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
open Printf
open Rresult
(* Test vectors from RFC4648
BASE64("") = ""
BASE64("f") = "Zg=="
BASE64("fo") = "Zm8="
BASE64("foo") = "Zm9v"
BASE64("foob") = "Zm9vYg=="
BASE64("fooba") = "Zm9vYmE="
BASE64("foobar") = "Zm9vYmFy"
*)
let rfc4648_tests =
[
("", "");
("f", "Zg==");
("fo", "Zm8=");
("foo", "Zm9v");
("foob", "Zm9vYg==");
("fooba", "Zm9vYmE=");
("foobar", "Zm9vYmFy");
]
let hannes_tests =
[
("dummy", "ZHVtbXk=");
("dummy", "ZHVtbXk");
("dummy", "ZHVtbXk==");
("dummy", "ZHVtbXk===");
("dummy", "ZHVtbXk====");
("dummy", "ZHVtbXk=====");
("dummy", "ZHVtbXk======");
]
let php_tests =
[
( "πάντα χωρεῖ καὶ οὐδὲν μένει …",
"z4DOrM69z4TOsSDPh8-Jz4HOteG_liDOus6x4b22IM6_4b2QzrThvbLOvSDOvM6tzr3Otc65IOKApg"
);
]
let rfc3548_tests =
[
("\x14\xfb\x9c\x03\xd9\x7e", "FPucA9l+");
("\x14\xfb\x9c\x03\xd9", "FPucA9k=");
("\x14\xfb\x9c\x03", "FPucAw==");
]
let cfcs_tests =
[
(0, 2, "\004", "BB");
(1, 2, "\004", "ABB");
(1, 2, "\004", "ABBA");
(2, 2, "\004", "AABBA");
(2, 2, "\004", "AABBAA");
(0, 0, "", "BB");
(1, 0, "", "BB");
(2, 0, "", "BB");
]
let nocrypto_tests =
[
("\x00\x5a\x6d\x39\x76", None);
("\x5a\x6d\x39\x76", Some "\x66\x6f\x6f");
("\x5a\x6d\x39\x76\x76", None);
("\x5a\x6d\x39\x76\x76\x76", None);
("\x5a\x6d\x39\x76\x76\x76\x76", None);
("\x5a\x6d\x39\x76\x00", None);
("\x5a\x6d\x39\x76\x62\x77\x3d\x3d", Some "\x66\x6f\x6f\x6f");
("\x5a\x6d\x39\x76\x62\x77\x3d\x3d\x00", None);
("\x5a\x6d\x39\x76\x62\x77\x3d\x3d\x00\x01", None);
("\x5a\x6d\x39\x76\x62\x77\x3d\x3d\x00\x01\x02", None);
("\x5a\x6d\x39\x76\x62\x77\x3d\x3d\x00\x01\x02\x03", None);
("\x5a\x6d\x39\x76\x62\x32\x38\x3d", Some "\x66\x6f\x6f\x6f\x6f");
("\x5a\x6d\x39\x76\x62\x32\x39\x76", Some "\x66\x6f\x6f\x6f\x6f\x6f");
("YWE=", Some "aa");
("YWE==", None);
("YWE===", None);
("YWE=====", None);
("YWE======", None);
]
let alphabet_size () =
List.iter
(fun (name, alphabet) ->
Alcotest.(check int)
(sprintf "Alphabet size %s = 64" name)
64
(Base64.length_alphabet alphabet))
[
("default", Base64.default_alphabet);
("uri_safe", Base64.uri_safe_alphabet);
]
(* Encode using OpenSSL `base64` utility *)
let openssl_encode buf =
Bos.(
OS.Cmd.in_string buf
|> OS.Cmd.run_io (Cmd.v "base64")
|> OS.Cmd.to_string ~trim:true)
|> function
| Ok r ->
prerr_endline r ;
r
| Error (`Msg e) -> raise (Failure (sprintf "OpenSSL decode: %s" e))
(* Encode using this library *)
let lib_encode buf = Base64.encode_exn ~pad:true buf
let test_rfc4648 () =
List.iter
(fun (c, r) ->
(* Base64 vs openssl *)
Alcotest.(check string)
(sprintf "encode %s" c) (openssl_encode c) (lib_encode c) ;
(* Base64 vs test cases above *)
Alcotest.(check string) (sprintf "encode rfc4648 %s" c) r (lib_encode c) ;
(* Base64 decode vs library *)
Alcotest.(check string) (sprintf "decode %s" r) c (Base64.decode_exn r))
rfc4648_tests
let test_rfc3548 () =
List.iter
(fun (c, r) ->
(* Base64 vs openssl *)
Alcotest.(check string)
(sprintf "encode %s" c) (openssl_encode c) (lib_encode c) ;
(* Base64 vs test cases above *)
Alcotest.(check string) (sprintf "encode rfc3548 %s" c) r (lib_encode c) ;
(* Base64 decode vs library *)
Alcotest.(check string) (sprintf "decode %s" r) c (Base64.decode_exn r))
rfc3548_tests
let test_hannes () =
List.iter
(fun (c, r) ->
(* Base64 vs test cases above *)
Alcotest.(check string)
(sprintf "decode %s" r) c
(Base64.decode_exn ~pad:false r))
hannes_tests
let test_php () =
List.iter
(fun (c, r) ->
Alcotest.(check string)
(sprintf "decode %s" r) c
(Base64.decode_exn ~pad:false ~alphabet:Base64.uri_safe_alphabet r))
php_tests
let test_cfcs () =
List.iter
(fun (off, len, c, r) ->
Alcotest.(check string)
(sprintf "decode %s" r) c
(Base64.decode_exn ~pad:false ~off ~len r))
cfcs_tests
let test_nocrypto () =
List.iter
(fun (input, res) ->
let res' =
match Base64.decode ~pad:true input with
| Ok v -> Some v
| Error _ -> None in
Alcotest.(check (option string)) (sprintf "decode %S" input) res' res)
nocrypto_tests
exception Malformed
exception Wrong_padding
let strict_base64_rfc2045_of_string x =
let decoder = Base64_rfc2045.decoder (`String x) in
let res = Buffer.create 16 in
let rec go () =
match Base64_rfc2045.decode decoder with
| `End -> ()
| `Wrong_padding -> raise Wrong_padding
| `Malformed _ -> raise Malformed
| `Flush x ->
Buffer.add_string res x ;
go ()
| `Await -> Alcotest.failf "Retrieve impossible case: `Await" in
Base64_rfc2045.src decoder (Bytes.unsafe_of_string x) 0 (String.length x) ;
go () ;
Buffer.contents res
let relaxed_base64_rfc2045_of_string x =
let decoder = Base64_rfc2045.decoder (`String x) in
let res = Buffer.create 16 in
let rec go () =
match Base64_rfc2045.decode decoder with
| `End -> ()
| `Wrong_padding -> go ()
| `Malformed _ -> go ()
| `Flush x ->
Buffer.add_string res x ;
go ()
| `Await -> Alcotest.failf "Retrieve impossible case: `Await" in
Base64_rfc2045.src decoder (Bytes.unsafe_of_string x) 0 (String.length x) ;
go () ;
Buffer.contents res
let test_strict_rfc2045 =
[
( "c2FsdXQgbGVzIGNvcGFpbnMgZmF1dCBhYnNvbHVtZW50IHF1ZSBqZSBkw6lwYXNzZSBsZXMgODAg\r\n\
Y2hhcmFjdGVycyBwb3VyIHZvaXIgc2kgbW9uIGVuY29kZXIgZml0cyBiaWVuIGRhbnMgbGVzIGxp\r\n\
bWl0ZXMgZGUgbGEgUkZDIDIwNDUgLi4u",
"salut les copains faut absolument que je dépasse les 80 characters \
pour voir si mon encoder fits bien dans les limites de la RFC 2045 ..."
);
("", "");
("Zg==", "f");
("Zm8=", "fo");
("Zm9v", "foo");
("Zm9vYg==", "foob");
("Zm9vYmE=", "fooba");
("Zm9vYmFy", "foobar");
]
let test_relaxed_rfc2045 =
[
("Zg", "f");
("Zm\n8", "fo");
("Zm\r9v", "foo");
("Zm9 vYg", "foob");
("Zm9\r\n vYmE", "fooba");
("Zm9évYmFy", "foobar");
]
let strict_base64_rfc2045_to_string x =
let res = Buffer.create 16 in
let encoder = Base64_rfc2045.encoder (`Buffer res) in
String.iter
(fun chr ->
match Base64_rfc2045.encode encoder (`Char chr) with
| `Ok -> ()
| `Partial ->
Alcotest.failf "Retrieve impossible case for (`Char %02x): `Partial"
(Char.code chr))
x ;
match Base64_rfc2045.encode encoder `End with
| `Ok -> Buffer.contents res
| `Partial -> Alcotest.fail "Retrieve impossible case for `End: `Partial"
let test_strict_with_malformed_input_rfc2045 =
List.mapi
(fun i (has, _) ->
Alcotest.test_case (Fmt.str "strict rfc2045 - %02d" i) `Quick @@ fun () ->
try
let _ = strict_base64_rfc2045_of_string has in
Alcotest.failf "Strict parser valids malformed input: %S" has
with Malformed | Wrong_padding -> ())
test_relaxed_rfc2045
let test_strict_rfc2045 =
List.mapi
(fun i (has, expect) ->
Alcotest.test_case (Fmt.str "strict rfc2045 - %02d" i) `Quick @@ fun () ->
try
let res0 = strict_base64_rfc2045_of_string has in
let res1 = strict_base64_rfc2045_to_string res0 in
Alcotest.(check string) "encode(decode(x)) = x" res1 has ;
Alcotest.(check string) "decode(x)" res0 expect
with Malformed | Wrong_padding -> Alcotest.failf "Invalid input %S" has)
test_strict_rfc2045
let test_relaxed_rfc2045 =
List.mapi
(fun i (has, expect) ->
Alcotest.test_case (Fmt.str "relaxed rfc2045 - %02d" i) `Quick
@@ fun () ->
let res0 = relaxed_base64_rfc2045_of_string has in
Alcotest.(check string) "decode(x)" res0 expect)
test_relaxed_rfc2045
let test_invariants = [ ("Alphabet size", `Quick, alphabet_size) ]
let test_codec =
[
("RFC4648 test vectors", `Quick, test_rfc4648);
("RFC3548 test vectors", `Quick, test_rfc3548);
("Hannes test vectors", `Quick, test_hannes);
("Cfcs test vectors", `Quick, test_cfcs);
("PHP test vectors", `Quick, test_php);
("Nocrypto test vectors", `Quick, test_nocrypto);
]
let () =
Alcotest.run "Base64"
[
("invariants", test_invariants);
("codec", test_codec);
("rfc2045 (0)", test_strict_rfc2045);
("rfc2045 (1)", test_strict_with_malformed_input_rfc2045);
("rfc2045 (2)", test_relaxed_rfc2045);
]
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-camlboy/output_results.ml
|
let () =
Format.printf
{|{ "name": "%s",
"results":
[ { "name": "Camlboy",
"metrics":
[ { "name": "Frames per second",
"units": "Hz",
"value": %s } ] } ] }@.|}
Sys.argv.(1)
(read_line ())
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/bigarrays/bench.ml
|
let pi = 4. *. atan 1.
let deltay = 40_000. /. 360. /. 3600. *. 1000.
let deltax = deltay *. cos (44. *. pi /. 180.)
let precompute tile_height tile_width tile =
let normals =
Bigarray.(Array3.create Int8_signed C_layout) (tile_height - 2) (tile_width - 2) 3
in
let heights =
Bigarray.(Array2.create Float32 C_layout) (tile_height - 2) (tile_width - 2)
in
for y = 1 to tile_height - 2 do
for x = 1 to tile_width - 2 do
let nx = (tile.{y, x - 1} -. tile.{y, x + 1}) *. deltay in
let ny = (tile.{y - 1, x} -. tile.{y + 1, x}) *. deltax in
let nz = 2. *. deltax *. deltay in
let n = 127. /. sqrt ((nx *. nx) +. (ny *. ny) +. (nz *. nz)) in
normals.{tile_height - 2 - y, x - 1, 0} <- truncate (nx *. n);
normals.{tile_height - 2 - y, x - 1, 1} <- truncate (ny *. n);
normals.{tile_height - 2 - y, x - 1, 2} <- truncate (nz *. n);
heights.{tile_height - 2 - y, x - 1} <- tile.{y, x}
done
done
let tile_height = 1024
let tile_width = 1024
let tile = Bigarray.(Array2.create Float32 C_layout) tile_height tile_width
let () =
for _ = 1 to 30 do
precompute tile_height tile_width tile
done
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/bin_prot/bench.ml
|
open Bin_prot.Std
type element =
{ a : string
; b : string
; c : string
; d : bool
; e : bool
; f : bool
; g : string option
; h : bool
; i : bool
; j : bool
; k : bool
; l : bool
; m : bool
; n : bool
; o : string option
; p : bool
; q : bool
; r : int
; s : int
; t : int
; u : int
; v : string list (* these are small - 1-5 *)
}
[@@deriving bin_io]
let s = "abcdefabcdefabcdef"
let v = [ s; s; s; s ]
let x =
{ a = s
; b = s
; c = s
; d = true
; e = true
; f = true
; g = Some s
; h = true
; i = true
; j = true
; k = true
; l = true
; m = true
; n = true
; o = Some s
; p = true
; q = true
; r = 65537
; s = 65537
; t = 65537
; u = 65537
; v
}
type t = element list [@@deriving bin_io]
let rec f acc n = if n = 0 then acc else f (x :: acc) (n - 1)
let () =
if Array.length Sys.argv > 1
then (
let count = int_of_string Sys.argv.(1) in
let l = f [] count in
let len = [%bin_size: t] l in
let b = Bin_prot.Common.create_buf len in
ignore ([%bin_write: t] b ~pos:0 l : int);
let s = Bytes.create len in
Bin_prot.Common.blit_buf_string ~src_pos:0 b ~dst_pos:0 s ~len;
Out_channel.with_open_bin "data" @@ fun ch -> Out_channel.output_bytes ch s)
else
let s = In_channel.with_open_bin "data" @@ In_channel.input_all in
let len = String.length s in
let b = Bin_prot.Common.create_buf len in
Bin_prot.Common.blit_string_buf ~src_pos:0 s ~dst_pos:0 b ~len;
let t = Unix.gettimeofday () in
for _ = 0 to 4 do
ignore ([%bin_read: t] b ~pos_ref:(ref 0) : t)
done;
let t' = Unix.gettimeofday () in
Format.printf "%.2f@." (t' -. t)
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
dune
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/bin_prot/dune
|
(executables
(names bench)
(modes js wasm)
(js_of_ocaml
(flags --opt 2))
(wasm_of_ocaml
(flags --opt 2))
(preprocess
(pps ppx_bin_prot))
(libraries unix))
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
dune
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/dune
|
; Ignore subdirectories
(dirs)
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/date.ml
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
type date = int
type gregorian = {
year : int;
month : int;
day : int;
hour : int;
minute : int
}
let hours_in_day = 24
let minutes_in_day = hours_in_day * 60
let fminutes_in_day = float minutes_in_day
let minutes_to_noon = (hours_in_day / 2) * 60
(*
Communications of the ACM by Henry F. Fliegel and Thomas C. Van Flandern,
``A Machine Algorithm for Processing Calendar Dates'',
CACM, volume 11, number 10, October 1968, p. 657
*)
let date_of_gregorian {year = y; month = m; day = d; hour = hr; minute = mn} =
(
(match m with
| 1 | 2 ->
( 1461 * ( y + 4800 - 1 ) ) / 4 +
( 367 * ( m + 10 ) ) / 12 -
( 3 * ( ( y + 4900 - 1 ) / 100 ) ) / 4
| _ ->
( 1461 * ( y + 4800 ) ) / 4 +
( 367 * ( m - 2 ) ) / 12 -
( 3 * ( ( y + 4900 ) / 100 ) ) / 4)
+ d - 32075 - 2444238) * minutes_in_day
+ hr * 60 + mn
let gregorian_of_date minutes_since_epoch =
let jul = minutes_since_epoch / minutes_in_day in
let l = jul + 68569 + 2444238 in
let n = ( 4 * l ) / 146097 in
let l = l - ( 146097 * n + 3 ) / 4 in
let i = ( 4000 * ( l + 1 ) ) / 1461001 in
let l = l - ( 1461 * i ) / 4 + 31 in
let j = ( 80 * l ) / 2447 in
let d = l - ( 2447 * j ) / 80 in
let l = j / 11 in
let m = j + 2 - ( 12 * l ) in
let y = 100 * ( n - 49 ) + i + l in
let daytime = minutes_since_epoch mod minutes_in_day in
if daytime = minutes_to_noon
then {year = y; month = m; day = d; hour = 12; minute = 0}
else {year = y; month = m; day = d; hour = daytime / 60; minute = daytime mod 60}
let check_date ~year ~month ~day =
1 <= day &&
1 <= month && month <= 12 &&
1980 <= year && year <= 2299 &&
begin
day <= 28 ||
match month with
| 2 -> day = 29 && year mod 4 = 0 && (year = 2000 || (year mod 100 <> 0))
(* we don't check y mod 400 because 2000 is ok and we don't support
neither 1600 nor 2400. *)
| 4 | 6 | 9 | 11 -> day <= 30
| _ -> day <= 31
end
let of_string s : date =
let sub ofs len =
let rec sub acc ofs len =
if len = 0
then acc
else sub (acc * 10 + int_of_char(String.unsafe_get s ofs) - 48) (ofs + 1) (len - 1)
in
sub (int_of_char(String.unsafe_get s ofs) - 48) (ofs + 1) (len - 1)
in
if String.length s < 10 then invalid_arg "date_of_string";
let year = sub 0 4 in
let month = sub 5 2 in
let day = sub 8 2 in
(* minimal coherence check of the date, just what is needed more than what the lexer is doing *)
if check_date ~year ~month ~day then
if String.length s < 16
then date_of_gregorian{year; month; day; hour=12; minute=0}
else date_of_gregorian{year; month; day; hour=sub 11 2; minute=sub 14 2}
else invalid_arg "date_of_string"
let days_between t1 t2 =
float (t1 - t2) /. fminutes_in_day
let act_365 t1 t2 = (days_between t1 t2) /. 365.
let leap y = (y mod 4 = 0) && ((y mod 100 <> 0) || (y mod 400 = 0))
let end_of_month year month =
match month with
| 2 when leap year -> 29
| 2 -> 28
| 4 | 6 | 9 | 11 -> 30
| _ -> 31
let add_months date nbmonths =
let {year = y; month = m; day = d; hour = _; minute = _;} as date = gregorian_of_date date in
let m = m + nbmonths in
let y, m = y + (m-1) / 12, ((m-1) mod 12) + 1 in
let y, m = if m <= 0 then y - 1, m + 12 else y, m in
date_of_gregorian {date with year = y; month = m; day = min d (end_of_month y m)}
let add_years date nbyears = add_months date (nbyears * 12)
let max_date = of_string "2299-12-31T23:59:59"
let min_date = of_string "1980-01-01T12:00:00"
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
mli
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/date.mli
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
type date
val max_date: date
val min_date: date
val of_string: string -> date
val days_between: date -> date -> float
val act_365: date -> date -> float
val add_months: date -> int -> date
val add_years: date -> int -> date
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
dune
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/dune
|
(executable
(name main)
(js_of_ocaml
(flags --opt 2))
(wasm_of_ocaml
(flags --opt 2))
(modes js wasm))
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/g2pp_calibration.ml
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
(* A 2-factor interest-rate model. Reference book: Brigo and Mercurio "Interest Rate Models" 2005 *)
open Date
let pi = 2. *. asin 1.
type extended_swaption =
{
maturity: date;
strike: float;
swap_schedule: (date * date) list;
}
type swap_frequency =
| Freq_3M
| Freq_6M
| Freq_1Y
type swaption =
{
swaption_maturity_in_year: int;
swap_frequency: swap_frequency;
swap_term_in_year: int;
}
let extended_swaption_of_swaption ~today ~zc {swaption_maturity_in_year; swap_frequency; swap_term_in_year} =
let maturity = add_years today swaption_maturity_in_year in
let frq =
match swap_frequency with
| Freq_3M -> 3
| Freq_6M -> 6
| Freq_1Y -> 12
in
let nschedule = 12 * swap_term_in_year / frq in
let swap_schedule = Array.init nschedule (fun i -> add_months maturity (i * frq), add_months maturity ((i + 1) * frq)) in
let swap_schedule = Array.to_list swap_schedule in
let lvl, t0, tn =
List.fold_left
(fun (acc_lvl, acc_t0, acc_tn) (tf, tp) ->
acc_lvl +. zc tp *. (act_365 tp tf), min acc_t0 tf, max acc_tn tp
) (0., max_date, min_date) swap_schedule
in
let strike = (zc t0 -. zc tn) /. lvl in (* atm strike *)
{maturity; swap_schedule; strike}
type parameters =
{
g_a : float;
g_b : float;
g_sigma : float;
g_nu : float;(* nu is eta in Brigo and Mercurio *)
g_rho : float;
}
(* Places with ** comments should take account of sigma=0 case *)
let b_fun z tau = (* ** *)
(1. -. exp (-. z *. tau)) /. z
exception Sdomain
(* \var(\int_t^T [x(u)+y(u)]du) *)
let bigv {g_a; g_b; g_rho; g_nu; g_sigma} tau = (* 4.10 p 135 *)
let t sigma x =
let expxtau = exp (-. x *. tau) in (* ** *)
let exp2xtau = expxtau *. expxtau in (* ** *)
sigma *. sigma /. (x *. x) *.
(tau +. 2. /. x *. expxtau -. 1. /. (2. *. x) *. exp2xtau -. 3. /. (2. *. x))
in
let t1 = t g_sigma g_a in
let t2 = t g_nu g_b in
let ba = b_fun g_a tau in
let bb = b_fun g_b tau in
let t3 = (* ** *)
2. *. g_rho *. g_nu *. g_sigma /. (g_a *. g_b) *.
(tau -. ba -. bb +. b_fun (g_a +. g_b) tau)
in
t1 +. t2 +. t3, ba, bb
(* x drift term in tmat-forward measure *)
let bigmx {g_a; g_b; g_rho; g_nu; g_sigma} today tmat s t =
let ts = act_365 t s in
let tmatt = act_365 tmat t in
let tmat0 = act_365 tmat today in
let tmats = act_365 tmat s in
let t0 = act_365 t today in
let s0 = act_365 s today in
(g_sigma *. g_sigma /. (g_a *. g_a) +. g_sigma *. g_rho *. g_nu /. (g_a *. g_b)) *. (1. -. exp (-. g_a *. ts)) -.
(g_sigma *. g_sigma /. (2. *. g_a *. g_a) *. (exp (-. g_a *. tmatt) -. exp (-. g_a *. (tmats +. ts)))) -.
g_rho *. g_sigma *. g_nu /. (g_b *. (g_a +. g_b)) *. (exp (-. g_b *. tmatt) -. exp (-. g_b *. tmat0 -. g_a *. t0 +. (g_a +. g_b) *. s0))
(* y drift term in tmat-forward measure *)
let bigmy {g_a; g_b; g_rho; g_nu; g_sigma} today tmat s t =
let ts = act_365 t s in
let tmatt = act_365 tmat t in
let tmat0 = act_365 tmat today in
let tmats = act_365 tmat s in
let t0 = act_365 t today in
let s0 = act_365 s today in
(g_nu *. g_nu /. (g_b *. g_b) +. g_sigma *. g_rho *. g_nu /. (g_a *. g_b)) *. (1. -. exp (-. g_b *. ts)) -.
(g_nu *. g_nu /. (2. *. g_b *. g_b) *. (exp (-. g_b *. tmatt) -. exp (-. g_b *. (tmats +. ts)))) -.
g_rho *. g_sigma *. g_nu /. (g_a *. (g_a +. g_b)) *. (exp (-. g_a *. tmatt) -. exp (-. g_a *. tmat0 -. g_b *. t0 +. (g_a +. g_b) *. s0))
let x_quadrature, w_quadrature = Math.Gaussian_quadrature.gauss_hermite_coefficients
let nquadrature = Array.length x_quadrature
let pricer_of_swaption ~today ~zc swaption =
let swaption = extended_swaption_of_swaption ~today ~zc swaption in
let maturity = swaption.maturity in
let strike = swaption.strike in
let tmat0 = act_365 maturity today in
let schedulei = Array.of_list swaption.swap_schedule in
let lastindex = Array.length schedulei - 1 in
let taui = Array.map (fun (start_date, end_date) -> act_365 end_date start_date) schedulei in
let ci =
Array.mapi
(fun i tau -> if i = lastindex then 1. +. tau *. strike else tau *. strike)
taui
in
let n_schedi = Array.length schedulei in
let bai = Array.make n_schedi 0. in
let bbi = Array.make n_schedi 0. in
let aici = Array.make n_schedi 0. in
let log_aici = Array.make n_schedi 0. in
let scales = Array.make n_schedi 0. in
let t1_cst = Array.make n_schedi 0. in
let scale = Array.make n_schedi 0. in
fun params ->
let {g_a; g_b; g_rho; g_nu; g_sigma} = params in
let v0_mat, _, _ = bigv params (act_365 maturity today) in
let zc_mat = zc maturity in
let a_fun end_date = (* defined top p138 *)
let v0_end, _, _ = bigv params (act_365 end_date today) in
let vt_end, ba, bb = bigv params (act_365 end_date maturity) in
zc end_date /. zc_mat *. exp (0.5 *. (vt_end -. v0_end +. v0_mat)), ba, bb
in
let sigmax = g_sigma *. sqrt (b_fun (2. *. g_a) tmat0) in
let sigmay = g_nu *. sqrt (b_fun (2. *. g_b) tmat0) in
let rhoxy = g_rho *. g_sigma *. g_nu /. (sigmax *. sigmay) *. (b_fun (g_a +. g_b) tmat0) in
let rhoxyc = 1. -. rhoxy *. rhoxy in
let rhoxycs = sqrt rhoxyc in
let t2 = rhoxy /. (sigmax *. rhoxycs) in
let sigmay_rhoxycs = sigmay *. rhoxycs in
let t4 = rhoxy *. sigmay /. sigmax in
let mux = -. bigmx params today maturity today maturity in
let muy = -. bigmy params today maturity today maturity in
for i = 0 to n_schedi - 1 do
let a, ba, bb = a_fun (snd schedulei.(i)) in
let x = ci.(i) *. a in
let log_ac = log x in
aici.(i) <- x;
log_aici.(i) <- log_ac;
bai.(i) <- ba;
bbi.(i) <- bb;
let t3 = muy -. 0.5 *. rhoxyc *. sigmay *. sigmay *. bb in
let cst = bb *. (mux *. t4 -. t3) in
t1_cst.(i) <- x *. exp cst;
scale.(i) <- -. (ba +. bb *. t4);
done;
let k = (-3.71901648545568) in (* ugaussian_Pinv 1e-4 *)
let exact_yhat x =
(* y_lo x <= yhat x <= y_up x*)
let lo = ref neg_infinity in
let up = ref 0. in
for i = 0 to n_schedi - 1 do
let baix = bai.(i) *. x in
lo := max !lo ((log_aici.(i) -. baix) /. bbi.(i));
up := !up +. aici.(i) *. exp (-. baix)
done;
let lo = !lo and s_up = !up in
if n_schedi = 1 then lo
else
let open Math.Rootfinder in
let up =
let log_s = log s_up in
let tmp = log_s /. bbi.(n_schedi - 1) in
if tmp <= 0. then tmp
else let tmp = log_s /. bbi.(0) in if 0. <= tmp then tmp
(* This case happens when all ai * ci are too close to 0. or x to high => to_solve x y is close to -1 for all y,
thus the root is reached for y negative with high absolute value (tosolve x is a decreasing function of y) *)
else neg_infinity
in
let yl = lo -. 1e-5 in
let yu = up +. 1e-5 in
(* y01 x = y0, y1 / phi(h_i(x, y0)) <= epsilon, 1 - phi(h_i(x, y1)) <= epsilon *)
let y0 = sigmay *. (rhoxy *. (x -. mux) /. sigmax +. k *. rhoxycs) -. rhoxyc /. g_b +. muy in
let y1 = sigmay *. (rhoxy *. (x -. mux) /. sigmax -. k *. rhoxycs) +. muy in
if y1 <= yl then y1 +. 1. (* yhat is greater than y1 => 1 - phi(h_i(x, yhat)) < epsilon *)
else if yu <= y0 then y0 -. 1. (* yhat is lower than y0 => phi(h_i(x, yhat)) < epsilon *)
else try
for i = 0 to n_schedi - 1 do
scales.(i) <- aici.(i) *. exp (-. bai.(i) *. x);
done;
let to_solve yhat = (* eqn at bottom p148 *)
let sum = ref (-1.) in
for i = 0 to n_schedi - 1 do
sum := !sum +. scales.(i) *. exp (-. bbi.(i) *. yhat);
done;
assert(!sum = !sum);
!sum
in
brent (max yl y0) (min yu y1) to_solve 1e-4
with
| Rootfinder NotbracketedBelow -> y0 -. 1.
| Rootfinder NotbracketedAbove -> y1 +. 1.
in
let yhat =
let eps = 0.5 *. sigmax in
let f = exact_yhat mux in
let df = 0.5 *. (exact_yhat (mux +. eps) -. exact_yhat (mux -. eps)) /. eps in
fun x -> f +. df *. (x -. mux)
in
let integrand x =
let t1 = exp (-. 0.5 *. ((x -. mux) /. sigmax) ** 2.) in
let yhat = yhat x in
let h1 =
let t1 = (yhat -. muy) /. sigmay_rhoxycs in
t1 -. t2 *. (x -. mux)
in
let t2 = Math.ugaussian_P (-.h1) in
let acc = ref 0. in
for i = 0 to n_schedi - 1 do
let h2 = h1 +. bbi.(i) *. sigmay_rhoxycs in
acc := !acc +. t1_cst.(i) *. exp (scale.(i) *. x) *. Math.ugaussian_P (-.h2)
done;
t1 *. (t2 -. !acc)
in
let integral =
let sqrt2sigmax = sqrt 2. *. sigmax in
let sum = ref 0. in
for i = 0 to nquadrature - 1 do
sum := !sum +. w_quadrature.(i) *. integrand (sqrt2sigmax *. x_quadrature.(i) +. mux)
done;
!sum /. (sqrt pi)
in
zc_mat *. integral
let black_price ~today ~zc swaption vol =
let swaption = extended_swaption_of_swaption ~today ~zc swaption in
let {swap_schedule; strike; maturity; _} = swaption in
let sqrtt = act_365 maturity today in
let lvl, t0, tn =
List.fold_left
(fun (acc_lvl, acc_t0, acc_tn) (tf, tp) ->
acc_lvl +. zc tp *. (act_365 tp tf), min acc_t0 tf, max acc_tn tp
) (0., max_date, min_date) swap_schedule
in
let s0 = (zc t0 -. zc tn) /. lvl in
let d1 = log (s0 /. strike) /. (vol *. sqrtt) +. 0.5 *. vol *. sqrtt in
let d2 = d1 -. vol *. sqrtt in
lvl *. (s0 *. Math.ugaussian_P d1 -. strike *. Math.ugaussian_P d2)
let calibrate ?feedback ~max_global ~today ~swaption_quotes ~variables ~zc () =
assert(Array.length variables = 5);
let quotes = Array.map (fun (sw, q) -> black_price ~today ~zc sw q) swaption_quotes in
let parameters_of_vector x =
let g_a = x.(0) in
let g_b = x.(1) in
let g_sigma = x.(2) in
let g_nu = x.(3) in
let g_rho = x.(4) in
{g_a; g_b; g_sigma; g_nu; g_rho}
in
let pricers = Array.map (fun (sw, _) -> pricer_of_swaption ~today ~zc sw) swaption_quotes in
let pricer params h =
try
for i = 0 to Array.length pricers - 1 do
h.(i) <- pricers.(i) params
done
with Sdomain -> raise Optimization.Infeasible
in
Optimization.least_squares ?feedback ~max_global ~parameters_of_vector ~pricer ~variables quotes
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
mli
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/g2pp_calibration.mli
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
(** G2++ 2-factors affine interest rate model. See Brigo and Mercurio
(2006), chapter 4.2 p142 for more details. *)
open Date
type swap_frequency =
| Freq_3M
| Freq_6M
| Freq_1Y
type swaption =
{
swaption_maturity_in_year: int;
swap_frequency: swap_frequency;
swap_term_in_year: int;
}
type parameters =
{
g_a : float;
g_b : float;
g_sigma : float;
g_nu : float;
g_rho : float;
}
(** A point in the calibration space of the G2++ model.
The model parameters of the G2++ model, with mean reversion parameters
[a] and [b], volatility parameters [sigma] and [nu] and correlation
coefficient [rho]. *)
exception Sdomain
(** This exception is raised by [swaption] if the numerical integration used in the
price calculation does not converge (indicating that the model parameters are
malformed). *)
val pricer_of_swaption: today: date -> zc:(date -> float) -> swaption -> (parameters -> float)
val black_price: today: date -> zc: (date -> float) -> swaption -> (float -> float)
val calibrate:
?feedback:(string -> unit) ->
max_global:int ->
today: date ->
swaption_quotes: (swaption * float) array ->
variables:Optimization.optimization_variable array ->
zc: (date -> float) ->
unit -> parameters Optimization.calibration_result
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/main.ml
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
open G2pp_calibration
open Date
let swaption_quotes =
[|
{swaption_maturity_in_year = 1; swap_term_in_year = 1; swap_frequency = Freq_6M}, 1.052;
{swaption_maturity_in_year = 2; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.81485;
{swaption_maturity_in_year = 3; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.6165;
{swaption_maturity_in_year = 4; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.46995;
{swaption_maturity_in_year = 5; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.38295;
{swaption_maturity_in_year = 6; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.3325;
{swaption_maturity_in_year = 7; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.3016;
{swaption_maturity_in_year = 8; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.2815;
{swaption_maturity_in_year = 9; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.26435;
{swaption_maturity_in_year = 10; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.2496;
{swaption_maturity_in_year = 15; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.2516;
{swaption_maturity_in_year = 20; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.28835;
{swaption_maturity_in_year = 25; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.27155;
{swaption_maturity_in_year = 30; swap_term_in_year = 1; swap_frequency = Freq_6M}, 0.23465;
{swaption_maturity_in_year = 1; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.61445;
{swaption_maturity_in_year = 2; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.54805;
{swaption_maturity_in_year = 3; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.46795;
{swaption_maturity_in_year = 4; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.3919;
{swaption_maturity_in_year = 5; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.3434;
{swaption_maturity_in_year = 6; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.3083;
{swaption_maturity_in_year = 7; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.28655;
{swaption_maturity_in_year = 8; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.2697;
{swaption_maturity_in_year = 9; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.25775;
{swaption_maturity_in_year = 10; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.2443;
{swaption_maturity_in_year = 15; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.26495;
{swaption_maturity_in_year = 20; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.28195;
{swaption_maturity_in_year = 25; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.26845;
{swaption_maturity_in_year = 30; swap_term_in_year = 2; swap_frequency = Freq_6M}, 0.20995;
{swaption_maturity_in_year = 1; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.5835;
{swaption_maturity_in_year = 2; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.49255;
{swaption_maturity_in_year = 3; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.42825;
{swaption_maturity_in_year = 4; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.3695;
{swaption_maturity_in_year = 5; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.329;
{swaption_maturity_in_year = 6; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.3022;
{swaption_maturity_in_year = 7; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.28165;
{swaption_maturity_in_year = 8; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.26615;
{swaption_maturity_in_year = 9; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.25485;
{swaption_maturity_in_year = 10; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.24375;
{swaption_maturity_in_year = 15; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.2718;
{swaption_maturity_in_year = 20; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.28135;
{swaption_maturity_in_year = 25; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.26865;
{swaption_maturity_in_year = 30; swap_term_in_year = 3; swap_frequency = Freq_6M}, 0.2131;
{swaption_maturity_in_year = 1; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.5415;
{swaption_maturity_in_year = 2; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.46235;
{swaption_maturity_in_year = 3; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.403;
{swaption_maturity_in_year = 4; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.3559;
{swaption_maturity_in_year = 5; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.3232;
{swaption_maturity_in_year = 6; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.29675;
{swaption_maturity_in_year = 7; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.27715;
{swaption_maturity_in_year = 8; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.26385;
{swaption_maturity_in_year = 9; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.254;
{swaption_maturity_in_year = 10; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.2454;
{swaption_maturity_in_year = 15; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.27845;
{swaption_maturity_in_year = 20; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.2821;
{swaption_maturity_in_year = 25; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.2678;
{swaption_maturity_in_year = 30; swap_term_in_year = 4; swap_frequency = Freq_6M}, 0.2131;
{swaption_maturity_in_year = 1; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.517;
{swaption_maturity_in_year = 2; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.446;
{swaption_maturity_in_year = 3; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.3903;
{swaption_maturity_in_year = 4; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.34755;
{swaption_maturity_in_year = 5; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.3166;
{swaption_maturity_in_year = 6; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.29305;
{swaption_maturity_in_year = 7; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.2745;
{swaption_maturity_in_year = 8; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.2639;
{swaption_maturity_in_year = 9; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.2534;
{swaption_maturity_in_year = 10; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.2499;
{swaption_maturity_in_year = 15; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.28315;
{swaption_maturity_in_year = 20; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.2825;
{swaption_maturity_in_year = 25; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.277;
{swaption_maturity_in_year = 30; swap_term_in_year = 5; swap_frequency = Freq_6M}, 0.21175;
{swaption_maturity_in_year = 1; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.478;
{swaption_maturity_in_year = 2; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.42105;
{swaption_maturity_in_year = 3; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.37715;
{swaption_maturity_in_year = 4; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.3378;
{swaption_maturity_in_year = 5; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.311;
{swaption_maturity_in_year = 6; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.2895;
{swaption_maturity_in_year = 7; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.2745;
{swaption_maturity_in_year = 8; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.264;
{swaption_maturity_in_year = 9; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.2573;
{swaption_maturity_in_year = 10; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.25475;
{swaption_maturity_in_year = 15; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.28815;
{swaption_maturity_in_year = 20; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.28195;
{swaption_maturity_in_year = 25; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.26015;
{swaption_maturity_in_year = 30; swap_term_in_year = 6; swap_frequency = Freq_6M}, 0.2097;
{swaption_maturity_in_year = 1; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.452;
{swaption_maturity_in_year = 2; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.4074;
{swaption_maturity_in_year = 3; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.368;
{swaption_maturity_in_year = 4; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.3307;
{swaption_maturity_in_year = 5; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.30645;
{swaption_maturity_in_year = 6; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.2877;
{swaption_maturity_in_year = 7; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.27475;
{swaption_maturity_in_year = 8; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.2664;
{swaption_maturity_in_year = 9; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.26155;
{swaption_maturity_in_year = 10; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.26035;
{swaption_maturity_in_year = 15; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.292;
{swaption_maturity_in_year = 20; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.2825;
{swaption_maturity_in_year = 25; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.25685;
{swaption_maturity_in_year = 30; swap_term_in_year = 7; swap_frequency = Freq_6M}, 0.2081;
{swaption_maturity_in_year = 1; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.43395;
{swaption_maturity_in_year = 2; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.39445;
{swaption_maturity_in_year = 3; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.35885;
{swaption_maturity_in_year = 4; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.3281;
{swaption_maturity_in_year = 5; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.30395;
{swaption_maturity_in_year = 6; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.28745;
{swaption_maturity_in_year = 7; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.2767;
{swaption_maturity_in_year = 8; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.27065;
{swaption_maturity_in_year = 9; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.26625;
{swaption_maturity_in_year = 10; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.26625;
{swaption_maturity_in_year = 15; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.2921;
{swaption_maturity_in_year = 20; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.2814;
{swaption_maturity_in_year = 25; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.25265;
{swaption_maturity_in_year = 30; swap_term_in_year = 8; swap_frequency = Freq_6M}, 0.2083;
{swaption_maturity_in_year = 1; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.42285;
{swaption_maturity_in_year = 2; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.3857;
{swaption_maturity_in_year = 3; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.3521;
{swaption_maturity_in_year = 4; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.3239;
{swaption_maturity_in_year = 5; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.30285;
{swaption_maturity_in_year = 6; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.2895;
{swaption_maturity_in_year = 7; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.2799;
{swaption_maturity_in_year = 8; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.27485;
{swaption_maturity_in_year = 9; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.2712;
{swaption_maturity_in_year = 10; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.27205;
{swaption_maturity_in_year = 15; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.29205;
{swaption_maturity_in_year = 20; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.27855;
{swaption_maturity_in_year = 25; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.24945;
{swaption_maturity_in_year = 30; swap_term_in_year = 9; swap_frequency = Freq_6M}, 0.219;
{swaption_maturity_in_year = 1; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.41765;
{swaption_maturity_in_year = 2; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.38095;
{swaption_maturity_in_year = 3; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.34795;
{swaption_maturity_in_year = 4; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.3217;
{swaption_maturity_in_year = 5; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.30365;
{swaption_maturity_in_year = 6; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.2916;
{swaption_maturity_in_year = 7; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.2842;
{swaption_maturity_in_year = 8; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.27985;
{swaption_maturity_in_year = 9; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.2769;
{swaption_maturity_in_year = 10; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.2775;
{swaption_maturity_in_year = 15; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.306;
{swaption_maturity_in_year = 20; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.2763;
{swaption_maturity_in_year = 25; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.2458;
{swaption_maturity_in_year = 30; swap_term_in_year = 10; swap_frequency = Freq_6M}, 0.22;
{swaption_maturity_in_year = 1; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.37905;
{swaption_maturity_in_year = 2; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.35465;
{swaption_maturity_in_year = 3; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.33505;
{swaption_maturity_in_year = 4; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.31725;
{swaption_maturity_in_year = 5; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.3008;
{swaption_maturity_in_year = 6; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.29075;
{swaption_maturity_in_year = 7; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.28365;
{swaption_maturity_in_year = 8; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.2787;
{swaption_maturity_in_year = 9; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.27385;
{swaption_maturity_in_year = 10; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.2709;
{swaption_maturity_in_year = 15; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.2689;
{swaption_maturity_in_year = 20; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.24225;
{swaption_maturity_in_year = 25; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.2096;
{swaption_maturity_in_year = 30; swap_term_in_year = 15; swap_frequency = Freq_6M}, 0.18285;
{swaption_maturity_in_year = 1; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.37975;
{swaption_maturity_in_year = 2; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.3605;
{swaption_maturity_in_year = 3; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.3407;
{swaption_maturity_in_year = 4; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.321;
{swaption_maturity_in_year = 5; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.3063;
{swaption_maturity_in_year = 6; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.29315;
{swaption_maturity_in_year = 7; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.28395;
{swaption_maturity_in_year = 8; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.2777;
{swaption_maturity_in_year = 9; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.27205;
{swaption_maturity_in_year = 10; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.26675;
{swaption_maturity_in_year = 15; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.24875;
{swaption_maturity_in_year = 20; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.21735;
{swaption_maturity_in_year = 25; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.1939;
{swaption_maturity_in_year = 30; swap_term_in_year = 20; swap_frequency = Freq_6M}, 0.17205;
{swaption_maturity_in_year = 1; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.38115;
{swaption_maturity_in_year = 2; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.3627;
{swaption_maturity_in_year = 3; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.34425;
{swaption_maturity_in_year = 4; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.3222;
{swaption_maturity_in_year = 5; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.3084;
{swaption_maturity_in_year = 6; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.2941;
{swaption_maturity_in_year = 7; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.28285;
{swaption_maturity_in_year = 8; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.2751;
{swaption_maturity_in_year = 9; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.2663;
{swaption_maturity_in_year = 10; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.26055;
{swaption_maturity_in_year = 15; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.2338;
{swaption_maturity_in_year = 20; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.20735;
{swaption_maturity_in_year = 25; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.1823;
{swaption_maturity_in_year = 30; swap_term_in_year = 25; swap_frequency = Freq_6M}, 0.1686;
{swaption_maturity_in_year = 1; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.38285;
{swaption_maturity_in_year = 2; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.3633;
{swaption_maturity_in_year = 3; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.34125;
{swaption_maturity_in_year = 4; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.3188;
{swaption_maturity_in_year = 5; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.30305;
{swaption_maturity_in_year = 6; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.2888;
{swaption_maturity_in_year = 7; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.2748;
{swaption_maturity_in_year = 8; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.26725;
{swaption_maturity_in_year = 9; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.25985;
{swaption_maturity_in_year = 10; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.25165;
{swaption_maturity_in_year = 15; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.2267;
{swaption_maturity_in_year = 20; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.1989;
{swaption_maturity_in_year = 25; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.18115;
{swaption_maturity_in_year = 30; swap_term_in_year = 30; swap_frequency = Freq_6M}, 0.16355;
|]
let named_variables =
let open Optimization in
[|
("a", Optimize_value {lower_bound = 0.; upper_bound = 1.; initial_value = 0.02});
("b", Optimize_value {lower_bound = 0.; upper_bound = 1.; initial_value = 0.02});
("sigma", Optimize_value {lower_bound = 0.; upper_bound = 0.2; initial_value = 0.04});
("nu", Optimize_value {lower_bound = 0.; upper_bound = 0.2; initial_value = 0.01});
("rho", Optimize_value {lower_bound = -1.; upper_bound = 1.; initial_value = 0.0});
|]
let variables = Array.map snd named_variables
let r = 0.03
let today = Date.of_string "2012-01-01"
let zc t = exp (-.0.03 *. (act_365 t today))
let sq x = x *. x
let () =
let {Optimization.cr_parameters = params; cr_root_mean_squared_error; cr_quoted_prices = _; cr_calibrated_prices = _} =
calibrate ~feedback: print_endline ~max_global: 2000 ~today ~swaption_quotes ~variables ~zc ()
in
let {g_a; g_b; g_sigma; g_nu; g_rho} = params in
let l = Array.to_list swaption_quotes in
let rms =
List.fold_left
(fun acc (swaption, quote) ->
let g2pp_price = pricer_of_swaption ~today ~zc swaption params in
let market_price = black_price ~today ~zc swaption quote in
Printf.printf "%dY%dY Swaption Calibrated Price: %.2f Market Price: %.2f\n" swaption.swaption_maturity_in_year swaption.swap_term_in_year (10000. *. g2pp_price) (10000. *. market_price);
acc +. sq ((g2pp_price -. market_price) /. market_price)
) 0. l;
in
let rms = 100. *. sqrt (rms /. (float (List.length l))) in
Printf.printf "a = %.5f, b = %.5f, sigma = %.5f, nu = %.5f, rho = %.5f\n" g_a g_b g_sigma g_nu g_rho;
Printf.printf "RMS = %.5f%%, re calculated RMS = %.5f%%\n" cr_root_mean_squared_error rms
let () =
try
let fn = Sys.getenv "OCAML_GC_STATS" in
let oc = open_out fn in
Gc.print_stat oc
with _ -> ()
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/math.ml
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
let p, a1, a2, a3, a4, a5 = 0.3275911, 0.254829592, (-0.284496736), 1.421413741, (-1.453152027), 1.061405429
let erf x =
let t = 1. /. (1. +. p *. x) in
let t2 = t *. t in
let t3 = t *. t2 in
let t4 = t *.t3 in
let t5 = t *. t4 in
1. -. (a1 *. t +. a2 *. t2 +. a3 *. t3 +. a4 *. t4 +. a5 *. t5) *. exp (-.x *. x)
(** Unit gaussian CDF. *)
let ugaussian_P x =
let u = x /. sqrt 2. in
let erf = if u < 0. then -.erf (-.u) else erf u in
0.5 *. (1. +. erf)
module Rootfinder = struct
type error =
| NotbracketedBelow
| NotbracketedAbove
let string_of_error = function
| NotbracketedBelow -> "Interval borders have both negative values."
| NotbracketedAbove -> "Interval borders have both positive values."
exception Rootfinder of error
let brent a b eval eps =
if a > b then invalid_arg "Math.brent: arguments should verify xlo <= xhi.";
let fa, fb = eval a, eval b in
if 0. < fa *. fb then raise(Rootfinder(if fa < 0. then NotbracketedBelow else NotbracketedAbove));
assert (0. <= eps);
let maxit = 10_000 in
let a, fa, b, fb = if abs_float fa < abs_float fb then b, fb, a, fa else a, fa, b, fb in
(* The root is between a and b, such that |f(b)| < |f(a)| *)
let rec iter i ~a ~b ~c ~d ~fa ~fb ~fc mflag =
if abs_float (b -. a) < eps || fb = 0. || maxit < i then b (* stop condition *)
else
let s =
if fa <> fc && fb <> fc then
a *. fb *. fc /. ((fa -. fb) *. (fa -. fc)) +. b *. fa *. fc /. ((fb -. fa) *. (fb -. fc)) +. c *. fa *. fb /. ((fc -. fa) *. (fc -. fb)) (* inverse quadratic interpolation *)
else
b -. fb *. (b -. a) /. (fb -. fa) (* secant rule *)
in
let s, mflag =
if
(4. *. s < 3. *. a +. b || b < s) ||
(mflag && 2. *. abs_float (s -. b) >= abs_float (b -. c)) ||
(not mflag && 2. *. abs_float (s -. b) >= abs_float (c -. d)) ||
(mflag && abs_float (b -. c) < eps) ||
(not mflag && abs_float (c -. d) < eps)
then 0.5 *. (a +. b), true else s, false
in
let fs = eval s in
(* d <- c; c <- b; *)
if fa *. fs < 0. then (* in this case, b <- s *)
if abs_float fa < abs_float fs then iter (i + 1) ~a: s ~b: a ~c: b ~d: c ~fa: fs ~fb: fa ~fc: fb mflag (* switch a, b *)
else iter (i + 1) ~a ~b: s ~c: b ~d: c ~fa ~fb: fs ~fc: fb mflag
else (* in this case, a <- s *)
if abs_float fs < abs_float fb then iter (i + 1) ~a: b ~b: s ~c: b ~d: c ~fa: fb ~fb: fs ~fc: fb mflag (* switch a, b *)
else iter (i + 1) ~a: s ~b ~c: b ~d: c ~fa: fs ~fb ~fc: fb mflag
in
iter 0 ~a ~b ~c: a ~d: nan ~fa ~fb ~fc: fa true
end
module Gaussian_quadrature =
struct
let gauss_hermite_coefficients =
[|
0.; 0.6568095668820999044613; -0.6568095668820997934390; -1.3265570844949334805563; 1.3265570844949330364670; 2.0259480158257567872226;
-2.0259480158257558990442; -2.7832900997816496513337; 2.7832900997816474308877; 3.6684708465595856630159; -3.6684708465595838866591
|],
[|
0.6547592869145917315876; 0.6609604194409607336169; 0.6609604194409606225946; 0.6812118810666693002887; 0.6812118810666689672217; 0.7219536247283847574252;
0.7219536247283852015144; 0.8025168688510405656800; 0.8025168688510396775015; 1.0065267861723647957461; 1.0065267861723774522886
|]
end
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
mli
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/math.mli
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
val ugaussian_P : float -> float
(** The cumulative distribution function for a normal variate with mean 0 and
variance 1. [ugaussian_P x] returns the probability that a variate takes a
value less than or equal to [x]. *)
module Rootfinder: sig
type error =
| NotbracketedBelow (** The function is below zero on both the given brackets. *)
| NotbracketedAbove (** The function is above zero on both the given brackets. *)
val string_of_error: error -> string
(** Pretty-printing of error. *)
exception Rootfinder of error
val brent: float -> float -> (float -> float) -> float -> float
(** [brent xlo xhi f eps] finds a root of function [f] given that
it is bracketed by [xlo, xhi]. [eps] is the absolute error on the
returned root. Raises {!Rootfinder.Rootfinder} exception when an error is encountered.
The root is found using brent's method (http://en.wikipedia.org/wiki/Brent's_method).
Requires [xlo < xhi]. *)
end
module Gaussian_quadrature:
sig
val gauss_hermite_coefficients: float array * float array
(** [gauss_hermite_coefficients nb_points] returns two arrays [x] and [w] such that
for all [f], the integral of [f] over \]-infty; infty\[ is approximated by \sum w_i f(x_i).
the approximation is good if [f(x)] is close to [exp(-x^2) * P(x)] with [P] a polynomial, and is exact
if [P] is a polynomial of degree less or equal to [2 * nb_points - 1]
*)
end
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/optimization.ml
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
(* Optimizations algorithm. *)
type termination =
{
maxit: int;
maxf: int;
target: float;
}
type status =
| Maxit_reached
| Maxf_reached
| Target_reached
type result =
{
x0: float array;
f: float;
nb_feval: int;
status: status;
}
let ( ** ) (x, f) r = match x with | None -> r | Some x -> f r x
exception Infeasible
let f_incr f ncalls x =
let f =
try
f x
with
| Infeasible -> infinity
in
incr ncalls;
f
module Rand = Random.State
module DE =
struct
type t =
{
np: int; (* Population size *)
cr: float; (* Crossover probability, in [0; 1] *)
}
let default_parameters n = {np = min (10 * n) 40; cr = 0.9;}
let parameters ?np ?cr n =
(cr, fun r cr -> {r with cr}) **
(np, fun r np -> {r with np}) **
default_parameters n
let optimize {np; cr;} ~f ~lower_bounds ~upper_bounds ~call_back ~termination =
let n = Array.length lower_bounds in
let rng = Rand.make [| 0 |] in
let ncalls = ref 0 in
let f = f_incr f ncalls in
let {maxit; maxf; target;} = termination in
let fx = Array.make np 0. in
let fx0 = ref infinity in (* current min *)
let v = Array.make_matrix np n 0. in (* potential mutations *)
let best_idx = ref 0 in (* index of x0 in x *)
(* initialize current population *)
let x =
Array.init np
(fun i ->
let x_i = Array.init n
(fun j ->
let blo = lower_bounds.(j) in
let db = upper_bounds.(j) -. blo in
blo +. db *. Rand.float rng 1.)
in
let f = f x_i in
fx.(i) <- f;
if f < !fx0 then
begin
best_idx := i;
fx0 := f;
call_back !ncalls f
end;
x_i)
in
let x0 = Array.copy x.(!best_idx) in
let mutation difw i x_i v_i =
(* draw successively _different_ random integers in [0; np - 1] \ {i} *)
let drawn = ref [i] in
let range = ref (np - 1) in
let rand () =
let res = ref 0 in
let rec adjust v = function
| drawn :: others when drawn <= v -> drawn :: adjust (v + 1) others
| drawn -> res := v; v :: drawn
in
drawn := adjust (Rand.int rng !range) !drawn;
decr range;
x.(!res)
in
let x_r1 = if Rand.float rng 1. <= 0.5 then x.(!best_idx) else rand () in
let x_r2 = rand () in
let x_r3 = rand () in
let j0 = Rand.int rng n in
for j = 0 to n - 1 do
let v =
let aux = x_r1.(j) +. difw *. (x_r2.(j) -. x_r3.(j)) in
if (j = j0 || Rand.float rng 1. <= cr) && lower_bounds.(j) <= aux && aux <= upper_bounds.(j) then
aux
else
x_i.(j)
in
v_i.(j) <- v
done
in
let recombination () =
Array.iteri
(fun i v_i ->
let f = f v_i in
if f < fx.(i) then
begin
fx.(i) <- f;
Array.blit v_i 0 x.(i) 0 n;
if f < !fx0 then
begin
best_idx := i;
fx0 := f;
call_back !ncalls f;
Array.blit v_i 0 x0 0 n
end;
end;
)
v
in
let rec iter nb_it =
let differential_weight = 0.5 +. Rand.float rng 0.5 in (* As recommanded on http://www.icsi.berkeley.edu/~storn/code.html#prac *)
Array.iteri (fun i x_i -> mutation differential_weight i x_i v.(i)) x;
recombination ();
let res status = {x0; f = !fx0; nb_feval = !ncalls; status} in
if !fx0 <= target then res Target_reached
else if maxf < !ncalls then res Maxf_reached
else if nb_it = 0 then res Maxit_reached
else iter (nb_it - 1)
in
iter maxit
end
type range =
{
lower_bound: float;
upper_bound: float;
initial_value: float;
}
type optimization_variable =
| Fixed_value of float
| Optimize_value of range
type 'a calibration_result =
{
cr_parameters: 'a;
cr_root_mean_squared_error: float; (* Calibrated rms. *)
cr_quoted_prices: float array; (* i.e. quoted_prices. *)
cr_calibrated_prices: float array; (* Closed-form prices obtained with calibrated parameters. *)
}
let least_squares
?absolute
?feedback
~max_global
~parameters_of_vector
~pricer
~variables
quotes
=
begin
match feedback with
| Some feedback -> feedback "Calibrating"
| _ -> ()
end;
let free_var_index_to_var_index, strict_subset, x, lower_bounds, upper_bounds =
let _i, free_vars_to_vars, strict_subset, x, lo, up =
Array.fold_left
(fun (i, free_vars_to_vars, strict_subset, x, lo, up) -> function
| Fixed_value _ -> i + 1, free_vars_to_vars, true, x, lo, up
| Optimize_value{initial_value; lower_bound; upper_bound} -> i + 1, i :: free_vars_to_vars, strict_subset, initial_value :: x, lower_bound :: lo, upper_bound :: up
)
(0, [], false, [], [], [])
variables
in
Array.of_list(List.rev free_vars_to_vars), strict_subset, x, Array.of_list(List.rev lo), Array.of_list(List.rev up)
in
let parameters_of_active_vars = match strict_subset with
| false -> parameters_of_vector
| true ->
let all_vars = Array.map (function | Fixed_value x -> x | Optimize_value _ -> nan) variables in
fun x ->
Array.iteri (fun i x -> all_vars.(free_var_index_to_var_index.(i)) <- x) x;
parameters_of_vector all_vars
in
let m = Array.length quotes in
let prices = Array.make m 0. in
let norm = match absolute with
| None -> fun acc price quote -> let rel = (price -. quote) /. quote in acc +. rel *. rel
| Some() -> fun acc price quote -> let dif = price -. quote in acc +. dif *. dif
in
let quotes_idx = Array.(init (length quotes) (fun i -> i)) in
let distance prices = Array.fold_left (fun acc i -> norm acc prices.(i) quotes.(i)) 0. quotes_idx in (* objective is L_2 norm *)
let rms_of_error =
let div = 10000. /. float_of_int m in
fun err -> sqrt (err *. div) in
(* Initial guess either from global optimization or argument of the calibration routine. *)
let x =
if max_global > 0 then
let call_back =
match feedback with
| None -> fun _ _ -> ()
| Some f -> (fun evals dist -> Printf.ksprintf f "Global Optimizer Evals: %5i RMS: %12.8g%%" evals (rms_of_error dist))
in
let f x =
pricer (parameters_of_active_vars x) prices;
distance prices
in
let {x0; _} = DE.optimize (DE.default_parameters (Array.length lower_bounds)) ~f ~lower_bounds ~upper_bounds ~call_back ~termination: {maxit = max_int; maxf = max_global; target = 0.;} in
x0
else
Array.of_list(List.rev x)
in
let cr_quoted_prices = quotes in
let cr_parameters = parameters_of_active_vars x in
pricer cr_parameters prices;
{
cr_parameters;
cr_root_mean_squared_error = rms_of_error (distance prices);
cr_quoted_prices;
cr_calibrated_prices = prices;
}
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
mli
|
js_of_ocaml-6.2.0/benchmarks/benchmark-others/lexifi-g2pp/optimization.mli
|
(***************************************************************************)
(* Copyright (C) 2000-2013 LexiFi SAS. All rights reserved. *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
(* it under the terms of the GNU General Public License as published *)
(* by the Free Software Foundation, either version 3 of the License, *)
(* or (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
(* You should have received a copy of the GNU General Public License *)
(* along with this program. If not, see <http://www.gnu.org/licenses/>. *)
(***************************************************************************)
type termination =
{
maxit: int;
maxf: int;
target: float;
}
type status =
| Maxit_reached
| Maxf_reached
| Target_reached
type result =
{
x0: float array;
f: float;
nb_feval: int;
status: status;
}
module DE:
(** Implementation based on Differential Evolution - A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces,
Rainer Storn and Kenneth Price.
Implemented srategies is a mixture of DE/rand/1/bin and DE/best/1/bin. The mutatant is lambda *. DE/rand/1/bin +. (1. -. lambda) *. DE/best/1/bin
where lambda is randomly choosen for each generation.
*)
sig
type t
val default_parameters: int -> t
val parameters: ?np: int -> ?cr: float -> int -> t
end
(** {2 Least Square Minimization} *)
exception Infeasible
(** To be raised by optimization callback functions to indicate that a point is infeasible. *)
type 'a calibration_result =
{
cr_parameters: 'a;
cr_root_mean_squared_error: float;
cr_quoted_prices: float array;
cr_calibrated_prices: float array;
}
(** General calibration result. It contains the model parameters of type ['a]
and some optional additional informations:
- [cr_parameters]. The optimal model parameter set
- [cr_root_mean_squared_error]. Root-mean-squared error of optimal fit
- [cr_quoted_prices]. Quotes to be fitted
- [cr_calibrated_prices]. Optimal model price of each quote
*)
type range = {
lower_bound: float;
upper_bound: float;
initial_value: float;
}
type optimization_variable =
| Fixed_value of float
| Optimize_value of range
val least_squares:
?absolute: unit ->
?feedback: (string -> unit) ->
max_global:int ->
parameters_of_vector:(float array -> 'parameters) ->
pricer:('parameters -> float array -> unit) ->
variables:optimization_variable array ->
float array ->
'parameters calibration_result
(** [least_squares ~pricer ~lo ~up quotes] outputs a vector of calibrated parameters. These calibrated parameters
correspond to the least square fitting of quotes from the [quotes] list and results of applying the [price] function.
This optimization is done first using Direct as a global optimizer then using Minpack as a local optimizer.
The input are:
- [pricer] is the pricer function; it takes as input a vector of parameters (to be optimized) and a price vector.
The price vector is filled by this function in order to be compared to quotes from the [quotes] list.
- [x] is the original value for the parameters. This is only used if no global optimization is performed, i.e. if [max_global] is 0.
- [lo] contains lower bounds for each parameters.
- [up] contains upper bounds for each parameters.
- [quotes] is the list of quotes to be matched by the least-square algorithm.
Optional parameters are:
- [absolute] is an optional parameter. If set, the distance is the absolute difference, not the default relative one.
- [feedback] is a feedback function that can be used to print the current RMS.
- [max_global] is the maximum number of steps performed in the global optimization (DE).
- [max_local] is the maximum number of steps performed in the local optimization (Minpack).
Note that [x], [lo], and [up] must have the same size. This size is the number of parameters, it is also equal to the size of
the vector in the output and should be equal to the size of the vector used as the first argument of the [price] function.
The size of the second argument of the [price] function should be equal to the length of the [quotes] list.
*)
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/benchmark-partial-render-table/summarize_results.ml
|
let delim = Str.regexp_string "│"
let geometric_mean l =
exp (List.fold_left ( +. ) 0. (List.map log l) /. float (List.length l))
let parse s =
Scanf.sscanf (String.trim s) "%f%s"
@@ fun f u ->
match u with
| "ns" -> f *. 1e-6
| "us" -> f *. 1e-3
| "ms" -> f
| "s" -> f *. 1e3
| _ -> assert false
let () =
let measures = ref [] in
(try
while true do
let l = read_line () in
if String.starts_with ~prefix:"├" l
then
let l = read_line () |> Str.split delim |> List.tl |> List.map parse in
measures := l @ !measures
done
with End_of_file -> ());
Format.printf
{|{ "name": "%s",
"results":
[ { "name": "Partial Render Table",
"metrics":
[ { "name": "Execution time (geometric mean)",
"units": "ms",
"value": %f } ] } ] }@.|}
(String.capitalize_ascii Sys.argv.(1))
(geometric_mean !measures)
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/common.ml
|
(* Js_of_ocaml benchmarks
* http://www.ocsigen.org/js_of_ocaml/
* Copyright (C) 2011 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open StdLabels
let split_on_char ~sep s =
let r = ref [] in
let j = ref (String.length s) in
for i = String.length s - 1 downto 0 do
if String.unsafe_get s i = sep
then (
r := String.sub s ~pos:(i + 1) ~len:(!j - i - 1) :: !r;
j := i)
done;
String.sub s ~pos:0 ~len:!j :: !r
let mean a =
let s = ref 0. in
for i = 0 to Array.length a - 1 do
s := !s +. a.(i)
done;
!s /. float (Array.length a)
let mean_variance a =
let m = mean a in
let s = ref 0. in
for i = 0 to Array.length a - 1 do
let d = a.(i) -. m in
s := !s +. (d *. d)
done;
(* https://en.wikipedia.org/wiki/Unbiased_estimation_of_standard_deviation
https://en.wikipedia.org/wiki/Bessel%27s_correction *)
m, !s /. float (Array.length a - 1)
(* 90% 95% 98% 99% 99.5% 99.8% 99.9%*)
let tinv_table =
[| 1, [| 6.314; 12.71; 31.82; 63.66; 127.3; 318.3; 636.6 |]
; 2, [| 2.920; 4.303; 6.965; 9.925; 14.09; 22.33; 31.60 |]
; 3, [| 2.353; 3.182; 4.541; 5.841; 7.453; 10.21; 12.92 |]
; 4, [| 2.132; 2.776; 3.747; 4.604; 5.598; 7.173; 8.610 |]
; 5, [| 2.015; 2.571; 3.365; 4.032; 4.773; 5.893; 6.869 |]
; 6, [| 1.943; 2.447; 3.143; 3.707; 4.317; 5.208; 5.959 |]
; 7, [| 1.895; 2.365; 2.998; 3.499; 4.029; 4.785; 5.408 |]
; 8, [| 1.860; 2.306; 2.896; 3.355; 3.833; 4.501; 5.041 |]
; 9, [| 1.833; 2.262; 2.821; 3.250; 3.690; 4.297; 4.781 |]
; 10, [| 1.812; 2.228; 2.764; 3.169; 3.581; 4.144; 4.587 |]
; 11, [| 1.796; 2.201; 2.718; 3.106; 3.497; 4.025; 4.437 |]
; 12, [| 1.782; 2.179; 2.681; 3.055; 3.428; 3.930; 4.318 |]
; 13, [| 1.771; 2.160; 2.650; 3.012; 3.372; 3.852; 4.221 |]
; 14, [| 1.761; 2.145; 2.624; 2.977; 3.326; 3.787; 4.140 |]
; 15, [| 1.753; 2.131; 2.602; 2.947; 3.286; 3.733; 4.073 |]
; 16, [| 1.746; 2.120; 2.583; 2.921; 3.252; 3.686; 4.015 |]
; 17, [| 1.740; 2.110; 2.567; 2.898; 3.222; 3.646; 3.965 |]
; 18, [| 1.734; 2.101; 2.552; 2.878; 3.197; 3.610; 3.922 |]
; 19, [| 1.729; 2.093; 2.539; 2.861; 3.174; 3.579; 3.883 |]
; 20, [| 1.725; 2.086; 2.528; 2.845; 3.153; 3.552; 3.850 |]
; 21, [| 1.721; 2.080; 2.518; 2.831; 3.135; 3.527; 3.819 |]
; 22, [| 1.717; 2.074; 2.508; 2.819; 3.119; 3.505; 3.792 |]
; 23, [| 1.714; 2.069; 2.500; 2.807; 3.104; 3.485; 3.767 |]
; 24, [| 1.711; 2.064; 2.492; 2.797; 3.091; 3.467; 3.745 |]
; 25, [| 1.708; 2.060; 2.485; 2.787; 3.078; 3.450; 3.725 |]
; 26, [| 1.706; 2.056; 2.479; 2.779; 3.067; 3.435; 3.707 |]
; 27, [| 1.703; 2.052; 2.473; 2.771; 3.057; 3.421; 3.690 |]
; 28, [| 1.701; 2.048; 2.467; 2.763; 3.047; 3.408; 3.674 |]
; 29, [| 1.699; 2.045; 2.462; 2.756; 3.038; 3.396; 3.659 |]
; 30, [| 1.697; 2.042; 2.457; 2.750; 3.030; 3.385; 3.646 |]
; 40, [| 1.684; 2.021; 2.423; 2.704; 2.971; 3.307; 3.551 |]
; 50, [| 1.676; 2.009; 2.403; 2.678; 2.937; 3.261; 3.496 |]
; 60, [| 1.671; 2.000; 2.390; 2.660; 2.915; 3.232; 3.460 |]
; 80, [| 1.664; 1.990; 2.374; 2.639; 2.887; 3.195; 3.416 |]
; 100, [| 1.660; 1.984; 2.364; 2.626; 2.871; 3.174; 3.390 |]
; 120, [| 1.658; 1.980; 2.358; 2.617; 2.860; 3.160; 3.373 |]
|]
let tinv_row n =
let i = ref 1 in
let l = Array.length tinv_table in
while !i < l && fst tinv_table.(!i) <= n do
incr i
done;
snd tinv_table.(!i - 1)
let tinv95 n = (tinv_row n).(1)
let tinv98 n = (tinv_row n).(2)
let tinv99 n = (tinv_row n).(3)
let mean_with_confidence a =
let m, v = mean_variance a in
let l = Array.length a in
m, sqrt v /. sqrt (float l) *. tinv98 (l - 1)
let src = "sources"
let code = "build"
let hostname = Unix.gethostname ()
module Measure = struct
type t =
{ name : string
; units : string
; description : string option
; trend : string option
; path : string
; color : string option
}
end
let times =
Measure.
{ name = "execution-time"
; units = "s"
; description = Some "Execution time"
; trend = Some "lower-is-better"
; path = Filename.concat "results/times" hostname
; color = None
}
let sizes =
Measure.
{ name = "code-size"
; units = "B"
; description = Some "Code size"
; trend = Some "lower-is-better"
; path = "results/sizes"
; color = None
}
let compiletimes =
Measure.
{ name = "compile-time"
; units = "s"
; description = Some "Compile time"
; trend = Some "lower-is-better"
; path = Filename.concat "results/compiletimes" hostname
; color = None
}
module Spec : sig
type t
val name : t -> string
val create : string -> string -> t
val dir : root:string -> t -> string
val file : root:string -> t -> string -> string
val no_ext : t -> t
val sub_spec : t -> string -> t
val find_names : root:string -> t -> string list
val ml : t
val js : t
val byte : t
val opt : t
val js_of_ocaml : t
val js_of_ocaml_o3 : t
val js_of_ocaml_js_string : t
val wasm_of_ocaml : t
val byte_unsafe : t
val opt_unsafe : t
val js_of_ocaml_unsafe : t
val js_of_ocaml_inline : t
val js_of_ocaml_deadcode : t
val js_of_ocaml_compact : t
val js_of_ocaml_call : t
val js_of_ocaml_effects_cps : t
val js_of_ocaml_effects_double_translation : t
end = struct
type t =
{ dir : string
; ext : string
}
let name { dir; _ } = dir
let create dir ext = { dir; ext }
let no_ext { dir; _ } = { dir; ext = "" }
let file ~root { dir; ext } nm = Format.sprintf "%s/%s/%s%s" root dir nm ext
let dir ~root { dir; _ } = Format.sprintf "%s/%s" root dir
let sub_spec { dir; ext } loc = { dir = Format.sprintf "%s/%s" dir loc; ext }
let find_names ~root spec =
let dir = dir ~root spec in
Sys.readdir dir
|> Array.to_list
|> List.filter ~f:(fun nm ->
let open Unix in
match stat (dir ^ "/" ^ nm) with
| { st_kind = S_REG | S_LNK; _ } -> true
| _ -> false)
|> (if spec.ext = ""
then fun x -> x
else
fun x ->
x
|> List.filter ~f:(fun nm -> Filename.check_suffix nm spec.ext)
|> List.map ~f:Filename.chop_extension)
|> List.sort ~cmp:compare
let ml = create "ml" ".ml"
let js = create "js" ".js"
let byte = create "byte" ""
let opt = create "opt" ""
let js_of_ocaml = create "js_of_ocaml" ".js"
let js_of_ocaml_o3 = create "o3" ".js"
let js_of_ocaml_js_string = create "jsstring" ".js"
let wasm_of_ocaml = create "wasm_of_ocaml" ".js"
let byte_unsafe = create "unsafe/byte" ""
let opt_unsafe = create "unsafe/opt" ""
let js_of_ocaml_unsafe = create "unsafe/js_of_ocaml" ".js"
let js_of_ocaml_inline = create "noinline" ".js"
let js_of_ocaml_deadcode = create "nodeadcode" ".js"
let js_of_ocaml_compact = create "notcompact" ".js"
let js_of_ocaml_call = create "nooptcall" ".js"
let js_of_ocaml_effects_cps = create "effects-cps" ".js"
let js_of_ocaml_effects_double_translation = create "effects-double-translation" ".js"
end
let rec mkdir d =
if not (Sys.file_exists d)
then (
mkdir (Filename.dirname d);
Unix.mkdir d 0o777)
let need_update src dst =
try
let d = Unix.stat dst in
d.Unix.st_kind <> Unix.S_REG
||
let s = Unix.stat src in
d.Unix.st_mtime < s.Unix.st_mtime
with Unix.Unix_error (Unix.ENOENT, _, _) -> true
let measures_need_update code meas spec nm =
let p = Spec.file ~root:code spec nm in
let m = Spec.file ~root:meas.Measure.path (Spec.no_ext spec) nm in
need_update p m
let read_measures path spec nm =
let m = Spec.file ~root:path (Spec.no_ext spec) nm in
let l = ref [] in
if Sys.file_exists m
then (
let ch = open_in m in
(try
while true do
l := float_of_string (input_line ch) :: !l
done
with End_of_file -> ());
close_in ch;
!l)
else []
let write_measures meas spec nm l =
let m = Spec.file ~root:meas.Measure.path (Spec.no_ext spec) nm in
let tmp = Spec.file ~root:meas.Measure.path (Spec.no_ext spec) "_tmp_" in
mkdir (Spec.dir ~root:meas.Measure.path spec);
let ch = open_out tmp in
List.iter ~f:(fun t -> Printf.fprintf ch "%f\n" t) (List.rev l);
close_out ch;
Sys.rename tmp m
let read_interpreter_config file =
if not (Sys.file_exists file)
then (
Format.eprintf "Configuration file '%s' not found!@." file;
exit 1);
let i = ref [] in
let ch = open_in file in
(try
while true do
let line = String.trim (input_line ch) in
if line.[0] <> '#'
then
match
List.filter
~f:(function
| "" -> false
| _ -> true)
(split_on_char line ~sep:' ')
with
| "interpreter" :: nm :: rem -> i := (String.concat ~sep:" " rem, nm) :: !i
| [ "interpreter" ] ->
Format.eprintf "Malformed config option '%s'@." line;
exit 1
| kind :: _ ->
Format.eprintf "Unknown config option '%s'@." kind;
exit 1
| [] ->
Format.eprintf "Bad config line '%s'@." line;
exit 1
done
with End_of_file -> ());
close_in ch;
List.rev !i
let read_report_config ?(column_ref = -1) file =
if not (Sys.file_exists file)
then (
Format.eprintf "Configuration file '%s' not found!@." file;
exit 1);
let fullinfo = ref [] in
let info = ref [] in
let i = ref 0 in
let reference = ref false in
let ch = open_in file in
let split_at_space l =
try
let i = String.index l ' ' in
String.sub l ~pos:0 ~len:i, String.sub l ~pos:(i + 1) ~len:(String.length l - i - 1)
with Not_found -> l, ""
in
let get_info measure rem refe =
let dir0 = measure.Measure.path in
let dir1, rem = split_at_space rem in
let dir2, rem = split_at_space rem in
let color, title = split_at_space rem in
let dir1 = if dir1 = "\"\"" then dir0 else dir0 ^ "/" ^ dir1 in
let name = String.concat ~sep:"-" [ measure.Measure.name; title ] in
let description =
match measure.Measure.description with
| None -> None
| Some d -> Some (String.concat ~sep:", " [ d; title ])
in
let measure = Measure.{ measure with name; description; color = Some color } in
info := Some (dir1, dir2, measure, refe) :: !info
in
(try
while true do
let l = input_line ch in
if String.length l = 0
then (
if !info <> []
then (
fullinfo := List.rev !info :: !fullinfo;
info := [];
i := 0))
else if l.[0] <> '#'
then (
incr i;
reference := column_ref = !i;
let kind, rem = split_at_space l in
let kind2, rem = split_at_space rem in
(match kind with
| "histogram" -> ()
| "histogramref" when column_ref < 0 -> reference := true
| _ ->
Format.eprintf "Unknown config options '%s'@." kind;
exit 1);
match kind2 with
| "blank" -> info := None :: !info
| "times" -> get_info times rem !reference
| "compiletimes" -> get_info compiletimes rem !reference
| "sizes" -> get_info sizes rem !reference
| _ ->
Format.eprintf "Unknown config options '%s'@." kind2;
exit 1)
done
with End_of_file -> ());
close_in ch;
if !info <> [] then fullinfo := List.rev !info :: !fullinfo;
List.rev !fullinfo
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
dune
|
js_of_ocaml-6.2.0/benchmarks/dune
|
(executables
(names report run stripdebug)
(libraries unix compiler-libs.bytecomp yojson))
(alias
(name default)
(deps report.exe run.exe))
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/report.ml
|
(* Js_of_ocaml benchmarks
* http://www.ocsigen.org/js_of_ocaml/
* Copyright (C) 2011 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open StdLabels
open Common
let reference = ref None
let maximum = ref (-1.)
let minimum = ref 0.
let omitted = ref []
let appended = ref []
let errors = ref false
let svg = ref false
let svgfontsize = ref 7
let svgwidth = ref 500
let svgheight = ref 150
let edgecaption = ref false
let ylabel = ref ""
let rec merge f l1 l2 =
match l1, l2 with
| [], _ | _, [] -> []
| (n1, v1) :: r1, (n2, v2) :: r2 ->
if n1 < n2
then merge f r1 l2
else if n1 > n2
then merge f l1 r2
else (n1, f v1 v2) :: merge f r1 r2
let merge_blank = List.map ~f:(fun (n2, v2) -> n2, (0.0, 0.0) :: v2)
let read_column ~measure path spec refe :
(Measure.t option list * (string * (float * float) list) list) option =
let l =
List.map
(Spec.find_names ~root:path (Spec.no_ext spec))
~f:(fun nm ->
let l = read_measures path spec nm in
let a = Array.of_list l in
let m, i = mean_with_confidence a in
nm, [ m, i ])
in
if refe then reference := Some l;
Some ([ Some measure ], l)
let read_blank_column () = None
let rec list_create n a = if n = 0 then [] else a :: list_create (n - 1) a
let merge_columns l old_table =
let rec aux = function
| [] | [ None ] -> [], []
| [ Some c ] -> c
| Some (h, c) :: r ->
let h', t = aux r in
h @ h', merge (fun v1 v2 -> v1 @ v2) c t
| None :: r ->
let h', t = aux r in
(*VVV utile ? *)
None :: h', merge_blank t
in
let rec remove_head_blank = function
| None :: l ->
let n, ll = remove_head_blank l in
n + 1, ll
| l -> 0, l
in
let add_blanks n (h, t) =
if n = 0
then h, t
else
let zeros = list_create n (0.0, 0.0) in
(*VVV utile ? *)
let nodisplays = list_create n None in
h @ nodisplays, List.map t ~f:(fun (a, l) -> a, l @ zeros)
in
(* if there was an old table, we keep only the lines corresponding
to entries in that table *)
let l =
match l, old_table with
| [], _ -> []
| _, None -> l
| Some (h, c) :: ll, Some o -> Some (h, merge (fun v1 _v2 -> v1) c o) :: ll
| None :: ll, Some o ->
Some ([ None ], List.map o ~f:(fun (nm, _) -> nm, [ 0.0, 0.0 ])) :: ll
in
let nb_blanks, l = remove_head_blank (List.rev l) in
let l = List.rev l in
add_blanks nb_blanks (aux l)
let normalize (h, t) =
match !reference with
| None -> h, t
| Some rr ->
( h
, List.map t ~f:(fun (nm, l) ->
let r, _ = List.hd (List.assoc nm rr) in
if r <> r
then (
Format.eprintf "No reference available for '%s'@." nm;
exit 1);
nm, List.map l ~f:(fun (v, i) -> v /. r, i /. r)) )
let stats (h, t) =
for i = 0 to List.length h - 1 do
match List.nth h i with
| Some Measure.{ name = nm; _ } ->
let l = List.map t ~f:(fun (_, l) -> fst (List.nth l i)) in
let a = Array.of_list l in
Array.sort a ~cmp:compare;
let p = List.fold_right l ~f:(fun x p -> x *. p) ~init:1. in
Format.eprintf
"%s:@. %f %f@."
nm
(p ** (1. /. float (List.length l)))
a.(Array.length a / 2)
| None -> ()
done
let escape_name_for_gnuplot s =
let b = Buffer.create (String.length s) in
String.iter s ~f:(function
| '_' -> Buffer.add_string b {|\\\_|}
| c -> Buffer.add_char b c);
Buffer.contents b
let text_output _no_header (h, t) =
Format.printf "-";
List.iter h ~f:(fun v ->
let nm =
match v with
| Some Measure.{ name; _ } -> name
| None -> ""
in
Format.printf " - \"%s\"" nm);
Format.printf "@.";
List.iter t ~f:(fun (nm, l) ->
Format.printf "%s" nm;
List.iter l ~f:(fun (m, i) -> Format.printf " %f %f" m i);
Format.printf "@.")
let gnuplot_output ch no_header (h, t) =
let n = List.length (snd (List.hd t)) in
if not no_header
then (
if !svg
then
Printf.fprintf
ch
"set terminal svg size %d %d font 'Arial,%d'\n"
!svgwidth
!svgheight
!svgfontsize;
if !edgecaption
then Printf.fprintf ch "set key tmargin horizontal Left left reverse\n";
Printf.fprintf
ch
"set multiplot\n\
set style data histograms\n\
set style fill solid 1 border rgb 'black'\n\
set style histogram errorbars gap 1%s\n\
set xtics border in scale 0,0 nomirror rotate by -30 offset character 0, 0, 0\n"
(if !errors then " lw 1" else "");
if !ylabel <> "" then Printf.fprintf ch "set ylabel \"%s\"\n" !ylabel;
if !maximum > 0.
then Printf.fprintf ch "set yrange [%f:%f]\n" !minimum !maximum
else Printf.fprintf ch "set yrange [0:]\n");
(* labels *)
for i = 0 to n - 1 do
let nn = ref 0. in
List.iter t ~f:(fun (_nm, l) ->
let v, _ii = List.nth l i in
if !maximum > 0. && v > !maximum
then
Printf.fprintf
ch
"set label font \",5\" \"%.2f\" at %f,%f center\n"
v
(!nn +. (float i /. float n) -. 0.5) (* why? *)
((!maximum *. 1.04) +. 0.01);
nn := !nn +. 1.)
done;
Printf.fprintf ch "plot";
for i = 0 to n - 1 do
match List.nth h i with
| Some Measure.{ color; _ } -> (
if i > 0
then Printf.fprintf ch ", \"-\" using 2:3 title columnhead lw 0"
else Printf.fprintf ch " \"-\" using 2:3:xtic(1) title columnhead lw 0";
match color with
| Some c -> Printf.fprintf ch " lc rgb '%s'" c
| None -> ())
| None ->
if i > 0
then Printf.fprintf ch ", \"-\" using 2:3 title columnhead lw 0"
else Printf.fprintf ch " \"-\" using 2:3:xtic(1) title columnhead lw 0"
(* notitle does not work ... I don't know why ... *)
done;
Printf.fprintf ch "\n";
for i = 0 to n - 1 do
let nm =
match List.nth h i with
| Some Measure.{ name; _ } -> name
| None -> ""
in
Printf.fprintf ch "- \"%s\"\n" (escape_name_for_gnuplot nm);
List.iter t ~f:(fun (nm, l) ->
let v, ii = List.nth l i in
Printf.fprintf
ch
"\"%s\" %f %f\n"
(escape_name_for_gnuplot nm)
v
(if ii <> ii then 0. else ii));
Printf.fprintf ch "e\n"
done
let filter (h, t) =
let l1 =
List.filter t ~f:(fun (nm, _) ->
not (List.mem nm ~set:!appended || List.mem nm ~set:!omitted))
in
let app =
List.fold_left !appended ~init:[] ~f:(fun beg nm ->
try (nm, List.assoc nm t) :: beg with Not_found -> beg)
in
h, l1 @ app
let output_table =
let old_table = ref None in
fun (l : (Measure.t option list * _) option list) f ->
let t = merge_columns l !old_table in
old_table := Some (snd t);
let t = filter t in
let t = normalize t in
stats t;
f t
let rec transpose (l : (string * 'a list) list) : (string * 'a) list list =
match l with
| (_, _ :: _) :: _ ->
List.map ~f:(fun (label, data) -> label, List.hd data) l
:: transpose (List.map ~f:(fun (label, data) -> label, List.tl data) l)
| (_, []) :: _ | [] -> []
let geometric_mean l =
exp
(List.fold_left ~f:( +. ) ~init:0. (List.map l ~f:(fun (_, (v, _)) -> log v))
/. float (List.length l))
let current_bench_output
(ch : out_channel)
(_no_header : bool)
((header : Measure.t option list), (t : (string * (float * float) list) list)) =
let suite_name = !ylabel in
let measure_descs =
(* Filter out blank columns *)
List.filter_map header ~f:Fun.id
in
let measures = transpose t in
assert (List.length measures = List.length measure_descs);
let summary =
let metrics =
List.map2 measure_descs measures ~f:(fun desc measures ->
let description =
Option.value desc.Measure.description ~default:desc.Measure.name
in
let mean = geometric_mean measures in
`Assoc
[ "name", `String description
; "value", `Float mean
; "units", `String desc.Measure.units
])
in
`Assoc
[ "name", `String "Microbenchmarks - summary (geometric means)"
; "metrics", `List metrics
]
in
let results =
List.map2 measure_descs measures ~f:(fun desc measures ->
let description =
Option.value desc.Measure.description ~default:desc.Measure.name
in
let metrics : Yojson.Basic.t list =
List.map measures ~f:(fun (test_name, (m, _confidence_itvl)) ->
`Assoc
[ "name", `String test_name
; "value", `Float m
; "units", `String desc.Measure.units
])
in
`Assoc
[ "name", `String (String.concat ~sep:" - " [ "Microbenchmarks"; description ])
; "metrics", `List metrics
])
in
let json =
`Assoc [ "name", `String suite_name; "results", `List (summary :: results) ]
in
Yojson.Basic.to_channel ch json;
output_char ch '\n'
let output ~format conf =
let output_function, close =
match format with
| `Text -> text_output, fun () -> ()
| `Gnuplot_script -> gnuplot_output stdout, fun () -> ()
| `Gnuplot ->
let ch = Unix.open_process_out "gnuplot -persist" in
gnuplot_output ch, fun () -> close_out ch
| `Current_bench -> current_bench_output stdout, fun () -> ()
in
let no_header = ref false in
List.iter conf ~f:(fun conf ->
output_table
(List.map conf ~f:(function
| None -> read_blank_column ()
| Some (dir1, dir2, measure, refe) ->
read_column ~measure dir1 (Spec.create dir2 "") refe))
(output_function !no_header);
no_header := true);
close ()
let _ =
let conf = ref "report.config" in
let format : [ `Gnuplot | `Gnuplot_script | `Text | `Current_bench ] ref =
ref `Gnuplot
in
let script = ref false in
let nreference = ref None in
let options =
[ ( "-ref"
, Arg.Int (fun i -> nreference := Some i)
, "<col> use column <col> as the baseline. Overrides histogramref." )
; "-max", Arg.Set_float maximum, "<m> truncate graph at level <max>"
; "-min", Arg.Set_float minimum, "<m> truncate graph below level <min>"
; ( "-format"
, Arg.Symbol
( [ "gnuplot"; "table"; "current-bench" ]
, function
| "gnuplot" -> format := `Gnuplot
| "table" -> format := `Text
| "current-bench" -> format := `Current_bench
| _ -> assert false )
, " output format: a Gnuplot graph, a text table, or a JSON object for use by \
current-bench (default gnuplot)" )
; ( "-omit"
, Arg.String (fun s -> omitted := split_on_char s ~sep:',' @ !omitted)
, " omit the given benchmark" )
; ( "-append"
, Arg.String (fun s -> appended := split_on_char s ~sep:',' @ !appended)
, " append the given benchmark at the end" )
; "-errors", Arg.Set errors, " display error bars"
; "-config", Arg.Set_string conf, "<file> use <file> as a config file"
; "-script", Arg.Set script, " output gnuplot script"
; ( "-svg"
, Arg.Tuple
[ Arg.Set svg
; Arg.Set_int svgfontsize
; Arg.Set_int svgwidth
; Arg.Set_int svgheight
]
, "<fontsize> <width> <height> svg output" )
; "-edgecaption", Arg.Set edgecaption, " display caption outside the diagram"
; "-ylabel", Arg.Set_string ylabel, " Y axis label"
]
in
Arg.parse
(Arg.align options)
(fun s -> raise (Arg.Bad (Format.sprintf "unknown option `%s'" s)))
(Format.sprintf "Usage: %s [options]" Sys.argv.(0));
let format =
match !format, !script with
| `Gnuplot, true -> `Gnuplot_script
| `Gnuplot, false -> `Gnuplot
| _, true ->
Printf.eprintf "-script only work with gnuplot format";
exit 2
| ((`Gnuplot_script | `Text | `Current_bench) as x), false -> x
in
let conf = read_report_config ?column_ref:!nreference !conf in
output ~format conf
(*
http://hacks.mozilla.org/2009/07/tracemonkey-overview/
*)
|
js_of_ocaml-lwt
|
6.2.0
|
[
|
https://ocsigen.org/js_of_ocaml/latest/manual/overview
|
git+https://github.com/ocsigen/js_of_ocaml.git
|
ml
|
js_of_ocaml-6.2.0/benchmarks/run.ml
|
(* Js_of_ocaml benchmarks
* http://www.ocsigen.org/js_of_ocaml/
* Copyright (C) 2011 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open StdLabels
open Common
module Param = struct
type t =
{ warm_up_time : float
; min_measures : int
; max_confidence : float
; max_duration : float
; verbose : bool
}
let default =
{ warm_up_time = 1.0
; min_measures = 10
; max_confidence = 0.03
; max_duration = 120.
; verbose = false
}
let fast x = { x with min_measures = 5; max_confidence = 0.15; max_duration = 20. }
let ffast x = { x with min_measures = 2; max_confidence = 42.; max_duration = 20. }
let verbose x = { x with verbose = true }
end
let run_command ~verbose cmd =
if verbose then Format.printf "+ %s@." cmd;
match Unix.system cmd with
| Unix.WEXITED res when res <> 0 ->
failwith (Printf.sprintf "Command '%s' failed with exit code %d." cmd res)
| Unix.WSIGNALED s ->
failwith (Format.sprintf "Command '%s' killed with signal %d." cmd s)
| _ -> ()
let time ~verbose cmd =
let t1 = (Unix.times ()).Unix.tms_cutime in
run_command ~verbose cmd;
let t2 = (Unix.times ()).Unix.tms_cutime in
t2 -. t1
let compile_gen
(param : Param.t)
~comptime
prog
src_dir
(src_spec : Spec.t)
dst_dir
dst_spec =
mkdir (Spec.dir ~root:dst_dir dst_spec);
List.iter (Spec.find_names ~root:src_dir src_spec) ~f:(fun nm ->
let src = Spec.file ~root:src_dir src_spec nm in
let dst = Spec.file ~root:dst_dir dst_spec nm in
if need_update src dst
then
let cmd = prog ~src ~dst in
try
if comptime
then write_measures compiletimes dst_spec nm [ time ~verbose:param.verbose cmd ]
else run_command ~verbose:param.verbose cmd
with Failure s -> Format.eprintf "Failure: %s@." s)
let compile param ~comptime prog =
compile_gen param ~comptime (fun ~src ~dst -> Printf.sprintf "%s %s -o %s" prog src dst)
(****)
let need_more ~print (param : Param.t) l =
let a = Array.of_list l in
let n = Array.length a in
if n = 0
then true
else
let m, i = mean_with_confidence a in
if print then Format.eprintf "==> %f +/- %f / %f %d\r%!" m i (i /. m) n;
n < param.min_measures || i /. m > param.max_confidence /. 2.
let warm_up (param : Param.t) cmd =
let t = ref 0. in
while !t < param.warm_up_time do
let t' =
time ~verbose:param.verbose (Printf.sprintf "timeout %f %s" param.max_duration cmd)
in
if t' > param.max_duration
then failwith (Printf.sprintf "Warmup took too long %.1fs" t');
t := !t +. t'
done
let rec measure_rec ~print (param : Param.t) cmd l =
let t = time ~verbose:param.verbose cmd in
let l = t :: l in
if need_more ~print param l then measure_rec ~print param cmd l else l
let measure_one param code (meas : Measure.t) spec nm cmd =
let l =
if measures_need_update code meas spec nm
then []
else read_measures meas.Measure.path spec nm
in
if need_more ~print:false param l
then (
Format.eprintf "warming up ...\r%!";
warm_up param cmd;
let l = measure_rec ~print:true param cmd l in
write_measures meas spec nm l;
Format.eprintf "\n%!";
l)
else l
let measure ~param ~code ~(meas : Measure.t) ~spec cmd =
List.iter (Spec.find_names ~root:code spec) ~f:(fun nm ->
let cmd = if cmd = "" then cmd else cmd ^ " " in
let cmd = Format.sprintf "%s%s" cmd (Spec.file ~root:code spec nm) in
Format.eprintf "Measure %s@." cmd;
try ignore (measure_one param code meas spec nm cmd)
with Failure s -> Format.eprintf "Failure: %s@." s)
(****)
let compile_no_ext param ~comptime prog src_dir src_spec dst_dir dst_spec =
compile_gen param ~comptime prog src_dir src_spec dst_dir (Spec.no_ext dst_spec)
let ml_size param =
compile_no_ext param ~comptime:false (fun ~src ~dst ->
Format.sprintf
"perl ./utils/remove_comments.pl %s | sed 's/^ *//g' | wc -c > %s"
src
dst)
let file_size ?(wasm = false) param =
compile_no_ext param ~comptime:false (fun ~src ~dst ->
let files =
if wasm then src ^ " " ^ Filename.remove_extension src ^ ".assets/*" else src
in
Format.sprintf "cat %s | wc -c > %s" files dst)
let compr_file_size ?(wasm = false) param =
compile_no_ext param ~comptime:false (fun ~src ~dst ->
let input =
if wasm
then
Printf.sprintf
"echo %s %s | xargs gzip -c"
src
(Filename.remove_extension src ^ ".assets/*")
else Printf.sprintf "sed 's/^ *//g' %s | gzip -c" src
in
Format.sprintf "%s | wc -c > %s" input dst)
let bzip2_file_size ?(wasm = false) param =
compile_no_ext param ~comptime:false (fun ~src ~dst ->
let input =
if wasm
then
Printf.sprintf
"echo %s %s | xargs bzip2 -c"
src
(Filename.remove_extension src ^ ".assets/*")
else Printf.sprintf "sed 's/^ *//g' %s | bzip2 -c" src
in
Format.sprintf "%s | wc -c > %s" input dst)
let runtime_size param =
compile_no_ext param ~comptime:false (fun ~src ~dst ->
Format.sprintf
{|awk -vRS="--MARK--start-of-jsoo-gen--MARK--" '{print length($0)}' %s | head -n1 > %s|}
src
dst)
let gen_size param =
compile_no_ext param ~comptime:false (fun ~src ~dst ->
Format.sprintf
{|awk -vRS="--MARK--start-of-jsoo-gen--MARK--" '{print length($0)}' %s | tail -n1 > %s|}
src
dst)
(****)
let _ =
let compile_only = ref false in
let full = ref false in
let interpreter_config = ref "run.config" in
let param = ref Param.default in
let reports = ref [] in
let fast_run () = param := Param.fast !param in
let ffast_run () = param := Param.ffast !param in
let verbose () = param := Param.verbose !param in
let options =
[ "-compile", Arg.Set compile_only, " only compiles"
; "-all", Arg.Set full, " run all benchmarks"
; "-config", Arg.Set_string interpreter_config, "<file> use <file> as a config file"
; "-fast", Arg.Unit fast_run, " perform less iterations"
; "-ffast", Arg.Unit ffast_run, " perform very few iterations"
; "-verbose", Arg.Unit verbose, " verbose"
]
in
Arg.parse
(Arg.align options)
(fun report -> reports := report :: !reports)
(Format.sprintf "Usage: %s [options] [REPORTS.config]*" Sys.argv.(0));
let compile_only = !compile_only in
let full = !full in
let param = !param in
let interpreters = read_interpreter_config !interpreter_config in
let filtered, filter_bench =
match !reports with
| [] -> false, fun (_, _) -> true
| reports ->
List.map reports ~f:read_report_config
|> List.concat_map ~f:(fun l ->
List.concat_map l ~f:(fun l ->
List.concat_map l ~f:(function
| None -> []
| Some (p1, p2, _measure, _) -> (
match String.split_on_char ~sep:'/' p1 with
| [ "results"; "times"; _host; interpreter ] ->
[ interpreter, p2 ]
| _ -> []))))
|> List.sort_uniq ~cmp:compare
|> fun required ->
true, fun (interp, suite) -> List.mem (interp, Spec.name suite) ~set:required
in
let compile = compile param ~comptime:true in
let compile_jsoo ?(effects = `None) opts =
compile
(Format.sprintf
"js_of_ocaml -q --target-env browser --debug mark-runtime-gen %s %s"
opts
(match effects with
| `None -> "--effects=disabled"
| `Cps -> "--effects=cps"
| `Double_translation -> "--effects=double-translation"))
in
let compile_wasmoo ?(effects = `None) opts =
compile
(Format.sprintf
"wasm_of_ocaml -q %s %s"
opts
(match effects with
| `None -> ""
| `Cps -> "--effects=cps"))
in
Format.eprintf "Compile@.";
compile "ocamlc" src Spec.ml code Spec.byte;
compile "ocamlopt" src Spec.ml code Spec.opt;
compile_wasmoo "--opt=2" code Spec.byte code Spec.wasm_of_ocaml;
compile_jsoo "--opt=2" code Spec.byte code Spec.js_of_ocaml;
compile_jsoo "--opt=3" code Spec.byte code Spec.js_of_ocaml_o3;
compile_jsoo "--enable=use-js-string" code Spec.byte code Spec.js_of_ocaml_js_string;
compile_jsoo "--disable inline" code Spec.byte code Spec.js_of_ocaml_inline;
compile_jsoo "--disable deadcode" code Spec.byte code Spec.js_of_ocaml_deadcode;
compile_jsoo "--disable compact" code Spec.byte code Spec.js_of_ocaml_compact;
compile_jsoo "--disable optcall" code Spec.byte code Spec.js_of_ocaml_call;
compile_jsoo ~effects:`Cps "" code Spec.byte code Spec.js_of_ocaml_effects_cps;
compile_jsoo
~effects:`Double_translation
""
code
Spec.byte
code
Spec.js_of_ocaml_effects_double_translation;
compile "ocamlc -unsafe" src Spec.ml code Spec.byte_unsafe;
compile "ocamlopt" src Spec.ml code Spec.opt_unsafe;
compile_jsoo "" code Spec.byte_unsafe code Spec.js_of_ocaml_unsafe;
Format.eprintf "Sizes@.";
let sizes = sizes.Measure.path in
ml_size param src Spec.ml sizes Spec.ml;
file_size param code Spec.byte sizes Spec.byte;
file_size param code Spec.js_of_ocaml sizes (Spec.sub_spec Spec.js_of_ocaml "full");
file_size
~wasm:true
param
code
Spec.wasm_of_ocaml
sizes
(Spec.sub_spec Spec.wasm_of_ocaml "full");
compr_file_size
param
code
Spec.js_of_ocaml
sizes
(Spec.sub_spec Spec.js_of_ocaml "gzipped");
compr_file_size
param
code
Spec.js_of_ocaml_effects_cps
sizes
(Spec.sub_spec Spec.js_of_ocaml_effects_cps "gzipped");
compr_file_size
param
code
Spec.js_of_ocaml_effects_double_translation
sizes
(Spec.sub_spec Spec.js_of_ocaml_effects_double_translation "gzipped");
compr_file_size
~wasm:true
param
code
Spec.wasm_of_ocaml
sizes
(Spec.sub_spec Spec.wasm_of_ocaml "gzipped");
bzip2_file_size
param
code
Spec.js_of_ocaml_effects_cps
sizes
(Spec.sub_spec Spec.js_of_ocaml_effects_cps "bzip2");
bzip2_file_size
param
code
Spec.js_of_ocaml_effects_double_translation
sizes
(Spec.sub_spec Spec.js_of_ocaml_effects_double_translation "bzip2");
bzip2_file_size
param
code
Spec.js_of_ocaml
sizes
(Spec.sub_spec Spec.js_of_ocaml "bzip2");
bzip2_file_size
~wasm:true
param
code
Spec.wasm_of_ocaml
sizes
(Spec.sub_spec Spec.wasm_of_ocaml "bzip2");
runtime_size
param
code
Spec.js_of_ocaml
sizes
(Spec.sub_spec Spec.js_of_ocaml "runtime");
gen_size param code Spec.js_of_ocaml sizes (Spec.sub_spec Spec.js_of_ocaml "generated");
gen_size param code Spec.js_of_ocaml_o3 sizes Spec.js_of_ocaml_o3;
gen_size param code Spec.js_of_ocaml_js_string sizes Spec.js_of_ocaml_js_string;
gen_size param code Spec.js_of_ocaml_inline sizes Spec.js_of_ocaml_inline;
gen_size param code Spec.js_of_ocaml_deadcode sizes Spec.js_of_ocaml_deadcode;
gen_size param code Spec.js_of_ocaml_compact sizes Spec.js_of_ocaml_compact;
gen_size param code Spec.js_of_ocaml_call sizes Spec.js_of_ocaml_call;
gen_size param code Spec.js_of_ocaml_effects_cps sizes Spec.js_of_ocaml_effects_cps;
gen_size
param
code
Spec.js_of_ocaml_effects_double_translation
sizes
Spec.js_of_ocaml_effects_double_translation;
if compile_only then exit 0;
Format.eprintf "Measure@.";
if filter_bench ("", Spec.opt) then measure ~param ~code ~meas:times ~spec:Spec.opt "";
if filter_bench ("", Spec.byte) then measure ~param ~code ~meas:times ~spec:Spec.byte "";
let all_spec =
[ Some Spec.js_of_ocaml
; Some Spec.js_of_ocaml_o3
; Some Spec.js_of_ocaml_js_string
; Some Spec.js_of_ocaml_unsafe
; Some Spec.js_of_ocaml_inline
; Some Spec.js_of_ocaml_deadcode
; Some Spec.js_of_ocaml_compact
; Some Spec.js_of_ocaml_call
; Some Spec.js_of_ocaml_effects_cps
; Some Spec.js_of_ocaml_effects_double_translation
; Some Spec.wasm_of_ocaml
]
in
let interpreters, suites =
if full || filtered
then interpreters, all_spec
else
( (match interpreters with
| i :: _ -> [ i ]
| [] -> [])
, [ Some Spec.js_of_ocaml; Some Spec.wasm_of_ocaml ] )
in
List.iter interpreters ~f:(fun (comp, dir) ->
(* Measure the time taken by an implementation in Javascript for comparison *)
if filter_bench (dir, Spec.js)
then
measure
~param
~code:src
~meas:Measure.{ times with path = Filename.concat times.path dir }
~spec:Spec.js
comp;
List.iter suites ~f:(function
| None -> ()
| Some suite ->
if filter_bench (dir, suite)
then
measure
~param
~code
~meas:Measure.{ times with path = Filename.concat times.path dir }
~spec:suite
comp))
|
End of preview. Expand
in Data Studio
This is a dataset automatically generated from ocaml/opam:archive. You can find more information about this dataset in this blogpost.
- Downloads last month
- 516