Skip to content

Commit

Permalink
refactor: make it easier to pass options when defining decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
ahamez committed Oct 7, 2024
1 parent 88f5fa0 commit 3a0bca6
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions lib/protox/define_decoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ defmodule Protox.DefineDecoder do
@moduledoc false
# Internal. Generates the decoder of a message.

@default_keep_unknown_field true

alias Protox.Field

use Protox.{
Expand All @@ -23,17 +25,11 @@ defmodule Protox.DefineDecoder do
# The public function to decode the binary protobuf.
decode_fun = make_decode_fun(required_fields, msg_name, vars)

# The function that decoded the binary protobuf and possibly dispatches to other decoding
# The function that decodes the binary protobuf and possibly dispatches to other decoding
# functions.
parse_key_value_fun =
make_parse_key_value_fun(
required_fields,
fields,
vars,
Keyword.get(opts, :keep_unknown_fields, true)
)

# The functions that decode maps.
parse_key_value_fun = make_parse_key_value_fun(required_fields, fields, vars, opts)

# The functions that decodes maps.
parse_map_entries = make_parse_map_entries_funs(vars, fields)

quote do
Expand Down Expand Up @@ -84,11 +80,11 @@ defmodule Protox.DefineDecoder do
end
end

defp make_parse_key_value_fun(required_fields, fields, vars, keep_unknown_fields) do
defp make_parse_key_value_fun(required_fields, fields, vars, opts) do
keep_set_fields = required_fields != []

parse_key_value_body =
make_parse_key_value_body(keep_set_fields, fields, vars, keep_unknown_fields)
make_parse_key_value_body(keep_set_fields, fields, vars, opts)

if keep_set_fields do
quote do
Expand All @@ -111,11 +107,12 @@ defmodule Protox.DefineDecoder do
end
end

defp make_parse_key_value_body(keep_set_fields, fields, vars, keep_unknown_fields) do
defp make_parse_key_value_body(keep_set_fields, fields, vars, opts) do
# Fragment to handle the (invalid) field with tag 0.
tag_0_case = make_parse_key_value_tag_0()

# Fragment to parse unknown fields. Those are identified with an unknown tag.
keep_unknown_fields = Keyword.get(opts, :keep_unknown_fields, @default_keep_unknown_field)
unknown_tag_case = make_parse_key_value_unknown(vars, keep_set_fields, keep_unknown_fields)

# Fragment to parse known fields.
Expand Down

0 comments on commit 3a0bca6

Please sign in to comment.