1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <nativehelper/JNIHelp.h>
20 #include <nativehelper/ScopedUtfChars.h>
21 
22 #include "unicode/uloc.h"
23 
24 
getLocale(const char * localeName,std::string & locale,UErrorCode * status)25 static void getLocale(const char* localeName, std::string& locale, UErrorCode* status) {
26     int length;
27     {
28         // Most common locale name should fit the max capacity.
29         char buffer[ULOC_FULLNAME_CAPACITY];
30         UErrorCode err = U_ZERO_ERROR;
31 
32         length = uloc_getName(localeName, buffer, ULOC_FULLNAME_CAPACITY, &err);
33         if (U_SUCCESS(err)) {
34             locale = buffer;
35             *status = err;
36             return;
37         } else if (err != U_BUFFER_OVERFLOW_ERROR) {
38             *status = err;
39             return;
40         }
41     }
42 
43     // Case U_BUFFER_OVERFLOW_ERROR
44     std::unique_ptr<char[]> buffer(new char[length+1]);
45     UErrorCode err = U_ZERO_ERROR;
46     uloc_getName(localeName, buffer.get(), length+1, &err);
47     if (U_SUCCESS(err)) {
48         locale = buffer.get();
49     }
50     *status = err;
51     return;
52 }
53 
54 class ScopedIcuULoc {
55  public:
ScopedIcuULoc(JNIEnv * env,jstring javaLocaleName)56   ScopedIcuULoc(JNIEnv* env, jstring javaLocaleName) {
57     isValid = false;
58 
59     if (javaLocaleName == NULL) {
60       jniThrowNullPointerException(env, "javaLocaleName == null");
61       return;
62     }
63 
64     const ScopedUtfChars localeName(env, javaLocaleName);
65     if (localeName.c_str() == NULL) {
66       return;
67     }
68 
69     UErrorCode status = U_ZERO_ERROR;
70     getLocale(localeName.c_str(), mLocale, &status);
71     isValid = U_SUCCESS(status);
72   }
73 
~ScopedIcuULoc()74   ~ScopedIcuULoc() {
75   }
76 
valid()77   bool valid() const {
78     return isValid;
79   }
80 
locale()81   const char* locale() const {
82     return mLocale.c_str();
83   }
84 
locale_length()85   int32_t locale_length() const {
86     return mLocale.length();
87   }
88 
89  private:
90   bool isValid;
91   std::string mLocale;
92 
93   // Disallow copy and assignment.
94   ScopedIcuULoc(const ScopedIcuULoc&);
95   void operator=(const ScopedIcuULoc&);
96 };
97