Skip to content

Commit fb13d63

Browse files
authored
Merge pull request #288 from ActualLab/main
feat: MemoryPackSerializer.ResetState, ResetReaderState, ResetWriterState
2 parents 4b1e3f8 + 3456984 commit fb13d63

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
using System.Runtime.CompilerServices;
2+
3+
namespace MemoryPack;
4+
5+
public static partial class MemoryPackSerializer
6+
{
7+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
8+
public static StateSnapshot ResetState(bool resetReaderState = true, bool resetWriterState = true)
9+
=> new(resetReaderState, resetWriterState);
10+
11+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
12+
public static StateSnapshot ResetReaderState()
13+
=> new(true, false);
14+
15+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
16+
public static StateSnapshot ResetWriterState()
17+
=> new(false, true);
18+
19+
// Nested types
20+
21+
public readonly struct StateSnapshot : IDisposable
22+
{
23+
readonly bool _resetReaderState;
24+
readonly bool _resetWriterState;
25+
readonly SerializerWriterThreadStaticState? _threadStaticState;
26+
readonly MemoryPackWriterOptionalState? _threadStaticWriterOptionalState;
27+
readonly MemoryPackReaderOptionalState? _threadStaticReaderOptionalState;
28+
29+
internal StateSnapshot(bool resetReaderState, bool resetWriterState)
30+
{
31+
_resetReaderState = resetReaderState;
32+
_resetWriterState = resetWriterState;
33+
34+
if (resetReaderState)
35+
{
36+
_threadStaticReaderOptionalState = threadStaticReaderOptionalState;
37+
threadStaticReaderOptionalState = null;
38+
39+
}
40+
41+
if (resetWriterState)
42+
{
43+
_threadStaticState = threadStaticState;
44+
threadStaticState = null;
45+
_threadStaticWriterOptionalState = threadStaticWriterOptionalState;
46+
threadStaticWriterOptionalState = null;
47+
}
48+
}
49+
50+
public void Dispose()
51+
{
52+
if (_resetReaderState)
53+
{
54+
threadStaticReaderOptionalState = _threadStaticReaderOptionalState;
55+
}
56+
57+
if (_resetWriterState)
58+
{
59+
threadStaticState = _threadStaticState;
60+
threadStaticWriterOptionalState = _threadStaticWriterOptionalState;
61+
}
62+
}
63+
}
64+
}

0 commit comments

Comments
 (0)