summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Globalization/TextInfo.cs
blob: 9b84486f4ea4188a884549ff8660ede2f38edf2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

////////////////////////////////////////////////////////////////////////////
//
//
//  Purpose:  This Class defines behaviors specific to a writing system.
//            A writing system is the collection of scripts and
//            orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////

using System.Security;

namespace System.Globalization {
    using System;
    using System.Text;
    using System.Threading;
    using System.Runtime;
    using System.Runtime.InteropServices;
    using System.Runtime.CompilerServices;
    using System.Runtime.Serialization;
    using System.Runtime.Versioning;
    using System.Security.Permissions;
    using System.Diagnostics.Contracts;


    [Serializable]
    [System.Runtime.InteropServices.ComVisible(true)]
    public partial class TextInfo : ICloneable, IDeserializationCallback
    {
        //--------------------------------------------------------------------//
        //                        Internal Information                        //
        //--------------------------------------------------------------------//

        private enum Tristate : byte
        {
            NotInitialized,
            True,
            False,
        }

        //
        //  Variables.
        //

        [OptionalField(VersionAdded = 2)]
        private String m_listSeparator;

        [OptionalField(VersionAdded = 2)]
        private bool m_isReadOnly = false;

        //
        // In Whidbey we had several names:
        //      m_win32LangID is the name of the culture, but only used for (de)serialization.
        //      customCultureName is the name of the creating custom culture (if custom)  In combination with m_win32LangID
        //              this is authoratative, ie when deserializing.
        //      m_cultureTableRecord was the data record of the creating culture.  (could have different name if custom)
        //      m_textInfoID is the LCID of the textinfo itself (no longer used)
        //      m_name is the culture name (from cultureinfo.name)
        //
        // In Silverlight/Arrowhead this is slightly different:
        //      m_cultureName is the name of the creating culture.  Note that we consider this authoratative,
        //              if the culture's textinfo changes when deserializing, then behavior may change.
        //              (ala Whidbey behavior).  This is the only string Arrowhead needs to serialize.
        //      m_cultureData is the data that backs this class.
        //      m_textInfoName  is the actual name of the textInfo (from cultureData.STEXTINFO)
        //              m_textInfoName can be the same as m_cultureName on Silverlight since the OS knows
        //              how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't
        //              know how to resolve custom locle names to sort ids so we have to have alredy resolved this.
        //      

        [OptionalField(VersionAdded = 3)]
        private String                          m_cultureName;      // Name of the culture that created this text info
        [NonSerialized]private CultureData      m_cultureData;      // Data record for the culture that made us, not for this textinfo
        [NonSerialized]private String           m_textInfoName;     // Name of the text info we're using (ie: m_cultureData.STEXTINFO)
        [NonSerialized]private IntPtr           m_dataHandle;       // Sort handle
        [NonSerialized]private IntPtr           m_handleOrigin;
        [NonSerialized]private Tristate         m_IsAsciiCasingSameAsInvariant = Tristate.NotInitialized;


        // Invariant text info
        internal static TextInfo Invariant  
        {
            get 
            {
                if (s_Invariant == null)
                    s_Invariant = new TextInfo(CultureData.Invariant);
                return s_Invariant;
            }
        }
        internal volatile static TextInfo s_Invariant;

