1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Integer and floating-point number formatting
13 // FIXME: #6220 Implement floating point formatting
15 #![allow(unsigned_negation)]
18 use iter::IteratorExt;
23 /// A type that represents a specific radix
26 /// The number of digits.
29 /// A radix-specific prefix string.
30 fn prefix(&self) -> &'static str { "" }
32 /// Converts an integer to corresponding radix digit.
33 fn digit(&self, x: u8) -> u8;
35 /// Format an integer using the radix using a formatter.
36 fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
37 // The radix can be as low as 2, so we need a buffer of at least 64
38 // characters for a base 2 number.
39 let zero = Int::zero();
40 let is_positive = x >= zero;
41 let mut buf = [0u8; 64];
42 let mut curr = buf.len();
43 let base = cast(self.base()).unwrap();
45 // Accumulate each digit of the number from the least significant
46 // to the most significant figure.
47 for byte in buf.iter_mut().rev() {
48 let n = x % base; // Get the current place value.
49 x = x / base; // Deaccumulate the number.
50 *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
52 if x == zero { break }; // No more digits left to accumulate.
55 // Do the same as above, but accounting for two's complement.
56 for byte in buf.iter_mut().rev() {
57 let n = zero - (x % base); // Get the current place value.
58 x = x / base; // Deaccumulate the number.
59 *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
61 if x == zero { break }; // No more digits left to accumulate.
64 let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) };
65 f.pad_integral(is_positive, self.prefix(), buf)
69 /// A binary (base 2) radix
70 #[derive(Clone, PartialEq)]
73 /// An octal (base 8) radix
74 #[derive(Clone, PartialEq)]
77 /// A decimal (base 10) radix
78 #[derive(Clone, PartialEq)]
81 /// A hexadecimal (base 16) radix, formatted with lower-case characters
82 #[derive(Clone, PartialEq)]
85 /// A hexadecimal (base 16) radix, formatted with upper-case characters
86 #[derive(Clone, PartialEq)]
90 ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
91 impl GenericRadix for $T {
92 fn base(&self) -> u8 { $base }
93 fn prefix(&self) -> &'static str { $prefix }
94 fn digit(&self, x: u8) -> u8 {
97 x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
104 radix! { Binary, 2, "0b", x @ 0 ... 2 => b'0' + x }
105 radix! { Octal, 8, "0o", x @ 0 ... 7 => b'0' + x }
106 radix! { Decimal, 10, "", x @ 0 ... 9 => b'0' + x }
107 radix! { LowerHex, 16, "0x", x @ 0 ... 9 => b'0' + x,
108 x @ 10 ... 15 => b'a' + (x - 10) }
109 radix! { UpperHex, 16, "0x", x @ 0 ... 9 => b'0' + x,
110 x @ 10 ... 15 => b'A' + (x - 10) }
112 /// A radix with in the range of `2..36`.
113 #[derive(Clone, Copy, PartialEq)]
114 #[unstable = "may be renamed or move to a different module"]
120 fn new(base: u8) -> Radix {
121 assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
126 impl GenericRadix for Radix {
127 fn base(&self) -> u8 { self.base }
128 fn digit(&self, x: u8) -> u8 {
130 x @ 0 ... 9 => b'0' + x,
131 x if x < self.base() => b'a' + (x - 10),
132 x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
137 /// A helper type for formatting radixes.
138 #[unstable = "may be renamed or move to a different module"]
140 pub struct RadixFmt<T, R>(T, R);
142 /// Constructs a radix formatter in the range of `2..36`.
147 /// use std::fmt::radix;
148 /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
150 #[unstable = "may be renamed or move to a different module"]
151 pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
152 RadixFmt(x, Radix::new(base))
155 macro_rules! radix_fmt {
156 ($T:ty as $U:ty, $fmt:ident, $S:expr) => {
157 impl fmt::Show for RadixFmt<$T, Radix> {
158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
159 try!(fmt::String::fmt(self, f));
163 impl fmt::String for RadixFmt<$T, Radix> {
164 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
170 macro_rules! int_base {
171 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
172 impl fmt::$Trait for $T {
173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
174 $Radix.fmt_int(*self as $U, f)
181 ($T:ident with $S:expr) => {
182 impl fmt::Show for $T {
183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184 try!(fmt::String::fmt(self, f));
190 macro_rules! integer {
191 ($Int:ident, $Uint:ident) => {
192 integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) }
194 ($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => {
195 int_base! { String for $Int as $Int -> Decimal }
196 int_base! { Binary for $Int as $Uint -> Binary }
197 int_base! { Octal for $Int as $Uint -> Octal }
198 int_base! { LowerHex for $Int as $Uint -> LowerHex }
199 int_base! { UpperHex for $Int as $Uint -> UpperHex }
200 radix_fmt! { $Int as $Int, fmt_int, $SI }
201 show! { $Int with $SI }
203 int_base! { String for $Uint as $Uint -> Decimal }
204 int_base! { Binary for $Uint as $Uint -> Binary }
205 int_base! { Octal for $Uint as $Uint -> Octal }
206 int_base! { LowerHex for $Uint as $Uint -> LowerHex }
207 int_base! { UpperHex for $Uint as $Uint -> UpperHex }
208 radix_fmt! { $Uint as $Uint, fmt_int, $SU }
209 show! { $Uint with $SU }
212 integer! { int, uint, "i", "u" }
214 integer! { i16, u16 }
215 integer! { i32, u32 }
216 integer! { i64, u64 }