Skip to content

Commit

Permalink
add NatsMemoryOwner (#162)
Browse files Browse the repository at this point in the history
Signed-off-by: Caleb Lloyd <[email protected]>
  • Loading branch information
caleblloyd authored Oct 20, 2023
1 parent 5430c18 commit 20797d2
Show file tree
Hide file tree
Showing 5 changed files with 405 additions and 65 deletions.
30 changes: 4 additions & 26 deletions src/NATS.Client.Core/INatsSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,6 @@ public interface ICountableBufferWriter : IBufferWriter<byte>
int WrittenCount { get; }
}

public readonly struct FixedSizeMemoryOwner : IMemoryOwner<byte>
{
private readonly IMemoryOwner<byte> _owner;

public FixedSizeMemoryOwner(IMemoryOwner<byte> owner, int size)
{
_owner = owner;
Memory = _owner.Memory.Slice(0, size);
}

public Memory<byte> Memory { get; }

public void Dispose() => _owner.Dispose();
}

public static class NatsDefaultSerializer
{
public static readonly INatsSerializer Default = new NatsRawSerializer(NatsJsonSerializer.Default);
Expand Down Expand Up @@ -118,9 +103,9 @@ public int Serialize<T>(ICountableBufferWriter bufferWriter, T? value)
return (T)(object)new ReadOnlySequence<byte>(buffer.ToArray());
}

if (typeof(T) == typeof(IMemoryOwner<byte>))
if (typeof(T) == typeof(IMemoryOwner<byte>) || typeof(T) == typeof(NatsMemoryOwner<byte>))
{
var memoryOwner = new FixedSizeMemoryOwner(MemoryPool<byte>.Shared.Rent((int)buffer.Length), (int)buffer.Length);
var memoryOwner = NatsMemoryOwner<byte>.Allocate((int)buffer.Length);
buffer.CopyTo(memoryOwner.Memory.Span);
return (T)(object)memoryOwner;
}
Expand All @@ -134,11 +119,7 @@ public int Serialize<T>(ICountableBufferWriter bufferWriter, T? value)

public sealed class NatsJsonSerializer : INatsSerializer
{
private static readonly JsonWriterOptions JsonWriterOpts = new JsonWriterOptions
{
Indented = false,
SkipValidation = true,
};
private static readonly JsonWriterOptions JsonWriterOpts = new JsonWriterOptions { Indented = false, SkipValidation = true, };

[ThreadStatic]
private static Utf8JsonWriter? _jsonWriter;
Expand All @@ -148,10 +129,7 @@ public sealed class NatsJsonSerializer : INatsSerializer
public NatsJsonSerializer(JsonSerializerOptions opts) => _opts = opts;

public static NatsJsonSerializer Default { get; } =
new(new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
});
new(new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, });

public INatsSerializer? Next => default;

Expand Down
Loading

0 comments on commit 20797d2

Please sign in to comment.