vxx2 / vlib / strconv / write_dec.v
50 lines · 47 sloc · 1.1 KB · 0874e2bf02c5c1ec86a36353a5f9de173879673e
Raw
1module strconv
2
3// write_dec writes the decimal representation of `n` into `buf`.
4// It returns the number of bytes written, or `-1` if `buf` is too small.
5@[direct_array_access]
6pub fn write_dec(n i64, mut buf []u8) int {
7 mut mag := u64(n)
8 if n < 0 {
9 mag = u64(0) - mag
10 ndigits := dec_digits(mag)
11 if buf.len < ndigits + 1 {
12 return -1
13 }
14 buf[0] = `-`
15 write_dec_u_digits(mag, mut buf, 1, ndigits)
16 return ndigits + 1
17 }
18 ndigits := dec_digits(mag)
19 if buf.len < ndigits {
20 return -1
21 }
22 write_dec_u_digits(mag, mut buf, 0, ndigits)
23 return ndigits
24}
25
26// write_dec_u writes the decimal representation of `n` into `buf`.
27// It returns the number of bytes written, or `-1` if `buf` is too small.
28@[direct_array_access]
29pub fn write_dec_u(n u64, mut buf []u8) int {
30 ndigits := dec_digits(n)
31 if buf.len < ndigits {
32 return -1
33 }
34 write_dec_u_digits(n, mut buf, 0, ndigits)
35 return ndigits
36}
37
38@[direct_array_access]
39fn write_dec_u_digits(n u64, mut buf []u8, offset int, ndigits int) {
40 mut x := n
41 mut i := offset + ndigits
42 for {
43 i--
44 buf[i] = u8(x % 10) + `0`
45 x /= 10
46 if x == 0 {
47 break
48 }
49 }
50}
51