Source

dumbstreaming / dumbstreaming_it.ml

Full commit
  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
value dbg fmt = Printf.eprintf fmt
;
(*
value dbg fmt = Printf.ifprintf stdout fmt
;
*)

value ( & ) f x = f x
;

open Ds_types
;


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

    value read :
      ~get_piece_it :
       ( ~totalsize:int64 ->
         ~totalcount:int ->
         ~piecesize:int ->
         ~piecenumber:int ->
         I.iteratee char 'i
       )
      -> ~combine_it : (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

    value ie_cont k = I.IE_cont None k
    ;

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


    (* 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

        module IO = I.It_IO;

        value ( & ) f x = f x;

        value ( >>% ) = IO.bind_rev;

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

        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)
            ;

            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
    ;

    open Printf
    ;

    module IO = I.It_IO;
    open I.Ops;


    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 read_the_char c =
      let err txt = ds_error "read_char: %C expected, %s found" c txt 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 ie_doneM
     (x : 'a)
     (s : I.stream 'el)
     : IO.m (I.iteratee 'el 'a  *  I.stream 'el)
     = IO.return (I.IE_done x, s)
    ;


    value (read_data_lens :
      ~get_piece_it :
       ( ~totalsize:int64 -> ~totalcount:int ->
         ~piecesize:int -> ~piecenumber:int ->
         I.iteratee char 'i
       )
      -> ~combine_it : (I.iteratee 'i 'a)
      -> ~totalsize : int64
      -> ~lens : list int
      -> ~totalcount : int
      -> I.iteratee char 'a
    )
      ~get_piece_it
      ~combine_it
      ~totalsize
      ~lens
      ~totalcount
     =
      let rec read_data_lens ~combine_it ~lens ~piecenumber
       : I.iteratee char 'a
       =
        match (lens, combine_it) with
        [ ([], _) ->
           read_x0A >>= fun () ->
           I.joinI (I.return combine_it)
        | ([len :: lens], (I.IE_done _ | I.IE_cont (Some _) _)) ->
            I.drop len >>= fun () ->
            read_x0A >>= fun () ->
            read_data_lens ~combine_it ~lens ~piecenumber:(piecenumber + 1)
        | ([len :: lens], I.IE_cont None k) ->
            let this_piece_it : I.iteratee char 'i = get_piece_it
              ~totalsize ~piecenumber ~piecesize:len ~totalcount in
            (I.joinI & I.take len this_piece_it) >>= fun this_piece_res ->
            read_x0A >>= fun () ->

            I.lift (I.feedI k (I.chunk_of this_piece_res))
              >>= fun combine_it ->

            read_data_lens ~combine_it ~lens ~piecenumber:(piecenumber + 1)
        ]
      in
        read_data_lens ~combine_it ~piecenumber:0 ~lens
    ;


    value read_data ~get_piece_it ~combine_it ~totalsize ~lens =
      let sum_lens = List.fold_left Int64.add 0L
        (List.map Int64.of_int lens) in
      if totalsize <> sum_lens
      then ds_error
        "total length (%Li) is not equal to sum of pieces' lengths (%Li)"
          totalsize sum_lens
      else
        let totalcount = List.length lens in
        read_data_lens
          ~get_piece_it ~combine_it ~totalsize
          ~totalcount ~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 : I.iteratee _ _ =
      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 ~totalsize:packet_length ~lens:[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 ~totalsize:packet_length ~lens: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 :
       ( ~totalsize:int64 ->
         ~totalcount:int ->
         ~piecesize:int ->
         ~piecenumber:int ->
         I.iteratee char 'i
       )
      -> ~combine_it : (I.iteratee 'i 'a)
      -> I.iteratee char (option 'a)
    )
     ~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
;