builder: add autofree compatibility; protect against b.str() twice in a row
parent
f2060d431e
commit
54b71242fe
|
@ -6,6 +6,7 @@ module strings
|
||||||
pub struct Builder {
|
pub struct Builder {
|
||||||
mut:
|
mut:
|
||||||
buf []byte
|
buf []byte
|
||||||
|
str_calls int
|
||||||
pub mut:
|
pub mut:
|
||||||
len int
|
len int
|
||||||
initial_size int = 1
|
initial_size int = 1
|
||||||
|
@ -78,9 +79,20 @@ pub fn (b &Builder) after(n int) string {
|
||||||
return string(copy)
|
return string(copy)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NB: in order to avoid memleaks and additional memory copies, after a call to b.str(),
|
||||||
|
// the builder b will be empty. The returned string *owns* the accumulated data so far.
|
||||||
pub fn (b mut Builder) str() string {
|
pub fn (b mut Builder) str() string {
|
||||||
|
b.str_calls++
|
||||||
|
if b.str_calls > 1 {
|
||||||
|
panic('builder.str() should be called just once.\n' +
|
||||||
|
'If you want to reuse a builder, call b.free() first.')
|
||||||
|
}
|
||||||
b.buf << `\0`
|
b.buf << `\0`
|
||||||
return string(b.buf,b.len)
|
s := string(b.buf,b.len)
|
||||||
|
bis := b.initial_size
|
||||||
|
b.buf = []byte{cap: bis}
|
||||||
|
b.len = 0
|
||||||
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn (b mut Builder) free() {
|
pub fn (b mut Builder) free() {
|
||||||
|
@ -91,5 +103,5 @@ pub fn (b mut Builder) free() {
|
||||||
s := b.initial_size
|
s := b.initial_size
|
||||||
b.buf = []byte{cap: s}
|
b.buf = []byte{cap: s}
|
||||||
b.len = 0
|
b.len = 0
|
||||||
|
b.str_calls = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue