Coverage Report

Created: 2026-09-14 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/port/cplstringlist.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  GDAL
4
 * Purpose:  CPLStringList implementation.
5
 * Author:   Frank Warmerdam, warmerdam@pobox.com
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2011, Frank Warmerdam <warmerdam@pobox.com>
9
 * Copyright (c) 2011, Even Rouault <even dot rouault at spatialys.com>
10
 *
11
 * SPDX-License-Identifier: MIT
12
 ****************************************************************************/
13
14
#include "cpl_port.h"
15
#include "cpl_string.h"
16
17
#include <cstddef>
18
#include <cstdio>
19
#include <cstdlib>
20
#include <cstring>
21
22
#include <algorithm>
23
#include <limits>
24
#include <string>
25
26
#include "cpl_conv.h"
27
#include "cpl_error.h"
28
29
static int CPLCompareKeyValueString(const char *pszKVa, const char *pszKVb);
30
31
/************************************************************************/
32
/*                           CPLStringList()                            */
33
/************************************************************************/
34
35
2.89k
CPLStringList::CPLStringList() = default;
36
37
/************************************************************************/
38
/*                           CPLStringList()                            */
39
/************************************************************************/
40
41
/**
42
 * CPLStringList constructor.
43
 *
44
 * @param papszListIn the NULL terminated list of strings to consume.
45
 * @param bTakeOwnership TRUE if the CPLStringList should take ownership
46
 * of the list of strings which implies responsibility to free them.
47
 */
48
49
CPLStringList::CPLStringList(char **papszListIn, int bTakeOwnership)
50
1.41k
    : CPLStringList()
51
52
1.41k
{
53
1.41k
    Assign(papszListIn, bTakeOwnership);
54
1.41k
}
55
56
/************************************************************************/
57
/*                           CPLStringList()                            */
58
/************************************************************************/
59
60
/**
61
 * CPLStringList constructor.
62
 *
63
 * The input list is copied.
64
 *
65
 * @param papszListIn the NULL terminated list of strings to ingest.
66
 */
67
68
0
CPLStringList::CPLStringList(CSLConstList papszListIn) : CPLStringList()
69
70
0
{
71
0
    Assign(CSLDuplicate(papszListIn));
72
0
}
73
74
/************************************************************************/
75
/*                           CPLStringList()                            */
76
/************************************************************************/
77
78
/**
79
 * CPLStringList constructor.
80
 *
81
 * The input list is copied.
82
 *
83
 * @param aosList input list.
84
 *
85
 * @since GDAL 3.9
86
 */
87
CPLStringList::CPLStringList(const std::vector<std::string> &aosList)
88
0
{
89
0
    if (!aosList.empty())
90
0
    {
91
0
        bOwnList = true;
92
0
        papszList = static_cast<char **>(
93
0
            VSI_CALLOC_VERBOSE(aosList.size() + 1, sizeof(char *)));
94
0
        nCount = static_cast<int>(aosList.size());
95
0
        for (int i = 0; i < nCount; ++i)
96
0
        {
97
0
            papszList[i] = VSI_STRDUP_VERBOSE(aosList[i].c_str());
98
0
        }
99
0
    }
100
0
}
101
102
/************************************************************************/
103
/*                           CPLStringList()                            */
104
/************************************************************************/
105
106
/**
107
 * CPLStringList constructor.
108
 *
109
 * The input list is copied.
110
 *
111
 * @param oInitList input list.
112
 *
113
 * @since GDAL 3.9
114
 */
115
CPLStringList::CPLStringList(std::initializer_list<const char *> oInitList)
116
0
{
117
0
    for (const char *pszStr : oInitList)
118
0
    {
119
0
        AddString(pszStr);
120
0
    }
121
0
}
122
123
/************************************************************************/
124
/*                           CPLStringList()                            */
125
/************************************************************************/
126
127
//! Copy constructor
128
0
CPLStringList::CPLStringList(const CPLStringList &oOther) : CPLStringList()
129
130
0
{
131
0
    operator=(oOther);
132
0
}
133
134
/************************************************************************/
135
/*                           CPLStringList()                            */
136
/************************************************************************/
137
138
//! Move constructor
139
24
CPLStringList::CPLStringList(CPLStringList &&oOther) : CPLStringList()
140
141
24
{
142
24
    operator=(std::move(oOther));
143
24
}
144
145
/************************************************************************/
146
/*                          BoundToConstList()                          */
147
/************************************************************************/
148
149
/**
150
 * Return a CPLStringList that wraps the passed list.
151
 *
152
 * The input list is *NOT* copied and must be kept alive while the
153
 * return CPLStringList is used.
154
 *
155
 * @param papszListIn a NULL terminated list of strings to wrap into the CPLStringList
156
 * @since GDAL 3.9
157
 */
