/
batString.mlv
1324 lines (1194 loc) · 40.3 KB
/
batString.mlv
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
(*
* BatString - Additional functions for string manipulations.
* Copyright (C) 2003 Nicolas Cannasse
* 2008 David Teller
* 2008 Edgar Friendly
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
include String
let compare = String.compare
(*$T compare
compare "FOO" "bar" = -1
*)
let equal a b = String.compare a b = 0
let ord = BatOrd.ord String.compare
let init = BatBytesCompat.string_init
(*$T init
init 5 (fun i -> BatChar.chr (i + int_of_char '0')) = "01234";
*)
let starts_with str p =
let len = length p in
if length str < len then false
else
(* length str >= length p *)
let rec loop str p i =
if i = len then true
else
(* 0 <= i < length p *)
if unsafe_get str i <> unsafe_get p i then false
else loop str p (i + 1)
in loop str p 0
(*$T starts_with
starts_with "foobarbaz" "foob"
starts_with "foobarbaz" ""
starts_with "" ""
not (starts_with "bar" "foobar")
not (starts_with "" "foo")
starts_with "Jon \"Maddog\" Orwant" "Jon"
not (starts_with "Jon \"Maddog\" Orwant" "Jon \"Maddog\" Orwants")
not (starts_with "Jon \"Maddog\" Orwant" "Orwants")
*)
let ends_with str p =
let el = length p
and sl = length str in
let diff = sl - el in
(* diff = length str - length p *)
if diff < 0 then false (*string is too short*)
else
(* diff >= 0 *)
let rec loop str p diff i =
if i = el then true
else
(* 0 <= i < length p *)
(* diff = length str - length p ==> diff <= i + diff < length str *)
if unsafe_get str (diff + i) <> unsafe_get p i then false
else loop str p diff (i + 1)
in loop str p diff 0
(*$T ends_with
ends_with "foobarbaz" "rbaz"
ends_with "foobarbaz" ""
ends_with "" ""
not (ends_with "foo" "foobar")
not (ends_with "" "foo")
ends_with "Jon \"Maddog\" Orwant" "want"
not (ends_with "Jon \"Maddog\" Orwant" "I'm Jon \"Maddog\" Orwant")
not (ends_with "Jon \"Maddog\" Orwant" "Jon")
*)
let find_from str pos sub =
let len = length str in
let sublen = length sub in
if pos < 0 || pos > len then invalid_arg "String.find_from";
if sublen = 0 then pos else
let rec find ~str ~sub i =
if i > len - sublen then raise Not_found
else
(* 0 <= i <= length str - length sub *)
let rec loop ~str ~sub i j =
if j = sublen then i
else
(* 0 <= j < length sub *)
(* ==> 0 <= i + j < length str *)
if unsafe_get str (i + j) <> unsafe_get sub j
then find ~str ~sub (i + 1)
else loop ~str ~sub i (j + 1)
in loop ~str ~sub i 0
in find ~str ~sub pos
(*$Q find_from
(Q.triple Q.string Q.char Q.small_int) ~count:1000 (fun (s, c, ofs) -> \
let v1 = try `res (find_from s ofs (String.make 1 c)) with Not_found -> `nf | Invalid_argument _ -> `inv in \
let v2 = try `res (String.index_from s ofs c) with Not_found -> `nf | Invalid_argument _ -> `inv in \
(match v1, v2 with `res s1, `res s2 when s1 = s2 -> true | `nf, `nf | `inv, `inv -> true | _ -> false) \
)
(Q.triple Q.string Q.string Q.small_int) ~count:1000 (fun (s, s2, ofs) -> \
let v1 = try `res (ofs + find (String.sub s ofs (String.length s - ofs)) s2) with Not_found -> `nf | Invalid_argument _ -> `inv in \
let v2 = try `res (find_from s ofs s2) with Not_found -> `nf | Invalid_argument _ -> `inv in \
(match v1, v2 with `res s1, `res s2 when s1 = s2 -> true | `nf, `nf | `inv, `inv -> true | _ -> false) \
)
*)
(*$T find_from
find_from "foobarbaz" 4 "ba" = 6
find_from "foobarbaz" 7 "" = 7
try ignore (find_from "" 0 "a"); false with Not_found -> true
try ignore (find_from "foo" 2 "foo"); false with Not_found -> true
try ignore (find_from "foo" 3 "foo"); false with Not_found -> true
try ignore (find_from "foo" 4 "foo"); false with Invalid_argument _ -> true
try ignore (find_from "foo" (-1) "foo"); false with Invalid_argument _ -> true
*)
let find str sub = find_from str 0 sub
(*$T find
find "foobarbaz" "bar" = 3
try ignore (find "foo" "bar"); false with Not_found -> true
*)
let rfind_from str pos sub =
let sublen = length sub
and len = length str in
if pos + 1 < 0 || pos + 1 > len then invalid_arg "String.rfind_from";
(* 0 <= pos + 1 <= length str *)
if sublen = 0 then pos + 1 else
(* length sub > 0 *)
(* (pos + 1 - sublen) <= length str - length sub < length str *)
let rec find ~str ~sub i =
if i < 0 then raise Not_found
else
(* 0 <= i <= length str - length sub < length str *)
let rec loop ~str ~sub i j =
if j = sublen then i
else
(* 0 <= j < length sub *)
(* ==> 0 <= i + j < length str *)
if unsafe_get str (i + j) <> unsafe_get sub j
then find ~str ~sub (i - 1)
else loop ~str ~sub i (j + 1)
in loop ~str ~sub i 0
in find ~str ~sub (pos - sublen + 1)
(*$Q rfind_from
(Q.triple Q.string Q.char Q.small_int) ~count:1000 (fun (s, c, ofs) -> \
let v1 = try `res (rfind_from s ofs (String.make 1 c)) with Not_found -> `nf | Invalid_argument _ -> `inv in \
let v2 = try `res (String.rindex_from s ofs c) with Not_found -> `nf | Invalid_argument _ -> `inv in \
(match v1, v2 with `res s1, `res s2 when s1 = s2 -> true | `nf, `nf | `inv, `inv -> true | _ -> false) \
)
(Q.triple Q.string Q.string Q.small_int) ~count:1000 (fun (s, s2, ofs) -> \
let v1 = try `res (rfind (String.sub s 0 (ofs + 1)) s2) with Not_found -> `nf | Invalid_argument _ -> `inv in \
let v2 = try `res (rfind_from s ofs s2) with Not_found -> `nf | Invalid_argument _ -> `inv in \
(match v1, v2 with `res s1, `res s2 when s1 = s2 -> true | `nf, `nf | `inv, `inv -> true | _ -> false) \
)
*)
(*$T rfind_from
rfind_from "foobarbaz" 5 "ba" = 3
rfind_from "foobarbaz" 7 "ba" = 6
rfind_from "foobarbaz" 6 "ba" = 3
rfind_from "foobarbaz" 7 "" = 8
try ignore (rfind_from "" 3 ""); false with Invalid_argument _ -> true
try ignore (rfind_from "" (-1) "a"); false with Not_found -> true
try ignore (rfind_from "foobarbaz" 2 "ba"); false with Not_found -> true
try ignore (rfind_from "foo" 3 "foo"); false with Invalid_argument _ -> true
try ignore (rfind_from "foo" (-2) "foo"); false with Invalid_argument _ -> true
*)
let rfind str sub = rfind_from str (String.length str - 1) sub
(*$T rfind
rfind "foobarbaz" "ba" = 6
try ignore (rfind "foo" "barr"); false with Not_found -> true
*)
let index_after_n chr n str =
if n < 0 then raise (Invalid_argument "String.index_after_n: n < 0")
else
let rec loop n i =
if n = 0 then i
else
let i = String.index_from str i chr in
loop (n - 1) (i + 1)
in
loop n 0
(*$T index_after_n
index_after_n ',' 0 "aa,bb,cc" = 0
index_after_n ',' 1 "aa,bb,cc" = 3
index_after_n ',' 2 "aa,bb,cc" = 6
index_after_n ',' 0 "" = 0
index_after_n '-' 0 "aa,bb,cc" = 0
try ignore (index_after_n ',' (-1) "aa,bb,cc"); false with Invalid_argument _ -> true
try ignore (index_after_n ',' 3 "aa,bb,cc"); false with Not_found -> true
try ignore (index_after_n '-' 1 "aa,bb,cc"); false with Not_found -> true
index_after_n ',' 0 ",ab" = 0
index_after_n ',' 1 ",ab" = 1
index_after_n ',' 1 "a,,b" = 2
index_after_n ',' 2 "a,,b" = 3
index_after_n ',' 1 "a," = 2
*)
let find_all str sub =
(* enumerator *)
let rec next r () =
try
let i = find_from str !r sub in
r := i+1;
i
with Not_found -> raise BatEnum.No_more_elements
in
let count r () =
let n = ref 0 in
let r' = BatRef.copy r in
begin try while true do ignore (next r' ()); incr n; done;
with BatEnum.No_more_elements -> ();
end;
!n
in
let rec clone r () = make (BatRef.copy r)
and make r = BatEnum.make ~next:(next r) ~count:(count r) ~clone:(clone r)
in
let r = ref 0 in
make r
(*$T find_all
find_all "aaabbaabaaa" "aa" |> List.of_enum = [0;1;5;8;9]
find_all "abcde" "bd" |> List.of_enum = []
find_all "baaaaaaaaaaaaaaaaaaaab" "baa" |> List.of_enum = [0]
find_all "aaabbaabaaa" "aa" |> Enum.skip 1 |> Enum.clone \
|> List.of_enum = [1;5;8;9]
find_all "aaabbaabaaa" "aa" |> Enum.skip 1 |> Enum.count = 4
find_all "" "foo" |> BatEnum.is_empty
let e = find_all "aaabbaabaaa" "aa" in \
Enum.drop 2 e; let e' = Enum.clone e in \
(List.of_enum e = [5;8;9]) && (Enum.skip 1 e' |> List.of_enum = [8;9])
*)
let count_string str sub =
if sub = "" then invalid_arg "String.count_string";
let m = length str in
let n = length sub in
let rec loop acc i =
if i >= m then
acc
else
try
let j = find_from str i sub in
loop (acc + 1) (j + n)
with Not_found -> acc
in
loop 0 0
(*$T count_string
try let _ = count_string "abc" "" in false with Invalid_argument _ -> true
count_string "aaa" "a" = 3
count_string "aaa" "aa" = 1
count_string "coucou" "cou" = 2
*)
let exists str sub =
try
ignore (find str sub);
true
with
Not_found -> false
(*$T exists
exists "foobarbaz" "obar"
exists "obar" "obar"
exists "foobarbaz" ""
exists "" ""
not (exists "foobar" "obb")
not (exists "" "foo")
exists "a" ""
not (exists "" "a")
exists "ab" "a"
exists "ab" "b"
not (exists "ab" "c")
*)
let strip_default = " \t\r\n"
let strip ?(chars = strip_default) s =
let p = ref 0 in
let l = length s in
while !p < l && contains chars (unsafe_get s !p) do
incr p;
done;
let p = !p in
let l = ref (l - 1) in
while !l >= p && contains chars (unsafe_get s !l) do
decr l;
done;
sub s p (!l - p + 1)
(*$T strip
strip ~chars:" ,()" " boo() bar()" = "boo() bar"
strip ~chars:"abc" "abbcbab" = ""
*)
let left s len =
if len >= length s then s else sub s 0 len
let right s len =
let slen = length s in
if len >= slen then s else sub s (slen - len) len
let head s pos =
left s pos
let tail s pos =
let slen = length s in
if pos >= slen then "" else sub s pos (slen - pos)
(*$T left
left "abc" 1 = "a"
left "ab" 3 = "ab"
left "abc" 3 = "abc"
left "abc" 10 = "abc"
left "abc" 0 = ""
*) (*$T right
right "abc" 1 = "c"
right "ab" 3 = "ab"
right "abc" 3 = "abc"
right "abc" 0 = ""
right "abc" 10 = "abc"
*) (*$T tail
tail "abc" 1 = "bc"
tail "ab" 3 = ""
tail "abc" 3 = ""
tail "abc" 10 = ""
tail "abc" 0 = "abc"
*) (*$T head
head "abc" 0 = ""
head "abc" 10 = "abc"
head "abc" 3 = "abc"
*)
let split str ~by:sep =
let p = find str sep in
let len = length sep in
let slen = length str in
sub str 0 p, sub str (p + len) (slen - p - len)
(*$T split
split "abcGxyzG123" ~by:"G" = ("abc","xyzG123")
split "abcGHIzyxGHI123" ~by:"GHI" = ("abc", "zyxGHI123")
split "abcGHIzyxGHI123" ~by:"" = ("", "abcGHIzyxGHI123")
try split "abcxyz" ~by:"G" |> ignore; false with Not_found -> true
split "abcabc" ~by:"abc" = ("", "abc")
split "abcabcd" ~by:"abcd" = ("abc", "")
*)
let rsplit str ~by:sep =
let p = rfind str sep in
let len = length sep in
let slen = length str in
sub str 0 p, sub str (p + len) (slen - p - len)
(*$T rsplit
rsplit "abcGxyzG123" ~by:"G" = ("abcGxyz","123")
rsplit "abcGHIzyxGHI123" ~by:"GHI" = ("abcGHIzyx", "123")
rsplit "abcGHIzyxGHI123" ~by:"" = ("abcGHIzyxGHI123", "")
try rsplit "abcxyz" ~by:"G" |> ignore; false with Not_found -> true
*)
(*
An implementation of [nsplit] in one pass.
This implementation traverses the string backwards, hence building the list
of substrings from the end to the beginning, so as to avoid a call to [List.rev].
*)
let nsplit str ~by:sep =
if str = "" then []
else if sep = "" then invalid_arg "String.nsplit: empty sep not allowed"
else
(* str is non empty *)
let seplen = String.length sep in
let rec aux acc ofs =
if ofs >= 0 then (
match
try Some (rfind_from str ofs sep)
with Not_found -> None
with
| Some idx -> (* sep found *)
let end_of_sep = idx + seplen - 1 in
if end_of_sep = ofs (* sep at end of str *)
then aux (""::acc) (idx - 1)
else
let token = sub str (end_of_sep + 1) (ofs - end_of_sep) in
aux (token::acc) (idx - 1)
| None -> (* sep NOT found *)
(sub str 0 (ofs + 1))::acc
)
else
(* Negative ofs: the last sep started at the beginning of str *)
""::acc
in
aux [] (length str - 1 )
(*$T nsplit
nsplit "a;b;c" ~by:";" = ["a"; "b"; "c"]
nsplit "" ~by:"x" = []
try nsplit "abc" ~by:"" = ["a"; "b"; "c"] with Invalid_argument _ -> true
nsplit "a/b/c" ~by:"/" = ["a"; "b"; "c"]
nsplit "/a/b/c//" ~by:"/" = [""; "a"; "b"; "c"; ""; ""]
nsplit "FOOaFOObFOOcFOOFOO" ~by:"FOO" = [""; "a"; "b"; "c"; ""; ""]
*)
let split_on_char sep str =
if str = "" then []
else
(* str is non empty *)
let rec loop acc ofs limit =
if ofs < 0 then sub str 0 limit :: acc
(* ofs >= 0 && ofs < length str *)
else if unsafe_get str ofs <> sep then loop acc (ofs - 1) limit
else loop (sub str (ofs + 1) (limit - ofs - 1) :: acc) (ofs - 1) ofs
in
let len = length str in loop [] (len - 1) len
(*$T split_on_char
split_on_char ';' "a;b;c" = ["a"; "b"; "c"]
split_on_char 'x' "" = []
split_on_char '/' "a/b/c" = ["a"; "b"; "c"]
split_on_char '/' "/a/b/c//" = [""; "a"; "b"; "c"; ""; ""]
*)
let cut_on_char chr pos str =
let i = index_after_n chr pos str in
let j = match index_from_opt str i chr with
| None -> length str
| Some valid_index -> valid_index
in
sub str i (j - i)
(*$T cut_on_char
cut_on_char ',' 0 "aa,bb,cc" = "aa"
cut_on_char ',' 1 "aa,bb,cc" = "bb"
cut_on_char ',' 2 "aa,bb,cc" = "cc"
cut_on_char '-' 0 "aa,bb,cc" = "aa,bb,cc"
cut_on_char ',' 0 "" = ""
try ignore (cut_on_char ',' (-1) "aa,bb,cc"); false with Invalid_argument _ -> true
try ignore (cut_on_char ',' 3 "aa,bb,cc"); false with Not_found -> true
try ignore (cut_on_char '-' 1 "aa,bb,cc"); false with Not_found -> true
cut_on_char ',' 0 ",ab" = ""
cut_on_char ',' 1 "a,,b" = ""
cut_on_char ',' 1 "a," = ""
*)
let join = concat
let unsafe_slice i j s =
if i >= j || i = length s then
""
else
sub s i (j-i)
let clip ~lo ~hi (x:int) = if x < lo then lo else if x > hi then hi else x
let wrap (x:int) ~hi = if x < 0 then hi + x else x
let slice ?(first = 0) ?(last = Sys.max_string_length) s =
let lo = 0 and hi = length s in
let i = clip ~lo ~hi (wrap first ~hi) in
let j = clip ~lo ~hi (wrap last ~hi) in
unsafe_slice i j s
(*$T slice
slice ~first:1 ~last:(-3) " foo bar baz" = "foo bar "
slice "foo" = "foo"
slice ~first:0 ~last:10 "foo" = "foo"
slice ~first:(-2) "foo" = "oo"
slice ~first:(-3) ~last:(-1) "foob" = "oo"
slice ~first:5 ~last:4 "foobarbaz" = ""
*)
let lchop ?(n = 1) s =
if n < 0 then
invalid_arg "String.lchop: number of characters to chop is negative"
else
let slen = length s in
if slen <= n then "" else sub s n (slen - n)
(*$T lchop
lchop "Weeble" = "eeble"
lchop "" = ""
lchop ~n:3 "Weeble" = "ble"
lchop ~n:1000 "Weeble" = ""
lchop ~n:0 "Weeble" = "Weeble"
try ignore (lchop ~n:(-1) "Weeble"); false with Invalid_argument _ -> true
*)
let rchop ?(n = 1) s =
if n < 0 then
invalid_arg "String.rchop: number of characters to chop is negative"
else
let slen = length s in
if slen <= n then "" else sub s 0 (slen - n)
(*$T rchop
rchop "Weeble" = "Weebl"
rchop "" = ""
rchop ~n:3 "Weeble" = "Wee"
rchop ~n:1000 "Weeble" = ""
try ignore (rchop ~n:(-1) "Weeble"); false with Invalid_argument _ -> true
*)
let chop ?(l = 1) ?(r = 1) s =
if l < 0 then
invalid_arg "String.chop: number of characters to chop on the left is negative";
if r < 0 then
invalid_arg "String.chop: number of characters to chop on the right is negative";
let slen = length s in
if slen < l + r then ""
else sub s l (slen - l - r)
(*$T chop
chop "\"Weeble\"" = "Weeble"
chop "" = ""
chop ~l:2 ~r:3 "01234567" = "234"
chop ~l:1000 "Weeble" = ""
chop ~r:1000 "Weeble" = ""
try ignore (chop ~l:(-1) "Weeble"); false with Invalid_argument _ -> true
try ignore (chop ~r:(-1) "Weeble"); false with Invalid_argument _ -> true
*)
let of_int = string_of_int
(*$T of_int
of_int 56 = "56"
of_int (-1) = "-1"
*)
let of_float = string_of_float
let of_char = make 1
(*$T of_char
of_char 's' = "s"
of_char '\000' = "\000"
*)
let to_int s = int_of_string s
(*$T to_int
to_int "8_480" = to_int "0x21_20"
try ignore (to_int ""); false with Failure "int_of_string" -> true
try ignore (to_int "2,3"); false with Failure "int_of_string" -> true
*)
let to_float s = float_of_string s
(*$T to_float
to_float "12.34e-1" = to_float "1.234"
to_float "1" = 1.
try ignore (to_float ""); false with Failure _ -> true
*)
let enum s =
let l = length s in
let rec make i =
BatEnum.make
~next:(fun () ->
if !i = l then
raise BatEnum.No_more_elements
else
unsafe_get s (BatRef.post_incr i)
)
~count:(fun () -> l - !i)
~clone:(fun () -> make (BatRef.copy i))
in
make (ref 0)
(*$T enum
"" |> enum |> List.of_enum = []
"foo" |> enum |> List.of_enum = ['f'; 'o'; 'o']
let e = enum "abcdef" in \
for _i = 0 to 2 do BatEnum.junk e done; \
let e2 = BatEnum.clone e in \
implode (BatList.of_enum e) = "def" && implode (BatList.of_enum e2) = "def"
*)
let backwards s =
let rec make i =
BatEnum.make
~next:(fun () ->
if !i <= 0 then
raise BatEnum.No_more_elements
else
unsafe_get s (BatRef.pre_decr i)
)
~count:(fun () -> !i)
~clone:(fun () -> make (BatRef.copy i))
in
make (ref (length s))
(*$T backwards
"" |> backwards |> of_enum = ""
"foo" |> backwards |> of_enum = "oof"
let e = backwards "abcdef" in \
for _i = 0 to 2 do BatEnum.junk e done; \
let e2 = BatEnum.clone e in \
implode (BatList.of_enum e) = "cba" && implode (BatList.of_enum e2) = "cba"
*)
let of_enum e =
(* TODO: use a buffer when not fast_count *)
let l = BatEnum.count e in
let s = Bytes.create l in
let i = ref 0 in
BatEnum.iter (fun c -> Bytes.unsafe_set s (BatRef.post_incr i) c) e;
Bytes.unsafe_to_string s
(*$T of_enum
Enum.init 3 (fun i -> char_of_int (i + int_of_char '0')) |> of_enum = "012"
Enum.init 0 (fun _i -> ' ') |> of_enum = ""
*)
let of_backwards e =
(* TODO: use a buffer when not fast_count *)
let l = BatEnum.count e in
let s = Bytes.create l in
let i = ref (l - 1) in
BatEnum.iter (fun c -> Bytes.unsafe_set s (BatRef.post_decr i) c) e;
Bytes.unsafe_to_string s
(*$T of_backwards
"" |> enum |> of_backwards = ""
"foo" |> enum |> of_backwards = "oof"
"foo" |> backwards |> of_backwards = "foo"
*)
let map f s =
let len = length s in
let sc = Bytes.create len in
for i = 0 to len - 1 do
Bytes.unsafe_set sc i (f (unsafe_get s i))
done;
Bytes.unsafe_to_string sc
(*$T map
map Char.uppercase "Five" = "FIVE"
map Char.uppercase "" = ""
map (String.of_char %> failwith) "" = ""
*)
let mapi f s =
let len = length s in
let sc = Bytes.create len in
for i = 0 to len - 1 do
Bytes.unsafe_set sc i (f i (unsafe_get s i))
done;
Bytes.unsafe_to_string sc
(*$T mapi
mapi (fun _ -> Char.uppercase) "Five" = "FIVE"
mapi (fun _ -> Char.uppercase) "" = ""
mapi (fun _ -> String.of_char %> failwith) "" = ""
mapi (fun i _c -> "0123456789".[9-i]) "0123456789" = "9876543210"
ignore (let last = ref (-1) in mapi (fun i _c -> assert (i > !last); last := i; '0') "012345"); true
*)
let filter_map f s =
let len = length s in
let sc = Buffer.create len in
for i = 0 to len - 1 do
match f (unsafe_get s i) with
| Some c -> Buffer.add_char sc c
| None -> ()
done;
Buffer.contents sc
(*$T filter_map
filter_map (function 'a'..'z' as c -> Some (Char.uppercase c) | _ -> None) "a b c" = "ABC"
*)
let filter f s =
let len = length s in
let sc = Buffer.create len in
for i = 0 to len - 1 do
let c = unsafe_get s i in
if f c then Buffer.add_char sc c
done;
Buffer.contents sc
(*$T filter
filter ((<>) ' ') "a b c" = "abc"
*)
(* fold_left and fold_right by Eric C. Cooper *)
let fold_left f init str =
let n = String.length str in
let rec loop i result =
if i = n then result
else loop (i + 1) (f result (unsafe_get str i))
in
loop 0 init
(*$T fold_left
fold_left (fun li c -> c::li) [] "foo" = ['o';'o';'f']
fold_left max 'a' "apples" = 's'
*)
let fold_lefti f init str =
let n = String.length str in
let rec loop i result =
if i = n then result
(* i >= 0 && i < len str *)
else loop (i + 1) (f result i (unsafe_get str i))
in loop 0 init
(*$T fold_lefti
fold_lefti (fun a i c->(i,c)::a) [] "foo"=[(2,'o');(1,'o');(0,'f')]
fold_lefti (fun a i _->i+a) 0 "" = 0
*)
let fold_right f str init =
let n = String.length str in
let rec loop i result =
if i = 0 then result
else
(* i > 0 && i <= len str *)
let i' = i - 1 in
(* i' >= 0 && i' < len str *)
loop i' (f (unsafe_get str i') result)
in
loop n init
(*$T fold_right
fold_right List.cons "foo" [] = ['f';'o';'o']
fold_right (fun c a -> if c = ' ' then a+1 else a) "a b c" 0 = 2
*)
let fold_righti f str init =
let n = String.length str in
let rec loop i result =
if i = 0 then result
else
(* i > 0 && i <= len str *)
let i' = i - 1 in
(* i' >= 0 && i' < len str *)
loop i' (f i' (unsafe_get str i') result)
in loop n init
(*$T fold_righti
fold_righti (fun i c a->(i,c)::a) "foo" []=[(0,'f');(1,'o');(2,'o')]
fold_righti (fun i _ a -> a + i) "" 0 = 0
*)
let iteri f str =
for i = 0 to String.length str - 1 do
f i (unsafe_get str i)
done
(*$R iteri
let letter_positions word =
let positions = Array.make 256 [] in
let count_letter pos c =
positions.(int_of_char c) <- pos :: positions.(int_of_char c) in
iteri count_letter word;
Array.mapi (fun c pos -> (char_of_int c, List.rev pos)) positions
|> Array.to_list
|> List.filter (fun (_c, pos) -> pos <> [])
in
assert_equal ~msg:"String.iteri test"
(letter_positions "hello")
['e',[1]; 'h',[0]; 'l',[2;3]; 'o',[4] ]
*)
(* explode and implode from the OCaml Expert FAQ. *)
let explode s =
let rec loop i l =
if i < 0 then
l
else
(* i >= 0 && i < length s *)
loop (i - 1) (unsafe_get s i :: l)
in
loop (String.length s - 1) []
(*$T explode
explode "foo" = ['f'; 'o'; 'o']
explode "" = []
*)
let to_list = explode
(*$T to_list
to_list "string" |> List.interleave ';' |> of_list = "s;t;r;i;n;g"
*)
let implode l =
let res = Bytes.create (List.length l) in
let rec imp i = function
| [] -> ()
| c :: l -> Bytes.set res i c; imp (i + 1) l in
imp 0 l;
Bytes.unsafe_to_string res
(*$T implode
implode ['b';'a';'r'] = "bar"
implode [] = ""
*)
let of_list = implode
(*$T of_list
['c'; 'h'; 'a'; 'r'; 's'] |> of_list = "chars"
[] |> of_list = ""
*)
let replace_chars f s =
let len = String.length s in
let tlen = ref 0 in
let rec loop i acc =
if i = len then
acc
else
let s = f (unsafe_get s i) in
tlen := !tlen + length s;
loop (i+1) (s :: acc)
in
let strs = loop 0 [] in
let sbuf = Bytes.create !tlen in
let pos = ref !tlen in
let rec loop2 = function
| [] -> ()
| s :: acc ->
let len = length s in
pos := !pos - len;
Bytes.blit_string s 0 sbuf !pos len;
loop2 acc
in
loop2 strs;
Bytes.unsafe_to_string sbuf
(*$T replace_chars
replace_chars (function ' ' -> "(space)" | c -> of_char c) "foo bar" = "foo(space)bar"
replace_chars (fun _ -> "") "foo" = ""
replace_chars (fun _ -> assert false) "" = ""
*)
let replace ~str ~sub ~by =
try
let subpos = find str sub in
let strlen = length str in
let sublen = length sub in
let bylen = length by in
let newstr = Bytes.create (strlen - sublen + bylen) in
blit str 0 newstr 0 subpos ;
blit by 0 newstr subpos bylen ;
blit str (subpos + sublen) newstr (subpos + bylen) (strlen - subpos - sublen) ;
(true, Bytes.unsafe_to_string newstr)
with Not_found -> (* find failed *)
(false, str)
(*$T replace
replace ~str:"foobarbaz" ~sub:"bar" ~by:"rab" = (true, "foorabbaz")
replace ~str:"foo" ~sub:"bar" ~by:"" = (false, "foo")
*)
let nreplace ~str ~sub ~by =
if sub = "" then
invalid_arg "String.nreplace: cannot replace all empty substrings" ;
let strlen = length str in
let sublen = length sub in
let bylen = length by in
let dlen = bylen - sublen in
let rec loop_subst idxes newlen i =
match (try rfind_from str (i-1) sub with Not_found -> -1) with
| -1 -> idxes, newlen
| i' -> loop_subst (i'::idxes) (newlen+dlen) i' in
let idxes, newlen = loop_subst [] strlen strlen in
let newstr = Bytes.create newlen in
let rec loop_copy i j idxes =
match idxes with
| [] ->
(* still need the last chunk *)
Bytes.blit_string str i newstr j (strlen-i)
| i'::rest ->
let di = i' - i in
Bytes.blit_string str i newstr j di ;
Bytes.blit_string by 0 newstr (j + di) bylen ;
loop_copy (i + di + sublen) (j + di + bylen) rest in
loop_copy 0 0 idxes ;
Bytes.unsafe_to_string newstr
(*$T nreplace
nreplace ~str:"bar foo aaa bar" ~sub:"aa" ~by:"foo" = "bar foo afoo bar"
nreplace ~str:"bar foo bar" ~sub:"bar" ~by:"foo" = "foo foo foo"
nreplace ~str:"aaaaaa" ~sub:"aa" ~by:"aaa" = "aaaaaaaaa"
nreplace ~str:"" ~sub:"aa" ~by:"bb" = ""
nreplace ~str:"foo bar baz" ~sub:"foo bar baz" ~by:"" = ""
nreplace ~str:"abc" ~sub:"abc" ~by:"def" = "def"
*)
let rev_in_place s =
let len = Bytes.length s in
if len > 0 then for k = 0 to (len - 1)/2 do
let old = Bytes.get s k and mirror = len - 1 - k in
Bytes.set s k (Bytes.get s mirror);
Bytes.set s mirror old;
done
(*$= rev_in_place as f & ~printer:identity
(let s=Bytes.of_string "" in f s; Bytes.to_string s) ""
(let s=Bytes.of_string "1" in f s; Bytes.to_string s) "1"
(let s=Bytes.of_string "12" in f s; Bytes.to_string s) "21"
(let s=Bytes.of_string "Example!" in f s; Bytes.to_string s) "!elpmaxE"
*)
let in_place_mirror = rev_in_place
let repeat s n =
let buf = Buffer.create ( n * (String.length s) ) in
for i = 1 to n do Buffer.add_string buf s done;
Buffer.contents buf
(*$T repeat
repeat "fo" 4 = "fofofofo"
repeat "fo" 0 = ""
repeat "" 4 = ""
*)
let rev s =
let len = String.length s in
let reversed = Bytes.create len in
for i = 0 to len - 1 do
Bytes.unsafe_set reversed (len - i - 1) (unsafe_get s i)
done;
Bytes.unsafe_to_string reversed
(*$T rev
rev "" = ""
rev "batteries" = "seirettab"
rev "even" = "neve"
*)
let trim s =
let len = length s in
let rec aux_1 i = (*locate leading whitespaces*)
if i = len then None (*The whole string is whitespace*)
else if BatChar.is_whitespace (unsafe_get s i) then aux_1 (i + 1)
else Some i in
match aux_1 0 with
| None -> ""
| Some last_leading_whitespace ->
let rec aux_2 i =
assert (i >= 0);
if BatChar.is_whitespace (unsafe_get s i) then aux_2 (i - 1)
else i in
let first_trailing_whitespace = aux_2 (len - 1) in
unsafe_slice last_leading_whitespace (first_trailing_whitespace + 1) s
(*$T trim
trim " \t foo\n " = "foo"
trim " foo bar " = "foo bar"
trim " \t " = ""
trim "" = ""
*)
let splice s1 off len s2 =
let len1 = length s1 and len2 = length s2 in
let off = wrap off ~hi:len1 in
let len = clip ~lo:0 ~hi:(len1 - off) len in
let out_len = len1 - len + len2 in
let s = Bytes.create out_len in
Bytes.blit_string s1 0 s 0 off; (* s1 before splice point *)
Bytes.blit_string s2 0 s off len2; (* s2 at splice point *)
Bytes.blit_string (* s1 after off+len *)
s1 (off+len) s (off+len2) (len1 - (off+len));
Bytes.unsafe_to_string s
(*$T splice
splice "foo bar baz" 3 5 "XXX" = "fooXXXbaz"
splice "foo bar baz" 5 0 "XXX" = "foo bXXXar baz"
splice "foo bar baz" 5 (-10) "XXX" = "foo bXXXar baz"
splice "foo bar baz" 5 50 "XXX" = "foo bXXX"
splice "foo bar baz" (-4) 2 "XXX" = "foo barXXXaz"
splice "bar baz" (-4) 2 "XXX" = "barXXXaz"
*)
let is_empty s = length s = 0
(*$T is_empty
is_empty ""
not (is_empty "foo")
is_empty (String.make 0 'a')
*)
let icompare s1 s2 = compare (String.lowercase s1) (String.lowercase s2)
(*$T icompare
icompare "FOO" "bar" = 1
*)
type t_alias = t (* needed for IString breaks type t = t *)
module IString =
struct
type t = t_alias
let compare = icompare
end
let numeric_compare s1 s2 =
let e1 = BatEnum.group BatChar.is_digit (enum s1) in
let e2 = BatEnum.group BatChar.is_digit (enum s2) in
BatEnum.compare (fun g1 g2 ->
let s1 = of_enum g1 in
let s2 = of_enum g2 in
if BatChar.is_digit s1.[0] && BatChar.is_digit s2.[0] then
let n1 = Big_int.big_int_of_string s1 in
let n2 = Big_int.big_int_of_string s2 in