text
stringlengths
12
786k
module IO = struct type ' a t = ' a Deferred . t let ( ) >>= = Deferred . ( ) >>= let return = Deferred . return type ic = ( unit -> unit Deferred . t ) * Reader . t type oc = ( unit -> unit Deferred . t ) * Writer . t type conn = unit let read_line ( _ , ic ) = Reader . read_line ic >>| function | ` Ok s -> Some s | ` Eof -> None let read ( _ , ic ) len = let buf = Bytes . create len in Reader . read ic ~ len buf >>| function | ` Ok len ' -> let content = Bytes . sub buf ~ pos : 0 ~ len : len ' in Bytes . to_string content | ` Eof -> " " let write ( _ , oc ) buf = Writer . write oc buf ; return ( ) let flush ( _ , oc ) = Async . Writer . flushed oc let close ( ( close1 , _ ) , ( close2 , _ ) ) = close1 ( ) >>= fun ( ) -> close2 ( ) let open_connection uri = match Uri . scheme uri with | Some " http " -> let port = match Uri . port uri with | None -> 80 | Some port -> port in begin match Uri . host uri with | Some host -> let endp = Host_and_port . create ~ host ~ port in Tcp . connect ( Tcp . Where_to_connect . of_host_and_port endp ) >>| fun ( _ , ic , oc ) -> Ok ( ( ( fun ( ) -> Reader . close ic ) , ic ) , ( ( fun ( ) -> Writer . close oc ) , oc ) ) | None -> return ( Error ( Failed_to_resolve_hostname " " ) ) end | Some x -> return ( Error ( Unsupported_scheme x ) ) | None -> return ( Error ( Unsupported_scheme " " ) ) let sleep s = after ( sec s ) let gettimeofday = Unix . gettimeofday end
let exn_to_string = function | Api_errors . Server_error ( code , params ) -> Printf . sprintf " % s % s " code ( String . concat ~ sep " : " params ) | e -> Printf . sprintf " Caught unexpected exception : % s " ( Exn . to_string e )
let do_it uri string = let uri = Uri . of_string uri in let connection = M . make uri in let ( ) >>= = Deferred . ( ) >>= in Monitor . protect ( fun ( ) -> M . rpc connection string >>= function | Ok x -> return x | Error e -> eprintf " Caught : % s \ n " %! ( exn_to_string e ) ; Exn . reraise e " connection error " ) ~ finally ( : fun ( ) -> M . disconnect connection )
let make ( ? timeout = 30 . ) uri call = let req = Xmlrpc . string_of_call call in do_it uri req >>| Xmlrpc . response_of_string
let make_json ( ? timeout = 30 . ) uri call = let req = Jsonrpc . string_of_call call in do_it uri req >>| Jsonrpc . response_of_string
module Client = Client . ClientF ( struct include Deferred let bind a f = bind a ~ f end )
module Lwt_unix_IO = struct type ' a t = ' a Lwt . t let ( ) >>= = Lwt . bind let return = Lwt . return let ( ) >> m n = m >>= fun _ -> n type ic = ( unit -> unit Lwt . t ) * Lwt_io . input_channel type oc = ( unit -> unit Lwt . t ) * Lwt_io . output_channel type conn = Lwt_unix . file_descr let read_line ( _ , ic ) = Lwt_io . read_line_opt ic let read ( _ , ic ) count = Lwt . catch ( fun ( ) -> Lwt_io . read ~ count ic ) ( function | End_of_file -> return " " | e -> Lwt . fail e ) let write ( _ , oc ) = Lwt_io . write oc let flush ( _ , oc ) = Lwt_io . flush oc let close ( ( close1 , _ ) , ( close2 , _ ) ) = close1 ( ) >> close2 ( ) let sslctx = Ssl . init ( ) ; Ssl . create_context Ssl . TLSv1_2 Ssl . Client_context let open_connection uri = ( match Uri . scheme uri with | Some " file " -> return ( Unix . PF_UNIX , Unix . ADDR_UNIX ( Uri . path uri ) , false ) | Some " http " | Some " https " -> Util . sockaddr_of_uri uri >|= fun ( sockaddr , ssl ) -> ( ( Unix . domain_of_sockaddr sockaddr ) , sockaddr , ssl ) | Some x -> fail ( Unsupported_scheme x ) | None -> fail ( Unsupported_scheme " " ) ) >>= fun ( domain , sockaddr , ssl ) -> if ssl then begin let fd = Lwt_unix . socket domain Unix . SOCK_STREAM 0 in Lwt . catch ( fun ( ) -> Lwt . catch ( fun ( ) -> Lwt_unix . connect fd sockaddr ) ( fun e -> Lwt_unix . close fd >>= fun ( ) -> Lwt . fail e ) >>= fun ( ) -> Lwt_ssl . ssl_connect fd sslctx >>= fun sock -> let ic = Lwt_ssl . in_channel_of_descr sock in let oc = Lwt_ssl . out_channel_of_descr sock in return ( Ok ( ( return , ic ) , ( ( fun ( ) -> Lwt_ssl . close sock ) , oc ) ) ) ) ( fun e -> return ( Error e ) ) end else begin let fd = Lwt_unix . socket domain Unix . SOCK_STREAM 0 in Lwt . catch ( fun ( ) -> Lwt . catch ( fun ( ) -> Lwt_unix . connect fd sockaddr ) ( fun e -> Lwt_unix . close fd >>= fun ( ) -> Lwt . fail e ) >>= fun ( ) -> let ic = Lwt_io . of_fd ~ close : return ~ mode : Lwt_io . input fd in let oc = Lwt_io . of_fd ~ close ( : fun ( ) -> Lwt_unix . close fd ) ~ mode : Lwt_io . output fd in return ( Ok ( ( ( fun ( ) -> Lwt_io . close ic ) , ic ) , ( ( fun ( ) -> Lwt_io . close oc ) , oc ) ) ) ) ( fun e -> return ( Error e ) ) end let sleep = Lwt_unix . sleep let gettimeofday = Unix . gettimeofday end
let exn_to_string = function | Api_errors . Server_error ( code , params ) -> Printf . sprintf " % s % s " code ( String . concat " " params ) | e -> Printexc . to_string e
let do_it uri string = let uri = Uri . of_string uri in let connection = M . make uri in Lwt . finalize ( fun ( ) -> M . rpc connection string >>= fun result -> match result with | Ok x -> return x | Error e -> Printf . fprintf stderr " Caught : % s \ n " %! ( exn_to_string e ) ; fail e ) ( fun ( ) -> M . disconnect connection )
let make ( ? timeout = 30 . ) uri call = let string = Xmlrpc . string_of_call call in do_it uri string >>= fun result -> Lwt . return ( Xmlrpc . response_of_string result )
let make_json ( ? timeout = 30 . ) uri call = let string = Jsonrpc . string_of_call call in do_it uri string >>= fun result -> Lwt . return ( Jsonrpc . response_of_string result )
type cf = [ ` Average | ` Min | ` Max ]
let string_of_cf = function | ` Average -> " AVERAGE " | ` Min -> " MIN " | ` Max -> " MAX "
let cf_of_string = function | " AVERAGE " -> ` Ok ` Average | " MIN " -> ` Ok ` Min | " MAX " -> ` Ok ` Max | x -> ` Error ( ` Msg ( Printf . sprintf " Unknown consolidation function : % s " x ) )
module Legend = struct type cls = [ ` VM | ` Host | ` Other of string ] type t = string * cf * cls * Uuidm . t let colon = Re . Str . regexp_string " " : let of_string x = match Re . Str . split_delim colon x with | cf :: cls :: uuid :: name :: [ ] -> begin match cf_of_string cf with | ` Error x -> ` Error x | ` Ok cf -> let cls = match cls with | " host " -> ` Host | " vm " -> ` VM | x -> ` Other x in begin match Uuidm . of_string uuid with | None -> ` Error ( ` Msg ( Printf . sprintf " Failed to parse uuid : % s " uuid ) ) | Some uuid -> ` Ok ( name , cf , cls , uuid ) end end | _ -> ` Error ( ` Msg ( Printf . sprintf " Failed to parse legend : % s " x ) ) let find_data_source dsl ( name , _ , _ , _ ) = try Some ( List . find ( fun ds -> ds . API . data_source_name_label = name ) dsl ) with Not_found -> None end
type interval = [ | ` Seconds | ` Minute | ` Hour | ` Day | ` Other of int ]
let seconds_of_interval = function | ` Seconds -> 5 | ` Minute -> 60 | ` Hour -> 60 * 60 | ` Day -> 24 * 60 * 60 | ` Other x -> x
let rec archive_length_of_interval = function | ` Seconds -> 10 * 60 | ` Minute -> 2 * 60 * 60 | ` Hour -> 7 * 24 * 60 * 60 | ` Day -> 365 * 7 * 24 * 60 * 60 | ` Other x -> if x <= ( seconds_of_interval ` Seconds ) then ( archive_length_of_interval ` Seconds ) else if x <= ( seconds_of_interval ` Minute ) then ( archive_length_of_interval ` Minute ) else if x <= ( seconds_of_interval ` Hour ) then ( archive_length_of_interval ` Hour ) else archive_length_of_interval ` Day
module Updates = struct let uri ~ host ~ authentication ~ start ( ? include_host = false ) ? interval ? cf ( ) = let ssl , scheme = match Uri . scheme host with | Some " https " -> true , " https " | Some " http " -> false , " http " | x -> failwith ( Printf . sprintf " Unknown scheme : % s " ( match x with None -> " None " | Some x -> x ) ) in let port = match Uri . port host with | Some x -> x | None -> if ssl then 443 else 80 in let query = [ " start " , [ string_of_int start ] ; " host " , [ string_of_bool include_host ] ] @ ( match interval with None -> [ ] | Some x -> [ " interval " , [ string_of_int ( seconds_of_interval x ) ] ] ) @ ( match cf with None -> [ ] | Some x -> [ " cf " , [ string_of_cf x ] ] ) in let userinfo = match authentication with | ` UserPassword ( user , pass ) -> Some ( user ^ " " : ^ pass ) | ` Session_id _ -> None in let query = match authentication with | ` UserPassword ( _ , _ ) -> query | ` Session_id s -> ( " session_id " , [ s ] ) :: query in Uri . make ~ scheme ? userinfo ? host ( : Uri . host host ) ~ port ~ path " :/ rrd_updates " ~ query ( ) let parse x = let input = Xmlm . make_input ( ` String ( 0 , x ) ) in Rrd_updates . of_xml input end
let ( |> ) a b = b a
let id x = x
module Fake_IO = struct type ' a t = T of ' a let return x = T x let ( ) >>= t f = match t with | T x -> f x let ( ) >> m n = m >>= fun _ -> n let rec iter f = function | [ ] -> return ( ) | x :: xs -> f x >>= fun ( ) -> ( iter f xs ) type ic = string Queue . t type oc = string Queue . t type conn = unit let read_line ic = if Queue . is_empty ic then begin return None end else begin let chunk = Queue . pop ic in return ( Some chunk ) end let read ic n = let chunk = Queue . pop ic in assert ( String . length chunk <= n ) ; return chunk let read_exactly ic buf off len = return ( if Queue . is_empty ic then false else begin let chunk = Queue . pop ic in String . blit chunk 0 buf off len ; true end ) let read_exactly ic len = let buf = Bytes . create len in read_exactly ic buf 0 len >>= function | true -> return ( Some buf ) | false -> return None let write oc string = Queue . push string oc ; return ( ) let flush _oc = return ( ) type connection = { address : Uri . t ; ic : ic ; oc : ic ; } let connections = ref [ ] let open_connection address = let ic = Queue . create ( ) and oc = Queue . create ( ) in let c = { address ; ic ; oc } in connections := c :: ! connections ; return ( Ok ( ic , oc ) ) let close ( ic , oc ) = let this_one c = c . ic == ic && c . oc == oc in ignore ( List . find this_one ! connections ) ; connections := List . filter ( fun c -> not ( this_one c ) ) ! connections ; return ( ) let timeofday = ref 0 . let gettimeofday ( ) = ! timeofday let num_sleeps = ref 0 let sleep x = incr num_sleeps ; timeofday := ! timeofday . + x ; return ( ) end
let test_login_fail _ = let module M = Xen_api . Make ( Fake_IO ) in let open Fake_IO in let rpc req = let xml = Xmlrpc . string_of_call req in M . rpc ( M . make ( Uri . of_string " http :// 127 . 0 . 0 . 1 " ) ) / xml >>= function | Ok _ -> failwith " should have failed with No_response " | Error e -> raise e in timeofday := 0 . ; num_sleeps := 0 ; begin try let _session_id = C . Session . login_with_password ~ rpc : rpc ~ uname " : root " ~ pwd " : password " ~ version " : 1 . 0 " ~ originator " : xen - api test " in ( ) with Xen_api . No_response -> ( ) end ; assert_equal ~ printer : string_of_float ~ msg " : timeofday " 31 . ! timeofday ; assert_equal ~ printer : string_of_int ~ msg " : num_sleeps " 31 ! num_sleeps ; ( )
let test_login_success _ = let session_id = " OpaqueRef : 9e9cf047 - 76d7 - 9f3a - 62ca - cb7bacf5a4e1 " in let result = Printf . sprintf " < methodResponse >< params >< param >< value >< struct >< member >< name > Status </ name >< value > Success </ value ></ member >< member >< name > Value </ name >< value >% s </ value ></ member ></ struct ></ value ></ param ></ params ></ methodResponse " > session_id in let module Fake_IO = struct include Fake_IO let open_connection address = let ic = Queue . create ( ) and oc = Queue . create ( ) in Queue . push " HTTP / 1 . 1 200 OK \ r \ n " ic ; Queue . push ( Printf . sprintf " Content - length : % d \ r \ n " ( String . length result ) ) ic ; Queue . push " \ r \ n " ic ; Queue . push result ic ; let c = { address ; ic ; oc } in connections := c :: ! connections ; return ( Ok ( ic , oc ) ) end in let open Fake_IO in let module M = Xen_api . Make ( Fake_IO ) in let rpc call = let s = Xmlrpc . string_of_call call in M . rpc ( M . make ( Uri . of_string " http :// 127 . 0 . 0 . 1 " ) ) / s >>= function | Ok x -> Xmlrpc . response_of_string x | Error e -> raise e in let session_id ' = C . Session . login_with_password ~ rpc ~ uname " : root " ~ pwd " : password " ~ version " : 1 . 0 " ~ originator " : xen - api test " in assert_equal ~ msg " : session_id " session_id ( API . Ref . string_of session_id ' )
let _ = let verbose = ref false in Arg . parse [ " - verbose " , Arg . Unit ( fun _ -> verbose := true ) , " Run in verbose mode " ; ] ( fun x -> Printf . fprintf stderr " Ignoring argument : % s " x ) " Test xen - api protocol code " ; let suite = " xen - api " >::: [ " login_fail " >:: test_login_fail ; " login_success " >:: test_login_success ; ] in run_test_tt ~ verbose :! verbose suite
type xexp = | Num of int | Var of string | Fn of string * xexp | App of xexp * xexp | If of xexp * xexp * xexp | Equal of xexp * xexp | Raise of xexp | Handle of xexp * int * xexp
type value = | N of int | B of bool | C of closure
type result = | Val of value | Exn of int
let emptyEnv = ( fun x -> raise ( RunError ( " unbound id : " ^ x ) ) )
let bind e x v = ( fun y -> if y = x then v else e y )
let getInt = function | N n -> n | _ -> raise ( TypeError " not an int " )
let getBool = function | B b -> b | _ -> raise ( TypeError " not a bool " )
let getClosure = function | C c -> c | _ -> raise ( TypeError " not a function " )
let rec eval env exp = match exp with | Num n -> Val ( N n ) | Var x -> Val ( env x ) | Fn ( x , e ) -> Val ( C ( x , e , env ) ) | App ( e1 , e2 ) -> ( match eval env e1 with | Val v1 -> let ( x , e_body , env ' ) = getClosure v1 in ( match eval env e2 with | Val v2 -> eval ( bind env ' x v2 ) e_body | Exn n -> Exn n ) | Exn n -> Exn n ) | If ( e1 , e2 , e3 ) -> ( match eval env e1 with | Val v -> if getBool v then eval env e2 else eval env e3 | Exn n -> Exn n ) | Equal ( e1 , e2 ) -> ( match eval env e1 with | Val v1 -> ( match eval env e2 with | Val v2 -> Val ( B ( getInt v1 = getInt v2 ) ) | Exn n -> Exn n ) | Exn n -> Exn n ) | Raise e -> ( match eval env e with | Val v -> Exn ( getInt v ) | Exn n -> Exn n ) | Handle ( e1 , n , e2 ) -> ( match eval env e1 with | Val v1 -> Val v1 | Exn n ' -> if n = n ' then eval env e2 else Exn n ' )
let run : xexp -> result = fun exp -> eval emptyEnv exp
let indent i = let rec iter = function | 0 -> ( ) | n -> ps " " ; iter ( n - 1 ) in nl ( ) ; iter i
let rec pp i exp = match exp with | Num n -> print_int n | Var s -> ps s | Fn ( x , e ) -> ps ( " fn " ^ x ^ " => " ) ; pp i e | App ( e , e ' ) -> ps " ( " ; pp i e ; ps " ) ( " ; pp i e ' ; ps " ) " | If ( e1 , e2 , e3 ) -> indent ( i + 1 ) ; ps " if " ; pp i e1 ; ps " then " ; indent ( i + 2 ) ; pp ( i + 2 ) e2 ; indent ( i + 1 ) ; ps " else " ; indent ( i + 2 ) ; pp ( i + 2 ) e3 ; nl ( ) | Equal ( e1 , e2 ) -> ps " ( " ; pp i e1 ; ps " = " ; pp i e2 ; ps " ) " | Raise e -> ps " raise ( " ; pp i e ; ps " ) " | Handle ( e1 , n , e2 ) -> ps " ( " ; pp i e1 ; ps " ) " ; ps ( " handle " ^ string_of_int n ^ " ( " ) ; pp i e2 ; ps " ) "
let print = pp 0
let rec is_sugarless = function | Num _ | Var _ -> true | Fn ( _ , e ) -> is_sugarless e | App ( e1 , e2 ) | Equal ( e1 , e2 ) -> is_sugarless e1 && is_sugarless e2 | If ( e1 , e2 , e3 ) -> is_sugarless e1 && is_sugarless e2 && is_sugarless e3 | Raise _ | Handle _ -> false
type t = { po_content : po_content ; translated : SetString . t }
let translations = ref { po_content = empty_po ; translated = SetString . empty }
let default_textdomain = ref None
let current_file = ref " "
let add_translation loc singular plural_opt domain = let t = ! translations in let filepos = let start = loc . Location . loc_start in let fname = match start . Lexing . pos_fname with " " -> ! current_file | fname -> fname in ( fname , start . Lexing . pos_lnum ) in let translated = SetString . add singular t . translated in let translated , translation = match plural_opt with | Some plural -> ( SetString . add plural translated , { po_comment_special = [ ] ; po_comment_filepos = [ filepos ] ; po_comment_translation = PoPlural ( [ singular ] , [ plural ] , [ [ " " ] ; [ " " ] ] ) ; } ) | None -> ( translated , { po_comment_special = [ ] ; po_comment_filepos = [ filepos ] ; po_comment_translation = PoSingular ( [ singular ] , [ " " ] ) ; } ) in let po_content = match ( domain , ! default_textdomain ) with | Some domain , _ -> add_po_translation_domain domain t . po_content translation | None , Some domain -> add_po_translation_domain domain t . po_content translation | None , None -> add_po_translation_no_domain t . po_content translation in translations := { po_content ; translated }
let output_translations ? output_file t = let fd = match output_file with Some f -> open_out f | None -> stdout in set_binary_mode_out fd true ; Marshal . to_channel fd t . po_content [ ]
let rec is_like lid = function | [ ] -> false | func :: functions -> ( match lid with | ( Lident f | Ldot ( _ , f ) ) when f = func -> true | _ -> is_like lid functions )
let visit_expr ( iterator : Ast_iterator . iterator ) expr = let loc = expr . pexp_loc in match expr . pexp_desc with | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } ) # endif :: _ ) when is_like lid [ " s_ " ; " f_ " ] -> add_translation loc singular None None | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } ) # endif :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ ) ) ; _ } ) # endif :: _ ) when is_like lid [ " sn_ " ; " fn_ " ] -> add_translation loc singular ( Some plural ) None | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , _ :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } ) # endif :: _ ) when is_like lid [ " gettext " ; " fgettext " ] -> add_translation loc singular None None | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , _ :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( domain , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( domain , _ ) ) ; _ } ) # endif :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } # endif ) :: _ ) when is_like lid [ " dgettext " ; " fdgettext " ; " dcgettext " ; " fdcgettext " ] -> add_translation loc singular None ( Some domain ) | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , _ :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } ) # endif :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ ) ) ; _ } ) # endif :: _ ) when is_like lid [ " ngettext " ; " fngettext " ] -> add_translation loc singular ( Some plural ) None | Pexp_apply ( { pexp_desc = Pexp_ident { Asttypes . txt = lid ; _ } ; _ } , _ :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( domain , _ , _ ) ) ; _ } ) # else { pexp_desc = Pexp_constant ( Pconst_string ( domain , _ ) ) ; _ } ) # endif :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ , _ ) ) ; _ } # else { pexp_desc = Pexp_constant ( Pconst_string ( singular , _ ) ) ; _ } # endif ) :: ( Asttypes . Nolabel , { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ , _ ) ) ; _ } # else { pexp_desc = Pexp_constant ( Pconst_string ( plural , _ ) ) ; _ } # endif ) :: _ ) when is_like lid [ " dngettext " ; " fdngettext " ; " dcngettext " ; " fdcngettext " ] -> add_translation loc singular ( Some plural ) ( Some domain ) | _ -> Ast_iterator . default_iterator . expr iterator expr
let ast_iterator = { Ast_iterator . default_iterator with expr = visit_expr }
let go fn = current_file := fn ; try let lexbuf = Lexing . from_channel ( open_in fn ) in let structure = Parse . implementation lexbuf in ast_iterator . Ast_iterator . structure ast_iterator structure with exn -> failwith ( fn ^ " : " ^ Printexc . to_string exn )
let ( ) = Arg . parse [ ] go " " ; output_translations ! translations
let hash x = seeded_hash_param 10 100 0 x
let hash_param n1 n2 x = seeded_hash_param n1 n2 0 x
let seeded_hash seed x = seeded_hash_param 10 100 seed x
type ' a t = { mutable size : int ; mutable data : ' a list array ; mutable seed : int ; initial_size : int ; }
let randomized_default = let params = try Sys . getenv " OCAMLRUNPARAM " with Not_found -> try Sys . getenv " CAMLRUNPARAM " with Not_found -> " " in String . contains params ' R '
let randomized = ref randomized_default
let randomize ( ) = randomized := true
let prng = lazy ( Random . State . make_self_init ( ) )
let rec power_2_above x n = if x >= n then x else if x * 2 > Sys . max_array_length then x else power_2_above ( x * 2 ) n
let create ( ? random = ! randomized ) initial_size = let s = power_2_above 16 initial_size in let seed = if random then Random . State . bits ( Lazy . force prng ) else 0 in { initial_size = s ; size = 0 ; seed = seed ; data = Array . make s [ ] }
let clear h = h . size <- 0 ; let len = Array . length h . data in for i = 0 to len - 1 do h . data . ( i ) <- [ ] done
let reset h = let len = Array . length h . data in if Obj . size ( Obj . repr h ) < 4 || len = h . initial_size then clear h else begin h . size <- 0 ; h . data <- Array . make h . initial_size [ ] end
let copy h = { h with data = Array . copy h . data }
let length h = h . size
let resize indexfun h = let odata = h . data in let osize = Array . length odata in let nsize = osize * 2 in if nsize < Sys . max_array_length then begin let ndata = Array . make nsize [ ] in h . data <- ndata ; let rec insert_bucket = function [ ] -> ( ) | key :: rest -> insert_bucket rest ; let nidx = indexfun h key in ndata . ( nidx ) <- key :: ndata . ( nidx ) in for i = 0 to osize - 1 do insert_bucket odata . ( i ) done end
let key_index h key = if Obj . size ( Obj . repr h ) >= 3 then ( seeded_hash_param 10 100 h . seed key ) land ( Array . length h . data - 1 ) else ( old_hash_param 10 100 key ) mod ( Array . length h . data )
let add h key = let i = key_index h key in let bucket = key :: h . data . ( i ) in h . data . ( i ) <- bucket ; h . size <- h . size + 1 ; if h . size > Array . length h . data lsl 1 then resize key_index h
let remove h key = let rec remove_bucket = function | [ ] -> [ ] | k :: next -> if compare k key = 0 then begin h . size <- h . size - 1 ; next end else k :: remove_bucket next in let i = key_index h key in h . data . ( i ) <- remove_bucket h . data . ( i )
let rec find_rec key = function | [ ] -> raise Not_found | k :: rest -> if compare key k = 0 then k else find_rec key rest
let find h key = match h . data . ( key_index h key ) with | [ ] -> raise Not_found | k1 :: rest1 -> if compare key k1 = 0 then k1 else match rest1 with | [ ] -> raise Not_found | k2 :: rest2 -> if compare key k2 = 0 then k2 else match rest2 with | [ ] -> raise Not_found | k3 :: rest3 -> if compare key k3 = 0 then k3 else find_rec key rest3
let find_all h key = let rec find_in_bucket = function | [ ] -> [ ] | k :: rest -> if compare k key = 0 then k :: find_in_bucket rest else find_in_bucket rest in find_in_bucket h . data . ( key_index h key )
let replace h key = let rec replace_bucket = function | [ ] -> raise Not_found | k :: next -> if compare k key = 0 then k :: next else k :: replace_bucket next in let i = key_index h key in let l = h . data . ( i ) in try h . data . ( i ) <- replace_bucket l with Not_found -> h . data . ( i ) <- key :: l ; h . size <- h . size + 1 ; if h . size > Array . length h . data lsl 1 then resize key_index h
let mem h key = let rec mem_in_bucket = function | [ ] -> false | k :: rest -> compare k key = 0 || mem_in_bucket rest in mem_in_bucket h . data . ( key_index h key )
let iter f h = let rec do_bucket = function | [ ] -> ( ) | k :: rest -> f k ; do_bucket rest in let d = h . data in for i = 0 to Array . length d - 1 do do_bucket d . ( i ) done
let fold f h init = let rec do_bucket b accu = match b with [ ] -> accu | k :: rest -> do_bucket rest ( f k accu ) in let d = h . data in let accu = ref init in for i = 0 to Array . length d - 1 do accu := do_bucket d . ( i ) ! accu done ; ! accu
let find_or_add tbl v = try find tbl v with | Not_found -> add tbl v ; v
type statistics = { num_bindings : int ; num_buckets : int ; max_bucket_length : int ; bucket_histogram : int array }
let rec bucket_length accu = function | [ ] -> accu | _ :: rest -> bucket_length ( accu + 1 ) rest
let stats h = let mbl = Array . fold_left ( fun m b -> max m ( bucket_length 0 b ) ) 0 h . data in let histo = Array . make ( mbl + 1 ) 0 in Array . iter ( fun b -> let l = bucket_length 0 b in histo . ( l ) <- histo . ( l ) + 1 ) h . data ; { num_bindings = h . size ; num_buckets = Array . length h . data ; max_bucket_length = mbl ; bucket_histogram = histo }
module type HashedType = sig type t val equal : t -> t -> bool val hash : t -> int end
module type SeededHashedType = sig type t val equal : t -> t -> bool val hash : int -> t -> int end
module type S = sig type key type t val create : int -> t val clear : t -> unit val reset : t -> unit val copy : t -> t val add : t -> key -> unit val remove : t -> key -> unit val find : t -> key -> key val find_all : t -> key -> key list val replace : t -> key -> unit val mem : t -> key -> bool val iter : ( key -> unit ) -> t -> unit val fold : ( key -> ' b -> ' b ) -> t -> ' b -> ' b val length : t -> int val stats : t -> statistics val find_or_add : t -> key -> key end
module type SeededS = sig type key type t val create : ? random : bool -> int -> t val clear : t -> unit val reset : t -> unit val copy : t -> t val add : t -> key -> unit val remove : t -> key -> unit val find : t -> key -> key val find_all : t -> key -> key list val replace : t -> key -> unit val mem : t -> key -> bool val iter : ( key -> unit ) -> t -> unit val fold : ( key -> ' b -> ' b ) -> t -> ' b -> ' b val length : t -> int val stats : t -> statistics val find_or_add : t -> key -> key end
module MakeSeeded ( H : SeededHashedType ) : ( SeededS with type key = H . t ) = struct type key = H . t type hashtbl = key t type t = hashtbl let create = create let clear = clear let reset = reset let copy = copy let key_index h key = ( H . hash h . seed key ) land ( Array . length h . data - 1 ) let add h key = let i = key_index h key in let bucket = key :: h . data . ( i ) in h . data . ( i ) <- bucket ; h . size <- h . size + 1 ; if h . size > Array . length h . data lsl 1 then resize key_index h let remove h key = let rec remove_bucket = function | [ ] -> [ ] | k :: next -> if H . equal k key then begin h . size <- h . size - 1 ; next end else k :: remove_bucket next in let i = key_index h key in h . data . ( i ) <- remove_bucket h . data . ( i ) let rec find_rec key = function | [ ] -> raise Not_found | k :: rest -> if H . equal key k then k else find_rec key rest let find h key = match h . data . ( key_index h key ) with | [ ] -> raise Not_found | k1 :: rest1 -> if H . equal key k1 then k1 else match rest1 with | [ ] -> raise Not_found | k2 :: rest2 -> if H . equal key k2 then k2 else match rest2 with | [ ] -> raise Not_found | k3 :: rest3 -> if H . equal key k3 then k3 else find_rec key rest3 let find_all h key = let rec find_in_bucket = function | [ ] -> [ ] | k :: rest -> if H . equal k key then k :: find_in_bucket rest else find_in_bucket rest in find_in_bucket h . data . ( key_index h key ) let replace h key = let rec replace_bucket = function | [ ] -> raise Not_found | k :: next -> if H . equal k key then key :: next else k :: replace_bucket next in let i = key_index h key in let l = h . data . ( i ) in try h . data . ( i ) <- replace_bucket l with Not_found -> h . data . ( i ) <- key :: l ; h . size <- h . size + 1 ; if h . size > Array . length h . data lsl 1 then resize key_index h let mem h key = let rec mem_in_bucket = function | [ ] -> false | k :: rest -> H . equal k key || mem_in_bucket rest in mem_in_bucket h . data . ( key_index h key ) let iter = iter let fold = fold let length = length let stats = stats let find_or_add tbl v = try find tbl v with | Not_found -> add tbl v ; v end
module Make ( H : HashedType ) : ( S with type key = H . t ) = struct include MakeSeeded ( struct type t = H . t let equal = H . equal let hash ( _seed : int ) x = H . hash x end ) let create sz = create ~ random : false sz end
int -> int -> int -> ' a -> int = " caml_hash " " noalloc " int -> int -> ' a -> int = " caml_hash_univ_param " " noalloc "
let hash x = seeded_hash_param 10 100 0 x
let hash_param n1 n2 x = seeded_hash_param n1 n2 0 x
let seeded_hash seed x = seeded_hash_param 10 100 seed x
type ( ' a , ' b ) t = { mutable size : int ; mutable data : ( ' a , ' b ) bucketlist array ; mutable seed : int ; initial_size : int ; } Empty | Cons of ' a * ' b * ( ' a , ' b ) bucketlist
let randomized_default = let params = try Sys . getenv " OCAMLRUNPARAM " with Not_found -> try Sys . getenv " CAMLRUNPARAM " with Not_found -> " " in String . contains params ' R '
let randomized = ref randomized_default
let randomize ( ) = randomized := true
let prng = lazy ( Random . State . make_self_init ( ) )
let rec power_2_above x n = if x >= n then x else if x * 2 > Sys . max_array_length then x else power_2_above ( x * 2 ) n
let create ( ? random = ! randomized ) initial_size = let s = power_2_above 16 initial_size in let seed = if random then Random . State . bits ( Lazy . force prng ) else 0 in { initial_size = s ; size = 0 ; seed = seed ; data = Array . make s Empty }
let clear h = h . size <- 0 ; let len = Array . length h . data in for i = 0 to len - 1 do h . data . ( i ) <- Empty done
let reset h = let len = Array . length h . data in if Obj . size ( Obj . repr h ) < 4 || len = h . initial_size then clear h else begin h . size <- 0 ; h . data <- Array . make h . initial_size Empty end
let copy h = { h with data = Array . copy h . data }
let length h = h . size