158
159
/* static */
160
const CPLStringList CPLStringList::BoundToConstList(CSLConstList papszListIn)
161
0
{
162
0
    return CPLStringList(const_cast<char **>(papszListIn),
163
0
                         /* bTakeOwnership= */ false);
164
0
}
165
166
/************************************************************************/
167
/*                             operator=()                              */
168
/************************************************************************/
169
170
CPLStringList &CPLStringList::operator=(const CPLStringList &oOther)
171
0
{
172
0
    if (this != &oOther)
173
0
    {
174
0
        char **l_papszList = CSLDuplicate(oOther.papszList);
175
0
        if (l_papszList)
176
0
        {
177
0
            Assign(l_papszList, TRUE);
178
0
            nAllocation = oOther.nCount > 0 ? oOther.nCount + 1 : 0;
179
0
            nCount = oOther.nCount;
180
0
            bIsSorted = oOther.bIsSorted;
181
0
        }
182
0
    }
183
184
0
    return *this;
185
0
}
186
187
/************************************************************************/
188
/*                             operator=()                              */
189
/************************************************************************/
190
191
CPLStringList &CPLStringList::operator=(CPLStringList &&oOther)
192
24
{
193
24
    if (this != &oOther)
194
24
    {
195
24
        Clear();
196
24
        papszList = oOther.papszList;
197
24
        oOther.papszList = nullptr;
198
24
        nCount = oOther.nCount;
199
24
        oOther.nCount = 0;
200
24
        nAllocation = oOther.nAllocation;
201
24
        oOther.nAllocation = 0;
202
24
        bOwnList = oOther.bOwnList;
203
24
        oOther.bOwnList = false;
204
24
        bIsSorted = oOther.bIsSorted;
205
24
        oOther.bIsSorted = true;
206
24
    }
207
208
24
    return *this;
209
24
}
210
211
/************************************************************************/
212
/*                             operator=()                              */
213
/************************************************************************/
214
215
CPLStringList &CPLStringList::operator=(CSLConstList papszListIn)
216
1
{
217
1
    if (papszListIn != papszList)
218
1
    {
219
1
        Assign(CSLDuplicate(papszListIn));
220
1
        bIsSorted = false;
221
1
    }
222
223
1
    return *this;
224
1
}
225
226
/************************************************************************/
227
/*                           ~CPLStringList()                           */
228
/************************************************************************/
229
230
CPLStringList::~CPLStringList()
231
232
2.85k
{
233
2.85k
    Clear();
234
2.85k
}
235
236
/************************************************************************/
237
/*                               Clear()                                */
238
/************************************************************************/
239
240
/**
241
 * Clear the string list.
242
 */
243
CPLStringList &CPLStringList::Clear()
244
245
4.96k
{
246
4.96k
    if (bOwnList)
247
196
    {
248
196
        CSLDestroy(papszList);
249
196
        papszList = nullptr;
250
251
196
        bOwnList = FALSE;
252
196
        nAllocation = 0;
253
196
        nCount = 0;
254
196
    }
255
256
4.96k
    return *this;
257
4.96k
}
258
259
/************************************************************************/
260
/*                               Assign()                               */
261
/************************************************************************/
262
263
/**
264
 * Assign a list of strings.
265
 *
266
 *
267
 * @param papszListIn the NULL terminated list of strings to consume.
268
 * @param bTakeOwnership TRUE if the CPLStringList should take ownership
269
 * of the list of strings which implies responsibility to free them.
270
 *
271
 * @return a reference to the CPLStringList on which it was invoked.
272
 */
273
274
CPLStringList &CPLStringList::Assign(char **papszListIn, int bTakeOwnership)
275
276
2.08k
{
277
2.08k
    Clear();
278
279
2.08k
    papszList = papszListIn;
280
2.08k
    bOwnList = CPL_TO_BOOL(bTakeOwnership);
281
282
2.08k
    if (papszList == nullptr || *papszList == nullptr)
283
951
        nCount = 0;
284
1.13k
    else
285
1.13k
        nCount = -1;  // unknown
286
287
2.08k
    nAllocation = 0;
288
2.08k
    bIsSorted = FALSE;
289
290
2.08k
    return *this;
291
2.08k
}
292
293
/************************************************************************/
294
/*                               Count()                                */
295
/************************************************************************/
296
297
/**
298
 * @return count of strings in the list, zero if empty.
299
 */
