Skip to content

Commit

Permalink
Lock writer while writing JSON on serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
neon-nyan committed Oct 13, 2023
1 parent eb7b686 commit 3903a23
Showing 1 changed file with 32 additions and 25 deletions.
57 changes: 32 additions & 25 deletions CollapseLauncher/Classes/Interfaces/Class/JSONSerializerHelper.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Hi3Helper;
using System;
using System;
using System.Buffers;
using System.IO;
using System.Text;
Expand Down Expand Up @@ -103,29 +102,37 @@ private static string InnerSerialize<T>(this T? data, JsonSerializerContext cont
// Check if the data is null, then return default value
if (data == null) return _defaultValue;

// Clear the writer and its buffer
jsonBufferWriter.Clear();

// SANITY CHECK: Check if the buffer is already zero-ed
if (jsonBufferWriter.WrittenCount != 0) throw new InvalidOperationException("Illegal Fault: The buffer hasn't been zeroed!");

// Reset the writer state
if (isWriteIndented) jsonWriterIndented.Reset();
else jsonWriter.Reset();

// Assign the writer
Utf8JsonWriter writer = isWriteIndented ? ref jsonWriterIndented : ref jsonWriter;

// Try serialize the type into JSON string
JsonSerializer.Serialize(writer, data, typeof(T), context);

// Write the buffer to string
ReadOnlySpan<byte> buffer = jsonBufferWriter.WrittenSpan;
string returnValue = Encoding.UTF8.GetString(buffer);

// If the serialization accepts \0 char at the end of the return, then return it with \0
// Otherwise, return as is.
return isIncludeNullEndChar ? returnValue + '\0' : returnValue;
// Lock the buffer
lock (jsonBufferWriter)
{
// Clear the writer and its buffer
jsonBufferWriter.Clear();

// SANITY CHECK: Check if the buffer is already zero-ed
if (jsonBufferWriter.WrittenCount != 0) throw new InvalidOperationException("Illegal Fault: The buffer hasn't been zeroed!");

// Reset the writer state
if (isWriteIndented) jsonWriterIndented.Reset();
else jsonWriter.Reset();

// Assign the writer
Utf8JsonWriter writer = isWriteIndented ? ref jsonWriterIndented : ref jsonWriter;

// Lock the writer
lock (writer)
{
// Try serialize the type into JSON string
JsonSerializer.Serialize(writer, data, typeof(T), context);

// Write the buffer to string
ReadOnlySpan<byte> buffer = jsonBufferWriter.WrittenSpan;
string returnValue = Encoding.UTF8.GetString(buffer);

// If the serialization accepts \0 char at the end of the return, then return it with \0
// Otherwise, return as is.
return isIncludeNullEndChar ? returnValue + '\0' : returnValue;
}
}
}
#nullable disable
}
Expand Down

0 comments on commit 3903a23

Please sign in to comment.