v.util: add Surrounder.builder_write_befores and Surrounder.builder_write_afters methods for writing to an existing strings.Builder

pull/12539/head
Delyan Angelov 2021-11-21 13:22:38 +02:00
parent 480f3876ee
commit 117c99d938
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
3 changed files with 28 additions and 4 deletions

View File

@ -802,9 +802,9 @@ fn (mut g Gen) gen_str_for_struct(info ast.Struct, styp string, str_fn_name stri
mut fn_body_surrounder := util.new_surrounder(info.fields.len) mut fn_body_surrounder := util.new_surrounder(info.fields.len)
mut fn_body := strings.new_builder(info.fields.len * 256) mut fn_body := strings.new_builder(info.fields.len * 256)
defer { defer {
fn_builder.write_string(fn_body_surrounder.before()) fn_body_surrounder.builder_write_befores(mut fn_builder)
fn_builder << fn_body fn_builder << fn_body
fn_builder.write_string(fn_body_surrounder.after()) fn_body_surrounder.builder_write_afters(mut fn_builder)
fn_builder.writeln('\tstring_free(&indents);') fn_builder.writeln('\tstring_free(&indents);')
fn_builder.writeln('\treturn res;') fn_builder.writeln('\treturn res;')
fn_builder.writeln('}') fn_builder.writeln('}')

View File

@ -57,7 +57,7 @@ eprint(res);
string_free(&res); string_free(&res);
strings__Builder_free(&sb); strings__Builder_free(&sb);
') ')
dump_fns.writeln(surrounder.before()) surrounder.builder_write_befores(mut dump_fns)
dump_fns.writeln("\tstrings__Builder_write_rune(&sb, '[');") dump_fns.writeln("\tstrings__Builder_write_rune(&sb, '[');")
dump_fns.writeln('\tstrings__Builder_write_string(&sb, fpath);') dump_fns.writeln('\tstrings__Builder_write_string(&sb, fpath);')
dump_fns.writeln("\tstrings__Builder_write_rune(&sb, ':');") dump_fns.writeln("\tstrings__Builder_write_rune(&sb, ':');")
@ -72,7 +72,7 @@ strings__Builder_free(&sb);
} }
dump_fns.writeln('\tstrings__Builder_write_string(&sb, value);') dump_fns.writeln('\tstrings__Builder_write_string(&sb, value);')
dump_fns.writeln("\tstrings__Builder_write_rune(&sb, '\\n');") dump_fns.writeln("\tstrings__Builder_write_rune(&sb, '\\n');")
dump_fns.writeln(surrounder.after()) surrounder.builder_write_afters(mut dump_fns)
dump_fns.writeln('\treturn dump_arg;') dump_fns.writeln('\treturn dump_arg;')
dump_fns.writeln('}') dump_fns.writeln('}')
} }

View File

@ -61,6 +61,30 @@ pub fn (s &Surrounder) after() string {
return '' return ''
} }
pub fn (s &Surrounder) builder_write_befores(mut sb strings.Builder) {
len := s.befores.len
if len > 0 {
for i := 0; i < len; i++ {
x := &s.befores[i]
if x.len > 0 {
sb.writeln(x)
}
}
}
}
pub fn (s &Surrounder) builder_write_afters(mut sb strings.Builder) {
len := s.afters.len
if len > 0 {
for i := len - 1; i >= 0; i-- {
x := &s.afters[i]
if x.len > 0 {
sb.writeln(x)
}
}
}
}
[unsafe] [unsafe]
pub fn (mut s Surrounder) free() { pub fn (mut s Surrounder) free() {
unsafe { unsafe {