300
301
int CPLStringList::Count() const
302
303
16
{
304
16
    if (nCount == -1)
305
1
    {
306
1
        if (papszList == nullptr)
307
0
        {
308
0
            nCount = 0;
309
0
            nAllocation = 0;
310
0
        }
311
1
        else
312
1
        {
313
1
            nCount = CSLCount(papszList);
314
1
            nAllocation = std::max(nCount + 1, nAllocation);
315
1
        }
316
1
    }
317
318
16
    return nCount;
319
16
}
320
321
/************************************************************************/
322
/*                           MakeOurOwnCopy()                           */
323
/*                                                                      */
324
/*      If we don't own the list, a copy is made which we own.          */
325
/*      Necessary if we are going to modify the list.                   */
326
/************************************************************************/
327
328
bool CPLStringList::MakeOurOwnCopy()
329
330
1.17k
{
331
1.17k
    if (bOwnList)
332
188
        return true;
333
334
983
    if (papszList == nullptr)
335
983
        return true;
336
337
0
    Count();
338
0
    char **papszListNew = CSLDuplicate(papszList);
339
0
    if (papszListNew == nullptr)
340
0
    {
341
0
        return false;
342
0
    }
343
0
    papszList = papszListNew;
344
0
    bOwnList = true;
345
0
    nAllocation = nCount + 1;
346
0
    return true;
347
0
}
348
349
/************************************************************************/
350
/*                          EnsureAllocation()                          */
351
/*                                                                      */
352
/*      Ensure we have enough room allocated for at least the           */
353
/*      requested number of strings (so nAllocation will be at least    */
354
/*      one more than the target)                                       */
355
/************************************************************************/
356
357
bool CPLStringList::EnsureAllocation(int nMaxList)
358
359
77.0k
{
360
77.0k
    if (!bOwnList)
361
972
    {
362
972
        if (!MakeOurOwnCopy())
363
0
            return false;
364
972
    }
365
366
77.0k
    if (papszList == nullptr || nAllocation <= nMaxList)
367
1.31k
    {
368
        // we need to be able to store nMaxList+1 as an int,
369
        // and allocate (nMaxList+1) * sizeof(char*) bytes
370
1.31k
        if (nMaxList < 0 || nMaxList > std::numeric_limits<int>::max() - 1 ||
371
1.31k
            static_cast<size_t>(nMaxList) >
372
1.31k
                std::numeric_limits<size_t>::max() / sizeof(char *) - 1)
373
0
        {
374
0
            return false;
375
0
        }
376
1.31k
        int nNewAllocation = nMaxList + 1;
377
1.31k
        if (nNewAllocation <= (std::numeric_limits<int>::max() - 20) / 2 /
378
1.31k
                                  static_cast<int>(sizeof(char *)))
379
1.31k
            nNewAllocation = std::max(nNewAllocation * 2 + 20, nMaxList + 1);
380
1.31k
        if (papszList == nullptr)
381
972
        {
382
972
            papszList = static_cast<char **>(
383
972
                VSI_CALLOC_VERBOSE(nNewAllocation, sizeof(char *)));
384
972
            bOwnList = true;
385
972
            nCount = 0;
386
972
            if (papszList == nullptr)
387
0
                return false;
388
972
        }
389
346
        else
390
346
        {
391
346
            char **papszListNew = static_cast<char **>(VSI_REALLOC_VERBOSE(
392
346
                papszList, nNewAllocation * sizeof(char *)));
393
346
            if (papszListNew == nullptr)
394
0
                return false;
395
346
            papszList = papszListNew;
396
346
        }
397
1.31k
        nAllocation = nNewAllocation;
398
1.31k
    }
399
77.0k
    return true;
400
77.0k
}
401
402
/************************************************************************/
403
/*                         AddStringDirectly()                          */
404
/************************************************************************/
405
406
/**
407
 * Add a string to the list.
408
 *
409
 * This method is similar to AddString(), but ownership of the
410
 * pszNewString is transferred to the CPLStringList class.
411
 *
412
 * @param pszNewString the string to add to the list.
413
 */
414
415
CPLStringList &CPLStringList::AddStringDirectly(char *pszNewString)
416
417
77.0k
{
418
77.0k
    if (nCount == -1)
419
0
        Count();
420
421
77.0k
    if (!EnsureAllocation(nCount + 1))
422
0
    {
423
0
        VSIFree(pszNewString);
424
0
        return *this;
425
0
    }
426
427
77.0k
    papszList[nCount++] = pszNewString;
428
77.0k
    papszList[nCount] = nullptr;
429
430
77.0k
    bIsSorted = false;
431
432
77.0k
    return *this;
433
77.0k
}
434
435
/************************************************************************/
436
/*                             AddString()                              */
437
/************************************************************************/
438
439
/**
440
 * Add a string to the list.
441
 *
442
 * A copy of the passed in string is made and inserted in the list.
443
 *
444
 * @param pszNewString the string to add to the list.
445
 */
446
447
CPLStringList &CPLStringList::AddString(const char *pszNewString)
448
449
12
{
450
12
    char *pszDupString = VSI_STRDUP_VERBOSE(pszNewString);
451
12
    if (pszDupString == nullptr)
452
0
        return *this;
453
12
    return AddStringDirectly(pszDupString);
454
12
}
455
456
/************************************************************************/
457
/*                             AddString()                              */
458
/************************************************************************/
459
/**
460
 * Add a string to the list.
461
 *
462
 * A copy of the passed in string is made and inserted in the list.
463
 *
464
 * @param newString the string to add to the list.
465
 * @return a reference to the CPLStringList on which it was invoked.
466
 */
467
468
CPLStringList &CPLStringList::AddString(const std::string &newString)
469
0
{
470
0
    return AddString(newString.c_str());
471
0
}
472
473
/************************************************************************/
474
/*                             AddString()                              */
475
/************************************************************************/
476
477
/**
478
 * Create a new string from a number and add it to the list.
479
 *
480
 * @param dfNumber the number to convert to a string.
481
 * @return a reference to the CPLStringList on which it was invoked.
482
 */
483
484
CPLStringList &CPLStringList::AddString(double dfNumber)
485
0
{
486
0
    return AddString(CPLSPrintf("%.17g", dfNumber));
487
0
}
488
489
/************************************************************************/
490
/*                             AddString()                              */
491
/************************************************************************/
492
/**
493
 * Add a string to the list.
494
 *
495
 * A copy of the passed in string_view is made and inserted in the list.
496
 *
497
 * @param newString the string to add to the list.
498
 * @return a reference to the CPLStringList on which it was invoked.
499
 */
