Skip to content

Commit

Permalink
init IBufferWriter Implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
j0nimost committed Oct 23, 2023
1 parent 17bf476 commit d6596ab
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 0 deletions.
79 changes: 79 additions & 0 deletions src/Kafa/Writer/KafaPooledWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System.Buffers;

namespace nyingi.Kafa.Writer
{
internal sealed class KafaPooledWriter : IBufferWriter<byte>, IDisposable
{
private const int MAXBUFFERLENGTH = 65556;
private byte[] _buffer;

private int _index = 0;

public int WrittenCount => _index;
public int Capacity => _buffer.Length;
public int FreeCapacity => _buffer.Length - _index;

public KafaPooledWriter(int length)
{
_buffer = ArrayPool<byte>.Shared.Rent(Math.Max(length, MAXBUFFERLENGTH));
}
public void Advance(int count)
{
if(count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
_index += count;
}

public Memory<byte> GetMemory(int sizeHint = 0)
{
Resize(sizeHint);
return _buffer.AsMemory(sizeHint);
}

public Span<byte> GetSpan(int sizeHint = 0)
{
Resize(sizeHint);
return _buffer.AsSpan(sizeHint);
}


public ReadOnlySpan<byte> WrittenAsSpan() => _buffer.AsSpan(0, _index);

private void Resize(int sizeHint)
{
if (sizeHint < 0)
{
throw new ArgumentOutOfRangeException(nameof(sizeHint));
}

if(sizeHint > FreeCapacity)
{
int growBy = Math.Max(Capacity, sizeHint);
int newCapacity = Capacity;
checked
{
newCapacity += growBy;
}

var newBuffer = ArrayPool<byte>.Shared.Rent(newCapacity);
Array.Copy(_buffer, newBuffer, Capacity);
_buffer = null!;
_buffer = newBuffer;
ArrayPool<byte>.Shared.Return(newBuffer);
}
}



public void Dispose()
{
if(_buffer == null)
{
return;
}
ArrayPool<byte>.Shared.Return(_buffer);
}
}
}
29 changes: 29 additions & 0 deletions src/Kafa/Writer/KafaWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Buffers;

namespace nyingi.Kafa.Writer
{
internal partial class KafaWriter : IDisposable
{
private readonly IBufferWriter<byte> _bufferWriter;
public int BytesWritten { get; private set; }
private Stream? _stream = default;
private Memory<byte> _memory = default;


public KafaWriter(IBufferWriter<byte> bufferWriter)
{
_bufferWriter = bufferWriter;
}

public KafaWriter(Stream stream)
{
_stream = stream;
}


public void Dispose()
{
throw new NotImplementedException();
}
}
}

0 comments on commit d6596ab

Please sign in to comment.