Files
dotnet/Microsoft.Toolkit.HighPerformance/Extensions/StringExtensions.cs
T
Sergio Pedri 21547f3712 Microsoft.Toolkit.HighPerformance package (part 2) (#3273)
* Added support for .NET Core 2.1 and 3.1 targets

* Fixed T[] dangerous accessors on .NET Standard

* Minor speed improvements to Array2DColumnEnumerable<T>

* Updated 2D array extensions

* Minor code tweaks

* Added DangerousGetLookupReferenceAt<T> extension

* Added BitHelper.HasLookupFlag APIs

* Added BitHelper.ExtractRange and SetRange APIs

* Added bool bitwise mask extensions

* Added StreamExtensions class on .NET Standard 2.0

* Added IBufferWriterExtensions type

* Added more Stream extensions

* Added object field offset extensions

* Minor code refactoring

* Improved description

* Switched managed count to IntPtr

* Refactored GetDjb2HashCode code, minor tweaks

* Unit tests fixes

* Refactored Count extensions, minor tweaks

* Fixed incorrect operators precedence

* Added SpanHelper.GetDjb2LikeByteHash method

* Minor code refactoring

* Code refactoring to HashCode<T>

* Minor style tweaks

* Updated comments styles to follow style convention

* Minor code tweaks to the Count method

* More code tweaks to the Count method

* Added tests for DangerousGetObjectDataByteOffset

* Fixed visibility of new object extensions

* Added tests for 64-bit extract/set range APIs

* Added tests for bool to bitwise mask APIs

* Fixed MemoryStream EOF exception type

* Enabled Stream extension tests on UWP

* Added StreamExtensions read/write value tests

* Minor code refactoring to IBufferWriter<T> extensions

* Added IBufferWriterExtensions tests

* Added MemoryBufferWriter<T> type

* Added IBuffer<T> interface

* Added MemoryBufferWriterDebugView<T> type

* Added MemoryBufferWriter<T> tests

* Fixed a unit test

* Fixed incorrect inlining attribute

* Removed leftover partial modifier

* Added missing readonly modifier for lock structs

* Improved summary for the Box<T> type

* Added comments for #pragma warning disable items

* Added info on (x << 5) + x over x * 33 optimization

* Improved XML docs for BitHelper APIs

* Fixed potentially misleading test method names

* Added comment for MemoryOwner<T>.Dispose test

* Fixed multi-target support for string extensions

* Improved IMemoryOwner.AsStream tests

* Added XML remarks to the HashCode<T> type

* Improved docs for ReadOnlySpanExtensions.GetDjb2HashCode<T>

* Tweaked an XML link

* Tweaked attributes for SpanHelper methods

* Minor optimizations to SpanHelper.Count

* Fixed an overflow bug in SpanHelper.Count

* Speed improvements to SpanHelper.Count

~35% speedup with large collections of byte-size values, ~10% with other types

* Updated .csproj description

* Added float/double support to SpanHelper.Count

* Added exception to the Box<T> constructor

* Removed unnecessary [SuppressMessage] attributes

* Removed [SuppressMessage] attributes

* Changed NullableRef<T>-s exceptions to follow Nullable<T>

* Added more operators to NullableRef<T> types

* Added missing in modifiers in ParallelHelper.For overloads

* Removed SIMD support for float/double count

It lacked proper handling of NaN values and both (signed) zeros

* Fixed compiler directives in SpanEnumerable<T>

* Updated ReadOnlySpanEnumerable<T> type

* Updated NuGet package tags

* Added HighPerformance package to readme.md list

* Added .NET Standard 1.4 target

* Added tests for implicit NullableRef<T> operators

* Removed unnecessary using directive

* Added missing sealed modifiers to MemoryStream methods

* Added Span<T>.IndexOf(ref T) extension

* Added ReadOnlySpan<T>.IndexOf<T>(in T) extension

* Added missing changes (incorrect commit)

* Removed unnecessary workaround (method is inlined)

* Added improved remarks for bool.ToBitwiseMask32/64

* Added internal NotNullWhen attribute when < .NET Standard 2.1

* Enabled .csproj-wide nullability annotations

* Minor code style tweaks

* Added [ReadOnly]NullableRef<T>.Null static properties
2020-05-13 12:32:20 -07:00

167 lines
7.9 KiB
C#

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.HighPerformance.Enumerables;
using Microsoft.Toolkit.HighPerformance.Helpers.Internals;
namespace Microsoft.Toolkit.HighPerformance.Extensions
{
/// <summary>
/// Helpers for working with the <see cref="string"/> type.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Returns a reference to the first element within a given <see cref="string"/>, with no bounds checks.
/// </summary>
/// <param name="text">The input <see cref="string"/> instance.</param>
/// <returns>A reference to the first element within <paramref name="text"/>, or the location it would have used, if <paramref name="text"/> is empty.</returns>
/// <remarks>This method doesn't do any bounds checks, therefore it is responsibility of the caller to perform checks in case the returned value is dereferenced.</remarks>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref char DangerousGetReference(this string text)
{
#if NETCOREAPP3_1
return ref Unsafe.AsRef(text.GetPinnableReference());
#elif NETCOREAPP2_1
var stringData = Unsafe.As<RawStringData>(text);
return ref stringData.Data;
#else
return ref MemoryMarshal.GetReference(text.AsSpan());
#endif
}
/// <summary>
/// Returns a reference to an element at a specified index within a given <see cref="string"/>, with no bounds checks.
/// </summary>
/// <param name="text">The input <see cref="string"/> instance.</param>
/// <param name="i">The index of the element to retrieve within <paramref name="text"/>.</param>
/// <returns>A reference to the element within <paramref name="text"/> at the index specified by <paramref name="i"/>.</returns>
/// <remarks>This method doesn't do any bounds checks, therefore it is responsibility of the caller to ensure the <paramref name="i"/> parameter is valid.</remarks>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref char DangerousGetReferenceAt(this string text, int i)
{
#if NETCOREAPP3_1
ref char r0 = ref Unsafe.AsRef(text.GetPinnableReference());
#elif NETCOREAPP2_1
ref char r0 = ref Unsafe.As<RawStringData>(text).Data;
#else
ref char r0 = ref MemoryMarshal.GetReference(text.AsSpan());
#endif
ref char ri = ref Unsafe.Add(ref r0, i);
return ref ri;
}
#if NETCOREAPP2_1
// Description adapted from CoreCLR: see https://source.dot.net/#System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs,285.
// CLR strings are laid out in memory as follows:
// [ sync block || pMethodTable || length || string data .. ]
// ^ ^
// | \-- ref Unsafe.As<RawStringData>(text).Data
// \-- string
// The reference to RawStringData.Data points to the first character in the
// string, skipping over the sync block, method table and string length.
[StructLayout(LayoutKind.Explicit)]
private sealed class RawStringData
{
#pragma warning disable CS0649 // Unassigned fields
#pragma warning disable SA1401 // Fields should be private
[FieldOffset(4)]
public char Data;
#pragma warning restore CS0649
#pragma warning restore SA1401
}
#endif
/// <summary>
/// Counts the number of occurrences of a given character into a target <see cref="string"/> instance.
/// </summary>
/// <param name="text">The input <see cref="string"/> instance to read.</param>
/// <param name="c">The character to look for.</param>
/// <returns>The number of occurrences of <paramref name="c"/> in <paramref name="text"/>.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Count(this string text, char c)
{
ref char r0 = ref text.DangerousGetReference();
IntPtr length = (IntPtr)text.Length;
return SpanHelper.Count(ref r0, length, c);
}
/// <summary>
/// Enumerates the items in the input <see cref="string"/> instance, as pairs of value/index values.
/// This extension should be used directly within a <see langword="foreach"/> loop:
/// <code>
/// string text = "Hello, world!";
///
/// foreach (var item in text.Enumerate())
/// {
/// // Access the index and value of each item here...
/// int index = item.Index;
/// string value = item.Value;
/// }
/// </code>
/// The compiler will take care of properly setting up the <see langword="foreach"/> loop with the type returned from this method.
/// </summary>
/// <param name="text">The source <see cref="string"/> to enumerate.</param>
/// <returns>A wrapper type that will handle the value/index enumeration for <paramref name="text"/>.</returns>
/// <remarks>The returned <see cref="ReadOnlySpanEnumerable{T}"/> value shouldn't be used directly: use this extension in a <see langword="foreach"/> loop.</remarks>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpanEnumerable<char> Enumerate(this string text)
{
return new ReadOnlySpanEnumerable<char>(text.AsSpan());
}
/// <summary>
/// Tokenizes the values in the input <see cref="string"/> instance using a specified separator.
/// This extension should be used directly within a <see langword="foreach"/> loop:
/// <code>
/// string text = "Hello, world!";
///
/// foreach (var token in text.Tokenize(','))
/// {
/// // Access the tokens here...
/// }
/// </code>
/// The compiler will take care of properly setting up the <see langword="foreach"/> loop with the type returned from this method.
/// </summary>
/// <param name="text">The source <see cref="string"/> to tokenize.</param>
/// <param name="separator">The separator character to use.</param>
/// <returns>A wrapper type that will handle the tokenization for <paramref name="text"/>.</returns>
/// <remarks>The returned <see cref="ReadOnlySpanTokenizer{T}"/> value shouldn't be used directly: use this extension in a <see langword="foreach"/> loop.</remarks>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpanTokenizer<char> Tokenize(this string text, char separator)
{
return new ReadOnlySpanTokenizer<char>(text.AsSpan(), separator);
}
/// <summary>
/// Gets a content hash from the input <see cref="string"/> instance using the Djb2 algorithm.
/// For more info, see the documentation for <see cref="ReadOnlySpanExtensions.GetDjb2HashCode{T}"/>.
/// </summary>
/// <param name="text">The source <see cref="string"/> to enumerate.</param>
/// <returns>The Djb2 value for the input <see cref="string"/> instance.</returns>
/// <remarks>The Djb2 hash is fully deterministic and with no random components.</remarks>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetDjb2HashCode(this string text)
{
ref char r0 = ref text.DangerousGetReference();
IntPtr length = (IntPtr)text.Length;
return SpanHelper.GetDjb2HashCode(ref r0, length);
}
}
}