aboutsummaryrefslogtreecommitdiff
path: root/ext/dropt/src/dropt_string.c
blob: 32e65758c1416cae1d3c9a57caa44f2fab764f17 (plain)
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
/** dropt_string.c
  *
  * String routines for dropt.
  *
  * Copyright (c) 2006-2012 James D. Lin <jameslin@cal.berkeley.edu>
  *
  * The latest version of this file can be downloaded from:
  * <http://www.taenarum.com/software/dropt/>
  *
  * This software is provided 'as-is', without any express or implied
  * warranty.  In no event will the authors be held liable for any damages
  * arising from the use of this software.
  *
  * Permission is granted to anyone to use this software for any purpose,
  * including commercial applications, and to alter it and redistribute it
  * freely, subject to the following restrictions:
  *
  * 1. The origin of this software must not be misrepresented; you must not
  *    claim that you wrote the original software. If you use this software
  *    in a product, an acknowledgment in the product documentation would be
  *    appreciated but is not required.
  *
  * 2. Altered source versions must be plainly marked as such, and must not be
  *    misrepresented as being the original software.
  *
  * 3. This notice may not be removed or altered from any source distribution.
  */
// This file has been altered to convert a call to the unsafe memcpy to a
// local loop.
#ifdef _MSC_VER
    #include <tchar.h>
#endif

#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <wctype.h>
#include <stdio.h>
#include <assert.h>

#if __STDC_VERSION__ >= 199901L
    #include <stdint.h>
#else
    /* Compatibility junk for things that don't yet support ISO C99. */
    #if defined _MSC_VER || defined __BORLANDC__
        #ifndef va_copy
            #define va_copy(dest, src) (dest = (src))
        #endif
    #else
        #ifndef va_copy
            #error Unsupported platform.  va_copy is not defined.
        #endif
    #endif

    #ifndef SIZE_MAX
        #define SIZE_MAX ((size_t) -1)
    #endif
#endif

#include "dropt_string.h"

#ifndef MAX
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#endif

#ifndef MIN
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#endif

#ifdef DROPT_DEBUG_STRING_BUFFERS
    enum { default_stringstream_buffer_size = 1 };
    #define GROWN_STRINGSTREAM_BUFFER_SIZE(oldSize, minAmount) \
        ((oldSize) + (minAmount))
#else
    enum { default_stringstream_buffer_size = 256 };
    #define GROWN_STRINGSTREAM_BUFFER_SIZE(oldSize, minAmount) \
        MAX((oldSize) * 2, (oldSize) + (minAmount))
#endif


#ifndef DROPT_NO_STRING_BUFFERS
struct dropt_stringstream
{
    dropt_char* string; /* The string buffer. */
    size_t maxSize;     /* Size of the string buffer, in dropt_char-s, including space for NUL. */
    size_t used;        /* Number of elements used in the string buffer, excluding NUL. */
};
#endif


/** dropt_safe_malloc
  *
  *     A version of malloc that checks for integer overflow.
  *
  * PARAMETERS:
  *     IN numElements : The number of elements to allocate.
  *     IN elementSize : The size of each element, in bytes.
  *
  * RETURNS:
  *     A pointer to the allocated memory.
  *     Returns NULL if numElements is 0.
  *     Returns NULL on error.
  */
void*
dropt_safe_malloc(size_t numElements, size_t elementSize)
{
    return dropt_safe_realloc(NULL, numElements, elementSize);
}


/** dropt_safe_realloc
  *
  *     Wrapper around realloc to check for integer overflow.
  *
  * PARAMETERS:
  *     IN/OUT p       : A pointer to the memory block to resize.
  *                      If NULL, a new memory block of the specified size
  *                        will be allocated.
  *     IN numElements : The number of elements to allocate.
  *                      If 0, frees p.
  *     IN elementSize : The size of each element, in bytes.
  *
  * RETURNS:
  *     A pointer to the allocated memory.
  *     Returns NULL if numElements is 0.
  *     Returns NULL on error.
  */
