MemoryExtensions.Fast.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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.Runtime.CompilerServices;
  7. using System.Runtime.InteropServices;
  8. using Internal.Runtime.CompilerServices;
  9. namespace System
  10. {
  11. /// <summary>
  12. /// Extension methods for Span{T}, Memory{T}, and friends.
  13. /// </summary>
  14. public static partial class MemoryExtensions
  15. {
  16. /// <summary>
  17. /// Returns a value indicating whether the specified <paramref name="value"/> occurs within the <paramref name="span"/>.
  18. /// <param name="span">The source span.</param>
  19. /// <param name="value">The value to seek within the source span.</param>
  20. /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
  21. /// </summary>
  22. public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
  23. {
  24. return (IndexOf(span, value, comparisonType) >= 0);
  25. }
  26. /// <summary>
  27. /// Determines whether this <paramref name="span"/> and the specified <paramref name="other"/> span have the same characters
  28. /// when compared using the specified <paramref name="comparisonType"/> option.
  29. /// <param name="span">The source span.</param>
  30. /// <param name="other">The value to compare with the source span.</param>
  31. /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="other"/> are compared.</param>
  32. /// </summary>
  33. public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
  34. {
  35. string.CheckStringComparison(comparisonType);
  36. switch (comparisonType)
  37. {
  38. case StringComparison.CurrentCulture:
  39. return (CultureInfo.CurrentCulture.CompareInfo.CompareOptionNone(span, other) == 0);
  40. case StringComparison.CurrentCultureIgnoreCase:
  41. return (CultureInfo.CurrentCulture.CompareInfo.CompareOptionIgnoreCase(span, other) == 0);
  42. case StringComparison.InvariantCulture:
  43. return (CompareInfo.Invariant.CompareOptionNone(span, other) == 0);
  44. case StringComparison.InvariantCultureIgnoreCase:
  45. return (CompareInfo.Invariant.CompareOptionIgnoreCase(span, other) == 0);
  46. case StringComparison.Ordinal:
  47. return EqualsOrdinal(span, other);
  48. case StringComparison.OrdinalIgnoreCase:
  49. return EqualsOrdinalIgnoreCase(span, other);
  50. }
  51. Debug.Fail("StringComparison outside range");
  52. return false;
  53. }
  54. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  55. internal static bool EqualsOrdinal(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
  56. {
  57. if (span.Length != value.Length)
  58. return false;
  59. if (value.Length == 0) // span.Length == value.Length == 0
  60. return true;
  61. return span.SequenceEqual(value);
  62. }
  63. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  64. internal static bool EqualsOrdinalIgnoreCase(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
  65. {
  66. if (span.Length != value.Length)
  67. return false;
  68. if (value.Length == 0) // span.Length == value.Length == 0
  69. return true;
  70. return CompareInfo.EqualsOrdinalIgnoreCase(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), span.Length);
  71. }
  72. /// <summary>
  73. /// Compares the specified <paramref name="span"/> and <paramref name="other"/> using the specified <paramref name="comparisonType"/>,
  74. /// and returns an integer that indicates their relative position in the sort order.
  75. /// <param name="span">The source span.</param>
  76. /// <param name="other">The value to compare with the source span.</param>
  77. /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="other"/> are compared.</param>
  78. /// </summary>
  79. public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
  80. {
  81. string.CheckStringComparison(comparisonType);
  82. switch (comparisonType)
  83. {
  84. case StringComparison.CurrentCulture:
  85. return CultureInfo.CurrentCulture.CompareInfo.CompareOptionNone(span, other);
  86. case StringComparison.CurrentCultureIgnoreCase:
  87. return CultureInfo.CurrentCulture.CompareInfo.CompareOptionIgnoreCase(span, other);
  88. case StringComparison.InvariantCulture:
  89. return CompareInfo.Invariant.CompareOptionNone(span, other);
  90. case StringComparison.InvariantCultureIgnoreCase:
  91. return CompareInfo.Invariant.CompareOptionIgnoreCase(span, other);
  92. case StringComparison.Ordinal:
  93. if (span.Length == 0 || other.Length == 0)
  94. return span.Length - other.Length;
  95. return string.CompareOrdinal(span, other);
  96. case StringComparison.OrdinalIgnoreCase:
  97. return CompareInfo.CompareOrdinalIgnoreCase(span, other);
  98. }
  99. Debug.Fail("StringComparison outside range");
  100. return 0;
  101. }
  102. /// <summary>
  103. /// Reports the zero-based index of the first occurrence of the specified <paramref name="value"/> in the current <paramref name="span"/>.
  104. /// <param name="span">The source span.</param>
  105. /// <param name="value">The value to seek within the source span.</param>
  106. /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
  107. /// </summary>
  108. public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
  109. {
  110. string.CheckStringComparison(comparisonType);
  111. if (value.Length == 0)
  112. {
  113. return 0;
  114. }
  115. if (span.Length == 0)
  116. {
  117. return -1;
  118. }
  119. if (comparisonType == StringComparison.Ordinal)
  120. {
  121. return SpanHelpers.IndexOf(
  122. ref MemoryMarshal.GetReference(span),
  123. span.Length,
  124. ref MemoryMarshal.GetReference(value),
  125. value.Length);
  126. }
  127. if (GlobalizationMode.Invariant)
  128. {
  129. return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None);
  130. }
  131. switch (comparisonType)
  132. {
  133. case StringComparison.CurrentCulture:
  134. case StringComparison.CurrentCultureIgnoreCase:
  135. return CultureInfo.CurrentCulture.CompareInfo.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
  136. case StringComparison.InvariantCulture:
  137. case StringComparison.InvariantCultureIgnoreCase:
  138. return CompareInfo.Invariant.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
  139. default:
  140. Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase);
  141. return CompareInfo.Invariant.IndexOfOrdinalIgnoreCase(span, value);
  142. }
  143. }
  144. /// <summary>
  145. /// Reports the zero-based index of the last occurrence of the specified <paramref name="value"/> in the current <paramref name="span"/>.
  146. /// <param name="span">The source span.</param>
  147. /// <param name="value">The value to seek within the source span.</param>
  148. /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
  149. /// </summary>
  150. public static int LastIndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
  151. {
  152. string.CheckStringComparison(comparisonType);
  153. if (value.Length == 0)
  154. {
  155. return span.Length > 0 ? span.Length - 1 : 0;
  156. }
  157. if (span.Length == 0)
  158. {
  159. return -1;
  160. }
  161. if (GlobalizationMode.Invariant)
  162. {
  163. return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None, fromBeginning: false);
  164. }
  165. switch (comparisonType)
  166. {
  167. case StringComparison.CurrentCulture:
  168. case StringComparison.CurrentCultureIgnoreCase:
  169. return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
  170. case StringComparison.InvariantCulture:
  171. case StringComparison.InvariantCultureIgnoreCase:
  172. return CompareInfo.Invariant.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
  173. default:
  174. Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase);
  175. return CompareInfo.Invariant.LastIndexOfOrdinal(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None);
  176. }
  177. }
  178. /// <summary>
  179. /// Copies the characters from the source span into the destination, converting each character to lowercase,
  180. /// using the casing rules of the specified culture.
  181. /// </summary>
  182. /// <param name="source">The source span.</param>
  183. /// <param name="destination">The destination span which contains the transformed characters.</param>
  184. /// <param name="culture">An object that supplies culture-specific casing rules.</param>
  185. /// <remarks>If the source and destinations overlap, this method behaves as if the original values are in
  186. /// a temporary location before the destination is overwritten.</remarks>
  187. /// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
  188. /// <exception cref="System.ArgumentNullException">
  189. /// Thrown when <paramref name="culture"/> is null.
  190. /// </exception>
  191. public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
  192. {
  193. if (culture == null)
  194. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture);
  195. // Assuming that changing case does not affect length
  196. if (destination.Length < source.Length)
  197. return -1;
  198. if (GlobalizationMode.Invariant)
  199. TextInfo.ToLowerAsciiInvariant(source, destination);
  200. else
  201. culture.TextInfo.ChangeCaseToLower(source, destination);
  202. return source.Length;
  203. }
  204. /// <summary>
  205. /// Copies the characters from the source span into the destination, converting each character to lowercase,
  206. /// using the casing rules of the invariant culture.
  207. /// </summary>
  208. /// <param name="source">The source span.</param>
  209. /// <param name="destination">The destination span which contains the transformed characters.</param>
  210. /// <remarks>If the source and destinations overlap, this method behaves as if the original values are in
  211. /// a temporary location before the destination is overwritten.</remarks>
  212. /// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
  213. public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination)
  214. {
  215. // Assuming that changing case does not affect length
  216. if (destination.Length < source.Length)
  217. return -1;
  218. if (GlobalizationMode.Invariant)
  219. TextInfo.ToLowerAsciiInvariant(source, destination);
  220. else
  221. CultureInfo.InvariantCulture.TextInfo.ChangeCaseToLower(source, destination);
  222. return source.Length;
  223. }
  224. /// <summary>
  225. /// Copies the characters from the source span into the destination, converting each character to uppercase,
  226. /// using the casing rules of the specified culture.
  227. /// </summary>
  228. /// <param name="source">The source span.</param>
  229. /// <param name="destination">The destination span which contains the transformed characters.</param>
  230. /// <param name="culture">An object that supplies culture-specific casing rules.</param>
  231. /// <remarks>If the source and destinations overlap, this method behaves as if the original values are in
  232. /// a temporary location before the destination is overwritten.</remarks>
  233. /// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
  234. /// <exception cref="System.ArgumentNullException">
  235. /// Thrown when <paramref name="culture"/> is null.
  236. /// </exception>
  237. public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture)
  238. {
  239. if (culture == null)
  240. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture);
  241. // Assuming that changing case does not affect length
  242. if (destination.Length < source.Length)
  243. return -1;
  244. if (GlobalizationMode.Invariant)
  245. TextInfo.ToUpperAsciiInvariant(source, destination);
  246. else
  247. culture.TextInfo.ChangeCaseToUpper(source, destination);
  248. return source.Length;
  249. }
  250. /// <summary>
  251. /// Copies the characters from the source span into the destination, converting each character to uppercase
  252. /// using the casing rules of the invariant culture.
  253. /// </summary>
  254. /// <param name="source">The source span.</param>
  255. /// <param name="destination">The destination span which contains the transformed characters.</param>
  256. /// <remarks>If the source and destinations overlap, this method behaves as if the original values are in
  257. /// a temporary location before the destination is overwritten.</remarks>
  258. /// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
  259. public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination)
  260. {
  261. // Assuming that changing case does not affect length
  262. if (destination.Length < source.Length)
  263. return -1;
  264. if (GlobalizationMode.Invariant)
  265. TextInfo.ToUpperAsciiInvariant(source, destination);
  266. else
  267. CultureInfo.InvariantCulture.TextInfo.ChangeCaseToUpper(source, destination);
  268. return source.Length;
  269. }
  270. /// <summary>
  271. /// Determines whether the end of the <paramref name="span"/> matches the specified <paramref name="value"/> when compared using the specified <paramref name="comparisonType"/> option.
  272. /// </summary>
  273. /// <param name="span">The source span.</param>
  274. /// <param name="value">The sequence to compare to the end of the source span.</param>
  275. /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
  276. public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
  277. {
  278. string.CheckStringComparison(comparisonType);
  279. if (value.Length == 0)
  280. {
  281. return true;
  282. }
  283. if (comparisonType >= StringComparison.Ordinal || GlobalizationMode.Invariant)
  284. {
  285. if (string.GetCaseCompareOfComparisonCulture(comparisonType) == CompareOptions.None)
  286. return span.EndsWith(value);
  287. return (span.Length >= value.Length) ? (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value) == 0) : false;
  288. }
  289. if (span.Length == 0)
  290. {
  291. return false;
  292. }
  293. return (comparisonType >= StringComparison.InvariantCulture) ?
  294. CompareInfo.Invariant.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)) :
  295. CultureInfo.CurrentCulture.CompareInfo.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
  296. }
  297. /// <summary>
  298. /// Determines whether the beginning of the <paramref name="span"/> matches the specified <paramref name="value"/> when compared using the specified <paramref name="comparisonType"/> option.
  299. /// </summary>
  300. /// <param name="span">The source span.</param>
  301. /// <param name="value">The sequence to compare to the beginning of the source span.</param>
  302. /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
  303. public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
  304. {
  305. string.CheckStringComparison(comparisonType);
  306. if (value.Length == 0)
  307. {
  308. return true;
  309. }
  310. if (comparisonType >= StringComparison.Ordinal || GlobalizationMode.Invariant)
  311. {
  312. if (string.GetCaseCompareOfComparisonCulture(comparisonType) == CompareOptions.None)
  313. return span.StartsWith(value);
  314. return (span.Length >= value.Length) ? (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(0, value.Length), value) == 0) : false;
  315. }
  316. if (span.Length == 0)
  317. {
  318. return false;
  319. }
  320. return (comparisonType >= StringComparison.InvariantCulture) ?
  321. CompareInfo.Invariant.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)) :
  322. CultureInfo.CurrentCulture.CompareInfo.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
  323. }
  324. /// <summary>
  325. /// Creates a new span over the portion of the target array.
  326. /// </summary>
  327. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  328. public static Span<T> AsSpan<T>(this T[] array, int start)
  329. {
  330. if (array == null)
  331. {
  332. if (start != 0)
  333. ThrowHelper.ThrowArgumentOutOfRangeException();
  334. return default;
  335. }
  336. if (default(T) == null && array.GetType() != typeof(T[]))
  337. ThrowHelper.ThrowArrayTypeMismatchException();
  338. if ((uint)start > (uint)array.Length)
  339. ThrowHelper.ThrowArgumentOutOfRangeException();
  340. return new Span<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start), array.Length - start);
  341. }
  342. /// <summary>
  343. /// Creates a new span over the portion of the target array.
  344. /// </summary>
  345. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  346. public static Span<T> AsSpan<T>(this T[] array, Index startIndex)
  347. {
  348. if (array == null)
  349. {
  350. if (!startIndex.Equals(Index.Start))
  351. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  352. return default;
  353. }
  354. if (default(T) == null && array.GetType() != typeof(T[]))
  355. ThrowHelper.ThrowArrayTypeMismatchException();
  356. int actualIndex = startIndex.GetOffset(array.Length);
  357. if ((uint)actualIndex > (uint)array.Length)
  358. ThrowHelper.ThrowArgumentOutOfRangeException();
  359. return new Span<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), actualIndex), array.Length - actualIndex);
  360. }
  361. /// <summary>
  362. /// Creates a new span over the portion of the target array.
  363. /// </summary>
  364. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  365. public static Span<T> AsSpan<T>(this T[] array, Range range)
  366. {
  367. if (array == null)
  368. {
  369. Index startIndex = range.Start;
  370. Index endIndex = range.End;
  371. if (!startIndex.Equals(Index.Start) || !endIndex.Equals(Index.Start))
  372. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  373. return default;
  374. }
  375. if (default(T) == null && array.GetType() != typeof(T[]))
  376. ThrowHelper.ThrowArrayTypeMismatchException();
  377. (int start, int length) = range.GetOffsetAndLength(array.Length);
  378. return new Span<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start), length);
  379. }
  380. /// <summary>
  381. /// Creates a new readonly span over the portion of the target string.
  382. /// </summary>
  383. /// <param name="text">The target string.</param>
  384. /// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
  385. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  386. public static ReadOnlySpan<char> AsSpan(this string text)
  387. {
  388. if (text == null)
  389. return default;
  390. return new ReadOnlySpan<char>(ref text.GetRawStringData(), text.Length);
  391. }
  392. /// <summary>
  393. /// Creates a new readonly span over the portion of the target string.
  394. /// </summary>
  395. /// <param name="text">The target string.</param>
  396. /// <param name="start">The index at which to begin this slice.</param>
  397. /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
  398. /// <exception cref="System.ArgumentOutOfRangeException">
  399. /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;text.Length).
  400. /// </exception>
  401. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  402. public static ReadOnlySpan<char> AsSpan(this string text, int start)
  403. {
  404. if (text == null)
  405. {
  406. if (start != 0)
  407. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  408. return default;
  409. }
  410. if ((uint)start > (uint)text.Length)
  411. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  412. return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), text.Length - start);
  413. }
  414. /// <summary>
  415. /// Creates a new readonly span over the portion of the target string.
  416. /// </summary>
  417. /// <param name="text">The target string.</param>
  418. /// <param name="start">The index at which to begin this slice.</param>
  419. /// <param name="length">The desired length for the slice (exclusive).</param>
  420. /// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
  421. /// <exception cref="System.ArgumentOutOfRangeException">
  422. /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range.
  423. /// </exception>
  424. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  425. public static ReadOnlySpan<char> AsSpan(this string text, int start, int length)
  426. {
  427. if (text == null)
  428. {
  429. if (start != 0 || length != 0)
  430. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  431. return default;
  432. }
  433. #if BIT64
  434. // See comment in Span<T>.Slice for how this works.
  435. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)text.Length)
  436. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  437. #else
  438. if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
  439. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  440. #endif
  441. return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), length);
  442. }
  443. /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
  444. /// <param name="text">The target string.</param>
  445. /// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
  446. public static ReadOnlyMemory<char> AsMemory(this string text)
  447. {
  448. if (text == null)
  449. return default;
  450. return new ReadOnlyMemory<char>(text, 0, text.Length);
  451. }
  452. /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
  453. /// <param name="text">The target string.</param>
  454. /// <param name="start">The index at which to begin this slice.</param>
  455. /// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
  456. /// <exception cref="System.ArgumentOutOfRangeException">
  457. /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;text.Length).
  458. /// </exception>
  459. public static ReadOnlyMemory<char> AsMemory(this string text, int start)
  460. {
  461. if (text == null)
  462. {
  463. if (start != 0)
  464. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  465. return default;
  466. }
  467. if ((uint)start > (uint)text.Length)
  468. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  469. return new ReadOnlyMemory<char>(text, start, text.Length - start);
  470. }
  471. /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
  472. /// <param name="text">The target string.</param>
  473. /// <param name="startIndex">The index at which to begin this slice.</param>
  474. public static ReadOnlyMemory<char> AsMemory(this string text, Index startIndex)
  475. {
  476. if (text == null)
  477. {
  478. if (!startIndex.Equals(Index.Start))
  479. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
  480. return default;
  481. }
  482. int actualIndex = startIndex.GetOffset(text.Length);
  483. if ((uint)actualIndex > (uint)text.Length)
  484. ThrowHelper.ThrowArgumentOutOfRangeException();
  485. return new ReadOnlyMemory<char>(text, actualIndex, text.Length - actualIndex);
  486. }
  487. /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
  488. /// <param name="text">The target string.</param>
  489. /// <param name="start">The index at which to begin this slice.</param>
  490. /// <param name="length">The desired length for the slice (exclusive).</param>
  491. /// <remarks>Returns default when <paramref name="text"/> is null.</remarks>
  492. /// <exception cref="System.ArgumentOutOfRangeException">
  493. /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range.
  494. /// </exception>
  495. public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length)
  496. {
  497. if (text == null)
  498. {
  499. if (start != 0 || length != 0)
  500. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  501. return default;
  502. }
  503. #if BIT64
  504. // See comment in Span<T>.Slice for how this works.
  505. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)text.Length)
  506. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  507. #else
  508. if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
  509. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
  510. #endif
  511. return new ReadOnlyMemory<char>(text, start, length);
  512. }
  513. /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary>
  514. /// <param name="text">The target string.</param>
  515. /// <param name="range">The range used to indicate the start and length of the sliced string.</param>
  516. public static ReadOnlyMemory<char> AsMemory(this string text, Range range)
  517. {
  518. if (text == null)
  519. {
  520. Index startIndex = range.Start;
  521. Index endIndex = range.End;
  522. if (!startIndex.Equals(Index.Start) || !endIndex.Equals(Index.Start))
  523. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
  524. return default;
  525. }
  526. (int start, int length) = range.GetOffsetAndLength(text.Length);
  527. return new ReadOnlyMemory<char>(text, start, length);
  528. }
  529. }
  530. }