500
501
CPLStringList &CPLStringList::AddString(std::string_view newString)
502
76.8k
{
503
76.8k
    char *pszDupString =
504
76.8k
        static_cast<char *>(VSI_MALLOC_VERBOSE(newString.size() + 1));
505
76.8k
    if (pszDupString == nullptr)
506
0
    {
507
0
        return *this;
508
0
    }
509
76.8k
    std::memcpy(pszDupString, newString.data(), newString.size());
510
76.8k
    pszDupString[newString.size()] = '\0';
511
512
76.8k
    return AddStringDirectly(pszDupString);
513
76.8k
}
514
515
/************************************************************************/
516
/*                             push_back()                              */
517
/************************************************************************/
518
519
/**
520
 * Add a string to the list.
521
 *
522
 * A copy of the passed in string is made and inserted in the list.
523
 *
524
 * @param svStr the string to add to the list.
525
 *
526
 * @since 3.13
527
 */
528
529
void CPLStringList::push_back(std::string_view svStr)
530
531
0
{
532
0
    char *pszDupString =
533
0
        static_cast<char *>(VSI_MALLOC_VERBOSE(svStr.size() + 1));
534
0
    if (pszDupString == nullptr)
535
0
        return;
536
0
    memcpy(pszDupString, svStr.data(), svStr.size());
537
0
    pszDupString[svStr.size()] = 0;
538
0
    CPL_IGNORE_RET_VAL(AddStringDirectly(pszDupString));
539
0
}
540
541
/************************************************************************/
542
/*                            AddNameValue()                            */
543
/************************************************************************/
544
545
/**
546
 * Add a name=value entry to the list.
547
 *
548
 * A key=value string is prepared and appended to the list.  There is no
549
 * check for other values for the same key in the list.
550
 *
551
 * @param pszKey the key name to add.
552
 * @param pszValue the key value to add.
553
 */
554
555
CPLStringList &CPLStringList::AddNameValue(const char *pszKey,
556
                                           const char *pszValue)
557
558
195
{
559
195
    if (pszKey == nullptr || pszValue == nullptr)
560
0
        return *this;
561
562
195
    if (!MakeOurOwnCopy())
563
0
        return *this;
564
565
    /* -------------------------------------------------------------------- */
566
    /*      Format the line.                                                */
567
    /* -------------------------------------------------------------------- */
568
195
    if (strlen(pszKey) >
569
195
            std::numeric_limits<size_t>::max() - strlen(pszValue) ||
570
195
        strlen(pszKey) + strlen(pszValue) >
571
195
            std::numeric_limits<size_t>::max() - 2)
572
0
    {
573
0
        CPLError(CE_Failure, CPLE_OutOfMemory,
574
0
                 "Too big strings in AddNameValue()");
575
0
        return *this;
576
0
    }
577
195
    const size_t nLen = strlen(pszKey) + strlen(pszValue) + 2;
578
195
    char *pszLine = static_cast<char *>(VSI_MALLOC_VERBOSE(nLen));
579
195
    if (pszLine == nullptr)
580
0
        return *this;
581
195
    snprintf(pszLine, nLen, "%s=%s", pszKey, pszValue);
582
583
    /* -------------------------------------------------------------------- */
584
    /*      If we don't need to keep the sort order things are pretty       */
585
    /*      straight forward.                                               */
586
    /* -------------------------------------------------------------------- */
587
195
    if (!IsSorted())
588
195
        return AddStringDirectly(pszLine);
589
590
    /* -------------------------------------------------------------------- */
591
    /*      Find the proper insertion point.                                */
592
    /* -------------------------------------------------------------------- */
593
0
    CPLAssert(IsSorted());
594
0
    const int iKey = FindSortedInsertionPoint(pszLine);
595
0
    InsertStringDirectly(iKey, pszLine);
596
0
    bIsSorted = true;  // We have actually preserved sort order.
597
598
0
    return *this;
599
0
}
600
601
/************************************************************************/
602
/*                            SetNameValue()                            */
603
/************************************************************************/
604
605
/**
606
 * Set name=value entry in the list.
607
 *
608
 * Similar to AddNameValue(), except if there is already a value for
609
 * the key in the list it is replaced instead of adding a new entry to
610
 * the list.  If pszValue is NULL any existing key entry is removed.
611
 *
612
 * @param pszKey the key name to add.
613
 * @param pszValue the key value to add.
614
 */
615
616
CPLStringList &CPLStringList::SetNameValue(const char *pszKey,
617
                                           const char *pszValue)
