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

namespace Slang
{
    // TODO: this belongs in a different file:

    SLANG_RETURN_NEVER void signalUnexpectedError(char const* message)
    {
        // Can be useful to uncomment during debug when problem is on CI
        // printf("Unexpected: %s\n", message);
        throw InternalError(message);
    }

    SLANG_FORCE_INLINE static bool _isWhiteSpace(char c)
    {
        return c == ' ' || c == '\t';
    }

    // OSString

    OSString::OSString()
        : m_begin(nullptr)
        , m_end(nullptr)
    {}

    OSString::OSString(wchar_t* begin, wchar_t* end)
        : m_begin(begin)
        , m_end(end)
    {}

    void OSString::_releaseBuffer()
    {
        if (m_begin)
        {
            delete[] m_begin;
        }
    }

    void OSString::set(const wchar_t* begin, const wchar_t* end)
    {
        if (m_begin)
        {
            delete[] m_begin;
            m_begin = nullptr;
            m_end = nullptr;
        }
        const size_t len = end - begin;
        if (len > 0)
        {
            // TODO(JS): The allocation is only done this way to be compatible with the buffer being detached from an array
            // This is unfortunate, because it means that the allocation stores the size (and alignment fix), which is a shame because we know the size
            m_begin = new wchar_t[len + 1];
            memcpy(m_begin, begin, len * sizeof(wchar_t));
            // Zero terminate
            m_begin[len] = 0;
            m_end = m_begin + len;
        }
    }

    static const wchar_t kEmptyOSString[] = { 0 };

    wchar_t const* OSString::begin() const
    {
        return m_begin ? m_begin : kEmptyOSString;
    }

    wchar_t const* OSString::end() const
    {
        return m_end ? m_end : kEmptyOSString;
    }

    // UnownedStringSlice

    bool UnownedStringSlice::startsWith(UnownedStringSlice const& other) const
    {
        UInt thisSize = getLength();
        UInt otherSize = other.getLength();

        if (otherSize > thisSize)
            return false;

        return UnownedStringSlice(begin(), begin() + otherSize) == other;
    }

    bool UnownedStringSlice::startsWith(char const* str) const
    {
        return startsWith(UnownedTerminatedStringSlice(str));
    }


    bool UnownedStringSlice::endsWith(UnownedStringSlice const& other) const
    {
        UInt thisSize = getLength();
        UInt otherSize = other.getLength();

        if (otherSize > thisSize)
            return false;

        return UnownedStringSlice(
            end() - otherSize, end()) == other;
    }

    bool UnownedStringSlice::endsWith(char const* str) const
    {
        return endsWith(UnownedTerminatedStringSlice(str));
    }

    
    UnownedStringSlice UnownedStringSlice::trim() const
    {
        const char* start = m_begin;
        const char* end = m_end;

        while (start < end && _isWhiteSpace(*start)) start++;
        while (end > start && _isWhiteSpace(end[-1])) end--;
        return UnownedStringSlice(start, end);
    }


    // StringSlice

    StringSlice::StringSlice()
        : representation(0)
        , beginIndex(0)
        , endIndex(0)
    {}

    StringSlice::StringSlice(String const& str)
        : representation(str.m_buffer)
        , beginIndex(0)
        , endIndex(str.getLength())
    {}

    StringSlice::StringSlice(String const& str, UInt beginIndex, UInt endIndex)
        : representation(str.m_buffer)
        , beginIndex(beginIndex)
        , endIndex(endIndex)
    {}


    //

	_EndLine EndLine;

    String operator+(const char * op1, const String & op2)
	{
        String result(op1);
        result.append(op2);
        return result;
	}

	String operator+(const String & op1, const char * op2)
	{
        String result(op1);
        result.append(op2);
        return result;
	}

	String operator+(const String & op1, const String & op2)
	{
        String result(op1);
        result.append(op2);
        return result;
	}

	int StringToInt(const String & str, int radix)
	{
		if (str.startsWith("0x"))
			return (int)strtoll(str.getBuffer(), NULL, 16);
		else
			return (int)strtoll(str.getBuffer(), NULL, radix);
	}
	unsigned int StringToUInt(const String & str, int radix)
	{
		if (str.startsWith("0x"))
			return (unsigned int)strtoull(str.getBuffer(), NULL, 16);
		else
			return (unsigned int)strtoull(str.getBuffer(), NULL, radix);
	}
	double StringToDouble(const String & str)
	{
		return (double)strtod(str.getBuffer(), NULL);
	}
	float StringToFloat(const String & str)
	{
		return strtof(str.getBuffer(), NULL);
	}

#if 0
	String String::ReplaceAll(String src, String dst) const
	{
		String rs = *this;
		int index = 0;
		int srcLen = src.length;
		int len = rs.length;
		while ((index = rs.IndexOf(src, index)) != -1)
		{
			rs = rs.SubString(0, index) + dst + rs.SubString(index + srcLen, len - index - srcLen);
			len = rs.length;
		}
		return rs;
	}
#endif

	String String::fromWString(const wchar_t * wstr)
	{
#ifdef _WIN32
		return Slang::Encoding::UTF16->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t)));
#else
		return Slang::Encoding::UTF32->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t)));