void*
dropt_safe_realloc(void* p, size_t numElements, size_t elementSize)
{
    size_t numBytes;

    /* elementSize shouldn't legally be 0, but we check for it in case a
     * caller got the argument order wrong.
     */
    if (numElements == 0 || elementSize == 0)
    {
        /* The behavior of realloc(p, 0) is implementation-defined.  Let's
         * enforce a particular behavior.
         */
        free(p);

        assert(elementSize != 0);
        return NULL;
    }

    numBytes = numElements * elementSize;
    if (numBytes / elementSize != numElements)
    {
        /* Overflow. */
        return NULL;
    }

    return realloc(p, numBytes);
}


/** dropt_strdup
  *
  *     Duplicates a string.
  *
  * PARAMETERS:
  *     IN s : A NUL-terminated string to duplicate.
  *
  * RETURNS:
  *     The duplicated string.  The caller is responsible for calling
  *       free() on it when no longer needed.
  *     Returns NULL on error.
  */
dropt_char*
dropt_strdup(const dropt_char* s)
{
    return dropt_strndup(s, SIZE_MAX);
}


/** dropt_strndup
  *
  *     Duplicates the first n characters of a string.
  *
  * PARAMETERS:
  *     IN s : The string to duplicate.
  *     IN n : The maximum number of dropt_char-s to copy, excluding the
  *              NUL-terminator.
  *
  * RETURNS:
  *     The duplicated string, which is always NUL-terminated.  The caller
  *       is responsible for calling free() on it when no longer needed.
  *     Returns NULL on error.
  */
dropt_char*
dropt_strndup(const dropt_char* s, size_t n)
{
    dropt_char* copy;
    size_t len = 0;
    size_t i = 0;

    assert(s != NULL);

    while (len < n && s[len] != DROPT_TEXT_LITERAL('\0'))
    {
        len++;
    }

    if (len + 1 < len)
    {
        /* This overflow check shouldn't be strictly necessary.  len can be
         * at most SIZE_MAX, so SIZE_MAX + 1 can wrap around to 0, but
         * dropt_safe_malloc will return NULL for a 0-sized allocation.
         * However, favor defensive paranoia.
         */
        return NULL;
    }

    copy = dropt_safe_malloc(len + 1 /* NUL */, sizeof *copy);
    if (copy != NULL)
    {
        for(i = 0; i < len; i+=1){
            copy[i] = s[i];
        }
        copy[len] = DROPT_TEXT_LITERAL('\0');
    }

    return copy;
}


/** dropt_stricmp
  *
  *     Compares two NUL-terminated strings ignoring case differences.  Not
  *       recommended for non-ASCII strings.
  *
  * PARAMETERS:
  *     IN s, t : The strings to compare.
  *
  * RETURNS:
  *     0 if the strings are equivalent,
  *     < 0 if s is lexically less than t,
  *     > 0 if s is lexically greater than t.
  */
int
dropt_stricmp(const dropt_char* s, const dropt_char* t)
{
    assert(s != NULL);
    assert(t != NULL);
    return dropt_strnicmp(s, t, SIZE_MAX);
}


/** dropt_strnicmp
  *
  *     Compares the first n characters of two strings, ignoring case
  *       differences.  Not recommended for non-ASCII strings.
  *
  * PARAMETERS:
  *     IN s, t : The strings to compare.
  *     IN n    : The maximum number of dropt_char-s to compare.
  *
  * RETURNS:
  *     0 if the strings are equivalent,
  *     < 0 if s is lexically less than t,
  *     > 0 if s is lexically greater than t.
  */
int
dropt_strnicmp(const dropt_char* s, const dropt_char* t, size_t n)
{
    assert(s != NULL);
    assert(t != NULL);

    if (s == t) { return 0; }

    while (n--)
    {
        if (*s == DROPT_TEXT_LITERAL('\0') && *t == DROPT_TEXT_LITERAL('\0'))
        {
            break;
        }
        else if (*s == *t || dropt_tolower(*s) == dropt_tolower(*t))
        {
            s++;
            t++;
        }
        else
        {
            return (dropt_tolower(*s) < dropt_tolower(*t))
                   ? -1
                   : +1;
        }
    }

    return 0;
}


#ifndef DROPT_NO_STRING_BUFFERS
/** dropt_vsnprintf
  *
  *     vsnprintf wrapper to provide ISO C99-compliant behavior.
  *
  * PARAMETERS:
  *     OUT s     : The destination buffer.  May be NULL if n is 0.
  *                 If non-NULL, always NUL-terminated.
  *     IN n      : The size of the destination buffer, measured in
  *                   dropt_char-s.
  *     IN format : printf-style format specifier.  Must not be NULL.
  *     IN args   : Arguments to insert into the formatted string.
  *
  * RETURNS:
  *     The number of characters that would be written to the destination
  *       buffer if it's sufficiently large, excluding the NUL-terminator.
  *     Returns -1 on error.
  */
int
dropt_vsnprintf(dropt_char* s, size_t n, const dropt_char* format, va_list args)
{
#if __STDC_VERSION__ >= 199901L || __GNUC__
    /* ISO C99-compliant.
     *
     * As far as I can tell, gcc's implementation of vsnprintf has always
     * matched the behavior required by the C99 standard (which is to
     * return the necessary buffer size).
     *
     * Note that this won't work with wchar_t because there is no true,
     * standard wchar_t equivalent of snprintf.  swprintf comes close but
     * doesn't return the necessary buffer size (and the standard does not
     * provide a guaranteed way to test if truncation occurred), and its
     * format string can't be used interchangeably with snprintf.
     *
     * It's simpler not to support wchar_t on non-Windows platforms.
     */
    assert(format != NULL);
    return vsnprintf(s, n, format, args);
#elif defined __BORLANDC__
    /* Borland's compiler neglects to NUL-terminate. */
    int ret;
    assert(format != NULL);
    ret = vsnprintf(s, n, format, args);
    if (n != 0) { s[n - 1] = DROPT_TEXT_LITERAL('\0'); }
    return ret;
#elif defined _MSC_VER
    /* _vsntprintf and _vsnprintf_s on Windows don't have C99 semantics;
     * they return -1 if truncation occurs.
     */
    va_list argsCopy;
    int ret;

    assert(format != NULL);

    va_copy(argsCopy, args);
    ret = _vsctprintf(format, argsCopy);
    va_end(argsCopy);

    if (n != 0)
    {
        assert(s != NULL);

    #if _MSC_VER >= 1400
        (void) _vsntprintf_s(s, n, _TRUNCATE, format, args);
    #else
        /* This version doesn't necessarily NUL-terminate.  Sigh. */
        (void) _vsnprintf(s, n, format, args);
        s[n - 1] = DROPT_TEXT_LITERAL('\0');
    #endif
    }

    return ret;

#else
    #error Unsupported platform.  dropt_vsnprintf unimplemented.
    return -1;
#endif
}


/** See dropt_vsnprintf. */
int
dropt_snprintf(dropt_char* s, size_t n, const dropt_char* format, ...)
{
    int ret;
    va_list args;
    va_start(args, format);
    ret = dropt_vsnprintf(s, n, format, args);
    va_end(args);
    return ret;
}


/** dropt_vasprintf
  *
  *     Allocates a formatted string with vprintf semantics.
  *
  * PARAMETERS:
  *     IN format : printf-style format specifier.  Must not be NULL.
  *     IN args   : Arguments to insert into the formatted string.
  *
  * RETURNS:
  *     The formatted string, which is always NUL-terminated.  The caller
  *       is responsible for calling free() on it when no longer needed.
  *     Returns NULL on error.
  */
