Created
October 14, 2021 15:36
-
-
Save evan-choi/08cac2ffb98b0e0b4e3d6522cf590c9c to your computer and use it in GitHub Desktop.
ReadOnlySequence SequenceEquals
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
using System; | |
using System.Buffers; | |
public static class ReadOnlySequenceExtension | |
{ | |
public static bool SequenceEquals<T>(in this ReadOnlySequence<T> a, in ReadOnlySequence<T> b) where T : IEquatable<T> | |
{ | |
if (a.Length != b.Length) | |
return false; | |
var aEnumerator = a.GetEnumerator(); | |
var bEnumerator = b.GetEnumerator(); | |
if (!aEnumerator.MoveNext() || !bEnumerator.MoveNext()) | |
return false; | |
ReadOnlyMemory<T> aMemory = aEnumerator.Current; | |
ReadOnlyMemory<T> bMemory = bEnumerator.Current; | |
while (!aMemory.IsEmpty || !bMemory.IsEmpty) | |
{ | |
var length = Math.Min(aMemory.Length, bMemory.Length); | |
if (!aMemory[..length].Span.SequenceEqual(bMemory[..length].Span)) | |
return false; | |
aMemory = aMemory[length..]; | |
bMemory = bMemory[length..]; | |
if (aMemory.IsEmpty && aEnumerator.MoveNext()) | |
aMemory = aEnumerator.Current; | |
if (bMemory.IsEmpty && bEnumerator.MoveNext()) | |
bMemory = bEnumerator.Current; | |
} | |
return aMemory.IsEmpty && bMemory.IsEmpty; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment