Coverage Report

Created: 2026-02-14 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/port/cpl_string.h
Line
Count
Source
1
/**********************************************************************
2
 *
3
 * Name:     cpl_string.h
4
 * Project:  CPL - Common Portability Library
5
 * Purpose:  String and StringList functions.
6
 * Author:   Daniel Morissette, dmorissette@mapgears.com
7
 *
8
 **********************************************************************
9
 * Copyright (c) 1998, Daniel Morissette
10
 * Copyright (c) 2008-2014, Even Rouault <even dot rouault at spatialys.com>
11
 *
12
 * SPDX-License-Identifier: MIT
13
 ****************************************************************************/
14
15
#ifndef CPL_STRING_H_INCLUDED
16
#define CPL_STRING_H_INCLUDED
17
18
#include "cpl_error.h"
19
#include "cpl_conv.h"
20
#include "cpl_vsi.h"
21
22
#include <stdbool.h>
23
24
/**
25
 * \file cpl_string.h
26
 *
27
 * Various convenience functions for working with strings and string lists.
28
 *
29
 * A StringList is just an array of strings with the last pointer being
30
 * NULL.  An empty StringList may be either a NULL pointer, or a pointer to
31
 * a pointer memory location with a NULL value.
32
 *
33
 * A common convention for StringLists is to use them to store name/value
34
 * lists.  In this case the contents are treated like a dictionary of
35
 * name/value pairs.  The actual data is formatted with each string having
36
 * the format "<name>:<value>" (though "=" is also an acceptable separator).
37
 * A number of the functions in the file operate on name/value style
38
 * string lists (such as CSLSetNameValue(), and CSLFetchNameValue()).
39
 *
40
 * To some extent the CPLStringList C++ class can be used to abstract
41
 * managing string lists a bit but still be able to return them from C
42
 * functions.
43
 *
44
 */
45
46
CPL_C_START
47
48
char CPL_DLL **CSLAddString(char **papszStrList,
49
                            const char *pszNewString) CPL_WARN_UNUSED_RESULT;
50
char CPL_DLL **
51
CSLAddStringMayFail(char **papszStrList,
52
                    const char *pszNewString) CPL_WARN_UNUSED_RESULT;
53
int CPL_DLL CSLCount(CSLConstList papszStrList);
54
const char CPL_DLL *CSLGetField(CSLConstList, int);
55
void CPL_DLL CPL_STDCALL CSLDestroy(char **papszStrList);
56
char CPL_DLL **CSLDuplicate(CSLConstList papszStrList) CPL_WARN_UNUSED_RESULT;
57
char CPL_DLL **CSLMerge(char **papszOrig,
58
                        CSLConstList papszOverride) CPL_WARN_UNUSED_RESULT;
59
60
char CPL_DLL **CSLTokenizeString(const char *pszString) CPL_WARN_UNUSED_RESULT;
61
char CPL_DLL **
62
CSLTokenizeStringComplex(const char *pszString, const char *pszDelimiter,
63
                         int bHonourStrings,
64
                         int bAllowEmptyTokens) CPL_WARN_UNUSED_RESULT;
65
char CPL_DLL **CSLTokenizeString2(const char *pszString,
66
                                  const char *pszDelimiter,
67
                                  int nCSLTFlags) CPL_WARN_UNUSED_RESULT;
68
69
/** Flag for CSLTokenizeString2() to honour strings */
70
11.4k
#define CSLT_HONOURSTRINGS 0x0001
71
/** Flag for CSLTokenizeString2() to allow empty tokens */
72
11.4k
#define CSLT_ALLOWEMPTYTOKENS 0x0002
73
/** Flag for CSLTokenizeString2() to preserve quotes */
74
0
#define CSLT_PRESERVEQUOTES 0x0004
75
/** Flag for CSLTokenizeString2() to preserve escape characters */
76
0
#define CSLT_PRESERVEESCAPES 0x0008
77
/** Flag for CSLTokenizeString2() to strip leading spaces */
78
11.4k
#define CSLT_STRIPLEADSPACES 0x0010
79
/** Flag for CSLTokenizeString2() to strip trailing spaces */
80
11.4k
#define CSLT_STRIPENDSPACES 0x0020
81
82
int CPL_DLL CSLPrint(CSLConstList papszStrList, FILE *fpOut);
83
char CPL_DLL **CSLLoad(const char *pszFname) CPL_WARN_UNUSED_RESULT;
84
char CPL_DLL **CSLLoad2(const char *pszFname, int nMaxLines, int nMaxCols,
85
                        CSLConstList papszOptions) CPL_WARN_UNUSED_RESULT;
86
int CPL_DLL CSLSave(CSLConstList papszStrList, const char *pszFname);
87
88
char CPL_DLL **
89
CSLInsertStrings(char **papszStrList, int nInsertAtLineNo,
90
                 CSLConstList papszNewLines) CPL_WARN_UNUSED_RESULT;
91
char CPL_DLL **CSLInsertString(char **papszStrList, int nInsertAtLineNo,
92
                               const char *pszNewLine) CPL_WARN_UNUSED_RESULT;
93
char CPL_DLL **
94
CSLRemoveStrings(char **papszStrList, int nFirstLineToDelete, int nNumToRemove,
95
                 char ***ppapszRetStrings) CPL_WARN_UNUSED_RESULT;
96
int CPL_DLL CSLFindString(CSLConstList papszList, const char *pszTarget);
97
int CPL_DLL CSLFindStringCaseSensitive(CSLConstList papszList,
98
                                       const char *pszTarget);
99
int CPL_DLL CSLPartialFindString(CSLConstList papszHaystack,
100
                                 const char *pszNeedle);
101
int CPL_DLL CSLFindName(CSLConstList papszStrList, const char *pszName);
102
int CPL_DLL CSLFetchBoolean(CSLConstList papszStrList, const char *pszKey,
103
                            int bDefault);
104
105
/* TODO: Deprecate CSLTestBoolean.  Remove in GDAL 3.x. */
106
int CPL_DLL CSLTestBoolean(const char *pszValue);
107
/* Do not use CPLTestBoolean in C++ code.  Use CPLTestBool. */
108
int CPL_DLL CPLTestBoolean(const char *pszValue);
109
110
bool CPL_DLL CPLTestBool(const char *pszValue);
111
bool CPL_DLL CPLFetchBool(CSLConstList papszStrList, const char *pszKey,
112
                          bool bDefault);
113
#ifdef __cplusplus
114
CPL_C_END
115
116
/*! @cond Doxygen_Suppress */
117
inline bool CPLFetchBool(CSLConstList papszStrList, const char *pszKey,
118
                         int bDefault)
119
0
{
120
0
    return CPLFetchBool(papszStrList, pszKey, bDefault != 0);
121
0
}
122
123
bool CPLFetchBool(CSLConstList papszStrList, const char *pszKey,
124
                  const char *) = delete;
125
126
/*! @endcond */
127
CPL_C_START
128
#endif
129
CPLErr CPL_DLL CPLParseMemorySize(const char *pszValue, GIntBig *pnValue,
130
                                  bool *pbUnitSpecified);
131
132
const char CPL_DLL *CPLParseNameValue(const char *pszNameValue, char **ppszKey);
133
const char CPL_DLL *CPLParseNameValueSep(const char *pszNameValue,
134
                                         char **ppszKey, char chSep);
135
136
const char CPL_DLL *CSLFetchNameValue(CSLConstList papszStrList,
137
                                      const char *pszName);
138
const char CPL_DLL *CSLFetchNameValueDef(CSLConstList papszStrList,
139
                                         const char *pszName,
140
                                         const char *pszDefault);
141
char CPL_DLL **CSLFetchNameValueMultiple(CSLConstList papszStrList,
142
                                         const char *pszName);
143
char CPL_DLL **CSLAddNameValue(char **papszStrList, const char *pszName,
144
                               const char *pszValue) CPL_WARN_UNUSED_RESULT;
145
char CPL_DLL **CSLSetNameValue(char **papszStrList, const char *pszName,
146
                               const char *pszValue) CPL_WARN_UNUSED_RESULT;
147
void CPL_DLL CSLSetNameValueSeparator(char **papszStrList,
148
                                      const char *pszSeparator);
149
150
char CPL_DLL **CSLParseCommandLine(const char *pszCommandLine);
151
152
/** Scheme for CPLEscapeString()/CPLUnescapeString() for backlash quoting */
153
33.3k
#define CPLES_BackslashQuotable 0
154
/** Scheme for CPLEscapeString()/CPLUnescapeString() for XML */
155
66.6k
#define CPLES_XML 1
156
/** Scheme for CPLEscapeString()/CPLUnescapeString() for URL */
157
66.6k
#define CPLES_URL 2
158
/** Scheme for CPLEscapeString()/CPLUnescapeString() for SQL */
159
0
#define CPLES_SQL 3
160
/** Scheme for CPLEscapeString()/CPLUnescapeString() for CSV */
161
0
#define CPLES_CSV 4
162
/** Scheme for CPLEscapeString()/CPLUnescapeString() for XML (preserves quotes)
163
 */
164
33.3k
#define CPLES_XML_BUT_QUOTES 5
165
/** Scheme for CPLEscapeString()/CPLUnescapeString() for CSV (forced quoting) */
166
0
#define CPLES_CSV_FORCE_QUOTING 6
167
/** Scheme for CPLEscapeString()/CPLUnescapeString() for SQL identifiers */
168
0
#define CPLES_SQLI 7
169
170
char CPL_DLL *CPLEscapeString(const char *pszString, int nLength,
171
                              int nScheme) CPL_WARN_UNUSED_RESULT;
172
char CPL_DLL *CPLUnescapeString(const char *pszString, int *pnLength,
173
                                int nScheme) CPL_WARN_UNUSED_RESULT;
174
175
char CPL_DLL *CPLBinaryToHex(int nBytes,
176
                             const GByte *pabyData) CPL_WARN_UNUSED_RESULT;
177
GByte CPL_DLL *CPLHexToBinary(const char *pszHex,
178
                              int *pnBytes) CPL_WARN_UNUSED_RESULT;
179
180
char CPL_DLL *CPLBase64Encode(int nBytes,
181
                              const GByte *pabyData) CPL_WARN_UNUSED_RESULT;
182
int CPL_DLL CPLBase64DecodeInPlace(GByte *pszBase64) CPL_WARN_UNUSED_RESULT;
183
184
/** Type of value */
185
typedef enum
186
{
187
    CPL_VALUE_STRING, /**< String */
188
    CPL_VALUE_REAL,   /**< Real number */
189
    CPL_VALUE_INTEGER /**< Integer */
190
} CPLValueType;
191
192
CPLValueType CPL_DLL CPLGetValueType(const char *pszValue);
193
194
int CPL_DLL CPLToupper(int c);
195
int CPL_DLL CPLTolower(int c);
196
197
size_t CPL_DLL CPLStrlcpy(char *pszDest, const char *pszSrc, size_t nDestSize);
198
size_t CPL_DLL CPLStrlcat(char *pszDest, const char *pszSrc, size_t nDestSize);
199
size_t CPL_DLL CPLStrnlen(const char *pszStr, size_t nMaxLen);
200
201
/* -------------------------------------------------------------------- */
202
/*      Locale independent formatting functions.                        */
203
/* -------------------------------------------------------------------- */
204
int CPL_DLL CPLvsnprintf(char *str, size_t size,
205
                         CPL_FORMAT_STRING(const char *fmt), va_list args)
206
    CPL_PRINT_FUNC_FORMAT(3, 0);
207
208
/* ALIAS_CPLSNPRINTF_AS_SNPRINTF might be defined to enable GCC 7 */
209
/* -Wformat-truncation= warnings, but shouldn't be set for normal use */
210
#if defined(ALIAS_CPLSNPRINTF_AS_SNPRINTF)
211
#define CPLsnprintf snprintf
212
#else
213
int CPL_DLL CPLsnprintf(char *str, size_t size,
214
                        CPL_FORMAT_STRING(const char *fmt), ...)
215
    CPL_PRINT_FUNC_FORMAT(3, 4);
216
#endif
217
218
/*! @cond Doxygen_Suppress */
219
#if defined(GDAL_COMPILATION) && !defined(DONT_DEPRECATE_SPRINTF)
220
int CPL_DLL CPLsprintf(char *str, CPL_FORMAT_STRING(const char *fmt), ...)
221
    CPL_PRINT_FUNC_FORMAT(2, 3) CPL_WARN_DEPRECATED("Use CPLsnprintf instead");
222
#else
223
int CPL_DLL CPLsprintf(char *str, CPL_FORMAT_STRING(const char *fmt), ...)
224
    CPL_PRINT_FUNC_FORMAT(2, 3);
225
#endif
226
/*! @endcond */
227
int CPL_DLL CPLprintf(CPL_FORMAT_STRING(const char *fmt), ...)
228
    CPL_PRINT_FUNC_FORMAT(1, 2);
229
230
/* For some reason Doxygen_Suppress is needed to avoid warning. Not sure why */
231
/*! @cond Doxygen_Suppress */
232
/* caution: only works with limited number of formats */
233
int CPL_DLL CPLsscanf(const char *str, CPL_SCANF_FORMAT_STRING(const char *fmt),
234
                      ...) CPL_SCAN_FUNC_FORMAT(2, 3);
235
/*! @endcond */
236
237
const char CPL_DLL *CPLSPrintf(CPL_FORMAT_STRING(const char *fmt), ...)
238
    CPL_PRINT_FUNC_FORMAT(1, 2) CPL_WARN_UNUSED_RESULT;
239
char CPL_DLL **CSLAppendPrintf(char **papszStrList,
240
                               CPL_FORMAT_STRING(const char *fmt), ...)
241
    CPL_PRINT_FUNC_FORMAT(2, 3) CPL_WARN_UNUSED_RESULT;
242
int CPL_DLL CPLVASPrintf(char **buf, CPL_FORMAT_STRING(const char *fmt),
243
                         va_list args) CPL_PRINT_FUNC_FORMAT(2, 0);
244
245
/* -------------------------------------------------------------------- */
246
/*      RFC 23 character set conversion/recoding API (cpl_recode.cpp).  */
247
/* -------------------------------------------------------------------- */
248
/** Encoding of the current locale */
249
#define CPL_ENC_LOCALE ""
250
/** UTF-8 encoding */
251
0
#define CPL_ENC_UTF8 "UTF-8"
252
/** UTF-16 encoding */
253
0
#define CPL_ENC_UTF16 "UTF-16"
254
/** UCS-2 encoding */
255
0
#define CPL_ENC_UCS2 "UCS-2"
256
/** UCS-4 encoding */
257
0
#define CPL_ENC_UCS4 "UCS-4"
258
/** ASCII encoding */
259
0
#define CPL_ENC_ASCII "ASCII"
260
/** ISO-8859-1 (LATIN1) encoding */
261
0
#define CPL_ENC_ISO8859_1 "ISO-8859-1"
262
263
int CPL_DLL CPLEncodingCharSize(const char *pszEncoding);
264
/*! @cond Doxygen_Suppress */
265
void CPL_DLL CPLClearRecodeWarningFlags(void);
266
/*! @endcond */
267
char CPL_DLL *CPLRecode(const char *pszSource, const char *pszSrcEncoding,
268
                        const char *pszDstEncoding)
269
    CPL_WARN_UNUSED_RESULT CPL_RETURNS_NONNULL;
270
char CPL_DLL *
271
CPLRecodeFromWChar(const wchar_t *pwszSource, const char *pszSrcEncoding,
272
                   const char *pszDstEncoding) CPL_WARN_UNUSED_RESULT;
