Skip to content

Commit

Permalink
Accept iolists for Msgpax.Ext
Browse files Browse the repository at this point in the history
  • Loading branch information
lexmag committed Nov 17, 2022
1 parent 5246617 commit 13ebe5e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
11 changes: 7 additions & 4 deletions lib/msgpax/ext.ex
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,15 @@ defmodule Msgpax.Ext do
"""

@type type :: 0..127
@type t :: %__MODULE__{type: type, data: binary}
@type t :: %__MODULE__{type: type, data: iodata}

defstruct [:type, :data]

@doc """
Creates a new `Msgpax.Ext` struct.
`type` must be an integer in `0..127` and it will be used as the type of the
extension (whose meaning depends on your application). `data` must be a binary
extension (whose meaning depends on your application). `data` must be an iodata
containing the serialized extension (whose serialization depends on your
application).
Expand All @@ -88,9 +88,12 @@ defmodule Msgpax.Ext do
iex> Msgpax.Ext.new(24, "foo")
#Msgpax.Ext<24, "foo">
iex> Msgpax.Ext.new(25, 'bar')
#Msgpax.Ext<25, 'bar'>
"""
def new(type, data)
when type in 0..127 and is_binary(data) do
when type in 0..127 and (is_binary(data) or is_list(data)) do
%__MODULE__{type: type, data: data}
end

Expand All @@ -102,7 +105,7 @@ defmodule Msgpax.Ext do
"#Msgpax.Ext<",
Inspect.Integer.inspect(type, opts),
", ",
Inspect.BitString.inspect(data, opts),
to_doc(data, opts),
">"
])
end
Expand Down
2 changes: 1 addition & 1 deletion lib/msgpax/packer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ defimpl Msgpax.Packer, for: [Msgpax.Ext, Msgpax.ReservedExt] do
end

defp format(data) do
size = byte_size(data)
size = IO.iodata_length(data)

cond do
size == 1 -> 0xD4
Expand Down
10 changes: 9 additions & 1 deletion test/msgpax/ext_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ defmodule Msgpax.ExtTest do

defimpl Msgpax.Packer do
def pack(%Sample{seed: seed, size: size}) do
Msgpax.Ext.new(42, String.duplicate(seed, size))
module = if is_list(seed), do: List, else: String

42
|> Msgpax.Ext.new(module.duplicate(seed, size))
|> @protocol.Msgpax.Ext.pack()
end
end
Expand Down Expand Up @@ -86,6 +89,11 @@ defmodule Msgpax.ExtTest do
assert_format Sample.new("G", 1), <<0xD4, 42, ?G>>, output
end

test "iodata input" do
output = Msgpax.Ext.new(42, "HH")
assert_format Sample.new('H', 2), <<0xD5, 42, ?H>>, output
end

test "broken ext" do
assert {:error, %UnpackError{reason: reason}} = Msgpax.unpack(<<0xD4, 42, ?A>>, ext: Broken)
assert reason == {:ext_unpack_failure, Broken, Msgpax.Ext.new(42, "A")}
Expand Down

0 comments on commit 13ebe5e

Please sign in to comment.