Merge pull request #3199 from lambdageek/dev/proxy-setter
[mono.git] / mcs / class / corlib / System.Globalization / CultureInfo.cs
1 //
2 // System.Globalization.CultureInfo.cs
3 //
4 // Authors:
5 // Miguel de Icaza (miguel@ximian.com)
6 // Dick Porter (dick@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
8 //
9 // (C) 2001, 2002, 2003 Ximian, Inc. (http://www.ximian.com)
10 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
11 // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System.Collections.Generic;
34 using System.Threading;
35 using System.Runtime.CompilerServices;
36 using System.Runtime.InteropServices;
37 using System.Diagnostics.Contracts;
38
39 namespace System.Globalization
40 {
41         [System.Runtime.InteropServices.ComVisible (true)]
42         [Serializable]
43         [StructLayout (LayoutKind.Sequential)]
44         public class CultureInfo : ICloneable, IFormatProvider
45         {
46                 static volatile CultureInfo invariant_culture_info = new CultureInfo (InvariantCultureId, false, true);
47                 static object shared_table_lock = new object ();
48                 static CultureInfo default_current_culture;
49
50 #pragma warning disable 169, 649
51                 bool m_isReadOnly;
52                 int  cultureID;
53                 [NonSerialized]
54                 int parent_lcid;
55                 [NonSerialized]
56                 int datetime_index;
57                 [NonSerialized]
58                 int number_index;
59                 [NonSerialized]
60                 int default_calendar_type;
61                 bool m_useUserOverride;
62                 internal volatile NumberFormatInfo numInfo;
63                 internal volatile DateTimeFormatInfo dateTimeInfo;
64                 volatile TextInfo textInfo;
65                 internal string m_name;
66                 
67                 [NonSerialized]
68                 private string englishname;
69                 [NonSerialized]
70                 private string nativename;
71                 [NonSerialized]
72                 private string iso3lang;
73                 [NonSerialized]
74                 private string iso2lang;
75                 [NonSerialized]
76                 private string win3lang;
77                 [NonSerialized]
78                 private string territory;
79                 [NonSerialized]
80                 string[] native_calendar_names;
81
82                 volatile CompareInfo compareInfo;
83                 [NonSerialized]
84                 private unsafe readonly void *textinfo_data;
85
86                 [StructLayout (LayoutKind.Sequential)]
87                 struct Data {
88                         public int ansi;
89                         public int ebcdic;
90                         public int mac;
91                         public int oem;
92                         public bool right_to_left;
93                         public byte list_sep;
94                 }
95
96                 int m_dataItem;         // MS.NET serializes this.
97 #pragma warning restore 169, 649
98
99                 Calendar calendar;
100
101                 [NonSerialized]
102                 CultureInfo parent_culture;
103
104                 // Deserialized instances will set this to false
105                 [NonSerialized]
106                 bool constructed;
107
108                 [NonSerialized]
109                 // Used by Thread.set_CurrentCulture
110                 internal byte[] cached_serialized_form;
111
112                 [NonSerialized]internal CultureData m_cultureData;
113                 [NonSerialized]internal bool m_isInherited;
114                 
115                 internal const int InvariantCultureId = 0x7F;
116                 const int CalendarTypeBits = 8;
117
118                 const string MSG_READONLY = "This instance is read only";
119                 
120                 public static CultureInfo InvariantCulture {
121                         get {
122                                 return invariant_culture_info;
123                         }
124                 }
125
126                 public static CultureInfo CurrentCulture {
127                         get {
128                                 return Thread.CurrentThread.CurrentCulture;
129                         }
130 #if NETSTANDARD
131                         set {
132                                 throw new NotImplementedException ();
133                         }
134 #endif
135                 }
136
137                 public static CultureInfo CurrentUICulture { 
138                         get {
139                                 return Thread.CurrentThread.CurrentUICulture;
140                         }
141 #if NETSTANDARD
142                         set {
143                                 throw new NotImplementedException ();
144                         }
145 #endif
146                 }
147
148                 internal static CultureInfo ConstructCurrentCulture ()
149                 {
150                         if (default_current_culture != null)
151                                 return default_current_culture;
152
153                         var locale_name = get_current_locale_name ();
154                         CultureInfo ci = null;
155
156                         if (locale_name != null) {
157                                 try {
158                                         ci = CreateSpecificCulture (locale_name);
159                                 } catch {
160                                 }
161                         }
162
163                         if (ci == null) {
164                                 ci = InvariantCulture;
165                         } else {
166                                 ci.m_isReadOnly = true;
167                                 ci.m_useUserOverride = true;
168                         }
169
170                         default_current_culture = ci;
171                         return ci;
172                 }
173
174                 internal static CultureInfo ConstructCurrentUICulture ()
175                 {
176                         return ConstructCurrentCulture ();
177                 }
178
179                 // it is used for RegionInfo.
180                 internal string Territory {
181                         get { return territory; }
182                 }
183
184 #if !NET_2_1
185                 // FIXME: It is implemented, but would be hell slow.
186                 [ComVisible (false)]
187                 public CultureTypes CultureTypes {
188                         get {
189                                 CultureTypes ret = (CultureTypes) 0;
190                                 foreach (CultureTypes v in Enum.GetValues (typeof (CultureTypes)))
191                                         if (Array.IndexOf (GetCultures (v), this) >= 0)
192                                                 ret |= v;
193                                 return ret;
194                         }
195                 }
196
197                 [ComVisible (false)]
198                 public CultureInfo GetConsoleFallbackUICulture ()
199                 {
200                         // as documented in MSDN ...
201                         switch (Name) {
202                         case "ar": case "ar-BH": case "ar-EG": case "ar-IQ":
203                         case "ar-JO": case "ar-KW": case "ar-LB": case "ar-LY":
204                         case "ar-QA": case "ar-SA": case "ar-SY": case "ar-AE":
205                         case "ar-YE":
206                         case "dv": case "dv-MV":
207                         case "fa": case "fa-IR":
208                         case "gu": case "gu-IN":
209                         case "he": case "he-IL":
210                         case "hi": case "hi-IN":
211                         case "kn": case "kn-IN":
212                         case "kok": case "kok-IN":
213                         case "mr": case "mr-IN":
214                         case "pa": case "pa-IN":
215                         case "sa": case "sa-IN":
216                         case "syr": case "syr-SY":
217                         case "ta": case "ta-IN":
218                         case "te": case "te-IN":
219                         case "th": case "th-TH":
220                         case "ur": case "ur-PK":
221                         case "vi": case "vi-VN":
222                                 return GetCultureInfo ("en");
223                         case "ar-DZ": case "ar-MA": case "ar-TN":
224                                 return GetCultureInfo ("fr");
225                         }
226                         return (CultureTypes & CultureTypes.WindowsOnlyCultures) != 0 ? CultureInfo.InvariantCulture : this;
227                 }
228
229                 [ComVisible (false)]
230                 public string IetfLanguageTag {
231                         // There could be more consistent way to implement
232                         // it, but right now it works just fine with this...
233                         get {
234                                 switch (Name) {
235                                 case "zh-CHS":
236                                         return "zh-Hans";
237                                 case "zh-CHT":
238                                         return "zh-Hant";
239                                 default:
240                                         return Name;
241                                 }
242                         }
243                 }
244
245                 // For specific cultures it basically returns LCID.
246                 // For neutral cultures it is mapped to the default(?) specific
247                 // culture, where the LCID of the specific culture seems to be
248                 // n + 1024 by default. zh-CHS is the only exception which is 
249                 // mapped to 2052, not 1028 (zh-CHT is mapped to 1028 instead).
250                 // There are very few exceptions, here I simply list them here.
251                 // It is Windows-specific property anyways, so no worthy of
252                 // trying to do some complex things with locale-builder.
253                 [ComVisible (false)]
254                 public virtual int KeyboardLayoutId {
255                         get {
256                                 switch (LCID) {
257                                 case 4: // zh-CHS (neutral)
258                                         return 2052;
259                                 case 1034: // es-ES Spanish 2
260                                         return 3082;
261                                 case 31748: // zh-CHT (neutral)
262                                         return 1028;
263                                 case 31770: // sr (neutral)
264                                         return 2074;
265                                 default:
266                                         return LCID < 1024 ? LCID + 1024 : LCID;
267                                 }
268                         }
269                 }
270 #endif
271
272                 public virtual int LCID {
273                         get {
274                                 return cultureID;
275                         }
276                 }
277
278                 public virtual string Name {
279                         get {
280                                 return(m_name);
281                         }
282                 }
283
284                 public virtual string NativeName {
285                         get {
286                                 if (!constructed) Construct ();
287                                 return nativename;
288                         }
289                 }
290
291                 internal string NativeCalendarName {
292                         get {
293                                 if (!constructed) Construct ();
294                                 return native_calendar_names[(default_calendar_type >> CalendarTypeBits) - 1];
295                         }
296                 }
297                 
298                 public virtual Calendar Calendar {
299                         get {
300                                 if (calendar == null) {
301                                         if (!constructed) Construct ();
302                                         calendar = CreateCalendar (default_calendar_type);
303                                 }
304
305                                 return calendar;
306                         }
307                 }
308
309                 [MonoLimitation ("Optional calendars are not supported only default calendar is returned")]
310                 public virtual Calendar[] OptionalCalendars {
311                         get {
312                                 return new[] { Calendar };
313                         }
314                 }
315
316                 public virtual CultureInfo Parent
317                 {
318                         get {
319                                 if (parent_culture == null) {
320                                         if (!constructed)
321                                                 Construct ();
322                                         if (parent_lcid == cultureID) {
323                                                 //
324                                                 // Parent lcid is same but culture info is not for legacy zh culture
325                                                 //
326                                                 if (parent_lcid == 0x7C04 && EnglishName [EnglishName.Length - 1] == 'y')
327                                                         return parent_culture = new CultureInfo ("zh-Hant");
328                                                 else if (parent_lcid == 0x0004 && EnglishName [EnglishName.Length -1] == 'y')
329                                                         return parent_culture = new CultureInfo ("zh-Hans");
330                                                 return null;
331                                         }
332                                         
333                                         if (parent_lcid == InvariantCultureId)
334                                                 parent_culture = InvariantCulture;
335                                         else if (cultureID == InvariantCultureId)
336                                                 parent_culture = this;
337                                         else if (cultureID == 0x0404) {
338                                                 // zh-tw has parent id 0x7C04 which is in this case zh-cht and not zh-hant
339                                                 parent_culture = new CultureInfo ("zh-CHT");
340                                         } else
341                                                 parent_culture = new CultureInfo (parent_lcid);
342                                 }
343                                 return parent_culture;
344                         }
345                 }
346
347                 public virtual TextInfo TextInfo
348                 {
349                         get {
350                                 if (textInfo == null) {
351                                         if (!constructed) Construct ();
352                                         lock (this) {
353                                                 if(textInfo == null) {
354                                                         textInfo = CreateTextInfo (m_isReadOnly);
355                                                 }
356                                         }
357                                 }
358                                 
359                                 return(textInfo);
360                         }
361                 }
362
363                 public virtual string ThreeLetterISOLanguageName {
364                         get {
365                                 if (!constructed) Construct ();
366                                 return iso3lang;
367                         }
368                 }
369
370                 public virtual string ThreeLetterWindowsLanguageName
371                 {
372                         get {
373                                 if (!constructed) Construct ();
374                                 return(win3lang);
375                         }
376                 }
377
378                 public virtual string TwoLetterISOLanguageName {
379                         get {
380                                 if (!constructed) Construct ();
381                                 return(iso2lang);
382                         }
383                 }
384
385                 public bool UseUserOverride
386                 {
387                         get {
388                                 return m_useUserOverride;
389                         }
390                 }
391
392                 public void ClearCachedData()
393                 {
394                         lock (shared_table_lock) {
395                                 shared_by_number = null;
396                                 shared_by_name = null;
397                         }
398
399                         //
400                         // ClearCachedData method does not refresh the information in
401                         // the Thread.CurrentCulture property for existing threads
402                         //
403                         default_current_culture = null;
404
405                         RegionInfo.ClearCachedData ();
406                         TimeZone.ClearCachedData ();
407                         TimeZoneInfo.ClearCachedData ();
408                 }
409
410                 public virtual object Clone()
411                 {
412                         if (!constructed) Construct ();
413                         CultureInfo ci=(CultureInfo)MemberwiseClone ();
414                         ci.m_isReadOnly=false;
415                         ci.cached_serialized_form=null;
416                         if (!IsNeutralCulture) {
417                                 ci.NumberFormat = (NumberFormatInfo)NumberFormat.Clone ();
418                                 ci.DateTimeFormat = (DateTimeFormatInfo)DateTimeFormat.Clone ();
419                         }
420                         return(ci);
421                 }
422
423                 public override bool Equals (object value)
424                 {
425                         CultureInfo b = value as CultureInfo;
426                         return b != null && b.cultureID == cultureID && b.m_name == m_name;
427                 }
428
429                 public static CultureInfo[] GetCultures(CultureTypes types)
430                 {
431                         bool neutral=((types & CultureTypes.NeutralCultures)!=0);
432                         bool specific=((types & CultureTypes.SpecificCultures)!=0);
433                         bool installed=((types & CultureTypes.InstalledWin32Cultures)!=0);  // TODO
434
435                         CultureInfo [] infos = internal_get_cultures (neutral, specific, installed);
436                         // The runtime returns a NULL in the first position of the array when
437                         // 'neutral' is true. We fill it in with a clone of InvariantCulture
438                         // since it must not be read-only
439                         int i = 0;
440                         if (neutral && infos.Length > 0 && infos [0] == null) {
441                                 infos [i++] = (CultureInfo) InvariantCulture.Clone ();
442                         }
443
444                         for (; i < infos.Length; ++i) {
445                                 var ci = infos [i];
446                                 var ti = ci.GetTextInfoData ();
447                                 infos [i].m_cultureData = CultureData.GetCultureData (ci.m_name, false, ci.datetime_index, ci.CalendarType, ci.number_index, ci.iso2lang,
448                                         ti.ansi, ti.oem, ti.mac, ti.ebcdic, ti.right_to_left, ((char)ti.list_sep).ToString ());
449                         }
450
451                         return infos;
452                 }
453
454                 unsafe Data GetTextInfoData ()
455                 {
456                         return *(Data*) textinfo_data;
457                 }
458
459                 public override int GetHashCode ()
460                 {
461                         return cultureID.GetHashCode ();
462                 }
463
464                 public static CultureInfo ReadOnly(CultureInfo ci)
465                 {
466                         if(ci==null) {
467                                 throw new ArgumentNullException("ci");
468                         }
469
470                         if(ci.m_isReadOnly) {
471                                 return(ci);
472                         } else {
473                                 CultureInfo new_ci=(CultureInfo)ci.Clone ();
474                                 new_ci.m_isReadOnly=true;
475                                 if (new_ci.numInfo != null)
476                                         new_ci.numInfo = NumberFormatInfo.ReadOnly (new_ci.numInfo);
477                                 if (new_ci.dateTimeInfo != null)
478                                         new_ci.dateTimeInfo = DateTimeFormatInfo.ReadOnly (new_ci.dateTimeInfo);
479                                 if (new_ci.textInfo != null)
480                                         new_ci.textInfo = TextInfo.ReadOnly (new_ci.textInfo);
481                                 return(new_ci);
482                         }
483                 }
484
485                 public override string ToString()
486                 {
487                         return(m_name);
488                 }
489                 
490                 public virtual CompareInfo CompareInfo
491                 {
492                         get {
493                                 if(compareInfo==null) {
494                                         if (!constructed)
495                                                 Construct ();
496
497                                         lock (this) {
498                                                 if(compareInfo==null) {
499                                                         compareInfo=new CompareInfo (this);
500                                                 }
501                                         }
502                                 }
503                                 
504                                 return(compareInfo);
505                         }
506                 }
507
508                 public virtual bool IsNeutralCulture {
509                         get {
510                                 if (cultureID == InvariantCultureId)
511                                         return false;
512
513                                 if (!constructed) Construct ();
514                                 return territory == null;
515                         }
516                 }
517
518                 internal void CheckNeutral ()
519                 {
520                 }
521
522                 public virtual NumberFormatInfo NumberFormat {
523                         get {
524                                 if (numInfo == null) {
525                                         NumberFormatInfo temp = new NumberFormatInfo(this.m_cultureData);
526                                         temp.isReadOnly = m_isReadOnly;
527                                         numInfo = temp;
528                                 }
529
530                                 return numInfo;
531                         }
532
533                         set {
534                                 if (!constructed) Construct ();
535                                 if (m_isReadOnly) throw new InvalidOperationException(MSG_READONLY);
536
537                                 if (value == null)
538                                         throw new ArgumentNullException ("NumberFormat");
539                                 
540                                 numInfo = value;
541                         }
542                 }
543
544                 public virtual DateTimeFormatInfo DateTimeFormat {
545                         get {
546                                 if (dateTimeInfo != null)
547                                         return dateTimeInfo;
548
549                                 if (!constructed) Construct ();
550                                 CheckNeutral ();
551
552                                 var temp = new DateTimeFormatInfo (m_cultureData, Calendar);
553                                 temp.m_isReadOnly = m_isReadOnly;
554                                 System.Threading.Thread.MemoryBarrier();
555                                 dateTimeInfo = temp;
556                                 return dateTimeInfo;
557                         }
558
559                         set {
560                                 if (!constructed) Construct ();
561                                 if (m_isReadOnly) throw new InvalidOperationException(MSG_READONLY);
562
563                                 if (value == null)
564                                         throw new ArgumentNullException ("DateTimeFormat");
565                                 
566                                 dateTimeInfo = value;
567                         }
568                 }
569
570                 public virtual string DisplayName {
571                         get {
572                                 // Mono is not localized and will always return english name regardless of OS locale
573                                 return EnglishName;
574                         }
575                 }
576
577                 public virtual string EnglishName {
578                         get {
579                                 if (!constructed) Construct ();
580                                 return englishname;
581                         }
582                 }
583
584                 public static CultureInfo InstalledUICulture {
585                         get {
586                                 return ConstructCurrentCulture ();
587                         }
588                 }
589
590                 public bool IsReadOnly {
591                         get {
592                                 return m_isReadOnly;
593                         }
594                 }
595                 
596
597                 // 
598                 // IFormatProvider implementation
599                 //
600                 public virtual object GetFormat( Type formatType )
601                 {
602                         object format = null;
603
604                         if ( formatType == typeof(NumberFormatInfo) )
605                                 format = NumberFormat;
606                         else if ( formatType == typeof(DateTimeFormatInfo) )
607                                 format = DateTimeFormat;
608                         
609                         return format;
610                 }
611                 
612                 void Construct ()
613                 {
614                         construct_internal_locale_from_lcid (cultureID);
615                         constructed = true;
616                 }
617
618                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
619                 private extern bool construct_internal_locale_from_lcid (int lcid);
620
621                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
622                 private extern bool construct_internal_locale_from_name (string name);
623
624                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
625                 private extern static string get_current_locale_name ();
626
627                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
628                 private extern static CultureInfo [] internal_get_cultures (bool neutral, bool specific, bool installed);
629
630                 private void ConstructInvariant (bool read_only)
631                 {
632                         cultureID = InvariantCultureId;
633
634                         /* NumberFormatInfo defaults to the invariant data */
635                         numInfo=NumberFormatInfo.InvariantInfo;
636
637                         if (!read_only) {
638                                 numInfo = (NumberFormatInfo) numInfo.Clone ();
639                         }
640
641                         textInfo = TextInfo.Invariant;
642
643                         m_name=String.Empty;
644                         englishname=
645                         nativename="Invariant Language (Invariant Country)";
646                         iso3lang="IVL";
647                         iso2lang="iv";
648                         win3lang="IVL";
649                         default_calendar_type = 1 << CalendarTypeBits | (int) GregorianCalendarTypes.Localized;
650                 }
651
652                 private unsafe TextInfo CreateTextInfo (bool readOnly)
653                 {
654                         TextInfo tempTextInfo = new TextInfo (this.m_cultureData);
655                         tempTextInfo.SetReadOnlyState (readOnly);
656                         return tempTextInfo;
657                 }
658
659                 public CultureInfo (int culture) : this (culture, true) {}
660
661                 public CultureInfo (int culture, bool useUserOverride) :
662                         this (culture, useUserOverride, false) {}
663
664                 private CultureInfo (int culture, bool useUserOverride, bool read_only)
665                 {
666                         if (culture < 0)
667                                 throw new ArgumentOutOfRangeException ("culture", "Positive "
668                                         + "number required.");
669
670                         constructed = true;
671                         m_isReadOnly = read_only;
672                         m_useUserOverride = useUserOverride;
673
674                         if (culture == InvariantCultureId) {
675                                 /* Short circuit the invariant culture */
676                                 m_cultureData = CultureData.Invariant;
677                                 ConstructInvariant (read_only);
678                                 return;
679                         }
680
681                         if (!construct_internal_locale_from_lcid (culture)) {
682                                 //
683                                 // Be careful not to cause recursive CultureInfo initialization
684                                 //
685                                 var msg = string.Format (InvariantCulture, "Culture ID {0} (0x{1}) is not a supported culture.", culture.ToString (InvariantCulture), culture.ToString ("X4", InvariantCulture));
686                                 throw new CultureNotFoundException ("culture", msg);
687                         }
688
689                         var ti = GetTextInfoData ();
690                         m_cultureData = CultureData.GetCultureData (m_name, m_useUserOverride, datetime_index, CalendarType, number_index, iso2lang,
691                                 ti.ansi, ti.oem, ti.mac, ti.ebcdic, ti.right_to_left, ((char)ti.list_sep).ToString ());
692                 }
693
694                 public CultureInfo (string name) : this (name, true) {}
695
696                 public CultureInfo (string name, bool useUserOverride) :
697                         this (name, useUserOverride, false) {}
698
699                 private CultureInfo (string name, bool useUserOverride, bool read_only)
700                 {
701                         if (name == null)
702                                 throw new ArgumentNullException ("name");
703
704                         constructed = true;
705                         m_isReadOnly = read_only;
706                         m_useUserOverride = useUserOverride;
707                         m_isInherited = GetType() != typeof(System.Globalization.CultureInfo);
708
709                         if (name.Length == 0) {
710                                 /* Short circuit the invariant culture */
711                                 m_cultureData = CultureData.Invariant;
712                                 ConstructInvariant (read_only);
713                                 return;
714                         }
715
716                         if (!construct_internal_locale_from_name (name.ToLowerInvariant ())) {
717                                 throw CreateNotFoundException (name);
718                         }
719
720                         var ti = GetTextInfoData ();
721                         m_cultureData = CultureData.GetCultureData (m_name, useUserOverride, datetime_index, CalendarType, number_index, iso2lang,
722                                 ti.ansi, ti.oem, ti.mac, ti.ebcdic, ti.right_to_left, ((char)ti.list_sep).ToString ());
723                 }
724
725                 // This is used when creating by specific name and creating by
726                 // current locale so we can initialize the object without
727                 // doing any member initialization
728                 private CultureInfo () { constructed = true; }
729                 static Dictionary<int, CultureInfo> shared_by_number;
730                 static Dictionary<string, CultureInfo> shared_by_name;
731                 
732                 static void insert_into_shared_tables (CultureInfo c)
733                 {
734                         if (shared_by_number == null){
735                                 shared_by_number = new Dictionary<int, CultureInfo> ();
736                                 shared_by_name = new Dictionary<string, CultureInfo> ();
737                         }
738                         shared_by_number [c.cultureID] = c;
739                         shared_by_name [c.m_name] = c;
740                 }
741                 
742                 public static CultureInfo GetCultureInfo (int culture)
743                 {
744                         if (culture < 1)
745                                 throw new ArgumentOutOfRangeException ("culture", "Positive number required.");
746
747                         CultureInfo c;
748                         
749                         lock (shared_table_lock){
750                                 if (shared_by_number != null) {
751                                         if (shared_by_number.TryGetValue (culture, out c))
752                                                 return c;
753                                 }
754
755                                 c = new CultureInfo (culture, false, true);
756                                 insert_into_shared_tables (c);
757                                 return c;
758                         }
759                 }
760
761                 public static CultureInfo GetCultureInfo (string name)
762                 {
763                         if (name == null)
764                                 throw new ArgumentNullException ("name");
765
766                         CultureInfo c;
767                         lock (shared_table_lock){
768                                 if (shared_by_name != null){
769                                         if (shared_by_name.TryGetValue (name, out c))
770                                                 return c;
771                                 }
772                                 c = new CultureInfo (name, false, true);
773                                 insert_into_shared_tables (c);
774                                 return c;
775                         }
776                 }
777
778                 [MonoTODO ("Currently it ignores the altName parameter")]
779                 public static CultureInfo GetCultureInfo (string name, string altName) {
780                         if (name == null)
781                                 throw new ArgumentNullException ("null");
782                         if (altName == null)
783                                 throw new ArgumentNullException ("null");
784
785                         return GetCultureInfo (name);
786                 }
787
788                 public static CultureInfo GetCultureInfoByIetfLanguageTag (string name)
789                 {
790                         // There could be more consistent way to implement
791                         // it, but right now it works just fine with this...
792                         switch (name) {
793                         case "zh-Hans":
794                                 return GetCultureInfo ("zh-CHS");
795                         case "zh-Hant":
796                                 return GetCultureInfo ("zh-CHT");
797                         default:
798                                 return GetCultureInfo (name);
799                         }
800                 }
801
802                 // used in runtime (icall.c) to construct CultureInfo for
803                 // AssemblyName of assemblies
804                 internal static CultureInfo CreateCulture (string name, bool reference)
805                 {
806                         bool read_only;
807                         bool use_user_override;
808
809                         bool invariant = name.Length == 0;
810                         if (reference) {
811                                 use_user_override = invariant ? false : true;
812                                 read_only = false;
813                         } else {
814                                 read_only = false;
815                                 use_user_override = invariant ? false : true;
816                         }
817
818                         return new CultureInfo (name, use_user_override, read_only);
819                 }
820
821                 public static CultureInfo CreateSpecificCulture (string name)
822                 {
823                         if (name == null)
824                                 throw new ArgumentNullException ("name");
825
826                         if (name.Length == 0)
827                                 return InvariantCulture;
828
829                         var src_name = name;
830                         name = name.ToLowerInvariant ();
831                         CultureInfo ci = new CultureInfo ();
832
833                         if (!ci.construct_internal_locale_from_name (name)) {
834                                 int idx = name.Length - 1;
835                                 if (idx > 0) {
836                                         while ((idx = name.LastIndexOf ('-', idx - 1)) > 0) {
837                                                 if (ci.construct_internal_locale_from_name (name.Substring (0, idx)))
838                                                         break;
839                                         }
840                                 }
841
842                                 if (idx <= 0)
843                                         throw CreateNotFoundException (src_name);
844                         }
845
846                         if (ci.IsNeutralCulture)
847                                 ci = CreateSpecificCultureFromNeutral (ci.Name);
848
849                         var ti = ci.GetTextInfoData ();
850
851                         ci.m_cultureData = CultureData.GetCultureData (ci.m_name, false, ci.datetime_index, ci.CalendarType, ci.number_index, ci.iso2lang,
852                                 ti.ansi, ti.oem, ti.mac, ti.ebcdic, ti.right_to_left, ((char)ti.list_sep).ToString ());
853                         return ci;
854                 }
855
856                 //
857                 // Creates specific culture from neutral culture. Used by CreateSpecificCulture
858                 // only but using separate method we can delay switch underlying Dictionary
859                 // initialization
860                 //
861                 static CultureInfo CreateSpecificCultureFromNeutral (string name)
862                 {
863                         int id;
864
865                         //
866                         // For neutral cultures find predefined default specific culture
867                         //
868                         // Use managed switch because we need this for only some cultures
869                         // and the method is not used frequently
870                         //
871                         // TODO: We could optimize for cultures with single specific culture 
872                         //
873                         switch (name.ToLowerInvariant ()) {
874                         case "af": id = 1078; break;
875                         case "am": id = 1118; break;
876                         case "ar": id = 1025; break;
877                         case "arn": id = 1146; break;
878                         case "as": id = 1101; break;
879                         case "az": id = 1068; break;
880                         case "az-cyrl": id = 2092; break;
881                         case "az-latn": id = 1068; break;
882                         case "ba": id = 1133; break;
883                         case "be": id = 1059; break;
884                         case "bg": id = 1026; break;
885                         case "bn": id = 1093; break;
886                         case "bo": id = 1105; break;
887                         case "br": id = 1150; break;
888                         case "bs": id = 5146; break;
889                         case "bs-cyrl": id = 8218; break;
890                         case "bs-latn": id = 5146; break;
891                         case "ca": id = 1027; break;
892                         case "co": id = 1155; break;
893                         case "cs": id = 1029; break;
894                         case "cy": id = 1106; break;
895                         case "da": id = 1030; break;
896                         case "de": id = 1031; break;
897                         case "dsb": id = 2094; break;
898                         case "dv": id = 1125; break;
899                         case "el": id = 1032; break;
900                         case "en": id = 1033; break;
901                         case "es": id = 3082; break;
902                         case "et": id = 1061; break;
903                         case "eu": id = 1069; break;
904                         case "fa": id = 1065; break;
905                         case "fi": id = 1035; break;
906                         case "fil": id = 1124; break;
907                         case "fo": id = 1080; break;
908                         case "fr": id = 1036; break;
909                         case "fy": id = 1122; break;
910                         case "ga": id = 2108; break;
911                         case "gd": id = 1169; break;
912                         case "gl": id = 1110; break;
913                         case "gsw": id = 1156; break;
914                         case "gu": id = 1095; break;
915                         case "ha": id = 1128; break;
916                         case "ha-latn": id = 1128; break;
917                         case "he": id = 1037; break;
918                         case "hi": id = 1081; break;
919                         case "hr": id = 1050; break;
920                         case "hsb": id = 1070; break;
921                         case "hu": id = 1038; break;
922                         case "hy": id = 1067; break;
923                         case "id": id = 1057; break;
924                         case "ig": id = 1136; break;
925                         case "ii": id = 1144; break;
926                         case "is": id = 1039; break;
927                         case "it": id = 1040; break;
928                         case "iu": id = 2141; break;
929                         case "iu-cans": id = 1117; break;
930                         case "iu-latn": id = 2141; break;
931                         case "ja": id = 1041; break;
932                         case "ka": id = 1079; break;
933                         case "kk": id = 1087; break;
934                         case "kl": id = 1135; break;
935                         case "km": id = 1107; break;
936                         case "kn": id = 1099; break;
937                         case "ko": id = 1042; break;
938                         case "kok": id = 1111; break;
939                         case "ky": id = 1088; break;
940                         case "lb": id = 1134; break;
941                         case "lo": id = 1108; break;
942                         case "lt": id = 1063; break;
943                         case "lv": id = 1062; break;
944                         case "mi": id = 1153; break;
945                         case "mk": id = 1071; break;
946                         case "ml": id = 1100; break;
947                         case "mn": id = 1104; break;
948                         case "mn-cyrl": id = 1104; break;
949                         case "mn-mong": id = 2128; break;
950                         case "moh": id = 1148; break;
951                         case "mr": id = 1102; break;
952                         case "ms": id = 1086; break;
953                         case "mt": id = 1082; break;
954                         case "nb": id = 1044; break;
955                         case "ne": id = 1121; break;
956                         case "nl": id = 1043; break;
957                         case "nn": id = 2068; break;
958                         case "no": id = 1044; break;
959                         case "nso": id = 1132; break;
960                         case "oc": id = 1154; break;
961                         case "or": id = 1096; break;
962                         case "pa": id = 1094; break;
963                         case "pl": id = 1045; break;
964                         case "prs": id = 1164; break;
965                         case "ps": id = 1123; break;
966                         case "pt": id = 1046; break;
967                         case "qut": id = 1158; break;
968                         case "quz": id = 1131; break;
969                         case "rm": id = 1047; break;
970                         case "ro": id = 1048; break;
971                         case "ru": id = 1049; break;
972                         case "rw": id = 1159; break;
973                         case "sa": id = 1103; break;
974                         case "sah": id = 1157; break;
975                         case "se": id = 1083; break;
976                         case "si": id = 1115; break;
977                         case "sk": id = 1051; break;
978                         case "sl": id = 1060; break;
979                         case "sma": id = 7227; break;
980                         case "smj": id = 5179; break;
981                         case "smn": id = 9275; break;
982                         case "sms": id = 8251; break;
983                         case "sq": id = 1052; break;
984                         case "sr": id = 9242; break;
985                         case "sr-cyrl": id = 10266; break;
986                         case "sr-latn": id = 9242; break;
987                         case "sv": id = 1053; break;
988                         case "sw": id = 1089; break;
989                         case "syr": id = 1114; break;
990                         case "ta": id = 1097; break;
991                         case "te": id = 1098; break;
992                         case "tg": id = 1064; break;
993                         case "tg-cyrl": id = 1064; break;
994                         case "th": id = 1054; break;
995                         case "tk": id = 1090; break;
996                         case "tn": id = 1074; break;
997                         case "tr": id = 1055; break;
998                         case "tt": id = 1092; break;
999                         case "tzm": id = 2143; break;
1000                         case "tzm-latn": id = 2143; break;
1001                         case "ug": id = 1152; break;
1002                         case "uk": id = 1058; break;
1003                         case "ur": id = 1056; break;
1004                         case "uz": id = 1091; break;
1005                         case "uz-cyrl": id = 2115; break;
1006                         case "uz-latn": id = 1091; break;
1007                         case "vi": id = 1066; break;
1008                         case "wo": id = 1160; break;
1009                         case "xh": id = 1076; break;
1010                         case "yo": id = 1130; break;
1011                         case "zh": id = 2052; break;
1012                         case "zh-chs":
1013                         case "zh-hans":
1014                                 id = 2052; break;
1015                         case "zh-cht":
1016                         case "zh-hant":
1017                                 id = 3076; break;
1018                         case "zu": id = 1077; break;
1019                         default:
1020                                 throw new NotImplementedException ("Mapping for neutral culture " + name);
1021                         }
1022
1023                         return new CultureInfo (id);
1024                 }
1025
1026                 internal int CalendarType {
1027                         get {
1028                                 switch (default_calendar_type >> CalendarTypeBits) {
1029                                 case 1:
1030                                         return Calendar.CAL_GREGORIAN;
1031                                 case 2:
1032                                         return Calendar.CAL_THAI;
1033                                 case 3:
1034                                         return Calendar.CAL_UMALQURA;
1035                                 case 4:
1036                                         return Calendar.CAL_HIJRI;
1037                                 default:
1038                                         throw new NotImplementedException ("CalendarType");
1039                                 }
1040                         }
1041                 }
1042
1043                 static Calendar CreateCalendar (int calendarType)
1044                 {
1045                         string name = null;
1046                         switch (calendarType >> CalendarTypeBits) {
1047                         case 1:
1048                                 GregorianCalendarTypes greg_type;
1049                                 greg_type = (GregorianCalendarTypes) (calendarType & 0xFF);
1050                                 return new GregorianCalendar (greg_type);
1051                         case 2:
1052                                 name = "System.Globalization.ThaiBuddhistCalendar";
1053                                 break;
1054                         case 3:
1055                                 name = "System.Globalization.UmAlQuraCalendar";
1056                                 break;
1057                         case 4:
1058                                 name = "System.Globalization.HijriCalendar";
1059                                 break;
1060                         default:
1061                                 throw new NotImplementedException ("Unknown calendar type: " + calendarType);
1062                         }
1063
1064                         Type type = Type.GetType (name, false);
1065                         if (type == null)
1066                                 return new GregorianCalendar (GregorianCalendarTypes.Localized); // return invariant calendar if not found
1067                         return (Calendar) Activator.CreateInstance (type);
1068                 }
1069
1070                 static Exception CreateNotFoundException (string name)
1071                 {
1072                         return new CultureNotFoundException ("name", "Culture name " + name + " is not supported.");
1073                 }
1074                 
1075                 public static CultureInfo DefaultThreadCurrentCulture {
1076                         get {
1077                                 return Thread.default_culture;
1078                         }
1079                         set {
1080                                 Thread.default_culture = value;
1081                         }
1082                 }
1083                 
1084                 public static CultureInfo DefaultThreadCurrentUICulture {
1085                         get {
1086                                 return Thread.default_ui_culture;
1087                         }
1088                         set {
1089                                 Thread.default_ui_culture = value;
1090                         }
1091                 }
1092
1093                 internal string SortName {
1094                         get {
1095                                 return m_name;
1096                         }
1097                 }
1098
1099 #region reference sources
1100                 // TODO:
1101                 internal static readonly bool IsTaiwanSku;
1102
1103         //
1104         // CheckDomainSafetyObject throw if the object is customized object which cannot be attached to 
1105         // other object (like CultureInfo or DateTimeFormatInfo).
1106         //
1107
1108         internal static void CheckDomainSafetyObject(Object obj, Object container)
1109         {
1110             if (obj.GetType().Assembly != typeof(System.Globalization.CultureInfo).Assembly) {
1111                 
1112                 throw new InvalidOperationException(
1113                             String.Format(
1114                                 CultureInfo.CurrentCulture, 
1115                                 Environment.GetResourceString("InvalidOperation_SubclassedObject"), 
1116                                 obj.GetType(),
1117                                 container.GetType()));
1118             }
1119             Contract.EndContractBlock();
1120         }
1121
1122         // For resource lookup, we consider a culture the invariant culture by name equality.
1123         // We perform this check frequently during resource lookup, so adding a property for
1124         // improved readability.
1125         internal bool HasInvariantCultureName
1126         {
1127             get { return Name == CultureInfo.InvariantCulture.Name; }
1128         }
1129
1130         internal static bool VerifyCultureName(String cultureName, bool throwException)
1131         {
1132             // This function is used by ResourceManager.GetResourceFileName(). 
1133             // ResourceManager searches for resource using CultureInfo.Name,
1134             // so we should check against CultureInfo.Name.
1135
1136             for (int i=0; i<cultureName.Length; i++) {
1137                 char c = cultureName[i];
1138                 // 
1139
1140                 if (Char.IsLetterOrDigit(c) || c=='-' || c=='_') {
1141                     continue;
1142                 }
1143                 if (throwException) {
1144                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidResourceCultureName", cultureName));
1145                 }
1146                 return false;
1147             }
1148             return true;
1149         }
1150
1151 #endregion
1152         }
1153 }