StringBuf
is a growable string buffer for efficient incremental
string building. Unlike String.append (which allocates a new string on
every call), StringBuf tracks capacity and grows geometrically, giving
amortized O(1) appends.
Installation
(load "git@github.com:carpentry-org/strbuf@0.3.0")
Usage
(let [sb (StringBuf.create)]
(do
(StringBuf.append-str &sb "hello")
(StringBuf.append-char &sb \space)
(StringBuf.append-str &sb "world")
(println* &(StringBuf.str &sb))))
Ownership
Buffers are managed like any other Carp value: an owned StringBuf is
deleted when it goes out of scope, copied by @, and moved when it is
passed on. You never call StringBuf.delete yourself.
To get a String out of a buffer, pick by what you want to happen to the
buffer: str copies the contents and leaves the buffer alone, to-string
copies them and resets the buffer for reuse, and into-string consumes the
buffer and hands its allocation to the String without copying.
append-bytes
(Fn [(Ref StringBuf a), (Ref (Array Byte) b)] ())
appends raw bytes to the buffer.
append-double
(Fn [(Ref StringBuf a), Double] ())
appends a double as its string representation.
append-float
(Fn [(Ref StringBuf a), Float] ())
appends a float as its string representation.
append-int
(Fn [(Ref StringBuf a), Int] ())
appends an integer as its decimal string representation.
append-long
(Fn [(Ref StringBuf a), Long] ())
appends a long as its decimal string representation.
delete
(Fn [StringBuf] ())
frees the buffer. This implements the delete interface, which
means Carp calls it for you when an owned buffer goes out of scope; you should
not need to call it directly.
into-string
(Fn [StringBuf] String)
consumes the buffer and returns its contents as an owned String. The buffer's allocation is handed over to the String, so nothing is copied and nothing is freed.
prn
(Fn [(Ref StringBuf a)] String)
(prn sb)
returns a copy of the buffer contents as a String without modifying the buffer.
str
(Fn [(Ref StringBuf a)] String)
returns a copy of the buffer contents as a String without modifying the buffer.
to-string
(Fn [(Ref StringBuf a)] String)
returns the buffer contents as an owned String and resets the buffer to empty. The buffer's allocation is kept for reuse.
with-capacity
(Fn [Int] StringBuf)
creates an empty StringBuf with the given initial capacity.