From d29805e477ee7a77dbaba8429c99b0664ec5e413 Mon Sep 17 00:00:00 2001 From: neuecc Date: Wed, 11 Nov 2026 10:57:42 +0900 Subject: [PATCH 1/6] Harden deserialization against malformed data - MemoryPackReader.GetSpanReference/Advance reject negative size (string header overflow, negative skip of version tolerant object) - byte count calculation of unmanaged array/span is checked - multi dimensional array validates dimensions by collection length before allocate - BrotliStringFormatter checks overflow of byte length before the size limit check - BitArrayFormatter uses public API when the private field layout of BitArray is not matched to BitArrayView (.NET 10 or later), binary format is not changed Valid binary and wire format are not changed. Co-Authored-By: Claude Fable 5.2 --- .../Formatters/BitArrayFormatter.cs | 54 ++++ .../MultiDimensionalArrayFormatters.cs | 24 +- .../Formatters/StringFormatter.cs | 2 +- src/MemoryPack.Core/MemoryPackReader.cs | 29 +- tests/MemoryPack.Tests/MalformedDataTest.cs | 297 ++++++++++++++++++ 5 files changed, 394 insertions(+), 12 deletions(-) create mode 100644 tests/MemoryPack.Tests/MalformedDataTest.cs diff --git a/src/MemoryPack.Core/Formatters/BitArrayFormatter.cs b/src/MemoryPack.Core/Formatters/BitArrayFormatter.cs index eab7fde7..b3979aea 100644 --- a/src/MemoryPack.Core/Formatters/BitArrayFormatter.cs +++ b/src/MemoryPack.Core/Formatters/BitArrayFormatter.cs @@ -1,5 +1,6 @@ using MemoryPack.Internal; using System.Collections; +using System.Reflection; using System.Runtime.CompilerServices; namespace MemoryPack.Formatters; @@ -9,6 +10,40 @@ public sealed class BitArrayFormatter : MemoryPackFormatter { // serialize [m_length, m_array] + // BitArrayView depends on private field layout of BitArray(int[] m_array, int m_length). + // .NET 10 changed it to (byte[] _array, int _bitLength), reinterpreting it reads/writes out of the array. + // When layout is not matched, use public API instead of BitArrayView(binary format is same). + static readonly bool canUseBitArrayView = CanUseBitArrayView(); + + static bool CanUseBitArrayView() + { + try + { + const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic; + if (typeof(BitArray).GetField("m_array", Flags)?.FieldType != typeof(int[]) + || typeof(BitArray).GetField("m_length", Flags)?.FieldType != typeof(int)) + { + return false; + } + + // fields exist but the offsets can be different from BitArrayView(depends on the runtime, for example it has other fields), check it by actual value. + var bitArray = new BitArray(37); + bitArray[36] = true; + ref var view = ref Unsafe.As(ref bitArray); + object? array = view.m_array; + return array != null + && array.GetType() == typeof(int[]) + && view.m_array.Length == 2 + && view.m_array[0] == 0 + && view.m_array[1] == 16 + && view.m_length == 37; + } + catch + { + return false; + } + } + [Preserve] public override void Serialize(ref MemoryPackWriter writer, scoped ref BitArray? value) { @@ -18,6 +53,17 @@ public override void Serialize(ref MemoryPackWriter 0 ? ((length - 1) >> 5) + 1 : 0]; // same as m_array of BitArray(length) + value.CopyTo(array, 0); + + writer.WriteUnmanagedWithObjectHeader(2, length); + writer.WriteUnmanagedArray(array); + return; + } + ref var view = ref Unsafe.As(ref value); writer.WriteUnmanagedWithObjectHeader(2, view.m_length); @@ -37,6 +83,14 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref BitArra reader.ReadUnmanaged(out int length); + if (!canUseBitArrayView) + { + var array = reader.ReadUnmanagedArray(); + value = new BitArray(array ?? Array.Empty()); + value.Length = length; + return; + } + var bitArray = new BitArray(length, false); // create internal int[] and set m_length to length ref var view = ref Unsafe.As(ref bitArray); diff --git a/src/MemoryPack.Core/Formatters/MultiDimensionalArrayFormatters.cs b/src/MemoryPack.Core/Formatters/MultiDimensionalArrayFormatters.cs index b78cdabd..96d0c253 100644 --- a/src/MemoryPack.Core/Formatters/MultiDimensionalArrayFormatters.cs +++ b/src/MemoryPack.Core/Formatters/MultiDimensionalArrayFormatters.cs @@ -71,6 +71,12 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref T?[,]? MemoryPackSerializationException.ThrowInvalidCollection(); } + // length is already validated by buffer size, dimensions(not validated) must be matched to it before allocate. + if (checked((long)iLength * jLength) != length) + { + MemoryPackSerializationException.ThrowMessage($"Array dimensions [{iLength}, {jLength}] are not matched to collection length {length}."); + } + if (value != null && value.GetLength(0) == iLength && value.GetLength(1) == jLength && value.Length == length) { // allow overwrite @@ -83,7 +89,7 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref T?[,]? #if NET7_0_OR_GREATER if (!RuntimeHelpers.IsReferenceOrContainsReferences()) { - var byteCount = Unsafe.SizeOf() * iLength * jLength; + var byteCount = checked(Unsafe.SizeOf() * iLength * jLength); ref var dest = ref MemoryMarshal.GetArrayDataReference(value); ref var src = ref reader.GetSpanReference(byteCount); Unsafe.CopyBlockUnaligned(ref dest, ref src, (uint)byteCount); @@ -182,6 +188,12 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref T?[,,]? MemoryPackSerializationException.ThrowInvalidCollection(); } + // length is already validated by buffer size, dimensions(not validated) must be matched to it before allocate. + if (checked((long)iLength * jLength * kLength) != length) + { + MemoryPackSerializationException.ThrowMessage($"Array dimensions [{iLength}, {jLength}, {kLength}] are not matched to collection length {length}."); + } + if (value != null && value.GetLength(0) == iLength && value.GetLength(1) == jLength && value.GetLength(2) == kLength && value.Length == length) { // allow overwrite @@ -194,7 +206,7 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref T?[,,]? #if NET7_0_OR_GREATER if (!RuntimeHelpers.IsReferenceOrContainsReferences()) { - var byteCount = Unsafe.SizeOf() * iLength * jLength * kLength; + var byteCount = checked(Unsafe.SizeOf() * iLength * jLength * kLength); ref var dest = ref MemoryMarshal.GetArrayDataReference(value); ref var src = ref reader.GetSpanReference(byteCount); Unsafe.CopyBlockUnaligned(ref dest, ref src, (uint)byteCount); @@ -301,6 +313,12 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref T?[,,,] MemoryPackSerializationException.ThrowInvalidCollection(); } + // length is already validated by buffer size, dimensions(not validated) must be matched to it before allocate. + if (checked((long)iLength * jLength * kLength * lLength) != length) + { + MemoryPackSerializationException.ThrowMessage($"Array dimensions [{iLength}, {jLength}, {kLength}, {lLength}] are not matched to collection length {length}."); + } + if (value != null && value.GetLength(0) == iLength && value.GetLength(1) == jLength && value.GetLength(2) == kLength && value.GetLength(3) == lLength && value.Length == length) { // allow overwrite @@ -313,7 +331,7 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref T?[,,,] #if NET7_0_OR_GREATER if (!RuntimeHelpers.IsReferenceOrContainsReferences()) { - var byteCount = Unsafe.SizeOf() * iLength * jLength * kLength * lLength; + var byteCount = checked(Unsafe.SizeOf() * iLength * jLength * kLength * lLength); ref var dest = ref MemoryMarshal.GetArrayDataReference(value); ref var src = ref reader.GetSpanReference(byteCount); Unsafe.CopyBlockUnaligned(ref dest, ref src, (uint)byteCount); diff --git a/src/MemoryPack.Core/Formatters/StringFormatter.cs b/src/MemoryPack.Core/Formatters/StringFormatter.cs index 010ff2f8..70086c91 100644 --- a/src/MemoryPack.Core/Formatters/StringFormatter.cs +++ b/src/MemoryPack.Core/Formatters/StringFormatter.cs @@ -186,7 +186,7 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref string? return; } - var byteLength = length * 2; + var byteLength = checked(length * 2); // security, require to check length if (decompressionSizeLimit < byteLength) diff --git a/src/MemoryPack.Core/MemoryPackReader.cs b/src/MemoryPack.Core/MemoryPackReader.cs index e72d153e..e3e43c0d 100644 --- a/src/MemoryPack.Core/MemoryPackReader.cs +++ b/src/MemoryPack.Core/MemoryPackReader.cs @@ -74,7 +74,8 @@ public MemoryPackReader(ReadOnlySpan buffer, MemoryPackReaderOptionalState [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref byte GetSpanReference(int sizeHint) { - if (sizeHint <= bufferLength) + // compare as unsigned, negative sizeHint(comes from malformed data) never takes this path and is rejected in GetNextSpan. + if ((uint)sizeHint <= (uint)bufferLength) { #if NET7_0_OR_GREATER return ref bufferReference; @@ -89,6 +90,11 @@ public ref byte GetSpanReference(int sizeHint) [MethodImpl(MethodImplOptions.NoInlining)] ref byte GetNextSpan(int sizeHint) { + if (sizeHint < 0) + { + MemoryPackSerializationException.ThrowMessage($"Requested size is {sizeHint}, negative size is invalid."); + } + if (rentBuffer != null) { ArrayPool.Shared.Return(rentBuffer); @@ -154,7 +160,9 @@ public void Advance(int count) if (count == 0) return; var rest = bufferLength - count; - if (rest < 0) + + // same as `rest < 0` but compare as unsigned, negative count(comes from malformed data) always goes to TryAdvanceSequence and is rejected there. + if ((uint)count > (uint)bufferLength) { if (TryAdvanceSequence(count)) { @@ -175,6 +183,11 @@ public void Advance(int count) [MethodImpl(MethodImplOptions.NoInlining)] bool TryAdvanceSequence(int count) { + if (count < 0) + { + MemoryPackSerializationException.ThrowMessage($"Advance count is {count}, negative count is invalid."); + } + var rest = bufferSource.Length - count; if (rest < 0) { @@ -740,7 +753,7 @@ public void ReadUnmanagedSpan(scoped ref Span value) if (length == 0) return Array.Empty(); - var byteCount = length * Unsafe.SizeOf(); + var byteCount = checked(length * Unsafe.SizeOf()); ref var src = ref GetSpanReference(byteCount); var dest = AllocateUninitializedArray(length); Unsafe.CopyBlockUnaligned(ref Unsafe.As(ref GetArrayDataReference(dest)), ref src, (uint)byteCount); @@ -764,7 +777,7 @@ public unsafe void DangerousReadUnmanagedArray(scoped ref T[]? value) return; } - var byteCount = length * Unsafe.SizeOf(); + var byteCount = checked(length * Unsafe.SizeOf()); ref var src = ref GetSpanReference(byteCount); if (value == null || value.Length != length) @@ -793,7 +806,7 @@ public unsafe void DangerousReadUnmanagedSpan(scoped ref Span value) return; } - var byteCount = length * Unsafe.SizeOf(); + var byteCount = checked(length * Unsafe.SizeOf()); ref var src = ref GetSpanReference(byteCount); if (value == null || value.Length != length) @@ -825,7 +838,7 @@ public void ReadSpanWithoutReadLengthHeader(int length, scoped ref Span v value = AllocateUninitializedArray(length); } - var byteCount = length * Unsafe.SizeOf(); + var byteCount = checked(length * Unsafe.SizeOf()); ref var src = ref GetSpanReference(byteCount); ref var dest = ref Unsafe.As(ref MemoryMarshal.GetReference(value)!); Unsafe.CopyBlockUnaligned(ref dest, ref src, (uint)byteCount); @@ -868,7 +881,7 @@ public void ReadPackableSpanWithoutReadLengthHeader(int length, scoped ref Sp value = AllocateUninitializedArray(length); } - var byteCount = length * Unsafe.SizeOf(); + var byteCount = checked(length * Unsafe.SizeOf()); ref var src = ref GetSpanReference(byteCount); ref var dest = ref Unsafe.As(ref MemoryMarshal.GetReference(value)!); Unsafe.CopyBlockUnaligned(ref dest, ref src, (uint)byteCount); @@ -908,7 +921,7 @@ public unsafe void DangerousReadUnmanagedSpanView(out bool isNull, out ReadOn return; } - var byteCount = length * Unsafe.SizeOf(); + var byteCount = checked(length * Unsafe.SizeOf()); ref var src = ref GetSpanReference(byteCount); var span = MemoryMarshal.CreateReadOnlySpan(ref src, byteCount); diff --git a/tests/MemoryPack.Tests/MalformedDataTest.cs b/tests/MemoryPack.Tests/MalformedDataTest.cs new file mode 100644 index 00000000..7f220a6d --- /dev/null +++ b/tests/MemoryPack.Tests/MalformedDataTest.cs @@ -0,0 +1,297 @@ +using MemoryPack.Compression; +using System; +using System.Buffers; +using System.Buffers.Binary; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace MemoryPack.Tests; + +// Malformed(untrusted) binary must be rejected by exception, never read/write outside of the buffer. +public partial class MalformedDataTest +{ + [Theory] + [InlineData(new byte[] { 1, 0, 0, 0, 128 })] // #306 + [InlineData(new byte[] { 1, 0, 0, 0, 128, 0, 0, 0, 0, 97, 98, 99, 100 })] // utf8 length = int.MaxValue + [InlineData(new byte[] { 1, 1, 0, 0, 128, 0, 0, 0, 0, 97, 98, 99, 100 })] // utf8 length = int.MaxValue - 1 + [InlineData(new byte[] { 1, 2, 0, 0, 128, 0, 0, 0, 0, 97, 98, 99, 100 })] // utf8 length = int.MaxValue - 2 + [InlineData(new byte[] { 1, 3, 0, 0, 128, 0, 0, 0, 0, 97, 98, 99, 100 })] // utf8 length = int.MaxValue - 3 + [InlineData(new byte[] { 1, 4, 0, 0, 128, 0, 0, 0, 0, 97, 98, 99, 100 })] // utf8 length = int.MaxValue - 4 + public void Utf8StringHeaderOverflow(byte[] payload) + { + Assert.Throws(() => MemoryPackSerializer.Deserialize(payload)); + Assert.Throws(() => MemoryPackSerializer.Deserialize(new ReadOnlySequence(payload))); + Assert.Throws(() => MemoryPackSerializer.Deserialize(ReadOnlySequenceBuilder.Create(payload.AsSpan(0, 3).ToArray(), payload.AsSpan(3).ToArray()))); + } + + [Fact] + public void VersionTolerantNegativeSkip() + { + // list of 2 elements. + // 1st: declares 2 members(type knows 1), member lengths are VarInt: member[0] = 4 bytes, member[1] = -100. + // 2nd: 1 member. + byte[] element = { 2, 4, 156, 1, 0, 0, 0 }; + var payload = new byte[4 + element.Length + 1 + 4 + 4]; + BinaryPrimitives.WriteInt32LittleEndian(payload, 2); + element.CopyTo(payload, 4); + payload[4 + element.Length] = 1; + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(4 + element.Length + 1), 2147483632); + + Assert.Throws(() => MemoryPackSerializer.Deserialize>(payload)); + Assert.Throws(() => MemoryPackSerializer.Deserialize>(new ReadOnlySequence(payload))); + Assert.Throws(() => MemoryPackSerializer.Deserialize>(ReadOnlySequenceBuilder.Create(payload.AsSpan(0, 6).ToArray(), payload.AsSpan(6).ToArray()))); + } + + [Fact] + public void VersionTolerantSkipIsStillWorking() + { + // unknown member(4 bytes) is skipped. + byte[] payload = { 2, 4, 4, 10, 0, 0, 0, 99, 99, 99, 99 }; + var value = MemoryPackSerializer.Deserialize(payload); + value!.A.Should().Be(10); + } + + [Theory] + [InlineData(-1)] + [InlineData(-4)] + [InlineData(int.MinValue)] + public void ReaderRejectsNegativeSize(int size) + { + var buffer = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + var sequences = new[] + { + new ReadOnlySequence(buffer), + ReadOnlySequenceBuilder.Create(new byte[] { 1, 2, 3 }, new byte[] { 4, 5, 6, 7, 8 }, new byte[] { 9, 10 }) + }; + + foreach (var sequence in sequences) + { + foreach (var advanceBefore in new[] { 0, 2, 4 }) + { + GetSpanReferenceIsFailed(sequence, advanceBefore, size).Should().BeTrue(); + AdvanceIsFailed(sequence, advanceBefore, size).Should().BeTrue(); + } + } + + static bool GetSpanReferenceIsFailed(ReadOnlySequence sequence, int advanceBefore, int size) + { + using var state = MemoryPackReaderOptionalStatePool.Rent(null); + var reader = new MemoryPackReader(sequence, state); + try + { + reader.GetSpanReference(advanceBefore); + reader.Advance(advanceBefore); + try + { + reader.GetSpanReference(size); + } + catch (MemoryPackSerializationException) + { + return true; + } + return false; + } + finally + { + reader.Dispose(); + } + } + + static bool AdvanceIsFailed(ReadOnlySequence sequence, int advanceBefore, int size) + { + using var state = MemoryPackReaderOptionalStatePool.Rent(null); + var reader = new MemoryPackReader(sequence, state); + try + { + reader.GetSpanReference(advanceBefore); + reader.Advance(advanceBefore); + try + { + reader.Advance(size); + } + catch (MemoryPackSerializationException) + { + reader.Consumed.Should().Be(advanceBefore); + return true; + } + return false; + } + finally + { + reader.Dispose(); + } + } + } + + [Fact] + public void UnmanagedArrayNegativeLength() + { + // length = -2 + byte[] payload = { 254, 255, 255, 255, 1, 2, 3, 4, 5, 6, 7, 8 }; + Assert.ThrowsAny(() => MemoryPackSerializer.Deserialize(payload)); + Assert.ThrowsAny(() => MemoryPackSerializer.Deserialize>(payload)); + Assert.ThrowsAny(() => MemoryPackSerializer.Deserialize(payload)); + } + + [Fact] + public void MultiDimensionalArrayDimensionsMismatch() + { + // 2D: dimensions [65536, 32768] but only 8 bytes of data, must not allocate by dimensions. + { + var payload = new byte[1 + 4 + 4 + 4 + 8]; + payload[0] = 3; + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(1), 65536); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(5), 32768); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(9), 8); + Assert.Throws(() => MemoryPackSerializer.Deserialize(payload)); + Assert.Throws(() => MemoryPackSerializer.Deserialize(payload)); + } + // 3D + { + var payload = new byte[1 + 4 + 4 + 4 + 4 + 8]; + payload[0] = 4; + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(1), 2048); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(5), 1024); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(9), 1024); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(13), 8); + Assert.Throws(() => MemoryPackSerializer.Deserialize(payload)); + Assert.Throws(() => MemoryPackSerializer.Deserialize(payload)); + } + // 4D + { + var payload = new byte[1 + 4 + 4 + 4 + 4 + 4 + 8]; + payload[0] = 5; + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(1), 256); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(5), 256); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(9), 256); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(13), 128); + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(17), 8); + Assert.Throws(() => MemoryPackSerializer.Deserialize(payload)); + Assert.Throws(() => MemoryPackSerializer.Deserialize(payload)); + } + } + + [Fact] + public void MultiDimensionalArrayIsStillWorking() + { + { + var value = new int[3, 4]; + var value2 = new string?[3, 4]; + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 4; j++) + { + value[i, j] = i * 10 + j; + value2[i, j] = (i * 10 + j).ToString(); + } + } + var result = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value))!; + var result2 = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value2))!; + (result.GetLength(0), result.GetLength(1)).Should().Be((3, 4)); + (result2.GetLength(0), result2.GetLength(1)).Should().Be((3, 4)); + result.Cast().Should().Equal(value.Cast()); + result2.Cast().Should().Equal(value2.Cast()); + } + { + var value = new int[2, 3, 4]; + var value2 = new int[2, 3, 4, 5]; + var n = 0; + foreach (ref var item in System.Runtime.InteropServices.MemoryMarshal.CreateSpan(ref value[0, 0, 0], value.Length)) item = n++; + foreach (ref var item in System.Runtime.InteropServices.MemoryMarshal.CreateSpan(ref value2[0, 0, 0, 0], value2.Length)) item = n++; + var result = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value))!; + var result2 = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value2))!; + (result.GetLength(0), result.GetLength(1), result.GetLength(2)).Should().Be((2, 3, 4)); + (result2.GetLength(0), result2.GetLength(1), result2.GetLength(2), result2.GetLength(3)).Should().Be((2, 3, 4, 5)); + result.Cast().Should().Equal(value.Cast()); + result2.Cast().Should().Equal(value2.Cast()); + } + { + // zero length dimension + MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(new int[0, 5]))!.GetLength(1).Should().Be(5); + MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(new string[2, 0, 5]))!.GetLength(2).Should().Be(5); + } + } + + [Fact] + public void BrotliStringLengthOverflow() + { + // string length 1073741825, byte length(* 2) overflows int, must not pass decompression size limit check. + var payload = new byte[1 + 4 + 8]; + payload[0] = 1; + BinaryPrimitives.WriteInt32LittleEndian(payload.AsSpan(1), 1073741825); + Assert.Throws(() => MemoryPackSerializer.Deserialize(payload)); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(31)] + [InlineData(32)] + [InlineData(33)] + [InlineData(64)] + [InlineData(100)] + [InlineData(1000)] + public void BitArrayRoundtrip(int length) + { + var value = new BitArray(length); + for (int i = 0; i < length; i += 3) + { + value[i] = true; + } + + var bin = MemoryPackSerializer.Serialize(value); + + // (object header, int length, (int collection length, int[])) + bin.Length.Should().Be(1 + 4 + 4 + ((length + 31) / 32) * 4); + + var value2 = MemoryPackSerializer.Deserialize(bin)!; + value2.Length.Should().Be(length); + for (int i = 0; i < length; i++) + { + value2[i].Should().Be(i % 3 == 0); + } + } + + [Fact] + public void BitArrayBinaryIsSameInAllRuntimes() + { + // BitArray(100), every third bit is true, serialized by .NET 8. + var expected = Convert.FromHexString("02640000000400000049922449922449922449922409000000"); + + var value = new BitArray(100); + for (int i = 0; i < 100; i += 3) + { + value[i] = true; + } + + MemoryPackSerializer.Serialize(value).Should().Equal(expected); + + var value2 = MemoryPackSerializer.Deserialize(expected)!; + value2.Length.Should().Be(100); + for (int i = 0; i < 100; i++) + { + value2[i].Should().Be(i % 3 == 0); + } + } +} + +[MemoryPackable] +public partial class MalformedStringData +{ + public string? Text { get; set; } +} + +[MemoryPackable(GenerateType.VersionTolerant)] +public partial class MalformedVersionTolerantData +{ + [MemoryPackOrder(0)] + public int A { get; set; } +} + +[MemoryPackable] +public partial class MalformedBrotliStringData +{ + [BrotliStringFormatter] + public string? Text { get; set; } +} From c6513bd89f7790ebfb2ead5811ed2a0fa28150af Mon Sep 17 00:00:00 2001 From: neuecc Date: Wed, 11 Nov 2026 10:57:43 +0900 Subject: [PATCH 2/6] Add Net10DateTimeOffset, UnityDateTimeOffset and MEMPACK043 warning DateTimeOffset is serialized as its memory layout but it depends on runtime. - .NET 9 or lower: (short offsetMinutes, long utcTicks) - .NET 10 or later: (int offsetMinutes, long utcTicks) - Unity: (long utcTicks, short offsetMinutes) Net10DateTimeOffset and UnityDateTimeOffset are fixed layout structs that can be converted from/to DateTimeOffset implicitly. - Net10DateTimeOffset: same as .NET 10 or later, can also read the binary of .NET 9 or lower - UnityDateTimeOffset: same as Unity When target framework is lower than .NET 10, source generator reports warning MEMPACK043 for members that use DateTimeOffset. Co-Authored-By: Claude Fable 5.2 --- ...oryPackFormatterProvider.WellknownTypes.cs | 6 + ...oryPackFormatterProvider.WellknownTypes.tt | 3 + src/MemoryPack.Core/Net10DateTimeOffset.cs | 67 ++++++ src/MemoryPack.Core/UnityDateTimeOffset.cs | 67 ++++++ .../DiagnosticDescriptors.cs | 11 + src/MemoryPack.Generator/IGeneratorContext.cs | 2 + .../MemoryPackGenerator.Parser.cs | 59 +++++ .../MemoryPackGenerator.cs | 20 +- .../Net10DateTimeOffsetTest.cs | 206 ++++++++++++++++++ ...GeneratorDiagnosticsTest.DateTimeOffset.cs | 146 +++++++++++++ .../UnityDateTimeOffsetTest.cs | 177 +++++++++++++++ 11 files changed, 758 insertions(+), 6 deletions(-) create mode 100644 src/MemoryPack.Core/Net10DateTimeOffset.cs create mode 100644 src/MemoryPack.Core/UnityDateTimeOffset.cs create mode 100644 tests/MemoryPack.Tests/Net10DateTimeOffsetTest.cs create mode 100644 tests/MemoryPack.Tests/SourceGeneratorTests/GeneratorDiagnosticsTest.DateTimeOffset.cs create mode 100644 tests/MemoryPack.Tests/UnityDateTimeOffsetTest.cs diff --git a/src/MemoryPack.Core/MemoryPackFormatterProvider.WellknownTypes.cs b/src/MemoryPack.Core/MemoryPackFormatterProvider.WellknownTypes.cs index 499692dc..61e7b4a6 100644 --- a/src/MemoryPack.Core/MemoryPackFormatterProvider.WellknownTypes.cs +++ b/src/MemoryPack.Core/MemoryPackFormatterProvider.WellknownTypes.cs @@ -91,6 +91,12 @@ internal static void RegisterWellKnownTypesFormatters() Register(new UnmanagedFormatter()); Register(new UnmanagedArrayFormatter()); Register(new NullableFormatter()); + Register(new UnmanagedFormatter()); + Register(new UnmanagedArrayFormatter()); + Register(new NullableFormatter()); + Register(new UnmanagedFormatter()); + Register(new UnmanagedArrayFormatter()); + Register(new NullableFormatter()); #if NET7_0_OR_GREATER Register(new UnmanagedFormatter()); Register(new UnmanagedArrayFormatter()); diff --git a/src/MemoryPack.Core/MemoryPackFormatterProvider.WellknownTypes.tt b/src/MemoryPack.Core/MemoryPackFormatterProvider.WellknownTypes.tt index 8e735d18..63fd2bc6 100644 --- a/src/MemoryPack.Core/MemoryPackFormatterProvider.WellknownTypes.tt +++ b/src/MemoryPack.Core/MemoryPackFormatterProvider.WellknownTypes.tt @@ -42,6 +42,9 @@ "Vector2", "Vector3", "Vector4", + // MemoryPack + "Net10DateTimeOffset", + "UnityDateTimeOffset", }); var net7UnmanagedTypeNames = new[] diff --git a/src/MemoryPack.Core/Net10DateTimeOffset.cs b/src/MemoryPack.Core/Net10DateTimeOffset.cs new file mode 100644 index 00000000..ec76c93f --- /dev/null +++ b/src/MemoryPack.Core/Net10DateTimeOffset.cs @@ -0,0 +1,67 @@ +using System.Runtime.InteropServices; + +namespace MemoryPack; + +/// +/// compatible struct that binary layout is fixed to the layout of .NET 10 or later(int offsetMinutes, long utcTicks). +/// +/// is serialized as its memory layout but it is different by runtime(.NET 9 or lower is (short offsetMinutes, long utcTicks), Unity is (long utcTicks, short offsetMinutes)). +/// If use this type instead of , the binary is same in all runtimes and it is compatible with of .NET 10 or later. +/// +/// +/// In deserialize, the binary serialized by of .NET 9 or lower can also be read. +/// The binary serialized by of Unity can not be read, use for it. +/// +/// +[StructLayout(LayoutKind.Explicit, Size = 16)] +public readonly struct Net10DateTimeOffset +{ +#pragma warning disable CS0414 // The field is assigned but its value is never used +#pragma warning disable IDE0052 + + // In .NET 9 or lower, DateTimeOffset is (short offsetMinutes, 6 bytes padding, long utcTicks) and padding is not initialized. + // In .NET 10 or later, DateTimeOffset is (int offsetMinutes, 4 bytes padding, long utcTicks). + // Write: offsetMinutes as int(sign extended) and padding as zero, it can be read from the both. + // Read: only uses lower 16 bit of offsetMinutes(valid range of offset is -840 ~ +840), it can read the both. + + [FieldOffset(0)] + readonly int offsetMinutes; + [FieldOffset(4)] + readonly int padding; + [FieldOffset(8)] + readonly long utcTicks; + +#pragma warning restore IDE0052 +#pragma warning restore CS0414 + + public Net10DateTimeOffset(DateTimeOffset value) + { + this.offsetMinutes = (int)(value.Offset.Ticks / TimeSpan.TicksPerMinute); + this.padding = 0; + this.utcTicks = value.UtcTicks; + } + + /// + /// Convert to , throws if the value(comes from malformed data) is out of range. + /// + public DateTimeOffset ToDateTimeOffset() + { + var offsetTicks = (short)offsetMinutes * TimeSpan.TicksPerMinute; + return new DateTimeOffset(unchecked(utcTicks + offsetTicks), new TimeSpan(offsetTicks)); + } + + public static implicit operator Net10DateTimeOffset(DateTimeOffset value) + { + return new Net10DateTimeOffset(value); + } + + public static implicit operator DateTimeOffset(Net10DateTimeOffset value) + { + return value.ToDateTimeOffset(); + } + + public override string ToString() + { + return ToDateTimeOffset().ToString(); + } +} diff --git a/src/MemoryPack.Core/UnityDateTimeOffset.cs b/src/MemoryPack.Core/UnityDateTimeOffset.cs new file mode 100644 index 00000000..c9f0ee09 --- /dev/null +++ b/src/MemoryPack.Core/UnityDateTimeOffset.cs @@ -0,0 +1,67 @@ +using System.Runtime.InteropServices; + +namespace MemoryPack; + +/// +/// compatible struct that binary layout is fixed to the layout of Unity(Mono, IL2CPP)(long utcTicks, short offsetMinutes). +/// +/// is serialized as its memory layout but it is different by runtime(.NET 9 or lower is (short offsetMinutes, long utcTicks), .NET 10 or later is (int offsetMinutes, long utcTicks)). +/// If use this type instead of , the binary is same in all runtimes and it is compatible with the binary serialized by of Unity. +/// +/// +/// If there is no need to read the binary that was serialized in Unity, use . +/// +/// +[StructLayout(LayoutKind.Explicit, Size = 16)] +public readonly struct UnityDateTimeOffset +{ +#pragma warning disable CS0414 // The field is assigned but its value is never used +#pragma warning disable IDE0052 + + // In Unity, layout of DateTimeOffset is not reordered so it is same as the declared order, (long utcTicks, short offsetMinutes, 6 bytes padding) and padding is not initialized. + // Write: padding as zero. + + [FieldOffset(0)] + readonly long utcTicks; + [FieldOffset(8)] + readonly short offsetMinutes; + [FieldOffset(10)] + readonly short padding1; + [FieldOffset(12)] + readonly int padding2; + +#pragma warning restore IDE0052 +#pragma warning restore CS0414 + + public UnityDateTimeOffset(DateTimeOffset value) + { + this.utcTicks = value.UtcTicks; + this.offsetMinutes = (short)(value.Offset.Ticks / TimeSpan.TicksPerMinute); + this.padding1 = 0; + this.padding2 = 0; + } + + /// + /// Convert to , throws if the value(comes from malformed data) is out of range. + /// + public DateTimeOffset ToDateTimeOffset() + { + var offsetTicks = offsetMinutes * TimeSpan.TicksPerMinute; + return new DateTimeOffset(unchecked(utcTicks + offsetTicks), new TimeSpan(offsetTicks)); + } + + public static implicit operator UnityDateTimeOffset(DateTimeOffset value) + { + return new UnityDateTimeOffset(value); + } + + public static implicit operator DateTimeOffset(UnityDateTimeOffset value) + { + return value.ToDateTimeOffset(); + } + + public override string ToString() + { + return ToDateTimeOffset().ToString(); + } +} diff --git a/src/MemoryPack.Generator/DiagnosticDescriptors.cs b/src/MemoryPack.Generator/DiagnosticDescriptors.cs index 50a77087..da82a784 100644 --- a/src/MemoryPack.Generator/DiagnosticDescriptors.cs +++ b/src/MemoryPack.Generator/DiagnosticDescriptors.cs @@ -340,4 +340,15 @@ internal static class DiagnosticDescriptors category: Category, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); + + public const string UseNet10DateTimeOffset = "MemoryPack.Net10DateTimeOffset(compatible with the binary that was serialized in .NET)"; + public const string UseUnityDateTimeOffset = "MemoryPack.UnityDateTimeOffset(compatible with the binary that was serialized in Unity)"; + + public static readonly DiagnosticDescriptor DateTimeOffsetLayoutDependsOnRuntime = new( + id: "MEMPACK043", + title: "DateTimeOffset binary layout depends on runtime", + messageFormat: "The MemoryPackable object '{0}' member '{1}' uses DateTimeOffset, its binary layout depends on runtime(.NET 9 or lower, .NET 10 or later and Unity are all different) so the binary can not be deserialized correctly in the other runtime. Use {2} or {3} instead of DateTimeOffset.", + category: Category, + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true); } diff --git a/src/MemoryPack.Generator/IGeneratorContext.cs b/src/MemoryPack.Generator/IGeneratorContext.cs index e0cef352..d155ef8b 100644 --- a/src/MemoryPack.Generator/IGeneratorContext.cs +++ b/src/MemoryPack.Generator/IGeneratorContext.cs @@ -11,6 +11,8 @@ public interface IGeneratorContext void AddSource(string hintName, string source); LanguageVersion LanguageVersion { get; } bool IsNet7OrGreater { get; } + bool IsNet10OrGreater { get; } + bool IsUnityCompilation { get; } // has UNITY_*** symbol bool IsForUnity { get; } } diff --git a/src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs b/src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs index 0806cd14..0be956bd 100644 --- a/src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs +++ b/src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs @@ -228,6 +228,45 @@ public static (CollectionKind, INamedTypeSymbol?) ParseCollectionKind(INamedType return (CollectionKind.None, null); } + // DateTimeOffset, DateTimeOffset?, DateTimeOffset[], List, (int, DateTimeOffset), unmanaged struct that has DateTimeOffset field, etc. + static bool ContainsDateTimeOffset(ITypeSymbol type, ReferenceSymbols reference, int depth) + { + if (depth > 8) return false; + + if (SymbolEqualityComparer.Default.Equals(type, reference.KnownTypes.System_DateTimeOffset)) + { + return true; + } + + if (type is IArrayTypeSymbol arrayType) + { + return ContainsDateTimeOffset(arrayType.ElementType, reference, depth + 1); + } + + if (type is INamedTypeSymbol namedType) + { + if (namedType.IsGenericType) + { + foreach (var typeArgument in namedType.TypeArguments) + { + if (ContainsDateTimeOffset(typeArgument, reference, depth + 1)) return true; + } + } + + // unmanaged struct is serialized as memory layout so needs to check fields. + // MemoryPackable struct is checked itself(when it is defined in other assembly, it was checked in that assembly). + if (namedType.TypeKind == TypeKind.Struct && namedType.SpecialType == SpecialType.None && namedType.IsUnmanagedType && !namedType.ContainsAttribute(reference.MemoryPackableAttribute)) + { + foreach (var member in namedType.GetMembers()) + { + if (member is IFieldSymbol { IsStatic: false } field && ContainsDateTimeOffset(field.Type, reference, depth + 1)) return true; + } + } + } + + return false; + } + public bool Validate(TypeDeclarationSyntax syntax, IGeneratorContext context, bool unionFormatter) { var noError = true; @@ -484,6 +523,26 @@ public bool Validate(TypeDeclarationSyntax syntax, IGeneratorContext context, bo } } + // DateTimeOffset is serialized as memory layout but it was changed in .NET 10(short offsetMinutes -> int offsetMinutes), and Unity is also different(field order). + // warning only, don't change noError. + if (!context.IsNet10OrGreater) + { + // In Unity, at first recommends UnityDateTimeOffset because Net10DateTimeOffset can not read the existing binary. + var (recommend1, recommend2) = context.IsUnityCompilation + ? (DiagnosticDescriptors.UseUnityDateTimeOffset, DiagnosticDescriptors.UseNet10DateTimeOffset) + : (DiagnosticDescriptors.UseNet10DateTimeOffset, DiagnosticDescriptors.UseUnityDateTimeOffset); + + foreach (var item in Members) + { + if (item.Symbol == null || item.Kind is MemberKind.NonSerializable or MemberKind.RefLike or MemberKind.Blank or MemberKind.CustomFormatter) continue; + + if (ContainsDateTimeOffset(item.MemberType, reference, 0)) + { + context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.DateTimeOffsetLayoutDependsOnRuntime, item.GetLocation(syntax), Symbol.Name, item.Name, recommend1, recommend2)); + } + } + } + // order if (SerializeLayout == SerializeLayout.Explicit) { diff --git a/src/MemoryPack.Generator/MemoryPackGenerator.cs b/src/MemoryPack.Generator/MemoryPackGenerator.cs index 760a4c0a..57300f62 100644 --- a/src/MemoryPack.Generator/MemoryPackGenerator.cs +++ b/src/MemoryPack.Generator/MemoryPackGenerator.cs @@ -64,7 +64,9 @@ void RegisterMemoryPackable(IncrementalGeneratorInitializationContext context) var csOptions = (CSharpParseOptions)parseOptions; var langVersion = csOptions.LanguageVersion; var net7 = csOptions.PreprocessorSymbolNames.Contains("NET7_0_OR_GREATER"); - return (langVersion, net7); + var net10 = csOptions.PreprocessorSymbolNames.Contains("NET10_0_OR_GREATER"); + var unity = csOptions.PreprocessorSymbolNames.Any(x => x.StartsWith("UNITY_", StringComparison.Ordinal)); + return (langVersion, net7, net10, unity); }) .WithTrackingName("MemoryPack.MemoryPackable.0_ParseOptionsProvider"); @@ -108,9 +110,9 @@ or RecordDeclarationSyntax { var (typeDeclaration, compilation) = source.Left.Item1; var logPath = source.Left.Item2; - var (langVersion, net7) = source.Right; + var (langVersion, net7, net10, unity) = source.Right; - Generate(typeDeclaration, compilation, logPath, new GeneratorContext(context, langVersion, net7)); + Generate(typeDeclaration, compilation, logPath, new GeneratorContext(context, langVersion, net7, net10, unity)); }); } { @@ -125,9 +127,9 @@ or RecordDeclarationSyntax { var (typeDeclaration, compilation) = source.Left.Item1; var logPath = source.Left.Item2; - var (langVersion, net7) = source.Right; + var (langVersion, net7, net10, unity) = source.Right; - Generate(typeDeclaration, compilation, logPath, new GeneratorContext(context, langVersion, net7)); + Generate(typeDeclaration, compilation, logPath, new GeneratorContext(context, langVersion, net7, net10, unity)); }); } } @@ -297,11 +299,13 @@ class GeneratorContext : IGeneratorContext { SourceProductionContext context; - public GeneratorContext(SourceProductionContext context, LanguageVersion languageVersion, bool isNet70OrGreater) + public GeneratorContext(SourceProductionContext context, LanguageVersion languageVersion, bool isNet70OrGreater, bool isNet100OrGreater, bool isUnityCompilation) { this.context = context; this.LanguageVersion = languageVersion; this.IsNet7OrGreater = isNet70OrGreater; + this.IsNet10OrGreater = isNet100OrGreater; + this.IsUnityCompilation = isUnityCompilation; } public CancellationToken CancellationToken => context.CancellationToken; @@ -310,6 +314,10 @@ public GeneratorContext(SourceProductionContext context, LanguageVersion languag public bool IsNet7OrGreater { get; } + public bool IsNet10OrGreater { get; } + + public bool IsUnityCompilation { get; } + public bool IsForUnity => false; public void AddSource(string hintName, string source) diff --git a/tests/MemoryPack.Tests/Net10DateTimeOffsetTest.cs b/tests/MemoryPack.Tests/Net10DateTimeOffsetTest.cs new file mode 100644 index 00000000..bf3e8520 --- /dev/null +++ b/tests/MemoryPack.Tests/Net10DateTimeOffsetTest.cs @@ -0,0 +1,206 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace MemoryPack.Tests; + +public partial class Net10DateTimeOffsetTest +{ + public static IEnumerable Values() + { + yield return new object[] { new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(-300)) }; + yield return new object[] { new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(540)) }; + yield return new object[] { new DateTimeOffset(2026, 11, 30, 16, 48, 36, 123, TimeSpan.FromMinutes(345)) }; + yield return new object[] { new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.Zero) }; + yield return new object[] { new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.FromHours(14)) }; + yield return new object[] { new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.FromHours(-14)) }; + yield return new object[] { DateTimeOffset.MinValue }; + yield return new object[] { DateTimeOffset.MaxValue }; + yield return new object[] { new DateTimeOffset(DateTime.MinValue.Ticks + TimeSpan.FromHours(14).Ticks, TimeSpan.FromHours(14)) }; + yield return new object[] { new DateTimeOffset(DateTime.MaxValue.Ticks - TimeSpan.FromHours(14).Ticks, TimeSpan.FromHours(-14)) }; + } + + static void ShouldBeSame(DateTimeOffset actual, DateTimeOffset expected) + { + // DateTimeOffset.Equals only compares UtcDateTime + actual.UtcTicks.Should().Be(expected.UtcTicks); + actual.Offset.Should().Be(expected.Offset); + actual.Ticks.Should().Be(expected.Ticks); + } + + // (int offsetMinutes, int zero, long utcTicks) + static byte[] ExpectedBinary(DateTimeOffset value) + { + var bin = new byte[16]; + BinaryPrimitives.WriteInt32LittleEndian(bin, (int)value.Offset.TotalMinutes); + BinaryPrimitives.WriteInt64LittleEndian(bin.AsSpan(8), value.UtcTicks); + return bin; + } + + [Fact] + public void Size() + { + Unsafe.SizeOf().Should().Be(16); + } + + [Theory] + [MemberData(nameof(Values))] + public void Convert(DateTimeOffset value) + { + Net10DateTimeOffset net10 = value; + DateTimeOffset value2 = net10; + ShouldBeSame(value2, value); + ShouldBeSame(new Net10DateTimeOffset(value).ToDateTimeOffset(), value); + net10.ToString().Should().Be(value.ToString()); + } + + [Theory] + [MemberData(nameof(Values))] + public void BinaryIsFixed(DateTimeOffset value) + { + var expected = ExpectedBinary(value); + + // serialized multiple times to check there is no uninitialized padding. + for (int i = 0; i < 10; i++) + { + MemoryPackSerializer.Serialize(value).Should().Equal(expected); + } + + ShouldBeSame(MemoryPackSerializer.Deserialize(expected), value); + } + + [Fact] + public void KnownBinary() + { + // 2026-11-30T16:48:36-05:00 + var value = new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(-300)); + + // memory dump of DateTimeOffset in .NET 10, (int offsetMinutes, 4 bytes padding, long utcTicks) + var net10 = System.Convert.FromHexString("D4FEFFFF000000000092B5AF2B4FDF08"); + // memory dump of DateTimeOffset in .NET 9, (short offsetMinutes, 6 bytes padding, long utcTicks) + var net9 = System.Convert.FromHexString("D4FE0000000000000092B5AF2B4FDF08"); + + MemoryPackSerializer.Serialize(value).Should().Equal(net10); + + ShouldBeSame(MemoryPackSerializer.Deserialize(net10), value); + ShouldBeSame(MemoryPackSerializer.Deserialize(net9), value); + } + + [Theory] + [MemberData(nameof(Values))] + public void ReadDateTimeOffsetBinaryOfNet9OrLower(DateTimeOffset value) + { + // (short offsetMinutes, 6 bytes padding(not initialized), long utcTicks) + var bin = new byte[16]; + var random = new Random(value.GetHashCode()); + for (int i = 0; i < 20; i++) + { + random.NextBytes(bin.AsSpan(2, 6)); // garbage padding + BinaryPrimitives.WriteInt16LittleEndian(bin, (short)value.Offset.TotalMinutes); + BinaryPrimitives.WriteInt64LittleEndian(bin.AsSpan(8), value.UtcTicks); + + ShouldBeSame(MemoryPackSerializer.Deserialize(bin), value); + } + } + + [Theory] + [MemberData(nameof(Values))] + public void ReadDateTimeOffsetBinaryOfNet10OrLater(DateTimeOffset value) + { + // (int offsetMinutes, 4 bytes padding(not initialized), long utcTicks) + var bin = new byte[16]; + var random = new Random(value.GetHashCode()); + for (int i = 0; i < 20; i++) + { + random.NextBytes(bin.AsSpan(4, 4)); // garbage padding + BinaryPrimitives.WriteInt32LittleEndian(bin, (int)value.Offset.TotalMinutes); + BinaryPrimitives.WriteInt64LittleEndian(bin.AsSpan(8), value.UtcTicks); + + ShouldBeSame(MemoryPackSerializer.Deserialize(bin), value); + } + } + + [Theory] + [MemberData(nameof(Values))] + public void CompatibleWithDateTimeOffsetOfCurrentRuntime(DateTimeOffset value) + { + // Net10DateTimeOffset -> DateTimeOffset, works in all runtimes. + ShouldBeSame(MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value)), value); + + // DateTimeOffset -> Net10DateTimeOffset, works in all runtimes. + ShouldBeSame(MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value)), value); + + // in .NET 10 or later, binary is same(exclude padding). + if (Environment.Version.Major >= 10) + { + var native = MemoryPackSerializer.Serialize(value); + native.AsSpan(4, 4).Clear(); + native.Should().Equal(MemoryPackSerializer.Serialize(value)); + } + } + + [Fact] + public void Members() + { + var value = new Net10DateTimeOffsetData + { + Value = new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(-300)), + Nullable = new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(540)), + NullableNull = null, + Array = Values().Select(x => (Net10DateTimeOffset)(DateTimeOffset)x[0]).ToArray(), + List = Values().Select(x => (Net10DateTimeOffset)(DateTimeOffset)x[0]).ToList(), + }; + + var bin = MemoryPackSerializer.Serialize(value); + var value2 = MemoryPackSerializer.Deserialize(bin)!; + + ShouldBeSame(value2.Value, value.Value); + ShouldBeSame(value2.Nullable!.Value, value.Nullable!.Value); + value2.NullableNull.Should().BeNull(); + value2.Array!.Length.Should().Be(value.Array.Length); + value2.List!.Count.Should().Be(value.List.Count); + for (int i = 0; i < value.Array.Length; i++) + { + ShouldBeSame(value2.Array[i], value.Array[i]); + ShouldBeSame(value2.List[i], value.List[i]); + } + + // array is (int length, Net10DateTimeOffset[]) + var arrayBin = MemoryPackSerializer.Serialize(value.Array); + arrayBin.Length.Should().Be(4 + value.Array.Length * 16); + arrayBin.AsSpan(4).ToArray().Should().Equal(value.Array.SelectMany(x => ExpectedBinary(x)).ToArray()); + } + + [Fact] + public void MalformedData() + { + // offset is out of range(900 minutes) + { + var bin = new byte[16]; + BinaryPrimitives.WriteInt32LittleEndian(bin, 900); + BinaryPrimitives.WriteInt64LittleEndian(bin.AsSpan(8), new DateTime(2026, 11, 30).Ticks); + var value = MemoryPackSerializer.Deserialize(bin); + Assert.Throws(() => value.ToDateTimeOffset()); + } + // ticks is out of range + foreach (var ticks in new[] { -1L, long.MinValue, long.MaxValue, DateTime.MaxValue.Ticks + 1 }) + { + var bin = new byte[16]; + BinaryPrimitives.WriteInt64LittleEndian(bin.AsSpan(8), ticks); + var value = MemoryPackSerializer.Deserialize(bin); + Assert.Throws(() => value.ToDateTimeOffset()); + } + } +} + +[MemoryPackable] +public partial class Net10DateTimeOffsetData +{ + public Net10DateTimeOffset Value { get; set; } + public Net10DateTimeOffset? Nullable { get; set; } + public Net10DateTimeOffset? NullableNull { get; set; } + public Net10DateTimeOffset[]? Array { get; set; } + public List? List { get; set; } +} diff --git a/tests/MemoryPack.Tests/SourceGeneratorTests/GeneratorDiagnosticsTest.DateTimeOffset.cs b/tests/MemoryPack.Tests/SourceGeneratorTests/GeneratorDiagnosticsTest.DateTimeOffset.cs new file mode 100644 index 00000000..1c8d3bbd --- /dev/null +++ b/tests/MemoryPack.Tests/SourceGeneratorTests/GeneratorDiagnosticsTest.DateTimeOffset.cs @@ -0,0 +1,146 @@ +#if NET7_0_OR_GREATER + +using Microsoft.CodeAnalysis; +using System.Linq; + +namespace MemoryPack.Tests; + +public partial class GeneratorDiagnosticsTest +{ + static readonly string[] Net9Symbols = new[] { "NET7_0_OR_GREATER", "NET8_0_OR_GREATER", "NET9_0_OR_GREATER" }; + static readonly string[] Net10Symbols = new[] { "NET7_0_OR_GREATER", "NET8_0_OR_GREATER", "NET9_0_OR_GREATER", "NET10_0_OR_GREATER" }; + static readonly string[] NetStandardSymbols = new[] { "NETSTANDARD2_1" }; + static readonly string[] UnitySymbols = new[] { "NETSTANDARD2_1", "UNITY_5_3_OR_NEWER", "UNITY_2022_3_OR_NEWER", "UNITY_EDITOR" }; + + static string DateTimeOffsetMemberCode(string memberType) + { + return $$""" +using System; +using System.Collections.Generic; +using MemoryPack; + +[MemoryPackable] +public partial class Hoge +{ + public int Id { get; set; } + public {{memberType}} Target { get; set; } +} + +public struct UnmanagedHasDateTimeOffset +{ + public int X; + public DateTimeOffset Y; +} + +public struct UnmanagedHasNoDateTimeOffset +{ + public int X; + public DateTime Y; + public Net10DateTimeOffset Z; + public UnityDateTimeOffset W; +} +"""; + } + + [Theory] + [InlineData("DateTimeOffset")] + [InlineData("DateTimeOffset?")] + [InlineData("DateTimeOffset[]")] + [InlineData("DateTimeOffset?[]")] + [InlineData("List")] + [InlineData("Dictionary")] + [InlineData("Dictionary")] + [InlineData("(int, DateTimeOffset)")] + [InlineData("List")] + [InlineData("UnmanagedHasDateTimeOffset")] + [InlineData("UnmanagedHasDateTimeOffset[]")] + public void MEMPACK043_DateTimeOffsetLayoutDependsOnRuntime(string memberType) + { + var code = DateTimeOffsetMemberCode(memberType); + + foreach (var symbols in new[] { Net9Symbols, NetStandardSymbols, UnitySymbols }) + { + var (_, diagnostics) = CSharpGeneratorRunner.RunGenerator(code, symbols); + diagnostics.Length.Should().Be(1); + diagnostics[0].Id.Should().Be("MEMPACK043"); + diagnostics[0].Severity.Should().Be(DiagnosticSeverity.Warning); + + // recommends both types, Unity is UnityDateTimeOffset first. + var message = diagnostics[0].GetMessage(); + message.Should().Contain("'Hoge' member 'Target'"); + var net10Index = message.IndexOf("MemoryPack.Net10DateTimeOffset"); + var unityIndex = message.IndexOf("MemoryPack.UnityDateTimeOffset"); + net10Index.Should().BeGreaterThan(0); + unityIndex.Should().BeGreaterThan(0); + if (symbols == UnitySymbols) + { + unityIndex.Should().BeLessThan(net10Index); + } + else + { + net10Index.Should().BeLessThan(unityIndex); + } + } + + // .NET 10 or later, no warning. + { + var (_, diagnostics) = CSharpGeneratorRunner.RunGenerator(code, Net10Symbols); + diagnostics.Length.Should().Be(0); + } + } + + [Theory] + [InlineData("Net10DateTimeOffset")] + [InlineData("Net10DateTimeOffset?")] + [InlineData("Net10DateTimeOffset[]")] + [InlineData("List")] + [InlineData("UnityDateTimeOffset")] + [InlineData("UnityDateTimeOffset?")] + [InlineData("UnityDateTimeOffset[]")] + [InlineData("List")] + [InlineData("DateTime")] + [InlineData("TimeSpan")] + [InlineData("List")] + [InlineData("UnmanagedHasNoDateTimeOffset")] + public void MEMPACK043_NoWarning(string memberType) + { + var code = DateTimeOffsetMemberCode(memberType); + + foreach (var symbols in new[] { Net9Symbols, NetStandardSymbols, UnitySymbols, Net10Symbols }) + { + var (_, diagnostics) = CSharpGeneratorRunner.RunGenerator(code, symbols); + diagnostics.Length.Should().Be(0); + } + } + + [Fact] + public void MEMPACK043_IgnoredMemberAndGeneratedCode() + { + // ignored member is not serialized, no warning. + { + var (_, diagnostics) = CSharpGeneratorRunner.RunGenerator(""" +using System; +using MemoryPack; + +[MemoryPackable] +public partial class Hoge +{ + public int Id { get; set; } + [MemoryPackIgnore] + public DateTimeOffset Target { get; set; } +} +""", Net9Symbols); + diagnostics.Length.Should().Be(0); + } + + // warning does not stop code generation, and Net10DateTimeOffset member is compilable. + foreach (var memberType in new[] { "DateTimeOffset", "Net10DateTimeOffset", "UnityDateTimeOffset" }) + { + var (compilation, _) = CSharpGeneratorRunner.RunGenerator(DateTimeOffsetMemberCode(memberType), Net9Symbols); + compilation.SyntaxTrees.Any(x => x.FilePath.Contains("Hoge")).Should().BeTrue(); + compilation.GetDiagnostics().Where(x => x.Severity == DiagnosticSeverity.Error).Should().BeEmpty(); + } + } +} + +#endif diff --git a/tests/MemoryPack.Tests/UnityDateTimeOffsetTest.cs b/tests/MemoryPack.Tests/UnityDateTimeOffsetTest.cs new file mode 100644 index 00000000..195de26a --- /dev/null +++ b/tests/MemoryPack.Tests/UnityDateTimeOffsetTest.cs @@ -0,0 +1,177 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace MemoryPack.Tests; + +public partial class UnityDateTimeOffsetTest +{ + public static IEnumerable Values() => Net10DateTimeOffsetTest.Values(); + + static void ShouldBeSame(DateTimeOffset actual, DateTimeOffset expected) + { + // DateTimeOffset.Equals only compares UtcDateTime + actual.UtcTicks.Should().Be(expected.UtcTicks); + actual.Offset.Should().Be(expected.Offset); + actual.Ticks.Should().Be(expected.Ticks); + } + + // (long utcTicks, short offsetMinutes, 6 bytes zero) + static byte[] ExpectedBinary(DateTimeOffset value) + { + var bin = new byte[16]; + BinaryPrimitives.WriteInt64LittleEndian(bin, value.UtcTicks); + BinaryPrimitives.WriteInt16LittleEndian(bin.AsSpan(8), (short)value.Offset.TotalMinutes); + return bin; + } + + [Fact] + public void Size() + { + Unsafe.SizeOf().Should().Be(16); + } + + [Theory] + [MemberData(nameof(Values))] + public void Convert(DateTimeOffset value) + { + UnityDateTimeOffset unity = value; + DateTimeOffset value2 = unity; + ShouldBeSame(value2, value); + ShouldBeSame(new UnityDateTimeOffset(value).ToDateTimeOffset(), value); + unity.ToString().Should().Be(value.ToString()); + + // Net10DateTimeOffset <-> UnityDateTimeOffset via DateTimeOffset + Net10DateTimeOffset net10 = unity.ToDateTimeOffset(); + UnityDateTimeOffset unity2 = net10.ToDateTimeOffset(); + ShouldBeSame(unity2, value); + } + + [Theory] + [MemberData(nameof(Values))] + public void BinaryIsFixed(DateTimeOffset value) + { + var expected = ExpectedBinary(value); + + // serialized multiple times to check there is no uninitialized padding. + for (int i = 0; i < 10; i++) + { + MemoryPackSerializer.Serialize(value).Should().Equal(expected); + } + + ShouldBeSame(MemoryPackSerializer.Deserialize(expected), value); + } + + [Fact] + public void KnownBinary() + { + // https://github.com/Cysharp/MemoryPack/issues/192 + // class that has one DateTimeOffset member, value is new(2023, 10, 25, 17, 45, 00, TimeSpan.FromHours(8)) + var value = new DateTimeOffset(2023, 10, 25, 17, 45, 00, TimeSpan.FromHours(8)); + + // serialized in Unity 2022.3.7f1 + var unity = new byte[] { 1, 0, 182, 36, 14, 63, 213, 219, 8, 224, 1, 0, 0, 0, 0, 0, 0 }; + // serialized in .NET 7 + var net7 = new byte[] { 1, 224, 1, 0, 0, 0, 0, 0, 0, 0, 182, 36, 14, 63, 213, 219, 8 }; + + ShouldBeSame(MemoryPackSerializer.Deserialize(unity)!.Value, value); + ShouldBeSame(MemoryPackSerializer.Deserialize(net7)!.Value, value); + + MemoryPackSerializer.Serialize(new UnityDateTimeOffsetHolder { Value = value }).Should().Equal(unity); + MemoryPackSerializer.Serialize(new Net10DateTimeOffsetHolder { Value = value }).Should().Equal(net7); // positive offset, same as .NET 10 + } + + [Theory] + [MemberData(nameof(Values))] + public void ReadDateTimeOffsetBinaryOfUnity(DateTimeOffset value) + { + // (long utcTicks, short offsetMinutes, 6 bytes padding(not initialized)) + var bin = new byte[16]; + var random = new Random(value.GetHashCode()); + for (int i = 0; i < 20; i++) + { + random.NextBytes(bin.AsSpan(10, 6)); // garbage padding + BinaryPrimitives.WriteInt64LittleEndian(bin, value.UtcTicks); + BinaryPrimitives.WriteInt16LittleEndian(bin.AsSpan(8), (short)value.Offset.TotalMinutes); + + ShouldBeSame(MemoryPackSerializer.Deserialize(bin), value); + } + } + + [Fact] + public void Members() + { + var value = new UnityDateTimeOffsetData + { + Value = new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(-300)), + Nullable = new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(540)), + NullableNull = null, + Array = Values().Select(x => (UnityDateTimeOffset)(DateTimeOffset)x[0]).ToArray(), + List = Values().Select(x => (UnityDateTimeOffset)(DateTimeOffset)x[0]).ToList(), + }; + + var bin = MemoryPackSerializer.Serialize(value); + var value2 = MemoryPackSerializer.Deserialize(bin)!; + + ShouldBeSame(value2.Value, value.Value); + ShouldBeSame(value2.Nullable!.Value, value.Nullable!.Value); + value2.NullableNull.Should().BeNull(); + value2.Array!.Length.Should().Be(value.Array.Length); + value2.List!.Count.Should().Be(value.List.Count); + for (int i = 0; i < value.Array.Length; i++) + { + ShouldBeSame(value2.Array[i], value.Array[i]); + ShouldBeSame(value2.List[i], value.List[i]); + } + + // array is (int length, UnityDateTimeOffset[]) + var arrayBin = MemoryPackSerializer.Serialize(value.Array); + arrayBin.Length.Should().Be(4 + value.Array.Length * 16); + arrayBin.AsSpan(4).ToArray().Should().Equal(value.Array.SelectMany(x => ExpectedBinary(x)).ToArray()); + } + + [Fact] + public void MalformedData() + { + // offset is out of range(900 minutes) + { + var bin = new byte[16]; + BinaryPrimitives.WriteInt64LittleEndian(bin, new DateTime(2026, 11, 30).Ticks); + BinaryPrimitives.WriteInt16LittleEndian(bin.AsSpan(8), 900); + var value = MemoryPackSerializer.Deserialize(bin); + Assert.Throws(() => value.ToDateTimeOffset()); + } + // ticks is out of range + foreach (var ticks in new[] { -1L, long.MinValue, long.MaxValue, DateTime.MaxValue.Ticks + 1 }) + { + var bin = new byte[16]; + BinaryPrimitives.WriteInt64LittleEndian(bin, ticks); + var value = MemoryPackSerializer.Deserialize(bin); + Assert.Throws(() => value.ToDateTimeOffset()); + } + } +} + +[MemoryPackable] +public partial class UnityDateTimeOffsetHolder +{ + public UnityDateTimeOffset Value { get; set; } +} + +[MemoryPackable] +public partial class Net10DateTimeOffsetHolder +{ + public Net10DateTimeOffset Value { get; set; } +} + +[MemoryPackable] +public partial class UnityDateTimeOffsetData +{ + public UnityDateTimeOffset Value { get; set; } + public UnityDateTimeOffset? Nullable { get; set; } + public UnityDateTimeOffset? NullableNull { get; set; } + public UnityDateTimeOffset[]? Array { get; set; } + public List? List { get; set; } +} From ff5434700821f5c65ee01ee19eca66d99e05ae60 Mon Sep 17 00:00:00 2001 From: neuecc Date: Wed, 11 Nov 2026 10:57:43 +0900 Subject: [PATCH 3/6] Add SafeNullable Nullable of unmanaged type is serialized as its memory layout (bool hasValue, padding, T value) and the padding is not initialized, so the binary of the same value is not always same. SafeNullable is (T hasValue, T value), it has no padding. When T is primitive or enum, the binary is compatible with Nullable. Co-Authored-By: Claude Fable 5.2 --- src/MemoryPack.Core/SafeNullable.cs | 128 +++++++++ tests/MemoryPack.Tests/SafeNullableTest.cs | 310 +++++++++++++++++++++ 2 files changed, 438 insertions(+) create mode 100644 src/MemoryPack.Core/SafeNullable.cs create mode 100644 tests/MemoryPack.Tests/SafeNullableTest.cs diff --git a/src/MemoryPack.Core/SafeNullable.cs b/src/MemoryPack.Core/SafeNullable.cs new file mode 100644 index 00000000..b2ed1611 --- /dev/null +++ b/src/MemoryPack.Core/SafeNullable.cs @@ -0,0 +1,128 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace MemoryPack; + +/// +/// compatible struct that has no padding. +/// +/// of unmanaged type is serialized as its memory layout(bool hasValue, padding, T value) and the padding is not initialized, +/// so the binary of the same value is not always same and it may include the garbage of memory. +/// This type is (T hasValue, T value) so there is no padding, the binary of the same value is always same. +/// +/// +/// When T is primitive type(int, long, double, bool, etc...) or enum, the binary is compatible with (the both can read each other). +/// In other types(Guid, decimal, user-defined struct, etc...), the binary is NOT compatible with . +/// +/// +[StructLayout(LayoutKind.Sequential)] +public readonly struct SafeNullable : IEquatable> + where T : unmanaged +{ + // Nullable is (bool hasValue, [alignment of T - 1] bytes padding, T value). + // If size of T is same as alignment of T(primitives, enum), (T hasValue, T value) is the same layout and has no padding. + // Write: first byte of hasValue is 0 or 1, others are zero. + // Read: only uses first byte of hasValue, it can read the binary of Nullable that padding is not initialized. + + readonly T hasValue; + readonly T value; + + public SafeNullable(T value) + { + this.hasValue = CreateHasValue(); + this.value = value; + } + + public SafeNullable(T? value) + { + if (value.HasValue) + { + this.hasValue = CreateHasValue(); + this.value = value.GetValueOrDefault(); + } + else + { + this.hasValue = default; + this.value = default; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static T CreateHasValue() + { + var hasValue = default(T); + Unsafe.As(ref hasValue) = 1; + return hasValue; + } + + public bool HasValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + return Unsafe.As(ref Unsafe.AsRef(in hasValue)) != 0; + } + } + + public T Value + { + get + { + if (!HasValue) + { + throw new InvalidOperationException("SafeNullable object must have a value."); + } + return value; + } + } + + public T GetValueOrDefault() + { + return HasValue ? value : default; + } + + public T GetValueOrDefault(T defaultValue) + { + return HasValue ? value : defaultValue; + } + + public T? ToNullable() + { + return HasValue ? value : null; + } + + public static implicit operator SafeNullable(T? value) + { + return new SafeNullable(value); + } + + public static implicit operator T?(SafeNullable value) + { + return value.ToNullable(); + } + + public bool Equals(SafeNullable other) + { + if (!HasValue) return !other.HasValue; + if (!other.HasValue) return false; + return EqualityComparer.Default.Equals(value, other.value); + } + + public override bool Equals(object? obj) + { + if (obj is SafeNullable other) return Equals(other); + if (obj == null) return !HasValue; + if (obj is T otherValue) return HasValue && EqualityComparer.Default.Equals(value, otherValue); + return false; + } + + public override int GetHashCode() + { + return HasValue ? value.GetHashCode() : 0; + } + + public override string ToString() + { + return HasValue ? (value.ToString() ?? "") : ""; + } +} diff --git a/tests/MemoryPack.Tests/SafeNullableTest.cs b/tests/MemoryPack.Tests/SafeNullableTest.cs new file mode 100644 index 00000000..280a780f --- /dev/null +++ b/tests/MemoryPack.Tests/SafeNullableTest.cs @@ -0,0 +1,310 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace MemoryPack.Tests; + +public partial class SafeNullableTest +{ + public enum ByteEnum : byte { A, B, C = 255 } + public enum IntEnum { A, B, C = int.MinValue } + public enum LongEnum : long { A, B, C = long.MaxValue } + + // primitives and enum are compatible with Nullable + [Fact] + public void CompatibleWithNullable() + { + Compatible(true, false); + Compatible(0, 1, 255); + Compatible(0, 1, -1, sbyte.MinValue); + Compatible(0, 1, -1, short.MinValue, short.MaxValue); + Compatible(0, 1, ushort.MaxValue); + Compatible(0, 1, -1, int.MinValue, int.MaxValue); + Compatible(0, 1, uint.MaxValue); + Compatible(0, 1, -1, long.MinValue, long.MaxValue); + Compatible(0, 1, ulong.MaxValue); + Compatible(0, 1.5f, -1.5f, float.NaN, float.MaxValue); + Compatible(0, 1.5, -1.5, double.NaN, double.MaxValue); + Compatible('\0', 'a', char.MaxValue); + Compatible(ByteEnum.A, ByteEnum.B, ByteEnum.C); + Compatible(IntEnum.A, IntEnum.B, IntEnum.C); + Compatible(LongEnum.A, LongEnum.B, LongEnum.C); + Compatible(default, new DateTime(2026, 11, 30, 16, 48, 36, DateTimeKind.Utc), DateTime.MaxValue); + Compatible(default, TimeSpan.FromMinutes(-300), TimeSpan.MaxValue); + } + + static void Compatible(params T[] values) + where T : unmanaged + { + var size = Unsafe.SizeOf(); + + // same size as Nullable, and always twice of T(no padding). + Unsafe.SizeOf>().Should().Be(Unsafe.SizeOf(), typeof(T).Name); + Unsafe.SizeOf>().Should().Be(size * 2, typeof(T).Name); + + foreach (var value in values) + { + // (hasValue = (1, 0...), value) + var expected = new byte[size * 2]; + expected[0] = 1; + MemoryMarshal.Write(expected.AsSpan(size), ref Unsafe.AsRef(in value)); + + // serialized multiple times, always same. + for (int i = 0; i < 10; i++) + { + MemoryPackSerializer.Serialize(new SafeNullable(value)).Should().Equal(expected); + MemoryPackSerializer.Serialize>(value).Should().Equal(expected); + } + + // SafeNullable -> Nullable + var nullable = MemoryPackSerializer.Deserialize(expected); + nullable.HasValue.Should().BeTrue(); + AsBytes(nullable.GetValueOrDefault()).Should().Equal(AsBytes(value)); + + // Nullable -> SafeNullable + var safe = MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(value)); + safe.HasValue.Should().BeTrue(); + AsBytes(safe.Value).Should().Equal(AsBytes(value)); + + // Nullable that padding is not initialized -> SafeNullable + var garbage = (byte[])expected.Clone(); + for (int i = 1; i < size; i++) + { + garbage[i] = (byte)(200 + i); + } + safe = MemoryPackSerializer.Deserialize>(garbage); + safe.HasValue.Should().BeTrue(); + AsBytes(safe.Value).Should().Equal(AsBytes(value)); + } + + // null is all zero + { + var expected = new byte[size * 2]; + for (int i = 0; i < 10; i++) + { + MemoryPackSerializer.Serialize(new SafeNullable(null)).Should().Equal(expected); + MemoryPackSerializer.Serialize(default(SafeNullable)).Should().Equal(expected); + MemoryPackSerializer.Serialize>(null).Should().Equal(expected); + } + + MemoryPackSerializer.Deserialize(expected).HasValue.Should().BeFalse(); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(null)).HasValue.Should().BeFalse(); + + // Nullable(null) that padding is not initialized + var garbage = (byte[])expected.Clone(); + for (int i = 1; i < size; i++) + { + garbage[i] = (byte)(200 + i); + } + MemoryPackSerializer.Deserialize>(garbage).HasValue.Should().BeFalse(); + } + } + + static byte[] AsBytes(T value) + where T : unmanaged + { + return MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref value, 1)).ToArray(); + } + + // not compatible with Nullable but can roundtrip itself. + [Fact] + public void NotCompatibleTypes() + { + Unsafe.SizeOf>().Should().Be(32); + Unsafe.SizeOf>().Should().NotBe(Unsafe.SizeOf()); + + var guid = Guid.NewGuid(); + var bin = MemoryPackSerializer.Serialize>(guid); + bin.Length.Should().Be(32); + bin.AsSpan(0, 16).ToArray().Should().Equal(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + MemoryPackSerializer.Deserialize>(bin).Value.Should().Be(guid); + + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize>(123.456m)).Value.Should().Be(123.456m); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize>(null)).HasValue.Should().BeFalse(); + } + + [Fact] + public void Api() + { + SafeNullable hasValue = 10; + SafeNullable isNull = null; + SafeNullable isDefault = default; + int? nullable = hasValue; + int? nullableNull = isNull; + + hasValue.HasValue.Should().BeTrue(); + hasValue.Value.Should().Be(10); + hasValue.GetValueOrDefault().Should().Be(10); + hasValue.GetValueOrDefault(99).Should().Be(10); + hasValue.ToNullable().Should().Be(10); + hasValue.ToString().Should().Be("10"); + nullable.Should().Be(10); + ((int)hasValue).Should().Be(10); + (hasValue == 10).Should().BeTrue(); + (hasValue == null).Should().BeFalse(); + + foreach (var item in new[] { isNull, isDefault, new SafeNullable(null) }) + { + item.HasValue.Should().BeFalse(); + Assert.Throws(() => item.Value); + item.GetValueOrDefault().Should().Be(0); + item.GetValueOrDefault(99).Should().Be(99); + item.ToNullable().Should().BeNull(); + item.ToString().Should().Be(""); + (item == null).Should().BeTrue(); + } + nullableNull.Should().BeNull(); + + // equality + hasValue.Equals(new SafeNullable(10)).Should().BeTrue(); + hasValue.Equals(new SafeNullable(11)).Should().BeFalse(); + hasValue.Equals(isNull).Should().BeFalse(); + isNull.Equals(hasValue).Should().BeFalse(); + isNull.Equals(isDefault).Should().BeTrue(); + hasValue.Equals((object)10).Should().BeTrue(); + hasValue.Equals((object)new SafeNullable(10)).Should().BeTrue(); + isNull.Equals((object?)null).Should().BeTrue(); + hasValue.GetHashCode().Should().Be(10.GetHashCode()); + isNull.GetHashCode().Should().Be(0); + + // deserialized from the binary of Nullable that has garbage padding is equal to the fresh value. + var fromGarbage = MemoryPackSerializer.Deserialize>(new byte[] { 1, 201, 202, 203, 10, 0, 0, 0 }); + fromGarbage.Equals(hasValue).Should().BeTrue(); + fromGarbage.GetHashCode().Should().Be(hasValue.GetHashCode()); + } + + [Fact] + public void Members() + { + var value = new SafeNullableData + { + Int = 10, + IntNull = null, + Long = long.MinValue, + Bool = true, + Enum = IntEnum.C, + Double = 1.5, + Array = new SafeNullable[] { 1, null, 3 }, + List = new List> { null, 2, 3 }, + Text = "foo", + }; + + var bin = MemoryPackSerializer.Serialize(value); + var value2 = MemoryPackSerializer.Deserialize(bin)!; + + value2.Int.Should().Be(value.Int); + value2.IntNull.HasValue.Should().BeFalse(); + value2.Long.Should().Be(value.Long); + value2.Bool.Should().Be(value.Bool); + value2.Enum.Should().Be(value.Enum); + value2.Double.Should().Be(value.Double); + value2.Array.Should().Equal(value.Array); + value2.List.Should().Equal(value.List); + value2.Text.Should().Be("foo"); + + // same binary as the object that uses Nullable(when padding is zero), and can read each other. + var nullableValue = MemoryPackSerializer.Deserialize(bin)!; + nullableValue.Int.Should().Be(10); + nullableValue.IntNull.Should().BeNull(); + nullableValue.Long.Should().Be(long.MinValue); + nullableValue.Bool.Should().Be(true); + nullableValue.Enum.Should().Be(IntEnum.C); + nullableValue.Double.Should().Be(1.5); + nullableValue.Array.Should().Equal(1, null, 3); + nullableValue.List.Should().Equal(null, 2, 3); + nullableValue.Text.Should().Be("foo"); + + var value3 = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(nullableValue))!; + value3.Int.Should().Be(value.Int); + value3.IntNull.HasValue.Should().BeFalse(); + value3.Long.Should().Be(value.Long); + value3.Bool.Should().Be(value.Bool); + value3.Enum.Should().Be(value.Enum); + value3.Double.Should().Be(value.Double); + value3.Array.Should().Equal(value.Array); + value3.List.Should().Equal(value.List); + value3.Text.Should().Be("foo"); + } + + [Fact] + public void BinaryIsDeterministic() + { + // https://github.com/Cysharp/MemoryPack/issues/381 + // https://github.com/Cysharp/MemoryPack/issues/475 + byte[]? first = null; + for (int i = 0; i < 100; i++) + { + PoisonStack((byte)i); + var bin = Serialize(i); + if (first == null) + { + first = bin; + } + else + { + bin.Should().Equal(first); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static byte[] Serialize(int i) + { + var value = new SafeNullableData + { + Int = 10, + IntNull = (i < 0) ? 1 : null, + Long = 20, + Bool = true, + Enum = IntEnum.B, + Double = 1.5, + Array = new SafeNullable[] { 1, null, 3 }, + List = new List> { null, 2, 3 }, + Text = "foo", + }; + return MemoryPackSerializer.Serialize(value); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static void PoisonStack(byte value) + { + Span s = stackalloc byte[2048]; + s.Fill(value); + Consume(s); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static void Consume(Span _) + { + } + } +} + +[MemoryPackable] +public partial class SafeNullableData +{ + public SafeNullable Int { get; set; } + public SafeNullable IntNull { get; set; } + public SafeNullable Long { get; set; } + public SafeNullable Bool { get; set; } + public SafeNullable Enum { get; set; } + public SafeNullable Double { get; set; } + public SafeNullable[]? Array { get; set; } + public List>? List { get; set; } + public string? Text { get; set; } +} + +[MemoryPackable] +public partial class NullableData +{ + public int? Int { get; set; } + public int? IntNull { get; set; } + public long? Long { get; set; } + public bool? Bool { get; set; } + public SafeNullableTest.IntEnum? Enum { get; set; } + public double? Double { get; set; } + public int?[]? Array { get; set; } + public List? List { get; set; } + public string? Text { get; set; } +} From 31b16f5223b98178ad9eda9d816dab6e1dae2d44 Mon Sep 17 00:00:00 2001 From: neuecc Date: Wed, 11 Nov 2026 10:57:43 +0900 Subject: [PATCH 4/6] Add Net10DateTimeOffset, UnityDateTimeOffset and SafeNullable to README Co-Authored-By: Claude Fable 5.2 --- README.md | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 08eec058..e675a201 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,69 @@ These types can be serialized by default: * `ConcurrentBag<>`, `ConcurrentQueue<>`, `ConcurrentStack<>`, `ConcurrentDictionary<,>`, `BlockingCollection<>` * Immutable collections (`ImmutableList<>`, etc.) and interfaces (`IImmutableList<>`, etc.) +### DateTimeOffset, Net10DateTimeOffset and UnityDateTimeOffset + +`DateTimeOffset` is serialized as its memory layout, but the layout depends on the runtime. + +| Runtime | Layout of `DateTimeOffset` | +| --- | --- | +| .NET 9 or lower | `short offsetMinutes`, `long utcTicks` | +| .NET 10 or later | `int offsetMinutes`, `long utcTicks` | +| Unity | `long utcTicks`, `short offsetMinutes` | + +Therefore, a binary serialized in .NET 9 or lower can not be deserialized correctly in .NET 10 or later (the reverse direction is OK), and a binary of Unity is not compatible with .NET. + +To avoid this problem, MemoryPack provides `Net10DateTimeOffset` and `UnityDateTimeOffset`. These are structs that only hold the fields in a fixed layout and can be converted from/to `DateTimeOffset` implicitly. Their binary is the same in all runtimes. + +* `Net10DateTimeOffset` - the same layout as `DateTimeOffset` of .NET 10 or later. It can also read a binary that was serialized as `DateTimeOffset` in .NET 9 or lower. Use this if your existing binary was serialized in .NET, or you don't have an existing binary. +* `UnityDateTimeOffset` - the same layout as `DateTimeOffset` of Unity. Use this if your existing binary was serialized in Unity. + +```csharp +[MemoryPackable] +public partial class Sample +{ + // DateTimeOffset -> Net10DateTimeOffset + public Net10DateTimeOffset Time { get; set; } + public Net10DateTimeOffset? NullableTime { get; set; } + public Net10DateTimeOffset[]? Times { get; set; } +} + +var sample = new Sample { Time = DateTimeOffset.Now }; // implicit conversion +DateTimeOffset time = sample.Time; // implicit conversion(or `ToDateTimeOffset()`) +``` + +| Serialized by | Deserialize as `DateTimeOffset` in .NET 9 or lower | Deserialize as `DateTimeOffset` in .NET 10 or later | Deserialize as `Net10DateTimeOffset` | +| --- | --- | --- | --- | +| `DateTimeOffset` in .NET 9 or lower | OK | **Broken** | OK | +| `DateTimeOffset` in .NET 10 or later | OK | OK | OK | +| `Net10DateTimeOffset` | OK | OK | OK | + +When the target framework is lower than .NET 10 (including Unity), the source generator reports warning `MEMPACK043` for members that use `DateTimeOffset` (including `DateTimeOffset?`, `DateTimeOffset[]`, `List`, etc.). If you already use .NET 10 or later and need to read a binary that was serialized in .NET 9 or lower, also use `Net10DateTimeOffset` for that member. + +> [!NOTE] +> `Net10DateTimeOffset` can not read a binary that was serialized as `DateTimeOffset` in Unity, and `UnityDateTimeOffset` can not read a binary that was serialized as `DateTimeOffset` in .NET. Choose the type by the runtime that serialized your existing binary. + +### SafeNullable + +`Nullable` of an unmanaged type (`int?`, `long?`, etc.) is serialized as its memory layout (`bool hasValue`, padding, `T value`). The padding is not initialized, so the binary of the same value is not always the same (for example, a hash of the binary can be different in each run), and it may include garbage of the memory. + +`SafeNullable` is a struct that has no padding (`T hasValue`, `T value`), the binary of the same value is always the same. It can be converted from/to `Nullable` implicitly. + +```csharp +[MemoryPackable] +public partial class Sample +{ + // int? -> SafeNullable + public SafeNullable Id { get; set; } + public SafeNullable[]? Values { get; set; } +} + +var sample = new Sample { Id = 10 }; // implicit conversion(also `= null`) +int? id = sample.Id; // implicit conversion(or `ToNullable()`, `HasValue`, `Value`, `GetValueOrDefault()`) +``` + +When `T` is a primitive type (`int`, `long`, `double`, `bool`, etc.) or an `enum`, the binary is compatible with `Nullable`, so you can replace `T?` with `SafeNullable` and both can read each other's binary. In other types (`Guid`, `decimal`, user-defined struct, etc.), the size is different from `Nullable` and the binary is **not** compatible. + Define `[MemoryPackable]` `class` / `struct` / `record` / `record struct` --- `[MemoryPackable]` can annotate to any `class`, `struct`, `record`, `record struct` and `interface`. If a type is `struct` or `record struct` which contains no reference types ([C# Unmanaged types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/unmanaged-types)) any additional annotation (ignore, include, constructor, callbacks) is not used, that serialize/deserialize directly from the memory. @@ -1382,7 +1445,7 @@ The `MemoryPack.UnityShims` package provides shims for Unity's standard structs - The affected types typically include the following types. - `DateTimeOffset` - `ValueTuple` - - Currently, the simple solution is to not use these types. + - Currently, the simple solution is to not use these types. For `DateTimeOffset`, you can use `Net10DateTimeOffset` or `UnityDateTimeOffset` instead, see [DateTimeOffset, Net10DateTimeOffset and UnityDateTimeOffset](#datetimeoffset-net10datetimeoffset-and-unitydatetimeoffset). Native AOT From a7a35d594335f34c14e5836e2c445b6c67bf1508 Mon Sep 17 00:00:00 2001 From: neuecc Date: Wed, 11 Nov 2026 10:57:43 +0900 Subject: [PATCH 5/6] Add Unity tests for compatible types, BitArray and malformed data Co-Authored-By: Claude Fable 5.2 --- .../Assets/Tests/CompatTypesTest.cs | 322 ++++++++++++++++++ .../Assets/Tests/CompatTypesTest.cs.meta | 11 + .../Tests/MemoryPackObjects/CompatTypes.cs | 65 ++++ .../MemoryPackObjects/CompatTypes.cs.meta | 11 + 4 files changed, 409 insertions(+) create mode 100644 src/MemoryPack.Unity/Assets/Tests/CompatTypesTest.cs create mode 100644 src/MemoryPack.Unity/Assets/Tests/CompatTypesTest.cs.meta create mode 100644 src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CompatTypes.cs create mode 100644 src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CompatTypes.cs.meta diff --git a/src/MemoryPack.Unity/Assets/Tests/CompatTypesTest.cs b/src/MemoryPack.Unity/Assets/Tests/CompatTypesTest.cs new file mode 100644 index 00000000..068e64a8 --- /dev/null +++ b/src/MemoryPack.Unity/Assets/Tests/CompatTypesTest.cs @@ -0,0 +1,322 @@ +using MemoryPack; +using MemoryPack.Tests.Models; +using NUnit.Framework; +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +// Net10DateTimeOffset, UnityDateTimeOffset, SafeNullable, BitArray and malformed data checks in Unity(Mono, IL2CPP). +public class CompatTypesTest +{ + static readonly DateTimeOffset[] Values = new[] + { + new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(-300)), + new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(540)), + new DateTimeOffset(2023, 10, 25, 17, 45, 0, TimeSpan.FromHours(8)), + new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.Zero), + DateTimeOffset.MinValue, + DateTimeOffset.MaxValue, + }; + + static string ToHex(byte[] bytes) + { + return BitConverter.ToString(bytes); + } + + static void AreSame(DateTimeOffset expected, DateTimeOffset actual) + { + Assert.AreEqual(expected.UtcTicks, actual.UtcTicks); + Assert.AreEqual(expected.Offset, actual.Offset); + } + + static byte[] UnityLayout(DateTimeOffset value) + { + // (long utcTicks, short offsetMinutes, 6 bytes zero) + var bin = new byte[16]; + BitConverter.GetBytes(value.UtcTicks).CopyTo(bin, 0); + BitConverter.GetBytes((short)value.Offset.TotalMinutes).CopyTo(bin, 8); + return bin; + } + + static byte[] Net10Layout(DateTimeOffset value) + { + // (int offsetMinutes, 4 bytes zero, long utcTicks) + var bin = new byte[16]; + BitConverter.GetBytes((int)value.Offset.TotalMinutes).CopyTo(bin, 0); + BitConverter.GetBytes(value.UtcTicks).CopyTo(bin, 8); + return bin; + } + + // IMPORTANT: this is the assumption of UnityDateTimeOffset, layout of DateTimeOffset in this runtime is (long utcTicks, short offsetMinutes, padding). + [Test] + public void NativeDateTimeOffsetLayoutIsUnityLayout() + { + foreach (var value in Values) + { + var native = MemoryPackSerializer.Serialize(value); + Debug.Log("DateTimeOffset " + value.ToString("o") + " native: " + ToHex(native) + " UnityDateTimeOffset: " + ToHex(MemoryPackSerializer.Serialize(value))); + + Assert.AreEqual(16, native.Length); + + // padding is not initialized, clear before compare. + Array.Clear(native, 10, 6); + CollectionAssert.AreEqual(UnityLayout(value), native); + } + } + + [Test] + public void UnityDateTimeOffsetIsCompatibleWithNativeDateTimeOffset() + { + foreach (var value in Values) + { + CollectionAssert.AreEqual(UnityLayout(value), MemoryPackSerializer.Serialize(value)); + + // DateTimeOffset -> UnityDateTimeOffset + AreSame(value, MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value))); + // UnityDateTimeOffset -> DateTimeOffset + AreSame(value, MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value))); + } + } + + [Test] + public void UnityDateTimeOffsetKnownBinary() + { + // https://github.com/Cysharp/MemoryPack/issues/192 serialized in Unity 2022.3.7f1 + var value = new DateTimeOffset(2023, 10, 25, 17, 45, 0, TimeSpan.FromHours(8)); + var bin = new byte[] { 0, 182, 36, 14, 63, 213, 219, 8, 224, 1, 0, 0, 0, 0, 0, 0 }; + + CollectionAssert.AreEqual(bin, MemoryPackSerializer.Serialize(value)); + AreSame(value, MemoryPackSerializer.Deserialize(bin)); + } + + [Test] + public void Net10DateTimeOffsetBinary() + { + foreach (var value in Values) + { + var bin = MemoryPackSerializer.Serialize(value); + CollectionAssert.AreEqual(Net10Layout(value), bin); + AreSame(value, MemoryPackSerializer.Deserialize(bin)); + } + + // memory dump of DateTimeOffset(2026-11-30T16:48:36-05:00) in .NET 10 and .NET 9 + var expected = new DateTimeOffset(2026, 11, 30, 16, 48, 36, TimeSpan.FromMinutes(-300)); + var net10 = new byte[] { 212, 254, 255, 255, 0, 0, 0, 0, 0, 146, 181, 175, 43, 79, 223, 8 }; + var net9 = new byte[] { 212, 254, 0, 0, 0, 0, 0, 0, 0, 146, 181, 175, 43, 79, 223, 8 }; + CollectionAssert.AreEqual(net10, MemoryPackSerializer.Serialize(expected)); + AreSame(expected, MemoryPackSerializer.Deserialize(net10)); + AreSame(expected, MemoryPackSerializer.Deserialize(net9)); + } + + [Test] + public void SafeNullableIsCompatibleWithNullable() + { + // (hasValue = (1, 0, 0, 0), value) + CollectionAssert.AreEqual(new byte[] { 1, 0, 0, 0, 10, 0, 0, 0 }, MemoryPackSerializer.Serialize>(10)); + CollectionAssert.AreEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, MemoryPackSerializer.Serialize>(null)); + CollectionAssert.AreEqual(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0 }, MemoryPackSerializer.Serialize>(10)); + CollectionAssert.AreEqual(new byte[] { 1, 1 }, MemoryPackSerializer.Serialize>(true)); + + // Nullable <-> SafeNullable + Assert.AreEqual(8, MemoryPackSerializer.Serialize(10).Length); + Assert.AreEqual(16, MemoryPackSerializer.Serialize(10).Length); + Assert.AreEqual(10, MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize>(10))); + Assert.AreEqual(null, MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize>(null))); + Assert.AreEqual(10, MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(10)).Value); + Assert.IsFalse(MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(null)).HasValue); + Assert.AreEqual(long.MinValue, MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(long.MinValue)).Value); + + // garbage padding of Nullable + Assert.AreEqual(10, MemoryPackSerializer.Deserialize>(new byte[] { 1, 201, 202, 203, 10, 0, 0, 0 }).Value); + Assert.IsFalse(MemoryPackSerializer.Deserialize>(new byte[] { 0, 201, 202, 203, 0, 0, 0, 0 }).HasValue); + + // members + var nullable = new CompatNullableData { SafeInt = 10, SafeIntNull = null, SafeLong = long.MinValue, SafeBool = true, SafeEnum = CompatIntEnum.C }; + var safe = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(nullable)); + Assert.AreEqual(10, safe.SafeInt.Value); + Assert.IsFalse(safe.SafeIntNull.HasValue); + Assert.AreEqual(long.MinValue, safe.SafeLong.Value); + Assert.AreEqual(true, safe.SafeBool.Value); + Assert.AreEqual(CompatIntEnum.C, safe.SafeEnum.Value); + + var nullable2 = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(safe)); + Assert.AreEqual(10, nullable2.SafeInt); + Assert.AreEqual(null, nullable2.SafeIntNull); + Assert.AreEqual(long.MinValue, nullable2.SafeLong); + Assert.AreEqual(true, nullable2.SafeBool); + Assert.AreEqual(CompatIntEnum.C, nullable2.SafeEnum); + } + + [Test] + public void Members() + { + var bits = new BitArray(100); + for (int i = 0; i < 100; i += 3) + { + bits[i] = true; + } + + var value = new CompatTypesData + { + Net10 = Values[0], + Unity = Values[1], + Net10Nullable = Values[2], + UnityArray = new UnityDateTimeOffset[] { Values[0], Values[1], Values[2] }, + Net10List = new List { Values[0], Values[1], Values[2] }, + SafeInt = 10, + SafeIntNull = null, + SafeLong = long.MinValue, + SafeBool = true, + SafeEnum = CompatIntEnum.C, + SafeArray = new SafeNullable[] { 1, null, 3 }, + SafeList = new List> { null, 2, 3 }, + Bits = bits, + Text = "foo", + }; + + var bin = MemoryPackSerializer.Serialize(value); + Debug.Log("CompatTypesData: " + ToHex(bin)); + var value2 = MemoryPackSerializer.Deserialize(bin); + + AreSame(Values[0], value2.Net10); + AreSame(Values[1], value2.Unity); + AreSame(Values[2], value2.Net10Nullable.Value); + Assert.AreEqual(3, value2.UnityArray.Length); + Assert.AreEqual(3, value2.Net10List.Count); + for (int i = 0; i < 3; i++) + { + AreSame(Values[i], value2.UnityArray[i]); + AreSame(Values[i], value2.Net10List[i]); + } + Assert.AreEqual(10, value2.SafeInt.Value); + Assert.IsFalse(value2.SafeIntNull.HasValue); + Assert.AreEqual(long.MinValue, value2.SafeLong.Value); + Assert.AreEqual(true, value2.SafeBool.Value); + Assert.AreEqual(CompatIntEnum.C, value2.SafeEnum.Value); + Assert.AreEqual(1, value2.SafeArray[0].Value); + Assert.IsFalse(value2.SafeArray[1].HasValue); + Assert.AreEqual(3, value2.SafeArray[2].Value); + Assert.IsFalse(value2.SafeList[0].HasValue); + Assert.AreEqual(2, value2.SafeList[1].Value); + Assert.AreEqual(3, value2.SafeList[2].Value); + Assert.AreEqual(100, value2.Bits.Length); + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(i % 3 == 0, value2.Bits[i]); + } + Assert.AreEqual("foo", value2.Text); + + // same binary in every serialize + for (int i = 0; i < 10; i++) + { + CollectionAssert.AreEqual(bin, MemoryPackSerializer.Serialize(value)); + } + } + + // https://github.com/Cysharp/MemoryPack/issues/399 + [Test] + public void BitArrayBinaryIsSameAsDotNet() + { + // BitArray(100), every third bit is true, serialized by .NET 8. + var expected = new byte[] { 2, 100, 0, 0, 0, 4, 0, 0, 0, 73, 146, 36, 73, 146, 36, 73, 146, 36, 73, 146, 36, 9, 0, 0, 0 }; + + var value = new BitArray(100); + for (int i = 0; i < 100; i += 3) + { + value[i] = true; + } + + var bin = MemoryPackSerializer.Serialize(value); + Debug.Log("BitArray: " + ToHex(bin)); + CollectionAssert.AreEqual(expected, bin); + + var value2 = MemoryPackSerializer.Deserialize(expected); + Assert.AreEqual(100, value2.Length); + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(i % 3 == 0, value2[i]); + } + + foreach (var length in new[] { 0, 1, 31, 32, 33, 64, 1000 }) + { + var bitArray = new BitArray(length); + for (int i = 0; i < length; i += 3) + { + bitArray[i] = true; + } + var bitArray2 = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(bitArray)); + Assert.AreEqual(length, bitArray2.Length); + for (int i = 0; i < length; i++) + { + Assert.AreEqual(i % 3 == 0, bitArray2[i]); + } + } + } + + [Test] + public void MalformedDataIsRejected() + { + // utf8 string header overflow, https://github.com/Cysharp/MemoryPack/issues/306 + Assert.Throws(() => MemoryPackSerializer.Deserialize(new byte[] { 1, 0, 0, 0, 128 })); + Assert.Throws(() => MemoryPackSerializer.Deserialize(new byte[] { 1, 0, 0, 0, 128, 0, 0, 0, 0, 97, 98, 99, 100 })); + Assert.Throws(() => MemoryPackSerializer.Deserialize(new byte[] { 1, 3, 0, 0, 128, 0, 0, 0, 0, 97, 98, 99, 100 })); + + // negative skip of version tolerant, list of 2 elements, 1st element has unknown member that length is -100. + var payload = new byte[] { 2, 0, 0, 0, 2, 4, 156, 1, 0, 0, 0, 1, 240, 255, 255, 127, 0, 0, 0, 0 }; + Assert.Throws(() => MemoryPackSerializer.Deserialize>(payload)); + + // version tolerant skip is still working + var tolerant = MemoryPackSerializer.Deserialize(new byte[] { 2, 4, 4, 10, 0, 0, 0, 99, 99, 99, 99 }); + Assert.AreEqual(10, tolerant.A); + + // negative length of unmanaged array + Assert.Throws(() => MemoryPackSerializer.Deserialize(new byte[] { 254, 255, 255, 255, 1, 2, 3, 4, 5, 6, 7, 8 })); + + // multi dimensional array, dimensions [65536, 32768] but collection length is 8 + var multi = new byte[] { 3, 0, 0, 1, 0, 0, 128, 0, 0, 8, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 }; + Assert.Throws(() => MemoryPackSerializer.Deserialize(multi)); + + // reader rejects negative size + Assert.IsTrue(ReaderRejectsNegative(-1)); + Assert.IsTrue(ReaderRejectsNegative(-4)); + Assert.IsTrue(ReaderRejectsNegative(int.MinValue)); + } + + static bool ReaderRejectsNegative(int size) + { + var state = MemoryPackReaderOptionalStatePool.Rent(null); + var reader = new MemoryPackReader(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, state); + try + { + reader.Advance(2); + + var getSpanReferenceFailed = false; + try + { + reader.GetSpanReference(size); + } + catch (MemoryPackSerializationException) + { + getSpanReferenceFailed = true; + } + + var advanceFailed = false; + try + { + reader.Advance(size); + } + catch (MemoryPackSerializationException) + { + advanceFailed = true; + } + + return getSpanReferenceFailed && advanceFailed && reader.Consumed == 2; + } + finally + { + reader.Dispose(); + ((IDisposable)state).Dispose(); + } + } +} diff --git a/src/MemoryPack.Unity/Assets/Tests/CompatTypesTest.cs.meta b/src/MemoryPack.Unity/Assets/Tests/CompatTypesTest.cs.meta new file mode 100644 index 00000000..5c4cae18 --- /dev/null +++ b/src/MemoryPack.Unity/Assets/Tests/CompatTypesTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eabb5a4455c447b381e2c8581f059b1f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CompatTypes.cs b/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CompatTypes.cs new file mode 100644 index 00000000..9d2c780e --- /dev/null +++ b/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CompatTypes.cs @@ -0,0 +1,65 @@ +#nullable enable +using System; +using System.Collections; +using System.Collections.Generic; + +namespace MemoryPack.Tests.Models +{ + public enum CompatIntEnum + { + A, B, C + } + + [MemoryPackable] + public partial class CompatTypesData + { + public Net10DateTimeOffset Net10; + public UnityDateTimeOffset Unity; + public Net10DateTimeOffset? Net10Nullable; + public UnityDateTimeOffset[]? UnityArray; + public List? Net10List; + public SafeNullable SafeInt; + public SafeNullable SafeIntNull; + public SafeNullable SafeLong; + public SafeNullable SafeBool; + public SafeNullable SafeEnum; + public SafeNullable[]? SafeArray; + public List>? SafeList; + public BitArray? Bits; + public string? Text; + } + + // same members as CompatTypesData but uses Nullable + [MemoryPackable] + public partial class CompatNullableData + { + public int? SafeInt; + public int? SafeIntNull; + public long? SafeLong; + public bool? SafeBool; + public CompatIntEnum? SafeEnum; + } + + [MemoryPackable] + public partial class CompatSafeNullableData + { + public SafeNullable SafeInt; + public SafeNullable SafeIntNull; + public SafeNullable SafeLong; + public SafeNullable SafeBool; + public SafeNullable SafeEnum; + } + + [MemoryPackable(GenerateType.VersionTolerant)] + public partial class CompatVersionTolerantData + { + [MemoryPackOrder(0)] + public int A; + } + + [MemoryPackable] + public partial class CompatStringData + { + public string? Text; + } +} diff --git a/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CompatTypes.cs.meta b/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CompatTypes.cs.meta new file mode 100644 index 00000000..17182bef --- /dev/null +++ b/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CompatTypes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 71b09b3571e74110aa4749a69b0f2848 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 501594112bee4e0e05fc47f155048bb9c426dc0b Mon Sep 17 00:00:00 2001 From: neuecc Date: Wed, 11 Nov 2026 16:37:08 +0900 Subject: [PATCH 6/6] Use only public API in List, Stack, ImmutableArray and BitArray formatters Remove the view types that reinterpret BCL collections by Unsafe.As (ListView, StackView, ImmutableArrayView, BitArrayView), the private field layout is not guaranteed and differs by runtime. - List: CollectionsMarshal.SetCount and AsSpan in .NET 8 or later, Add one by one in net7.0 and netstandard2.1. - Stack: CopyTo the pooled array to serialize, constructor or Push to deserialize. - ImmutableArray: read to the pooled array and ImmutableArray.Create in net7.0 and netstandard2.1, .NET 8 or later is not changed. - BitArray: CopyTo(int[]) and new BitArray(int[]) in all runtimes, clear unused bits of the last element, reject the length that is not matched to the array. Binary format is not changed. Co-Authored-By: Claude Fable 5.2 --- .../Formatters/BitArrayFormatter.cs | 98 ++---- .../Formatters/CollectionFormatters.cs | 91 +++-- .../ImmutableCollectionFormatters.cs | 45 ++- .../Internal/CollectionsMarshalEx.cs | 56 ---- .../Assets/Tests/CollectionPublicApiTest.cs | 225 +++++++++++++ .../Tests/CollectionPublicApiTest.cs.meta | 11 + .../MemoryPackObjects/CollectionPublicApi.cs | 31 ++ .../CollectionPublicApi.cs.meta | 11 + .../Assets/Tests/Tests.asmdef | 3 +- .../CollectionPublicApiTest.cs | 311 ++++++++++++++++++ 10 files changed, 726 insertions(+), 156 deletions(-) delete mode 100644 src/MemoryPack.Core/Internal/CollectionsMarshalEx.cs create mode 100644 src/MemoryPack.Unity/Assets/Tests/CollectionPublicApiTest.cs create mode 100644 src/MemoryPack.Unity/Assets/Tests/CollectionPublicApiTest.cs.meta create mode 100644 src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CollectionPublicApi.cs create mode 100644 src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CollectionPublicApi.cs.meta create mode 100644 tests/MemoryPack.Tests/CollectionPublicApiTest.cs diff --git a/src/MemoryPack.Core/Formatters/BitArrayFormatter.cs b/src/MemoryPack.Core/Formatters/BitArrayFormatter.cs index b3979aea..976fcc14 100644 --- a/src/MemoryPack.Core/Formatters/BitArrayFormatter.cs +++ b/src/MemoryPack.Core/Formatters/BitArrayFormatter.cs @@ -1,48 +1,16 @@ using MemoryPack.Internal; +using System.Buffers; using System.Collections; -using System.Reflection; -using System.Runtime.CompilerServices; namespace MemoryPack.Formatters; [Preserve] public sealed class BitArrayFormatter : MemoryPackFormatter { - // serialize [m_length, m_array] + // serialize [length(bit count), int[]] - // BitArrayView depends on private field layout of BitArray(int[] m_array, int m_length). - // .NET 10 changed it to (byte[] _array, int _bitLength), reinterpreting it reads/writes out of the array. - // When layout is not matched, use public API instead of BitArrayView(binary format is same). - static readonly bool canUseBitArrayView = CanUseBitArrayView(); - - static bool CanUseBitArrayView() - { - try - { - const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic; - if (typeof(BitArray).GetField("m_array", Flags)?.FieldType != typeof(int[]) - || typeof(BitArray).GetField("m_length", Flags)?.FieldType != typeof(int)) - { - return false; - } - - // fields exist but the offsets can be different from BitArrayView(depends on the runtime, for example it has other fields), check it by actual value. - var bitArray = new BitArray(37); - bitArray[36] = true; - ref var view = ref Unsafe.As(ref bitArray); - object? array = view.m_array; - return array != null - && array.GetType() == typeof(int[]) - && view.m_array.Length == 2 - && view.m_array[0] == 0 - && view.m_array[1] == 16 - && view.m_length == 37; - } - catch - { - return false; - } - } + // Private fields of BitArray depend on the runtime(.NET 9 or lower is (int[] m_array, int m_length), .NET 10 or later is (byte[] _array, int _bitLength), Mono has different field offsets), + // so only use the public API. [Preserve] public override void Serialize(ref MemoryPackWriter writer, scoped ref BitArray? value) @@ -53,21 +21,29 @@ public override void Serialize(ref MemoryPackWriter.Shared.Rent(arrayLength); + try { - var length = value.Length; - var array = new int[length > 0 ? ((length - 1) >> 5) + 1 : 0]; // same as m_array of BitArray(length) - value.CopyTo(array, 0); + value.CopyTo(rented, 0); + var span = rented.AsSpan(0, arrayLength); + + // unused bits of the last element are not cleared in some runtimes, clear to write the same binary. + var extraBits = length & 31; + if (extraBits != 0) + { + span[span.Length - 1] &= (1 << extraBits) - 1; + } writer.WriteUnmanagedWithObjectHeader(2, length); - writer.WriteUnmanagedArray(array); - return; + writer.WriteUnmanagedSpan(span); + } + finally + { + ArrayPool.Shared.Return(rented); } - - ref var view = ref Unsafe.As(ref value); - - writer.WriteUnmanagedWithObjectHeader(2, view.m_length); - writer.WriteUnmanagedArray(view.m_array); } [Preserve] @@ -82,29 +58,21 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref BitArra if (count != 2) MemoryPackSerializationException.ThrowInvalidPropertyCount(2, count); reader.ReadUnmanaged(out int length); + var array = reader.ReadUnmanagedArray() ?? Array.Empty(); - if (!canUseBitArrayView) + // the array can be longer than required(BitArray does not always shrink the inner array) but must not be shorter. + if (length < 0 || array.Length < GetInt32ArrayLength(length)) { - var array = reader.ReadUnmanagedArray(); - value = new BitArray(array ?? Array.Empty()); - value.Length = length; - return; + MemoryPackSerializationException.ThrowMessage($"BitArray length {length} is not matched to array length {array.Length}."); } - var bitArray = new BitArray(length, false); // create internal int[] and set m_length to length - - ref var view = ref Unsafe.As(ref bitArray); - reader.ReadUnmanagedArray(ref view.m_array!); - + var bitArray = new BitArray(array); + bitArray.Length = length; value = bitArray; } -} -#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. -[Preserve] -internal class BitArrayView -{ - public int[] m_array; - public int m_length; - public int _version; + static int GetInt32ArrayLength(int bitLength) + { + return bitLength > 0 ? ((bitLength - 1) >> 5) + 1 : 0; + } } diff --git a/src/MemoryPack.Core/Formatters/CollectionFormatters.cs b/src/MemoryPack.Core/Formatters/CollectionFormatters.cs index de6066ed..28e7c68e 100644 --- a/src/MemoryPack.Core/Formatters/CollectionFormatters.cs +++ b/src/MemoryPack.Core/Formatters/CollectionFormatters.cs @@ -105,15 +105,17 @@ public static void DeserializePackable(ref MemoryPackReader reader, scoped re { value = new List(length); } -#if NET7_0_OR_GREATER +#if NET8_0_OR_GREATER else if (value.Count == length) { value.Clear(); } - var span = CollectionsMarshalEx.CreateSpan(value, length); + CollectionsMarshal.SetCount(value, length); + var span = CollectionsMarshal.AsSpan(value); reader.ReadPackableSpanWithoutReadLengthHeader(length, ref span); #else + // .NET 7 or lower has no public API to set the count, add one by one. else { value.Clear(); @@ -166,15 +168,17 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref List(length); } -#if NET7_0_OR_GREATER +#if NET8_0_OR_GREATER else if (value.Count == length) { value.Clear(); } - var span = CollectionsMarshalEx.CreateSpan(value, length); + CollectionsMarshal.SetCount(value, length); + var span = CollectionsMarshal.AsSpan(value); reader.ReadSpanWithoutReadLengthHeader(length, ref span); #else + // .NET 7 or lower has no public API to set the count, add one by one. else { value.Clear(); @@ -202,17 +206,30 @@ public override void Serialize(ref MemoryPackWriter(); - writer.WriteCollectionHeader(value.Count); - foreach (var item in value.Reverse()) // serialize reverse order + var count = value.Count; + if (count == 0) { - var v = item; - formatter.Serialize(ref writer, ref v); + writer.WriteCollectionHeader(0); + return; + } + + // Stack has no public API to get the inner array, copy to the pooled array. + var rented = ArrayPool.Shared.Rent(count); + try + { + value.CopyTo(rented, 0); // order of Pop(top to bottom) + var span = rented.AsSpan(0, count); + span.Reverse(); // serialize as the order of Push(bottom to top) + writer.WriteSpan(span); + } + finally + { + if (RuntimeHelpers.IsReferenceOrContainsReferences()) + { + rented.AsSpan(0, count).Clear(); + } + ArrayPool.Shared.Return(rented); } -#endif } [Preserve] @@ -224,23 +241,52 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref Stack()) { - value = new Stack(length); - } + // read at once to the pooled array. + var rented = ArrayPool.Shared.Rent(length); + try + { + var span = rented.AsSpan(0, length); + reader.ReadSpanWithoutReadLengthHeader(length, ref span); + + if (value == null) + { + // constructor pushes in order, it copies ICollection at once. + value = new Stack(new ArraySegment(rented, 0, length)); + } + else + { + value.Clear(); #if NET7_0_OR_GREATER - else if (value.Count != length) - { - value.Clear(); + value.EnsureCapacity(length); +#endif + for (int i = 0; i < span.Length; i++) + { + value.Push(span[i]); + } + } + } + finally + { + ArrayPool.Shared.Return(rented); + } + return; } - var span = CollectionsMarshalEx.CreateSpan(value, length); - reader.ReadSpanWithoutReadLengthHeader(length, ref span); -#else + if (value == null) + { + value = new Stack(length); + } else { value.Clear(); +#if NET7_0_OR_GREATER + value.EnsureCapacity(length); +#endif } + var formatter = reader.GetFormatter(); for (int i = 0; i < length; i++) { @@ -248,7 +294,6 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref Stack(ref MemoryPackWriter value) { +#if NET8_0_OR_GREATER var array = reader.ReadArray(); if (array == null) { @@ -64,23 +65,45 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref Immutab return; } -#if NET8_0_OR_GREATER value = ImmutableCollectionsMarshal.AsImmutableArray(array); #else - // create Empty and replace inner T[] field(avoid defensive copy of Create) - value = ImmutableArray.Create(); - ref var view = ref Unsafe.As, ImmutableArrayView>(ref value); - view.array = array; + if (!reader.TryReadCollectionHeader(out var length)) + { + value = default; + return; + } + + if (length == 0) + { + value = ImmutableArray.Empty; + return; + } + + // .NET 7 or lower has no public API to create ImmutableArray without copy, read to the pooled array and create from it. + var isReference = RuntimeHelpers.IsReferenceOrContainsReferences(); + var rented = ArrayPool.Shared.Rent(length); + try + { + var span = rented.AsSpan(0, length); + if (isReference) + { + span.Clear(); // pooled array has garbage, don't overwrite to it. + } + reader.ReadSpanWithoutReadLengthHeader(length, ref span); + value = ImmutableArray.Create(rented, 0, length); + } + finally + { + if (isReference) + { + rented.AsSpan(0, length).Clear(); + } + ArrayPool.Shared.Return(rented); + } #endif } } - [Preserve] - internal struct ImmutableArrayView - { - public T[]? array; - } - [Preserve] public sealed class ImmutableListFormatter : MemoryPackFormatter> { diff --git a/src/MemoryPack.Core/Internal/CollectionsMarshalEx.cs b/src/MemoryPack.Core/Internal/CollectionsMarshalEx.cs deleted file mode 100644 index 5ccbe415..00000000 --- a/src/MemoryPack.Core/Internal/CollectionsMarshalEx.cs +++ /dev/null @@ -1,56 +0,0 @@ -#if NET7_0_OR_GREATER - -#pragma warning disable CS8618 -#pragma warning disable CS0649 - -using System.Runtime.CompilerServices; - -namespace MemoryPack.Internal; - -internal static class CollectionsMarshalEx -{ - /// - /// similar as AsSpan but modify size to create fixed-size span. - /// - public static Span CreateSpan(List list, int length) - { - list.EnsureCapacity(length); - - ref var view = ref Unsafe.As, ListView>(ref list); - view._size = length; - return view._items.AsSpan(0, length); - } - - public static Span AsSpan(Stack stack) - { - ref var view = ref Unsafe.As, StackView>(ref stack); - return view._items.AsSpan(0, view._size); - } - - public static Span CreateSpan(Stack stack, int length) - { - stack.EnsureCapacity(length); - - ref var view = ref Unsafe.As, StackView>(ref stack); - view._size = length; - return view._items.AsSpan(0, view._size); - } - - // NOTE: These structure depndent on .NET 7, if changed, require to keep same structure. - - internal sealed class ListView - { - public T[] _items; - public int _size; - public int _version; - } - - internal sealed class StackView - { - public T[] _items; - public int _size; - public int _version; - } -} - -#endif diff --git a/src/MemoryPack.Unity/Assets/Tests/CollectionPublicApiTest.cs b/src/MemoryPack.Unity/Assets/Tests/CollectionPublicApiTest.cs new file mode 100644 index 00000000..5f29771a --- /dev/null +++ b/src/MemoryPack.Unity/Assets/Tests/CollectionPublicApiTest.cs @@ -0,0 +1,225 @@ +using MemoryPack; +using MemoryPack.Tests.Models; +using NUnit.Framework; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +// List, Stack, ImmutableArray and BitArray formatters only use the public API(do not depend on the private field layout), checks in Unity(Mono, IL2CPP). +// https://github.com/Cysharp/MemoryPack/issues/460 +public class CollectionPublicApiTest +{ + static byte[] Int32Collection(params int[] values) + { + var bin = new byte[4 + values.Length * 4]; + BitConverter.GetBytes(values.Length).CopyTo(bin, 0); + for (int i = 0; i < values.Length; i++) + { + BitConverter.GetBytes(values[i]).CopyTo(bin, 4 + i * 4); + } + return bin; + } + + static byte[] BitArrayBinary(int length, params int[] array) + { + // (object header, int length, (int collection length, int[])) + var bin = new byte[1 + 4 + 4 + array.Length * 4]; + bin[0] = 2; + BitConverter.GetBytes(length).CopyTo(bin, 1); + Int32Collection(array).CopyTo(bin, 5); + return bin; + } + + static Stack CreateStack(IEnumerable values) + { + var stack = new Stack(); + foreach (var item in values) + { + stack.Push(item); + } + return stack; + } + + static CollectionPublicApiItem Item(int id) + { + return id % 4 == 0 ? null : new CollectionPublicApiItem { Id = id, Name = "v" + id }; + } + + static string ItemToString(CollectionPublicApiItem item) + { + return item == null ? "(null)" : item.Id + ":" + item.Name; + } + + static CollectionPublicApiData Create(int count) + { + var ints = Enumerable.Range(1, count).ToArray(); + var strings = ints.Select(x => x % 4 == 0 ? null : "v" + x).ToArray(); + var items = ints.Select(x => Item(x)).ToArray(); + + var bits = new BitArray(count); + for (int i = 0; i < count; i += 3) + { + bits[i] = true; + } + + return new CollectionPublicApiData + { + IntList = ints.ToList(), + StringList = strings.ToList(), + ItemList = items.ToList(), + IntStack = CreateStack(ints), + LongStack = CreateStack(ints.Select(x => (long)x * int.MaxValue)), + StringStack = CreateStack(strings), + ItemStack = CreateStack(items), + IntImmutableArray = ImmutableArray.Create(ints), + StringImmutableArray = ImmutableArray.Create(strings), + ItemImmutableArray = ImmutableArray.Create(items), + Bits = bits, + }; + } + + static void AreSame(CollectionPublicApiData expected, CollectionPublicApiData actual) + { + CollectionAssert.AreEqual(expected.IntList, actual.IntList); + CollectionAssert.AreEqual(expected.StringList, actual.StringList); + CollectionAssert.AreEqual(expected.ItemList.Select(ItemToString).ToArray(), actual.ItemList.Select(ItemToString).ToArray()); + // enumerate Stack is the order of Pop + CollectionAssert.AreEqual(expected.IntStack.ToArray(), actual.IntStack.ToArray()); + CollectionAssert.AreEqual(expected.LongStack.ToArray(), actual.LongStack.ToArray()); + CollectionAssert.AreEqual(expected.StringStack.ToArray(), actual.StringStack.ToArray()); + CollectionAssert.AreEqual(expected.ItemStack.Select(ItemToString).ToArray(), actual.ItemStack.Select(ItemToString).ToArray()); + CollectionAssert.AreEqual(expected.IntImmutableArray.ToArray(), actual.IntImmutableArray.ToArray()); + CollectionAssert.AreEqual(expected.StringImmutableArray.ToArray(), actual.StringImmutableArray.ToArray()); + CollectionAssert.AreEqual(expected.ItemImmutableArray.Select(ItemToString).ToArray(), actual.ItemImmutableArray.Select(ItemToString).ToArray()); + CollectionAssert.AreEqual(expected.Bits.Cast().ToArray(), actual.Bits.Cast().ToArray()); + } + + [Test] + public void Roundtrip() + { + foreach (var count in new[] { 0, 1, 3, 5, 100, 1000, 100000 }) + { + var value = Create(count); + var bin = MemoryPackSerializer.Serialize(value); + AreSame(value, MemoryPackSerializer.Deserialize(bin)); + + // source is not changed, same binary in every serialize. + AreSame(Create(count), value); + CollectionAssert.AreEqual(bin, MemoryPackSerializer.Serialize(value)); + } + + // null and default + var empty = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(new CollectionPublicApiData())); + Assert.IsNull(empty.IntList); + Assert.IsNull(empty.IntStack); + Assert.IsNull(empty.StringStack); + Assert.IsTrue(empty.IntImmutableArray.IsDefault); + Assert.IsTrue(empty.StringImmutableArray.IsDefault); + Assert.IsNull(empty.Bits); + } + + [Test] + public void Overwrite() + { + foreach (var existingCount in new[] { 0, 3, 5, 1000 }) + { + foreach (var count in new[] { 0, 3, 5, 1000 }) + { + var source = Create(count); + var bin = MemoryPackSerializer.Serialize(source); + + var value = Create(existingCount); + var intList = value.IntList; + var stringList = value.StringList; + var intStack = value.IntStack; + var stringStack = value.StringStack; + + MemoryPackSerializer.Deserialize(bin, ref value); + AreSame(source, value); + + // List and Stack are reused. + Assert.AreSame(intList, value.IntList); + Assert.AreSame(stringList, value.StringList); + Assert.AreSame(intStack, value.IntStack); + Assert.AreSame(stringStack, value.StringStack); + + // collections are still valid. + value.IntList.Add(9999); + value.IntStack.Push(9999); + value.StringStack.Push("last"); + Assert.AreEqual(count + 1, value.IntList.Count); + Assert.AreEqual(9999, value.IntList[count]); + Assert.AreEqual(9999, value.IntStack.Pop()); + Assert.AreEqual("last", value.StringStack.Pop()); + Assert.AreEqual(count, value.IntStack.Count); + } + } + } + + [Test] + public void BinaryIsSameAsDotNet() + { + // register formatters + MemoryPackSerializer.Serialize(new CollectionPublicApiData()); + + // Stack is serialized as the order of Push(bottom to top) + var stack = CreateStack(new[] { 1, 2, 3 }); + CollectionAssert.AreEqual(Int32Collection(1, 2, 3), MemoryPackSerializer.Serialize(stack)); + CollectionAssert.AreEqual(new[] { 3, 2, 1 }, stack.ToArray()); + CollectionAssert.AreEqual(new[] { 3, 2, 1 }, MemoryPackSerializer.Deserialize>(Int32Collection(1, 2, 3)).ToArray()); + + CollectionAssert.AreEqual(Int32Collection(1, 2, 3), MemoryPackSerializer.Serialize(new List { 1, 2, 3 })); + CollectionAssert.AreEqual(new[] { 1, 2, 3 }, MemoryPackSerializer.Deserialize>(Int32Collection(1, 2, 3)).ToArray()); + + CollectionAssert.AreEqual(Int32Collection(1, 2, 3), MemoryPackSerializer.Serialize(ImmutableArray.Create(1, 2, 3))); + CollectionAssert.AreEqual(new[] { 1, 2, 3 }, MemoryPackSerializer.Deserialize>(Int32Collection(1, 2, 3)).ToArray()); + Assert.IsTrue(MemoryPackSerializer.Deserialize>(Int32Collection()).IsEmpty); + + // same binary as array + var strings = new[] { "a", null, "c" }; + var stringsBin = MemoryPackSerializer.Serialize(strings); + CollectionAssert.AreEqual(stringsBin, MemoryPackSerializer.Serialize(CreateStack(strings))); + CollectionAssert.AreEqual(stringsBin, MemoryPackSerializer.Serialize(ImmutableArray.Create(strings))); + CollectionAssert.AreEqual(new[] { "c", null, "a" }, MemoryPackSerializer.Deserialize>(stringsBin).ToArray()); + CollectionAssert.AreEqual(strings, MemoryPackSerializer.Deserialize>(stringsBin).ToArray()); + } + + [Test] + public void BitArrayUnusedBitsAreCleared() + { + // inner array of BitArray(100, true) is filled by 0xFFFFFFFF, unused bits of the last element are not written. + CollectionAssert.AreEqual(BitArrayBinary(100, -1, -1, -1, 15), MemoryPackSerializer.Serialize(new BitArray(100, true))); + CollectionAssert.AreEqual(BitArrayBinary(100, -1, -1, -1, 15), MemoryPackSerializer.Serialize(new BitArray(100).Not())); + CollectionAssert.AreEqual(BitArrayBinary(64, -1, -1), MemoryPackSerializer.Serialize(new BitArray(64, true))); + CollectionAssert.AreEqual(BitArrayBinary(31, int.MaxValue), MemoryPackSerializer.Serialize(new BitArray(31, true))); + CollectionAssert.AreEqual(BitArrayBinary(0), MemoryPackSerializer.Serialize(new BitArray(0))); + + var shrink = new BitArray(1000, true); + shrink.Length = 10; + CollectionAssert.AreEqual(BitArrayBinary(10, 1023), MemoryPackSerializer.Serialize(shrink)); + + // binary of the older version can have garbage in unused bits and longer array. + var value = MemoryPackSerializer.Deserialize(BitArrayBinary(100, -1, -1, -1, -1)); + Assert.AreEqual(100, value.Length); + Assert.IsTrue(value.Cast().All(x => x)); + + var longer = MemoryPackSerializer.Deserialize(BitArrayBinary(10, Enumerable.Repeat(-1, 32).ToArray())); + Assert.AreEqual(10, longer.Length); + CollectionAssert.AreEqual(BitArrayBinary(10, 1023), MemoryPackSerializer.Serialize(longer)); + + // older version in Unity(Mono) wrote the length as 0, https://github.com/Cysharp/MemoryPack/issues/399 + Assert.AreEqual(0, MemoryPackSerializer.Deserialize(BitArrayBinary(0, 1, 2, 3, 4)).Length); + } + + [Test] + public void BitArrayLengthIsNotMatchedToArray() + { + Assert.Throws(() => MemoryPackSerializer.Deserialize(BitArrayBinary(1))); + Assert.Throws(() => MemoryPackSerializer.Deserialize(BitArrayBinary(33, 1))); + Assert.Throws(() => MemoryPackSerializer.Deserialize(BitArrayBinary(int.MaxValue))); + Assert.Throws(() => MemoryPackSerializer.Deserialize(BitArrayBinary(-1))); + Assert.Throws(() => MemoryPackSerializer.Deserialize(BitArrayBinary(int.MinValue, 1, 2))); + } +} diff --git a/src/MemoryPack.Unity/Assets/Tests/CollectionPublicApiTest.cs.meta b/src/MemoryPack.Unity/Assets/Tests/CollectionPublicApiTest.cs.meta new file mode 100644 index 00000000..50b70f17 --- /dev/null +++ b/src/MemoryPack.Unity/Assets/Tests/CollectionPublicApiTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5337a52657564a7c95b09e796adf8790 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CollectionPublicApi.cs b/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CollectionPublicApi.cs new file mode 100644 index 00000000..8a889e80 --- /dev/null +++ b/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CollectionPublicApi.cs @@ -0,0 +1,31 @@ +#nullable enable +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace MemoryPack.Tests.Models +{ + [MemoryPackable] + public partial class CollectionPublicApiItem + { + public int Id; + public string? Name; + } + + [MemoryPackable] + public partial class CollectionPublicApiData + { + public List? IntList; + public List? StringList; + public List? ItemList; + public Stack? IntStack; + public Stack? LongStack; + public Stack? StringStack; + public Stack? ItemStack; + public ImmutableArray IntImmutableArray; + public ImmutableArray StringImmutableArray; + public ImmutableArray ItemImmutableArray; + public BitArray? Bits; + } +} diff --git a/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CollectionPublicApi.cs.meta b/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CollectionPublicApi.cs.meta new file mode 100644 index 00000000..89717fb9 --- /dev/null +++ b/src/MemoryPack.Unity/Assets/Tests/MemoryPackObjects/CollectionPublicApi.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6bf06e0d45c24723882c4e86baa6061d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/src/MemoryPack.Unity/Assets/Tests/Tests.asmdef b/src/MemoryPack.Unity/Assets/Tests/Tests.asmdef index da2c745e..21e45069 100644 --- a/src/MemoryPack.Unity/Assets/Tests/Tests.asmdef +++ b/src/MemoryPack.Unity/Assets/Tests/Tests.asmdef @@ -14,7 +14,8 @@ "overrideReferences": true, "precompiledReferences": [ "nunit.framework.dll", - "MemoryPack.Core.dll" + "MemoryPack.Core.dll", + "System.Collections.Immutable.dll" ], "autoReferenced": false, "defineConstraints": [ diff --git a/tests/MemoryPack.Tests/CollectionPublicApiTest.cs b/tests/MemoryPack.Tests/CollectionPublicApiTest.cs new file mode 100644 index 00000000..a52539dd --- /dev/null +++ b/tests/MemoryPack.Tests/CollectionPublicApiTest.cs @@ -0,0 +1,311 @@ +using System; +using System.Buffers.Binary; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace MemoryPack.Tests; + +// List, Stack, ImmutableArray and BitArray formatters only use the public API(do not depend on the private field layout), binary format must not be changed. +// https://github.com/Cysharp/MemoryPack/issues/460 +public class CollectionPublicApiTest +{ + static byte[] Int32Collection(params int[] values) + { + var bin = new byte[4 + values.Length * 4]; + BinaryPrimitives.WriteInt32LittleEndian(bin, values.Length); + for (int i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteInt32LittleEndian(bin.AsSpan(4 + i * 4), values[i]); + } + return bin; + } + + static Stack CreateStack(params T[] values) + { + var stack = new Stack(); + foreach (var item in values) + { + stack.Push(item); + } + return stack; + } + + [Fact] + public void ListBinary() + { + var list = new List { 1, 2, 3 }; + MemoryPackSerializer.Serialize(list).Should().Equal(Int32Collection(1, 2, 3)); + MemoryPackSerializer.Deserialize>(Int32Collection(1, 2, 3)).Should().Equal(1, 2, 3); + + MemoryPackSerializer.Serialize(new List()).Should().Equal(Int32Collection()); + MemoryPackSerializer.Deserialize>(Int32Collection()).Should().BeEmpty(); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize>(null)).Should().BeNull(); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(0, 5)] + [InlineData(5, 0)] + [InlineData(5, 5)] + [InlineData(3, 5)] + [InlineData(5, 3)] + [InlineData(1000, 3)] + [InlineData(3, 1000)] + public void ListOverwrite(int existingCount, int count) + { + // unmanaged + { + var source = Enumerable.Range(1, count).ToList(); + var bin = MemoryPackSerializer.Serialize(source); + + var list = Enumerable.Range(1, existingCount).Select(x => -x).ToList(); + var original = list; + MemoryPackSerializer.Deserialize(bin, ref list); + + list.Should().BeSameAs(original); + list.Should().Equal(source); + + // list is still valid. + list!.Add(9999); + list.Should().Equal(source.Append(9999)); + list.RemoveAt(list.Count - 1); + list.Should().Equal(source); + } + // reference + { + var source = Enumerable.Range(1, count).Select(x => (string?)(x % 4 == 0 ? null : "v" + x)).ToList(); + var bin = MemoryPackSerializer.Serialize(source); + + var list = Enumerable.Range(1, existingCount).Select(x => (string?)("old" + x)).ToList(); + var original = list; + MemoryPackSerializer.Deserialize(bin, ref list); + + list.Should().BeSameAs(original); + list.Should().Equal(source); + + list!.Add("last"); + list.Should().Equal(source.Append("last")); + } + // packable + { + var source = new CollectionPublicApiData { List = Enumerable.Range(1, count).Select(x => new CollectionPublicApiItem { Id = x, Name = "v" + x }).ToList() }; + var bin = MemoryPackSerializer.Serialize(source); + + var value = new CollectionPublicApiData { List = Enumerable.Range(1, existingCount).Select(x => new CollectionPublicApiItem { Id = -x, Name = "old" + x }).ToList() }; + var original = value.List; + MemoryPackSerializer.Deserialize(bin, ref value); + + value!.List.Should().BeSameAs(original); + value.List!.Select(x => (x!.Id, x.Name)).Should().Equal(source.List.Select(x => (x!.Id, x.Name))); + } + } + + [Fact] + public void StackBinary() + { + // serialize as the order of Push(bottom to top) + var stack = CreateStack(1, 2, 3); + var bin = MemoryPackSerializer.Serialize(stack); + bin.Should().Equal(Int32Collection(1, 2, 3)); + + // source is not changed + stack.Should().Equal(3, 2, 1); + + var stack2 = MemoryPackSerializer.Deserialize>(Int32Collection(1, 2, 3))!; + stack2.Should().Equal(3, 2, 1); + stack2.Pop().Should().Be(3); + stack2.Pop().Should().Be(2); + stack2.Pop().Should().Be(1); + + MemoryPackSerializer.Serialize(new Stack()).Should().Equal(Int32Collection()); + MemoryPackSerializer.Deserialize>(Int32Collection()).Should().BeEmpty(); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize>(null)).Should().BeNull(); + + // same binary as List and array + MemoryPackSerializer.Serialize(CreateStack("a", null, "c")).Should().Equal(MemoryPackSerializer.Serialize(new[] { "a", null, "c" })); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(new[] { "a", null, "c" })).Should().Equal("c", null, "a"); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(0, 5)] + [InlineData(5, 0)] + [InlineData(5, 5)] + [InlineData(3, 5)] + [InlineData(5, 3)] + [InlineData(1000, 3)] + [InlineData(3, 1000)] + [InlineData(0, 100000)] + public void StackOverwrite(int existingCount, int count) + { + // unmanaged + { + var source = CreateStack(Enumerable.Range(1, count).ToArray()); + var bin = MemoryPackSerializer.Serialize(source); + MemoryPackSerializer.Deserialize>(bin).Should().Equal(source); + + var stack = CreateStack(Enumerable.Range(1, existingCount).Select(x => -x).ToArray()); + var original = stack; + MemoryPackSerializer.Deserialize(bin, ref stack); + + stack.Should().BeSameAs(original); + stack.Should().Equal(source); + + // stack is still valid. + stack!.Push(9999); + stack.Pop().Should().Be(9999); + stack.Should().Equal(source); + } + // unmanaged struct(larger than int) + { + var source = CreateStack(Enumerable.Range(1, count).Select(x => (x, (long)x * 2, Guid.NewGuid())).ToArray()); + var bin = MemoryPackSerializer.Serialize(source); + + var stack = CreateStack(Enumerable.Range(1, existingCount).Select(x => (-x, 0L, Guid.Empty)).ToArray()); + MemoryPackSerializer.Deserialize(bin, ref stack); + stack.Should().Equal(source); + } + // reference + { + var source = CreateStack(Enumerable.Range(1, count).Select(x => (string?)(x % 4 == 0 ? null : "v" + x)).ToArray()); + var bin = MemoryPackSerializer.Serialize(source); + MemoryPackSerializer.Deserialize>(bin).Should().Equal(source); + + var stack = CreateStack(Enumerable.Range(1, existingCount).Select(x => (string?)("old" + x)).ToArray()); + var original = stack; + MemoryPackSerializer.Deserialize(bin, ref stack); + + stack.Should().BeSameAs(original); + stack.Should().Equal(source); + } + } + + [Fact] + public void StackMembers() + { + var value = new CollectionPublicApiData + { + Stack = CreateStack(new CollectionPublicApiItem { Id = 1, Name = "a" }, null, new CollectionPublicApiItem { Id = 3, Name = "c" }), + NestedStack = CreateStack(CreateStack(1, 2), CreateStack(), CreateStack(3, 4, 5)), + ImmutableArray = ImmutableArray.Create("a", null, "c"), + Bits = new BitArray(new[] { true, false, true }), + }; + + var value2 = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value))!; + + value2.Stack!.Select(x => x?.Id).Should().Equal(3, null, 1); + value2.Stack!.Select(x => x?.Name).Should().Equal("c", null, "a"); + value2.NestedStack!.Select(x => x!.ToArray()).Should().BeEquivalentTo(new[] { new[] { 5, 4, 3 }, Array.Empty(), new[] { 2, 1 } }, x => x.WithStrictOrdering()); + value2.ImmutableArray.Should().Equal("a", null, "c"); + value2.Bits!.Cast().Should().Equal(true, false, true); + } + + [Fact] + public void ImmutableArrayBinary() + { + MemoryPackSerializer.Serialize(ImmutableArray.Create(1, 2, 3)).Should().Equal(Int32Collection(1, 2, 3)); + MemoryPackSerializer.Deserialize>(Int32Collection(1, 2, 3)).Should().Equal(1, 2, 3); + + MemoryPackSerializer.Deserialize>(Int32Collection()).IsEmpty.Should().BeTrue(); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(default(ImmutableArray))).IsDefault.Should().BeTrue(); + + var strings = ImmutableArray.Create("a", null, "c"); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(strings)).Should().Equal(strings); + + var large = Enumerable.Range(1, 100000).ToImmutableArray(); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(large)).Should().Equal(large); + + var largeStrings = Enumerable.Range(1, 1000).Select(x => "v" + x).ToImmutableArray(); + MemoryPackSerializer.Deserialize>(MemoryPackSerializer.Serialize(largeStrings)).Should().Equal(largeStrings); + } + + static byte[] BitArrayBinary(int length, params int[] array) + { + // (object header, int length, (int collection length, int[])) + var bin = new byte[1 + 4 + 4 + array.Length * 4]; + bin[0] = 2; + BinaryPrimitives.WriteInt32LittleEndian(bin.AsSpan(1), length); + Int32Collection(array).CopyTo(bin, 5); + return bin; + } + + [Fact] + public void BitArrayUnusedBitsAreCleared() + { + // inner array of BitArray(100, true) is filled by 0xFFFFFFFF, unused bits of the last element are not written. + MemoryPackSerializer.Serialize(new BitArray(100, true)).Should().Equal(BitArrayBinary(100, -1, -1, -1, 0b1111)); + MemoryPackSerializer.Serialize(new BitArray(100).Not()).Should().Equal(BitArrayBinary(100, -1, -1, -1, 0b1111)); + MemoryPackSerializer.Serialize(new BitArray(64, true)).Should().Equal(BitArrayBinary(64, -1, -1)); + MemoryPackSerializer.Serialize(new BitArray(1, true)).Should().Equal(BitArrayBinary(1, 1)); + MemoryPackSerializer.Serialize(new BitArray(31, true)).Should().Equal(BitArrayBinary(31, int.MaxValue)); + MemoryPackSerializer.Serialize(new BitArray(0)).Should().Equal(BitArrayBinary(0)); + + // shrink, inner array is larger than required but only writes required length. + var shrink = new BitArray(1000, true); + shrink.Length = 10; + MemoryPackSerializer.Serialize(shrink).Should().Equal(BitArrayBinary(10, 0b1111111111)); + } + + [Fact] + public void BitArrayReadsUnusedBitsAndLongerArray() + { + // binary of the older version can have garbage in unused bits and longer array. + var value = MemoryPackSerializer.Deserialize(BitArrayBinary(100, -1, -1, -1, -1))!; + value.Length.Should().Be(100); + value.Cast().Should().OnlyContain(x => x); + value.Length = 128; + value.Cast().Skip(100).Should().OnlyContain(x => !x); // garbage does not appear + + var longer = MemoryPackSerializer.Deserialize(BitArrayBinary(10, Enumerable.Repeat(-1, 32).ToArray()))!; + longer.Length.Should().Be(10); + longer.Cast().Should().OnlyContain(x => x); + MemoryPackSerializer.Serialize(longer).Should().Equal(BitArrayBinary(10, 0b1111111111)); + + // older version in Unity(Mono) wrote the length as 0, https://github.com/Cysharp/MemoryPack/issues/399 + MemoryPackSerializer.Deserialize(BitArrayBinary(0, 1, 2, 3, 4))!.Length.Should().Be(0); + } + + [Theory] + [InlineData(1)] + [InlineData(32)] + [InlineData(33)] + [InlineData(int.MaxValue)] + [InlineData(-1)] + [InlineData(int.MinValue)] + public void BitArrayLengthIsNotMatchedToArray(int length) + { + // must not allocate by the length that is not backed by the data. + var array = length == 33 ? new[] { 1 } : Array.Empty(); + Assert.Throws(() => MemoryPackSerializer.Deserialize(BitArrayBinary(length, array))); + + // null array + var bin = new byte[] { 2, 0, 0, 0, 0, 255, 255, 255, 255 }; + BinaryPrimitives.WriteInt32LittleEndian(bin.AsSpan(1), length); + Assert.Throws(() => MemoryPackSerializer.Deserialize(bin)); + } + + [Fact] + public void BitArrayNullArray() + { + MemoryPackSerializer.Deserialize(new byte[] { 2, 0, 0, 0, 0, 255, 255, 255, 255 })!.Length.Should().Be(0); + } +} + +[MemoryPackable] +public partial class CollectionPublicApiItem +{ + public int Id { get; set; } + public string? Name { get; set; } +} + +[MemoryPackable] +public partial class CollectionPublicApiData +{ + public List? List { get; set; } + public Stack? Stack { get; set; } + public Stack?>? NestedStack { get; set; } + public ImmutableArray ImmutableArray { get; set; } + public BitArray? Bits { get; set; } +}