Source

dumbstreaming / dumbstreaming_it.ml

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
(*
value dbg fmt = Printf.eprintf fmt
;
*)
value dbg fmt = Printf.ifprintf stdout fmt
;

value ( & ) f x = f x
;

module type IT_TYPE
 =
  sig
    module It_IO
     :
      sig
        type m +'a;
        value return : 'a -> m 'a;
        value bind_rev : m 'a -> ('a -> m 'b) -> m 'b;
        value error : exn -> m 'a;
      end
    ;

    type stream 'el;
    value empty_stream : stream 'el;
    value chunk_of : 'el -> stream 'el;

    type err_msg = exn;

    type iteratee 'el 'a =
      [ IE_done of 'a
      | IE_cont of option err_msg and
          ( stream 'el
            -> It_IO.m (iteratee 'el 'a * stream 'el)
          )
      ]
    ;

    value return : 'a -> iteratee 'el 'a
    ;

    value throw_err : err_msg -> iteratee 'el 'a
    ;

    value peek : iteratee 'el (option 'el)
    ;

    value bindI :
      ('a -> iteratee 'el 'b) -> iteratee 'el 'a -> iteratee 'el 'b
    ;

    value joinI :
      iteratee 'el (iteratee 'el' 'a) -> iteratee 'el 'a
    ;

    value drop : int -> iteratee 'el unit
    ;

    value drop_while : ('el -> bool) -> iteratee 'el unit
    ;

    value break_chars : (char -> bool) -> iteratee char string
    ;

    type enumeratee 'elo 'eli 'a = 
      iteratee 'eli 'a -> iteratee 'elo (iteratee 'eli 'a)
    ;

    value limit : int -> enumeratee 'el 'el 'a
    ;

    value sequence_stream : iteratee 'elo 'eli
      -> enumeratee 'elo 'eli 'a
    ;

    value catch :
      (unit -> iteratee 'el 'a) ->
      ( err_msg ->
         iteratee 'el 'a
      ) ->
      iteratee 'el 'a
    ;

    value take : int -> enumeratee 'el 'el 'a
    ;

    value stream2list : iteratee 'el (list 'el)
    ;

  end
;


type ntotal = int64
 and npart = int
 and nbytes = int
;


module Make (I : IT_TYPE)
 :
  sig
    (* None of EOF *)

    value read :
      (~ntotal:ntotal -> ~npart:npart -> ~nbytes:nbytes -> I.iteratee char 'i)
      -> I.iteratee 'i 'a
      -> I.iteratee char (option 'a)
    ;


    (* for tests: *)
    value read_uint : I.iteratee char int;

    (* for tests: *)
    value read_uint_nz : I.iteratee char int;

    value read_lengths : int -> I.iteratee char (list int)
    ;

  end
 =
  struct

    (* todo: move to ocaml-iteratees: *)
    module It_add
     :
      sig
        value itlist_anyresult_lasterror
         : list (I.iteratee 'el 'a) -> I.iteratee 'el 'a
        ;

        (* leading zeroes accepted *)
        value read_uint : I.iteratee char int
        ;

        (* leading zeroes = error *)
        value read_uint_nz : I.iteratee char int
        ;

        (* leading zeroes accepted *)
        value read_uint64 : I.iteratee char int64
        ;

        (* leading zeroes = error *)
        value read_uint64_nz : I.iteratee char int64
        ;

      end
     =
      struct

        exception Itlist_empty;

        module IO = I.It_IO;

        value ( & ) f x = f x;

        value ( >>% ) = IO.bind_rev;

        open I;
        value ( >>= ) m f = bindI f m;
 
        value itlist_step_firstresult_lasterror
          (lst : list (iteratee 'el 'a))
          (s : stream 'el)
         :
          IO.m [= `First_result of (iteratee 'el 'a * stream 'el)
               |  `Last_error of err_msg
               |  `Cont of list (iteratee 'el 'a)
               ]
         =
          let rec loop lasterropt acc lst =
            match lst with
            [ [] ->
                if acc = []
                then
                  match lasterropt with
                  [ None -> assert False
                  | Some err -> IO.return & `Last_error err
                  ]
                else
                  IO.return & `Cont (List.rev acc)
            | [hd :: tl] ->
                match hd with
                [ (IE_done _) as it -> IO.return & `First_result (it, s)
                | IE_cont ((Some _) as someerr) _ ->
                    loop someerr acc tl
                | IE_cont None k ->
                    k s >>% fun
                    [ (IE_done _, _) as r ->
                        IO.return & `First_result r
                    | (IE_cont (Some _ as someerr) _, _) ->
                        loop someerr acc tl
                    | ((IE_cont None _ as hd'), _s) ->
                        loop lasterropt [hd' :: acc] tl
                    ]
                ]
            ]
          in
            if lst = []
            then IO.return & `Last_error Itlist_empty
            else loop None [] lst
        ;

        value get_any_done lst =
          loop lst
          where rec loop lst =
            match lst with
            [ [ ((IE_done _) as x) :: _ ] -> Some x
            | [] -> None
            | [ (IE_cont _ _) :: _ ] -> loop lst
            ]
        ;

        value ie_cont k = IE_cont None k
        ;

        value ie_contM k = IO.return (IE_cont None k, empty_stream)
        ;


        value itlist_anyresult_lasterror
          (lst : list (iteratee 'el 'a))
         :
          iteratee 'el 'a
         =
          match get_any_done lst with
          [ Some x -> x
          | None -> ie_cont & step lst
              where rec step lst s =
                itlist_step_firstresult_lasterror lst s >>% fun
                [ `First_result r -> IO.return r
                | `Last_error e -> IO.error e
                | `Cont lst -> ie_contM & step lst
                ]
          ]
        ;


        module type SIGNED_INT
         =
          sig
            type t;
            value max_int : t;
            (* min_int = -max_int - 1 *)

            (* must work for small ints and small numbers:t : *)
            value of_int : int -> t;
            value to_int : t -> int;

            (* may overflow silently: *)
            value ( + ) : t -> t -> t;
            value ( - ) : t -> t -> t;
            value ( * ) : t -> t -> t;

            (* should truncate towards zero: *)
            value ( / ) : t -> t -> t;

            value ( <? ) : t -> t -> bool;
            value ( =? ) : t -> t -> bool;
          end
        ;

        module SInt_T : SIGNED_INT with type t = int
         =
          struct
            type t = int;
            value max_int = Pervasives.max_int;
            value of_int x = x;
            value to_int x = x;
            value ( + ) = Pervasives.( + );
            value ( - ) = Pervasives.( - );
            value ( * ) = Pervasives.( * );
            value ( / ) = Pervasives.( / );
            value ( <? ) = Pervasives.( < );
            value ( =? ) = Pervasives.( == );
          end
        ;

        module SInt64_T : SIGNED_INT with type t = int64
         =
          struct
            type t = int64;
            value max_int = Int64.max_int;
            value of_int = Int64.of_int;
            value to_int = Int64.to_int;
            value ( + ) = Int64.add;
            value ( - ) = Int64.sub;
            value ( * ) = Int64.mul;
            value ( / ) = Int64.div;
            value ( <? ) a b = (Int64.compare a b) < 0;
            value ( =? ) a b = (Int64.compare a b) = 0;
          end
        ;

        exception SInt_overflow;
        exception SInt_not_a_number of string;

        module SInt_F (S : SIGNED_INT)
         :
          sig
            (* value digits : S.t -> int; *)

            value read_unsigned_gen : ~allow0:bool -> iteratee char S.t;
          end
         =
          struct
            open S;

            value zero = of_int 0
            ;

            value ( ~- ) n = zero - n
              and ( >? ) a b = not (a <? b) && not (a =? b)
              and ( >=? ) a b = not (a <? b)
              and ( <>? ) a b = not (a =? b)
            ;

            value ten = of_int 10
            ;

            value rec digits n =
              Pervasives.( + )
                1
                (let n' = n / ten in
                 if n' =? zero
                 then 0
                 else digits n'
                )
            ;

            value rem a b = (a - (a / b) * b)
            ;

            module P = Pervasives;

            value string_reverse_inplace str =
              let len = String.length str in
              let len1 = P.( - ) len 1 in
              let len2 = P.( / ) len 2 in
              ( for i = 0 to len2
                do
                  let j = P.( - ) len1 i in
                  let tmp = str.[i] in
                  ( str.[i] := str.[j]
                  ; str.[j] := tmp
                  )
                done
              ; str
              )
            ;

            (* value min_int_digits = digits min_int; *)
            value max_int_digits = digits max_int;

            value to_base b n =
              let buf = Buffer.create max_int_digits in
              let intb = to_int b in
              let digit n =
                let n = to_int n in
                ( assert (n >= 0 && n < intb)
                ; assert (n < 10)
                ; Char.chr (P.( + ) n (Char.code '0'))
                ) in
              let rec loop n =
                let d = rem n b in
                let () = Buffer.add_char buf (digit d) in
                let n' = n / b in
                if n' =? zero
                then string_reverse_inplace (Buffer.contents buf)
                else loop n'
              in
                loop n
            ;

            value to_dec = to_base ten
            ;

            value max_int_dec = to_dec max_int;

            value from_base_neg b maxstr str =
              let len = String.length str in
              let rec loop acc i =
                if i = len
                then acc
                else
                  let digit ch =
                    if (ch >= '0' && ch <= '9')
                    then
                      let d = of_int (P.( - ) (Char.code ch) (Char.code '0')) in
                      if d >=? b
                      then raise (SInt_not_a_number "")
                      else d
                    else assert False
                  in
                  let ch = str.[i] in
                  let acc' = acc * b - digit ch in
                  loop acc' (P.( + ) i 1)
              in
                if len = 0
                then `Empty
                else
                let maxlen = String.length maxstr in
                if len > maxlen
                then
                  let () = dbg "(from_base: len>maxlen) %!" in
                  `Overflow
                else if len = maxlen && str > maxstr
                then
                  let () = dbg "(from_base: str>maxstr) %!" in
                  `Overflow
                else
                  try
                    `Ok (loop zero 0)
                  with
                  [ SInt_not_a_number _ -> `Not_a_number ]
            ;

            value from_dec_neg = from_base_neg ten max_int_dec
            ;

            value is_digit c = (c <= '9' && c >= '0')
            ;

            value is_not_digit c = not (is_digit c)
            ;

            (* to iteratees: *)
            value junk = drop 1
            ;

            value inan msg = I.throw_err (SInt_not_a_number msg)
            ;

            value peek_digit =
              peek >>= fun optc ->
              I.return (
                match optc with
                [ Some c when is_digit c -> optc
                | None | Some _ -> None
                ]
              )
            ;

            value read_unsigned_gen
              ~allow0
             :
              iteratee char S.t
             =
              let rec read_beginning ~read0 =
                peek_digit >>= fun optd ->
                match optd with
                [ None ->
                    if read0
                    then I.return (Some zero)
                    else inan "begins with not a digit"
                | Some d ->
                    match (d, read0, allow0) with
                    [ ('0', _, True)
                    | ('0', False, False) ->
                      junk >>= fun () ->
                      read_beginning ~read0:True
                    | (_, True, False) -> inan "leading zeroes"
                    | (_, False, _) -> I.return None
                    | (_, True, True) -> I.return None
                    ]
                ]
              in
              read_beginning ~read0:False >>= fun
              [ Some r -> I.return r
              | None ->
                   (I.limit max_int_digits &
                    I.break_chars is_not_digit
                   ) >>= fun it ->
                   I.joinI (I.return it) >>= fun res ->
                   peek_digit >>= fun optd ->
                   match (it, res, optd) with
                   [ (I.IE_done _, _, Some _) ->
                       assert False
                       (* так как limit должен был выдать IE_cont *)
                   | (I.IE_cont (Some _) _, _, _) ->
                       assert False
                       (* так как joinI кинет эту ошибку сам *)
                   | (I.IE_done str, _, None)
                   | (I.IE_cont None _, str, None) ->
                       let () = assert
                         (String.length str <= max_int_digits) in
                       match from_dec_neg str with
                       [ `Not_a_number -> assert False
                       | `Empty -> assert False
                       | `Ok r -> I.return (-r)
                       | `Overflow -> I.throw_err SInt_overflow
                       ]

                   | (IE_cont _ _, _, Some _) ->
                       let () = dbg "(read_gen: cont/digit) %!" in
                       I.throw_err SInt_overflow
                   ]
              ]
            ;

          end
        ;

        module SInt = SInt_F(SInt_T)
        ;

        module SInt64 = SInt_F(SInt64_T)
        ;

        (* leading zeroes = error *)
        value read_uint_nz
         : I.iteratee char int
         =
          SInt.read_unsigned_gen ~allow0:False
        ;

        value read_uint =
          SInt.read_unsigned_gen ~allow0:True
        ;

        (* leading zeroes = error *)
        value read_uint64_nz
         : I.iteratee char int64
         =
          SInt64.read_unsigned_gen ~allow0:False
        ;

        value read_uint64 =
          SInt64.read_unsigned_gen ~allow0:True
        ;

      end
    ;

    open It_add
    ;

    value read_uint = read_uint;
    value read_uint_nz = read_uint_nz;
    value read_uint64 = read_uint64;
    value read_uint64_nz = read_uint64_nz;


    value itpair_anyresult_lasterror it1 it2 =
      itlist_anyresult_lasterror [it1; it2]
    ;


    exception Dumbstreaming of string
    ;

    value ds_error fmt = Printf.ksprintf
      (fun s -> I.throw_err (Dumbstreaming s))
      fmt
    ;

    value ( >>= ) m f = I.bindI f m
    ;

    value read_the_char c =
      let err txt = ds_error "read_char: %C expected, %s found" c in
      I.peek >>= fun
      [ Some c' ->
          if c == c'
          then
            I.drop 1
          else
            err & sprintf "%C" c'
      | None ->
          err "eof"
      ]
    ;

    value read_space = read_the_char '\x20'
      and read_x0A = read_the_char '\x0A'
    ;


    value read_data_lens ~get_piece_it ~combine_it ~ntotal lens =
      loop ~combine_it ~npart:0
      where rec loop ~combine_it ~npart =
        match lens with
        [ [] -> I.joinI (I.return combine_it)
        | [piece_len :: lens] ->
            let this_piece_it = get_piece_it
              ~ntotal ~npart ~nbytes:piece_len in
            I.joinI (I.take piece_len this_piece_it) >>= fun piece_res ->

            .. скормить piece_res, идти дальше.

            combine_it ..


        ]
    ;


    value read_data ~get_piece_it ~combine_it packet_length lens =
      let sum_lens = List.fold_left Int64.add 0L
        (List.map Int64.of_int lens) in
      if packet_length <> sum_lens
      then ds_error
        "total length (%Li) is not equal to sum of pieces' lengths (%Li)"
          packet_length sum_lens
      else
        read_data_lens ~get_piece_it ~combine_it lens
    ;


    value read_lengths count : I.iteratee char (list int) =

      let read_len
       : I.iteratee char int
       = read_space >>= fun () -> read_uint
      in

      let enumerate_over_lens
       : I.iteratee int (list int)
         -> I.iteratee char (I.iteratee int (list int))
       = I.sequence_stream read_len
      in

      let list_of_count
       : I.iteratee int (list int)
       = I.joinI (I.take count I.stream2list)
      in

      I.joinI (enumerate_over_lens list_of_count)

(* ==
      I.joinI
        ( (I.sequence_stream (read_space >>= fun () -> read_uint))
          (I.joinI (I.take count I.stream2list))
        )
*)
    ;


    value int_of_int64 =
      let max = Int64.of_int Pervasives.max_int
      and min = Int64.of_int Pervasives.min_int in
      fun msg x ->
        if x < min || x > max
        then ds_error "int_of_int64: %s" msg
        else I.return (Int64.to_int x)
    ;

    value read_some ~get_piece_it ~combine_it =
      read_uint64 >>= fun packet_length ->
      let read_data_gen = read_data ~get_piece_it ~combine_it
      in
      let read_ver1 () =
        int_of_int64 "read_ver1" packet_length >>= fun pl ->
        read_data_gen packet_length [pl]

      and read_ver2 () =
        read_uint >>= fun count ->
        let () = assert (count >= 0) in
        read_lengths count >>= fun lengths ->
        let lengths_count = List.length lengths in
        if lengths_count < count
        then ds_error "too few pieces' lengths: expected %i, got %i"
                      count lengths_count
        else
        let () = assert (count = List.length lengths) in
        read_x0A >>= fun () ->
        read_data_gen packet_length lengths

      in
      I.peek >>= fun
      [ Some '\x20' -> junk >>= read_ver2
      | Some '\x0A' -> junk >>= read_ver1
      | Some _ | None -> ds_error
          "space or \\x0A expected after packet length"
      ]
    ;

    value read ~get_piece_it ~combine_it =
      I.peek >>= fun
      [ None | Some '\x0A' -> I.return None
      | Some _ ->
          I.catch
            (fun () ->
               read_some ~get_piece_it ~combine_it >>= fun r ->
               I.return (Some r)
            )
            (fun e -> ds_error "%s" & Printexc.to_string e
            )
      ]
    ;

  end
;
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.