GamePacketFactory.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. public static class GamePacketFactory
  4. {
  5. static readonly Dictionary<byte, Func<byte[], IGamePacket>> Factories = new();
  6. static readonly Dictionary<Type, byte> IdLookup = new();
  7. static byte NextID = 0;
  8. public static void Register<T>(Func<byte[], T> factory) where T : IGamePacket
  9. {
  10. Type type = typeof(T);
  11. if (IdLookup.ContainsKey(type))
  12. {
  13. return;
  14. }
  15. byte id = NextID++;
  16. IdLookup[type] = id;
  17. Factories[id] = bytes => factory(bytes);
  18. }
  19. public static IGamePacket Create(byte id, byte[] bytes)
  20. {
  21. if (!Factories.TryGetValue(id, out var factory))
  22. {
  23. return null;
  24. }
  25. return factory(bytes);
  26. }
  27. public static byte GetId(Type type)
  28. {
  29. if (!IdLookup.TryGetValue(type, out byte id))
  30. {
  31. throw new InvalidOperationException($"{type.Name} is not a registered packet");
  32. }
  33. return id;
  34. }
  35. }