[API Proposal]: MemoryExtensions.CommonSuffixLength<T>
- Dominant language
- C#
- Stars
- 18.3k
- Forks
- 5.6k
- PR merge metrics
- PR metrics pending
Description
### Background and motivation
I've run into wanting this a few times over the years - most recently, it was for subtracting two BigInt's (my own custom ones, which done similarly to the normal BigInteger, but slightly differently to the BCL ones) - but this is not the only case I've run into wanting this for (I could try to find other cases if wanted, but might take me a while to actually find the relevant code, as I don't remember off the top of my head where it is or what it was for).
This to me doesn't seem any different to having both `IndexOf` and `LastIndexOf`, despite `IndexOf` being used much more overall.
### API Proposal
```csharp
namespace System
{
public static class MemoryExtensions
{
+ public static int CommonSuffixLength(this ReadOnlySpan span, ReadOnlySpan other);
+ public static int CommonSuffixLength(this ReadOnlySpan span, ReadOnlySpan other, IEqualityComparer? comparer = null);
}
}
```
### API Usage
```csharp
var bits1 = ...;
var bits2 = ...;
if (bits1.Length == bits2.Length)
{
var commonSuffixLength = bits1.CommonSuffixLength(bits2);
bits1 = bits1[..^commonSuffixLength];
bits2 = bits2[..^commonSuffixLength];
}
...
```
### Alternative Designs
We could also add the `this Span` ones for consistency with `CommonPrefixLength`, but idk if that's necessary with first class span these days, although it probably helps with languages like VB.NET using it.
If https://github.com/dotnet/runtime/issues/126756 gets approved, then we probably want a `public static int CommonSuffixLength(this ReadOnlySpan other, StringComparison comparisonType);` also to match it.
### Risks
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.