dropt_char*
dropt_vasprintf(const dropt_char* format, va_list args)
{
    dropt_char* s = NULL;
    int len;
    va_list argsCopy;
    assert(format != NULL);

    va_copy(argsCopy, args);
    len = dropt_vsnprintf(NULL, 0, format, argsCopy);
    va_end(argsCopy);

    if (len >= 0)
    {
        size_t n = len + 1 /* NUL */;
        s = dropt_safe_malloc(n, sizeof *s);
        if (s != NULL)
        {
            dropt_vsnprintf(s, n, format, args);
        }
    }

    return s;
}


/** See dropt_vasprintf. */
dropt_char*
dropt_asprintf(const dropt_char* format, ...)
{
    dropt_char* s;

    va_list args;
    va_start(args, format);
    s = dropt_vasprintf(format, args);
    va_end(args);

    return s;
}


/** dropt_ssopen
  *
  *     Constructs a new dropt_stringstream.
  *
  * RETURNS:
  *     An initialized dropt_stringstream.  The caller is responsible for
  *       calling either dropt_ssclose() or dropt_ssfinalize() on it when
  *       no longer needed.
  *     Returns NULL on error.
  */
dropt_stringstream*
dropt_ssopen(void)
{
    dropt_stringstream* ss = malloc(sizeof *ss);
    if (ss != NULL)
    {
        ss->used = 0;
        ss->maxSize = default_stringstream_buffer_size;
        ss->string = dropt_safe_malloc(ss->maxSize, sizeof *ss->string);
        if (ss->string == NULL)
        {
            free(ss);
            ss = NULL;
        }
        else
        {
            ss->string[0] = DROPT_TEXT_LITERAL('\0');
        }
    }
    return ss;
}


/** dropt_ssclose
  *
  *     Destroys a dropt_stringstream.
  *
  * PARAMETERS:
  *     IN/OUT ss : The dropt_stringstream.
  */
void
dropt_ssclose(dropt_stringstream* ss)
{
    if (ss != NULL)
    {
        free(ss->string);
        free(ss);
    }
}


/** dropt_ssgetfreespace
  *
  * RETURNS:
  *     The amount of free space in the dropt_stringstream's internal
  *       buffer, measured in dropt_char-s.  Space used for the
  *       NUL-terminator is considered free. (The amount of free space
  *       therefore is always positive.)
  */
static size_t
dropt_ssgetfreespace(const dropt_stringstream* ss)
{
    assert(ss != NULL);
    assert(ss->maxSize > 0);
    assert(ss->maxSize > ss->used);
    return ss->maxSize - ss->used;
}


/** dropt_ssresize
  *
  *     Resizes a dropt_stringstream's internal buffer.  If the requested
  *     size is less than the amount of buffer already in use, the buffer
  *     will be shrunk to the minimum size necessary.
  *
  * PARAMETERS:
  *     IN/OUT ss : The dropt_stringstream.
  *     IN n      : The desired buffer size, in dropt_char-s.
  *
  * RETURNS:
  *     The new size of the dropt_stringstream's buffer in dropt_char-s,
  *       including space for a terminating NUL.
  */
static size_t
dropt_ssresize(dropt_stringstream* ss, size_t n)
{
    assert(ss != NULL);

    /* Don't allow shrinking if it will truncate the string. */
    if (n < ss->maxSize) { n = MAX(n, ss->used + 1 /* NUL */); }

    /* There should always be a buffer to point to. */
    assert(n > 0);

    if (n != ss->maxSize)
    {
        dropt_char* p = dropt_safe_realloc(ss->string, n, sizeof *ss->string);
        if (p != NULL)
        {
            ss->string = p;
            ss->maxSize = n;
            assert(ss->maxSize > 0);
         }
    }
    return ss->maxSize;
}


