Skip to content

Commit

Permalink
Add StringStream implementation to std (#721)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcauberer authored Jan 19, 2025
1 parent d9bb728 commit 917c9fc
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 0 deletions.
74 changes: 74 additions & 0 deletions std/text/stringstream.spice
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* Helper data structure to construct strings.
* It is useful to avoid copying large strings around.
*/
public type StringStream struct {
String buffer
}

public p StringStream.ctor() {
// Initialize buffer empty
this.buffer = String();
}

public p StringStream.ctor(string input) {
// Initialize buffer with an initial string
this.buffer = String(input);
}

public p StringStream.ctor(const String& input) {
// Initialize buffer with an initial string
this.buffer = input;
}

/**
* Clear the buffer
*/
public p StringStream.clear() {
this.buffer.clear();
}

/**
* Get the value of the buffer
*
* @return Resulting String object
*/
public f<const String&> StringStream.str() {
return this.buffer;
}

/**
* Append a raw string to the buffer
*/
#[ignoreUnusedReturnValue]
public f<StringStream&> operator<<(StringStream& ss, string input) {
ss.buffer += input;
return ss;
}

/**
* Append a String to the buffer
*/
#[ignoreUnusedReturnValue]
public f<StringStream&> operator<<(StringStream& ss, const String& input) {
ss.buffer += input;
return ss;
}

/**
* Append a single char to the buffer
*/
#[ignoreUnusedReturnValue]
public f<StringStream&> operator<<(StringStream& ss, char input) {
ss.buffer += input;
return ss;
}

/**
* Return end line character
*
* @return End line character
*/
public f<char> endl() {
return '\n';
}
1 change: 1 addition & 0 deletions test/test-files/std/text/stringstream/cout.out
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
All assertions passed!
30 changes: 30 additions & 0 deletions test/test-files/std/text/stringstream/source.spice
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import "std/text/stringstream";

f<int> main() {
// Basic usage with raw string literals
StringStream ss1;
ss1 << "Hello" << " World!";
assert ss1.str() == "Hello World!";

// Basic usage with String values
StringStream ss2 = StringStream(String("This "));
ss2 << String("is") << String(" a ") << String("test!") << endl();
assert ss2.str() == "This is a test!\n";

// Mixed usage
StringStream ss3 = StringStream("Hello");
ss3 << String(" fellow") << " Programmers" << endl();
assert ss3.str() == "Hello fellow Programmers\n";

// Usage spread over multiple lines
StringStream ss4 = StringStream();
ss4 << "This ";
ss4 << "is ";
ss4 << "a ";
ss4 << "multiline ";
ss4 << "test";
ss4 << endl();
assert ss4.str() == "This is a multiline test\n";

printf("All assertions passed!");
}

0 comments on commit 917c9fc

Please sign in to comment.