273
wchar_t CPL_DLL *
274
CPLRecodeToWChar(const char *pszSource, const char *pszSrcEncoding,
275
                 const char *pszDstEncoding) CPL_WARN_UNUSED_RESULT;
276
int CPL_DLL CPLIsUTF8(const char *pabyData, int nLen);
277
bool CPL_DLL CPLIsASCII(const char *pabyData, size_t nLen);
278
char CPL_DLL *CPLForceToASCII(const char *pabyData, int nLen,
279
                              char chReplacementChar) CPL_WARN_UNUSED_RESULT;
280
char CPL_DLL *CPLUTF8ForceToASCII(const char *pszStr, char chReplacementChar)
281
    CPL_WARN_UNUSED_RESULT;
282
int CPL_DLL CPLStrlenUTF8(const char *pszUTF8Str)
283
    /*! @cond Doxygen_Suppress */
284
    CPL_WARN_DEPRECATED("Use CPLStrlenUTF8Ex() instead")
285
    /*! @endcond */
286
    ;
287
size_t CPL_DLL CPLStrlenUTF8Ex(const char *pszUTF8Str);
288
int CPL_DLL CPLCanRecode(const char *pszTestStr, const char *pszSrcEncoding,
289
                         const char *pszDstEncoding) CPL_WARN_UNUSED_RESULT;
