Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix encode_to_iodata/1 not matching encode/1 behaviour #397

Merged
merged 3 commits into from
Jan 14, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions lib/protobuf/encoder.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ defmodule Protobuf.Encoder do

@spec encode_to_iodata(struct()) :: iodata()
def encode_to_iodata(%mod{} = struct) do
encode_with_message_props(struct, mod.__message_props__())
struct
|> transform_module(mod)
|> do_encode_to_iodata()
end

@spec encode(struct()) :: binary()
Expand All @@ -19,6 +21,10 @@ defmodule Protobuf.Encoder do
|> IO.iodata_to_binary()
end

defp do_encode_to_iodata(%mod{} = struct) do
encode_with_message_props(struct, mod.__message_props__())
end

defp encode_with_message_props(
struct,
%MessageProps{syntax: syntax, field_props: field_props, ordered_tags: ordered_tags} =
Expand Down Expand Up @@ -148,15 +154,15 @@ defmodule Protobuf.Encoder do
defp encode_from_type(mod, msg) do
case msg do
%{__struct__: ^mod} ->
encode_to_iodata(msg)
do_encode_to_iodata(msg)

%other_mod{} = struct ->
raise Protobuf.EncodeError,
message:
"struct #{inspect(other_mod)} can't be encoded as #{inspect(mod)}: #{inspect(struct)}"

_ ->
encode_to_iodata(struct(mod, msg))
do_encode_to_iodata(struct(mod, msg))
end
end

Expand Down
Loading