forked from CommunityToolkit/WindowsCommunityToolkit
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathStringExtensions.cs
144 lines (134 loc) · 7.14 KB
/
StringExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// 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;
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)
{
var stringData = Unsafe.As<RawStringData>(text);
return ref stringData.Data;
}
/// <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)
{
var stringData = Unsafe.As<RawStringData>(text);
ref var ri = ref Unsafe.Add(ref stringData.Data, i);
return ref ri;
}
// 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
}
/// <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)
{
return text.AsSpan().Count(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.
/// </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)
{
return text.AsSpan().GetDjb2HashCode();
}
}
}