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_negate)]
17 use collections::Collection;
19 use iter::{Iterator, DoubleEndedIterator};
20 use num::{Int, cast, zero};
21 use option::{Some, None};
22 use slice::{ImmutableVector, MutableVector};
24 /// 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 mut buf = [0u8, ..64];
40 let base = cast(self.base()).unwrap();
41 let mut curr = buf.len();
42 let is_positive = x >= zero();
44 // Accumulate each digit of the number from the least significant
45 // to the most significant figure.
46 for byte in buf.mut_iter().rev() {
47 let n = x % base; // Get the current place value.
48 x = x / base; // Deaccumulate the number.
49 *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
51 if x == zero() { break; } // No more digits left to accumulate.
54 // Do the same as above, but accounting for two's complement.
55 for byte in buf.mut_iter().rev() {
56 let n = -(x % base); // Get the current place value.
57 x = x / base; // Deaccumulate the number.
58 *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
60 if x == zero() { break; } // No more digits left to accumulate.
63 f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr))
67 /// A binary (base 2) radix
68 #[deriving(Clone, PartialEq)]
71 /// An octal (base 8) radix
72 #[deriving(Clone, PartialEq)]
75 /// A decimal (base 10) radix
76 #[deriving(Clone, PartialEq)]
79 /// A hexadecimal (base 16) radix, formatted with lower-case characters
80 #[deriving(Clone, PartialEq)]
83 /// A hexadecimal (base 16) radix, formatted with upper-case characters
84 #[deriving(Clone, PartialEq)]
88 ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
89 impl GenericRadix for $T {
90 fn base(&self) -> u8 { $base }
91 fn prefix(&self) -> &'static str { $prefix }
92 fn digit(&self, x: u8) -> u8 {
95 x => fail!("number not in the range 0..{}: {}", self.base() - 1, x),
102 radix!(Binary, 2, "0b", x @ 0 .. 2 => '0' as u8 + x)
103 radix!(Octal, 8, "0o", x @ 0 .. 7 => '0' as u8 + x)
104 radix!(Decimal, 10, "", x @ 0 .. 9 => '0' as u8 + x)
105 radix!(LowerHex, 16, "0x", x @ 0 .. 9 => '0' as u8 + x,
106 x @ 10 ..15 => 'a' as u8 + (x - 10))
107 radix!(UpperHex, 16, "0x", x @ 0 .. 9 => '0' as u8 + x,
108 x @ 10 ..15 => 'A' as u8 + (x - 10))
110 /// A radix with in the range of `2..36`.
111 #[deriving(Clone, PartialEq)]
117 fn new(base: u8) -> Radix {
118 assert!(2 <= base && base <= 36, "the base must be in the range of 0..36: {}", base);
123 impl GenericRadix for Radix {
124 fn base(&self) -> u8 { self.base }
125 fn digit(&self, x: u8) -> u8 {
127 x @ 0 ..9 => '0' as u8 + x,
128 x if x < self.base() => 'a' as u8 + (x - 10),
129 x => fail!("number not in the range 0..{}: {}", self.base() - 1, x),
134 /// A helper type for formatting radixes.
135 pub struct RadixFmt<T, R>(T, R);
137 /// Constructs a radix formatter in the range of `2..36`.
142 /// use std::fmt::radix;
143 /// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
145 pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
146 RadixFmt(x, Radix::new(base))
149 macro_rules! radix_fmt {
150 ($T:ty as $U:ty, $fmt:ident) => {
151 impl fmt::Show for RadixFmt<$T, Radix> {
152 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
153 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
158 macro_rules! int_base {
159 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
160 impl fmt::$Trait for $T {
161 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162 $Radix.fmt_int(*self as $U, f)
167 macro_rules! integer {
168 ($Int:ident, $Uint:ident) => {
169 int_base!(Show for $Int as $Int -> Decimal)
170 int_base!(Signed for $Int as $Int -> Decimal)
171 int_base!(Binary for $Int as $Uint -> Binary)
172 int_base!(Octal for $Int as $Uint -> Octal)
173 int_base!(LowerHex for $Int as $Uint -> LowerHex)
174 int_base!(UpperHex for $Int as $Uint -> UpperHex)
175 radix_fmt!($Int as $Int, fmt_int)
177 int_base!(Show for $Uint as $Uint -> Decimal)
178 int_base!(Unsigned for $Uint as $Uint -> Decimal)
179 int_base!(Binary for $Uint as $Uint -> Binary)
180 int_base!(Octal for $Uint as $Uint -> Octal)
181 int_base!(LowerHex for $Uint as $Uint -> LowerHex)
182 int_base!(UpperHex for $Uint as $Uint -> UpperHex)
183 radix_fmt!($Uint as $Uint, fmt_int)
195 use super::{Binary, Octal, Decimal, LowerHex, UpperHex};
196 use super::{GenericRadix, Radix};
197 use realstd::str::Str;
200 fn test_radix_base() {
201 assert_eq!(Binary.base(), 2);
202 assert_eq!(Octal.base(), 8);
203 assert_eq!(Decimal.base(), 10);
204 assert_eq!(LowerHex.base(), 16);
205 assert_eq!(UpperHex.base(), 16);
206 assert_eq!(Radix { base: 36 }.base(), 36);
210 fn test_radix_prefix() {
211 assert_eq!(Binary.prefix(), "0b");
212 assert_eq!(Octal.prefix(), "0o");
213 assert_eq!(Decimal.prefix(), "");
214 assert_eq!(LowerHex.prefix(), "0x");
215 assert_eq!(UpperHex.prefix(), "0x");
216 assert_eq!(Radix { base: 36 }.prefix(), "");
220 fn test_radix_digit() {
221 assert_eq!(Binary.digit(0), '0' as u8);
222 assert_eq!(Binary.digit(2), '2' as u8);
223 assert_eq!(Octal.digit(0), '0' as u8);
224 assert_eq!(Octal.digit(7), '7' as u8);
225 assert_eq!(Decimal.digit(0), '0' as u8);
226 assert_eq!(Decimal.digit(9), '9' as u8);
227 assert_eq!(LowerHex.digit(0), '0' as u8);
228 assert_eq!(LowerHex.digit(10), 'a' as u8);
229 assert_eq!(LowerHex.digit(15), 'f' as u8);
230 assert_eq!(UpperHex.digit(0), '0' as u8);
231 assert_eq!(UpperHex.digit(10), 'A' as u8);
232 assert_eq!(UpperHex.digit(15), 'F' as u8);
233 assert_eq!(Radix { base: 36 }.digit(0), '0' as u8);
234 assert_eq!(Radix { base: 36 }.digit(15), 'f' as u8);
235 assert_eq!(Radix { base: 36 }.digit(35), 'z' as u8);
240 fn test_hex_radix_digit_overflow() {
241 let _ = LowerHex.digit(16);
245 fn test_format_int() {
246 // Formatting integers should select the right implementation based off
247 // the type of the argument. Also, hex/octal/binary should be defined
248 // for integers, but they shouldn't emit the negative sign.
249 assert!(format!("{}", 1i).as_slice() == "1");
250 assert!(format!("{}", 1i8).as_slice() == "1");
251 assert!(format!("{}", 1i16).as_slice() == "1");
252 assert!(format!("{}", 1i32).as_slice() == "1");
253 assert!(format!("{}", 1i64).as_slice() == "1");
254 assert!(format!("{:d}", -1i).as_slice() == "-1");
255 assert!(format!("{:d}", -1i8).as_slice() == "-1");
256 assert!(format!("{:d}", -1i16).as_slice() == "-1");
257 assert!(format!("{:d}", -1i32).as_slice() == "-1");
258 assert!(format!("{:d}", -1i64).as_slice() == "-1");
259 assert!(format!("{:t}", 1i).as_slice() == "1");
260 assert!(format!("{:t}", 1i8).as_slice() == "1");
261 assert!(format!("{:t}", 1i16).as_slice() == "1");
262 assert!(format!("{:t}", 1i32).as_slice() == "1");
263 assert!(format!("{:t}", 1i64).as_slice() == "1");
264 assert!(format!("{:x}", 1i).as_slice() == "1");
265 assert!(format!("{:x}", 1i8).as_slice() == "1");
266 assert!(format!("{:x}", 1i16).as_slice() == "1");
267 assert!(format!("{:x}", 1i32).as_slice() == "1");
268 assert!(format!("{:x}", 1i64).as_slice() == "1");
269 assert!(format!("{:X}", 1i).as_slice() == "1");
270 assert!(format!("{:X}", 1i8).as_slice() == "1");
271 assert!(format!("{:X}", 1i16).as_slice() == "1");
272 assert!(format!("{:X}", 1i32).as_slice() == "1");
273 assert!(format!("{:X}", 1i64).as_slice() == "1");
274 assert!(format!("{:o}", 1i).as_slice() == "1");
275 assert!(format!("{:o}", 1i8).as_slice() == "1");
276 assert!(format!("{:o}", 1i16).as_slice() == "1");
277 assert!(format!("{:o}", 1i32).as_slice() == "1");
278 assert!(format!("{:o}", 1i64).as_slice() == "1");
280 assert!(format!("{}", 1u).as_slice() == "1");
281 assert!(format!("{}", 1u8).as_slice() == "1");
282 assert!(format!("{}", 1u16).as_slice() == "1");
283 assert!(format!("{}", 1u32).as_slice() == "1");
284 assert!(format!("{}", 1u64).as_slice() == "1");
285 assert!(format!("{:u}", 1u).as_slice() == "1");
286 assert!(format!("{:u}", 1u8).as_slice() == "1");
287 assert!(format!("{:u}", 1u16).as_slice() == "1");
288 assert!(format!("{:u}", 1u32).as_slice() == "1");
289 assert!(format!("{:u}", 1u64).as_slice() == "1");
290 assert!(format!("{:t}", 1u).as_slice() == "1");
291 assert!(format!("{:t}", 1u8).as_slice() == "1");
292 assert!(format!("{:t}", 1u16).as_slice() == "1");
293 assert!(format!("{:t}", 1u32).as_slice() == "1");
294 assert!(format!("{:t}", 1u64).as_slice() == "1");
295 assert!(format!("{:x}", 1u).as_slice() == "1");
296 assert!(format!("{:x}", 1u8).as_slice() == "1");
297 assert!(format!("{:x}", 1u16).as_slice() == "1");
298 assert!(format!("{:x}", 1u32).as_slice() == "1");
299 assert!(format!("{:x}", 1u64).as_slice() == "1");
300 assert!(format!("{:X}", 1u).as_slice() == "1");
301 assert!(format!("{:X}", 1u8).as_slice() == "1");
302 assert!(format!("{:X}", 1u16).as_slice() == "1");
303 assert!(format!("{:X}", 1u32).as_slice() == "1");
304 assert!(format!("{:X}", 1u64).as_slice() == "1");
305 assert!(format!("{:o}", 1u).as_slice() == "1");
306 assert!(format!("{:o}", 1u8).as_slice() == "1");
307 assert!(format!("{:o}", 1u16).as_slice() == "1");
308 assert!(format!("{:o}", 1u32).as_slice() == "1");
309 assert!(format!("{:o}", 1u64).as_slice() == "1");
311 // Test a larger number
312 assert!(format!("{:t}", 55).as_slice() == "110111");
313 assert!(format!("{:o}", 55).as_slice() == "67");
314 assert!(format!("{:d}", 55).as_slice() == "55");
315 assert!(format!("{:x}", 55).as_slice() == "37");
316 assert!(format!("{:X}", 55).as_slice() == "37");
320 fn test_format_int_zero() {
321 assert!(format!("{}", 0i).as_slice() == "0");
322 assert!(format!("{:d}", 0i).as_slice() == "0");
323 assert!(format!("{:t}", 0i).as_slice() == "0");
324 assert!(format!("{:o}", 0i).as_slice() == "0");
325 assert!(format!("{:x}", 0i).as_slice() == "0");
326 assert!(format!("{:X}", 0i).as_slice() == "0");
328 assert!(format!("{}", 0u).as_slice() == "0");
329 assert!(format!("{:u}", 0u).as_slice() == "0");
330 assert!(format!("{:t}", 0u).as_slice() == "0");
331 assert!(format!("{:o}", 0u).as_slice() == "0");
332 assert!(format!("{:x}", 0u).as_slice() == "0");
333 assert!(format!("{:X}", 0u).as_slice() == "0");
337 fn test_format_int_flags() {
338 assert!(format!("{:3d}", 1).as_slice() == " 1");
339 assert!(format!("{:>3d}", 1).as_slice() == " 1");
340 assert!(format!("{:>+3d}", 1).as_slice() == " +1");
341 assert!(format!("{:<3d}", 1).as_slice() == "1 ");
342 assert!(format!("{:#d}", 1).as_slice() == "1");
343 assert!(format!("{:#x}", 10).as_slice() == "0xa");
344 assert!(format!("{:#X}", 10).as_slice() == "0xA");
345 assert!(format!("{:#5x}", 10).as_slice() == " 0xa");
346 assert!(format!("{:#o}", 10).as_slice() == "0o12");
347 assert!(format!("{:08x}", 10).as_slice() == "0000000a");
348 assert!(format!("{:8x}", 10).as_slice() == " a");
349 assert!(format!("{:<8x}", 10).as_slice() == "a ");
350 assert!(format!("{:>8x}", 10).as_slice() == " a");
351 assert!(format!("{:#08x}", 10).as_slice() == "0x00000a");
352 assert!(format!("{:08d}", -10).as_slice() == "-0000010");
353 assert!(format!("{:x}", -1u8).as_slice() == "ff");
354 assert!(format!("{:X}", -1u8).as_slice() == "FF");
355 assert!(format!("{:t}", -1u8).as_slice() == "11111111");
356 assert!(format!("{:o}", -1u8).as_slice() == "377");
357 assert!(format!("{:#x}", -1u8).as_slice() == "0xff");
358 assert!(format!("{:#X}", -1u8).as_slice() == "0xFF");
359 assert!(format!("{:#t}", -1u8).as_slice() == "0b11111111");
360 assert!(format!("{:#o}", -1u8).as_slice() == "0o377");
364 fn test_format_int_sign_padding() {
365 assert!(format!("{:+5d}", 1).as_slice() == " +1");
366 assert!(format!("{:+5d}", -1).as_slice() == " -1");
367 assert!(format!("{:05d}", 1).as_slice() == "00001");
368 assert!(format!("{:05d}", -1).as_slice() == "-0001");
369 assert!(format!("{:+05d}", 1).as_slice() == "+0001");
370 assert!(format!("{:+05d}", -1).as_slice() == "-0001");
374 fn test_format_int_twos_complement() {
375 use {i8, i16, i32, i64};
376 assert!(format!("{}", i8::MIN).as_slice() == "-128");
377 assert!(format!("{}", i16::MIN).as_slice() == "-32768");
378 assert!(format!("{}", i32::MIN).as_slice() == "-2147483648");
379 assert!(format!("{}", i64::MIN).as_slice() == "-9223372036854775808");
383 fn test_format_radix() {
384 assert!(format!("{:04}", radix(3, 2)).as_slice() == "0011");
385 assert!(format!("{}", radix(55, 36)).as_slice() == "1j");
390 fn test_radix_base_too_large() {
391 let _ = radix(55, 37);
400 use super::test::Bencher;
402 use realstd::rand::{weak_rng, Rng};
405 fn format_bin(b: &mut Bencher) {
406 let mut rng = weak_rng();
407 b.iter(|| { format!("{:t}", rng.gen::<uint>()); })
411 fn format_oct(b: &mut Bencher) {
412 let mut rng = weak_rng();
413 b.iter(|| { format!("{:o}", rng.gen::<uint>()); })
417 fn format_dec(b: &mut Bencher) {
418 let mut rng = weak_rng();
419 b.iter(|| { format!("{:u}", rng.gen::<uint>()); })
423 fn format_hex(b: &mut Bencher) {
424 let mut rng = weak_rng();
425 b.iter(|| { format!("{:x}", rng.gen::<uint>()); })
429 fn format_base_36(b: &mut Bencher) {
430 let mut rng = weak_rng();
431 b.iter(|| { format!("{}", radix(rng.gen::<uint>(), 36)); })
436 use super::test::Bencher;
438 use realstd::rand::{weak_rng, Rng};
441 fn format_bin(b: &mut Bencher) {
442 let mut rng = weak_rng();
443 b.iter(|| { format!("{:t}", rng.gen::<int>()); })
447 fn format_oct(b: &mut Bencher) {
448 let mut rng = weak_rng();
449 b.iter(|| { format!("{:o}", rng.gen::<int>()); })
453 fn format_dec(b: &mut Bencher) {
454 let mut rng = weak_rng();
455 b.iter(|| { format!("{:d}", rng.gen::<int>()); })
459 fn format_hex(b: &mut Bencher) {
460 let mut rng = weak_rng();
461 b.iter(|| { format!("{:x}", rng.gen::<int>()); })
465 fn format_base_36(b: &mut Bencher) {
466 let mut rng = weak_rng();
467 b.iter(|| { format!("{}", radix(rng.gen::<int>(), 36)); })