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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use std::convert::{TryFrom, TryInto};

use crate::{ConversionSpecifier, ConversionType, NumericParam, PrintfError, Result};

/// Trait for types that can be formatted using printf strings
///
/// Implemented for the basic types and shouldn't need implementing for
/// anything else.
pub trait Printf {
    /// Format `self` based on the conversion configured in `spec`.
    fn format(&self, spec: &ConversionSpecifier) -> Result<String>;
    /// Get `self` as an integer for use as a field width, if possible.
    fn as_int(&self) -> Option<i32>;
}

impl Printf for u64 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        let mut base = 10;
        let mut digits: Vec<char> = "0123456789".chars().collect();
        let mut alt_prefix = "";
        match spec.conversion_type {
            ConversionType::DecInt => {}
            ConversionType::HexIntLower => {
                base = 16;
                digits = "0123456789abcdef".chars().collect();
                alt_prefix = "0x";
            }
            ConversionType::HexIntUpper => {
                base = 16;
                digits = "0123456789ABCDEF".chars().collect();
                alt_prefix = "0X";
            }
            ConversionType::OctInt => {
                base = 8;
                digits = "01234567".chars().collect();
                alt_prefix = "0";
            }
            _ => {
                return Err(PrintfError::WrongType);
            }
        }
        let prefix = if spec.alt_form {
            alt_prefix.to_owned()
        } else {
            String::new()
        };

        // Build the actual number (in reverse)
        let mut rev_num = String::new();
        let mut n = *self;
        while n > 0 {
            let digit = n % base;
            n /= base;
            rev_num.push(digits[digit as usize]);
        }
        if rev_num.is_empty() {
            rev_num.push('0');
        }

        // Take care of padding
        let width: usize = match spec.width {
            NumericParam::Literal(w) => w,
            _ => {
                return Err(PrintfError::Unknown); // should not happen at this point!!
            }
        }
        .try_into()
        .unwrap_or_default();
        let formatted = if spec.left_adj {
            let mut num_str = prefix + &rev_num.chars().rev().collect::<String>();
            while num_str.len() < width {
                num_str.push(' ');
            }
            num_str
        } else if spec.zero_pad {
            while prefix.len() + rev_num.len() < width {
                rev_num.push('0');
            }
            prefix + &rev_num.chars().rev().collect::<String>()
        } else {
            let mut num_str = prefix + &rev_num.chars().rev().collect::<String>();
            while num_str.len() < width {
                num_str = " ".to_owned() + &num_str;
            }
            num_str
        };

        Ok(formatted)
    }
    fn as_int(&self) -> Option<i32> {
        i32::try_from(*self).ok()
    }
}

impl Printf for i64 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        match spec.conversion_type {
            // signed integer format
            ConversionType::DecInt => {
                // do I need a sign prefix?
                let negative = *self < 0;
                let abs_val = self.abs();
                let sign_prefix = if negative {
                    "-"
                } else if spec.force_sign {
                    "+"
                } else if spec.space_sign {
                    " "
                } else {
                    ""
                }
                .to_owned();
                let mut mod_spec = *spec;
                mod_spec.width = match spec.width {
                    NumericParam::Literal(w) => NumericParam::Literal(w - sign_prefix.len() as i32),
                    _ => {
                        return Err(PrintfError::Unknown);
                    }
                };

                let formatted = (abs_val as u64).format(&mod_spec)?;
                // put the sign a after any leading spaces
                let mut actual_number = &formatted[0..];
                let mut leading_spaces = &formatted[0..0];
                if let Some(first_non_space) = formatted.find(|c| c != ' ') {
                    actual_number = &formatted[first_non_space..];
                    leading_spaces = &formatted[0..first_non_space];
                }
                Ok(leading_spaces.to_owned() + &sign_prefix + actual_number)
            }
            // unsigned-only formats
            ConversionType::HexIntLower | ConversionType::HexIntUpper | ConversionType::OctInt => {
                (*self as u64).format(spec)
            }
            _ => Err(PrintfError::WrongType),
        }
    }
    fn as_int(&self) -> Option<i32> {
        i32::try_from(*self).ok()
    }
}

