Skip to content

Commit c86c0c6

Browse files
authored
Don't reallocate StringBuffer when flushing (#939)
I think that the allocation here is not needed, so let's avoid it. Also adds more tests for the StringBuffer.
1 parent 5d16082 commit c86c0c6

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

examples/stdlib/stringbuffer.check

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
hello, world
2+
3+
Effekt = Effekt
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import stringbuffer
2+
3+
def main() = stringbuffer::examples::main()

libraries/common/stringbuffer.effekt

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,11 @@ def stringBuffer[A] { prog: => A / StringBuffer }: A = {
3535
resume(())
3636
}
3737
def flush() = {
38-
// resize buffer to strip trailing zeros that otherwise would be converted into 0x00 characters
38+
// resize (& copy) buffer to strip trailing zeros that otherwise would be converted into 0x00 characters
3939
val str = bytearray::resize(buffer, pos).toString()
40-
// after flushing, the stringbuffer should be empty again
41-
buffer = bytearray::allocate(initialCapacity)
40+
// NOTE: Keep the `buffer` as-is (no wipe, no realloc),
41+
// just reset the `pos` in case we want to use it again.
42+
pos = 0
4243
resume(str)
4344
}
4445
}
@@ -55,11 +56,22 @@ def s { prog: () => Unit / { literal, splice[String] } }: String =
5556
namespace examples {
5657
def main() = {
5758
with stringBuffer
59+
5860
do write("hello")
5961
do write(", world")
6062
// prints `hello, world`
6163
println(do flush())
64+
6265
// prints the empty string
6366
println(do flush())
67+
68+
do write("Ef")
69+
do write("fe")
70+
do write("kt")
71+
do write(" = ")
72+
do write("")
73+
do write("Effekt")
74+
// prints `Effekt = Effekt`
75+
println(do flush())
6476
}
6577
}

0 commit comments

Comments
 (0)