#endif
	}

	String String::fromWString(const wchar_t * wstr, const wchar_t * wend)
	{
#ifdef _WIN32
		return Slang::Encoding::UTF16->ToString((const char*)wstr, (int)((wend - wstr) * sizeof(wchar_t)));
#else
		return Slang::Encoding::UTF32->ToString((const char*)wstr, (int)((wend - wstr) * sizeof(wchar_t)));
#endif
	}

	String String::fromWChar(const wchar_t ch)
	{
#ifdef _WIN32
		return Slang::Encoding::UTF16->ToString((const char*)&ch, (int)(sizeof(wchar_t)));
#else
		return Slang::Encoding::UTF32->ToString((const char*)&ch, (int)(sizeof(wchar_t)));
#endif
	}

	String String::fromUnicodePoint(unsigned int codePoint)
	{
		char buf[6];
		int len = Slang::EncodeUnicodePointToUTF8(buf, (int)codePoint);
		buf[len] = 0;
		return String(buf);
	}

	OSString String::toWString(Index* outLength) const
	{
		if (!m_buffer)
		{
            return OSString();
		}
		else
		{
			List<char> buf;
            switch(sizeof(wchar_t))
            {
            case 2:
                Slang::Encoding::UTF16->GetBytes(buf, *this);                
                break;

            case 4:
                Slang::Encoding::UTF32->GetBytes(buf, *this);                
                break;

            default:
                break;
            }

            auto length = Index(buf.getCount() / sizeof(wchar_t));
			if (outLength)
				*outLength = length;

            for(int ii = 0; ii < sizeof(wchar_t); ++ii)
    			buf.add(0);

            wchar_t* beginData = (wchar_t*)buf.getBuffer();
            wchar_t* endData = beginData + length;

			buf.detachBuffer();

            return OSString(beginData, endData);
		}
	}

    //

    void String::ensureUniqueStorageWithCapacity(Index requiredCapacity)
    {
        if (m_buffer && m_buffer->isUniquelyReferenced() && m_buffer->capacity >= requiredCapacity)
            return;

        Index newCapacity = m_buffer ? 2 * m_buffer->capacity : 16;
        if (newCapacity < requiredCapacity)
        {
            newCapacity = requiredCapacity;
        }

        Index length = getLength();
        StringRepresentation* newRepresentation = StringRepresentation::createWithCapacityAndLength(newCapacity, length);

        if (m_buffer)
        {
            memcpy(newRepresentation->getData(), m_buffer->getData(), length + 1);
        }

        m_buffer = newRepresentation;
    }

    char* String::prepareForAppend(Index count)
    {
        auto oldLength = getLength();
        auto newLength = oldLength + count;
        ensureUniqueStorageWithCapacity(newLength);
        return getData() + oldLength;
    }
    void String::appendInPlace(const char* chars, Index count)
    {
        SLANG_UNUSED(chars);

        if (count > 0)
        {
            SLANG_ASSERT(m_buffer && m_buffer->isUniquelyReferenced());

            auto oldLength = getLength();
            auto newLength = oldLength + count;

            char* dst = m_buffer->getData();

            // Make sure the input buffer is the same one returned from prepareForAppend
            SLANG_ASSERT(chars == dst + oldLength);
            // It has to fit within the capacity
            SLANG_ASSERT(newLength <= m_buffer->capacity);

            // We just need to modify the length
            m_buffer->length = newLength;

            // And mark with a terminating 0
            dst[newLength] = 0;
        }
    }

    void String::append(const char* textBegin, char const* textEnd)
    {
        auto oldLength = getLength();
        auto textLength = textEnd - textBegin;

        auto newLength = oldLength + textLength;

        ensureUniqueStorageWithCapacity(newLength);

        memcpy(getData() + oldLength, textBegin, textLength);
        getData()[newLength] = 0;
        m_buffer->length = newLength;
    }

    void String::append(char const* str)
    {
        if (str)
        {
            append(str, str + strlen(str));
        }
    }

    void String::append(char chr)
    {
        append(&chr, &chr + 1);
    }


    void String::appendChar(char chr)
    {
        append(&chr, &chr + 1);
    }

    void String::append(String const& str)
    {
        if (!m_buffer)
        {
            m_buffer = str.m_buffer;
            return;
        }

        append(str.begin(), str.end());
    }

    void String::append(StringSlice const& slice)
    {
        append(slice.begin(), slice.end());
    }

    void String::append(UnownedStringSlice const& slice)
    {
        append(slice.begin(), slice.end());
    }

    void String::append(int32_t value, int radix)
    {
        enum { kCount = 33 };
        char* data = prepareForAppend(kCount);
        auto count = IntToAscii(data, value, radix);
        ReverseInternalAscii(data, count);
        m_buffer->length += count;
    }

    void String::append(uint32_t value, int radix)
    {
        enum { kCount = 33 };
        char* data = prepareForAppend(kCount);
        auto count = IntToAscii(data, value, radix);
        ReverseInternalAscii(data, count);
        m_buffer->length += count;
    }

    void String::append(int64_t value, int radix)
    {
        enum { kCount = 65 };
        char* data = prepareForAppend(kCount);
        auto count = IntToAscii(data, value, radix);
        ReverseInternalAscii(data, count);
        m_buffer->length += count;
    }

    void String::append(uint64_t value, int radix)
    {
        enum { kCount = 65 };
        char* data = prepareForAppend(kCount);
        auto count = IntToAscii(data, value, radix);
        ReverseInternalAscii(data, count);
        m_buffer->length += count;
    }

    void String::append(float val, const char * format)
    {
        enum { kCount = 128 };
        char* data = prepareForAppend(kCount);
        sprintf_s(data, kCount, format, val);
        m_buffer->length += strnlen_s(data, kCount);
    }

    void String::append(double val, const char * format)
    {
        enum { kCount = 128 };
        char* data = prepareForAppend(kCount);
        sprintf_s(data, kCount, format, val);
        m_buffer->length += strnlen_s(data, kCount);
    }
}