From 4dd3c63ba5dc06852ea0815777d7e3ff9b60d17f Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Wed, 12 Jun 2013 19:35:48 +0200 Subject: [PATCH] aesthetic in Bencode --- .ocamlinit | 1 + bencode.ml | 14 ++++++++++++++ bencode.mli | 3 +++ 3 files changed, 18 insertions(+) diff --git a/.ocamlinit b/.ocamlinit index 8719260a..73ae4b14 100644 --- a/.ocamlinit +++ b/.ocamlinit @@ -6,5 +6,6 @@ #require "threads";; #load "thread_containers.cma";; open Gen.Infix;; +#install_printer Bencode.pretty;; (* vim:syntax=ocaml: *) diff --git a/bencode.ml b/bencode.ml index a8c1fec5..65c7b200 100644 --- a/bencode.ml +++ b/bencode.ml @@ -83,6 +83,20 @@ let fmt formatter t = to_buf b t; Format.pp_print_string formatter (Buffer.contents b) +let rec pretty fmt t = match t with + | I i -> Format.fprintf fmt "%d" i + | S s -> Format.fprintf fmt "@[\"%s\"@]" s + | L l -> + Format.fprintf fmt "@[[@,"; + List.iter (fun t' -> Format.fprintf fmt "%a@ " pretty t') l; + Format.fprintf fmt "]@]"; + | D d -> + Format.fprintf fmt "@[{@,"; + SMap.iter + (fun k t' -> Format.fprintf fmt "%a -> %a@ " pretty (S k) pretty t') + d; + Format.fprintf fmt "}@]"; + (** {2 Deserialization (decoding)} *) (** Deserialization is based on the {! decoder} type. Parsing can be diff --git a/bencode.mli b/bencode.mli index 3cb8c1f9..e4fdb5d0 100644 --- a/bencode.mli +++ b/bencode.mli @@ -49,6 +49,9 @@ val to_string : t -> string val to_chan : out_channel -> t -> unit val fmt : Format.formatter -> t -> unit +val pretty : Format.formatter -> t -> unit + (** Print the tree itself, not its encoding *) + (** {2 Deserialization (decoding)} *) (** Deserialization is based on the {! decoder} type. Parsing can be