From a0cae2af57f8bc4fb7b932a63cd686d838b0e3b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Henry?= Date: Sun, 13 May 2018 20:21:48 +0200 Subject: [PATCH] Data_encoding: enforce fixed-size strings in JSON. --- src/lib_data_encoding/json.ml | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/lib_data_encoding/json.ml b/src/lib_data_encoding/json.ml index c9d41c21f..b36f118e6 100644 --- a/src/lib_data_encoding/json.ml +++ b/src/lib_data_encoding/json.ml @@ -159,8 +159,28 @@ let rec json : type a. a Encoding.desc -> a Json_encoding.encoding = | Bool -> bool | Float -> float | RangedFloat { minimum; maximum } -> ranged_float ~minimum ~maximum "rangedFloat" - | String _ -> string (* TODO: check length *) - | Bytes _ -> bytes_jsont (* TODO check length *) + | String (`Fixed expected) -> + let check s = + let found = String.length s in + if found <> expected then + raise (Cannot_destruct + ([] , + Unexpected (Format.asprintf "string (len %d)" found, + Format.asprintf "string (len %d)" expected))) ; + s in + conv check check string + | String _ -> string + | Bytes (`Fixed expected) -> + let check s = + let found = MBytes.length s in + if found <> expected then + raise (Cannot_destruct + ([] , + Unexpected (Format.asprintf "string (len %d)" found, + Format.asprintf "string (len %d)" expected))) ; + s in + conv check check bytes_jsont + | Bytes _ -> bytes_jsont | String_enum (tbl, _) -> string_enum (Hashtbl.fold (fun a (str, _) acc -> (str, a) :: acc) tbl []) | Array e -> array (get_json e) | List e -> list (get_json e)