        ////////////////////////////////////////////////////////////////////////
        //
        //  TextInfo Constructors
        //
        //  Implements CultureInfo.TextInfo.
        //
        ////////////////////////////////////////////////////////////////////////
        internal TextInfo(CultureData cultureData) 
        {
            // This is our primary data source, we don't need most of the rest of this
            this.m_cultureData = cultureData;
            this.m_cultureName = this.m_cultureData.CultureName;
            this.m_textInfoName = this.m_cultureData.STEXTINFO;
#if !FEATURE_CORECLR
            IntPtr handleOrigin;
            this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
            this.m_handleOrigin = handleOrigin;
#endif
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  Serialization / Deserialization
        //
        //  Note that we have to respect the Whidbey behavior for serialization compatibility
        //
        ////////////////////////////////////////////////////////////////////////

#region Serialization 
        // the following fields are defined to keep the compatibility with Whidbey.
        // don't change/remove the names/types of these fields.
        [OptionalField(VersionAdded = 2)]
        private string customCultureName;

        // the following fields are defined to keep compatibility with Everett.
        // don't change/remove the names/types of these fields.
        [OptionalField(VersionAdded = 1)]
        internal int    m_nDataItem;
        [OptionalField(VersionAdded = 1)]
        internal bool   m_useUserOverride;
        [OptionalField(VersionAdded = 1)]
        internal int    m_win32LangID;


        [OnDeserializing] 
        private void OnDeserializing(StreamingContext ctx) 
        { 
            // Clear these so we can check if we've fixed them yet            
            this.m_cultureData = null;
            this.m_cultureName = null;            
        }   

        private void OnDeserialized()
        {
            // this method will be called twice because of the support of IDeserializationCallback
            if (this.m_cultureData == null)
            {
                if (this.m_cultureName == null)
                {
                    // This is whidbey data, get it from customCultureName/win32langid               
                    if (this.customCultureName != null)
                    {
                        // They gave a custom cultuer name, so use that
                        this.m_cultureName = this.customCultureName; 
                    }
#if FEATURE_USE_LCID
                    else
                    {
                        if (m_win32LangID == 0)
                        {
                            // m_cultureName and m_win32LangID are nulls which means we got uninitialized textinfo serialization stream. 
                            // To be compatible with v2/3/3.5 we need to return ar-SA TextInfo in this case.
                            m_cultureName = "ar-SA";
                        }
                        else
                        {
                            // No custom culture, use the name from the LCID
                            m_cultureName = CultureInfo.GetCultureInfo(m_win32LangID).m_cultureData.CultureName;
                        }
                    }
#endif
                }
                
                // Get the text info name belonging to that culture
                this.m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData;
                this.m_textInfoName = this.m_cultureData.STEXTINFO;
#if !FEATURE_CORECLR
                IntPtr handleOrigin;
                this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
                this.m_handleOrigin = handleOrigin;
#endif
            }            
        }

        
        [OnDeserialized]
        private void OnDeserialized(StreamingContext ctx)
        {
            OnDeserialized();
        }   
        
        [OnSerializing]
        private void OnSerializing(StreamingContext ctx) 
        { 
#if !FEATURE_CORECLR
            // Initialize the fields Whidbey expects:
            // Whidbey expected this, so set it, but the value doesn't matter much
            this.m_useUserOverride = false;
#endif // FEATURE_CORECLR

            // Relabel our name since Whidbey expects it to be called customCultureName
            this.customCultureName = this.m_cultureName;

#if FEATURE_USE_LCID
            // Ignore the m_win32LangId because whidbey'll just get it by name if we make it the LOCALE_CUSTOM_UNSPECIFIED.
            this.m_win32LangID     = (CultureInfo.GetCultureInfo(m_cultureName)).LCID;
#endif
        }   
        
#endregion Serialization

        //
        // Internal ordinal comparison functions
        //
        internal static int GetHashCodeOrdinalIgnoreCase(String s)
        {
            return GetHashCodeOrdinalIgnoreCase(s, false, 0);
        }

        internal static int GetHashCodeOrdinalIgnoreCase(String s, bool forceRandomizedHashing, long additionalEntropy)
        {
            // This is the same as an case insensitive hash for Invariant
            // (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules)
            return (Invariant.GetCaseInsensitiveHashCode(s, forceRandomizedHashing, additionalEntropy));
        }

        [System.Security.SecuritySafeCritical]
        internal static unsafe bool TryFastFindStringOrdinalIgnoreCase(int searchFlags, String source, int startIndex, String value, int count, ref int foundIndex)
        {
            return InternalTryFindStringOrdinalIgnoreCase(searchFlags, source, count, startIndex, value, value.Length, ref foundIndex);
        }

        // This function doesn't check arguments. Please do check in the caller.
        // The underlying unmanaged code will assert the sanity of arguments.
        [System.Security.SecuritySafeCritical]  // auto-generated
        internal static unsafe int CompareOrdinalIgnoreCase(String str1, String str2)
        {
            // Compare the whole string and ignore case.
            return InternalCompareStringOrdinalIgnoreCase(str1, 0, str2, 0, str1.Length, str2.Length);
        }

        // This function doesn't check arguments. Please do check in the caller.
        // The underlying unmanaged code will assert the sanity of arguments.
        [System.Security.SecuritySafeCritical]  // auto-generated
        internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB )
        {
            Contract.Assert(strA.Length >= indexA + lengthA,  "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
            Contract.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx]  Caller should've validated strB.Length >= indexB + lengthB");
            return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB);
        }

        internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
        {
            Contract.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
            Contract.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
            Contract.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");

            // We return 0 if both inputs are empty strings
            if (source.Length == 0 && value.Length == 0)
            {
                return 0;
            }

            // fast path
            int ret = -1;
            if (TryFastFindStringOrdinalIgnoreCase(Microsoft.Win32.Win32Native.FIND_FROMSTART, source, startIndex, value, count, ref ret))
                return ret;

            // the search space within [source] starts at offset [startIndex] inclusive and includes
            // [count] characters (thus the last included character is at index [startIndex + count -1]
            // [end] is the index of the next character after the search space
            // (it points past the end of the search space)
            int end = startIndex + count;
            
            // maxStartIndex is the index beyond which we never *start* searching, inclusive; in other words;
            // a search could include characters beyond maxStartIndex, but we'd never begin a search at an 
            // index strictly greater than maxStartIndex. 
            int maxStartIndex = end - value.Length;

            for (; startIndex <= maxStartIndex; startIndex++)
            {
                // We should always have the same or more characters left to search than our actual pattern
                Contract.Assert(end - startIndex >= value.Length);
                // since this is an ordinal comparison, we can assume that the lengths must match
                if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
                {
                    return startIndex;
                }
            }
            
            // Not found
            return -1;
        }

        internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
        {
            Contract.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
            Contract.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
            Contract.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
            Contract.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");

            // If value is Empty, the return value is startIndex
            if (value.Length == 0)
            {
                return startIndex;
            }

            // fast path
            int ret = -1;
            if (TryFastFindStringOrdinalIgnoreCase(Microsoft.Win32.Win32Native.FIND_FROMEND, source, startIndex, value, count, ref ret))
                return ret;

            // the search space within [source] ends at offset [startIndex] inclusive
            // and includes [count] characters 
            // minIndex is the first included character and is at index [startIndex - count + 1]
            int minIndex = startIndex - count + 1;
        
            // First place we can find it is start index - (value.length -1)
            if (value.Length > 0)
            {
                startIndex -= (value.Length - 1);
            }

            for (; startIndex >= minIndex; startIndex--)
            {
                if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
                {
                    return startIndex;
                }
            }
        
            // Not found
            return -1;
        }


        ////////////////////////////////////////////////////////////////////////
        //
        //  CodePage
        //
        //  Returns the number of the code page used by this writing system.
        //  The type parameter can be any of the following values:
        //      ANSICodePage
        //      OEMCodePage
        //      MACCodePage
        //
        ////////////////////////////////////////////////////////////////////////


        public virtual int ANSICodePage 
        {
            get 
            {
                return (this.m_cultureData.IDEFAULTANSICODEPAGE);
            }
        }

 
        public virtual int OEMCodePage 
        {
            get 
            {
                return (this.m_cultureData.IDEFAULTOEMCODEPAGE);
            }
        }


        public virtual int MacCodePage 
        {
            get 
            {
                return (this.m_cultureData.IDEFAULTMACCODEPAGE);
            }
        }


