The Labs \ Source Viewer \ SSCLI \ System.Globalization \ StringInfo

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

Developer Fusion