formatx 0.2.4

A macro for formatting non literal strings at runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use crate::error::Error;
use std::fmt::{Debug, Display};

macro_rules! parse {
    ($($arg:tt)*) => {
        return Err($crate::error::Error::new_parse(format!($($arg)*)))
    };
}

macro_rules! ufs {
    ($($arg:tt)*) => {
        return Err($crate::error::Error::new_ufs(format!($($arg)*)))
    };
}

#[derive(Debug, Default, Clone)]
pub struct FormatSpec {
    align: Option<(Option<String>, String)>,
    sign: Option<String>,
    hashtag: bool,
    zero: bool,
    width: Option<usize>,
    precision: Option<usize>,
    types: Option<String>,
}

impl FormatSpec {
    pub(crate) fn new(placeholder: &str) -> Result<Self, Error> {
        if placeholder.rfind(':').is_some() {
            let spec = placeholder.split(':').last().unwrap().to_owned();
            Self::validate(spec.clone(), placeholder)?;
            return Ok(Self::parse(spec));
        }

        Ok(Self::default())
    }

    fn validate(mut spec: String, placeholder: &str) -> Result<(), Error> {
        let mut align_index = match (spec.find('<'), spec.find('^'), spec.find('>')) {
            (None, None, None) => None,
            (Some(left), None, None) => Some(left),
            (None, Some(center), None) => Some(center),
            (None, None, Some(right)) => Some(right),
            _ => parse!("multiple align specifiers used in {{{}}}", placeholder),
        };

        if let Some(x) = align_index {
            if x == 1 {
                spec.replace_range((x - 1)..x, "");
                align_index = Some(0);
            }
        }

        let sign_index = match (spec.find('+'), spec.find('-')) {
            (None, None) => None,
            (Some(positive), None) => Some(positive),
            (None, Some(negative)) => Some(negative),
            _ => parse!("multiple signs used in {{{}}}", placeholder),
        };

        let hashtag_index = spec.find('#');
        let mut zero_index = spec.find('0');
        let precision_index = spec.find('.');

        if let Some(x) = zero_index {
            if let Some(y) = precision_index {
                if x > y {
                    zero_index = None;
                }
            }
        }

        let question_index = spec.find('?');

        if let Some(x) = align_index {
            for (spec_name, spec_index) in [
                ("sign", sign_index),
                ("#", hashtag_index),
                ("0 padding and width", zero_index),
                ("precision", precision_index),
                ("?", question_index),
            ]
            .iter()
            {
                if let Some(spec_index) = spec_index {
                    if x > *spec_index {
                        parse!(
                            "align should be used before {} in {{{}}}",
                            spec_name,
                            placeholder
                        );
                    }
                }
            }
        }

        if let Some(x) = sign_index {
            for (spec_name, spec_index) in [
                ("#", hashtag_index),
                ("0 padding and width", zero_index),
                ("precision", precision_index),
                ("?", question_index),
            ]
            .iter()
            {
                if let Some(spec_index) = spec_index {
                    if x > *spec_index {
                        parse!(
                            "sign should be used before {} in {{{}}}",
                            spec_name,
                            placeholder
                        );
                    }
                }
            }
        }

        if let Some(x) = hashtag_index {
            for (spec_name, spec_index) in [
                ("0 padding and width", zero_index),
                ("precision", precision_index),
                ("?", question_index),
            ]
            .iter()
            {
                if let Some(spec_index) = spec_index {
                    if x > *spec_index {
                        parse!(
                            "# should be used before {} in {{{}}}",
                            spec_name,
                            placeholder
                        );
                    }
                }
            }
        }

        if let Some(x) = zero_index {
            for (spec_name, spec_index) in
                [("precision", precision_index), ("?", question_index)].iter()
            {
                if let Some(spec_index) = spec_index {
                    if x > *spec_index {
                        parse!(
                            "0 should be used before {} in {{{}}}",
                            spec_name,
                            placeholder
                        );
                    }
                }
            }
        }

        if let Some(x) = precision_index {
            for (spec_name, spec_index) in [("?", question_index)].iter() {
                if let Some(spec_index) = spec_index {
                    if x > *spec_index {
                        parse!(
                            "precision should be used before {} in {{{}}}",
                            spec_name,
                            placeholder
                        );
                    }
                }
            }

            if let Some(y) = spec.get((x + 1)..(x + 2)) {
                if y.parse::<usize>().is_err() {
                    parse!(
                        "precision value is not a valid usize in {{{}}}",
                        placeholder
                    );
                }
            } else {
                parse!("precision value not supplied in {{{}}}", placeholder);
            }
        }

        // UNSUPPORTED FORMAT SPECS

        if spec.contains('$') {
            ufs!(
                "parameter setting through $ sign argument is not supported but used in {{{}}}",
                placeholder
            );
        }

        if spec.contains(".*") {
            ufs!(
                "asterisk .* formatting is not supported but used in {{{}}}",
                placeholder
            );
        }

        if spec.contains('o') {
            ufs!(
                "o formatting is not supported but used in {{{}}}",
                placeholder
            );
        }

        if spec.contains('x') {
            ufs!(
                "x formatting is not supported but used in {{{}}}",
                placeholder
            );
        }

        if spec.contains('X') {
            ufs!(
                "X formatting is not supported but used in {{{}}}",
                placeholder
            );
        }

        if spec.contains('p') {
            ufs!(
                "p formatting is not supported but used in {{{}}}",
                placeholder
            );
        }

        if spec.contains('b') {
            ufs!(
                "b formatting is not supported but used in {{{}}}",
                placeholder
            );
        }

        if spec.contains('e') {
            ufs!(
                "e formatting is not supported but used in {{{}}}",
                placeholder
            );
        }

        if spec.contains('E') {
            ufs!(
                "E formatting is not supported but used in {{{}}}",
                placeholder
            );
        }

        Ok(())
    }

    fn parse(mut spec: String) -> Self {
        let spec_copy = spec.clone();
        let align = if let Some(align) = spec_copy.get(0..1) {
            if align == "<" || align == "^" || align == ">" {
                spec.replace_range(0..1, "");
                Some((None, align.to_owned()))
            } else if let Some(align) = spec_copy.get(1..2) {
                if align == "<" || align == "^" || align == ">" {
                    spec.replace_range(0..2, "");
                    Some((
                        Some(spec_copy.get(0..1).unwrap().to_owned()),
                        align.to_owned(),
                    ))
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        };

        let spec_copy = spec.clone();
        let sign = if let Some(sign) = spec_copy.get(0..1) {
            if sign == "+" || sign == "-" {
                spec.replace_range(0..1, "");
                Some(sign.to_owned())
            } else {
                None
            }
        } else {
            None
        };

        let hashtag = if let Some(hastag) = spec.get(0..1) {
            if hastag == "#" {
                spec.replace_range(0..1, "");
                true
            } else {
                false
            }
        } else {
            false
        };

        let zero = if let Some(zero) = spec.get(0..1) {
            if zero == "0" {
                spec.replace_range(0..1, "");
                true
            } else {
                false
            }
        } else {
            false
        };

        let width = crate::utils::usize_token(&spec, 0);

        if let Some(x) = width {
            spec = spec.trim_start_matches(&x.to_string()).to_owned();
        }

        let precision = if let Some(point) = spec.get(0..1) {
            if point == "." {
                crate::utils::usize_token(&spec, 1)
            } else {
                None
            }
        } else {
            None
        };

        if let Some(x) = precision {
            spec = spec.trim_start_matches(&format!(".{}", x)).to_owned();
        }

        let types = if spec.is_empty() {
            None
        } else {
            Some(spec.split(' ').next().unwrap().to_owned())
        };

        Self {
            align,
            sign,
            hashtag,
            zero,
            width,
            precision,
            types,
        }
    }

    pub fn format<T: Display + Debug>(&self, value: T) -> String {
        let mut fmtval = format!("{}", value);

        if let Some(precision) = self.precision {
            if self.zero && self.hashtag {
                fmtval = format!("{:#0.1$}", value, precision);
            } else if self.hashtag {
                fmtval = format!("{:#.1$}", value, precision);
            } else {
                fmtval = format!("{:.1$}", value, precision);
            }
        }

        if let Some(types) = &self.types {
            if self.hashtag {
                if types == "?" {
                    return format!("{:#?}", value);
                } else if types == "x?" {
                    return format!("{:#x?}", value);
                } else if types == "X?" {
                    return format!("{:#X?}", value);
                }
            } else if types == "?" {
                return format!("{:?}", value);
            } else if types == "x?" {
                return format!("{:x?}", value);
            } else if types == "X?" {
                return format!("{:X?}", value);
            }
        }

        if let Some(sign) = &self.sign {
            if sign == "+" && !self.zero && crate::utils::is_number_and_positive(&fmtval) {
                fmtval = "+".to_owned() + &fmtval;
            }
        }

        match &self.align {
            Some((Some(fill), align)) => {
                fmtval = fmtval.trim().to_owned();
                let chars_count = fmtval.chars().count();
                let width = self.width.unwrap_or(0);

                if width > chars_count {
                    if align == "<" {
                        fmtval = fmtval + &fill.repeat(width - chars_count);
                    } else if align == "^" {
                        let factor = usize::from(chars_count % 2 != 0);
                        let start = fill.repeat((width - chars_count - factor) / 2);
                        let end = fill.repeat((width - chars_count + factor) / 2);
                        fmtval = start + &fmtval + &end;
                    } else if align == ">" {
                        fmtval = fill.repeat(width - chars_count) + &fmtval;
                    }
                }
            }
            Some((None, align)) => {
                if align == "<" {
                    fmtval = format!("{:<1$}", fmtval, self.width.unwrap_or(0));
                } else if align == "^" {
                    fmtval = format!("{:^1$}", fmtval, self.width.unwrap_or(0));
                } else if align == ">" {
                    fmtval = format!("{:>1$}", fmtval, self.width.unwrap_or(0));
                }
            }
            None => (),
        }

        if let Some(width) = self.width {
            if crate::utils::is_number(&fmtval) {
                let chars_count = fmtval.chars().count();

                if self.zero && width > chars_count {
                    if let Some(sign) = &self.sign {
                        if sign == "+" {
                            if crate::utils::is_number_and_positive(&fmtval) {
                                fmtval =
                                    "+".to_owned() + &"0".repeat(width - chars_count - 1) + &fmtval;
                            } else {
                                fmtval = "-".to_owned()
                                    + &"0".repeat(width - chars_count)
                                    + &fmtval[1..];
                            }
                        } else if sign == "-" {
                            fmtval =
                                "-".to_owned() + &"0".repeat(width - chars_count) + &fmtval[1..];
                        }
                    } else if fmtval.starts_with('-') {
                        fmtval = "-".to_owned() + &"0".repeat(width - chars_count) + &fmtval[1..];
                    } else {
                        fmtval = "0".repeat(width - chars_count) + &fmtval;
                    }
                } else if width > chars_count {
                    fmtval = " ".repeat(width - chars_count) + &fmtval;
                }
            } else if self.zero && self.hashtag {
                fmtval = format!("{:#01$}", fmtval, width);
            } else if self.zero {
                fmtval = format!("{:01$}", fmtval, width);
            } else if self.hashtag {
                fmtval = format!("{:#1$}", fmtval, width);
            } else {
                fmtval = format!("{:1$}", fmtval, width);
            }
        }

        fmtval
    }
}