oficina / fichas Public

Clone
git clone https://amadan.net/oficina/fichas

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3// The interim number reading (level-up spec §6.8, "Phase 1 reads
4// numbers without R2"): the reader's own convention only, as
5// rastrillo's Strict money fields read, built on rastrillo's locale
6// data. One convention means one reading, so it is never ambiguous; it
7// never rounds and it writes the canonical form. It is deleted when
8// rastrillo's plain number reading (R2) lands in Phase 2.
9
10import (
11 "strings"
12 "unicode"
13 "unicode/utf8"
14
15 "amadan.net/rastrillo/rastrillo/locales"
16)
17
18// maxDigits is §6.2's bound on a number's digits.
19const maxDigits = 30
20
21// numberMarks are one locale's marks for plain numbers.
22type numberMarks struct {
23 decimal, group rune
24 primary, secondary int
25 minus rune
26 digits []rune // the locale's own ten digits
27}
28
29func marksFor(format string) numberMarks {
30 d, _ := locales.Data(format)
31 m := numberMarks{decimal: '.', group: ',', primary: 3, secondary: 3, minus: '-'}
32 if r, _ := utf8.DecodeRuneInString(d.Decimal); r != utf8.RuneError {
33 m.decimal = r
34 }
35 // rastrillo's packs carry the currency group mark and not yet the
36 // plain one (R1). It is read as a group mark only where it can never
37 // also be a decimal mark in this locale (§6.8): not when it is the
38 // decimal mark, and not where money's decimal mark differs from the
39 // ordinary one (fr-CH). Phase 1 draws numbers ungrouped, so nothing
40 // it draws needs the group mark read.
41 m.group = 0
42 if r, _ := utf8.DecodeRuneInString(d.CurrencyGroup); r != utf8.RuneError &&
43 d.CurrencyGroup != d.Decimal && (d.CurrencyDecimal == "" || d.CurrencyDecimal == d.Decimal) {
44 m.group = foldSpaceRune(r)
45 }
46 if r, _ := utf8.DecodeRuneInString(d.Minus); r != utf8.RuneError {
47 m.minus = r
48 }
49 m.digits = []rune(d.Digits)
50 if p, s := patternGrouping(d.Standard); p > 0 {
51 m.primary, m.secondary = p, s
52 }
53 return m
54}
55
56// patternGrouping reads a CLDR pattern's group sizes: "#,##,##0.00" is
57// 3 then 2.
58func patternGrouping(pattern string) (int, int) {
59 pos, _, _ := strings.Cut(pattern, ";")
60 start := strings.IndexAny(pos, "#0,.")
61 end := strings.LastIndexAny(pos, "#0,.") + 1
62 if start < 0 || end <= start {
63 return 0, 0
64 }
65 intPart, _, _ := strings.Cut(pos[start:end], ".")
66 groups := strings.Split(intPart, ",")
67 if len(groups) < 2 {
68 return 0, 0
69 }
70 primary := len(groups[len(groups)-1])
71 secondary := primary
72 if len(groups) > 2 {
73 secondary = len(groups[len(groups)-2])
74 }
75 return primary, secondary
76}
77
78// foldSpaceRune makes every space one mark, and U+2019 the apostrophe,
79// as rastrillo's Clean and money parser treat them.
80func foldSpaceRune(r rune) rune {
81 if unicode.IsSpace(r) || unicode.In(r, unicode.Zs) {
82 return ' '
83 }
84 if r == '\u2019' {
85 return '\''
86 }
87 return r
88}
89
90// numberError is a refused number, with an example in the reader's own
91// format.
92type numberError struct{ example string }
93
94func (e numberError) Error() string { return "Enter a number, like " + e.example + "." }
95
96// readNumber reads s in format's own convention into the canonical
97// form. Blank is "", nil: whether blank is allowed is the field's call.
98func readNumber(format, s string) (string, error) {
99 m := marksFor(format)
100 refuse := numberError{example: seedNumber(format, "1200.5")}
101 s = cleanNumber(s)
102 if s == "" {
103 return "", nil
104 }
105 negative := false
106 if r, size := utf8.DecodeRuneInString(s); r == '-' || r == '−' || r == m.minus {
107 negative, s = true, s[size:]
108 }
109 whole, frac, ok := splitNumber(s, m)
110 if !ok || len(whole)+len(frac) > maxDigits || whole+frac == "" {
111 return "", refuse
112 }
113 return canonicalOf(negative, whole, frac), nil
114}
115
116// cleanNumber drops bidi marks and folds every space to U+0020, as
117// rastrillo's currency.Clean does, then trims.
118func cleanNumber(s string) string {
119 var b strings.Builder
120 for _, r := range s {
121 switch {
122 case r == '‎' || r == '‏' || r == '؜' || (r >= '‪' && r <= '‮') || (r >= '⁦' && r <= '⁩'):
123 default:
124 b.WriteRune(foldSpaceRune(r))
125 }
126 }
127 return strings.TrimSpace(b.String())
128}
129
130// splitNumber reads digits, the group mark at valid positions only and
131// the decimal mark once, into ASCII whole and fraction digits.
132func splitNumber(s string, m numberMarks) (whole, frac string, ok bool) {
133 var groups []string
134 var cur strings.Builder
135 sawDecimal, sawGroup := false, false
136 for _, r := range s {
137 d, isDigit := digitOf(r, m.digits)
138 switch {
139 case isDigit:
140 cur.WriteByte(d)
141 case r == m.decimal && !sawDecimal:
142 groups, sawDecimal = append(groups, cur.String()), true
143 cur.Reset()
144 case m.group != 0 && r == m.group && !sawDecimal && cur.Len() > 0:
145 groups, sawGroup = append(groups, cur.String()), true
146 cur.Reset()
147 default:
148 return "", "", false
149 }
150 }
151 if sawDecimal {
152 frac = cur.String()
153 if frac == "" && (len(groups) == 0 || groups[len(groups)-1] == "") {
154 return "", "", false
155 }
156 } else {
157 groups = append(groups, cur.String())
158 }
159 if sawGroup && !validGroups(groups, m.primary, m.secondary) {
160 return "", "", false
161 }
162 return strings.Join(groups, ""), frac, true
163}
164
165// validGroups: the last group has the primary size, earlier ones the
166// secondary size, and the first one to the secondary size.
167func validGroups(groups []string, primary, secondary int) bool {
168 n := len(groups)
169 if n < 2 || len(groups[n-1]) != primary {
170 return false
171 }
172 for i := 1; i < n-1; i++ {
173 if len(groups[i]) != secondary {
174 return false
175 }
176 }
177 return len(groups[0]) >= 1 && len(groups[0]) <= secondary
178}
179
180func digitOf(r rune, local []rune) (byte, bool) {
181 if r >= '0' && r <= '9' {
182 return byte(r), true
183 }
184 for i, l := range local {
185 if r == l && i < 10 {
186 return byte('0' + i), true
187 }
188 }
189 return 0, false
190}
191
192func canonicalOf(negative bool, whole, frac string) string {
193 whole = strings.TrimLeft(whole, "0")
194 if whole == "" {
195 whole = "0"
196 }
197 frac = strings.TrimRight(frac, "0")
198 out := whole
199 if frac != "" {
200 out += "." + frac
201 }
202 if negative && out != "0" {
203 out = "-" + out
204 }
205 return out
206}
207
208// seedNumber is a canonical number as an editor starts from it: the
209// reader's decimal mark and no group marks (§6.8), so it reads back as
210// itself under every reading. ASCII digits, which every reading takes.
211func seedNumber(format, canonical string) string {
212 if !canonicalNumber(canonical) {
213 return canonical
214 }
215 m := marksFor(format)
216 return strings.Replace(canonical, ".", string(m.decimal), 1)
217}
218
219// readNumberInput is what a posted number means: was itself when the
220// text is was's own seed (the unchanged-seed rule, §6.8), otherwise the
221// strict reading.
222func readNumberInput(format, posted, was string) (string, error) {
223 if was != "" && cleanNumber(posted) == seedNumber(format, was) {
224 return was, nil
225 }
226 return readNumber(format, posted)
227}
228