A growable string buffer for Carp.
(load "git@github.com:carpentry-org/strbuf@0.3.0")StringBuf provides amortized O(1) appends, unlike String.append which
allocates a new string on every call.
(let [sb (StringBuf.create)]
(do
(StringBuf.append-str &sb "HTTP/1.1 ")
(StringBuf.append-int &sb 200)
(StringBuf.append-str &sb " OK")
(StringBuf.append-crlf &sb)
(println* &(StringBuf.str &sb))))Buffers follow Carp's memory model like any other value. An owned StringBuf
is deleted when it goes out of scope, no matter where it lives: in a let, in
an array, inside a struct or sum type, returned from a function, or moved into
one. @ copies a buffer, and the copy is freed independently. You never call
StringBuf.delete yourself; it is there because it implements the delete
interface that the compiler calls for you.
Three functions hand you a String, and they differ in what happens to the
buffer:
strcopies the contents and leaves the buffer untouchedto-stringcopies the contents and resets the buffer for reuseinto-stringconsumes the buffer and hands its allocation to theString, so nothing is copied and nothing is freed
Use into-string when you build a string once and are done with the buffer,
and to-string when you keep appending to the same buffer afterwards.
(defn greeting [name]
(let-do [sb (StringBuf.create)]
(StringBuf.append-str &sb "hello, ")
(StringBuf.append-str &sb name)
(StringBuf.into-string sb)))StringBuf.create/StringBuf.with-capacity— constructorsStringBuf.append-str— append a stringStringBuf.append-char— append a single characterStringBuf.append-bytes— append raw bytesStringBuf.append-int— append integer as decimalStringBuf.append-long— append long as decimalStringBuf.append-double/StringBuf.append-float— append as stringStringBuf.append-bool— appendtrueorfalseStringBuf.append-crlf— append\r\nStringBuf.length— current byte countStringBuf.str/StringBuf.prn— copy as String, keep the buffer as isStringBuf.to-string— copy as String, reset the bufferStringBuf.into-string— consume the buffer, no copyStringBuf.clear— reset without freeing
carp -x --log-memory test/strbuf.carp
Have fun!