-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathlogfmt.ml
More file actions
41 lines (33 loc) · 1.05 KB
/
logfmt.ml
File metadata and controls
41 lines (33 loc) · 1.05 KB
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
let[@inline] needs_escape c =
Char.code c < 0x20 || c = '"' || c = '\\'
let[@inline] needs_quotes c =
c = ' ' || Char.code c >= 0x80
type cat = Safe | Has_space | Needs_escape
let categorize s : cat =
let quote = ref false in
try
for i=0 to String.length s-1 do
let c = String.unsafe_get s i in
if needs_escape c then raise_notrace Exit;
if needs_quotes c then quote := true
done;
if !quote then Has_space else Safe
with Exit -> Needs_escape
let add_pair buf k v =
Buffer.add_string buf k;
Buffer.add_char buf '=';
match categorize v with
| Safe -> Buffer.add_string buf v
| Has_space -> Printf.bprintf buf {|"%s"|} v
| Needs_escape -> Printf.bprintf buf "%S" v
let rec add_to_buffer buf (pairs:Logger.Pairs.t) : unit =
match pairs with
| [] -> ()
| [k,v] -> add_pair buf k v
| (k,v) :: pairs -> add_pair buf k v; Buffer.add_char buf ' '; add_to_buffer buf pairs
let to_string pairs = match pairs with
| [] -> ""
| _ ->
let buf = Buffer.create 32 in
add_to_buffer buf pairs;
Buffer.contents buf