diff options
Diffstat (limited to 'lib/concepts')
| -rw-r--r-- | lib/concepts/Encoding.ml | 8 | ||||
| -rw-r--r-- | lib/concepts/Tuple.ml | 14 |
2 files changed, 13 insertions, 9 deletions
diff --git a/lib/concepts/Encoding.ml b/lib/concepts/Encoding.ml index 50eb6e6..34ca3a0 100644 --- a/lib/concepts/Encoding.ml +++ b/lib/concepts/Encoding.ml @@ -113,6 +113,14 @@ module Bencode = struct let as_int = function Int n -> Ok n | _ -> Error (Error.type_mismatch ~expected:"integer") let as_list = function List l -> Ok l | _ -> Error (Error.type_mismatch ~expected:"list") let as_dict = function Dict d -> Ok d | _ -> Error (Error.type_mismatch ~expected:"dict") + let of_map f map = Dict (List.map (fun (k, v) -> k, f v) (BatMap.String.bindings map)) + + let to_map f data = + let open Utilities.Result in + let* kvs = as_dict data in + List.map (fun (k, v) -> f v |> Result.map (fun v -> k, v)) kvs + |> Utilities.List.sequence + |> Result.map BatMap.String.of_list let of_bytes (bytes : bytes) : (t, Condition.condition) result = let open Utilities.Result in diff --git a/lib/concepts/Tuple.ml b/lib/concepts/Tuple.ml index dfb7cbe..943c1f6 100644 --- a/lib/concepts/Tuple.ml +++ b/lib/concepts/Tuple.ml @@ -23,19 +23,15 @@ and Body : Encoding.Record.BODY = struct let fields {type_; attributes} = [ "type", Encoding.Bencode.String type_; - ( "attributes", - Encoding.Bencode.Dict - ( BatMap.String.enum attributes - |> BatEnum.fold (fun acc (name, value) -> (name, bencode_of_value value) :: acc) [] ) ) ] + "attributes", Encoding.Bencode.of_map bencode_of_value attributes ] let of_fields data = let open Utilities.Result in let* type_ = Encoding.Bencode.field "type" data |>> Encoding.Bencode.as_string in - let* kvs = Encoding.Bencode.field "attributes" data |>> Encoding.Bencode.as_dict in - kvs - |> List.map (fun (name, v) -> value_of_bencode v |> Result.map (fun v -> name, v)) - |> Utilities.List.sequence - |> Result.map (fun kvs -> {type_; attributes= BatMap.String.of_list kvs}) + let* attributes = + Encoding.Bencode.field "attributes" data |>> Encoding.Bencode.to_map value_of_bencode + in + Ok {type_; attributes} end let hash tuple = Representation.to_blob tuple |> Hash.hash_of_blob |
