From 122d5a7442217150f3939bf81ac3f56c2c43d323 Mon Sep 17 00:00:00 2001 From: Rutherther Date: Sun, 1 Jan 2023 13:30:55 +0100 Subject: [PATCH] feat(packets): do not add the same packet multiple times --- .../Packets/PacketTypesRepository.cs | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/Packets/NosSmooth.PacketSerializer/Packets/PacketTypesRepository.cs b/Packets/NosSmooth.PacketSerializer/Packets/PacketTypesRepository.cs index fd091ef2989895c7785aef70f3da64c6a5d0e690..379463c03dd17bc7758732fe91545bb79f02d9d8 100644 --- a/Packets/NosSmooth.PacketSerializer/Packets/PacketTypesRepository.cs +++ b/Packets/NosSmooth.PacketSerializer/Packets/PacketTypesRepository.cs @@ -6,16 +6,14 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Reflection; -using Microsoft.Extensions.DependencyInjection; -using NosSmooth.Packets.Converters; -using NosSmooth.Packets.Errors; +using NosSmooth.Packets; using NosSmooth.PacketSerializer.Abstractions; using NosSmooth.PacketSerializer.Abstractions.Attributes; +using NosSmooth.PacketSerializer.Errors; using Remora.Results; -namespace NosSmooth.Packets.Packets; +namespace NosSmooth.PacketSerializer.Packets; /// /// Repository of packet types for finding information about packets. @@ -46,13 +44,18 @@ public class PacketTypesRepository : IPacketTypesRepository { if (!typeof(IPacket).IsAssignableFrom(type)) { - return new ArgumentInvalidError(nameof(type), $"The type has to be assignable to IPacket. {type.FullName} isn't."); + return new ArgumentInvalidError + (nameof(type), $"The type has to be assignable to IPacket. {type.FullName} isn't."); } var header = type.GetCustomAttribute(); if (header is null) { - return new ArgumentInvalidError(nameof(type), $"Every packet has to specify the header. {type.FullName} didn't."); + return new ArgumentInvalidError + ( + nameof(type), + $"Every packet has to have a header specified using [PacketHeader] attribute. {type.FullName} doesn't have a header." + ); } var converterResult = _stringConverterRepository.GetTypeConverter(type); @@ -62,15 +65,19 @@ public class PacketTypesRepository : IPacketTypesRepository } var info = new PacketInfo(header.Identifier, type, converterResult.Entity); - - if (!_headerToPacket.ContainsKey(header.Source)) + if (type.FullName is not null) { - _headerToPacket[header.Source] = new Dictionary(); + if (_typeToPacket.ContainsKey(type.FullName)) + { // The packet was already added. + return Result.FromSuccess(); + } + + _typeToPacket[type.FullName] = info; } - if (type.FullName is not null) + if (!_headerToPacket.ContainsKey(header.Source)) { - _typeToPacket[type.FullName] = info; + _headerToPacket[header.Source] = new Dictionary(); } if (header.Identifier is not null)