Line data Source code
1 : ///////////////////////////////////////////////////////////////////////////////
2 : //
3 : // Project: C++ Test Suite for GDAL/OGR
4 : // Purpose: Test general CPL features.
5 : // Author: Mateusz Loskot <mateusz@loskot.net>
6 : //
7 : ///////////////////////////////////////////////////////////////////////////////
8 : // Copyright (c) 2006, Mateusz Loskot <mateusz@loskot.net>
9 : // Copyright (c) 2008-2012, Even Rouault <even dot rouault at spatialys.com>
10 : // Copyright (c) 2017, Dmitry Baryshnikov <polimax@mail.ru>
11 : // Copyright (c) 2017, NextGIS <info@nextgis.com>
12 : /*
13 : * SPDX-License-Identifier: MIT
14 : ****************************************************************************/
15 :
16 : #ifndef GDAL_COMPILATION
17 : #define GDAL_COMPILATION
18 : #endif
19 :
20 : #include "gdal_unit_test.h"
21 :
22 : #include "cpl_compressor.h"
23 : #include "cpl_enumerate.h"
24 : #include "cpl_error.h"
25 : #include "cpl_error_internal.h"
26 : #include "cpl_float.h"
27 : #include "cpl_hash_set.h"
28 : #include "cpl_levenshtein.h"
29 : #include "cpl_list.h"
30 : #include "cpl_mask.h"
31 : #include "cpl_sha256.h"
32 : #include "cpl_string.h"
33 : #include "cpl_safemaths.hpp"
34 : #include "cpl_time.h"
35 : #include "cpl_json.h"
36 : #include "cpl_json_streaming_parser.h"
37 : #include "cpl_json_streaming_writer.h"
38 : #include "cpl_mem_cache.h"
39 : #include "cpl_http.h"
40 : #include "cpl_auto_close.h"
41 : #include "cpl_minixml.h"
42 : #include "cpl_quad_tree.h"
43 : #include "cpl_spawn.h"
44 : #include "cpl_worker_thread_pool.h"
45 : #include "cpl_vsi_virtual.h"
46 : #include "cpl_threadsafe_queue.hpp"
47 :
48 : #include <algorithm>
49 : #include <atomic>
50 : #include <charconv>
51 : #include <cmath>
52 : #include <limits>
53 : #include <fstream>
54 : #include <string>
55 :
56 : #if !defined(_WIN32)
57 : #include <unistd.h>
58 : #endif
59 :
60 : #include "test_data.h"
61 :
62 : #include "gtest_include.h"
63 :
64 : static bool gbGotError = false;
65 :
66 2 : static void CPL_STDCALL myErrorHandler(CPLErr, CPLErrorNum, const char *)
67 : {
68 2 : gbGotError = true;
69 2 : }
70 :
71 : namespace
72 : {
73 :
74 : // Common fixture with test data
75 : struct test_cpl : public ::testing::Test
76 : {
77 : std::string data_;
78 :
79 110 : test_cpl()
80 110 : {
81 : // Compose data path for test group
82 110 : data_ = tut::common::data_basedir;
83 110 : }
84 :
85 110 : void SetUp() override
86 : {
87 110 : CPLSetConfigOptions(nullptr);
88 110 : CPLSetThreadLocalConfigOptions(nullptr);
89 110 : }
90 : };
91 :
92 : // Test cpl_list API
93 4 : TEST_F(test_cpl, CPLList)
94 : {
95 : CPLList *list;
96 :
97 1 : list = CPLListInsert(nullptr, (void *)nullptr, 0);
98 1 : EXPECT_TRUE(CPLListCount(list) == 1);
99 1 : list = CPLListRemove(list, 2);
100 1 : EXPECT_TRUE(CPLListCount(list) == 1);
101 1 : list = CPLListRemove(list, 1);
102 1 : EXPECT_TRUE(CPLListCount(list) == 1);
103 1 : list = CPLListRemove(list, 0);
104 1 : EXPECT_TRUE(CPLListCount(list) == 0);
105 1 : list = nullptr;
106 :
107 1 : list = CPLListInsert(nullptr, (void *)nullptr, 2);
108 1 : EXPECT_TRUE(CPLListCount(list) == 3);
109 1 : list = CPLListRemove(list, 2);
110 1 : EXPECT_TRUE(CPLListCount(list) == 2);
111 1 : list = CPLListRemove(list, 1);
112 1 : EXPECT_TRUE(CPLListCount(list) == 1);
113 1 : list = CPLListRemove(list, 0);
114 1 : EXPECT_TRUE(CPLListCount(list) == 0);
115 1 : list = nullptr;
116 :
117 1 : list = CPLListAppend(list, (void *)1);
118 1 : EXPECT_TRUE(CPLListGet(list, 0) == list);
119 1 : EXPECT_TRUE(CPLListGet(list, 1) == nullptr);
120 1 : list = CPLListAppend(list, (void *)2);
121 1 : list = CPLListInsert(list, (void *)3, 2);
122 1 : EXPECT_TRUE(CPLListCount(list) == 3);
123 1 : CPLListDestroy(list);
124 1 : list = nullptr;
125 :
126 1 : list = CPLListAppend(list, (void *)1);
127 1 : list = CPLListAppend(list, (void *)2);
128 1 : list = CPLListInsert(list, (void *)4, 3);
129 1 : CPLListGet(list, 2)->pData = (void *)3;
130 1 : EXPECT_TRUE(CPLListCount(list) == 4);
131 1 : EXPECT_TRUE(CPLListGet(list, 0)->pData == (void *)1);
132 1 : EXPECT_TRUE(CPLListGet(list, 1)->pData == (void *)2);
133 1 : EXPECT_TRUE(CPLListGet(list, 2)->pData == (void *)3);
134 1 : EXPECT_TRUE(CPLListGet(list, 3)->pData == (void *)4);
135 1 : CPLListDestroy(list);
136 1 : list = nullptr;
137 :
138 1 : list = CPLListInsert(list, (void *)4, 1);
139 1 : CPLListGet(list, 0)->pData = (void *)2;
140 1 : list = CPLListInsert(list, (void *)1, 0);
141 1 : list = CPLListInsert(list, (void *)3, 2);
142 1 : EXPECT_TRUE(CPLListCount(list) == 4);
143 1 : EXPECT_TRUE(CPLListGet(list, 0)->pData == (void *)1);
144 1 : EXPECT_TRUE(CPLListGet(list, 1)->pData == (void *)2);
145 1 : EXPECT_TRUE(CPLListGet(list, 2)->pData == (void *)3);
146 1 : EXPECT_TRUE(CPLListGet(list, 3)->pData == (void *)4);
147 1 : list = CPLListRemove(list, 1);
148 1 : list = CPLListRemove(list, 1);
149 1 : list = CPLListRemove(list, 0);
150 1 : list = CPLListRemove(list, 0);
151 1 : EXPECT_TRUE(list == nullptr);
152 1 : }
153 :
154 : typedef struct
155 : {
156 : const char *testString;
157 : CPLValueType expectedResult;
158 : } TestStringStruct;
159 :
160 : // Test CPLGetValueType
161 4 : TEST_F(test_cpl, CPLGetValueType)
162 : {
163 1 : TestStringStruct asTestStrings[] = {
164 : {"+25.e+3", CPL_VALUE_REAL}, {"-25.e-3", CPL_VALUE_REAL},
165 : {"25.e3", CPL_VALUE_REAL}, {"25e3", CPL_VALUE_REAL},
166 : {" 25e3 ", CPL_VALUE_REAL}, {".1e3", CPL_VALUE_REAL},
167 :
168 : {"25", CPL_VALUE_INTEGER}, {"-25", CPL_VALUE_INTEGER},
169 : {"+25", CPL_VALUE_INTEGER},
170 :
171 : {"25e 3", CPL_VALUE_STRING}, {"25e.3", CPL_VALUE_STRING},
172 : {"-2-5e3", CPL_VALUE_STRING}, {"2-5e3", CPL_VALUE_STRING},
173 : {"25.25.3", CPL_VALUE_STRING}, {"25e25e3", CPL_VALUE_STRING},
174 : {"25e2500", CPL_VALUE_STRING}, /* #6128 */
175 :
176 : {"d1", CPL_VALUE_STRING}, /* #6305 */
177 :
178 : {"01", CPL_VALUE_STRING}, {"0.1", CPL_VALUE_REAL},
179 : {"0", CPL_VALUE_INTEGER},
180 : };
181 :
182 21 : for (const auto &sText : asTestStrings)
183 : {
184 20 : EXPECT_EQ(CPLGetValueType(sText.testString), sText.expectedResult)
185 0 : << sText.testString;
186 : }
187 1 : }
188 :
189 : // Test cpl_hash_set API
190 4 : TEST_F(test_cpl, CPLHashSet)
191 : {
192 : CPLHashSet *set =
193 1 : CPLHashSetNew(CPLHashSetHashStr, CPLHashSetEqualStr, CPLFree);
194 1 : EXPECT_TRUE(CPLHashSetInsert(set, CPLStrdup("hello")) == TRUE);
195 1 : EXPECT_TRUE(CPLHashSetInsert(set, CPLStrdup("good morning")) == TRUE);
196 1 : EXPECT_TRUE(CPLHashSetInsert(set, CPLStrdup("bye bye")) == TRUE);
197 1 : EXPECT_TRUE(CPLHashSetSize(set) == 3);
198 1 : EXPECT_TRUE(CPLHashSetInsert(set, CPLStrdup("bye bye")) == FALSE);
199 1 : EXPECT_TRUE(CPLHashSetSize(set) == 3);
200 1 : EXPECT_TRUE(CPLHashSetRemove(set, "bye bye") == TRUE);
201 1 : EXPECT_TRUE(CPLHashSetSize(set) == 2);
202 1 : EXPECT_TRUE(CPLHashSetRemove(set, "good afternoon") == FALSE);
203 1 : EXPECT_TRUE(CPLHashSetSize(set) == 2);
204 1 : CPLHashSetDestroy(set);
205 1 : }
206 :
207 1000 : static int sumValues(void *elt, void *user_data)
208 : {
209 1000 : int *pnSum = (int *)user_data;
210 1000 : *pnSum += *(int *)elt;
211 1000 : return TRUE;
212 : }
213 :
214 : // Test cpl_hash_set API
215 4 : TEST_F(test_cpl, CPLHashSet2)
216 : {
217 1 : const int HASH_SET_SIZE = 1000;
218 :
219 : int data[HASH_SET_SIZE];
220 1001 : for (int i = 0; i < HASH_SET_SIZE; ++i)
221 : {
222 1000 : data[i] = i;
223 : }
224 :
225 1 : CPLHashSet *set = CPLHashSetNew(nullptr, nullptr, nullptr);
226 1001 : for (int i = 0; i < HASH_SET_SIZE; i++)
227 : {
228 1000 : EXPECT_TRUE(CPLHashSetInsert(set, (void *)&data[i]) == TRUE);
229 : }
230 1 : EXPECT_EQ(CPLHashSetSize(set), HASH_SET_SIZE);
231 :
232 1001 : for (int i = 0; i < HASH_SET_SIZE; i++)
233 : {
234 1000 : EXPECT_TRUE(CPLHashSetInsert(set, (void *)&data[i]) == FALSE);
235 : }
236 1 : EXPECT_EQ(CPLHashSetSize(set), HASH_SET_SIZE);
237 :
238 1001 : for (int i = 0; i < HASH_SET_SIZE; i++)
239 : {
240 1000 : EXPECT_TRUE(CPLHashSetLookup(set, (const void *)&data[i]) ==
241 : (const void *)&data[i]);
242 : }
243 :
244 1 : int sum = 0;
245 1 : CPLHashSetForeach(set, sumValues, &sum);
246 1 : EXPECT_EQ(sum, (HASH_SET_SIZE - 1) * HASH_SET_SIZE / 2);
247 :
248 1001 : for (int i = 0; i < HASH_SET_SIZE; i++)
249 : {
250 1000 : EXPECT_TRUE(CPLHashSetRemove(set, (void *)&data[i]) == TRUE);
251 : }
252 1 : EXPECT_EQ(CPLHashSetSize(set), 0);
253 :
254 1 : CPLHashSetDestroy(set);
255 1 : }
256 :
257 : // Test cpl_string API
258 4 : TEST_F(test_cpl, CSLTokenizeString2)
259 : {
260 : {
261 : CPLStringList aosStringList(
262 1 : CSLTokenizeString2("one two three", " ", 0));
263 1 : ASSERT_EQ(aosStringList.size(), 3);
264 1 : EXPECT_STREQ(aosStringList[0], "one");
265 1 : EXPECT_STREQ(aosStringList[1], "two");
266 1 : EXPECT_STREQ(aosStringList[2], "three");
267 :
268 : // Test range-based for loop
269 1 : int i = 0;
270 4 : for (const char *pszVal : aosStringList)
271 : {
272 3 : EXPECT_STREQ(pszVal, aosStringList[i]);
273 3 : ++i;
274 : }
275 1 : EXPECT_EQ(i, 3);
276 : }
277 : {
278 2 : CPLStringList aosStringList;
279 : // Test range-based for loop on empty list
280 1 : int i = 0;
281 1 : for (const char *pszVal : aosStringList)
282 : {
283 0 : EXPECT_EQ(pszVal, nullptr); // should not reach that point...
284 0 : ++i;
285 : }
286 1 : EXPECT_EQ(i, 0);
287 : }
288 : {
289 : CPLStringList aosStringList(
290 1 : CSLTokenizeString2(",one two, three;four,five; six,", " ;,", 0));
291 1 : ASSERT_EQ(aosStringList.size(), 6);
292 1 : EXPECT_STREQ(aosStringList[0], "one");
293 1 : EXPECT_STREQ(aosStringList[1], "two");
294 1 : EXPECT_STREQ(aosStringList[2], "three");
295 1 : EXPECT_STREQ(aosStringList[3], "four");
296 1 : EXPECT_STREQ(aosStringList[4], "five");
297 1 : EXPECT_STREQ(aosStringList[5], "six");
298 : }
299 :
300 : {
301 : CPLStringList aosStringList(CSLTokenizeString2(
302 1 : ",one two,,,five,six,", " ,", CSLT_ALLOWEMPTYTOKENS));
303 1 : ASSERT_EQ(aosStringList.size(), 8);
304 1 : EXPECT_STREQ(aosStringList[0], "");
305 1 : EXPECT_STREQ(aosStringList[1], "one");
306 1 : EXPECT_STREQ(aosStringList[2], "two");
307 1 : EXPECT_STREQ(aosStringList[3], "");
308 1 : EXPECT_STREQ(aosStringList[4], "");
309 1 : EXPECT_STREQ(aosStringList[5], "five");
310 1 : EXPECT_STREQ(aosStringList[6], "six");
311 1 : EXPECT_STREQ(aosStringList[7], "");
312 : }
313 :
314 : {
315 : CPLStringList aosStringList(CSLTokenizeString2(
316 1 : "one two,\"three,four ,\",five,six", " ,", CSLT_HONOURSTRINGS));
317 1 : ASSERT_EQ(aosStringList.size(), 5);
318 1 : EXPECT_STREQ(aosStringList[0], "one");
319 1 : EXPECT_STREQ(aosStringList[1], "two");
320 1 : EXPECT_STREQ(aosStringList[2], "three,four ,");
321 1 : EXPECT_STREQ(aosStringList[3], "five");
322 1 : EXPECT_STREQ(aosStringList[4], "six");
323 : }
324 :
325 : {
326 : CPLStringList aosStringList(CSLTokenizeString2(
327 1 : "one two,\"three,four ,\",five,six", " ,", CSLT_PRESERVEQUOTES));
328 1 : ASSERT_EQ(aosStringList.size(), 7);
329 1 : EXPECT_STREQ(aosStringList[0], "one");
330 1 : EXPECT_STREQ(aosStringList[1], "two");
331 1 : EXPECT_STREQ(aosStringList[2], "\"three");
332 1 : EXPECT_STREQ(aosStringList[3], "four");
333 1 : EXPECT_STREQ(aosStringList[4], "\"");
334 1 : EXPECT_STREQ(aosStringList[5], "five");
335 1 : EXPECT_STREQ(aosStringList[6], "six");
336 : }
337 :
338 : {
339 : CPLStringList aosStringList(
340 : CSLTokenizeString2("one two,\"three,four ,\",five,six", " ,",
341 1 : CSLT_HONOURSTRINGS | CSLT_PRESERVEQUOTES));
342 1 : ASSERT_EQ(aosStringList.size(), 5);
343 1 : EXPECT_STREQ(aosStringList[0], "one");
344 1 : EXPECT_STREQ(aosStringList[1], "two");
345 1 : EXPECT_STREQ(aosStringList[2], "\"three,four ,\"");
346 1 : EXPECT_STREQ(aosStringList[3], "five");
347 1 : EXPECT_STREQ(aosStringList[4], "six");
348 : }
349 :
350 : {
351 : CPLStringList aosStringList(
352 : CSLTokenizeString2("one \\two,\"three,\\four ,\",five,six", " ,",
353 1 : CSLT_PRESERVEESCAPES));
354 1 : ASSERT_EQ(aosStringList.size(), 7);
355 1 : EXPECT_STREQ(aosStringList[0], "one");
356 1 : EXPECT_STREQ(aosStringList[1], "\\two");
357 1 : EXPECT_STREQ(aosStringList[2], "\"three");
358 1 : EXPECT_STREQ(aosStringList[3], "\\four");
359 1 : EXPECT_STREQ(aosStringList[4], "\"");
360 1 : EXPECT_STREQ(aosStringList[5], "five");
361 1 : EXPECT_STREQ(aosStringList[6], "six");
362 : }
363 :
364 : {
365 : CPLStringList aosStringList(
366 : CSLTokenizeString2("one \\two,\"three,\\four ,\",five,six", " ,",
367 1 : CSLT_PRESERVEQUOTES | CSLT_PRESERVEESCAPES));
368 1 : ASSERT_EQ(aosStringList.size(), 7);
369 1 : EXPECT_STREQ(aosStringList[0], "one");
370 1 : EXPECT_STREQ(aosStringList[1], "\\two");
371 1 : EXPECT_STREQ(aosStringList[2], "\"three");
372 1 : EXPECT_STREQ(aosStringList[3], "\\four");
373 1 : EXPECT_STREQ(aosStringList[4], "\"");
374 1 : EXPECT_STREQ(aosStringList[5], "five");
375 1 : EXPECT_STREQ(aosStringList[6], "six");
376 : }
377 :
378 : {
379 : CPLStringList aosStringList(
380 1 : CSLTokenizeString2("one ,two, three, four ,five ", ",", 0));
381 1 : ASSERT_EQ(aosStringList.size(), 5);
382 1 : EXPECT_STREQ(aosStringList[0], "one ");
383 1 : EXPECT_STREQ(aosStringList[1], "two");
384 1 : EXPECT_STREQ(aosStringList[2], " three");
385 1 : EXPECT_STREQ(aosStringList[3], " four ");
386 1 : EXPECT_STREQ(aosStringList[4], "five ");
387 : }
388 :
389 : {
390 : CPLStringList aosStringList(CSLTokenizeString2(
391 1 : "one ,two, three, four ,five ", ",", CSLT_STRIPLEADSPACES));
392 1 : ASSERT_EQ(aosStringList.size(), 5);
393 1 : EXPECT_STREQ(aosStringList[0], "one ");
394 1 : EXPECT_STREQ(aosStringList[1], "two");
395 1 : EXPECT_STREQ(aosStringList[2], "three");
396 1 : EXPECT_STREQ(aosStringList[3], "four ");
397 1 : EXPECT_STREQ(aosStringList[4], "five ");
398 : }
399 :
400 : {
401 : CPLStringList aosStringList(CSLTokenizeString2(
402 1 : "one ,two, three, four ,five ", ",", CSLT_STRIPENDSPACES));
403 1 : ASSERT_EQ(aosStringList.size(), 5);
404 1 : EXPECT_STREQ(aosStringList[0], "one");
405 1 : EXPECT_STREQ(aosStringList[1], "two");
406 1 : EXPECT_STREQ(aosStringList[2], " three");
407 1 : EXPECT_STREQ(aosStringList[3], " four");
408 1 : EXPECT_STREQ(aosStringList[4], "five");
409 : }
410 :
411 : {
412 : CPLStringList aosStringList(
413 : CSLTokenizeString2("one ,two, three, four ,five ", ",",
414 1 : CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
415 1 : ASSERT_EQ(aosStringList.size(), 5);
416 1 : EXPECT_STREQ(aosStringList[0], "one");
417 1 : EXPECT_STREQ(aosStringList[1], "two");
418 1 : EXPECT_STREQ(aosStringList[2], "three");
419 1 : EXPECT_STREQ(aosStringList[3], "four");
420 1 : EXPECT_STREQ(aosStringList[4], "five");
421 : }
422 :
423 : {
424 5 : const std::vector<std::string> oVector{"a", "bc"};
425 : // Test CPLStringList(const std::vector<std::string>&) constructor
426 1 : const CPLStringList aosList(oVector);
427 1 : ASSERT_EQ(aosList.size(), 2);
428 1 : EXPECT_STREQ(aosList[0], "a");
429 1 : EXPECT_STREQ(aosList[1], "bc");
430 1 : EXPECT_EQ(aosList[2], nullptr);
431 :
432 : // Test CPLStringList::operator std::vector<std::string>(void) const
433 2 : const std::vector<std::string> oVector2(aosList);
434 1 : EXPECT_EQ(oVector, oVector2);
435 :
436 2 : EXPECT_EQ(oVector, cpl::ToVector(aosList.List()));
437 : }
438 :
439 : {
440 2 : const CPLStringList aosList(std::vector<std::string>{});
441 1 : EXPECT_EQ(aosList.List(), nullptr);
442 : }
443 :
444 : {
445 : // Test CPLStringList(std::initializer_list<const char*>) constructor
446 1 : const CPLStringList aosList{"a", "bc"};
447 1 : ASSERT_EQ(aosList.size(), 2);
448 1 : EXPECT_STREQ(aosList[0], "a");
449 1 : EXPECT_STREQ(aosList[1], "bc");
450 1 : EXPECT_EQ(aosList[2], nullptr);
451 :
452 : // Test cpl::Iterate(CSLConstList)
453 1 : CSLConstList papszList = aosList.List();
454 1 : CPLStringList aosList2;
455 3 : for (const char *pszStr : cpl::Iterate(papszList))
456 : {
457 2 : aosList2.AddString(pszStr);
458 : }
459 1 : ASSERT_EQ(aosList2.size(), 2);
460 1 : EXPECT_STREQ(aosList2[0], "a");
461 1 : EXPECT_STREQ(aosList2[1], "bc");
462 1 : EXPECT_EQ(aosList2[2], nullptr);
463 : }
464 :
465 : {
466 : // Test cpl::Iterate() on a null list
467 1 : CSLConstList papszList = nullptr;
468 1 : auto oIteratorWrapper = cpl::Iterate(papszList);
469 1 : EXPECT_TRUE(oIteratorWrapper.begin() == oIteratorWrapper.end());
470 : }
471 :
472 : {
473 : // Test cpl::IterateNameValue()
474 1 : const CPLStringList aosList{"foo=bar", "illegal", "bar=baz"};
475 1 : CSLConstList papszList = aosList.List();
476 1 : std::map<std::string, std::string> oMap;
477 3 : for (const auto &[name, value] : cpl::IterateNameValue(papszList))
478 : {
479 2 : oMap[name] = value;
480 : }
481 1 : ASSERT_EQ(oMap.size(), 2U);
482 2 : EXPECT_EQ(oMap["foo"], "bar");
483 2 : EXPECT_EQ(oMap["bar"], "baz");
484 : }
485 :
486 : {
487 : // Test cpl::IterateNameValue() on a list with only invalid values
488 2 : const CPLStringList aosList{"illegal"};
489 1 : CSLConstList papszList = aosList.List();
490 1 : auto oIteratorWrapper = cpl::IterateNameValue(papszList);
491 1 : EXPECT_TRUE(oIteratorWrapper.begin() == oIteratorWrapper.end());
492 : }
493 :
494 : {
495 : // Test cpl::IterateNameValue() on a null list
496 1 : CSLConstList papszList = nullptr;
497 1 : auto oIteratorWrapper = cpl::IterateNameValue(papszList);
498 1 : EXPECT_TRUE(oIteratorWrapper.begin() == oIteratorWrapper.end());
499 : }
500 :
501 : {
502 : // Test colon separator within string tokens
503 : CPLStringList aosList(CSLTokenizeString2(
504 : R"(one:"two:two_and_half":three:"four:four_and_half":five)", ":",
505 2 : CSLT_HONOURSTRINGS | CSLT_PRESERVEQUOTES));
506 1 : EXPECT_EQ(aosList.size(), 5);
507 1 : EXPECT_STREQ(aosList[0], "one");
508 1 : EXPECT_STREQ(aosList[1], "\"two:two_and_half\"");
509 1 : EXPECT_STREQ(aosList[2], "three");
510 1 : EXPECT_STREQ(aosList[3], "\"four:four_and_half\"");
511 1 : EXPECT_STREQ(aosList[4], "five");
512 : }
513 : }
514 :
515 : typedef struct
516 : {
517 : char szEncoding[24];
518 : char szString[1024 - 24];
519 : } TestRecodeStruct;
520 :
521 : // Test cpl_recode API
522 4 : TEST_F(test_cpl, CPLRecode)
523 : {
524 : /*
525 : * NOTE: This test will generally fail if iconv() is not
526 : * linked in.
527 : *
528 : * CPLRecode() will be tested using the test file containing
529 : * a list of strings of the same text in different encoding. The
530 : * string is non-ASCII to avoid trivial transformations. Test file
531 : * has a simple binary format: a table of records, each record
532 : * is 1024 bytes long. The first 24 bytes of each record contain
533 : * encoding name (ASCII, zero padded), the last 1000 bytes contain
534 : * encoded string, zero padded.
535 : *
536 : * NOTE 1: We can't use a test file in human readable text format
537 : * here because of multiple different encodings including
538 : * multibyte ones.
539 : *
540 : * The test file could be generated with the following simple shell
541 : * script:
542 : *
543 : * #!/bin/sh
544 : *
545 : * # List of encodings to convert the test string into
546 : * ENCODINGS="UTF-8 CP1251 KOI8-R UCS-2 UCS-2BE UCS-2LE UCS-4 UCS-4BE
547 : * UCS-4LE UTF-16 UTF-32" # The test string itself in UTF-8 encoding. # This
548 : * means "Improving GDAL internationalization." in Russian.
549 : * TESTSTRING="\u0423\u043b\u0443\u0447\u0448\u0430\u0435\u043c
550 : * \u0438\u043d\u0442\u0435\u0440\u043d\u0430\u0446\u0438\u043e\u043d\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044e
551 : * GDAL."
552 : *
553 : * RECORDSIZE=1024
554 : * ENCSIZE=24
555 : *
556 : * i=0
557 : * for enc in ${ENCODINGS}; do
558 : * env printf "${enc}" | dd ibs=${RECORDSIZE} conv=sync obs=1
559 : * seek=$((${RECORDSIZE}*${i})) of="recode-rus.dat" status=noxfer env printf
560 : * "${TESTSTRING}" | iconv -t ${enc} | dd ibs=${RECORDSIZE} conv=sync obs=1
561 : * seek=$((${RECORDSIZE}*${i}+${ENCSIZE})) of="recode-rus.dat" status=noxfer
562 : * i=$((i+1))
563 : * done
564 : *
565 : * NOTE 2: The test string is encoded with the special format
566 : * "\uXXXX" sequences, so we able to paste it here.
567 : *
568 : * NOTE 3: We need a printf utility from the coreutils because of
569 : * that. "env printf" should work avoiding the shell
570 : * built-in.
571 : *
572 : * NOTE 4: "iconv" utility without the "-f" option will work with
573 : * encoding read from the current locale.
574 : *
575 : * TODO: 1. Add more encodings maybe more test files.
576 : * 2. Add test for CPLRecodeFromWChar()/CPLRecodeToWChar().
577 : * 3. Test translation between each possible pair of
578 : * encodings in file, not only into the UTF-8.
579 : */
580 :
581 2 : std::ifstream fin((data_ + SEP + "recode-rus.dat").c_str(),
582 2 : std::ifstream::binary);
583 : TestRecodeStruct oReferenceString;
584 :
585 : // Read reference string (which is the first one in the file)
586 1 : fin.read(oReferenceString.szEncoding, sizeof(oReferenceString.szEncoding));
587 1 : oReferenceString.szEncoding[sizeof(oReferenceString.szEncoding) - 1] = '\0';
588 1 : fin.read(oReferenceString.szString, sizeof(oReferenceString.szString));
589 1 : oReferenceString.szString[sizeof(oReferenceString.szString) - 1] = '\0';
590 :
591 : while (true)
592 : {
593 : TestRecodeStruct oTestString;
594 :
595 11 : fin.read(oTestString.szEncoding, sizeof(oTestString.szEncoding));
596 11 : oTestString.szEncoding[sizeof(oTestString.szEncoding) - 1] = '\0';
597 11 : if (fin.eof())
598 1 : break;
599 10 : fin.read(oTestString.szString, sizeof(oTestString.szString));
600 10 : oTestString.szString[sizeof(oTestString.szString) - 1] = '\0';
601 :
602 : // Compare each string with the reference one
603 10 : CPLErrorReset();
604 : char *pszDecodedString =
605 10 : CPLRecode(oTestString.szString, oTestString.szEncoding,
606 : oReferenceString.szEncoding);
607 10 : if (strstr(CPLGetLastErrorMsg(),
608 20 : "Recode from CP1251 to UTF-8 not supported") != nullptr ||
609 10 : strstr(CPLGetLastErrorMsg(),
610 : "Recode from KOI8-R to UTF-8 not supported") != nullptr)
611 : {
612 0 : CPLFree(pszDecodedString);
613 0 : break;
614 : }
615 :
616 20 : size_t nLength = std::min(strlen(pszDecodedString),
617 10 : sizeof(oReferenceString.szEncoding));
618 10 : bool bOK =
619 10 : (memcmp(pszDecodedString, oReferenceString.szString, nLength) == 0);
620 : // FIXME Some tests fail on Mac. Not sure why, but do not error out just
621 : // for that
622 10 : if (!bOK &&
623 0 : (strstr(CPLGetConfigOption("TRAVIS_OS_NAME", ""), "osx") !=
624 0 : nullptr ||
625 0 : strstr(CPLGetConfigOption("BUILD_NAME", ""), "osx") != nullptr ||
626 0 : getenv("DO_NOT_FAIL_ON_RECODE_ERRORS") != nullptr))
627 : {
628 0 : fprintf(stderr, "Recode from %s failed\n", oTestString.szEncoding);
629 : }
630 : else
631 : {
632 : #ifdef CPL_MSB
633 : if (!bOK && strcmp(oTestString.szEncoding, "UCS-2") == 0)
634 : {
635 : // Presumably the content in the test file is UCS-2LE, but
636 : // there's no way to know the byte order without a BOM
637 : fprintf(stderr, "Recode from %s failed\n",
638 : oTestString.szEncoding);
639 : }
640 : else
641 : #endif
642 : {
643 10 : EXPECT_TRUE(bOK) << "Recode from " << oTestString.szEncoding;
644 : }
645 : }
646 10 : CPLFree(pszDecodedString);
647 10 : }
648 :
649 1 : fin.close();
650 1 : }
651 :
652 : /************************************************************************/
653 : /* CPLStringList tests */
654 : /************************************************************************/
655 4 : TEST_F(test_cpl, CPLStringList_Base)
656 : {
657 1 : CPLStringList oCSL;
658 :
659 1 : ASSERT_TRUE(oCSL.List() == nullptr);
660 :
661 1 : oCSL.AddString("def");
662 1 : oCSL.AddString("abc");
663 :
664 1 : ASSERT_EQ(oCSL.Count(), 2);
665 1 : ASSERT_TRUE(EQUAL(oCSL[0], "def"));
666 1 : ASSERT_TRUE(EQUAL(oCSL[1], "abc"));
667 1 : ASSERT_TRUE(oCSL[17] == nullptr);
668 1 : ASSERT_TRUE(oCSL[-1] == nullptr);
669 1 : ASSERT_EQ(oCSL.FindString("abc"), 1);
670 :
671 1 : oCSL.RemoveStrings(0, 1);
672 1 : ASSERT_EQ(oCSL.Count(), 1);
673 1 : ASSERT_EQ(oCSL.FindString("abc"), 0);
674 :
675 1 : CSLDestroy(oCSL.StealList());
676 1 : ASSERT_EQ(oCSL.Count(), 0);
677 1 : ASSERT_TRUE(oCSL.List() == nullptr);
678 :
679 : // Test that the list will make an internal copy when needed to
680 : // modify a read-only list.
681 :
682 1 : oCSL.AddString("def");
683 1 : oCSL.AddString("abc");
684 :
685 1 : CPLStringList oCopy(oCSL.List(), FALSE);
686 :
687 1 : ASSERT_EQ(oCSL.List(), oCopy.List());
688 1 : ASSERT_EQ(oCSL.Count(), oCopy.Count());
689 :
690 1 : oCopy.AddString("xyz");
691 1 : ASSERT_TRUE(oCSL.List() != oCopy.List());
692 1 : ASSERT_EQ(oCopy.Count(), 3);
693 1 : ASSERT_EQ(oCSL.Count(), 2);
694 1 : ASSERT_TRUE(EQUAL(oCopy[2], "xyz"));
695 : }
696 :
697 : // Test CSLRemoveStrings() with the special values of nFirstLineToDelete
698 : // documented as meaning "remove the nNumToRemove last strings".
699 4 : TEST_F(test_cpl, CSLRemoveStrings_last_strings)
700 : {
701 7 : const auto MakeList = []()
702 : {
703 7 : char **papszList = nullptr;
704 7 : papszList = CSLAddString(papszList, "aaaa");
705 7 : papszList = CSLAddString(papszList, "bbbb");
706 7 : papszList = CSLAddString(papszList, "cccc");
707 7 : papszList = CSLAddString(papszList, "dddd");
708 7 : return papszList;
709 : };
710 :
711 : // nFirstLineToDelete == -1, discarding the removed strings.
712 : {
713 1 : char **papszList = MakeList();
714 1 : papszList = CSLRemoveStrings(papszList, -1, 2, nullptr);
715 1 : EXPECT_EQ(CSLCount(papszList), 2);
716 1 : if (CSLCount(papszList) == 2)
717 : {
718 1 : EXPECT_STREQ(papszList[0], "aaaa");
719 1 : EXPECT_STREQ(papszList[1], "bbbb");
720 : }
721 1 : CSLDestroy(papszList);
722 : }
723 :
724 : // nFirstLineToDelete == -1, retrieving the removed strings.
725 : {
726 1 : char **papszList = MakeList();
727 1 : char **papszRemoved = nullptr;
728 1 : papszList = CSLRemoveStrings(papszList, -1, 2, &papszRemoved);
729 1 : EXPECT_EQ(CSLCount(papszList), 2);
730 1 : if (CSLCount(papszList) == 2)
731 : {
732 1 : EXPECT_STREQ(papszList[0], "aaaa");
733 1 : EXPECT_STREQ(papszList[1], "bbbb");
734 : }
735 1 : EXPECT_EQ(CSLCount(papszRemoved), 2);
736 1 : if (CSLCount(papszRemoved) == 2)
737 : {
738 1 : EXPECT_STREQ(papszRemoved[0], "cccc");
739 1 : EXPECT_STREQ(papszRemoved[1], "dddd");
740 : }
741 1 : CSLDestroy(papszRemoved);
742 1 : CSLDestroy(papszList);
743 : }
744 :
745 : // nFirstLineToDelete larger than the number of strings.
746 : {
747 1 : char **papszList = MakeList();
748 1 : papszList = CSLRemoveStrings(papszList, 100, 2, nullptr);
749 1 : EXPECT_EQ(CSLCount(papszList), 2);
750 1 : if (CSLCount(papszList) == 2)
751 : {
752 1 : EXPECT_STREQ(papszList[0], "aaaa");
753 1 : EXPECT_STREQ(papszList[1], "bbbb");
754 : }
755 1 : CSLDestroy(papszList);
756 : }
757 :
758 : // nFirstLineToDelete equal to the number of strings: the range to remove
759 : // would extend past the end of the list.
760 : {
761 1 : char **papszList = MakeList();
762 1 : papszList = CSLRemoveStrings(papszList, 4, 1, nullptr);
763 1 : EXPECT_EQ(CSLCount(papszList), 3);
764 1 : if (CSLCount(papszList) == 3)
765 : {
766 1 : EXPECT_STREQ(papszList[0], "aaaa");
767 1 : EXPECT_STREQ(papszList[2], "cccc");
768 : }
769 1 : CSLDestroy(papszList);
770 : }
771 :
772 : // Valid nFirstLineToDelete, but nNumToRemove makes the range overrun the
773 : // end of the list by one.
774 : {
775 1 : char **papszList = MakeList();
776 1 : papszList = CSLRemoveStrings(papszList, 3, 2, nullptr);
777 1 : EXPECT_EQ(CSLCount(papszList), 2);
778 1 : if (CSLCount(papszList) == 2)
779 : {
780 1 : EXPECT_STREQ(papszList[0], "aaaa");
781 1 : EXPECT_STREQ(papszList[1], "bbbb");
782 : }
783 1 : CSLDestroy(papszList);
784 : }
785 :
786 : // Removing from a well defined offset must be unaffected. Note that all
787 : // the removed strings must be freed, which ASAN/valgrind builds check.
788 : {
789 1 : char **papszList = MakeList();
790 1 : papszList = CSLRemoveStrings(papszList, 1, 2, nullptr);
791 1 : EXPECT_EQ(CSLCount(papszList), 2);
792 1 : if (CSLCount(papszList) == 2)
793 : {
794 1 : EXPECT_STREQ(papszList[0], "aaaa");
795 1 : EXPECT_STREQ(papszList[1], "dddd");
796 : }
797 1 : CSLDestroy(papszList);
798 : }
799 :
800 : // Same special values through the CPLStringList wrapper.
801 : {
802 1 : CPLStringList oCSL(MakeList());
803 1 : oCSL.RemoveStrings(-1, 2);
804 1 : ASSERT_EQ(oCSL.size(), 2);
805 1 : EXPECT_STREQ(oCSL[0], "aaaa");
806 1 : EXPECT_STREQ(oCSL[1], "bbbb");
807 : }
808 : }
809 :
810 4 : TEST_F(test_cpl, CPLStringList_SetString)
811 : {
812 1 : CPLStringList oCSL;
813 :
814 1 : oCSL.AddString("abc");
815 1 : oCSL.AddString("def");
816 1 : oCSL.AddString("ghi");
817 :
818 1 : oCSL.Sort();
819 :
820 1 : CPLStringList oCSL2(oCSL.List(), false);
821 1 : oCSL2.Sort();
822 :
823 1 : oCSL2.SetString(0, "bcd");
824 1 : ASSERT_TRUE(EQUAL(oCSL[0], "abc"));
825 1 : ASSERT_TRUE(EQUAL(oCSL2[0], "bcd"));
826 1 : ASSERT_TRUE(oCSL2.IsSorted());
827 :
828 1 : oCSL2.SetString(1, std::string("efg"));
829 1 : ASSERT_TRUE(oCSL2.IsSorted());
830 :
831 1 : oCSL2.SetString(2, "hij");
832 1 : ASSERT_TRUE(oCSL2.IsSorted());
833 :
834 4 : for (int i = 0; i < oCSL.size(); i++)
835 : {
836 3 : CPLStringList oCopy(oCSL);
837 3 : oCopy.SetString(0, "xyz");
838 3 : ASSERT_FALSE(oCopy.IsSorted());
839 : }
840 : }
841 :
842 4 : TEST_F(test_cpl, CPLStringList_NameValue)
843 : {
844 : // Test some name=value handling stuff.
845 1 : CPLStringList oNVL;
846 :
847 1 : oNVL.AddNameValue("KEY1", "VALUE1");
848 1 : oNVL.AddNameValue("2KEY", "VALUE2");
849 1 : ASSERT_EQ(oNVL.Count(), 2);
850 1 : ASSERT_TRUE(EQUAL(oNVL.FetchNameValue("2KEY"), "VALUE2"));
851 1 : ASSERT_TRUE(oNVL.FetchNameValue("MISSING") == nullptr);
852 :
853 1 : oNVL.AddNameValue("KEY1", "VALUE3");
854 1 : ASSERT_TRUE(EQUAL(oNVL.FetchNameValue("KEY1"), "VALUE1"));
855 1 : ASSERT_TRUE(EQUAL(oNVL[2], "KEY1=VALUE3"));
856 1 : ASSERT_TRUE(EQUAL(oNVL.FetchNameValueDef("MISSING", "X"), "X"));
857 :
858 1 : oNVL.SetNameValue("2KEY", "VALUE4");
859 1 : ASSERT_TRUE(EQUAL(oNVL.FetchNameValue("2KEY"), "VALUE4"));
860 1 : ASSERT_EQ(oNVL.Count(), 3);
861 :
862 : // make sure deletion works.
863 1 : oNVL.SetNameValue("2KEY", nullptr);
864 1 : ASSERT_TRUE(oNVL.FetchNameValue("2KEY") == nullptr);
865 1 : ASSERT_EQ(oNVL.Count(), 2);
866 :
867 : // Test boolean support.
868 1 : ASSERT_EQ(oNVL.FetchBoolean("BOOL", TRUE), TRUE);
869 1 : ASSERT_EQ(oNVL.FetchBoolean("BOOL", FALSE), FALSE);
870 :
871 1 : oNVL.SetNameValue("BOOL", "YES");
872 1 : ASSERT_EQ(oNVL.FetchBoolean("BOOL", TRUE), TRUE);
873 1 : ASSERT_EQ(oNVL.FetchBoolean("BOOL", FALSE), TRUE);
874 :
875 1 : oNVL.SetNameValue("BOOL", "1");
876 1 : ASSERT_EQ(oNVL.FetchBoolean("BOOL", FALSE), TRUE);
877 :
878 1 : oNVL.SetNameValue("BOOL", "0");
879 1 : ASSERT_EQ(oNVL.FetchBoolean("BOOL", TRUE), FALSE);
880 :
881 1 : oNVL.SetNameValue("BOOL", "FALSE");
882 1 : ASSERT_EQ(oNVL.FetchBoolean("BOOL", TRUE), FALSE);
883 :
884 1 : oNVL.SetNameValue("BOOL", "ON");
885 1 : ASSERT_EQ(oNVL.FetchBoolean("BOOL", FALSE), TRUE);
886 :
887 : // Test assignment operator.
888 1 : CPLStringList oCopy;
889 :
890 : {
891 2 : CPLStringList oTemp;
892 1 : oTemp.AddString("test");
893 1 : oCopy = oTemp;
894 1 : oTemp.AddString("avoid_coverity_scan_warning");
895 : }
896 1 : EXPECT_STREQ(oCopy[0], "test");
897 :
898 1 : auto &oCopyRef(oCopy);
899 1 : oCopy = oCopyRef;
900 1 : EXPECT_STREQ(oCopy[0], "test");
901 :
902 : // Test copy constructor.
903 1 : CPLStringList oCopy2(oCopy);
904 1 : EXPECT_EQ(oCopy2.Count(), oCopy.Count());
905 1 : oCopy.Clear();
906 1 : EXPECT_STREQ(oCopy2[0], "test");
907 :
908 : // Test move constructor
909 1 : CPLStringList oMoved(std::move(oCopy2));
910 1 : EXPECT_STREQ(oMoved[0], "test");
911 :
912 : // Test move assignment operator
913 1 : CPLStringList oMoved2;
914 1 : oMoved2 = std::move(oMoved);
915 1 : EXPECT_STREQ(oMoved2[0], "test");
916 :
917 : // Test sorting
918 1 : CPLStringList oTestSort;
919 1 : oTestSort.AddNameValue("Z", "1");
920 1 : oTestSort.AddNameValue("L", "2");
921 1 : oTestSort.AddNameValue("T", "3");
922 1 : oTestSort.AddNameValue("A", "4");
923 1 : oTestSort.Sort();
924 1 : EXPECT_STREQ(oTestSort[0], "A=4");
925 1 : EXPECT_STREQ(oTestSort[1], "L=2");
926 1 : EXPECT_STREQ(oTestSort[2], "T=3");
927 1 : EXPECT_STREQ(oTestSort[3], "Z=1");
928 1 : ASSERT_EQ(oTestSort[4], (const char *)nullptr);
929 :
930 : // Test FetchNameValue() in a sorted list
931 1 : EXPECT_STREQ(oTestSort.FetchNameValue("A"), "4");
932 1 : EXPECT_STREQ(oTestSort.FetchNameValue("L"), "2");
933 1 : EXPECT_STREQ(oTestSort.FetchNameValue("T"), "3");
934 1 : EXPECT_STREQ(oTestSort.FetchNameValue("Z"), "1");
935 :
936 : // Test AddNameValue() in a sorted list
937 1 : oTestSort.AddNameValue("B", "5");
938 1 : EXPECT_STREQ(oTestSort[0], "A=4");
939 1 : EXPECT_STREQ(oTestSort[1], "B=5");
940 1 : EXPECT_STREQ(oTestSort[2], "L=2");
941 1 : EXPECT_STREQ(oTestSort[3], "T=3");
942 1 : EXPECT_STREQ(oTestSort[4], "Z=1");
943 1 : ASSERT_EQ(oTestSort[5], (const char *)nullptr);
944 :
945 : // Test SetNameValue() of an existing item in a sorted list
946 1 : oTestSort.SetNameValue("Z", "6");
947 1 : EXPECT_STREQ(oTestSort[4], "Z=6");
948 :
949 : // Test SetNameValue() of a non-existing item in a sorted list
950 1 : oTestSort.SetNameValue("W", "7");
951 1 : EXPECT_STREQ(oTestSort[0], "A=4");
952 1 : EXPECT_STREQ(oTestSort[1], "B=5");
953 1 : EXPECT_STREQ(oTestSort[2], "L=2");
954 1 : EXPECT_STREQ(oTestSort[3], "T=3");
955 1 : EXPECT_STREQ(oTestSort[4], "W=7");
956 1 : EXPECT_STREQ(oTestSort[5], "Z=6");
957 1 : ASSERT_EQ(oTestSort[6], (const char *)nullptr);
958 : }
959 :
960 4 : TEST_F(test_cpl, CPLStringList_Sort)
961 : {
962 : // Test some name=value handling stuff *with* sorting active.
963 1 : CPLStringList oNVL;
964 :
965 1 : oNVL.Sort();
966 :
967 1 : oNVL.AddNameValue("KEY1", "VALUE1");
968 1 : oNVL.AddNameValue("2KEY", "VALUE2");
969 1 : ASSERT_EQ(oNVL.Count(), 2);
970 1 : EXPECT_STREQ(oNVL.FetchNameValue("KEY1"), "VALUE1");
971 1 : EXPECT_STREQ(oNVL.FetchNameValue("2KEY"), "VALUE2");
972 1 : ASSERT_TRUE(oNVL.FetchNameValue("MISSING") == nullptr);
973 :
974 1 : oNVL.AddNameValue("KEY1", "VALUE3");
975 1 : ASSERT_EQ(oNVL.Count(), 3);
976 1 : EXPECT_STREQ(oNVL.FetchNameValue("KEY1"), "VALUE1");
977 1 : EXPECT_STREQ(oNVL.FetchNameValueDef("MISSING", "X"), "X");
978 :
979 1 : oNVL.SetNameValue("2KEY", "VALUE4");
980 1 : EXPECT_STREQ(oNVL.FetchNameValue("2KEY"), "VALUE4");
981 1 : ASSERT_EQ(oNVL.Count(), 3);
982 :
983 : // make sure deletion works.
984 1 : oNVL.SetNameValue("2KEY", nullptr);
985 1 : ASSERT_TRUE(oNVL.FetchNameValue("2KEY") == nullptr);
986 1 : ASSERT_EQ(oNVL.Count(), 2);
987 :
988 : // Test insertion logic pretty carefully.
989 1 : oNVL.Clear();
990 1 : ASSERT_TRUE(oNVL.IsSorted() == TRUE);
991 :
992 1 : oNVL.SetNameValue("B", "BB");
993 1 : oNVL.SetNameValue("A", "AA");
994 1 : oNVL.SetNameValue("D", "DD");
995 1 : oNVL.SetNameValue("C", "CC");
996 :
997 : // items should be in sorted order.
998 1 : EXPECT_STREQ(oNVL[0], "A=AA");
999 1 : EXPECT_STREQ(oNVL[1], "B=BB");
1000 1 : EXPECT_STREQ(oNVL[2], "C=CC");
1001 1 : EXPECT_STREQ(oNVL[3], "D=DD");
1002 :
1003 1 : EXPECT_STREQ(oNVL.FetchNameValue("A"), "AA");
1004 1 : EXPECT_STREQ(oNVL.FetchNameValue("B"), "BB");
1005 1 : EXPECT_STREQ(oNVL.FetchNameValue("C"), "CC");
1006 1 : EXPECT_STREQ(oNVL.FetchNameValue("D"), "DD");
1007 : }
1008 :
1009 4 : TEST_F(test_cpl, URLEncode)
1010 : {
1011 2 : EXPECT_STREQ(CPLString("AB").URLEncode(), "AB");
1012 2 : EXPECT_STREQ(CPLString("A/B").URLEncode(), "A/B");
1013 2 : EXPECT_STREQ(CPLString("A B").URLEncode(), "A%20B");
1014 :
1015 1 : const char *uriA =
1016 : "http://example.com/path with space%20/pipe|/query?param=1&val=A B";
1017 1 : const char *uriB = "http://example.com/path%20with%20space%20/pipe%7C/"
1018 : "query?param=1&val=A%20B";
1019 2 : EXPECT_STREQ(CPLString(uriA).URLEncode(), uriB);
1020 2 : EXPECT_STREQ(CPLString(uriA).URLEncode(), CPLString(uriB).URLEncode());
1021 2 : EXPECT_STREQ(CPLString(uriA).URLEncode().URLEncode(), uriB);
1022 1 : }
1023 :
1024 4 : TEST_F(test_cpl, CPL_HMAC_SHA256)
1025 : {
1026 : GByte abyDigest[CPL_SHA256_HASH_SIZE];
1027 : char szDigest[2 * CPL_SHA256_HASH_SIZE + 1];
1028 :
1029 1 : CPL_HMAC_SHA256("key", 3, "The quick brown fox jumps over the lazy dog",
1030 : strlen("The quick brown fox jumps over the lazy dog"),
1031 : abyDigest);
1032 33 : for (int i = 0; i < CPL_SHA256_HASH_SIZE; i++)
1033 32 : snprintf(szDigest + 2 * i, sizeof(szDigest) - 2 * i, "%02x",
1034 32 : abyDigest[i]);
1035 : // fprintf(stderr, "%s\n", szDigest);
1036 1 : EXPECT_STREQ(
1037 : szDigest,
1038 : "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8");
1039 :
1040 1 : CPL_HMAC_SHA256(
1041 : "mysupersupersupersupersupersupersupersupersupersupersupersupersupersup"
1042 : "ersupersupersupersupersupersuperlongkey",
1043 : strlen("mysupersupersupersupersupersupersupersupersupersupersupersupers"
1044 : "upersupersupersupersupersupersupersuperlongkey"),
1045 : "msg", 3, abyDigest);
1046 33 : for (int i = 0; i < CPL_SHA256_HASH_SIZE; i++)
1047 32 : snprintf(szDigest + 2 * i, sizeof(szDigest) - 2 * i, "%02x",
1048 32 : abyDigest[i]);
1049 : // fprintf(stderr, "%s\n", szDigest);
1050 1 : EXPECT_STREQ(
1051 : szDigest,
1052 : "a3051520761ed3cb43876b35ce2dd93ac5b332dc3bad898bb32086f7ac71ffc1");
1053 1 : }
1054 :
1055 4 : TEST_F(test_cpl, VSIMalloc)
1056 : {
1057 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
1058 :
1059 : // The following tests will fail because of overflows
1060 :
1061 : {
1062 1 : CPLErrorReset();
1063 1 : void *ptr = VSIMalloc2(~(size_t)0, ~(size_t)0);
1064 1 : EXPECT_EQ(ptr, nullptr);
1065 1 : VSIFree(ptr);
1066 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1067 : }
1068 :
1069 : {
1070 1 : CPLErrorReset();
1071 1 : void *ptr = VSIMalloc3(1, ~(size_t)0, ~(size_t)0);
1072 1 : EXPECT_EQ(ptr, nullptr);
1073 1 : VSIFree(ptr);
1074 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1075 : }
1076 :
1077 : {
1078 1 : CPLErrorReset();
1079 1 : void *ptr = VSIMalloc3(~(size_t)0, 1, ~(size_t)0);
1080 1 : EXPECT_EQ(ptr, nullptr);
1081 1 : VSIFree(ptr);
1082 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1083 : }
1084 :
1085 : {
1086 1 : CPLErrorReset();
1087 1 : void *ptr = VSIMalloc3(~(size_t)0, ~(size_t)0, 1);
1088 1 : EXPECT_EQ(ptr, nullptr);
1089 1 : VSIFree(ptr);
1090 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1091 : }
1092 :
1093 1 : if (!CSLTestBoolean(CPLGetConfigOption("SKIP_MEM_INTENSIVE_TEST", "NO")))
1094 : {
1095 : // The following tests will fail because such allocations cannot succeed
1096 : #if SIZEOF_VOIDP == 8
1097 : {
1098 1 : CPLErrorReset();
1099 1 : void *ptr = VSIMalloc(~(size_t)0);
1100 1 : EXPECT_EQ(ptr, nullptr);
1101 1 : VSIFree(ptr);
1102 1 : EXPECT_EQ(CPLGetLastErrorType(), CE_None); /* no error reported */
1103 : }
1104 :
1105 : {
1106 1 : CPLErrorReset();
1107 1 : void *ptr = VSIMalloc2(~(size_t)0, 1);
1108 1 : EXPECT_EQ(ptr, nullptr);
1109 1 : VSIFree(ptr);
1110 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1111 : }
1112 :
1113 : {
1114 1 : CPLErrorReset();
1115 1 : void *ptr = VSIMalloc3(~(size_t)0, 1, 1);
1116 1 : EXPECT_EQ(ptr, nullptr);
1117 1 : VSIFree(ptr);
1118 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1119 : }
1120 :
1121 : {
1122 1 : CPLErrorReset();
1123 1 : void *ptr = VSICalloc(~(size_t)0, 1);
1124 1 : EXPECT_EQ(ptr, nullptr);
1125 1 : VSIFree(ptr);
1126 1 : EXPECT_EQ(CPLGetLastErrorType(), CE_None); /* no error reported */
1127 : }
1128 :
1129 : {
1130 1 : CPLErrorReset();
1131 1 : void *ptr = VSIRealloc(nullptr, ~(size_t)0);
1132 1 : EXPECT_EQ(ptr, nullptr);
1133 1 : VSIFree(ptr);
1134 1 : EXPECT_EQ(CPLGetLastErrorType(), CE_None); /* no error reported */
1135 : }
1136 :
1137 : {
1138 1 : CPLErrorReset();
1139 1 : void *ptr = VSI_MALLOC_VERBOSE(~(size_t)0);
1140 1 : EXPECT_EQ(ptr, nullptr);
1141 1 : VSIFree(ptr);
1142 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1143 : }
1144 :
1145 : {
1146 1 : CPLErrorReset();
1147 1 : void *ptr = VSI_MALLOC2_VERBOSE(~(size_t)0, 1);
1148 1 : EXPECT_EQ(ptr, nullptr);
1149 1 : VSIFree(ptr);
1150 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1151 : }
1152 :
1153 : {
1154 1 : CPLErrorReset();
1155 1 : void *ptr = VSI_MALLOC3_VERBOSE(~(size_t)0, 1, 1);
1156 1 : EXPECT_EQ(ptr, nullptr);
1157 1 : VSIFree(ptr);
1158 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1159 : }
1160 :
1161 : {
1162 1 : CPLErrorReset();
1163 1 : void *ptr = VSI_CALLOC_VERBOSE(~(size_t)0, 1);
1164 1 : EXPECT_EQ(ptr, nullptr);
1165 1 : VSIFree(ptr);
1166 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1167 : }
1168 :
1169 : {
1170 1 : CPLErrorReset();
1171 1 : void *ptr = VSI_REALLOC_VERBOSE(nullptr, ~(size_t)0);
1172 1 : EXPECT_EQ(ptr, nullptr);
1173 1 : VSIFree(ptr);
1174 1 : EXPECT_NE(CPLGetLastErrorType(), CE_None);
1175 : }
1176 : #endif
1177 : }
1178 :
1179 1 : CPLPopErrorHandler();
1180 :
1181 : // The following allocs will return NULL because of 0 byte alloc
1182 : {
1183 1 : CPLErrorReset();
1184 1 : void *ptr = VSIMalloc2(0, 1);
1185 1 : EXPECT_EQ(ptr, nullptr);
1186 1 : VSIFree(ptr);
1187 1 : EXPECT_EQ(CPLGetLastErrorType(), CE_None);
1188 : }
1189 :
1190 : {
1191 1 : void *ptr = VSIMalloc2(1, 0);
1192 1 : EXPECT_EQ(ptr, nullptr);
1193 1 : VSIFree(ptr);
1194 : }
1195 :
1196 : {
1197 1 : CPLErrorReset();
1198 1 : void *ptr = VSIMalloc3(0, 1, 1);
1199 1 : EXPECT_EQ(ptr, nullptr);
1200 1 : VSIFree(ptr);
1201 1 : EXPECT_EQ(CPLGetLastErrorType(), CE_None);
1202 : }
1203 :
1204 : {
1205 1 : void *ptr = VSIMalloc3(1, 0, 1);
1206 1 : EXPECT_EQ(ptr, nullptr);
1207 1 : VSIFree(ptr);
1208 : }
1209 :
1210 : {
1211 1 : void *ptr = VSIMalloc3(1, 1, 0);
1212 1 : EXPECT_EQ(ptr, nullptr);
1213 1 : VSIFree(ptr);
1214 : }
1215 1 : }
1216 :
1217 4 : TEST_F(test_cpl, CPLFormFilename)
1218 : {
1219 1 : EXPECT_TRUE(strcmp(CPLFormFilename("a", "b", nullptr), "a/b") == 0 ||
1220 : strcmp(CPLFormFilename("a", "b", nullptr), "a\\b") == 0);
1221 1 : EXPECT_TRUE(strcmp(CPLFormFilename("a/", "b", nullptr), "a/b") == 0 ||
1222 : strcmp(CPLFormFilename("a/", "b", nullptr), "a\\b") == 0);
1223 1 : EXPECT_TRUE(strcmp(CPLFormFilename("a\\", "b", nullptr), "a/b") == 0 ||
1224 : strcmp(CPLFormFilename("a\\", "b", nullptr), "a\\b") == 0);
1225 1 : EXPECT_STREQ(CPLFormFilename(nullptr, "a", "b"), "a.b");
1226 1 : EXPECT_STREQ(CPLFormFilename(nullptr, "a", ".b"), "a.b");
1227 1 : EXPECT_STREQ(CPLFormFilename("/a", "..", nullptr), "/");
1228 1 : EXPECT_STREQ(CPLFormFilename("/a/", "..", nullptr), "/");
1229 1 : EXPECT_STREQ(CPLFormFilename("/a/b", "..", nullptr), "/a");
1230 1 : EXPECT_STREQ(CPLFormFilename("/a/b/", "..", nullptr), "/a");
1231 1 : EXPECT_TRUE(EQUAL(CPLFormFilename("c:", "..", nullptr), "c:/..") ||
1232 : EQUAL(CPLFormFilename("c:", "..", nullptr), "c:\\.."));
1233 1 : EXPECT_TRUE(EQUAL(CPLFormFilename("c:\\", "..", nullptr), "c:/..") ||
1234 : EQUAL(CPLFormFilename("c:\\", "..", nullptr), "c:\\.."));
1235 1 : EXPECT_STREQ(CPLFormFilename("c:\\a", "..", nullptr), "c:");
1236 1 : EXPECT_STREQ(CPLFormFilename("c:\\a\\", "..", nullptr), "c:");
1237 1 : EXPECT_STREQ(CPLFormFilename("c:\\a\\b", "..", nullptr), "c:\\a");
1238 1 : EXPECT_STREQ(CPLFormFilename("\\\\$\\c:\\a", "..", nullptr), "\\\\$\\c:");
1239 1 : EXPECT_TRUE(
1240 : EQUAL(CPLFormFilename("\\\\$\\c:", "..", nullptr), "\\\\$\\c:/..") ||
1241 : EQUAL(CPLFormFilename("\\\\$\\c:", "..", nullptr), "\\\\$\\c:\\.."));
1242 1 : EXPECT_STREQ(CPLFormFilename("/a", "../", nullptr), "/");
1243 1 : EXPECT_STREQ(CPLFormFilename("/a/", "../", nullptr), "/");
1244 1 : EXPECT_STREQ(CPLFormFilename("/a", "../b", nullptr), "/b");
1245 1 : EXPECT_STREQ(CPLFormFilename("/a/", "../b", nullptr), "/b");
1246 1 : EXPECT_STREQ(CPLFormFilename("/a", "../b/c", nullptr), "/b/c");
1247 1 : EXPECT_STREQ(CPLFormFilename("/a/", "../b/c/d", nullptr), "/b/c/d");
1248 1 : EXPECT_STREQ(CPLFormFilename("/a/b", "../../c", nullptr), "/c");
1249 1 : EXPECT_STREQ(CPLFormFilename("/a/b/", "../../c/d", nullptr), "/c/d");
1250 1 : EXPECT_STREQ(CPLFormFilename("/a/b", "../..", nullptr), "/");
1251 1 : EXPECT_STREQ(CPLFormFilename("/a/b", "../../", nullptr), "/");
1252 1 : EXPECT_STREQ(CPLFormFilename("/a/b/c", "../../d", nullptr), "/a/d");
1253 1 : EXPECT_STREQ(CPLFormFilename("/a/b/c/", "../../d", nullptr), "/a/d");
1254 : // we could also just error out, but at least this preserves the original
1255 : // semantics
1256 1 : EXPECT_STREQ(CPLFormFilename("/a", "../../b", nullptr), "/a/../../b");
1257 1 : EXPECT_STREQ(
1258 : CPLFormFilename("/vsicurl/http://example.com?foo", "bar", nullptr),
1259 : "/vsicurl/http://example.com/bar?foo");
1260 1 : }
1261 :
1262 4 : TEST_F(test_cpl, CPLGetPath)
1263 : {
1264 1 : EXPECT_STREQ(CPLGetPath("/foo/bar/"), "/foo/bar");
1265 1 : EXPECT_STREQ(CPLGetPath("/foo/bar"), "/foo");
1266 1 : EXPECT_STREQ(CPLGetPath("/vsicurl/http://example.com/foo/bar?suffix"),
1267 : "/vsicurl/http://example.com/foo?suffix");
1268 1 : EXPECT_STREQ(
1269 : CPLGetPath(
1270 : "/vsicurl?foo=bar&url=https%3A%2F%2Fraw.githubusercontent.com%"
1271 : "2FOSGeo%2Fgdal%2Fmaster%2Fautotest%2Fogr%2Fdata%2Fpoly.shp"),
1272 : "/vsicurl?foo=bar&url=https%3A%2F%2Fraw.githubusercontent.com%2FOSGeo%"
1273 : "2Fgdal%2Fmaster%2Fautotest%2Fogr%2Fdata");
1274 1 : }
1275 :
1276 4 : TEST_F(test_cpl, CPLGetDirname)
1277 : {
1278 1 : EXPECT_STREQ(CPLGetDirname("/foo/bar/"), "/foo/bar");
1279 1 : EXPECT_STREQ(CPLGetDirname("/foo/bar"), "/foo");
1280 1 : EXPECT_STREQ(CPLGetDirname("/vsicurl/http://example.com/foo/bar?suffix"),
1281 : "/vsicurl/http://example.com/foo?suffix");
1282 1 : EXPECT_STREQ(
1283 : CPLGetDirname(
1284 : "/vsicurl?foo=bar&url=https%3A%2F%2Fraw.githubusercontent.com%"
1285 : "2FOSGeo%2Fgdal%2Fmaster%2Fautotest%2Fogr%2Fdata%2Fpoly.shp"),
1286 : "/vsicurl?foo=bar&url=https%3A%2F%2Fraw.githubusercontent.com%2FOSGeo%"
1287 : "2Fgdal%2Fmaster%2Fautotest%2Fogr%2Fdata");
1288 1 : }
1289 :
1290 4 : TEST_F(test_cpl, CPLLexicallyNormalize)
1291 : {
1292 2 : EXPECT_STREQ(CPLLexicallyNormalize("", '/').c_str(), "");
1293 2 : EXPECT_STREQ(CPLLexicallyNormalize("x", '/').c_str(), "x");
1294 2 : EXPECT_STREQ(CPLLexicallyNormalize("xy", '/').c_str(), "xy");
1295 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/", '/').c_str(), "x/");
1296 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/.", '/').c_str(), "x/");
1297 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/./", '/').c_str(), "x/");
1298 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/y", '/').c_str(), "x/y");
1299 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/yz", '/').c_str(), "x/yz");
1300 2 : EXPECT_STREQ(CPLLexicallyNormalize("xy/z", '/').c_str(), "xy/z");
1301 2 : EXPECT_STREQ(CPLLexicallyNormalize("x//y", '/').c_str(), "x/y");
1302 2 : EXPECT_STREQ(CPLLexicallyNormalize("/", '/').c_str(), "/");
1303 2 : EXPECT_STREQ(CPLLexicallyNormalize("/x", '/').c_str(), "/x");
1304 2 : EXPECT_STREQ(CPLLexicallyNormalize("../x", '/').c_str(), "../x");
1305 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/../y", '/').c_str(), "y");
1306 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/..", '/').c_str(), "");
1307 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/../", '/').c_str(), "");
1308 2 : EXPECT_STREQ(CPLLexicallyNormalize("xy/../z", '/').c_str(), "z");
1309 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/../yz", '/').c_str(), "yz");
1310 2 : EXPECT_STREQ(CPLLexicallyNormalize("x/../../yz", '/').c_str(), "../yz");
1311 2 : EXPECT_STREQ(CPLLexicallyNormalize("a/x/y/../../t", '/').c_str(), "a/t");
1312 2 : EXPECT_STREQ(CPLLexicallyNormalize("a\\x\\y\\..\\..\\t", '/', '\\').c_str(),
1313 : "a\\t");
1314 1 : }
1315 :
1316 4 : TEST_F(test_cpl, CPLsscanf)
1317 : {
1318 : double a, b, c;
1319 :
1320 1 : a = b = 0;
1321 1 : ASSERT_EQ(CPLsscanf("1 2", "%lf %lf", &a, &b), 2);
1322 1 : ASSERT_EQ(a, 1.0);
1323 1 : ASSERT_EQ(b, 2.0);
1324 :
1325 1 : a = b = 0;
1326 1 : ASSERT_EQ(CPLsscanf("1\t2", "%lf %lf", &a, &b), 2);
1327 1 : ASSERT_EQ(a, 1.0);
1328 1 : ASSERT_EQ(b, 2.0);
1329 :
1330 1 : a = b = 0;
1331 1 : ASSERT_EQ(CPLsscanf("1 2", "%lf\t%lf", &a, &b), 2);
1332 1 : ASSERT_EQ(a, 1.0);
1333 1 : ASSERT_EQ(b, 2.0);
1334 :
1335 1 : a = b = 0;
1336 1 : ASSERT_EQ(CPLsscanf("1 2", "%lf %lf", &a, &b), 2);
1337 1 : ASSERT_EQ(a, 1.0);
1338 1 : ASSERT_EQ(b, 2.0);
1339 :
1340 1 : a = b = 0;
1341 1 : ASSERT_EQ(CPLsscanf("1 2", "%lf %lf", &a, &b), 2);
1342 1 : ASSERT_EQ(a, 1.0);
1343 1 : ASSERT_EQ(b, 2.0);
1344 :
1345 1 : a = b = c = 0;
1346 1 : ASSERT_EQ(CPLsscanf("1 2", "%lf %lf %lf", &a, &b, &c), 2);
1347 1 : ASSERT_EQ(a, 1.0);
1348 1 : ASSERT_EQ(b, 2.0);
1349 : }
1350 :
1351 4 : TEST_F(test_cpl, CPLsnprintf)
1352 : {
1353 : {
1354 : char buf[32];
1355 1 : EXPECT_EQ(CPLsnprintf(buf, sizeof(buf), "a%.*fb", 1, 2.12), 5);
1356 1 : EXPECT_STREQ(buf, "a2.1b");
1357 : }
1358 1 : }
1359 :
1360 4 : TEST_F(test_cpl, CPLSetErrorHandler)
1361 : {
1362 1 : CPLString oldVal = CPLGetConfigOption("CPL_DEBUG", "");
1363 1 : CPLSetConfigOption("CPL_DEBUG", "TEST");
1364 :
1365 1 : CPLErrorHandler oldHandler = CPLSetErrorHandler(myErrorHandler);
1366 1 : gbGotError = false;
1367 1 : CPLDebug("TEST", "Test");
1368 1 : ASSERT_EQ(gbGotError, true);
1369 1 : gbGotError = false;
1370 1 : CPLSetErrorHandler(oldHandler);
1371 :
1372 1 : CPLPushErrorHandler(myErrorHandler);
1373 1 : gbGotError = false;
1374 1 : CPLDebug("TEST", "Test");
1375 1 : ASSERT_EQ(gbGotError, true);
1376 1 : gbGotError = false;
1377 1 : CPLPopErrorHandler();
1378 :
1379 1 : oldHandler = CPLSetErrorHandler(myErrorHandler);
1380 1 : CPLSetCurrentErrorHandlerCatchDebug(FALSE);
1381 1 : gbGotError = false;
1382 1 : CPLDebug("TEST", "Test");
1383 1 : ASSERT_EQ(gbGotError, false);
1384 1 : gbGotError = false;
1385 1 : CPLSetErrorHandler(oldHandler);
1386 1 : CPLSetCurrentErrorHandlerCatchDebug(true);
1387 :
1388 1 : CPLPushErrorHandler(myErrorHandler);
1389 1 : CPLSetCurrentErrorHandlerCatchDebug(FALSE);
1390 1 : gbGotError = false;
1391 1 : CPLDebug("TEST", "Test");
1392 1 : ASSERT_EQ(gbGotError, false);
1393 1 : gbGotError = false;
1394 1 : CPLPopErrorHandler();
1395 :
1396 1 : CPLSetConfigOption("CPL_DEBUG", oldVal.size() ? oldVal.c_str() : nullptr);
1397 :
1398 1 : oldHandler = CPLSetErrorHandler(nullptr);
1399 1 : CPLDebug("TEST", "Test");
1400 1 : CPLError(CE_Failure, CPLE_AppDefined, "test");
1401 1 : CPLErrorHandler newOldHandler = CPLSetErrorHandler(nullptr);
1402 1 : ASSERT_EQ(newOldHandler, static_cast<CPLErrorHandler>(nullptr));
1403 1 : CPLDebug("TEST", "Test");
1404 1 : CPLError(CE_Failure, CPLE_AppDefined, "test");
1405 1 : CPLSetErrorHandler(oldHandler);
1406 : }
1407 :
1408 4 : TEST_F(test_cpl, global_error_handler_and_CPLSetCurrentErrorHandlerCatchDebug)
1409 : {
1410 : static bool gbGotDebugMessage = false;
1411 : static bool gbGotExpectedUserData = false;
1412 :
1413 : struct MyStruct
1414 : {
1415 1 : static void CPL_STDCALL myErrorHandler(CPLErr eErr, CPLErrorNum,
1416 : const char *msg)
1417 : {
1418 1 : if (CPLGetErrorHandlerUserData() == &gbGotExpectedUserData)
1419 : {
1420 1 : gbGotExpectedUserData = true;
1421 : }
1422 1 : if (eErr == CE_Debug && strcmp(msg, "TEST: my debug message") == 0)
1423 : {
1424 1 : gbGotDebugMessage = true;
1425 : }
1426 1 : }
1427 : };
1428 :
1429 : CPLErrorHandler oldHandler =
1430 1 : CPLSetErrorHandlerEx(MyStruct::myErrorHandler, &gbGotExpectedUserData);
1431 :
1432 2 : CPLErrorAccumulator oAccumulator;
1433 : {
1434 2 : auto scopedAccumulator = oAccumulator.InstallForCurrentScope();
1435 1 : CPL_IGNORE_RET_VAL(scopedAccumulator);
1436 :
1437 2 : CPLConfigOptionSetter oSetter("CPL_DEBUG", "ON", false);
1438 1 : CPLDebug("TEST", "my debug message");
1439 : }
1440 :
1441 1 : EXPECT_TRUE(gbGotExpectedUserData);
1442 1 : EXPECT_TRUE(gbGotDebugMessage);
1443 :
1444 1 : CPLSetErrorHandler(oldHandler);
1445 1 : }
1446 :
1447 : /************************************************************************/
1448 : /* CPLString::replaceAll() */
1449 : /************************************************************************/
1450 :
1451 4 : TEST_F(test_cpl, CPLString_replaceAll)
1452 : {
1453 1 : CPLString osTest;
1454 1 : osTest = "foobarbarfoo";
1455 1 : osTest.replaceAll("bar", "was_bar");
1456 1 : ASSERT_EQ(osTest, "foowas_barwas_barfoo");
1457 :
1458 1 : osTest = "foobarbarfoo";
1459 1 : osTest.replaceAll("X", "was_bar");
1460 1 : ASSERT_EQ(osTest, "foobarbarfoo");
1461 :
1462 1 : osTest = "foobarbarfoo";
1463 1 : osTest.replaceAll("", "was_bar");
1464 1 : ASSERT_EQ(osTest, "foobarbarfoo");
1465 :
1466 1 : osTest = "foobarbarfoo";
1467 1 : osTest.replaceAll("bar", "");
1468 1 : ASSERT_EQ(osTest, "foofoo");
1469 :
1470 1 : osTest = "foobarbarfoo";
1471 1 : osTest.replaceAll('b', 'B');
1472 1 : ASSERT_EQ(osTest, "fooBarBarfoo");
1473 :
1474 1 : osTest = "foobarbarfoo";
1475 1 : osTest.replaceAll('b', "B");
1476 1 : ASSERT_EQ(osTest, "fooBarBarfoo");
1477 :
1478 1 : osTest = "foobarbarfoo";
1479 1 : osTest.replaceAll("b", 'B');
1480 1 : ASSERT_EQ(osTest, "fooBarBarfoo");
1481 : }
1482 :
1483 : /************************************************************************/
1484 : /* VSIMallocAligned() */
1485 : /************************************************************************/
1486 4 : TEST_F(test_cpl, VSIMallocAligned)
1487 : {
1488 1 : GByte *ptr = static_cast<GByte *>(VSIMallocAligned(sizeof(void *), 1));
1489 1 : ASSERT_TRUE(ptr != nullptr);
1490 1 : ASSERT_TRUE(((size_t)ptr % sizeof(void *)) == 0);
1491 1 : *ptr = 1;
1492 1 : VSIFreeAligned(ptr);
1493 :
1494 1 : ptr = static_cast<GByte *>(VSIMallocAligned(16, 1));
1495 1 : ASSERT_TRUE(ptr != nullptr);
1496 1 : ASSERT_TRUE(((size_t)ptr % 16) == 0);
1497 1 : *ptr = 1;
1498 1 : VSIFreeAligned(ptr);
1499 :
1500 1 : VSIFreeAligned(nullptr);
1501 :
1502 : #ifndef _WIN32
1503 : // Illegal use of API. Returns non NULL on Windows
1504 1 : ptr = static_cast<GByte *>(VSIMallocAligned(2, 1));
1505 1 : EXPECT_TRUE(ptr == nullptr);
1506 1 : VSIFree(ptr);
1507 :
1508 : // Illegal use of API. Crashes on Windows
1509 1 : ptr = static_cast<GByte *>(VSIMallocAligned(5, 1));
1510 1 : EXPECT_TRUE(ptr == nullptr);
1511 1 : VSIFree(ptr);
1512 : #endif
1513 :
1514 1 : if (!CSLTestBoolean(CPLGetConfigOption("SKIP_MEM_INTENSIVE_TEST", "NO")))
1515 : {
1516 : // The following tests will fail because such allocations cannot succeed
1517 : #if SIZEOF_VOIDP == 8
1518 : ptr = static_cast<GByte *>(
1519 1 : VSIMallocAligned(sizeof(void *), ~((size_t)0)));
1520 1 : EXPECT_TRUE(ptr == nullptr);
1521 1 : VSIFree(ptr);
1522 :
1523 : ptr = static_cast<GByte *>(
1524 1 : VSIMallocAligned(sizeof(void *), (~((size_t)0)) - sizeof(void *)));
1525 1 : EXPECT_TRUE(ptr == nullptr);
1526 1 : VSIFree(ptr);
1527 : #endif
1528 : }
1529 : }
1530 :
1531 : /************************************************************************/
1532 : /* CPLGetConfigOptions() / CPLSetConfigOptions() */
1533 : /************************************************************************/
1534 4 : TEST_F(test_cpl, CPLGetConfigOptions)
1535 : {
1536 1 : CPLSetConfigOption("FOOFOO", "BAR");
1537 1 : char **options = CPLGetConfigOptions();
1538 1 : EXPECT_STREQ(CSLFetchNameValue(options, "FOOFOO"), "BAR");
1539 1 : CPLSetConfigOptions(nullptr);
1540 1 : EXPECT_STREQ(CPLGetConfigOption("FOOFOO", "i_dont_exist"), "i_dont_exist");
1541 1 : CPLSetConfigOptions(options);
1542 1 : EXPECT_STREQ(CPLGetConfigOption("FOOFOO", "i_dont_exist"), "BAR");
1543 1 : CSLDestroy(options);
1544 1 : }
1545 :
1546 : /************************************************************************/
1547 : /* CPLGetThreadLocalConfigOptions() / CPLSetThreadLocalConfigOptions() */
1548 : /************************************************************************/
1549 4 : TEST_F(test_cpl, CPLGetThreadLocalConfigOptions)
1550 : {
1551 1 : CPLSetThreadLocalConfigOption("FOOFOO", "BAR");
1552 1 : char **options = CPLGetThreadLocalConfigOptions();
1553 1 : EXPECT_STREQ(CSLFetchNameValue(options, "FOOFOO"), "BAR");
1554 1 : CPLSetThreadLocalConfigOptions(nullptr);
1555 1 : EXPECT_STREQ(CPLGetThreadLocalConfigOption("FOOFOO", "i_dont_exist"),
1556 : "i_dont_exist");
1557 1 : CPLSetThreadLocalConfigOptions(options);
1558 1 : EXPECT_STREQ(CPLGetThreadLocalConfigOption("FOOFOO", "i_dont_exist"),
1559 : "BAR");
1560 1 : CSLDestroy(options);
1561 1 : }
1562 :
1563 4 : TEST_F(test_cpl, CPLExpandTilde)
1564 : {
1565 1 : EXPECT_STREQ(CPLExpandTilde("/foo/bar"), "/foo/bar");
1566 :
1567 1 : CPLSetConfigOption("HOME", "/foo");
1568 1 : ASSERT_TRUE(EQUAL(CPLExpandTilde("~/bar"), "/foo/bar") ||
1569 : EQUAL(CPLExpandTilde("~/bar"), "/foo\\bar"));
1570 1 : CPLSetConfigOption("HOME", nullptr);
1571 : }
1572 :
1573 4 : TEST_F(test_cpl, CPLDeclareKnownConfigOption)
1574 : {
1575 2 : CPLConfigOptionSetter oDebugSetter("CPL_DEBUG", "ON", false);
1576 : {
1577 2 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1578 1 : CPLErrorReset();
1579 : CPLConfigOptionSetter oDeclaredConfigOptionSetter("UNDECLARED_OPTION",
1580 2 : "FOO", false);
1581 1 : EXPECT_STREQ(CPLGetLastErrorMsg(),
1582 : "Unknown configuration option 'UNDECLARED_OPTION'.");
1583 : }
1584 : {
1585 1 : CPLDeclareKnownConfigOption("DECLARED_OPTION", nullptr);
1586 :
1587 2 : const CPLStringList aosKnownConfigOptions(CPLGetKnownConfigOptions());
1588 1 : EXPECT_GE(aosKnownConfigOptions.FindString("CPL_DEBUG"), 0);
1589 1 : EXPECT_GE(aosKnownConfigOptions.FindString("DECLARED_OPTION"), 0);
1590 :
1591 2 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1592 1 : CPLErrorReset();
1593 : CPLConfigOptionSetter oDeclaredConfigOptionSetter("DECLARED_OPTION",
1594 2 : "FOO", false);
1595 1 : EXPECT_STREQ(CPLGetLastErrorMsg(), "");
1596 : }
1597 1 : }
1598 :
1599 4 : TEST_F(test_cpl, CPLErrorSetState)
1600 : {
1601 : // NOTE: Assumes cpl_error.cpp defines DEFAULT_LAST_ERR_MSG_SIZE=500
1602 1 : char pszMsg[] = "0abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1603 : "1abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1604 : "2abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1605 : "3abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1606 : "4abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1607 : "5abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1608 : "6abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1609 : "7abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1610 : "8abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|"
1611 : "9abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|" // 500
1612 : "0abcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()_+=|" // 550
1613 : ;
1614 :
1615 1 : CPLErrorReset();
1616 1 : CPLErrorSetState(CE_Warning, 1, pszMsg);
1617 1 : ASSERT_EQ(strlen(pszMsg) - 50 - 1, // length - 50 - 1 (null-terminator)
1618 : strlen(CPLGetLastErrorMsg())); // DEFAULT_LAST_ERR_MSG_SIZE - 1
1619 : }
1620 :
1621 4 : TEST_F(test_cpl, CPLUnescapeString)
1622 : {
1623 1 : char *pszText = CPLUnescapeString(
1624 : "<>&'"???", nullptr, CPLES_XML);
1625 1 : EXPECT_STREQ(pszText, "<>&'\"???");
1626 1 : CPLFree(pszText);
1627 :
1628 : // Integer overflow
1629 1 : pszText = CPLUnescapeString("&10000000000000000;", nullptr, CPLES_XML);
1630 : // We do not really care about the return value
1631 1 : CPLFree(pszText);
1632 :
1633 : // Integer overflow
1634 1 : pszText = CPLUnescapeString("�", nullptr, CPLES_XML);
1635 : // We do not really care about the return value
1636 1 : CPLFree(pszText);
1637 :
1638 : // Error case
1639 1 : pszText = CPLUnescapeString("&foo", nullptr, CPLES_XML);
1640 1 : EXPECT_STREQ(pszText, "");
1641 1 : CPLFree(pszText);
1642 :
1643 : // Error case
1644 1 : pszText = CPLUnescapeString("&#x", nullptr, CPLES_XML);
1645 1 : EXPECT_STREQ(pszText, "");
1646 1 : CPLFree(pszText);
1647 :
1648 : // Error case
1649 1 : pszText = CPLUnescapeString("&#", nullptr, CPLES_XML);
1650 1 : EXPECT_STREQ(pszText, "");
1651 1 : CPLFree(pszText);
1652 1 : }
1653 :
1654 : // Test signed int safe maths
1655 4 : TEST_F(test_cpl, CPLSM_signed)
1656 : {
1657 1 : ASSERT_EQ((CPLSM(-2) + CPLSM(3)).v(), 1);
1658 1 : ASSERT_EQ((CPLSM(-2) + CPLSM(1)).v(), -1);
1659 1 : ASSERT_EQ((CPLSM(-2) + CPLSM(-1)).v(), -3);
1660 1 : ASSERT_EQ((CPLSM(2) + CPLSM(-3)).v(), -1);
1661 1 : ASSERT_EQ((CPLSM(2) + CPLSM(-1)).v(), 1);
1662 1 : ASSERT_EQ((CPLSM(2) + CPLSM(1)).v(), 3);
1663 1 : ASSERT_EQ((CPLSM(INT_MAX - 1) + CPLSM(1)).v(), INT_MAX);
1664 1 : ASSERT_EQ((CPLSM(1) + CPLSM(INT_MAX - 1)).v(), INT_MAX);
1665 1 : ASSERT_EQ((CPLSM(INT_MAX) + CPLSM(-1)).v(), INT_MAX - 1);
1666 1 : ASSERT_EQ((CPLSM(-1) + CPLSM(INT_MAX)).v(), INT_MAX - 1);
1667 1 : ASSERT_EQ((CPLSM(INT_MIN + 1) + CPLSM(-1)).v(), INT_MIN);
1668 1 : ASSERT_EQ((CPLSM(-1) + CPLSM(INT_MIN + 1)).v(), INT_MIN);
1669 : try
1670 : {
1671 1 : (CPLSM(INT_MAX) + CPLSM(1)).v();
1672 0 : ASSERT_TRUE(false);
1673 : }
1674 1 : catch (...)
1675 : {
1676 : }
1677 : try
1678 : {
1679 1 : (CPLSM(1) + CPLSM(INT_MAX)).v();
1680 0 : ASSERT_TRUE(false);
1681 : }
1682 1 : catch (...)
1683 : {
1684 : }
1685 : try
1686 : {
1687 1 : (CPLSM(INT_MIN) + CPLSM(-1)).v();
1688 0 : ASSERT_TRUE(false);
1689 : }
1690 1 : catch (...)
1691 : {
1692 : }
1693 : try
1694 : {
1695 1 : (CPLSM(-1) + CPLSM(INT_MIN)).v();
1696 0 : ASSERT_TRUE(false);
1697 : }
1698 1 : catch (...)
1699 : {
1700 : }
1701 :
1702 1 : ASSERT_EQ((CPLSM(-2) - CPLSM(1)).v(), -3);
1703 1 : ASSERT_EQ((CPLSM(-2) - CPLSM(-1)).v(), -1);
1704 1 : ASSERT_EQ((CPLSM(-2) - CPLSM(-3)).v(), 1);
1705 1 : ASSERT_EQ((CPLSM(2) - CPLSM(-1)).v(), 3);
1706 1 : ASSERT_EQ((CPLSM(2) - CPLSM(1)).v(), 1);
1707 1 : ASSERT_EQ((CPLSM(2) - CPLSM(3)).v(), -1);
1708 1 : ASSERT_EQ((CPLSM(INT_MAX) - CPLSM(1)).v(), INT_MAX - 1);
1709 1 : ASSERT_EQ((CPLSM(INT_MIN + 1) - CPLSM(1)).v(), INT_MIN);
1710 1 : ASSERT_EQ((CPLSM(0) - CPLSM(INT_MIN + 1)).v(), INT_MAX);
1711 1 : ASSERT_EQ((CPLSM(0) - CPLSM(INT_MAX)).v(), -INT_MAX);
1712 : try
1713 : {
1714 1 : (CPLSM(INT_MIN) - CPLSM(1)).v();
1715 0 : ASSERT_TRUE(false);
1716 : }
1717 1 : catch (...)
1718 : {
1719 : }
1720 : try
1721 : {
1722 1 : (CPLSM(0) - CPLSM(INT_MIN)).v();
1723 0 : ASSERT_TRUE(false);
1724 : }
1725 1 : catch (...)
1726 : {
1727 : }
1728 : try
1729 : {
1730 1 : (CPLSM(INT_MIN) - CPLSM(1)).v();
1731 0 : ASSERT_TRUE(false);
1732 : }
1733 1 : catch (...)
1734 : {
1735 : }
1736 :
1737 1 : ASSERT_EQ((CPLSM(INT_MIN + 1) * CPLSM(-1)).v(), INT_MAX);
1738 1 : ASSERT_EQ((CPLSM(-1) * CPLSM(INT_MIN + 1)).v(), INT_MAX);
1739 1 : ASSERT_EQ((CPLSM(INT_MIN) * CPLSM(1)).v(), INT_MIN);
1740 1 : ASSERT_EQ((CPLSM(1) * CPLSM(INT_MIN)).v(), INT_MIN);
1741 1 : ASSERT_EQ((CPLSM(1) * CPLSM(INT_MAX)).v(), INT_MAX);
1742 1 : ASSERT_EQ((CPLSM(INT_MIN / 2) * CPLSM(2)).v(), INT_MIN);
1743 1 : ASSERT_EQ((CPLSM(INT_MAX / 2) * CPLSM(2)).v(), INT_MAX - 1);
1744 1 : ASSERT_EQ((CPLSM(INT_MAX / 2 + 1) * CPLSM(-2)).v(), INT_MIN);
1745 1 : ASSERT_EQ((CPLSM(0) * CPLSM(INT_MIN)).v(), 0);
1746 1 : ASSERT_EQ((CPLSM(INT_MIN) * CPLSM(0)).v(), 0);
1747 1 : ASSERT_EQ((CPLSM(0) * CPLSM(INT_MAX)).v(), 0);
1748 1 : ASSERT_EQ((CPLSM(INT_MAX) * CPLSM(0)).v(), 0);
1749 : try
1750 : {
1751 1 : (CPLSM(INT_MAX / 2 + 1) * CPLSM(2)).v();
1752 0 : ASSERT_TRUE(false);
1753 : }
1754 1 : catch (...)
1755 : {
1756 : }
1757 : try
1758 : {
1759 1 : (CPLSM(2) * CPLSM(INT_MAX / 2 + 1)).v();
1760 0 : ASSERT_TRUE(false);
1761 : }
1762 1 : catch (...)
1763 : {
1764 : }
1765 : try
1766 : {
1767 1 : (CPLSM(INT_MIN) * CPLSM(-1)).v();
1768 0 : ASSERT_TRUE(false);
1769 : }
1770 1 : catch (...)
1771 : {
1772 : }
1773 : try
1774 : {
1775 1 : (CPLSM(INT_MIN) * CPLSM(2)).v();
1776 0 : ASSERT_TRUE(false);
1777 : }
1778 1 : catch (...)
1779 : {
1780 : }
1781 : try
1782 : {
1783 1 : (CPLSM(2) * CPLSM(INT_MIN)).v();
1784 0 : ASSERT_TRUE(false);
1785 : }
1786 1 : catch (...)
1787 : {
1788 : }
1789 :
1790 1 : ASSERT_EQ((CPLSM(4) / CPLSM(2)).v(), 2);
1791 1 : ASSERT_EQ((CPLSM(4) / CPLSM(-2)).v(), -2);
1792 1 : ASSERT_EQ((CPLSM(-4) / CPLSM(2)).v(), -2);
1793 1 : ASSERT_EQ((CPLSM(-4) / CPLSM(-2)).v(), 2);
1794 1 : ASSERT_EQ((CPLSM(0) / CPLSM(2)).v(), 0);
1795 1 : ASSERT_EQ((CPLSM(0) / CPLSM(-2)).v(), 0);
1796 1 : ASSERT_EQ((CPLSM(INT_MAX) / CPLSM(1)).v(), INT_MAX);
1797 1 : ASSERT_EQ((CPLSM(INT_MAX) / CPLSM(-1)).v(), -INT_MAX);
1798 1 : ASSERT_EQ((CPLSM(INT_MIN) / CPLSM(1)).v(), INT_MIN);
1799 : try
1800 : {
1801 1 : (CPLSM(-1) * CPLSM(INT_MIN)).v();
1802 0 : ASSERT_TRUE(false);
1803 : }
1804 1 : catch (...)
1805 : {
1806 : }
1807 : try
1808 : {
1809 1 : (CPLSM(INT_MIN) / CPLSM(-1)).v();
1810 0 : ASSERT_TRUE(false);
1811 : }
1812 1 : catch (...)
1813 : {
1814 : }
1815 : try
1816 : {
1817 1 : (CPLSM(1) / CPLSM(0)).v();
1818 0 : ASSERT_TRUE(false);
1819 : }
1820 1 : catch (...)
1821 : {
1822 : }
1823 :
1824 1 : ASSERT_EQ(CPLSM_TO_UNSIGNED(1).v(), 1U);
1825 : try
1826 : {
1827 1 : CPLSM_TO_UNSIGNED(-1);
1828 0 : ASSERT_TRUE(false);
1829 : }
1830 1 : catch (...)
1831 : {
1832 : }
1833 : }
1834 :
1835 : // Test unsigned int safe maths
1836 4 : TEST_F(test_cpl, CPLSM_unsigned)
1837 : {
1838 1 : ASSERT_EQ((CPLSM(2U) + CPLSM(3U)).v(), 5U);
1839 1 : ASSERT_EQ((CPLSM(UINT_MAX - 1) + CPLSM(1U)).v(), UINT_MAX);
1840 : try
1841 : {
1842 1 : (CPLSM(UINT_MAX) + CPLSM(1U)).v();
1843 0 : ASSERT_TRUE(false);
1844 : }
1845 1 : catch (...)
1846 : {
1847 : }
1848 :
1849 1 : ASSERT_EQ((CPLSM(4U) - CPLSM(3U)).v(), 1U);
1850 1 : ASSERT_EQ((CPLSM(4U) - CPLSM(4U)).v(), 0U);
1851 1 : ASSERT_EQ((CPLSM(UINT_MAX) - CPLSM(1U)).v(), UINT_MAX - 1);
1852 : try
1853 : {
1854 1 : (CPLSM(4U) - CPLSM(5U)).v();
1855 0 : ASSERT_TRUE(false);
1856 : }
1857 1 : catch (...)
1858 : {
1859 : }
1860 :
1861 1 : ASSERT_EQ((CPLSM(0U) * CPLSM(UINT_MAX)).v(), 0U);
1862 1 : ASSERT_EQ((CPLSM(UINT_MAX) * CPLSM(0U)).v(), 0U);
1863 1 : ASSERT_EQ((CPLSM(UINT_MAX) * CPLSM(1U)).v(), UINT_MAX);
1864 1 : ASSERT_EQ((CPLSM(1U) * CPLSM(UINT_MAX)).v(), UINT_MAX);
1865 : try
1866 : {
1867 1 : (CPLSM(UINT_MAX) * CPLSM(2U)).v();
1868 0 : ASSERT_TRUE(false);
1869 : }
1870 1 : catch (...)
1871 : {
1872 : }
1873 : try
1874 : {
1875 1 : (CPLSM(2U) * CPLSM(UINT_MAX)).v();
1876 0 : ASSERT_TRUE(false);
1877 : }
1878 1 : catch (...)
1879 : {
1880 : }
1881 :
1882 1 : ASSERT_EQ((CPLSM(4U) / CPLSM(2U)).v(), 2U);
1883 1 : ASSERT_EQ((CPLSM(UINT_MAX) / CPLSM(1U)).v(), UINT_MAX);
1884 : try
1885 : {
1886 1 : (CPLSM(1U) / CPLSM(0U)).v();
1887 0 : ASSERT_TRUE(false);
1888 : }
1889 1 : catch (...)
1890 : {
1891 : }
1892 :
1893 1 : ASSERT_EQ((CPLSM(static_cast<uint64_t>(2) * 1000 * 1000 * 1000) +
1894 : CPLSM(static_cast<uint64_t>(3) * 1000 * 1000 * 1000))
1895 : .v(),
1896 : static_cast<uint64_t>(5) * 1000 * 1000 * 1000);
1897 1 : ASSERT_EQ((CPLSM(std::numeric_limits<uint64_t>::max() - 1) +
1898 : CPLSM(static_cast<uint64_t>(1)))
1899 : .v(),
1900 : std::numeric_limits<uint64_t>::max());
1901 : try
1902 : {
1903 2 : (CPLSM(std::numeric_limits<uint64_t>::max()) +
1904 3 : CPLSM(static_cast<uint64_t>(1)));
1905 : }
1906 1 : catch (...)
1907 : {
1908 : }
1909 :
1910 1 : ASSERT_EQ((CPLSM(static_cast<uint64_t>(2) * 1000 * 1000 * 1000) *
1911 : CPLSM(static_cast<uint64_t>(3) * 1000 * 1000 * 1000))
1912 : .v(),
1913 : static_cast<uint64_t>(6) * 1000 * 1000 * 1000 * 1000 * 1000 *
1914 : 1000);
1915 1 : ASSERT_EQ((CPLSM(std::numeric_limits<uint64_t>::max()) *
1916 : CPLSM(static_cast<uint64_t>(1)))
1917 : .v(),
1918 : std::numeric_limits<uint64_t>::max());
1919 : try
1920 : {
1921 2 : (CPLSM(std::numeric_limits<uint64_t>::max()) *
1922 3 : CPLSM(static_cast<uint64_t>(2)));
1923 : }
1924 1 : catch (...)
1925 : {
1926 : }
1927 : }
1928 :
1929 : // Test CPLParseRFC822DateTime()
1930 4 : TEST_F(test_cpl, CPLParseRFC822DateTime)
1931 : {
1932 : int year, month, day, hour, min, sec, tz, weekday;
1933 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("", &year, &month, &day, &hour, &min,
1934 : &sec, &tz, &weekday));
1935 :
1936 1 : ASSERT_EQ(CPLParseRFC822DateTime("Thu, 15 Jan 2017 12:34:56 +0015", nullptr,
1937 : nullptr, nullptr, nullptr, nullptr,
1938 : nullptr, nullptr, nullptr),
1939 : TRUE);
1940 :
1941 1 : ASSERT_EQ(CPLParseRFC822DateTime("Thu, 15 Jan 2017 12:34:56 +0015", &year,
1942 : &month, &day, &hour, &min, &sec, &tz,
1943 : &weekday),
1944 : TRUE);
1945 1 : ASSERT_EQ(year, 2017);
1946 1 : ASSERT_EQ(month, 1);
1947 1 : ASSERT_EQ(day, 15);
1948 1 : ASSERT_EQ(hour, 12);
1949 1 : ASSERT_EQ(min, 34);
1950 1 : ASSERT_EQ(sec, 56);
1951 1 : ASSERT_EQ(tz, 101);
1952 1 : ASSERT_EQ(weekday, 4);
1953 :
1954 1 : ASSERT_EQ(CPLParseRFC822DateTime("Thu, 15 Jan 2017 12:34:56 GMT", &year,
1955 : &month, &day, &hour, &min, &sec, &tz,
1956 : &weekday),
1957 : TRUE);
1958 1 : ASSERT_EQ(year, 2017);
1959 1 : ASSERT_EQ(month, 1);
1960 1 : ASSERT_EQ(day, 15);
1961 1 : ASSERT_EQ(hour, 12);
1962 1 : ASSERT_EQ(min, 34);
1963 1 : ASSERT_EQ(sec, 56);
1964 1 : ASSERT_EQ(tz, 100);
1965 1 : ASSERT_EQ(weekday, 4);
1966 :
1967 : // Without day of week, second and timezone
1968 1 : ASSERT_EQ(CPLParseRFC822DateTime("15 Jan 2017 12:34", &year, &month, &day,
1969 : &hour, &min, &sec, &tz, &weekday),
1970 : TRUE);
1971 1 : ASSERT_EQ(year, 2017);
1972 1 : ASSERT_EQ(month, 1);
1973 1 : ASSERT_EQ(day, 15);
1974 1 : ASSERT_EQ(hour, 12);
1975 1 : ASSERT_EQ(min, 34);
1976 1 : ASSERT_EQ(sec, -1);
1977 1 : ASSERT_EQ(tz, 0);
1978 1 : ASSERT_EQ(weekday, 0);
1979 :
1980 1 : ASSERT_EQ(CPLParseRFC822DateTime("XXX, 15 Jan 2017 12:34:56 GMT", &year,
1981 : &month, &day, &hour, &min, &sec, &tz,
1982 : &weekday),
1983 : TRUE);
1984 1 : ASSERT_EQ(weekday, 0);
1985 :
1986 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("Sun, 01 Jan 2017 12", &year, &month,
1987 : &day, &hour, &min, &sec, &tz,
1988 : &weekday));
1989 :
1990 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("00 Jan 2017 12:34:56 GMT", &year,
1991 : &month, &day, &hour, &min, &sec, &tz,
1992 : &weekday));
1993 :
1994 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("32 Jan 2017 12:34:56 GMT", &year,
1995 : &month, &day, &hour, &min, &sec, &tz,
1996 : &weekday));
1997 :
1998 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("01 XXX 2017 12:34:56 GMT", &year,
1999 : &month, &day, &hour, &min, &sec, &tz,
2000 : &weekday));
2001 :
2002 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("01 Jan 2017 -1:34:56 GMT", &year,
2003 : &month, &day, &hour, &min, &sec, &tz,
2004 : &weekday));
2005 :
2006 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("01 Jan 2017 24:34:56 GMT", &year,
2007 : &month, &day, &hour, &min, &sec, &tz,
2008 : &weekday));
2009 :
2010 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("01 Jan 2017 12:-1:56 GMT", &year,
2011 : &month, &day, &hour, &min, &sec, &tz,
2012 : &weekday));
2013 :
2014 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("01 Jan 2017 12:60:56 GMT", &year,
2015 : &month, &day, &hour, &min, &sec, &tz,
2016 : &weekday));
2017 :
2018 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("01 Jan 2017 12:34:-1 GMT", &year,
2019 : &month, &day, &hour, &min, &sec, &tz,
2020 : &weekday));
2021 :
2022 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("01 Jan 2017 12:34:61 GMT", &year,
2023 : &month, &day, &hour, &min, &sec, &tz,
2024 : &weekday));
2025 :
2026 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("15 Jan 2017 12:34:56 XXX", &year,
2027 : &month, &day, &hour, &min, &sec, &tz,
2028 : &weekday));
2029 :
2030 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("15 Jan 2017 12:34:56 +-100", &year,
2031 : &month, &day, &hour, &min, &sec, &tz,
2032 : &weekday));
2033 :
2034 1 : ASSERT_TRUE(!CPLParseRFC822DateTime("15 Jan 2017 12:34:56 +9900", &year,
2035 : &month, &day, &hour, &min, &sec, &tz,
2036 : &weekday));
2037 : }
2038 :
2039 : // Test CPLParseMemorySize()
2040 4 : TEST_F(test_cpl, CPLParseMemorySize)
2041 : {
2042 : GIntBig nValue;
2043 : bool bUnitSpecified;
2044 : CPLErr result;
2045 :
2046 1 : result = CPLParseMemorySize("327mb", &nValue, &bUnitSpecified);
2047 1 : EXPECT_EQ(result, CE_None);
2048 1 : EXPECT_EQ(nValue, 327 * 1024 * 1024);
2049 1 : EXPECT_TRUE(bUnitSpecified);
2050 :
2051 1 : result = CPLParseMemorySize("327MB", &nValue, &bUnitSpecified);
2052 1 : EXPECT_EQ(result, CE_None);
2053 1 : EXPECT_EQ(nValue, 327 * 1024 * 1024);
2054 1 : EXPECT_TRUE(bUnitSpecified);
2055 :
2056 1 : result = CPLParseMemorySize("102.9K", &nValue, &bUnitSpecified);
2057 1 : EXPECT_EQ(result, CE_None);
2058 1 : EXPECT_EQ(nValue, static_cast<GIntBig>(102.9 * 1024));
2059 1 : EXPECT_TRUE(bUnitSpecified);
2060 :
2061 1 : result = CPLParseMemorySize("102.9 kB", &nValue, &bUnitSpecified);
2062 1 : EXPECT_EQ(result, CE_None);
2063 1 : EXPECT_EQ(nValue, static_cast<GIntBig>(102.9 * 1024));
2064 1 : EXPECT_TRUE(bUnitSpecified);
2065 :
2066 1 : result = CPLParseMemorySize("100%", &nValue, &bUnitSpecified);
2067 1 : EXPECT_EQ(result, CE_None);
2068 1 : EXPECT_GT(nValue, 100 * 1024 * 1024);
2069 1 : EXPECT_TRUE(bUnitSpecified);
2070 :
2071 1 : result = CPLParseMemorySize("0", &nValue, &bUnitSpecified);
2072 1 : EXPECT_EQ(result, CE_None);
2073 1 : EXPECT_EQ(nValue, 0);
2074 1 : EXPECT_FALSE(bUnitSpecified);
2075 :
2076 1 : result = CPLParseMemorySize("0MB", &nValue, &bUnitSpecified);
2077 1 : EXPECT_EQ(result, CE_None);
2078 1 : EXPECT_EQ(nValue, 0);
2079 1 : EXPECT_TRUE(bUnitSpecified);
2080 :
2081 1 : result = CPLParseMemorySize(" 802 ", &nValue, &bUnitSpecified);
2082 1 : EXPECT_EQ(result, CE_None);
2083 1 : EXPECT_EQ(nValue, 802);
2084 1 : EXPECT_FALSE(bUnitSpecified);
2085 :
2086 1 : result = CPLParseMemorySize("110%", &nValue, &bUnitSpecified);
2087 1 : EXPECT_EQ(result, CE_Failure);
2088 :
2089 1 : result = CPLParseMemorySize("8kbit", &nValue, &bUnitSpecified);
2090 1 : EXPECT_EQ(result, CE_Failure);
2091 :
2092 1 : result = CPLParseMemorySize("8ZB", &nValue, &bUnitSpecified);
2093 1 : EXPECT_EQ(result, CE_Failure);
2094 :
2095 1 : result = CPLParseMemorySize("8Z", &nValue, &bUnitSpecified);
2096 1 : EXPECT_EQ(result, CE_Failure);
2097 :
2098 1 : result = CPLParseMemorySize("", &nValue, &bUnitSpecified);
2099 1 : EXPECT_EQ(result, CE_Failure);
2100 :
2101 1 : result = CPLParseMemorySize(" ", &nValue, &bUnitSpecified);
2102 1 : EXPECT_EQ(result, CE_Failure);
2103 :
2104 1 : result = CPLParseMemorySize("-100MB", &nValue, &bUnitSpecified);
2105 1 : EXPECT_EQ(result, CE_Failure);
2106 :
2107 1 : result = CPLParseMemorySize("nan", &nValue, &bUnitSpecified);
2108 1 : EXPECT_EQ(result, CE_Failure);
2109 1 : }
2110 :
2111 : // Test CPLCopyTree()
2112 4 : TEST_F(test_cpl, CPLCopyTree)
2113 : {
2114 1 : CPLString osTmpPath(CPLGetDirname(CPLGenerateTempFilename(nullptr)));
2115 1 : CPLString osSrcDir(CPLFormFilename(osTmpPath, "src_dir", nullptr));
2116 1 : CPLString osNewDir(CPLFormFilename(osTmpPath, "new_dir", nullptr));
2117 1 : CPLString osSrcFile(CPLFormFilename(osSrcDir, "my.bin", nullptr));
2118 1 : CPLString osNewFile(CPLFormFilename(osNewDir, "my.bin", nullptr));
2119 :
2120 : // Cleanup if previous test failed
2121 1 : VSIUnlink(osNewFile);
2122 1 : VSIRmdir(osNewDir);
2123 1 : VSIUnlink(osSrcFile);
2124 1 : VSIRmdir(osSrcDir);
2125 :
2126 1 : ASSERT_TRUE(VSIMkdir(osSrcDir, 0755) == 0);
2127 1 : VSILFILE *fp = VSIFOpenL(osSrcFile, "wb");
2128 1 : ASSERT_TRUE(fp != nullptr);
2129 1 : VSIFCloseL(fp);
2130 :
2131 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2132 1 : ASSERT_TRUE(CPLCopyTree(osNewDir, "/i/do_not/exist") < 0);
2133 1 : CPLPopErrorHandler();
2134 :
2135 1 : ASSERT_TRUE(CPLCopyTree(osNewDir, osSrcDir) == 0);
2136 : VSIStatBufL sStat;
2137 1 : ASSERT_TRUE(VSIStatL(osNewFile, &sStat) == 0);
2138 :
2139 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2140 1 : ASSERT_TRUE(CPLCopyTree(osNewDir, osSrcDir) < 0);
2141 1 : CPLPopErrorHandler();
2142 :
2143 1 : VSIUnlink(osNewFile);
2144 1 : VSIRmdir(osNewDir);
2145 1 : VSIUnlink(osSrcFile);
2146 1 : VSIRmdir(osSrcDir);
2147 : }
2148 :
2149 : class CPLJSonStreamingParserDump : public CPLJSonStreamingParser
2150 : {
2151 : std::vector<bool> m_abFirstMember;
2152 : CPLString m_osSerialized;
2153 : CPLString m_osException;
2154 :
2155 : public:
2156 76 : CPLJSonStreamingParserDump()
2157 76 : {
2158 76 : }
2159 :
2160 23 : virtual void Reset() override
2161 : {
2162 23 : m_osSerialized.clear();
2163 23 : m_osException.clear();
2164 23 : CPLJSonStreamingParser::Reset();
2165 23 : }
2166 :
2167 : virtual void String(std::string_view s) override;
2168 : virtual void Number(std::string_view s) override;
2169 : virtual void Boolean(bool bVal) override;
2170 : virtual void Null() override;
2171 :
2172 : virtual void StartObject() override;
2173 : virtual void EndObject() override;
2174 : virtual void StartObjectMember(std::string_view key) override;
2175 :
2176 : virtual void StartArray() override;
2177 : virtual void EndArray() override;
2178 : virtual void StartArrayMember() override;
2179 :
2180 : virtual void Exception(const char *pszMessage) override;
2181 :
2182 46 : const CPLString &GetSerialized() const
2183 : {
2184 46 : return m_osSerialized;
2185 : }
2186 :
2187 53 : const CPLString &GetException() const
2188 : {
2189 53 : return m_osException;
2190 : }
2191 : };
2192 :
2193 19 : void CPLJSonStreamingParserDump::StartObject()
2194 : {
2195 19 : m_osSerialized += "{";
2196 19 : m_abFirstMember.push_back(true);
2197 19 : }
2198 :
2199 8 : void CPLJSonStreamingParserDump::EndObject()
2200 : {
2201 8 : m_osSerialized += "}";
2202 8 : m_abFirstMember.pop_back();
2203 8 : }
2204 :
2205 16 : void CPLJSonStreamingParserDump::StartObjectMember(std::string_view key)
2206 : {
2207 16 : if (!m_abFirstMember.back())
2208 4 : m_osSerialized += ", ";
2209 16 : m_osSerialized += '"';
2210 16 : m_osSerialized += key;
2211 16 : m_osSerialized += "\": ";
2212 16 : m_abFirstMember.back() = false;
2213 16 : }
2214 :
2215 14 : void CPLJSonStreamingParserDump::String(std::string_view v)
2216 : {
2217 14 : m_osSerialized += GetSerializedString(v);
2218 14 : }
2219 :
2220 22 : void CPLJSonStreamingParserDump::Number(std::string_view v)
2221 : {
2222 22 : m_osSerialized += v;
2223 22 : }
2224 :
2225 8 : void CPLJSonStreamingParserDump::Boolean(bool bVal)
2226 : {
2227 8 : m_osSerialized += bVal ? "true" : "false";
2228 8 : }
2229 :
2230 6 : void CPLJSonStreamingParserDump::Null()
2231 : {
2232 6 : m_osSerialized += "null";
2233 6 : }
2234 :
2235 20 : void CPLJSonStreamingParserDump::StartArray()
2236 : {
2237 20 : m_osSerialized += "[";
2238 20 : m_abFirstMember.push_back(true);
2239 20 : }
2240 :
2241 12 : void CPLJSonStreamingParserDump::EndArray()
2242 : {
2243 12 : m_osSerialized += "]";
2244 12 : m_abFirstMember.pop_back();
2245 12 : }
2246 :
2247 14 : void CPLJSonStreamingParserDump::StartArrayMember()
2248 : {
2249 14 : if (!m_abFirstMember.back())
2250 2 : m_osSerialized += ", ";
2251 14 : m_abFirstMember.back() = false;
2252 14 : }
2253 :
2254 53 : void CPLJSonStreamingParserDump::Exception(const char *pszMessage)
2255 : {
2256 53 : m_osException = pszMessage;
2257 53 : }
2258 :
2259 : // Test CPLJSonStreamingParser()
2260 4 : TEST_F(test_cpl, CPLJSonStreamingParser)
2261 : {
2262 : // nominal cases
2263 :
2264 : const auto NominalCase =
2265 23 : [](const std::string &s, const std::string &sExpected = std::string())
2266 : {
2267 46 : CPLJSonStreamingParserDump oParser;
2268 23 : EXPECT_TRUE(oParser.Parse(s, true));
2269 23 : if (!sExpected.empty())
2270 8 : EXPECT_STREQ(oParser.GetSerialized(), sExpected.c_str());
2271 : else
2272 15 : EXPECT_STREQ(oParser.GetSerialized(), s.c_str());
2273 :
2274 23 : oParser.Reset();
2275 257 : for (size_t i = 0; i < s.size(); i++)
2276 : {
2277 234 : EXPECT_TRUE(oParser.Parse(std::string_view(s.c_str() + i, 1),
2278 : i + 1 == s.size()));
2279 : }
2280 23 : if (!sExpected.empty())
2281 8 : EXPECT_STREQ(oParser.GetSerialized(), sExpected.c_str());
2282 : else
2283 15 : EXPECT_STREQ(oParser.GetSerialized(), s.c_str());
2284 23 : };
2285 :
2286 1 : NominalCase("false");
2287 1 : NominalCase("true");
2288 1 : NominalCase("null");
2289 1 : NominalCase("10");
2290 1 : NominalCase("123eE-34");
2291 1 : NominalCase("\"\"");
2292 1 : NominalCase("\"simple string\"");
2293 1 : NominalCase("");
2294 1 : NominalCase("\"\\\\a\\b\\f\\n\\r\\t\\u0020\\u0001\\\"\"",
2295 : "\"\\\\a\\b\\f\\n\\r\\t \\u0001\\\"\"");
2296 1 : NominalCase(
2297 : "\"\\u0001\\u0020\\ud834\\uDD1E\\uDD1E\\uD834\\uD834\\uD834\"",
2298 : "\"\\u0001 \xf0\x9d\x84\x9e\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\"");
2299 1 : NominalCase("\"\\ud834\"", "\"\xef\xbf\xbd\"");
2300 1 : NominalCase("\"\\ud834\\t\"", "\"\xef\xbf\xbd\\t\"");
2301 1 : NominalCase("\"\\u00e9\"", "\"\xc3\xa9\"");
2302 1 : NominalCase("{}");
2303 1 : NominalCase("[]");
2304 1 : NominalCase("[[]]");
2305 1 : NominalCase("[1]");
2306 1 : NominalCase("[1,2]", "[1, 2]");
2307 1 : NominalCase("{\"a\":null}", "{\"a\": null}");
2308 1 : NominalCase(" { \"a\" : null ,\r\n\t\"b\": {\"c\": 1}, \"d\": [1] }",
2309 : "{\"a\": null, \"b\": {\"c\": 1}, \"d\": [1]}");
2310 1 : NominalCase("infinity");
2311 1 : NominalCase("-infinity");
2312 1 : NominalCase("nan");
2313 :
2314 : // errors
2315 :
2316 49 : const auto ErrorCase = [](const std::string &s)
2317 : {
2318 98 : CPLJSonStreamingParserDump oParser;
2319 49 : EXPECT_FALSE(oParser.Parse(s, true));
2320 49 : EXPECT_FALSE(oParser.GetException().empty());
2321 49 : };
2322 :
2323 1 : ErrorCase("tru");
2324 1 : ErrorCase("tru1");
2325 1 : ErrorCase("truxe");
2326 1 : ErrorCase("truex");
2327 1 : ErrorCase("fals");
2328 1 : ErrorCase("falsxe");
2329 1 : ErrorCase("falsex");
2330 1 : ErrorCase("nul");
2331 1 : ErrorCase("nulxl");
2332 1 : ErrorCase("nullx");
2333 1 : ErrorCase("na");
2334 1 : ErrorCase("nanx");
2335 1 : ErrorCase("naxn");
2336 1 : ErrorCase("infinit");
2337 1 : ErrorCase("infinityx");
2338 1 : ErrorCase("-infinit");
2339 1 : ErrorCase("-infinityx");
2340 1 : ErrorCase("true false");
2341 1 : ErrorCase("x");
2342 1 : ErrorCase("{");
2343 1 : ErrorCase("}");
2344 1 : ErrorCase("[");
2345 1 : ErrorCase("[1");
2346 1 : ErrorCase("[,");
2347 1 : ErrorCase("[|");
2348 1 : ErrorCase("]");
2349 1 : ErrorCase("{ :");
2350 1 : ErrorCase("{ ,");
2351 1 : ErrorCase("{ |");
2352 1 : ErrorCase("{ 1");
2353 1 : ErrorCase("{ \"x\"");
2354 1 : ErrorCase("{ \"x\": ");
2355 1 : ErrorCase("{ \"x\": 1 2");
2356 1 : ErrorCase("{ \"x\" }");
2357 1 : ErrorCase("{ \"x\", ");
2358 1 : ErrorCase("{ \"a\" x}");
2359 1 : ErrorCase("1x");
2360 1 : ErrorCase("\"");
2361 1 : ErrorCase("\"\\");
2362 1 : ErrorCase("\"\\x\"");
2363 1 : ErrorCase("\"\\u");
2364 1 : ErrorCase("\"\\ux");
2365 1 : ErrorCase("\"\\u000");
2366 1 : ErrorCase("\"\\uD834\\ux\"");
2367 1 : ErrorCase("\"\\\"");
2368 1 : ErrorCase("[,]");
2369 1 : ErrorCase("[true,]");
2370 1 : ErrorCase("[true,,true]");
2371 1 : ErrorCase("[true true]");
2372 :
2373 : {
2374 1 : CPLJSonStreamingParserDump oParser;
2375 1 : oParser.SetMaxStringSize(2);
2376 1 : ASSERT_TRUE(!oParser.Parse("\"too long\"", true));
2377 1 : ASSERT_TRUE(!oParser.GetException().empty());
2378 : }
2379 : {
2380 1 : CPLJSonStreamingParserDump oParser;
2381 1 : oParser.SetMaxStringSize(2);
2382 1 : ASSERT_TRUE(oParser.Parse("\"", false));
2383 1 : ASSERT_TRUE(!oParser.Parse("too long\"", true));
2384 1 : ASSERT_TRUE(!oParser.GetException().empty());
2385 : }
2386 : {
2387 1 : CPLJSonStreamingParserDump oParser;
2388 1 : oParser.SetMaxDepth(1);
2389 1 : ASSERT_TRUE(!oParser.Parse("[[]]", true));
2390 1 : ASSERT_TRUE(!oParser.GetException().empty());
2391 : }
2392 : {
2393 1 : CPLJSonStreamingParserDump oParser;
2394 1 : oParser.SetMaxDepth(1);
2395 1 : ASSERT_TRUE(!oParser.Parse("{ \"x\": {} }", true));
2396 1 : ASSERT_TRUE(!oParser.GetException().empty());
2397 : }
2398 : }
2399 :
2400 : // Test cpl_mem_cache
2401 4 : TEST_F(test_cpl, cpl_mem_cache)
2402 : {
2403 1 : lru11::Cache<int, int> cache(2, 1);
2404 1 : ASSERT_EQ(cache.size(), 0U);
2405 1 : ASSERT_TRUE(cache.empty());
2406 1 : cache.clear();
2407 : int val;
2408 1 : ASSERT_TRUE(!cache.tryGet(0, val));
2409 : try
2410 : {
2411 1 : cache.get(0);
2412 0 : ASSERT_TRUE(false);
2413 : }
2414 2 : catch (const lru11::KeyNotFound &)
2415 : {
2416 1 : ASSERT_TRUE(true);
2417 : }
2418 1 : ASSERT_TRUE(!cache.remove(0));
2419 1 : ASSERT_TRUE(!cache.contains(0));
2420 1 : ASSERT_EQ(cache.getMaxSize(), 2U);
2421 1 : ASSERT_EQ(cache.getElasticity(), 1U);
2422 1 : ASSERT_EQ(cache.getMaxAllowedSize(), 3U);
2423 : int out;
2424 1 : ASSERT_TRUE(!cache.removeAndRecycleOldestEntry(out));
2425 :
2426 1 : cache.insert(0, 1);
2427 1 : val = 0;
2428 1 : ASSERT_TRUE(cache.tryGet(0, val));
2429 1 : int *ptr = cache.getPtr(0);
2430 1 : ASSERT_TRUE(ptr);
2431 1 : ASSERT_EQ(*ptr, 1);
2432 1 : ASSERT_TRUE(cache.getPtr(-1) == nullptr);
2433 1 : ASSERT_EQ(val, 1);
2434 1 : ASSERT_EQ(cache.get(0), 1);
2435 1 : ASSERT_EQ(cache.getCopy(0), 1);
2436 1 : ASSERT_EQ(cache.size(), 1U);
2437 1 : ASSERT_TRUE(!cache.empty());
2438 1 : ASSERT_TRUE(cache.contains(0));
2439 1 : bool visited = false;
2440 2 : auto lambda = [&visited](const lru11::KeyValuePair<int, int> &kv)
2441 : {
2442 1 : if (kv.key == 0 && kv.value == 1)
2443 1 : visited = true;
2444 2 : };
2445 1 : cache.cwalk(lambda);
2446 1 : ASSERT_TRUE(visited);
2447 :
2448 1 : out = -1;
2449 1 : ASSERT_TRUE(cache.removeAndRecycleOldestEntry(out));
2450 1 : ASSERT_EQ(out, 1);
2451 :
2452 1 : cache.insert(0, 1);
2453 1 : cache.insert(0, 2);
2454 1 : ASSERT_EQ(cache.get(0), 2);
2455 1 : ASSERT_EQ(cache.size(), 1U);
2456 1 : cache.insert(1, 3);
2457 1 : cache.insert(2, 4);
2458 1 : ASSERT_EQ(cache.size(), 3U);
2459 1 : cache.insert(3, 5);
2460 1 : ASSERT_EQ(cache.size(), 2U);
2461 1 : ASSERT_TRUE(cache.contains(2));
2462 1 : ASSERT_TRUE(cache.contains(3));
2463 1 : ASSERT_TRUE(!cache.contains(0));
2464 1 : ASSERT_TRUE(!cache.contains(1));
2465 1 : ASSERT_TRUE(cache.remove(2));
2466 1 : ASSERT_TRUE(!cache.contains(2));
2467 1 : ASSERT_EQ(cache.size(), 1U);
2468 :
2469 : {
2470 : // Check that MyObj copy constructor and copy-assignment operator
2471 : // are not needed
2472 : struct MyObj
2473 : {
2474 : int m_v;
2475 :
2476 4 : MyObj(int v) : m_v(v)
2477 : {
2478 4 : }
2479 :
2480 : MyObj(const MyObj &) = delete;
2481 : MyObj &operator=(const MyObj &) = delete;
2482 : MyObj(MyObj &&) = default;
2483 : MyObj &operator=(MyObj &&) = default;
2484 : };
2485 :
2486 1 : lru11::Cache<int, MyObj> cacheMyObj(2, 0);
2487 1 : ASSERT_EQ(cacheMyObj.insert(0, MyObj(0)).m_v, 0);
2488 1 : cacheMyObj.getPtr(0);
2489 1 : ASSERT_EQ(cacheMyObj.insert(1, MyObj(1)).m_v, 1);
2490 1 : ASSERT_EQ(cacheMyObj.insert(2, MyObj(2)).m_v, 2);
2491 1 : MyObj outObj(-1);
2492 1 : cacheMyObj.removeAndRecycleOldestEntry(outObj);
2493 : }
2494 :
2495 : {
2496 : // Check that MyObj copy constructor and copy-assignment operator
2497 : // are not triggered
2498 : struct MyObj
2499 : {
2500 : int m_v;
2501 :
2502 4 : MyObj(int v) : m_v(v)
2503 : {
2504 4 : }
2505 :
2506 : static void should_not_happen()
2507 : {
2508 : ASSERT_TRUE(false);
2509 : }
2510 :
2511 : MyObj(const MyObj &) : m_v(-1)
2512 : {
2513 : should_not_happen();
2514 : }
2515 :
2516 : MyObj &operator=(const MyObj &)
2517 : {
2518 : should_not_happen();
2519 : return *this;
2520 : }
2521 :
2522 : MyObj(MyObj &&) = default;
2523 : MyObj &operator=(MyObj &&) = default;
2524 : };
2525 :
2526 1 : lru11::Cache<int, MyObj> cacheMyObj(2, 0);
2527 1 : ASSERT_EQ(cacheMyObj.insert(0, MyObj(0)).m_v, 0);
2528 1 : cacheMyObj.getPtr(0);
2529 1 : ASSERT_EQ(cacheMyObj.insert(1, MyObj(1)).m_v, 1);
2530 1 : ASSERT_EQ(cacheMyObj.insert(2, MyObj(2)).m_v, 2);
2531 1 : MyObj outObj(-1);
2532 1 : cacheMyObj.removeAndRecycleOldestEntry(outObj);
2533 : }
2534 : }
2535 :
2536 : // Test CPLJSONDocument
2537 4 : TEST_F(test_cpl, CPLJSONDocument)
2538 : {
2539 : {
2540 : // Test Json document LoadUrl
2541 1 : CPLJSONDocument oDocument;
2542 1 : const char *options[5] = {"CONNECTTIMEOUT=15", "TIMEOUT=20",
2543 : "MAX_RETRY=5", "RETRY_DELAY=1", nullptr};
2544 :
2545 1 : oDocument.GetRoot().Add("foo", "bar");
2546 :
2547 1 : if (CPLHTTPEnabled())
2548 : {
2549 1 : CPLSetConfigOption("CPL_CURL_ENABLE_VSIMEM", "YES");
2550 1 : VSILFILE *fpTmp = VSIFOpenL("/vsimem/test.json", "wb");
2551 1 : const char *pszContent = "{ \"foo\": \"bar\" }";
2552 1 : VSIFWriteL(pszContent, 1, strlen(pszContent), fpTmp);
2553 1 : VSIFCloseL(fpTmp);
2554 1 : ASSERT_TRUE(oDocument.LoadUrl("/vsimem/test.json",
2555 : const_cast<char **>(options)));
2556 1 : CPLSetConfigOption("CPL_CURL_ENABLE_VSIMEM", nullptr);
2557 1 : VSIUnlink("/vsimem/test.json");
2558 :
2559 1 : CPLJSONObject oJsonRoot = oDocument.GetRoot();
2560 1 : ASSERT_TRUE(oJsonRoot.IsValid());
2561 :
2562 2 : CPLString value = oJsonRoot.GetString("foo", "");
2563 1 : ASSERT_STRNE(value, "bar"); // not equal
2564 : }
2565 : }
2566 : {
2567 : // Test Json document LoadChunks
2568 1 : CPLJSONDocument oDocument;
2569 :
2570 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2571 1 : ASSERT_TRUE(!oDocument.LoadChunks("/i_do/not/exist", 512));
2572 1 : CPLPopErrorHandler();
2573 :
2574 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2575 1 : ASSERT_TRUE(!oDocument.LoadChunks("test_cpl.cpp", 512));
2576 1 : CPLPopErrorHandler();
2577 :
2578 1 : oDocument.GetRoot().Add("foo", "bar");
2579 :
2580 1 : ASSERT_TRUE(
2581 : oDocument.LoadChunks((data_ + SEP + "test.json").c_str(), 512));
2582 :
2583 1 : CPLJSONObject oJsonRoot = oDocument.GetRoot();
2584 1 : ASSERT_TRUE(oJsonRoot.IsValid());
2585 1 : ASSERT_EQ(oJsonRoot.GetInteger("resource/id", 10), 0);
2586 :
2587 2 : CPLJSONObject oJsonResource = oJsonRoot.GetObj("resource");
2588 1 : ASSERT_TRUE(oJsonResource.IsValid());
2589 1 : std::vector<CPLJSONObject> children = oJsonResource.GetChildren();
2590 1 : ASSERT_TRUE(children.size() == 11);
2591 :
2592 2 : CPLJSONArray oaScopes = oJsonRoot.GetArray("resource/scopes");
2593 1 : ASSERT_TRUE(oaScopes.IsValid());
2594 1 : ASSERT_EQ(oaScopes.Size(), 2);
2595 :
2596 2 : CPLJSONObject oHasChildren = oJsonRoot.GetObj("resource/children");
2597 1 : ASSERT_TRUE(oHasChildren.IsValid());
2598 1 : ASSERT_EQ(oHasChildren.ToBool(), true);
2599 :
2600 1 : ASSERT_EQ(oJsonResource.GetBool("children", false), true);
2601 :
2602 2 : CPLJSONObject oJsonId = oJsonRoot["resource/owner_user/id"];
2603 1 : ASSERT_TRUE(oJsonId.IsValid());
2604 : }
2605 : {
2606 1 : CPLJSONDocument oDocument;
2607 1 : ASSERT_TRUE(!oDocument.LoadMemory(nullptr, 0));
2608 1 : ASSERT_TRUE(!oDocument.LoadMemory(CPLString()));
2609 1 : ASSERT_TRUE(oDocument.LoadMemory(std::string("true")));
2610 1 : ASSERT_TRUE(oDocument.GetRoot().GetType() ==
2611 : CPLJSONObject::Type::Boolean);
2612 1 : ASSERT_TRUE(oDocument.GetRoot().ToBool());
2613 1 : ASSERT_TRUE(oDocument.LoadMemory(std::string("false")));
2614 1 : ASSERT_TRUE(oDocument.GetRoot().GetType() ==
2615 : CPLJSONObject::Type::Boolean);
2616 1 : ASSERT_TRUE(!oDocument.GetRoot().ToBool());
2617 : }
2618 : {
2619 : // Copy constructor
2620 1 : CPLJSONDocument oDocument;
2621 1 : ASSERT_TRUE(oDocument.LoadMemory(std::string("true")));
2622 1 : oDocument.GetRoot();
2623 1 : CPLJSONDocument oDocument2(oDocument);
2624 1 : CPLJSONObject oObj(oDocument.GetRoot());
2625 1 : ASSERT_TRUE(oObj.ToBool());
2626 1 : CPLJSONObject oObj2(oObj);
2627 1 : ASSERT_TRUE(oObj2.ToBool());
2628 : // Assignment operator
2629 1 : oDocument2 = oDocument;
2630 1 : oDocument.GetRoot(); // avoid Coverity Scan warning
2631 1 : auto &oDocument2Ref(oDocument2);
2632 1 : oDocument2 = oDocument2Ref;
2633 1 : oObj2 = oObj;
2634 1 : oObj.GetType(); // avoid Coverity Scan warning
2635 1 : auto &oObj2Ref(oObj2);
2636 1 : oObj2 = oObj2Ref;
2637 1 : CPLJSONObject oObj3(std::move(oObj2));
2638 1 : ASSERT_TRUE(oObj3.ToBool());
2639 1 : CPLJSONObject oObj4;
2640 1 : oObj4 = std::move(oObj3);
2641 1 : ASSERT_TRUE(oObj4.ToBool());
2642 : }
2643 : {
2644 : // Move constructor
2645 2 : CPLJSONDocument oDocument;
2646 1 : oDocument.GetRoot();
2647 1 : CPLJSONDocument oDocument2(std::move(oDocument));
2648 : }
2649 : {
2650 : // Move assignment
2651 2 : CPLJSONDocument oDocument;
2652 1 : oDocument.GetRoot();
2653 2 : CPLJSONDocument oDocument2;
2654 1 : oDocument2 = std::move(oDocument);
2655 : }
2656 : {
2657 : // Save
2658 1 : CPLJSONDocument oDocument;
2659 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2660 1 : ASSERT_TRUE(!oDocument.Save("/i_do/not/exist"));
2661 1 : CPLPopErrorHandler();
2662 : }
2663 : {
2664 2 : CPLJSONObject oObj(nullptr);
2665 1 : EXPECT_EQ(oObj.GetType(), CPLJSONObject::Type::Null);
2666 : }
2667 : {
2668 2 : CPLJSONObject oObj(true);
2669 1 : EXPECT_EQ(oObj.GetType(), CPLJSONObject::Type::Boolean);
2670 1 : EXPECT_EQ(oObj.ToBool(), true);
2671 : }
2672 : {
2673 2 : CPLJSONObject oObj(1);
2674 1 : EXPECT_EQ(oObj.GetType(), CPLJSONObject::Type::Integer);
2675 1 : EXPECT_EQ(oObj.ToInteger(), 1);
2676 : }
2677 : {
2678 2 : CPLJSONObject oObj(static_cast<int64_t>(123) * 1024 * 1024 * 1024);
2679 1 : EXPECT_EQ(oObj.GetType(), CPLJSONObject::Type::Long);
2680 1 : EXPECT_EQ(oObj.ToLong(),
2681 : static_cast<int64_t>(123) * 1024 * 1024 * 1024);
2682 : }
2683 : {
2684 2 : CPLJSONObject oObj(static_cast<uint64_t>(123) * 1024 * 1024 * 1024);
2685 : // Might be a string with older libjson versions
2686 1 : if (oObj.GetType() == CPLJSONObject::Type::Long)
2687 : {
2688 1 : EXPECT_EQ(oObj.ToLong(),
2689 : static_cast<int64_t>(123) * 1024 * 1024 * 1024);
2690 : }
2691 : }
2692 : {
2693 2 : CPLJSONObject oObj(1.5);
2694 1 : EXPECT_EQ(oObj.GetType(), CPLJSONObject::Type::Double);
2695 1 : EXPECT_EQ(oObj.ToDouble(), 1.5);
2696 : }
2697 : {
2698 2 : CPLJSONObject oObj("ab");
2699 1 : EXPECT_EQ(oObj.GetType(), CPLJSONObject::Type::String);
2700 2 : EXPECT_STREQ(oObj.ToString().c_str(), "ab");
2701 : }
2702 : {
2703 3 : CPLJSONObject oObj(std::string("ab"));
2704 1 : EXPECT_EQ(oObj.GetType(), CPLJSONObject::Type::String);
2705 2 : EXPECT_STREQ(oObj.ToString().c_str(), "ab");
2706 : }
2707 : {
2708 1 : CPLJSONObject oObj;
2709 1 : oObj.Add("string", std::string("my_string"));
2710 2 : ASSERT_EQ(oObj.GetString("string"), std::string("my_string"));
2711 2 : ASSERT_EQ(oObj.GetString("inexisting_string", "default"),
2712 : std::string("default"));
2713 1 : oObj.Add("const_char_star", nullptr);
2714 1 : oObj.Add("const_char_star", "my_const_char_star");
2715 1 : ASSERT_TRUE(oObj.GetObj("const_char_star").GetType() ==
2716 : CPLJSONObject::Type::String);
2717 1 : oObj.Add("int", 1);
2718 1 : ASSERT_EQ(oObj.GetInteger("int"), 1);
2719 1 : ASSERT_EQ(oObj.GetInteger("inexisting_int", -987), -987);
2720 1 : ASSERT_TRUE(oObj.GetObj("int").GetType() ==
2721 : CPLJSONObject::Type::Integer);
2722 1 : oObj.Add("int64", GINT64_MAX);
2723 2 : ASSERT_EQ(oObj.GetLong("int64"), GINT64_MAX);
2724 2 : ASSERT_EQ(oObj.GetLong("inexisting_int64", GINT64_MIN), GINT64_MIN);
2725 1 : ASSERT_TRUE(oObj.GetObj("int64").GetType() ==
2726 : CPLJSONObject::Type::Long);
2727 1 : oObj.Add("double", 1.25);
2728 1 : ASSERT_EQ(oObj.GetDouble("double"), 1.25);
2729 1 : ASSERT_EQ(oObj.GetDouble("inexisting_double", -987.0), -987.0);
2730 1 : ASSERT_TRUE(oObj.GetObj("double").GetType() ==
2731 : CPLJSONObject::Type::Double);
2732 1 : oObj.Add("array", CPLJSONArray());
2733 1 : ASSERT_TRUE(oObj.GetObj("array").GetType() ==
2734 : CPLJSONObject::Type::Array);
2735 1 : oObj.Add("obj", CPLJSONObject());
2736 1 : ASSERT_TRUE(oObj.GetObj("obj").GetType() ==
2737 : CPLJSONObject::Type::Object);
2738 1 : oObj.Add("bool", true);
2739 1 : ASSERT_EQ(oObj.GetBool("bool"), true);
2740 1 : ASSERT_EQ(oObj.GetBool("inexisting_bool", false), false);
2741 1 : ASSERT_TRUE(oObj.GetObj("bool").GetType() ==
2742 : CPLJSONObject::Type::Boolean);
2743 1 : oObj.AddNull("null_field");
2744 1 : ASSERT_TRUE(oObj.GetObj("null_field").GetType() ==
2745 : CPLJSONObject::Type::Null);
2746 1 : ASSERT_TRUE(oObj.GetObj("inexisting").GetType() ==
2747 : CPLJSONObject::Type::Unknown);
2748 1 : oObj.Set("string", std::string("my_string"));
2749 1 : oObj.Set("const_char_star", nullptr);
2750 1 : oObj.Set("const_char_star", "my_const_char_star");
2751 1 : oObj.Set("int", 1);
2752 1 : oObj.Set("int64", GINT64_MAX);
2753 1 : oObj.Set("double", 1.25);
2754 : // oObj.Set("array", CPLJSONArray());
2755 : // oObj.Set("obj", CPLJSONObject());
2756 1 : oObj.Set("bool", true);
2757 1 : oObj.SetNull("null_field");
2758 1 : ASSERT_TRUE(CPLJSONArray().GetChildren().empty());
2759 1 : oObj.ToArray();
2760 : }
2761 : {
2762 2 : CPLJSONObject oObj;
2763 1 : oObj.Set("foo", "bar");
2764 2 : EXPECT_STREQ(oObj.Format(CPLJSONObject::PrettyFormat::Spaced).c_str(),
2765 : "{ \"foo\": \"bar\" }");
2766 2 : EXPECT_STREQ(oObj.Format(CPLJSONObject::PrettyFormat::Pretty).c_str(),
2767 : "{\n \"foo\":\"bar\"\n}");
2768 2 : EXPECT_STREQ(oObj.Format(CPLJSONObject::PrettyFormat::Plain).c_str(),
2769 : "{\"foo\":\"bar\"}");
2770 : }
2771 : {
2772 2 : CPLJSONArray oArrayConstructorString(std::string("foo"));
2773 1 : CPLJSONArray oArray;
2774 1 : oArray.Add(CPLJSONObject());
2775 1 : oArray.Add(std::string("str"));
2776 1 : oArray.Add("const_char_star");
2777 1 : oArray.Add(1.25);
2778 1 : oArray.Add(1);
2779 1 : oArray.Add(GINT64_MAX);
2780 1 : oArray.Add(true);
2781 1 : oArray.AddNull();
2782 1 : ASSERT_EQ(oArray.Size(), 8);
2783 :
2784 1 : int nCount = 0;
2785 9 : for (const auto &obj : oArray)
2786 : {
2787 8 : ASSERT_EQ(obj.GetInternalHandle(),
2788 : oArray[nCount].GetInternalHandle());
2789 8 : nCount++;
2790 : }
2791 1 : ASSERT_EQ(nCount, 8);
2792 : }
2793 : {
2794 1 : CPLJSONDocument oDocument;
2795 1 : ASSERT_TRUE(oDocument.LoadMemory(CPLString("{ \"/foo\" : \"bar\" }")));
2796 2 : ASSERT_EQ(oDocument.GetRoot().GetString("/foo"), std::string("bar"));
2797 : }
2798 : }
2799 :
2800 : // Test CPLRecodeIconv() with re-allocation
2801 : // (this test also passed on Windows using its native recoding API)
2802 4 : TEST_F(test_cpl, CPLRecodeIconv)
2803 : {
2804 : #if defined(CPL_RECODE_ICONV) || defined(_WIN32)
2805 1 : int N = 32800;
2806 1 : char *pszIn = static_cast<char *>(CPLMalloc(N + 1));
2807 32801 : for (int i = 0; i < N; i++)
2808 32800 : pszIn[i] = '\xA1';
2809 1 : pszIn[N] = 0;
2810 1 : char *pszExpected = static_cast<char *>(CPLMalloc(N * 2 + 1));
2811 32801 : for (int i = 0; i < N; i++)
2812 : {
2813 32800 : pszExpected[2 * i] = '\xD0';
2814 32800 : pszExpected[2 * i + 1] = '\x81';
2815 : }
2816 1 : pszExpected[N * 2] = 0;
2817 1 : char *pszRet = CPLRecode(pszIn, "ISO-8859-5", CPL_ENC_UTF8);
2818 1 : EXPECT_EQ(memcmp(pszExpected, pszRet, N * 2 + 1), 0);
2819 1 : CPLFree(pszIn);
2820 1 : CPLFree(pszRet);
2821 1 : CPLFree(pszExpected);
2822 : #else
2823 : GTEST_SKIP() << "CPL_RECODE_ICONV missing";
2824 : #endif
2825 1 : }
2826 :
2827 : // Test CP1252 to UTF-8
2828 4 : TEST_F(test_cpl, CPLRecodeStubCP1252_to_UTF8_strict_alloc)
2829 : {
2830 1 : CPLClearRecodeWarningFlags();
2831 1 : CPLErrorReset();
2832 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2833 : // Euro character expands to 3-bytes
2834 1 : char *pszRet = CPLRecode("\x80", "CP1252", CPL_ENC_UTF8);
2835 1 : CPLPopErrorHandler();
2836 1 : EXPECT_STREQ(CPLGetLastErrorMsg(), "");
2837 1 : EXPECT_EQ(memcmp(pszRet, "\xE2\x82\xAC\x00", 4), 0);
2838 1 : CPLFree(pszRet);
2839 1 : }
2840 :
2841 : // Test CP1252 to UTF-8
2842 4 : TEST_F(test_cpl, CPLRecodeStubCP1252_to_UTF8_with_ascii)
2843 : {
2844 1 : CPLClearRecodeWarningFlags();
2845 1 : CPLErrorReset();
2846 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2847 1 : char *pszRet = CPLRecode("x\x80y", "CP1252", CPL_ENC_UTF8);
2848 1 : CPLPopErrorHandler();
2849 1 : EXPECT_STREQ(CPLGetLastErrorMsg(), "");
2850 1 : EXPECT_EQ(memcmp(pszRet, "x\xE2\x82\xACy\x00", 6), 0);
2851 1 : CPLFree(pszRet);
2852 1 : }
2853 :
2854 : // Test CP1252 to UTF-8
2855 4 : TEST_F(test_cpl, CPLRecodeStubCP1252_to_UTF8_with_warning)
2856 : {
2857 1 : CPLClearRecodeWarningFlags();
2858 1 : CPLErrorReset();
2859 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2860 : // \x90 is an invalid CP1252 character. Will be skipped
2861 1 : char *pszRet = CPLRecode("\x90\x80", "CP1252", CPL_ENC_UTF8);
2862 1 : CPLPopErrorHandler();
2863 1 : EXPECT_STREQ(
2864 : CPLGetLastErrorMsg(),
2865 : "One or several characters couldn't be converted correctly from CP1252 "
2866 : "to UTF-8. This warning will not be emitted anymore");
2867 1 : EXPECT_EQ(memcmp(pszRet, "\xE2\x82\xAC\x00", 4), 0);
2868 1 : CPLFree(pszRet);
2869 1 : }
2870 :
2871 : // Test CPLHTTPParseMultipartMime()
2872 4 : TEST_F(test_cpl, CPLHTTPParseMultipartMime)
2873 : {
2874 : CPLHTTPResult *psResult;
2875 :
2876 : psResult =
2877 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2878 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2879 1 : EXPECT_TRUE(!CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
2880 1 : CPLPopErrorHandler();
2881 1 : CPLHTTPDestroyResult(psResult);
2882 :
2883 : // Missing boundary value
2884 : psResult =
2885 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2886 1 : psResult->pszContentType = CPLStrdup("multipart/form-data; boundary=");
2887 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2888 1 : EXPECT_TRUE(!CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
2889 1 : CPLPopErrorHandler();
2890 1 : CPLHTTPDestroyResult(psResult);
2891 :
2892 : // No content
2893 : psResult =
2894 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2895 1 : psResult->pszContentType =
2896 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
2897 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2898 1 : EXPECT_TRUE(!CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
2899 1 : CPLPopErrorHandler();
2900 1 : CPLHTTPDestroyResult(psResult);
2901 :
2902 : // No part
2903 : psResult =
2904 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2905 1 : psResult->pszContentType =
2906 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
2907 : {
2908 1 : const char *pszText = "--myboundary some junk\r\n";
2909 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
2910 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
2911 : }
2912 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2913 1 : EXPECT_TRUE(!CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
2914 1 : CPLPopErrorHandler();
2915 1 : CPLHTTPDestroyResult(psResult);
2916 :
2917 : // Missing end boundary
2918 : psResult =
2919 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2920 1 : psResult->pszContentType =
2921 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
2922 : {
2923 1 : const char *pszText = "--myboundary some junk\r\n"
2924 : "\r\n"
2925 : "Bla";
2926 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
2927 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
2928 : }
2929 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2930 1 : EXPECT_TRUE(!CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
2931 1 : CPLPopErrorHandler();
2932 1 : CPLHTTPDestroyResult(psResult);
2933 :
2934 : // Truncated header
2935 : psResult =
2936 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2937 1 : psResult->pszContentType =
2938 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
2939 : {
2940 1 : const char *pszText = "--myboundary some junk\r\n"
2941 : "Content-Type: foo";
2942 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
2943 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
2944 : }
2945 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2946 1 : EXPECT_TRUE(!CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
2947 1 : CPLPopErrorHandler();
2948 1 : CPLHTTPDestroyResult(psResult);
2949 :
2950 : // Invalid end boundary
2951 : psResult =
2952 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2953 1 : psResult->pszContentType =
2954 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
2955 : {
2956 1 : const char *pszText = "--myboundary some junk\r\n"
2957 : "\r\n"
2958 : "Bla"
2959 : "\r\n"
2960 : "--myboundary";
2961 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
2962 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
2963 : }
2964 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2965 1 : EXPECT_TRUE(!CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
2966 1 : CPLPopErrorHandler();
2967 1 : CPLHTTPDestroyResult(psResult);
2968 :
2969 : // Invalid end boundary
2970 : psResult =
2971 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2972 1 : psResult->pszContentType =
2973 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
2974 : {
2975 1 : const char *pszText = "--myboundary some junk\r\n"
2976 : "\r\n"
2977 : "Bla"
2978 : "\r\n"
2979 : "--myboundary";
2980 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
2981 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
2982 : }
2983 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
2984 1 : EXPECT_TRUE(!CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
2985 1 : CPLPopErrorHandler();
2986 1 : CPLHTTPDestroyResult(psResult);
2987 :
2988 : // Valid single part, no header
2989 : psResult =
2990 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
2991 1 : psResult->pszContentType =
2992 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
2993 : {
2994 1 : const char *pszText = "--myboundary some junk\r\n"
2995 : "\r\n"
2996 : "Bla"
2997 : "\r\n"
2998 : "--myboundary--\r\n";
2999 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
3000 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
3001 : }
3002 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3003 1 : EXPECT_EQ(psResult->nMimePartCount, 1);
3004 1 : if (psResult->nMimePartCount == 1)
3005 : {
3006 1 : EXPECT_EQ(psResult->pasMimePart[0].papszHeaders,
3007 : static_cast<char **>(nullptr));
3008 1 : EXPECT_EQ(psResult->pasMimePart[0].nDataLen, 3);
3009 1 : EXPECT_TRUE(
3010 : strncmp(reinterpret_cast<char *>(psResult->pasMimePart[0].pabyData),
3011 : "Bla", 3) == 0);
3012 : }
3013 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3014 1 : CPLHTTPDestroyResult(psResult);
3015 :
3016 : // Valid single part, with header
3017 : psResult =
3018 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
3019 1 : psResult->pszContentType =
3020 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
3021 : {
3022 1 : const char *pszText = "--myboundary some junk\r\n"
3023 : "Content-Type: bla\r\n"
3024 : "\r\n"
3025 : "Bla"
3026 : "\r\n"
3027 : "--myboundary--\r\n";
3028 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
3029 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
3030 : }
3031 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3032 1 : EXPECT_EQ(psResult->nMimePartCount, 1);
3033 1 : if (psResult->nMimePartCount == 1)
3034 : {
3035 1 : EXPECT_EQ(CSLCount(psResult->pasMimePart[0].papszHeaders), 1);
3036 1 : EXPECT_STREQ(psResult->pasMimePart[0].papszHeaders[0],
3037 : "Content-Type=bla");
3038 1 : EXPECT_EQ(psResult->pasMimePart[0].nDataLen, 3);
3039 1 : EXPECT_TRUE(
3040 : strncmp(reinterpret_cast<char *>(psResult->pasMimePart[0].pabyData),
3041 : "Bla", 3) == 0);
3042 : }
3043 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3044 1 : CPLHTTPDestroyResult(psResult);
3045 :
3046 : // Valid single part, 2 headers
3047 : psResult =
3048 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
3049 1 : psResult->pszContentType =
3050 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
3051 : {
3052 1 : const char *pszText = "--myboundary some junk\r\n"
3053 : "Content-Type: bla\r\n"
3054 : "Content-Disposition: bar\r\n"
3055 : "\r\n"
3056 : "Bla"
3057 : "\r\n"
3058 : "--myboundary--\r\n";
3059 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
3060 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
3061 : }
3062 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3063 1 : EXPECT_EQ(psResult->nMimePartCount, 1);
3064 1 : if (psResult->nMimePartCount == 1)
3065 : {
3066 1 : EXPECT_EQ(CSLCount(psResult->pasMimePart[0].papszHeaders), 2);
3067 1 : EXPECT_STREQ(psResult->pasMimePart[0].papszHeaders[0],
3068 : "Content-Type=bla");
3069 1 : EXPECT_STREQ(psResult->pasMimePart[0].papszHeaders[1],
3070 : "Content-Disposition=bar");
3071 1 : EXPECT_EQ(psResult->pasMimePart[0].nDataLen, 3);
3072 1 : EXPECT_TRUE(
3073 : strncmp(reinterpret_cast<char *>(psResult->pasMimePart[0].pabyData),
3074 : "Bla", 3) == 0);
3075 : }
3076 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3077 1 : CPLHTTPDestroyResult(psResult);
3078 :
3079 : // Single part, but with header without extra terminating \r\n
3080 : // (invalid normally, but apparently necessary for some ArcGIS WCS
3081 : // implementations)
3082 : psResult =
3083 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
3084 1 : psResult->pszContentType =
3085 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
3086 : {
3087 1 : const char *pszText = "--myboundary some junk\r\n"
3088 : "Content-Type: bla\r\n"
3089 : "Bla"
3090 : "\r\n"
3091 : "--myboundary--\r\n";
3092 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
3093 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
3094 : }
3095 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3096 1 : EXPECT_EQ(psResult->nMimePartCount, 1);
3097 1 : if (psResult->nMimePartCount == 1)
3098 : {
3099 1 : EXPECT_STREQ(psResult->pasMimePart[0].papszHeaders[0],
3100 : "Content-Type=bla");
3101 1 : EXPECT_EQ(psResult->pasMimePart[0].nDataLen, 3);
3102 1 : EXPECT_TRUE(
3103 : strncmp(reinterpret_cast<char *>(psResult->pasMimePart[0].pabyData),
3104 : "Bla", 3) == 0);
3105 : }
3106 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3107 1 : CPLHTTPDestroyResult(psResult);
3108 :
3109 : // Valid 2 parts, no header
3110 : psResult =
3111 1 : static_cast<CPLHTTPResult *>(CPLCalloc(1, sizeof(CPLHTTPResult)));
3112 1 : psResult->pszContentType =
3113 1 : CPLStrdup("multipart/form-data; boundary=myboundary");
3114 : {
3115 1 : const char *pszText = "--myboundary some junk\r\n"
3116 : "\r\n"
3117 : "Bla"
3118 : "\r\n"
3119 : "--myboundary\r\n"
3120 : "\r\n"
3121 : "second part"
3122 : "\r\n"
3123 : "--myboundary--\r\n";
3124 1 : psResult->pabyData = reinterpret_cast<GByte *>(CPLStrdup(pszText));
3125 1 : psResult->nDataLen = static_cast<int>(strlen(pszText));
3126 : }
3127 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3128 1 : EXPECT_EQ(psResult->nMimePartCount, 2);
3129 1 : if (psResult->nMimePartCount == 2)
3130 : {
3131 1 : EXPECT_EQ(psResult->pasMimePart[0].papszHeaders,
3132 : static_cast<char **>(nullptr));
3133 1 : EXPECT_EQ(psResult->pasMimePart[0].nDataLen, 3);
3134 1 : EXPECT_TRUE(
3135 : strncmp(reinterpret_cast<char *>(psResult->pasMimePart[0].pabyData),
3136 : "Bla", 3) == 0);
3137 1 : EXPECT_EQ(psResult->pasMimePart[1].nDataLen, 11);
3138 1 : EXPECT_TRUE(
3139 : strncmp(reinterpret_cast<char *>(psResult->pasMimePart[1].pabyData),
3140 : "second part", 11) == 0);
3141 : }
3142 1 : EXPECT_TRUE(CPL_TO_BOOL(CPLHTTPParseMultipartMime(psResult)));
3143 1 : CPLHTTPDestroyResult(psResult);
3144 1 : }
3145 :
3146 : // Test cpl::down_cast
3147 4 : TEST_F(test_cpl, down_cast)
3148 : {
3149 : struct Base
3150 : {
3151 2 : virtual ~Base()
3152 2 : {
3153 2 : }
3154 : };
3155 :
3156 : struct Derived : public Base
3157 : {
3158 : };
3159 :
3160 0 : Base b;
3161 0 : Derived d;
3162 1 : Base *p_b_d = &d;
3163 :
3164 : #ifdef wont_compile
3165 : struct OtherBase
3166 : {
3167 : };
3168 :
3169 : OtherBase ob;
3170 : ASSERT_EQ(cpl::down_cast<OtherBase *>(p_b_d), &ob);
3171 : #endif
3172 : #ifdef compile_with_warning
3173 : ASSERT_EQ(cpl::down_cast<Base *>(p_b_d), p_b_d);
3174 : #endif
3175 1 : ASSERT_EQ(cpl::down_cast<Derived *>(p_b_d), &d);
3176 1 : ASSERT_EQ(cpl::down_cast<Derived *>(static_cast<Base *>(nullptr)),
3177 : static_cast<Derived *>(nullptr));
3178 : }
3179 :
3180 : // Test CPLPrintTime() in particular case of RFC822 formatting in C locale
3181 4 : TEST_F(test_cpl, CPLPrintTime_RFC822)
3182 : {
3183 : char szDate[64];
3184 : struct tm tm;
3185 1 : tm.tm_sec = 56;
3186 1 : tm.tm_min = 34;
3187 1 : tm.tm_hour = 12;
3188 1 : tm.tm_mday = 20;
3189 1 : tm.tm_mon = 6 - 1;
3190 1 : tm.tm_year = 2018 - 1900;
3191 1 : tm.tm_wday = 3; // Wednesday
3192 1 : tm.tm_yday = 0; // unused
3193 1 : tm.tm_isdst = 0; // unused
3194 1 : int nRet = CPLPrintTime(szDate, sizeof(szDate) - 1,
3195 : "%a, %d %b %Y %H:%M:%S GMT", &tm, "C");
3196 1 : szDate[nRet] = 0;
3197 1 : ASSERT_STREQ(szDate, "Wed, 20 Jun 2018 12:34:56 GMT");
3198 : }
3199 :
3200 : // Test CPLAutoClose
3201 4 : TEST_F(test_cpl, CPLAutoClose)
3202 : {
3203 : static int counter = 0;
3204 :
3205 : class AutoCloseTest
3206 : {
3207 : public:
3208 2 : AutoCloseTest()
3209 2 : {
3210 2 : counter += 222;
3211 2 : }
3212 :
3213 4 : virtual ~AutoCloseTest()
3214 2 : {
3215 2 : counter -= 22;
3216 4 : }
3217 :
3218 2 : static AutoCloseTest *Create()
3219 : {
3220 2 : return new AutoCloseTest;
3221 : }
3222 :
3223 2 : static void Destroy(AutoCloseTest *p)
3224 : {
3225 2 : delete p;
3226 2 : }
3227 : };
3228 :
3229 : {
3230 1 : AutoCloseTest *p1 = AutoCloseTest::Create();
3231 2 : CPL_AUTO_CLOSE_WARP(p1, AutoCloseTest::Destroy);
3232 :
3233 1 : AutoCloseTest *p2 = AutoCloseTest::Create();
3234 1 : CPL_AUTO_CLOSE_WARP(p2, AutoCloseTest::Destroy);
3235 : }
3236 1 : ASSERT_EQ(counter, 400);
3237 : }
3238 :
3239 : // Test cpl_minixml
3240 4 : TEST_F(test_cpl, cpl_minixml)
3241 : {
3242 1 : CPLXMLNode *psRoot = CPLCreateXMLNode(nullptr, CXT_Element, "Root");
3243 1 : CPLXMLNode *psElt = CPLCreateXMLElementAndValue(psRoot, "Elt", "value");
3244 1 : CPLAddXMLAttributeAndValue(psElt, "attr1", "val1");
3245 1 : CPLAddXMLAttributeAndValue(psElt, "attr2", "val2");
3246 1 : EXPECT_GE(CPLXMLNodeGetRAMUsageEstimate(psRoot), 0);
3247 1 : char *str = CPLSerializeXMLTree(psRoot);
3248 1 : CPLDestroyXMLNode(psRoot);
3249 1 : ASSERT_STREQ(
3250 : str,
3251 : "<Root>\n <Elt attr1=\"val1\" attr2=\"val2\">value</Elt>\n</Root>\n");
3252 1 : CPLFree(str);
3253 : }
3254 :
3255 : // Test CPLCharUniquePtr
3256 4 : TEST_F(test_cpl, CPLCharUniquePtr)
3257 : {
3258 0 : CPLCharUniquePtr x;
3259 1 : ASSERT_TRUE(x.get() == nullptr);
3260 1 : x.reset(CPLStrdup("foo"));
3261 1 : ASSERT_STREQ(x.get(), "foo");
3262 : }
3263 :
3264 : // Test CPLJSonStreamingWriter
3265 4 : TEST_F(test_cpl, CPLJSonStreamingWriter)
3266 : {
3267 : {
3268 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3269 2 : ASSERT_EQ(x.GetString(), std::string());
3270 : }
3271 : {
3272 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3273 1 : x.Add(true);
3274 2 : ASSERT_EQ(x.GetString(), std::string("true"));
3275 : }
3276 : {
3277 1 : std::string res;
3278 :
3279 : struct MyCallback
3280 : {
3281 1 : static void f(const char *pszText, void *user_data)
3282 : {
3283 1 : *static_cast<std::string *>(user_data) += pszText;
3284 1 : }
3285 : };
3286 :
3287 1 : CPLJSonStreamingWriter x(&MyCallback::f, &res);
3288 1 : x.Add(true);
3289 2 : ASSERT_EQ(x.GetString(), std::string());
3290 2 : ASSERT_EQ(res, std::string("true"));
3291 : }
3292 : {
3293 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3294 1 : x.Add(false);
3295 2 : ASSERT_EQ(x.GetString(), std::string("false"));
3296 : }
3297 : {
3298 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3299 1 : x.AddNull();
3300 2 : ASSERT_EQ(x.GetString(), std::string("null"));
3301 : }
3302 : {
3303 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3304 1 : x.Add(1);
3305 2 : ASSERT_EQ(x.GetString(), std::string("1"));
3306 : }
3307 : {
3308 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3309 1 : x.Add(4200000000U);
3310 2 : ASSERT_EQ(x.GetString(), std::string("4200000000"));
3311 : }
3312 : {
3313 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3314 1 : x.Add(static_cast<std::int64_t>(-10000) * 1000000);
3315 2 : ASSERT_EQ(x.GetString(), std::string("-10000000000"));
3316 : }
3317 : {
3318 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3319 1 : x.Add(static_cast<std::uint64_t>(10000) * 1000000);
3320 2 : ASSERT_EQ(x.GetString(), std::string("10000000000"));
3321 : }
3322 : {
3323 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3324 1 : x.Add(1.5f);
3325 2 : ASSERT_EQ(x.GetString(), std::string("1.5"));
3326 : }
3327 : {
3328 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3329 1 : x.Add(std::numeric_limits<float>::quiet_NaN());
3330 2 : ASSERT_EQ(x.GetString(), std::string("\"NaN\""));
3331 : }
3332 : {
3333 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3334 1 : x.Add(std::numeric_limits<float>::infinity());
3335 2 : ASSERT_EQ(x.GetString(), std::string("\"Infinity\""));
3336 : }
3337 : {
3338 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3339 1 : x.Add(-std::numeric_limits<float>::infinity());
3340 2 : ASSERT_EQ(x.GetString(), std::string("\"-Infinity\""));
3341 : }
3342 : {
3343 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3344 1 : x.Add(1.25);
3345 2 : ASSERT_EQ(x.GetString(), std::string("1.25"));
3346 : }
3347 : {
3348 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3349 1 : x.Add(std::numeric_limits<double>::quiet_NaN());
3350 2 : ASSERT_EQ(x.GetString(), std::string("\"NaN\""));
3351 : }
3352 : {
3353 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3354 1 : x.Add(std::numeric_limits<double>::infinity());
3355 2 : ASSERT_EQ(x.GetString(), std::string("\"Infinity\""));
3356 : }
3357 : {
3358 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3359 1 : x.Add(-std::numeric_limits<double>::infinity());
3360 2 : ASSERT_EQ(x.GetString(), std::string("\"-Infinity\""));
3361 : }
3362 : {
3363 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3364 1 : x.Add(std::string("foo\\bar\"baz\b\f\n\r\t"
3365 : "\x01"
3366 : "boo"));
3367 2 : ASSERT_EQ(
3368 : x.GetString(),
3369 : std::string("\"foo\\\\bar\\\"baz\\b\\f\\n\\r\\t\\u0001boo\""));
3370 : }
3371 : {
3372 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3373 1 : x.Add("foo\\bar\"baz\b\f\n\r\t"
3374 : "\x01"
3375 : "boo");
3376 2 : ASSERT_EQ(
3377 : x.GetString(),
3378 : std::string("\"foo\\\\bar\\\"baz\\b\\f\\n\\r\\t\\u0001boo\""));
3379 : }
3380 : {
3381 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3382 1 : x.SetPrettyFormatting(false);
3383 : {
3384 1 : auto ctxt(x.MakeObjectContext());
3385 : }
3386 2 : ASSERT_EQ(x.GetString(), std::string("{}"));
3387 : }
3388 : {
3389 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3390 : {
3391 1 : auto ctxt(x.MakeObjectContext());
3392 : }
3393 2 : ASSERT_EQ(x.GetString(), std::string("{}"));
3394 : }
3395 : {
3396 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3397 1 : x.SetPrettyFormatting(false);
3398 : {
3399 2 : auto ctxt(x.MakeObjectContext());
3400 1 : x.AddObjKey("key");
3401 1 : x.Add("value");
3402 : }
3403 2 : ASSERT_EQ(x.GetString(), std::string("{\"key\":\"value\"}"));
3404 : }
3405 : {
3406 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3407 : {
3408 2 : auto ctxt(x.MakeObjectContext());
3409 1 : x.AddObjKey("key");
3410 1 : x.Add("value");
3411 : }
3412 2 : ASSERT_EQ(x.GetString(), std::string("{\n \"key\": \"value\"\n}"));
3413 : }
3414 : {
3415 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3416 : {
3417 2 : auto ctxt(x.MakeObjectContext());
3418 1 : x.AddObjKey("key");
3419 1 : x.Add("value");
3420 1 : x.AddObjKey("key2");
3421 1 : x.Add("value2");
3422 : }
3423 2 : ASSERT_EQ(
3424 : x.GetString(),
3425 : std::string("{\n \"key\": \"value\",\n \"key2\": \"value2\"\n}"));
3426 : }
3427 : {
3428 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3429 : {
3430 1 : auto ctxt(x.MakeArrayContext());
3431 : }
3432 2 : ASSERT_EQ(x.GetString(), std::string("[]"));
3433 : }
3434 : {
3435 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3436 : {
3437 2 : auto ctxt(x.MakeArrayContext());
3438 1 : x.Add(1);
3439 : }
3440 2 : ASSERT_EQ(x.GetString(), std::string("[\n 1\n]"));
3441 : }
3442 : {
3443 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3444 : {
3445 2 : auto ctxt(x.MakeArrayContext());
3446 1 : x.Add(1);
3447 1 : x.Add(2);
3448 : }
3449 2 : ASSERT_EQ(x.GetString(), std::string("[\n 1,\n 2\n]"));
3450 : }
3451 : {
3452 1 : CPLJSonStreamingWriter x(nullptr, nullptr);
3453 : {
3454 2 : auto ctxt(x.MakeArrayContext(true));
3455 1 : x.Add(1);
3456 1 : x.Add(2);
3457 : }
3458 2 : ASSERT_EQ(x.GetString(), std::string("[1, 2]"));
3459 : }
3460 : }
3461 :
3462 : // Test CPLWorkerThreadPool
3463 4 : TEST_F(test_cpl, CPLWorkerThreadPool)
3464 : {
3465 1 : CPLWorkerThreadPool oPool;
3466 1 : ASSERT_TRUE(oPool.Setup(2, nullptr, nullptr, false));
3467 :
3468 3000 : const auto myJob = [](void *pData) { (*static_cast<int *>(pData))++; };
3469 :
3470 : {
3471 1 : std::vector<int> res(1000);
3472 1001 : for (int i = 0; i < 1000; i++)
3473 : {
3474 1000 : res[i] = i;
3475 1000 : oPool.SubmitJob(myJob, &res[i]);
3476 : }
3477 1 : oPool.WaitCompletion();
3478 1001 : for (int i = 0; i < 1000; i++)
3479 : {
3480 1000 : ASSERT_EQ(res[i], i + 1);
3481 : }
3482 : }
3483 :
3484 : {
3485 1 : std::vector<int> res(1000);
3486 1 : std::vector<void *> resPtr(1000);
3487 1001 : for (int i = 0; i < 1000; i++)
3488 : {
3489 1000 : res[i] = i;
3490 1000 : resPtr[i] = res.data() + i;
3491 : }
3492 1 : oPool.SubmitJobs(myJob, resPtr);
3493 1 : oPool.WaitEvent();
3494 1 : oPool.WaitCompletion();
3495 1001 : for (int i = 0; i < 1000; i++)
3496 : {
3497 1000 : ASSERT_EQ(res[i], i + 1);
3498 : }
3499 : }
3500 :
3501 : {
3502 1 : auto jobQueue1 = oPool.CreateJobQueue();
3503 1 : auto jobQueue2 = oPool.CreateJobQueue();
3504 :
3505 1 : ASSERT_EQ(jobQueue1->GetPool(), &oPool);
3506 :
3507 1 : std::vector<int> res(1000);
3508 1001 : for (int i = 0; i < 1000; i++)
3509 : {
3510 1000 : res[i] = i;
3511 1000 : if (i % 2)
3512 500 : jobQueue1->SubmitJob(myJob, &res[i]);
3513 : else
3514 500 : jobQueue2->SubmitJob(myJob, &res[i]);
3515 : }
3516 1 : jobQueue1->WaitCompletion();
3517 1 : jobQueue2->WaitCompletion();
3518 1001 : for (int i = 0; i < 1000; i++)
3519 : {
3520 1000 : ASSERT_EQ(res[i], i + 1);
3521 : }
3522 : }
3523 : }
3524 :
3525 : // Test CPLHTTPFetch
3526 4 : TEST_F(test_cpl, CPLHTTPFetch)
3527 : {
3528 : #ifdef HAVE_CURL
3529 2 : CPLStringList oOptions;
3530 1 : oOptions.AddNameValue("FORM_ITEM_COUNT", "5");
3531 1 : oOptions.AddNameValue("FORM_KEY_0", "qqq");
3532 1 : oOptions.AddNameValue("FORM_VALUE_0", "www");
3533 1 : CPLHTTPResult *pResult = CPLHTTPFetch("http://example.com", oOptions);
3534 1 : EXPECT_EQ(pResult->nStatus, 34);
3535 1 : CPLHTTPDestroyResult(pResult);
3536 1 : pResult = nullptr;
3537 1 : oOptions.Clear();
3538 :
3539 1 : oOptions.AddNameValue("FORM_FILE_PATH", "not_existed");
3540 1 : pResult = CPLHTTPFetch("http://example.com", oOptions);
3541 1 : EXPECT_EQ(pResult->nStatus, 34);
3542 1 : CPLHTTPDestroyResult(pResult);
3543 : #else
3544 : GTEST_SKIP() << "CURL not available";
3545 : #endif // HAVE_CURL
3546 1 : }
3547 :
3548 : // Test CPLHTTPPushFetchCallback
3549 4 : TEST_F(test_cpl, CPLHTTPPushFetchCallback)
3550 : {
3551 : struct myCbkUserDataStruct
3552 : {
3553 : CPLString osURL{};
3554 : CSLConstList papszOptions = nullptr;
3555 : GDALProgressFunc pfnProgress = nullptr;
3556 : void *pProgressArg = nullptr;
3557 : CPLHTTPFetchWriteFunc pfnWrite = nullptr;
3558 : void *pWriteArg = nullptr;
3559 : };
3560 :
3561 1 : const auto myCbk = [](const char *pszURL, CSLConstList papszOptions,
3562 : GDALProgressFunc pfnProgress, void *pProgressArg,
3563 : CPLHTTPFetchWriteFunc pfnWrite, void *pWriteArg,
3564 : void *pUserData)
3565 : {
3566 1 : myCbkUserDataStruct *pCbkUserData =
3567 : static_cast<myCbkUserDataStruct *>(pUserData);
3568 1 : pCbkUserData->osURL = pszURL;
3569 1 : pCbkUserData->papszOptions = papszOptions;
3570 1 : pCbkUserData->pfnProgress = pfnProgress;
3571 1 : pCbkUserData->pProgressArg = pProgressArg;
3572 1 : pCbkUserData->pfnWrite = pfnWrite;
3573 1 : pCbkUserData->pWriteArg = pWriteArg;
3574 : auto psResult =
3575 1 : static_cast<CPLHTTPResult *>(CPLCalloc(sizeof(CPLHTTPResult), 1));
3576 1 : psResult->nStatus = 123;
3577 1 : return psResult;
3578 : };
3579 :
3580 1 : myCbkUserDataStruct userData;
3581 1 : EXPECT_TRUE(CPLHTTPPushFetchCallback(myCbk, &userData));
3582 :
3583 1 : int progressArg = 0;
3584 0 : const auto myWriteCbk = [](void *, size_t, size_t, void *) -> size_t
3585 0 : { return 0; };
3586 1 : int writeCbkArg = 00;
3587 :
3588 1 : CPLStringList aosOptions;
3589 1 : GDALProgressFunc pfnProgress = GDALTermProgress;
3590 1 : CPLHTTPFetchWriteFunc pfnWriteCbk = myWriteCbk;
3591 : CPLHTTPResult *pResult =
3592 1 : CPLHTTPFetchEx("http://example.com", aosOptions.List(), pfnProgress,
3593 : &progressArg, pfnWriteCbk, &writeCbkArg);
3594 1 : ASSERT_TRUE(pResult != nullptr);
3595 1 : EXPECT_EQ(pResult->nStatus, 123);
3596 1 : CPLHTTPDestroyResult(pResult);
3597 :
3598 1 : EXPECT_TRUE(CPLHTTPPopFetchCallback());
3599 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
3600 1 : EXPECT_TRUE(!CPLHTTPPopFetchCallback());
3601 1 : CPLPopErrorHandler();
3602 :
3603 1 : EXPECT_STREQ(userData.osURL, "http://example.com");
3604 1 : EXPECT_EQ(userData.papszOptions, aosOptions.List());
3605 1 : EXPECT_EQ(userData.pfnProgress, pfnProgress);
3606 1 : EXPECT_EQ(userData.pProgressArg, &progressArg);
3607 1 : EXPECT_EQ(userData.pfnWrite, pfnWriteCbk);
3608 1 : EXPECT_EQ(userData.pWriteArg, &writeCbkArg);
3609 : }
3610 :
3611 : // Test CPLHTTPSetFetchCallback
3612 4 : TEST_F(test_cpl, CPLHTTPSetFetchCallback)
3613 : {
3614 : struct myCbkUserDataStruct
3615 : {
3616 : CPLString osURL{};
3617 : CSLConstList papszOptions = nullptr;
3618 : GDALProgressFunc pfnProgress = nullptr;
3619 : void *pProgressArg = nullptr;
3620 : CPLHTTPFetchWriteFunc pfnWrite = nullptr;
3621 : void *pWriteArg = nullptr;
3622 : };
3623 :
3624 1 : const auto myCbk2 = [](const char *pszURL, CSLConstList papszOptions,
3625 : GDALProgressFunc pfnProgress, void *pProgressArg,
3626 : CPLHTTPFetchWriteFunc pfnWrite, void *pWriteArg,
3627 : void *pUserData)
3628 : {
3629 1 : myCbkUserDataStruct *pCbkUserData =
3630 : static_cast<myCbkUserDataStruct *>(pUserData);
3631 1 : pCbkUserData->osURL = pszURL;
3632 1 : pCbkUserData->papszOptions = papszOptions;
3633 1 : pCbkUserData->pfnProgress = pfnProgress;
3634 1 : pCbkUserData->pProgressArg = pProgressArg;
3635 1 : pCbkUserData->pfnWrite = pfnWrite;
3636 1 : pCbkUserData->pWriteArg = pWriteArg;
3637 : auto psResult =
3638 1 : static_cast<CPLHTTPResult *>(CPLCalloc(sizeof(CPLHTTPResult), 1));
3639 1 : psResult->nStatus = 124;
3640 1 : return psResult;
3641 : };
3642 1 : myCbkUserDataStruct userData2;
3643 1 : CPLHTTPSetFetchCallback(myCbk2, &userData2);
3644 :
3645 1 : int progressArg = 0;
3646 0 : const auto myWriteCbk = [](void *, size_t, size_t, void *) -> size_t
3647 0 : { return 0; };
3648 1 : int writeCbkArg = 00;
3649 :
3650 1 : CPLStringList aosOptions;
3651 1 : GDALProgressFunc pfnProgress = GDALTermProgress;
3652 1 : CPLHTTPFetchWriteFunc pfnWriteCbk = myWriteCbk;
3653 : CPLHTTPResult *pResult =
3654 1 : CPLHTTPFetchEx("http://example.com", aosOptions.List(), pfnProgress,
3655 : &progressArg, pfnWriteCbk, &writeCbkArg);
3656 1 : ASSERT_TRUE(pResult != nullptr);
3657 1 : EXPECT_EQ(pResult->nStatus, 124);
3658 1 : CPLHTTPDestroyResult(pResult);
3659 :
3660 1 : CPLHTTPSetFetchCallback(nullptr, nullptr);
3661 :
3662 1 : EXPECT_STREQ(userData2.osURL, "http://example.com");
3663 1 : EXPECT_EQ(userData2.papszOptions, aosOptions.List());
3664 1 : EXPECT_EQ(userData2.pfnProgress, pfnProgress);
3665 1 : EXPECT_EQ(userData2.pProgressArg, &progressArg);
3666 1 : EXPECT_EQ(userData2.pfnWrite, pfnWriteCbk);
3667 1 : EXPECT_EQ(userData2.pWriteArg, &writeCbkArg);
3668 : }
3669 :
3670 : // Test CPLLoadConfigOptionsFromFile() and
3671 : // CPLLoadConfigOptionsFromPredefinedFiles()
3672 4 : TEST_F(test_cpl, CPLLoadConfigOptionsFromFile)
3673 : {
3674 1 : CPLLoadConfigOptionsFromFile("/i/do/not/exist", false);
3675 :
3676 1 : VSILFILE *fp = VSIFOpenL("/vsimem/.gdal/gdalrc", "wb");
3677 1 : VSIFPrintfL(fp, "# some comment\n");
3678 1 : VSIFPrintfL(fp, "\n"); // blank line
3679 1 : VSIFPrintfL(fp, " \n"); // blank line
3680 1 : VSIFPrintfL(fp, "[configoptions]\n");
3681 1 : VSIFPrintfL(fp, "# some comment\n");
3682 1 : VSIFPrintfL(fp, "FOO_CONFIGOPTION=BAR\n");
3683 1 : VSIFCloseL(fp);
3684 :
3685 : // Try CPLLoadConfigOptionsFromFile()
3686 1 : CPLLoadConfigOptionsFromFile("/vsimem/.gdal/gdalrc", false);
3687 1 : ASSERT_TRUE(EQUAL(CPLGetConfigOption("FOO_CONFIGOPTION", ""), "BAR"));
3688 1 : CPLSetConfigOption("FOO_CONFIGOPTION", nullptr);
3689 :
3690 : // Try CPLLoadConfigOptionsFromPredefinedFiles() with GDAL_CONFIG_FILE set
3691 1 : CPLSetConfigOption("GDAL_CONFIG_FILE", "/vsimem/.gdal/gdalrc");
3692 1 : CPLLoadConfigOptionsFromPredefinedFiles();
3693 1 : ASSERT_TRUE(EQUAL(CPLGetConfigOption("FOO_CONFIGOPTION", ""), "BAR"));
3694 1 : CPLSetConfigOption("FOO_CONFIGOPTION", nullptr);
3695 :
3696 : // Try CPLLoadConfigOptionsFromPredefinedFiles() with $HOME/.gdal/gdalrc
3697 : // file
3698 : #ifdef _WIN32
3699 : const char *pszHOMEEnvVarName = "USERPROFILE";
3700 : #else
3701 1 : const char *pszHOMEEnvVarName = "HOME";
3702 : #endif
3703 1 : CPLString osOldVal(CPLGetConfigOption(pszHOMEEnvVarName, ""));
3704 1 : CPLSetConfigOption(pszHOMEEnvVarName, "/vsimem/");
3705 1 : CPLLoadConfigOptionsFromPredefinedFiles();
3706 1 : ASSERT_TRUE(EQUAL(CPLGetConfigOption("FOO_CONFIGOPTION", ""), "BAR"));
3707 1 : CPLSetConfigOption("FOO_CONFIGOPTION", nullptr);
3708 1 : if (!osOldVal.empty())
3709 1 : CPLSetConfigOption(pszHOMEEnvVarName, osOldVal.c_str());
3710 : else
3711 0 : CPLSetConfigOption(pszHOMEEnvVarName, nullptr);
3712 :
3713 1 : VSIUnlink("/vsimem/.gdal/gdalrc");
3714 : }
3715 :
3716 : // Test decompressor side of cpl_compressor.h
3717 4 : TEST_F(test_cpl, decompressor)
3718 : {
3719 : const auto compressionLambda =
3720 0 : [](const void * /* input_data */, size_t /* input_size */,
3721 : void ** /* output_data */, size_t * /* output_size */,
3722 : CSLConstList /* options */, void * /* compressor_user_data */)
3723 0 : { return false; };
3724 1 : int dummy = 0;
3725 :
3726 : CPLCompressor sComp;
3727 1 : sComp.nStructVersion = 1;
3728 1 : sComp.eType = CCT_COMPRESSOR;
3729 1 : sComp.pszId = "my_comp";
3730 1 : const char *const apszMetadata[] = {"FOO=BAR", nullptr};
3731 1 : sComp.papszMetadata = apszMetadata;
3732 1 : sComp.pfnFunc = compressionLambda;
3733 1 : sComp.user_data = &dummy;
3734 :
3735 1 : ASSERT_TRUE(CPLRegisterDecompressor(&sComp));
3736 :
3737 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
3738 1 : ASSERT_TRUE(!CPLRegisterDecompressor(&sComp));
3739 1 : CPLPopErrorHandler();
3740 :
3741 1 : char **decompressors = CPLGetDecompressors();
3742 1 : ASSERT_TRUE(decompressors != nullptr);
3743 1 : EXPECT_TRUE(CSLFindString(decompressors, sComp.pszId) >= 0);
3744 9 : for (auto iter = decompressors; *iter; ++iter)
3745 : {
3746 8 : const auto pCompressor = CPLGetDecompressor(*iter);
3747 8 : EXPECT_TRUE(pCompressor);
3748 8 : if (pCompressor)
3749 : {
3750 : const char *pszOptions =
3751 8 : CSLFetchNameValue(pCompressor->papszMetadata, "OPTIONS");
3752 8 : if (pszOptions)
3753 : {
3754 3 : auto psNode = CPLParseXMLString(pszOptions);
3755 3 : EXPECT_TRUE(psNode);
3756 3 : CPLDestroyXMLNode(psNode);
3757 : }
3758 : else
3759 : {
3760 5 : CPLDebug("TEST", "Decompressor %s has no OPTIONS", *iter);
3761 : }
3762 : }
3763 : }
3764 1 : CSLDestroy(decompressors);
3765 :
3766 1 : EXPECT_TRUE(CPLGetDecompressor("invalid") == nullptr);
3767 1 : const auto pCompressor = CPLGetDecompressor(sComp.pszId);
3768 1 : ASSERT_TRUE(pCompressor);
3769 1 : EXPECT_STREQ(pCompressor->pszId, sComp.pszId);
3770 1 : EXPECT_EQ(CSLCount(pCompressor->papszMetadata),
3771 : CSLCount(sComp.papszMetadata));
3772 1 : EXPECT_TRUE(pCompressor->pfnFunc != nullptr);
3773 1 : EXPECT_EQ(pCompressor->user_data, sComp.user_data);
3774 :
3775 1 : CPLDestroyCompressorRegistry();
3776 1 : EXPECT_TRUE(CPLGetDecompressor(sComp.pszId) == nullptr);
3777 : }
3778 :
3779 : // Test compressor side of cpl_compressor.h
3780 4 : TEST_F(test_cpl, compressor)
3781 : {
3782 : const auto compressionLambda =
3783 0 : [](const void * /* input_data */, size_t /* input_size */,
3784 : void ** /* output_data */, size_t * /* output_size */,
3785 : CSLConstList /* options */, void * /* compressor_user_data */)
3786 0 : { return false; };
3787 1 : int dummy = 0;
3788 :
3789 : CPLCompressor sComp;
3790 1 : sComp.nStructVersion = 1;
3791 1 : sComp.eType = CCT_COMPRESSOR;
3792 1 : sComp.pszId = "my_comp";
3793 1 : const char *const apszMetadata[] = {"FOO=BAR", nullptr};
3794 1 : sComp.papszMetadata = apszMetadata;
3795 1 : sComp.pfnFunc = compressionLambda;
3796 1 : sComp.user_data = &dummy;
3797 :
3798 1 : ASSERT_TRUE(CPLRegisterCompressor(&sComp));
3799 :
3800 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
3801 1 : ASSERT_TRUE(!CPLRegisterCompressor(&sComp));
3802 1 : CPLPopErrorHandler();
3803 :
3804 1 : char **compressors = CPLGetCompressors();
3805 1 : ASSERT_TRUE(compressors != nullptr);
3806 1 : EXPECT_TRUE(CSLFindString(compressors, sComp.pszId) >= 0);
3807 9 : for (auto iter = compressors; *iter; ++iter)
3808 : {
3809 8 : const auto pCompressor = CPLGetCompressor(*iter);
3810 8 : EXPECT_TRUE(pCompressor);
3811 8 : if (pCompressor)
3812 : {
3813 : const char *pszOptions =
3814 8 : CSLFetchNameValue(pCompressor->papszMetadata, "OPTIONS");
3815 8 : if (pszOptions)
3816 : {
3817 7 : auto psNode = CPLParseXMLString(pszOptions);
3818 7 : EXPECT_TRUE(psNode);
3819 7 : CPLDestroyXMLNode(psNode);
3820 : }
3821 : else
3822 : {
3823 1 : CPLDebug("TEST", "Compressor %s has no OPTIONS", *iter);
3824 : }
3825 : }
3826 : }
3827 1 : CSLDestroy(compressors);
3828 :
3829 1 : EXPECT_TRUE(CPLGetCompressor("invalid") == nullptr);
3830 1 : const auto pCompressor = CPLGetCompressor(sComp.pszId);
3831 1 : ASSERT_TRUE(pCompressor);
3832 1 : if (pCompressor == nullptr)
3833 0 : return;
3834 1 : EXPECT_STREQ(pCompressor->pszId, sComp.pszId);
3835 1 : EXPECT_EQ(CSLCount(pCompressor->papszMetadata),
3836 : CSLCount(sComp.papszMetadata));
3837 1 : EXPECT_TRUE(pCompressor->pfnFunc != nullptr);
3838 1 : EXPECT_EQ(pCompressor->user_data, sComp.user_data);
3839 :
3840 1 : CPLDestroyCompressorRegistry();
3841 1 : EXPECT_TRUE(CPLGetDecompressor(sComp.pszId) == nullptr);
3842 : }
3843 :
3844 : // Test builtin compressors/decompressor
3845 4 : TEST_F(test_cpl, builtin_compressors)
3846 : {
3847 7 : for (const char *id : {"blosc", "zlib", "gzip", "lzma", "zstd", "lz4"})
3848 : {
3849 6 : const auto pCompressor = CPLGetCompressor(id);
3850 6 : if (pCompressor == nullptr)
3851 : {
3852 0 : CPLDebug("TEST", "%s not available", id);
3853 0 : if (strcmp(id, "zlib") == 0 || strcmp(id, "gzip") == 0)
3854 : {
3855 0 : ASSERT_TRUE(false);
3856 : }
3857 0 : continue;
3858 : }
3859 6 : CPLDebug("TEST", "Testing %s", id);
3860 :
3861 6 : const char my_str[] = "my string to compress";
3862 6 : const char *const options[] = {"TYPESIZE=1", nullptr};
3863 :
3864 : // Compressor side
3865 :
3866 : // Just get output size
3867 6 : size_t out_size = 0;
3868 6 : ASSERT_TRUE(pCompressor->pfnFunc(my_str, strlen(my_str), nullptr,
3869 : &out_size, options,
3870 : pCompressor->user_data));
3871 6 : ASSERT_TRUE(out_size != 0);
3872 :
3873 : // Let it alloc the output buffer
3874 6 : void *out_buffer2 = nullptr;
3875 6 : size_t out_size2 = 0;
3876 6 : ASSERT_TRUE(pCompressor->pfnFunc(my_str, strlen(my_str), &out_buffer2,
3877 : &out_size2, options,
3878 : pCompressor->user_data));
3879 6 : ASSERT_TRUE(out_buffer2 != nullptr);
3880 6 : ASSERT_TRUE(out_size2 != 0);
3881 6 : ASSERT_TRUE(out_size2 <= out_size);
3882 :
3883 6 : std::vector<GByte> out_buffer3(out_size);
3884 :
3885 : // Provide not large enough buffer size
3886 6 : size_t out_size3 = 1;
3887 6 : void *out_buffer3_ptr = &out_buffer3[0];
3888 6 : ASSERT_TRUE(!(pCompressor->pfnFunc(my_str, strlen(my_str),
3889 : &out_buffer3_ptr, &out_size3,
3890 : options, pCompressor->user_data)));
3891 :
3892 : // Provide the output buffer
3893 6 : out_size3 = out_buffer3.size();
3894 6 : out_buffer3_ptr = &out_buffer3[0];
3895 6 : ASSERT_TRUE(pCompressor->pfnFunc(my_str, strlen(my_str),
3896 : &out_buffer3_ptr, &out_size3, options,
3897 : pCompressor->user_data));
3898 6 : ASSERT_TRUE(out_buffer3_ptr != nullptr);
3899 6 : ASSERT_TRUE(out_buffer3_ptr == &out_buffer3[0]);
3900 6 : ASSERT_TRUE(out_size3 != 0);
3901 6 : ASSERT_EQ(out_size3, out_size2);
3902 :
3903 6 : out_buffer3.resize(out_size3);
3904 6 : out_buffer3_ptr = &out_buffer3[0];
3905 :
3906 6 : ASSERT_TRUE(memcmp(out_buffer3_ptr, out_buffer2, out_size2) == 0);
3907 :
3908 6 : CPLFree(out_buffer2);
3909 :
3910 6 : const std::vector<GByte> compressedData(out_buffer3);
3911 :
3912 : // Decompressor side
3913 6 : const auto pDecompressor = CPLGetDecompressor(id);
3914 6 : ASSERT_TRUE(pDecompressor != nullptr);
3915 :
3916 6 : out_size = 0;
3917 6 : ASSERT_TRUE(pDecompressor->pfnFunc(
3918 : compressedData.data(), compressedData.size(), nullptr, &out_size,
3919 : nullptr, pDecompressor->user_data));
3920 6 : ASSERT_TRUE(out_size != 0);
3921 6 : ASSERT_TRUE(out_size >= strlen(my_str));
3922 :
3923 6 : out_buffer2 = nullptr;
3924 6 : out_size2 = 0;
3925 6 : ASSERT_TRUE(pDecompressor->pfnFunc(
3926 : compressedData.data(), compressedData.size(), &out_buffer2,
3927 : &out_size2, options, pDecompressor->user_data));
3928 6 : ASSERT_TRUE(out_buffer2 != nullptr);
3929 6 : ASSERT_TRUE(out_size2 != 0);
3930 6 : ASSERT_EQ(out_size2, strlen(my_str));
3931 6 : ASSERT_TRUE(memcmp(out_buffer2, my_str, strlen(my_str)) == 0);
3932 6 : CPLFree(out_buffer2);
3933 :
3934 6 : out_buffer3.clear();
3935 6 : out_buffer3.resize(out_size);
3936 6 : out_size3 = out_buffer3.size();
3937 6 : out_buffer3_ptr = &out_buffer3[0];
3938 6 : ASSERT_TRUE(pDecompressor->pfnFunc(
3939 : compressedData.data(), compressedData.size(), &out_buffer3_ptr,
3940 : &out_size3, options, pDecompressor->user_data));
3941 6 : ASSERT_TRUE(out_buffer3_ptr != nullptr);
3942 6 : ASSERT_TRUE(out_buffer3_ptr == &out_buffer3[0]);
3943 6 : ASSERT_EQ(out_size3, strlen(my_str));
3944 6 : ASSERT_TRUE(memcmp(out_buffer3.data(), my_str, strlen(my_str)) == 0);
3945 : }
3946 : }
3947 :
3948 : // Test builtin compressors/decompressor
3949 4 : TEST_F(test_cpl, builtin_compressors_zlib_high_compression_rate)
3950 : {
3951 1 : const auto pCompressor = CPLGetCompressor("zlib");
3952 1 : ASSERT_TRUE(pCompressor != nullptr);
3953 :
3954 1 : std::vector<GByte> abyInput(1024 * 1024, 0x01);
3955 :
3956 : // Compressor side
3957 :
3958 : // Let it alloc the output buffer
3959 1 : void *out_buffer = nullptr;
3960 1 : size_t out_size = 0;
3961 1 : ASSERT_TRUE(pCompressor->pfnFunc(abyInput.data(), abyInput.size(),
3962 : &out_buffer, &out_size, nullptr,
3963 : pCompressor->user_data));
3964 1 : ASSERT_TRUE(out_buffer != nullptr);
3965 1 : ASSERT_TRUE(out_size != 0);
3966 :
3967 : // Decompressor side
3968 1 : const auto pDecompressor = CPLGetDecompressor("zlib");
3969 1 : ASSERT_TRUE(pDecompressor != nullptr);
3970 :
3971 1 : void *out_buffer2 = nullptr;
3972 1 : size_t out_size2 = 0;
3973 1 : ASSERT_TRUE(pDecompressor->pfnFunc(out_buffer, out_size, &out_buffer2,
3974 : &out_size2, nullptr,
3975 : pDecompressor->user_data));
3976 1 : CPLFree(out_buffer);
3977 :
3978 1 : ASSERT_TRUE(out_buffer2 != nullptr);
3979 1 : ASSERT_TRUE(out_size2 != 0);
3980 1 : ASSERT_EQ(out_size2, abyInput.size());
3981 1 : ASSERT_TRUE(memcmp(out_buffer2, abyInput.data(), abyInput.size()) == 0);
3982 1 : CPLFree(out_buffer2);
3983 : }
3984 :
3985 : template <class T> struct TesterDelta
3986 : {
3987 24 : static void test(const char *dtypeOption)
3988 : {
3989 24 : const auto pCompressor = CPLGetCompressor("delta");
3990 24 : ASSERT_TRUE(pCompressor);
3991 24 : if (pCompressor == nullptr)
3992 0 : return;
3993 24 : const auto pDecompressor = CPLGetDecompressor("delta");
3994 24 : ASSERT_TRUE(pDecompressor);
3995 24 : if (pDecompressor == nullptr)
3996 0 : return;
3997 :
3998 24 : const T tabIn[] = {static_cast<T>(-2), 3, 1};
3999 : T tabCompress[3];
4000 : T tabOut[3];
4001 24 : const char *const apszOptions[] = {dtypeOption, nullptr};
4002 :
4003 24 : void *outPtr = &tabCompress[0];
4004 24 : size_t outSize = sizeof(tabCompress);
4005 24 : ASSERT_TRUE(pCompressor->pfnFunc(&tabIn[0], sizeof(tabIn), &outPtr,
4006 : &outSize, apszOptions,
4007 : pCompressor->user_data));
4008 24 : ASSERT_EQ(outSize, sizeof(tabCompress));
4009 :
4010 : // ASSERT_EQ(tabCompress[0], 2);
4011 : // ASSERT_EQ(tabCompress[1], 1);
4012 : // ASSERT_EQ(tabCompress[2], -2);
4013 :
4014 24 : outPtr = &tabOut[0];
4015 24 : outSize = sizeof(tabOut);
4016 24 : ASSERT_TRUE(pDecompressor->pfnFunc(&tabCompress[0], sizeof(tabCompress),
4017 : &outPtr, &outSize, apszOptions,
4018 : pDecompressor->user_data));
4019 24 : ASSERT_EQ(outSize, sizeof(tabOut));
4020 24 : ASSERT_EQ(tabOut[0], tabIn[0]);
4021 24 : ASSERT_EQ(tabOut[1], tabIn[1]);
4022 24 : ASSERT_EQ(tabOut[2], tabIn[2]);
4023 : }
4024 : };
4025 :
4026 : // Test delta compressor/decompressor
4027 4 : TEST_F(test_cpl, delta_compressor)
4028 : {
4029 1 : TesterDelta<int8_t>::test("DTYPE=i1");
4030 :
4031 1 : TesterDelta<uint8_t>::test("DTYPE=u1");
4032 :
4033 1 : TesterDelta<int16_t>::test("DTYPE=i2");
4034 1 : TesterDelta<int16_t>::test("DTYPE=<i2");
4035 1 : TesterDelta<int16_t>::test("DTYPE=>i2");
4036 :
4037 1 : TesterDelta<uint16_t>::test("DTYPE=u2");
4038 1 : TesterDelta<uint16_t>::test("DTYPE=<u2");
4039 1 : TesterDelta<uint16_t>::test("DTYPE=>u2");
4040 :
4041 1 : TesterDelta<int32_t>::test("DTYPE=i4");
4042 1 : TesterDelta<int32_t>::test("DTYPE=<i4");
4043 1 : TesterDelta<int32_t>::test("DTYPE=>i4");
4044 :
4045 1 : TesterDelta<uint32_t>::test("DTYPE=u4");
4046 1 : TesterDelta<uint32_t>::test("DTYPE=<u4");
4047 1 : TesterDelta<uint32_t>::test("DTYPE=>u4");
4048 :
4049 1 : TesterDelta<int64_t>::test("DTYPE=i8");
4050 1 : TesterDelta<int64_t>::test("DTYPE=<i8");
4051 1 : TesterDelta<int64_t>::test("DTYPE=>i8");
4052 :
4053 1 : TesterDelta<uint64_t>::test("DTYPE=u8");
4054 1 : TesterDelta<uint64_t>::test("DTYPE=<u8");
4055 1 : TesterDelta<uint64_t>::test("DTYPE=>u8");
4056 :
4057 1 : TesterDelta<float>::test("DTYPE=f4");
4058 : #ifdef CPL_MSB
4059 : TesterDelta<float>::test("DTYPE=>f4");
4060 : #else
4061 1 : TesterDelta<float>::test("DTYPE=<f4");
4062 : #endif
4063 :
4064 1 : TesterDelta<double>::test("DTYPE=f8");
4065 : #ifdef CPL_MSB
4066 : TesterDelta<double>::test("DTYPE=>f8");
4067 : #else
4068 1 : TesterDelta<double>::test("DTYPE=<f8");
4069 : #endif
4070 1 : }
4071 :
4072 : // Test CPLQuadTree
4073 4 : TEST_F(test_cpl, CPLQuadTree)
4074 : {
4075 1 : unsigned next = 0;
4076 :
4077 4 : const auto DummyRandInit = [&next](unsigned initValue)
4078 5 : { next = initValue; };
4079 :
4080 1 : constexpr int MAX_RAND_VAL = 32767;
4081 :
4082 : // Slightly improved version of https://xkcd.com/221/, as suggested by
4083 : // "man srand"
4084 16000 : const auto DummyRand = [&]()
4085 : {
4086 16000 : next = next * 1103515245 + 12345;
4087 16000 : return ((unsigned)(next / 65536) % (MAX_RAND_VAL + 1));
4088 1 : };
4089 :
4090 : CPLRectObj globalbounds;
4091 1 : globalbounds.minx = 0;
4092 1 : globalbounds.miny = 0;
4093 1 : globalbounds.maxx = 1;
4094 1 : globalbounds.maxy = 1;
4095 :
4096 1 : auto hTree = CPLQuadTreeCreate(&globalbounds, nullptr);
4097 1 : ASSERT_TRUE(hTree != nullptr);
4098 :
4099 4000 : const auto GenerateRandomRect = [&](CPLRectObj &rect)
4100 : {
4101 4000 : rect.minx = double(DummyRand()) / MAX_RAND_VAL;
4102 4000 : rect.miny = double(DummyRand()) / MAX_RAND_VAL;
4103 4000 : rect.maxx =
4104 4000 : rect.minx + double(DummyRand()) / MAX_RAND_VAL * (1 - rect.minx);
4105 4000 : rect.maxy =
4106 4000 : rect.miny + double(DummyRand()) / MAX_RAND_VAL * (1 - rect.miny);
4107 4001 : };
4108 :
4109 3 : for (int j = 0; j < 2; j++)
4110 : {
4111 2 : DummyRandInit(j);
4112 2002 : for (int i = 0; i < 1000; i++)
4113 : {
4114 : CPLRectObj rect;
4115 2000 : GenerateRandomRect(rect);
4116 2000 : void *hFeature =
4117 2000 : reinterpret_cast<void *>(static_cast<uintptr_t>(i));
4118 2000 : CPLQuadTreeInsertWithBounds(hTree, hFeature, &rect);
4119 : }
4120 :
4121 : {
4122 2 : int nFeatureCount = 0;
4123 2 : CPLFree(CPLQuadTreeSearch(hTree, &globalbounds, &nFeatureCount));
4124 2 : ASSERT_EQ(nFeatureCount, 1000);
4125 : }
4126 :
4127 2 : DummyRandInit(j);
4128 2002 : for (int i = 0; i < 1000; i++)
4129 : {
4130 : CPLRectObj rect;
4131 2000 : GenerateRandomRect(rect);
4132 2000 : void *hFeature =
4133 2000 : reinterpret_cast<void *>(static_cast<uintptr_t>(i));
4134 2000 : CPLQuadTreeRemove(hTree, hFeature, &rect);
4135 : }
4136 :
4137 : {
4138 2 : int nFeatureCount = 0;
4139 2 : CPLFree(CPLQuadTreeSearch(hTree, &globalbounds, &nFeatureCount));
4140 2 : ASSERT_EQ(nFeatureCount, 0);
4141 : }
4142 : }
4143 :
4144 1 : CPLQuadTreeDestroy(hTree);
4145 : }
4146 :
4147 : // Test bUnlinkAndSize on VSIGetMemFileBuffer
4148 4 : TEST_F(test_cpl, VSIGetMemFileBuffer_unlink_and_size)
4149 : {
4150 : VSIVirtualHandleUniquePtr fp(
4151 1 : VSIFOpenL("/vsimem/test_unlink_and_seize.tif", "wb"));
4152 1 : VSIFWriteL("test", 5, 1, fp.get());
4153 : std::unique_ptr<GByte, VSIFreeReleaser> pRawData(VSIGetMemFileBuffer(
4154 1 : "/vsimem/test_unlink_and_seize.tif", nullptr, true));
4155 1 : ASSERT_TRUE(EQUAL(reinterpret_cast<const char *>(pRawData.get()), "test"));
4156 1 : ASSERT_TRUE(VSIGetMemFileBuffer("/vsimem/test_unlink_and_seize.tif",
4157 : nullptr, false) == nullptr);
4158 : VSIVirtualHandleUniquePtr fp2(
4159 1 : VSIFOpenL("/vsimem/test_unlink_and_seize.tif", "r"));
4160 1 : ASSERT_TRUE(fp2.get() == nullptr);
4161 1 : ASSERT_TRUE(VSIFReadL(pRawData.get(), 5, 1, fp.get()) == 0);
4162 1 : ASSERT_TRUE(VSIFWriteL(pRawData.get(), 5, 1, fp.get()) == 0);
4163 1 : ASSERT_TRUE(VSIFSeekL(fp.get(), 0, SEEK_END) == 0);
4164 : }
4165 :
4166 : // Test CPLLoadConfigOptionsFromFile() for VSI credentials
4167 4 : TEST_F(test_cpl, CPLLoadConfigOptionsFromFile_VSI_credentials)
4168 : {
4169 1 : VSILFILE *fp = VSIFOpenL("/vsimem/credentials.txt", "wb");
4170 1 : VSIFPrintfL(fp, "[credentials]\n");
4171 1 : VSIFPrintfL(fp, "\n");
4172 1 : VSIFPrintfL(fp, "[.my_subsection]\n");
4173 1 : VSIFPrintfL(fp, "path=/vsi_test/foo/bar\n");
4174 1 : VSIFPrintfL(fp, "FOO=BAR\n");
4175 1 : VSIFPrintfL(fp, "FOO2=BAR2\n");
4176 1 : VSIFPrintfL(fp, "\n");
4177 1 : VSIFPrintfL(fp, "[.my_subsection2]\n");
4178 1 : VSIFPrintfL(fp, "path=/vsi_test/bar/baz\n");
4179 1 : VSIFPrintfL(fp, "BAR=BAZ\n");
4180 1 : VSIFPrintfL(fp, "[configoptions]\n");
4181 1 : VSIFPrintfL(fp, "configoptions_FOO=BAR\n");
4182 1 : VSIFCloseL(fp);
4183 :
4184 1 : CPLErrorReset();
4185 1 : CPLLoadConfigOptionsFromFile("/vsimem/credentials.txt", false);
4186 1 : ASSERT_EQ(CPLGetLastErrorType(), CE_None);
4187 :
4188 : {
4189 : const char *pszVal =
4190 1 : VSIGetPathSpecificOption("/vsi_test/foo/bar", "FOO", nullptr);
4191 1 : ASSERT_TRUE(pszVal != nullptr);
4192 2 : ASSERT_EQ(std::string(pszVal), std::string("BAR"));
4193 : }
4194 :
4195 : {
4196 : const char *pszVal =
4197 1 : VSIGetPathSpecificOption("/vsi_test/foo/bar", "FOO2", nullptr);
4198 1 : ASSERT_TRUE(pszVal != nullptr);
4199 2 : ASSERT_EQ(std::string(pszVal), std::string("BAR2"));
4200 : }
4201 :
4202 : {
4203 : const char *pszVal =
4204 1 : VSIGetPathSpecificOption("/vsi_test/bar/baz", "BAR", nullptr);
4205 1 : ASSERT_TRUE(pszVal != nullptr);
4206 2 : ASSERT_EQ(std::string(pszVal), std::string("BAZ"));
4207 : }
4208 :
4209 : {
4210 1 : const char *pszVal = CPLGetConfigOption("configoptions_FOO", nullptr);
4211 1 : ASSERT_TRUE(pszVal != nullptr);
4212 2 : ASSERT_EQ(std::string(pszVal), std::string("BAR"));
4213 : }
4214 :
4215 1 : VSIClearPathSpecificOptions("/vsi_test/bar/baz");
4216 1 : CPLSetConfigOption("configoptions_FOO", nullptr);
4217 :
4218 : {
4219 : const char *pszVal =
4220 1 : VSIGetPathSpecificOption("/vsi_test/bar/baz", "BAR", nullptr);
4221 1 : ASSERT_TRUE(pszVal == nullptr);
4222 : }
4223 :
4224 1 : VSIUnlink("/vsimem/credentials.txt");
4225 : }
4226 :
4227 : // Test CPLLoadConfigOptionsFromFile() for VSI credentials, warning case
4228 4 : TEST_F(test_cpl, CPLLoadConfigOptionsFromFile_VSI_credentials_warning)
4229 : {
4230 1 : VSILFILE *fp = VSIFOpenL("/vsimem/credentials.txt", "wb");
4231 1 : VSIFPrintfL(fp, "[credentials]\n");
4232 1 : VSIFPrintfL(fp, "\n");
4233 1 : VSIFPrintfL(fp, "FOO=BAR\n"); // content outside of subsection
4234 1 : VSIFCloseL(fp);
4235 :
4236 1 : CPLErrorReset();
4237 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
4238 1 : CPLLoadConfigOptionsFromFile("/vsimem/credentials.txt", false);
4239 1 : CPLPopErrorHandler();
4240 1 : ASSERT_EQ(CPLGetLastErrorType(), CE_Warning);
4241 :
4242 1 : VSIUnlink("/vsimem/credentials.txt");
4243 : }
4244 :
4245 : // Test CPLLoadConfigOptionsFromFile() for VSI credentials, warning case
4246 4 : TEST_F(test_cpl,
4247 : CPLLoadConfigOptionsFromFile_VSI_credentials_subsection_warning)
4248 : {
4249 1 : VSILFILE *fp = VSIFOpenL("/vsimem/credentials.txt", "wb");
4250 1 : VSIFPrintfL(fp, "[credentials]\n");
4251 1 : VSIFPrintfL(fp, "[.subsection]\n");
4252 1 : VSIFPrintfL(fp, "FOO=BAR\n"); // first key is not 'path'
4253 1 : VSIFCloseL(fp);
4254 :
4255 1 : CPLErrorReset();
4256 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
4257 1 : CPLLoadConfigOptionsFromFile("/vsimem/credentials.txt", false);
4258 1 : CPLPopErrorHandler();
4259 1 : ASSERT_EQ(CPLGetLastErrorType(), CE_Warning);
4260 :
4261 1 : VSIUnlink("/vsimem/credentials.txt");
4262 : }
4263 :
4264 : // Test CPLLoadConfigOptionsFromFile() for VSI credentials, warning case
4265 4 : TEST_F(test_cpl,
4266 : CPLLoadConfigOptionsFromFile_VSI_credentials_warning_path_specific)
4267 : {
4268 1 : VSILFILE *fp = VSIFOpenL("/vsimem/credentials.txt", "wb");
4269 1 : VSIFPrintfL(fp, "[credentials]\n");
4270 1 : VSIFPrintfL(fp, "[.subsection]\n");
4271 1 : VSIFPrintfL(fp, "path=/vsi_test/foo\n");
4272 1 : VSIFPrintfL(fp, "path=/vsi_test/bar\n"); // duplicated path
4273 1 : VSIFPrintfL(fp, "FOO=BAR\n"); // first key is not 'path'
4274 1 : VSIFPrintfL(fp, "[unrelated_section]");
4275 1 : VSIFPrintfL(fp, "BAR=BAZ\n"); // first key is not 'path'
4276 1 : VSIFCloseL(fp);
4277 :
4278 1 : CPLErrorReset();
4279 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
4280 1 : CPLLoadConfigOptionsFromFile("/vsimem/credentials.txt", false);
4281 1 : CPLPopErrorHandler();
4282 1 : ASSERT_EQ(CPLGetLastErrorType(), CE_Warning);
4283 :
4284 : {
4285 : const char *pszVal =
4286 1 : VSIGetPathSpecificOption("/vsi_test/foo", "FOO", nullptr);
4287 1 : ASSERT_TRUE(pszVal != nullptr);
4288 : }
4289 :
4290 : {
4291 : const char *pszVal =
4292 1 : VSIGetPathSpecificOption("/vsi_test/foo", "BAR", nullptr);
4293 1 : ASSERT_TRUE(pszVal == nullptr);
4294 : }
4295 :
4296 1 : VSIUnlink("/vsimem/credentials.txt");
4297 : }
4298 :
4299 : // Test CPLRecodeFromWCharIconv() with 2 bytes/char source encoding
4300 4 : TEST_F(test_cpl, CPLRecodeFromWCharIconv_2byte_source_encoding)
4301 : {
4302 : #ifdef CPL_RECODE_ICONV
4303 1 : int N = 2048;
4304 : wchar_t *pszIn =
4305 1 : static_cast<wchar_t *>(CPLMalloc((N + 1) * sizeof(wchar_t)));
4306 2049 : for (int i = 0; i < N; i++)
4307 2048 : pszIn[i] = L'A';
4308 1 : pszIn[N] = L'\0';
4309 1 : char *pszExpected = static_cast<char *>(CPLMalloc(N + 1));
4310 2049 : for (int i = 0; i < N; i++)
4311 2048 : pszExpected[i] = 'A';
4312 1 : pszExpected[N] = '\0';
4313 1 : char *pszRet = CPLRecodeFromWChar(pszIn, CPL_ENC_UTF16, CPL_ENC_UTF8);
4314 1 : const bool bOK = memcmp(pszExpected, pszRet, N + 1) == 0;
4315 : // FIXME Some tests fail on Mac. Not sure why, but do not error out just for
4316 : // that
4317 1 : if (!bOK &&
4318 0 : (strstr(CPLGetConfigOption("TRAVIS_OS_NAME", ""), "osx") != nullptr ||
4319 0 : strstr(CPLGetConfigOption("BUILD_NAME", ""), "osx") != nullptr ||
4320 0 : getenv("DO_NOT_FAIL_ON_RECODE_ERRORS") != nullptr))
4321 : {
4322 0 : fprintf(stderr, "Recode from CPL_ENC_UTF16 to CPL_ENC_UTF8 failed\n");
4323 : }
4324 : else
4325 : {
4326 1 : EXPECT_TRUE(bOK);
4327 : }
4328 1 : CPLFree(pszIn);
4329 1 : CPLFree(pszRet);
4330 1 : CPLFree(pszExpected);
4331 : #else
4332 : GTEST_SKIP() << "iconv support missing";
4333 : #endif
4334 1 : }
4335 :
4336 : // VERY MINIMAL testing of VSI plugin functionality
4337 4 : TEST_F(test_cpl, VSI_plugin_minimal_testing)
4338 : {
4339 1 : auto psCallbacks = VSIAllocFilesystemPluginCallbacksStruct();
4340 3 : psCallbacks->open = [](void *pUserData, const char *pszFilename,
4341 : const char *pszAccess) -> void *
4342 : {
4343 : (void)pUserData;
4344 2 : if (strcmp(pszFilename, "test") == 0 && strcmp(pszAccess, "rb") == 0)
4345 1 : return const_cast<char *>("ok");
4346 1 : return nullptr;
4347 1 : };
4348 1 : EXPECT_EQ(VSIInstallPluginHandler("/vsimyplugin/", psCallbacks), 0);
4349 1 : VSIFreeFilesystemPluginCallbacksStruct(psCallbacks);
4350 1 : VSILFILE *fp = VSIFOpenL("/vsimyplugin/test", "rb");
4351 1 : EXPECT_TRUE(fp != nullptr);
4352 :
4353 : // Check it doesn't crash
4354 1 : vsi_l_offset nOffset = 5;
4355 1 : size_t nSize = 10;
4356 1 : reinterpret_cast<VSIVirtualHandle *>(fp)->AdviseRead(1, &nOffset, &nSize);
4357 :
4358 1 : VSIFCloseL(fp);
4359 1 : EXPECT_TRUE(VSIVirtualHandleUniquePtr(
4360 : VSIFOpenL("/vsimyplugin/i_dont_exist", "rb")) == nullptr);
4361 :
4362 : // Check that we can remove the handler
4363 1 : VSIRemovePluginHandler("/vsimyplugin/");
4364 :
4365 1 : EXPECT_TRUE(VSIVirtualHandleUniquePtr(
4366 : VSIFOpenL("/vsimyplugin/test", "rb")) == nullptr);
4367 1 : EXPECT_TRUE(VSIVirtualHandleUniquePtr(
4368 : VSIFOpenL("/vsimyplugin/i_dont_exist", "rb")) == nullptr);
4369 :
4370 : // Removing a non-existing handler is a no-op
4371 1 : VSIRemovePluginHandler("/vsimyplugin/");
4372 1 : VSIRemovePluginHandler("/vsifoobar/");
4373 1 : }
4374 :
4375 4 : TEST_F(test_cpl, VSI_plugin_advise_read)
4376 : {
4377 1 : auto psCallbacks = VSIAllocFilesystemPluginCallbacksStruct();
4378 :
4379 : struct UserData
4380 : {
4381 : int nRanges = 0;
4382 : const vsi_l_offset *panOffsets = nullptr;
4383 : const size_t *panSizes = nullptr;
4384 : };
4385 :
4386 1 : UserData userData;
4387 :
4388 1 : psCallbacks->pUserData = &userData;
4389 2 : psCallbacks->open = [](void *pUserData, const char * /*pszFilename*/,
4390 : const char * /*pszAccess*/) -> void *
4391 2 : { return pUserData; };
4392 :
4393 2 : psCallbacks->advise_read = [](void *pFile, int nRanges,
4394 : const vsi_l_offset *panOffsets,
4395 : const size_t *panSizes)
4396 : {
4397 1 : static_cast<UserData *>(pFile)->nRanges = nRanges;
4398 1 : static_cast<UserData *>(pFile)->panOffsets = panOffsets;
4399 1 : static_cast<UserData *>(pFile)->panSizes = panSizes;
4400 2 : };
4401 1 : EXPECT_EQ(VSIInstallPluginHandler("/VSI_plugin_advise_read/", psCallbacks),
4402 : 0);
4403 1 : VSIFreeFilesystemPluginCallbacksStruct(psCallbacks);
4404 1 : VSILFILE *fp = VSIFOpenL("/VSI_plugin_advise_read/test", "rb");
4405 1 : EXPECT_TRUE(fp != nullptr);
4406 :
4407 1 : vsi_l_offset nOffset = 5;
4408 1 : size_t nSize = 10;
4409 1 : reinterpret_cast<VSIVirtualHandle *>(fp)->AdviseRead(1, &nOffset, &nSize);
4410 1 : EXPECT_EQ(userData.nRanges, 1);
4411 1 : EXPECT_EQ(userData.panOffsets, &nOffset);
4412 1 : EXPECT_EQ(userData.panSizes, &nSize);
4413 :
4414 1 : VSIFCloseL(fp);
4415 1 : }
4416 :
4417 : // Test CPLIsASCII()
4418 4 : TEST_F(test_cpl, CPLIsASCII)
4419 : {
4420 1 : ASSERT_TRUE(CPLIsASCII("foo", 3));
4421 1 : ASSERT_TRUE(CPLIsASCII("foo", static_cast<size_t>(-1)));
4422 1 : ASSERT_TRUE(!CPLIsASCII("\xFF", 1));
4423 : }
4424 :
4425 : // Test VSIIsLocal()
4426 4 : TEST_F(test_cpl, VSIIsLocal)
4427 : {
4428 1 : ASSERT_TRUE(VSIIsLocal("/vsimem/"));
4429 1 : ASSERT_TRUE(VSIIsLocal("/vsigzip//vsimem/tmp.gz"));
4430 : #ifdef HAVE_CURL
4431 1 : ASSERT_TRUE(!VSIIsLocal("/vsicurl/http://example.com"));
4432 : #endif
4433 : VSIStatBufL sStat;
4434 : #ifdef _WIN32
4435 : if (VSIStatL("c:\\", &sStat) == 0)
4436 : {
4437 : ASSERT_TRUE(VSIIsLocal("c:\\i_do_not_exist"));
4438 : }
4439 : #else
4440 1 : if (VSIStatL("/tmp", &sStat) == 0)
4441 : {
4442 1 : ASSERT_TRUE(VSIIsLocal("/tmp/i_do_not_exist"));
4443 : }
4444 : #endif
4445 : }
4446 :
4447 : // Test VSISupportsSequentialWrite()
4448 4 : TEST_F(test_cpl, VSISupportsSequentialWrite)
4449 : {
4450 1 : ASSERT_TRUE(VSISupportsSequentialWrite("/vsimem/", false));
4451 : #ifdef HAVE_CURL
4452 1 : ASSERT_TRUE(
4453 : !VSISupportsSequentialWrite("/vsicurl/http://example.com", false));
4454 1 : ASSERT_TRUE(VSISupportsSequentialWrite("/vsis3/test_bucket/", false));
4455 : #endif
4456 1 : ASSERT_TRUE(VSISupportsSequentialWrite("/vsigzip//vsimem/tmp.gz", false));
4457 : #ifdef HAVE_CURL
4458 1 : ASSERT_TRUE(!VSISupportsSequentialWrite(
4459 : "/vsigzip//vsicurl/http://example.com/tmp.gz", false));
4460 : #endif
4461 : VSIStatBufL sStat;
4462 : #ifdef _WIN32
4463 : if (VSIStatL("c:\\", &sStat) == 0)
4464 : {
4465 : ASSERT_TRUE(VSISupportsSequentialWrite("c:\\", false));
4466 : }
4467 : #else
4468 1 : if (VSIStatL("/tmp", &sStat) == 0)
4469 : {
4470 1 : ASSERT_TRUE(VSISupportsSequentialWrite("/tmp/i_do_not_exist", false));
4471 : }
4472 : #endif
4473 : }
4474 :
4475 : // Test VSISupportsRandomWrite()
4476 4 : TEST_F(test_cpl, VSISupportsRandomWrite)
4477 : {
4478 1 : ASSERT_TRUE(VSISupportsRandomWrite("/vsimem/", false));
4479 : #ifdef HAVE_CURL
4480 1 : ASSERT_TRUE(!VSISupportsRandomWrite("/vsicurl/http://example.com", false));
4481 1 : ASSERT_TRUE(!VSISupportsRandomWrite("/vsis3/test_bucket/", false));
4482 1 : ASSERT_TRUE(!VSISupportsRandomWrite("/vsis3/test_bucket/", true));
4483 1 : CPLSetConfigOption("CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", "YES");
4484 1 : ASSERT_TRUE(VSISupportsRandomWrite("/vsis3/test_bucket/", true));
4485 1 : CPLSetConfigOption("CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", nullptr);
4486 : #endif
4487 1 : ASSERT_TRUE(!VSISupportsRandomWrite("/vsigzip//vsimem/tmp.gz", false));
4488 : #ifdef HAVE_CURL
4489 1 : ASSERT_TRUE(!VSISupportsRandomWrite(
4490 : "/vsigzip//vsicurl/http://example.com/tmp.gz", false));
4491 : #endif
4492 : VSIStatBufL sStat;
4493 : #ifdef _WIN32
4494 : if (VSIStatL("c:\\", &sStat) == 0)
4495 : {
4496 : ASSERT_TRUE(VSISupportsRandomWrite("c:\\", false));
4497 : }
4498 : #else
4499 1 : if (VSIStatL("/tmp", &sStat) == 0)
4500 : {
4501 1 : ASSERT_TRUE(VSISupportsRandomWrite("/tmp", false));
4502 : }
4503 : #endif
4504 : }
4505 :
4506 : // Test ignore-env-vars = yes of configuration file
4507 4 : TEST_F(test_cpl, config_file_ignore_env_vars)
4508 : {
4509 1 : char szEnvVar[] = "SOME_ENV_VAR_FOR_TEST_CPL_61=FOO";
4510 1 : putenv(szEnvVar);
4511 1 : ASSERT_STREQ(CPLGetConfigOption("SOME_ENV_VAR_FOR_TEST_CPL_61", nullptr),
4512 : "FOO");
4513 :
4514 1 : VSILFILE *fp = VSIFOpenL("/vsimem/.gdal/gdalrc", "wb");
4515 1 : VSIFPrintfL(fp, "[directives]\n");
4516 1 : VSIFPrintfL(fp, "ignore-env-vars=yes\n");
4517 1 : VSIFPrintfL(fp, "[configoptions]\n");
4518 1 : VSIFPrintfL(fp, "CONFIG_OPTION_FOR_TEST_CPL_61=BAR\n");
4519 1 : VSIFCloseL(fp);
4520 :
4521 : // Load configuration file
4522 1 : constexpr bool bOverrideEnvVars = false;
4523 1 : CPLLoadConfigOptionsFromFile("/vsimem/.gdal/gdalrc", bOverrideEnvVars);
4524 :
4525 : // Check that reading configuration option works
4526 1 : ASSERT_STREQ(CPLGetConfigOption("CONFIG_OPTION_FOR_TEST_CPL_61", ""),
4527 : "BAR");
4528 :
4529 : // Check that environment variables are not read as configuration options
4530 1 : ASSERT_TRUE(CPLGetConfigOption("SOME_ENV_VAR_FOR_TEST_CPL_61", nullptr) ==
4531 : nullptr);
4532 :
4533 : // Reset ignore-env-vars=no
4534 1 : fp = VSIFOpenL("/vsimem/.gdal/gdalrc", "wb");
4535 1 : VSIFPrintfL(fp, "[directives]\n");
4536 1 : VSIFPrintfL(fp, "ignore-env-vars=no\n");
4537 1 : VSIFPrintfL(fp, "[configoptions]\n");
4538 1 : VSIFPrintfL(fp, "SOME_ENV_VAR_FOR_TEST_CPL_61=BAR\n");
4539 1 : VSIFCloseL(fp);
4540 :
4541 : // Reload configuration file
4542 1 : CPLLoadConfigOptionsFromFile("/vsimem/.gdal/gdalrc", false);
4543 :
4544 : // Check that environment variables override configuration options defined
4545 : // in the file (config file was loaded with bOverrideEnvVars = false)
4546 1 : ASSERT_TRUE(CPLGetConfigOption("SOME_ENV_VAR_FOR_TEST_CPL_61", nullptr) !=
4547 : nullptr);
4548 1 : ASSERT_STREQ(CPLGetConfigOption("SOME_ENV_VAR_FOR_TEST_CPL_61", ""), "FOO");
4549 :
4550 1 : VSIUnlink("/vsimem/.gdal/gdalrc");
4551 : }
4552 :
4553 : // Test that explicitly defined configuration options override environment variables
4554 : // with the same name
4555 4 : TEST_F(test_cpl, test_config_overrides_environment)
4556 : {
4557 1 : char szEnvVar[] = "TEST_CONFIG_OVERRIDES_ENVIRONMENT=123";
4558 1 : putenv(szEnvVar);
4559 :
4560 1 : constexpr const char *key = "TEST_CONFIG_OVERRIDES_ENVIRONMENT";
4561 :
4562 1 : ASSERT_STREQ(CPLGetConfigOption(key, nullptr), "123");
4563 :
4564 1 : CPLSetConfigOption(key, "456");
4565 :
4566 1 : ASSERT_STREQ(CPLGetConfigOption(key, nullptr), "456");
4567 :
4568 1 : CPLSetConfigOption(key, nullptr);
4569 :
4570 1 : ASSERT_STREQ(CPLGetConfigOption(key, nullptr), "123");
4571 :
4572 1 : CPLSetConfigOption(key, CPL_NULL_VALUE);
4573 :
4574 1 : ASSERT_EQ(CPLGetConfigOption(key, nullptr), nullptr);
4575 :
4576 1 : CPLSetConfigOption(key, nullptr);
4577 :
4578 1 : ASSERT_STREQ(CPLGetConfigOption(key, nullptr), "123");
4579 :
4580 : {
4581 1 : CPLConfigOptionSetter oSetter(key, nullptr, false);
4582 :
4583 1 : ASSERT_EQ(CPLGetConfigOption(key, nullptr), nullptr);
4584 : }
4585 :
4586 1 : ASSERT_STREQ(CPLGetConfigOption(key, nullptr), "123");
4587 :
4588 1 : CPLSetThreadLocalConfigOption(key, CPL_NULL_VALUE);
4589 :
4590 1 : ASSERT_EQ(CPLGetConfigOption(key, nullptr), nullptr);
4591 :
4592 1 : ASSERT_EQ(CPLGetThreadLocalConfigOption(key, nullptr), nullptr);
4593 : }
4594 :
4595 : // Test CPLWorkerThreadPool recursion
4596 4 : TEST_F(test_cpl, CPLWorkerThreadPool_recursion)
4597 : {
4598 : struct Context
4599 : {
4600 : CPLWorkerThreadPool oThreadPool{};
4601 : std::atomic<int> nCounter{0};
4602 : std::mutex mutex{};
4603 : std::condition_variable cv{};
4604 : bool you_can_leave = false;
4605 : int threadStarted = 0;
4606 :
4607 1 : void notifyYouCanLeave()
4608 : {
4609 2 : std::lock_guard<std::mutex> guard(mutex);
4610 1 : you_can_leave = true;
4611 1 : cv.notify_one();
4612 1 : }
4613 :
4614 1 : void waitYouCanLeave()
4615 : {
4616 2 : std::unique_lock<std::mutex> guard(mutex);
4617 2 : while (!you_can_leave)
4618 : {
4619 1 : cv.wait(guard);
4620 : }
4621 1 : }
4622 : };
4623 :
4624 1 : Context ctxt;
4625 1 : ctxt.oThreadPool.Setup(2, nullptr, nullptr, /* waitAllStarted = */ true);
4626 :
4627 : struct Data
4628 : {
4629 : Context *psCtxt;
4630 : int iJob;
4631 : GIntBig nThreadLambda = 0;
4632 :
4633 3 : Data(Context *psCtxtIn, int iJobIn) : psCtxt(psCtxtIn), iJob(iJobIn)
4634 : {
4635 3 : }
4636 :
4637 : Data(const Data &) = default;
4638 : };
4639 :
4640 3 : const auto lambda = [](void *pData)
4641 : {
4642 3 : auto psData = static_cast<Data *>(pData);
4643 3 : if (psData->iJob > 0)
4644 : {
4645 : // wait for both threads to be started
4646 4 : std::unique_lock<std::mutex> guard(psData->psCtxt->mutex);
4647 2 : psData->psCtxt->threadStarted++;
4648 2 : psData->psCtxt->cv.notify_one();
4649 3 : while (psData->psCtxt->threadStarted < 2)
4650 : {
4651 1 : psData->psCtxt->cv.wait(guard);
4652 : }
4653 : }
4654 :
4655 3 : psData->nThreadLambda = CPLGetPID();
4656 : // fprintf(stderr, "lambda %d: " CPL_FRMT_GIB "\n",
4657 : // psData->iJob, psData->nThreadLambda);
4658 9 : const auto lambda2 = [](void *pData2)
4659 : {
4660 9 : const auto psData2 = static_cast<Data *>(pData2);
4661 9 : const int iJob = psData2->iJob;
4662 9 : const int nCounter = psData2->psCtxt->nCounter++;
4663 9 : CPL_IGNORE_RET_VAL(nCounter);
4664 9 : const auto nThreadLambda2 = CPLGetPID();
4665 : // fprintf(stderr, "lambda2 job=%d, counter(before)=%d, thread="
4666 : // CPL_FRMT_GIB "\n", iJob, nCounter, nThreadLambda2);
4667 9 : if (iJob == 100 + 0)
4668 : {
4669 1 : ASSERT_TRUE(nThreadLambda2 != psData2->nThreadLambda);
4670 : // make sure that job 0 run in the other thread
4671 : // takes sufficiently long that job 2 has been submitted
4672 : // before it completes
4673 1 : psData2->psCtxt->waitYouCanLeave();
4674 : }
4675 8 : else if (iJob == 100 + 1 || iJob == 100 + 2)
4676 : {
4677 2 : ASSERT_TRUE(nThreadLambda2 == psData2->nThreadLambda);
4678 : }
4679 : };
4680 6 : auto poQueue = psData->psCtxt->oThreadPool.CreateJobQueue();
4681 3 : Data d0(*psData);
4682 3 : d0.iJob = 100 + d0.iJob * 3 + 0;
4683 3 : Data d1(*psData);
4684 3 : d1.iJob = 100 + d1.iJob * 3 + 1;
4685 3 : Data d2(*psData);
4686 3 : d2.iJob = 100 + d2.iJob * 3 + 2;
4687 3 : poQueue->SubmitJob(lambda2, &d0);
4688 3 : poQueue->SubmitJob(lambda2, &d1);
4689 3 : poQueue->SubmitJob(lambda2, &d2);
4690 3 : if (psData->iJob == 0)
4691 : {
4692 1 : psData->psCtxt->notifyYouCanLeave();
4693 : }
4694 3 : };
4695 : {
4696 2 : auto poQueue = ctxt.oThreadPool.CreateJobQueue();
4697 1 : Data data0(&ctxt, 0);
4698 1 : poQueue->SubmitJob(lambda, &data0);
4699 : }
4700 : {
4701 2 : auto poQueue = ctxt.oThreadPool.CreateJobQueue();
4702 1 : Data data1(&ctxt, 1);
4703 1 : Data data2(&ctxt, 2);
4704 1 : poQueue->SubmitJob(lambda, &data1);
4705 1 : poQueue->SubmitJob(lambda, &data2);
4706 : }
4707 1 : ASSERT_EQ(ctxt.nCounter, 3 * 3);
4708 : }
4709 :
4710 : // Test /vsimem/ PRead() implementation
4711 4 : TEST_F(test_cpl, vsimem_pread)
4712 : {
4713 1 : char szContent[] = "abcd";
4714 1 : VSILFILE *fp = VSIFileFromMemBuffer(
4715 : "", reinterpret_cast<GByte *>(szContent), 4, FALSE);
4716 1 : VSIVirtualHandle *poHandle = reinterpret_cast<VSIVirtualHandle *>(fp);
4717 1 : ASSERT_TRUE(poHandle->HasPRead());
4718 : {
4719 1 : char szBuffer[5] = {0};
4720 1 : ASSERT_EQ(poHandle->PRead(szBuffer, 2, 1), 2U);
4721 2 : ASSERT_EQ(std::string(szBuffer), std::string("bc"));
4722 : }
4723 : {
4724 1 : char szBuffer[5] = {0};
4725 1 : ASSERT_EQ(poHandle->PRead(szBuffer, 4, 1), 3U);
4726 2 : ASSERT_EQ(std::string(szBuffer), std::string("bcd"));
4727 : }
4728 : {
4729 1 : char szBuffer[5] = {0};
4730 1 : ASSERT_EQ(poHandle->PRead(szBuffer, 1, 4), 0U);
4731 2 : ASSERT_EQ(std::string(szBuffer), std::string());
4732 : }
4733 1 : VSIFCloseL(fp);
4734 : }
4735 :
4736 : // Test regular file system PRead() implementation
4737 4 : TEST_F(test_cpl, file_system_pread)
4738 : {
4739 1 : VSILFILE *fp = VSIFOpenL("temp_test_64.bin", "wb+");
4740 1 : if (fp == nullptr)
4741 0 : return;
4742 1 : VSIVirtualHandle *poHandle = reinterpret_cast<VSIVirtualHandle *>(fp);
4743 1 : poHandle->Write("abcd", 4, 1);
4744 1 : if (poHandle->HasPRead())
4745 : {
4746 1 : poHandle->Flush();
4747 : {
4748 1 : char szBuffer[5] = {0};
4749 1 : ASSERT_EQ(poHandle->PRead(szBuffer, 2, 1), 2U);
4750 2 : ASSERT_EQ(std::string(szBuffer), std::string("bc"));
4751 : }
4752 : {
4753 1 : char szBuffer[5] = {0};
4754 1 : ASSERT_EQ(poHandle->PRead(szBuffer, 4, 1), 3U);
4755 2 : ASSERT_EQ(std::string(szBuffer), std::string("bcd"));
4756 : }
4757 : {
4758 1 : char szBuffer[5] = {0};
4759 1 : ASSERT_EQ(poHandle->PRead(szBuffer, 1, 4), 0U);
4760 2 : ASSERT_EQ(std::string(szBuffer), std::string());
4761 : }
4762 : }
4763 1 : VSIFCloseL(fp);
4764 1 : VSIUnlink("temp_test_64.bin");
4765 : }
4766 :
4767 : // Test CPLMask implementation
4768 4 : TEST_F(test_cpl, CPLMask)
4769 : {
4770 1 : constexpr std::size_t sz = 71;
4771 1 : auto m = CPLMaskCreate(sz, true);
4772 :
4773 : // Mask is set by default
4774 72 : for (std::size_t i = 0; i < sz; i++)
4775 : {
4776 71 : EXPECT_EQ(CPLMaskGet(m, i), true) << "bit " << i;
4777 : }
4778 :
4779 1 : VSIFree(m);
4780 1 : m = CPLMaskCreate(sz, false);
4781 1 : auto m2 = CPLMaskCreate(sz, false);
4782 :
4783 : // Mask is unset by default
4784 72 : for (std::size_t i = 0; i < sz; i++)
4785 : {
4786 71 : EXPECT_EQ(CPLMaskGet(m, i), false) << "bit " << i;
4787 : }
4788 :
4789 : // Set a few bits
4790 1 : CPLMaskSet(m, 10);
4791 1 : CPLMaskSet(m, 33);
4792 1 : CPLMaskSet(m, 70);
4793 :
4794 : // Check all bits
4795 72 : for (std::size_t i = 0; i < sz; i++)
4796 : {
4797 71 : if (i == 10 || i == 33 || i == 70)
4798 : {
4799 3 : EXPECT_EQ(CPLMaskGet(m, i), true) << "bit " << i;
4800 : }
4801 : else
4802 : {
4803 68 : EXPECT_EQ(CPLMaskGet(m, i), false) << "bit " << i;
4804 : }
4805 : }
4806 :
4807 : // Unset some bits
4808 1 : CPLMaskClear(m, 10);
4809 1 : CPLMaskClear(m, 70);
4810 :
4811 : // Check all bits
4812 72 : for (std::size_t i = 0; i < sz; i++)
4813 : {
4814 71 : if (i == 33)
4815 : {
4816 1 : EXPECT_EQ(CPLMaskGet(m, i), true) << "bit " << i;
4817 : }
4818 : else
4819 : {
4820 70 : EXPECT_EQ(CPLMaskGet(m, i), false) << "bit " << i;
4821 : }
4822 : }
4823 :
4824 1 : CPLMaskSet(m2, 36);
4825 1 : CPLMaskMerge(m2, m, sz);
4826 :
4827 : // Check all bits
4828 72 : for (std::size_t i = 0; i < sz; i++)
4829 : {
4830 71 : if (i == 36 || i == 33)
4831 : {
4832 4 : ASSERT_EQ(CPLMaskGet(m2, i), true) << "bit " << i;
4833 : }
4834 : else
4835 : {
4836 69 : ASSERT_EQ(CPLMaskGet(m2, i), false) << "bit " << i;
4837 : }
4838 : }
4839 :
4840 1 : CPLMaskClearAll(m, sz);
4841 1 : CPLMaskSetAll(m2, sz);
4842 :
4843 : // Check all bits
4844 72 : for (std::size_t i = 0; i < sz; i++)
4845 : {
4846 71 : EXPECT_EQ(CPLMaskGet(m, i), false) << "bit " << i;
4847 71 : EXPECT_EQ(CPLMaskGet(m2, i), true) << "bit " << i;
4848 : }
4849 :
4850 1 : VSIFree(m);
4851 1 : VSIFree(m2);
4852 : }
4853 :
4854 : // Test cpl::ThreadSafeQueue
4855 4 : TEST_F(test_cpl, ThreadSafeQueue)
4856 : {
4857 1 : cpl::ThreadSafeQueue<int> queue;
4858 1 : ASSERT_TRUE(queue.empty());
4859 1 : ASSERT_EQ(queue.size(), 0U);
4860 1 : queue.push(1);
4861 1 : ASSERT_TRUE(!queue.empty());
4862 1 : ASSERT_EQ(queue.size(), 1U);
4863 1 : queue.clear();
4864 1 : ASSERT_TRUE(queue.empty());
4865 1 : ASSERT_EQ(queue.size(), 0U);
4866 1 : int val = 10;
4867 1 : queue.push(std::move(val));
4868 1 : ASSERT_TRUE(!queue.empty());
4869 1 : ASSERT_EQ(queue.size(), 1U);
4870 1 : ASSERT_EQ(queue.get_and_pop_front(), 10);
4871 1 : ASSERT_TRUE(queue.empty());
4872 : }
4873 :
4874 4 : TEST_F(test_cpl, CPLGetExecPath)
4875 : {
4876 1 : std::vector<char> achBuffer(1024, 'x');
4877 1 : if (!CPLGetExecPath(achBuffer.data(), static_cast<int>(achBuffer.size())))
4878 : {
4879 0 : GTEST_SKIP() << "CPLGetExecPath() not implemented for this platform";
4880 : }
4881 : else
4882 : {
4883 1 : bool bFoundNulTerminatedChar = false;
4884 71 : for (char ch : achBuffer)
4885 : {
4886 71 : if (ch == '\0')
4887 : {
4888 1 : bFoundNulTerminatedChar = true;
4889 1 : break;
4890 : }
4891 : }
4892 1 : ASSERT_TRUE(bFoundNulTerminatedChar);
4893 :
4894 : // Check that the file exists
4895 : VSIStatBufL sStat;
4896 1 : EXPECT_EQ(VSIStatL(achBuffer.data(), &sStat), 0);
4897 :
4898 2 : const std::string osStrBefore(achBuffer.data());
4899 :
4900 : // Resize the buffer to just the minimum size
4901 1 : achBuffer.resize(strlen(achBuffer.data()) + 1);
4902 1 : EXPECT_TRUE(CPLGetExecPath(achBuffer.data(),
4903 : static_cast<int>(achBuffer.size())));
4904 :
4905 1 : EXPECT_STREQ(osStrBefore.c_str(), achBuffer.data());
4906 :
4907 : // Too small buffer
4908 1 : achBuffer.resize(achBuffer.size() - 1);
4909 1 : EXPECT_FALSE(CPLGetExecPath(achBuffer.data(),
4910 : static_cast<int>(achBuffer.size())));
4911 : }
4912 : }
4913 :
4914 4 : TEST_F(test_cpl, VSIDuplicateFileSystemHandler)
4915 : {
4916 : {
4917 2 : CPLErrorHandlerPusher oErrorHandler(CPLQuietErrorHandler);
4918 1 : EXPECT_FALSE(VSIDuplicateFileSystemHandler(
4919 : "/vsi_i_dont_exist/", "/vsi_i_will_not_be_created/"));
4920 : }
4921 : {
4922 2 : CPLErrorHandlerPusher oErrorHandler(CPLQuietErrorHandler);
4923 1 : EXPECT_FALSE(
4924 : VSIDuplicateFileSystemHandler("/", "/vsi_i_will_not_be_created/"));
4925 : }
4926 1 : EXPECT_EQ(VSIFileManager::GetHandler("/vsi_test_clone_vsimem/"),
4927 : VSIFileManager::GetHandler("/"));
4928 1 : EXPECT_TRUE(
4929 : VSIDuplicateFileSystemHandler("/vsimem/", "/vsi_test_clone_vsimem/"));
4930 1 : EXPECT_NE(VSIFileManager::GetHandler("/vsi_test_clone_vsimem/"),
4931 : VSIFileManager::GetHandler("/"));
4932 : {
4933 2 : CPLErrorHandlerPusher oErrorHandler(CPLQuietErrorHandler);
4934 1 : EXPECT_FALSE(VSIDuplicateFileSystemHandler("/vsimem/",
4935 : "/vsi_test_clone_vsimem/"));
4936 : }
4937 1 : }
4938 :
4939 4 : TEST_F(test_cpl, CPLAtoGIntBigEx)
4940 : {
4941 : {
4942 1 : int bOverflow = 0;
4943 1 : EXPECT_EQ(CPLAtoGIntBigEx("9223372036854775807", false, &bOverflow),
4944 : std::numeric_limits<int64_t>::max());
4945 1 : EXPECT_EQ(bOverflow, FALSE);
4946 : }
4947 : {
4948 1 : int bOverflow = 0;
4949 1 : EXPECT_EQ(CPLAtoGIntBigEx("9223372036854775808", false, &bOverflow),
4950 : std::numeric_limits<int64_t>::max());
4951 1 : EXPECT_EQ(bOverflow, TRUE);
4952 : }
4953 : {
4954 1 : int bOverflow = 0;
4955 1 : EXPECT_EQ(CPLAtoGIntBigEx("-9223372036854775808", false, &bOverflow),
4956 : std::numeric_limits<int64_t>::min());
4957 1 : EXPECT_EQ(bOverflow, FALSE);
4958 : }
4959 : {
4960 1 : int bOverflow = 0;
4961 1 : EXPECT_EQ(CPLAtoGIntBigEx("-9223372036854775809", false, &bOverflow),
4962 : std::numeric_limits<int64_t>::min());
4963 1 : EXPECT_EQ(bOverflow, TRUE);
4964 : }
4965 1 : }
4966 :
4967 4 : TEST_F(test_cpl, CPLSubscribeToSetConfigOption)
4968 : {
4969 : struct Event
4970 : {
4971 : std::string osKey;
4972 : std::string osValue;
4973 : bool bThreadLocal;
4974 : };
4975 :
4976 2 : std::vector<Event> events;
4977 4 : const auto cbk = +[](const char *pszKey, const char *pszValue,
4978 : bool bThreadLocal, void *pUserData)
4979 : {
4980 3 : std::vector<Event> *pEvents =
4981 : static_cast<std::vector<Event> *>(pUserData);
4982 6 : Event ev;
4983 3 : ev.osKey = pszKey;
4984 3 : ev.osValue = pszValue ? pszValue : "";
4985 3 : ev.bThreadLocal = bThreadLocal;
4986 3 : pEvents->emplace_back(ev);
4987 3 : };
4988 :
4989 : // Subscribe and unsubscribe immediately
4990 : {
4991 1 : int nId = CPLSubscribeToSetConfigOption(cbk, &events);
4992 1 : CPLSetConfigOption("CPLSubscribeToSetConfigOption", "bar");
4993 1 : EXPECT_EQ(events.size(), 1U);
4994 1 : if (!events.empty())
4995 : {
4996 1 : EXPECT_STREQ(events[0].osKey.c_str(),
4997 : "CPLSubscribeToSetConfigOption");
4998 1 : EXPECT_STREQ(events[0].osValue.c_str(), "bar");
4999 1 : EXPECT_FALSE(events[0].bThreadLocal);
5000 : }
5001 1 : CPLUnsubscribeToSetConfigOption(nId);
5002 : }
5003 1 : events.clear();
5004 :
5005 : // Subscribe and unsubscribe in non-nested order
5006 : {
5007 1 : int nId1 = CPLSubscribeToSetConfigOption(cbk, &events);
5008 1 : int nId2 = CPLSubscribeToSetConfigOption(cbk, &events);
5009 1 : CPLUnsubscribeToSetConfigOption(nId1);
5010 1 : int nId3 = CPLSubscribeToSetConfigOption(cbk, &events);
5011 :
5012 1 : CPLSetConfigOption("CPLSubscribeToSetConfigOption", nullptr);
5013 1 : EXPECT_EQ(events.size(), 2U);
5014 :
5015 1 : CPLUnsubscribeToSetConfigOption(nId2);
5016 1 : CPLUnsubscribeToSetConfigOption(nId3);
5017 :
5018 1 : CPLSetConfigOption("CPLSubscribeToSetConfigOption", nullptr);
5019 1 : EXPECT_EQ(events.size(), 2U);
5020 : }
5021 1 : }
5022 :
5023 4 : TEST_F(test_cpl, VSIGetCanonicalFilename)
5024 : {
5025 2 : std::string osTmp = CPLGenerateTempFilename(nullptr);
5026 1 : if (!CPLIsFilenameRelative(osTmp.c_str()))
5027 : {
5028 : // Get the canonical filename of the base temporary file
5029 : // to be able to test afterwards just the differences on the case
5030 : // of the extension
5031 0 : VSILFILE *fp = VSIFOpenL(osTmp.c_str(), "wb");
5032 0 : EXPECT_TRUE(fp != nullptr);
5033 0 : if (fp)
5034 : {
5035 0 : VSIFCloseL(fp);
5036 0 : char *pszRes = VSIGetCanonicalFilename(osTmp.c_str());
5037 0 : osTmp = pszRes;
5038 0 : CPLFree(pszRes);
5039 0 : VSIUnlink(osTmp.c_str());
5040 : }
5041 : }
5042 :
5043 2 : std::string osLC = osTmp + ".tmp";
5044 2 : std::string osUC = osTmp + ".TMP";
5045 : // Create a file in lower case
5046 1 : VSILFILE *fp = VSIFOpenL(osLC.c_str(), "wb");
5047 1 : EXPECT_TRUE(fp != nullptr);
5048 1 : if (fp)
5049 : {
5050 1 : VSIFCloseL(fp);
5051 : VSIStatBufL sStat;
5052 : // And try to stat it in upper case
5053 1 : if (VSIStatL(osUC.c_str(), &sStat) == 0)
5054 : {
5055 0 : char *pszRes = VSIGetCanonicalFilename(osUC.c_str());
5056 0 : EXPECT_TRUE(pszRes);
5057 0 : if (pszRes)
5058 : {
5059 : #if defined(_WIN32) || (defined(__MACH__) && defined(__APPLE__))
5060 : // On Windows or Mac, we should get the real canonical name,
5061 : // i.e. in lower case
5062 : EXPECT_STREQ(pszRes, osLC.c_str());
5063 : #else
5064 : // On other operating systems, VSIGetCanonicalFilename()
5065 : // could not be implemented, so be laxer in the check
5066 0 : EXPECT_STREQ(CPLString(pszRes).tolower().c_str(),
5067 : CPLString(osLC).tolower().c_str());
5068 : #endif
5069 : }
5070 0 : CPLFree(pszRes);
5071 : }
5072 :
5073 : {
5074 1 : char *pszRes = VSIGetCanonicalFilename(osLC.c_str());
5075 1 : EXPECT_TRUE(pszRes);
5076 1 : if (pszRes)
5077 : {
5078 1 : EXPECT_STREQ(pszRes, osLC.c_str());
5079 : }
5080 1 : CPLFree(pszRes);
5081 : }
5082 : }
5083 1 : VSIUnlink(osLC.c_str());
5084 1 : }
5085 :
5086 4 : TEST_F(test_cpl, CPLStrtod)
5087 : {
5088 : {
5089 1 : const char *pszVal = "5";
5090 1 : char *pszEnd = nullptr;
5091 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd), 5.0);
5092 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5093 : }
5094 :
5095 : {
5096 1 : const char *pszVal = "-5 foo";
5097 1 : char *pszEnd = nullptr;
5098 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd), -5.0);
5099 1 : EXPECT_EQ(pszEnd, pszVal + 2);
5100 : }
5101 :
5102 : {
5103 1 : const char *pszVal = "3.1415";
5104 1 : char *pszEnd = nullptr;
5105 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd), 3.1415);
5106 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5107 : }
5108 :
5109 : {
5110 1 : const char *pszVal = "6.022e23";
5111 1 : char *pszEnd = nullptr;
5112 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd), 6.022e23);
5113 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5114 : }
5115 :
5116 : {
5117 1 : const char *pszVal = " +6.022E+23";
5118 1 : char *pszEnd = nullptr;
5119 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd), 6.022e23);
5120 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5121 : }
5122 : {
5123 1 : const char *pszVal = "1.e-23";
5124 1 : char *pszEnd = nullptr;
5125 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd), 1.0e-23);
5126 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5127 : }
5128 :
5129 : {
5130 1 : const char *pszVal = "foo";
5131 1 : char *pszEnd = nullptr;
5132 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd), 0.0);
5133 1 : EXPECT_EQ(pszEnd, pszVal);
5134 : }
5135 :
5136 : {
5137 1 : const char *pszVal = "-inf";
5138 1 : char *pszEnd = nullptr;
5139 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5140 : -std::numeric_limits<double>::infinity());
5141 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5142 : }
5143 : {
5144 1 : const char *pszVal = "-Inf";
5145 1 : char *pszEnd = nullptr;
5146 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5147 : -std::numeric_limits<double>::infinity());
5148 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5149 : }
5150 : {
5151 1 : const char *pszVal = "-INF";
5152 1 : char *pszEnd = nullptr;
5153 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5154 : -std::numeric_limits<double>::infinity());
5155 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5156 : }
5157 : {
5158 1 : const char *pszVal = "-Infinity";
5159 1 : char *pszEnd = nullptr;
5160 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5161 : -std::numeric_limits<double>::infinity());
5162 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5163 : }
5164 : {
5165 1 : const char *pszVal = "-1.#INF";
5166 1 : char *pszEnd = nullptr;
5167 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5168 : -std::numeric_limits<double>::infinity());
5169 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5170 : }
5171 :
5172 : {
5173 1 : const char *pszVal = "inf";
5174 1 : char *pszEnd = nullptr;
5175 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5176 : std::numeric_limits<double>::infinity());
5177 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5178 : }
5179 : {
5180 1 : const char *pszVal = "Inf";
5181 1 : char *pszEnd = nullptr;
5182 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5183 : std::numeric_limits<double>::infinity());
5184 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5185 : }
5186 : {
5187 1 : const char *pszVal = "INF";
5188 1 : char *pszEnd = nullptr;
5189 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5190 : std::numeric_limits<double>::infinity());
5191 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5192 : }
5193 : {
5194 1 : const char *pszVal = "Infinity";
5195 1 : char *pszEnd = nullptr;
5196 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5197 : std::numeric_limits<double>::infinity());
5198 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5199 : }
5200 : {
5201 1 : const char *pszVal = "1.#INF";
5202 1 : char *pszEnd = nullptr;
5203 1 : EXPECT_EQ(CPLStrtod(pszVal, &pszEnd),
5204 : std::numeric_limits<double>::infinity());
5205 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5206 : }
5207 :
5208 : {
5209 1 : const char *pszVal = "-1.#QNAN";
5210 1 : char *pszEnd = nullptr;
5211 1 : EXPECT_TRUE(std::isnan(CPLStrtod(pszVal, &pszEnd)));
5212 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5213 : }
5214 : {
5215 1 : const char *pszVal = "-1.#IND";
5216 1 : char *pszEnd = nullptr;
5217 1 : EXPECT_TRUE(std::isnan(CPLStrtod(pszVal, &pszEnd)));
5218 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5219 : }
5220 : {
5221 1 : const char *pszVal = "1.#QNAN";
5222 1 : char *pszEnd = nullptr;
5223 1 : EXPECT_TRUE(std::isnan(CPLStrtod(pszVal, &pszEnd)));
5224 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5225 : }
5226 : {
5227 1 : const char *pszVal = "1.#SNAN";
5228 1 : char *pszEnd = nullptr;
5229 1 : EXPECT_TRUE(std::isnan(CPLStrtod(pszVal, &pszEnd)));
5230 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5231 : }
5232 : {
5233 1 : const char *pszVal = "NaN";
5234 1 : char *pszEnd = nullptr;
5235 1 : EXPECT_TRUE(std::isnan(CPLStrtod(pszVal, &pszEnd)));
5236 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5237 : }
5238 : {
5239 1 : const char *pszVal = "nan";
5240 1 : char *pszEnd = nullptr;
5241 1 : EXPECT_TRUE(std::isnan(CPLStrtod(pszVal, &pszEnd)));
5242 1 : EXPECT_EQ(pszEnd, pszVal + strlen(pszVal));
5243 : }
5244 1 : }
5245 :
5246 4 : TEST_F(test_cpl, CPLStringToComplex)
5247 : {
5248 5 : const auto EXPECT_PARSED = [](const char *str, double real, double imag)
5249 : {
5250 5 : double r = -999;
5251 5 : double i = -999;
5252 5 : EXPECT_EQ(CPLStringToComplex(str, &r, &i), CE_None)
5253 0 : << "Unexpected error parsing " << str;
5254 5 : EXPECT_EQ(r, real);
5255 5 : EXPECT_EQ(i, imag);
5256 5 : };
5257 10 : const auto EXPECT_ERROR = [](const char *str)
5258 : {
5259 20 : CPLErrorStateBackuper state(CPLQuietErrorHandler);
5260 : double r, i;
5261 10 : EXPECT_EQ(CPLStringToComplex(str, &r, &i), CE_Failure)
5262 0 : << "Did not receive expected error parsing " << str;
5263 10 : };
5264 :
5265 1 : EXPECT_PARSED("05401", 5401, 0);
5266 1 : EXPECT_PARSED("-5401", -5401, 0);
5267 1 : EXPECT_PARSED(" 611.2-38.4i", 611.2, -38.4);
5268 1 : EXPECT_PARSED("611.2+38.4i ", 611.2, 38.4);
5269 1 : EXPECT_PARSED("-611.2+38.4i", -611.2, 38.4);
5270 :
5271 1 : EXPECT_ERROR("-611.2+38.4ii");
5272 1 : EXPECT_ERROR("-611.2+38.4ji");
5273 1 : EXPECT_ERROR("-611.2+38.4ij");
5274 1 : EXPECT_ERROR("f-611.2+38.4i");
5275 1 : EXPECT_ERROR("-611.2+f38.4i");
5276 1 : EXPECT_ERROR("-611.2+-38.4i");
5277 1 : EXPECT_ERROR("611.2+38.4");
5278 1 : EXPECT_ERROR("38.4i");
5279 1 : EXPECT_ERROR("38.4x");
5280 1 : EXPECT_ERROR("invalid");
5281 1 : }
5282 :
5283 4 : TEST_F(test_cpl, CPLForceToASCII)
5284 : {
5285 : {
5286 1 : char *pszOut = CPLForceToASCII("foo", -1, '_');
5287 1 : EXPECT_STREQ(pszOut, "foo");
5288 1 : CPLFree(pszOut);
5289 : }
5290 : {
5291 1 : char *pszOut = CPLForceToASCII("foo", 1, '_');
5292 1 : EXPECT_STREQ(pszOut, "f");
5293 1 : CPLFree(pszOut);
5294 : }
5295 : {
5296 1 : char *pszOut = CPLForceToASCII("foo\xFF", -1, '_');
5297 1 : EXPECT_STREQ(pszOut, "foo_");
5298 1 : CPLFree(pszOut);
5299 : }
5300 1 : }
5301 :
5302 4 : TEST_F(test_cpl, CPLUTF8ForceToASCII)
5303 : {
5304 : {
5305 1 : char *pszOut = CPLUTF8ForceToASCII("foo", '_');
5306 1 : EXPECT_STREQ(pszOut, "foo");
5307 1 : CPLFree(pszOut);
5308 : }
5309 : {
5310 : // Truncated UTF-8 character
5311 1 : char *pszOut = CPLUTF8ForceToASCII("foo\xC0", '_');
5312 1 : EXPECT_STREQ(pszOut, "foo");
5313 1 : CPLFree(pszOut);
5314 : }
5315 : {
5316 1 : char *pszOut = CPLUTF8ForceToASCII("foo\xc2\x80", '_');
5317 1 : EXPECT_STREQ(pszOut, "foo_");
5318 1 : CPLFree(pszOut);
5319 : }
5320 : {
5321 1 : char *pszOut = CPLUTF8ForceToASCII("foo\xc2\x80x", '_');
5322 1 : EXPECT_STREQ(pszOut, "foo_x");
5323 1 : CPLFree(pszOut);
5324 : }
5325 : {
5326 1 : std::string s;
5327 : {
5328 : VSILFILE *f =
5329 1 : VSIFOpenL((data_ + SEP + "utf8accents.txt").c_str(), "rb");
5330 1 : ASSERT_NE(f, nullptr);
5331 1 : VSIFSeekL(f, 0, SEEK_END);
5332 1 : s.resize(static_cast<size_t>(VSIFTellL(f)));
5333 1 : VSIFSeekL(f, 0, SEEK_SET);
5334 1 : VSIFReadL(&s[0], 1, s.size(), f);
5335 1 : VSIFCloseL(f);
5336 2 : while (!s.empty() && s.back() == '\n')
5337 1 : s.pop_back();
5338 : }
5339 1 : std::string sRef;
5340 : {
5341 1 : VSILFILE *f = VSIFOpenL(
5342 2 : (data_ + SEP + "utf8accents_ascii.txt").c_str(), "rb");
5343 1 : ASSERT_NE(f, nullptr);
5344 1 : VSIFSeekL(f, 0, SEEK_END);
5345 1 : sRef.resize(static_cast<size_t>(VSIFTellL(f)));
5346 1 : VSIFSeekL(f, 0, SEEK_SET);
5347 1 : VSIFReadL(&sRef[0], 1, sRef.size(), f);
5348 1 : VSIFCloseL(f);
5349 2 : while (!sRef.empty() && sRef.back() == '\n')
5350 1 : sRef.pop_back();
5351 : }
5352 1 : char *pszOut = CPLUTF8ForceToASCII(s.c_str(), '_');
5353 1 : EXPECT_STREQ(pszOut, sRef.c_str());
5354 1 : CPLFree(pszOut);
5355 : }
5356 : }
5357 :
5358 : #ifndef _WIN32
5359 4 : TEST_F(test_cpl, CPLSpawn)
5360 : {
5361 : VSIStatBufL sStatBuf;
5362 1 : if (VSIStatL("/bin/true", &sStatBuf) == 0)
5363 : {
5364 1 : const char *const apszArgs[] = {"/bin/true", nullptr};
5365 1 : EXPECT_EQ(CPLSpawn(apszArgs, nullptr, nullptr, false), 0);
5366 : }
5367 1 : if (VSIStatL("/bin/false", &sStatBuf) == 0)
5368 : {
5369 1 : const char *const apszArgs[] = {"/bin/false", nullptr};
5370 1 : EXPECT_EQ(CPLSpawn(apszArgs, nullptr, nullptr, false), 1);
5371 : }
5372 :
5373 : {
5374 1 : const char *const apszArgs[] = {"/i_do/not/exist", nullptr};
5375 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
5376 1 : EXPECT_EQ(CPLSpawn(apszArgs, nullptr, nullptr, false), -1);
5377 1 : CPLPopErrorHandler();
5378 : }
5379 1 : }
5380 : #endif
5381 :
5382 2 : static bool ENDS_WITH(const char *pszStr, const char *pszEnd)
5383 : {
5384 4 : return strlen(pszStr) >= strlen(pszEnd) &&
5385 4 : strcmp(pszStr + strlen(pszStr) - strlen(pszEnd), pszEnd) == 0;
5386 : }
5387 :
5388 4 : TEST_F(test_cpl, VSIMemGenerateHiddenFilename)
5389 : {
5390 : {
5391 : // Initial cleanup
5392 1 : VSIRmdirRecursive("/vsimem/");
5393 1 : VSIRmdirRecursive("/vsimem/.#!HIDDEN!#.");
5394 :
5395 : // Generate unlisted filename
5396 2 : const std::string osFilename1 = VSIMemGenerateHiddenFilename(nullptr);
5397 1 : const char *pszFilename1 = osFilename1.c_str();
5398 1 : EXPECT_TRUE(STARTS_WITH(pszFilename1, "/vsimem/.#!HIDDEN!#./"));
5399 1 : EXPECT_TRUE(ENDS_WITH(pszFilename1, "/unnamed"));
5400 :
5401 : {
5402 : // Check the file doesn't exist yet
5403 : VSIStatBufL sStat;
5404 1 : EXPECT_EQ(VSIStatL(pszFilename1, &sStat), -1);
5405 : }
5406 :
5407 : // Create the file with some content
5408 1 : GByte abyDummyData[1] = {0};
5409 1 : VSIFCloseL(VSIFileFromMemBuffer(pszFilename1, abyDummyData,
5410 : sizeof(abyDummyData), false));
5411 :
5412 : {
5413 : // Check the file exists now
5414 : VSIStatBufL sStat;
5415 1 : EXPECT_EQ(VSIStatL(pszFilename1, &sStat), 0);
5416 : }
5417 :
5418 : // Gets back content
5419 1 : EXPECT_EQ(VSIGetMemFileBuffer(pszFilename1, nullptr, false),
5420 : abyDummyData);
5421 :
5422 : {
5423 : // Check the hidden file doesn't popup
5424 2 : const CPLStringList aosFiles(VSIReadDir("/vsimem/"));
5425 1 : EXPECT_EQ(aosFiles.size(), 0);
5426 : }
5427 :
5428 : {
5429 : // Check that we can list the below directory if we know it exists
5430 : // and there's just one subdir
5431 2 : const CPLStringList aosFiles(VSIReadDir("/vsimem/.#!HIDDEN!#."));
5432 1 : EXPECT_EQ(aosFiles.size(), 1);
5433 : }
5434 :
5435 : {
5436 : // but that it is not an explicit directory
5437 : VSIStatBufL sStat;
5438 1 : EXPECT_EQ(VSIStatL("/vsimem/.#!HIDDEN!#.", &sStat), -1);
5439 : }
5440 :
5441 : // Creates second file
5442 2 : const std::string osFilename2 = VSIMemGenerateHiddenFilename(nullptr);
5443 1 : const char *pszFilename2 = osFilename2.c_str();
5444 1 : EXPECT_TRUE(strcmp(pszFilename1, pszFilename2) != 0);
5445 :
5446 : // Create it
5447 1 : VSIFCloseL(VSIFileFromMemBuffer(pszFilename2, abyDummyData,
5448 : sizeof(abyDummyData), false));
5449 :
5450 : {
5451 : // Check that we can list the root hidden dir if we know it exists
5452 2 : const CPLStringList aosFiles(VSIReadDir("/vsimem/.#!HIDDEN!#."));
5453 1 : EXPECT_EQ(aosFiles.size(), 2);
5454 : }
5455 :
5456 : {
5457 : // Create an explicit subdirectory in a hidden directory
5458 : const std::string osBaseName =
5459 2 : VSIMemGenerateHiddenFilename(nullptr);
5460 : const std::string osSubDir =
5461 2 : CPLFormFilename(osBaseName.c_str(), "mysubdir", nullptr);
5462 1 : EXPECT_EQ(VSIMkdir(osSubDir.c_str(), 0), 0);
5463 :
5464 : // Check the subdirectory exists
5465 : {
5466 : VSIStatBufL sStat;
5467 1 : EXPECT_EQ(VSIStatL(osSubDir.c_str(), &sStat), 0);
5468 : }
5469 :
5470 : // but not its hidden parent
5471 : {
5472 : VSIStatBufL sStat;
5473 1 : EXPECT_EQ(VSIStatL(osBaseName.c_str(), &sStat), -1);
5474 : }
5475 :
5476 : // Create file within the subdirectory
5477 1 : VSIFCloseL(VSIFileFromMemBuffer(
5478 : CPLFormFilename(osSubDir.c_str(), "my.bin", nullptr),
5479 : abyDummyData, sizeof(abyDummyData), false));
5480 :
5481 : {
5482 : // Check that we can list the subdirectory
5483 2 : const CPLStringList aosFiles(VSIReadDir(osSubDir.c_str()));
5484 1 : EXPECT_EQ(aosFiles.size(), 1);
5485 : }
5486 :
5487 : {
5488 : // Check that we can list the root hidden dir if we know it exists
5489 : const CPLStringList aosFiles(
5490 2 : VSIReadDir("/vsimem/.#!HIDDEN!#."));
5491 1 : EXPECT_EQ(aosFiles.size(), 3);
5492 : }
5493 : }
5494 :
5495 : // Directly create a directory with the return of VSIMemGenerateHiddenFilename()
5496 : {
5497 2 : const std::string osDirname = VSIMemGenerateHiddenFilename(nullptr);
5498 1 : EXPECT_EQ(VSIMkdir(osDirname.c_str(), 0), 0);
5499 :
5500 : // Check the subdirectory exists
5501 : {
5502 : VSIStatBufL sStat;
5503 1 : EXPECT_EQ(VSIStatL(osDirname.c_str(), &sStat), 0);
5504 : }
5505 :
5506 : // Create file within the subdirectory
5507 1 : VSIFCloseL(VSIFileFromMemBuffer(
5508 : CPLFormFilename(osDirname.c_str(), "my.bin", nullptr),
5509 : abyDummyData, sizeof(abyDummyData), false));
5510 :
5511 : {
5512 : // Check there's a file in this subdirectory
5513 2 : const CPLStringList aosFiles(VSIReadDir(osDirname.c_str()));
5514 1 : EXPECT_EQ(aosFiles.size(), 1);
5515 : }
5516 :
5517 1 : EXPECT_EQ(VSIRmdirRecursive(osDirname.c_str()), 0);
5518 :
5519 : {
5520 : // Check there's no longer any file in this subdirectory
5521 2 : const CPLStringList aosFiles(VSIReadDir(osDirname.c_str()));
5522 1 : EXPECT_EQ(aosFiles.size(), 0);
5523 : }
5524 :
5525 : {
5526 : // Check that it no longer exists
5527 : VSIStatBufL sStat;
5528 1 : EXPECT_EQ(VSIStatL(osDirname.c_str(), &sStat), -1);
5529 : }
5530 : }
5531 :
5532 : // Check that operations on "/vsimem/" do not interfere with hidden files
5533 : {
5534 : // Create regular file
5535 1 : VSIFCloseL(VSIFileFromMemBuffer("/vsimem/regular_file",
5536 : abyDummyData, sizeof(abyDummyData),
5537 : false));
5538 :
5539 : // Check it is visible
5540 1 : EXPECT_EQ(CPLStringList(VSIReadDir("/vsimem/")).size(), 1);
5541 :
5542 : // Clean root /vsimem/
5543 1 : VSIRmdirRecursive("/vsimem/");
5544 :
5545 : // No more user files
5546 1 : EXPECT_TRUE(CPLStringList(VSIReadDir("/vsimem/")).empty());
5547 :
5548 : // But still hidden files
5549 1 : EXPECT_TRUE(
5550 : !CPLStringList(VSIReadDir("/vsimem/.#!HIDDEN!#.")).empty());
5551 : }
5552 :
5553 : // Clean-up hidden files
5554 1 : EXPECT_EQ(VSIRmdirRecursive("/vsimem/.#!HIDDEN!#."), 0);
5555 :
5556 : {
5557 : // Check the root hidden dir is empty
5558 2 : const CPLStringList aosFiles(VSIReadDir("/vsimem/.#!HIDDEN!#."));
5559 1 : EXPECT_TRUE(aosFiles.empty());
5560 : }
5561 :
5562 1 : EXPECT_EQ(VSIRmdirRecursive("/vsimem/.#!HIDDEN!#."), 0);
5563 : }
5564 :
5565 : {
5566 2 : const std::string osFilename = VSIMemGenerateHiddenFilename("foo.bar");
5567 1 : const char *pszFilename = osFilename.c_str();
5568 1 : EXPECT_TRUE(STARTS_WITH(pszFilename, "/vsimem/.#!HIDDEN!#./"));
5569 1 : EXPECT_TRUE(ENDS_WITH(pszFilename, "/foo.bar"));
5570 : }
5571 1 : }
5572 :
5573 4 : TEST_F(test_cpl, VSIGlob)
5574 : {
5575 1 : GByte abyDummyData[1] = {0};
5576 1 : const std::string osFilenameRadix = VSIMemGenerateHiddenFilename("");
5577 1 : const std::string osFilename = osFilenameRadix + "trick";
5578 1 : VSIFCloseL(VSIFileFromMemBuffer(osFilename.c_str(), abyDummyData,
5579 : sizeof(abyDummyData), false));
5580 :
5581 : {
5582 : CPLStringList aosRes(
5583 1 : VSIGlob(osFilename.c_str(), nullptr, nullptr, nullptr));
5584 1 : ASSERT_EQ(aosRes.size(), 1);
5585 1 : EXPECT_STREQ(aosRes[0], osFilename.c_str());
5586 : }
5587 :
5588 : {
5589 : CPLStringList aosRes(
5590 1 : VSIGlob(osFilename.substr(0, osFilename.size() - 1).c_str(),
5591 1 : nullptr, nullptr, nullptr));
5592 1 : ASSERT_EQ(aosRes.size(), 0);
5593 : }
5594 :
5595 : {
5596 : CPLStringList aosRes(
5597 1 : VSIGlob(std::string(osFilenameRadix).append("?rick").c_str(),
5598 1 : nullptr, nullptr, nullptr));
5599 1 : ASSERT_EQ(aosRes.size(), 1);
5600 1 : EXPECT_STREQ(aosRes[0], osFilename.c_str());
5601 : }
5602 :
5603 : {
5604 : CPLStringList aosRes(
5605 1 : VSIGlob(std::string(osFilenameRadix).append("?rack").c_str(),
5606 1 : nullptr, nullptr, nullptr));
5607 1 : ASSERT_EQ(aosRes.size(), 0);
5608 : }
5609 :
5610 : {
5611 : CPLStringList aosRes(
5612 1 : VSIGlob(std::string(osFilenameRadix).append("*ick").c_str(),
5613 1 : nullptr, nullptr, nullptr));
5614 1 : ASSERT_EQ(aosRes.size(), 1);
5615 1 : EXPECT_STREQ(aosRes[0], osFilename.c_str());
5616 : }
5617 :
5618 : {
5619 : CPLStringList aosRes(
5620 1 : VSIGlob(std::string(osFilenameRadix).append("*").c_str(), nullptr,
5621 1 : nullptr, nullptr));
5622 1 : ASSERT_EQ(aosRes.size(), 1);
5623 1 : EXPECT_STREQ(aosRes[0], osFilename.c_str());
5624 : }
5625 :
5626 : {
5627 : CPLStringList aosRes(
5628 1 : VSIGlob(std::string(osFilenameRadix).append("*ack").c_str(),
5629 1 : nullptr, nullptr, nullptr));
5630 1 : ASSERT_EQ(aosRes.size(), 0);
5631 : }
5632 :
5633 : {
5634 : CPLStringList aosRes(
5635 1 : VSIGlob(std::string(osFilenameRadix).append("*ic*").c_str(),
5636 1 : nullptr, nullptr, nullptr));
5637 1 : ASSERT_EQ(aosRes.size(), 1);
5638 1 : EXPECT_STREQ(aosRes[0], osFilename.c_str());
5639 : }
5640 :
5641 : {
5642 : CPLStringList aosRes(
5643 1 : VSIGlob(std::string(osFilenameRadix).append("*ac*").c_str(),
5644 1 : nullptr, nullptr, nullptr));
5645 1 : ASSERT_EQ(aosRes.size(), 0);
5646 : }
5647 :
5648 : {
5649 : CPLStringList aosRes(VSIGlob(
5650 1 : std::string(osFilenameRadix).append("[st][!s]ic[j-l]").c_str(),
5651 1 : nullptr, nullptr, nullptr));
5652 1 : ASSERT_EQ(aosRes.size(), 1);
5653 1 : EXPECT_STREQ(aosRes[0], osFilename.c_str());
5654 : }
5655 :
5656 : {
5657 : CPLStringList aosRes(
5658 1 : VSIGlob(std::string(osFilenameRadix).append("[!s]rick").c_str(),
5659 1 : nullptr, nullptr, nullptr));
5660 1 : ASSERT_EQ(aosRes.size(), 1);
5661 1 : EXPECT_STREQ(aosRes[0], osFilename.c_str());
5662 : }
5663 :
5664 : {
5665 : CPLStringList aosRes(
5666 1 : VSIGlob(std::string(osFilenameRadix).append("[").c_str(), nullptr,
5667 1 : nullptr, nullptr));
5668 1 : ASSERT_EQ(aosRes.size(), 0);
5669 : }
5670 :
5671 1 : const std::string osFilenameWithSpecialChars = osFilenameRadix + "[!-]";
5672 1 : VSIFCloseL(VSIFileFromMemBuffer(osFilenameWithSpecialChars.c_str(),
5673 : abyDummyData, sizeof(abyDummyData), false));
5674 :
5675 : {
5676 : CPLStringList aosRes(VSIGlob(
5677 1 : std::string(osFilenameRadix).append("[[][!]a-][-][]]").c_str(),
5678 1 : nullptr, nullptr, nullptr));
5679 1 : ASSERT_EQ(aosRes.size(), 1);
5680 1 : EXPECT_STREQ(aosRes[0], osFilenameWithSpecialChars.c_str());
5681 : }
5682 :
5683 1 : const std::string osFilename2 = osFilenameRadix + "truck/track";
5684 1 : VSIFCloseL(VSIFileFromMemBuffer(osFilename2.c_str(), abyDummyData,
5685 : sizeof(abyDummyData), false));
5686 :
5687 : {
5688 : CPLStringList aosRes(
5689 1 : VSIGlob(std::string(osFilenameRadix).append("*uc*/track").c_str(),
5690 1 : nullptr, nullptr, nullptr));
5691 1 : ASSERT_EQ(aosRes.size(), 1);
5692 1 : EXPECT_STREQ(aosRes[0], osFilename2.c_str());
5693 : }
5694 :
5695 : {
5696 : CPLStringList aosRes(
5697 1 : VSIGlob(std::string(osFilenameRadix).append("*uc*/truck").c_str(),
5698 1 : nullptr, nullptr, nullptr));
5699 1 : ASSERT_EQ(aosRes.size(), 0);
5700 : }
5701 :
5702 : {
5703 : CPLStringList aosRes(
5704 1 : VSIGlob(std::string(osFilenameRadix).append("**/track").c_str(),
5705 1 : nullptr, nullptr, nullptr));
5706 1 : ASSERT_EQ(aosRes.size(), 1);
5707 1 : EXPECT_STREQ(aosRes[0], osFilename2.c_str());
5708 : }
5709 :
5710 1 : VSIUnlink(osFilename.c_str());
5711 1 : VSIUnlink(osFilenameWithSpecialChars.c_str());
5712 1 : VSIUnlink(osFilename2.c_str());
5713 1 : VSIUnlink(osFilenameRadix.c_str());
5714 :
5715 : #if !defined(_WIN32)
5716 : {
5717 1 : std::string osCurDir;
5718 1 : osCurDir.resize(4096);
5719 1 : getcwd(&osCurDir[0], osCurDir.size());
5720 1 : osCurDir.resize(strlen(osCurDir.c_str()));
5721 1 : ASSERT_EQ(chdir(TUT_ROOT_DATA_DIR), 0);
5722 1 : CPLStringList aosRes(VSIGlob("byte*.tif", nullptr, nullptr, nullptr));
5723 1 : chdir(osCurDir.c_str());
5724 1 : ASSERT_EQ(aosRes.size(), 1);
5725 1 : EXPECT_STREQ(aosRes[0], "byte.tif");
5726 : }
5727 : #endif
5728 : }
5729 :
5730 4 : TEST_F(test_cpl, CPLGreatestCommonDivisor)
5731 : {
5732 2 : CPLErrorStateBackuper state(CPLQuietErrorHandler);
5733 :
5734 : // These tests serve to document the current behavior.
5735 : // In some cases the results are dependent on various
5736 : // hardcoded epsilons and it may be appropriate to change
5737 : // the expected results.
5738 :
5739 1 : EXPECT_EQ(CPLGreatestCommonDivisor(0.0, 1.0), 0.0);
5740 1 : EXPECT_EQ(
5741 : CPLGreatestCommonDivisor(std::numeric_limits<double>::quiet_NaN(), 1.0),
5742 : 0.0);
5743 1 : EXPECT_EQ(
5744 : CPLGreatestCommonDivisor(std::numeric_limits<double>::infinity(), 1.0),
5745 : 0.0);
5746 1 : EXPECT_EQ(
5747 : CPLGreatestCommonDivisor(-std::numeric_limits<double>::infinity(), 1.0),
5748 : 0.0);
5749 1 : EXPECT_EQ(CPLGreatestCommonDivisor(1.0, 0.0), 0.0);
5750 1 : EXPECT_EQ(
5751 : CPLGreatestCommonDivisor(1.0, std::numeric_limits<double>::quiet_NaN()),
5752 : 0.0);
5753 1 : EXPECT_EQ(
5754 : CPLGreatestCommonDivisor(1.0, std::numeric_limits<double>::infinity()),
5755 : 0.0);
5756 1 : EXPECT_EQ(
5757 : CPLGreatestCommonDivisor(1.0, -std::numeric_limits<double>::infinity()),
5758 : 0.0);
5759 :
5760 1 : EXPECT_EQ(CPLGreatestCommonDivisor(std::numeric_limits<double>::min(),
5761 : std::numeric_limits<double>::max()),
5762 : 0.0);
5763 :
5764 1 : EXPECT_EQ(CPLGreatestCommonDivisor(-2.0, 4.0), -2.0);
5765 1 : EXPECT_EQ(CPLGreatestCommonDivisor(-2.0, -4.0), -2.0);
5766 1 : EXPECT_EQ(CPLGreatestCommonDivisor(2.0, -4.0), 2.0);
5767 :
5768 1 : EXPECT_EQ(CPLGreatestCommonDivisor(3.0, 5.0), 1.0);
5769 1 : EXPECT_EQ(CPLGreatestCommonDivisor(3.0 / 3600, 5.0 / 3600), 1.0 / 3600);
5770 1 : EXPECT_EQ(CPLGreatestCommonDivisor(5.0 / 3600, 2.5 / 3600), 2.5 / 3600);
5771 1 : EXPECT_EQ(CPLGreatestCommonDivisor(1.0 / 10, 1.0), 1.0 / 10);
5772 1 : EXPECT_EQ(CPLGreatestCommonDivisor(1.0 / 17, 1.0 / 13), 1.0 / 221);
5773 1 : EXPECT_EQ(CPLGreatestCommonDivisor(1.0 / 17, 1.0 / 3600), 1.0 / 61200);
5774 :
5775 : // GLO-90 resolutoins
5776 1 : EXPECT_EQ(CPLGreatestCommonDivisor(3.0 / 3600, 4.5 / 3600), 1.5 / 3600);
5777 :
5778 : // WorldDEM resolutions
5779 1 : EXPECT_EQ(CPLGreatestCommonDivisor(0.4 / 3600, 0.6 / 3600), 0.2 / 3600);
5780 1 : EXPECT_EQ(CPLGreatestCommonDivisor(0.6 / 3600, 0.8 / 3600), 0.2 / 3600);
5781 :
5782 1 : EXPECT_EQ(CPLGreatestCommonDivisor(M_PI, M_PI / 6), M_PI / 6);
5783 1 : EXPECT_EQ(CPLGreatestCommonDivisor(M_PI / 5, M_PI / 6),
5784 : 0); // Ideally we would get M_PI / 30
5785 :
5786 1 : EXPECT_EQ(CPLGreatestCommonDivisor(2.999999, 3.0), 0);
5787 1 : EXPECT_EQ(CPLGreatestCommonDivisor(2.9999999, 3.0), 0);
5788 1 : EXPECT_EQ(CPLGreatestCommonDivisor(2.99999999, 3.0), 2.99999999);
5789 1 : }
5790 :
5791 4 : TEST_F(test_cpl, CPLLevenshteinDistance)
5792 : {
5793 1 : EXPECT_EQ(CPLLevenshteinDistance("", "", false), 0);
5794 1 : EXPECT_EQ(CPLLevenshteinDistance("a", "a", false), 0);
5795 1 : EXPECT_EQ(CPLLevenshteinDistance("a", "b", false), 1);
5796 1 : EXPECT_EQ(CPLLevenshteinDistance("a", "", false), 1);
5797 1 : EXPECT_EQ(CPLLevenshteinDistance("abc", "ac", false), 1);
5798 1 : EXPECT_EQ(CPLLevenshteinDistance("ac", "abc", false), 1);
5799 1 : EXPECT_EQ(CPLLevenshteinDistance("0ab1", "0xy1", false), 2);
5800 1 : EXPECT_EQ(CPLLevenshteinDistance("0ab1", "0xy1", true), 2);
5801 1 : EXPECT_EQ(CPLLevenshteinDistance("0ab1", "0ba1", false), 2);
5802 1 : EXPECT_EQ(CPLLevenshteinDistance("0ab1", "0ba1", true), 1);
5803 :
5804 2 : std::string longStr(32768, 'x');
5805 1 : EXPECT_EQ(CPLLevenshteinDistance(longStr.c_str(), longStr.c_str(), true),
5806 : 0);
5807 1 : EXPECT_EQ(CPLLevenshteinDistance(longStr.c_str(), "another_one", true),
5808 : std::numeric_limits<size_t>::max());
5809 1 : }
5810 :
5811 4 : TEST_F(test_cpl, CPLLockFileEx)
5812 : {
5813 1 : const std::string osLockFilename = CPLGenerateTempFilename(".lock");
5814 :
5815 1 : ASSERT_EQ(CPLLockFileEx(nullptr, nullptr, nullptr), CLFS_API_MISUSE);
5816 :
5817 1 : ASSERT_EQ(CPLLockFileEx(osLockFilename.c_str(), nullptr, nullptr),
5818 : CLFS_API_MISUSE);
5819 :
5820 1 : CPLLockFileHandle hLockFileHandle = nullptr;
5821 :
5822 1 : ASSERT_EQ(CPLLockFileEx(osLockFilename.c_str(), &hLockFileHandle, nullptr),
5823 : CLFS_OK);
5824 1 : ASSERT_NE(hLockFileHandle, nullptr);
5825 :
5826 : // Check the lock file has been created
5827 : VSIStatBufL sStat;
5828 1 : ASSERT_EQ(VSIStatL(osLockFilename.c_str(), &sStat), 0);
5829 :
5830 : {
5831 1 : CPLStringList aosOptions;
5832 1 : aosOptions.SetNameValue("WAIT_TIME", "0.1");
5833 1 : CPLLockFileHandle hLockFileHandle2 = nullptr;
5834 1 : ASSERT_EQ(CPLLockFileEx(osLockFilename.c_str(), &hLockFileHandle2,
5835 : aosOptions.List()),
5836 : CLFS_LOCK_BUSY);
5837 : }
5838 :
5839 1 : CPLUnlockFileEx(hLockFileHandle);
5840 :
5841 : // Check the lock file has been deleted
5842 1 : ASSERT_EQ(VSIStatL(osLockFilename.c_str(), &sStat), -1);
5843 :
5844 1 : CPLUnlockFileEx(nullptr);
5845 : }
5846 :
5847 4 : TEST_F(test_cpl, CPLFormatReadableFileSize)
5848 : {
5849 2 : EXPECT_STREQ(CPLFormatReadableFileSize(1.23e18).c_str(), "1.23 HB");
5850 2 : EXPECT_STREQ(CPLFormatReadableFileSize(1.23e15).c_str(), "1.23 PB");
5851 2 : EXPECT_STREQ(CPLFormatReadableFileSize(1.23e12).c_str(), "1.23 TB");
5852 2 : EXPECT_STREQ(CPLFormatReadableFileSize(1.23e9).c_str(), "1.23 GB");
5853 2 : EXPECT_STREQ(CPLFormatReadableFileSize(1.23e6).c_str(), "1.23 MB");
5854 2 : EXPECT_STREQ(
5855 : CPLFormatReadableFileSize(static_cast<uint64_t>(123456)).c_str(),
5856 : "123,456 bytes");
5857 1 : }
5858 :
5859 4 : TEST_F(test_cpl, CPLStrlenUTF8)
5860 : {
5861 1 : EXPECT_EQ(CPLStrlenUTF8("a"), 1);
5862 1 : EXPECT_EQ(CPLStrlenUTF8("a"
5863 : "\xC3\xA9"
5864 : "b"),
5865 : 3);
5866 1 : }
5867 :
5868 4 : TEST_F(test_cpl, CPLStrlenUTF8Ex)
5869 : {
5870 1 : EXPECT_EQ(CPLStrlenUTF8Ex("a"), 1);
5871 1 : EXPECT_EQ(CPLStrlenUTF8Ex("a"
5872 : "\xC3\xA9"
5873 : "b"),
5874 : 3);
5875 1 : }
5876 :
5877 4 : TEST_F(test_cpl, CPLGetRemainingFileDescriptorCount)
5878 : {
5879 : #ifdef _WIN32
5880 : EXPECT_EQ(CPLGetRemainingFileDescriptorCount(), -1);
5881 : #else
5882 1 : EXPECT_GE(CPLGetRemainingFileDescriptorCount(), 0);
5883 : #endif
5884 1 : }
5885 :
5886 4 : TEST_F(test_cpl, CPLGetCurrentThreadCount)
5887 : {
5888 : #if defined(_WIN32) || defined(__linux) || defined(__FreeBSD__) || \
5889 : defined(__NetBSD__) || (defined(__APPLE__) && defined(__MACH__))
5890 : // Not sure why it returns 0 on those, whereas it works fine on build-windows-msys2-mingw
5891 1 : if (strstr(CPLGetConfigOption("BUILD_NAME", ""), "build-windows-conda") !=
5892 1 : nullptr &&
5893 0 : strstr(CPLGetConfigOption("BUILD_NAME", ""), "build-windows-minimum") !=
5894 : nullptr)
5895 : {
5896 0 : EXPECT_GE(CPLGetCurrentThreadCount(), 1);
5897 : }
5898 : #else
5899 : EXPECT_EQ(CPLGetCurrentThreadCount(), 0);
5900 : #endif
5901 1 : }
5902 :
5903 4 : TEST_F(test_cpl, CPLHasPathTraversal)
5904 : {
5905 1 : EXPECT_TRUE(CPLHasPathTraversal("a/../b"));
5906 1 : EXPECT_TRUE(CPLHasPathTraversal("a/../"));
5907 1 : EXPECT_TRUE(CPLHasPathTraversal("a/.."));
5908 1 : EXPECT_TRUE(CPLHasPathTraversal("a\\..\\b"));
5909 1 : EXPECT_FALSE(CPLHasPathTraversal("a/b"));
5910 : {
5911 : CPLConfigOptionSetter oSetter("CPL_ENABLE_PATH_TRAVERSAL_DETECTION",
5912 2 : "NO", true);
5913 1 : EXPECT_FALSE(CPLHasPathTraversal("a/../b"));
5914 1 : EXPECT_FALSE(CPLHasPathTraversal("a\\..\\b"));
5915 : }
5916 1 : }
5917 :
5918 4 : TEST_F(test_cpl, CPLHasUnbalancedPathTraversal)
5919 : {
5920 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("a"));
5921 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("."));
5922 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("./"));
5923 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("a/.."));
5924 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("a/../b"));
5925 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("./a/../b"));
5926 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("a\\..\\b"));
5927 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("a/../b/../"));
5928 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("a/../b/.."));
5929 1 : EXPECT_FALSE(CPLHasUnbalancedPathTraversal("a/b"));
5930 :
5931 1 : EXPECT_TRUE(CPLHasUnbalancedPathTraversal(".."));
5932 1 : EXPECT_TRUE(CPLHasUnbalancedPathTraversal("../"));
5933 1 : EXPECT_TRUE(CPLHasUnbalancedPathTraversal("../b"));
5934 1 : EXPECT_TRUE(CPLHasUnbalancedPathTraversal("a/../../"));
5935 1 : EXPECT_TRUE(CPLHasUnbalancedPathTraversal("a/../b/../.."));
5936 1 : EXPECT_TRUE(CPLHasUnbalancedPathTraversal("a/../b/../../"));
5937 1 : EXPECT_TRUE(CPLHasUnbalancedPathTraversal("a\\..\\..\\"));
5938 1 : }
5939 :
5940 4 : TEST_F(test_cpl, cpl_enumerate)
5941 : {
5942 : {
5943 1 : size_t expectedIdx = 0;
5944 1 : const int tab[] = {3, 1, 2};
5945 4 : for (auto [idx, val] : cpl::enumerate(tab))
5946 : {
5947 3 : EXPECT_EQ(idx, expectedIdx);
5948 3 : EXPECT_EQ(val, tab[idx]);
5949 3 : ++expectedIdx;
5950 : }
5951 1 : EXPECT_EQ(expectedIdx, 3U);
5952 : }
5953 : {
5954 1 : int tab[] = {3, 1, 2};
5955 4 : for (auto [idx, val] : cpl::enumerate(tab))
5956 : {
5957 : (void)idx;
5958 3 : ++val;
5959 : }
5960 1 : EXPECT_EQ(tab[0], 4);
5961 1 : EXPECT_EQ(tab[1], 2);
5962 1 : EXPECT_EQ(tab[2], 3);
5963 : }
5964 1 : }
5965 :
5966 4 : TEST_F(test_cpl, CPL_SWAP)
5967 : {
5968 : {
5969 1 : uint8_t x = 1;
5970 1 : EXPECT_EQ(CPL_SWAP(x), x);
5971 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
5972 : }
5973 : {
5974 1 : int8_t x = 1;
5975 1 : EXPECT_EQ(CPL_SWAP(x), x);
5976 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
5977 : }
5978 : {
5979 1 : uint16_t x = 0x0123;
5980 1 : auto y = CPL_SWAP(x);
5981 1 : EXPECT_NE(y, x);
5982 1 : EXPECT_EQ(CPL_SWAP(y), x);
5983 : #if CPL_IS_LSB
5984 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
5985 : #else
5986 : EXPECT_EQ(CPL_AS_LSB(x), CPL_SWAP(x));
5987 : #endif
5988 : }
5989 : {
5990 1 : int16_t x = 0x0123;
5991 1 : auto y = CPL_SWAP(x);
5992 1 : EXPECT_NE(y, x);
5993 1 : EXPECT_EQ(CPL_SWAP(y), x);
5994 : #if CPL_IS_LSB
5995 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
5996 : #else
5997 : EXPECT_EQ(CPL_AS_LSB(x), CPL_SWAP(x));
5998 : #endif
5999 : }
6000 : {
6001 1 : uint32_t x = 0x01234567;
6002 1 : auto y = CPL_SWAP(x);
6003 1 : EXPECT_NE(y, x);
6004 1 : EXPECT_EQ(CPL_SWAP(y), x);
6005 : #if CPL_IS_LSB
6006 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
6007 : #else
6008 : EXPECT_EQ(CPL_AS_LSB(x), CPL_SWAP(x));
6009 : #endif
6010 : }
6011 : {
6012 1 : int32_t x = 0x01234567;
6013 1 : auto y = CPL_SWAP(x);
6014 1 : EXPECT_NE(y, x);
6015 1 : EXPECT_EQ(CPL_SWAP(y), x);
6016 : #if CPL_IS_LSB
6017 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
6018 : #else
6019 : EXPECT_EQ(CPL_AS_LSB(x), CPL_SWAP(x));
6020 : #endif
6021 : }
6022 : {
6023 1 : uint64_t x = (static_cast<uint64_t>(0x01234567) << 32) | 0x89ABCDEF;
6024 1 : auto y = CPL_SWAP(x);
6025 1 : EXPECT_NE(y, x);
6026 1 : EXPECT_EQ(CPL_SWAP(y), x);
6027 : #if CPL_IS_LSB
6028 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
6029 : #else
6030 : EXPECT_EQ(CPL_AS_LSB(x), CPL_SWAP(x));
6031 : #endif
6032 : }
6033 : {
6034 1 : int64_t x = (static_cast<int64_t>(0x01234567) << 32) | 0x89ABCDEF;
6035 1 : auto y = CPL_SWAP(x);
6036 1 : EXPECT_NE(y, x);
6037 1 : EXPECT_EQ(CPL_SWAP(y), x);
6038 : #if CPL_IS_LSB
6039 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
6040 : #else
6041 : EXPECT_EQ(CPL_AS_LSB(x), CPL_SWAP(x));
6042 : #endif
6043 : }
6044 : {
6045 1 : float x = 1.5;
6046 1 : auto y = CPL_SWAP(x);
6047 1 : EXPECT_NE(y, x);
6048 1 : EXPECT_EQ(CPL_SWAP(y), x);
6049 : #if CPL_IS_LSB
6050 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
6051 : #else
6052 : EXPECT_EQ(CPL_AS_LSB(x), CPL_SWAP(x));
6053 : #endif
6054 : }
6055 : {
6056 1 : double x = 1.5;
6057 1 : auto y = CPL_SWAP(x);
6058 1 : EXPECT_NE(y, x);
6059 1 : EXPECT_EQ(CPL_SWAP(y), x);
6060 : #if CPL_IS_LSB
6061 1 : EXPECT_EQ(CPL_AS_LSB(x), x);
6062 : #else
6063 : EXPECT_EQ(CPL_AS_LSB(x), CPL_SWAP(x));
6064 : #endif
6065 : }
6066 1 : }
6067 :
6068 4 : TEST_F(test_cpl, CPLLaunderForFilenameSafe)
6069 : {
6070 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("").c_str(), "");
6071 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a").c_str(), "a");
6072 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a<b").c_str(), "a_b");
6073 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a>b").c_str(), "a_b");
6074 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a:b").c_str(), "a_b");
6075 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a\"b").c_str(), "a_b");
6076 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a/b").c_str(), "a_b");
6077 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a\\b").c_str(), "a_b");
6078 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a|b").c_str(), "a_b");
6079 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a?b").c_str(), "a_b");
6080 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a*b").c_str(), "a_b");
6081 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a^b").c_str(), "a_b");
6082 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe(".").c_str(), "._");
6083 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("..").c_str(), ".._");
6084 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a.b").c_str(), "a.b");
6085 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe(" a ").c_str(), " a _");
6086 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe(".a.").c_str(), ".a._");
6087 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe(" a ", ';').c_str(), " a ;");
6088 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("CON").c_str(), "CON_");
6089 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a<b c", ';', " ").c_str(), "a;b;c");
6090 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("a<b c", '\0', " ").c_str(), "abc");
6091 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("CON", '\0', nullptr).c_str(),
6092 : "CON_");
6093 2 : EXPECT_STREQ(CPLLaunderForFilenameSafe("CON", ';').c_str(), "CON;");
6094 1 : }
6095 :
6096 4 : TEST_F(test_cpl, cpl_starts_with)
6097 : {
6098 2 : std::string str = "abc";
6099 1 : const char *cstr = "abc";
6100 1 : std::string_view sv = std::string_view(str).substr(0, 2);
6101 :
6102 1 : EXPECT_TRUE(cpl::starts_with(str, "ab"));
6103 1 : EXPECT_TRUE(cpl::starts_with(cstr, "ab"));
6104 1 : EXPECT_TRUE(cpl::starts_with(sv, "ab"));
6105 1 : EXPECT_TRUE(cpl::starts_with(sv, ""));
6106 :
6107 1 : EXPECT_TRUE(cpl::starts_with_ci(str, "ab"));
6108 1 : EXPECT_TRUE(cpl::starts_with_ci(str, "aB"));
6109 1 : EXPECT_TRUE(cpl::starts_with_ci(str, ""));
6110 :
6111 1 : EXPECT_FALSE(cpl::starts_with(str, "ac"));
6112 1 : EXPECT_FALSE(cpl::starts_with(str, "abcd"));
6113 1 : EXPECT_FALSE(cpl::starts_with(str, "aB"));
6114 1 : EXPECT_FALSE(cpl::starts_with(std::string_view(str).substr(0, 1), "ab"));
6115 1 : }
6116 :
6117 4 : TEST_F(test_cpl, cpl_ends_with)
6118 : {
6119 2 : std::string str = "abc";
6120 1 : const char *cstr = "abc";
6121 1 : std::string_view sv = std::string_view(str).substr(0, 3);
6122 :
6123 1 : EXPECT_TRUE(cpl::ends_with(str, "bc"));
6124 1 : EXPECT_TRUE(cpl::ends_with(cstr, "bc"));
6125 1 : EXPECT_TRUE(cpl::ends_with(sv, "bc"));
6126 1 : EXPECT_TRUE(cpl::ends_with(sv, ""));
6127 :
6128 1 : EXPECT_TRUE(cpl::ends_with_ci(str, "bc"));
6129 1 : EXPECT_TRUE(cpl::ends_with_ci(str, "bC"));
6130 1 : EXPECT_TRUE(cpl::ends_with_ci(str, ""));
6131 :
6132 1 : EXPECT_FALSE(cpl::ends_with(str, "ac"));
6133 1 : EXPECT_FALSE(cpl::ends_with(str, "abcd"));
6134 1 : EXPECT_FALSE(cpl::ends_with(str, "Bc"));
6135 1 : EXPECT_FALSE(cpl::ends_with(std::string_view(str).substr(0, 2), "bc"));
6136 1 : }
6137 :
6138 4 : TEST_F(test_cpl, cpl_equals)
6139 : {
6140 2 : std::string str = "abc";
6141 1 : const char *cstr = "abc";
6142 1 : std::string_view sv = str;
6143 :
6144 1 : EXPECT_TRUE(cpl::equals(str, cstr));
6145 1 : EXPECT_TRUE(cpl::equals(cstr, sv));
6146 1 : EXPECT_TRUE(cpl::equals(sv, str));
6147 :
6148 1 : EXPECT_FALSE(cpl::equals(str, ""));
6149 1 : EXPECT_FALSE(cpl::equals(str, std::string_view(str).substr(0, 2)));
6150 :
6151 1 : EXPECT_FALSE(cpl::equals(str, "abC"));
6152 1 : EXPECT_TRUE(cpl::equals_ci(str, "abC"));
6153 1 : EXPECT_FALSE(cpl::equals_ci(str, ""));
6154 1 : }
6155 :
6156 4 : TEST_F(test_cpl, trim)
6157 : {
6158 : // input type: const char*
6159 : {
6160 1 : const char *str = "";
6161 1 : const auto trimmed = cpl::trim(str);
6162 1 : EXPECT_EQ(trimmed, "");
6163 1 : EXPECT_EQ(trimmed.data(), str); // trimmed points within str
6164 :
6165 1 : const auto ltrimmed = cpl::ltrim(str);
6166 1 : EXPECT_EQ(ltrimmed, "");
6167 1 : EXPECT_EQ(ltrimmed.data(), str);
6168 :
6169 1 : const auto rtrimmed = cpl::rtrim(str);
6170 1 : EXPECT_EQ(rtrimmed, "");
6171 1 : EXPECT_EQ(rtrimmed.data(), str);
6172 : }
6173 :
6174 : // input type: std::string
6175 : {
6176 2 : const std::string str = "\r\n\t \r\n\t";
6177 1 : const auto trimmed = cpl::trim(str);
6178 :
6179 1 : EXPECT_EQ(trimmed, "");
6180 1 : EXPECT_EQ(trimmed.data(), str.data() + str.size());
6181 :
6182 1 : const auto ltrimmed = cpl::ltrim(str);
6183 :
6184 1 : EXPECT_EQ(ltrimmed, "");
6185 1 : EXPECT_EQ(ltrimmed.data(), str.data() + str.size());
6186 :
6187 1 : const auto rtrimmed = cpl::rtrim(str);
6188 :
6189 1 : EXPECT_EQ(rtrimmed, "");
6190 1 : EXPECT_EQ(rtrimmed.data(), str.data());
6191 : }
6192 :
6193 : // input type: std::string_view
6194 : {
6195 1 : const std::string_view str = " abc\t ";
6196 1 : const auto trimmed = cpl::trim(str);
6197 :
6198 1 : EXPECT_EQ(trimmed, "abc");
6199 1 : EXPECT_EQ(trimmed.data(), str.data() + 2); // trimmed points within str
6200 :
6201 1 : const auto ltrimmed = cpl::ltrim(str);
6202 :
6203 1 : EXPECT_EQ(ltrimmed, "abc\t ");
6204 1 : EXPECT_EQ(ltrimmed.data(), str.data() + 2);
6205 :
6206 1 : const auto rtrimmed = cpl::rtrim(str);
6207 :
6208 1 : EXPECT_EQ(rtrimmed, " abc");
6209 1 : EXPECT_EQ(rtrimmed.data(), str.data());
6210 : }
6211 :
6212 : // input_type: std::string_view&&
6213 : {
6214 : // line below should not compile
6215 : //auto trimmed = cpl::trim(std::string("abc"));
6216 : }
6217 1 : }
6218 :
6219 4 : TEST_F(test_cpl, parse_name_value)
6220 : {
6221 : {
6222 2 : std::string input = "OPT_NAME=VALUE";
6223 1 : auto [name, value] = cpl::parse_name_value(input);
6224 :
6225 1 : EXPECT_EQ(name, "OPT_NAME");
6226 1 : EXPECT_EQ(value, "VALUE");
6227 : }
6228 :
6229 : {
6230 1 : const char *input = " OPT_NAME = VALUE WITH SPACE ";
6231 1 : auto [name, value] = cpl::parse_name_value(input);
6232 :
6233 1 : EXPECT_EQ(name, "OPT_NAME");
6234 1 : EXPECT_EQ(value, "VALUE WITH SPACE");
6235 : }
6236 :
6237 : {
6238 2 : std::string input = "OPT_NAME=";
6239 1 : auto [name, value] = cpl::parse_name_value(input);
6240 :
6241 1 : EXPECT_EQ(name, "OPT_NAME");
6242 1 : EXPECT_EQ(value, "");
6243 : }
6244 :
6245 : {
6246 2 : std::string input = "=VALUE";
6247 1 : auto [name, value] = cpl::parse_name_value(input);
6248 :
6249 1 : EXPECT_EQ(name, "");
6250 1 : EXPECT_EQ(value, "");
6251 : }
6252 :
6253 : {
6254 2 : std::string input = "INVALID";
6255 1 : auto [name, value] = cpl::parse_name_value(input);
6256 :
6257 1 : EXPECT_EQ(name, "");
6258 1 : EXPECT_EQ(value, "");
6259 : }
6260 :
6261 : {
6262 1 : const char *input = "";
6263 1 : auto [name, value] = cpl::parse_name_value(input);
6264 :
6265 1 : EXPECT_EQ(name, "");
6266 1 : EXPECT_EQ(value, "");
6267 : }
6268 1 : }
6269 :
6270 4 : TEST_F(test_cpl, strict_parse)
6271 : {
6272 1 : EXPECT_EQ(cpl::strict_parse<bool>("YES"), true);
6273 1 : EXPECT_EQ(cpl::strict_parse<bool>("1 "), true);
6274 1 : EXPECT_EQ(cpl::strict_parse<bool>(" ON "), true);
6275 1 : EXPECT_EQ(cpl::strict_parse<bool>("\tyes "), true);
6276 1 : EXPECT_EQ(cpl::strict_parse<bool>("TRUEE"), std::nullopt);
6277 1 : EXPECT_EQ(cpl::strict_parse<bool>(""), std::nullopt);
6278 :
6279 1 : EXPECT_EQ(cpl::strict_parse<bool>("NO"), false);
6280 1 : EXPECT_EQ(cpl::strict_parse<bool>("0 "), false);
6281 1 : EXPECT_EQ(cpl::strict_parse<bool>(" OFF "), false);
6282 1 : EXPECT_EQ(cpl::strict_parse<bool>("\tno "), false);
6283 1 : EXPECT_EQ(cpl::strict_parse<bool>("NON"), std::nullopt);
6284 :
6285 1 : EXPECT_EQ(cpl::strict_parse<int>("123"), 123);
6286 1 : EXPECT_EQ(cpl::strict_parse<int>("0123"), 123);
6287 1 : EXPECT_EQ(cpl::strict_parse<int>(" -456"), -456);
6288 1 : EXPECT_EQ(cpl::strict_parse<int>(" - 456"), std::nullopt);
6289 1 : EXPECT_EQ(cpl::strict_parse<int>("789."), 789);
6290 1 : EXPECT_EQ(cpl::strict_parse<int>("789.0"), 789);
6291 1 : EXPECT_EQ(cpl::strict_parse<int>("789.0.0"), std::nullopt);
6292 1 : EXPECT_EQ(cpl::strict_parse<int>("789.1"), std::nullopt);
6293 1 : EXPECT_EQ(cpl::strict_parse<int>("789e3"), 789000);
6294 1 : EXPECT_EQ(cpl::strict_parse<int>("789.e3"), 789000);
6295 1 : EXPECT_EQ(cpl::strict_parse<int>("789.0e3"), 789000);
6296 1 : EXPECT_EQ(cpl::strict_parse<int>("789.0e3f"), std::nullopt);
6297 1 : EXPECT_EQ(cpl::strict_parse<int>("789.0e3.2"), std::nullopt);
6298 1 : EXPECT_EQ(cpl::strict_parse<int>("789.0e30"), std::nullopt);
6299 1 : EXPECT_EQ(cpl::strict_parse<int>("50000000000000000"), std::nullopt);
6300 1 : EXPECT_EQ(cpl::strict_parse<int>(""), std::nullopt);
6301 1 : EXPECT_EQ(cpl::strict_parse<int>("123c"), std::nullopt);
6302 1 : EXPECT_EQ(cpl::strict_parse<int>("Q"), std::nullopt);
6303 :
6304 1 : EXPECT_EQ(cpl::strict_parse<double>("3.141569"), 3.141569);
6305 1 : EXPECT_EQ(cpl::strict_parse<double>("3,141569"), std::nullopt);
6306 1 : EXPECT_EQ(cpl::strict_parse<double>("-8.33e-2"), -8.33e-2);
6307 1 : EXPECT_EQ(cpl::strict_parse<double>("06.022e23"), 6.022e23);
6308 1 : EXPECT_EQ(cpl::strict_parse<double>("6.022E23"), 6.022e23);
6309 1 : EXPECT_EQ(cpl::strict_parse<double>("6.022e+23"), 6.022e23);
6310 1 : EXPECT_EQ(cpl::strict_parse<double>("6.022e+23"), 6.022e23);
6311 1 : EXPECT_EQ(cpl::strict_parse<double>(""), std::nullopt);
6312 1 : EXPECT_EQ(cpl::strict_parse<double>(" "), std::nullopt);
6313 1 : EXPECT_EQ(cpl::strict_parse<double>(" -"), std::nullopt);
6314 1 : EXPECT_EQ(cpl::strict_parse<double>("123.2e"), std::nullopt);
6315 1 : EXPECT_EQ(cpl::strict_parse<double>("q"), std::nullopt);
6316 :
6317 1 : EXPECT_EQ(cpl::strict_parse<double>("inf"),
6318 : std::numeric_limits<double>::infinity());
6319 1 : EXPECT_EQ(cpl::strict_parse<double>("-inf"),
6320 : -std::numeric_limits<double>::infinity());
6321 :
6322 1 : EXPECT_EQ(std::isnan(cpl::strict_parse<double>("nan").value()), true);
6323 1 : EXPECT_EQ(std::isnan(cpl::strict_parse<double>("NaN").value()), true);
6324 1 : EXPECT_EQ(std::isnan(cpl::strict_parse<double>("NAN").value()), true);
6325 1 : EXPECT_EQ(cpl::strict_parse<double>("NANA"), std::nullopt);
6326 :
6327 1 : EXPECT_EQ(cpl::strict_parse<float>("3.4e39"), std::nullopt);
6328 1 : EXPECT_EQ(cpl::strict_parse<float>("-3.4e39"), std::nullopt);
6329 1 : EXPECT_EQ(cpl::strict_parse<float>("1e-39"), std::nullopt);
6330 1 : EXPECT_EQ(cpl::strict_parse<float>("-1e-39"), std::nullopt);
6331 1 : }
6332 :
6333 : } // namespace
|