String.Comparison.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.Numerics;
  7. using System.Runtime.CompilerServices;
  8. using System.Runtime.InteropServices;
  9. using Internal.Runtime.CompilerServices;
  10. #if BIT64
  11. using nuint = System.UInt64;
  12. #else
  13. using nuint = System.UInt32;
  14. #endif
  15. namespace System
  16. {
  17. public partial class String
  18. {
  19. //
  20. // Search/Query methods
  21. //
  22. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  23. private static bool EqualsHelper(string strA, string strB)
  24. {
  25. Debug.Assert(strA != null);
  26. Debug.Assert(strB != null);
  27. Debug.Assert(strA.Length == strB.Length);
  28. return SpanHelpers.SequenceEqual(
  29. ref Unsafe.As<char, byte>(ref strA.GetRawStringData()),
  30. ref Unsafe.As<char, byte>(ref strB.GetRawStringData()),
  31. ((nuint)strA.Length) * 2);
  32. }
  33. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  34. private static int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB)
  35. {
  36. Debug.Assert(strA != null);
  37. Debug.Assert(strB != null);
  38. Debug.Assert(indexA >= 0 && indexB >= 0);
  39. Debug.Assert(countA >= 0 && countB >= 0);
  40. Debug.Assert(indexA + countA <= strA.Length && indexB + countB <= strB.Length);
  41. return SpanHelpers.SequenceCompareTo(ref Unsafe.Add(ref strA.GetRawStringData(), indexA), countA, ref Unsafe.Add(ref strB.GetRawStringData(), indexB), countB);
  42. }
  43. private static bool EqualsOrdinalIgnoreCase(string strA, string strB)
  44. {
  45. Debug.Assert(strA.Length == strB.Length);
  46. return CompareInfo.EqualsOrdinalIgnoreCase(ref strA.GetRawStringData(), ref strB.GetRawStringData(), strB.Length);
  47. }
  48. private static unsafe int CompareOrdinalHelper(string strA, string strB)
  49. {
  50. Debug.Assert(strA != null);
  51. Debug.Assert(strB != null);
  52. // NOTE: This may be subject to change if eliminating the check
  53. // in the callers makes them small enough to be inlined
  54. Debug.Assert(strA._firstChar == strB._firstChar,
  55. "For performance reasons, callers of this method should " +
  56. "check/short-circuit beforehand if the first char is the same.");
  57. int length = Math.Min(strA.Length, strB.Length);
  58. fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
  59. {
  60. char* a = ap;
  61. char* b = bp;
  62. // Check if the second chars are different here
  63. // The reason we check if _firstChar is different is because
  64. // it's the most common case and allows us to avoid a method call
  65. // to here.
  66. // The reason we check if the second char is different is because
  67. // if the first two chars the same we can increment by 4 bytes,
  68. // leaving us word-aligned on both 32-bit (12 bytes into the string)
  69. // and 64-bit (16 bytes) platforms.
  70. // For empty strings, the second char will be null due to padding.
  71. // The start of the string is the type pointer + string length, which
  72. // takes up 8 bytes on 32-bit, 12 on x64. For empty strings the null
  73. // terminator immediately follows, leaving us with an object
  74. // 10/14 bytes in size. Since everything needs to be a multiple
  75. // of 4/8, this will get padded and zeroed out.
  76. // For one-char strings the second char will be the null terminator.
  77. // NOTE: If in the future there is a way to read the second char
  78. // without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe
  79. // is exposed to mscorlib, or a future version of C# allows inline IL),
  80. // then do that and short-circuit before the fixed.
  81. if (*(a + 1) != *(b + 1)) goto DiffOffset1;
  82. // Since we know that the first two chars are the same,
  83. // we can increment by 2 here and skip 4 bytes.
  84. // This leaves us 8-byte aligned, which results
  85. // on better perf for 64-bit platforms.
  86. length -= 2; a += 2; b += 2;
  87. // unroll the loop
  88. #if BIT64
  89. while (length >= 12)
  90. {
  91. if (*(long*)a != *(long*)b) goto DiffOffset0;
  92. if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4;
  93. if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8;
  94. length -= 12; a += 12; b += 12;
  95. }
  96. #else // BIT64
  97. while (length >= 10)
  98. {
  99. if (*(int*)a != *(int*)b) goto DiffOffset0;
  100. if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2;
  101. if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4;
  102. if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6;
  103. if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8;
  104. length -= 10; a += 10; b += 10;
  105. }
  106. #endif // BIT64
  107. // Fallback loop:
  108. // go back to slower code path and do comparison on 4 bytes at a time.
  109. // This depends on the fact that the String objects are
  110. // always zero terminated and that the terminating zero is not included
  111. // in the length. For odd string sizes, the last compare will include
  112. // the zero terminator.
  113. while (length > 0)
  114. {
  115. if (*(int*)a != *(int*)b) goto DiffNextInt;
  116. length -= 2;
  117. a += 2;
  118. b += 2;
  119. }
  120. // At this point, we have compared all the characters in at least one string.
  121. // The longer string will be larger.
  122. return strA.Length - strB.Length;
  123. #if BIT64
  124. DiffOffset8: a += 4; b += 4;
  125. DiffOffset4: a += 4; b += 4;
  126. #else // BIT64
  127. // Use jumps instead of falling through, since
  128. // otherwise going to DiffOffset8 will involve
  129. // 8 add instructions before getting to DiffNextInt
  130. DiffOffset8: a += 8; b += 8; goto DiffOffset0;
  131. DiffOffset6: a += 6; b += 6; goto DiffOffset0;
  132. DiffOffset4: a += 2; b += 2;
  133. DiffOffset2: a += 2; b += 2;
  134. #endif // BIT64
  135. DiffOffset0:
  136. // If we reached here, we already see a difference in the unrolled loop above
  137. #if BIT64
  138. if (*(int*)a == *(int*)b)
  139. {
  140. a += 2; b += 2;
  141. }
  142. #endif // BIT64
  143. DiffNextInt:
  144. if (*a != *b) return *a - *b;
  145. DiffOffset1:
  146. Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
  147. return *(a + 1) - *(b + 1);
  148. }
  149. }
  150. // Provides a culture-correct string comparison. StrA is compared to StrB
  151. // to determine whether it is lexicographically less, equal, or greater, and then returns
  152. // either a negative integer, 0, or a positive integer; respectively.
  153. //
  154. public static int Compare(string? strA, string? strB)
  155. {
  156. return Compare(strA, strB, StringComparison.CurrentCulture);
  157. }
  158. // Provides a culture-correct string comparison. strA is compared to strB
  159. // to determine whether it is lexicographically less, equal, or greater, and then a
  160. // negative integer, 0, or a positive integer is returned; respectively.
  161. // The case-sensitive option is set by ignoreCase
  162. //
  163. public static int Compare(string? strA, string? strB, bool ignoreCase)
  164. {
  165. var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
  166. return Compare(strA, strB, comparisonType);
  167. }
  168. // Provides a more flexible function for string comparison. See StringComparison
  169. // for meaning of different comparisonType.
  170. public static int Compare(string? strA, string? strB, StringComparison comparisonType)
  171. {
  172. if (object.ReferenceEquals(strA, strB))
  173. {
  174. CheckStringComparison(comparisonType);
  175. return 0;
  176. }
  177. // They can't both be null at this point.
  178. if (strA == null)
  179. {
  180. CheckStringComparison(comparisonType);
  181. return -1;
  182. }
  183. if (strB == null)
  184. {
  185. CheckStringComparison(comparisonType);
  186. return 1;
  187. }
  188. switch (comparisonType)
  189. {
  190. case StringComparison.CurrentCulture:
  191. case StringComparison.CurrentCultureIgnoreCase:
  192. return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType));
  193. case StringComparison.InvariantCulture:
  194. case StringComparison.InvariantCultureIgnoreCase:
  195. return CompareInfo.Invariant.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType));
  196. case StringComparison.Ordinal:
  197. // Most common case: first character is different.
  198. // Returns false for empty strings.
  199. if (strA._firstChar != strB._firstChar)
  200. {
  201. return strA._firstChar - strB._firstChar;
  202. }
  203. return CompareOrdinalHelper(strA, strB);
  204. case StringComparison.OrdinalIgnoreCase:
  205. return CompareInfo.CompareOrdinalIgnoreCase(strA, strB);
  206. default:
  207. throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
  208. }
  209. }
  210. // Provides a culture-correct string comparison. strA is compared to strB
  211. // to determine whether it is lexicographically less, equal, or greater, and then a
  212. // negative integer, 0, or a positive integer is returned; respectively.
  213. //
  214. public static int Compare(string? strA, string? strB, CultureInfo? culture, CompareOptions options)
  215. {
  216. CultureInfo compareCulture = culture ?? CultureInfo.CurrentCulture;
  217. return compareCulture.CompareInfo.Compare(strA, strB, options);
  218. }
  219. // Provides a culture-correct string comparison. strA is compared to strB
  220. // to determine whether it is lexicographically less, equal, or greater, and then a
  221. // negative integer, 0, or a positive integer is returned; respectively.
  222. // The case-sensitive option is set by ignoreCase, and the culture is set
  223. // by culture
  224. //
  225. public static int Compare(string? strA, string? strB, bool ignoreCase, CultureInfo? culture)
  226. {
  227. var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
  228. return Compare(strA, strB, culture, options);
  229. }
  230. // Determines whether two string regions match. The substring of strA beginning
  231. // at indexA of given length is compared with the substring of strB
  232. // beginning at indexB of the same length.
  233. //
  234. public static int Compare(string? strA, int indexA, string? strB, int indexB, int length)
  235. {
  236. // NOTE: It's important we call the boolean overload, and not the StringComparison
  237. // one. The two have some subtly different behavior (see notes in the former).
  238. return Compare(strA, indexA, strB, indexB, length, ignoreCase: false);
  239. }
  240. // Determines whether two string regions match. The substring of strA beginning
  241. // at indexA of given length is compared with the substring of strB
  242. // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean.
  243. //
  244. public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase)
  245. {
  246. // Ideally we would just forward to the string.Compare overload that takes
  247. // a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase.
  248. // That function will return early if an optimization can be applied, e.g. if
  249. // (object)strA == strB && indexA == indexB then it will return 0 straightaway.
  250. // There are a couple of subtle behavior differences that prevent us from doing so
  251. // however:
  252. // - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works
  253. // since that method also returns early for nulls before validation. It shouldn't
  254. // for this overload.
  255. // - Since we originally forwarded to CompareInfo.Compare for all of the argument
  256. // validation logic, the ArgumentOutOfRangeExceptions thrown will contain different
  257. // parameter names.
  258. // Therefore, we have to duplicate some of the logic here.
  259. int lengthA = length;
  260. int lengthB = length;
  261. if (strA != null)
  262. {
  263. lengthA = Math.Min(lengthA, strA.Length - indexA);
  264. }
  265. if (strB != null)
  266. {
  267. lengthB = Math.Min(lengthB, strB.Length - indexB);
  268. }
  269. var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
  270. return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
  271. }
  272. // Determines whether two string regions match. The substring of strA beginning
  273. // at indexA of length length is compared with the substring of strB
  274. // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean,
  275. // and the culture is set by culture.
  276. //
  277. public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase, CultureInfo? culture)
  278. {
  279. var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
  280. return Compare(strA, indexA, strB, indexB, length, culture, options);
  281. }
  282. // Determines whether two string regions match. The substring of strA beginning
  283. // at indexA of length length is compared with the substring of strB
  284. // beginning at indexB of the same length.
  285. //
  286. public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, CultureInfo? culture, CompareOptions options)
  287. {
  288. CultureInfo compareCulture = culture ?? CultureInfo.CurrentCulture;
  289. int lengthA = length;
  290. int lengthB = length;
  291. if (strA != null)
  292. {
  293. lengthA = Math.Min(lengthA, strA.Length - indexA);
  294. }
  295. if (strB != null)
  296. {
  297. lengthB = Math.Min(lengthB, strB.Length - indexB);
  298. }
  299. return compareCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
  300. }
  301. public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, StringComparison comparisonType)
  302. {
  303. CheckStringComparison(comparisonType);
  304. if (strA == null || strB == null)
  305. {
  306. if (object.ReferenceEquals(strA, strB))
  307. {
  308. // They're both null
  309. return 0;
  310. }
  311. return strA == null ? -1 : 1;
  312. }
  313. if (length < 0)
  314. {
  315. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
  316. }
  317. if (indexA < 0 || indexB < 0)
  318. {
  319. string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
  320. throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
  321. }
  322. if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
  323. {
  324. string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
  325. throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
  326. }
  327. if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
  328. {
  329. return 0;
  330. }
  331. int lengthA = Math.Min(length, strA.Length - indexA);
  332. int lengthB = Math.Min(length, strB.Length - indexB);
  333. switch (comparisonType)
  334. {
  335. case StringComparison.CurrentCulture:
  336. case StringComparison.CurrentCultureIgnoreCase:
  337. return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, GetCaseCompareOfComparisonCulture(comparisonType));
  338. case StringComparison.InvariantCulture:
  339. case StringComparison.InvariantCultureIgnoreCase:
  340. return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, GetCaseCompareOfComparisonCulture(comparisonType));
  341. case StringComparison.Ordinal:
  342. return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
  343. default:
  344. Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase); // CheckStringComparison validated these earlier
  345. return CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB);
  346. }
  347. }
  348. // Compares strA and strB using an ordinal (code-point) comparison.
  349. //
  350. public static int CompareOrdinal(string? strA, string? strB)
  351. {
  352. if (object.ReferenceEquals(strA, strB))
  353. {
  354. return 0;
  355. }
  356. // They can't both be null at this point.
  357. if (strA == null)
  358. {
  359. return -1;
  360. }
  361. if (strB == null)
  362. {
  363. return 1;
  364. }
  365. // Most common case, first character is different.
  366. // This will return false for empty strings.
  367. if (strA._firstChar != strB._firstChar)
  368. {
  369. return strA._firstChar - strB._firstChar;
  370. }
  371. return CompareOrdinalHelper(strA, strB);
  372. }
  373. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  374. internal static int CompareOrdinal(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
  375. => SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(strA), strA.Length, ref MemoryMarshal.GetReference(strB), strB.Length);
  376. // Compares strA and strB using an ordinal (code-point) comparison.
  377. //
  378. public static int CompareOrdinal(string? strA, int indexA, string? strB, int indexB, int length)
  379. {
  380. if (strA == null || strB == null)
  381. {
  382. if (object.ReferenceEquals(strA, strB))
  383. {
  384. // They're both null
  385. return 0;
  386. }
  387. return strA == null ? -1 : 1;
  388. }
  389. // COMPAT: Checking for nulls should become before the arguments are validated,
  390. // but other optimizations which allow us to return early should come after.
  391. if (length < 0)
  392. {
  393. throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount);
  394. }
  395. if (indexA < 0 || indexB < 0)
  396. {
  397. string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
  398. throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
  399. }
  400. int lengthA = Math.Min(length, strA.Length - indexA);
  401. int lengthB = Math.Min(length, strB.Length - indexB);
  402. if (lengthA < 0 || lengthB < 0)
  403. {
  404. string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
  405. throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
  406. }
  407. if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
  408. {
  409. return 0;
  410. }
  411. return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
  412. }
  413. // Compares this String to another String (cast as object), returning an integer that
  414. // indicates the relationship. This method returns a value less than 0 if this is less than value, 0
  415. // if this is equal to value, or a value greater than 0 if this is greater than value.
  416. //
  417. public int CompareTo(object? value)
  418. {
  419. if (value == null)
  420. {
  421. return 1;
  422. }
  423. if (!(value is string other))
  424. {
  425. throw new ArgumentException(SR.Arg_MustBeString);
  426. }
  427. return CompareTo(other); // will call the string-based overload
  428. }
  429. // Determines the sorting relation of StrB to the current instance.
  430. //
  431. public int CompareTo(string? strB)
  432. {
  433. return string.Compare(this, strB, StringComparison.CurrentCulture);
  434. }
  435. // Determines whether a specified string is a suffix of the current instance.
  436. //
  437. // The case-sensitive and culture-sensitive option is set by options,
  438. // and the default culture is used.
  439. //
  440. public bool EndsWith(string value)
  441. {
  442. return EndsWith(value, StringComparison.CurrentCulture);
  443. }
  444. public bool EndsWith(string value, StringComparison comparisonType)
  445. {
  446. if ((object)value == null)
  447. {
  448. throw new ArgumentNullException(nameof(value));
  449. }
  450. if ((object)this == (object)value)
  451. {
  452. CheckStringComparison(comparisonType);
  453. return true;
  454. }
  455. if (value.Length == 0)
  456. {
  457. CheckStringComparison(comparisonType);
  458. return true;
  459. }
  460. switch (comparisonType)
  461. {
  462. case StringComparison.CurrentCulture:
  463. case StringComparison.CurrentCultureIgnoreCase:
  464. return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType));
  465. case StringComparison.InvariantCulture:
  466. case StringComparison.InvariantCultureIgnoreCase:
  467. return CompareInfo.Invariant.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType));
  468. case StringComparison.Ordinal:
  469. int offset = this.Length - value.Length;
  470. return (uint)offset <= (uint)this.Length && this.AsSpan(offset).SequenceEqual(value);
  471. case StringComparison.OrdinalIgnoreCase:
  472. return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
  473. default:
  474. throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
  475. }
  476. }
  477. public bool EndsWith(string value, bool ignoreCase, CultureInfo? culture)
  478. {
  479. if (null == value)
  480. {
  481. throw new ArgumentNullException(nameof(value));
  482. }
  483. if ((object)this == (object)value)
  484. {
  485. return true;
  486. }
  487. CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
  488. return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
  489. }
  490. public bool EndsWith(char value)
  491. {
  492. int lastPos = Length - 1;
  493. return ((uint)lastPos < (uint)Length) && this[lastPos] == value;
  494. }
  495. // Determines whether two strings match.
  496. public override bool Equals(object? obj)
  497. {
  498. if (object.ReferenceEquals(this, obj))
  499. return true;
  500. if (!(obj is string str))
  501. return false;
  502. if (this.Length != str.Length)
  503. return false;
  504. return EqualsHelper(this, str);
  505. }
  506. // Determines whether two strings match.
  507. public bool Equals(string? value)
  508. {
  509. if (object.ReferenceEquals(this, value))
  510. return true;
  511. // NOTE: No need to worry about casting to object here.
  512. // If either side of an == comparison between strings
  513. // is null, Roslyn generates a simple ceq instruction
  514. // instead of calling string.op_Equality.
  515. if (value == null)
  516. return false;
  517. if (this.Length != value.Length)
  518. return false;
  519. return EqualsHelper(this, value);
  520. }
  521. public bool Equals(string? value, StringComparison comparisonType)
  522. {
  523. if (object.ReferenceEquals(this, value))
  524. {
  525. CheckStringComparison(comparisonType);
  526. return true;
  527. }
  528. if (value is null)
  529. {
  530. CheckStringComparison(comparisonType);
  531. return false;
  532. }
  533. switch (comparisonType)
  534. {
  535. case StringComparison.CurrentCulture:
  536. case StringComparison.CurrentCultureIgnoreCase:
  537. return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0);
  538. case StringComparison.InvariantCulture:
  539. case StringComparison.InvariantCultureIgnoreCase:
  540. return (CompareInfo.Invariant.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0);
  541. case StringComparison.Ordinal:
  542. if (this.Length != value.Length)
  543. return false;
  544. return EqualsHelper(this, value);
  545. case StringComparison.OrdinalIgnoreCase:
  546. if (this.Length != value.Length)
  547. return false;
  548. return EqualsOrdinalIgnoreCase(this, value);
  549. default:
  550. throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
  551. }
  552. }
  553. // Determines whether two Strings match.
  554. public static bool Equals(string? a, string? b)
  555. {
  556. if (object.ReferenceEquals(a,b))
  557. {
  558. return true;
  559. }
  560. if (a is null || b is null || a.Length != b.Length)
  561. {
  562. return false;
  563. }
  564. return EqualsHelper(a, b);
  565. }
  566. public static bool Equals(string? a, string? b, StringComparison comparisonType)
  567. {
  568. if (object.ReferenceEquals(a, b))
  569. {
  570. CheckStringComparison(comparisonType);
  571. return true;
  572. }
  573. if (a is null || b is null)
  574. {
  575. CheckStringComparison(comparisonType);
  576. return false;
  577. }
  578. switch (comparisonType)
  579. {
  580. case StringComparison.CurrentCulture:
  581. case StringComparison.CurrentCultureIgnoreCase:
  582. return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0);
  583. case StringComparison.InvariantCulture:
  584. case StringComparison.InvariantCultureIgnoreCase:
  585. return (CompareInfo.Invariant.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0);
  586. case StringComparison.Ordinal:
  587. if (a.Length != b.Length)
  588. return false;
  589. return EqualsHelper(a, b);
  590. case StringComparison.OrdinalIgnoreCase:
  591. if (a.Length != b.Length)
  592. return false;
  593. return EqualsOrdinalIgnoreCase(a, b);
  594. default:
  595. throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
  596. }
  597. }
  598. public static bool operator ==(string? a, string? b)
  599. {
  600. return string.Equals(a, b);
  601. }
  602. public static bool operator !=(string? a, string? b)
  603. {
  604. return !string.Equals(a, b);
  605. }
  606. // Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
  607. // they will return the same hash code.
  608. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  609. public override int GetHashCode()
  610. {
  611. ulong seed = Marvin.DefaultSeed;
  612. // Multiplication below will not overflow since going from positive Int32 to UInt32.
  613. return Marvin.ComputeHash32(ref Unsafe.As<char, byte>(ref _firstChar), (uint)_stringLength * 2 /* in bytes, not chars */, (uint)seed, (uint)(seed >> 32));
  614. }
  615. // Gets a hash code for this string and this comparison. If strings A and B and comparison C are such
  616. // that string.Equals(A, B, C), then they will return the same hash code with this comparison C.
  617. public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this);
  618. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  619. internal int GetHashCodeOrdinalIgnoreCase()
  620. {
  621. ulong seed = Marvin.DefaultSeed;
  622. return Marvin.ComputeHash32OrdinalIgnoreCase(ref _firstChar, _stringLength /* in chars, not bytes */, (uint)seed, (uint)(seed >> 32));
  623. }
  624. // A span-based equivalent of String.GetHashCode(). Computes an ordinal hash code.
  625. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  626. public static int GetHashCode(ReadOnlySpan<char> value)
  627. {
  628. ulong seed = Marvin.DefaultSeed;
  629. // Multiplication below will not overflow since going from positive Int32 to UInt32.
  630. return Marvin.ComputeHash32(ref Unsafe.As<char, byte>(ref MemoryMarshal.GetReference(value)), (uint)value.Length * 2 /* in bytes, not chars */, (uint)seed, (uint)(seed >> 32));
  631. }
  632. // A span-based equivalent of String.GetHashCode(StringComparison). Uses the specified comparison type.
  633. public static int GetHashCode(ReadOnlySpan<char> value, StringComparison comparisonType)
  634. {
  635. switch (comparisonType)
  636. {
  637. case StringComparison.CurrentCulture:
  638. case StringComparison.CurrentCultureIgnoreCase:
  639. return CultureInfo.CurrentCulture.CompareInfo.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType));
  640. case StringComparison.InvariantCulture:
  641. case StringComparison.InvariantCultureIgnoreCase:
  642. return CultureInfo.InvariantCulture.CompareInfo.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType));
  643. case StringComparison.Ordinal:
  644. return GetHashCode(value);
  645. case StringComparison.OrdinalIgnoreCase:
  646. return GetHashCodeOrdinalIgnoreCase(value);
  647. default:
  648. ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType);
  649. Debug.Fail("Should not reach this point.");
  650. return default;
  651. }
  652. }
  653. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  654. internal static int GetHashCodeOrdinalIgnoreCase(ReadOnlySpan<char> value)
  655. {
  656. ulong seed = Marvin.DefaultSeed;
  657. return Marvin.ComputeHash32OrdinalIgnoreCase(ref MemoryMarshal.GetReference(value), value.Length /* in chars, not bytes */, (uint)seed, (uint)(seed >> 32));
  658. }
  659. // Use this if and only if 'Denial of Service' attacks are not a concern (i.e. never used for free-form user input),
  660. // or are otherwise mitigated
  661. internal unsafe int GetNonRandomizedHashCode()
  662. {
  663. fixed (char* src = &_firstChar)
  664. {
  665. Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
  666. Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
  667. uint hash1 = (5381 << 16) + 5381;
  668. uint hash2 = hash1;
  669. uint* ptr = (uint*)src;
  670. int length = this.Length;
  671. while (length > 2)
  672. {
  673. length -= 4;
  674. // Where length is 4n-1 (e.g. 3,7,11,15,19) this additionally consumes the null terminator
  675. hash1 = (BitOperations.RotateLeft(hash1, 5) + hash1) ^ ptr[0];
  676. hash2 = (BitOperations.RotateLeft(hash2, 5) + hash2) ^ ptr[1];
  677. ptr += 2;
  678. }
  679. if (length > 0)
  680. {
  681. // Where length is 4n-3 (e.g. 1,5,9,13,17) this additionally consumes the null terminator
  682. hash2 = (BitOperations.RotateLeft(hash2, 5) + hash2) ^ ptr[0];
  683. }
  684. return (int)(hash1 + (hash2 * 1566083941));
  685. }
  686. }
  687. // Determines whether a specified string is a prefix of the current instance
  688. //
  689. public bool StartsWith(string value)
  690. {
  691. if (value is null)
  692. {
  693. throw new ArgumentNullException(nameof(value));
  694. }
  695. return StartsWith(value, StringComparison.CurrentCulture);
  696. }
  697. public bool StartsWith(string value, StringComparison comparisonType)
  698. {
  699. if (value is null)
  700. {
  701. throw new ArgumentNullException(nameof(value));
  702. }
  703. if ((object)this == (object)value)
  704. {
  705. CheckStringComparison(comparisonType);
  706. return true;
  707. }
  708. if (value.Length == 0)
  709. {
  710. CheckStringComparison(comparisonType);
  711. return true;
  712. }
  713. switch (comparisonType)
  714. {
  715. case StringComparison.CurrentCulture:
  716. case StringComparison.CurrentCultureIgnoreCase:
  717. return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType));
  718. case StringComparison.InvariantCulture:
  719. case StringComparison.InvariantCultureIgnoreCase:
  720. return CompareInfo.Invariant.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType));
  721. case StringComparison.Ordinal:
  722. if (this.Length < value.Length || _firstChar != value._firstChar)
  723. {
  724. return false;
  725. }
  726. return (value.Length == 1) ?
  727. true : // First char is the same and thats all there is to compare
  728. SpanHelpers.SequenceEqual(
  729. ref Unsafe.As<char, byte>(ref this.GetRawStringData()),
  730. ref Unsafe.As<char, byte>(ref value.GetRawStringData()),
  731. ((nuint)value.Length) * 2);
  732. case StringComparison.OrdinalIgnoreCase:
  733. if (this.Length < value.Length)
  734. {
  735. return false;
  736. }
  737. return CompareInfo.EqualsOrdinalIgnoreCase(ref this.GetRawStringData(), ref value.GetRawStringData(), value.Length);
  738. default:
  739. throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
  740. }
  741. }
  742. public bool StartsWith(string value, bool ignoreCase, CultureInfo? culture)
  743. {
  744. if (null == value)
  745. {
  746. throw new ArgumentNullException(nameof(value));
  747. }
  748. if ((object)this == (object)value)
  749. {
  750. return true;
  751. }
  752. CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
  753. return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
  754. }
  755. public bool StartsWith(char value) => Length != 0 && _firstChar == value;
  756. internal static void CheckStringComparison(StringComparison comparisonType)
  757. {
  758. // Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
  759. if ((uint)comparisonType > (uint)StringComparison.OrdinalIgnoreCase)
  760. {
  761. ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType);
  762. }
  763. }
  764. internal static CompareOptions GetCaseCompareOfComparisonCulture(StringComparison comparisonType)
  765. {
  766. Debug.Assert((uint)comparisonType <= (uint)StringComparison.OrdinalIgnoreCase);
  767. // Culture enums can be & with CompareOptions.IgnoreCase 0x01 to extract if IgnoreCase or CompareOptions.None 0x00
  768. //
  769. // CompareOptions.None 0x00
  770. // CompareOptions.IgnoreCase 0x01
  771. //
  772. // StringComparison.CurrentCulture: 0x00
  773. // StringComparison.InvariantCulture: 0x02
  774. // StringComparison.Ordinal 0x04
  775. //
  776. // StringComparison.CurrentCultureIgnoreCase: 0x01
  777. // StringComparison.InvariantCultureIgnoreCase: 0x03
  778. // StringComparison.OrdinalIgnoreCase 0x05
  779. return (CompareOptions)((int)comparisonType & (int)CompareOptions.IgnoreCase);
  780. }
  781. }
  782. }