text
stringlengths
0
601k
let rec firsts = function | [ ] -> assert false | [ p ] -> [ ] , p | p :: l -> let head , tail = firsts l in p :: head , tail
module State = struct type ' a t = | Empty | Cons of ' a * ' a t | Par of ' a t * ' a t let singleton x = Cons ( x , Empty ) let cons x s = Cons ( x , s ) let seq s1 s2 = match s1 , s2 with | ( Empty , s ) | ( s , Empty ) -> s | _ -> Seq ( s1 , s2 ) let par s1 s2 = match s1 , s2 with | ( Empty , s ) | ( s , Empty ) -> s | _ -> Par ( s1 , s2 ) let empty = Empty let is_empty s = ( s = empty ) let rec fold f s acc = match s with | Empty -> acc | Cons ( x , l ) -> f x ( fold f l acc ) | Par ( l1 , l2 ) -> fold f l1 ( fold f l2 acc ) | Seq ( l1 , l2 ) -> fold f l1 ( fold f l2 acc ) let list acc s = fold ( fun l ls -> l :: ls ) s acc let cons_list xs s = List . fold_left ( fun s x -> Cons ( x , s ) ) s ( List . rev xs ) let rec map f s = match s with | Empty -> Empty | Cons ( x , l ) -> Cons ( f x , map f l ) | Par ( l1 , l2 ) -> Par ( map f l1 , map f l2 ) | Seq ( l1 , l2 ) -> Seq ( map f l1 , map f l2 ) let rec iter f s = match s with | Empty -> ( ) | Cons ( x , l ) -> ( f x ; iter f l ) | Par ( l1 , l2 ) | Seq ( l1 , l2 ) -> ( iter f l1 ; iter f l2 ) let rec partition f s = match s with | Empty -> Empty , Empty | Cons ( x , l ) -> let left , right = partition f l in if f x then Cons ( x , left ) , right else left , Cons ( x , right ) | Par ( l1 , l2 ) -> let left1 , right1 = partition f l1 in let left2 , right2 = partition f l2 in Par ( left1 , left2 ) , Par ( right1 , right2 ) | Seq ( l1 , l2 ) -> let left1 , right1 = partition f l1 in let left2 , right2 = partition f l2 in Seq ( left1 , left2 ) , Seq ( right1 , right2 ) let fprint_t fprint_v ff s = let rec print ff s = Format . fprintf ff " [ @< hov >% a ] " @ print s end
let internal_error message printer input = Format . eprintf " [ @ Internal error ( % s ) . @ % a . ] " @@ message printer input ; raise Error
module Context = struct type t external create : unit -> t = " caml_zmq_new " external terminate : t -> unit = " caml_zmq_term " type int_option = | ZMQ_IO_THREADS | ZMQ_MAX_SOCKETS | ZMQ_IPV6 external set_int_option : t -> int_option -> int -> unit = " caml_zmq_ctx_set_int_option " external get_int_option : t -> int_option -> int = " caml_zmq_ctx_get_int_option " let get_io_threads ctx = get_int_option ctx ZMQ_IO_THREADS let set_io_threads ctx = set_int_option ctx ZMQ_IO_THREADS let get_max_sockets ctx = get_int_option ctx ZMQ_MAX_SOCKETS let set_max_sockets ctx = set_int_option ctx ZMQ_MAX_SOCKETS let get_ipv6 ctx = ( get_int_option ctx ZMQ_IPV6 ) ZMQ_IPV6 == 1 let set_ipv6 ctx has_ipv6 = set_int_option ctx ZMQ_IPV6 ( if has_ipv6 then 1 else 0 ) 0 end
module Msg = struct open Bigarray type t type bigstring = ( char , int8_unsigned_elt , c_layout ) c_layout Array1 . t external native_init_data : bigstring -> int -> int -> t = " caml_zmq_msg_init_data " let init_data ( ? offset = 0 ) 0 ? length buf = let length = let max_possible = Array1 . dim buf - offset in match length with | Some l -> min l max_possible | None -> max_possible in native_init_data buf offset length external size : t -> int = " caml_zmq_msg_size " external unsafe_data : t -> bigstring = " caml_zmq_msg_data " let copy_data msg = let data = unsafe_data msg in let copy = Array1 . create char c_layout ( Array1 . dim data ) data in Array1 . blit data copy ; copy external close : t -> unit = " caml_zmq_msg_close " external gets : t -> string -> string = " caml_zmq_msg_gets " end
module Socket = struct open Stdint type + ' a t type ' a kind = int let pair = 0 let pub = 1 let sub = 2 let req = 3 let rep = 4 let dealer = 5 let router = 6 let pull = 7 let push = 8 let xpub = 9 let xsub = 10 let stream = 11 external create : Context . t -> ' a kind -> ' a t = " caml_zmq_socket " external close : ' a t -> unit = " caml_zmq_close " external connect : ' a t -> string -> unit = " caml_zmq_connect " external disconnect : ' a t -> string -> unit = " caml_zmq_disconnect " external bind : ' a t -> string -> unit = " caml_zmq_bind " external unbind : ' a t -> string -> unit = " caml_zmq_unbind " external native_recv : ' a t -> bool -> string = " caml_zmq_recv " let recv ( ? block = true ) true socket = native_recv socket block external native_send : ' a t -> string -> bool -> bool -> unit = " caml_zmq_send " let send ( ? block = true ) true ( ? more = false ) false socket message = native_send socket message block more external native_recv_msg : ' a t -> bool -> Msg . t = " caml_zmq_recv_msg " let recv_msg ( ? block = true ) true socket = native_recv_msg socket block external native_send_msg : ' a t -> Msg . t -> bool -> bool -> unit = " caml_zmq_send_msg " let send_msg ( ? block = true ) true ( ? more = false ) false socket message = native_send_msg socket message block more type int64_option = | ZMQ_MAXMSGSIZE external set_int64_option : ' a t -> int64_option -> int64 -> unit = " caml_zmq_set_int64_option " external get_int64_option : ' a t -> int64_option -> int64 = " caml_zmq_get_int64_option " type uint64_option = | ZMQ_AFFINITY external set_uint64_option : ' a t -> uint64_option -> Uint64 . t -> unit = " caml_zmq_set_uint64_option " external get_uint64_option : ' a t -> uint64_option -> Uint64 . t = " caml_zmq_get_uint64_option " type string_option = | ZMQ_IDENTITY | ZMQ_SUBSCRIBE | ZMQ_UNSUBSCRIBE | ZMQ_LAST_ENDPOINT | ZMQ_TCP_ACCEPT_FILTER | ZMQ_PLAIN_USERNAME | ZMQ_PLAIN_PASSWORD | ZMQ_CURVE_PUBLICKEY | ZMQ_CURVE_SECRETKEY | ZMQ_CURVE_SERVERKEY | ZMQ_ZAP_DOMAIN external set_string_option : ' a t -> string_option -> string -> unit = " caml_zmq_set_string_option " external get_string_option : ' a t -> string_option -> int -> string = " caml_zmq_get_string_option " [ @@@ warning " - 37 ] " type int_option = | ZMQ_RATE | ZMQ_RECOVERY_IVL | ZMQ_SNDBUF | ZMQ_RCVBUF | ZMQ_RCVMORE | ZMQ_EVENTS | ZMQ_TYPE | ZMQ_LINGER | ZMQ_RECONNECT_IVL | ZMQ_BACKLOG | ZMQ_RECONNECT_IVL_MAX | ZMQ_SNDHWM | ZMQ_RCVHWM | ZMQ_MULTICAST_HOPS | ZMQ_RCVTIMEO | ZMQ_SNDTIMEO | ZMQ_IPV6 | ZMQ_ROUTER_MANDATORY | ZMQ_TCP_KEEPALIVE | ZMQ_TCP_KEEPALIVE_CNT | ZMQ_TCP_KEEPALIVE_IDLE | ZMQ_TCP_KEEPALIVE_INTVL | ZMQ_IMMEDIATE | ZMQ_XPUB_VERBOSE | ZMQ_MECHANISM | ZMQ_PLAIN_SERVER | ZMQ_CURVE_SERVER | ZMQ_PROBE_ROUTER | ZMQ_REQ_CORRELATE | ZMQ_REQ_RELAXED | ZMQ_CONFLATE [ @@@ warning " + 37 ] " external set_int_option : ' a t -> int_option -> int -> unit = " caml_zmq_set_int_option " external get_int_option : ' a t -> int_option -> int = " caml_zmq_get_int_option " let validate_string_length min max str msg = match String . length str with | n when n < min -> invalid_arg msg | n when n > max -> invalid_arg msg | _ -> ( ) let set_max_message_size socket size = set_int64_option socket ZMQ_MAXMSGSIZE ( Int64 . of_int size ) size let get_max_message_size socket = Int64 . to_int ( get_int64_option socket ZMQ_MAXMSGSIZE ) ZMQ_MAXMSGSIZE let set_affinity socket size = set_uint64_option socket ZMQ_AFFINITY ( Uint64 . of_int size ) size let get_affinity socket = Uint64 . to_int ( get_uint64_option socket ZMQ_AFFINITY ) ZMQ_AFFINITY let set_identity socket identity = validate_string_length 1 255 identity " set_identity " ; set_string_option socket ZMQ_IDENTITY identity let maximal_buffer_length = 255 let curve_z85_buffer_length = 41 let get_identity socket = get_string_option socket ZMQ_IDENTITY maximal_buffer_length let subscribe socket topic = set_string_option socket ZMQ_SUBSCRIBE topic let unsubscribe socket topic = set_string_option socket ZMQ_UNSUBSCRIBE topic let get_last_endpoint socket = get_string_option socket ZMQ_LAST_ENDPOINT maximal_buffer_length let set_tcp_accept_filter socket filter = set_string_option socket ZMQ_TCP_ACCEPT_FILTER filter let set_rate socket rate = set_int_option socket ZMQ_RATE rate let get_rate socket = get_int_option socket ZMQ_RATE let set_recovery_interval socket interval = set_int_option socket ZMQ_RECOVERY_IVL interval let get_recovery_interval socket = get_int_option socket ZMQ_RECOVERY_IVL let set_send_buffer_size socket size = set_int_option socket ZMQ_SNDBUF size let get_send_buffer_size socket = get_int_option socket ZMQ_SNDBUF let set_receive_buffer_size socket size = set_int_option socket ZMQ_RCVBUF size let get_receive_buffer_size socket = get_int_option socket ZMQ_RCVBUF let has_more socket = get_int_option socket ZMQ_RCVMORE != 0 let set_linger_period socket period = set_int_option socket ZMQ_LINGER period let get_linger_period socket = get_int_option socket ZMQ_LINGER let set_reconnect_interval socket interval = set_int_option socket ZMQ_RECONNECT_IVL interval let get_reconnect_interval socket = get_int_option socket ZMQ_RECONNECT_IVL let set_connection_backlog socket backlog = set_int_option socket ZMQ_BACKLOG backlog let get_connection_backlog socket = get_int_option socket ZMQ_BACKLOG let set_reconnect_interval_max socket interval = set_int_option socket ZMQ_RECONNECT_IVL_MAX interval let get_reconnect_interval_max socket = get_int_option socket ZMQ_RECONNECT_IVL_MAX let set_send_high_water_mark socket mark = set_int_option socket ZMQ_SNDHWM mark let get_send_high_water_mark socket = get_int_option socket ZMQ_SNDHWM let set_receive_high_water_mark socket mark = set_int_option socket ZMQ_RCVHWM mark let get_receive_high_water_mark socket = get_int_option socket ZMQ_RCVHWM let set_multicast_hops socket hops = set_int_option socket ZMQ_MULTICAST_HOPS hops let get_multicast_hops socket = get_int_option socket ZMQ_MULTICAST_HOPS let set_receive_timeout socket timeout = set_int_option socket ZMQ_RCVTIMEO timeout let get_receive_timeout socket = get_int_option socket ZMQ_RCVTIMEO let set_send_timeout socket timeout = set_int_option socket ZMQ_SNDTIMEO timeout let get_send_timeout socket = get_int_option socket ZMQ_SNDTIMEO let set_ipv6 socket flag = let value = match flag with true -> 1 | false -> 0 in set_int_option socket ZMQ_IPV6 value let get_ipv6 socket = match get_int_option socket ZMQ_IPV6 with | 0 -> false | _ -> true let set_router_mandatory socket flag = let value = match flag with true -> 1 | false -> 0 in set_int_option socket ZMQ_ROUTER_MANDATORY value let get_router_mandatory socket = match get_int_option socket ZMQ_ROUTER_MANDATORY with | 0 -> false | _ -> true let set_tcp_keepalive socket flag = let value = match flag with | ` Default -> - 1 | ` Value false -> 0 | ` Value true -> 1 in set_int_option socket ZMQ_TCP_KEEPALIVE value let get_tcp_keepalive socket = match get_int_option socket ZMQ_TCP_KEEPALIVE with | - 1 -> ` Default | 0 -> ` Value false | _ -> ` Value true let set_tcp_keepalive_idle socket flag = let value = match flag with | ` Default -> - 1 | ` Value n when n <= 0 -> invalid_arg " set_tcp_keepalive_idle " | ` Value n -> n in set_int_option socket ZMQ_TCP_KEEPALIVE_IDLE value let get_tcp_keepalive_idle socket = match get_int_option socket ZMQ_TCP_KEEPALIVE_IDLE with | - 1 -> ` Default | n when n <= 0 -> assert false | n -> ` Value n let set_tcp_keepalive_interval socket flag = let value = match flag with | ` Default -> - 1 | ` Value n when n <= 0 -> invalid_arg " set_tcp_keepalive_interval " | ` Value n -> n in set_int_option socket ZMQ_TCP_KEEPALIVE_INTVL value let get_tcp_keepalive_interval socket = match get_int_option socket ZMQ_TCP_KEEPALIVE_INTVL with | - 1 -> ` Default | n when n <= 0 -> assert false | n -> ` Value n let set_tcp_keepalive_count socket flag = let value = match flag with | ` Default -> - 1 | ` Value n when n <= 0 -> invalid_arg " set_tcp_keepalive_count " | ` Value n -> n in set_int_option socket ZMQ_TCP_KEEPALIVE_CNT value let get_tcp_keepalive_count socket = match get_int_option socket ZMQ_TCP_KEEPALIVE_CNT with | - 1 -> ` Default | n when n <= 0 -> assert false | n -> ` Value n let set_immediate socket flag = let value = match flag with | true -> 1 | false -> 0 in set_int_option socket ZMQ_IMMEDIATE value let get_immediate socket = match get_int_option socket ZMQ_IMMEDIATE with | 0 -> false | _ -> true let set_xpub_verbose socket flag = let value = match flag with | true -> 1 | false -> 0 in set_int_option socket ZMQ_XPUB_VERBOSE value let set_probe_router socket flag = set_int_option socket ZMQ_PROBE_ROUTER ( if flag then 1 else 0 ) 0 let set_req_correlate socket flag = set_int_option socket ZMQ_REQ_CORRELATE ( if flag then 1 else 0 ) 0 let set_req_relaxed socket flag = set_int_option socket ZMQ_REQ_RELAXED ( if flag then 1 else 0 ) 0 let set_plain_server socket flag = set_int_option socket ZMQ_PLAIN_SERVER ( if flag then 1 else 0 ) 0 let set_curve_server socket flag = set_int_option socket ZMQ_CURVE_SERVER ( if flag then 1 else 0 ) 0 let set_plain_username socket = set_string_option socket ZMQ_PLAIN_USERNAME let get_plain_username socket = get_string_option socket ZMQ_PLAIN_USERNAME maximal_buffer_length let set_plain_password socket = set_string_option socket ZMQ_PLAIN_PASSWORD let get_plain_password socket = get_string_option socket ZMQ_PLAIN_PASSWORD maximal_buffer_length let validate_curve_key_length str msg = match String . length str with | 32 | 40 -> ( ) | _ -> invalid_arg msg let get_curve_publickey socket = get_string_option socket ZMQ_CURVE_PUBLICKEY curve_z85_buffer_length let set_curve_publickey socket str = validate_curve_key_length str " set_curve_publickey " ; set_string_option socket ZMQ_CURVE_PUBLICKEY str let get_curve_secretkey socket = get_string_option socket ZMQ_CURVE_SECRETKEY curve_z85_buffer_length let set_curve_secretkey socket str = validate_curve_key_length str " set_curve_secretkey " ; set_string_option socket ZMQ_CURVE_SECRETKEY str let get_curve_serverkey socket = get_string_option socket ZMQ_CURVE_SERVERKEY curve_z85_buffer_length let set_curve_serverkey socket str = validate_curve_key_length str " set_curve_serverkey " ; set_string_option socket ZMQ_CURVE_SERVERKEY str let get_mechanism socket = match get_int_option socket ZMQ_MECHANISM with | 0 -> ` Null | 1 -> ` Plain | 2 -> ` Curve | _ -> assert false let set_zap_domain socket = set_string_option socket ZMQ_ZAP_DOMAIN let get_zap_domain socket = get_string_option socket ZMQ_ZAP_DOMAIN maximal_buffer_length let set_conflate socket flag = set_int_option socket ZMQ_CONFLATE ( if flag then 1 else 0 ) 0 external get_fd : ' a t -> Unix . file_descr = " caml_zmq_get_fd " type event = No_event | Poll_in | Poll_out | Poll_in_out | Poll_error external events : ' a t -> event = " caml_zmq_get_events " let recv_all_wrapper ( f : ? block : bool -> _ t -> _ ) _ = let rec loop socket accu = if has_more socket then loop socket ( f socket :: accu ) accu else accu in fun ? block socket -> let first = f ? block socket in List . rev ( loop socket [ first ] first ) first let send_all_wrapper ( f : ? block : bool -> ? more : bool -> _ t -> _ -> unit ) unit = let rec send_all_inner_loop socket message = match message with | [ ] -> ( ) | hd :: [ ] -> f socket hd | hd :: tl -> f ~ more : true socket hd ; send_all_inner_loop socket tl in fun ? block socket message -> match message with | [ ] -> ( ) | hd :: [ ] -> f ? block ~ more : false socket hd | hd :: tl -> f ? block ~ more : true socket hd ; send_all_inner_loop socket tl let recv_all ? block socket = recv_all_wrapper recv ? block socket let send_all ? block socket message = send_all_wrapper send ? block socket message let recv_msg_all ? block socket = recv_all_wrapper recv_msg ? block socket let send_msg_all ? block socket message = send_all_wrapper send_msg ? block socket message end
module Proxy = struct external zmq_proxy2 : ' a Socket . t -> ' b Socket . t -> unit = " caml_zmq_proxy2 " external zmq_proxy3 : ' a Socket . t -> ' b Socket . t -> ' c Socket . t -> unit = " caml_zmq_proxy3 " let create ? capture frontend backend = match capture with | Some capture -> zmq_proxy3 frontend backend capture | None -> zmq_proxy2 frontend backend end
module Poll = struct type t type poll_event = In | Out | In_out type ' a poll_mask = ( ' a Socket . t * poll_event ) poll_event let mask_in_out t = ( t :> [ ` Pair ` | Pub ` | Sub ` | Req ` | Rep ` | Dealer ` | Router ` | Pull ` | Push ` | Xsub ` | Xpub ` | Stream ] Stream Socket . t ) , In_out let mask_in t = ( t :> [ ` Pair ` | Pub ` | Sub ` | Req ` | Rep ` | Dealer ` | Router ` | Pull ` | Push ` | Xsub ` | Xpub ` | Stream ] Stream Socket . t ) , In let mask_out t = ( t :> [ ` Pair ` | Pub ` | Sub ` | Req ` | Rep ` | Dealer ` | Router ` | Pull ` | Push ` | Xsub ` | Xpub ` | Stream ] Stream Socket . t ) , Out external mask_of : ' a poll_mask array -> t = " caml_zmq_poll_of_pollitem_array " external of_masks : ' a poll_mask array -> t = " caml_zmq_poll_of_pollitem_array " external native_poll : t -> int -> poll_event option array = " caml_zmq_poll " let poll ( ? timeout = - 1 ) 1 items = native_poll items timeout end
module Monitor = struct type t = string type address = string type error_no = int type error_text = string type event = | Connected of address * Unix . file_descr | Connect_delayed of address | Connect_retried of address * int | Listening of address * Unix . file_descr | Bind_failed of address * error_no * error_text | Accepted of address * Unix . file_descr | Accept_failed of address * error_no * error_text | Closed of address * Unix . file_descr | Close_failed of address * error_no * error_text | Disconnected of address * Unix . file_descr | Monitor_stopped of address | Handshake_failed_no_detail of address | Handshake_succeeded of address | Handshake_failed_protocol of address * int | Handshake_failed_auth of address * int external socket_monitor : ' a Socket . t -> string -> unit = " caml_zmq_socket_monitor " let create socket = let socket_id = Hashtbl . hash ( Socket . get_fd socket ) socket in let address = Printf . sprintf " inproc :// _socket_monitor -% d -% x . % x " ( Unix . getpid ( ) ) socket_id ( Random . bits ( ) ) in socket_monitor socket address ; address let connect ctx t = let s = Socket . create ctx Socket . pair in Socket . connect s t ; s external decode_monitor_event : string -> string -> event = " caml_decode_monitor_event " let recv ? block socket = let event = Socket . recv ? block socket in assert ( Socket . has_more socket ) socket ; let addr = Socket . recv ~ block : false socket in decode_monitor_event event addr let get_peer_address fd = try let sockaddr = Unix . getpeername fd in let domain = match Unix . domain_of_sockaddr sockaddr with | Unix . PF_UNIX -> " unix " | Unix . PF_INET -> " tcp " | Unix . PF_INET6 -> " tcp6 " in match sockaddr with | Unix . ADDR_UNIX s -> Printf . sprintf " % s ://% s " domain s ; | Unix . ADDR_INET ( addr , port ) port -> Printf . sprintf " % s ://% s :% d " domain ( Unix . string_of_inet_addr addr ) addr port with | Unix . Unix_error _ -> " unknown " let internal_string_of_event push_address pop_address = function | Connected ( addr , fd ) fd -> Printf . sprintf " Connect : % s . peer % s " addr ( push_address fd ) fd | Connect_delayed addr -> Printf . sprintf " Connect delayed : % s " addr | Connect_retried ( addr , interval ) interval -> Printf . sprintf " Connect retried : % s - % d " addr interval | Listening ( addr , fd ) fd -> Printf . sprintf " Listening : % s - peer % s " addr ( push_address fd ) fd | Bind_failed ( addr , error_no , error_text ) error_text -> Printf . sprintf " Bind failed : % s . % d :% s " addr error_no error_text | Accepted ( addr , fd ) fd -> Printf . sprintf " Accepted : % s . peer % s " addr ( push_address fd ) fd | Accept_failed ( addr , error_no , error_text ) error_text -> Printf . sprintf " Accept failed : % s . % d :% s " addr error_no error_text | Closed ( addr , fd ) fd -> Printf . sprintf " Closed : % s . peer % s " addr ( pop_address fd ) fd | Close_failed ( addr , error_no , error_text ) error_text -> Printf . sprintf " Close failed : % s . % d :% s " addr error_no error_text | Disconnected ( addr , fd ) fd -> Printf . sprintf " Disconnect : % s . peer % s " addr ( pop_address fd ) fd | Monitor_stopped addr -> Printf . sprintf " Monitor_stopped : % s " addr | Handshake_failed_no_detail addr -> Printf . sprintf " Handshake_failed_no_detail : % s " addr | Handshake_succeeded addr -> Printf . sprintf " Handshake_succeeded : % s " addr | Handshake_failed_protocol ( addr , code ) code -> Printf . sprintf " Handshake_failed_protocol : % s - % d " addr code | Handshake_failed_auth ( addr , code ) code -> Printf . sprintf " Handshake_failed_auth : % s - % d " addr code let string_of_event event = internal_string_of_event get_peer_address get_peer_address event let mk_string_of_event ( ) = let state = ref [ ] in let pop_address fd = let rec pop acc = function | [ ] -> ( get_peer_address fd , acc ) acc | ( fd ' , address ) address :: xs when fd ' = fd -> ( address , acc @ xs ) xs | x :: xs -> pop ( x :: acc ) acc xs in let ( address , new_state ) new_state = pop [ ] ! state in state := new_state ; address in let push_address fd = let address = get_peer_address fd in state := ( fd , address ) address :: ! state ; address in internal_string_of_event push_address pop_address end
module Z85 = struct external encode : string -> string = " caml_z85_encode " external decode : string -> string = " caml_z85_decode " end
module Curve = struct external keypair : unit -> string * string = " caml_curve_keypair " end
let zmq_raise e str func_name = let exn = match e with | I_ENOTSUP -> Unix ( . Unix_error ( EOPNOTSUPP , func_name , ) ) " " | I_EPROTONOSUPPORT -> Unix ( . Unix_error ( EPROTONOSUPPORT , func_name , ) ) " " | I_ENOBUFS -> Unix ( . Unix_error ( ENOBUFS , func_name , ) ) " " | I_ENETDOWN -> Unix ( . Unix_error ( ENETDOWN , func_name , ) ) " " | I_EADDRINUSE -> Unix ( . Unix_error ( EADDRINUSE , func_name , ) ) " " | I_EADDRNOTAVAIL -> Unix ( . Unix_error ( EADDRNOTAVAIL , func_name , ) ) " " | I_ECONNREFUSED -> Unix ( . Unix_error ( ECONNREFUSED , func_name , ) ) " " | I_EINPROGRESS -> Unix ( . Unix_error ( EINPROGRESS , func_name , ) ) " " | I_ENOTSOCK -> Unix ( . Unix_error ( ENOTSOCK , func_name , ) ) " " | I_EMSGSIZE -> Unix ( . Unix_error ( EMSGSIZE , func_name , ) ) " " | I_EAFNOSUPPORT -> Unix ( . Unix_error ( EAFNOSUPPORT , func_name , ) ) " " | I_ENETUNREACH -> Unix ( . Unix_error ( ENETUNREACH , func_name , ) ) " " | I_ECONNABORTED -> Unix ( . Unix_error ( ECONNABORTED , func_name , ) ) " " | I_ECONNRESET -> Unix ( . Unix_error ( ECONNRESET , func_name , ) ) " " | I_ENOTCONN -> Unix ( . Unix_error ( ENOTCONN , func_name , ) ) " " | I_ETIMEDOUT -> Unix ( . Unix_error ( ETIMEDOUT , func_name , ) ) " " | I_EHOSTUNREACH -> Unix ( . Unix_error ( EHOSTUNREACH , func_name , ) ) " " | I_ENETRESET -> Unix ( . Unix_error ( ENETRESET , func_name , ) ) " " | I_EFSM -> ZMQ_exception ( EFSM , str ) str | I_ENOCOMPATPROTO -> ZMQ_exception ( ENOCOMPATPROTO , str ) str | I_ETERM -> ZMQ_exception ( ETERM , str ) str | I_EMTHREAD -> ZMQ_exception ( EMTHREAD , str ) str | I_EUNKNOWN -> ZMQ_exception ( EUNKNOWN , str ) str in raise exn
let ( ) = Callback . register " Zmq . zmq_raise " zmq_raise
let debug fmt = Printf . ksprintf ( fun s -> print_endline s ; flush stdout ) stdout fmt
let sleep t = ignore ( ignoreUnix . select [ ] [ ] [ ] ( ( float t ) t . / 1000 . 0 ) 0 ) 0
let dump_events l = let f = function | None -> " None " | Some In -> " In " | Some Out -> " Out " | Some In_out -> " In / Out " in let l = Array . to_list ( Array . map f l ) l in [ " " | ^ ( String . concat " ; " l ) l ^ ] " " |
let test_ctx_options ( ) = let ctx = Context . create ( ) in let test_set_get_int msg setter getter ctx v = let default = getter ctx in setter ctx v ; assert_equal ~ msg ~ printer : string_of_int v ( getter ctx ) ctx ; setter ctx default ; assert_equal ~ msg default ( getter ctx ) ctx ; ( ) in let test_set_get_bool msg setter getter ctx v = let default = getter ctx in setter ctx v ; assert_equal ~ msg ~ printer : string_of_bool v ( getter ctx ) ctx ; setter ctx default ; assert_equal ~ msg default ( getter ctx ) ctx ; ( ) in test_set_get_int " IO threads " set_io_threads get_io_threads ctx 1 ; test_set_get_int " Max sockets " set_max_sockets get_max_sockets ctx 1024 ; test_set_get_bool " IPv6 " Context . set_ipv6 Context . get_ipv6 ctx false ; Context . terminate ctx
let test_socket_options ( ) = let ctx = Context . create ( ) in let socket = create ctx push in let test_set_get_int msg setter getter socket v = let default = getter socket in setter socket v ; assert_equal ~ msg ~ printer : string_of_int v ( getter socket ) socket ; setter socket default ; assert_equal ~ msg default ( getter socket ) socket ; ( ) in let test_set_get_value msg setter getter socket v = let default = getter socket in setter socket v ; assert_equal ~ msg ~ printer ( : function ` Default -> " default " | ` Value n -> string_of_int n ) n v ( getter socket ) socket ; setter socket default ; assert_equal ~ msg default ( getter socket ) socket ; ( ) in test_set_get_int " Highwatermark " set_receive_high_water_mark get_receive_high_water_mark socket 1235 ; test_set_get_int " Affinity " set_affinity get_affinity socket 3 ; test_set_get_int " Receive timeout " set_receive_timeout get_receive_timeout socket 1000 ; test_set_get_value " Tcp keepalive interval " set_tcp_keepalive_interval get_tcp_keepalive_interval socket ( ` Value 1000 ) 1000 ; Socket . close socket ; Context . terminate ctx ; ( )
let test_monitor ( ) = let endpoint = " ipc :// monitor_socket " in let expect_handshake = match Zmq . version ( ) with | ( 4 , n , _ ) _ when n < 3 -> false | ( 3 , _ , _ ) _ -> failwith " Only zmq version 4 or higher is supported " | _ -> true in let assert_event name socket event = let printer x = x in let rec cmp str1 str2 = match String . length str1 <= String . length str2 with | true -> String . sub str2 0 ( String . length str1 ) str1 = str1 | false -> cmp str2 str1 in let rec receive_event ~ end_time = match Zmq . Monitor . recv ~ block : false socket with | event -> Zmq . Monitor . string_of_event event | exception Unix . Unix_error ( Unix_errorUnix . EAGAIN , _ , _ ) _ when end_time > ( Unix . gettimeofday ( ) ) -> sleep 10 ; receive_event ~ end_time | exception Unix . Unix_error ( Unix_errorUnix . EAGAIN , _ , _ ) _ -> " No event received " in let received = receive_event ~ end_time ( : Unix . gettimeofday ( ) . + 1 . 0 ) 0 in assert_equal ~ msg ( : Printf . sprintf " Wrong event received on % s " name ) name ~ printer ~ cmp ( Printf . sprintf " % s : % s " event endpoint ) endpoint received in let ctx = Context . create ( ) in let s1 = Zmq . Socket . create ctx Zmq . Socket . pair in let s2 = Zmq . Socket . create ctx Zmq . Socket . pair in let m1 = let mon_t = Zmq . Monitor . create s1 in Zmq . Monitor . connect ctx mon_t in let m2 = let mon_t = Zmq . Monitor . create s2 in Zmq . Monitor . connect ctx mon_t in Zmq . Socket . bind s1 endpoint ; assert_event " m1 " m1 " Listening " ; Zmq . Socket . connect s2 endpoint ; assert_event " m1 " m1 " Accepted " ; assert_event " m2 " m2 " Connect " ; if ( expect_handshake ) expect_handshake then begin assert_event " m1 " m1 " Handshake_succeeded " ; assert_event " m2 " m2 " Handshake_succeeded " end ; Zmq . Socket . close s1 ; assert_event " m1 " m1 " Closed " ; Zmq . Socket . close s2 ; assert_event " m2 " m2 " Disconnect " ; Zmq . Socket . close m2 ; Zmq . Socket . close m1 ; Context . terminate ctx ; ( )
let test_proxy ( ) = let ctx = Zmq . Context . create ( ) in let pull_endpoint = " inproc :// pull " in let pub_endpoint = " inproc :// pub " in let pull = Zmq . Socket . create ctx pull in let pub = Zmq . Socket . create ctx pub in let proxy ( pull , pub ) pub = Zmq . Socket . bind pull pull_endpoint ; Zmq . Socket . bind pub pub_endpoint ; try Zmq . Proxy . create pull pub ; assert_failure " Proxy . create must raise an exception when completed " with Unix . Unix_error ( Unix . ENOTSOCK , _ , _ ) _ -> ( ) in let _thread = Thread . create proxy ( pull , pub ) pub in sleep 10 ; let sub = let s = Zmq . Socket . create ctx sub in Zmq . Socket . connect s pub_endpoint ; Zmq . Socket . subscribe s " " ; s in let push = let s = Zmq . Socket . create ctx push in Zmq . Socket . connect s pull_endpoint ; s in let msg1 = " Message1 " in let msg2 = " Message2 " in Zmq . Socket . send push msg1 ; Zmq . Socket . send push msg2 ; assert_equal msg1 ( Zmq . Socket . recv sub ) sub ; assert_equal msg2 ( Zmq . Socket . recv sub ) sub ; Zmq . Socket . close sub ; Zmq . Socket . close push ; Zmq . Socket . close pull ; Zmq . Socket . close pub ; Zmq . Context . terminate ctx ; ( )
let test_unix_exceptions = bracket ( fun ( ) -> let ctx = Zmq . Context . create ( ) in let s = Zmq . Socket . create ctx pull in ( ctx , s ) s ) ( fun ( _ , s ) s -> let mask = Zmq . Poll . of_masks [ | s , Zmq . Poll . In ] | in Sys ( . set_signal sigalrm ( Signal_handle ( fun _ -> ( ) ) ) ) ; ignore ( Unix . alarm 1 ) 1 ; assert_raises ~ msg " : Failed to raise EINTR " Unix ( . Unix_error ( Unix_errorEINTR , " zmq_poll " , ) ) " " ( fun _ -> Zmq . Poll . poll ~ timeout : 2000 mask ) mask ; ( ) ) ( fun ( ctx , s ) s -> Zmq . Socket . close s ; Zmq . Context . terminate ctx )
let test_zmq_exception = bracket ( fun ( ) -> let ctx = Zmq . Context . create ( ) in let socket = Zmq . Socket . create ctx req in ( ctx , socket ) socket ) ( fun ( _ , socket ) socket -> assert_raises ( Zmq . ZMQ_exception ( ZMQ_exceptionZmq . EFSM , " Operation cannot be accomplished in current state ) ) " ( fun ( ) -> Zmq . Socket . recv socket ) socket ; ) ( fun ( ctx , socket ) socket -> Zmq . Socket . close socket ; Zmq . Context . terminate ctx ; )
let test_socket_gc ( ) = let sock = let ctx = Zmq . Context . create ( ) in Zmq . Socket . create ctx Zmq . Socket . req in Gc . compact ( ) ; Zmq . Socket . close sock ; Gc . compact ( )
let test_context_gc ( ) = let ctx = let ctx = Zmq . Context . create ( ) in let sock = Zmq . Socket . create ctx Zmq . Socket . pair in Zmq . Socket . connect sock " ipc :// context_gc_socket " ; Zmq . Socket . send sock " test " ; ctx in Gc . compact ( ) ; Zmq . Context . terminate ctx ; ( )
let test_z85 ( ) = let binary = " \ xBB \ x88 \ x47 \ x1D \ x65 \ xE2 \ x65 \ x9B " ^ " \ x30 \ xC5 \ x5A \ x53 \ x21 \ xCE \ xBB \ x5A " ^ " \ xAB \ x2B \ x70 \ xA3 \ x98 \ x64 \ x5C \ x26 " ^ " \ xDC \ xA2 \ xB2 \ xFC \ xB4 \ x3F \ xC5 \ x18 " in let ascii = " Yne @$ w - vo < fVvi ] fVvia < NY6T1ed : M $ fCG [ * IaLV { IaLVhID " in assert_equal ~ printer ( : Printf . sprintf " % S ) " binary ( Zmq . Z85 . decode ascii ) ascii ; assert_equal ~ printer ( : Printf . sprintf " % S ) " ascii ( Zmq . Z85 . encode binary ) binary ; assert_raises ( Invalid_argument " zmq_z85_encode ) " ( fun ( ) -> Zmq . Z85 . encode " 123 ) " ; assert_raises ( Invalid_argument " zmq_z85_decode ) " ( fun ( ) -> Zmq . Z85 . decode " 123 ) " ; ( )
let suite = " zmq test " >::: [ " request reply " >:: ( bracket ( fun ( ) -> let ctx = Zmq . Context . create ( ) in let req = create ctx req in let rep = create ctx rep in ctx , req , rep ) ( fun ( _ , req , rep ) rep -> let endpoint = " inproc :// endpoint " in bind rep endpoint ; connect req endpoint ; send req " request " ; let msg = recv rep in assert_equal " request " msg ; send rep " reply " ; let msg = recv req in assert_equal " reply " msg ) ( fun ( ctx , req , rep ) rep -> close req ; close rep ; Zmq . Context . terminate ctx ) ) ; " request reply ( multi - part ) part " >:: ( bracket ( fun ( ) -> let ctx = Zmq . Context . create ( ) in let req = create ctx req in let rep = create ctx rep in ctx , req , rep ) ( fun ( _ , req , rep ) rep -> let endpoint = " inproc :// endpoint " in bind rep endpoint ; connect req endpoint ; send_all req [ " request " ; " and more ] " ; let msg = recv_all rep in assert_equal [ " request " ; " and more ] " msg ; send_all rep [ " reply " ; " and more ] " ; let msg = recv_all req in assert_equal [ " reply " ; " and more ] " msg ) ( fun ( ctx , req , rep ) rep -> close req ; close rep ; Zmq . Context . terminate ctx ) ) ; " poll " >:: ( bracket ( fun ( ) -> let ctx = Zmq . Context . create ( ) in let req = create ctx req in let rep = create ctx rep in let sub = create ctx sub in ctx , req , rep , sub ) ( fun ( _ , req , rep , sub ) sub -> let endpoint = " inproc :// endpoint " in bind rep endpoint ; connect req endpoint ; subscribe sub " " ; let mask = of_masks [ | Poll . mask_in_out req ; Poll . mask_in_out rep ; Poll . mask_in_out sub ] | in assert_equal [ | Some Out ; None ; None ] | ( poll ~ timeout : 1000 mask ) mask ; send req " request " ; assert_equal [ | None ; Some In ; None ] | ( poll ~ timeout : 1000 mask ) mask ; let msg = recv ~ block : false rep in assert_equal " request " msg ; send rep " reply " ; assert_equal [ | Some In ; None ; None ] | ( poll ~ timeout : 1000 mask ) mask ; let msg = recv req in assert_equal " reply " msg ; ) ( fun ( ctx , req , rep , sub ) sub -> close req ; close rep ; close sub ; Zmq . Context . terminate ctx ; ) ) ; " get / set context options " >:: test_ctx_options ; " get / set socket options " >:: test_socket_options ; " proxy " >:: test_proxy ; " monitor " >:: test_monitor ; " z85 encoding / decoding " >:: test_z85 ; " unix exceptions " >:: test_unix_exceptions ; " zmq exceptions " >:: test_zmq_exception ; ]
module type ZN = sig type t include S . B58_DATA with type t := t include S . ENCODER with type t := t val zero : t val one : t val n : Z . t val ( + ) : t -> t -> t val ( * ) : t -> t -> t val ( - ) : t -> t -> t val ( = ) : t -> t -> bool val of_int : int -> t val of_Z : Z . t -> t val to_Z : t -> Z . t val of_bits_exn : String . t -> t val to_bits : t -> String . t val pow : t -> Z . t -> t val inv : t -> t option end
module type INT = sig val n : Z . t end
module MakeZn ( N : INT ) ( B : sig val b58_prefix : string end ) : ZN = struct type t = Z . t let n = N . n let max_char_length = 2 * Z . numbits n let zero = Z . zero let one = Z . one let of_Z r = Z . ( erem r n ) let to_Z a = a let of_int u = u |> Z . of_int |> of_Z let to_bits h = h |> Zplus . serialize |> fun s -> String . sub s 0 ( String . length s - 1 ) let of_bits_exn bits = if Compare . Int . ( String . length bits > max_char_length ) then failwith " input too long " else let x = Zplus . deserialize bits in if Zplus . ( x < zero || x >= N . n ) then failwith " out of range " else of_Z x let pow a x = Z . powm a Z . ( erem x ( sub n one ) ) n let ( + ) x y = Z . ( erem ( add x y ) n ) let ( * ) x y = Z . ( erem ( mul x y ) n ) let ( - ) x y = Z . ( erem ( sub x y ) n ) let ( = ) x y = Z . equal x y let inv a = Zplus . invert a n let title = Format . sprintf " Znz . Make ( % s ) " ( Z . to_string N . n ) let name = Format . sprintf " An element of Z / nZ for n = % s " ( Z . to_string N . n ) type Base58 . data += Data of t let b58check_encoding = Base58 . register_encoding ~ prefix : B . b58_prefix ~ length : 32 ~ to_raw : to_bits ~ of_raw ( : fun s -> Option . catch ( fun ( ) -> of_bits_exn s ) ) ~ wrap ( : fun x -> Data x ) include Helpers . MakeB58 ( struct type nonrec t = t let name = name let b58check_encoding = b58check_encoding end ) include Helpers . MakeEncoder ( struct type nonrec t = t let name = name let title = title let raw_encoding = Data_encoding . ( conv to_bits of_bits_exn string ) let to_b58check = to_b58check let to_short_b58check = to_short_b58check let of_b58check = of_b58check let of_b58check_opt = of_b58check_opt let of_b58check_exn = of_b58check_exn end ) end
module Stable = struct module Full_data = struct module V1 = struct module Index = struct type t = int let next = Int . succ let prev = Int . pred let before_first_transition = - 1 let to_external t = max 0 t let of_external ( _ : t ) = - 1 include Binable . Of_binable_without_uuid [ @ alert " - legacy " ] ( Int ) ( struct type t = int let to_binable = to_external let of_binable = of_external end ) include Sexpable . Of_sexpable ( Int ) ( struct type t = int let to_sexpable = to_external let of_sexpable = of_external end ) end module Regime = struct type t = { utc_offset_in_seconds : Int63 . Stable . V1 . t ; is_dst : bool ; abbrv : string } [ @@ deriving bin_io , sexp ] end module Leap_second = struct type t = { time_in_seconds_since_epoch : Int63 . Stable . V1 . t ; seconds : int } [ @@ deriving bin_io , sexp ] end module Transition = struct type t = { start_time_in_seconds_since_epoch : Int63 . Stable . V1 . t ; new_regime : Regime . t } [ @@ deriving bin_io , sexp ] end type t = { name : string ; original_filename : string option ; digest : Md5 . As_binary_string . t option ; transitions : Transition . t array ; mutable last_regime_index : Index . t ; default_local_time_type : Regime . t ; leap_seconds : Leap_second . t list } [ @@ deriving bin_io , sexp ] let compare t1 t2 = String . compare t1 . name t2 . name let original_filename zone = zone . original_filename let digest zone = zone . digest module Zone_file : sig val input_tz_file : zonename : string -> filename : string -> t end = struct let bool_of_int i = i <> 0 let input_long_as_int32 = let long = Bytes . create 4 in let int32_of_char chr = Int32 . of_int_exn ( int_of_char chr ) in fun ic -> In_channel . really_input_exn ic ~ buf : long ~ pos : 0 ~ len : 4 ; let sb1 = Int32 . shift_left ( int32_of_char ( Bytes . get long 0 ) ) 24 in let sb2 = Int32 . shift_left ( int32_of_char ( Bytes . get long 1 ) ) 16 in let sb3 = Int32 . shift_left ( int32_of_char ( Bytes . get long 2 ) ) 8 in let sb4 = int32_of_char ( Bytes . get long 3 ) in Int32 . bit_or ( Int32 . bit_or sb1 sb2 ) ( Int32 . bit_or sb3 sb4 ) ; ; let input_long_as_int ic = Int32 . to_int_exn ( input_long_as_int32 ic ) let input_long_as_int63 ic = Int63 . of_int32 ( input_long_as_int32 ic ) let input_long_long_as_int63 ic = let int63_of_char chr = Int63 . of_int_exn ( int_of_char chr ) in let shift c bits = Int63 . shift_left ( int63_of_char c ) bits in let long_long = Bytes . create 8 in In_channel . really_input_exn ic ~ buf : long_long ~ pos : 0 ~ len : 8 ; let result = shift ( Bytes . get long_long 0 ) 56 in let result = Int63 . bit_or result ( shift ( Bytes . get long_long 1 ) 48 ) in let result = Int63 . bit_or result ( shift ( Bytes . get long_long 2 ) 40 ) in let result = Int63 . bit_or result ( shift ( Bytes . get long_long 3 ) 32 ) in let result = Int63 . bit_or result ( shift ( Bytes . get long_long 4 ) 24 ) in let result = Int63 . bit_or result ( shift ( Bytes . get long_long 5 ) 16 ) in let result = Int63 . bit_or result ( shift ( Bytes . get long_long 6 ) 8 ) in let result = Int63 . bit_or result ( int63_of_char ( Bytes . get long_long 7 ) ) in result ; ; let input_list ic ~ len ~ f = let rec loop c lst = if c > 0 then loop ( c - 1 ) ( f ic :: lst ) else List . rev lst in loop len [ ] ; ; let input_array ic ~ len ~ f = Array . of_list ( input_list ic ~ len ~ f ) let input_regime ic = let utc_offset_in_seconds = input_long_as_int63 ic in let is_dst = bool_of_int ( Option . value_exn ( In_channel . input_byte ic ) ) in let abbrv_index = Option . value_exn ( In_channel . input_byte ic ) in let lt abbrv = { Regime . utc_offset_in_seconds ; is_dst ; abbrv } in lt , abbrv_index ; ; let input_abbreviations ic ~ len = let raw_abbrvs = input_list ic ~ len ~ f ( : fun ic -> Option . value_exn ( In_channel . input_char ic ) ) in let buf = Buffer . create len in let _ , indexed_abbrvs = List . fold raw_abbrvs ~ init ( : 0 , Map . Poly . empty ) ~ f ( : fun ( index , abbrvs ) c -> match c with | ' \ 000 ' -> let data = Buffer . contents buf in let next_index = index + String . length data + 1 in let abbrvs = Map . set abbrvs ~ key : index ~ data in Buffer . clear buf ; next_index , abbrvs | c -> Buffer . add_char buf c ; index , abbrvs ) in if Buffer . length buf <> 0 then raise ( Invalid_file_format " missing \ 000 terminating character in input_abbreviations " ) ; indexed_abbrvs ; ; let input_tz_file_gen ~ input_transition ~ input_leap_second ic = let utc_local_count = input_long_as_int ic in let std_wall_count = input_long_as_int ic in let leap_count = input_long_as_int ic in let transition_count = input_long_as_int ic in let type_count = input_long_as_int ic in let abbrv_char_count = input_long_as_int ic in let transition_times = input_list ic ~ f : input_transition ~ len : transition_count in let transition_indices = input_list ic ~ f ( : fun ic -> Option . value_exn ( In_channel . input_byte ic ) ) ~ len : transition_count in let regimes = input_list ic ~ f : input_regime ~ len : type_count in let abbreviations = input_abbreviations ic ~ len : abbrv_char_count in let leap_seconds = input_list ic ~ f : input_leap_second ~ len : leap_count in let _std_wall_indicators = input_array ic ~ len : std_wall_count ~ f ( : fun ic -> bool_of_int ( Option . value_exn ( In_channel . input_byte ic ) ) ) in let _utc_local_indicators = input_array ic ~ len : utc_local_count ~ f ( : fun ic -> bool_of_int ( Option . value_exn ( In_channel . input_byte ic ) ) ) in let regimes = Array . of_list ( List . map regimes ~ f ( : fun ( lt , abbrv_index ) -> let abbrv = Map . find_exn abbreviations abbrv_index in lt abbrv ) ) in let raw_transitions = List . map2_exn transition_times transition_indices ~ f ( : fun time index -> let regime = regimes . ( index ) in time , regime ) in let transitions = let rec make_transitions acc l = match l with | [ ] -> Array . of_list ( List . rev acc ) | ( start_time_in_seconds_since_epoch , new_regime ) :: rest -> make_transitions ( { Transition . start_time_in_seconds_since_epoch ; new_regime } :: acc ) rest in make_transitions [ ] raw_transitions in let default_local_time_type = match Array . find regimes ~ f ( : fun r -> not r . Regime . is_dst ) with | None -> regimes . ( 0 ) | Some ltt -> ltt in fun name ~ original_filename ~ digest -> { name ; original_filename = Some original_filename ; digest = Some digest ; transitions ; last_regime_index = Index . before_first_transition ; default_local_time_type ; leap_seconds } ; ; let input_leap_second_gen ~ input_leap_second ic = let time_in_seconds_since_epoch = input_leap_second ic in let seconds = input_long_as_int ic in { Leap_second . time_in_seconds_since_epoch ; seconds } ; ; let read_header ic = let magic = let buf = Bytes . create 4 in In_channel . really_input_exn ic ~ buf ~ pos : 0 ~ len : 4 ; Bytes . unsafe_to_string ~ no_mutation_while_string_reachable : buf in if not ( String . equal magic " TZif " ) then raise ( Invalid_file_format " magic characters TZif not present " ) ; let version = match In_channel . input_char ic with | Some ' \ 000 ' -> ` V1 | Some ' 2 ' -> ` V2 | Some ' 3 ' -> ` V3 | None -> raise ( Invalid_file_format " expected version , found nothing " ) | Some bad_version -> raise ( Invalid_file_format ( sprintf " version ( % c ) is invalid " bad_version ) ) in In_channel . really_input_exn ic ~ buf ( : Bytes . create 15 ) ~ pos : 0 ~ len : 15 ; version ; ; let input_tz_file_v1 ic = let input_leap_second = input_leap_second_gen ~ input_leap_second : input_long_as_int63 in input_tz_file_gen ~ input_transition : input_long_as_int63 ~ input_leap_second ic ; ; let input_tz_file_v2_or_v3 ~ version ic = let ( _ : string -> original_filename : string -> digest : Md5_lib . t -> t ) = input_tz_file_v1 ic in assert ( [ % compare . equal : [ ` V1 | ` V2 | ` V3 ] ] ( read_header ic ) version ) ; let input_leap_second = input_leap_second_gen ~ input_leap_second : input_long_long_as_int63 in input_tz_file_gen ~ input_transition : input_long_long_as_int63 ~ input_leap_second ic ; ; let input_tz_file ~ zonename ~ filename = try protectx ( In_channel . create filename ) ~ finally : In_channel . close ~ f ( : fun ic -> let make_zone = match read_header ic with | ` V1 -> input_tz_file_v1 ic | ( ` V2 | ` V3 ) as version -> input_tz_file_v2_or_v3 ~ version ic in let digest = Md5 . digest_file_blocking filename in let r = make_zone zonename ~ original_filename : filename ~ digest in r ) with | Invalid_file_format reason -> raise ( Invalid_file_format ( sprintf " % s - % s " filename reason ) ) ; ; end let of_utc_offset ~ hours : offset = assert ( offset >= - 24 && offset <= 24 ) ; let name = if offset = 0 then " UTC " else sprintf " UTC % s % d " ( if offset < 0 then " " - else " " ) + ( abs offset ) in let utc_offset_in_seconds = Int63 . of_int ( offset * 60 * 60 ) in { name ; original_filename = None ; digest = None ; transitions = [ ] || ; last_regime_index = Index . before_first_transition ; default_local_time_type = { Regime . utc_offset_in_seconds ; is_dst = false ; abbrv = name } ; leap_seconds = [ ] } ; ; end end end
let sexp_of_t t = Sexp . Atom t . name
let likely_machine_zones = ref [ " America / New_York " ; " Europe / London " ; " Asia / Hong_Kong " ; " America / Chicago " ] ; ;
let utc = of_utc_offset ~ hours : 0
let name zone = zone . name
let reset_transition_cache t = t . last_regime_index <- Index . before_first_transition
let get_regime_exn t index = if index < 0 then t . default_local_time_type else t . transitions . ( index ) . new_regime ; ;
module Mode = struct type t = | Absolute | Date_and_ofday end
let effective_start_time ~ mode ( x : Transition . t ) = let open Int63 . O in match ( mode : Mode . t ) with | Absolute -> x . start_time_in_seconds_since_epoch | Date_and_ofday -> x . start_time_in_seconds_since_epoch + x . new_regime . utc_offset_in_seconds ; ;
let index_lower_bound_contains_seconds_since_epoch t index ~ mode seconds = index < 0 || Int63 . ( >= ) seconds ( effective_start_time ~ mode t . transitions . ( index ) ) ; ;
let index_upper_bound_contains_seconds_since_epoch t index ~ mode seconds = index + 1 >= Array . length t . transitions || Int63 . ( < ) seconds ( effective_start_time ~ mode t . transitions . ( index + 1 ) ) ; ;
let binary_search_index_of_seconds_since_epoch t ~ mode seconds : Index . t = Array . binary_search_segmented t . transitions ` Last_on_left ~ segment_of ( : fun transition -> if Int63 . ( <= ) ( effective_start_time transition ~ mode ) seconds then ` Left else ` Right ) |> Option . value ~ default : Index . before_first_transition ; ;
let index_of_seconds_since_epoch t ~ mode seconds = let index = let index = t . last_regime_index in if not ( index_lower_bound_contains_seconds_since_epoch t index ~ mode seconds ) then ( let index = index - 1 in if not ( index_lower_bound_contains_seconds_since_epoch t index ~ mode seconds ) then binary_search_index_of_seconds_since_epoch t ~ mode seconds else index ) else if not ( index_upper_bound_contains_seconds_since_epoch t index ~ mode seconds ) then ( let index = index + 1 in if not ( index_upper_bound_contains_seconds_since_epoch t index ~ mode seconds ) then binary_search_index_of_seconds_since_epoch t ~ mode seconds else index ) else index in t . last_regime_index <- index ; index ; ;
module Time_in_seconds : sig include Zone_intf . Time_in_seconds module Span = struct type t = Int63 . t let of_int63_seconds = ident let to_int63_seconds_round_down_exn = ident end module Absolute = struct type t = Int63 . t let of_span_since_epoch = ident let to_span_since_epoch = ident end module Date_and_ofday = struct type t = Int63 . t let of_synthetic_span_since_epoch = ident let to_synthetic_span_since_epoch = ident end include Absolute end
let index t time = Time_in_seconds . to_span_since_epoch time |> Time_in_seconds . Span . to_int63_seconds_round_down_exn |> index_of_seconds_since_epoch t ~ mode : Absolute ; ;
let index_of_date_and_ofday t time = Time_in_seconds . Date_and_ofday . to_synthetic_span_since_epoch time |> Time_in_seconds . Span . to_int63_seconds_round_down_exn |> index_of_seconds_since_epoch t ~ mode : Date_and_ofday ; ;
let index_has_prev_clock_shift t index = index >= 0 && index < Array . length t . transitions
let index_has_next_clock_shift t index = index_has_prev_clock_shift t ( index + 1 )
let index_prev_clock_shift_time_exn t index = let transition = t . transitions . ( index ) in transition . start_time_in_seconds_since_epoch |> Time_in_seconds . Span . of_int63_seconds |> Time_in_seconds . of_span_since_epoch ; ;
let index_next_clock_shift_time_exn t index = index_prev_clock_shift_time_exn t ( index + 1 ) ; ;
let index_prev_clock_shift_amount_exn t index = let transition = t . transitions . ( index ) in let after = transition . new_regime in let before = if index = 0 then t . default_local_time_type else t . transitions . ( index - 1 ) . new_regime in Int63 . ( - ) after . utc_offset_in_seconds before . utc_offset_in_seconds |> Time_in_seconds . Span . of_int63_seconds ; ;
let index_next_clock_shift_amount_exn t index = index_prev_clock_shift_amount_exn t ( index + 1 ) ; ;
let index_abbreviation_exn t index = let regime = get_regime_exn t index in regime . abbrv ; ;
let index_offset_from_utc_exn t index = let regime = get_regime_exn t index in Time_in_seconds . Span . of_int63_seconds regime . utc_offset_in_seconds ; ;
module type Time_in_seconds = sig module Span : sig type t val of_int63_seconds : Int63 . t -> t val to_int63_seconds_round_down_exn : t -> Int63 . t end module Date_and_ofday : sig type t val of_synthetic_span_since_epoch : Span . t -> t val to_synthetic_span_since_epoch : t -> Span . t end type t val of_span_since_epoch : Span . t -> t val to_span_since_epoch : t -> Span . t end
module type S = sig type t [ @@ deriving sexp_of , compare ] val input_tz_file : zonename : string -> filename : string -> t val likely_machine_zones : string list ref val of_utc_offset : hours : int -> t val utc : t val name : t -> string val original_filename : t -> string option val digest : t -> Md5 . t option module Time_in_seconds : Time_in_seconds val reset_transition_cache : t -> unit module Index : sig type t [ @@ immediate ] val next : t -> t val prev : t -> t end val index : t -> Time_in_seconds . t -> Index . t val index_of_date_and_ofday : t -> Time_in_seconds . Date_and_ofday . t -> Index . t val index_offset_from_utc_exn : t -> Index . t -> Time_in_seconds . Span . t val index_abbreviation_exn : t -> Index . t -> string val index_has_prev_clock_shift : t -> Index . t -> bool val index_prev_clock_shift_time_exn : t -> Index . t -> Time_in_seconds . t val index_prev_clock_shift_amount_exn : t -> Index . t -> Time_in_seconds . Span . t val index_has_next_clock_shift : t -> Index . t -> bool val index_next_clock_shift_time_exn : t -> Index . t -> Time_in_seconds . t val index_next_clock_shift_amount_exn : t -> Index . t -> Time_in_seconds . Span . t end
module type S_stable = sig type t module Full_data : sig module V1 : Stable_module_types . S0_without_comparator with type t = t end end
module type Zone = sig module type S = S module type S_stable = S_stable include S module Stable : S_stable with type t := t end
let month_limits = Map . Poly . of_alist_exn [ 1 , 31 ; 2 , 28 ; 3 , 31 ; 4 , 30 ; 5 , 31 ; 6 , 30 ; 7 , 31 ; 8 , 31 ; 9 , 30 ; 10 , 31 ; 11 , 30 ; 12 , 31 ]
let random_time state = let year = 1970 + Random . State . int state 67 in let month = 1 + ( Random . State . int state 12 ) in let day = 1 + ( Random . State . int state ( Map . find_exn month_limits month ) ) in let hour = Random . State . int state 12 + 8 in let min = Random . State . int state 60 in let sec = Random . State . int state 60 in let ms = Random . State . int state 1_000 in let mic = Random . State . int state 1_000 in ( year , month , day , hour , min , sec , ms , mic ) ; ;
let random_time_str state = let year , month , day , hour , min , sec , ms , _mic = random_time state in sprintf " % d . -% 2d . -% 2d . % 2d . :% 2d . :% 2d . . % 3d000 " year month day hour min sec ms ; ;
let random_tm state = let ( year , month , day , hour , min , sec , _ , _ ) = random_time state in { Unix . tm_sec = sec ; tm_min = min ; tm_hour = hour ; tm_mday = day ; tm_mon = month ; tm_year = year - 1900 ; tm_wday = 0 ; tm_yday = 0 ; tm_isdst = false ; }
let zone_tests = ref [ ]
let add name test = zone_tests := ( name >:: test ) :: ! zone_tests
let add_random_string_round_trip_test state s1 = let pos_neg = if Random . State . bool state then " " + else " " - in let distance = Int . to_string ( Random . State . int state 10 + 1 ) in let s2 = String . concat [ s1 ; pos_neg ; distance ; " : 00 " ] in let zone = ( force Time . Zone . local ) in let s1 = let t = Time . of_string s1 in let utc_epoch = Time . Zone . date_and_ofday_of_absolute_time zone t |> Time . Zone . absolute_time_of_date_and_ofday Time . Zone . utc in let f = Time . diff utc_epoch t |> Time . Span . to_sec |> Float . to_int in s1 ^ ( if f = 0 then " Z " else Printf . sprintf " %+ 03d : 00 " ( f / 3600 ) ) in add ( " roundtrip string " ^ s1 ) ( fun ( ) -> " s1 " @? ( s1 = ( Time . to_string_abs ( Time . of_string s1 ) ~ zone ) ) ; " s2 - time " @? ( let s2_time1 = Time . of_string s2 in let s2_time2 = Time . of_string ( Time . to_string_abs s2_time1 ~ zone ) in Time . ( . ) = s2_time1 s2_time2 ) )
let add_random_string_round_trip_tests state = for _ = 1 to 100 do add_random_string_round_trip_test state ( random_time_str state ) done ; ; ;
let add_roundtrip_conversion_test state ( zone_name , ( zone : Time . Zone . t ) ) = add ( " roundtrip conversion " ^ zone_name ) ( fun ( ) -> let tm = random_tm state in let unix_time = 1664476678 . 000 in let time = Time . of_span_since_epoch ( Time . Span . of_sec unix_time ) in let ( zone_date , zone_ofday ) = let date , ofday = Time . to_date_ofday ~ zone ( : force Time . Zone . local ) time in Time . convert ~ from_tz ( : force Time . Zone . local ) ~ to_tz : zone date ofday in let round_trip_time = let round_date , round_ofday = Time . convert ~ from_tz : zone ~ to_tz ( : force Time . Zone . local ) zone_date zone_ofday in Time . of_date_ofday ~ zone ( : force Time . Zone . local ) round_date round_ofday in " time " @? ( if time = round_trip_time then true else begin failwith ( String . concat [ sprintf " tm : % s \ n " ( Sexp . to_string_hum ( Unix . sexp_of_tm tm ) ) ; sprintf " unix_time : . % 20f \ n " unix_time ; sprintf " our_time : . % 20f \ n " ( Time . to_span_since_epoch time |> Time . Span . to_sec ) ; sprintf " date , ofday : % s , % s \ n " ( Date . to_string zone_date ) ( Time . Ofday . to_string zone_ofday ) ; sprintf " round_trip : . % 20f \ n " ( Time . to_span_since_epoch round_trip_time |> Time . Span . to_sec ) ] ) end ) )
module Localtime_test_data = struct type t = { zone_name : string ; unix_time : float ; localtime_date_string : string ; localtime_ofday_string : string ; our_date_string : string ; our_ofday_string : string ; } [ @@ deriving sexp ] end
let add_random_localtime_tests state = List . iter ( Time . Zone . initialized_zones ( ) ) ~ f ( : fun ( zone_name , zone ) -> add ( " localtime " ^ zone_name ) ( fun ( ) -> let tm = random_tm state in let tm = Unix . gmtime ( Unix . timegm tm ) in Unix . putenv ~ key " : TZ " ~ data : zone_name ; ignore ( Unix . localtime 1000 . ) ; let unix_time , _ = Unix . mktime tm in let localtime = Unix . localtime unix_time in let localtime_date_string = Unix . strftime localtime " % Y -% m -% d " in let localtime_ofday_string = Unix . strftime localtime " % H :% M :% S . 000000 " in Unix . unsetenv ( " TZ " ) ; ignore ( Unix . localtime 1000 . ) ; let our_date , our_ofday = Time . to_date_ofday ( Time . of_span_since_epoch ( Time . Span . of_sec unix_time ) ) ~ zone in let test_data = { Localtime_test_data . zone_name ; unix_time ; our_date_string = Date . to_string our_date ; our_ofday_string = Time . Ofday . to_string our_ofday ; localtime_date_string ; localtime_ofday_string ; } in " date " @? ( if Localtime_test_data . ( test_data . localtime_date_string = test_data . our_date_string ) then true else failwith ( Sexp . to_string ( Localtime_test_data . sexp_of_t test_data ) ) ) ; " ofday " @? ( if Localtime_test_data . ( test_data . localtime_ofday_string = test_data . our_ofday_string ) then true else failwith ( Sexp . to_string ( Localtime_test_data . sexp_of_t test_data ) ) ) ) ) ; ;
let add_roundtrip_conversion_tests state = List . iter ( Time . Zone . initialized_zones ( ) ) ~ f ( : add_roundtrip_conversion_test state ) ; ;
let add_randomized_tests ( ) = let state = Random . State . make [ | 1 ; 2 ; 3 ; 4 ] | in add_random_string_round_trip_tests state ; add_random_localtime_tests state ; add_roundtrip_conversion_tests state ; ;
let ( ) = add_randomized_tests ( ) ; ; ;
let test = " zone " >::: ! zone_tests
type zenv = { env : Deftypes . tentry Env . t ; ren : Zident . t Env . t ; size : int }
let zempty = { env = Env . empty ; ren = Env . empty ; size = 0 }
let zero_from_env env = let select key { t_sort = s } = match s with | Smem { m_kind = Some ( Zero ) } -> true | _ -> false in Env . partition select env
let vars_of_env vars env = List . filter ( fun { vardec_name = x } -> Env . mem x env ) vars
let make env2 env1 = let one key _ ( l , acc ) = match l with | [ ] -> assert false | ( key ' , _ ) :: l -> l , Env . add key key ' acc in let l1 = Env . bindings env1 in let _ , ren = Env . fold one env2 ( l1 , Env . empty ) in ren
let compose r2_by_1 r2 = Env . map ( fun n2 -> try Env . find n2 r2_by_1 with Not_found -> assert false ) r2
let parallel { env = env1 ; ren = r1 ; size = s1 } { env = env2 ; ren = r2 ; size = s2 } = { env = Env . append env1 env2 ; ren = Env . append r1 r2 ; size = s1 + s2 }
let sharp { env = env1 ; ren = r1 ; size = s1 } { env = env2 ; ren = r2 ; size = s2 } = if s1 >= s2 then let r2_by_1 = make env2 env1 in let r = Env . append r1 ( Env . append r2_by_1 ( compose r2_by_1 r2 ) ) in { env = env1 ; ren = r ; size = s1 } else let r1_by_2 = make env1 env2 in let r = Env . append r2 ( Env . append r1_by_2 ( compose r1_by_2 r1 ) ) in { env = env2 ; ren = r ; size = s2 }
let rec equation ( { eq_desc = desc } as eq ) = match desc with | EQeq _ | EQpluseq _ | EQder _ | EQinit _ -> eq , zempty | EQmatch ( total , e , m_h_list ) -> let m_h_list , zenv = Zmisc . map_fold ( fun acc ( { m_body = b } as m_h ) -> { eq with eq_desc = EQmatch ( total , e , m_h_list ) } , zenv | EQreset ( eq_list , e ) -> let eq_list , zenv = equation_list eq_list in { eq with eq_desc = EQreset ( eq_list , e ) } , zenv | EQand ( and_eq_list ) -> let and_eq_list , zenv = equation_list and_eq_list in { eq with eq_desc = EQand ( and_eq_list ) } , zenv | EQbefore ( before_eq_list ) -> let before_eq_list , zenv = equation_list before_eq_list in { eq with eq_desc = EQbefore ( before_eq_list ) } , zenv | EQforall _ -> eq , zempty | EQblock _ | EQpresent _ | EQautomaton _ | EQnext _ | EQemit _ -> Zmisc . map_fold ( fun acc eq -> let eq , zenv = equation eq in let zero_env , b_env = zero_from_env b_env in let eq_list , zenv = equation_list eq_list in { b with b_vars = vars_of_env vars b_env ; b_env = b_env ; b_body = eq_list } , parallel { env = zero_env ; ren = Env . empty ; size = Env . cardinal zero_env } zenv
let rec rename_expression ren ( { e_desc = desc } as e ) = match desc with | Econst _ | Econstr0 _ | Eglobal _ -> e | Elocal ( x ) -> { e with e_desc = Elocal ( apply x ren ) } | Elast ( x ) -> { e with e_desc = Elast ( apply x ren ) } | Etuple ( e_list ) -> { e with e_desc = Etuple ( List . map ( rename_expression ren ) e_list ) } | Econstr1 ( c , e_list ) -> { e with e_desc = Econstr1 ( c , List . map ( rename_expression ren ) e_list ) } | Erecord ( n_e_list ) -> { e with e_desc = | Erecord_access ( e_record , ln ) -> { e with e_desc = Erecord_access ( rename_expression ren e_record , ln ) } | Erecord_with ( e_record , n_e_list ) -> { e with e_desc = | Eop ( op , e_list ) -> { e with e_desc = Eop ( op , List . map ( rename_expression ren ) e_list ) } | Eapp ( app , e_op , e_list ) -> let e_op = rename_expression ren e_op in let e_list = List . map ( rename_expression ren ) e_list in { e with e_desc = Eapp ( app , e_op , e_list ) } | Etypeconstraint ( e1 , ty ) -> { e with e_desc = Etypeconstraint ( rename_expression ren e1 , ty ) } | Eseq ( e1 , e2 ) -> { e with e_desc = Eseq ( rename_expression ren e1 , rename_expression ren e2 ) } | Eperiod _ | Epresent _ | Ematch _ | Elet _ | Eblock _ -> assert false let eq_list = rename_equation_list ren eq_list in { l with l_eq = eq_list } let desc = match desc with | EQeq ( { p_desc = Evarpat ( x ) } as p , e ) -> EQeq ( { p with p_desc = Evarpat ( apply x ren ) } , rename_expression ren e ) | EQeq ( p , e ) -> EQeq ( p , rename_expression ren e ) | EQpluseq ( x , e ) -> EQpluseq ( apply x ren , rename_expression ren e ) | EQinit ( x , e0 ) -> EQinit ( apply x ren , rename_expression ren e0 ) | EQmatch ( total , e , m_h_list ) -> let m_h_list = EQmatch ( total , rename_expression ren e , m_h_list ) | EQder ( x , e , None , [ ] ) -> EQder ( x , rename_expression ren e , None , [ ] ) | EQreset ( res_eq_list , e ) -> let e = rename_expression ren e in let res_eq_list = rename_equation_list ren res_eq_list in EQreset ( res_eq_list , e ) | EQand ( and_eq_list ) -> EQand ( rename_equation_list ren and_eq_list ) | EQbefore ( before_eq_list ) -> EQbefore ( rename_equation_list ren before_eq_list ) | EQforall ( { for_index = i_list ; for_init = init_list ; let index ( { desc = desc } as ind ) = let init ( { desc = desc } as ini ) = let i_list = List . map index i_list in let init_list = List . map init init_list in let b_eq_list = rename_block ren b_eq_list in EQforall { body with for_index = i_list ; for_init = init_list ; | EQblock _ | EQautomaton _ | EQpresent _ | EQemit _ | EQder _ | EQnext _ -> assert false in { eq with eq_desc = desc } let eq_list = rename_equation_list ren eq_list in { b with b_body = eq_list } try Env . find x ren with | Not_found -> x
let local ( { l_eq = eq_list ; l_env = l_env } as l ) = let eq_list , { env = env ; ren = ren } = equation_list eq_list in let eq_list = rename_equation_list ren eq_list in { l with l_eq = eq_list ; l_env = Env . append env l_env }
let expression ( { e_desc = desc } as e ) = let desc = match desc with | Elet ( l , e ) -> Elet ( local l , e ) | _ -> desc in { e with e_desc = desc }
let implementation impl = match impl . desc with | Econstdecl ( n , is_static , e ) -> { impl with desc = Econstdecl ( n , is_static , expression e ) } | Efundecl ( n , ( { f_body = e } as body ) ) -> { impl with desc = Efundecl ( n , { body with f_body = expression e } ) } | _ -> impl
let implementation_list impl_list = Zmisc . iter implementation impl_list
type kind = | S | AS | A | C | AD | D | P
type qualident = { qual : name ; id : name }
type longname = | Name of name | Modname of qualident
type ' a localized = { desc : ' a ; loc : Zlocation . location }
type type_expression = type_expression_desc localized | Etypevar of name | Etypeconstr of longname * type_expression list | Etypetuple of type_expression list | Etypevec of type_expression * size | Etypefun of kind * string option * type_expression * type_expression | Sconst of int | Sname of longname | Sop of size_op * size * size
type interface = interface_desc localized | Einter_open of name | Einter_typedecl of name * name list * type_decl | Einter_constdecl of name * type_expression | Eabstract_type | Eabbrev of type_expression | Evariant_type of constr_decl list | Erecord_type of ( name * type_expression ) list | Econstr0decl of name | Econstr1decl of name * type_expression list | Eopen of name | Etypedecl of name * name list * type_decl | Econstdecl of name * is_static * exp | Efundecl of name * funexp { f_kind : kind ; f_atomic : is_atomic ; f_args : pattern list ; f_body : exp ; f_loc : location } | Evar of longname | Econst of immediate | Econstr0 of constr | Econstr1 of constr * exp list | Elast of name | Eapp of app * exp * exp list | Eop of op * exp list | Etuple of exp list | Erecord_access of exp * longname | Erecord of ( longname * exp ) list | Erecord_with of exp * ( longname * exp ) list | Etypeconstraint of exp * type_expression | Elet of is_rec * eq list * exp | Eseq of exp * exp | Eperiod of period | Ematch of exp * exp match_handler list | Epresent of exp present_handler list * exp default option | Eautomaton of exp state_handler list * state_exp option | Ereset of exp * exp | Eblock of eq list block * exp | Init of ' a | Default of ' a | Efby | Eunarypre | Eifthenelse | Eminusgreater | Eup | Einitial | Edisc | Etest | Eaccess | Eupdate | Eslice of size * size | Econcat | Eatomic | Eint of int | Efloat of float | Ebool of bool | Echar of char | Estring of string | Evoid | Cimmediate of immediate | Cglobal of longname { p_phase : exp option ; p_period : exp } | Etuplepat of pattern list | Evarpat of name | Ewildpat | Econstpat of immediate | Econstr0pat of longname | Econstr1pat of longname * pattern list | Ealiaspat of pattern * name | Eorpat of pattern * pattern | Erecordpat of ( longname * pattern ) list | Etypeconstraintpat of pattern * type_expression | EQeq of pattern * exp | EQder of name * exp * exp option * exp present_handler list | EQinit of name * exp | EQnext of name * exp * exp option | EQemit of name * exp option | EQpluseq of name * exp | EQautomaton of eq list state_handler list * state_exp option | EQpresent of eq list block present_handler list * eq list block option | EQmatch of exp * eq list block match_handler list | EQifthenelse of exp * eq list block * eq list block option | EQreset of eq list * exp | EQand of eq list | EQbefore of eq list | EQblock of eq list block | EQforall of forall_handler { b_vars : vardec list ; b_locals : local list ; b_body : ' a } { vardec_name : name ; vardec_default : constant default option ; vardec_combine : longname option ; } | Estate0pat of name | Estate1pat of name * name list | Estate0 of name | Estate1 of name * exp list { e_cond : scondpat ; e_reset : bool ; e_block : eq list block option ; e_next_state : state_exp ; } | Econdand of scondpat * scondpat | Econdor of scondpat * scondpat | Econdexp of exp | Econdon of scondpat * exp | Econdpat of exp * pattern { m_pat : pattern ; m_body : ' a ; } { p_cond : scondpat ; p_body : ' a ; } { s_state : statepat ; s_block : ' a block ; s_until : escape list ; s_unless : escape list } { for_indexes : indexes_desc localized list ; for_init : init_desc localized list ; for_body : eq list block } | Einput of name * exp | Eoutput of name * name | Eindex of name * exp * exp | Einit_last of name * exp
let remove_trailing_null s = let n = String . length s in let i = ref ( n - 1 ) in while ! i >= 0 && s . [ ! i ] = ' \ 000 ' do i := ! i - 1 done ; String . sub s 0 ( ! i + 1 )
let serialize z = let n = if Z . ( lt z zero ) then Z . ( neg ( add ( add z z ) one ) ) else Z . ( add z z ) in n |> Z . to_bits |> remove_trailing_null
let deserialize z = let n = Z . of_bits z in let z = Z . shift_right_trunc n 1 in if Z . ( n land one = zero ) then z else Z . neg z
let leq a b = Z . compare a b <= 0
let geq a b = Z . compare a b >= 0
let lt a b = Z . compare a b < 0
let gt a b = Z . compare a b > 0
let ( < ) = lt