Skip to content

Commit d9624ab

Browse files
committed
Add generic EnumCache
1 parent 6640a04 commit d9624ab

File tree

3 files changed

+11
-4
lines changed

3 files changed

+11
-4
lines changed

Source/Common/ByteReader.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ public virtual ulong[] ReadPrefixedULongs()
140140

141141
public virtual T ReadEnum<T>() where T : Enum
142142
{
143-
var values = EnumCache.GetValues(typeof(T));
143+
var values = EnumCache<T>.Values;
144144
ushort enumIndex = values.Length switch
145145
{
146146
<= byte.MaxValue => ReadByte(),

Source/Common/ByteWriter.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Runtime.CompilerServices;
66
using System.Text;
77
using Multiplayer.Common.Util;
8+
using Verse;
89

910
namespace Multiplayer.Common
1011
{
@@ -86,7 +87,7 @@ public virtual ByteWriter WriteString(string? s)
8687

8788
public virtual void WriteEnum<T>(T value) where T : Enum
8889
{
89-
var values = EnumCache.GetValues(value.GetType());
90+
var values = typeof(T) == typeof(Enum) ? EnumCache.Values(value.GetType()) : EnumCache<T>.Values;
9091
var index = Array.IndexOf(values, value);
9192
switch (values.Length)
9293
{

Source/Common/Util/EnumCache.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
using System;
22
using System.Collections.Concurrent;
3+
using System.Linq;
34

45
namespace Multiplayer.Common.Util;
56

7+
internal static class EnumCache<T> where T: Enum
8+
{
9+
public static readonly T[] Values = Enum.GetValues(typeof(T)).Cast<T>().ToArray();
10+
}
11+
612
internal static class EnumCache
713
{
814
private static readonly ConcurrentDictionary<Type, Array> Cache = new();
915

10-
public static Array GetValues(Type enumType) => Cache.GetOrAdd(enumType, Enum.GetValues);
11-
}
16+
public static Array Values(Type enumType) => Cache.GetOrAdd(enumType, Enum.GetValues);
17+
}

0 commit comments

Comments
 (0)