/*
MIT License
Copyright (c) 2019 Gérald Barré
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// TODO: remove when analyzer is fixed: https://github.com/dotnet/roslyn-analyzers/issues/5158
#pragma warning disable CA1034 // Nested types should not be visible
using System;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
namespace Jellyfin.Extensions
{
///
/// Extension class for splitting lines without unnecessary allocations.
///
public static class SplitStringExtensions
{
///
/// Creates a new string split enumerator.
///
/// The string to split.
/// The separator to split on.
/// The enumerator struct.
[Pure]
public static Enumerator SpanSplit(this string str, char separator) => new (str.AsSpan(), separator);
///
/// Creates a new span split enumerator.
///
/// The span to split.
/// The separator to split on.
/// The enumerator struct.
[Pure]
public static Enumerator Split(this ReadOnlySpan str, char separator) => new (str, separator);
///
/// Provides an enumerator for the substrings seperated by the separator.
///
[StructLayout(LayoutKind.Auto)]
public ref struct Enumerator
{
private readonly char _separator;
private ReadOnlySpan _str;
///
/// Initializes a new instance of the struct.
///
/// The span to split.
/// The separator to split on.
public Enumerator(ReadOnlySpan str, char separator)
{
_str = str;
_separator = separator;
Current = default;
}
///
/// Gets a reference to the item at the current position of the enumerator.
///
public ReadOnlySpan Current { get; private set; }
///
/// Returns this.
///
/// this.
public readonly Enumerator GetEnumerator() => this;
///
/// Advances the enumerator to the next item.
///
/// true if there is a next element; otherwise false.
public bool MoveNext()
{
if (_str.Length == 0)
{
return false;
}
var span = _str;
var index = span.IndexOf(_separator);
if (index == -1)
{
_str = ReadOnlySpan.Empty;
Current = span;
return true;
}
Current = span.Slice(0, index);
_str = span[(index + 1)..];
return true;
}
}
}
}