Created
September 11, 2018 16:02
-
-
Save GeorgeTsiokos/8bce21daf2b43640acafdd8cbb656283 to your computer and use it in GitHub Desktop.
ReadOnlySequence<byte> TO IReadOnlyList<string> && IReadOnlyList<string> TO ref Span<byte>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal sealed class ReadOnlySequenceConsumer | |
{ | |
readonly List<string> _result = new List<string>(); | |
public IReadOnlyList<string> Result => _result; | |
public void Consume(ReadOnlySequence<byte> message) => _result.Add(GetString(message)); | |
public string GetString(ReadOnlySequence<byte> message) => message.IsSingleSegment ? Encoding.ASCII.GetString(message.First.Span) : string.Create((int)message.Length, message, GetChars); | |
static void GetChars(Span<char> span, ReadOnlySequence<byte> sequence) | |
{ | |
foreach (var segment in sequence) | |
{ | |
Encoding.ASCII.GetChars(segment.Span, span); | |
span = span.Slice(segment.Length); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal sealed class SpanDataProducer | |
{ | |
const int BufferSize = 0xFA00; | |
readonly IMemoryOwner<byte> _memoryOwner; | |
readonly IReadOnlyList<string> _requests; | |
int _index; | |
public RawBetaProducer(IReadOnlyList<string> requests) | |
{ | |
_requests = requests; | |
_memoryOwner = MemoryPool<byte>.Shared.Rent(BufferSize); | |
} | |
public int Count => _requests.Count; | |
public void Encode(int length, ref Span<byte> span) | |
{ | |
if (BufferSize < length) | |
throw new ArgumentOutOfRangeException(nameof(length)); | |
var slice = _memoryOwner.Memory.Span.Slice(0, length); | |
slice.CopyTo(span); | |
if (++_index == _requests.Count) | |
_memoryOwner.Dispose(); | |
} | |
public int Length => Encoding.ASCII.GetBytes(_requests[_index], _memoryOwner.Memory.Span); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment