StringInfo.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. ////////////////////////////////////////////////////////////////////////////
  5. //
  6. //
  7. // Purpose: This class defines behaviors specific to a writing system.
  8. // A writing system is the collection of scripts and
  9. // orthographic rules required to represent a language as text.
  10. //
  11. //
  12. ////////////////////////////////////////////////////////////////////////////
  13. using System;
  14. using System.Diagnostics;
  15. namespace System.Globalization
  16. {
  17. public class StringInfo
  18. {
  19. private string _str;
  20. private int[] _indexes;
  21. // Legacy constructor
  22. public StringInfo() : this("") { }
  23. // Primary, useful constructor
  24. public StringInfo(string value)
  25. {
  26. this.String = value;
  27. }
  28. public override bool Equals(object value)
  29. {
  30. if (value is StringInfo that)
  31. {
  32. return (_str.Equals(that._str));
  33. }
  34. return (false);
  35. }
  36. public override int GetHashCode()
  37. {
  38. return _str.GetHashCode();
  39. }
  40. // Our zero-based array of index values into the string. Initialize if
  41. // our private array is not yet, in fact, initialized.
  42. private int[] Indexes
  43. {
  44. get
  45. {
  46. if ((null == _indexes) && (0 < this.String.Length))
  47. {
  48. _indexes = StringInfo.ParseCombiningCharacters(this.String);
  49. }
  50. return (_indexes);
  51. }
  52. }
  53. public string String
  54. {
  55. get
  56. {
  57. return (_str);
  58. }
  59. set
  60. {
  61. if (null == value)
  62. {
  63. throw new ArgumentNullException(nameof(String),
  64. SR.ArgumentNull_String);
  65. }
  66. _str = value;
  67. _indexes = null;
  68. }
  69. }
  70. public int LengthInTextElements
  71. {
  72. get
  73. {
  74. if (null == this.Indexes)
  75. {
  76. // Indexes not initialized, so assume length zero
  77. return (0);
  78. }
  79. return (this.Indexes.Length);
  80. }
  81. }
  82. public string SubstringByTextElements(int startingTextElement)
  83. {
  84. // If the string is empty, no sense going further.
  85. if (null == this.Indexes)
  86. {
  87. // Just decide which error to give depending on the param they gave us....
  88. if (startingTextElement < 0)
  89. {
  90. throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
  91. }
  92. else
  93. {
  94. throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
  95. }
  96. }
  97. return (SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement));
  98. }
  99. public string SubstringByTextElements(int startingTextElement, int lengthInTextElements)
  100. {
  101. if (startingTextElement < 0)
  102. {
  103. throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
  104. }
  105. if (this.String.Length == 0 || startingTextElement >= Indexes.Length)
  106. {
  107. throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
  108. }
  109. if (lengthInTextElements < 0)
  110. {
  111. throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.ArgumentOutOfRange_NeedPosNum);
  112. }
  113. if (startingTextElement > Indexes.Length - lengthInTextElements)
  114. {
  115. throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.Arg_ArgumentOutOfRangeException);
  116. }
  117. int start = Indexes[startingTextElement];
  118. if (startingTextElement + lengthInTextElements == Indexes.Length)
  119. {
  120. // We are at the last text element in the string and because of that
  121. // must handle the call differently.
  122. return (this.String.Substring(start));
  123. }
  124. else
  125. {
  126. return (this.String.Substring(start, (Indexes[lengthInTextElements + startingTextElement] - start)));
  127. }
  128. }
  129. public static string GetNextTextElement(string str)
  130. {
  131. return (GetNextTextElement(str, 0));
  132. }
  133. ////////////////////////////////////////////////////////////////////////
  134. //
  135. // Get the code point count of the current text element.
  136. //
  137. // A combining class is defined as:
  138. // A character/surrogate that has the following Unicode category:
  139. // * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
  140. // * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
  141. // * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
  142. //
  143. // In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
  144. //
  145. // 1. If a character/surrogate is in the following category, it is a text element.
  146. // It can NOT further combine with characters in the combinging class to form a text element.
  147. // * one of the Unicode category in the combinging class
  148. // * UnicodeCategory.Format
  149. // * UnicodeCateogry.Control
  150. // * UnicodeCategory.OtherNotAssigned
  151. // 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
  152. //
  153. // Return:
  154. // The length of the current text element
  155. //
  156. // Parameters:
  157. // String str
  158. // index The starting index
  159. // len The total length of str (to define the upper boundary)
  160. // ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
  161. // currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
  162. //
  163. ////////////////////////////////////////////////////////////////////////
  164. internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
  165. {
  166. Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
  167. Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
  168. if (index + currentCharCount == len)
  169. {
  170. // This is the last character/surrogate in the string.
  171. return (currentCharCount);
  172. }
  173. // Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
  174. int nextCharCount;
  175. UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
  176. if (CharUnicodeInfo.IsCombiningCategory(ucNext))
  177. {
  178. // The next element is a combining class.
  179. // Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
  180. // not a format character, and not a control character).
  181. if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
  182. || (ucCurrent == UnicodeCategory.Format)
  183. || (ucCurrent == UnicodeCategory.Control)
  184. || (ucCurrent == UnicodeCategory.OtherNotAssigned)
  185. || (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
  186. {
  187. // Will fall thru and return the currentCharCount
  188. }
  189. else
  190. {
  191. int startIndex = index; // Remember the current index.
  192. // We have a valid base characters, and we have a character (or surrogate) that is combining.
  193. // Check if there are more combining characters to follow.
  194. // Check if the next character is a nonspacing character.
  195. index += currentCharCount + nextCharCount;
  196. while (index < len)
  197. {
  198. ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
  199. if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
  200. {
  201. ucCurrent = ucNext;
  202. currentCharCount = nextCharCount;
  203. break;
  204. }
  205. index += nextCharCount;
  206. }
  207. return (index - startIndex);
  208. }
  209. }
  210. // The return value will be the currentCharCount.
  211. int ret = currentCharCount;
  212. ucCurrent = ucNext;
  213. // Update currentCharCount.
  214. currentCharCount = nextCharCount;
  215. return (ret);
  216. }
  217. // Returns the str containing the next text element in str starting at
  218. // index index. If index is not supplied, then it will start at the beginning
  219. // of str. It recognizes a base character plus one or more combining
  220. // characters or a properly formed surrogate pair as a text element. See also
  221. // the ParseCombiningCharacters() and the ParseSurrogates() methods.
  222. public static string GetNextTextElement(string str, int index)
  223. {
  224. //
  225. // Validate parameters.
  226. //
  227. if (str == null)
  228. {
  229. throw new ArgumentNullException(nameof(str));
  230. }
  231. int len = str.Length;
  232. if (index < 0 || index >= len)
  233. {
  234. if (index == len)
  235. {
  236. return (string.Empty);
  237. }
  238. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  239. }
  240. int charLen;
  241. UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
  242. return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
  243. }
  244. public static TextElementEnumerator GetTextElementEnumerator(string str)
  245. {
  246. return (GetTextElementEnumerator(str, 0));
  247. }
  248. public static TextElementEnumerator GetTextElementEnumerator(string str, int index)
  249. {
  250. //
  251. // Validate parameters.
  252. //
  253. if (str == null)
  254. {
  255. throw new ArgumentNullException(nameof(str));
  256. }
  257. int len = str.Length;
  258. if (index < 0 || (index > len))
  259. {
  260. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
  261. }
  262. return (new TextElementEnumerator(str, index, len));
  263. }
  264. /*
  265. * Returns the indices of each base character or properly formed surrogate pair
  266. * within the str. It recognizes a base character plus one or more combining
  267. * characters or a properly formed surrogate pair as a text element and returns
  268. * the index of the base character or high surrogate. Each index is the
  269. * beginning of a text element within a str. The length of each element is
  270. * easily computed as the difference between successive indices. The length of
  271. * the array will always be less than or equal to the length of the str. For
  272. * example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
  273. * return the indices: 0, 2, 4.
  274. */
  275. public static int[] ParseCombiningCharacters(string str)
  276. {
  277. if (str == null)
  278. {
  279. throw new ArgumentNullException(nameof(str));
  280. }
  281. int len = str.Length;
  282. int[] result = new int[len];
  283. if (len == 0)
  284. {
  285. return (result);
  286. }
  287. int resultCount = 0;
  288. int i = 0;
  289. int currentCharLen;
  290. UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
  291. while (i < len)
  292. {
  293. result[resultCount++] = i;
  294. i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
  295. }
  296. if (resultCount < len)
  297. {
  298. int[] returnArray = new int[resultCount];
  299. Array.Copy(result, 0, returnArray, 0, resultCount);
  300. return (returnArray);
  301. }
  302. return (result);
  303. }
  304. }
  305. }