Skip to content

Commit

Permalink
Merge pull request #43 from artemeff/optimize-cast
Browse files Browse the repository at this point in the history
optimize cast to move error_values option higher and update bench script to see reductions
  • Loading branch information
artemeff authored Nov 14, 2022
2 parents 6beeb14 + 2ba15d4 commit cdc11fa
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
9 changes: 6 additions & 3 deletions bench/struct_bench.exs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@ end

Benchee.run(
%{
"make" => fn -> {:ok, _} = Example.make(%{a: "test", b: 1.42, c: %{a: 0, b: 42}, d: %{e: "embeds"}}) end,
"make" => fn ->
{:ok, _} = Example.make(%{a: "test", b: 1.42, c: %{a: 0, b: 42}, d: %{e: "embeds"}})
end,
},
time: 10,
memory_time: 2
time: 3,
memory_time: 3,
reduction_time: 3
)
10 changes: 5 additions & 5 deletions lib/construct/cast.ex
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,9 @@ defmodule Construct.Cast do
params = convert_params(params)
types = convert_types(types)
permitted = Map.keys(types)
error_values = Keyword.get(opts, :error_values, false)

case Enum.reduce(permitted, {%{}, %{}, true}, &process_param(&1, params, types, opts, &2)) do
case Enum.reduce(permitted, {%{}, %{}, true}, &process_param(&1, params, types, error_values, opts, &2)) do
{changes, _errors, true} -> {:ok, changes}
{_changes, errors, false} -> {:error, errors}
end
Expand Down Expand Up @@ -151,11 +152,11 @@ defmodule Construct.Cast do
raise Construct.Error, "expected types to be a {key, value} structure, got: #{inspect(types)}"
end

defp process_param(key, params, types, opts, {changes, errors, valid?}) do
defp process_param(key, params, types, error_values, opts, {changes, errors, valid?}) do
param_key = Atom.to_string(key)
{type, type_opts} = type!(key, types)

case cast_field(param_key, type, type_opts, params, opts) do
case cast_field(param_key, type, type_opts, params, error_values, opts) do
{:ok, value} ->
{Map.put(changes, key, value), errors, valid?}

Expand All @@ -173,9 +174,8 @@ defmodule Construct.Cast do
end
end

defp cast_field(param_key, type, type_opts, params, opts) do
defp cast_field(param_key, type, type_opts, params, error_values, opts) do
default_value = Keyword.get(type_opts, :default, @default_value)
error_values = Keyword.get(opts, :error_values, false)

case params do
%{^param_key => value} when default_value != @default_value and value == default_value ->
Expand Down

0 comments on commit cdc11fa

Please sign in to comment.