Tizen 2.0 Release
[framework/web/wrt-commons.git] / modules / core / src / string.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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  * @file        string.cpp
18  * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
19  * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
20  * @version     1.0
21  */
22 #include <stddef.h>
23 #include <dpl/string.h>
24 #include <dpl/char_traits.h>
25 #include <dpl/errno_string.h>
26 #include <dpl/exception.h>
27 #include <dpl/scoped_array.h>
28 #include <dpl/log/log.h>
29 #include <string>
30 #include <vector>
31 #include <algorithm>
32 #include <cstring>
33 #include <errno.h>
34 #include <iconv.h>
35 #include <unicode/ustring.h>
36
37 // TODO: Completely move to ICU
38 namespace DPL
39 {
40 namespace //anonymous
41 {
42 class ASCIIValidator
43 {
44     const std::string& m_TestedString;
45
46 public:
47     ASCIIValidator(const std::string& aTestedString);
48
49     void operator()(char aCharacter) const;
50 };
51
52 ASCIIValidator::ASCIIValidator(const std::string& aTestedString)
53     : m_TestedString(aTestedString)
54 {
55 }
56
57 void ASCIIValidator::operator()(char aCharacter) const
58 {
59     // Check for ASCII data range
60     if (aCharacter <= 0)
61     {
62         ThrowMsg(StringException::InvalidASCIICharacter,
63                  "invalid character code " << static_cast<int>(aCharacter)
64                  << " from string [" << m_TestedString
65                  << "] passed as ASCII");
66     }
67 }
68
69 const iconv_t gc_IconvOperError = reinterpret_cast<iconv_t>(-1);
70 const size_t gc_IconvConvertError = static_cast<size_t>(-1);
71 } // namespace anonymous
72
73 String FromUTF8String(const std::string& aIn)
74 {
75     if (aIn.empty())
76
77         return String();
78
79     size_t inbytes = aIn.size();
80
81     // Default iconv UTF-32 module adds BOM (4 bytes) in from of string
82     // The worst case is when 8bit UTF-8 char converts to 32bit UTF-32
83     // newsize = oldsize * 4 + end + bom
84     // newsize - bytes for UTF-32 string
85     // oldsize - letters in UTF-8 string
86     // end - end character for UTF-32 (\0)
87     // bom - Unicode header in front of string (0xfeff)
88     size_t outbytes = sizeof(wchar_t)*(inbytes + 2);
89     std::vector<wchar_t> output(inbytes + 2, 0);
90
91     size_t outbytesleft = outbytes;
92     char* inbuf = const_cast<char*>(aIn.c_str());
93
94     // vector is used to provide buffer for iconv which expects char* buffer
95     // but during conversion from UTF32 uses internaly wchar_t
96     char* outbuf = reinterpret_cast<char*>(&output[0]);
97
98     iconv_t iconvHandle = iconv_open("UTF-32","UTF-8");
99
100     if (gc_IconvOperError == iconvHandle)
101     {
102         int error = errno;
103
104         ThrowMsg(StringException::IconvInitErrorUTF8ToUTF32,
105                  "iconv_open failed for " << "UTF-32 <- UTF-8" <<
106                  "error: " << GetErrnoString(error));
107     }
108
109     size_t iconvRet = iconv(iconvHandle, &inbuf, &inbytes, &outbuf, &outbytesleft);
110
111     iconv_close(iconvHandle);
112
113     if (gc_IconvConvertError == iconvRet)
114     {
115         ThrowMsg(StringException::IconvConvertErrorUTF8ToUTF32,
116                  "iconv failed for " << "UTF-32 <- UTF-8" << "error: "
117                             << GetErrnoString());
118     }
119
120     // Ignore BOM in front of UTF-32
121     return &output[1];
122 }
123
124 std::string ToUTF8String(const DPL::String& aIn)
125 {
126     if (aIn.empty())
127
128         return std::string();
129
130     size_t inbytes = aIn.size() * sizeof(wchar_t);
131     size_t outbytes = inbytes + sizeof(char);
132
133     // wstring returns wchar_t but iconv expects char*
134     // iconv internally is processing input as wchar_t
135     char* inbuf =  reinterpret_cast<char*>(const_cast<wchar_t*>(aIn.c_str()));
136     std::vector<char> output(inbytes, 0);
137     char* outbuf = &output[0];
138
139     size_t outbytesleft = outbytes;
140
141     iconv_t iconvHandle = iconv_open("UTF-8","UTF-32");
142
143     if (gc_IconvOperError == iconvHandle)
144     {
145         ThrowMsg(StringException::IconvInitErrorUTF32ToUTF8,
146                  "iconv_open failed for " << "UTF-8 <- UTF-32"
147                             << "error: " << GetErrnoString());
148     }
149
150     size_t iconvRet = iconv(iconvHandle, &inbuf, &inbytes, &outbuf, &outbytesleft);
151
152     iconv_close(iconvHandle);
153
154     if (gc_IconvConvertError == iconvRet)
155     {
156         ThrowMsg(StringException::IconvConvertErrorUTF32ToUTF8,
157                  "iconv failed for " << "UTF-8 <- UTF-32"
158                             << "error: " << GetErrnoString());
159     }
160
161     return &output[0];
162 }
163
164 String FromASCIIString(const std::string& aString)
165 {
166     String output;
167
168     std::for_each(aString.begin(), aString.end(), ASCIIValidator(aString));
169     std::copy(aString.begin(), aString.end(), std::back_inserter<String>(output));
170
171     return output;
172 }
173
174 String FromUTF32String(const std::wstring& aString)
175 {
176     return String(&aString[0]);
177 }
178
179 static UChar *ConvertToICU(const String &inputString)
180 {
181     ScopedArray<UChar> outputString;
182     int32_t size = 0;
183     int32_t convertedSize = 0;
184     UErrorCode error = U_ZERO_ERROR;
185
186     // Calculate size of output string
187     ::u_strFromWCS(NULL,
188                    0,
189                    &size,
190                    inputString.c_str(),
191                    -1,
192                    &error);
193
194     if (error == U_ZERO_ERROR ||
195         error == U_BUFFER_OVERFLOW_ERROR)
196     {
197         // What buffer size is ok ?
198         LogPedantic("ICU: Output buffer size: " << size);
199     }
200     else
201     {
202         ThrowMsg(StringException::ICUInvalidCharacterFound,
203                  "ICU: Failed to retrieve output string size. Error: "
204                  << error);
205     }
206
207     // Allocate proper buffer
208     outputString.Reset(new UChar[size + 1]);
209     ::memset(outputString.Get(), 0, sizeof(UChar) * (size + 1));
210
211     error = U_ZERO_ERROR;
212
213     // Do conversion
214     ::u_strFromWCS(outputString.Get(),
215                    size + 1,
216                    &convertedSize,
217                    inputString.c_str(),
218                    -1,
219                    &error);
220
221     if (!U_SUCCESS(error))
222     {
223         ThrowMsg(StringException::ICUInvalidCharacterFound,
224                  "ICU: Failed to convert string. Error: " << error);
225     }
226
227     // Done
228     return outputString.Release();
229 }
230
231 int StringCompare(const String &left,
232                   const String &right,
233                   bool caseInsensitive)
234 {
235     // Convert input strings
236     ScopedArray<UChar> leftICU(ConvertToICU(left));
237     ScopedArray<UChar> rightICU(ConvertToICU(right));
238
239     if (caseInsensitive)
240     {
241         return static_cast<int>(u_strcasecmp(leftICU.Get(), rightICU.Get(), 0));
242     }
243     else
244     {
245         return static_cast<int>(u_strcmp(leftICU.Get(), rightICU.Get()));
246     }
247 }
248 } //namespace DPL
249
250 std::ostream& operator<<(std::ostream& aStream, const DPL::String& aString)
251 {
252     return aStream << DPL::ToUTF8String(aString);
253 }