summaryrefslogtreecommitdiffstats
path: root/source/core/slang-string-util.cpp
blob: 29f8dc0ca83c5e7f980c323d7a489a24e8ff680f (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
#include "slang-string-util.h"

namespace Slang {

/* static */void StringUtil::split(const UnownedStringSlice& in, char splitChar, List<UnownedStringSlice>& slicesOut)
{
    slicesOut.Clear();

    const char* start = in.begin();
    const char* end = in.end();

    while (start < end)
    {
        // Move cur so it's either at the end or at next split character
        const char* cur = start;
        while (cur < end && *cur != splitChar)
        {
            cur++;
        }

        // Add to output
        slicesOut.Add(UnownedStringSlice(start, cur));

        // Skip the split character, if at end we are okay anyway
        start = cur + 1;
    }
}


/* static */void StringUtil::append(const char* format, va_list args, StringBuilder& buf)
{
    int numChars = 0;

#if SLANG_WINDOWS_FAMILY
    numChars = _vscprintf(format, args);
#else
    {
        va_list argsCopy;
        va_copy(argsCopy, args);
        numChars = vsnprintf(nullptr, 0, format, argsCopy);
        va_end(argsCopy);
    }
#endif

    List<char> chars;
    chars.SetSize(numChars + 1);

#if SLANG_WINDOWS_FAMILY
    vsnprintf_s(chars.Buffer(), numChars + 1, _TRUNCATE, format, args);
#else
    vsnprintf(chars.Buffer(), numChars + 1, format, args);
#endif

    buf.Append(chars.Buffer(), numChars);
}

/* static */void StringUtil::appendFormat(StringBuilder& buf, const char* format, ...)
{
    va_list args;
    va_start(args, format);
    append(format, args, buf);
    va_end(args);
}

/* static */String StringUtil::makeStringWithFormat(const char* format, ...)
{
    StringBuilder builder;

    va_list args;
    va_start(args, format);
    append(format, args, builder);
    va_end(args);

    return builder;
}

} // namespace Slang