Source file stringx.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
module Levenshtein = Levenshtein
open Uutf
open Stdlib
(** [utf8_length s] returns the number of Unicode code points in UTF-8 string
[s]. This counts characters correctly, including multibyte characters like
Japanese or emojis. *)
let utf8_length s =
let dec = Uutf.decoder ~encoding:`UTF_8 (`String s) in
let rec loop acc =
match Uutf.decode dec with
| `End -> acc
| `Uchar _ -> loop (acc + 1)
| `Malformed _ -> loop (acc + 1)
| `Await -> acc
in
loop 0
let repeat_utf8 pad n =
let rec loop acc i = if i = 0 then acc else loop (acc ^ pad) (i - 1) in
loop "" n
let take_utf8 s n =
let dec = Uutf.decoder ~encoding:`UTF_8 (`String s) in
let b = Buffer.create (String.length s) in
let rec loop i =
if i >= n then ()
else
match Uutf.decode dec with
| `Uchar u ->
Buffer.add_utf_8_uchar b u;
loop (i + 1)
| `End | `Await -> ()
| `Malformed _ ->
Buffer.add_string b "?";
loop (i + 1)
in
loop 0;
Buffer.contents b
let times_needed count pad_len = ((count + pad_len - 1) / pad_len) + 1
(** [center s len pad] centers string [s] in a field of [len] characters,
padding with [pad] on both sides. If [s] is already [len] or longer, it is
returned unchanged. If [pad] is empty, [s] is returned. This function is
Unicode-aware. *)
let center s len pad =
if pad = "" then s
else
let slen = utf8_length s in
if slen >= len then s
else
let total_pad = len - slen in
let left_pad = total_pad / 2 in
let right_pad = total_pad - left_pad in
let pad_len = utf8_length pad in
let left_full = repeat_utf8 pad (times_needed left_pad pad_len) in
let right_full = repeat_utf8 pad (times_needed right_pad pad_len) in
let left = take_utf8 left_full left_pad in
let right = take_utf8 right_full right_pad in
left ^ s ^ right
(** Decode a UTF-8 string into a list of Unicode characters (Uchar.t). *)
let decode_utf8 (s : string) : Uchar.t list =
let dec = decoder ~encoding:`UTF_8 (`String s) in
let rec loop acc =
match decode dec with
| `Uchar u -> loop (u :: acc)
| `End -> List.rev acc
| `Malformed _ -> loop acc
| `Await -> acc
in
loop []
(** Encode a list of Unicode characters (Uchar.t) into a UTF-8 string. *)
let encode_utf8 (uchars : Uchar.t list) : string =
let buf = Buffer.create 64 in
let enc = encoder `UTF_8 (`Buffer buf) in
let () =
List.iter (fun u -> ignore (encode enc (`Uchar u))) uchars;
ignore (encode enc `End)
in
Buffer.contents buf
(** Expand a character range from [start] to [stop], inclusive. *)
let expand_range (start : Uchar.t) (stop : Uchar.t) : Uchar.t list =
let s = Uchar.to_int start in
let e = Uchar.to_int stop in
let low, high = if s <= e then (s, e) else (e, s) in
List.init (high - low + 1) (fun i -> Uchar.of_int (low + i))
(** Parse the pattern string and build a matcher function. Supports:
- direct characters: "aeiou"
- ranges: "a-k"
- negation: "^a-k" *)
let build_matcher (pattern : string) : Uchar.t -> bool =
let uchars = decode_utf8 pattern in
let is_negated =
match uchars with
| u :: _ when Uchar.equal u (Uchar.of_char '^') -> true
| _ -> false
in
let uchars = if is_negated then List.tl uchars else uchars in
let rec parse acc = function
| [] -> acc
| a :: b :: c :: tl when Uchar.equal b (Uchar.of_char '-') ->
let range = expand_range a c in
parse (range @ acc) tl
| ch :: tl -> parse (ch :: acc) tl
in
let matcher_list = parse [] uchars in
if is_negated then fun u -> not (List.mem u matcher_list)
else fun u -> List.mem u matcher_list
(** Count how many Unicode characters in [str] match the given [pattern]. *)
let count (str : string) (pattern : string) : int =
let matcher = build_matcher pattern in
let dec = decoder ~encoding:`UTF_8 (`String str) in
let rec loop acc =
match decode dec with
| `Uchar u -> if matcher u then loop (acc + 1) else loop acc
| `End -> acc
| `Malformed _ -> loop acc
| `Await -> acc
in
loop 0
(** [delete str pattern] returns a new string in which all characters in [str]
that match the given [pattern] are removed.
The [pattern] follows the same syntax as used in [count] and [translate],
and supports:
- character sets: e.g., "aeiou"
- ranges: e.g., "a-k"
- negation with ^: e.g., "^a-k"
Unicode-aware: input string is treated as a sequence of UTF-8 characters.
Examples:
- [delete "hello" "aeiou"] returns ["hll"]
- [delete "hello" "a-k"] returns ["llo"]
- [delete "hello" "^a-k"] returns ["he"]
@param str The UTF-8 encoded input string
@param pattern The character pattern to match
@return A new string with matched characters removed *)
let delete (str : string) (pattern : string) : string =
let matcher = build_matcher pattern in
decode_utf8 str |> List.filter (fun u -> not (matcher u)) |> encode_utf8
let len (str : string) : int =
let dec = Uutf.decoder ~encoding:`UTF_8 (`String str) in
let rec loop acc =
match Uutf.decode dec with
| `End -> acc
| `Uchar _ -> loop (acc + 1)
| `Malformed _ -> loop (acc + 1)
| `Await -> acc
in
loop 0
(** [reverse s] reverses a UTF-8 encoded string [s]. *)
let reverse (s : string) : string = decode_utf8 s |> List.rev |> encode_utf8
(** [contains s substr] reports whether [substr] is within [s]. Returns true if
[substr] is the empty string. *)
let contains (s : string) (substr : string) : bool =
if substr = "" then true
else
let len_s = String.length s in
let len_sub = String.length substr in
let rec loop i =
if i > len_s - len_sub then false
else if String.sub s i len_sub = substr then true
else loop (i + 1)
in
loop 0
(** [has_prefix s prefix] checks if the string [s] starts with the given
[prefix]. Returns true if [prefix] is empty. This function operates on
bytes, not Unicode code points. *)
let has_prefix (s : string) (prefix : string) : bool =
let len_s = String.length s in
let len_p = String.length prefix in
if len_p = 0 then true
else if len_s < len_p then false
else String.sub s 0 len_p = prefix
(** [has_suffix s suffix] reports whether the string [s] ends with [suffix].
Returns true if [suffix] is the empty string. This function is
Unicode-agnostic and operates on bytes, not code points. *)
let has_suffix (s : string) (suffix : string) : bool =
let len_s = String.length s in
let len_suf = String.length suffix in
if len_suf = 0 then true
else if len_s < len_suf then false
else String.sub s (len_s - len_suf) len_suf = suffix
(** [contains_any s chars] reports whether any Unicode code points in [chars]
are within [s]. Returns false if [chars] is empty. Unicode-aware. *)
let contains_any (s : string) (chars : string) : bool =
if chars = "" then false
else
let set = decode_utf8 chars |> List.sort_uniq Uchar.compare in
let rec loop = function
| [] -> false
| u :: tl -> if List.mem u set then true else loop tl
in
loop (decode_utf8 s)
(** [count_substring s substr] counts the number of non-overlapping instances of
[substr] in [s]. If [substr] is the empty string, returns 1 + the number of
Unicode code points in [s]. This function is Unicode-agnostic and operates
on bytes, not code points. *)
let count_substring (s : string) (substr : string) : int =
if substr = "" then 1 + len s
else
let len_s = String.length s in
let len_sub = String.length substr in
let rec loop i acc =
if i > len_s - len_sub then acc
else if String.sub s i len_sub = substr then loop (i + len_sub) (acc + 1)
else loop (i + 1) acc
in
loop 0 0
(** [equal_fold s t] reports whether [s] and [t], interpreted as UTF-8 strings,
are equal under simple Unicode case-folding (ASCII only). *)
let equal_fold (s : string) (t : string) : bool =
let to_simple_fold str =
decode_utf8 str
|> List.map (fun u ->
let c = Uchar.to_int u in
if c >= 0x41 && c <= 0x5A then Uchar.of_int (c + 0x20) else u)
|> encode_utf8
in
to_simple_fold s = to_simple_fold t
(** [is_space u] returns true if the Unicode character [u] is a whitespace
character. *)
let is_space (u : Uchar.t) : bool =
match Uchar.to_int u with
| 0x09 | 0x0A | 0x0B | 0x0C | 0x0D | 0x20 | 0x85 | 0xA0 | 0x1680 | 0x2000
| 0x2001 | 0x2002 | 0x2003 | 0x2004 | 0x2005 | 0x2006 | 0x2007 | 0x2008
| 0x2009 | 0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000 ->
true
| _ -> false
(** [fields s] splits [s] into substrings separated by one or more Unicode
whitespace characters. Returns an empty list if [s] contains only
whitespace. *)
let fields (s : string) : string list =
let uchars = decode_utf8 s in
let rec skip_spaces = function
| u :: tl when is_space u -> skip_spaces tl
| rest -> rest
in
let rec take_word acc = function
| u :: tl when not (is_space u) -> take_word (u :: acc) tl
| rest -> (List.rev acc, rest)
in
let rec loop acc l =
match skip_spaces l with
| [] -> List.rev acc
| l' ->
let word, rest = take_word [] l' in
if word = [] then List.rev acc else loop (encode_utf8 word :: acc) rest
in
loop [] uchars
(** [fields_func s f] splits [s] at each run of Unicode code points [c]
satisfying [f c]. Returns an empty list if all code points in [s] satisfy
[f] or [s] is empty. *)
let fields_func (s : string) (f : Uchar.t -> bool) : string list =
let uchars = decode_utf8 s in
let rec skip_sep = function
| u :: tl when f u -> skip_sep tl
| rest -> rest
in
let rec take_field acc = function
| u :: tl when not (f u) -> take_field (u :: acc) tl
| rest -> (List.rev acc, rest)
in
let rec loop acc l =
match skip_sep l with
| [] -> List.rev acc
| l' ->
let word, rest = take_field [] l' in
if word = [] then List.rev acc else loop (encode_utf8 word :: acc) rest
in
loop [] uchars
(** [index s substr] returns the index of the first instance of [substr] in [s],
or -1 if [substr] is not present. The index is a byte offset (not code point
index). *)
let index (s : string) (substr : string) : int =
let len_s = String.length s in
let len_sub = String.length substr in
if substr = "" then 0
else if len_sub > len_s then -1
else
let rec loop i =
if i > len_s - len_sub then -1
else if String.sub s i len_sub = substr then i
else loop (i + 1)
in
loop 0
(** [repeat s count] returns a new string consisting of [count] copies of [s].
Raises [Invalid_argument] if [count] is negative. *)
let repeat (s : string) (count : int) : string =
if count < 0 then invalid_arg "repeat: negative count"
else
let rec loop acc n = if n = 0 then acc else loop (acc ^ s) (n - 1) in
loop "" count
(** [join elems sep] concatenates the elements of [elems], inserting [sep]
between each element. Returns the empty string if [elems] is empty. *)
let join (elems : string list) (sep : string) : string =
match elems with
| [] -> ""
| hd :: tl -> List.fold_left (fun acc s -> acc ^ sep ^ s) hd tl
(** [trim s cutset] returns [s] with all leading and trailing Unicode code
points contained in [cutset] removed. Unicode-aware. *)
let trim (s : string) (cutset : string) : string =
if cutset = "" || s = "" then s
else
let set = decode_utf8 cutset |> List.sort_uniq Uchar.compare in
let uchars = decode_utf8 s in
let rec drop_leading = function
| u :: tl when List.mem u set -> drop_leading tl
| rest -> rest
in
let rec drop_trailing l =
match List.rev l with
| u :: tl when List.mem u set -> drop_trailing (List.rev tl)
| _ -> l
in
drop_leading uchars |> drop_trailing |> encode_utf8
(** [trim_func s f] returns [s] with all leading and trailing Unicode code
points [c] satisfying [f c] removed. Unicode-aware. *)
let trim_func (s : string) (f : Uchar.t -> bool) : string =
if s = "" then s
else
let uchars = decode_utf8 s in
let rec drop_leading = function
| u :: tl when f u -> drop_leading tl
| rest -> rest
in
let rec drop_trailing l =
match List.rev l with
| u :: tl when f u -> drop_trailing (List.rev tl)
| _ -> l
in
drop_leading uchars |> drop_trailing |> encode_utf8
(** [trim_left s cutset] returns [s] with all leading Unicode code points
contained in [cutset] removed. Unicode-aware. *)
let trim_left (s : string) (cutset : string) : string =
if cutset = "" || s = "" then s
else
let set = decode_utf8 cutset |> List.sort_uniq Uchar.compare in
let uchars = decode_utf8 s in
let rec drop_leading = function
| u :: tl when List.mem u set -> drop_leading tl
| rest -> rest
in
drop_leading uchars |> encode_utf8
(** [trim_left_func s f] returns [s] with all leading Unicode code points [c]
satisfying [f c] removed. Unicode-aware. *)
let trim_left_func (s : string) (f : Uchar.t -> bool) : string =
if s = "" then s
else
let uchars = decode_utf8 s in
let rec drop_leading = function
| u :: tl when f u -> drop_leading tl
| rest -> rest
in
drop_leading uchars |> encode_utf8
(** [trim_right s cutset] returns [s] with all trailing Unicode code points
contained in [cutset] removed. Unicode-aware. *)
let trim_right (s : string) (cutset : string) : string =
if cutset = "" || s = "" then s
else
let set = decode_utf8 cutset |> List.sort_uniq Uchar.compare in
let uchars = decode_utf8 s in
let rec drop_trailing l =
match List.rev l with
| u :: tl when List.mem u set -> drop_trailing (List.rev tl)
| _ -> l
in
drop_trailing uchars |> encode_utf8
(** [trim_right_func s f] returns [s] with all trailing Unicode code points [c]
satisfying [f c] removed. Unicode-aware. *)
let trim_right_func (s : string) (f : Uchar.t -> bool) : string =
if s = "" then s
else
let uchars = decode_utf8 s in
let rec drop_trailing l =
match List.rev l with
| u :: tl when f u -> drop_trailing (List.rev tl)
| _ -> l
in
drop_trailing uchars |> encode_utf8
(** [trim_space s] returns [s] with all leading and trailing Unicode whitespace
removed. Unicode-aware. *)
let trim_space (s : string) : string =
let is_space = is_space in
if s = "" then s
else
let uchars = decode_utf8 s in
let rec drop_leading = function
| u :: tl when is_space u -> drop_leading tl
| rest -> rest
in
let rec drop_trailing l =
match List.rev l with
| u :: tl when is_space u -> drop_trailing (List.rev tl)
| _ -> l
in
drop_leading uchars |> drop_trailing |> encode_utf8
(** [trim_suffix s suffix] returns [s] without the provided trailing [suffix]
string. If [s] does not end with [suffix], [s] is returned unchanged. This
function is byte-based, not Unicode-aware. *)
let trim_suffix (s : string) (suffix : string) : string =
let len_s = String.length s in
let len_suf = String.length suffix in
if len_suf = 0 then s
else if len_s < len_suf then s
else if String.sub s (len_s - len_suf) len_suf = suffix then
String.sub s 0 (len_s - len_suf)
else s
(** [to_lower s] returns [s] with all Unicode letters mapped to their lower
case. This function is ASCII-only for now. *)
let to_lower (s : string) : string =
let lower u =
let c = Uchar.to_int u in
if c >= 0x41 && c <= 0x5A then Uchar.of_int (c + 0x20) else u
in
decode_utf8 s |> List.map lower |> encode_utf8
(** [to_title s] returns [s] with all Unicode letters mapped to their Unicode
title case. Currently, only ASCII letters are supported (A-Z, a-z). TODO:
Support full Unicode title case in the future. *)
let to_title (s : string) : string =
let title u =
let c = Uchar.to_int u in
if c >= 0x61 && c <= 0x7A then Uchar.of_int (c - 0x20)
else if c >= 0x41 && c <= 0x5A then u
else u
in
decode_utf8 s |> List.map title |> encode_utf8
(** [to_upper s] returns [s] with all Unicode letters mapped to their upper
case. This function is ASCII-only for now. *)
let to_upper (s : string) : string =
let upper u =
let c = Uchar.to_int u in
if c >= 0x61 && c <= 0x7A then Uchar.of_int (c - 0x20) else u
in
decode_utf8 s |> List.map upper |> encode_utf8
(** [to_camel_case s] converts words separated by space, underscore, or hyphen
to camel case. Leading and trailing underscores are preserved. Multiple
consecutive separators are treated as a single word boundary. If there are
no separators, the string is returned unchanged.
- Words are split on '_', '-', or space.
- The first word is lowercased (even if originally all uppercase).
- Subsequent words are capitalized (first letter uppercase, rest lowercase).
- All-uppercase words are handled (e.g. "GOLANG_IS_GREAT" →
"golangIsGreat").
- If there are no separators, the original string is returned (e.g.
"alreadyCamel" → "alreadyCamel").
- Leading and trailing underscores are preserved (e.g. "_complex__case_" →
"_complexCase_").
- Hyphens and spaces are also treated as word boundaries.
Examples:
- [to_camel_case "some_words"] returns ["someWords"]
- [to_camel_case "_complex__case_"] returns ["_complexCase_"]
- [to_camel_case "GOLANG_IS_GREAT"] returns ["golangIsGreat"]
- [to_camel_case "alreadyCamel"] returns ["alreadyCamel"]
- [to_camel_case "foo-BarBaz"] returns ["fooBarBaz"]
- [to_camel_case "word"] returns ["word"]
- [to_camel_case ""] returns [""] *)
let to_camel_case (s : string) : string =
let is_sep c = c = '_' || c = '-' || c = ' ' in
let len = String.length s in
let rec count_lead i =
if i < len && s.[i] = '_' then 1 + count_lead (i + 1) else 0
in
let lead = count_lead 0 in
let rec count_trail i =
if i >= 0 && s.[i] = '_' then 1 + count_trail (i - 1) else 0
in
let trail = count_trail (len - 1) in
let core_start = lead in
let core_len = len - lead - trail in
let core = if core_len > 0 then String.sub s core_start core_len else "" in
let split_core str =
let n = String.length str in
let rec aux i acc =
if i >= n then List.rev acc
else if is_sep str.[i] then aux (i + 1) acc
else
let j = ref i in
while !j < n && not (is_sep str.[!j]) do
incr j
done;
let word = String.sub str i (!j - i) in
aux !j (word :: acc)
in
aux 0 []
in
let is_all_upper seg =
seg <> "" && String.for_all (fun c -> 'A' <= c && c <= 'Z') seg
in
let buf = Buffer.create len in
for _ = 1 to lead do
Buffer.add_char buf '_'
done;
(if core = "" then ()
else if not (String.exists (fun c -> is_sep c) core) then
Buffer.add_string buf core
else
let segments = split_core core in
match segments with
| [] -> ()
| first :: rest ->
Buffer.add_string buf (String.lowercase_ascii first);
List.iter
(fun seg ->
if seg = "" then ()
else if is_all_upper seg then (
let low = String.lowercase_ascii seg in
let c0 = low.[0] in
Buffer.add_char buf (Char.uppercase_ascii c0);
if String.length low > 1 then
Buffer.add_string buf
(String.sub low 1 (String.length low - 1)))
else
let c0 = seg.[0] in
Buffer.add_char buf (Char.uppercase_ascii c0);
if String.length seg > 1 then
Buffer.add_string buf
(String.sub seg 1 (String.length seg - 1)))
rest);
for _ = 1 to trail do
Buffer.add_char buf '_'
done;
Buffer.contents buf
(** [to_kebab_case s] converts a string to kebab-case.
- Uppercase ASCII letters are converted to lowercase.
- Word boundaries are detected at transitions from lowercase to uppercase,
from letter to digit, and at underscores, spaces, or hyphens.
- All word boundaries are replaced with a single hyphen '-'.
- Multiple consecutive separators are treated as a single hyphen.
- Leading and trailing hyphens are removed.
- If the input is empty, returns the empty string.
Examples:
- [to_kebab_case "FirstName"] returns ["first-name"]
- [to_kebab_case "HTTPServer"] returns ["http-server"]
- [to_kebab_case "NoHTTPS"] returns ["no-https"]
- [to_kebab_case "GO_PATH"] returns ["go-path"]
- [to_kebab_case "GO PATH"] returns ["go-path"]
- [to_kebab_case "GO-PATH"] returns ["go-path"]
- [to_kebab_case "http2xx"] returns ["http-2xx"]
- [to_kebab_case "HTTP20xOK"] returns ["http-20x-ok"]
- [to_kebab_case "Duration2m3s"] returns ["duration-2m-3s"]
- [to_kebab_case "Bld4Floor3rd"] returns ["bld4-floor-3rd"] *)
let to_kebab_case (s : string) : string =
let is_lower c = 'a' <= c && c <= 'z' in
let is_upper c = 'A' <= c && c <= 'Z' in
let is_digit c = '0' <= c && c <= '9' in
let is_sep c = c = '_' || c = '-' || c = ' ' in
let len = String.length s in
let raw_segs = ref [] in
let i = ref 0 in
while !i < len do
while !i < len && is_sep s.[!i] do
incr i
done;
if !i < len then (
let start = !i in
incr i;
while
!i < len
&& (not (is_sep s.[!i]))
&& not
(let prev = s.[!i - 1] in
let curr = s.[!i] in
let next_opt = if !i + 1 < len then Some s.[!i + 1] else None in
(is_lower prev && is_upper curr)
|| (is_upper prev && is_upper curr
&& match next_opt with Some c2 -> is_lower c2 | None -> false)
|| ((is_lower prev || is_upper prev) && is_digit curr)
|| (is_digit prev && is_upper curr))
do
incr i
done;
let seg = String.sub s start (!i - start) in
raw_segs := seg :: !raw_segs)
done;
let segs = Array.of_list (List.rev !raw_segs) in
let n = Array.length segs in
let merged = ref [] in
let j = ref 0 in
while !j < n do
let seg = segs.(!j) in
let only_digits = seg <> "" && String.for_all (fun c -> is_digit c) seg in
if only_digits && !j > 0 && !j < n - 1 then
let next = segs.(!j + 1) in
if next <> "" && is_upper next.[0] then (
let prev = List.hd !merged in
merged := List.tl !merged;
merged := (prev ^ seg) :: !merged;
incr j)
else (
segs.(!j + 1) <- seg ^ next;
incr j)
else (
merged := seg :: !merged;
incr j)
done;
let final = List.rev !merged in
String.concat "-" (List.map String.lowercase_ascii final)
(** [to_pascal_case s] converts words separated by space, underscore, or hyphen
to PascalCase.
- Words are split on '_', '-', or space.
- Each word is capitalized (first letter uppercase, rest lowercase).
- All-uppercase words are handled (e.g. "OCAML_IS_GREAT" → "OcamlIsGreat").
- If there are no separators, the first letter is uppercased, the rest
lowercased.
- Leading and trailing underscores are preserved (e.g. "_complex__case_" →
"_ComplexCase_").
- Multiple consecutive separators are preserved as single underscores.
- Hyphens and spaces are also treated as word boundaries.
Examples:
- [to_pascal_case "some_words"] returns ["SomeWords"]
- [to_pascal_case "_complex__case_"] returns ["_ComplexCase_"]
- [to_pascal_case "GOLANG_IS_GREAT"] returns ["GolangIsGreat"]
- [to_pascal_case "alreadyPascal"] returns ["AlreadyPascal"]
- [to_pascal_case "foo-BarBaz"] returns ["FooBarBaz"]
- [to_pascal_case "word"] returns ["Word"]
- [to_pascal_case ""] returns [""] *)
let to_pascal_case (s : string) : string =
let is_sep c = c = '_' || c = '-' || c = ' ' in
let is_upper c = 'A' <= c && c <= 'Z' in
let len = String.length s in
let rec count_lead i =
if i < len && s.[i] = '_' then 1 + count_lead (i + 1) else 0
in
let lead = count_lead 0 in
let rec count_trail i =
if i >= 0 && s.[i] = '_' then 1 + count_trail (i - 1) else 0
in
let trail = count_trail (len - 1) in
let core_start = lead in
let core_end = len - trail in
let buf = Buffer.create len in
for _ = 1 to lead do
Buffer.add_char buf '_'
done;
(if core_start < core_end then
let core = String.sub s core_start (core_end - core_start) in
let has_sep = String.exists (fun c -> is_sep c) core in
if not has_sep then (
Buffer.add_char buf (Char.uppercase_ascii core.[0]);
if String.length core > 1 then
Buffer.add_substring buf core 1 (String.length core - 1))
else
let rec split i acc =
if i >= String.length core then List.rev acc
else if is_sep core.[i] then split (i + 1) acc
else
let j = ref i in
while !j < String.length core && not (is_sep core.[!j]) do
incr j
done;
let seg = String.sub core i (!j - i) in
split !j (seg :: acc)
in
let segments = split 0 [] in
List.iter
(fun seg ->
if seg <> "" then
let all_upper = seg <> "" && String.for_all is_upper seg in
if all_upper then (
let low = String.lowercase_ascii seg in
Buffer.add_char buf (Char.uppercase_ascii low.[0]);
if String.length low > 1 then
Buffer.add_substring buf low 1 (String.length low - 1))
else (
Buffer.add_char buf (Char.uppercase_ascii seg.[0]);
if String.length seg > 1 then
Buffer.add_substring buf seg 1 (String.length seg - 1)))
segments);
for _ = 1 to trail do
Buffer.add_char buf '_'
done;
Buffer.contents buf
(** [to_snake_case s] converts a string to snake_case.
- Uppercase ASCII letters are converted to lowercase.
- Word boundaries are detected at transitions from lowercase to uppercase,
from letter to digit, and at underscores, spaces, or hyphens.
- All word boundaries are replaced with a single underscore '_'.
- Multiple consecutive separators are treated as a single underscore.
- Leading and trailing underscores are removed.
- If the input is empty, returns the empty string.
Examples:
- [to_snake_case "FirstName"] returns ["first_name"]
- [to_snake_case "HTTPServer"] returns ["http_server"]
- [to_snake_case "NoHTTPS"] returns ["no_https"]
- [to_snake_case "GO_PATH"] returns ["go_path"]
- [to_snake_case "GO PATH"] returns ["go_path"]
- [to_snake_case "GO-PATH"] returns ["go_path"]
- [to_snake_case "http2xx"] returns ["http_2xx"]
- [to_snake_case "HTTP20xOK"] returns ["http_20x_ok"]
- [to_snake_case "Duration2m3s"] returns ["duration_2m3s"]
- [to_snake_case "Bld4Floor3rd"] returns ["bld4_floor_3rd"] *)
let to_snake_case (s : string) : string =
let is_lower c = 'a' <= c && c <= 'z' in
let is_upper c = 'A' <= c && c <= 'Z' in
let is_digit c = '0' <= c && c <= '9' in
let is_sep c = c = '_' || c = '-' || c = ' ' in
let n = String.length s in
let segments = ref [] in
let i = ref 0 in
while !i < n do
if is_sep s.[!i] then incr i
else
let start = !i in
let seg =
if is_digit s.[!i] then (
let j = ref !i in
while !j + 1 < n && (is_digit s.[!j + 1] || is_lower s.[!j + 1]) do
incr j
done;
i := !j + 1;
String.sub s start (!j - start + 1))
else if is_upper s.[!i] then (
let j = ref !i in
while !j + 1 < n && is_upper s.[!j + 1] do
incr j
done;
if !j > start && !j + 1 < n && is_lower s.[!j + 1] then (
let acr_end = !j - 1 in
i := acr_end + 1;
String.sub s start (acr_end - start + 1))
else if !j > start then (
let len = !j - start + 1 in
i := !j + 1;
String.sub s start len)
else
let k = ref !j in
while !k + 1 < n && is_lower s.[!k + 1] do
incr k
done;
i := !k + 1;
String.sub s start (!k - start + 1))
else if is_lower s.[!i] then (
let j = ref !i in
while !j + 1 < n && is_lower s.[!j + 1] do
incr j
done;
i := !j + 1;
String.sub s start (!j - start + 1))
else (
incr i;
String.make 1 s.[start])
in
if seg <> "" then segments := seg :: !segments
done;
let merged = ref [] in
List.iter
(fun seg ->
if
String.length seg = 1
&& String.for_all (fun c -> is_digit c) seg
&& !merged <> []
then (
let prev = List.hd !merged in
merged := List.tl !merged;
merged := (prev ^ seg) :: !merged)
else merged := seg :: !merged)
(List.rev !segments);
let final = List.rev !merged in
String.concat "_" (List.map String.lowercase_ascii final)