Skip to content

Commit 0f2be16

Browse files
committed
Refactor hexdump_to_buffer_expr
1 parent 3f54124 commit 0f2be16

File tree

1 file changed

+20
-21
lines changed

1 file changed

+20
-21
lines changed

ppx/ppx_cstruct.ml

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -213,28 +213,27 @@ let hexdump_expr s =
213213
]
214214

215215
let hexdump_to_buffer_expr s =
216-
let hexdump =
217-
List.fold_left (fun a f ->
218-
let get_f = op_evar s (Op_get f) in
219-
[%expr
220-
[%e a]; Buffer.add_string buf [%e Ast.str (" "^f.field^" = ")];
221-
[%e match f.ty with
222-
|Prim Char ->
223-
[%expr Printf.bprintf buf "%c\n" ([%e get_f] v)]
224-
|Prim (UInt8|UInt16) ->
225-
[%expr Printf.bprintf buf "0x%x\n" ([%e get_f] v)]
226-
|Prim UInt32 ->
227-
[%expr Printf.bprintf buf "0x%lx\n" ([%e get_f] v)]
228-
|Prim UInt64 ->
229-
[%expr Printf.bprintf buf "0x%Lx\n" ([%e get_f] v)]
230-
|Buffer (_,_) ->
231-
[%expr Printf.bprintf buf "<buffer %s>"
232-
[%e Ast.str (field_to_string f)];
233-
Cstruct.hexdump_to_buffer buf ([%e get_f] v)]
234-
]]
235-
) (Ast.unit ()) s.fields
216+
let prim_format_string = function
217+
| Char -> [%expr "%c\n"]
218+
| UInt8 | UInt16 -> [%expr "0x%x\n"]
219+
| UInt32 -> [%expr "0x%lx\n"]
220+
| UInt64 -> [%expr "0x%Lx\n"]
236221
in
237-
[%expr fun buf v -> [%e hexdump]]
222+
let hexdump_field f =
223+
let get_f = op_evar s (Op_get f) in
224+
let expr =
225+
match f.ty with
226+
|Prim p ->
227+
[%expr Printf.bprintf buf [%e prim_format_string p] ([%e get_f] v)]
228+
|Buffer (_,_) ->
229+
[%expr Printf.bprintf buf "<buffer %s>" [%e Ast.str (field_to_string f)];
230+
Cstruct.hexdump_to_buffer buf ([%e get_f] v)]
231+
in
232+
[%expr
233+
Printf.bprintf buf " %s = " [%e Ast.str f.field];
234+
[%e expr]]
235+
in
236+
[%expr fun buf v -> [%e Ast.sequence (List.map hexdump_field s.fields)]]
238237

239238
let op_expr loc s = function
240239
| Op_sizeof -> Ast.int s.len

0 commit comments

Comments
 (0)