From 5d202005fc509229564381c035f859ec5ffd6058 Mon Sep 17 00:00:00 2001 From: Rutherther Date: Sun, 8 Jan 2023 10:17:15 +0100 Subject: [PATCH] feat(packets): allow multiple packet headers --- .../Attributes/PacketHeaderAttribute.cs | 2 +- .../Packets/PacketTypesRepository.cs | 32 +++++++++++++++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/Packets/NosSmooth.PacketSerializer.Abstractions/Attributes/PacketHeaderAttribute.cs b/Packets/NosSmooth.PacketSerializer.Abstractions/Attributes/PacketHeaderAttribute.cs index bcb3cc603bf4bcaad2504dfe5b0ee6d8dc0b53cd..cf8db3b703780d44215754fd4977a0a9a238bf6e 100644 --- a/Packets/NosSmooth.PacketSerializer.Abstractions/Attributes/PacketHeaderAttribute.cs +++ b/Packets/NosSmooth.PacketSerializer.Abstractions/Attributes/PacketHeaderAttribute.cs @@ -9,7 +9,7 @@ namespace NosSmooth.PacketSerializer.Abstractions.Attributes; /// /// Attribute for specifying the header identifier of the packet. /// -[AttributeUsage(AttributeTargets.Class)] +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class PacketHeaderAttribute : Attribute { /// diff --git a/Packets/NosSmooth.PacketSerializer/Packets/PacketTypesRepository.cs b/Packets/NosSmooth.PacketSerializer/Packets/PacketTypesRepository.cs index 379463c03dd17bc7758732fe91545bb79f02d9d8..da7665053bd5924fcef0a071d8bedb770351cde8 100644 --- a/Packets/NosSmooth.PacketSerializer/Packets/PacketTypesRepository.cs +++ b/Packets/NosSmooth.PacketSerializer/Packets/PacketTypesRepository.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Reflection; using NosSmooth.Packets; using NosSmooth.PacketSerializer.Abstractions; @@ -48,8 +49,8 @@ public class PacketTypesRepository : IPacketTypesRepository (nameof(type), $"The type has to be assignable to IPacket. {type.FullName} isn't."); } - var header = type.GetCustomAttribute(); - if (header is null) + var headers = type.GetCustomAttributes().ToList(); + if (headers.Count == 0) { return new ArgumentInvalidError ( @@ -64,7 +65,32 @@ public class PacketTypesRepository : IPacketTypesRepository return Result.FromError(converterResult); } - var info = new PacketInfo(header.Identifier, type, converterResult.Entity); + if (headers.Count == 1) + { + return AddPacket(headers[0], type, converterResult.Entity); + } + + var errors = new List(); + foreach (var header in headers) + { + var result = AddPacket(header, type, converterResult.Entity); + if (!result.IsSuccess) + { + errors.Add(result); + } + } + + return errors.Count switch + { + 0 => Result.FromSuccess(), + 1 => (Result)errors[0], + _ => new AggregateError(errors) + }; + } + + private Result AddPacket(PacketHeaderAttribute header, Type type, IStringConverter converter) + { + var info = new PacketInfo(header.Identifier, type, converter); if (type.FullName is not null) { if (_typeToPacket.ContainsKey(type.FullName))