1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

strings: cleanup strings builder, allow reusing it

This commit is contained in:
Delyan Angelov 2021-02-21 13:32:18 +02:00
parent 6e46f3850c
commit 514cabd7c8
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
2 changed files with 9 additions and 8 deletions

View File

@ -10,7 +10,6 @@ module strings
pub struct Builder { pub struct Builder {
pub mut: pub mut:
buf []byte buf []byte
str_calls int
len int len int
initial_size int = 1 initial_size int = 1
} }
@ -20,7 +19,6 @@ pub fn new_builder(initial_size int) Builder {
return Builder{ return Builder{
// buf: make(0, initial_size) // buf: make(0, initial_size)
buf: []byte{cap: initial_size} buf: []byte{cap: initial_size}
str_calls: 0
len: 0 len: 0
initial_size: initial_size initial_size: initial_size
} }
@ -126,13 +124,10 @@ pub fn (b &Builder) after(n int) string {
// accumulated data that was in the string builder, before the // accumulated data that was in the string builder, before the
// .str() call. // .str() call.
pub fn (mut b Builder) str() string { pub fn (mut b Builder) str() string {
b.str_calls++
if b.str_calls > 1 {
panic('builder.str() should be called just once.\nIf you want to reuse a builder, call b.free() first.')
}
b.buf << `\0` b.buf << `\0`
s := unsafe { byteptr(memdup(b.buf.data, b.len)).vstring_with_len(b.len) } s := unsafe { byteptr(memdup(b.buf.data, b.len)).vstring_with_len(b.len) }
b.len = 0 b.len = 0
b.buf.trim(0)
return s return s
} }
@ -140,7 +135,5 @@ pub fn (mut b Builder) str() string {
[unsafe] [unsafe]
pub fn (mut b Builder) free() { pub fn (mut b Builder) free() {
unsafe { free(b.buf.data) } unsafe { free(b.buf.data) }
// b.buf = []byte{cap: b.initial_size}
b.len = 0 b.len = 0
b.str_calls = 0
} }

View File

@ -75,3 +75,11 @@ fn test_byte_write() {
sb_final := sb.str() sb_final := sb.str()
assert sb_final == temp_str assert sb_final == temp_str
} }
fn test_strings_builder_reuse() {
mut sb := strings.new_builder(256)
sb.write('world')
assert sb.str() == 'world'
sb.write('hello')
assert sb.str() == 'hello'
}