Skip to content

Commit

Permalink
Add enum ValueWriter support.
Browse files Browse the repository at this point in the history
  • Loading branch information
SvenGroot committed Oct 26, 2023
1 parent 8db4d18 commit 8c21109
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Ookii.Jumbo.Test/ValueWriterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ public void TestValueTupleSerialization()
TestSerialization(("test", 1, 2, 3, 4L, true, DateTime.UtcNow, 5.0f));
}

[Test]
public void TestEnumSerialization()
{
TestSerialization(DayOfWeek.Friday);
}

private void TestSerialization<T>(T expected)
{
using (MemoryStream stream = new MemoryStream())
Expand Down
15 changes: 15 additions & 0 deletions src/Ookii.Jumbo/IO/DefaultValueWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,19 @@ public void Write(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> value, BinaryWri
}
}

private class EnumWriter<T, TUnderlying> : IValueWriter<T>
where T : Enum
where TUnderlying : notnull
{
private readonly IValueWriter<TUnderlying> _underlyingWriter = ValueWriter<TUnderlying>.Writer!;

public T Read(BinaryReader reader)
=> (T)Enum.ToObject(typeof(T), _underlyingWriter.Read(reader));

public void Write(T value, BinaryWriter writer)
=> _underlyingWriter.Write((TUnderlying)Convert.ChangeType(value, typeof(TUnderlying)), writer);
}


#endregion

Expand Down Expand Up @@ -606,6 +619,8 @@ public static object GetWriter(Type type)
return new DateTimeWriter();
else if (type == typeof(Boolean))
return new BooleanWriter();
else if (type.IsEnum)
return Activator.CreateInstance(typeof(EnumWriter<,>).MakeGenericType(type, type.GetEnumUnderlyingType()))!;
else if (type.IsGenericType)
{
var definition = type.GetGenericTypeDefinition();
Expand Down

0 comments on commit 8c21109

Please sign in to comment.