@@ -130,6 +130,25 @@ String? computeMessageName(String? name, String? text, String? meaning) {
130130 return meaning == null ? text : '${text }_$meaning ' ;
131131}
132132
133+ /// Returns an index of a separator between language and region.
134+ ///
135+ /// Assumes that language length can be only 2 or 3.
136+ int _separatorIndex (String locale) {
137+ if (locale.length < 3 ) {
138+ return - 1 ;
139+ }
140+ if (locale[2 ] == '-' || locale[2 ] == '_' ) {
141+ return 2 ;
142+ }
143+ if (locale.length < 4 ) {
144+ return - 1 ;
145+ }
146+ if (locale[3 ] == '-' || locale[3 ] == '_' ) {
147+ return 3 ;
148+ }
149+ return - 1 ;
150+ }
151+
133152String canonicalizedLocale (String ? aLocale) {
134153// Locales of length < 5 are presumably two-letter forms, or else malformed.
135154// We return them unmodified and if correct they will be found.
@@ -141,11 +160,16 @@ String canonicalizedLocale(String? aLocale) {
141160 if (aLocale == null ) return global_state.getCurrentLocale ();
142161 if (aLocale == 'C' ) return 'en_ISO' ;
143162 if (aLocale.length < 5 ) return aLocale;
144- if (aLocale[2 ] != '-' && (aLocale[2 ] != '_' )) return aLocale;
145- var region = aLocale.substring (3 );
146- // If it's longer than three it's something odd, so don't touch it.
163+
164+ var separatorIndex = _separatorIndex (aLocale);
165+ if (separatorIndex == - 1 ) {
166+ return aLocale;
167+ }
168+ var language = aLocale.substring (0 , separatorIndex);
169+ var region = aLocale.substring (separatorIndex + 1 );
170+ // If it's longer than three it's something odd, so don't touch it.
147171 if (region.length <= 3 ) region = region.toUpperCase ();
148- return '${aLocale [ 0 ]}${ aLocale [ 1 ] }_$region ' ;
172+ return '${language }_$region ' ;
149173}
150174
151175String ? verifiedLocale (String ? newLocale, bool Function (String ) localeExists,
@@ -182,6 +206,22 @@ String _throwLocaleError(String localeName) {
182206
183207/// Return the short version of a locale name, e.g. 'en_US' => 'en'
184208String shortLocale (String aLocale) {
185- if (aLocale.length < 2 ) return aLocale;
186- return aLocale.substring (0 , 2 ).toLowerCase ();
209+ // TODO(b/241094372): Remove this check.
210+ if (aLocale == 'invalid' ) {
211+ return 'in' ;
212+ }
213+ if (aLocale.length < 2 ) {
214+ return aLocale;
215+ }
216+ var separatorIndex = _separatorIndex (aLocale);
217+ if (separatorIndex == - 1 ) {
218+ if (aLocale.length < 4 ) {
219+ // aLocale is already only a language code.
220+ return aLocale.toLowerCase ();
221+ } else {
222+ // Something weird, returning as is.
223+ return aLocale;
224+ }
225+ }
226+ return aLocale.substring (0 , separatorIndex).toLowerCase ();
187227}
0 commit comments