-
-
Notifications
You must be signed in to change notification settings - Fork 212
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #361 from haqoff/feature/321-allow-mutable-structs…
…-as-buffer-writer Support for mutable structs as BufferWriter.
- Loading branch information
Showing
2 changed files
with
70 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
tests/MemoryPack.Tests/SerializerStructBufferWriterTest.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
using System; | ||
using System.Buffers; | ||
using MemoryPack.Tests.Models; | ||
|
||
namespace MemoryPack.Tests; | ||
|
||
public class SerializerStructBufferWriterTest | ||
{ | ||
[Fact] | ||
public void Serialize_ShouldSupportStructAsBufferWriter_WhenValueIsNotReferenceAndNotContainsReferences() | ||
{ | ||
var writer = new TestBufferWriter(); | ||
MemoryPackSerializer.Serialize(writer, 16); | ||
Assert.Equal(4, writer.WrittenSize); | ||
} | ||
|
||
[Fact] | ||
public void Serialize_ShouldSupportStructAsBufferWriter_WhenValueIsUnmanagedSZArray() | ||
{ | ||
var writer = new TestBufferWriter(); | ||
MemoryPackSerializer.Serialize(writer, new UnmanagedStruct[] { new() { X = 1, Y = 2, Z = 3 } }); | ||
Assert.Equal(16, writer.WrittenSize); | ||
} | ||
|
||
[Fact] | ||
public void Serialize_ShouldSupportStructAsBufferWriter_WhenFormatterRequired() | ||
{ | ||
var writer = new TestBufferWriter(); | ||
MemoryPackSerializer.Serialize(writer, new TestData(1)); | ||
Assert.Equal(5, writer.WrittenSize); | ||
} | ||
} | ||
|
||
[MemoryPackable] | ||
public partial record TestData(int A); | ||
|
||
public struct TestBufferWriter : IBufferWriter<byte> | ||
{ | ||
public int WrittenSize = 0; | ||
|
||
public TestBufferWriter() | ||
{ | ||
} | ||
|
||
public void Advance(int count) | ||
{ | ||
WrittenSize += count; | ||
} | ||
|
||
public Memory<byte> GetMemory(int sizeHint = 0) | ||
{ | ||
throw new InvalidOperationException(); | ||
} | ||
|
||
public Span<byte> GetSpan(int sizeHint = 0) | ||
{ | ||
return new byte[sizeHint]; | ||
} | ||
} |