]> git.lizzy.rs Git - rust.git/blob - src/libstd/fmt/num.rs
auto merge of #13600 : brandonw/rust/master, r=brson
[rust.git] / src / libstd / fmt / num.rs
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.
4 //
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.
10
11 //! Integer and floating-point number formatting
12
13 // FIXME: #6220 Implement floating point formatting
14
15 use container::Container;
16 use fmt;
17 use iter::{Iterator, DoubleEndedIterator};
18 use num::{Int, cast, zero};
19 use option::{Some, None};
20 use slice::{ImmutableVector, MutableVector};
21
22 /// A type that represents a specific radix
23 trait GenericRadix {
24     /// The number of digits.
25     fn base(&self) -> u8;
26
27     /// A radix-specific prefix string.
28     fn prefix(&self) -> &'static str { "" }
29
30     /// Converts an integer to corresponding radix digit.
31     fn digit(&self, x: u8) -> u8;
32
33     /// Format an integer using the radix using a formatter.
34     fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
35         // The radix can be as low as 2, so we need a buffer of at least 64
36         // characters for a base 2 number.
37         let mut buf = [0u8, ..64];
38         let base = cast(self.base()).unwrap();
39         let mut curr = buf.len();
40         let is_positive = x >= zero();
41         if is_positive {
42             // Accumulate each digit of the number from the least significant
43             // to the most significant figure.
44             for byte in buf.mut_iter().rev() {
45                 let n = x % base;                         // Get the current place value.
46                 x = x / base;                             // Deaccumulate the number.
47                 *byte = self.digit(cast(n).unwrap());     // Store the digit in the buffer.
48                 curr -= 1;
49                 if x == zero() { break; }                 // No more digits left to accumulate.
50             }
51         } else {
52             // Do the same as above, but accounting for two's complement.
53             for byte in buf.mut_iter().rev() {
54                 let n = -(x % base);                      // Get the current place value.
55                 x = x / base;                             // Deaccumulate the number.
56                 *byte = self.digit(cast(n).unwrap());     // Store the digit in the buffer.
57                 curr -= 1;
58                 if x == zero() { break; }                 // No more digits left to accumulate.
59             }
60         }
61         f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr))
62     }
63 }
64
65 /// A binary (base 2) radix
66 #[deriving(Clone, Eq)]
67 struct Binary;
68
69 /// An octal (base 8) radix
70 #[deriving(Clone, Eq)]
71 struct Octal;
72
73 /// A decimal (base 10) radix
74 #[deriving(Clone, Eq)]
75 struct Decimal;
76
77 /// A hexidecimal (base 16) radix, formatted with lower-case characters
78 #[deriving(Clone, Eq)]
79 struct LowerHex;
80
81 /// A hexidecimal (base 16) radix, formatted with upper-case characters
82 #[deriving(Clone, Eq)]
83 pub struct UpperHex;
84
85 macro_rules! radix {
86     ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
87         impl GenericRadix for $T {
88             fn base(&self) -> u8 { $base }
89             fn prefix(&self) -> &'static str { $prefix }
90             fn digit(&self, x: u8) -> u8 {
91                 match x {
92                     $($x => $conv,)+
93                     x => fail!("number not in the range 0..{}: {}", self.base() - 1, x),
94                 }
95             }
96         }
97     }
98 }
99
100 radix!(Binary,    2, "0b", x @  0 .. 2 => '0' as u8 + x)
101 radix!(Octal,     8, "0o", x @  0 .. 7 => '0' as u8 + x)
102 radix!(Decimal,  10, "",   x @  0 .. 9 => '0' as u8 + x)
103 radix!(LowerHex, 16, "0x", x @  0 .. 9 => '0' as u8 + x,
104                            x @ 10 ..15 => 'a' as u8 + (x - 10))
105 radix!(UpperHex, 16, "0x", x @  0 .. 9 => '0' as u8 + x,
106                            x @ 10 ..15 => 'A' as u8 + (x - 10))
107
108 /// A radix with in the range of `2..36`.
109 #[deriving(Clone, Eq)]
110 pub struct Radix {
111     base: u8,
112 }
113
114 impl Radix {
115     fn new(base: u8) -> Radix {
116         assert!(2 <= base && base <= 36, "the base must be in the range of 0..36: {}", base);
117         Radix { base: base }
118     }
119 }
120
121 impl GenericRadix for Radix {
122     fn base(&self) -> u8 { self.base }
123     fn digit(&self, x: u8) -> u8 {
124         match x {
125             x @  0 ..9 => '0' as u8 + x,
126             x if x < self.base() => 'a' as u8 + (x - 10),
127             x => fail!("number not in the range 0..{}: {}", self.base() - 1, x),
128         }
129     }
130 }
131
132 /// A helper type for formatting radixes.
133 pub struct RadixFmt<T, R>(T, R);
134
135 /// Constructs a radix formatter in the range of `2..36`.
136 ///
137 /// # Example
138 ///
139 /// ~~~
140 /// use std::fmt::radix;
141 /// assert_eq!(format!("{}", radix(55, 36)), ~"1j");
142 /// ~~~
143 pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
144     RadixFmt(x, Radix::new(base))
145 }
146
147 macro_rules! radix_fmt {
148     ($T:ty as $U:ty, $fmt:ident) => {
149         impl fmt::Show for RadixFmt<$T, Radix> {
150             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
151                 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
152             }
153         }
154     }
155 }
156 macro_rules! int_base {
157     ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
158         impl fmt::$Trait for $T {
159             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
160                 $Radix.fmt_int(*self as $U, f)
161             }
162         }
163     }
164 }
165 macro_rules! integer {
166     ($Int:ident, $Uint:ident) => {
167         int_base!(Show     for $Int as $Int   -> Decimal)
168         int_base!(Signed   for $Int as $Int   -> Decimal)
169         int_base!(Binary   for $Int as $Uint  -> Binary)
170         int_base!(Octal    for $Int as $Uint  -> Octal)
171         int_base!(LowerHex for $Int as $Uint  -> LowerHex)
172         int_base!(UpperHex for $Int as $Uint  -> UpperHex)
173         radix_fmt!($Int as $Uint, fmt_int)
174
175         int_base!(Show     for $Uint as $Uint -> Decimal)
176         int_base!(Unsigned for $Uint as $Uint -> Decimal)
177         int_base!(Binary   for $Uint as $Uint -> Binary)
178         int_base!(Octal    for $Uint as $Uint -> Octal)
179         int_base!(LowerHex for $Uint as $Uint -> LowerHex)
180         int_base!(UpperHex for $Uint as $Uint -> UpperHex)
181         radix_fmt!($Uint as $Uint, fmt_int)
182     }
183 }
184 integer!(int, uint)
185 integer!(i8, u8)
186 integer!(i16, u16)
187 integer!(i32, u32)
188 integer!(i64, u64)
189
190 #[cfg(test)]
191 mod tests {
192     use fmt::radix;
193     use super::{Binary, Octal, Decimal, LowerHex, UpperHex};
194     use super::{GenericRadix, Radix};
195
196     #[test]
197     fn test_radix_base() {
198         assert_eq!(Binary.base(), 2);
199         assert_eq!(Octal.base(), 8);
200         assert_eq!(Decimal.base(), 10);
201         assert_eq!(LowerHex.base(), 16);
202         assert_eq!(UpperHex.base(), 16);
203         assert_eq!(Radix { base: 36 }.base(), 36);
204     }
205
206     #[test]
207     fn test_radix_prefix() {
208         assert_eq!(Binary.prefix(), "0b");
209         assert_eq!(Octal.prefix(), "0o");
210         assert_eq!(Decimal.prefix(), "");
211         assert_eq!(LowerHex.prefix(), "0x");
212         assert_eq!(UpperHex.prefix(), "0x");
213         assert_eq!(Radix { base: 36 }.prefix(), "");
214     }
215
216     #[test]
217     fn test_radix_digit() {
218         assert_eq!(Binary.digit(0), '0' as u8);
219         assert_eq!(Binary.digit(2), '2' as u8);
220         assert_eq!(Octal.digit(0), '0' as u8);
221         assert_eq!(Octal.digit(7), '7' as u8);
222         assert_eq!(Decimal.digit(0), '0' as u8);
223         assert_eq!(Decimal.digit(9), '9' as u8);
224         assert_eq!(LowerHex.digit(0), '0' as u8);
225         assert_eq!(LowerHex.digit(10), 'a' as u8);
226         assert_eq!(LowerHex.digit(15), 'f' as u8);
227         assert_eq!(UpperHex.digit(0), '0' as u8);
228         assert_eq!(UpperHex.digit(10), 'A' as u8);
229         assert_eq!(UpperHex.digit(15), 'F' as u8);
230         assert_eq!(Radix { base: 36 }.digit(0), '0' as u8);
231         assert_eq!(Radix { base: 36 }.digit(15), 'f' as u8);
232         assert_eq!(Radix { base: 36 }.digit(35), 'z' as u8);
233     }
234
235     #[test]
236     #[should_fail]
237     fn test_hex_radix_digit_overflow() {
238         let _ = LowerHex.digit(16);
239     }
240
241     #[test]
242     fn test_format_int() {
243         // Formatting integers should select the right implementation based off
244         // the type of the argument. Also, hex/octal/binary should be defined
245         // for integers, but they shouldn't emit the negative sign.
246         assert_eq!(format!("{}", 1i), ~"1");
247         assert_eq!(format!("{}", 1i8), ~"1");
248         assert_eq!(format!("{}", 1i16), ~"1");
249         assert_eq!(format!("{}", 1i32), ~"1");
250         assert_eq!(format!("{}", 1i64), ~"1");
251         assert_eq!(format!("{:d}", -1i), ~"-1");
252         assert_eq!(format!("{:d}", -1i8), ~"-1");
253         assert_eq!(format!("{:d}", -1i16), ~"-1");
254         assert_eq!(format!("{:d}", -1i32), ~"-1");
255         assert_eq!(format!("{:d}", -1i64), ~"-1");
256         assert_eq!(format!("{:t}", 1i), ~"1");
257         assert_eq!(format!("{:t}", 1i8), ~"1");
258         assert_eq!(format!("{:t}", 1i16), ~"1");
259         assert_eq!(format!("{:t}", 1i32), ~"1");
260         assert_eq!(format!("{:t}", 1i64), ~"1");
261         assert_eq!(format!("{:x}", 1i), ~"1");
262         assert_eq!(format!("{:x}", 1i8), ~"1");
263         assert_eq!(format!("{:x}", 1i16), ~"1");
264         assert_eq!(format!("{:x}", 1i32), ~"1");
265         assert_eq!(format!("{:x}", 1i64), ~"1");
266         assert_eq!(format!("{:X}", 1i), ~"1");
267         assert_eq!(format!("{:X}", 1i8), ~"1");
268         assert_eq!(format!("{:X}", 1i16), ~"1");
269         assert_eq!(format!("{:X}", 1i32), ~"1");
270         assert_eq!(format!("{:X}", 1i64), ~"1");
271         assert_eq!(format!("{:o}", 1i), ~"1");
272         assert_eq!(format!("{:o}", 1i8), ~"1");
273         assert_eq!(format!("{:o}", 1i16), ~"1");
274         assert_eq!(format!("{:o}", 1i32), ~"1");
275         assert_eq!(format!("{:o}", 1i64), ~"1");
276
277         assert_eq!(format!("{}", 1u), ~"1");
278         assert_eq!(format!("{}", 1u8), ~"1");
279         assert_eq!(format!("{}", 1u16), ~"1");
280         assert_eq!(format!("{}", 1u32), ~"1");
281         assert_eq!(format!("{}", 1u64), ~"1");
282         assert_eq!(format!("{:u}", 1u), ~"1");
283         assert_eq!(format!("{:u}", 1u8), ~"1");
284         assert_eq!(format!("{:u}", 1u16), ~"1");
285         assert_eq!(format!("{:u}", 1u32), ~"1");
286         assert_eq!(format!("{:u}", 1u64), ~"1");
287         assert_eq!(format!("{:t}", 1u), ~"1");
288         assert_eq!(format!("{:t}", 1u8), ~"1");
289         assert_eq!(format!("{:t}", 1u16), ~"1");
290         assert_eq!(format!("{:t}", 1u32), ~"1");
291         assert_eq!(format!("{:t}", 1u64), ~"1");
292         assert_eq!(format!("{:x}", 1u), ~"1");
293         assert_eq!(format!("{:x}", 1u8), ~"1");
294         assert_eq!(format!("{:x}", 1u16), ~"1");
295         assert_eq!(format!("{:x}", 1u32), ~"1");
296         assert_eq!(format!("{:x}", 1u64), ~"1");
297         assert_eq!(format!("{:X}", 1u), ~"1");
298         assert_eq!(format!("{:X}", 1u8), ~"1");
299         assert_eq!(format!("{:X}", 1u16), ~"1");
300         assert_eq!(format!("{:X}", 1u32), ~"1");
301         assert_eq!(format!("{:X}", 1u64), ~"1");
302         assert_eq!(format!("{:o}", 1u), ~"1");
303         assert_eq!(format!("{:o}", 1u8), ~"1");
304         assert_eq!(format!("{:o}", 1u16), ~"1");
305         assert_eq!(format!("{:o}", 1u32), ~"1");
306         assert_eq!(format!("{:o}", 1u64), ~"1");
307
308         // Test a larger number
309         assert_eq!(format!("{:t}", 55), ~"110111");
310         assert_eq!(format!("{:o}", 55), ~"67");
311         assert_eq!(format!("{:d}", 55), ~"55");
312         assert_eq!(format!("{:x}", 55), ~"37");
313         assert_eq!(format!("{:X}", 55), ~"37");
314     }
315
316     #[test]
317     fn test_format_int_zero() {
318         assert_eq!(format!("{}", 0i), ~"0");
319         assert_eq!(format!("{:d}", 0i), ~"0");
320         assert_eq!(format!("{:t}", 0i), ~"0");
321         assert_eq!(format!("{:o}", 0i), ~"0");
322         assert_eq!(format!("{:x}", 0i), ~"0");
323         assert_eq!(format!("{:X}", 0i), ~"0");
324
325         assert_eq!(format!("{}", 0u), ~"0");
326         assert_eq!(format!("{:u}", 0u), ~"0");
327         assert_eq!(format!("{:t}", 0u), ~"0");
328         assert_eq!(format!("{:o}", 0u), ~"0");
329         assert_eq!(format!("{:x}", 0u), ~"0");
330         assert_eq!(format!("{:X}", 0u), ~"0");
331     }
332
333     #[test]
334     fn test_format_int_flags() {
335         assert_eq!(format!("{:3d}", 1), ~"  1");
336         assert_eq!(format!("{:>3d}", 1), ~"  1");
337         assert_eq!(format!("{:>+3d}", 1), ~" +1");
338         assert_eq!(format!("{:<3d}", 1), ~"1  ");
339         assert_eq!(format!("{:#d}", 1), ~"1");
340         assert_eq!(format!("{:#x}", 10), ~"0xa");
341         assert_eq!(format!("{:#X}", 10), ~"0xA");
342         assert_eq!(format!("{:#5x}", 10), ~"  0xa");
343         assert_eq!(format!("{:#o}", 10), ~"0o12");
344         assert_eq!(format!("{:08x}", 10), ~"0000000a");
345         assert_eq!(format!("{:8x}", 10), ~"       a");
346         assert_eq!(format!("{:<8x}", 10), ~"a       ");
347         assert_eq!(format!("{:>8x}", 10), ~"       a");
348         assert_eq!(format!("{:#08x}", 10), ~"0x00000a");
349         assert_eq!(format!("{:08d}", -10), ~"-0000010");
350         assert_eq!(format!("{:x}", -1u8), ~"ff");
351         assert_eq!(format!("{:X}", -1u8), ~"FF");
352         assert_eq!(format!("{:t}", -1u8), ~"11111111");
353         assert_eq!(format!("{:o}", -1u8), ~"377");
354         assert_eq!(format!("{:#x}", -1u8), ~"0xff");
355         assert_eq!(format!("{:#X}", -1u8), ~"0xFF");
356         assert_eq!(format!("{:#t}", -1u8), ~"0b11111111");
357         assert_eq!(format!("{:#o}", -1u8), ~"0o377");
358     }
359
360     #[test]
361     fn test_format_int_sign_padding() {
362         assert_eq!(format!("{:+5d}", 1), ~"   +1");
363         assert_eq!(format!("{:+5d}", -1), ~"   -1");
364         assert_eq!(format!("{:05d}", 1), ~"00001");
365         assert_eq!(format!("{:05d}", -1), ~"-0001");
366         assert_eq!(format!("{:+05d}", 1), ~"+0001");
367         assert_eq!(format!("{:+05d}", -1), ~"-0001");
368     }
369
370     #[test]
371     fn test_format_int_twos_complement() {
372         use {i8, i16, i32, i64};
373         assert_eq!(format!("{}", i8::MIN), ~"-128");
374         assert_eq!(format!("{}", i16::MIN), ~"-32768");
375         assert_eq!(format!("{}", i32::MIN), ~"-2147483648");
376         assert_eq!(format!("{}", i64::MIN), ~"-9223372036854775808");
377     }
378
379     #[test]
380     fn test_format_radix() {
381         assert_eq!(format!("{:04}", radix(3, 2)), ~"0011");
382         assert_eq!(format!("{}", radix(55, 36)), ~"1j");
383     }
384
385     #[test]
386     #[should_fail]
387     fn test_radix_base_too_large() {
388         let _ = radix(55, 37);
389     }
390 }
391
392 #[cfg(test)]
393 mod bench {
394     extern crate test;
395
396     mod uint {
397         use super::test::Bencher;
398         use fmt::radix;
399         use rand::{XorShiftRng, Rng};
400
401         #[bench]
402         fn format_bin(b: &mut Bencher) {
403             let mut rng = XorShiftRng::new().unwrap();
404             b.iter(|| { format!("{:t}", rng.gen::<uint>()); })
405         }
406
407         #[bench]
408         fn format_oct(b: &mut Bencher) {
409             let mut rng = XorShiftRng::new().unwrap();
410             b.iter(|| { format!("{:o}", rng.gen::<uint>()); })
411         }
412
413         #[bench]
414         fn format_dec(b: &mut Bencher) {
415             let mut rng = XorShiftRng::new().unwrap();
416             b.iter(|| { format!("{:u}", rng.gen::<uint>()); })
417         }
418
419         #[bench]
420         fn format_hex(b: &mut Bencher) {
421             let mut rng = XorShiftRng::new().unwrap();
422             b.iter(|| { format!("{:x}", rng.gen::<uint>()); })
423         }
424
425         #[bench]
426         fn format_base_36(b: &mut Bencher) {
427             let mut rng = XorShiftRng::new().unwrap();
428             b.iter(|| { format!("{}", radix(rng.gen::<uint>(), 36)); })
429         }
430     }
431
432     mod int {
433         use super::test::Bencher;
434         use fmt::radix;
435         use rand::{XorShiftRng, Rng};
436
437         #[bench]
438         fn format_bin(b: &mut Bencher) {
439             let mut rng = XorShiftRng::new().unwrap();
440             b.iter(|| { format!("{:t}", rng.gen::<int>()); })
441         }
442
443         #[bench]
444         fn format_oct(b: &mut Bencher) {
445             let mut rng = XorShiftRng::new().unwrap();
446             b.iter(|| { format!("{:o}", rng.gen::<int>()); })
447         }
448
449         #[bench]
450         fn format_dec(b: &mut Bencher) {
451             let mut rng = XorShiftRng::new().unwrap();
452             b.iter(|| { format!("{:d}", rng.gen::<int>()); })
453         }
454
455         #[bench]
456         fn format_hex(b: &mut Bencher) {
457             let mut rng = XorShiftRng::new().unwrap();
458             b.iter(|| { format!("{:x}", rng.gen::<int>()); })
459         }
460
461         #[bench]
462         fn format_base_36(b: &mut Bencher) {
463             let mut rng = XorShiftRng::new().unwrap();
464             b.iter(|| { format!("{}", radix(rng.gen::<int>(), 36)); })
465         }
466     }
467 }