Skip to content

Commit

Permalink
char decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
benbellick committed Dec 17, 2024
1 parent d91b15b commit 82d9317
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
6 changes: 5 additions & 1 deletion src/decoders_deriver.ml
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,11 @@ let rec expr_of_typ (typ : core_type)
| [%type: float] -> Ast_builder.Default.evar ~loc "D.float"
| [%type: bool] -> Ast_builder.Default.evar ~loc "D.bool"
| [%type: char] ->
failwith "Cannot directly handle character; please cast to string first"
[%expr
let open D.Infix in
D.string >>= fun s ->
if String.length s = 1 then D.succeed @@ String.get s 0
else D.fail "Expected a string of length 1"]
| [%type: string] | [%type: String.t] ->
Ast_builder.Default.evar ~loc "D.string"
| [%type: bytes] | [%type: Bytes.t] ->
Expand Down
15 changes: 12 additions & 3 deletions test/test_decoders.ml
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
module D = Decoders_yojson.Safe.Decode

type my_int = int [@@deriving decoders]

(* type my_int32 = int32 [@@deriving decoders] *)
(* type my_int64 = int64 [@@deriving decoders] *)
type my_float = float [@@deriving decoders]
type my_string = string [@@deriving decoders]
type my_bool = bool [@@deriving decoders]
Expand Down Expand Up @@ -310,3 +307,15 @@ module Ints = struct
| Ok 5438n -> true
| _ -> false
end

type my_char = char [@@deriving decoders]

let%test "char" =
(match D.decode_string my_char_decoder {|"c"|} with
| Ok 'c' -> true
| _ -> false)
&&
match D.decode_string my_char_decoder {|"abc"|} with
(* We expect an error here because the string must have length 1 *)
| Error _ -> true
| _ -> false

0 comments on commit 82d9317

Please sign in to comment.