From 7cbfdd23acf4577f79f8047accafcf6f2e0461a8 Mon Sep 17 00:00:00 2001 From: Magnus Date: Wed, 25 Oct 2023 10:17:38 +0200 Subject: [PATCH] Expand load data at compile time (#570) --- rustler_mix/lib/rustler.ex | 46 ++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/rustler_mix/lib/rustler.ex b/rustler_mix/lib/rustler.ex index 30ccb685..226ff087 100644 --- a/rustler_mix/lib/rustler.ex +++ b/rustler_mix/lib/rustler.ex @@ -120,35 +120,21 @@ defmodule Rustler do quote do @on_load :rustler_init - @doc false - def rustler_init do - # Remove any old modules that may be loaded so we don't get - # {:error, {:upgrade, 'Upgrade not supported by this NIF library.'}} - :code.purge(__MODULE__) - - {otp_app, path} = @load_from - - load_path = - otp_app - |> Application.app_dir(path) - |> to_charlist() - - load_data = _construct_load_data(@load_data, @load_data_fun) - - :erlang.load_nif(load_path, load_data) - end - - defp _construct_load_data(load_data, load_data_fun) do + defmacrop _construct_load_data do default_load_data_value = unquote(default_load_data_value) default_fun_value = unquote(default_fun_value) - case {load_data, load_data_fun} do + case {@load_data, @load_data_fun} do {load_data, ^default_fun_value} -> - load_data + quote do + unquote(load_data) + end {^default_load_data_value, {module, function}} when is_atom(module) and is_atom(function) -> - apply(module, function, []) + quote do + apply(unquote(module), unquote(function), []) + end {^default_load_data_value, provided_value} -> raise """ @@ -164,6 +150,22 @@ defmodule Rustler do """ end end + + @doc false + def rustler_init do + # Remove any old modules that may be loaded so we don't get + # {:error, {:upgrade, 'Upgrade not supported by this NIF library.'}} + :code.purge(__MODULE__) + + {otp_app, path} = @load_from + + load_path = + otp_app + |> Application.app_dir(path) + |> to_charlist() + + :erlang.load_nif(load_path, _construct_load_data()) + end end end