618
619
198
{
620
198
    int iKey = FindName(pszKey);
621
622
198
    if (iKey == -1)
623
195
        return AddNameValue(pszKey, pszValue);
624
625
3
    Count();
626
3
    if (!MakeOurOwnCopy())
627
0
        return *this;
628
629
3
    CPLFree(papszList[iKey]);
630
3
    if (pszValue == nullptr)  // delete entry
631
0
    {
632
633
        // shift everything down by one.
634
0
        do
635
0
        {
636
0
            papszList[iKey] = papszList[iKey + 1];
637
0
        } while (papszList[iKey++] != nullptr);
638
639
0
        nCount--;
640
0
    }
641
3
    else
642
3
    {
643
3
        if (strlen(pszKey) >
644
3
                std::numeric_limits<size_t>::max() - strlen(pszValue) ||
645
3
            strlen(pszKey) + strlen(pszValue) >
646
3
                std::numeric_limits<size_t>::max() - 2)
647
0
        {
648
0
            CPLError(CE_Failure, CPLE_OutOfMemory,
649
0
                     "Too big strings in AddNameValue()");
650
0
            return *this;
651
0
        }
652
3
        const size_t nLen = strlen(pszKey) + strlen(pszValue) + 2;
653
3
        char *pszLine = static_cast<char *>(VSI_MALLOC_VERBOSE(nLen));
654
3
        if (pszLine == nullptr)
655
0
            return *this;
656
3
        snprintf(pszLine, nLen, "%s=%s", pszKey, pszValue);
657
658
3
        papszList[iKey] = pszLine;
659
3
    }
660
661
3
    return *this;
662
3
}
663
664
/************************************************************************/
665
/*                             SetString()                              */
666
/************************************************************************/
667
668
/**
669
 * Replace a string within the list.
670
 *
671
 * @param pos 0-index position of the string to replace
672
 * @param pszString value to be used (will be copied)
673
 * @return a reference to the CPLStringList on which it was invoked.
674
 * @since 3.13
675
 */
676
CPLStringList &CPLStringList::SetString(int pos, const char *pszString)
677
0
{
678
0
    return SetStringDirectly(pos, VSI_STRDUP_VERBOSE(pszString));
679
0
}
680
681
/**
682
 * Replace a string within the list.
683
 *
684
 * @param pos 0-index position of the string to replace
685
 * @param osString value to be used (will be copied)
686
 * @return a reference to the CPLStringList on which it was invoked.
687
 * @since 3.13
688
 */
689
CPLStringList &CPLStringList::SetString(int pos, const std::string &osString)
690
0
{
691
0
    return SetString(pos, osString.c_str());
692
0
}
693
694
/**
695
 * Replace a string within the list.
696
 *
697
 * @param pos 0-index position of the string to replace
698
 * @param pszString value to be used (ownership is taken)
699
 * @return a reference to the CPLStringList on which it was invoked.
700
 * @since 3.13
701
 */
702
CPLStringList &CPLStringList::SetStringDirectly(int pos, char *pszString)
703
0
{
704
0
    if (!MakeOurOwnCopy())
705
0
        return *this;
706
707
0
    CPLFree(papszList[pos]);
708
0
    papszList[pos] = pszString;
709
710
0
    if (bIsSorted)
711
0
    {
712
0
        if (pos > 0 &&
713
0
            CPLCompareKeyValueString(papszList[pos], papszList[pos - 1]) == -1)
714
0
        {
715
0
            bIsSorted = false;
716
0
        }
717
0
        if (pos < Count() - 1 &&
718
0
            CPLCompareKeyValueString(papszList[pos], papszList[pos + 1]) == 1)
719
0
        {
720
0
            bIsSorted = false;
721
0
        }
722
0
    }
723
724
0
    return *this;
725
0
}
726
727
/************************************************************************/
728
/*                              operator[]                              */
729
/************************************************************************/
730
731
/**
732
 * Fetch entry "i".
733
 *
734
 * Fetches the requested item in the list.  Note that the returned string
735
 * remains owned by the CPLStringList.  If "i" is out of range NULL is
736
 * returned.
737
 *
738
 * @param i the index of the list item to return.
739
 * @return selected entry in the list.
740
 */
741
char *CPLStringList::operator[](int i)
742
743
0
{
744
0
    if (nCount == -1)
745
0
        Count();
746
747
0
    if (i < 0 || i >= nCount)
748
0
        return nullptr;
749
750
0
    return papszList[i];
751
0
}
752
753
const char *CPLStringList::operator[](int i) const
754
755
0
{
756
0
    if (nCount == -1)
757
0
        Count();
758
759
0
    if (i < 0 || i >= nCount)
760
0
        return nullptr;
761
762
0
    return papszList[i];
763
0
}
764
765
/************************************************************************/
766
/*                             StealList()                              */
767
/************************************************************************/
768
769
/**
770
 * Seize ownership of underlying string array.
771
 *
772
 * This method is similar to List(), except that the returned list is
773
 * now owned by the caller and the CPLStringList is emptied.
774
 *
775
 * @return the C style string list.
776
 */
