v / vlib / strconv
Raw file | 67 loc (64 sloc) | 1.57 KB | Latest commit hash 017ace6ea
1module strconv
2
3const base_digits = '0123456789abcdefghijklmnopqrstuvwxyz'
4
5// format_int returns the string representation of the number n in base `radix`
6// for digit values > 10, this function uses the small latin leters a-z.
7[direct_array_access; manualfree]
8pub fn format_int(n i64, radix int) string {
9 unsafe {
10 if radix < 2 || radix > 36 {
11 panic('invalid radix: ${radix} . It should be => 2 and <= 36')
12 }
13 if n == 0 {
14 return '0'
15 }
16 mut n_copy := n
17 mut have_minus := false
18 if n < 0 {
19 have_minus = true
20 n_copy = -n_copy
21 }
22 mut res := ''
23 for n_copy != 0 {
24 tmp_0 := res
25 bdx := int(n_copy % radix)
26 tmp_1 := strconv.base_digits[bdx].ascii_str()
27 res = tmp_1 + res
28 tmp_0.free()
29 tmp_1.free()
30 // res = base_digits[n_copy % radix].ascii_str() + res
31 n_copy /= radix
32 }
33 if have_minus {
34 final_res := '-' + res
35 res.free()
36 return final_res
37 }
38 return res
39 }
40}
41
42// format_uint returns the string representation of the number n in base `radix`
43// for digit values > 10, this function uses the small latin leters a-z.
44[direct_array_access; manualfree]
45pub fn format_uint(n u64, radix int) string {
46 unsafe {
47 if radix < 2 || radix > 36 {
48 panic('invalid radix: ${radix} . It should be => 2 and <= 36')
49 }
50 if n == 0 {
51 return '0'
52 }
53 mut n_copy := n
54 mut res := ''
55 uradix := u64(radix)
56 for n_copy != 0 {
57 tmp_0 := res
58 tmp_1 := strconv.base_digits[n_copy % uradix].ascii_str()
59 res = tmp_1 + res
60 tmp_0.free()
61 tmp_1.free()
62 // res = base_digits[n_copy % uradix].ascii_str() + res
63 n_copy /= uradix
64 }
65 return res
66 }
67}