Coverage Report

Created: 2025-08-28 06:57

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