I am writing Typst code that needs to append a lot of strings onto each other. They are generated one by one, so - as someone with a long history in Java - I would like to write something like:
#let buf = string-buffer()
#buf.add("hello ")
#buf.add("world")
#buf.to-string()
It would be good if I could do this in linear time - so no #let buf = buf + str2, which would copy buf and therefore give me quadratic runtime.
I have two questions about this, which are of independent interest to me. First, is there already a mechanism in Typst that can do what I’m asking? For instance, is the += operator for strings constant time in the length of the left-hand side, so that a sequence of += operations would run in time linear in the total length of the concatenated string?
Second, how would I implement a string buffer “class” myself? I thought the slightly sneaky, pseudo object-oriented code below might work, but it fails on parts.push with “error: variables from outside the function are read-only and cannot be modified”.
#let string-buffer() = {
let parts = ()
let write(x) = parts.push(x)
let to-string() = parts.join("")
("write": write, "to-string": to-string)
}
#let buf = string-buffer()
#{(buf.write)("hello ")}
#{(buf.write)("world")}
#{buf.to-string()}