Source file CCUtf8_string.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
(** {1 UTF8 strings} *)

(** Ref {{: https://en.wikipedia.org/wiki/UTF-8} Wikipedia}

    We only deal with UTF8 strings as they naturally map to OCaml bytestrings *)

open CCShims_

type uchar = Uchar.t
type 'a gen = unit -> 'a option
type 'a iter = ('a -> unit) -> unit

let equal (a : string) b = Stdlib.( = ) a b
let hash : string -> int = Hashtbl.hash
let pp = Format.pp_print_string

include String

let empty = ""
let to_string x = x

(** State for decoding *)
module Dec = struct
  type t = { s: string; len: int; (* max offset *) mutable i: int (* offset *) }

  let make ?(idx = 0) (s : string) : t = { s; i = idx; len = String.length s }
end

let n_bytes = length

exception Malformed of string * int
(** Malformed string at given offset *)

(* decode next char. Mutate state, calls [yield c] if a char [c] is
   read, [stop ()] otherwise.
   @raise Malformed if an invalid substring is met *)
let next_ (type a) (st : Dec.t) ~(yield : uchar -> a) ~(stop : unit -> a) () : a
    =
  let open Dec in
  let malformed st = raise (Malformed (st.s, st.i)) in
  (* read a multi-byte character.
     @param acc the accumulator (containing the first byte of the char)
     @param n_bytes number of bytes to read (i.e. [width char - 1])
     @param overlong minimal bound on second byte (to detect overlong encoding)
  *)
  let read_multi ?(overlong = 0) n_bytes acc =
    (* inner loop j = 1..jmax *)
    let rec aux j acc =
      let c = Char.code st.s.[st.i + j] in
      (* check that c is in 0b10xxxxxx *)
      if c lsr 6 <> 0b10 then malformed st;
      (* overlong encoding? *)
      if j = 1 && overlong <> 0 && c land 0b111111 < overlong then malformed st;
      (* except for first, each char gives 6 bits *)
      let next = (acc lsl 6) lor (c land 0b111111) in
      if j = n_bytes then
        if (* done reading the codepoint *)
           Uchar.is_valid next then (
          st.i <- st.i + j + 1;
          (* +1 for first char *)
          yield (Uchar.unsafe_of_int next)
        ) else
          malformed st
      else
        aux (j + 1) next
    in
    assert (n_bytes >= 1);
    (* is the string long enough to contain the whole codepoint? *)
    if st.i + n_bytes < st.len then
      aux 1 acc
    (* start with j=1, first char is already processed! *)
    else
      (* char is truncated *)
      malformed st
  in
  if st.i >= st.len then
    stop ()
  else (
    let c = st.s.[st.i] in
    (* find leading byte, and detect some impossible cases
       according to https://en.wikipedia.org/wiki/Utf8#Codepage_layout *)
    match c with
    | '\000' .. '\127' ->
      st.i <- 1 + st.i;
      yield (Uchar.of_int @@ Char.code c) (* 0xxxxxxx *)
    | '\194' .. '\223' -> read_multi 1 (Char.code c land 0b11111) (* 110yyyyy *)
    | '\225' .. '\239' -> read_multi 2 (Char.code c land 0b1111) (* 1110zzzz *)
    | '\241' .. '\244' -> read_multi 3 (Char.code c land 0b111) (* 11110uuu *)
    | '\224' ->
      (* overlong: if next byte is < than [0b001000000] then the char
         would fit in 1 byte *)
      read_multi ~overlong:0b00100000 2 (Char.code c land 0b1111)
      (* 1110zzzz *)
    | '\240' ->
      (* overlong: if next byte is < than [0b000100000] then the char
         would fit in 2 bytes *)
      read_multi ~overlong:0b00010000 3 (Char.code c land 0b111)
      (* 11110uuu *)
    | '\128' .. '\193' (* 192,193 are forbidden *) | '\245' .. '\255' ->
      malformed st
  )

let to_gen ?(idx = 0) str : uchar gen =
  let st = Dec.make ~idx str in
  fun () -> next_ st ~yield:(fun c -> Some c) ~stop:(fun () -> None) ()

exception Stop

let to_iter ?(idx = 0) s : uchar iter =
 fun yield ->
  let st = Dec.make ~idx s in
  try
    while true do
      next_ st ~yield ~stop:(fun () -> raise Stop) ()
    done
  with Stop -> ()

let to_seq ?(idx = 0) s : uchar Seq.t =
  let rec loop st =
    let r = ref None in
    fun () ->
      match !r with
      | Some c -> c
      | None ->
        let c =
          next_ st
            ~yield:(fun x -> Seq.Cons (x, loop st))
            ~stop:(fun () -> Seq.Nil)
            ()
        in
        r := Some c;
        c
  in
  let st = Dec.make ~idx s in
  loop st

let iter ?idx f s = to_iter ?idx s f

let fold ?idx f acc s =
  let st = Dec.make ?idx s in
  let rec aux acc =
    next_ st
      ~yield:(fun x ->
        let acc = f acc x in
        aux acc)
      ~stop:(fun () -> acc)
      ()
  in
  aux acc

let n_chars = fold (fun x _ -> x + 1) 0

let to_list ?(idx = 0) s : uchar list =
  fold ~idx (fun acc x -> x :: acc) [] s |> List.rev

(* Convert a code point (int) into a string;
   There are various equally trivial versions of this around.
*)

let[@inline] uchar_to_bytes (c : uchar) (f : char -> unit) : unit =
  let c = Uchar.to_int c in
  let mask = 0b111111 in
  assert (Uchar.is_valid c);
  if c <= 0x7f then
    f (Char.unsafe_chr c)
  else if c <= 0x7ff then (
    f (Char.unsafe_chr (0xc0 lor (c lsr 6)));
    f (Char.unsafe_chr (0x80 lor (c land mask)))
  ) else if c <= 0xffff then (
    f (Char.unsafe_chr (0xe0 lor (c lsr 12)));
    f (Char.unsafe_chr (0x80 lor ((c lsr 6) land mask)));
    f (Char.unsafe_chr (0x80 lor (c land mask)))
  ) else if c <= 0x1fffff then (
    f (Char.unsafe_chr (0xf0 lor (c lsr 18)));
    f (Char.unsafe_chr (0x80 lor ((c lsr 12) land mask)));
    f (Char.unsafe_chr (0x80 lor ((c lsr 6) land mask)));
    f (Char.unsafe_chr (0x80 lor (c land mask)))
  ) else (
    f (Char.unsafe_chr (0xf8 lor (c lsr 24)));
    f (Char.unsafe_chr (0x80 lor ((c lsr 18) land mask)));
    f (Char.unsafe_chr (0x80 lor ((c lsr 12) land mask)));
    f (Char.unsafe_chr (0x80 lor ((c lsr 6) land mask)));
    f (Char.unsafe_chr (0x80 lor (c land mask)))
  )

(* number of bytes required to encode this codepoint. A skeleton version
   of {!uchar_to_bytes}. *)
let[@inline] uchar_num_bytes (c : uchar) : int =
  let c = Uchar.to_int c in
  if c <= 0x7f then
    1
  else if c <= 0x7ff then
    2
  else if c <= 0xffff then
    3
  else if c <= 0x1fffff then
    4
  else
    5

let of_gen g : t =
  let buf = Buffer.create 32 in
  let rec aux () =
    match g () with
    | None -> Buffer.contents buf
    | Some c ->
      uchar_to_bytes c (Buffer.add_char buf);
      aux ()
  in
  aux ()

let of_seq seq : t =
  let buf = Buffer.create 32 in
  Seq.iter (fun c -> uchar_to_bytes c (Buffer.add_char buf)) seq;
  Buffer.contents buf

let of_iter i : t =
  let buf = Buffer.create 32 in
  i (fun c -> uchar_to_bytes c (Buffer.add_char buf));
  Buffer.contents buf

let make n c =
  if n = 0 then
    empty
  else (
    let n_bytes = uchar_num_bytes c in
    let buf = Bytes.create (n * n_bytes) in
    (* copy [c] at the beginning of the buffer *)
    let i = ref 0 in
    uchar_to_bytes c (fun b ->
        Bytes.set buf !i b;
        incr i);
    (* now repeat the prefix n-1 times *)
    for j = 1 to n - 1 do
      Bytes.blit buf 0 buf (n_bytes * j) n_bytes
    done;
    Bytes.unsafe_to_string buf
  )

let[@inline] of_uchar c : t = make 1 c

let of_list l : t =
  let len = List.fold_left (fun n c -> n + uchar_num_bytes c) 0 l in
  if len > Sys.max_string_length then
    invalid_arg "CCUtf8_string.of_list: string size limit exceeded";
  let buf = Bytes.make len '\000' in
  let i = ref 0 in
  List.iter
    (fun c ->
      uchar_to_bytes c (fun byte ->
          Bytes.unsafe_set buf !i byte;
          incr i))
    l;
  assert (!i = len);
  Bytes.unsafe_to_string buf

let map f s : t =
  let buf = Buffer.create (n_bytes s) in
  iter (fun c -> uchar_to_bytes (f c) (Buffer.add_char buf)) s;
  Buffer.contents buf

let filter_map f s : t =
  let buf = Buffer.create (n_bytes s) in
  iter
    (fun c ->
      match f c with
      | None -> ()
      | Some c -> uchar_to_bytes c (Buffer.add_char buf))
    s;
  Buffer.contents buf

let flat_map f s : t =
  let buf = Buffer.create (n_bytes s) in
  iter (fun c -> iter (fun c -> uchar_to_bytes c (Buffer.add_char buf)) (f c)) s;
  Buffer.contents buf

let append = Stdlib.( ^ )
let unsafe_of_string s = s

let is_valid (s : string) : bool =
  try
    let st = Dec.make s in
    while true do
      next_ st ~yield:(fun _ -> ()) ~stop:(fun () -> raise Stop) ()
    done;
    assert false
  with
  | Malformed _ -> false
  | Stop -> true

let of_string_exn s =
  if is_valid s then
    s
  else
    invalid_arg "CCUtf8_string.of_string_exn"

let of_string s =
  if is_valid s then
    Some s
  else
    None