Skip to content

Commit af7a213

Browse files
authored
strings: add Bulder.write_decimal/1 method (write a decimal number, without additional allocations) (#19625)
1 parent 39310a2 commit af7a213

2 files changed

Lines changed: 50 additions & 1 deletion

File tree

vlib/strings/builder.c.v

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,34 @@ pub fn (mut b Builder) write_byte(data byte) {
7474
b << data
7575
}
7676

77-
// write implements the Writer interface
77+
// write_decimal appends a decimal representation of the number `n` into the builder `b`,
78+
// without dynamic allocation. The higher order digits come first, i.e. 6123 will be written
79+
// with the digit `6` first, then `1`, then `2` and `3` last.
80+
[direct_array_access]
81+
pub fn (mut b Builder) write_decimal(n i64) {
82+
if n == 0 {
83+
b.write_u8(0x30)
84+
return
85+
}
86+
mut buf := [25]u8{}
87+
mut x := if n < 0 { -n } else { n }
88+
mut i := 24
89+
for x != 0 {
90+
nextx := x / 10
91+
r := x % 10
92+
buf[i] = u8(r) + 0x30
93+
x = nextx
94+
i--
95+
}
96+
if n < 0 {
97+
buf[i] = `-`
98+
i--
99+
}
100+
unsafe { b.write_ptr(&buf[i + 1], 24 - i) }
101+
}
102+
103+
// write implements the io.Writer interface, that is why it
104+
// it returns how many bytes were written to the string builder.
78105
pub fn (mut b Builder) write(data []u8) !int {
79106
if data.len == 0 {
80107
return 0

vlib/strings/builder_test.v

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,25 @@ fn test_drain_builder() {
144144
assert target_sb.len == 3
145145
assert target_sb.str() == 'abc'
146146
}
147+
148+
[manualfree]
149+
fn sb_i64_str(n i64) string {
150+
mut sb := strings.new_builder(24)
151+
defer {
152+
unsafe { sb.free() }
153+
}
154+
sb.write_decimal(n)
155+
return sb.str()
156+
}
157+
158+
fn test_write_decimal() {
159+
assert sb_i64_str(0) == '0'
160+
assert sb_i64_str(1) == '1'
161+
assert sb_i64_str(-1) == '-1'
162+
assert sb_i64_str(1001) == '1001'
163+
assert sb_i64_str(-1001) == '-1001'
164+
assert sb_i64_str(1234567890) == '1234567890'
165+
assert sb_i64_str(-1234567890) == '-1234567890'
166+
assert sb_i64_str(9223372036854775807) == '9223372036854775807'
167+
assert sb_i64_str(-9223372036854775807) == '-9223372036854775807'
168+
}

0 commit comments

Comments
 (0)