777
char **CPLStringList::StealList()
778
779
2.83k
{
780
2.83k
    char **papszRetList = papszList;
781
782
2.83k
    bOwnList = false;
783
2.83k
    papszList = nullptr;
784
2.83k
    nCount = 0;
785
2.83k
    nAllocation = 0;
786
787
2.83k
    return papszRetList;
788
2.83k
}
789
790
/* Case insensitive comparison function */
791
static int CPLCompareKeyValueString(const char *pszKVa, const char *pszKVb)
792
187
{
793
187
    const char *pszItera = pszKVa;
794
187
    const char *pszIterb = pszKVb;
795
1.08k
    while (true)
796
1.08k
    {
797
1.08k
        char cha = *pszItera;
798
1.08k
        char chb = *pszIterb;
799
1.08k
        if (cha == '=' || cha == '\0')
800
2
        {
801
2
            if (chb == '=' || chb == '\0')
802
0
                return 0;
803
2
            else
804
2
                return -1;
805
2
        }
806
1.08k
        if (chb == '=' || chb == '\0')
807
2
        {
808
2
            return 1;
809
2
        }
810
1.08k
        if (cha >= 'a' && cha <= 'z')
811
0
            cha -= ('a' - 'A');
812
1.08k
        if (chb >= 'a' && chb <= 'z')
813
0
            chb -= ('a' - 'A');
814
1.08k
        if (cha < chb)
815
113
            return -1;
816
972
        else if (cha > chb)
817
70
            return 1;
818
902
        pszItera++;
819
902
        pszIterb++;
820
902
    }
821
187
}
822
823
/************************************************************************/
824
/*                                Sort()                                */
825
/************************************************************************/
826
827
/**
828
 * Sort the entries in the list and mark list sorted.
829
 *
830
 * Note that once put into "sorted" mode, the CPLStringList will attempt to
831
 * keep things in sorted order through calls to AddString(),
832
 * AddStringDirectly(), AddNameValue(), SetNameValue(). Complete list
833
 * assignments (via Assign() and operator= will clear the sorting state.
834
 * When in sorted order FindName(), FetchNameValue() and FetchNameValueDef()
835
 * will do a binary search to find the key, substantially improve lookup
836
 * performance in large lists.
837
 */
838
839
CPLStringList &CPLStringList::Sort()
840
841
1
{
842
1
    Count();
843
1
    if (!MakeOurOwnCopy())
844
0
        return *this;
845
846
1
    if (nCount > 1)
847
1
    {
848
1
        std::sort(papszList, papszList + nCount,
849
1
                  [](const char *a, const char *b)
850
187
                  { return CPLCompareKeyValueString(a, b) < 0; });
851
1
    }
852
1
    bIsSorted = true;
853
854
1
    return *this;
855
1
}
856
857
/************************************************************************/
858
/*                              FindName()                              */
859
/************************************************************************/
860
861
/**
862
 * Get index of given name/value keyword.
863
 *
864
 * Note that this search is for a line in the form name=value or name:value.
865
 * Use FindString() or PartialFindString() for searches not based on name=value
866
 * pairs.
867
 *
868
 * @param pszKey the name to search for.
869
 *
870
 * @return the string list index of this name, or -1 on failure.
871
 */
872
873
int CPLStringList::FindName(const char *pszKey) const
874
875
11.8k
{
876
11.8k
    if (!IsSorted())
877
11.8k
        return CSLFindName(papszList, pszKey);
878
879
    // If we are sorted, we can do an optimized binary search.
880
0
    int iStart = 0;
881
0
    int iEnd = nCount - 1;
882
0
    size_t nKeyLen = strlen(pszKey);
883
884
0
    while (iStart <= iEnd)
885
0
    {
886
0
        const int iMiddle = (iEnd + iStart) / 2;
887
0
        const char *pszMiddle = papszList[iMiddle];
888
889
0
        if (EQUALN(pszMiddle, pszKey, nKeyLen) &&
890
0
            (pszMiddle[nKeyLen] == '=' || pszMiddle[nKeyLen] == ':'))
891
0
            return iMiddle;
892
893
0
        if (CPLCompareKeyValueString(pszKey, pszMiddle) < 0)
894
0
            iEnd = iMiddle - 1;
895
0
        else
896
0
            iStart = iMiddle + 1;
897
0
    }
898
899
0
    return -1;
900
0
}
901
902
/************************************************************************/
903
/*                             FetchBool()                              */
904
/************************************************************************/
905
/**
906
 *
907
 * Check for boolean key value.
908
 *
909
 * In a CPLStringList of "Name=Value" pairs, look to see if there is a key
910
 * with the given name, and if it can be interpreted as being TRUE.  If
911
 * the key appears without any "=Value" portion it will be considered true.
912
 * If the value is NO, FALSE or 0 it will be considered FALSE otherwise
913
 * if the key appears in the list it will be considered TRUE.  If the key
914
 * doesn't appear at all, the indicated default value will be returned.
915
 *
916
 * @param pszKey the key value to look for (case insensitive).
917
 * @param bDefault the value to return if the key isn't found at all.
918
 *
919
 * @return true or false
920
 */
921
922
bool CPLStringList::FetchBool(const char *pszKey, bool bDefault) const
923
924
0
{
925
0
    const char *pszValue = FetchNameValue(pszKey);
926
927
0
    if (pszValue == nullptr)
928
0
        return bDefault;
929
930
0
    return CPLTestBool(pszValue);
931
0
}
932
933
/************************************************************************/
934
/*                            FetchBoolean()                            */
935
/************************************************************************/
936
/**
937
 *
938
 * DEPRECATED: Check for boolean key value.
939
 *
940
 * In a CPLStringList of "Name=Value" pairs, look to see if there is a key
941
 * with the given name, and if it can be interpreted as being TRUE.  If
942
 * the key appears without any "=Value" portion it will be considered true.
943
 * If the value is NO, FALSE or 0 it will be considered FALSE otherwise
944
 * if the key appears in the list it will be considered TRUE.  If the key
945
 * doesn't appear at all, the indicated default value will be returned.
946
 *
947
 * @param pszKey the key value to look for (case insensitive).
948
 * @param bDefault the value to return if the key isn't found at all.
949
 *
950
 * @return TRUE or FALSE
951
 */
