diff --git a/vlib/strings/builder.c.v b/vlib/strings/builder.c.v index c6041d0091..b9a227eb4d 100644 --- a/vlib/strings/builder.c.v +++ b/vlib/strings/builder.c.v @@ -62,6 +62,17 @@ pub fn (mut b Builder) write(data []byte) ?int { return data.len } +// drain_builder writes all of the `other` builder content, then re-initialises +// `other`, so that the `other` strings builder is ready to receive new content. +[manualfree] +pub fn (mut b Builder) drain_builder(mut other Builder, other_new_cap int) { + b.write(other) or { panic(err) } + unsafe { other.free() } + other = new_builder(other_new_cap) +} + +// byte_at returns a byte, located at a given index `i`. +// NB: it can panic, if there are not enough bytes in the strings builder yet. [inline] pub fn (b &Builder) byte_at(n int) byte { return unsafe { (&[]byte(b))[n] } diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 8bf8cef9eb..daaf7cf076 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -342,18 +342,10 @@ pub fn gen(files []&ast.File, table &ast.Table, pref &pref.Preferences) string { for file in files { global_g.file = file global_g.gen_file() - - global_g.inits[file.mod.name].write(global_g.init) or { panic(err) } - unsafe { global_g.init.free() } - global_g.init = strings.new_builder(100) - - global_g.cleanups[file.mod.name].write(global_g.cleanup) or { panic(err) } - unsafe { global_g.cleanup.free() } - global_g.cleanup = strings.new_builder(100) - - global_g.global_inits[file.mod.name].write(global_g.global_init) or { panic(err) } - unsafe { global_g.global_init.free() } - global_g.global_init = strings.new_builder(100) + global_g.inits[file.mod.name].drain_builder(mut global_g.init, 100) + global_g.cleanups[file.mod.name].drain_builder(mut global_g.cleanup, 100) + global_g.global_inits[file.mod.name].drain_builder(mut global_g.global_init, + 100) } global_g.timers.start('cgen unification') }