strings: add Builder.write_rune/1 and Builder.write_runes/1 methods

pull/11240/head
Delyan Angelov 2021-08-19 07:14:20 +03:00
parent 26b77515b9
commit fe08e1c504
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
3 changed files with 46 additions and 7 deletions

View File

@ -34,9 +34,7 @@ pub fn (c rune) str() string {
[manualfree] [manualfree]
pub fn (ra []rune) string() string { pub fn (ra []rune) string() string {
mut sb := strings.new_builder(ra.len) mut sb := strings.new_builder(ra.len)
for r in ra { sb.write_runes(ra)
sb.write_string(r.str())
}
res := sb.str() res := sb.str()
unsafe { sb.free() } unsafe { sb.free() }
return res return res

View File

@ -23,6 +23,29 @@ pub fn (mut b Builder) write_ptr(ptr &byte, len int) {
unsafe { b.push_many(ptr, len) } 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 // write_b appends a single `data` byte to the accumulated buffer
pub fn (mut b Builder) write_b(data byte) { pub fn (mut b Builder) write_b(data byte) {
b << data b << data

View File

@ -2,6 +2,8 @@ import strings
type MyInt = int type MyInt = int
const maxn = 100000
fn test_sb() { fn test_sb() {
mut sb := strings.new_builder(100) mut sb := strings.new_builder(100)
sb.write_string('hi') sb.write_string('hi')
@ -40,10 +42,6 @@ fn test_sb() {
//} //}
} }
const (
maxn = 100000
)
fn test_big_sb() { fn test_big_sb() {
mut sb := strings.new_builder(100) mut sb := strings.new_builder(100)
mut sb2 := strings.new_builder(10000) mut sb2 := strings.new_builder(10000)
@ -94,3 +92,23 @@ fn test_cut_to() {
assert sb.cut_to(32) == '' assert sb.cut_to(32) == ''
assert sb.len == 0 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'
}