Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: MemoryPackSerializer.ResetState, ResetReaderState, ResetWriterState #288

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/MemoryPack.Core/MemoryPackSerializer.StateBackup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System.Runtime.CompilerServices;

namespace MemoryPack;

public static partial class MemoryPackSerializer
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static StateSnapshot ResetState(bool resetReaderState = true, bool resetWriterState = true)
=> new(resetReaderState, resetWriterState);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static StateSnapshot ResetReaderState()
=> new(true, false);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static StateSnapshot ResetWriterState()
=> new(false, true);

// Nested types

public readonly struct StateSnapshot : IDisposable
{
readonly bool _resetReaderState;
readonly bool _resetWriterState;
readonly SerializerWriterThreadStaticState? _threadStaticState;
readonly MemoryPackWriterOptionalState? _threadStaticWriterOptionalState;
readonly MemoryPackReaderOptionalState? _threadStaticReaderOptionalState;

internal StateSnapshot(bool resetReaderState, bool resetWriterState)
{
_resetReaderState = resetReaderState;
_resetWriterState = resetWriterState;

if (resetReaderState)
{
_threadStaticReaderOptionalState = threadStaticReaderOptionalState;
threadStaticReaderOptionalState = null;

}

if (resetWriterState)
{
_threadStaticState = threadStaticState;
threadStaticState = null;
_threadStaticWriterOptionalState = threadStaticWriterOptionalState;
threadStaticWriterOptionalState = null;
}
}

public void Dispose()
{
if (_resetReaderState)
{
threadStaticReaderOptionalState = _threadStaticReaderOptionalState;
}

if (_resetWriterState)
{
threadStaticState = _threadStaticState;
threadStaticWriterOptionalState = _threadStaticWriterOptionalState;
}
}
}
}