@@ -511,9 +511,9 @@ impl fmt::Debug for Duration {
511
511
// The next digit is written at this position
512
512
let mut pos = 0 ;
513
513
514
- // We can stop when there are no non-zero digits left or (when a
515
- // precision was set and we already emitted that many digits) .
516
- while fractional_part > 0 && f. precision ( ) . map ( |p| p > pos ) . unwrap_or ( true ) {
514
+ // We keep writing digits into the buffer while there are non-zero
515
+ // digits left and we haven't written enough digits yet .
516
+ while fractional_part > 0 && pos < f. precision ( ) . unwrap_or ( 9 ) {
517
517
// Write new digit into the buffer
518
518
buf[ pos] = b'0' + ( fractional_part / divisor) as u8 ;
519
519
@@ -556,9 +556,13 @@ impl fmt::Debug for Duration {
556
556
}
557
557
}
558
558
559
+ // Determine the end of the buffer: if precision is set, we just
560
+ // use as many digits from the buffer (capped to 9). If it isn't
561
+ // set, we only use all digits up to the last non-zero one.
562
+ let end = f. precision ( ) . map ( |p| :: cmp:: min ( p, 9 ) ) . unwrap_or ( pos) ;
563
+
559
564
// If we haven't emitted a single fractional digit and the precision
560
565
// wasn't set to a non-zero value, we don't print the decimal point.
561
- let end = f. precision ( ) . unwrap_or ( pos) ;
562
566
if end == 0 {
563
567
write ! ( f, "{}" , integer_part)
564
568
} else {
@@ -568,7 +572,9 @@ impl fmt::Debug for Duration {
568
572
:: str:: from_utf8_unchecked ( & buf[ ..end] )
569
573
} ;
570
574
571
- write ! ( f, "{}.{}" , integer_part, s)
575
+ // If the user request a precision > 9, we pad '0's at the end.
576
+ let w = f. precision ( ) . unwrap_or ( pos) ;
577
+ write ! ( f, "{}.{:0<width$}" , integer_part, s, width = w)
572
578
}
573
579
}
574
580
@@ -587,7 +593,8 @@ impl fmt::Debug for Duration {
587
593
fmt_decimal ( f, self . nanos as u64 / 1_000 , self . nanos % 1_000 , 100 ) ?;
588
594
f. write_str ( "µs" )
589
595
} else {
590
- write ! ( f, "{}ns" , self . nanos)
596
+ fmt_decimal ( f, self . nanos as u64 , 0 , 1 ) ?;
597
+ f. write_str ( "ns" )
591
598
}
592
599
}
593
600
}
0 commit comments