Source file csv.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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
#1 "src/csv.pp.ml"
include Csv_utils
module Row = Csv_row.Row
type t = string list list
class type in_obj_channel =
object
method input : Bytes.t -> int -> int -> int
method close_in : unit -> unit
end
class type out_obj_channel =
object
method output : Bytes.t -> int -> int -> int
method close_out : unit -> unit
end
exception Failure of int * int * string
let buffer_len = 0x1FFF
type std_in_channel = in_channel
let std_input = input
let std_close_in = close_in
type in_channel = {
in_chan : in_obj_channel;
in_buf : Bytes.t;
mutable in0 : int;
mutable in1 : int;
mutable end_of_file : bool;
current_field : Buffer.t;
mutable record : string list;
mutable record_n : int;
has_header : bool;
mutable header : Header.t;
separator : char;
backslash_escape : bool;
excel_tricks : bool;
fix: bool;
is_space : char -> bool;
lstrip_buffer : Buffer.t -> unit;
rstrip_substring : Bytes.t -> int -> int -> string;
rstrip_contents : Buffer.t -> string;
}
let fill_in_buf_or_Eof ic =
if ic.end_of_file then raise End_of_file
else if ic.in0 >= ic.in1 then begin
ic.in0 <- 0;
try
ic.in1 <- ic.in_chan#input ic.in_buf 0 buffer_len;
with End_of_file ->
ic.end_of_file <- true;
raise End_of_file
end
let rec add_if_satisfy ic predicate i =
if i >= ic.in1 then (
Buffer.add_subbytes ic.current_field ic.in_buf ic.in0 (i - ic.in0);
ic.in0 <- i;
fill_in_buf_or_Eof ic;
add_if_satisfy ic predicate 0
)
else
let c = Bytes.unsafe_get ic.in_buf i in
if predicate c then
add_if_satisfy ic predicate (i + 1)
else (
Buffer.add_subbytes ic.current_field ic.in_buf ic.in0 (i - ic.in0);
ic.in0 <- i;
()
)
let add_spaces ic = add_if_satisfy ic ic.is_space ic.in0
let has_next_field ic =
assert(ic.in0 < ic.in1);
let c = Bytes.unsafe_get ic.in_buf ic.in0 in
ic.in0 <- ic.in0 + 1;
if c = '\r' then (
try fill_in_buf_or_Eof ic;
if Bytes.unsafe_get ic.in_buf ic.in0 = '\n' then
ic.in0 <- ic.in0 + 1;
(false)
with End_of_file -> (false))
else (c = ic.separator)
let rec seek_unquoted_separator ic i =
if i >= ic.in1 then (
Buffer.add_subbytes ic.current_field ic.in_buf ic.in0 (i - ic.in0);
ic.in0 <- i;
fill_in_buf_or_Eof ic;
seek_unquoted_separator ic 0
)
else
let c = Bytes.unsafe_get ic.in_buf i in
if c = ic.separator || c = '\n' || c = '\r' then (
if Buffer.length ic.current_field = 0 then
ic.record <- ic.rstrip_substring ic.in_buf ic.in0 (i - ic.in0)
:: ic.record
else (
Buffer.add_subbytes ic.current_field ic.in_buf ic.in0 (i - ic.in0);
ic.record <- ic.rstrip_contents ic.current_field :: ic.record
);
ic.in0 <- i;
has_next_field ic
)
else seek_unquoted_separator ic (i+1)
let add_unquoted_field ic =
try seek_unquoted_separator ic ic.in0
with End_of_file ->
ic.record <- ic.rstrip_contents ic.current_field :: ic.record;
(false)
let rec examine_quoted_field ic field_no after_final_quote
~after_bad_quote i =
if i >= ic.in1 then (
Buffer.add_subbytes ic.current_field ic.in_buf ic.in0 (i - ic.in0);
ic.in0 <- i;
fill_in_buf_or_Eof ic;
examine_quoted_field ic field_no after_final_quote ~after_bad_quote 0
)
else
let c = Bytes.unsafe_get ic.in_buf i in
if c = '\"' then (
after_final_quote := true;
Buffer.add_subbytes ic.current_field ic.in_buf ic.in0 (i - ic.in0);
ic.in0 <- i + 1;
fill_in_buf_or_Eof ic;
let c = Bytes.unsafe_get ic.in_buf ic.in0 in
if c = ic.separator || c = '\n' || c = '\r' then (
ic.record <- Buffer.contents ic.current_field :: ic.record;
has_next_field ic
)
else if c = '\"' then (
Buffer.add_char ic.current_field '\"';
ic.in0 <- ic.in0 + 1;
let len_field = Buffer.length ic.current_field in
add_spaces ic;
let c = Bytes.unsafe_get ic.in_buf ic.in0 in
if after_bad_quote
&& (c = ic.separator || c = '\n' || c = '\r') then (
ic.record <- Buffer.sub ic.current_field 0 len_field :: ic.record;
has_next_field ic
)
else (
after_final_quote := false;
examine_quoted_field ic field_no after_final_quote
~after_bad_quote ic.in0
)
)
else if ic.excel_tricks && c = '0' then (
after_final_quote := false;
Buffer.add_char ic.current_field '\000';
ic.in0 <- ic.in0 + 1;
examine_quoted_field ic field_no after_final_quote
~after_bad_quote ic.in0
)
else if ic.is_space c || ic.fix then (
let len_field = Buffer.length ic.current_field in
Buffer.add_char ic.current_field '\"';
add_spaces ic;
let c = Bytes.unsafe_get ic.in_buf ic.in0 in
if c = ic.separator || c = '\n' || c = '\r' then (
ic.record <- Buffer.sub ic.current_field 0 len_field :: ic.record;
has_next_field ic
)
else if ic.fix then (
after_final_quote := false;
examine_quoted_field ic field_no after_final_quote
~after_bad_quote:(not after_bad_quote) ic.in0
)
else raise(Failure(ic.record_n, field_no,
"Non-space char after closing the quoted field"))
)
else raise(Failure(ic.record_n, field_no, "Bad '\"' in quoted field"))
)
else if ic.backslash_escape && c = '\\' then (
Buffer.add_subbytes ic.current_field ic.in_buf ic.in0 (i - ic.in0);
ic.in0 <- i + 1;
fill_in_buf_or_Eof ic;
let c = Bytes.unsafe_get ic.in_buf ic.in0 in
Buffer.add_char ic.current_field unescape.(Char.code c);
ic.in0 <- ic.in0 + 1;
examine_quoted_field ic field_no after_final_quote
~after_bad_quote ic.in0
)
else examine_quoted_field ic field_no after_final_quote
~after_bad_quote (i+1)
let add_quoted_field ic field_no =
let after_final_quote = ref false in
try examine_quoted_field ic field_no after_final_quote
~after_bad_quote:false ic.in0
with End_of_file ->
ic.record <- Buffer.contents ic.current_field :: ic.record;
if !after_final_quote || ic.fix then
(false)
else raise(Failure(ic.record_n, field_no,
"Quoted field closed by end of file"))
let add_next_field ic field_no =
Buffer.clear ic.current_field;
try
add_spaces ic;
let c = Bytes.unsafe_get ic.in_buf ic.in0 in
if c = '\"' then (
ic.in0 <- ic.in0 + 1;
Buffer.clear ic.current_field;
add_quoted_field ic field_no
)
else if ic.excel_tricks && c = '=' then (
ic.in0 <- ic.in0 + 1;
try
fill_in_buf_or_Eof ic;
if Bytes.unsafe_get ic.in_buf ic.in0 = '\"' then (
ic.in0 <- ic.in0 + 1;
add_quoted_field ic field_no
)
else (
ic.lstrip_buffer ic.current_field;
Buffer.add_char ic.current_field '=';
add_unquoted_field ic
)
with End_of_file ->
ic.record <- "=" :: ic.record;
(false)
)
else (
ic.lstrip_buffer ic.current_field;
add_unquoted_field ic
)
with End_of_file ->
ic.record <- "" :: ic.record;
(false)
let rec add_all_record_fields ic ~more_fields ~field_no =
if more_fields then (
let more = add_next_field ic field_no in
add_all_record_fields ic ~more_fields:more ~field_no:(field_no + 1)
)
else ()
let next ic =
if ic.in1 < 0 then raise(Sys_error "Bad file descriptor")
else (
fill_in_buf_or_Eof ic;
ic.record <- [];
ic.record_n <- ic.record_n + 1;
add_all_record_fields ic ~more_fields:true ~field_no:1;
ic.record <- List.rev ic.record;
(ic.record)
)
let current_record ic = ic.record
let fold_left ~f ~init:a0 ic =
let a = ref a0 in
try
while true do
a := f !a (next ic)
done;
assert false
with End_of_file -> !a
let iter ~f ic =
try while true do f (next ic) done;
with End_of_file -> ()
let input_all ic =
let records = fold_left ~f:(fun l r -> (r :: l)) ~init:[] ic in
(List.rev records)
let fold_right ~f ic a0 =
let lr = fold_left ~f:(fun l r -> (r :: l)) ~init:[] ic in
List.fold_left (fun a r -> f r a) a0 lr
let of_in_obj ?(separator=',') ?(strip=true) ?(=false) ?
?(backslash_escape=false) ?(excel_tricks=true) ?(fix=false)
in_chan =
if separator = '\n' || separator = '\r' then
invalid_arg "Csv (input): the separator cannot be '\\n' or '\\r'";
let ic = {
in_chan = in_chan;
in_buf = Bytes.create buffer_len;
in0 = 0;
in1 = 0;
end_of_file = false;
current_field = Buffer.create 0xFF;
record = [];
record_n = 0;
has_header = has_header || header <> None;
header = Header.empty;
separator = separator;
backslash_escape;
excel_tricks = excel_tricks;
fix = fix;
is_space = (if separator = '\t' then is_real_space else is_space_or_tab);
lstrip_buffer = (if strip then Buffer.clear else do_nothing);
rstrip_substring = (if strip then rstrip_substring else Bytes.sub_string);
rstrip_contents = (if strip then rstrip_contents else Buffer.contents);
} in
if has_header then (
try
let names = next ic in
let h = Header.of_names names in
let h = match header with
| None -> h
| Some h0 -> Header.merge ~main:(Header.of_names h0) h in
{ ic with header = h }
with End_of_file | Failure _ -> (ic)
)
else (
match header with
| None -> (ic)
| Some h0 -> { ic with header = Header.of_names h0 }
)
let of_channel ?separator ?strip ? ?
?backslash_escape ?excel_tricks ?fix fh =
of_in_obj ?separator ?strip ?has_header ?header
?backslash_escape ?excel_tricks ?fix
(object
val fh = fh
method input s ofs len =
try
let r = std_input fh s ofs len in
if r = 0 then raise End_of_file;
r
with Sys_blocked_io -> 0
method close_in() = std_close_in fh
end)
let of_string ?separator ?strip ? ?
?backslash_escape ?excel_tricks ?fix str =
of_in_obj ?separator ?strip ?has_header ?header
?backslash_escape ?excel_tricks ?fix
(object
val mutable position = 0
method input buf ofs len =
if position >= String.length str
then raise End_of_file
else
( let actual = min len (String.length str - position) in
String.blit str position buf ofs actual ;
position <- position + actual ;
actual )
method close_in() = ()
end)
let close_in ic =
if ic.in1 >= 0 then begin
ic.in0 <- 0;
ic.in1 <- -1;
ic.in_chan#close_in();
end
else ()
let to_in_obj ic =
object
val ic = ic
method input buf ofs len =
if ofs < 0 || len < 0 || ofs + len > Bytes.length buf
then invalid_arg "Csv.to_in_obj#input";
if ic.in1 < 0 then raise(Sys_error "Bad file descriptor");
fill_in_buf_or_Eof ic;
let r = min len (ic.in1 - ic.in0) in
Bytes.blit ic.in_buf ic.in0 buf ofs r;
ic.in0 <- ic.in0 + r;
r
method close_in() = close_in ic
end
let load ?separator ?strip ?backslash_escape ?excel_tricks ?fix fname =
let fh = if fname = "-" then stdin
else
open_in fname in
let csv = of_channel ?separator ?strip ?backslash_escape
?excel_tricks ?fix fh in
let t = input_all csv in
close_in csv;
(t)
let load_in ?separator ?strip ?backslash_escape ?excel_tricks ?fix ch =
let fh = of_channel ?separator ?strip ?backslash_escape
?excel_tricks ?fix ch in
input_all fh
let load_rows ?separator ?strip ?backslash_escape ?excel_tricks ?fix f ch =
iter ~f (of_channel ?separator ?strip ?backslash_escape ?excel_tricks
?fix ch)
let must_escape = Array.make 256 false
let () =
List.iter (fun c -> must_escape.(Char.code c) <- true)
['\"'; '\\'; '\000'; '\b'; '\n'; '\r'; '\t'; '\026']
let escape =
let escape_of c =
match Char.unsafe_chr c with
| '\000' -> '0'
| '\b' -> 'b'
| '\n' -> 'n'
| '\r' -> 'r'
| '\t' -> 't'
| '\026' -> 'Z'
| c -> c in
Array.init 256 escape_of
type std_out_channel = out_channel
let std_close_out = close_out
type out_channel = {
out_chan : out_obj_channel;
out_separator : char;
out_separator_bytes : Bytes.t;
out_backslash_escape : bool;
out_excel_tricks : bool;
quote_all: bool;
}
let to_out_obj ?(separator=',') ?(backslash_escape=false) ?(excel_tricks=false)
?(quote_all=false) out_chan =
if separator = '\n' || separator = '\r' then
invalid_arg "Csv (output): the separator cannot be '\\n' or '\\r'";
{
out_chan = out_chan;
out_separator = separator;
out_separator_bytes = Bytes.make 1 separator;
out_backslash_escape = backslash_escape;
out_excel_tricks = excel_tricks;
quote_all = quote_all;
}
let to_channel ?separator ?backslash_escape ?excel_tricks ?quote_all fh =
to_out_obj ?separator ?backslash_escape ?excel_tricks ?quote_all
(object
val fh = fh
method output s ofs len = output fh s ofs len; len
method close_out () = close_out fh
end)
let to_buffer ?separator ?backslash_escape ?excel_tricks ?quote_all buf =
to_out_obj ?separator ?backslash_escape ?excel_tricks ?quote_all
(object
method output s ofs len = Buffer.add_subbytes buf s ofs len; len
method close_out () = ()
end)
let close_out oc =
oc.out_chan#close_out()
let rec really_output oc s ofs len =
let w = oc.out_chan#output s ofs len in
if w < len then really_output oc s (ofs+w) (len-w)
else ()
let quote_bytes = Bytes.make 1 '\"'
let output_quote oc = really_output oc quote_bytes 0 1
let equal_quote_bytes = Bytes.make 2 '='
let () = Bytes.unsafe_set equal_quote_bytes 1 '\"'
let output_equal_quote oc = really_output oc equal_quote_bytes 0 2
let newline_bytes = Bytes.make 1 '\n'
let output_newline oc = really_output oc newline_bytes 0 1
let must_quote oc s len =
let quote = ref(is_space_or_tab(String.unsafe_get s 0)
|| is_space_or_tab(String.unsafe_get s (len - 1))) in
let n = ref 0 in
for i = 0 to len - 1 do
let c = String.unsafe_get s i in
if oc.out_backslash_escape && must_escape.(Char.code c) then (
quote := true;
incr n)
else if c = oc.out_separator || c = '\n' || c = '\r' then quote := true
else if c = '"' || (oc.out_excel_tricks && c = '\000') then (
quote := true;
incr n)
done;
if !quote then !n else -1
let need_excel_trick s len =
let c = String.unsafe_get s 0 in
is_space_or_tab c || c = '0' || is_space_or_tab(String.unsafe_get s (len - 1))
let write_escaped oc field =
if String.length field > 0 then begin
let len = String.length field in
let use_excel_trick = oc.out_excel_tricks && need_excel_trick field len
and n = must_quote oc field len in
if n < 0 && not use_excel_trick && not oc.quote_all then
really_output oc (Bytes.unsafe_of_string field) 0 len
else (
let field =
if n <= 0 then Bytes.unsafe_of_string field
else
let s = Bytes.create (len + n) in
let j = ref 0 in
for i = 0 to len - 1 do
let c = String.unsafe_get field i in
if oc.out_backslash_escape && must_escape.(Char.code c) then (
Bytes.unsafe_set s !j '\\'; incr j;
Bytes.unsafe_set s !j escape.(Char.code c); incr j
)
else if c = '"' then (
Bytes.unsafe_set s !j '"'; incr j;
Bytes.unsafe_set s !j '"'; incr j
)
else if oc.out_excel_tricks && c = '\000' then (
Bytes.unsafe_set s !j '"'; incr j;
Bytes.unsafe_set s !j '0'; incr j
)
else (Bytes.unsafe_set s !j c; incr j)
done;
s
in
(if use_excel_trick then output_equal_quote oc
else output_quote oc);
really_output oc field 0 (Bytes.length field);
output_quote oc
)
end
else if oc.quote_all then (output_quote oc; output_quote oc)
else ()
let output_record oc = function
| [] ->
output_newline oc
| [f] ->
write_escaped oc f;
output_newline oc
| f :: tl ->
write_escaped oc f;
List.iter (fun f ->
really_output oc oc.out_separator_bytes 0 1;
write_escaped oc f
) tl;
output_newline oc
let output_all oc t =
List.iter (fun r -> output_record oc r) t
let print ?separator ?backslash_escape ?excel_tricks ?quote_all t =
let csv = to_channel ?separator ?backslash_escape
?excel_tricks ?quote_all stdout in
output_all csv t;
flush stdout
let save_out ?separator ?backslash_escape ?excel_tricks ch t =
let csv = to_channel ?separator ?backslash_escape ?excel_tricks ch in
output_all csv t
let save ?separator ?backslash_escape ?excel_tricks ?quote_all fname t =
let ch =
open_out fname in
let csv = to_channel ?separator ?backslash_escape ?excel_tricks
?quote_all ch in
output_all csv t;
std_close_out ch
module Rows = struct
let ic = Header.names ic.header
let ?(replace=false) ic names =
let h0 = Header.of_names names in
ic.header <- if replace then h0 else Header.merge ~main:h0 ic.header
let current ic = Row.make ic.header ic.record
let next ic =
let record = next ic in
(Row.make ic.header record)
let fold_left ~f ~init:a0 ic =
let a = ref a0 in
try
while true do
a := f !a (next ic)
done;
assert false
with End_of_file -> !a
let iter ~f ic =
try while true do f (next ic) done;
with End_of_file -> ()
let input_all ic =
let records = fold_left ~f:(fun l r -> (r :: l)) ~init:[] ic in
(List.rev records)
let fold_right ~f ic a0 =
let lr = fold_left ~f:(fun l r -> (r :: l)) ~init:[] ic in
List.fold_left (fun a r -> f r a) a0 lr
let load ?separator ?strip ? ?
?backslash_escape ?excel_tricks ?fix fname =
let fh = if fname = "-" then stdin
else
open_in fname in
let csv = of_channel ?separator ?strip ?has_header ?header
?backslash_escape ?excel_tricks ?fix fh in
let t = input_all csv in
close_in csv;
(t)
end
#1 "src/csv_memory.ml"
let lines = List.length
let columns csv =
let m = ref 0 in
List.iter (fun row -> m := max !m (List.length row)) csv;
!m
let rec dropwhile f = function
| [] -> []
| x :: xs when f x -> dropwhile f xs
| xs -> xs
let rec empty_row = function
| [] -> true
| "" :: xs -> empty_row xs
| _ :: _ -> false
let trim ?(top=true) ?(left=true) ?(right=true) ?(bottom=true) csv =
let csv = if top then dropwhile empty_row csv else csv in
let csv =
if right then
List.map (fun row ->
let row = List.rev row in
let row = dropwhile ((=) "") row in
let row = List.rev row in
row) csv
else csv in
let csv =
if bottom then (
let csv = List.rev csv in
let csv = dropwhile empty_row csv in
let csv = List.rev csv in
csv
) else csv in
let and_empty_left_cell (col_empty, one_nonempty_row) = function
| [] -> col_empty, one_nonempty_row
| "" :: _ -> col_empty, true
| _ -> false, true in
let empty_left_col =
List.fold_left and_empty_left_cell (true, false) in
let remove_left_col =
List.map (function [] -> [] | _ :: xs -> xs) in
let rec loop csv =
let left_col_empty, one_nonempty_row = empty_left_col csv in
if left_col_empty && one_nonempty_row then
loop(remove_left_col csv)
else
csv
in
let csv = if left then loop csv else csv in
csv
let square csv =
let columns = columns csv in
List.map (
fun row ->
let n = List.length row in
let row = List.rev row in
let rec loop acc = function
| 0 -> acc
| i -> "" :: loop acc (i-1)
in
let row = loop row (columns - n) in
List.rev row
) csv
let is_square csv =
let columns = columns csv in
List.for_all (fun row -> List.length row = columns) csv
let rec set_columns ~cols = function
| [] -> []
| r :: rs ->
let rec loop i cells =
if i < cols then (
match cells with
| [] -> "" :: loop (succ i) []
| c :: cs -> c :: loop (succ i) cs
)
else []
in
loop 0 r :: set_columns ~cols rs
let rec set_rows ~rows csv =
if rows > 0 then (
match csv with
| [] -> [] :: set_rows ~rows:(pred rows) []
| r :: rs -> r :: set_rows ~rows:(pred rows) rs
)
else []
let set_size ~rows ~cols csv =
set_columns ~cols (set_rows ~rows csv)
let rec drop n = function
| _ :: l when n > 0 -> drop (n-1) l
| l -> l
let sub ~r ~c ~rows ~cols csv =
let csv = drop r csv in
let csv = List.map (drop c) csv in
let csv = set_rows ~rows csv in
let csv = set_columns ~cols csv in
csv
let rec compare_row (row1 : string list) row2 =
match row1, row2 with
| [], [] -> 0
| x :: xs, y :: ys ->
let c = compare x y in
if c <> 0 then c else compare_row xs ys
| "" :: xs , [] ->
compare_row xs []
| _ :: _, [] ->
1
| [], "" :: ys ->
compare_row [] ys
| [], _ :: _ ->
-1
let rec compare (csv1 : t) csv2 =
match csv1, csv2 with
| [], [] -> 0
| x :: xs, y :: ys ->
let c = compare_row x y in
if c <> 0 then c else compare xs ys
| x :: xs, [] ->
let c = compare_row x [] in
if c <> 0 then c else compare xs []
| [], y :: ys ->
let c = compare_row [] y in
if c <> 0 then c else compare [] ys
let rec concat = function
| [] -> []
| [csv] -> csv
| left_csv :: csvs ->
let right_csv = concat csvs in
let nr_rows = max (lines left_csv) (lines right_csv) in
let left_csv = set_rows ~rows:nr_rows left_csv in
let right_csv = set_rows ~rows:nr_rows right_csv in
let left_csv = square left_csv in
List.map (
fun (left_row, right_row) -> List.append left_row right_row
) (List.combine left_csv right_csv)
let transpose =
let rec row_of_1st_col tr_row empty = function
| [] -> (tr_row, empty)
| r :: rows ->
match !r with
| [] ->
let tr_row = if tr_row = [] then tr_row else "" :: tr_row in
row_of_1st_col tr_row empty rows
| a :: tl ->
r := tl;
let tr_row = if a = "" && tr_row = [] then [] else a :: tr_row in
row_of_1st_col tr_row false rows in
let rec tr tr_csv csv =
let row, empty = row_of_1st_col [] true csv in
if empty then List.rev tr_csv
else tr (row :: tr_csv) csv in
fun csv -> tr [] (List.rev_map ref csv)
let to_array csv =
Array.of_list (List.map Array.of_list csv)
let of_array csv =
List.map Array.to_list (Array.to_list csv)
let rec combine ~ row = match header, row with
| [], _ -> []
| _, [] -> List.map (fun h -> (h, "")) header
| h0 :: h, x :: r -> (h0, x) :: combine ~header:h r
let associate data =
List.map (fun row -> combine ~header row) data
let map ~f csv =
List.map (fun row -> List.map (fun el -> f el) row) csv
let rec save_out_row chan row ~length widths =
match row, widths with
| [], _ -> ()
| _, [] -> failwith "Csv.save_out_readable: internal error"
| [cell], _ -> output_string chan cell
| cell :: cells, width :: widths ->
output_string chan cell;
for _ = 1 to width - length cell + 1 do output_char chan ' ' done;
save_out_row chan cells ~length widths
let save_out_readable chan ?(length = String.length) csv =
let widths =
let csv = List.filter (function [_] -> false | _ -> true) csv in
let csv = square csv in
match csv with
| [] -> []
| row1 :: rest ->
let lengths_row1 = List.map length row1 in
let lengths_rest = List.map (List.map length) rest in
let max2rows r1 r2 =
let rp =
try List.combine r1 r2
with
Invalid_argument _ ->
failwith (Printf.sprintf "Csv.save_out_readable: internal \
error: length r1 = %d, length r2 = %d"
(List.length r1) (List.length r2)) in
List.map (fun ((a : int), (b : int)) -> max a b) rp
in
List.fold_left max2rows lengths_row1 lengths_rest in
List.iter (
function
| [cell] ->
output_string chan cell;
output_char chan '\n'
| row ->
save_out_row chan row widths ~length;
output_char chan '\n'
) csv
let print_readable = save_out_readable stdout