Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 64 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<DateTimeOffset>`, 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<T>` 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<T>` 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<T>` implicitly.

```csharp
[MemoryPackable]
public partial class Sample
{
// int? -> SafeNullable<int>
public SafeNullable<int> Id { get; set; }
public SafeNullable<long>[]? 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<T>`, so you can replace `T?` with `SafeNullable<T>` and both can read each other's binary. In other types (`Guid`, `decimal`, user-defined struct, etc.), the size is different from `Nullable<T>` 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.
Expand Down Expand Up @@ -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
Expand Down
56 changes: 39 additions & 17 deletions src/MemoryPack.Core/Formatters/BitArrayFormatter.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
using MemoryPack.Internal;
using System.Buffers;
using System.Collections;
using System.Runtime.CompilerServices;

namespace MemoryPack.Formatters;

[Preserve]
public sealed class BitArrayFormatter : MemoryPackFormatter<BitArray>
{
// serialize [m_length, m_array]
// serialize [length(bit count), int[]]

// 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<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref BitArray? value)
Expand All @@ -18,10 +21,29 @@ public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter
return;
}

ref var view = ref Unsafe.As<BitArray, BitArrayView>(ref value);
var length = value.Length;
var arrayLength = GetInt32ArrayLength(length);

var rented = ArrayPool<int>.Shared.Rent(arrayLength);
try
{
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, view.m_length);
writer.WriteUnmanagedArray(view.m_array);
writer.WriteUnmanagedWithObjectHeader(2, length);
writer.WriteUnmanagedSpan(span);
}
finally
{
ArrayPool<int>.Shared.Return(rented);
}
}

[Preserve]
Expand All @@ -36,21 +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<int>() ?? Array.Empty<int>();

var bitArray = new BitArray(length, false); // create internal int[] and set m_length to length

ref var view = ref Unsafe.As<BitArray, BitArrayView>(ref bitArray);
reader.ReadUnmanagedArray(ref view.m_array!);
// 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))
{
MemoryPackSerializationException.ThrowMessage($"BitArray length {length} is not matched to array length {array.Length}.");
}

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;
}
}
91 changes: 68 additions & 23 deletions src/MemoryPack.Core/Formatters/CollectionFormatters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,15 +105,17 @@ public static void DeserializePackable<T>(ref MemoryPackReader reader, scoped re
{
value = new List<T?>(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();
Expand Down Expand Up @@ -166,15 +168,17 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref List<T?
{
value = new List<T?>(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();
Expand Down Expand Up @@ -202,17 +206,30 @@ public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter
return;
}

#if NET7_0_OR_GREATER
writer.WriteSpan(CollectionsMarshalEx.AsSpan(value));
#else
var formatter = writer.GetFormatter<T?>();
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<T?>.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<T>())
{
rented.AsSpan(0, count).Clear();
}
ArrayPool<T?>.Shared.Return(rented);
}
#endif
}

[Preserve]
Expand All @@ -224,31 +241,59 @@ public override void Deserialize(ref MemoryPackReader reader, scoped ref Stack<T
return;
}

if (value == null)
// Stack has no public API to get the inner array.
if (length != 0 && !RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
value = new Stack<T?>(length);
}
// read at once to the pooled array.
var rented = ArrayPool<T?>.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<T> at once.
value = new Stack<T?>(new ArraySegment<T?>(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<T?>.Shared.Return(rented);
}
return;
}

var span = CollectionsMarshalEx.CreateSpan(value, length);
reader.ReadSpanWithoutReadLengthHeader(length, ref span);
#else
if (value == null)
{
value = new Stack<T?>(length);
}
else
{
value.Clear();
#if NET7_0_OR_GREATER
value.EnsureCapacity(length);
#endif
}

var formatter = reader.GetFormatter<T?>();
for (int i = 0; i < length; i++)
{
T? v = default;
formatter.Deserialize(ref reader, ref v);
value.Push(v);
}
#endif
}
}

Expand Down
45 changes: 34 additions & 11 deletions src/MemoryPack.Core/Formatters/ImmutableCollectionFormatters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter
[Preserve]
public override void Deserialize(ref MemoryPackReader reader, scoped ref ImmutableArray<T?> value)
{
#if NET8_0_OR_GREATER
var array = reader.ReadArray<T?>();
if (array == null)
{
Expand All @@ -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<T?>();
ref var view = ref Unsafe.As<ImmutableArray<T?>, ImmutableArrayView<T?>>(ref value);
view.array = array;
if (!reader.TryReadCollectionHeader(out var length))
{
value = default;
return;
}

if (length == 0)
{
value = ImmutableArray<T?>.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<T>();
var rented = ArrayPool<T?>.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<T?>.Shared.Return(rented);
}
#endif
}
}

[Preserve]
internal struct ImmutableArrayView<T>
{
public T[]? array;
}

[Preserve]
public sealed class ImmutableListFormatter<T> : MemoryPackFormatter<ImmutableList<T?>>
{
Expand Down
Loading
Loading