-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
string_rt.spice
680 lines (596 loc) · 18.7 KB
/
string_rt.spice
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
#![core.compiler.alwaysKeepOnNameCollision = true]
import "std/type/error";
// Link external functions
// We intentionally do not use the memory_rt here to avoid dependency circles
ext f<heap char*> malloc(unsigned long);
ext f<heap char*> realloc(heap char*, unsigned long);
ext p free(heap char*);
ext p memcpy(heap char*, heap char*, unsigned long);
// Constants
const unsigned long INITIAL_ALLOC_COUNT = 5l;
const unsigned int RESIZE_FACTOR = 2;
/**
* Heap-allocated builtin String type to enable dynamic modification in contrast
* to the primitive string type.
*/
public type String struct {
heap char* contents // Pointer to the first char
unsigned long capacity // Allocated number of chars (without null terminator)
unsigned long length // Used number of chars
}
// Generic type definitions
type IntLong int|long;
type IntLongShort int|long|short;
type StrTy String|string;
type RawStrChar string|char;
type StrTyChar String|string|char;
public p String.ctor(const string value = "") {
this.length = getRawLength(value);
this.capacity = this.length > INITIAL_ALLOC_COUNT ? this.length * RESIZE_FACTOR : INITIAL_ALLOC_COUNT;
unsafe {
// Allocate space for the initial number of elements
unsigned long requiredBytes = this.capacity + 1l; // +1 because of null terminator
this.contents = malloc(requiredBytes);
this.checkForOOM();
// Save initial value
memcpy(this.contents, (char*) value, this.length + 1l); // +1 because of null terminator
}
}
public p String.ctor(const char value) {
this.length = 1l;
this.capacity = INITIAL_ALLOC_COUNT;
unsafe {
// Allocate space for the initial number of elements
unsigned long requiredBytes = this.capacity + 1l; // +1 because of null terminator
this.contents = malloc(requiredBytes);
this.checkForOOM();
// Save initial value
this.contents[0] = value;
this.contents[1] = '\0';
}
}
public p String.ctor(const String& value) {
this.length = value.length;
this.capacity = value.capacity;
unsafe {
// Allocate space
unsigned long requiredBytes = this.capacity + 1l; // +1 because of null terminator
this.contents = malloc(requiredBytes);
this.checkForOOM();
// Copy the contents from the other string
memcpy(this.contents, value.contents, value.length + 1l); // +1 because of null terminator
}
}
public p String.ctor<IntLong>(IntLong initialSize) {
this.length = (unsigned long) initialSize;
this.capacity = initialSize > INITIAL_ALLOC_COUNT ? (unsigned long) initialSize * RESIZE_FACTOR : INITIAL_ALLOC_COUNT;
unsafe {
// Allocate space for the initial number of elements
unsigned long requiredBytes = this.capacity + 1l; // +1 because of null terminator
this.contents = malloc(requiredBytes);
this.checkForOOM();
// Save the initial value
this.contents[0] = '\0';
}
}
public p String.dtor() {
unsafe {
free(this.contents);
}
}
/**
* Appends the given string to the current one
*
* @param appendix String to be appended
*/
public p String.append(const string appendix) {
const unsigned long appendixLength = getRawLength(appendix);
// Check if we need to re-allocate memory
while this.capacity < this.length + appendixLength {
this.resize(this.capacity * RESIZE_FACTOR);
}
// Save data
unsafe {
for unsigned long i = 0l; i < appendixLength + 1l; i++ { // +1 because of null terminator
this.contents[this.length++] = appendix[i];
}
}
this.length--; // Remove null terminator
}
/**
* Appends the given String to the current one
*
* @param appendix String to be appended
*/
public p String.append(const String& appendix) {
this.append(appendix.getRaw());
}
/**
* Appends the given char to the string and resize it if needed
*
* @param c Char to append
*/
public p String.append(const char c) {
// Check if we need to re-allocate memory
if this.capacity < this.length + 1l {
this.resize(this.capacity * RESIZE_FACTOR);
}
// Insert the char at the right position
unsafe {
this.contents[this.length++] = c;
this.contents[this.length] = '\0';
}
}
/**
* Concatenates two strings and returns the result
*
* @parem a String a
* @param b String b
* @return Concatenated string
*/
public f<String> operator+<StrTy, StrTyChar>(const StrTy& a, const StrTyChar& b) {
result = String(a);
result.append(b);
}
/**
* Concatenates b to the end of a
*
* @param a String a
* @param b String/string/char b
*/
public p operator+=<StrTyChar>(String& a, const StrTyChar& b) {
a.append(b);
}
/**
* Concatenates the given string with itself n times.
*
* @param str Input string
* @param n Multiplication operand
* @return Result string
*/
public f<String> operator*<IntLongShort>(const String& str, const IntLongShort n) {
// Shortcuts
if n < 1 { return String(); }
if n == 1 { return str; }
// Copy the input string
result = String(str);
const unsigned long newLength = n * str.length;
result.reserve(newLength);
// Save the value
unsafe {
for unsigned long i = 0l; i < newLength; i++ {
result.contents[i] = str.contents[i % str.length];
}
result.contents[newLength] = '\0';
}
result.length = newLength;
}
/**
* Concatenates the given string with itself n times
*
* @param n Multiplication operand
* @param str Input string
* @return Result string
*/
public f<String> operator*<IntLongShort>(const IntLongShort n, const String& str) {
return str * n;
}
/**
* Concatenates this string with itself n times
*
* @param str Input string
* @param n Multiplication operand
*/
public p operator*=<IntLongShort>(String& str, const IntLongShort n) {
// Cancel if operand is less than 2
if n < 2 { return; }
// Reserve new length
unsigned long newLength = n * str.length;
str.reserve(newLength);
// Save the value
unsafe {
for unsigned long i = 0l; i < newLength; i++ {
str.contents[i] = str.contents[i % str.length];
}
str.contents[newLength] = '\0';
}
str.length = newLength;
}
/**
* Checks if two strings have the same value
*
* @param a First input string
* @param b Second input string
* @return Equal or not
*/
public f<bool> operator==(const String& a, const String& b) {
// Compare sizes
if a.length != b.length { return false; }
// Compare contents
unsafe {
for unsigned long i = 0l; i < a.length; i++ {
if a.contents[i] != b.contents[i] {
return false;
}
}
}
return true;
}
public f<bool> operator==(const String& a, string b) {
return isRawEqual(a.getRaw(), b);
}
public f<bool> operator==(string a, const String& b) {
return isRawEqual(a, b.getRaw());
}
/**
* Checks if two strings have not the same value
*
* @param a First input string
* @param b Second input string
* @return Not equal or not
*/
public f<bool> operator!=(const String& a, const String& b) {
return !(a == b);
}
public f<bool> operator!=(const String& a, const string& b) {
return !(a == b);
}
public f<bool> operator!=(const string& a, const String& b) {
return !(a == b);
}
/**
* Get the raw and immutable string from this container instance
*
* @return Raw immutable string
*/
public inline f<string> String.getRaw() {
unsafe {
return (string) this.contents;
}
}
/**
* Retrieve the current length of the string
*
* @return Current length of the string
*/
public inline f<unsigned long> String.getLength() {
return this.length;
}
/**
* Check if the string is empty
*/
public inline f<bool> String.isEmpty() {
return this.length == 0;
}
/**
* Retrieve the current capacity of the string
*
* @return Current capacity of the string
*/
public inline f<unsigned long> String.getCapacity() {
return this.capacity;
}
/**
* Checks if the string exhausts its capacity
*
* @return Full or not full
*/
public inline f<bool> String.isFull() {
return this.length == this.capacity;
}
/**
* Replaces the current contents of the string with an empty string
*/
public p String.clear() {
this.length = 0l;
unsafe {
this.contents[0] = '\0';
}
}
/**
* Searches for a substring in a string. Returns -1 if the string was not found.
*
* @param startIndex Index where to start the search
* @return Index, where the substring was found / -1
*/
public f<long> String.find(string needle, unsigned long startIndex = 0l) {
// Return -1 if the startIndex is out of bounds
if startIndex >= this.length { return (long) -1l; }
const unsigned long needleLength = getRawLength(needle);
// Return false if the needle is longer than the haystack
if this.length < needleLength { return (long) -1l; }
// Search needle in haystack
for unsigned long idx = startIndex; idx <= this.length - needleLength; idx++ {
// Start matching at startIdx
for unsigned long charIdx = 0l; charIdx < needleLength; charIdx++ {
unsafe {
if this.contents[idx + charIdx] != needle[charIdx] {
continue 2;
}
}
}
// Whole string was matched
return idx;
}
return (long) -1l;
}
/**
* Searches for a substring in a string. Returns -1 if the string was not found.
*
* @param startIndex Index where to start the search
* @return Index, where the substring was found / -1
*/
public f<long> String.find(string needle, unsigned int startIndex) {
return this.find(needle, (unsigned long) startIndex);
}
/**
* Searches for a subchar in a string. Returns -1 if the char was not found.
*
* @param startIndex Index where to start the search
* @return Index, where the subchar was found / -1
*/
public f<long> String.find(char needle, unsigned long startIndex = 0l) {
const String needleStr = String(needle);
return this.find(needleStr.getRaw(), startIndex);
}
/**
* Searches for a substring in a string from the back. Returns -1 if the string was not found.
*
* @param startIndex Index where to start the search
* @return Index, where the substring was found / -1
*/
public f<long> String.rfind(string needle, unsigned long startIndex = 0l) {
// Return -1 if the startIndex is out of bounds
if startIndex >= this.length { return (long) -1l; }
const unsigned long needleLength = getRawLength(needle);
// Return false if the needle is longer than the haystack
if this.length < needleLength { return (long) -1l; }
if startIndex == 0l { startIndex = this.length - needleLength; }
// Search needle in haystack
for unsigned long idx = startIndex; idx >= 0; idx-- {
// Start matching at startIdx
for unsigned long charIdx = 0l; charIdx < needleLength; charIdx++ {
unsafe {
if this.contents[idx + charIdx] != needle[charIdx] {
continue 2;
}
}
}
// Whole string was matched
return idx;
}
return (long) -1l;
}
/**
* Searches for a substring in a string from the back. Returns -1 if the string was not found.
*
* @param startIndex Index where to start the search
* @return Index, where the substring was found / -1
*/
public f<long> String.rfind(string needle, unsigned int startIndex) {
return this.rfind(needle, (unsigned long) startIndex);
}
/**
* Searches for a subchar in a string from the back. Returns -1 if the char was not found.
*
* @param startIndex Index where to start the search
* @return Index, where the subchar was found / -1
*/
public f<long> String.rfind(char needle, unsigned long startIndex = 0l) {
const String needleStr = String(needle);
return this.rfind(needleStr.getRaw(), startIndex);
}
/**
* Checks if the string contains a substring
*
* @param needle Substring to search for
* @return Found or not
*/
public inline f<bool> String.contains(string needle) {
return this.find(needle) != -1l;
}
/**
* Checks if the string starts with a given prefix
*
* @param prefix Prefix to check for
* @return Starts with prefix or not
*/
public f<bool> String.startsWith(string prefix) {
return this.find(prefix) == 0l;
}
/**
* Checks if the string ends with a given suffix
*
* @param prefix Suffix to check for
* @return Ends with suffix or not
*/
public f<bool> String.endsWith(string suffix) {
const unsigned long index = this.length - getRawLength(suffix);
return this.rfind(suffix) == index;
}
/**
* Reverse the string
*/
public p String.reverse() {
unsafe {
for unsigned long i = 0l; i < this.length / 2l; i++ {
unsigned long currentUpperIdx = this.length - i - 1l;
this.contents[i] ^= this.contents[currentUpperIdx];
this.contents[currentUpperIdx] ^= this.contents[i];
this.contents[i] ^= this.contents[currentUpperIdx];
}
}
}
/**
* Replace occurrence of substring with the replacement string
*
* @param needle Substring to replace
* @param replacement Replacement for the substring
*/
public f<bool> String.replace(
string needle,
string replacement,
unsigned long startIdx = 0l
) {
// Abort, if needle or replacement are nullptrs
if (char*) needle == nil<char*> || (char*) replacement == nil<char*> {
return false;
}
// Find occurrence
startIdx = this.find(needle, startIdx);
// Return if not found
if startIdx == -1l { return false; }
// Calculate metrics
const unsigned long needleLength = getRawLength(needle);
const unsigned long replacementLength = getRawLength(replacement);
const unsigned long suffixLength = this.length - startIdx - needleLength;
const unsigned long finalLength = this.length - needleLength + replacementLength;
// Resize the string if required
while this.capacity < finalLength {
this.resize(this.capacity * RESIZE_FACTOR);
}
unsafe {
// Move the suffix to the left or right
const heap char* stringAddr = this.contents;
const heap char* startAddr = stringAddr + startIdx;
if needleLength != replacementLength {
const heap char* oldSuffixAddr = startAddr + needleLength;
const heap char* newSuffixAddr = startAddr + replacementLength;
memcpy(newSuffixAddr, oldSuffixAddr, suffixLength + 1l); // +1 because of null terminator
}
// Replace needle with replacement
memcpy(startAddr, (char*) replacement, replacementLength);
}
// Update length
this.length = finalLength;
return true;
}
/**
* Replace all occurrences of substring with the replacement string
*
* @param needle Substring to replace
* @param replacement Replacement for the substring
*/
public f<unsigned long> String.replaceAll(string needle, string replacement) {
unsigned long startIdx = 0l;
unsigned long foundOccurrences = 0l;
const unsigned long needleLength = getRawLength(needle);
const unsigned long replacementLength = getRawLength(replacement);
while startIdx <= this.length - needleLength {
if !this.replace(needle, replacement, startIdx) {
break;
}
startIdx += replacementLength;
foundOccurrences++;
}
return foundOccurrences;
}
public f<unsigned long> String.replaceAll(char needle, char replacement) {
const String needleStr = String(needle);
const String replacementStr = String(replacement);
return this.replaceAll(needleStr.getRaw(), replacementStr.getRaw());
}
/**
* Returns the substring of the current string, starting at position `startIndex` with
* the length of `length`.
*
* @param startIndex Substring start index
* @param length Length of substring
* @return Substring
*/
public f<String> String.getSubstring<IntLongShort>(unsigned IntLongShort startIdx, long length = -1l) {
// Return empty string if the length is 0 or the startIndex is out of bounds
if length == 0l || startIdx >= this.length {
return String("");
}
// Get everything after startIndex if length is -1
if length == -1l {
length = this.length - startIdx;
}
// Do not exceed original string length
if startIdx + length > this.length {
length = this.length - startIdx;
}
// Get substring
String substring = String("");
substring.reserve(length);
const unsigned long endIdx = startIdx + length;
for unsigned long charIndex = (unsigned long) startIdx; charIndex < endIdx; charIndex++ {
unsafe {
substring.contents[charIndex - startIdx] = this.contents[charIndex];
}
}
// Terminate string
unsafe {
substring.contents[length] = '\0';
}
// Return the substring
return substring;
}
/**
* Reserves `charCount` items
*
* @param charCount Number of chars to reserve for the string
*/
public p String.reserve<IntLongShort>(unsigned IntLongShort charCount) {
if charCount > this.capacity {
this.resize((unsigned long) charCount);
}
}
/**
* Re-allocates heap space for the string contents
*
* @param newLength new length of the string after resizing
*/
p String.resize(unsigned long newLength) {
// Allocate the new memory
unsafe {
heap char* oldAddress = this.contents;
unsigned long requiredBytes = newLength + 1l; // +1 because of null terminator
this.contents = realloc(oldAddress, requiredBytes);
this.checkForOOM();
}
// Set new capacity
this.capacity = newLength;
}
p String.checkForOOM() {
if this.contents == nil<heap byte*> {
panic(Error("Could not allocate enough memory for dynamic string object"));
}
}
// ======================================================= Static functions ======================================================
/**
* Returns the length of a string
*
* @param input Input string
* @return Length of the input string
*/
public f<unsigned long> getRawLength(string input) {
// Handle nullptr gracefully
if (char*) input == nil<char*> { return 0l; }
// Otherwise count the chars until the null terminator
result = 0l;
while input[result] != '\0' {
result++;
}
}
/**
* Checks the equality of two raw strings
*
* @param lhs First input raw string
* @param rhs Second input raw string
* @return Equality of lhs and rhs
*/
public f<bool> isRawEqual(string lhs, string rhs) {
unsigned long lhsLength = getRawLength(lhs);
unsigned long rhsLength = getRawLength(rhs);
// Return false immediately if length does not match
if lhsLength != rhsLength { return false; }
// Compare chars
for unsigned long i = 0l; i < lhsLength; i++ {
if lhs[i] != rhs[i] {
return false;
}
}
return true;
}