        public virtual int EBCDICCodePage 
        {
            get 
            {
                return (this.m_cultureData.IDEFAULTEBCDICCODEPAGE);
            }
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  LCID
        //
        //  We need a way to get an LCID from outside of the BCL. This prop is the way.
        //  NOTE: neutral cultures will cause GPS incorrect LCIDS from this
        //
        ////////////////////////////////////////////////////////////////////////

#if FEATURE_USE_LCID
        [System.Runtime.InteropServices.ComVisible(false)]
        public int LCID 
        {
            get 
            {
                // Just use the LCID from our text info name
                return CultureInfo.GetCultureInfo(this.m_textInfoName).LCID;
            }
        }
#endif
        ////////////////////////////////////////////////////////////////////////
        //
        //  CultureName
        //
        //  The name of the culture associated with the current TextInfo.
        //
        ////////////////////////////////////////////////////////////////////////
        [System.Runtime.InteropServices.ComVisible(false)]
        public string CultureName 
        {
            get 
            {
                return(this.m_textInfoName);
            }
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  IsReadOnly
        //
        //  Detect if the object is readonly.
        //
        ////////////////////////////////////////////////////////////////////////
        [System.Runtime.InteropServices.ComVisible(false)]
        public bool IsReadOnly 
        {
            get { return (m_isReadOnly); }
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  Clone
        //
        //  Is the implementation of ICloneable.
        //
        ////////////////////////////////////////////////////////////////////////
        [System.Runtime.InteropServices.ComVisible(false)]
        public virtual Object Clone()
        {
            object o = MemberwiseClone();
            ((TextInfo) o).SetReadOnlyState(false);
            return (o);
        }
        
        ////////////////////////////////////////////////////////////////////////
        //
        //  ReadOnly
        //
        //  Create a cloned readonly instance or return the input one if it is 
        //  readonly.
        //
        ////////////////////////////////////////////////////////////////////////
        [System.Runtime.InteropServices.ComVisible(false)]
        public static TextInfo ReadOnly(TextInfo textInfo) 
        {
            if (textInfo == null)       { throw new ArgumentNullException("textInfo"); }
            Contract.EndContractBlock();
            if (textInfo.IsReadOnly)    { return (textInfo); }
            
            TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
            clonedTextInfo.SetReadOnlyState(true);
            
            return (clonedTextInfo);
        }

        private void VerifyWritable()
        {
            if (m_isReadOnly) 
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
            }
            Contract.EndContractBlock();
        }

        internal void SetReadOnlyState(bool readOnly)
        {
            m_isReadOnly = readOnly;
        }


        ////////////////////////////////////////////////////////////////////////
        //
        //  ListSeparator
        //
        //  Returns the string used to separate items in a list.
        //
        ////////////////////////////////////////////////////////////////////////


        public virtual String ListSeparator 
        {
            [System.Security.SecuritySafeCritical]  // auto-generated
            get 
            {
                if (m_listSeparator == null) {
                    m_listSeparator = this.m_cultureData.SLIST;
                }
                return (m_listSeparator);
            }

            [System.Runtime.InteropServices.ComVisible(false)]
            set 
            {
                if (value == null) 
                {
                    throw new ArgumentNullException("value", Environment.GetResourceString("ArgumentNull_String"));
                }
                Contract.EndContractBlock();
                VerifyWritable();
                m_listSeparator = value;
            }
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  ToLower
        //
        //  Converts the character or string to lower case.  Certain locales
        //  have different casing semantics from the file systems in Win32.
        //
        ////////////////////////////////////////////////////////////////////////

        [System.Security.SecuritySafeCritical]  // auto-generated
        public unsafe virtual char ToLower(char c) 
        {
            if(IsAscii(c) && IsAsciiCasingSameAsInvariant)
            {
                return ToLowerAsciiInvariant(c);
            }
            return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, false));
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        public unsafe virtual String ToLower(String str) 
        {
            if (str == null) { throw new ArgumentNullException("str"); }
            Contract.EndContractBlock();

            return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, false);

        }

        static private Char ToLowerAsciiInvariant(Char c)
        {
            if ('A' <= c && c <= 'Z')
            {
                c = (Char)(c | 0x20);
            }
            return c;
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  ToUpper
        //
        //  Converts the character or string to upper case.  Certain locales
        //  have different casing semantics from the file systems in Win32.
        //
        ////////////////////////////////////////////////////////////////////////

        [System.Security.SecuritySafeCritical]  // auto-generated
        public unsafe virtual char ToUpper(char c) 
        {
            if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
            {
                return ToUpperAsciiInvariant(c);
            }
            return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, true));
        }


