Skip to content

Commit

Permalink
Refactor streaming function (qcam#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
qcam authored Dec 17, 2018
1 parent 75bd195 commit a5618a5
Show file tree
Hide file tree
Showing 4 changed files with 168 additions and 165 deletions.
3 changes: 2 additions & 1 deletion .formatter.exs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Used by "mix format"
[
inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"],
line_length: 130
line_length: 130,
locals_without_parens: [defhalt: 1]
]
46 changes: 20 additions & 26 deletions lib/saxy/buffering_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,20 @@ defmodule Saxy.BufferingHelper do

@parser_config Application.get_env(:saxy, :parser, [])

defmacro defhalt(fun_name, arity, token) do
defmacro defhalt(call) do
if streaming_enabled?(@parser_config) do
params_splice = build_params_splice(token, arity)
context_fun = build_context_fun(fun_name, token, arity)

quote do
defp unquote(fun_name)(unquote_splicing(params_splice)) do
{:halted, unquote(context_fun)}
end
case Macro.decompose_call(call) do
{name, args} ->
context_fun = build_context_fun(name, args)

quote do
defp unquote(name)(unquote_splicing(args)) do
{:halted, unquote(context_fun)}
end
end

_invalid ->
raise ArgumentError, "invalid syntax in defhalt #{Macro.to_string(call)}"
end
end
end
Expand All @@ -32,27 +37,16 @@ defmodule Saxy.BufferingHelper do
Keyword.get(config, :streaming, true)
end

defp build_context_fun(fun_name, token, arity) do
default_params = quote(do: [unquote(token) <> cont_buffer, more?, original <> cont_buffer, pos, state])

params = append_acc_variables(default_params, arity)

defp build_context_fun(fun_name, [token, _more?, original | args]) do
quote do
fn cont_buffer, more? ->
unquote(fun_name)(unquote_splicing(params))
unquote(fun_name)(
unquote(token) <> cont_buffer,
more?,
unquote(original) <> cont_buffer,
unquote_splicing(args)
)
end
end
end

defp build_params_splice(token, arity) do
default_params = quote(do: [unquote(token), true, original, pos, state])

append_acc_variables(default_params, arity)
end

defp append_acc_variables(vars, arity) do
acc_count = arity - length(vars)

for(i <- 0..acc_count, i > 0, into: vars, do: Macro.var(:"acc#{i}", __MODULE__))
end
end
Loading

0 comments on commit a5618a5

Please sign in to comment.