File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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.
78105pub fn (mut b Builder) write (data []u8 ) ! int {
79106 if data.len == 0 {
80107 return 0
Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments