forked from Cysharp/MemoryPack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemoryPackSerializer.Serialize.cs
188 lines (166 loc) · 6.07 KB
/
MemoryPackSerializer.Serialize.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
using MemoryPack.Internal;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace MemoryPack;
#if NET7_0_OR_GREATER
using static MemoryMarshal;
using static GC;
#else
using static MemoryPack.Internal.MemoryMarshalEx;
#endif
public static partial class MemoryPackSerializer
{
[ThreadStatic]
static SerializerWriterThreadStaticState? threadStaticState;
[ThreadStatic]
static MemoryPackWriterOptionalState? threadStaticWriterOptionalState;
public static byte[] Serialize<T>(in T? value, MemoryPackSerializeOptions? options = default)
{
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
var array = AllocateUninitializedArray<byte>(Unsafe.SizeOf<T>());
Unsafe.WriteUnaligned(ref GetArrayDataReference(array), value);
return array;
}
#if NET7_0_OR_GREATER
if (TypeHelpers.TryGetUnmanagedSZArrayElementSize<T>(out var elementSize))
{
if (value == null)
{
return MemoryPackCode.NullCollectionData.ToArray();
}
var srcArray = ((Array)(object)value!);
var length = srcArray.Length;
if (length == 0)
{
return new byte[4] { 0, 0, 0, 0 };
}
var dataSize = elementSize * length;
var destArray = AllocateUninitializedArray<byte>(dataSize + 4);
ref var head = ref MemoryMarshal.GetArrayDataReference(destArray);
Unsafe.WriteUnaligned(ref head, length);
Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref head, 4), ref MemoryMarshal.GetArrayDataReference(srcArray), (uint)dataSize);
return destArray;
}
#endif
var state = threadStaticState;
if (state == null)
{
state = threadStaticState = new SerializerWriterThreadStaticState();
}
state.Init(options);
try
{
var writer = new MemoryPackWriter<ReusableLinkedArrayBufferWriter>(ref state.BufferWriter, state.BufferWriter.DangerousGetFirstBuffer(), state.OptionalState);
Serialize(ref writer, value);
return state.BufferWriter.ToArrayAndReset();
}
finally
{
state.Reset();
}
}
public static unsafe void Serialize<T, TBufferWriter>(in TBufferWriter bufferWriter, in T? value, MemoryPackSerializeOptions? options = default)
#if NET7_0_OR_GREATER
where TBufferWriter : IBufferWriter<byte>
#else
where TBufferWriter : class, IBufferWriter<byte>
#endif
{
if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
var buffer = bufferWriter.GetSpan(Unsafe.SizeOf<T>());
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(buffer), value);
bufferWriter.Advance(Unsafe.SizeOf<T>());
return;
}
#if NET7_0_OR_GREATER
if (TypeHelpers.TryGetUnmanagedSZArrayElementSize<T>(out var elementSize))
{
if (value == null)
{
var span = bufferWriter.GetSpan(4);
MemoryPackCode.NullCollectionData.CopyTo(span);
bufferWriter.Advance(4);
return;
}
var srcArray = ((Array)(object)value!);
var length = srcArray.Length;
if (length == 0)
{
var span = bufferWriter.GetSpan(4);
MemoryPackCode.ZeroCollectionData.CopyTo(span);
bufferWriter.Advance(4);
return;
}
var dataSize = elementSize * length;
var destSpan = bufferWriter.GetSpan(dataSize + 4);
ref var head = ref MemoryMarshal.GetReference(destSpan);
Unsafe.WriteUnaligned(ref head, length);
Unsafe.CopyBlockUnaligned(ref Unsafe.Add(ref head, 4), ref MemoryMarshal.GetArrayDataReference(srcArray), (uint)dataSize);
bufferWriter.Advance(dataSize + 4);
return;
}
#endif
var state = threadStaticWriterOptionalState;
if (state == null)
{
state = threadStaticWriterOptionalState = new MemoryPackWriterOptionalState();
}
state.Init(options);
try
{
var writer = new MemoryPackWriter<TBufferWriter>(ref Unsafe.AsRef(bufferWriter), state);
Serialize(ref writer, value);
}
finally
{
state.Reset();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Serialize<T, TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, in T? value)
#if NET7_0_OR_GREATER
where TBufferWriter : IBufferWriter<byte>
#else
where TBufferWriter : class, IBufferWriter<byte>
#endif
{
writer.WriteValue(value);
writer.Flush();
}
public static async ValueTask SerializeAsync<T>(Stream stream, T? value, MemoryPackSerializeOptions? options = default, CancellationToken cancellationToken = default)
{
var tempWriter = ReusableLinkedArrayBufferWriterPool.Rent();
try
{
Serialize(tempWriter, value, options);
await tempWriter.WriteToAndResetAsync(stream, cancellationToken).ConfigureAwait(false);
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
ReusableLinkedArrayBufferWriterPool.Return(tempWriter);
}
}
sealed class SerializerWriterThreadStaticState
{
public ReusableLinkedArrayBufferWriter BufferWriter;
public MemoryPackWriterOptionalState OptionalState;
public SerializerWriterThreadStaticState()
{
BufferWriter = new ReusableLinkedArrayBufferWriter(useFirstBuffer: true, pinned: true);
OptionalState = new MemoryPackWriterOptionalState();
}
public void Init(MemoryPackSerializeOptions? options)
{
OptionalState.Init(options);
}
public void Reset()
{
BufferWriter.Reset();
OptionalState.Reset();
}
}
}