952
953
int CPLStringList::FetchBoolean(const char *pszKey, int bDefault) const
954
955
0
{
956
0
    return FetchBool(pszKey, CPL_TO_BOOL(bDefault)) ? TRUE : FALSE;
957
0
}
958
959
/************************************************************************/
960
/*                           FetchNameValue()                           */
961
/************************************************************************/
962
963
/**
964
 * Fetch value associated with this key name.
965
 *
966
 * If this list sorted, a fast binary search is done, otherwise a linear
967
 * scan is done.  Name lookup is case insensitive.
968
 *
969
 * @param pszName the key name to search for.
970
 *
971
 * @return the corresponding value or NULL if not found.  The returned string
972
 * should not be modified and points into internal object state that may
973
 * change on future calls.
974
 */
975
976
const char *CPLStringList::FetchNameValue(const char *pszName) const
977
978
11.6k
{
979
11.6k
    const int iKey = FindName(pszName);
980
981
11.6k
    if (iKey == -1)
982
20
        return nullptr;
983
984
11.6k
    CPLAssert(papszList[iKey][strlen(pszName)] == '=' ||
985
11.6k
              papszList[iKey][strlen(pszName)] == ':');
986
987
11.6k
    return papszList[iKey] + strlen(pszName) + 1;
988
11.6k
}
989
990
/************************************************************************/
991
/*                         FetchNameValueDef()                          */
992
/************************************************************************/
993
994
/**
995
 * Fetch value associated with this key name.
996
 *
997
 * If this list sorted, a fast binary search is done, otherwise a linear
998
 * scan is done.  Name lookup is case insensitive.
999
 *
1000
 * @param pszName the key name to search for.
1001
 * @param pszDefault the default value returned if the named entry isn't found.
1002
 *
1003
 * @return the corresponding value or the passed default if not found.
1004
 */
1005
1006
const char *CPLStringList::FetchNameValueDef(const char *pszName,
1007
                                             const char *pszDefault) const
1008
1009
0
{
1010
0
    const char *pszValue = FetchNameValue(pszName);
1011
0
    if (pszValue == nullptr)
1012
0
        return pszDefault;
1013
1014
0
    return pszValue;
1015
0
}
1016
1017
/************************************************************************/
1018
/*                            InsertString()                            */
1019
/************************************************************************/
1020
1021
/**
1022
 * \fn CPLStringList *CPLStringList::InsertString( int nInsertAtLineNo,
1023
 *                                                 const char *pszNewLine );
1024
 *
1025
 * \brief Insert into the list at identified location.
1026
 *
1027
 * This method will insert a string into the list at the identified
1028
 * location.  The insertion point must be within or at the end of the list.
1029
 * The following entries are pushed down to make space.
1030
 *
1031
 * @param nInsertAtLineNo the line to insert at, zero to insert at front.
1032
 * @param pszNewLine to the line to insert.  This string will be copied.
1033
 */
1034
1035
/************************************************************************/
1036
/*                        InsertStringDirectly()                        */
1037
/************************************************************************/
1038
1039
/**
1040
 * Insert into the list at identified location.
1041
 *
1042
 * This method will insert a string into the list at the identified
1043
 * location.  The insertion point must be within or at the end of the list.
1044
 * The following entries are pushed down to make space.
1045
 *
1046
 * @param nInsertAtLineNo the line to insert at, zero to insert at front.
1047
 * @param pszNewLine to the line to insert, the ownership of this string
1048
 * will be taken over the by the object.  It must have been allocated on the
1049
 * heap.
1050
 */
1051
1052
CPLStringList &CPLStringList::InsertStringDirectly(int nInsertAtLineNo,
1053
                                                   char *pszNewLine)
1054
1055
0
{
1056
0
    if (nCount == -1)
1057
0
        Count();
1058
1059
0
    if (!EnsureAllocation(nCount + 1))
1060
0
    {
1061
0
        VSIFree(pszNewLine);
1062
0
        return *this;
1063
0
    }
1064
1065
0
    if (nInsertAtLineNo < 0 || nInsertAtLineNo > nCount)
1066
0
    {
1067
0
        CPLError(CE_Failure, CPLE_AppDefined,
1068
0
                 "CPLStringList::InsertString() requested beyond list end.");
1069
0
        return *this;
1070
0
    }
1071
1072
0
    bIsSorted = false;
1073
1074
0
    for (int i = nCount; i > nInsertAtLineNo; i--)
1075
0
        papszList[i] = papszList[i - 1];
1076
1077
0
    papszList[nInsertAtLineNo] = pszNewLine;
1078
0
    papszList[++nCount] = nullptr;
1079
1080
0
    return *this;
1081
0
}
1082
1083
/************************************************************************/
1084
/*                           RemoveStrings()                            */
1085
/************************************************************************/
1086
1087
/**
1088
 * Remove strings inside a CPLStringList.
1089
 *
1090
 * @param nFirstLineToDelete the 0-based index of the first string to
1091
 * remove. If this value is -1 or is larger than the actual
1092
 * number of strings in list then the nNumToRemove last strings are
1093
 * removed.
1094
 * @param nNumToRemove the number of strings to remove
1095
 *
1096
 * @return a reference to the CPLStringList on which it was invoked.
1097
 * @since 3.13
1098
 */
1099
CPLStringList &CPLStringList::RemoveStrings(int nFirstLineToDelete,
1100
                                            int nNumToRemove)
1101
0
{
1102
0
    if (!MakeOurOwnCopy())
1103
0
        return *this;
1104
1105
0
    papszList =
1106
0
        CSLRemoveStrings(papszList, nFirstLineToDelete, nNumToRemove, nullptr);
1107
0
    nCount = -1;
1108
0
    return *this;
1109
0
}
1110
1111
/************************************************************************/
1112
/*                      FindSortedInsertionPoint()                      */
1113
/*                                                                      */
1114
/*      Find the location at which the indicated line should be         */
1115
/*      inserted in order to keep things in sorted order.               */
1116
/************************************************************************/
1117
1118
int CPLStringList::FindSortedInsertionPoint(const char *pszLine)
1119
1120
0
{
1121
0
    CPLAssert(IsSorted());
1122
1123
0
    int iStart = 0;
1124
0
    int iEnd = nCount - 1;
1125
1126
0
    while (iStart <= iEnd)
1127
0
    {
1128
0
        const int iMiddle = (iEnd + iStart) / 2;
1129
0
        const char *pszMiddle = papszList[iMiddle];
1130
1131
0
        if (CPLCompareKeyValueString(pszLine, pszMiddle) < 0)
1132
0
            iEnd = iMiddle - 1;
1133
0
        else
1134
0
            iStart = iMiddle + 1;
1135
0
    }
1136
1137
0
    iEnd++;
1138
0
    CPLAssert(iEnd >= 0 && iEnd <= nCount);
1139
0
    CPLAssert(iEnd == 0 ||
1140
0
              CPLCompareKeyValueString(pszLine, papszList[iEnd - 1]) >= 0);
1141
0
    CPLAssert(iEnd == nCount ||
1142
0
              CPLCompareKeyValueString(pszLine, papszList[iEnd]) <= 0);
1143
1144
0
    return iEnd;
1145
0
}
1146
1147
namespace cpl
1148
{
1149
1150
/************************************************************************/
1151
/*          CSLIterator::operator==(const CSLIterator &other)           */
1152
/************************************************************************/
1153
1154
/*! @cond Doxygen_Suppress */
1155
bool CSLIterator::operator==(const CSLIterator &other) const
1156
0
{
1157
0
    if (!m_bAtEnd && other.m_bAtEnd)
1158
0
    {
1159
0
        return m_papszList == nullptr || *m_papszList == nullptr;
1160
0
    }
1161
0
    if (!m_bAtEnd && !other.m_bAtEnd)
1162
0
    {
1163
0
        return m_papszList == other.m_papszList;
1164
0
    }
1165
0
    if (m_bAtEnd && other.m_bAtEnd)
1166
0
    {
1167
0
        return true;
1168
0
    }
1169
0
    return false;
1170
0
}
1171
1172
/*! @endcond */
1173
1174
/************************************************************************/
1175
/*                  CSLNameValueIterator::operator*()                   */
1176
/************************************************************************/
1177
1178
/*! @cond Doxygen_Suppress */
1179
CSLNameValueIterator::value_type CSLNameValueIterator::operator*()
1180
0
{
1181
0
    if (m_papszList)
1182
0
    {
1183
0
        while (*m_papszList)
1184
0
        {
1185
0
            char *pszKey = nullptr;
1186
0
            const char *pszValue = CPLParseNameValue(*m_papszList, &pszKey);
1187
0
            if (pszKey)
1188
0
            {
1189
0
                m_osKey = pszKey;
1190
0
                CPLFree(pszKey);
1191
0
                return {m_osKey.c_str(), pszValue};
1192
0
            }
1193
0
            else if (m_bReturnNullKeyIfNotNameValue)
1194
0
            {
1195
0
                return {nullptr, *m_papszList};
1196
0
            }
1197
            // Skip entries that are not name=value pairs.
1198
0
            ++m_papszList;
1199
0
        }
1200
0
    }
1201
    // Should not happen
1202
0
    CPLAssert(false);
1203
0
    return {"", ""};
1204
0
}
1205
1206
/*! @endcond */
1207
1208
/************************************************************************/
1209
/*                  CSLNameValueIteratorWrapper::end()                  */
1210
/************************************************************************/
1211
1212
/*! @cond Doxygen_Suppress */
1213
CSLNameValueIterator CSLNameValueIteratorWrapper::end() const
1214
0
{
1215
0
    int nCount = CSLCount(m_papszList);
1216
0
    if (!m_bReturnNullKeyIfNotNameValue)
1217
0
    {
1218
0
        while (nCount > 0 && strchr(m_papszList[nCount - 1], '=') == nullptr)
1219
0
            --nCount;
1220
0
    }
1221
0
    return CSLNameValueIterator{m_papszList + nCount,
1222
0
                                m_bReturnNullKeyIfNotNameValue};
1223
0
}
1224
1225
/*! @endcond */
1226
1227
}  // namespace cpl