290
CPL_C_END
291
292
#if defined(__cplusplus) && !defined(CPL_SUPRESS_CPLUSPLUS)
293
294
extern "C++"
295
{
296
    std::string CPL_DLL CPLRemoveSQLComments(const std::string &osInput);
297
}
298
299
#endif
300
301
/************************************************************************/
302
/*                              CPLString                               */
303
/************************************************************************/
304
305
#if defined(__cplusplus) && !defined(CPL_SUPRESS_CPLUSPLUS)
306
307
extern "C++"
308
{
309
#ifndef DOXYGEN_SKIP
310
#include <string>
311
#include <vector>
312
#endif
313
314
// VC++ implicitly applies __declspec(dllexport) to template base classes
315
// of classes marked with __declspec(dllexport).
316
// Hence, if marked with CPL_DLL, VC++ would export symbols for the
317
// specialization of std::basic_string<char>, since it is a base class of
318
// CPLString. As a result, if an application linked both gdal.dll and a static
319
// library that (implicitly) instantiates std::string (almost all do!), then the
320
// linker would emit an error concerning duplicate symbols for std::string. The
321
// least intrusive solution is to not mark the whole class with
322
// __declspec(dllexport) for VC++, but only its non-inline methods.
323
#ifdef _MSC_VER
324
#define CPLSTRING_CLASS_DLL
325
#define CPLSTRING_METHOD_DLL CPL_DLL
326
#else
327
/*! @cond Doxygen_Suppress */
328
#define CPLSTRING_CLASS_DLL CPL_DLL
329
#define CPLSTRING_METHOD_DLL
330
/*! @endcond */
331
#endif
332
333
    //! Convenient string class based on std::string.
334
    class CPLSTRING_CLASS_DLL CPLString : public std::string
335
    {
336
      public:
337
        /** Constructor */
338
        CPLString(void)
339
34.2k
        {
340
34.2k
        }
341
342
        /** Constructor */
343
        // cppcheck-suppress noExplicitConstructor
344
28.9k
        CPLString(const std::string &oStr) : std::string(oStr)
345
28.9k
        {
346
28.9k
        }
347
348
        /** Constructor */
349
        // cppcheck-suppress noExplicitConstructor
350
87.7k
        CPLString(const char *pszStr) : std::string(pszStr)
351
87.7k
        {
352
87.7k
        }
353
354
        /** Constructor */
355
0
        CPLString(const char *pszStr, size_t n) : std::string(pszStr, n)
356
0
        {
357
0
        }
358
359
        /** Return string as zero terminated character array */
360
        operator const char *(void) const
361
16.7k
        {
362
16.7k
            return c_str();
363
16.7k
        }
364
365
        /** Return character at specified index */
366
        char &operator[](std::string::size_type i)
367
355k
        {
368
355k
            return std::string::operator[](i);
369
355k
        }
370
371
        /** Return character at specified index */
372
        const char &operator[](std::string::size_type i) const
373
0
        {
374
0
            return std::string::operator[](i);
375
0
        }
376
377
        /** Return character at specified index */
378
        char &operator[](int i)
379
0
        {
380
0
            return std::string::operator[](
381
0
                static_cast<std::string::size_type>(i));
382
0
        }
383
384
        /** Return character at specified index */
385
        const char &operator[](int i) const
386
0
        {
387
0
            return std::string::operator[](
388
0
                static_cast<std::string::size_type>(i));
389
0
        }
390
391
        /** Clear the string */
392
        void Clear()
393
0
        {
394
0
            resize(0);
395
0
        }
396
397
        /** Assign specified string and take ownership of it (assumed to be
398
         * allocated with CPLMalloc()). NULL can be safely passed to clear the
399
         * string. */
400
        void Seize(char *pszValue)
401
0
        {
402
0
            if (pszValue == nullptr)
403
0
                Clear();
404
0
            else
405
0
            {
406
0
                *this = pszValue;
407
0
                CPLFree(pszValue);
408
0
            }
409
0
        }
410
411
        /* There seems to be a bug in the way the compiler count indices...
412
         * Should be CPL_PRINT_FUNC_FORMAT (1, 2) */
413
        CPLSTRING_METHOD_DLL CPLString &
414
        Printf(CPL_FORMAT_STRING(const char *pszFormat), ...)
415
            CPL_PRINT_FUNC_FORMAT(2, 3);
416
        CPLSTRING_METHOD_DLL CPLString &
417
        vPrintf(CPL_FORMAT_STRING(const char *pszFormat), va_list args)
418
            CPL_PRINT_FUNC_FORMAT(2, 0);
419
        CPLSTRING_METHOD_DLL CPLString &
420
        FormatC(double dfValue, const char *pszFormat = nullptr);
421
        CPLSTRING_METHOD_DLL CPLString &Trim();
422
        CPLSTRING_METHOD_DLL CPLString &Recode(const char *pszSrcEncoding,
423
                                               const char *pszDstEncoding);
424
        CPLSTRING_METHOD_DLL CPLString &replaceAll(const std::string &osBefore,
425
                                                   const std::string &osAfter);
426
        CPLSTRING_METHOD_DLL CPLString &replaceAll(const std::string &osBefore,
427
                                                   char chAfter);
428
        CPLSTRING_METHOD_DLL CPLString &replaceAll(char chBefore,
429
                                                   const std::string &osAfter);
430
        CPLSTRING_METHOD_DLL CPLString &replaceAll(char chBefore, char chAfter);
431
432
        /* case insensitive find alternates */
433
        CPLSTRING_METHOD_DLL size_t ifind(const std::string &str,
434
                                          size_t pos = 0) const;
435
        CPLSTRING_METHOD_DLL size_t ifind(const char *s, size_t pos = 0) const;
436
        CPLSTRING_METHOD_DLL CPLString &toupper(void);
437
        CPLSTRING_METHOD_DLL CPLString &tolower(void);
438
439
        CPLSTRING_METHOD_DLL bool endsWith(const std::string &osStr) const;
440
441
        CPLSTRING_METHOD_DLL CPLString URLEncode() const;
442
443
        CPLSTRING_METHOD_DLL CPLString SQLQuotedIdentifier() const;
444
445
        CPLSTRING_METHOD_DLL CPLString SQLQuotedLiteral() const;
446
447
      private:
448
        operator void *(void) = delete;
449
    };
450
451
#undef CPLSTRING_CLASS_DLL
452
#undef CPLSTRING_METHOD_DLL
453
454
    CPLString CPL_DLL CPLOPrintf(CPL_FORMAT_STRING(const char *pszFormat), ...)
455
        CPL_PRINT_FUNC_FORMAT(1, 2);
456
    CPLString CPL_DLL CPLOvPrintf(CPL_FORMAT_STRING(const char *pszFormat),
457
                                  va_list args) CPL_PRINT_FUNC_FORMAT(1, 0);
458
    CPLString CPL_DLL CPLQuotedSQLIdentifier(const char *pszIdent);
459
460
    /* -------------------------------------------------------------------- */
461
    /*      URL processing functions, here since they depend on CPLString.  */
462
    /* -------------------------------------------------------------------- */
463
    CPLString CPL_DLL CPLURLGetValue(const char *pszURL, const char *pszKey);
464
    CPLString CPL_DLL CPLURLAddKVP(const char *pszURL, const char *pszKey,
465
                                   const char *pszValue);
466
467
    /************************************************************************/
468
    /*                            CPLStringList                             */
469
    /************************************************************************/
470
471
    //! String list class designed around our use of C "char**" string lists.
472
    class CPL_DLL CPLStringList
473
    {
474
        char **papszList = nullptr;
475
        mutable int nCount = 0;
476
        mutable int nAllocation = 0;
477
        bool bOwnList = false;
478
        bool bIsSorted = false;
479
480
        bool MakeOurOwnCopy();
481
        bool EnsureAllocation(int nMaxLength);
482
        int FindSortedInsertionPoint(const char *pszLine);
483
484
      public:
485
        CPLStringList();
486
        explicit CPLStringList(char **papszList, int bTakeOwnership = TRUE);
487
        explicit CPLStringList(CSLConstList papszList);
488
        explicit CPLStringList(const std::vector<std::string> &aosList);
489
        explicit CPLStringList(std::initializer_list<const char *> oInitList);
490
        CPLStringList(const CPLStringList &oOther);
491
        CPLStringList(CPLStringList &&oOther);
492
        ~CPLStringList();
493
494
        static const CPLStringList BoundToConstList(CSLConstList papszList);
495
496
        CPLStringList &Clear();
497
498
        /** Clear the list */
499
        inline void clear()
500
0
        {
501
0
            Clear();
502
0
        }
503
504
        /** Return size of list */
505
        int size() const
506
30.0k
        {
507
30.0k
            return Count();
508
30.0k
        }
509
510
        int Count() const;
511
512
        /** Return whether the list is empty. */
513
        bool empty() const
514
0
        {
515
0
            return Count() == 0;
516
0
        }
517
518
        CPLStringList &AddString(const char *pszNewString);
519
        CPLStringList &AddString(const std::string &newString);
520
        CPLStringList &AddStringDirectly(char *pszNewString);
521
522
        /** Add a string to the list */
523
        void push_back(const char *pszNewString)
524
0
        {
525
0
            AddString(pszNewString);
526
0
        }
527
528
        /** Add a string to the list */
529
        void push_back(const std::string &osStr)
530
0
        {
531
0
            AddString(osStr.c_str());
532
0
        }
533
534
        CPLStringList &InsertString(int nInsertAtLineNo, const char *pszNewLine)
535
0
        {
536
0
            return InsertStringDirectly(nInsertAtLineNo, CPLStrdup(pszNewLine));
537
0
        }
538
539
        CPLStringList &InsertStringDirectly(int nInsertAtLineNo,
540
                                            char *pszNewLine);
541
542
        // CPLStringList &InsertStrings( int nInsertAtLineNo, char
543
        // **papszNewLines );
544
545
        CPLStringList &RemoveStrings(int nFirstLineToDelete,
546
                                     int nNumToRemove = 1);
547
548
        /** Return index of pszTarget in the list, or -1 */
549
        int FindString(const char *pszTarget) const
550
0
        {
551
0
            return CSLFindString(papszList, pszTarget);
552
0
        }
553
554
        /** Return index of pszTarget in the list (using partial search), or -1
555
         */
556
        int PartialFindString(const char *pszNeedle) const
557
0
        {
558
0
            return CSLPartialFindString(papszList, pszNeedle);
559
0
        }
560
561
        int FindName(const char *pszName) const;
562
        bool FetchBool(const char *pszKey, bool bDefault) const;
563
        // Deprecated.
564
        int FetchBoolean(const char *pszKey, int bDefault) const;
565
        const char *FetchNameValue(const char *pszKey) const;
566
        const char *FetchNameValueDef(const char *pszKey,
567
                                      const char *pszDefault) const;
568
        CPLStringList &AddNameValue(const char *pszKey, const char *pszValue);
569
        CPLStringList &SetNameValue(const char *pszKey, const char *pszValue);
570
571
        CPLStringList &SetString(int pos, const char *pszString);
572
        CPLStringList &SetString(int pos, const std::string &osString);
573
        CPLStringList &SetStringDirectly(int pos, char *pszString);
574
575
        CPLStringList &Assign(char **papszListIn, int bTakeOwnership = TRUE);
576
577
        /** Assignment operator */
578
        CPLStringList &operator=(char **papszListIn)
579
0
        {
580
0
            return Assign(papszListIn, TRUE);
581
0
        }
582
583
        /** Assignment operator */
584
        CPLStringList &operator=(const CPLStringList &oOther);
585
        /** Assignment operator */
586
        CPLStringList &operator=(CSLConstList papszListIn);
587
        /** Move assignment operator */
588
        CPLStringList &operator=(CPLStringList &&oOther);
589
590
        /** Return string at specified index */
591
        char *operator[](int i);
592
593
        /** Return string at specified index */
594
        char *operator[](size_t i)
595
0
        {
596
0
            return (*this)[static_cast<int>(i)];
597
0
        }
598
599
        /** Return string at specified index */
600
        const char *operator[](int i) const;
601
602
        /** Return string at specified index */
603
        const char *operator[](size_t i) const
604
0
        {
605
0
            return (*this)[static_cast<int>(i)];
606
0
        }
607
608
        /** Return value corresponding to pszKey, or nullptr */
609
        const char *operator[](const char *pszKey) const
610
0
        {
611
0
            return FetchNameValue(pszKey);
612
0
        }
613
614
        /** Return first element */
615
        inline const char *front() const
616
0
        {
617
0
            return papszList[0];
618
0
        }
619
620
        /** Return last element */
621
        inline const char *back() const
622
0
        {
623
0
            return papszList[size() - 1];
624
0
        }
625
626
        /** begin() implementation */
627
        const char *const *begin() const
628
0
        {
629
0
            return papszList ? &papszList[0] : nullptr;
630
0
        }
631
632
        /** end() implementation */
633
        const char *const *end() const
634
0
        {
635
0
            return papszList ? &papszList[size()] : nullptr;
636
0
        }
637
638
        /** Return list. Ownership remains to the object */
639
        char **List()
640
11.4k
        {
641
11.4k
            return papszList;
642
11.4k
        }
643
644
        /** Return list. Ownership remains to the object */
645
        CSLConstList List() const
646
0
        {
647
0
            return papszList;
648
0
        }
649
650
        char **StealList();
651
652
        CPLStringList &Sort();
653
654
        /** Returns whether the list is sorted */
655
        int IsSorted() const
656
0
        {
657
0
            return bIsSorted;
658
0
        }
659
660
        /** Return lists */
661
        operator char **(void)
662
0
        {
663
0
            return List();
664
0
        }
665
666
        /** Return lists */
667
        operator CSLConstList(void) const
668
0
        {
669
0
            return List();
670
0
        }
671
672
        /** Return the list as a vector of strings */
673
        operator std::vector<std::string>(void) const
674
0
        {
675
0
            return std::vector<std::string>{begin(), end()};
676
0
        }
677
678
      private:
679
        operator void *(void) = delete;
680
    };
681
682
#ifdef GDAL_COMPILATION
683
684
#include <iterator>  // For std::input_iterator_tag
685
#include <memory>
686
#include <string_view>
687
#include <utility>  // For std::pair
688
689
    /*! @cond Doxygen_Suppress */
690
    struct CPL_DLL CSLDestroyReleaser
691
    {
692
        void operator()(char **papszStr) const
693
0
        {
694
0
            CSLDestroy(papszStr);
695
0
        }
696
    };
697
698
    /*! @endcond */
699
700
    /** Unique pointer type to use with CSL functions returning a char** */
701
    using CSLUniquePtr = std::unique_ptr<char *, CSLDestroyReleaser>;
702
703
    /** Unique pointer type to use with functions returning a char* to release
704
     * with VSIFree */
705
    using CPLCharUniquePtr = std::unique_ptr<char, VSIFreeReleaser>;
706
707
    namespace cpl
708
    {
709
710
    /*! @cond Doxygen_Suppress */
711
712
    /** Equivalent of C++20 std::string::starts_with(const char*) */
713
    template <class StringType>
714
    inline bool starts_with(const StringType &str, const char *prefix)
715
5.08k
    {
716
5.08k
        const size_t prefixLen = strlen(prefix);
717
5.08k
        return str.size() >= prefixLen &&
718
0
               str.compare(0, prefixLen, prefix, prefixLen) == 0;
719
5.08k
    }
720
721
    /** Equivalent of C++20 std::string::starts_with(const std::string &) */
722
    template <class StringType>
723
    inline bool starts_with(const StringType &str, const std::string &prefix)
724
0
    {
725
0
        return str.size() >= prefix.size() &&
726
0
               str.compare(0, prefix.size(), prefix) == 0;
727
0
    }
728
729
    /** Equivalent of C++20 std::string::starts_with(std::string_view) */
730
    template <class StringType>
731
    inline bool starts_with(const StringType &str, std::string_view prefix)
732
    {
733
        return str.size() >= prefix.size() &&
734
               str.compare(0, prefix.size(), prefix) == 0;
735
    }
736
737
    /** Equivalent of C++20 std::string::ends_with(const char*) */
738
    template <class StringType>
739
    inline bool ends_with(const StringType &str, const char *suffix)
740
0
    {
741
0
        const size_t suffixLen = strlen(suffix);
742
0
        return str.size() >= suffixLen &&
743
0
               str.compare(str.size() - suffixLen, suffixLen, suffix,
744
0
                           suffixLen) == 0;
745
0
    }
Unexecuted instantiation: bool cpl::ends_with<std::__1::basic_string_view<char, std::__1::char_traits<char> > >(std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, char const*)
Unexecuted instantiation: bool cpl::ends_with<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, char const*)
746
747
    /** Equivalent of C++20 std::string::ends_with(const std::string &) */
748
    template <class StringType>
749
    inline bool ends_with(const StringType &str, const std::string &suffix)
750
0
    {
751
0
        return str.size() >= suffix.size() &&
752
0
               str.compare(str.size() - suffix.size(), suffix.size(), suffix) ==
753
0
                   0;
754
0
    }
755
756
    /** Equivalent of C++20 std::string::ends_with(std::string_view) */
757
    template <class StringType>
758
    inline bool ends_with(const StringType &str, std::string_view suffix)
759
    {
760
        return str.size() >= suffix.size() &&
761
               str.compare(str.size() - suffix.size(), suffix.size(), suffix) ==
762
                   0;
763
    }
764
765
    /** Iterator for a CSLConstList */
766
    struct CPL_DLL CSLIterator
767
    {
768
        using iterator_category = std::input_iterator_tag;
769
        using difference_type = std::ptrdiff_t;
770
        using value_type = const char *;
771
        using pointer = value_type *;
772
        using reference = value_type &;
773
774
        CSLConstList m_papszList = nullptr;
775
        bool m_bAtEnd = false;
776
777
        inline const char *operator*() const
778
0
        {
779
0
            return *m_papszList;
780
0
        }
781
782
        inline CSLIterator &operator++()
783
0
        {
784
0
            if (m_papszList)
785
0
                ++m_papszList;
786
0
            return *this;
787
0
        }
788
789
        bool operator==(const CSLIterator &other) const;
790
791
        inline bool operator!=(const CSLIterator &other) const
792
0
        {
793
0
            return !(operator==(other));
794
0
        }
795
    };
796
797
    /*! @endcond */
798
799
    /** Wrapper for a CSLConstList that can be used with C++ iterators.
800
     *
801
     * @since GDAL 3.9
802
     */
803
    struct CPL_DLL CSLIteratorWrapper
804
    {
805
      public:
806
        /** Constructor */
807
        inline explicit CSLIteratorWrapper(CSLConstList papszList)
808
0
            : m_papszList(papszList)
809
0
        {
810
0
        }
811
812
        /** Get the begin of the list */
813
        inline CSLIterator begin() const
814
0
        {
815
0
            return {m_papszList, false};
816
0
        }
817
818
        /** Get the end of the list */
819
        inline CSLIterator end() const
820
0
        {
821
0
            return {m_papszList, true};
822
0
        }
823
824
      private:
825
        CSLConstList m_papszList;
826
    };
827
828
    /** Wraps a CSLConstList in a structure that can be used with C++ iterators.
829
     *
830
     * @since GDAL 3.9
831
     */
832
    inline CSLIteratorWrapper Iterate(CSLConstList papszList)
833
0
    {
834
0
        return CSLIteratorWrapper{papszList};
835
0
    }
836
837
    /*! @cond Doxygen_Suppress */
838
    inline CSLIteratorWrapper Iterate(const CPLStringList &aosList)
839
0
    {
840
0
        return Iterate(aosList.List());
841
0
    }
842
843
    /*! @endcond */
844
845
    /*! @cond Doxygen_Suppress */
846
    inline CSLIteratorWrapper Iterate(char **) = delete;
847
848
    /*! @endcond */
849
850
    /*! @cond Doxygen_Suppress */
851
    /** Iterator for a CSLConstList as (name, value) pairs. */
852
    struct CPL_DLL CSLNameValueIterator
853
    {
854
        using iterator_category = std::input_iterator_tag;
855
        using difference_type = std::ptrdiff_t;
856
        using value_type = std::pair<const char *, const char *>;
857
        using pointer = value_type *;
858
        using reference = value_type &;
859
860
        CSLConstList m_papszList = nullptr;
861
        bool m_bReturnNullKeyIfNotNameValue = false;
862
        std::string m_osKey{};
863
864
        value_type operator*();
865
866
        inline CSLNameValueIterator &operator++()
867
0
        {
868
0
            if (m_papszList)
869
0
                ++m_papszList;
870
0
            return *this;
871
0
        }
872
873
        inline bool operator==(const CSLNameValueIterator &other) const
874
0
        {
875
0
            return m_papszList == other.m_papszList;
876
0
        }
877
878
        inline bool operator!=(const CSLNameValueIterator &other) const
879
0
        {
880
0
            return !(operator==(other));
881
0
        }
882
    };
883
884
    /*! @endcond */
885
886
    /** Wrapper for a CSLConstList that can be used with C++ iterators
887
     * to get (name, value) pairs.
888
     *
889
     * This can for example be used to do the following:
890
     * for (const auto& [name, value]: cpl::IterateNameValue(papszList)) {}
891
     *
892
     * Note that a (name, value) pair returned by dereferencing an iterator
893
     * is invalidated by the next iteration on the iterator.
894
     *
895
     * @since GDAL 3.9
896
     */
897
    struct CPL_DLL CSLNameValueIteratorWrapper
898
    {
899
      public:
900
        /** Constructor */
901
        inline explicit CSLNameValueIteratorWrapper(
902
            CSLConstList papszList, bool bReturnNullKeyIfNotNameValue)
903
0
            : m_papszList(papszList),
904
0
              m_bReturnNullKeyIfNotNameValue(bReturnNullKeyIfNotNameValue)
905
0
        {
906
0
        }
907
908
        /** Get the begin of the list */
909
        inline CSLNameValueIterator begin() const
910
0
        {
911
0
            return {m_papszList, m_bReturnNullKeyIfNotNameValue};
912
0
        }
913
914
        /** Get the end of the list */
915
        CSLNameValueIterator end() const;
916
917
      private:
918
        CSLConstList m_papszList;
919
        const bool m_bReturnNullKeyIfNotNameValue;
920
    };
921
922
    /** Wraps a CSLConstList in a structure that can be used with C++ iterators
923
     * to get (name, value) pairs.
924
     *
925
     * This can for example be used to do the following:
926
     * for (const auto& [name, value]: cpl::IterateNameValue(papszList)) {}
927
     *
928
     * Note that a (name, value) pair returned by dereferencing an iterator
929
     * is invalidated by the next iteration on the iterator.
930
     *
931
     * @param papszList List to iterate over.
932
     * @param bReturnNullKeyIfNotNameValue When this is set to true, if a string
933
     * contained in the list if not of the form name=value, then the value of
934
     * the iterator will be (nullptr, string).
935
     *
936
     * @since GDAL 3.9
937
     */
938
    inline CSLNameValueIteratorWrapper
939
    IterateNameValue(CSLConstList papszList,
940
                     bool bReturnNullKeyIfNotNameValue = false)
941
0
    {
942
0
        return CSLNameValueIteratorWrapper{papszList,
943
0
                                           bReturnNullKeyIfNotNameValue};
944
0
    }
945
946
    /*! @cond Doxygen_Suppress */
947
    inline CSLNameValueIteratorWrapper
948
    IterateNameValue(const CPLStringList &aosList,
949
                     bool bReturnNullKeyIfNotNameValue = false)
950
0
    {
951
0
        return IterateNameValue(aosList.List(), bReturnNullKeyIfNotNameValue);
952
0
    }
953
954
    /*! @endcond */
955
956
    /*! @cond Doxygen_Suppress */
957
    inline CSLIteratorWrapper IterateNameValue(char **, bool = false) = delete;
958
959
    /*! @endcond */
960
961
    /** Converts a CSLConstList to a std::vector<std::string> */
962
    inline std::vector<std::string> ToVector(CSLConstList papszList)
963
0
    {
964
0
        return CPLStringList::BoundToConstList(papszList);
965
0
    }
966
967
    inline std::vector<std::string> ToVector(char **) = delete;
968
969
    }  // namespace cpl
970
971
#endif
972
973
}  // extern "C++"
974
975
#endif /* def __cplusplus && !CPL_SUPRESS_CPLUSPLUS */
976
977
#endif /* CPL_STRING_H_INCLUDED */