Merge pull request #2859 from lambdageek/dev/monoerror-object-c
[mono.git] / mono / metadata / locales.c
1 /*
2  * locales.c: Culture-sensitive handling
3  *
4  * Authors:
5  *      Dick Porter (dick@ximian.com)
6  *      Mohammad DAMT (mdamt@cdl2000.com)
7  *      Marek Safar (marek.safar@gmail.com)
8  *
9  * Copyright 2003 Ximian, Inc (http://www.ximian.com)
10  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11  * (C) 2003 PT Cakram Datalingga Duaribu  http://www.cdl2000.com
12  * Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
13  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14  */
15
16 #include <config.h>
17 #include <glib.h>
18 #include <string.h>
19
20 #include <mono/metadata/debug-helpers.h>
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/appdomain.h>
23 #include <mono/metadata/exception.h>
24 #include <mono/metadata/monitor.h>
25 #include <mono/metadata/locales.h>
26 #include <mono/metadata/culture-info.h>
27 #include <mono/metadata/culture-info-tables.h>
28 #include <mono/utils/bsearch.h>
29
30 #ifndef DISABLE_NORMALIZATION
31 #include <mono/metadata/normalization-tables.h>
32 #endif
33
34 #include <locale.h>
35 #if defined(__APPLE__)
36 #include <CoreFoundation/CoreFoundation.h>
37 #endif
38
39 #undef DEBUG
40
41 static gint32 string_invariant_compare_char (gunichar2 c1, gunichar2 c2,
42                                              gint32 options);
43 static gint32 string_invariant_compare (MonoString *str1, gint32 off1,
44                                         gint32 len1, MonoString *str2,
45                                         gint32 off2, gint32 len2,
46                                         gint32 options);
47 static gint32 string_invariant_indexof (MonoString *source, gint32 sindex,
48                                         gint32 count, MonoString *value,
49                                         MonoBoolean first);
50 static gint32 string_invariant_indexof_char (MonoString *source, gint32 sindex,
51                                              gint32 count, gunichar2 value,
52                                              MonoBoolean first);
53
54 static const CultureInfoEntry* culture_info_entry_from_lcid (int lcid);
55
56 static const RegionInfoEntry* region_info_entry_from_lcid (int lcid);
57
58 /* Lazy class loading functions */
59 static GENERATE_GET_CLASS_WITH_CACHE (culture_info, System.Globalization, CultureInfo)
60
61 static int
62 culture_lcid_locator (const void *a, const void *b)
63 {
64         const int *lcid = (const int *)a;
65         const CultureInfoEntry *bb = (const CultureInfoEntry *)b;
66
67         return *lcid - bb->lcid;
68 }
69
70 static int
71 culture_name_locator (const void *a, const void *b)
72 {
73         const char *aa = (const char *)a;
74         const CultureInfoNameEntry *bb = (const CultureInfoNameEntry *)b;
75         int ret;
76         
77         ret = strcmp (aa, idx2string (bb->name));
78
79         return ret;
80 }
81
82 static int
83 region_name_locator (const void *a, const void *b)
84 {
85         const char *aa = (const char *)a;
86         const RegionInfoNameEntry *bb = (const RegionInfoNameEntry *)b;
87         int ret;
88         
89         ret = strcmp (aa, idx2string (bb->name));
90
91         return ret;
92 }
93
94 static MonoArray*
95 create_group_sizes_array (const gint *gs, gint ml, MonoError *error)
96 {
97         MonoArray *ret;
98         int i, len = 0;
99
100         mono_error_init (error);
101
102         for (i = 0; i < ml; i++) {
103                 if (gs [i] == -1)
104                         break;
105                 len++;
106         }
107         
108         ret = mono_array_new_cached (mono_domain_get (),
109                                      mono_get_int32_class (), len, error);
110         return_val_if_nok (error, NULL);
111
112         for(i = 0; i < len; i++)
113                 mono_array_set (ret, gint32, i, gs [i]);
114
115         return ret;
116 }
117
118 static MonoArray*
119 create_names_array_idx (const guint16 *names, int ml, MonoError *error)
120 {
121         MonoArray *ret;
122         MonoDomain *domain;
123         int i;
124
125         mono_error_init (error);
126
127         if (names == NULL)
128                 return NULL;
129
130         domain = mono_domain_get ();
131
132         ret = mono_array_new_cached (mono_domain_get (), mono_get_string_class (), ml, error);
133         return_val_if_nok (error, NULL);
134
135         for(i = 0; i < ml; i++)
136                 mono_array_setref (ret, i, mono_string_new (domain, idx2string (names [i])));
137
138         return ret;
139 }
140
141 static MonoArray*
142 create_names_array_idx_dynamic (const guint16 *names, int ml, MonoError *error)
143 {
144         MonoArray *ret;
145         MonoDomain *domain;
146         int i, len = 0;
147
148         mono_error_init (error);
149
150         if (names == NULL)
151                 return NULL;
152
153         domain = mono_domain_get ();
154
155         for (i = 0; i < ml; i++) {
156                 if (names [i] == 0)
157                         break;
158                 len++;
159         }
160
161         ret = mono_array_new_cached (mono_domain_get (), mono_get_string_class (), len, error);
162         return_val_if_nok (error, NULL);
163
164         for(i = 0; i < len; i++)
165                 mono_array_setref (ret, i, mono_string_new (domain, idx2string (names [i])));
166
167         return ret;
168 }
169
170 MonoBoolean
171 ves_icall_System_Globalization_CalendarData_fill_calendar_data (MonoCalendarData *this_obj, MonoString *name, gint32 calendar_index)
172 {
173         MonoError error;
174         MonoDomain *domain;
175         const DateTimeFormatEntry *dfe;
176         const CultureInfoNameEntry *ne;
177         const CultureInfoEntry *ci;
178         char *n;
179
180         n = mono_string_to_utf8 (name);
181         ne = (const CultureInfoNameEntry *)mono_binary_search (n, culture_name_entries, NUM_CULTURE_ENTRIES,
182                         sizeof (CultureInfoNameEntry), culture_name_locator);
183         g_free (n);
184         if (ne == NULL) {
185                 return FALSE;
186         }
187
188         ci = &culture_entries [ne->culture_entry_index];
189         dfe = &datetime_format_entries [ci->datetime_format_index];
190
191         domain = mono_domain_get ();
192
193         MONO_OBJECT_SETREF (this_obj, NativeName, mono_string_new (domain, idx2string (ci->nativename)));
194         MonoArray *short_date_patterns = create_names_array_idx_dynamic (dfe->short_date_patterns,
195                                                                          NUM_SHORT_DATE_PATTERNS, &error);
196         return_val_and_set_pending_if_nok (&error, FALSE);
197         MONO_OBJECT_SETREF (this_obj, ShortDatePatterns, short_date_patterns);
198         MonoArray *year_month_patterns =create_names_array_idx_dynamic (dfe->year_month_patterns,
199                                                                         NUM_YEAR_MONTH_PATTERNS, &error);
200         return_val_and_set_pending_if_nok (&error, FALSE);
201         MONO_OBJECT_SETREF (this_obj, YearMonthPatterns, year_month_patterns);
202
203         MonoArray *long_date_patterns = create_names_array_idx_dynamic (dfe->long_date_patterns,
204                                                                         NUM_LONG_DATE_PATTERNS, &error);
205         return_val_and_set_pending_if_nok (&error, FALSE);
206         MONO_OBJECT_SETREF (this_obj, LongDatePatterns, long_date_patterns);
207
208         MONO_OBJECT_SETREF (this_obj, MonthDayPattern, mono_string_new (domain, idx2string (dfe->month_day_pattern)));
209
210         MonoArray *day_names = create_names_array_idx (dfe->day_names, NUM_DAYS, &error);
211         return_val_and_set_pending_if_nok (&error, FALSE);
212         MONO_OBJECT_SETREF (this_obj, DayNames, day_names);
213
214         MonoArray *abbr_day_names = create_names_array_idx (dfe->abbreviated_day_names, 
215                                                             NUM_DAYS, &error);
216         return_val_and_set_pending_if_nok (&error, FALSE);
217         MONO_OBJECT_SETREF (this_obj, AbbreviatedDayNames, abbr_day_names);
218
219         MonoArray *ss_day_names = create_names_array_idx (dfe->shortest_day_names, NUM_DAYS, &error);
220         return_val_and_set_pending_if_nok (&error, FALSE);
221         MONO_OBJECT_SETREF (this_obj, SuperShortDayNames, ss_day_names);
222
223         MonoArray *month_names = create_names_array_idx (dfe->month_names, NUM_MONTHS, &error);
224         return_val_and_set_pending_if_nok (&error, FALSE);
225         MONO_OBJECT_SETREF (this_obj, MonthNames, month_names);
226
227         MonoArray *abbr_mon_names = create_names_array_idx (dfe->abbreviated_month_names,
228                                                             NUM_MONTHS, &error);
229         return_val_and_set_pending_if_nok (&error, FALSE);
230         MONO_OBJECT_SETREF (this_obj, AbbreviatedMonthNames, abbr_mon_names);
231
232         
233         MonoArray *gen_month_names = create_names_array_idx (dfe->month_genitive_names, NUM_MONTHS, &error);
234         return_val_and_set_pending_if_nok (&error, FALSE);
235         MONO_OBJECT_SETREF (this_obj, GenitiveMonthNames, gen_month_names);
236
237         MonoArray *gen_abbr_mon_names = create_names_array_idx (dfe->abbreviated_month_genitive_names, NUM_MONTHS, &error);
238         return_val_and_set_pending_if_nok (&error, FALSE);
239         MONO_OBJECT_SETREF (this_obj, GenitiveAbbreviatedMonthNames, gen_abbr_mon_names);
240
241         return TRUE;
242 }
243
244 void
245 ves_icall_System_Globalization_CultureData_fill_culture_data (MonoCultureData *this_obj, gint32 datetime_index)
246 {
247         MonoError error;
248         MonoDomain *domain;
249         const DateTimeFormatEntry *dfe;
250
251         g_assert (datetime_index >= 0);
252
253         dfe = &datetime_format_entries [datetime_index];
254
255         domain = mono_domain_get ();
256
257         MONO_OBJECT_SETREF (this_obj, AMDesignator, mono_string_new (domain, idx2string (dfe->am_designator)));
258         MONO_OBJECT_SETREF (this_obj, PMDesignator, mono_string_new (domain, idx2string (dfe->pm_designator)));
259         MONO_OBJECT_SETREF (this_obj, TimeSeparator, mono_string_new (domain, idx2string (dfe->time_separator)));
260
261         MonoArray *long_time_patterns = create_names_array_idx_dynamic (dfe->long_time_patterns,
262                                                                         NUM_LONG_TIME_PATTERNS, &error);
263         if (mono_error_set_pending_exception (&error))
264                 return;
265         MONO_OBJECT_SETREF (this_obj, LongTimePatterns, long_time_patterns);
266
267         MonoArray *short_time_patterns = create_names_array_idx_dynamic (dfe->short_time_patterns,
268                                                                          NUM_SHORT_TIME_PATTERNS, &error);
269         if (mono_error_set_pending_exception (&error))
270                 return;
271         MONO_OBJECT_SETREF (this_obj, ShortTimePatterns, short_time_patterns);
272         this_obj->FirstDayOfWeek = dfe->first_day_of_week;
273         this_obj->CalendarWeekRule = dfe->calendar_week_rule;
274 }
275
276 void
277 ves_icall_System_Globalization_CultureData_fill_number_data (MonoNumberFormatInfo* number, gint32 number_index)
278 {
279         MonoError error;
280         MonoDomain *domain;
281         const NumberFormatEntry *nfe;
282
283         g_assert (number_index >= 0);
284
285         nfe = &number_format_entries [number_index];
286
287         domain = mono_domain_get ();
288
289         number->currencyDecimalDigits = nfe->currency_decimal_digits;
290         MONO_OBJECT_SETREF (number, currencyDecimalSeparator, mono_string_new (domain,
291                         idx2string (nfe->currency_decimal_separator)));
292         MONO_OBJECT_SETREF (number, currencyGroupSeparator, mono_string_new (domain,
293                         idx2string (nfe->currency_group_separator)));
294         MonoArray *currency_sizes_arr = create_group_sizes_array (nfe->currency_group_sizes,
295                                                                   GROUP_SIZE, &error);
296         if (mono_error_set_pending_exception (&error))
297                 return;
298         MONO_OBJECT_SETREF (number, currencyGroupSizes, currency_sizes_arr);
299         number->currencyNegativePattern = nfe->currency_negative_pattern;
300         number->currencyPositivePattern = nfe->currency_positive_pattern;
301         MONO_OBJECT_SETREF (number, currencySymbol, mono_string_new (domain, idx2string (nfe->currency_symbol)));
302         MONO_OBJECT_SETREF (number, naNSymbol, mono_string_new (domain, idx2string (nfe->nan_symbol)));
303         MONO_OBJECT_SETREF (number, negativeInfinitySymbol, mono_string_new (domain,
304                         idx2string (nfe->negative_infinity_symbol)));
305         MONO_OBJECT_SETREF (number, negativeSign, mono_string_new (domain, idx2string (nfe->negative_sign)));
306         number->numberDecimalDigits = nfe->number_decimal_digits;
307         MONO_OBJECT_SETREF (number, numberDecimalSeparator, mono_string_new (domain,
308                         idx2string (nfe->number_decimal_separator)));
309         MONO_OBJECT_SETREF (number, numberGroupSeparator, mono_string_new (domain, idx2string (nfe->number_group_separator)));
310         MonoArray *number_sizes_arr = create_group_sizes_array (nfe->number_group_sizes,
311                                                                 GROUP_SIZE, &error);
312         if (mono_error_set_pending_exception (&error))
313                 return;
314         MONO_OBJECT_SETREF (number, numberGroupSizes, number_sizes_arr);
315         number->numberNegativePattern = nfe->number_negative_pattern;
316         number->percentNegativePattern = nfe->percent_negative_pattern;
317         number->percentPositivePattern = nfe->percent_positive_pattern;
318         MONO_OBJECT_SETREF (number, percentSymbol, mono_string_new (domain, idx2string (nfe->percent_symbol)));
319         MONO_OBJECT_SETREF (number, perMilleSymbol, mono_string_new (domain, idx2string (nfe->per_mille_symbol)));
320         MONO_OBJECT_SETREF (number, positiveInfinitySymbol, mono_string_new (domain,
321                         idx2string (nfe->positive_infinity_symbol)));
322         MONO_OBJECT_SETREF (number, positiveSign, mono_string_new (domain, idx2string (nfe->positive_sign)));
323 }
324
325 static MonoBoolean
326 construct_culture (MonoCultureInfo *this_obj, const CultureInfoEntry *ci, MonoError *error)
327 {
328         MonoDomain *domain = mono_domain_get ();
329
330         mono_error_init (error);
331
332         this_obj->lcid = ci->lcid;
333         MONO_OBJECT_SETREF (this_obj, name, mono_string_new (domain, idx2string (ci->name)));
334         MONO_OBJECT_SETREF (this_obj, englishname, mono_string_new (domain, idx2string (ci->englishname)));
335         MONO_OBJECT_SETREF (this_obj, nativename, mono_string_new (domain, idx2string (ci->nativename)));
336         MONO_OBJECT_SETREF (this_obj, win3lang, mono_string_new (domain, idx2string (ci->win3lang)));
337         MONO_OBJECT_SETREF (this_obj, iso3lang, mono_string_new (domain, idx2string (ci->iso3lang)));
338         MONO_OBJECT_SETREF (this_obj, iso2lang, mono_string_new (domain, idx2string (ci->iso2lang)));
339
340         // It's null for neutral cultures
341         if (ci->territory > 0)
342                 MONO_OBJECT_SETREF (this_obj, territory, mono_string_new (domain, idx2string (ci->territory)));
343
344         MonoArray *native_calendar_names = create_names_array_idx (ci->native_calendar_names, NUM_CALENDARS, error);
345         return_val_if_nok (error, FALSE);
346         MONO_OBJECT_SETREF (this_obj, native_calendar_names, native_calendar_names);
347         this_obj->parent_lcid = ci->parent_lcid;
348         this_obj->datetime_index = ci->datetime_format_index;
349         this_obj->number_index = ci->number_format_index;
350         this_obj->calendar_type = ci->calendar_type;
351         this_obj->text_info_data = &ci->text_info;
352         
353         return TRUE;
354 }
355
356 static MonoBoolean
357 construct_region (MonoRegionInfo *this_obj, const RegionInfoEntry *ri)
358 {
359         MonoDomain *domain = mono_domain_get ();
360
361         this_obj->geo_id = ri->geo_id;
362         MONO_OBJECT_SETREF (this_obj, iso2name, mono_string_new (domain, idx2string (ri->iso2name)));
363         MONO_OBJECT_SETREF (this_obj, iso3name, mono_string_new (domain, idx2string (ri->iso3name)));
364         MONO_OBJECT_SETREF (this_obj, win3name, mono_string_new (domain, idx2string (ri->win3name)));
365         MONO_OBJECT_SETREF (this_obj, english_name, mono_string_new (domain, idx2string (ri->english_name)));
366         MONO_OBJECT_SETREF (this_obj, native_name, mono_string_new (domain, idx2string (ri->native_name)));
367         MONO_OBJECT_SETREF (this_obj, currency_symbol, mono_string_new (domain, idx2string (ri->currency_symbol)));
368         MONO_OBJECT_SETREF (this_obj, iso_currency_symbol, mono_string_new (domain, idx2string (ri->iso_currency_symbol)));
369         MONO_OBJECT_SETREF (this_obj, currency_english_name, mono_string_new (domain, idx2string (ri->currency_english_name)));
370         MONO_OBJECT_SETREF (this_obj, currency_native_name, mono_string_new (domain, idx2string (ri->currency_native_name)));
371         
372         return TRUE;
373 }
374
375 static const CultureInfoEntry*
376 culture_info_entry_from_lcid (int lcid)
377 {
378         const CultureInfoEntry *ci;
379
380         ci = (const CultureInfoEntry *)mono_binary_search (&lcid, culture_entries, NUM_CULTURE_ENTRIES, sizeof (CultureInfoEntry), culture_lcid_locator);
381
382         return ci;
383 }
384
385 static const RegionInfoEntry*
386 region_info_entry_from_lcid (int lcid)
387 {
388         const RegionInfoEntry *entry;
389         const CultureInfoEntry *ne;
390
391         ne = (const CultureInfoEntry *)mono_binary_search (&lcid, culture_entries, NUM_CULTURE_ENTRIES, sizeof (CultureInfoEntry), culture_lcid_locator);
392
393         if (ne == NULL)
394                 return FALSE;
395
396         entry = &region_entries [ne->region_entry_index];
397
398         return entry;
399 }
400
401 #if defined (__APPLE__)
402 static gchar*
403 get_darwin_locale (void)
404 {
405         static gchar *darwin_locale = NULL;
406         CFLocaleRef locale = NULL;
407         CFStringRef locale_language = NULL;
408         CFStringRef locale_country = NULL;
409         CFStringRef locale_script = NULL;
410         CFStringRef locale_cfstr = NULL;
411         CFIndex bytes_converted;
412         CFIndex bytes_written;
413         CFIndex len;
414         int i;
415
416         if (darwin_locale != NULL)
417                 return g_strdup (darwin_locale);
418
419         locale = CFLocaleCopyCurrent ();
420
421         if (locale) {
422                 locale_language = CFLocaleGetValue (locale, kCFLocaleLanguageCode);
423                 if (locale_language != NULL && CFStringGetBytes(locale_language, CFRangeMake (0, CFStringGetLength (locale_language)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) {
424                         len = bytes_converted + 1;
425
426                         locale_country = CFLocaleGetValue (locale, kCFLocaleCountryCode);
427                         if (locale_country != NULL && CFStringGetBytes (locale_country, CFRangeMake (0, CFStringGetLength (locale_country)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) {
428                                 len += bytes_converted + 1;
429
430                                 locale_script = CFLocaleGetValue (locale, kCFLocaleScriptCode);
431                                 if (locale_script != NULL && CFStringGetBytes (locale_script, CFRangeMake (0, CFStringGetLength (locale_script)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) {
432                                         len += bytes_converted + 1;
433                                 }
434
435                                 darwin_locale = (char *) malloc (len + 1);
436                                 CFStringGetBytes (locale_language, CFRangeMake (0, CFStringGetLength (locale_language)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) darwin_locale, len, &bytes_converted);
437
438                                 darwin_locale[bytes_converted] = '-';
439                                 bytes_written = bytes_converted + 1;
440                                 if (locale_script != NULL && CFStringGetBytes (locale_script, CFRangeMake (0, CFStringGetLength (locale_script)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) &darwin_locale[bytes_written], len - bytes_written, &bytes_converted) > 0) {
441                                         darwin_locale[bytes_written + bytes_converted] = '-';
442                                         bytes_written += bytes_converted + 1;
443                                 }
444
445                                 CFStringGetBytes (locale_country, CFRangeMake (0, CFStringGetLength (locale_country)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) &darwin_locale[bytes_written], len - bytes_written, &bytes_converted);
446                                 darwin_locale[bytes_written + bytes_converted] = '\0';
447                         }
448                 }
449
450                 if (darwin_locale == NULL) {
451                         locale_cfstr = CFLocaleGetIdentifier (locale);
452
453                         if (locale_cfstr) {
454                                 len = CFStringGetMaximumSizeForEncoding (CFStringGetLength (locale_cfstr), kCFStringEncodingMacRoman) + 1;
455                                 darwin_locale = (char *) malloc (len);
456                                 if (!CFStringGetCString (locale_cfstr, darwin_locale, len, kCFStringEncodingMacRoman)) {
457                                         free (darwin_locale);
458                                         CFRelease (locale);
459                                         darwin_locale = NULL;
460                                         return NULL;
461                                 }
462
463                                 for (i = 0; i < strlen (darwin_locale); i++)
464                                         if (darwin_locale [i] == '_')
465                                                 darwin_locale [i] = '-';
466                         }                       
467                 }
468
469                 CFRelease (locale);
470         }
471
472         return g_strdup (darwin_locale);
473 }
474 #endif
475
476 static char *
477 get_posix_locale (void)
478 {
479         const char *locale;
480
481         locale = g_getenv ("LC_ALL");
482         if (locale == NULL) {
483                 locale = g_getenv ("LANG");
484                 if (locale == NULL)
485                         locale = setlocale (LC_ALL, NULL);
486         }
487         if (locale == NULL)
488                 return NULL;
489
490         /* Skip English-only locale 'C' */
491         if (strcmp (locale, "C") == 0)
492                 return NULL;
493
494         return g_strdup (locale);
495 }
496
497
498 static gchar *
499 get_current_locale_name (void)
500 {
501         char *locale;
502         char *p, *ret;
503                 
504 #ifdef HOST_WIN32
505         locale = g_win32_getlocale ();
506 #elif defined (__APPLE__)       
507         locale = get_darwin_locale ();
508         if (!locale)
509                 locale = get_posix_locale ();
510 #else
511         locale = get_posix_locale ();
512 #endif
513
514         if (locale == NULL)
515                 return NULL;
516
517         p = strchr (locale, '.');
518         if (p != NULL)
519                 *p = 0;
520         p = strchr (locale, '@');
521         if (p != NULL)
522                 *p = 0;
523         p = strchr (locale, '_');
524         if (p != NULL)
525                 *p = '-';
526
527         ret = g_ascii_strdown (locale, -1);
528         g_free (locale);
529
530         return ret;
531 }
532
533 MonoString*
534 ves_icall_System_Globalization_CultureInfo_get_current_locale_name (void)
535 {
536         gchar *locale;
537         MonoString* ret;
538         MonoDomain *domain;
539
540         locale = get_current_locale_name ();
541         if (locale == NULL)
542                 return NULL;
543
544         domain = mono_domain_get ();
545         ret = mono_string_new (domain, locale);
546         g_free (locale);
547
548         return ret;
549 }
550
551 MonoBoolean
552 ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_lcid (MonoCultureInfo *this_obj,
553                 gint lcid)
554 {
555         MonoError error;
556         const CultureInfoEntry *ci;
557         
558         ci = culture_info_entry_from_lcid (lcid);
559         if(ci == NULL)
560                 return FALSE;
561
562         if (!construct_culture (this_obj, ci, &error)) {
563                 mono_error_set_pending_exception (&error);
564                 return FALSE;
565         }
566         return TRUE;
567 }
568
569 MonoBoolean
570 ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_name (MonoCultureInfo *this_obj,
571                 MonoString *name)
572 {
573         MonoError error;
574         const CultureInfoNameEntry *ne;
575         char *n;
576         
577         n = mono_string_to_utf8 (name);
578         ne = (const CultureInfoNameEntry *)mono_binary_search (n, culture_name_entries, NUM_CULTURE_ENTRIES,
579                         sizeof (CultureInfoNameEntry), culture_name_locator);
580
581         if (ne == NULL) {
582                 /*g_print ("ne (%s) is null\n", n);*/
583                 g_free (n);
584                 return FALSE;
585         }
586         g_free (n);
587
588         if (!construct_culture (this_obj, &culture_entries [ne->culture_entry_index], &error)) {
589                 mono_error_set_pending_exception (&error);
590                 return FALSE;
591         }
592         return TRUE;
593 }
594 /*
595 MonoBoolean
596 ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_specific_name (MonoCultureInfo *ci,
597                 MonoString *name)
598 {
599         gchar *locale;
600         gboolean ret;
601
602         locale = mono_string_to_utf8 (name);
603         ret = construct_culture_from_specific_name (ci, locale);
604         g_free (locale);
605
606         return ret;
607 }
608 */
609 MonoBoolean
610 ves_icall_System_Globalization_RegionInfo_construct_internal_region_from_lcid (MonoRegionInfo *this_obj,
611                 gint lcid)
612 {
613         const RegionInfoEntry *ri;
614         
615         ri = region_info_entry_from_lcid (lcid);
616         if(ri == NULL)
617                 return FALSE;
618
619         return construct_region (this_obj, ri);
620 }
621
622 MonoBoolean
623 ves_icall_System_Globalization_RegionInfo_construct_internal_region_from_name (MonoRegionInfo *this_obj,
624                 MonoString *name)
625 {
626         const RegionInfoNameEntry *ne;
627         char *n;
628         
629         n = mono_string_to_utf8 (name);
630         ne = (const RegionInfoNameEntry *)mono_binary_search (n, region_name_entries, NUM_REGION_ENTRIES,
631                 sizeof (RegionInfoNameEntry), region_name_locator);
632
633         if (ne == NULL) {
634                 /*g_print ("ne (%s) is null\n", n);*/
635                 g_free (n);
636                 return FALSE;
637         }
638         g_free (n);
639
640         return construct_region (this_obj, &region_entries [ne->region_entry_index]);
641 }
642
643 MonoArray*
644 ves_icall_System_Globalization_CultureInfo_internal_get_cultures (MonoBoolean neutral,
645                 MonoBoolean specific, MonoBoolean installed)
646 {
647         MonoError error;
648         MonoArray *ret;
649         MonoClass *klass;
650         MonoCultureInfo *culture;
651         MonoDomain *domain;
652         const CultureInfoEntry *ci;
653         gint i, len;
654         gboolean is_neutral;
655
656         domain = mono_domain_get ();
657
658         len = 0;
659         for (i = 0; i < NUM_CULTURE_ENTRIES; i++) {
660                 ci = &culture_entries [i];
661                 is_neutral = ci->territory == 0;
662                 if ((neutral && is_neutral) || (specific && !is_neutral))
663                         len++;
664         }
665
666         klass = mono_class_get_culture_info_class ();
667
668         /* The InvariantCulture is not in culture_entries */
669         /* We reserve the first slot in the array for it */
670         if (neutral)
671                 len++;
672
673         ret = mono_array_new_checked (domain, klass, len, &error);
674         if (!is_ok (&error))
675                 goto fail;
676
677         if (len == 0)
678                 return ret;
679
680         len = 0;
681         if (neutral)
682                 mono_array_setref (ret, len++, NULL);
683
684         for (i = 0; i < NUM_CULTURE_ENTRIES; i++) {
685                 ci = &culture_entries [i];
686                 is_neutral = ci->territory == 0;
687                 if ((neutral && is_neutral) || (specific && !is_neutral)) {
688                         culture = (MonoCultureInfo *) mono_object_new_checked (domain, klass, &error);
689                         if (!is_ok (&error)) goto fail;
690                         mono_runtime_object_init_checked ((MonoObject *) culture, &error);
691                         if (!is_ok (&error)) goto fail;
692                         if (!construct_culture (culture, ci, &error))
693                                 goto fail;
694                         culture->use_user_override = TRUE;
695                         mono_array_setref (ret, len++, culture);
696                 }
697         }
698
699         return ret;
700
701 fail:
702         mono_error_set_pending_exception (&error);
703         return ret;
704 }
705
706 int ves_icall_System_Globalization_CompareInfo_internal_compare (MonoCompareInfo *this_obj, MonoString *str1, gint32 off1, gint32 len1, MonoString *str2, gint32 off2, gint32 len2, gint32 options)
707 {
708         /* Do a normal ascii string compare, as we only know the
709          * invariant locale if we dont have ICU
710          */
711         return(string_invariant_compare (str1, off1, len1, str2, off2, len2,
712                                          options));
713 }
714
715 void ves_icall_System_Globalization_CompareInfo_assign_sortkey (MonoCompareInfo *this_obj, MonoSortKey *key, MonoString *source, gint32 options)
716 {
717         MonoError error;
718         MonoArray *arr;
719         gint32 keylen, i;
720
721         keylen=mono_string_length (source);
722         
723         arr=mono_array_new_checked (mono_domain_get (), mono_get_byte_class (),
724                                     keylen, &error);
725         if (mono_error_set_pending_exception (&error))
726                 return;
727
728         for(i=0; i<keylen; i++) {
729                 mono_array_set (arr, guint8, i, mono_string_chars (source)[i]);
730         }
731         
732         MONO_OBJECT_SETREF (key, key, arr);
733 }
734
735 int ves_icall_System_Globalization_CompareInfo_internal_index (MonoCompareInfo *this_obj, MonoString *source, gint32 sindex, gint32 count, MonoString *value, gint32 options, MonoBoolean first)
736 {
737         return(string_invariant_indexof (source, sindex, count, value, first));
738 }
739
740 int ves_icall_System_Globalization_CompareInfo_internal_index_char (MonoCompareInfo *this_obj, MonoString *source, gint32 sindex, gint32 count, gunichar2 value, gint32 options, MonoBoolean first)
741 {
742         return(string_invariant_indexof_char (source, sindex, count, value,
743                                               first));
744 }
745
746 int ves_icall_System_Threading_Thread_current_lcid (void)
747 {
748         /* Invariant */
749         return(0x007F);
750 }
751
752 static gint32 string_invariant_compare_char (gunichar2 c1, gunichar2 c2,
753                                              gint32 options)
754 {
755         gint32 result;
756
757         /* Ordinal can not be mixed with other options, and must return the difference, not only -1, 0, 1 */
758         if (options & CompareOptions_Ordinal) 
759                 return (gint32) c1 - c2;
760         
761         if (options & CompareOptions_IgnoreCase) {
762                 GUnicodeType c1type, c2type;
763
764                 c1type = g_unichar_type (c1);
765                 c2type = g_unichar_type (c2);
766         
767                 result = (gint32) (c1type != G_UNICODE_LOWERCASE_LETTER ? g_unichar_tolower(c1) : c1) -
768                         (c2type != G_UNICODE_LOWERCASE_LETTER ? g_unichar_tolower(c2) : c2);
769         } else {
770                 /*
771                  * No options. Kana, symbol and spacing options don't
772                  * apply to the invariant culture.
773                  */
774
775                 /*
776                  * FIXME: here we must use the information from c1type and c2type
777                  * to find out the proper collation, even on the InvariantCulture, the
778                  * sorting is not done by computing the unicode values, but their
779                  * actual sort order.
780                  */
781                 result = (gint32) c1 - c2;
782         }
783
784         return ((result < 0) ? -1 : (result > 0) ? 1 : 0);
785 }
786
787 static gint32 string_invariant_compare (MonoString *str1, gint32 off1,
788                                         gint32 len1, MonoString *str2,
789                                         gint32 off2, gint32 len2,
790                                         gint32 options)
791 {
792         /* c translation of C# code from old string.cs.. :) */
793         gint32 length;
794         gint32 charcmp;
795         gunichar2 *ustr1;
796         gunichar2 *ustr2;
797         gint32 pos;
798
799         if(len1 >= len2) {
800                 length=len1;
801         } else {
802                 length=len2;
803         }
804
805         ustr1 = mono_string_chars(str1)+off1;
806         ustr2 = mono_string_chars(str2)+off2;
807
808         pos = 0;
809
810         for (pos = 0; pos != length; pos++) {
811                 if (pos >= len1 || pos >= len2)
812                         break;
813
814                 charcmp = string_invariant_compare_char(ustr1[pos], ustr2[pos],
815                                                         options);
816                 if (charcmp != 0) {
817                         return(charcmp);
818                 }
819         }
820
821         /* the lesser wins, so if we have looped until length we just
822          * need to check the last char
823          */
824         if (pos == length) {
825                 return(string_invariant_compare_char(ustr1[pos - 1],
826                                                      ustr2[pos - 1], options));
827         }
828
829         /* Test if one of the strings has been compared to the end */
830         if (pos >= len1) {
831                 if (pos >= len2) {
832                         return(0);
833                 } else {
834                         return(-1);
835                 }
836         } else if (pos >= len2) {
837                 return(1);
838         }
839
840         /* if not, check our last char only.. (can this happen?) */
841         return(string_invariant_compare_char(ustr1[pos], ustr2[pos], options));
842 }
843
844 static gint32 string_invariant_indexof (MonoString *source, gint32 sindex,
845                                         gint32 count, MonoString *value,
846                                         MonoBoolean first)
847 {
848         gint32 lencmpstr;
849         gunichar2 *src;
850         gunichar2 *cmpstr;
851         gint32 pos,i;
852         
853         lencmpstr = mono_string_length(value);
854         
855         src = mono_string_chars(source);
856         cmpstr = mono_string_chars(value);
857
858         if(first) {
859                 count -= lencmpstr;
860                 for(pos=sindex;pos <= sindex+count;pos++) {
861                         for(i=0;src[pos+i]==cmpstr[i];) {
862                                 if(++i==lencmpstr) {
863                                         return(pos);
864                                 }
865                         }
866                 }
867                 
868                 return(-1);
869         } else {
870                 for(pos=sindex-lencmpstr+1;pos>sindex-count;pos--) {
871                         if(memcmp (src+pos, cmpstr,
872                                    lencmpstr*sizeof(gunichar2))==0) {
873                                 return(pos);
874                         }
875                 }
876                 
877                 return(-1);
878         }
879 }
880
881 static gint32 string_invariant_indexof_char (MonoString *source, gint32 sindex,
882                                              gint32 count, gunichar2 value,
883                                              MonoBoolean first)
884 {
885         gint32 pos;
886         gunichar2 *src;
887
888         src = mono_string_chars(source);
889         if(first) {
890                 for (pos = sindex; pos != count + sindex; pos++) {
891                         if (src [pos] == value) {
892                                 return(pos);
893                         }
894                 }
895
896                 return(-1);
897         } else {
898                 for (pos = sindex; pos > sindex - count; pos--) {
899                         if (src [pos] == value)
900                                 return(pos);
901                 }
902
903                 return(-1);
904         }
905 }
906
907 void ves_icall_System_Text_Normalization_load_normalization_resource (guint8 **argProps,
908                                                                                                                                           guint8 **argMappedChars,
909                                                                                                                                           guint8 **argCharMapIndex,
910                                                                                                                                           guint8 **argHelperIndex,
911                                                                                                                                           guint8 **argMapIdxToComposite,
912                                                                                                                                           guint8 **argCombiningClass)
913 {
914 #ifdef DISABLE_NORMALIZATION
915         mono_set_pending_exception (mono_get_exception_not_supported ("This runtime has been compiled without string normalization support."));
916         return;
917 #else
918         *argProps = (guint8*)props;
919         *argMappedChars = (guint8*) mappedChars;
920         *argCharMapIndex = (guint8*) charMapIndex;
921         *argHelperIndex = (guint8*) helperIndex;
922         *argMapIdxToComposite = (guint8*) mapIdxToComposite;
923         *argCombiningClass = (guint8*)combiningClass;
924 #endif
925 }
926
927