1 | module strconv |
2 | |
3 | /* |
4 | printf/sprintf V implementation |
5 | |
6 | Copyright (c) 2020 Dario Deledda. All rights reserved. |
7 | Use of this source code is governed by an MIT license |
8 | that can be found in the LICENSE file. |
9 | |
10 | This file contains the printf/sprintf functions |
11 | */ |
12 | import strings |
13 | |
14 | pub enum Align_text { |
15 | right = 0 |
16 | left |
17 | center |
18 | } |
19 | |
20 | /* |
21 | Float conversion utility |
22 | */ |
23 | const ( |
24 | // rounding value |
25 | dec_round = [ |
26 | f64(0.5), |
27 | 0.05, |
28 | 0.005, |
29 | 0.0005, |
30 | 0.00005, |
31 | 0.000005, |
32 | 0.0000005, |
33 | 0.00000005, |
34 | 0.000000005, |
35 | 0.0000000005, |
36 | 0.00000000005, |
37 | 0.000000000005, |
38 | 0.0000000000005, |
39 | 0.00000000000005, |
40 | 0.000000000000005, |
41 | 0.0000000000000005, |
42 | 0.00000000000000005, |
43 | 0.000000000000000005, |
44 | 0.0000000000000000005, |
45 | 0.00000000000000000005, |
46 | ]! |
47 | ) |
48 | |
49 | /* |
50 | const( |
51 | // rounding value |
52 | dec_round = [ |
53 | f64(0.44), |
54 | 0.044, |
55 | 0.0044, |
56 | 0.00044, |
57 | 0.000044, |
58 | 0.0000044, |
59 | 0.00000044, |
60 | 0.000000044, |
61 | 0.0000000044, |
62 | 0.00000000044, |
63 | 0.000000000044, |
64 | 0.0000000000044, |
65 | 0.00000000000044, |
66 | 0.000000000000044, |
67 | 0.0000000000000044, |
68 | 0.00000000000000044, |
69 | 0.000000000000000044, |
70 | 0.0000000000000000044, |
71 | 0.00000000000000000044, |
72 | 0.000000000000000000044, |
73 | ] |
74 | ) |
75 | */ |
76 | // max float 1.797693134862315708145274237317043567981e+308 |
77 | |
78 | /* |
79 | Single format functions |
80 | */ |
81 | pub struct BF_param { |
82 | pub mut: |
83 | pad_ch u8 = u8(` `) // padding char |
84 | len0 int = -1 // default len for whole the number or string |
85 | len1 int = 6 // number of decimal digits, if needed |
86 | positive bool = true // mandatory: the sign of the number passed |
87 | sign_flag bool // flag for print sign as prefix in padding |
88 | allign Align_text = .right // alignment of the string |
89 | rm_tail_zero bool // remove the tail zeros from floats |
90 | } |
91 | |
92 | // format_str returns a `string` formatted according to the options set in `p`. |
93 | [manualfree] |
94 | pub fn format_str(s string, p BF_param) string { |
95 | if p.len0 <= 0 { |
96 | return s.clone() |
97 | } |
98 | dif := p.len0 - utf8_str_visible_length(s) |
99 | if dif <= 0 { |
100 | return s.clone() |
101 | } |
102 | mut res := strings.new_builder(s.len + dif) |
103 | defer { |
104 | unsafe { res.free() } |
105 | } |
106 | if p.allign == .right { |
107 | for i1 := 0; i1 < dif; i1++ { |
108 | res.write_u8(p.pad_ch) |
109 | } |
110 | } |
111 | res.write_string(s) |
112 | if p.allign == .left { |
113 | for i1 := 0; i1 < dif; i1++ { |
114 | res.write_u8(p.pad_ch) |
115 | } |
116 | } |
117 | return res.str() |
118 | } |