-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathjstring.cpp
More file actions
3119 lines (2794 loc) · 77.8 KB
/
jstring.cpp
File metadata and controls
3119 lines (2794 loc) · 77.8 KB
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
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#include "platform.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <math.h>
#include <algorithm>
#include "jstring.hpp"
#include "jexcept.hpp"
#include "jhash.hpp"
#include "jlog.hpp"
#include "jfile.hpp"
#include "jdebug.hpp"
#include "jutil.hpp"
#include "junicode.hpp"
#define DOUBLE_FORMAT "%.16g"
#define FLOAT_FORMAT "%.7g"
#ifndef va_copy
/* WARNING - DANGER - ASSUMES TYPICAL STACK MACHINE */
#define va_copy(dst, src) ((void)((dst) = (src)))
#endif
static const char * TheNullStr = "";
constexpr unsigned STRING_FIRST_CHUNK_SIZE=8;
constexpr unsigned STRING_DOUBLE_LIMIT = 0x100000; // must be a power of 2
constexpr unsigned STRING_DETACH_GRANULARITY = 16;
//===========================================================================
StringBuffer::StringBuffer()
{
init();
}
#if 0
StringBuffer::StringBuffer(size_t initial)
{
init();
ensureCapacity(initial);
}
#endif
StringBuffer::StringBuffer(String & value)
{
init();
append(value);
}
StringBuffer::StringBuffer(const char *value)
{
init();
append(value);
}
StringBuffer::StringBuffer(char value)
{
init();
append(value);
}
StringBuffer::StringBuffer(size_t len, const char *value)
{
init();
append(len, value);
}
StringBuffer::StringBuffer(const StringBuffer & value)
{
init();
append(value);
}
StringBuffer::StringBuffer(StringBuffer && value)
{
init();
swapWith(value);
}
StringBuffer::~StringBuffer()
{
#ifdef CATCH_USE_AFTER_FREE
if (buffer == internalBuffer)
strncpy(internalBuffer, "use-after-free", InternalBufferSize-1);
else
strncpy(buffer, "use-after-free", curLen);
#endif
freeBuffer();
#ifdef CATCH_USE_AFTER_FREE
//Try and cause any use after free to access invalid memory
curLen = 0;
maxLen = (size_t)-1;
buffer = nullptr;
#endif
}
void StringBuffer::freeBuffer()
{
if (buffer != internalBuffer)
free(buffer);
}
void StringBuffer::setBuffer(size_t buffLen, char * newBuff, size_t strLen)
{
assertex(newBuff);
assertex(buffLen>0 && strLen<buffLen);
freeBuffer();
buffer = newBuff;
maxLen = buffLen;
curLen = strLen;
}
void StringBuffer::_realloc(size_t newLen)
{
if (newLen >= maxLen)
{
size_t newMax = maxLen;
if (newMax == 0)
newMax = STRING_FIRST_CHUNK_SIZE;
if (newLen > STRING_DOUBLE_LIMIT)
{
newMax = (newLen + STRING_DOUBLE_LIMIT) & ~(STRING_DOUBLE_LIMIT-1);
if (newLen >= newMax)
throw MakeStringException(MSGAUD_operator, -1, "StringBuffer::_realloc: Request for %zu bytes oldMax = %zu", newLen, maxLen);
}
else
{
while (newLen >= newMax)
newMax += newMax;
}
char * newStr;
char * originalBuffer = (buffer == internalBuffer) ? NULL : buffer;
if (!newMax || !(newStr=(char *)realloc(originalBuffer, newMax)))
{
DBGLOG("StringBuffer::_realloc: Failed to realloc = %zu, oldMax = %zu", newMax, maxLen);
PrintStackReport();
PrintMemoryReport();
throw MakeStringException(MSGAUD_operator, -1, "StringBuffer::_realloc: Failed to realloc = %zu, oldMax = %zu", newMax, maxLen);
}
if (useInternal())
memcpy_iflen(newStr, internalBuffer, curLen);
buffer = newStr;
maxLen = newMax;
}
}
char * StringBuffer::detach()
{
dbgassertex(buffer);
char * result;
if (buffer == internalBuffer)
{
result = (char *)malloc(curLen+1);
memcpy_iflen(result, buffer, curLen);
}
else
{
if (maxLen>curLen+1+STRING_DETACH_GRANULARITY)
buffer = (char *)realloc(buffer,curLen+1); // shrink
result = buffer;
}
result[curLen] = '\0'; // There is always room for this null
init();
return result;
}
StringBuffer & StringBuffer::append(char value)
{
ensureCapacity(1);
buffer[curLen] = value;
++curLen;
return *this;
}
StringBuffer & StringBuffer::append(unsigned char value)
{
ensureCapacity(1);
buffer[curLen] = value;
++curLen;
return *this;
}
StringBuffer & StringBuffer::append(const char * value)
{
if (likely(value))
{
size_t SourceLen = strlen(value);
if (likely(SourceLen))
{
ensureCapacity(SourceLen);
memcpy(buffer + curLen, value, SourceLen);
curLen += SourceLen;
}
}
return *this;
}
StringBuffer & StringBuffer::append(size_t len, const char * value)
{
if (likely(len))
{
unsigned truncLen = (unsigned)len;
assertex(truncLen == len); // MORE: StringBuffer should use size_t throughout
if (likely(truncLen))
{
ensureCapacity(truncLen);
memcpy(buffer + curLen, value, truncLen);
curLen += truncLen;
}
}
return *this;
}
StringBuffer & StringBuffer::append(const unsigned char * value)
{
return append((const char *) value);
}
StringBuffer & StringBuffer::append(const char * value, size_t offset, size_t len)
{
if (likely(len))
{
ensureCapacity(len);
memcpy(buffer + curLen, value+offset, len);
curLen += len;
}
return *this;
}
StringBuffer & StringBuffer::append(const IAtom * value)
{
if (value)
append(value->queryStr());
return *this;
}
StringBuffer & StringBuffer::append(double value)
{
size_t len = length();
size_t newlen = appendf(DOUBLE_FORMAT, value).length();
while (len < newlen)
{
switch (charAt(len))
{
case '.':
case 'E':
case 'e':
case 'N': // Not a number/infinity
case 'n':
return *this;
}
len++;
}
return append(".0");
}
StringBuffer & StringBuffer::append(float value)
{
size_t len = length();
size_t newlen = appendf(FLOAT_FORMAT, value).length();
while (len < newlen)
{
switch (charAt(len))
{
case '.':
case 'E':
case 'e':
case 'N': // Not a number/infinity
case 'n':
return *this;
}
len++;
}
return append(".0");
}
StringBuffer & StringBuffer::append(int value)
{
char temp[12];
unsigned written = numtostr(temp, value);
return append(written, temp);
}
StringBuffer & StringBuffer::append(unsigned value)
{
char temp[12];
unsigned written = numtostr(temp, value);
return append(written, temp);
}
StringBuffer & StringBuffer::appendlong(long value)
{
char temp[24];
unsigned written = numtostr(temp, value);
return append(written, temp);
}
StringBuffer & StringBuffer::appendulong(unsigned long value)
{
char temp[24];
unsigned written = numtostr(temp, value);
return append(written, temp);
}
StringBuffer & StringBuffer::append(__int64 value)
{
char temp[24];
unsigned written = numtostr(temp, value);
return append(written, temp);
}
StringBuffer & StringBuffer::append(unsigned __int64 value)
{
char temp[24];
unsigned written = numtostr(temp, value);
return append(written, temp);
}
StringBuffer & StringBuffer::append(const String & value)
{
size_t SourceLen = value.length();
ensureCapacity(SourceLen);
value.getChars(0, SourceLen, buffer, curLen);
curLen += SourceLen;
return *this;
}
StringBuffer & StringBuffer::append(const IStringVal & value)
{
return append(value.str());
}
StringBuffer & StringBuffer::append(const IStringVal * value)
{
if (value)
return append(value->str());
else
return *this;
}
StringBuffer & StringBuffer::append(const StringBuffer & value)
{
size_t SourceLen = value.length();
ensureCapacity(SourceLen);
value.getChars(0, SourceLen, buffer + curLen);
curLen += SourceLen;
return *this;
}
StringBuffer & StringBuffer::appendf(const char *format, ...)
{
va_list args;
va_start(args, format);
valist_appendf(format, args);
va_end(args);
return *this;
}
StringBuffer & StringBuffer::appendLower(size_t len, const char * value)
{
if (len)
{
ensureCapacity(len);
const byte * from = reinterpret_cast<const byte *>(value);
for (size_t i = 0; i < len; i++)
buffer[curLen + i] = tolower(from[i]);
curLen += len;
}
return *this;
}
StringBuffer & StringBuffer::setf(const char *format, ...)
{
clear();
va_list args;
va_start(args, format);
valist_appendf(format, args);
va_end(args);
return *this;
}
StringBuffer & StringBuffer::limited_valist_appendf(size_t szLimit, const char *format, va_list args)
{
#define BUF_SIZE 1024
#define MAX_BUF_SIZE (1024*1024) // limit buffer size to 1MB when doubling
// handle string that is bigger that BUF_SIZE bytes
size_t size = (0 == szLimit||szLimit>BUF_SIZE)?BUF_SIZE:szLimit;
int len;
va_list args2;
va_copy(args2, args);
try { ensureCapacity(size); }
catch (IException *e)
{
StringBuffer eMsg;
IException *e2 = MakeStringException(-1, "StringBuffer::valist_appendf(\"%s\"): vsnprintf failed or result exceeds limit (%zu): %s", format, size, e->errorMessage(eMsg).str());
e->Release();
throw e2;
}
len = _vsnprintf(buffer+curLen,size,format,args);
if (len >= 0)
{
if ((size_t)len >= size)
{
if (szLimit && (size_t)len >= szLimit)
{
if ((size_t)len>szLimit)
{
len = size;
if (len>3) memcpy(buffer+len-3, "...", 3);
}
}
else
{
ensureCapacity(len);
// no need for _vsnprintf since the buffer is already made big enough
vsprintf(buffer+curLen,format,args2);
}
}
}
else if (size == szLimit)
{
len = size;
if (len>3) memcpy(buffer+len-3, "...", 3);
}
else
{
size = BUF_SIZE * 2;
for (;;)
{
if (0 != szLimit && size>szLimit) size = szLimit; // if so, will be last attempt
if (size>MAX_BUF_SIZE)
{
IWARNLOG("StringBuffer::valist_appendf(\"%s\"): vsnprintf exceeds limit (%zu)", format, size);
size = szLimit = MAX_BUF_SIZE;
}
try { ensureCapacity(size); }
catch (IException *e)
{
StringBuffer eMsg;
IException *e2 = MakeStringException(-1, "StringBuffer::valist_appendf(\"%s\"): vsnprintf failed (%zu): %s", format, size, e->errorMessage(eMsg).str());
e->Release();
throw e2;
}
va_list args3;
va_copy(args3, args2);
len = _vsnprintf(buffer+curLen,size,format,args3);
va_end(args3);
if (len>=0) // NB: len>size not possible, 1st _vsnprintf would have handled.
break;
if (size == szLimit)
{
len = size;
if (len>3) memcpy(buffer+len-3, "...", 3);
break;
}
size <<= 1;
}
}
va_end(args2);
curLen += len;
return *this;
}
StringBuffer & StringBuffer::appendN(size_t count, char fill)
{
ensureCapacity(count);
memset(buffer+curLen, fill, count);
curLen += count;
return *this;
}
void StringBuffer::setLength(size_t len)
{
if (len > curLen)
{
ensureCapacity(len-curLen);
}
curLen = len;
}
char * StringBuffer::ensureCapacity(size_t max, size_t & got)
{
if (maxLen <= curLen + max)
_realloc(curLen + max);
got = maxLen - curLen - 1;
return buffer + curLen;
}
size32_t StringBuffer::lengthUtf8() const
{
size_t chars = 0;
for (size_t offset=0; offset < curLen; offset += readUtf8Size(buffer+offset))
chars++;
return (size32_t)chars; // NB: preserving return type as size32_t for backward compatibility (as might be used in serialization)
}
char * StringBuffer::reserve(size_t size)
{
ensureCapacity(size);
char *ret = buffer+curLen;
curLen += size;
return ret;
}
char * StringBuffer::reserveTruncate(size_t size)
{
size_t newMax = curLen+size+1;
if (buffer == internalBuffer)
{
if (newMax > InternalBufferSize)
{
char * newStr = (char *)malloc(newMax);
if (!newStr)
throw MakeStringException(-1, "StringBuffer::_realloc: Failed to realloc newMax = %zu, oldMax = %zu", newMax, maxLen);
memcpy_iflen(newStr, buffer, curLen);
buffer = newStr;
maxLen = newMax;
}
}
else if (newMax != maxLen)
{
char * newStr = (char *) realloc(buffer, newMax);
if (!newStr)
throw MakeStringException(-1, "StringBuffer::_realloc: Failed to realloc newMax = %zu, oldMax = %zu", newMax, maxLen);
buffer = newStr;
maxLen = newMax;
}
char *ret = buffer+curLen;
curLen += size;
return ret;
}
void StringBuffer::swapWith(StringBuffer &other)
{
//Swap max
size_t tempMax = maxLen;
maxLen = other.maxLen;
other.maxLen = tempMax;
//Swap lengths
size_t thisLen = curLen;
size_t otherLen = other.curLen;
curLen = otherLen;
other.curLen = thisLen;
//Swap buffers
char * thisBuffer = buffer;
char * otherBuffer = other.buffer;
if (useInternal())
{
if (other.useInternal())
{
//NOTE: The c++ compiler can generate better code for the fixed size memcpy than it can
// if only the required characters are copied.
char temp[InternalBufferSize];
memcpy(temp, thisBuffer, InternalBufferSize);
memcpy(thisBuffer, otherBuffer, InternalBufferSize);
memcpy(otherBuffer, temp, InternalBufferSize);
//buffers already point in the correct place
}
else
{
memcpy(other.internalBuffer, thisBuffer, InternalBufferSize);
buffer = otherBuffer;
other.buffer = other.internalBuffer;
}
}
else
{
if (other.useInternal())
{
memcpy(internalBuffer, otherBuffer, InternalBufferSize);
buffer = internalBuffer;
other.buffer = thisBuffer;
}
else
{
buffer = otherBuffer;
other.buffer = thisBuffer;
}
}
}
void StringBuffer::setown(StringBuffer &other)
{
maxLen = other.maxLen;
curLen = other.curLen;
freeBuffer();
if (other.useInternal())
{
memcpy(internalBuffer, other.internalBuffer, InternalBufferSize);
buffer = internalBuffer;
}
else
{
buffer = other.buffer;
}
other.init();
}
void StringBuffer::kill()
{
freeBuffer();
init();
}
void StringBuffer::getChars(size_t srcBegin, size_t srcEnd, char * target) const
{
if (srcEnd > curLen)
srcEnd = curLen;
const int len = srcEnd - srcBegin;
if (target && buffer && len > 0)
memcpy(target, buffer + srcBegin, len);
}
void StringBuffer::_insert(size_t offset, size_t insertLen)
{
ensureCapacity(insertLen);
memmove(buffer + offset + insertLen, buffer + offset, curLen - offset);
curLen += insertLen;
}
StringBuffer & StringBuffer::insert(size_t offset, char value)
{
_insert(offset, 1);
buffer[offset] = value;
return *this;
}
StringBuffer & StringBuffer::insert(size_t offset, const char * value)
{
if (!value) return *this;
size_t len = strlen(value);
if (likely(len))
{
_insert(offset, len);
memcpy(buffer + offset, value, len);
}
return *this;
}
StringBuffer & StringBuffer::insert(size_t offset, double value)
{
char temp[36];
sprintf(temp, "%f", value);
insert(offset, temp);
return *this;
}
StringBuffer & StringBuffer::insert(size_t offset, float value)
{
return insert(offset, (double)value);
}
StringBuffer & StringBuffer::insert(size_t offset, int value)
{
char temp[12];
numtostr(temp, value);
return insert(offset, temp);
}
StringBuffer & StringBuffer::insert(size_t offset, unsigned value)
{
char temp[12];
numtostr(temp, value);
return insert(offset, temp);
}
#if 0
StringBuffer & StringBuffer::insert(size_t offset, long value)
{
char temp[24];
numtostr(temp, value);
return insert(offset, temp);
}
#endif
StringBuffer & StringBuffer::insert(size_t offset, __int64 value)
{
char temp[24];
numtostr(temp, value);
return insert(offset, temp);
}
StringBuffer & StringBuffer::insert(size_t offset, const String & value)
{
size_t len = value.length();
_insert(offset, len);
value.getChars(0, len, buffer, offset);
return *this;
}
StringBuffer & StringBuffer::insert(size_t offset, const StringBuffer & value)
{
size_t len = value.length();
_insert(offset, len);
value.getChars(0, len, buffer+offset);
return *this;
}
StringBuffer & StringBuffer::insert(size_t offset, const IStringVal & value)
{
return insert(offset, value.str());
}
StringBuffer & StringBuffer::insert(size_t offset, const IStringVal * value)
{
if (value)
return insert(offset, value->str());
else
return *this;
}
StringBuffer & StringBuffer::newline()
{
return append("\n");
}
StringBuffer & StringBuffer::pad(size_t count)
{
ensureCapacity(count);
memset(buffer + curLen, ' ', count);
curLen += count;
return *this;
}
StringBuffer & StringBuffer::padTo(size_t count)
{
if (curLen<count)
pad(count-curLen);
return *this;
}
StringBuffer & StringBuffer::clip()
{
while (curLen && isspace(buffer[curLen-1]))
curLen--;
return *this;
}
StringBuffer & StringBuffer::trim()
{
return clip().trimLeft();
}
StringBuffer & StringBuffer::trimLeft()
{
char *p;
if (curLen==0)
return *this;
buffer[curLen] = 0;
for(p = buffer;isspace(*p);p++)
;
if (p!=buffer)
{
curLen -= p-buffer;
memmove(buffer,p,curLen);
}
return *this;
}
StringBuffer & StringBuffer::remove(size_t start, size_t len)
{
if (start > curLen) start = curLen;
if (start + len > curLen) len = curLen - start;
unsigned start2 = start + len;
memmove(buffer + start, buffer + start2, curLen - start2);
setLength(curLen - len);
return *this;
}
StringBuffer &StringBuffer::reverse()
{
size_t max = curLen/2;
char * end = buffer + curLen;
size_t idx;
for (idx = 0; idx < max; idx++)
{
char temp = buffer[idx];
end--;
buffer[idx] = *end;
*end = temp;
}
return *this;
}
MemoryBuffer & StringBuffer::deserialize(MemoryBuffer & in)
{
unsigned len;
in.read(len);
append(len, (const char *)in.readDirect(len));
return in;
}
MemoryBuffer & StringBuffer::serialize(MemoryBuffer & out) const
{
return out.append((unsigned)curLen).append(curLen, buffer);
}
StringBuffer &StringBuffer::loadFile(const char *filename, bool binaryMode)
{
FILE *in = fopen(filename, binaryMode?"rb":"rt");
if (in)
{
char buffer[1024];
size_t bytes;
for (;;)
{
bytes = (size_t)fread(buffer, 1, sizeof(buffer), in);
if (!bytes)
break;
append(buffer, 0, bytes);
}
fclose(in);
return *this;
}
else
throw MakeStringException(errno, "File %s could not be opened", filename);
}
StringBuffer & StringBuffer::loadFile(IFile* f)
{
if(!f)
return *this;
Owned<IFileIO> io = f->open(IFOread);
if(!io)
throw MakeStringException(errno, "file %s could not be opened for reading", f->queryFilename());
char buf[2048];
const unsigned requestedSize = sizeof(buf);
offset_t pos = 0;
for (;;)
{
size32_t len = io->read(pos, requestedSize, buf);
if (len == 0)
break;
append(len, buf);
pos += len;
if (len != requestedSize)
break;
}
return *this;
}
void StringBuffer::setCharAt(size_t offset, char value)
{
if (offset < curLen)
buffer[offset] = value;
}
void StringBuffer::replace(size_t offset, size_t len, const void * value)
{
if ((offset >= curLen) || (len == 0))
return;
if (offset + len > curLen)
len = curLen - offset;
memcpy(buffer + offset, value, len);
}
StringBuffer & StringBuffer::toLowerCase()
{
size_t l = curLen;
for (size_t i = 0; i < l; i++)
{
if (isupper(buffer[i]))
buffer[i] = tolower(buffer[i]);
}
return *this;
}
StringBuffer & StringBuffer::toUpperCase()
{
size32_t l = curLen;
for (size32_t i = 0; i < l; i++)
{
if (islower(buffer[i]))
buffer[i] = toupper(buffer[i]);
}
return *this;
}
StringBuffer & StringBuffer::replace(char oldChar, char newChar)
{
size_t l = curLen;
for (size_t i = 0; i < l; i++)
{
if (buffer[i] == oldChar)
{
buffer[i] = newChar;
if (newChar == '\0')
{
curLen = i;
break;
}
}
}
return *this;
}
// Copy source to result, replacing all occurrences of "oldStr" with "newStr"
bool replaceString(StringBuffer & result, size_t lenSource, const char *source, size_t lenOldStr, const char* oldStr, size_t lenNewStr, const char* newStr, bool avoidCopyIfUnmatched)
{
if (lenOldStr && lenSource >= lenOldStr)
{
size_t offset = 0;
size_t lastCopied = 0;
size_t maxOffset = lenSource - lenOldStr + 1;
char firstChar = oldStr[0];
while (offset < maxOffset)
{
if (unlikely(source[offset] == firstChar)
&& unlikely((lenOldStr == 1) || memcmp(source + offset, oldStr, lenOldStr)==0))
{
// Wait to allocate memory until a match is found
if (!lastCopied)
result.ensureCapacity(lenSource); // Avoid allocating an unnecessarly large buffer and match the source string
// If lastCopied matches the offset nothing is appended, but we can avoid a test for offset == lastCopied
result.append(offset - lastCopied, source + lastCopied);
result.append(lenNewStr, newStr);
offset += lenOldStr;
lastCopied = offset;
}
else
offset++;
}
if (lastCopied || !avoidCopyIfUnmatched)
result.append(lenSource - lastCopied, source + lastCopied); // Append the remaining characters
return lastCopied != 0;
}
else if (!avoidCopyIfUnmatched)
result.append(lenSource, source); // Search string does not fit in source or is empty
return false;
}
StringBuffer &replaceVariables(StringBuffer & result, const char *source, bool exceptions, IVariableSubstitutionHelper *helper, const char* delim, const char* term)
{
if (isEmptyString(source) || isEmptyString(delim) || isEmptyString(term))
return result;
size_t lenDelim = strlen(delim);
size_t lenTerm = strlen(term);
size_t left = strlen(source);
size_t minLen = lenDelim + lenTerm + 1;