summaryrefslogtreecommitdiff
path: root/src/dpl/core/src/string.cpp
blob: 7c8223dc1ab0106b1f7d670037fe8ba4ef0a5558 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*
 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
/*
 * @file        string.cpp
 * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
 * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
 * @version     1.0
 */
#include <stddef.h>
#include <string>
#include <vector>
#include <algorithm>
#include <cstring>
#include <errno.h>
#include <iconv.h>
#include <unicode/ustring.h>

#include <cchecker/dpl/string.h>
#include <cchecker/dpl/char_traits.h>
#include <cchecker/dpl/errno_string.h>
#include <cchecker/dpl/exception.h>
#include <cchecker/dpl/scoped_array.h>
#include "common/log.h"

// TODO: Completely move to ICU
namespace CCHECKER {
namespace //anonymous
{
class ASCIIValidator
{
    const std::string& m_TestedString;

  public:
    ASCIIValidator(const std::string& aTestedString);

    void operator()(signed char aCharacter) const;
};

ASCIIValidator::ASCIIValidator(const std::string& aTestedString) :
    m_TestedString(aTestedString)
{}

void ASCIIValidator::operator()(signed char aCharacter) const
{
    // Check for ASCII data range
    if (aCharacter <= 0) {
        ThrowMsg(
            StringException::InvalidASCIICharacter,
            "invalid character code " << static_cast<int>(aCharacter)
                                      << " from string [" <<
            m_TestedString
                                      << "] passed as ASCII");
    }
}

const iconv_t gc_IconvOperError = reinterpret_cast<iconv_t>(-1);
const size_t gc_IconvConvertError = static_cast<size_t>(-1);
} // namespace anonymous

String FromUTF8String(const std::string& aIn)
{
    if (aIn.empty()) {
        return String();
    }

    size_t inbytes = aIn.size();

    // Default iconv UTF-32 module adds BOM (4 bytes) in from of string
    // The worst case is when 8bit UTF-8 char converts to 32bit UTF-32
    // newsize = oldsize * 4 + end + bom
    // newsize - bytes for UTF-32 string
    // oldsize - letters in UTF-8 string
    // end - end character for UTF-32 (\0)
    // bom - Unicode header in front of string (0xfeff)
    size_t outbytes = sizeof(wchar_t) * (inbytes + 2);
    std::vector<wchar_t> output(inbytes + 2, 0);

    size_t outbytesleft = outbytes;
    char* inbuf = const_cast<char*>(aIn.c_str());

    // vector is used to provide buffer for iconv which expects char* buffer
    // but during conversion from UTF32 uses internaly wchar_t
    char* outbuf = reinterpret_cast<char*>(&output[0]);

    iconv_t iconvHandle = iconv_open("UTF-32", "UTF-8");

    if (gc_IconvOperError == iconvHandle) {
        int error = errno;

        ThrowMsg(StringException::IconvInitErrorUTF8ToUTF32,
                 "iconv_open failed for " << "UTF-32 <- UTF-8" <<
                 "error: " << GetErrnoString(error));
    }

    size_t iconvRet = iconv(iconvHandle,
                            &inbuf,
                            &inbytes,
                            &outbuf,
                            &outbytesleft);

    iconv_close(iconvHandle);

    if (gc_IconvConvertError == iconvRet) {
        ThrowMsg(StringException::IconvConvertErrorUTF8ToUTF32,
                 "iconv failed for " << "UTF-32 <- UTF-8" << "error: "
                                     << GetErrnoString());
    }

    // Ignore BOM in front of UTF-32
    return &output[1];
}

std::string ToUTF8String(const CCHECKER::String& aIn)
{
    if (aIn.empty()) {
        return std::string();
    }

    size_t inbytes = aIn.size() * sizeof(wchar_t);
    size_t outbytes = inbytes + sizeof(char);

    // wstring returns wchar_t but iconv expects char*
    // iconv internally is processing input as wchar_t
    char* inbuf = reinterpret_cast<char*>(const_cast<wchar_t*>(aIn.c_str()));
    std::vector<char> output(inbytes, 0);
    char* outbuf = &output[0];

    size_t outbytesleft = outbytes;

    iconv_t iconvHandle = iconv_open("UTF-8", "UTF-32");

    if (gc_IconvOperError == iconvHandle) {
        ThrowMsg(StringException::IconvInitErrorUTF32ToUTF8,
                 "iconv_open failed for " << "UTF-8 <- UTF-32"
                                          << "error: " << GetErrnoString());
    }

    size_t iconvRet = iconv(iconvHandle,
                            &inbuf,
                            &inbytes,
                            &outbuf,
                            &outbytesleft);

    iconv_close(iconvHandle);

    if (gc_IconvConvertError == iconvRet) {
        ThrowMsg(StringException::IconvConvertErrorUTF32ToUTF8,
                 "iconv failed for " << "UTF-8 <- UTF-32"
                                     << "error: " << GetErrnoString());
    }

    return &output[0];
}

String FromASCIIString(const std::string& aString)
{
    String output;

    std::for_each(aString.begin(), aString.end(), ASCIIValidator(aString));
    std::copy(aString.begin(), aString.end(), std::back_inserter<String>(output));

    return output;
}

String FromUTF32String(const std::wstring& aString)
{
    return String(&aString[0]);
}

static UChar *ConvertToICU(const String &inputString)
{
    ScopedArray<UChar> outputString;
    int32_t size = 0;
    int32_t convertedSize = 0;
    UErrorCode error = U_ZERO_ERROR;

    // Calculate size of output string
    ::u_strFromWCS(NULL,
                   0,
                   &size,
                   inputString.c_str(),
                   -1,
                   &error);

    if (error == U_ZERO_ERROR ||
        error == U_BUFFER_OVERFLOW_ERROR)
    {
        // What buffer size is ok ?
        LogDebug("ICU: Output buffer size: " << size);
    } else {
        ThrowMsg(StringException::ICUInvalidCharacterFound,
                 "ICU: Failed to retrieve output string size. Error: "
                 << error);
    }

    // Allocate proper buffer
    outputString.Reset(new UChar[size + 1]);
    ::memset(outputString.Get(), 0, sizeof(UChar) * (size + 1));

    error = U_ZERO_ERROR;

    // Do conversion
    ::u_strFromWCS(outputString.Get(),
                   size + 1,
                   &convertedSize,
                   inputString.c_str(),
                   -1,
                   &error);

    if (!U_SUCCESS(error)) {
        ThrowMsg(StringException::ICUInvalidCharacterFound,
                 "ICU: Failed to convert string. Error: " << error);
    }

    // Done
    return outputString.Release();
}

int StringCompare(const String &left,
                  const String &right,
                  bool caseInsensitive)
{
    // Convert input strings
    ScopedArray<UChar> leftICU(ConvertToICU(left));
    ScopedArray<UChar> rightICU(ConvertToICU(right));

    if (caseInsensitive) {
        return static_cast<int>(u_strcasecmp(leftICU.Get(), rightICU.Get(), 0));
    } else {
        return static_cast<int>(u_strcmp(leftICU.Get(), rightICU.Get()));
    }
}
} //namespace CCHECKER

std::ostream& operator<<(std::ostream& aStream, const CCHECKER::String& aString)
{
    return aStream << CCHECKER::ToUTF8String(aString);
}