Skip to content

Instantly share code, notes, and snippets.

@thenameless314159
Created January 8, 2020 15:05
Show Gist options
  • Save thenameless314159/e99ff3f0570cf89c3316e70bebf7c796 to your computer and use it in GitHub Desktop.
Save thenameless314159/e99ff3f0570cf89c3316e70bebf7c796 to your computer and use it in GitHub Desktop.
public ref struct SpanWriter
{
private readonly Span<byte> _buffer;
private int _position;
public int Remaining => Count - Position;
public int Count { get; }
public int Position
{
get => _position;
private set
{
if (value > Count || value < 0)
{
throw new InvalidOperationException(
$"Cannot set position at {value} because < 0 or > count:{Count} !");
}
_position = value;
}
}
public SpanWriter(Span<byte> buffer)
{
Count = buffer.Length;
_buffer = buffer;
_position = 0;
Position = 0;
}
public void Seek(int position) => Position = position;
public void Advance(int count) => Position += count;
public Span<byte> GetSpan(int count = 0)
=> count == 0
? _buffer.Slice(Position)
: _buffer.Slice(Position, count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment