Debian Codegraph @

src/format_spec.rs

raw symbols SCIP
1 use crate::error::Error;
2 use std::fmt::{Debug, Display};
3
4 macro_rules! parse {
5 ($($arg:tt)*) => {
6 return Err($crate::error::Error::new_parse(format!($($arg)*)))
7 };
8 }
9
10 macro_rules! ufs {
11 ($($arg:tt)*) => {
12 return Err($crate::error::Error::new_ufs(format!($($arg)*)))
13 };
14 }
15
16 #[derive(Debug, Default, Clone)]
17 pub struct FormatSpec {
18 align: Option<(Option<String>, String)>,
19 sign: Option<String>,
20 hashtag: bool,
21 zero: bool,
22 width: Option<usize>,
23 precision: Option<usize>,
24 types: Option<String>,
25 }
26
27 impl FormatSpec {
28 pub(crate) fn new(placeholder: &str) -> Result<Self, Error> {
29 if placeholder.rfind(':').is_some() {
30 let spec = placeholder.split(':').last().unwrap().to_owned();
31 Self::validate(spec.clone(), placeholder)?;
32 return Ok(Self::parse(spec));
33 }
34
35 Ok(Self::default())
36 }
37
38 fn validate(mut spec: String, placeholder: &str) -> Result<(), Error> {
39 let mut align_index = match (spec.find('<'), spec.find('^'), spec.find('>')) {
40 (None, None, None) => None,
41 (Some(left), None, None) => Some(left),
42 (None, Some(center), None) => Some(center),
43 (None, None, Some(right)) => Some(right),
44 _ => parse!("multiple align specifiers used in {{{}}}", placeholder),
45 };
46
47 if let Some(x) = align_index {
48 if x == 1 {
49 spec.replace_range((x - 1)..x, "");
50 align_index = Some(0);
51 }
52 }
53
54 let sign_index = match (spec.find('+'), spec.find('-')) {
55 (None, None) => None,
56 (Some(positive), None) => Some(positive),
57 (None, Some(negative)) => Some(negative),
58 _ => parse!("multiple signs used in {{{}}}", placeholder),
59 };
60
61 let hashtag_index = spec.find('#');
62 let mut zero_index = spec.find('0');
63 let precision_index = spec.find('.');
64
65 if let Some(x) = zero_index {
66 if let Some(y) = precision_index {
67 if x > y {
68 zero_index = None;
69 }
70 }
71 }
72
73 let question_index = spec.find('?');
74
75 if let Some(x) = align_index {
76 for (spec_name, spec_index) in [
77 ("sign", sign_index),
78 ("#", hashtag_index),
79 ("0 padding and width", zero_index),
80 ("precision", precision_index),
81 ("?", question_index),
82 ]
83 .iter()
84 {
85 if let Some(spec_index) = spec_index {
86 if x > *spec_index {
87 parse!(
88 "align should be used before {} in {{{}}}",
89 spec_name,
90 placeholder
91 );
92 }
93 }
94 }
95 }
96
97 if let Some(x) = sign_index {
98 for (spec_name, spec_index) in [
99 ("#", hashtag_index),
100 ("0 padding and width", zero_index),
101 ("precision", precision_index),
102 ("?", question_index),
103 ]
104 .iter()
105 {
106 if let Some(spec_index) = spec_index {
107 if x > *spec_index {
108 parse!(
109 "sign should be used before {} in {{{}}}",
110 spec_name,
111 placeholder
112 );
113 }
114 }
115 }
116 }
117
118 if let Some(x) = hashtag_index {
119 for (spec_name, spec_index) in [
120 ("0 padding and width", zero_index),
121 ("precision", precision_index),
122 ("?", question_index),
123 ]
124 .iter()
125 {
126 if let Some(spec_index) = spec_index {
127 if x > *spec_index {
128 parse!(
129 "# should be used before {} in {{{}}}",
130 spec_name,
131 placeholder
132 );
133 }
134 }
135 }
136 }
137
138 if let Some(x) = zero_index {
139 for (spec_name, spec_index) in
140 [("precision", precision_index), ("?", question_index)].iter()
141 {
142 if let Some(spec_index) = spec_index {
143 if x > *spec_index {
144 parse!(
145 "0 should be used before {} in {{{}}}",
146 spec_name,
147 placeholder
148 );
149 }
150 }
151 }
152 }
153
154 if let Some(x) = precision_index {
155 for (spec_name, spec_index) in [("?", question_index)].iter() {
156 if let Some(spec_index) = spec_index {
157 if x > *spec_index {
158 parse!(
159 "precision should be used before {} in {{{}}}",
160 spec_name,
161 placeholder
162 );
163 }
164 }
165 }
166
167 if let Some(y) = spec.get((x + 1)..(x + 2)) {
168 if y.parse::<usize>().is_err() {
169 parse!(
170 "precision value is not a valid usize in {{{}}}",
171 placeholder
172 );
173 }
174 } else {
175 parse!("precision value not supplied in {{{}}}", placeholder);
176 }
177 }
178
179 // UNSUPPORTED FORMAT SPECS
180
181 if spec.contains('$') {
182 ufs!(
183 "parameter setting through $ sign argument is not supported but used in {{{}}}",
184 placeholder
185 );
186 }
187
188 if spec.contains(".*") {
189 ufs!(
190 "asterisk .* formatting is not supported but used in {{{}}}",
191 placeholder
192 );
193 }
194
195 if spec.contains('o') {
196 ufs!(
197 "o formatting is not supported but used in {{{}}}",
198 placeholder
199 );
200 }
201
202 if spec.contains('x') {
203 ufs!(
204 "x formatting is not supported but used in {{{}}}",
205 placeholder
206 );
207 }
208
209 if spec.contains('X') {
210 ufs!(
211 "X formatting is not supported but used in {{{}}}",
212 placeholder
213 );
214 }
215
216 if spec.contains('p') {
217 ufs!(
218 "p formatting is not supported but used in {{{}}}",
219 placeholder
220 );
221 }
222
223 if spec.contains('b') {
224 ufs!(
225 "b formatting is not supported but used in {{{}}}",
226 placeholder
227 );
228 }
229
230 if spec.contains('e') {
231 ufs!(
232 "e formatting is not supported but used in {{{}}}",
233 placeholder
234 );
235 }
236
237 if spec.contains('E') {
238 ufs!(
239 "E formatting is not supported but used in {{{}}}",
240 placeholder
241 );
242 }
243
244 Ok(())
245 }
246
247 fn parse(mut spec: String) -> Self {
248 let spec_copy = spec.clone();
249 let align = if let Some(align) = spec_copy.get(0..1) {
250 if align == "<" || align == "^" || align == ">" {
251 spec.replace_range(0..1, "");
252 Some((None, align.to_owned()))
253 } else if let Some(align) = spec_copy.get(1..2) {
254 if align == "<" || align == "^" || align == ">" {
255 spec.replace_range(0..2, "");
256 Some((
257 Some(spec_copy.get(0..1).unwrap().to_owned()),
258 align.to_owned(),
259 ))
260 } else {
261 None
262 }
263 } else {
264 None
265 }
266 } else {
267 None
268 };
269
270 let spec_copy = spec.clone();
271 let sign = if let Some(sign) = spec_copy.get(0..1) {
272 if sign == "+" || sign == "-" {
273 spec.replace_range(0..1, "");
274 Some(sign.to_owned())
275 } else {
276 None
277 }
278 } else {
279 None
280 };
281
282 let hashtag = if let Some(hastag) = spec.get(0..1) {
283 if hastag == "#" {
284 spec.replace_range(0..1, "");
285 true
286 } else {
287 false
288 }
289 } else {
290 false
291 };
292
293 let zero = if let Some(zero) = spec.get(0..1) {
294 if zero == "0" {
295 spec.replace_range(0..1, "");
296 true
297 } else {
298 false
299 }
300 } else {
301 false
302 };
303
304 let width = crate::utils::usize_token(&spec, 0);
305
306 if let Some(x) = width {
307 spec = spec.trim_start_matches(&x.to_string()).to_owned();
308 }
309
310 let precision = if let Some(point) = spec.get(0..1) {
311 if point == "." {
312 crate::utils::usize_token(&spec, 1)
313 } else {
314 None
315 }
316 } else {
317 None
318 };
319
320 if let Some(x) = precision {
321 spec = spec.trim_start_matches(&format!(".{}", x)).to_owned();
322 }
323
324 let types = if spec.is_empty() {
325 None
326 } else {
327 Some(spec.split(' ').next().unwrap().to_owned())
328 };
329
330 Self {
331 align,
332 sign,
333 hashtag,
334 zero,
335 width,
336 precision,
337 types,
338 }
339 }
340
341 pub fn format<T: Display + Debug>(&self, value: T) -> String {
342 let mut fmtval = format!("{}", value);
343
344 if let Some(precision) = self.precision {
345 if self.zero && self.hashtag {
346 fmtval = format!("{:#0.1$}", value, precision);
347 } else if self.hashtag {
348 fmtval = format!("{:#.1$}", value, precision);
349 } else {
350 fmtval = format!("{:.1$}", value, precision);
351 }
352 }
353
354 if let Some(types) = &self.types {
355 if self.hashtag {
356 if types == "?" {
357 return format!("{:#?}", value);
358 } else if types == "x?" {
359 return format!("{:#x?}", value);
360 } else if types == "X?" {
361 return format!("{:#X?}", value);
362 }
363 } else if types == "?" {
364 return format!("{:?}", value);
365 } else if types == "x?" {
366 return format!("{:x?}", value);
367 } else if types == "X?" {
368 return format!("{:X?}", value);
369 }
370 }
371
372 if let Some(sign) = &self.sign {
373 if sign == "+" && !self.zero && crate::utils::is_number_and_positive(&fmtval) {
374 fmtval = "+".to_owned() + &fmtval;
375 }
376 }
377
378 match &self.align {
379 Some((Some(fill), align)) => {
380 fmtval = fmtval.trim().to_owned();
381 let chars_count = fmtval.chars().count();
382 let width = self.width.unwrap_or(0);
383
384 if width > chars_count {
385 if align == "<" {
386 fmtval = fmtval + &fill.repeat(width - chars_count);
387 } else if align == "^" {
388 let factor = usize::from(chars_count % 2 != 0);
389 let start = fill.repeat((width - chars_count - factor) / 2);
390 let end = fill.repeat((width - chars_count + factor) / 2);
391 fmtval = start + &fmtval + &end;
392 } else if align == ">" {
393 fmtval = fill.repeat(width - chars_count) + &fmtval;
394 }
395 }
396 }
397 Some((None, align)) => {
398 if align == "<" {
399 fmtval = format!("{:<1$}", fmtval, self.width.unwrap_or(0));
400 } else if align == "^" {
401 fmtval = format!("{:^1$}", fmtval, self.width.unwrap_or(0));
402 } else if align == ">" {
403 fmtval = format!("{:>1$}", fmtval, self.width.unwrap_or(0));
404 }
405 }
406 None => (),
407 }
408
409 if let Some(width) = self.width {
410 if crate::utils::is_number(&fmtval) {
411 let chars_count = fmtval.chars().count();
412
413 if self.zero && width > chars_count {
414 if let Some(sign) = &self.sign {
415 if sign == "+" {
416 if crate::utils::is_number_and_positive(&fmtval) {
417 fmtval =
418 "+".to_owned() + &"0".repeat(width - chars_count - 1) + &fmtval;
419 } else {
420 fmtval = "-".to_owned()
421 + &"0".repeat(width - chars_count)
422 + &fmtval[1..];
423 }
424 } else if sign == "-" {
425 fmtval =
426 "-".to_owned() + &"0".repeat(width - chars_count) + &fmtval[1..];
427 }
428 } else if fmtval.starts_with('-') {
429 fmtval = "-".to_owned() + &"0".repeat(width - chars_count) + &fmtval[1..];
430 } else {
431 fmtval = "0".repeat(width - chars_count) + &fmtval;
432 }
433 } else if width > chars_count {
434 fmtval = " ".repeat(width - chars_count) + &fmtval;
435 }
436 } else if self.zero && self.hashtag {
437 fmtval = format!("{:#01$}", fmtval, width);
438 } else if self.zero {
439 fmtval = format!("{:01$}", fmtval, width);
440 } else if self.hashtag {
441 fmtval = format!("{:#1$}", fmtval, width);
442 } else {
443 fmtval = format!("{:1$}", fmtval, width);
444 }
445 }
446
447 fmtval
448 }
449 }