summaryrefslogtreecommitdiffstats
path: root/source/core/slang-string.h
blob: ed333f8e8ad9f2d5686974fb04a47d64ae210a2a (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
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
#ifndef FUNDAMENTAL_LIB_STRING_H
#define FUNDAMENTAL_LIB_STRING_H

#include <string.h>
#include <cstdlib>
#include <stdio.h>

#include "smart-pointer.h"
#include "common.h"
#include "hash.h"
#include "secure-crt.h"

#include <new>

namespace Slang
{
	class _EndLine
	{};
	extern _EndLine EndLine;

	// in-place reversion, works only for ascii string
	inline void ReverseInternalAscii(char * buffer, int length)
	{
		int i, j;
		char c;
		for (i = 0, j = length - 1; i<j; i++, j--)
		{
			c = buffer[i];
			buffer[i] = buffer[j];
			buffer[j] = c;
		}
	}
	template<typename IntType>
	inline int IntToAscii(char * buffer, IntType val, int radix)
	{
		int i = 0;
		IntType sign;
		sign = val;
		if (sign < 0)
			val = (IntType)(0 - val);
		do
		{
			int digit = (val % radix);
			if (digit <= 9)
				buffer[i++] = (char)(digit + '0');
			else
				buffer[i++] = (char)(digit - 10 + 'A');
		} while ((val /= radix) > 0);
		if (sign < 0)
			buffer[i++] = '-';
		buffer[i] = '\0';
		return i;
	}

	inline bool IsUtf8LeadingByte(char ch)
	{
		return (((unsigned char)ch) & 0xC0) == 0xC0;
	}

	inline bool IsUtf8ContinuationByte(char ch)
	{
		return (((unsigned char)ch) & 0xC0) == 0x80;
	}

    // A `StringRepresentation` provides the backing storage for
    // all reference-counted string-related types.
    class StringRepresentation : public RefObject
    {
    public:
        UInt length;
        UInt capacity;

        UInt getLength()
        {
            return length;
        }

        char* getData()
        {
            return (char*) (this + 1);
        }

        static StringRepresentation* createWithCapacityAndLength(UInt capacity, UInt length)
        {
            SLANG_ASSERT(capacity >= length);
            void* allocation = operator new(sizeof(StringRepresentation) + capacity + 1);
            StringRepresentation* obj = new(allocation) StringRepresentation();
            obj->capacity = capacity;
            obj->length = length;
            obj->getData()[length] = 0;
            return obj;
        }

        static StringRepresentation* createWithCapacity(UInt capacity)
        {
            return createWithCapacityAndLength(capacity, 0);
        }

        static StringRepresentation* createWithLength(UInt length)
        {
            return createWithCapacityAndLength(length, length);
        }

        StringRepresentation* cloneWithCapacity(UInt newCapacity)
        {
            StringRepresentation* newObj = createWithCapacityAndLength(newCapacity, length);
            memcpy(getData(), newObj->getData(), length + 1);
            return newObj;
        }

        StringRepresentation* clone()
        {
            return cloneWithCapacity(length);
        }

        StringRepresentation* ensureCapacity(UInt required)
        {
            if (capacity >= required) return this;

            UInt newCapacity = capacity;
            if (!newCapacity) newCapacity = 16; // TODO: figure out good value for minimum capacity

            while (newCapacity < required)
            {
                newCapacity = 2 * newCapacity;
            }

            return cloneWithCapacity(newCapacity);
        }
    };

    class String;

    struct UnownedStringSlice
    {
    public:

        char const* begin() const
        {
            return beginData;
        }

        char const* end() const
        {
            return endData;
        }

    private:
        char const* beginData;
        char const* endData;
    };

    struct StringSlice
    {
    public:
        StringSlice();

        StringSlice(String const& str);

        StringSlice(String const& str, UInt beginIndex, UInt endIndex);

        UInt getLength() const
        {
            return endIndex - beginIndex;
        }

        char const* begin() const
        {
            return representation ? representation->getData() + beginIndex : "";
        }

        char const* end() const
        {
            return begin() + getLength();
        }

    private:
        RefPtr<StringRepresentation> representation;
        UInt beginIndex;
        UInt endIndex;

        friend class String;

        StringSlice(RefPtr<StringRepresentation> const& representation, UInt beginIndex, UInt endIndex)
            : representation(representation)
            , beginIndex(beginIndex)
            , endIndex(endIndex)
        {}
    };

    /// String as expected by underlying platform APIs
    class OSString
    {
    public:
        OSString();
        OSString(wchar_t* begin, wchar_t* end);
        ~OSString();

        operator wchar_t const*() const
        {
            return begin();
        }

        wchar_t const* begin() const;
        wchar_t const* end() const;

    private:
        wchar_t* beginData;
        wchar_t* endData;
    };

	/*!
	@brief Represents a UTF-8 encoded string.
	*/

	class String
	{
        friend struct StringSlice;
		friend class StringBuilder;
	private:


        char* getData() const
        {
            return buffer ? buffer->getData() : "";
        }

        UInt getLength() const
        {
            return buffer ? buffer->getLength() : 0;
        }

        void ensureUniqueStorageWithCapacity(UInt capacity);
        char* prepareForAppend(UInt count);

        RefPtr<StringRepresentation> buffer;

        String(StringRepresentation* buffer)
            : buffer(buffer)
        {}

    public:
		static String FromWString(const wchar_t * wstr);
		static String FromWString(const wchar_t * wstr, const wchar_t * wend);
		static String FromWChar(const wchar_t ch);
		static String FromUnicodePoint(unsigned int codePoint);
		String()
		{
		}

		const char * begin() const
		{
			return getData();
		}
		const char * end() const
		{
			return getData() + getLength();
		}

        void append(int32_t value, int radix = 10);
        void append(uint32_t value, int radix = 10);
        void append(int64_t value, int radix = 10);
        void append(uint64_t value, int radix = 10);
        void append(float val, const char * format = "%g");
        void append(double val, const char * format = "%g");

        void append(char const* str);
        void append(const char* textBegin, char const* textEnd);
        void append(char chr);
        void append(String const& str);
        void append(StringSlice const& slice);

		String(int val, int radix = 10)
		{
            append(val, radix);
#if 0
            buffer = StringRepresentation::createWithLength(33);
			buffer->length = IntToAscii(getData(), val, radix);
			ReverseInternalAscii(getData(), getLength());
#endif
		}
		String(unsigned int val, int radix = 10)
		{
            append(val, radix);
#if 0
            buffer = StringRepresentation::createWithLength(33);
			buffer->length = IntToAscii(getData(), val, radix);
			ReverseInternalAscii(getData(), getLength());
#endif
		}
		String(long long val, int radix = 10)
		{
            append(val, radix);
#if 0
            buffer = StringRepresentation::createWithLength(65);
			buffer->length = IntToAscii(getData(), val, radix);
			ReverseInternalAscii(getData(), getLength());
#endif
		}
		String(float val, const char * format = "%g")
		{
            append(val, format);
#if 0
            buffer = StringRepresentation::createWithLength(128);
			sprintf_s(getData(), 128, format, val);
			buffer->length = (int)strnlen_s(begin(), 128);
#endif
		}
		String(double val, const char * format = "%g")
		{
            append(val, format);
#if 0
            buffer = StringRepresentation::createWithLength(128);
			sprintf_s(getData(), 128, format, val);
			buffer->length = (int)strnlen_s(begin(), 128);
#endif
		}
		String(const char * str)
		{
            append(str);
#if 0
			if (str)
			{
                buffer = StringRepresentation::createWithLength(strlen(str));
				memcpy(buffer.Ptr(), str, getLength() + 1);
			}
#endif
		}
        String(const char* textBegin, char const* textEnd)
		{
            append(textBegin, textEnd);
#if 0
			if (textBegin != textEnd)
			{
                buffer = StringRepresentation::createWithLength(textEnd - textBegin);
				memcpy(buffer.Ptr(), textBegin, getLength());
                buffer->getData()[getLength()] = 0;
			}
#endif
		}
		String(char chr)
		{
            append(chr);
#if 0
			if (chr)
			{
                buffer = StringRepresentation::createWithLength(1);
                buffer->getData()[0] = chr;
                buffer->getData()[1] = 0;
			}
#endif
		}
		String(String const& str)
		{
            buffer = str.buffer;
#if 0
			this->operator=(str);
#endif
		}
		String(String&& other)
		{
            buffer = _Move(other.buffer);
		}

        String(StringSlice const& slice)
        {
            append(slice);
        }

		~String()
		{
            buffer = 0;
		}

		String & operator=(const String & str)
		{
            buffer = str.buffer;
			return *this;
		}
		String & operator=(String&& other)
		{
            buffer = _Move(other.buffer);
            return *this;
		}
		char operator[](UInt id) const
		{
#if _DEBUG
			if (id < 0 || id >= getLength())
				throw "Operator[]: index out of range.";
#endif
			return begin()[id];
		}

		friend String operator+(const char*op1, const String & op2);
		friend String operator+(const String & op1, const char * op2);
		friend String operator+(const String & op1, const String & op2);

		StringSlice TrimStart() const
		{
			if (!buffer)
				return StringSlice();
			UInt startIndex = 0;
			while (startIndex < getLength() &&
				(getData()[startIndex] == ' ' || getData()[startIndex] == '\t' || getData()[startIndex] == '\r' || getData()[startIndex] == '\n'))
				startIndex++;
            return StringSlice(buffer, startIndex, getLength());
		}

		StringSlice TrimEnd() const
		{
			if (!buffer)
				return StringSlice();

			UInt endIndex = getLength();
			while (endIndex > 0 &&
				(getData()[endIndex-1] == ' ' || getData()[endIndex-1] == '\t' || getData()[endIndex-1] == '\r' || getData()[endIndex-1] == '\n'))
				endIndex--;

            return StringSlice(buffer, 0, endIndex);
		}

		StringSlice Trim() const
		{
			if (!buffer)
				return StringSlice();

			UInt startIndex = 0;
			while (startIndex < getLength() &&
				(getData()[startIndex] == ' ' || getData()[startIndex] == '\t'))
				startIndex++;
			UInt endIndex = getLength();
			while (endIndex > startIndex &&
				(getData()[endIndex-1] == ' ' || getData()[endIndex-1] == '\t'))
				endIndex--;

            return StringSlice(buffer, startIndex, endIndex);
		}

		StringSlice SubString(UInt id, UInt len) const
		{
			if (len == 0)
				return StringSlice();

            if (id + len > getLength())
				len = getLength() - id;
#if _DEBUG
			if (id < 0 || id >= getLength() || (id + len) > getLength())
				throw "SubString: index out of range.";
			if (len < 0)
				throw "SubString: length less than zero.";
#endif
            return StringSlice(buffer, id, id + len);
		}

		char const* Buffer() const
		{
            return getData();
		}

        OSString ToWString(UInt* len = 0) const;

		bool Equals(const String & str, bool caseSensitive = true)
		{
			if (caseSensitive)
				return (strcmp(begin(), str.begin()) == 0);
			else
			{
#ifdef _MSC_VER
				return (_stricmp(begin(), str.begin()) == 0);
#else
				return (strcasecmp(begin(), str.begin()) == 0);
#endif
			}
		}
		bool operator==(const char * strbuffer) const
		{
			return (strcmp(begin(), strbuffer) == 0);
		}

		bool operator==(const String & str) const
		{
			return (strcmp(begin(), str.begin()) == 0);
		}
		bool operator!=(const char * strbuffer) const
		{
			return (strcmp(begin(), strbuffer) != 0);
		}
		bool operator!=(const String & str) const
		{
			return (strcmp(begin(), str.begin()) != 0);
		}
		bool operator>(const String & str) const
		{
			return (strcmp(begin(), str.begin()) > 0);
		}
		bool operator<(const String & str) const
		{
			return (strcmp(begin(), str.begin()) < 0);
		}
		bool operator>=(const String & str) const
		{
			return (strcmp(begin(), str.begin()) >= 0);
		}
		bool operator<=(const String & str) const
		{
			return (strcmp(begin(), str.begin()) <= 0);
		}

		String ToUpper() const
		{
            String result;
            for (auto c : *this)
            {
                char d = (c >= 'a' && c <= 'z') ? (c - ('a' - 'A')) : c;
                result.append(d);
            }
            return result;
		}

		String ToLower() const
		{
            String result;
            for (auto c : *this)
            {
                char d = (c >= 'A' && c <= 'Z') ? (c - ('A' - 'a')) : c;
                result.append(d);
            }
            return result;
		}

		UInt Length() const
		{
			return getLength();
		}

		UInt IndexOf(const char * str, UInt id) const // String str
		{
			if (id < 0 || id >= getLength())
				return UInt(-1);
			auto findRs = strstr(begin() + id, str);
			UInt res = findRs ? findRs - begin() : -1;
			return res;
		}

		UInt IndexOf(const String & str, UInt id) const
		{
			return IndexOf(str.begin(), id);
		}

		UInt IndexOf(const char * str) const
		{
			return IndexOf(str, 0);
		}

		UInt IndexOf(const String & str) const
		{
			return IndexOf(str.begin(), 0);
		}

		UInt IndexOf(char ch, UInt id) const
		{
#if _DEBUG
			if (id < 0 || id >= getLength())
				throw "SubString: index out of range.";
#endif
			if (!buffer)
				return UInt(-1);
			for (UInt i = id; i < getLength(); i++)
				if (getData()[i] == ch)
					return i;
			return UInt(-1);
		}

		UInt IndexOf(char ch) const
		{
			return IndexOf(ch, 0);
		}

		UInt LastIndexOf(char ch) const
		{
			for (UInt i = getLength(); i > 0; i--)
				if (getData()[i-1] == ch)
					return i-1;
			return UInt(-1);
		}

		bool StartsWith(const char * str) const // String str
		{
			if (!buffer)
				return false;
			UInt strLen = strlen(str);
			if (strLen > getLength())
				return false;
			for (UInt i = 0; i < strLen; i++)
				if (str[i] != getData()[i])
					return false;
			return true;
		}

		bool StartsWith(const String & str) const
		{
			return StartsWith(str.begin());
		}

		bool EndsWith(char const * str)  const // String str
		{
			if (!buffer)
				return false;
			UInt strLen = strlen(str);
			if (strLen > getLength())
				return false;
			for (UInt i = strLen; i > 0; i--)
				if (str[i-1] != getData()[getLength() - strLen + i-1])
					return false;
			return true;
		}

		bool EndsWith(const String & str) const
		{
			return EndsWith(str.begin());
		}

		bool Contains(const char * str) const // String str
		{
			if (!buffer)
				return false;
			return (IndexOf(str) >= 0) ? true : false;
		}

		bool Contains(const String & str) const
		{
			return Contains(str.begin());
		}

		int GetHashCode() const
		{
			return Slang::GetHashCode((const char*)begin());
		}
	};

	class StringBuilder : public String
	{
	private:
        enum { InitialSize = 1024 };
	public:
		explicit StringBuilder(UInt bufferSize = InitialSize)
		{
            ensureUniqueStorageWithCapacity(bufferSize);
		}
		void EnsureCapacity(UInt size)
		{
            ensureUniqueStorageWithCapacity(size);
		}
		StringBuilder & operator << (char ch)
		{
			Append(&ch, 1);
			return *this;
		}
		StringBuilder & operator << (int val)
		{
			Append(val);
			return *this;
		}
		StringBuilder & operator << (unsigned int val)
		{
			Append(val);
			return *this;
		}
		StringBuilder & operator << (long long val)
		{
			Append(val);
			return *this;
		}
		StringBuilder & operator << (float val)
		{
			Append(val);
			return *this;
		}
		StringBuilder & operator << (double val)
		{
			Append(val);
			return *this;
		}
		StringBuilder & operator << (const char * str)
		{
			Append(str, strlen(str));
			return *this;
		}
		StringBuilder & operator << (const String & str)
		{
			Append(str);
			return *this;
		}
		StringBuilder & operator << (const _EndLine)
		{
			Append('\n');
			return *this;
		}
		void Append(char ch)
		{
			Append(&ch, 1);
		}
		void Append(float val)
		{
			char buf[128];
			sprintf_s(buf, 128, "%g", val);
			int len = (int)strnlen_s(buf, 128);
			Append(buf, len);
		}
		void Append(double val)
		{
			char buf[128];
			sprintf_s(buf, 128, "%g", val);
			int len = (int)strnlen_s(buf, 128);
			Append(buf, len);
		}
		void Append(unsigned int value, int radix = 10)
		{
			char vBuffer[33];
			int len = IntToAscii(vBuffer, value, radix);
			ReverseInternalAscii(vBuffer, len);
			Append(vBuffer);
		}
		void Append(int value, int radix = 10)
		{
			char vBuffer[33];
			int len = IntToAscii(vBuffer, value, radix);
			ReverseInternalAscii(vBuffer, len);
			Append(vBuffer);
		}
		void Append(long long value, int radix = 10)
		{
			char vBuffer[65];
			int len = IntToAscii(vBuffer, value, radix);
			ReverseInternalAscii(vBuffer, len);
			Append(vBuffer);
		}
		void Append(const String & str)
		{
			Append(str.Buffer(), str.Length());
		}
		void Append(const char * str)
		{
			Append(str, strlen(str));
		}
		void Append(const char * str, UInt strLen)
		{
            append(str, str + strLen);
		}

#if 0
		int Capacity()
		{
			return bufferSize;
		}

		char * Buffer()
		{
			return buffer;
		}

		int Length()
		{
			return length;
		}
#endif

		String ToString()
		{
            return *this;
		}

		String ProduceString()
		{
            return *this;
		}

#if 0
		String GetSubString(int start, int count)
		{
			String rs;
			rs.buffer = new char[count + 1];
			rs.length = count;
			strncpy_s(rs.buffer.Ptr(), count + 1, buffer + start, count);
			rs.buffer[count] = 0;
			return rs;
		}
#endif

#if 0
		void Remove(int id, int len)
		{
#if _DEBUG
			if (id >= length || id < 0)
				throw "Remove: Index out of range.";
			if (len < 0)
				throw "Remove: remove length smaller than zero.";
#endif
			int actualDelLength = ((id + len) >= length) ? (length - id) : len;
			for (int i = id + actualDelLength; i <= length; i++)
				buffer[i - actualDelLength] = buffer[i];
			length -= actualDelLength;
		}
#endif

		void Clear()
		{
            buffer = 0;
		}
	};

	int StringToInt(const String & str, int radix = 10);
	unsigned int StringToUInt(const String & str, int radix = 10);
	double StringToDouble(const String & str);
	float StringToFloat(const String & str);
}

#endif