package catapult-sqlite

  1. Overview
  2. Docs

Source file ev_to_json.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
module P = Catapult
module Out = Catapult_utils.Json_out

let[@inline] field_col oc = Out.char oc ':'
let[@inline] field_sep oc = Out.char oc ','
let any_val oc (j : string) = Out.raw_string oc j

(* emit [k:v] using printer [f] for the value *)
let field oc k f v : unit =
  Out.raw_string oc k;
  field_col oc;
  f oc v

let[@inline] opt_iter o f =
  match o with
  | None -> ()
  | Some x -> f x

let to_json buf (ev : P.Ser.Event.t) : string =
  let {
    P.Ser.Event.id;
    name;
    ph;
    pid;
    tid;
    cat;
    ts_us;
    args;
    stack;
    dur;
    extra;
  } =
    ev
  in

  Buffer.clear buf;
  Out.char buf '{';

  field buf {|"name"|} Out.str_val name;
  field_sep buf;

  field buf {|"ph"|} Out.char_val (Char.chr ph);
  field_sep buf;

  field buf {|"tid"|} Out.int64 tid;
  field_sep buf;

  field buf {|"ts"|} Out.float ts_us;
  field_sep buf;

  opt_iter dur (fun dur ->
      field buf {|"dur"|} Out.float dur;
      field_sep buf);

  opt_iter id (fun i ->
      field buf {|"id"|} Out.str_val i;
      field_sep buf);

  opt_iter stack (fun s ->
      Out.raw_string buf {|"stack"|};
      field_col buf;
      Out.char buf '[';
      Array.iteri
        (fun i x ->
          if i > 0 then field_sep buf;
          any_val buf x)
        s;
      Out.char buf ']';
      field_sep buf);

  opt_iter cat (fun cs ->
      Out.raw_string buf {|"cat"|};
      field_col buf;
      Out.char buf '"';
      Array.iteri
        (fun i x ->
          if i > 0 then field_sep buf;
          Out.raw_string buf x)
        cs;
      Out.char buf '"';
      field_sep buf);

  opt_iter args (fun args ->
      Out.raw_string buf {|"args"|};
      field_col buf;
      Out.char buf '{';
      Array.iteri
        (fun i { P.Ser.Arg.key; value } ->
          if i > 0 then field_sep buf;
          Out.str_val buf key;
          field_col buf;
          match value with
          | P.Ser.Arg_value.Int64 i -> Out.int64 buf i
          | P.Ser.Arg_value.String s -> Out.str_val buf s
          | P.Ser.Arg_value.Float64 f -> Out.float buf f
          | P.Ser.Arg_value.Bool s -> Out.bool buf s
          | P.Ser.Arg_value.Void -> Out.null buf)
        args;
      Out.char buf '}';
      field_sep buf);

  opt_iter extra (fun l ->
      Array.iter
        (fun { P.Ser.Extra.key; value } ->
          Out.str_val buf key;
          field_col buf;
          Out.str_val buf value;
          field_sep buf)
        l);

  field buf {|"pid"|} Out.int64 pid;
  Out.char buf '}';
  Buffer.contents buf