forked from OSGeo/gdal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpl_conv.cpp
3486 lines (2998 loc) · 114 KB
/
cpl_conv.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: CPL - Common Portability Library
* Purpose: Convenience functions.
* Author: Frank Warmerdam, [email protected]
*
******************************************************************************
* Copyright (c) 1998, Frank Warmerdam
* Copyright (c) 2007-2014, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_config.h"
#ifdef HAVE_USELOCALE
// For uselocale, define _XOPEN_SOURCE = 700
// but on Solaris, we don't have uselocale and we cannot have
// std=c++11 with _XOPEN_SOURCE != 600
#if defined(__sun__) && __cplusplus >= 201103L
#if _XOPEN_SOURCE != 600
#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif
#define _XOPEN_SOURCE 600
#endif
#else
#ifdef _XOPEN_SOURCE
#undef _XOPEN_SOURCE
#endif
#define _XOPEN_SOURCE 700
#endif
#endif
// For atoll (at least for NetBSD)
#define _ISOC99_SOURCE
#ifdef MSVC_USE_VLD
#include <vld.h>
#endif
#include "cpl_conv.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <climits>
#include <clocale>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_XLOCALE_H
#include <xlocale.h> // for LC_NUMERIC_MASK on MacOS
#endif
#ifdef DEBUG_CONFIG_OPTIONS
#include <set>
#endif
#include <string>
#include "cpl_config.h"
#include "cpl_multiproc.h"
#include "cpl_string.h"
#include "cpl_vsi.h"
#include "cpl_vsil_curl_priv.h"
#ifdef DEBUG
#define OGRAPISPY_ENABLED
#endif
#ifdef OGRAPISPY_ENABLED
// Keep in sync with ograpispy.cpp
void OGRAPISPYCPLSetConfigOption(const char *, const char *);
void OGRAPISPYCPLSetThreadLocalConfigOption(const char *, const char *);
#endif
// Uncomment to get list of options that have been fetched and set.
// #define DEBUG_CONFIG_OPTIONS
static CPLMutex *hConfigMutex = nullptr;
static volatile char **g_papszConfigOptions = nullptr;
static bool gbIgnoreEnvVariables =
false; // if true, only take into account configuration options set through
// configuration file or
// CPLSetConfigOption()/CPLSetThreadLocalConfigOption()
static std::vector<std::pair<CPLSetConfigOptionSubscriber, void *>>
gSetConfigOptionSubscribers{};
// Used by CPLOpenShared() and friends.
static CPLMutex *hSharedFileMutex = nullptr;
static int nSharedFileCount = 0;
static CPLSharedFileInfo *pasSharedFileList = nullptr;
// Used by CPLsetlocale().
static CPLMutex *hSetLocaleMutex = nullptr;
// Note: ideally this should be added in CPLSharedFileInfo*
// but CPLSharedFileInfo is exposed in the API, hence that trick
// to hide this detail.
typedef struct
{
GIntBig nPID; // pid of opening thread.
} CPLSharedFileInfoExtra;
static volatile CPLSharedFileInfoExtra *pasSharedFileListExtra = nullptr;
/************************************************************************/
/* CPLCalloc() */
/************************************************************************/
/**
* Safe version of calloc().
*
* This function is like the C library calloc(), but raises a CE_Fatal
* error with CPLError() if it fails to allocate the desired memory. It
* should be used for small memory allocations that are unlikely to fail
* and for which the application is unwilling to test for out of memory
* conditions. It uses VSICalloc() to get the memory, so any hooking of
* VSICalloc() will apply to CPLCalloc() as well. CPLFree() or VSIFree()
* can be used free memory allocated by CPLCalloc().
*
* @param nCount number of objects to allocate.
* @param nSize size (in bytes) of object to allocate.
* @return pointer to newly allocated memory, only NULL if nSize * nCount is
* NULL.
*/
void *CPLCalloc(size_t nCount, size_t nSize)
{
if (nSize * nCount == 0)
return nullptr;
void *pReturn = CPLMalloc(nCount * nSize);
memset(pReturn, 0, nCount * nSize);
return pReturn;
}
/************************************************************************/
/* CPLMalloc() */
/************************************************************************/
/**
* Safe version of malloc().
*
* This function is like the C library malloc(), but raises a CE_Fatal
* error with CPLError() if it fails to allocate the desired memory. It
* should be used for small memory allocations that are unlikely to fail
* and for which the application is unwilling to test for out of memory
* conditions. It uses VSIMalloc() to get the memory, so any hooking of
* VSIMalloc() will apply to CPLMalloc() as well. CPLFree() or VSIFree()
* can be used free memory allocated by CPLMalloc().
*
* @param nSize size (in bytes) of memory block to allocate.
* @return pointer to newly allocated memory, only NULL if nSize is zero.
*/
void *CPLMalloc(size_t nSize)
{
if (nSize == 0)
return nullptr;
CPLVerifyConfiguration();
if ((nSize >> (8 * sizeof(nSize) - 1)) != 0)
{
// coverity[dead_error_begin]
CPLError(CE_Failure, CPLE_AppDefined,
"CPLMalloc(%ld): Silly size requested.",
static_cast<long>(nSize));
return nullptr;
}
void *pReturn = VSIMalloc(nSize);
if (pReturn == nullptr)
{
if (nSize < 2000)
{
CPLEmergencyError("CPLMalloc(): Out of memory allocating a small "
"number of bytes.");
}
CPLError(CE_Fatal, CPLE_OutOfMemory,
"CPLMalloc(): Out of memory allocating %ld bytes.",
static_cast<long>(nSize));
}
return pReturn;
}
/************************************************************************/
/* CPLRealloc() */
/************************************************************************/
/**
* Safe version of realloc().
*
* This function is like the C library realloc(), but raises a CE_Fatal
* error with CPLError() if it fails to allocate the desired memory. It
* should be used for small memory allocations that are unlikely to fail
* and for which the application is unwilling to test for out of memory
* conditions. It uses VSIRealloc() to get the memory, so any hooking of
* VSIRealloc() will apply to CPLRealloc() as well. CPLFree() or VSIFree()
* can be used free memory allocated by CPLRealloc().
*
* It is also safe to pass NULL in as the existing memory block for
* CPLRealloc(), in which case it uses VSIMalloc() to allocate a new block.
*
* @param pData existing memory block which should be copied to the new block.
* @param nNewSize new size (in bytes) of memory block to allocate.
* @return pointer to allocated memory, only NULL if nNewSize is zero.
*/
void *CPLRealloc(void *pData, size_t nNewSize)
{
if (nNewSize == 0)
{
VSIFree(pData);
return nullptr;
}
if ((nNewSize >> (8 * sizeof(nNewSize) - 1)) != 0)
{
// coverity[dead_error_begin]
CPLError(CE_Failure, CPLE_AppDefined,
"CPLRealloc(%ld): Silly size requested.",
static_cast<long>(nNewSize));
return nullptr;
}
void *pReturn = nullptr;
if (pData == nullptr)
pReturn = VSIMalloc(nNewSize);
else
pReturn = VSIRealloc(pData, nNewSize);
if (pReturn == nullptr)
{
if (nNewSize < 2000)
{
char szSmallMsg[80] = {};
snprintf(szSmallMsg, sizeof(szSmallMsg),
"CPLRealloc(): Out of memory allocating %ld bytes.",
static_cast<long>(nNewSize));
CPLEmergencyError(szSmallMsg);
}
else
{
CPLError(CE_Fatal, CPLE_OutOfMemory,
"CPLRealloc(): Out of memory allocating %ld bytes.",
static_cast<long>(nNewSize));
}
}
return pReturn;
}
/************************************************************************/
/* CPLStrdup() */
/************************************************************************/
/**
* Safe version of strdup() function.
*
* This function is similar to the C library strdup() function, but if
* the memory allocation fails it will issue a CE_Fatal error with
* CPLError() instead of returning NULL. Memory
* allocated with CPLStrdup() can be freed with CPLFree() or VSIFree().
*
* It is also safe to pass a NULL string into CPLStrdup(). CPLStrdup()
* will allocate and return a zero length string (as opposed to a NULL
* string).
*
* @param pszString input string to be duplicated. May be NULL.
* @return pointer to a newly allocated copy of the string. Free with
* CPLFree() or VSIFree().
*/
char *CPLStrdup(const char *pszString)
{
if (pszString == nullptr)
pszString = "";
const size_t nLen = strlen(pszString);
char *pszReturn = static_cast<char *>(CPLMalloc(nLen + 1));
memcpy(pszReturn, pszString, nLen + 1);
return (pszReturn);
}
/************************************************************************/
/* CPLStrlwr() */
/************************************************************************/
/**
* Convert each characters of the string to lower case.
*
* For example, "ABcdE" will be converted to "abcde".
* This function is locale dependent.
*
* @param pszString input string to be converted.
* @return pointer to the same string, pszString.
*/
char *CPLStrlwr(char *pszString)
{
if (pszString == nullptr)
return nullptr;
char *pszTemp = pszString;
while (*pszTemp)
{
*pszTemp = static_cast<char>(tolower(*pszTemp));
pszTemp++;
}
return pszString;
}
/************************************************************************/
/* CPLFGets() */
/* */
/* Note: LF = \n = ASCII 10 */
/* CR = \r = ASCII 13 */
/************************************************************************/
// ASCII characters.
constexpr char knLF = 10;
constexpr char knCR = 13;
/**
* Reads in at most one less than nBufferSize characters from the fp
* stream and stores them into the buffer pointed to by pszBuffer.
* Reading stops after an EOF or a newline. If a newline is read, it
* is _not_ stored into the buffer. A '\\0' is stored after the last
* character in the buffer. All three types of newline terminators
* recognized by the CPLFGets(): single '\\r' and '\\n' and '\\r\\n'
* combination.
*
* @param pszBuffer pointer to the targeting character buffer.
* @param nBufferSize maximum size of the string to read (not including
* terminating '\\0').
* @param fp file pointer to read from.
* @return pointer to the pszBuffer containing a string read
* from the file or NULL if the error or end of file was encountered.
*/
char *CPLFGets(char *pszBuffer, int nBufferSize, FILE *fp)
{
if (nBufferSize == 0 || pszBuffer == nullptr || fp == nullptr)
return nullptr;
/* -------------------------------------------------------------------- */
/* Let the OS level call read what it things is one line. This */
/* will include the newline. On windows, if the file happens */
/* to be in text mode, the CRLF will have been converted to */
/* just the newline (LF). If it is in binary mode it may well */
/* have both. */
/* -------------------------------------------------------------------- */
const long nOriginalOffset = VSIFTell(fp);
if (VSIFGets(pszBuffer, nBufferSize, fp) == nullptr)
return nullptr;
int nActuallyRead = static_cast<int>(strlen(pszBuffer));
if (nActuallyRead == 0)
return nullptr;
/* -------------------------------------------------------------------- */
/* If we found \r and out buffer is full, it is possible there */
/* is also a pending \n. Check for it. */
/* -------------------------------------------------------------------- */
if (nBufferSize == nActuallyRead + 1 &&
pszBuffer[nActuallyRead - 1] == knCR)
{
const int chCheck = fgetc(fp);
if (chCheck != knLF)
{
// unget the character.
if (VSIFSeek(fp, nOriginalOffset + nActuallyRead, SEEK_SET) == -1)
{
CPLError(CE_Failure, CPLE_FileIO,
"Unable to unget a character");
}
}
}
/* -------------------------------------------------------------------- */
/* Trim off \n, \r or \r\n if it appears at the end. We don't */
/* need to do any "seeking" since we want the newline eaten. */
/* -------------------------------------------------------------------- */
if (nActuallyRead > 1 && pszBuffer[nActuallyRead - 1] == knLF &&
pszBuffer[nActuallyRead - 2] == knCR)
{
pszBuffer[nActuallyRead - 2] = '\0';
}
else if (pszBuffer[nActuallyRead - 1] == knLF ||
pszBuffer[nActuallyRead - 1] == knCR)
{
pszBuffer[nActuallyRead - 1] = '\0';
}
/* -------------------------------------------------------------------- */
/* Search within the string for a \r (MacOS convention */
/* apparently), and if we find it we need to trim the string, */
/* and seek back. */
/* -------------------------------------------------------------------- */
char *pszExtraNewline = strchr(pszBuffer, knCR);
if (pszExtraNewline != nullptr)
{
nActuallyRead = static_cast<int>(pszExtraNewline - pszBuffer + 1);
*pszExtraNewline = '\0';
if (VSIFSeek(fp, nOriginalOffset + nActuallyRead - 1, SEEK_SET) != 0)
return nullptr;
// This hackery is necessary to try and find our correct
// spot on win32 systems with text mode line translation going
// on. Sometimes the fseek back overshoots, but it doesn't
// "realize it" till a character has been read. Try to read till
// we get to the right spot and get our CR.
int chCheck = fgetc(fp);
while ((chCheck != knCR && chCheck != EOF) ||
VSIFTell(fp) < nOriginalOffset + nActuallyRead)
{
static bool bWarned = false;
if (!bWarned)
{
bWarned = true;
CPLDebug("CPL",
"CPLFGets() correcting for DOS text mode translation "
"seek problem.");
}
chCheck = fgetc(fp);
}
}
return pszBuffer;
}
/************************************************************************/
/* CPLReadLineBuffer() */
/* */
/* Fetch readline buffer, and ensure it is the desired size, */
/* reallocating if needed. Manages TLS (thread local storage) */
/* issues for the buffer. */
/* We use a special trick to track the actual size of the buffer */
/* The first 4 bytes are reserved to store it as a int, hence the */
/* -4 / +4 hacks with the size and pointer. */
/************************************************************************/
static char *CPLReadLineBuffer(int nRequiredSize)
{
/* -------------------------------------------------------------------- */
/* A required size of -1 means the buffer should be freed. */
/* -------------------------------------------------------------------- */
if (nRequiredSize == -1)
{
int bMemoryError = FALSE;
void *pRet = CPLGetTLSEx(CTLS_RLBUFFERINFO, &bMemoryError);
if (pRet != nullptr)
{
CPLFree(pRet);
CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
}
return nullptr;
}
/* -------------------------------------------------------------------- */
/* If the buffer doesn't exist yet, create it. */
/* -------------------------------------------------------------------- */
int bMemoryError = FALSE;
GUInt32 *pnAlloc =
static_cast<GUInt32 *>(CPLGetTLSEx(CTLS_RLBUFFERINFO, &bMemoryError));
if (bMemoryError)
return nullptr;
if (pnAlloc == nullptr)
{
pnAlloc = static_cast<GUInt32 *>(VSI_MALLOC_VERBOSE(200));
if (pnAlloc == nullptr)
return nullptr;
*pnAlloc = 196;
CPLSetTLS(CTLS_RLBUFFERINFO, pnAlloc, TRUE);
}
/* -------------------------------------------------------------------- */
/* If it is too small, grow it bigger. */
/* -------------------------------------------------------------------- */
if (static_cast<int>(*pnAlloc) - 1 < nRequiredSize)
{
const int nNewSize = nRequiredSize + 4 + 500;
if (nNewSize <= 0)
{
VSIFree(pnAlloc);
CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
CPLError(CE_Failure, CPLE_OutOfMemory,
"CPLReadLineBuffer(): Trying to allocate more than "
"2 GB.");
return nullptr;
}
GUInt32 *pnAllocNew =
static_cast<GUInt32 *>(VSI_REALLOC_VERBOSE(pnAlloc, nNewSize));
if (pnAllocNew == nullptr)
{
VSIFree(pnAlloc);
CPLSetTLS(CTLS_RLBUFFERINFO, nullptr, FALSE);
return nullptr;
}
pnAlloc = pnAllocNew;
*pnAlloc = nNewSize - 4;
CPLSetTLS(CTLS_RLBUFFERINFO, pnAlloc, TRUE);
}
return reinterpret_cast<char *>(pnAlloc + 1);
}
/************************************************************************/
/* CPLReadLine() */
/************************************************************************/
/**
* Simplified line reading from text file.
*
* Read a line of text from the given file handle, taking care
* to capture CR and/or LF and strip off ... equivalent of
* DKReadLine(). Pointer to an internal buffer is returned.
* The application shouldn't free it, or depend on its value
* past the next call to CPLReadLine().
*
* Note that CPLReadLine() uses VSIFGets(), so any hooking of VSI file
* services should apply to CPLReadLine() as well.
*
* CPLReadLine() maintains an internal buffer, which will appear as a
* single block memory leak in some circumstances. CPLReadLine() may
* be called with a NULL FILE * at any time to free this working buffer.
*
* @param fp file pointer opened with VSIFOpen().
*
* @return pointer to an internal buffer containing a line of text read
* from the file or NULL if the end of file was encountered.
*/
const char *CPLReadLine(FILE *fp)
{
/* -------------------------------------------------------------------- */
/* Cleanup case. */
/* -------------------------------------------------------------------- */
if (fp == nullptr)
{
CPLReadLineBuffer(-1);
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Loop reading chunks of the line till we get to the end of */
/* the line. */
/* -------------------------------------------------------------------- */
size_t nBytesReadThisTime = 0;
char *pszRLBuffer = nullptr;
size_t nReadSoFar = 0;
do
{
/* --------------------------------------------------------------------
*/
/* Grow the working buffer if we have it nearly full. Fail out */
/* of read line if we can't reallocate it big enough (for */
/* instance for a _very large_ file with no newlines). */
/* --------------------------------------------------------------------
*/
if (nReadSoFar > 100 * 1024 * 1024)
// It is dubious that we need to read a line longer than 100 MB.
return nullptr;
pszRLBuffer = CPLReadLineBuffer(static_cast<int>(nReadSoFar) + 129);
if (pszRLBuffer == nullptr)
return nullptr;
/* --------------------------------------------------------------------
*/
/* Do the actual read. */
/* --------------------------------------------------------------------
*/
if (CPLFGets(pszRLBuffer + nReadSoFar, 128, fp) == nullptr &&
nReadSoFar == 0)
return nullptr;
nBytesReadThisTime = strlen(pszRLBuffer + nReadSoFar);
nReadSoFar += nBytesReadThisTime;
} while (nBytesReadThisTime >= 127 && pszRLBuffer[nReadSoFar - 1] != knCR &&
pszRLBuffer[nReadSoFar - 1] != knLF);
return pszRLBuffer;
}
/************************************************************************/
/* CPLReadLineL() */
/************************************************************************/
/**
* Simplified line reading from text file.
*
* Similar to CPLReadLine(), but reading from a large file API handle.
*
* @param fp file pointer opened with VSIFOpenL().
*
* @return pointer to an internal buffer containing a line of text read
* from the file or NULL if the end of file was encountered.
*/
const char *CPLReadLineL(VSILFILE *fp)
{
return CPLReadLine2L(fp, -1, nullptr);
}
/************************************************************************/
/* CPLReadLine2L() */
/************************************************************************/
/**
* Simplified line reading from text file.
*
* Similar to CPLReadLine(), but reading from a large file API handle.
*
* @param fp file pointer opened with VSIFOpenL().
* @param nMaxCars maximum number of characters allowed, or -1 for no limit.
* @param papszOptions NULL-terminated array of options. Unused for now.
* @return pointer to an internal buffer containing a line of text read
* from the file or NULL if the end of file was encountered or the maximum
* number of characters allowed reached.
*
* @since GDAL 1.7.0
*/
const char *CPLReadLine2L(VSILFILE *fp, int nMaxCars,
CPL_UNUSED CSLConstList papszOptions)
{
int nBufLength;
return CPLReadLine3L(fp, nMaxCars, &nBufLength, papszOptions);
}
/************************************************************************/
/* CPLReadLine3L() */
/************************************************************************/
/**
* Simplified line reading from text file.
*
* Similar to CPLReadLine(), but reading from a large file API handle.
*
* @param fp file pointer opened with VSIFOpenL().
* @param nMaxCars maximum number of characters allowed, or -1 for no limit.
* @param papszOptions NULL-terminated array of options. Unused for now.
* @param[out] pnBufLength size of output string (must be non-NULL)
* @return pointer to an internal buffer containing a line of text read
* from the file or NULL if the end of file was encountered or the maximum
* number of characters allowed reached.
*
* @since GDAL 2.3.0
*/
const char *CPLReadLine3L(VSILFILE *fp, int nMaxCars, int *pnBufLength,
CPL_UNUSED CSLConstList papszOptions)
{
/* -------------------------------------------------------------------- */
/* Cleanup case. */
/* -------------------------------------------------------------------- */
if (fp == nullptr)
{
CPLReadLineBuffer(-1);
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Loop reading chunks of the line till we get to the end of */
/* the line. */
/* -------------------------------------------------------------------- */
char *pszRLBuffer = nullptr;
const size_t nChunkSize = 40;
char szChunk[nChunkSize] = {};
size_t nChunkBytesRead = 0;
size_t nChunkBytesConsumed = 0;
*pnBufLength = 0;
szChunk[0] = 0;
while (true)
{
/* --------------------------------------------------------------------
*/
/* Read a chunk from the input file. */
/* --------------------------------------------------------------------
*/
if (*pnBufLength > INT_MAX - static_cast<int>(nChunkSize) - 1)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Too big line : more than 2 billion characters!.");
CPLReadLineBuffer(-1);
return nullptr;
}
pszRLBuffer =
CPLReadLineBuffer(static_cast<int>(*pnBufLength + nChunkSize + 1));
if (pszRLBuffer == nullptr)
return nullptr;
if (nChunkBytesRead == nChunkBytesConsumed + 1)
{
// case where one character is left over from last read.
szChunk[0] = szChunk[nChunkBytesConsumed];
nChunkBytesConsumed = 0;
nChunkBytesRead = VSIFReadL(szChunk + 1, 1, nChunkSize - 1, fp) + 1;
}
else
{
nChunkBytesConsumed = 0;
// fresh read.
nChunkBytesRead = VSIFReadL(szChunk, 1, nChunkSize, fp);
if (nChunkBytesRead == 0)
{
if (*pnBufLength == 0)
return nullptr;
break;
}
}
/* --------------------------------------------------------------------
*/
/* copy over characters watching for end-of-line. */
/* --------------------------------------------------------------------
*/
bool bBreak = false;
while (nChunkBytesConsumed < nChunkBytesRead - 1 && !bBreak)
{
if ((szChunk[nChunkBytesConsumed] == knCR &&
szChunk[nChunkBytesConsumed + 1] == knLF) ||
(szChunk[nChunkBytesConsumed] == knLF &&
szChunk[nChunkBytesConsumed + 1] == knCR))
{
nChunkBytesConsumed += 2;
bBreak = true;
}
else if (szChunk[nChunkBytesConsumed] == knLF ||
szChunk[nChunkBytesConsumed] == knCR)
{
nChunkBytesConsumed += 1;
bBreak = true;
}
else
{
pszRLBuffer[(*pnBufLength)++] = szChunk[nChunkBytesConsumed++];
if (nMaxCars >= 0 && *pnBufLength == nMaxCars)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Maximum number of characters allowed reached.");
return nullptr;
}
}
}
if (bBreak)
break;
/* --------------------------------------------------------------------
*/
/* If there is a remaining character and it is not a newline */
/* consume it. If it is a newline, but we are clearly at the */
/* end of the file then consume it. */
/* --------------------------------------------------------------------
*/
if (nChunkBytesConsumed == nChunkBytesRead - 1 &&
nChunkBytesRead < nChunkSize)
{
if (szChunk[nChunkBytesConsumed] == knLF ||
szChunk[nChunkBytesConsumed] == knCR)
{
nChunkBytesConsumed++;
break;
}
pszRLBuffer[(*pnBufLength)++] = szChunk[nChunkBytesConsumed++];
break;
}
}
/* -------------------------------------------------------------------- */
/* If we have left over bytes after breaking out, seek back to */
/* ensure they remain to be read next time. */
/* -------------------------------------------------------------------- */
if (nChunkBytesConsumed < nChunkBytesRead)
{
const size_t nBytesToPush = nChunkBytesRead - nChunkBytesConsumed;
if (VSIFSeekL(fp, VSIFTellL(fp) - nBytesToPush, SEEK_SET) != 0)
return nullptr;
}
pszRLBuffer[*pnBufLength] = '\0';
return pszRLBuffer;
}
/************************************************************************/
/* CPLScanString() */
/************************************************************************/
/**
* Scan up to a maximum number of characters from a given string,
* allocate a buffer for a new string and fill it with scanned characters.
*
* @param pszString String containing characters to be scanned. It may be
* terminated with a null character.
*
* @param nMaxLength The maximum number of character to read. Less
* characters will be read if a null character is encountered.
*
* @param bTrimSpaces If TRUE, trim ending spaces from the input string.
* Character considered as empty using isspace(3) function.
*
* @param bNormalize If TRUE, replace ':' symbol with the '_'. It is needed if
* resulting string will be used in CPL dictionaries.
*
* @return Pointer to the resulting string buffer. Caller responsible to free
* this buffer with CPLFree().
*/
char *CPLScanString(const char *pszString, int nMaxLength, int bTrimSpaces,
int bNormalize)
{
if (!pszString)
return nullptr;
if (!nMaxLength)
return CPLStrdup("");
char *pszBuffer = static_cast<char *>(CPLMalloc(nMaxLength + 1));
if (!pszBuffer)
return nullptr;
strncpy(pszBuffer, pszString, nMaxLength);
pszBuffer[nMaxLength] = '\0';
if (bTrimSpaces)
{
size_t i = strlen(pszBuffer);
while (i > 0)
{
i--;
if (!isspace(static_cast<unsigned char>(pszBuffer[i])))
break;
pszBuffer[i] = '\0';
}
}
if (bNormalize)
{
size_t i = strlen(pszBuffer);
while (i > 0)
{
i--;
if (pszBuffer[i] == ':')
pszBuffer[i] = '_';
}
}
return pszBuffer;
}
/************************************************************************/
/* CPLScanLong() */
/************************************************************************/
/**
* Scan up to a maximum number of characters from a string and convert
* the result to a long.
*
* @param pszString String containing characters to be scanned. It may be
* terminated with a null character.
*
* @param nMaxLength The maximum number of character to consider as part
* of the number. Less characters will be considered if a null character
* is encountered.
*
* @return Long value, converted from its ASCII form.
*/
long CPLScanLong(const char *pszString, int nMaxLength)
{
CPLAssert(nMaxLength >= 0);
if (pszString == nullptr)
return 0;
const size_t nLength = CPLStrnlen(pszString, nMaxLength);
const std::string osValue(pszString, nLength);
return atol(osValue.c_str());
}
/************************************************************************/
/* CPLScanULong() */
/************************************************************************/
/**
* Scan up to a maximum number of characters from a string and convert
* the result to a unsigned long.
*
* @param pszString String containing characters to be scanned. It may be
* terminated with a null character.
*
* @param nMaxLength The maximum number of character to consider as part
* of the number. Less characters will be considered if a null character
* is encountered.
*
* @return Unsigned long value, converted from its ASCII form.
*/
unsigned long CPLScanULong(const char *pszString, int nMaxLength)
{
CPLAssert(nMaxLength >= 0);
if (pszString == nullptr)
return 0;
const size_t nLength = CPLStrnlen(pszString, nMaxLength);
const std::string osValue(pszString, nLength);
return strtoul(osValue.c_str(), nullptr, 10);
}
/************************************************************************/
/* CPLScanUIntBig() */
/************************************************************************/
/**
* Extract big integer from string.
*
* Scan up to a maximum number of characters from a string and convert
* the result to a GUIntBig.
*
* @param pszString String containing characters to be scanned. It may be
* terminated with a null character.
*
* @param nMaxLength The maximum number of character to consider as part
* of the number. Less characters will be considered if a null character
* is encountered.
*
* @return GUIntBig value, converted from its ASCII form.
*/
GUIntBig CPLScanUIntBig(const char *pszString, int nMaxLength)
{
CPLAssert(nMaxLength >= 0);
if (pszString == nullptr)
return 0;
const size_t nLength = CPLStrnlen(pszString, nMaxLength);
const std::string osValue(pszString, nLength);
/* -------------------------------------------------------------------- */
/* Fetch out the result */
/* -------------------------------------------------------------------- */
return strtoull(osValue.c_str(), nullptr, 10);
}
/************************************************************************/