v / vlib / strconv / format.v
104 lines · 94 sloc · 2.43 KB · 3ed799ef7b6859cd469b9725f6877cc01e553b2e
Raw
1module strconv
2
3import strings
4
5/*
6printf/sprintf V implementation
7
8Copyright (c) 2020 Dario Deledda. All rights reserved.
9Use of this source code is governed by an MIT license
10that can be found in the LICENSE file.
11
12This file contains the printf/sprintf functions
13*/
14
15// Align_text is used to describe the different ways to align a text - left, right and center
16pub enum Align_text {
17 right = 0
18 left
19 center
20}
21
22// Float conversion utility
23
24// rounding value
25const 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 0.000000000000000000005,
47 0.0000000000000000000005,
48 0.00000000000000000000005,
49 0.000000000000000000000005,
50 0.0000000000000000000000005,
51 0.00000000000000000000000005,
52 0.000000000000000000000000005,
53 0.0000000000000000000000000005,
54 0.00000000000000000000000000005,
55 0.000000000000000000000000000005,
56 0.0000000000000000000000000000005,
57 0.00000000000000000000000000000005,
58 0.000000000000000000000000000000005,
59 0.0000000000000000000000000000000005,
60 0.00000000000000000000000000000000005,
61 0.000000000000000000000000000000000005,
62]!
63
64// Single format functions
65
66// BF_param is used for describing the formatting options for a single interpolated value
67pub struct BF_param {
68pub mut:
69 pad_ch u8 = u8(` `) // padding char
70 len0 int = -1 // default len for whole the number or string
71 len1 int = 6 // number of decimal digits, if needed
72 positive bool = true // mandatory: the sign of the number passed
73 sign_flag bool // flag for print sign as prefix in padding
74 align Align_text = .right // alignment of the string
75 rm_tail_zero bool // remove the tail zeros from floats
76}
77
78// format_str returns the `s` formatted, according to the options set in `p`.
79@[manualfree]
80pub fn format_str(s string, p BF_param) string {
81 if p.len0 <= 0 {
82 return s.clone()
83 }
84 dif := p.len0 - utf8_str_visible_length(s)
85 if dif <= 0 {
86 return s.clone()
87 }
88 mut res := strings.new_builder(s.len + dif)
89 defer {
90 unsafe { res.free() }
91 }
92 if p.align == .right {
93 for i1 := 0; i1 < dif; i1++ {
94 res.write_u8(p.pad_ch)
95 }
96 }
97 res.write_string(s)
98 if p.align == .left {
99 for i1 := 0; i1 < dif; i1++ {
100 res.write_u8(p.pad_ch)
101 }
102 }
103 return res.str()
104}
105