Skip to content

Commit

Permalink
Add insert method for String type (#786)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcauberer authored Feb 16, 2025
1 parent a94b5dc commit bee2a40
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
39 changes: 39 additions & 0 deletions std/runtime/string_rt.spice
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,45 @@ public p String.append(const char c) {
}
}

p String.prepareInsert<IntLong>(unsigned IntLong position, unsigned long strLength) {
// Check if the position is out of bounds
if position > this.length {
panic(Error("Insert index out of bounds"));
}
// Check if we need to re-allocate memory
while this.capacity < this.length + strLength {
this.resize(this.capacity * RESIZE_FACTOR);
}
this.length += strLength;
unsafe {
// Shift all chars, starting from the back
for unsigned long i = this.length; i > position; i-- {
this.contents[i] = this.contents[i - strLength];
}
}
}

public p String.insert<IntLong>(unsigned IntLong position, string str) {
const unsigned long strLength = len(str);
this.prepareInsert(position, strLength);
unsafe {
for unsigned long i = 0l; i < strLength; i++ {
this.contents[position + i] = str[i];
}
}
}

public p String.insert<IntLong>(unsigned IntLong position, const String& str) {
this.insert(position, str.getRaw());
}

public p String.insert<IntLong>(unsigned IntLong position, char c) {
this.prepareInsert(position, 1l);
unsafe {
this.contents[position] = c;
}
}

/**
* Concatenates two strings and returns the result
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ f<int> main() {
assert s.getRaw() == "This was a demo. And because this was a d, it was a demonstration.";
assert s.replaceAll('t', 'y') == 4;
assert s.getRaw() == "This was a demo. And because yhis was a d, iy was a demonsyrayion.";
String test = String("Test");
test.insert(4, '.');
test.insert(2, "--");
test.insert(4, String("foo"));
assert test.getRaw() == "Te--foost.";

printf("All assertions passed!");
}

0 comments on commit bee2a40

Please sign in to comment.