/** dropt_ssclear
  *
  *     Clears and re-initializes a dropt_stringstream.
  *
  * PARAMETERS:
  *     IN/OUT ss : The dropt_stringstream
  */
void
dropt_ssclear(dropt_stringstream* ss)
{
    assert(ss != NULL);

    ss->string[0] = DROPT_TEXT_LITERAL('\0');
    ss->used = 0;

    dropt_ssresize(ss, default_stringstream_buffer_size);
}


/** dropt_ssfinalize
  *
  *     Finalizes a dropt_stringstream; returns the contained string and
  *     destroys the dropt_stringstream.
  *
  * PARAMETERS:
  *     IN/OUT ss : The dropt_stringstream.
  *
  * RETURNS:
  *     The dropt_stringstream's string, which is always NUL-terminated.
  *       Note that the caller assumes ownership of the returned string and
  *       is responsible for calling free() on it when no longer needed.
  */
dropt_char*
dropt_ssfinalize(dropt_stringstream* ss)
{
    dropt_char* s;
    assert(ss != NULL);

    /* Shrink to fit. */
    dropt_ssresize(ss, 0);

    s = ss->string;
    ss->string = NULL;

    dropt_ssclose(ss);

    return s;
}


/** dropt_ssgetstring
  *
  * PARAMETERS:
  *     IN ss : The dropt_stringstream.
  *
  * RETURNS:
  *     The dropt_stringstream's string, which is always NUL-terminated.
  *       The returned string will no longer be valid if further operations
  *       are performed on the dropt_stringstream or if the
  *       dropt_stringstream is closed.
  */
const dropt_char*
dropt_ssgetstring(const dropt_stringstream* ss)
{
    assert(ss != NULL);
    return ss->string;
}


/** dropt_vssprintf
  *
  *     Appends a formatted string with vprintf semantics to a
  *     dropt_stringstream.
  *
  * PARAMETERS:
  *     IN/OUT ss : The dropt_stringstream.
  *     IN format : printf-style format specifier.  Must not be NULL.
  *     IN args   : Arguments to insert into the formatted string.
  *
  * RETURNS:
  *     The number of characters written to the dropt_stringstream,
  *       excluding the NUL-terminator.
  *     Returns a negative value on error.
  */
int
dropt_vssprintf(dropt_stringstream* ss, const dropt_char* format, va_list args)
{
    int n;
    va_list argsCopy;
    assert(ss != NULL);
    assert(format != NULL);

    va_copy(argsCopy, args);
    n = dropt_vsnprintf(NULL, 0, format, argsCopy);
    va_end(argsCopy);

    if (n > 0)
    {
        size_t available = dropt_ssgetfreespace(ss);
        if ((unsigned int) n >= available)
        {
            /* It's possible that newSize < ss->maxSize if
             * GROWN_STRINGSTREAM_BUFFER_SIZE overflows, but it should be
             * safe since we'll recompute the available space.
             */
            size_t newSize = GROWN_STRINGSTREAM_BUFFER_SIZE(ss->maxSize, n);
            dropt_ssresize(ss, newSize);
            available = dropt_ssgetfreespace(ss);
        }
        assert(available > 0); /* Space always is reserved for NUL. */

        /* snprintf's family of functions return the number of characters
         * that would be output with a sufficiently large buffer, excluding
         * NUL.
         */
        n = dropt_vsnprintf(ss->string + ss->used, available, format, args);

        /* We couldn't allocate enough space. */
        if ((unsigned int) n >= available) { n = -1; }

        if (n > 0) { ss->used += n; }
    }
    return n;
}


/** See dropt_vssprintf. */
int
dropt_ssprintf(dropt_stringstream* ss, const dropt_char* format, ...)
{
    int n;

    va_list args;
    va_start(args, format);
    n = dropt_vssprintf(ss, format, args);
    va_end(args);

    return n;
}
#endif /* DROPT_NO_STRING_BUFFERS */