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)]
21 use ops::{Div, Rem, Sub};
25 trait Int: Zero + PartialEq + PartialOrd + Div<Output=Self> + Rem<Output=Self> +
26 Sub<Output=Self> + Copy {
27 fn from_u8(u: u8) -> Self;
28 fn to_u8(&self) -> u8;
32 ($($t:ident)*) => ($(impl Int for $t {
33 fn from_u8(u: u8) -> $t { u as $t }
34 fn to_u8(&self) -> u8 { *self as u8 }
37 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
39 /// A type that represents a specific radix
42 /// The number of digits.
45 /// A radix-specific prefix string.
46 fn prefix(&self) -> &'static str { "" }
48 /// Converts an integer to corresponding radix digit.
49 fn digit(&self, x: u8) -> u8;
51 /// Format an integer using the radix using a formatter.
52 fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
53 // The radix can be as low as 2, so we need a buffer of at least 64
54 // characters for a base 2 number.
56 let is_positive = x >= zero;
57 let mut buf = [0; 64];
58 let mut curr = buf.len();
59 let base = T::from_u8(self.base());
61 // Accumulate each digit of the number from the least significant
62 // to the most significant figure.
63 for byte in buf.iter_mut().rev() {
64 let n = x % base; // Get the current place value.
65 x = x / base; // Deaccumulate the number.
66 *byte = self.digit(n.to_u8()); // Store the digit in the buffer.
68 if x == zero { break }; // No more digits left to accumulate.
71 // Do the same as above, but accounting for two's complement.
72 for byte in buf.iter_mut().rev() {
73 let n = zero - (x % base); // Get the current place value.
74 x = x / base; // Deaccumulate the number.
75 *byte = self.digit(n.to_u8()); // Store the digit in the buffer.
77 if x == zero { break }; // No more digits left to accumulate.
80 let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) };
81 f.pad_integral(is_positive, self.prefix(), buf)
85 /// A binary (base 2) radix
86 #[derive(Clone, PartialEq)]
89 /// An octal (base 8) radix
90 #[derive(Clone, PartialEq)]
93 /// A decimal (base 10) radix
94 #[derive(Clone, PartialEq)]
97 /// A hexadecimal (base 16) radix, formatted with lower-case characters
98 #[derive(Clone, PartialEq)]
101 /// A hexadecimal (base 16) radix, formatted with upper-case characters
102 #[derive(Clone, PartialEq)]
106 ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
107 impl GenericRadix for $T {
108 fn base(&self) -> u8 { $base }
109 fn prefix(&self) -> &'static str { $prefix }
110 fn digit(&self, x: u8) -> u8 {
113 x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
120 radix! { Binary, 2, "0b", x @ 0 ... 2 => b'0' + x }
121 radix! { Octal, 8, "0o", x @ 0 ... 7 => b'0' + x }
122 radix! { Decimal, 10, "", x @ 0 ... 9 => b'0' + x }
123 radix! { LowerHex, 16, "0x", x @ 0 ... 9 => b'0' + x,
124 x @ 10 ... 15 => b'a' + (x - 10) }
125 radix! { UpperHex, 16, "0x", x @ 0 ... 9 => b'0' + x,
126 x @ 10 ... 15 => b'A' + (x - 10) }
128 /// A radix with in the range of `2..36`.
129 #[derive(Clone, Copy, PartialEq)]
130 #[unstable(feature = "core",
131 reason = "may be renamed or move to a different module")]
137 fn new(base: u8) -> Radix {
138 assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
143 impl GenericRadix for Radix {
144 fn base(&self) -> u8 { self.base }
145 fn digit(&self, x: u8) -> u8 {
147 x @ 0 ... 9 => b'0' + x,
148 x if x < self.base() => b'a' + (x - 10),
149 x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
154 /// A helper type for formatting radixes.
155 #[unstable(feature = "core",
156 reason = "may be renamed or move to a different module")]
157 #[derive(Copy, Clone)]
158 pub struct RadixFmt<T, R>(T, R);
160 /// Constructs a radix formatter in the range of `2..36`.
165 /// # #![feature(core)]
166 /// use std::fmt::radix;
167 /// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
169 #[unstable(feature = "core",
170 reason = "may be renamed or move to a different module")]
171 pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
172 RadixFmt(x, Radix::new(base))
175 macro_rules! radix_fmt {
176 ($T:ty as $U:ty, $fmt:ident) => {
177 #[stable(feature = "rust1", since = "1.0.0")]
178 impl fmt::Debug for RadixFmt<$T, Radix> {
179 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
180 fmt::Display::fmt(self, f)
183 #[stable(feature = "rust1", since = "1.0.0")]
184 impl fmt::Display for RadixFmt<$T, Radix> {
185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
186 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
191 macro_rules! int_base {
192 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
193 #[stable(feature = "rust1", since = "1.0.0")]
194 impl fmt::$Trait for $T {
195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
196 $Radix.fmt_int(*self as $U, f)
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl fmt::Debug for $T {
206 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207 fmt::Display::fmt(self, f)
212 macro_rules! integer {
213 ($Int:ident, $Uint:ident) => {
214 int_base! { Display for $Int as $Int -> Decimal }
215 int_base! { Binary for $Int as $Uint -> Binary }
216 int_base! { Octal for $Int as $Uint -> Octal }
217 int_base! { LowerHex for $Int as $Uint -> LowerHex }
218 int_base! { UpperHex for $Int as $Uint -> UpperHex }
219 radix_fmt! { $Int as $Int, fmt_int }
222 int_base! { Display for $Uint as $Uint -> Decimal }
223 int_base! { Binary for $Uint as $Uint -> Binary }
224 int_base! { Octal for $Uint as $Uint -> Octal }
225 int_base! { LowerHex for $Uint as $Uint -> LowerHex }
226 int_base! { UpperHex for $Uint as $Uint -> UpperHex }
227 radix_fmt! { $Uint as $Uint, fmt_int }
231 integer! { isize, usize }
233 integer! { i16, u16 }
234 integer! { i32, u32 }
235 integer! { i64, u64 }