text
stringlengths 12
786k
|
---|
let challenge_polynomial ~ one ~ add ~ mul chals = let ( + ) = add and ( * ) = mul in stage ( fun pt -> let k = Array . length chals in let pow_two_pows = let res = Array . init k ~ f ( : fun _ -> pt ) pt in for i = 1 to k - 1 do let y = res ( . i - 1 ) 1 in res ( . i ) i <- y * y done ; res in let prod f = let r = ref ( f 0 ) 0 in for i = 1 to k - 1 do r := f i * ! r done ; ! r in prod ( fun i -> one + ( chals ( . i ) i * pow_two_pows ( . k - 1 - i ) i ) i ) i ) |
module Make ( Inputs : Inputs with type Impl . field = Tock . Field . t and type Impl . Bigint . t = Tock . Bigint . R . t and type Inner_curve . Constant . Scalar . t = Tick . Field . t ) t = struct open Inputs open Impl module Other_field = struct module Packed = struct module Constant = Other_field type t = Impls . Wrap . Other_field . t let typ = Impls . Wrap . Other_field . typ let to_bits_unsafe ( x : t ) t = Wrap_main_inputs . Unsafe . unpack_unboolean x let absorb_shifted sponge ( x : t Shifted_value . Type1 . t ) t = match x with Shifted_value x -> Sponge . absorb sponge x end module With_top_bit0 = struct module Constant = Other_field type t = Impls . Wrap . Other_field . t let typ = Impls . Wrap . Other_field . typ_unchecked let absorb_shifted sponge ( x : t Shifted_value . Type1 . t ) t = match x with Shifted_value x -> Sponge . absorb sponge x end end let print_g lab ( x , y ) y = if debug then as_prover As_prover ( . fun ( ) -> printf " !% s : { % sexp : Backend . Tock . Field . t } t , { % sexp : Backend . Tock . Field . t } t \ n \ " %! lab ( read_var x ) x ( read_var y ) y ) y let print_w lab gs = if debug then Array . iteri gs ~ f ( : fun i ( fin , g ) g -> as_prover As_prover ( . fun ( ) -> printf " fin =% b " %! ( read Boolean . typ fin ) fin ) fin ; ksprintf print_g " % s [ s % d ] d " lab i g ) let print_chal lab x = if debug then as_prover As_prover ( . fun ( ) -> printf " in - snark % s " :%! lab ; Field . Constant . print ( Field . Constant . project ( List . map ~ f ( : read Boolean . typ ) typ x ) x ) x ; printf " \ n ) " %! let print_bool lab x = if debug then as_prover ( fun ( ) -> printf " % s : % b \ n " %! lab ( As_prover . read Boolean . typ x ) x ) module Challenge = Challenge . Make ( Impl ) Impl module Digest = Digest . Make ( Impl ) Impl module Scalar_challenge = SC . Make ( Impl ) Impl ( Inner_curve ) Inner_curve ( Challenge ) Challenge ( Endo . Wrap_inner_curve ) Wrap_inner_curve module Ops = Plonk_curve_ops . Make ( Impl ) Impl ( Inner_curve ) Inner_curve let product m f = List . reduce_exn ( List . init m ~ f ) f ~ f : Field ( . * ) let absorb sponge ty t = absorb ~ mask_g1_opt ( : fun ( ) -> assert false ) false ~ absorb_field ( : Sponge . absorb sponge ) sponge ~ g1_to_field_elements : Inner_curve . to_field_elements ~ absorb_scalar ( : Sponge . absorb sponge ) sponge ty t let scalar_to_field s = SC . to_field_checked ( module Impl ) Impl s ~ endo : Endo . Step_inner_curve . scalar let lowest_128_bits ~ constrain_low_bits x = let assert_128_bits a = ignore ( scalar_to_field ( SC . SC . create a ) a : Field . t ) t in Util . lowest_128_bits ~ constrain_low_bits ~ assert_128_bits ( module Impl ) Impl x let squeeze_challenge sponge : Field . t = lowest_128_bits ~ constrain_low_bits : true ( Sponge . squeeze sponge ) sponge let squeeze_scalar sponge : Field . t SC . SC . t = SC . SC . create ( lowest_128_bits ~ constrain_low_bits : false ( Sponge . squeeze sponge ) sponge ) sponge let bullet_reduce sponge gammas = let absorb t = absorb sponge t in let prechallenges = Array . map gammas ~ f ( : fun gammas_i -> absorb ( PC :: PC ) PC gammas_i ; squeeze_scalar sponge ) in let term_and_challenge ( l , r ) r pre = let left_term = Scalar_challenge . endo_inv l pre in let right_term = Scalar_challenge . endo r pre in ( Ops . add_fast left_term right_term , { Bulletproof_challenge . prechallenge = pre } ) in let terms , challenges = Array . map2_exn gammas prechallenges ~ f : term_and_challenge |> Array . unzip in ( Array . reduce_exn terms ~ f : Ops . add_fast , challenges ) challenges let equal_g g1 g2 = List . map2_exn ~ f : Field . equal ( Inner_curve . to_field_elements g1 ) g1 ( Inner_curve . to_field_elements g2 ) g2 |> Boolean . all module One_hot_vector = One_hot_vector . Make ( Impl ) Impl type ' a index ' = ' a Plonk_verification_key_evals . t type ' a index = ' a Plonk_verification_key_evals . t let choose_key : type n . n One_hot_vector . t -> ( Inner_curve . t index ' , n ) n Vector . t -> Inner_curve . t index ' = let open Tuple_lib in let map = Plonk_verification_key_evals . map in let map2 = Plonk_verification_key_evals . map2 in fun bs keys -> let open Field in Vector . map2 ( bs :> ( Boolean . var , n ) n Vector . t ) t keys ~ f ( : fun b key -> map key ~ f ( : fun g -> Double . map g ~ f ( ( : * ) ( b :> t ) t ) t ) t ) t |> Vector . reduce_exn ~ f ( : map2 ~ f ( : Double . map2 ~ f ( : + ) ) ) |> map ~ f ( : fun g -> Double . map ~ f ( : Util . seal ( module Impl ) Impl ) Impl g ) g let lagrange ( type n ) n ~ domain : ( ( which_branch : n One_hot_vector . t ) t , ( domains : ( Domains . t , n ) n Vector . t ) t ) i = Vector . map domains ~ f ( : fun d -> let d = Precomputed . Lagrange_precomputations . index_of_domain_log2 ( Domain . log2_size d . h ) h in match Precomputed . Lagrange_precomputations . vesta ( . d ) d ( . i ) i with | [ | g ] | -> let g = Inner_curve . Constant . of_affine g in Inner_curve . constant g | _ -> assert false ) |> Vector . map2 ( which_branch :> ( Boolean . var , n ) n Vector . t ) t ~ f ( : fun b ( x , y ) y -> Field ( ( . b :> t ) t * x , ( b :> t ) t * y ) y ) y |> Vector . reduce_exn ~ f ( : Double . map2 ~ f : Field ( . + ) ) let lagrange_with_correction ( type n ) n ~ input_length ~ domain : ( ( which_branch : n One_hot_vector . t ) t , ( domains : ( Domains . t , n ) n Vector . t ) t ) i : Inner_curve . t Double . t = with_label __LOC__ ( fun ( ) -> let actual_shift = Ops . bits_per_chunk * Ops . chunks_needed ~ num_bits : input_length in let rec pow2pow x i = if i = 0 then x else pow2pow Inner_curve . Constant ( . x + x ) x ( i - 1 ) 1 in let base_and_correction ( h : Domain . t ) t = let d = Precomputed . Lagrange_precomputations . index_of_domain_log2 ( Domain . log2_size h ) h in match Precomputed . Lagrange_precomputations . vesta ( . d ) d ( . i ) i with | [ | g ] | -> let open Inner_curve . Constant in let g = of_affine g in ( Inner_curve . constant g , Inner_curve . constant ( negate ( pow2pow g actual_shift ) actual_shift ) actual_shift ) | xs -> failwithf " expected commitment to have length 1 . got % d " ( Array . length xs ) xs ( ) in match domains with | [ ] -> assert false | d :: ds -> if Vector . for_all ds ~ f ( : fun d ' -> Domain . equal d . h d ' . h ) h then base_and_correction d . h else Vector . map domains ~ f ( : fun ( ds : Domains . t ) t -> base_and_correction ds . h ) |> Vector . map2 ( which_branch :> ( Boolean . var , n ) n Vector . t ) t ~ f ( : fun b pr -> Double . map pr ~ f ( : fun ( x , y ) y -> Field ( ( . b :> t ) t * x , ( b :> t ) t * y ) y ) ) |> Vector . reduce_exn ~ f ( : Double . map2 ~ f ( : Double . map2 ~ f : Field ( . + ) ) ) |> Double . map ~ f ( : Double . map ~ f ( : Util . seal ( module Impl ) Impl ) Impl ) Impl ) let h_precomp = Lazy . map ~ f : Inner_curve . Scaling_precomputation . create Generators . h let group_map = let f = lazy ( let module M = Group_map . Bw19 . Make ( Field . Constant ) Constant ( Field ) Field ( struct let params = Group_map . Bw19 . Params . create ( module Field . Constant ) Constant { b = Inner_curve . Params . b } end ) end in let open M in Snarky_group_map . Checked . wrap ( module Impl ) Impl ~ potential_xs ~ y_squared ( : fun ~ x -> Field ( . ( x * x * x ) x + ( constant Inner_curve . Params . a * x ) x + constant Inner_curve . Params . b ) b ) |> unstage ) in fun x -> Lazy . force f x module Split_commitments = struct module Point = struct type t = [ ` Finite of Inner_curve . t | ` Maybe_finite of Boolean . var * Inner_curve . t ] let finite : t -> Boolean . var = function | ` Finite _ -> Boolean . true_ | ` Maybe_finite ( b , _ ) _ -> b let add ( p : t ) t ( q : Inner_curve . t ) t = match p with | ` Finite p -> Ops . add_fast p q | ` Maybe_finite ( finite , p ) p -> Inner_curve . if_ finite ~ then_ ( : Ops . add_fast p q ) q ~ else_ : q let underlying = function ` Finite p -> p | ` Maybe_finite ( _ , p ) p -> p end module Curve_opt = struct type t = { point : Inner_curve . t ; non_zero : Boolean . var } end let combine batch ~ xi without_bound with_bound = let { Curve_opt . non_zero ; point } = Pcs_batch . combine_split_commitments batch ~ scale_and_add ( : fun ( ~ acc : Curve_opt . t ) t ~ xi ( keep , ( p : Point . t ) t ) t -> let point = Inner_curve ( . if_ keep ~ then_ : ( if_ acc . non_zero ~ then_ ( : Point . add p ( Scalar_challenge . endo acc . point xi ) xi ) xi ~ else_ : ( Point . underlying p ) ) ~ else_ : acc . point ) point in let non_zero = Boolean ( . keep &&& Point . finite p ||| acc . non_zero ) non_zero in { Curve_opt . non_zero ; point } ) ~ xi ~ init ( : fun ( keep , p ) p -> { non_zero = Boolean ( . keep &&& Point . finite p ) p ; point = Point . underlying p } ) without_bound with_bound in Boolean . Assert . is_true non_zero ; point end let scale_fast = Ops . scale_fast let check_bulletproof ~ pcs_batch ( ~ sponge : Sponge . t ) t ( ~ xi : Scalar_challenge . t ) t ( ~ advice : Other_field . Packed . t Shifted_value . Type1 . t Types . Step . Bulletproof . Advice . t ) ~ polynomials ( : without_degree_bound , with_degree_bound ) with_degree_bound ~ openings_proof : ( { lr ; delta ; z_1 ; z_2 ; challenge_polynomial_commitment } : ( Inner_curve . t , Other_field . Packed . t Shifted_value . Type1 . t ) Openings . Bulletproof . t ) = with_label __LOC__ ( fun ( ) -> Other_field . Packed . absorb_shifted sponge advice . combined_inner_product ; let u = let t = Sponge . squeeze_field sponge in group_map t in let open Inner_curve in let combined_polynomial = Split_commitments . combine pcs_batch ~ xi without_degree_bound with_degree_bound in let scale_fast = scale_fast ~ num_bits : Other_field . Packed . Constant . size_in_bits in let lr_prod , challenges = bullet_reduce sponge lr in let p_prime = let uc = scale_fast u advice . combined_inner_product in combined_polynomial + uc in let q = p_prime + lr_prod in absorb sponge PC delta ; let c = squeeze_scalar sponge in let lhs = let cq = Scalar_challenge . endo q c in cq + delta in let rhs = let b_u = scale_fast u advice . b in let z_1_g_plus_b_u = scale_fast ( challenge_polynomial_commitment + b_u ) b_u z_1 in let z2_h = scale_fast ( Inner_curve . constant ( Lazy . force Generators . h ) h ) h z_2 in z_1_g_plus_b_u + z2_h in ( ` Success ( equal_g lhs rhs ) rhs , challenges ) challenges ) module Opt = struct include Opt_sponge . Make ( Impl ) Impl ( Wrap_main_inputs . Sponge . Permutation ) Permutation let challenge ( s : t ) t : Field . t = lowest_128_bits ( squeeze s ) s ~ constrain_low_bits : true let scalar_challenge ( s : t ) t : Scalar_challenge . t = SC . SC . create ( lowest_128_bits ( squeeze s ) s ~ constrain_low_bits : false ) false end let absorb sponge ty t = Util . absorb ~ absorb_field ( : Opt . absorb sponge ) sponge ~ g1_to_field_elements ( : fun ( b , ( x , y ) y ) y -> [ ( b , x ) x ; ( b , y ) y ] ) ~ absorb_scalar ( : fun x -> Opt . absorb sponge ( Boolean . true_ , x ) x ) x ~ mask_g1_opt ( : fun ( ( finite : Boolean . var ) var , ( x , y ) y ) y -> ( Boolean . true_ , Field ( ( . finite :> t ) t * x , ( finite :> t ) t * y ) y ) y ) ty t module Pseudo = Pseudo . Make ( Impl ) Impl let mask ( type n ) n ( lengths : ( int , n ) n Vector . t ) t ( choice : n One_hot_vector . t ) t : Boolean . var array = let max = Option . value_exn ( List . max_elt ~ compare : Int . compare ( Vector . to_list lengths ) lengths ) lengths in let length = Pseudo . choose ( choice , lengths ) lengths ~ f : Field . of_int in let ( T max ) max = Nat . of_int max in Vector . to_array ( ones_vector ( module Impl ) Impl ~ first_zero : length max ) max module Plonk = Types . Wrap . Proof_state . Deferred_values . Plonk let iter2 ~ chal ~ scalar_chal { Plonk . Minimal . alpha = alpha_0 ; beta = beta_0 ; gamma = gamma_0 ; zeta = zeta_0 } { Plonk . Minimal . alpha = alpha_1 ; beta = beta_1 ; gamma = gamma_1 ; zeta = zeta_1 } = chal beta_0 beta_1 ; chal gamma_0 gamma_1 ; scalar_chal alpha_0 alpha_1 ; scalar_chal zeta_0 zeta_1 let assert_eq_marlin ( m1 : ( _ , Field . t Import . Scalar_challenge . t ) t Plonk . Minimal . t ) t ( m2 : ( _ , Scalar_challenge . t ) t Plonk . Minimal . t ) t = iter2 m1 m2 ~ chal ( : fun c1 c2 -> Field . Assert . equal c1 c2 ) c2 ~ scalar_chal ( : fun ( { inner = t1 } : _ Import . Scalar_challenge . t ) t ( { inner = t2 } : Scalar_challenge . t ) t -> Field . Assert . equal t1 t2 ) let incrementally_verify_proof ( type b ) b ( module Max_proofs_verified : Nat . Add . Intf with type n = b ) b ~ step_widths ~ step_domains ~ verification_key ( : m : _ Plonk_verification_key_evals . t ) t ~ xi ~ sponge ( ~ public_input : [ ` Field of Field . t * Boolean . var | ` Packed_bits of Field . t * int ] array ) ( ~ sg_old : ( _ , Max_proofs_verified . n ) n Vector . t ) t ~ advice ( ~ messages : _ Messages . t ) t ~ which_branch ~ openings_proof ( ~ plonk : _ Types . Wrap . Proof_state . Deferred_values . Plonk . In_circuit . t ) t = let T = Max_proofs_verified . eq in let public_input = Array . concat_map public_input ~ f ( : function | ` Field ( x , b ) b -> [ | ( x , Field . size_in_bits ) size_in_bits ; ( ( b :> Field . t ) t , 1 ) 1 ] | | ` Packed_bits ( x , n ) n -> [ | ( x , n ) n ] | ) in let sg_old = with_label __LOC__ ( fun ( ) -> let actual_width = Pseudo . choose ( which_branch , step_widths ) step_widths ~ f : Field . of_int in Vector . map2 ( ones_vector ( module Impl ) Impl ~ first_zero : actual_width Max_proofs_verified . n ) sg_old ~ f ( : fun keep sg -> [ | ( keep , sg ) sg ] ) | ) in with_label __LOC__ ( fun ( ) -> let sample ( ) = Opt . challenge sponge in let sample_scalar ( ) : Scalar_challenge . t = Opt . scalar_challenge sponge in let open Plonk_types . Messages in let x_hat = with_label __LOC__ ( fun ( ) -> let domain = ( which_branch , step_domains ) step_domains in let terms = with_label __LOC__ ( fun ( ) -> Array . mapi public_input ~ f ( : fun i x -> match x with | b , 1 -> assert_ ( Constraint . boolean ( b :> Field . t ) t ) t ; ` Cond_add ( Boolean . Unsafe . of_cvar b , lagrange ~ domain i ) i | x , n -> ` Add_with_correction ( ( x , n ) n , lagrange_with_correction ~ input_length : n ~ domain i ) ) ) in let correction = with_label __LOC__ ( fun ( ) -> Array . reduce_exn ( Array . filter_map terms ~ f ( : function | ` Cond_add _ -> None | ` Add_with_correction ( _ , ( _ , corr ) corr ) corr -> Some corr ) ) ~ f : Ops . add_fast ) in with_label __LOC__ ( fun ( ) -> Array . foldi terms ~ init : correction ~ f ( : fun i acc term -> match term with | ` Cond_add ( b , g ) g -> with_label __LOC__ ( fun ( ) -> Inner_curve . if_ b ~ then_ ( : Ops . add_fast g acc ) acc ~ else_ : acc ) | ` Add_with_correction ( ( x , num_bits ) num_bits , ( g , _ ) _ ) _ -> Ops . add_fast acc ( Ops . scale_fast2 ' ( module Other_field . With_top_bit0 ) With_top_bit0 g x ~ num_bits ) ) ) ) |> Inner_curve . negate in let without = Type . Without_degree_bound in let absorb_g gs = absorb sponge without ( Array . map gs ~ f ( : fun g -> ( Boolean . true_ , g ) g ) g ) g in absorb sponge PC ( Boolean . true_ , x_hat ) x_hat ; let w_comm = messages . w_comm in Vector . iter ~ f : absorb_g w_comm ; let beta = sample ( ) in let gamma = sample ( ) in let z_comm = messages . z_comm in absorb_g z_comm ; let alpha = sample_scalar ( ) in let t_comm : ( Inputs . Impl . Field . t * Inputs . Impl . Field . t ) t Pickles_types__Plonk_types . Poly_comm . Without_degree_bound . t = messages . t_comm in absorb_g t_comm ; let zeta = sample_scalar ( ) in let sponge = match sponge with | { state ; sponge_state ; params } -> ( match sponge_state with | Squeezed n -> S . make ~ state ~ sponge_state ( : Squeezed n ) n ~ params | _ -> assert false ) in let sponge_before_evaluations = Sponge . copy sponge in let sponge_digest_before_evaluations = Sponge . squeeze_field sponge in let sigma_comm_init , [ _ ] = Vector . split m . sigma_comm ( snd ( Permuts_minus_1 . add Nat . N1 . n ) n ) n in let scale_fast = scale_fast ~ num_bits : Other_field . Packed . Constant . size_in_bits in let ft_comm = with_label __LOC__ ( fun ( ) -> Common . ft_comm ~ add : Ops . add_fast ~ scale : scale_fast ~ negate : Inner_curve . negate ~ endoscale : Scalar_challenge . endo ~ verification_key : m ~ plonk ~ alpha ~ t_comm ) in let bulletproof_challenges = let num_commitments_without_degree_bound = Nat . N26 . n in let without_degree_bound = Vector . append sg_old ( [ | x_hat ] | :: [ | ft_comm ] | :: z_comm :: [ | m . generic_comm ] | :: [ | m . psm_comm ] | :: Vector . append w_comm ( Vector . map sigma_comm_init ~ f ( : fun g -> [ | g ] ) ) | ( snd ( Columns . add Permuts_minus_1 . n ) n ) n |> Vector . map ~ f ( : Array . map ~ f ( : fun g -> ( Boolean . true_ , g ) g ) g ) g ) ( snd ( Max_proofs_verified . add num_commitments_without_degree_bound ) num_commitments_without_degree_bound ) in check_bulletproof ~ pcs_batch : ( Common . dlog_pcs_batch ( Max_proofs_verified . add num_commitments_without_degree_bound ) num_commitments_without_degree_bound ) ~ sponge : sponge_before_evaluations ~ xi ~ advice ~ openings_proof ~ polynomials : ( Vector . map without_degree_bound ~ f ( : Array . map ~ f ( : fun ( keep , x ) x -> ( keep , ` Finite x ) x ) x ) x , [ ] ) in assert_eq_marlin { alpha = plonk . alpha ; beta = plonk . beta ; gamma = plonk . gamma ; zeta = plonk . zeta } { alpha ; beta ; gamma ; zeta } ; ( sponge_digest_before_evaluations , bulletproof_challenges ) bulletproof_challenges ) module Split_evaluations = struct let combine_split_evaluations ' s = Pcs_batch . combine_split_evaluations s ~ mul ( : fun ( keep , x ) x ( y : Field . t ) t -> ( keep , Field ( . y * x ) x ) x ) x ~ mul_and_add ( : fun ~ acc ~ xi ( keep , fx ) fx -> Field . if_ keep ~ then_ : Field ( . fx + ( xi * acc ) acc ) acc ~ else_ : acc ) ~ init ( : fun ( _ , fx ) fx -> fx ) fx ~ shifted_pow : ( Pseudo . Degree_bound . shifted_pow ~ crs_max_degree : Common . Max_degree . wrap ) end let mask_evals ( type n ) n ( ~ lengths : ( int , n ) n Vector . t Evals . t ) t ( choice : n One_hot_vector . t ) t ( e : Field . t array Evals . t ) t : ( Boolean . var * Field . t ) t array Evals . t = Evals . map2 lengths e ~ f ( : fun lengths e -> Array . zip_exn ( mask lengths choice ) choice e ) let combined_evaluation ( type b b_plus_26 ) b_plus_26 b_plus_26 ~ xi ~ evaluation_point ( ( without_degree_bound : ( _ , b_plus_26 ) b_plus_26 Vector . t ) t , with_degree_bound ) with_degree_bound ~ max_quot_size = let open Field in with_label __LOC__ ( fun ( ) -> Pcs_batch . combine_split_evaluations ~ mul ~ last : Array . last ~ mul_and_add ( : fun ~ acc ~ xi fx -> fx + ( xi * acc ) acc ) acc ~ shifted_pow : ( Pseudo . Degree_bound . shifted_pow ~ crs_max_degree : Common . Max_degree . wrap ) ~ init : Fn . id ~ evaluation_point ~ xi ( Common . dlog_pcs_batch b_plus_26 ) b_plus_26 without_degree_bound with_degree_bound ) let compute_challenges ~ scalar chals = Vector . map chals ~ f ( : fun { Bulletproof_challenge . prechallenge } -> scalar prechallenge ) let challenge_polynomial = Field ( . challenge_polynomial ~ add ~ mul ~ one ) one let pow2pow ( pt : Field . t ) t ( n : int ) int : Field . t = with_label __LOC__ ( fun ( ) -> let rec go acc i = if i = 0 then acc else go ( Field . square acc ) acc ( i - 1 ) 1 in go pt n ) let actual_evaluation ( e : Field . t array ) array ( ~ pt_to_n : Field . t ) t : Field . t = with_label __LOC__ ( fun ( ) -> match List . rev ( Array . to_list e ) e with | e :: es -> List . fold ~ init : e es ~ f ( : fun acc y -> let acc ' = exists Field . typ ~ compute ( : fun ( ) -> As_prover . read_var Field ( . y + ( pt_to_n * acc ) acc ) acc ) in let pt_n_acc = Field ( . pt_to_n * acc ) acc in let open Kimchi_backend_common . Plonk_constraint_system . Plonk_constraint in let open Field . Constant in assert_ [ { annotation = None ; basic = T ( Basic { l = ( one , y ) y ; r = ( one , pt_n_acc ) pt_n_acc ; o = ( negate one , acc ' ) acc ' ; m = zero ; c = zero } ) } ] ; acc ' ) | [ ] -> failwith " empty list " ) let shift1 = Shifted_value . Type1 . Shift ( . map ~ f : Field . constant ( create ( module Field . Constant ) Constant ) Constant ) Constant let shift2 = Shifted_value . Type2 . Shift ( . map ~ f : Field . constant ( create ( module Field . Constant ) Constant ) Constant ) Constant let % test_unit " endo scalar " = SC . test ( module Impl ) Impl ~ endo : Endo . Step_inner_curve . scalar let map_plonk_to_field plonk = Types . Step . Proof_state . Deferred_values . Plonk . In_circuit . map_challenges ~ f ( : Util . seal ( module Impl ) Impl ) Impl ~ scalar : scalar_to_field plonk |> Types . Step . Proof_state . Deferred_values . Plonk . In_circuit . map_fields ~ f ( : Shifted_value . Type2 . map ~ f ( : Util . seal ( module Impl ) Impl ) Impl ) Impl module Plonk_checks = struct include Plonk_checks include Plonk_checks . Make ( Shifted_value . Type2 ) Type2 ( Plonk_checks . Scalars . Tock ) Tock end let finalize_other_proof ( type b ) b ( module Proofs_verified : Nat . Add . Intf with type n = b ) b ? actual_proofs_verified ~ domain ~ max_quot_size ~ sponge ( ~ old_bulletproof_challenges : ( _ , b ) b Vector . t ) t ( { xi ; combined_inner_product ; bulletproof_challenges ; b ; plonk } : ( _ , _ , _ Shifted_value . Type2 . t , _ ) Types . Step . Proof_state . Deferred_values . In_circuit . t ) { Plonk_types . All_evals . ft_eval1 ; evals = ( { evals = evals1 ; public_input = x_hat1 } , { evals = evals2 ; public_input = x_hat2 } ) } = let T = Proofs_verified . eq in let open Vector in let open Field in let absorb_evals x_hat e = with_label __LOC__ ( fun ( ) -> let xs , ys = Evals . to_vectors e in List . iter Vector ( [ . | x_hat ] | :: ( to_list xs @ to_list ys ) ys ) ys ~ f ( : Array . iter ~ f ( : Sponge . absorb sponge ) sponge ) sponge ) in absorb_evals x_hat1 evals1 ; absorb_evals x_hat2 evals2 ; Sponge . absorb sponge ft_eval1 ; let xi_actual = squeeze_scalar sponge in let r_actual = squeeze_challenge sponge in let xi_correct = with_label __LOC__ ( fun ( ) -> let { SC . SC . inner = xi_actual } = xi_actual in let { SC . SC . inner = xi } = xi in Field . equal xi_actual xi ) in let xi = scalar_to_field xi in let r = scalar_to_field ( SC . SC . create r_actual ) r_actual in let plonk = map_plonk_to_field plonk in let zetaw = Field . mul domain # generator plonk . zeta in let plonk_minimal = Plonk . to_minimal plonk in let combined_evals = let n = Common . Max_degree . wrap_log2 in let zeta_n = pow2pow plonk . zeta n in let zetaw_n = pow2pow zetaw n in ( Plonk_types . Evals . map ~ f ( : actual_evaluation ~ pt_to_n : zeta_n ) zeta_n evals1 , Plonk_types . Evals . map ~ f ( : actual_evaluation ~ pt_to_n : zetaw_n ) zetaw_n evals2 ) in let env = Plonk_checks . scalars_env ( module Field ) Field ~ srs_length_log2 : Common . Max_degree . wrap_log2 ~ endo ( : Impl . Field . constant Endo . Wrap_inner_curve . base ) base ~ mds : sponge_params . mds ~ field_of_hex ( : fun s -> Kimchi_pasta . Pasta . Bigint256 . of_hex_string s |> Kimchi_pasta . Pasta . Fq . of_bigint |> Field . constant ) ~ domain ( Plonk . to_minimal plonk ) plonk combined_evals in let combined_inner_product_correct = with_label __LOC__ ( fun ( ) -> let ft_eval0 : Field . t = with_label __LOC__ ( fun ( ) -> Plonk_checks . ft_eval0 ( module Field ) Field ~ env ~ domain plonk_minimal combined_evals x_hat1 ) in let actual_combined_inner_product = let sg_olds = Vector . map old_bulletproof_challenges ~ f ( : fun chals -> unstage ( challenge_polynomial ( Vector . to_array chals ) chals ) chals ) in let combine ~ ft pt x_hat e = let pi = Proofs_verified . add Nat . N26 . n in let a , b = Evals . to_vectors ( e : Field . t array Evals . t ) t in let sg_evals = match actual_proofs_verified with | None -> Vector . map sg_olds ~ f ( : fun f -> [ | f pt ] ) | | Some proofs_verified -> let mask = ones_vector ( module Impl ) Impl ~ first_zero : proofs_verified ( Vector . length sg_olds ) sg_olds in with_label __LOC__ ( fun ( ) -> Vector . map2 mask sg_olds ~ f ( : fun b f -> [ | Field ( ( . b :> t ) t * f pt ) pt ] | ) ) in let v = Vector . append sg_evals ( [ | x_hat ] | :: [ | ft ] | :: a ) a ( snd pi ) pi in combined_evaluation pi ~ xi ~ evaluation_point : pt ( v , b ) b ~ max_quot_size in combine ~ ft : ft_eval0 plonk . zeta x_hat1 evals1 + ( r * combine ~ ft : ft_eval1 zetaw x_hat2 evals2 ) evals2 in with_label __LOC__ ( fun ( ) -> equal ( Shifted_value . Type2 . to_field ( module Field ) Field ~ shift : shift2 combined_inner_product ) actual_combined_inner_product ) ) in let bulletproof_challenges = with_label __LOC__ ( fun ( ) -> compute_challenges ~ scalar : scalar_to_field bulletproof_challenges ) in let b_correct = with_label __LOC__ ( fun ( ) -> let challenge_poly = unstage ( challenge_polynomial ( Vector . to_array bulletproof_challenges ) bulletproof_challenges ) bulletproof_challenges in let b_actual = challenge_poly plonk . zeta + ( r * challenge_poly zetaw ) zetaw in equal ( Shifted_value . Type2 . to_field ( module Field ) Field ~ shift : shift2 b ) b b_actual ) in let plonk_checks_passed = with_label __LOC__ ( fun ( ) -> Plonk_checks . checked ( module Impl ) Impl ~ env ~ shift : shift2 plonk combined_evals ) in print_bool " xi_correct " xi_correct ; print_bool " combined_inner_product_correct " combined_inner_product_correct ; print_bool " plonk_checks_passed " plonk_checks_passed ; print_bool " b_correct " b_correct ; ( Boolean . all [ xi_correct ; b_correct ; combined_inner_product_correct ; plonk_checks_passed ] , bulletproof_challenges ) let map_challenges { Types . Step . Proof_state . Deferred_values . plonk ; combined_inner_product ; xi ; bulletproof_challenges ; b } ~ f ~ scalar = { Types . Step . Proof_state . Deferred_values . plonk = Types . Step . Proof_state . Deferred_values . Plonk . In_circuit . map_challenges plonk ~ f ~ scalar ; combined_inner_product ; bulletproof_challenges = Vector . map bulletproof_challenges ~ f ( : fun ( r : _ Bulletproof_challenge . t ) t -> { Bulletproof_challenge . prechallenge = scalar r . prechallenge } ) ; xi = scalar xi ; b } let hash_me_only ( type n ) n ( _max_proofs_verified : n Nat . t ) t ( t : ( _ , ( _ , n ) n Vector . t ) t Types . Wrap . Proof_state . Me_only . t ) t = let sponge = Sponge . create sponge_params in Array . iter ~ f ( : Sponge . absorb sponge ) sponge ( Types . Wrap . Proof_state . Me_only . to_field_elements ~ g1 : Inner_curve . to_field_elements t ) ; Sponge . squeeze_field sponge end |
let merge ( { dv = dv1 } as def1 , s1 ) ( { dv = dv2 } as def2 , s2 ) = Total . union def1 def2 , S . union dv1 ( S . union dv2 ( S . union s1 s2 ) ) |
let union ( { dv = dv1 } as def1 , s1 ) ( { dv = dv2 } as def2 , s2 ) = Total . union def1 def2 , S . union ( S . inter dv1 dv2 ) ( S . union s1 s2 ) |
let filter_env shared_set b_env = let filter n ( { t_sort = sort } as entry ) ( bounded , env ) = let entry = match sort with S . add n bounded , Env . add n entry env in Env . fold filter b_env ( S . empty , Env . empty ) |
let rec equation ( { eq_desc = desc } as eq ) = let eq , defnames , shared_set = match desc with | EQeq ( pat , e ) -> { eq with eq_desc = EQeq ( pat , expression e ) } , { Deftypes . empty with dv = Vars . fv_pat S . empty S . empty pat } , S . empty | EQpluseq ( n , e ) -> { eq with eq_desc = EQpluseq ( n , expression e ) } , { Deftypes . empty with dv = S . singleton n } , S . empty | EQder ( n , e , None , [ ] ) -> { eq with eq_desc = EQder ( n , expression e , None , [ ] ) } , { Deftypes . empty with der = S . singleton n } , S . empty | EQinit ( n , e ) -> { eq with eq_desc = EQinit ( n , expression e ) } , { Deftypes . empty with di = S . singleton n } , S . empty | EQmatch ( total , e , m_h_list ) -> let m_h_list , ( defnames , shared_set ) = { eq with eq_desc = EQmatch ( total , expression e , m_h_list ) } , defnames , shared_set | EQreset ( eq_list , e ) -> let eq_list , ( defnames , shared_set ) = let defnames , shared_set = { eq with eq_desc = EQreset ( eq_list , expression e ) } , defnames , shared_set | EQand ( and_eq_list ) -> let and_eq_list , ( defnames , shared_set ) = { eq with eq_desc = EQand ( and_eq_list ) } , defnames , shared_set | EQbefore ( before_eq_list ) -> let before_eq_list , ( defnames , shared_set ) = { eq with eq_desc = EQbefore ( before_eq_list ) } , defnames , shared_set | EQblock ( b ) -> let b , defnames , shared_set = block b in { eq with eq_desc = EQblock ( b ) } , defnames , shared_set | EQforall ( { for_index = i_list ; for_init = init_list ; let index xi_out_x ( { desc = desc } as ind ) = let init acc ( { desc = desc } as ini ) = let i_list , xi_out_x = Zmisc . map_fold index Env . empty i_list in let init_list , i_set = Zmisc . map_fold init S . empty init_list in let b_eq_list , { dv = dv ; di = di ; der = der ; nv = nv ; mv = mv } , shared_set = block b_eq_list in let x_of_xi xi = try Env . find xi xi_out_x with Not_found -> xi in let defnames = mv = S . map x_of_xi mv } in let shared_set = S . map x_of_xi shared_set in let defnames , shared_set = { eq with eq_desc = defnames , shared_set | EQpresent _ | EQautomaton _ | EQder _ | EQnext _ | EQemit _ -> assert false in { eq with eq_write = defnames } , defnames , shared_set Zmisc . map_fold ( fun acc eq -> let eq , defnames , shared_set = equation eq in let l_list = List . map local l_list in let eq_list , ( { dv = dv ; der = der ; di = di ; nv = nv ; mv = mv } , shared_set ) = equation_list ( Deftypes . empty , S . empty ) eq_list in let bounded , b_env = filter_env shared_set b_env in let dv = S . diff dv bounded in let di = S . diff di bounded in let der = S . diff der bounded in let nv = S . diff nv bounded in let mv = S . diff mv bounded in let shared_set = S . diff shared_set bounded in let local_defnames = { dv = dv ; der = der ; di = di ; nv = nv ; mv = mv } in { b with b_write = local_defnames ; b_locals = l_list ; local_defnames , shared_set let eq_list , ( _ , shared_set ) = equation_list ( Deftypes . empty , S . empty ) eq_list in let _ , l_env = filter_env shared_set l_env in { l with l_eq = eq_list ; l_env = l_env } let desc = match desc with | Elocal _ | Eglobal _ | Econst _ | Econstr0 _ | Elast _ -> desc | Eop ( op , e_list ) -> Eop ( op , List . map expression e_list ) | Eapp ( app , op , e_list ) -> Eapp ( app , op , List . map expression e_list ) | Etuple ( e_list ) -> Etuple ( List . map expression e_list ) | Econstr1 ( c , e_list ) -> Econstr1 ( c , List . map expression e_list ) | Erecord_access ( e_record , ln ) -> Erecord_access ( expression e_record , ln ) | Erecord ( l_e_list ) -> Erecord ( List . map ( fun ( l , e ) -> ( l , expression e ) ) l_e_list ) | Erecord_with ( e_record , l_e_list ) -> Erecord_with ( expression e_record , | Etypeconstraint ( e , ty ) -> Etypeconstraint ( expression e , ty ) | Elet ( l , e ) -> Elet ( local l , expression e ) | Eblock ( b , e ) -> let b , _ , _ = block b in Eblock ( b , expression e ) | Eseq ( e1 , e2 ) -> Eseq ( expression e1 , expression e2 ) | Eperiod { p_phase = p1 ; p_period = p2 } -> Eperiod | Epresent _ | Ematch _ -> assert false 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 |
module Core_over_monad ( Monad : Preface_specs . MONAD ) ( Tape : Preface_specs . MONOID ) = struct type tape = Tape . t type ' a monad = ' a Monad . t type ' a t = ( ' a * tape ) monad let upper m = Monad . bind ( fun a -> Monad . return ( a , Tape . neutral ) ) m let writer ( x , t ) = Monad . return ( x , t ) let run writer_m = writer_m let exec x = Monad . map snd x let tell s = writer ( ( ) , s ) let listen m = Monad . map ( fun ( x , b ) -> ( ( x , b ) , b ) ) m let listens f m = Monad . map ( fun ( x , b ) -> ( ( x , f b ) , b ) ) m let pass m = Monad . map ( fun ( ( x , f ) , b ) -> ( x , f b ) ) m let censor f m = Monad . map ( fun ( x , b ) -> ( x , f b ) ) m end |
module Functor ( F : Preface_specs . FUNCTOR ) ( Tape : Preface_specs . MONOID ) = type ' a t = ( ' a * Tape . t ) F . t let map f x = F . map ( fun ( y , t ) -> ( f y , t ) ) x end ) |
module Applicative ( A : Preface_specs . APPLICATIVE ) ( Tape : Preface_specs . MONOID ) = type ' a t = ( ' a * Tape . t ) A . t let pure x = A . pure ( x , Tape . neutral ) let apply f v = let g ( x , t ) ( y , u ) = ( x y , Tape . combine t u ) in A . lift2 g f v ; ; end ) |
module Alternative ( A : Preface_specs . ALTERNATIVE ) ( Tape : Preface_specs . MONOID ) = Alternative . Over_applicative ( Applicative ( A ) ( Tape ) ) ( struct type ' a t = ( ' a * Tape . t ) A . t let neutral = A . neutral let combine writer_l writer_r = A . combine writer_l writer_r end ) |
module Monad ( M : Preface_specs . MONAD ) ( Tape : Preface_specs . MONOID ) = type ' a t = ( ' a * Tape . t ) M . t let return x = M . return ( x , Tape . neutral ) let bind f m = M . ( m >>= fun ( x , t ) -> f x >|= fun ( y , u ) -> ( y , Tape . combine t u ) ) ; ; end ) |
module Monad_plus ( M : Preface_specs . MONAD_PLUS ) ( Tape : Preface_specs . MONOID ) = Monad_plus . Over_monad ( Monad ( M ) ( Tape ) ) ( struct type ' a t = ( ' a * Tape . t ) M . t let neutral = M . neutral let combine writer_l writer_r = M . combine writer_l writer_r end ) |
module Over_monad ( M : Preface_specs . MONAD ) ( Tape : Preface_specs . MONOID ) = struct include Core_over_monad ( M ) ( Tape ) module Monad = Monad ( M ) ( Tape ) include Monad end |
module Id = Unique_id . Int63 ( ) |
let io_stats = Io_stats . create ( ) |
module Time_ns_suppress_sexp_in_test = struct type t = Time_ns . t let sexp_of_t t = if am_running_inline_test then Sexp . List [ ] else Time_ns . sexp_of_t t end |
module Flush_result = struct type t = | Error | Consumer_left | Flushed of Time_ns_suppress_sexp_in_test . t [ @@ deriving sexp_of ] end |
module Line_ending = struct type t = | Dos | Unix [ @@ deriving sexp_of ] end |
module Check_buffer_age ' = struct type ' a t = { writer : ' a ; maximum_age : Time_ns . Span . t ; mutable bytes_received_at_now_minus_maximum_age : Int63 . t ; bytes_received_queue : Int63 . t Queue . t ; times_received_queue : Time_ns . t Queue . t ; mutable bytes_seen : Int63 . t ; mutable too_old : unit Ivar . t ; for_this_time_source : ' a per_time_source } and ' a per_time_source = { active_checks : ( ' a t [ @ sexp . opaque ] ) Bag . t ; closed : unit Ivar . t } [ @@ deriving fields , sexp_of ] end |
type open_flags = ( Open_flags . t , exn ) Result . t [ @@ deriving sexp_of ] |
module Destroy_or_keep = struct type t = | Destroy | Keep [ @@ deriving sexp_of ] end |
module Scheduled = struct type t = ( Bigstring . t IOVec . t * Destroy_or_keep . t ) Deque . t let length ( t : t ) = Deque . fold t ~ init : 0 ~ f ( : fun n ( iovec , _ ) -> n + iovec . len ) end |
module Stop_reason = struct type t = | Error | Consumer_left [ @@ deriving sexp_of ] end |
type t = { id : Id . t ; mutable fd : Fd . t ; monitor : Monitor . t ; inner_monitor : Monitor . t ; mutable background_writer_state : [ ` Running | ` Not_running | ` Stopped_permanently of Stop_reason . t ] ; background_writer_stopped : unit Ivar . t ; syscall : [ ` Per_cycle | ` Periodic of Time . Span . t ] ; mutable bytes_received : Int63 . t ; mutable bytes_written : Int63 . t ; scheduled : Scheduled . t ; mutable scheduled_bytes : int ; mutable buf : Bigstring . t ; mutable scheduled_back : int ; mutable back : int ; time_source : Time_source . t ; flushes : ( Flush_result . t Ivar . t * Int63 . t ) Queue . t ; mutable close_state : [ ` Open | ` Closed_and_flushing | ` Closed ] ; close_finished : unit Ivar . t ; close_started : unit Ivar . t ; producers_to_flush_at_close : ( unit -> unit Deferred . t ) Bag . t ; mutable flush_at_shutdown_elt : t Bag . Elt . t option ; mutable check_buffer_age : t Check_buffer_age ' . t Bag . Elt . t option ; consumer_left : unit Ivar . t ; mutable raise_when_consumer_leaves : bool ; open_flags : open_flags Deferred . t ; line_ending : Line_ending . t ; mutable backing_out_channel : Backing_out_channel . t option } |
let sexp_of_t t = [ % sexp ( t . fd : Fd . t_hum ) ] |
let sexp_of_t_internals { id ; fd ; monitor ; inner_monitor ; background_writer_state ; background_writer_stopped ; syscall ; bytes_received ; bytes_written ; scheduled = _ ; scheduled_bytes ; buf = _ ; scheduled_back ; back ; time_source ; flushes = _ ; close_state ; close_finished ; close_started ; producers_to_flush_at_close ; flush_at_shutdown_elt ; check_buffer_age ; consumer_left ; raise_when_consumer_leaves ; open_flags ; line_ending ; backing_out_channel } = let suppress_in_test x = if am_running_inline_test then None else Some x in let monitor_name_in_test monitor = if am_running_inline_test then [ % sexp ( Monitor . name monitor : Info . t ) ] else [ % sexp ( monitor : Monitor . t ) ] in let time_source = if phys_equal time_source ( Time_source . wall_clock ( ) ) then None else Some time_source in [ % sexp { id = ( suppress_in_test id : ( Id . t option [ @ sexp . option ] ) ) ; fd = ( suppress_in_test fd : ( Fd . t option [ @ sexp . option ] ) ) ; monitor = ( monitor_name_in_test monitor : Sexp . t ) ; inner_monitor = ( monitor_name_in_test inner_monitor : Sexp . t ) ; background_writer_state : [ ` Running | ` Not_running | ` Stopped_permanently of Stop_reason . t ] ; background_writer_stopped : unit Ivar . t ; syscall : [ ` Per_cycle | ` Periodic of Time . Span . t ] ; bytes_received : Int63 . t ; bytes_written : Int63 . t ; scheduled_bytes : int ; scheduled_back : int ; back : int ; time_source : ( Time_source . t option [ @ sexp . option ] ) ; close_state : [ ` Open | ` Closed_and_flushing | ` Closed ] ; close_finished : unit Ivar . t ; close_started : unit Ivar . t ; num_producers_to_flush_at_close = ( Bag . length producers_to_flush_at_close : int ) ; flush_at_shutdown_elt = ( suppress_in_test flush_at_shutdown_elt : ( ( t [ @ sexp . opaque ] ) Bag . Elt . t option option [ @ sexp . option ] ) ) ; check_buffer_age = ( suppress_in_test check_buffer_age : ( ( t [ @ sexp . opaque ] ) Check_buffer_age ' . t Bag . Elt . t option option [ @ sexp . option ] ) ) ; consumer_left : unit Ivar . t ; raise_when_consumer_leaves : bool ; open_flags = ( suppress_in_test open_flags : ( open_flags Deferred . t option [ @ sexp . option ] ) ) ; line_ending : Line_ending . t ; backing_out_channel : ( Backing_out_channel . t option [ @ sexp . option ] ) } ] ; ; |
type writer = t [ @@ deriving sexp_of ] |
let set_raise_when_consumer_leaves t bool = t . raise_when_consumer_leaves <- bool |
let bytes_to_write t = t . scheduled_bytes + t . back - t . scheduled_back |
let is_stopped_permanently t = match t . background_writer_state with | ` Stopped_permanently _ -> true | ` Running | ` Not_running -> false ; ; |
let invariant t : unit = try let check f field = f ( Field . get field t ) in Fields . iter ~ id : ignore ~ fd : ignore ~ monitor : ignore ~ inner_monitor : ignore ~ buf : ignore ~ background_writer_state : ( check ( function | ` Stopped_permanently _ -> assert ( bytes_to_write t = 0 ) ; assert ( Ivar . is_full t . background_writer_stopped ) | ` Running | ` Not_running -> assert ( Bigstring . length t . buf > 0 ) ; assert ( Int63 . ( t . bytes_received - t . bytes_written = of_int ( bytes_to_write t ) ) ) ; assert ( Ivar . is_empty t . background_writer_stopped ) ) ) ~ background_writer_stopped : ignore ~ syscall : ignore ~ bytes_written : ( check ( fun bytes_written -> assert ( Int63 . ( zero <= bytes_written && bytes_written <= t . bytes_received ) ) ) ) ~ bytes_received : ignore ~ scheduled : ( check ( fun ( scheduled : Scheduled . t ) -> Deque . iter scheduled ~ f ( : fun ( iovec , kind ) -> if phys_equal t . buf iovec . buf then assert ( match kind with | Keep -> true | Destroy -> false ) ) ) ) ~ scheduled_bytes : ( check ( fun scheduled_bytes -> assert ( scheduled_bytes = Scheduled . length t . scheduled ) ) ) ~ scheduled_back : ( check ( fun scheduled_back -> assert ( 0 <= scheduled_back && scheduled_back <= t . back ) ) ) ~ back ( : check ( fun back -> assert ( back <= Bigstring . length t . buf ) ) ) ~ time_source : ignore ~ flushes : ignore ~ close_state : ignore ~ close_finished : ( check ( fun close_finished -> match t . close_state with | ` Open | ` Closed_and_flushing -> assert ( Ivar . is_empty close_finished ) | ` Closed -> ( ) ) ) ~ close_started : ( check ( fun close_started -> [ % test_result : bool ] ( Ivar . is_empty close_started ) ~ expect : ( match t . close_state with | ` Open -> true | ` Closed | ` Closed_and_flushing -> false ) ) ) ~ producers_to_flush_at_close : ignore ~ flush_at_shutdown_elt : ( check ( fun o -> assert ( Bool . equal ( is_none o ) ( Ivar . is_full t . close_finished ) ) ; Option . iter o ~ f ( : fun elt -> assert ( phys_equal t ( Bag . Elt . value elt ) ) ) ) ) ~ check_buffer_age : ignore ~ consumer_left : ( check ( fun consumer_left -> if Ivar . is_full consumer_left then assert ( is_stopped_permanently t ) ) ) ~ raise_when_consumer_leaves : ignore ~ open_flags : ignore ~ line_ending : ignore ~ backing_out_channel ( : check ( Option . invariant Backing_out_channel . invariant ) ) with | exn -> raise_s [ % message " writer invariant failed " ( exn : exn ) ~ writer ( : t : t_internals ) ] ; ; |
module Check_buffer_age : sig type t = writer Check_buffer_age ' . t Bag . Elt . t option val dummy : t val create : writer -> maximum_age [ : ` At_most of Time . Span . t | ` Unlimited ] -> t val destroy : t -> unit val too_old : t -> unit Deferred . t module Internal_for_unit_test : sig val check_now : check_invariants : bool -> time_source : Time_source . t -> unit val num_active_checks_for : Time_source . t -> int option end open Check_buffer_age ' type t = writer Check_buffer_age ' . t Bag . Elt . t option let elt_invariant t : unit = Invariant . invariant [ % here ] t [ % sexp_of : _ t ] ( fun ( ) -> let check f field = f ( Field . get field t ) in assert ( Queue . length t . bytes_received_queue = Queue . length t . times_received_queue ) ; Fields . iter ~ writer : ignore ~ maximum_age : ignore ~ too_old : ( check ( fun ivar -> let imply a b = ( not a ) || b in assert ( imply Int63 . O . ( t . bytes_received_at_now_minus_maximum_age > t . writer . bytes_written ) ( Ivar . is_full ivar ) ) ) ) ~ bytes_received_queue : ( check ( fun q -> let n = Queue . fold q ~ init : t . bytes_received_at_now_minus_maximum_age ~ f ( : fun prev count -> assert ( Int63 . ( < ) prev count ) ; count ) in assert ( Int63 . ( <= ) n t . writer . bytes_received ) ; assert ( Int63 . ( = ) n t . bytes_seen ) ) ) ~ times_received_queue : ( check ( fun q -> match Queue . to_list q with | [ ] -> ( ) | times -> [ % test_result : Time_ns . t list ] ~ expect : times ( List . sort times ~ compare : Time_ns . compare ) ; assert ( Time_ns . Span . ( <= ) ( Time_ns . diff ( List . last_exn times ) ( List . hd_exn times ) ) t . maximum_age ) ) ) ~ bytes_received_at_now_minus_maximum_age : ignore ~ bytes_seen : ignore ~ for_this_time_source : ignore ) ; ; let dummy = None let rec sync e ~ now = if not ( Queue . is_empty e . bytes_received_queue ) then ( let bytes_received = Queue . peek_exn e . bytes_received_queue in let time_received = Queue . peek_exn e . times_received_queue in let bytes_are_written = Int63 . ( <= ) bytes_received e . writer . bytes_written in let bytes_are_too_old = Time_ns . Span . ( > ) ( Time_ns . diff now time_received ) e . maximum_age in if bytes_are_too_old then e . bytes_received_at_now_minus_maximum_age <- bytes_received ; if bytes_are_written || bytes_are_too_old then ( ignore ( Queue . dequeue_exn e . bytes_received_queue : Int63 . t ) ; ignore ( Queue . dequeue_exn e . times_received_queue : Time_ns . t ) ; sync e ~ now ) ) ; ; module Per_time_source = struct type t = writer Check_buffer_age ' . per_time_source let process_active_check e = let now = Time_source . now e . writer . time_source in sync e ~ now ; let bytes_received = e . writer . bytes_received in let bytes_written = e . writer . bytes_written in if Int63 . O . ( bytes_received > e . bytes_seen ) then ( e . bytes_seen <- bytes_received ; if Int63 . O . ( bytes_received > bytes_written ) then ( Queue . enqueue e . bytes_received_queue e . writer . bytes_received ; Queue . enqueue e . times_received_queue now ) ) ; let too_old = Int63 . O . ( e . bytes_received_at_now_minus_maximum_age > bytes_written ) in match Ivar . is_full e . too_old , too_old with | true , true | false , false -> ( ) | true , false -> e . too_old <- Ivar . create ( ) | false , true -> Ivar . fill e . too_old ( ) ; let writer = e . writer in Monitor . send_exn e . writer . monitor ( Exn . create_s [ % message " writer buffer has data older than " ~ maximum_age ( : e . maximum_age : Time_ns . Span . t ) ~ beginning_of_buffer : ( Bigstring . to_string writer . buf ~ pos : 0 ~ len ( : Int . min 1024 ( Bigstring . length writer . buf ) ) : string ) ( writer : writer ) ] ) ; ; let create ( ) = { active_checks = Bag . create ( ) ; closed = Ivar . create ( ) } let check t = Bag . iter t . active_checks ~ f : process_active_check let internal_check_now_for_unit_test t ~ check_invariants = if check_invariants then Bag . iter t . active_checks ~ f : elt_invariant ; check t ; ; end module Time_source_key = Hashable . Make_plain ( struct type t = Time_source . t [ @@ deriving sexp_of ] let hash_fold_t state t = Time_source . Id . hash_fold_t state ( Time_source . id t ) let hash t = Time_source . Id . hash ( Time_source . id t ) let compare t1 t2 = Time_source . Id . compare ( Time_source . id t1 ) ( Time_source . id t2 ) end ) let by_time_source : Per_time_source . t Time_source_key . Table . t = Time_source_key . Table . create ( ) ; ; module Internal_for_unit_test = struct let num_active_checks_for time_source = Option . map ( Hashtbl . find by_time_source time_source ) ~ f ( : fun pt -> Bag . length pt . active_checks ) ; ; let check_now ~ check_invariants ~ time_source = Per_time_source . internal_check_now_for_unit_test ( Hashtbl . find_exn by_time_source time_source ) ~ check_invariants ; ; end let create writer ~ maximum_age = match maximum_age with | ` Unlimited -> None | ` At_most maximum_age -> let time_source = writer . time_source in let for_this_time_source = Hashtbl . find_or_add by_time_source time_source ~ default ( : fun ( ) -> let pt = Per_time_source . create ( ) in Time_source . every time_source Time_ns . Span . second ~ stop ( : Ivar . read pt . closed ) ~ continue_on_error : false ( fun ( ) -> Per_time_source . check pt ) ; pt ) in Some ( Bag . add for_this_time_source . active_checks { writer ; bytes_received_queue = Queue . create ( ) ; times_received_queue = Queue . create ( ) ; maximum_age = Time_ns . Span . of_span_float_round_nearest maximum_age ; bytes_seen = Int63 . zero ; bytes_received_at_now_minus_maximum_age = Int63 . zero ; too_old = Ivar . create ( ) ; for_this_time_source } ) ; ; let destroy t = match t with | None -> ( ) | Some elt -> let t = Bag . Elt . value elt in let per_time_source = t . for_this_time_source in Bag . remove per_time_source . active_checks elt ; if Bag . is_empty per_time_source . active_checks then ( Hashtbl . remove by_time_source t . writer . time_source ; Ivar . fill_if_empty per_time_source . closed ( ) ) ; ; let too_old t = match t with | None -> Deferred . never ( ) | Some elt -> Ivar . read ( Bag . Elt . value elt ) . too_old ; ; end |
let flushed_or_failed_with_result t = match t . backing_out_channel with | Some backing_out_channel -> Backing_out_channel . flush backing_out_channel ; return ( Flush_result . Flushed ( Time_source . now t . time_source ) ) | None -> if Int63 . O . ( t . bytes_written = t . bytes_received ) then return ( Flush_result . Flushed ( Time_source . now t . time_source ) ) else ( match t . background_writer_state with | ` Stopped_permanently Error -> return Flush_result . Error | ` Stopped_permanently Consumer_left -> return Flush_result . Consumer_left | ` Running | ` Not_running -> if Ivar . is_full t . close_finished then Deferred . return Flush_result . Error else Deferred . create ( fun ivar -> Queue . enqueue t . flushes ( ivar , t . bytes_received ) ) ) ; ; |
let eager_map t ~ f = if Deferred . is_determined t then return ( f ( Deferred . value_exn t ) ) else Deferred . map t ~ f ; ; |
let eager_bind t ~ f = if Deferred . is_determined t then f ( Deferred . value_exn t ) else Deferred . bind t ~ f ; ; |
let flushed_or_failed_unit t = eager_map ( flushed_or_failed_with_result t ) ~ f : ignore |
let flushed_time_ns t = eager_bind ( flushed_or_failed_with_result t ) ~ f ( : function | Flushed t -> Deferred . return t | Error | Consumer_left -> Deferred . never ( ) ) ; ; |
let flushed_time t = eager_map ( flushed_time_ns t ) ~ f : Time_ns . to_time_float_round_nearest |
let flushed t = eager_map ( flushed_time_ns t ) ~ f ( : ignore : Time_ns . t -> unit ) ; ; |
let set_backing_out_channel t backing_out_channel = t . backing_out_channel <- Some backing_out_channel ; ; |
let set_synchronous_backing_out_channel t backing_out_channel = let rec wait_until_no_bytes_to_write ( ) = if bytes_to_write t = 0 then ( set_backing_out_channel t backing_out_channel ; return ( ) ) else ( let % bind ( ) = flushed t in wait_until_no_bytes_to_write ( ) ) in wait_until_no_bytes_to_write ( ) ; ; |
let set_synchronous_out_channel t out_channel = set_synchronous_backing_out_channel t ( Backing_out_channel . of_out_channel out_channel ) ; ; |
let using_synchronous_backing_out_channel t = Option . is_some t . backing_out_channel |
let clear_synchronous_out_channel t = if is_some t . backing_out_channel then ( assert ( bytes_to_write t = 0 ) ; t . backing_out_channel <- None ) ; ; |
let with_synchronous_backing_out_channel t backing_out_channel ~ f = let saved_backing_out_channel = t . backing_out_channel in Monitor . protect ( fun ( ) -> let % bind ( ) = set_synchronous_backing_out_channel t backing_out_channel in f ( ) ) ~ finally ( : fun ( ) -> t . backing_out_channel <- saved_backing_out_channel ; return ( ) ) ; ; |
let with_synchronous_out_channel t out_channel ~ f = with_synchronous_backing_out_channel t ~ f ( Backing_out_channel . of_out_channel out_channel ) ; ; |
let set_fd t fd = let % map ( ) = flushed t in t . fd <- fd ; ; |
let consumer_left t = Ivar . read t . consumer_left |
let close_finished t = Ivar . read t . close_finished |
let close_started t = Ivar . read t . close_started |
let is_closed t = match t . close_state with | ` Open -> false | ` Closed | ` Closed_and_flushing -> true ; ; |
let is_open t = not ( is_closed t ) |
let writers_to_flush_at_shutdown : t Bag . t = Bag . create ( ) |
let final_flush ? force t = let producers_flushed = Deferred . List . iter ~ how ` : Parallel ~ f ( : fun f -> f ( ) ) ( Bag . to_list t . producers_to_flush_at_close ) in let force = match force with | Some fc -> fc | None -> ( match Fd . kind t . fd with | File -> Deferred . never ( ) | Char | Fifo | Socket _ -> Time_source . after t . time_source ( Time_ns . Span . of_sec 5 . ) ) in Deferred . any_unit [ consumer_left t ; Deferred . all_unit [ producers_flushed ; flushed t ] ; force ; Check_buffer_age . too_old t . check_buffer_age ] ; ; |
let close ? force_close t = if debug then Debug . log " Writer . close " t [ % sexp_of : t ] ; ( match t . close_state with | ` Closed_and_flushing | ` Closed -> ( ) | ` Open -> t . close_state <- ` Closed_and_flushing ; Ivar . fill t . close_started ( ) ; final_flush t ? force : force_close >>> fun ( ) -> t . close_state <- ` Closed ; Check_buffer_age . destroy t . check_buffer_age ; ( match t . flush_at_shutdown_elt with | None -> assert false | Some elt -> Bag . remove writers_to_flush_at_shutdown elt ) ; Unix . close t . fd >>> fun ( ) -> Ivar . fill t . close_finished ( ) ) ; close_finished t ; ; |
let ( ) = Shutdown . at_shutdown ( fun ( ) -> if debug then Debug . log_string " Writer . at_shutdown " ; Deferred . List . iter ~ how ` : Parallel ( Bag . to_list writers_to_flush_at_shutdown ) ~ f ( : fun t -> Deferred . any_unit [ final_flush t ; close_finished t ] ) ) ; ; |
let fill_flushes { bytes_written ; flushes ; time_source ; _ } = if not ( Queue . is_empty flushes ) then ( let now = Time_source . now time_source in let rec loop ( ) = match Queue . peek flushes with | None -> ( ) | Some ( ivar , z ) -> if Int63 . ( z <= bytes_written ) then ( Ivar . fill ivar ( Flush_result . Flushed now ) ; ignore ( Queue . dequeue flushes : ( Flush_result . t Ivar . t * Int63 . t ) option ) ; loop ( ) ) in loop ( ) ) ; ; |
let stop_permanently t ( outcome : Stop_reason . t ) = t . background_writer_state <- ` Stopped_permanently outcome ; Deque . clear t . scheduled ; t . scheduled_bytes <- 0 ; t . buf <- Bigstring . create 0 ; t . scheduled_back <- 0 ; t . back <- 0 ; Ivar . fill_if_empty t . background_writer_stopped ( ) ; Queue . iter t . flushes ~ f ( : fun ( ivar , _ ) -> Ivar . fill ivar ( match outcome with | Error -> Flush_result . Error | Consumer_left -> Flush_result . Consumer_left ) ) ; Queue . clear t . flushes ; ; |
let stopped_permanently t = Ivar . read t . background_writer_stopped |
let die t sexp = stop_permanently t Error ; raise_s sexp ; ; |
type buffer_age_limit = [ ` At_most of Time . Span . t | ` Unlimited ] |
let create ? buf_len ( ? syscall = ` Per_cycle ) ? buffer_age_limit ( ? raise_when_consumer_leaves = true ) ( ? line_ending = Line_ending . Unix ) ? time_source fd = let time_source = match time_source with | Some x -> Time_source . read_only x | None -> Time_source . wall_clock ( ) in let buffer_age_limit = match buffer_age_limit with | Some z -> z | None -> ( match Fd . kind fd with | File -> ` Unlimited | Char | Fifo | Socket _ -> ` At_most ( Time . Span . of_min 2 . ) ) in let buf_len = match buf_len with | None -> 65 * 1024 * 2 | Some buf_len -> if buf_len <= 0 then invalid_arg " Writer . create : buf_len <= 0 " else buf_len in let id = Id . create ( ) in let monitor = Monitor . create ( ) ? name ( : if am_running_inline_test then Some " Writer . monitor " else None ) in let inner_monitor = Monitor . create ( ) ? name ( : if am_running_inline_test then Some " Writer . inner_monitor " else None ) in let consumer_left = Ivar . create ( ) in let open_flags = try_with ( fun ( ) -> Unix . fcntl_getfl fd ) in let t = { id ; fd ; syscall ; monitor ; inner_monitor ; buf = Bigstring . create buf_len ; back = 0 ; scheduled_back = 0 ; scheduled = Deque . create ( ) ; scheduled_bytes = 0 ; bytes_received = Int63 . zero ; bytes_written = Int63 . zero ; time_source ; flushes = Queue . create ( ) ; background_writer_state = ` Not_running ; background_writer_stopped = Ivar . create ( ) ; close_state = ` Open ; close_finished = Ivar . create ( ) ; close_started = Ivar . create ( ) ; producers_to_flush_at_close = Bag . create ( ) ; flush_at_shutdown_elt = None ; check_buffer_age = Check_buffer_age . dummy ; consumer_left ; raise_when_consumer_leaves ; open_flags ; line_ending ; backing_out_channel = None } in Monitor . detach_and_iter_errors inner_monitor ~ f ( : fun ( exn : Exn . t ) -> Monitor . send_exn monitor ( Exn . create_s [ % message " Writer error from inner_monitor " ~ _ ( : Monitor . extract_exn exn : Exn . t ) ~ writer ( : t : t_internals ) ] ) ) ; t . check_buffer_age <- Check_buffer_age . create t ~ maximum_age : buffer_age_limit ; t . flush_at_shutdown_elt <- Some ( Bag . add writers_to_flush_at_shutdown t ) ; t ; ; |
let set_buffer_age_limit t maximum_age = Check_buffer_age . destroy t . check_buffer_age ; t . check_buffer_age <- Check_buffer_age . create t ~ maximum_age ; ; |
let of_out_channel oc kind = create ( Fd . of_out_channel oc kind ) |
let can_write t = match t . close_state with | ` Open | ` Closed_and_flushing -> true | ` Closed -> false ; ; |
let ensure_can_write t = if not ( can_write t ) then raise_s [ % message " attempt to use closed writer " ~ _ ( : t : t ) ] ; ; |
let open_file ( ? append = false ) ? buf_len ? syscall ( ? perm = 0o666 ) ? line_ending ? time_source file = let mode = [ ` Wronly ; ` Creat ] in let mode = ( if append then ` Append else ` Trunc ) :: mode in Unix . openfile file ~ mode ~ perm >>| create ? buf_len ? syscall ? line_ending ? time_source ; ; |
let with_close t ~ f = Monitor . protect f ~ finally ( : fun ( ) -> close t ) |
let with_writer_exclusive t f = let % bind ( ) = Unix . lockf t . fd Exclusive in Monitor . protect f ~ finally ( : fun ( ) -> let % map ( ) = flushed t in Unix . unlockf t . fd ) ; ; |
let with_file ? perm ? append ? syscall ( ? exclusive = false ) ? line_ending ? time_source file ~ f = let % bind t = open_file ? perm ? append ? syscall ? line_ending ? time_source file in with_close t ~ f ( : fun ( ) -> if exclusive then with_writer_exclusive t ( fun ( ) -> f t ) else f t ) ; ; |
let got_bytes t n = t . bytes_received <- Int63 . ( t . bytes_received + of_int n ) |
let add_iovec t kind ( iovec : _ IOVec . t ) ~ count_bytes_as_received = assert ( t . scheduled_back = t . back ) ; if count_bytes_as_received then got_bytes t iovec . len ; if not ( is_stopped_permanently t ) then ( t . scheduled_bytes <- t . scheduled_bytes + iovec . len ; Deque . enqueue_back t . scheduled ( iovec , kind ) ) ; assert ( t . scheduled_back = t . back ) ; ; |
let schedule_unscheduled t kind = let need_to_schedule = t . back - t . scheduled_back in assert ( need_to_schedule >= 0 ) ; if need_to_schedule > 0 then ( let pos = t . scheduled_back in t . scheduled_back <- t . back ; add_iovec t kind ( IOVec . of_bigstring t . buf ~ pos ~ len : need_to_schedule ) ~ count_bytes_as_received : false ) ; ; |
let dummy_iovec = IOVec . empty IOVec . bigstring_kind |
let mk_iovecs t = schedule_unscheduled t Keep ; let n_iovecs = Int . min ( Deque . length t . scheduled ) ( Lazy . force IOVec . max_iovecs ) in let iovecs = Array . create ~ len : n_iovecs dummy_iovec in let contains_mmapped_ref = ref false in let iovecs_len = ref 0 in with_return ( fun r -> let i = ref 0 in Deque . iter t . scheduled ~ f ( : fun ( iovec , _ ) -> if ! i >= n_iovecs then r . return ( ) ; if ( not ! contains_mmapped_ref ) && Bigstring . is_mmapped iovec . buf then contains_mmapped_ref := true ; iovecs_len := ! iovecs_len + iovec . len ; iovecs . ( ! i ) <- iovec ; incr i ) ) ; iovecs , ! contains_mmapped_ref , ! iovecs_len ; ; |
let is_running = function | ` Running -> true | _ -> false ; ; |
let fd_closed t = if not ( is_closed t ) then die t [ % message " writer fd unexpectedly closed " ] ; ; |
let rec start_write t = if debug then Debug . log " Writer . start_write " t [ % sexp_of : t ] ; assert ( is_running t . background_writer_state ) ; let iovecs , contains_mmapped , iovecs_len = mk_iovecs t in let handle_write_result = function | ` Already_closed -> fd_closed t | ` Ok n -> if n >= 0 then write_finished t n else die t [ % message " write system call returned negative result " ( n : int ) ] | ` Error ( Unix . Unix_error ( ( EWOULDBLOCK | EAGAIN ) , _ , _ ) ) -> write_when_ready t | ` Error ( Unix . Unix_error ( EBADF , _ , _ ) ) -> die t [ % message " write got EBADF " ] | ` Error ( Unix . Unix_error ( ( EPIPE | ECONNRESET | EHOSTUNREACH | ENETDOWN | ENETRESET | ENETUNREACH | ETIMEDOUT ) , _ , _ ) as exn ) -> assert ( Ivar . is_empty t . consumer_left ) ; Ivar . fill t . consumer_left ( ) ; if t . raise_when_consumer_leaves then ( stop_permanently t Error ; raise exn ) else stop_permanently t Consumer_left | ` Error exn -> die t [ % message " " ~ _ ( : exn : Exn . t ) ] in let should_write_in_thread = ( not ( Fd . supports_nonblock t . fd ) ) || iovecs_len > thread_io_cutoff || contains_mmapped in if should_write_in_thread then Fd . syscall_in_thread t . fd ~ name " : writev " ( fun file_descr -> Bigstring_unix . writev file_descr iovecs ) >>> handle_write_result else handle_write_result ( Fd . syscall t . fd ~ nonblocking : true ( fun file_descr -> Bigstring_unix . writev_assume_fd_is_nonblocking file_descr iovecs ) ) if debug then Debug . log " Writer . write_when_ready " t [ % sexp_of : t ] ; assert ( is_running t . background_writer_state ) ; Fd . ready_to t . fd ` Write >>> function | ` Bad_fd -> die t [ % message " writer ready_to got Bad_fd " ] | ` Closed -> fd_closed t | ` Ready -> start_write t if debug then Debug . log " Writer . write_finished " ( bytes_written , t ) [ % sexp_of : int * t ] ; assert ( is_running t . background_writer_state ) ; let int63_bytes_written = Int63 . of_int bytes_written in Io_stats . update io_stats ~ kind ( : Fd . kind t . fd ) ~ bytes : int63_bytes_written ; t . bytes_written <- Int63 . ( int63_bytes_written + t . bytes_written ) ; if Int63 . ( t . bytes_written > t . bytes_received ) then die t [ % message " writer wrote more bytes than it received " ] ; fill_flushes t ; t . scheduled_bytes <- t . scheduled_bytes - bytes_written ; let rec remove_done bytes_written = assert ( bytes_written >= 0 ) ; match Deque . dequeue_front t . scheduled with | None -> if bytes_written > 0 then die t [ % message " writer wrote nonzero amount but IO_queue is empty " ] | Some ( { buf ; pos ; len } , kind ) -> if bytes_written >= len then ( ( match kind with | Destroy -> Bigstring . unsafe_destroy buf | Keep -> ( ) ) ; remove_done ( bytes_written - len ) ) else ( let new_iovec = IOVec . of_bigstring buf ~ pos ( : pos + bytes_written ) ~ len ( : len - bytes_written ) in Deque . enqueue_front t . scheduled ( new_iovec , kind ) ) in remove_done bytes_written ; schedule_unscheduled t Keep ; if Deque . is_empty t . scheduled then ( t . back <- 0 ; t . scheduled_back <- 0 ; t . background_writer_state <- ` Not_running ) else ( match t . syscall with | ` Per_cycle -> write_when_ready t | ` Periodic span -> Time_source . after t . time_source ( Time_ns . Span . of_span_float_round_nearest span ) >>> fun _ -> start_write t ) ; ; |
let maybe_start_writer t = match t . background_writer_state with | ` Stopped_permanently _ | ` Running -> ( ) | ` Not_running -> if bytes_to_write t > 0 then ( t . background_writer_state <- ` Running ; schedule ~ monitor : t . inner_monitor ~ priority : Priority . low ( fun ( ) -> t . open_flags >>> fun open_flags -> let can_write_fd = match open_flags with | Error _ -> false | Ok flags -> Unix . Open_flags . can_write flags in if not can_write_fd then die t [ % message " not allowed to write due to file - descriptor flags " ( open_flags : open_flags ) ] ; start_write t ) ) ; ; |
let give_buf t desired = assert ( desired > 0 ) ; assert ( not ( is_stopped_permanently t ) ) ; got_bytes t desired ; let buf_len = Bigstring . length t . buf in let available = buf_len - t . back in if desired <= available then ( let pos = t . back in t . back <- t . back + desired ; t . buf , pos ) else if desired > buf_len / 2 then ( schedule_unscheduled t Keep ; let buf = Bigstring . create desired in add_iovec t Destroy ( IOVec . of_bigstring ~ len : desired buf ) ~ count_bytes_as_received : false ; buf , 0 ) else ( schedule_unscheduled t Destroy ; let buf = Bigstring . create buf_len in t . buf <- buf ; t . scheduled_back <- 0 ; t . back <- desired ; buf , 0 ) ; ; |
let write_gen_internal ( type a ) t src ~ src_pos ~ src_len ~ allow_partial_write ( ~ blit_to_bigstring : ( a , Bigstring . t ) Blit . blit ) = if is_stopped_permanently t then got_bytes t src_len else ( match t . backing_out_channel with | Some backing_out_channel -> got_bytes t src_len ; Backing_out_channel . output backing_out_channel ~ blit_to_bigstring ~ src ~ src_len ~ src_pos ; t . bytes_written <- Int63 . ( t . bytes_written + of_int src_len ) | None -> let available = Bigstring . length t . buf - t . back in if available >= src_len then ( got_bytes t src_len ; let dst_pos = t . back in t . back <- dst_pos + src_len ; blit_to_bigstring ~ src ~ src_pos ~ len : src_len ~ dst : t . buf ~ dst_pos ) else if allow_partial_write then ( got_bytes t available ; let dst_pos = t . back in t . back <- dst_pos + available ; blit_to_bigstring ~ src ~ src_pos ~ len : available ~ dst : t . buf ~ dst_pos ; let remaining = src_len - available in let dst , dst_pos = give_buf t remaining in blit_to_bigstring ~ src ~ src_pos ( : src_pos + available ) ~ len : remaining ~ dst ~ dst_pos ) else ( let dst , dst_pos = give_buf t src_len in blit_to_bigstring ~ src ~ src_pos ~ dst ~ dst_pos ~ len : src_len ) ; maybe_start_writer t ) ; ; |
let write_direct t ~ f = if is_stopped_permanently t then None else ( let pos = t . back in let len = Bigstring . length t . buf - pos in let x , written = f t . buf ~ pos ~ len in if written < 0 || written > len then raise_s [ % message " [ write_direct ] ' s [ ~ f ] argument returned invalid [ written ] " ( written : int ) ( len : int ) ~ writer ( : t : t ) ] ; t . back <- pos + written ; got_bytes t written ; maybe_start_writer t ; Some x ) ; ; |
let write_gen_unchecked ? pos ? len t src ~ blit_to_bigstring ~ length = let src_pos , src_len = Ordered_collection_common . get_pos_len_exn ( ) ? pos ? len ~ total_length ( : length src ) in write_gen_internal t src ~ src_pos ~ src_len ~ allow_partial_write : true ~ blit_to_bigstring ; ; |
let write_gen_whole_unchecked t src ~ blit_to_bigstring ~ length = let src_len = length src in write_gen_internal t src ~ src_pos : 0 ~ src_len ~ allow_partial_write : false ~ blit_to_bigstring ( : fun ~ src ~ src_pos ~ dst ~ dst_pos ~ len -> assert ( src_pos = 0 ) ; assert ( len = src_len ) ; blit_to_bigstring src dst ~ pos : dst_pos ) ; ; |
let write_bytes ? pos ? len t src = write_gen_unchecked ? pos ? len t src ~ blit_to_bigstring : Bigstring . From_bytes . blit ~ length : Bytes . length ; ; |
let write ? pos ? len t src = write_gen_unchecked ? pos ? len t src ~ blit_to_bigstring : Bigstring . From_string . blit ~ length : String . length ; ; |
let write_bigstring ? pos ? len t src = write_gen_unchecked ? pos ? len t src ~ blit_to_bigstring : Bigstring . blit ~ length : Bigstring . length ; ; |
let write_iobuf ? pos ? len t iobuf = let iobuf = Iobuf . read_only ( Iobuf . no_seek iobuf ) in write_gen_unchecked ? pos ? len t iobuf ~ blit_to_bigstring : Iobuf . Peek . To_bigstring . blit ~ length : Iobuf . length ; ; |
let write_substring t substring = write_bytes t ( Substring . base substring ) ~ pos ( : Substring . pos substring ) ~ len ( : Substring . length substring ) ; ; |
let write_bigsubstring t bigsubstring = write_bigstring t ( Bigsubstring . base bigsubstring ) ~ pos ( : Bigsubstring . pos bigsubstring ) ~ len ( : Bigsubstring . length bigsubstring ) ; ; |
let writef t = ksprintf ( fun s -> write t s ) |
let write_gen ? pos ? len t src ~ blit_to_bigstring ~ length = try write_gen_unchecked ? pos ? len t src ~ blit_to_bigstring ~ length with | exn -> die t [ % message " Writer . write_gen : error writing value " ( exn : exn ) ] ; ; |
let write_gen_whole t src ~ blit_to_bigstring ~ length = try write_gen_whole_unchecked t src ~ blit_to_bigstring ~ length with | exn -> die t [ % message " Writer . write_gen_whole : error writing value " ( exn : exn ) ] ; ; |
let to_formatter t = Format . make_formatter ( fun str pos len -> let str = Bytes . of_string str in ensure_can_write t ; write_substring t ( Substring . create str ~ pos ~ len ) ) ignore ; ; |
let write_char t c = if is_stopped_permanently t then got_bytes t 1 else ( match t . backing_out_channel with | Some backing_out_channel -> got_bytes t 1 ; Backing_out_channel . output_char backing_out_channel c ; t . bytes_written <- Int63 . ( t . bytes_written + of_int 1 ) | None -> if Bigstring . length t . buf - t . back >= 1 then ( got_bytes t 1 ; t . buf . { t . back } <- c ; t . back <- t . back + 1 ) else ( let dst , dst_pos = give_buf t 1 in dst . { dst_pos } <- c ) ; maybe_start_writer t ) ; ; |
let newline ? line_ending t = let line_ending = match line_ending with | Some x -> x | None -> t . line_ending in ( match line_ending with | Unix -> ( ) | Dos -> write_char t ' \ r ' ) ; write_char t ' \ n ' ; ; |
let write_line ? line_ending t s = write t s ; newline t ? line_ending ; ; |
let write_byte t i = write_char t ( char_of_int ( i % 256 ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.