impl Printf for i32 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        match spec.conversion_type {
            // signed integer format
            ConversionType::DecInt => (*self as i64).format(spec),
            // unsigned-only formats
            ConversionType::HexIntLower | ConversionType::HexIntUpper | ConversionType::OctInt => {
                (*self as u32).format(spec)
            }
            _ => Err(PrintfError::WrongType),
        }
    }
    fn as_int(&self) -> Option<i32> {
        Some(*self)
    }
}

impl Printf for u32 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        (*self as u64).format(spec)
    }
    fn as_int(&self) -> Option<i32> {
        i32::try_from(*self).ok()
    }
}

impl Printf for i16 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        match spec.conversion_type {
            // signed integer format
            ConversionType::DecInt => (*self as i64).format(spec),
            // unsigned-only formats
            ConversionType::HexIntLower | ConversionType::HexIntUpper | ConversionType::OctInt => {
                (*self as u16).format(spec)
            }
            _ => Err(PrintfError::WrongType),
        }
    }
    fn as_int(&self) -> Option<i32> {
        Some(*self as i32)
    }
}

impl Printf for u16 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        (*self as u64).format(spec)
    }
    fn as_int(&self) -> Option<i32> {
        Some(*self as i32)
    }
}

impl Printf for i8 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        match spec.conversion_type {
            // signed integer format
            ConversionType::DecInt => (*self as i64).format(spec),
            // unsigned-only formats
            ConversionType::HexIntLower | ConversionType::HexIntUpper | ConversionType::OctInt => {
                (*self as u8).format(spec)
            }
            _ => Err(PrintfError::WrongType),
        }
    }
    fn as_int(&self) -> Option<i32> {
        Some(*self as i32)
    }
}

impl Printf for u8 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        (*self as u64).format(spec)
    }
    fn as_int(&self) -> Option<i32> {
        Some(*self as i32)
    }
}

impl Printf for usize {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        (*self as u64).format(spec)
    }
    fn as_int(&self) -> Option<i32> {
        i32::try_from(*self).ok()
    }
}

impl Printf for isize {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        (*self as u64).format(spec)
    }
    fn as_int(&self) -> Option<i32> {
        i32::try_from(*self).ok()
    }
}

