From fe08e1c504a512a1d305508a506bb6c556d1059d Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Thu, 19 Aug 2021 07:14:20 +0300 Subject: [PATCH] strings: add Builder.write_rune/1 and Builder.write_runes/1 methods --- vlib/builtin/rune.v | 4 +--- vlib/strings/builder.v | 23 +++++++++++++++++++++++ vlib/strings/builder_test.v | 26 ++++++++++++++++++++++---- 3 files changed, 46 insertions(+), 7 deletions(-) diff --git a/vlib/builtin/rune.v b/vlib/builtin/rune.v index bc2a9ba7e4..3364d9001a 100644 --- a/vlib/builtin/rune.v +++ b/vlib/builtin/rune.v @@ -34,9 +34,7 @@ pub fn (c rune) str() string { [manualfree] pub fn (ra []rune) string() string { mut sb := strings.new_builder(ra.len) - for r in ra { - sb.write_string(r.str()) - } + sb.write_runes(ra) res := sb.str() unsafe { sb.free() } return res diff --git a/vlib/strings/builder.v b/vlib/strings/builder.v index cec4f6cd07..4616a19f2a 100644 --- a/vlib/strings/builder.v +++ b/vlib/strings/builder.v @@ -23,6 +23,29 @@ pub fn (mut b Builder) write_ptr(ptr &byte, len int) { unsafe { b.push_many(ptr, len) } } +// write_rune appends a single rune to the accumulated buffer +[manualfree] +pub fn (mut b Builder) write_rune(r rune) { + mut buffer := [5]byte{} + res := unsafe { utf32_to_str_no_malloc(u32(r), &buffer[0]) } + if res.len == 0 { + return + } + unsafe { b.push_many(res.str, res.len) } +} + +// write_runes appends all the given runes to the accumulated buffer +pub fn (mut b Builder) write_runes(runes []rune) { + mut buffer := [5]byte{} + for r in runes { + res := unsafe { utf32_to_str_no_malloc(u32(r), &buffer[0]) } + if res.len == 0 { + continue + } + unsafe { b.push_many(res.str, res.len) } + } +} + // write_b appends a single `data` byte to the accumulated buffer pub fn (mut b Builder) write_b(data byte) { b << data diff --git a/vlib/strings/builder_test.v b/vlib/strings/builder_test.v index a714722e45..9180c09af0 100644 --- a/vlib/strings/builder_test.v +++ b/vlib/strings/builder_test.v @@ -2,6 +2,8 @@ import strings type MyInt = int +const maxn = 100000 + fn test_sb() { mut sb := strings.new_builder(100) sb.write_string('hi') @@ -40,10 +42,6 @@ fn test_sb() { //} } -const ( - maxn = 100000 -) - fn test_big_sb() { mut sb := strings.new_builder(100) mut sb2 := strings.new_builder(10000) @@ -94,3 +92,23 @@ fn test_cut_to() { assert sb.cut_to(32) == '' assert sb.len == 0 } + +fn test_write_rune() { + mut sb := strings.new_builder(10) + sb.write_rune(`h`) + sb.write_rune(`e`) + sb.write_rune(`l`) + sb.write_rune(`l`) + sb.write_rune(`o`) + x := sb.str() + assert x == 'hello' +} + +fn test_write_runes() { + mut sb := strings.new_builder(20) + sb.write_runes([`h`, `e`, `l`, `l`, `o`]) + sb.write_rune(` `) + sb.write_runes([`w`, `o`, `r`, `l`, `d`]) + x := sb.str() + assert x == 'hello world' +}