StringInfo.cs 13 KB

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