        [System.Security.SecuritySafeCritical]  // auto-generated
        public unsafe virtual String ToUpper(String str) 
        {
            if (str == null) { throw new ArgumentNullException("str"); }
            Contract.EndContractBlock();
            return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, true);
        }

        static private Char ToUpperAsciiInvariant(Char c)
        {
            if ('a' <= c && c <= 'z')
            {
                c = (Char)(c & ~0x20);
            }
            return c;
        }

        static private bool IsAscii(Char c)
        {
            return c < 0x80;
        }

        private bool IsAsciiCasingSameAsInvariant
        {
            get
            {
                if (m_IsAsciiCasingSameAsInvariant == Tristate.NotInitialized)
                {
                    m_IsAsciiCasingSameAsInvariant =
                        CultureInfo.GetCultureInfo(m_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
                                                                             "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                                                                             CompareOptions.IgnoreCase) == 0 ? Tristate.True : Tristate.False;
                }
                return m_IsAsciiCasingSameAsInvariant == Tristate.True;
            }
        }

        ////////////////////////////////////////////////////////////////////////
        //
        //  Equals
        //
        //  Implements Object.Equals().  Returns a boolean indicating whether
        //  or not object refers to the same CultureInfo as the current instance.
        //
        ////////////////////////////////////////////////////////////////////////


        public override bool Equals(Object obj)
        {
            TextInfo that = obj as TextInfo;
            
            if (that != null)
            {
                return this.CultureName.Equals(that.CultureName);
            }
            
            return (false);
        }


        ////////////////////////////////////////////////////////////////////////
        //
        //  GetHashCode
        //
        //  Implements Object.GetHashCode().  Returns the hash code for the
        //  CultureInfo.  The hash code is guaranteed to be the same for CultureInfo A
        //  and B where A.Equals(B) is true.
        //
        ////////////////////////////////////////////////////////////////////////


        public override int GetHashCode()
        {
            return (this.CultureName.GetHashCode());
        }


        ////////////////////////////////////////////////////////////////////////
        //
        //  ToString
        //
        //  Implements Object.ToString().  Returns a string describing the
        //  TextInfo.
        //
        ////////////////////////////////////////////////////////////////////////


        public override String ToString()
        {
            return ("TextInfo - " + this.m_cultureData.CultureName);
        }


        //
        // Titlecasing:
        // -----------
        // Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter
        // and the rest of the letters are lowercase.  The choice of which words to titlecase in headings
        // and titles is dependent on language and local conventions.  For example, "The Merry Wives of Windor"
        // is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased.
        // In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von"
        // are not titlecased.  In French even fewer words are titlecased: "Les joyeuses commeres de Windsor."
        //
        // Moreover, the determination of what actually constitutes a word is language dependent, and this can
        // influence which letter or letters of a "word" are uppercased when titlecasing strings.  For example
        // "l'arbre" is considered two words in French, whereas "can't" is considered one word in English.
        //
        //
        // Differences between UNICODE 5.0 and the .NET Framework:
        // -------------------------------------------------------------------------------------
        // The .NET Framework previously shipped a naive titlecasing implementation.  Every word is titlecased
        // regardless of language or orthographic practice.  Furthermore, apostrophe is always considered to be
        // a word joiner as used in English.  The longterm vision is to depend on the operating system for
        // titlecasing.  Windows 7 is expected to be the first release with this feature.  On the Macintosh side,
        // titlecasing is not available as of version 10.5 of the operating system.
        //
        public unsafe String ToTitleCase(String str) 
        {
            if (str == null)  
            {
                throw new ArgumentNullException("str");
            }
            Contract.EndContractBlock();
            if (str.Length == 0) 
            {
                return (str);
            }

            StringBuilder result = new StringBuilder();
            String lowercaseData = null;

            for (int i = 0; i < str.Length; i++) 
            {
                UnicodeCategory charType;
                int charLen;

                charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
                if (Char.CheckLetter(charType)) 
                {
                    // Do the titlecasing for the first character of the word.
                    i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
                     
                    //
                    // Convert the characters until the end of the this word
                    // to lowercase.
                    //
                    int lowercaseStart = i;

                    //
                    // Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc)
                    // This is in line with Word 2000 behavior of titlecasing.
                    //
                    bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter);
                    // Use a loop to find all of the other letters following this letter.
                    while (i < str.Length) 
                    {
                        charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
                        if (IsLetterCategory(charType)) 
                        {
                            if (charType == UnicodeCategory.LowercaseLetter) 
                            {
                                hasLowerCase = true;
                            }
                            i += charLen;
                        } 
                        else if (str[i] == '\'') 
                        {
                            i++;
                            if (hasLowerCase) 
                            {
                                if (lowercaseData == null) 
                                {
                                    lowercaseData = this.ToLower(str);
                                }
                                result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
                            } 
                            else 
                            {
                                result.Append(str, lowercaseStart, i - lowercaseStart);
                            }
                            lowercaseStart = i;
                            hasLowerCase = true;
                        } 
                        else if (!IsWordSeparator(charType)) 
                        {
                            // This category is considered to be part of the word.
                            // This is any category that is marked as false in wordSeprator array.
                            i+= charLen;
                        } 
                        else 
                        {
                            // A word separator. Break out of the loop.
                            break;
                        }
                    }

                    int count = i - lowercaseStart;

                    if (count>0) 
                    {
                        if (hasLowerCase) 
                        {
                            if (lowercaseData == null) 
                            {
                                lowercaseData = this.ToLower(str);
                            }
                            result.Append(lowercaseData, lowercaseStart, count);
                        } 
                        else 
                        {
                            result.Append(str, lowercaseStart, count);
                        }
                    }

                    if (i < str.Length) 
                    {
                        // not a letter, just append it
                        i = AddNonLetter(ref result, ref str, i, charLen);
                    }
                }
                else 
                {
                    // not a letter, just append it
                    i = AddNonLetter(ref result, ref str, i, charLen);
                }
            }
            return (result.ToString());
        }

        private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) 
        {
            Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
            if (charLen == 2) 
            {
                // Surrogate pair
                result.Append(input[inputIndex++]);
                result.Append(input[inputIndex]);
            }
            else 
            {
                result.Append(input[inputIndex]);
            }                   
            return inputIndex;
        }


        private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) 
        {
            Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");

            // for surrogate pairs do a simple ToUpper operation on the substring
            if (charLen == 2) 
            {
                // Surrogate pair
                result.Append( this.ToUpper(input.Substring(inputIndex, charLen)) );
                inputIndex++;
            }
            else 
            {
                switch (input[inputIndex]) 
                {
                    //
                    // For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below.
                    case (char)0x01C4:  // DZ with Caron -> Dz with Caron
                    case (char)0x01C5:  // Dz with Caron -> Dz with Caron
                    case (char)0x01C6:  // dz with Caron -> Dz with Caron
                        result.Append( (char)0x01C5 );
                        break;
                    case (char)0x01C7:  // LJ -> Lj
                    case (char)0x01C8:  // Lj -> Lj
                    case (char)0x01C9:  // lj -> Lj
                        result.Append( (char)0x01C8 );
                        break;
                    case (char)0x01CA:  // NJ -> Nj
                    case (char)0x01CB:  // Nj -> Nj
                    case (char)0x01CC:  // nj -> Nj
                        result.Append( (char)0x01CB );
                        break;
                    case (char)0x01F1:  // DZ -> Dz
                    case (char)0x01F2:  // Dz -> Dz
                    case (char)0x01F3:  // dz -> Dz
                        result.Append( (char)0x01F2 );
                        break;
                    default:
                        result.Append( this.ToUpper(input[inputIndex]) );
                        break;
                }
            }                   
            return inputIndex;
        }


        //
        // Used in ToTitleCase():
        // When we find a starting letter, the following array decides if a category should be
        // considered as word seprator or not.
        //
        private const int wordSeparatorMask = 
            /* false */ (0 <<  0) | // UppercaseLetter = 0,
            /* false */ (0 <<  1) | // LowercaseLetter = 1,
            /* false */ (0 <<  2) | // TitlecaseLetter = 2,
            /* false */ (0 <<  3) | // ModifierLetter = 3,
            /* false */ (0 <<  4) | // OtherLetter = 4,
            /* false */ (0 <<  5) | // NonSpacingMark = 5,
            /* false */ (0 <<  6) | // SpacingCombiningMark = 6,
            /* false */ (0 <<  7) | // EnclosingMark = 7,
            /* false */ (0 <<  8) | // DecimalDigitNumber = 8,
            /* false */ (0 <<  9) | // LetterNumber = 9,
            /* false */ (0 << 10) | // OtherNumber = 10,
            /* true  */ (1 << 11) | // SpaceSeparator = 11,
            /* true  */ (1 << 12) | // LineSeparator = 12,
            /* true  */ (1 << 13) | // ParagraphSeparator = 13,
            /* true  */ (1 << 14) | // Control = 14,
            /* true  */ (1 << 15) | // Format = 15,
            /* false */ (0 << 16) | // Surrogate = 16,
            /* false */ (0 << 17) | // PrivateUse = 17,
            /* true  */ (1 << 18) | // ConnectorPunctuation = 18,
            /* true  */ (1 << 19) | // DashPunctuation = 19,
            /* true  */ (1 << 20) | // OpenPunctuation = 20,
            /* true  */ (1 << 21) | // ClosePunctuation = 21,
            /* true  */ (1 << 22) | // InitialQuotePunctuation = 22,
            /* true  */ (1 << 23) | // FinalQuotePunctuation = 23,
            /* true  */ (1 << 24) | // OtherPunctuation = 24,
            /* true  */ (1 << 25) | // MathSymbol = 25,
            /* true  */ (1 << 26) | // CurrencySymbol = 26,
            /* true  */ (1 << 27) | // ModifierSymbol = 27,
            /* true  */ (1 << 28) | // OtherSymbol = 28,
            /* false */ (0 << 29);  // OtherNotAssigned = 29;

        private static bool IsWordSeparator(UnicodeCategory category) 
        {
            return (wordSeparatorMask & (1 << (int)category)) != 0;
        }

        private static bool IsLetterCategory(UnicodeCategory uc) 
        {
            return (uc == UnicodeCategory.UppercaseLetter
                 || uc == UnicodeCategory.LowercaseLetter
                 || uc == UnicodeCategory.TitlecaseLetter
                 || uc == UnicodeCategory.ModifierLetter
                 || uc == UnicodeCategory.OtherLetter);
        }

        // IsRightToLeft
        //
        // Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
        //
        [System.Runtime.InteropServices.ComVisible(false)]
        public bool IsRightToLeft
        {
            get
            {
                return this.m_cultureData.IsRightToLeft;
            }
        }

        /// <internalonly/>
        void IDeserializationCallback.OnDeserialization(Object sender)
        {
            OnDeserialized();
        }

        //
        // Get case-insensitive hash code for the specified string.
        //
        // NOTENOTE: this is an internal function.  The caller should verify the string
        // is not null before calling this.  Currenlty, CaseInsensitiveHashCodeProvider
        // does that.
        //
        [System.Security.SecuritySafeCritical]  // auto-generated
        internal unsafe int GetCaseInsensitiveHashCode(String str)
        {
            return GetCaseInsensitiveHashCode(str, false, 0);
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        internal unsafe int GetCaseInsensitiveHashCode(String str, bool forceRandomizedHashing, long additionalEntropy)
        {
            // Validate inputs
            if (str==null) 
            {
                 throw new ArgumentNullException("str");
            }
            Contract.EndContractBlock();

            // Return our result
            return (InternalGetCaseInsHash(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, forceRandomizedHashing, additionalEntropy));
        }

        // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseChar
        [System.Security.SecurityCritical]  // auto-generated
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static unsafe extern char InternalChangeCaseChar(IntPtr handle, IntPtr handleOrigin, String localeName, char ch, bool isToUpper);
        
        // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseString
        [System.Security.SecurityCritical]  // auto-generated
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static unsafe extern String InternalChangeCaseString(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool isToUpper);

        // Get case insensitive hash -- ComNlsInfo::InternalGetCaseInsHash
        [System.Security.SecurityCritical]  // auto-generated
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static unsafe extern int InternalGetCaseInsHash(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool forceRandomizedHashing, long additionalEntropy);

        // Call ::CompareStringOrdinal -- ComNlsInfo::InternalCompareStringOrdinalIgnoreCase
        // Start at indexes and compare for length characters (or remainder of string if length == -1)
        [System.Security.SecurityCritical]  // auto-generated
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private static unsafe extern int InternalCompareStringOrdinalIgnoreCase(String string1, int index1, String string2, int index2, int length1, int length2);

        // ComNlsInfo::InternalTryFindStringOrdinalIgnoreCase attempts a faster IndexOf/LastIndexOf OrdinalIgnoreCase using a kernel function.
        // Returns true if FindStringOrdinal was handled, with foundIndex set to the target's index into the source
        // Returns false when FindStringOrdinal wasn't handled
        [System.Security.SecurityCritical]  // auto-generated
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static unsafe extern bool InternalTryFindStringOrdinalIgnoreCase(int searchFlags, String source, int sourceCount, int startIndex, String target, int targetCount, ref int foundIndex);
    }

}