Skip to content

Instantly share code, notes, and snippets.

@evan-choi
Created October 14, 2021 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evan-choi/08cac2ffb98b0e0b4e3d6522cf590c9c to your computer and use it in GitHub Desktop.
Save evan-choi/08cac2ffb98b0e0b4e3d6522cf590c9c to your computer and use it in GitHub Desktop.
ReadOnlySequence SequenceEquals
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