impl Printf for f64 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        let mut prefix = String::new();
        let mut number = String::new();

        // set up the sign
        if self.is_sign_negative() {
            prefix.push('-');
        } else if spec.space_sign {
            prefix.push(' ');
        } else if spec.force_sign {
            prefix.push('+');
        }

        if self.is_finite() {
            let mut use_scientific = false;
            let mut exp_symb = 'e';
            let mut strip_trailing_0s = false;
            let mut abs = self.abs();
            let mut exponent = abs.log10().floor() as i32;
            let mut precision = match spec.precision {
                NumericParam::Literal(p) => p,
                _ => {
                    return Err(PrintfError::Unknown);
                }
            };
            if precision <= 0 {
                precision = 0;
            }
            match spec.conversion_type {
                ConversionType::DecFloatLower | ConversionType::DecFloatUpper => {
                    // default
                }
                ConversionType::SciFloatLower => {
                    use_scientific = true;
                }
                ConversionType::SciFloatUpper => {
                    use_scientific = true;
                    exp_symb = 'E';
                }
                ConversionType::CompactFloatLower | ConversionType::CompactFloatUpper => {
                    if spec.conversion_type == ConversionType::CompactFloatUpper {
                        exp_symb = 'E'
                    }
                    strip_trailing_0s = true;
                    if precision == 0 {
                        precision = 1;
                    }
                    // exponent signifies significant digits - we must round now
                    // to (re)calculate the exponent
                    let rounding_factor = 10.0_f64.powf((precision - 1 - exponent) as f64);
                    let rounded_fixed = (abs * rounding_factor).round();
                    abs = rounded_fixed / rounding_factor;
                    exponent = abs.log10().floor() as i32;
                    if exponent < -4 || exponent >= precision {
                        use_scientific = true;
                        precision -= 1;
                    } else {
                        // precision specifies the number of significant digits
                        precision -= 1 + exponent;
                    }
                }
                _ => {
                    return Err(PrintfError::WrongType);
                }
            }

            if use_scientific {
                let mut normal = abs / 10.0_f64.powf(exponent as f64);

                if precision > 0 {
                    let mut int_part = normal.trunc();
                    let mut exp_factor = 10.0_f64.powf(precision as f64);
                    let mut tail = ((normal - int_part) * exp_factor).round() as u64;
                    while tail >= exp_factor as u64 {
                        // Overflow, must round
                        int_part += 1.0;
                        tail -= exp_factor as u64;
                        if int_part >= 10.0 {
                            // keep same precision - which means changing exponent
                            exponent += 1;
                            exp_factor /= 10.0;
                            normal /= 10.0;
                            int_part = normal.trunc();
                            tail = ((normal - int_part) * exp_factor).round() as u64;
                        }
                    }

                    let mut rev_tail_str = String::new();
                    for _ in 0..precision {
                        rev_tail_str.push((b'0' + (tail % 10) as u8) as char);
                        tail /= 10;
                    }
                    number.push_str(&format!("{}", int_part));
                    number.push('.');
                    number.push_str(&rev_tail_str.chars().rev().collect::<String>());
                    if strip_trailing_0s {
                        number = number.trim_end_matches('0').to_owned();
                    }
                } else {
                    number.push_str(&format!("{}", normal.round()));
                }
                number.push(exp_symb);
                number.push_str(&format!("{:+03}", exponent));
            } else {
                if precision > 0 {
                    let mut int_part = abs.trunc();
                    let exp_factor = 10.0_f64.powf(precision as f64);
                    let mut tail = ((abs - int_part) * exp_factor).round() as u64;
                    let mut rev_tail_str = String::new();
                    if tail >= exp_factor as u64 {
                        // overflow - we must round up
                        int_part += 1.0;
                        tail -= exp_factor as u64;
                        // no need to change the exponent as we don't have one
                        // (not scientific notation)
                    }
                    for _ in 0..precision {
                        rev_tail_str.push((b'0' + (tail % 10) as u8) as char);
                        tail /= 10;
                    }
                    number.push_str(&format!("{}", int_part));
                    number.push('.');
                    number.push_str(&rev_tail_str.chars().rev().collect::<String>());
                    if strip_trailing_0s {
                        number = number.trim_end_matches('0').to_owned();
                    }
                } else {
                    number.push_str(&format!("{}", abs.round()));
                }
            }
        } else {
            // not finite
            match spec.conversion_type {
                ConversionType::DecFloatLower
                | ConversionType::SciFloatLower
                | ConversionType::CompactFloatLower => {
                    if self.is_infinite() {
                        number.push_str("inf")
                    } else {
                        number.push_str("nan")
                    }
                }
                ConversionType::DecFloatUpper
                | ConversionType::SciFloatUpper
                | ConversionType::CompactFloatUpper => {
                    if self.is_infinite() {
                        number.push_str("INF")
                    } else {
                        number.push_str("NAN")
                    }
                }
                _ => {
                    return Err(PrintfError::WrongType);
                }
            }
        }
        // Take care of padding
        let width: usize = match spec.width {
            NumericParam::Literal(w) => w,
            _ => {
                return Err(PrintfError::Unknown); // should not happen at this point!!
            }
        }
        .try_into()
        .unwrap_or_default();
        let formatted = if spec.left_adj {
            let mut full_num = prefix + &number;
            while full_num.len() < width {
                full_num.push(' ');
            }
            full_num
        } else if spec.zero_pad && self.is_finite() {
            while prefix.len() + number.len() < width {
                prefix.push('0');
            }
            prefix + &number
        } else {
            let mut full_num = prefix + &number;
            while full_num.len() < width {
                full_num = " ".to_owned() + &full_num;
            }
            full_num
        };
        Ok(formatted)
    }
    fn as_int(&self) -> Option<i32> {
        None
    }
}

impl Printf for f32 {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        (*self as f64).format(spec)
    }
    fn as_int(&self) -> Option<i32> {
        None
    }
}

impl Printf for &str {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        if spec.conversion_type == ConversionType::String {
            Ok((*self).to_owned())
        } else {
            Err(PrintfError::WrongType)
        }
    }
    fn as_int(&self) -> Option<i32> {
        None
    }
}

impl Printf for char {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        if spec.conversion_type == ConversionType::Char {
            let mut s = String::new();
            s.push(*self);
            Ok(s)
        } else {
            Err(PrintfError::WrongType)
        }
    }
    fn as_int(&self) -> Option<i32> {
        None
    }
}

impl Printf for String {
    fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
        (self as &str).format(spec)
    }
    fn as_int(&self) -> Option<i32> {
        None
    }
}