-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathCompareInfo.cs
More file actions
1603 lines (1376 loc) · 66.6 KB
/
Copy pathCompareInfo.cs
File metadata and controls
1603 lines (1376 loc) · 66.6 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
namespace System.Globalization
{
/// <summary>
/// This class implements a set of methods for comparing strings.
/// </summary>
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed partial class CompareInfo : IDeserializationCallback
{
// Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags.
private const CompareOptions ValidIndexMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
// Mask used to check if Compare() / GetHashCode(string) / GetSortKey has the right flags.
private const CompareOptions ValidCompareMaskOffFlags =
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
// Cache the invariant CompareInfo
internal static readonly CompareInfo Invariant = CultureInfo.InvariantCulture.CompareInfo;
// CompareInfos have an interesting identity. They are attached to the locale that created them,
// ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US.
// The interesting part is that since haw-US doesn't have its own sort, it has to point at another
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization)
[NonSerialized]
private IntPtr _sortHandle;
[NonSerialized]
private string _sortName; // The name that defines our behavior
[OptionalField(VersionAdded = 3)]
private SortVersion? m_SortVersion; // Do not rename (binary serialization)
private int culture; // Do not rename (binary serialization). The fields sole purpose is to support Desktop serialization.
internal CompareInfo(CultureInfo culture)
{
m_name = culture._name;
InitSort(culture);
}
/// <summary>
/// Get the CompareInfo constructed from the data table in the specified
/// assembly for the specified culture.
/// Warning: The assembly versioning mechanism is dead!
/// </summary>
public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
{
ArgumentNullException.ThrowIfNull(assembly);
// Parameter checking.
if (assembly != typeof(object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib, nameof(assembly));
}
return GetCompareInfo(culture);
}
/// <summary>
/// Get the CompareInfo constructed from the data table in the specified
/// assembly for the specified culture.
/// The purpose of this method is to provide version for CompareInfo tables.
/// </summary>
public static CompareInfo GetCompareInfo(string name, Assembly assembly)
{
ArgumentNullException.ThrowIfNull(name);
ArgumentNullException.ThrowIfNull(assembly);
if (assembly != typeof(object).Module.Assembly)
{
throw new ArgumentException(SR.Argument_OnlyMscorlib, nameof(assembly));
}
return GetCompareInfo(name);
}
/// <summary>
/// Get the CompareInfo for the specified culture.
/// This method is provided for ease of integration with NLS-based software.
/// </summary>
public static CompareInfo GetCompareInfo(int culture)
{
if (CultureData.IsCustomCultureId(culture))
{
throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
}
/// <summary>
/// Get the CompareInfo for the specified culture.
/// </summary>
public static CompareInfo GetCompareInfo(string name)
{
ArgumentNullException.ThrowIfNull(name);
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
public static bool IsSortable(char ch)
{
return IsSortable(new ReadOnlySpan<char>(in ch));
}
public static bool IsSortable(string text)
{
ArgumentNullException.ThrowIfNull(text);
return IsSortable(text.AsSpan());
}
/// <summary>
/// Indicates whether a specified Unicode string is sortable.
/// </summary>
/// <param name="text">A string of zero or more Unicode characters.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="text"/> is non-empty and contains
/// only sortable Unicode characters; otherwise, <see langword="false"/>.
/// </returns>
public static bool IsSortable(ReadOnlySpan<char> text)
{
if (text.Length == 0)
{
return false;
}
if (GlobalizationMode.Invariant)
{
return true; // all chars are sortable in invariant mode
}
return (GlobalizationMode.UseNls) ? NlsIsSortable(text) : IcuIsSortable(text);
}
/// <summary>
/// Indicates whether a specified <see cref="Rune"/> is sortable.
/// </summary>
/// <param name="value">A Unicode scalar value.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="value"/> is a sortable Unicode scalar
/// value; otherwise, <see langword="false"/>.
/// </returns>
public static bool IsSortable(Rune value)
{
Span<char> valueAsUtf16 = stackalloc char[Rune.MaxUtf16CharsPerRune];
int charCount = value.EncodeToUtf16(valueAsUtf16);
return IsSortable(valueAsUtf16.Slice(0, charCount));
}
[MemberNotNull(nameof(_sortName))]
private void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
if (GlobalizationMode.UseNls)
{
NlsInitSortHandle();
}
else
{
IcuInitSortHandle(culture.InteropName!);
}
}
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
// this becomes null for a brief moment before deserialization
// after serialization is finished it is never null.
m_name = null!;
}
void IDeserializationCallback.OnDeserialization(object? sender)
{
OnDeserialized();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
OnDeserialized();
}
private void OnDeserialized()
{
// If we didn't have a name, use the LCID
if (m_name == null)
{
// From whidbey, didn't have a name
m_name = CultureInfo.GetCultureInfo(culture)._name;
}
else
{
InitSort(CultureInfo.GetCultureInfo(m_name));
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
// This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
culture = CultureInfo.GetCultureInfo(Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
}
/// <summary>
/// Returns the name of the culture (well actually, of the sort).
/// Very important for providing a non-LCID way of identifying
/// what the sort is.
///
/// Note that this name isn't dereferenced in case the CompareInfo is a different locale
/// which is consistent with the behaviors of earlier versions. (so if you ask for a sort
/// and the locale's changed behavior, then you'll get changed behavior, which is like
/// what happens for a version update)
/// </summary>
public string Name
{
get
{
Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set");
if (m_name == "zh-CHT" || m_name == "zh-CHS")
{
return m_name;
}
return _sortName;
}
}
/// <summary>
/// Compares the two strings with the given options. Returns 0 if the
/// two strings are equal, a number less than 0 if string1 is less
/// than string2, and a number greater than 0 if string1 is greater
/// than string2.
/// </summary>
public int Compare(string? string1, string? string2)
{
return Compare(string1, string2, CompareOptions.None);
}
public int Compare(string? string1, string? string2, CompareOptions options)
{
int retVal;
// Our paradigm is that null sorts less than any other string and
// that two nulls sort as equal.
if (string1 == null)
{
retVal = (string2 == null) ? 0 : -1;
goto CheckOptionsAndReturn;
}
if (string2 == null)
{
retVal = 1;
goto CheckOptionsAndReturn;
}
return Compare(string1.AsSpan(), string2.AsSpan(), options);
CheckOptionsAndReturn:
// If we're short-circuiting the globalization logic, we still need to check that
// the provided options were valid.
CheckCompareOptionsForCompare(options);
return retVal;
}
internal int CompareOptionIgnoreCase(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2) =>
GlobalizationMode.Invariant ?
InvariantModeCasing.CompareStringIgnoreCase(ref MemoryMarshal.GetReference(string1), string1.Length, ref MemoryMarshal.GetReference(string2), string2.Length) :
CompareStringCore(string1, string2, CompareOptions.IgnoreCase);
/// <summary>
/// Compares the specified regions of the two strings with the given
/// options.
/// Returns 0 if the two strings are equal, a number less than 0 if
/// string1 is less than string2, and a number greater than 0 if
/// string1 is greater than string2.
/// </summary>
public int Compare(string? string1, int offset1, int length1, string? string2, int offset2, int length2)
{
return Compare(string1, offset1, length1, string2, offset2, length2, CompareOptions.None);
}
public int Compare(string? string1, int offset1, string? string2, int offset2, CompareOptions options)
{
return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1,
string2, offset2, string2 == null ? 0 : string2.Length - offset2, options);
}
public int Compare(string? string1, int offset1, string? string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, CompareOptions.None);
}
public int Compare(string? string1, int offset1, int length1, string? string2, int offset2, int length2, CompareOptions options)
{
ReadOnlySpan<char> span1 = default;
ReadOnlySpan<char> span2 = default;
if (string1 == null)
{
if (offset1 != 0 || length1 != 0)
{
goto BoundsCheckError;
}
}
else if (!string1.TryGetSpan(offset1, length1, out span1))
{
goto BoundsCheckError;
}
if (string2 == null)
{
if (offset2 != 0 || length2 != 0)
{
goto BoundsCheckError;
}
}
else if (!string2.TryGetSpan(offset2, length2, out span2))
{
goto BoundsCheckError;
}
// At this point both string1 and string2 have been bounds-checked.
int retVal;
// Our paradigm is that null sorts less than any other string and
// that two nulls sort as equal.
if (string1 == null)
{
retVal = (string2 == null) ? 0 : -1;
goto CheckOptionsAndReturn;
}
if (string2 == null)
{
retVal = 1;
goto CheckOptionsAndReturn;
}
// At this point we know both string1 and string2 weren't null,
// though they may have been empty.
Debug.Assert(!Unsafe.IsNullRef(ref MemoryMarshal.GetReference(span1)));
Debug.Assert(!Unsafe.IsNullRef(ref MemoryMarshal.GetReference(span2)));
return Compare(span1, span2, options);
CheckOptionsAndReturn:
// If we're short-circuiting the globalization logic, we still need to check that
// the provided options were valid.
CheckCompareOptionsForCompare(options);
return retVal;
BoundsCheckError:
// We know a bounds check error occurred. Now we just need to figure
// out the correct error message to surface.
if (length1 < 0 || length2 < 0)
{
throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 < 0 || offset2 < 0)
{
throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength);
}
Debug.Assert(offset2 > (string2 == null ? 0 : string2.Length) - length2);
throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength);
}
/// <summary>
/// Compares two strings.
/// </summary>
/// <param name="string1">The first string to compare.</param>
/// <param name="string2">The second string to compare.</param>
/// <param name="options">The <see cref="CompareOptions"/> to use during the comparison.</param>
/// <returns>
/// Zero if <paramref name="string1"/> and <paramref name="string2"/> are equal;
/// or a negative value if <paramref name="string1"/> sorts before <paramref name="string2"/>;
/// or a positive value if <paramref name="string1"/> sorts after <paramref name="string2"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="options"/> contains an unsupported combination of flags.
/// </exception>
public int Compare(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options = CompareOptions.None)
{
if (string1 == string2) // referential equality + length
{
CheckCompareOptionsForCompare(options);
return 0;
}
if ((options & ValidCompareMaskOffFlags) == 0)
{
// Common case: caller is attempting to perform linguistic comparison.
// Pass the flags down to NLS or ICU unless we're running in invariant
// mode, at which point we normalize the flags to Ordinal[IgnoreCase].
if (!GlobalizationMode.Invariant)
{
return CompareStringCore(string1, string2, options);
}
if ((options & CompareOptions.IgnoreCase) == 0)
{
return string1.SequenceCompareTo(string2);
}
return Ordinal.CompareStringIgnoreCase(ref MemoryMarshal.GetReference(string1), string1.Length, ref MemoryMarshal.GetReference(string2), string2.Length);
}
else
{
// Less common case: caller is attempting to perform non-linguistic comparison,
// or an invalid combination of flags was supplied.
if (options == CompareOptions.Ordinal)
{
return string1.SequenceCompareTo(string2);
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return Ordinal.CompareStringIgnoreCase(ref MemoryMarshal.GetReference(string1), string1.Length, ref MemoryMarshal.GetReference(string2), string2.Length);
}
ThrowCompareOptionsCheckFailed(options);
return -1; // make the compiler happy;
}
}
// Checks that 'CompareOptions' is valid for a call to Compare, throwing the appropriate
// exception if the check fails.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[StackTraceHidden]
private static void CheckCompareOptionsForCompare(CompareOptions options)
{
// Any combination of defined CompareOptions flags is valid, except for
// Ordinal and OrdinalIgnoreCase, which may only be used in isolation.
if ((options & ValidCompareMaskOffFlags) != 0)
{
if (options != CompareOptions.Ordinal && options != CompareOptions.OrdinalIgnoreCase)
{
ThrowCompareOptionsCheckFailed(options);
}
}
}
[DoesNotReturn]
[StackTraceHidden]
private static void ThrowCompareOptionsCheckFailed(CompareOptions options)
{
throw new ArgumentException(
paramName: nameof(options),
message: ((options & CompareOptions.Ordinal) != 0) ? SR.Argument_CompareOptionOrdinal : SR.Argument_InvalidFlag);
}
private unsafe int CompareStringCore(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options) =>
GlobalizationMode.UseNls ?
NlsCompareString(string1, string2, options) :
IcuCompareString(string1, string2, options);
/// <summary>
/// Determines whether prefix is a prefix of string. If prefix equals
/// string.Empty, true is returned.
/// </summary>
public bool IsPrefix(string source, string prefix, CompareOptions options)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (prefix == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.prefix);
}
return IsPrefix(source.AsSpan(), prefix.AsSpan(), options);
}
/// <summary>
/// Determines whether a string starts with a specific prefix.
/// </summary>
/// <param name="source">The string to search within.</param>
/// <param name="prefix">The prefix to attempt to match at the start of <paramref name="source"/>.</param>
/// <param name="options">The <see cref="CompareOptions"/> to use during the match.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="prefix"/> occurs at the start of <paramref name="source"/>;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="options"/> contains an unsupported combination of flags.
/// </exception>
public unsafe bool IsPrefix(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options = CompareOptions.None)
{
// The empty string is trivially a prefix of every other string. For compat with
// earlier versions of the Framework we'll early-exit here before validating the
// 'options' argument.
if (prefix.IsEmpty)
{
return true;
}
if ((options & ValidIndexMaskOffFlags) == 0)
{
// Common case: caller is attempting to perform a linguistic search.
// Pass the flags down to NLS or ICU unless we're running in invariant
// mode, at which point we normalize the flags to Ordinal[IgnoreCase].
if (!GlobalizationMode.Invariant)
{
return StartsWithCore(source, prefix, options, matchLengthPtr: null);
}
if ((options & CompareOptions.IgnoreCase) == 0)
{
return source.StartsWith(prefix);
}
return source.StartsWithOrdinalIgnoreCase(prefix);
}
else
{
// Less common case: caller is attempting to perform non-linguistic comparison,
// or an invalid combination of flags was supplied.
if (options == CompareOptions.Ordinal)
{
return source.StartsWith(prefix);
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.StartsWithOrdinalIgnoreCase(prefix);
}
ThrowCompareOptionsCheckFailed(options);
return false; // make the compiler happy;
}
}
/// <summary>
/// Determines whether a string starts with a specific prefix.
/// </summary>
/// <param name="source">The string to search within.</param>
/// <param name="prefix">The prefix to attempt to match at the start of <paramref name="source"/>.</param>
/// <param name="options">The <see cref="CompareOptions"/> to use during the match.</param>
/// <param name="matchLength">When this method returns, contains the number of characters of
/// <paramref name="source"/> that matched the desired prefix. This may be different than the
/// length of <paramref name="prefix"/> if a linguistic comparison is performed. Set to 0
/// if the prefix did not match.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="prefix"/> occurs at the start of <paramref name="source"/>;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="options"/> contains an unsupported combination of flags.
/// </exception>
/// <remarks>
/// This method has greater overhead than other <see cref="IsPrefix"/> overloads which don't
/// take a <paramref name="matchLength"/> argument. Call this overload only if you require
/// the match length information.
/// </remarks>
public unsafe bool IsPrefix(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options, out int matchLength)
{
bool matched;
if (GlobalizationMode.Invariant || prefix.IsEmpty || (options & ValidIndexMaskOffFlags) != 0)
{
// Non-linguistic (ordinal) comparison requested, or options are invalid.
// Delegate to other overload, which validates options and throws on failure.
// If success, non-linguistic matches will always preserve prefix length.
matched = IsPrefix(source, prefix, options);
matchLength = (matched) ? prefix.Length : 0;
}
else
{
// Linguistic comparison requested and we don't need to special-case any args.
int tempMatchLength = 0;
matched = StartsWithCore(source, prefix, options, &tempMatchLength);
matchLength = tempMatchLength;
}
return matched;
}
private unsafe bool StartsWithCore(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options, int* matchLengthPtr) =>
GlobalizationMode.UseNls ?
NlsStartsWith(source, prefix, options, matchLengthPtr) :
IcuStartsWith(source, prefix, options, matchLengthPtr);
public bool IsPrefix(string source, string prefix)
{
return IsPrefix(source, prefix, CompareOptions.None);
}
/// <summary>
/// Determines whether suffix is a suffix of string. If suffix equals
/// string.Empty, true is returned.
/// </summary>
public bool IsSuffix(string source, string suffix, CompareOptions options)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (suffix == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.suffix);
}
return IsSuffix(source.AsSpan(), suffix.AsSpan(), options);
}
/// <summary>
/// Determines whether a string ends with a specific suffix.
/// </summary>
/// <param name="source">The string to search within.</param>
/// <param name="suffix">The suffix to attempt to match at the end of <paramref name="source"/>.</param>
/// <param name="options">The <see cref="CompareOptions"/> to use during the match.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="suffix"/> occurs at the end of <paramref name="source"/>;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="options"/> contains an unsupported combination of flags.
/// </exception>
public unsafe bool IsSuffix(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options = CompareOptions.None)
{
// The empty string is trivially a suffix of every other string. For compat with
// earlier versions of the Framework we'll early-exit here before validating the
// 'options' argument.
if (suffix.IsEmpty)
{
return true;
}
if ((options & ValidIndexMaskOffFlags) == 0)
{
// Common case: caller is attempting to perform a linguistic search.
// Pass the flags down to NLS or ICU unless we're running in invariant
// mode, at which point we normalize the flags to Ordinal[IgnoreCase].
if (!GlobalizationMode.Invariant)
{
return EndsWithCore(source, suffix, options, matchLengthPtr: null);
}
if ((options & CompareOptions.IgnoreCase) == 0)
{
return source.EndsWith(suffix);
}
return source.EndsWithOrdinalIgnoreCase(suffix);
}
else
{
// Less common case: caller is attempting to perform non-linguistic comparison,
// or an invalid combination of flags was supplied.
if (options == CompareOptions.Ordinal)
{
return source.EndsWith(suffix);
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.EndsWithOrdinalIgnoreCase(suffix);
}
ThrowCompareOptionsCheckFailed(options);
return false; // make the compiler happy;
}
}
/// <summary>
/// Determines whether a string ends with a specific suffix.
/// </summary>
/// <param name="source">The string to search within.</param>
/// <param name="suffix">The suffix to attempt to match at the end of <paramref name="source"/>.</param>
/// <param name="options">The <see cref="CompareOptions"/> to use during the match.</param>
/// <param name="matchLength">When this method returns, contains the number of characters of
/// <paramref name="source"/> that matched the desired suffix. This may be different than the
/// length of <paramref name="suffix"/> if a linguistic comparison is performed. Set to 0
/// if the suffix did not match.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="suffix"/> occurs at the end of <paramref name="source"/>;
/// otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="options"/> contains an unsupported combination of flags.
/// </exception>
/// <remarks>
/// This method has greater overhead than other <see cref="IsSuffix"/> overloads which don't
/// take a <paramref name="matchLength"/> argument. Call this overload only if you require
/// the match length information.
/// </remarks>
public unsafe bool IsSuffix(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options, out int matchLength)
{
bool matched;
if (GlobalizationMode.Invariant || suffix.IsEmpty || (options & ValidIndexMaskOffFlags) != 0)
{
// Non-linguistic (ordinal) comparison requested, or options are invalid.
// Delegate to other overload, which validates options and throws on failure.
// If success, non-linguistic matches will always preserve prefix length.
matched = IsSuffix(source, suffix, options);
matchLength = (matched) ? suffix.Length : 0;
}
else
{
// Linguistic comparison requested and we don't need to special-case any args.
int tempMatchLength = 0;
matched = EndsWithCore(source, suffix, options, &tempMatchLength);
matchLength = tempMatchLength;
}
return matched;
}
public bool IsSuffix(string source, string suffix)
{
return IsSuffix(source, suffix, CompareOptions.None);
}
private unsafe bool EndsWithCore(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options, int* matchLengthPtr) =>
GlobalizationMode.UseNls ?
NlsEndsWith(source, suffix, options, matchLengthPtr) :
IcuEndsWith(source, suffix, options, matchLengthPtr);
/// <summary>
/// Returns the first index where value is found in string. The
/// search starts from startIndex and ends at endIndex. Returns -1 if
/// the specified value is not found. If value equals string.Empty,
/// startIndex is returned. Throws IndexOutOfRange if startIndex or
/// endIndex is less than zero or greater than the length of string.
/// Throws ArgumentException if value (as a string) is null.
/// </summary>
public int IndexOf(string source, char value)
{
return IndexOf(source, value, CompareOptions.None);
}
public int IndexOf(string source, string value)
{
return IndexOf(source, value, CompareOptions.None);
}
public int IndexOf(string source, char value, CompareOptions options)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
return IndexOf(source, new ReadOnlySpan<char>(in value), options);
}
public int IndexOf(string source, string value, CompareOptions options)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (value == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
return IndexOf(source.AsSpan(), value.AsSpan(), options);
}
public int IndexOf(string source, char value, int startIndex)
{
return IndexOf(source, value, startIndex, CompareOptions.None);
}
public int IndexOf(string source, string value, int startIndex)
{
return IndexOf(source, value, startIndex, CompareOptions.None);
}
public int IndexOf(string source, char value, int startIndex, CompareOptions options)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public int IndexOf(string source, string value, int startIndex, CompareOptions options)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public int IndexOf(string source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public int IndexOf(string source, string value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public unsafe int IndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (!source.TryGetSpan(startIndex, count, out ReadOnlySpan<char> sourceSpan))
{
// Bounds check failed - figure out exactly what went wrong so that we can
// surface the correct argument exception.
if ((uint)startIndex > (uint)source.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
else
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
}
}
int result = IndexOf(sourceSpan, new ReadOnlySpan<char>(in value), options);
if (result >= 0)
{
result += startIndex;
}
return result;
}
public unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (value == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
if (!source.TryGetSpan(startIndex, count, out ReadOnlySpan<char> sourceSpan))
{
// Bounds check failed - figure out exactly what went wrong so that we can
// surface the correct argument exception.
if ((uint)startIndex > (uint)source.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
else
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
}
}
int result = IndexOf(sourceSpan, value, options);
if (result >= 0)
{
result += startIndex;
}
return result;
}
/// <summary>
/// Searches for the first occurrence of a substring within a source string.
/// </summary>
/// <param name="source">The string to search within.</param>
/// <param name="value">The substring to locate within <paramref name="source"/>.</param>
/// <param name="options">The <see cref="CompareOptions"/> to use during the search.</param>
/// <returns>
/// The zero-based index into <paramref name="source"/> where the substring <paramref name="value"/>
/// first appears; or -1 if <paramref name="value"/> cannot be found within <paramref name="source"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="options"/> contains an unsupported combination of flags.
/// </exception>
public unsafe int IndexOf(ReadOnlySpan<char> source, ReadOnlySpan<char> value, CompareOptions options = CompareOptions.None)
{
if ((options & ValidIndexMaskOffFlags) == 0)
{
// Common case: caller is attempting to perform a linguistic search.
// Pass the flags down to NLS or ICU unless we're running in invariant
// mode, at which point we normalize the flags to Ordinal[IgnoreCase].
if (!GlobalizationMode.Invariant)
{
if (value.IsEmpty)
{
return 0; // Empty target string trivially occurs at index 0 of every search space.
}
else
{
return IndexOfCore(source, value, options, matchLengthPtr: null, fromBeginning: true);
}
}
if ((options & CompareOptions.IgnoreCase) == 0)
{
return source.IndexOf(value);
}
return Ordinal.IndexOfOrdinalIgnoreCase(source, value);
}
else
{
// Less common case: caller is attempting to perform non-linguistic comparison,
// or an invalid combination of flags was supplied.
if (options == CompareOptions.Ordinal)
{
return source.IndexOf(value);
}
if (options == CompareOptions.OrdinalIgnoreCase)
{
return Ordinal.IndexOfOrdinalIgnoreCase(source, value);
}
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidFlag, ExceptionArgument.options);
return -1; // make the compiler happy;
}
}
/// <summary>
/// Searches for the first occurrence of a substring within a source string.
/// </summary>
/// <param name="source">The string to search within.</param>
/// <param name="value">The substring to locate within <paramref name="source"/>.</param>
/// <param name="options">The <see cref="CompareOptions"/> to use during the search.</param>
/// <param name="matchLength">When this method returns, contains the number of characters of
/// <paramref name="source"/> that matched the desired value. This may be different than the
/// length of <paramref name="value"/> if a linguistic comparison is performed. Set to 0
/// if <paramref name="value"/> is not found within <paramref name="source"/>.</param>
/// <returns>
/// The zero-based index into <paramref name="source"/> where the substring <paramref name="value"/>
/// first appears; or -1 if <paramref name="value"/> cannot be found within <paramref name="source"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="options"/> contains an unsupported combination of flags.
/// </exception>
/// <remarks>
/// This method has greater overhead than other <see cref="IndexOf"/> overloads which don't
/// take a <paramref name="matchLength"/> argument. Call this overload only if you require
/// the match length information.