From 7b3d817a80c184e46dbeae657434c04e96922c35 Mon Sep 17 00:00:00 2001 From: DarkyZ aka NotAVirus <17680522+ImNotAVirus@users.noreply.github.com> Date: Wed, 13 Sep 2023 14:49:09 +0200 Subject: [PATCH] :sparkles: Support :if condition on packet serialization --- lib/elven_gard/network/packet_serializer.ex | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/lib/elven_gard/network/packet_serializer.ex b/lib/elven_gard/network/packet_serializer.ex index 1b2a675..f7f155d 100644 --- a/lib/elven_gard/network/packet_serializer.ex +++ b/lib/elven_gard/network/packet_serializer.ex @@ -221,14 +221,26 @@ defmodule ElvenGard.Network.PacketSerializer do defp def_serialize(%{id: id, fields: fields}) do fields_ast = Enum.map(fields, fn %{name: name, type: type, opts: opts} -> - quote location: :keep do - unquote(type).encode(Map.fetch!(var!(packet), unquote(name)), unquote(opts)) + case Keyword.get(opts, :if) do + nil -> + quote location: :keep do + unquote(type).encode(Map.fetch!(var!(packet), unquote(name)), unquote(opts)) + end + + condition -> + quote location: :keep do + if unquote(condition) in [nil, false] do + :"$drop" + else + unquote(type).encode(Map.fetch!(var!(packet), unquote(name)), unquote(opts)) + end + end end end) quote location: :keep, generated: true do def serialize(%__MODULE__{} = var!(packet)) do - {unquote(id), unquote(fields_ast)} + {unquote(id), Enum.reject(unquote(fields_ast), &match?(:"$drop", &1))} end end end