Created
January 30, 2025 22:38
-
-
Save to11mtm/6889858a52c4ff22793d4c815f2daacd to your computer and use it in GitHub Desktop.
Akka Bytestring ReadOnlySequence WIP/example
This file contains hidden or 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
public class ByteStringReadOnlySequenceSegment : ReadOnlySequenceSegment<byte> | |
{ | |
public ByteStringReadOnlySequenceSegment(ReadOnlyMemory<byte> memory, long runningIndex) | |
{ | |
Memory = memory; | |
RunningIndex = runningIndex; | |
} | |
public static (ByteStringReadOnlySequenceSegment first, ByteStringReadOnlySequenceSegment last) Create(ByteString bs) | |
{ | |
var bArr = bs.Buffers; | |
var toMake = bArr.Count; | |
var first = new ByteStringReadOnlySequenceSegment(bArr[0],0); | |
var last = new ByteStringReadOnlySequenceSegment(bArr[toMake-1], bs.Count-bArr[toMake-1].Count); | |
if (toMake == 2) | |
{ | |
first.Next = last; | |
} | |
else | |
{ | |
var prior = first; | |
for (int i = 1; i < toMake-1; i++) | |
{ | |
var item = bArr[i]; | |
var curr = new ByteStringReadOnlySequenceSegment(item, prior.RunningIndex+prior.Memory.Length); | |
prior.Next = curr; | |
prior = curr; | |
} | |
prior.Next = last; | |
} | |
//var first = new ByteStringReadOnlySequenceSegment(bs, 0, 0); | |
//var last = new ByteStringReadOnlySequenceSegment(bs, bs.Count, bs.Buffers.Count - 1); | |
//first.Next = last; | |
return (first, last); | |
} | |
} | |
/// <summary> | |
/// A rope-like immutable data structure containing bytes. | |
/// The goal of this structure is to reduce copying of arrays | |
/// when concatenating and slicing sequences of bytes, | |
/// and also providing a thread safe way of working with bytes. | |
/// </summary> | |
[DebuggerDisplay("(Count = {_count}, Buffers = {_buffers})")] | |
public sealed class ByteString : IEquatable<ByteString>, IEnumerable<byte> | |
{ | |
public ReadOnlySequence<byte> AsReadOnlySequence() | |
{ | |
if (_count == 0) | |
{ | |
return ReadOnlySequence<byte>.Empty; | |
} | |
else if (_buffers.Length == 1) | |
{ | |
return new ReadOnlySequence<byte>(_buffers[0]); | |
} | |
else | |
{ | |
var (first, last) = ByteStringReadOnlySequenceSegment.Create(this); | |
return new ReadOnlySequence<byte>(first,0,last,last.Memory.Length); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment