]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/num.rs
auto merge of #17654 : gereeter/rust/no-unnecessary-cell, r=alexcrichton
[rust.git] / src / libcore / 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 #![allow(unsigned_negate)]
16
17 use collections::Collection;
18 use fmt;
19 use iter::DoubleEndedIterator;
20 use num::{Int, cast, zero};
21 use slice::{ImmutableSlice, MutableSlice};
22
23 /// A type that represents a specific radix
24 #[doc(hidden)]
25 trait GenericRadix {
26     /// The number of digits.
27     fn base(&self) -> u8;
28
29     /// A radix-specific prefix string.
30     fn prefix(&self) -> &'static str { "" }
31
32     /// Converts an integer to corresponding radix digit.
33     fn digit(&self, x: u8) -> u8;
34
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();
43         if is_positive {
44             // Accumulate each digit of the number from the least significant
45             // to the most significant figure.
46             for byte in buf.iter_mut().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.
50                 curr -= 1;
51                 if x == zero() { break; }                 // No more digits left to accumulate.
52             }
53         } else {
54             // Do the same as above, but accounting for two's complement.
55             for byte in buf.iter_mut().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.
59                 curr -= 1;
60                 if x == zero() { break; }                 // No more digits left to accumulate.
61             }
62         }
63         f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr))
64     }
65 }
66
67 /// A binary (base 2) radix
68 #[deriving(Clone, PartialEq)]
69 struct Binary;
70
71 /// An octal (base 8) radix
72 #[deriving(Clone, PartialEq)]
73 struct Octal;
74
75 /// A decimal (base 10) radix
76 #[deriving(Clone, PartialEq)]
77 struct Decimal;
78
79 /// A hexadecimal (base 16) radix, formatted with lower-case characters
80 #[deriving(Clone, PartialEq)]
81 struct LowerHex;
82
83 /// A hexadecimal (base 16) radix, formatted with upper-case characters
84 #[deriving(Clone, PartialEq)]
85 pub struct UpperHex;
86
87 macro_rules! radix {
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 {
93                 match x {
94                     $($x => $conv,)+
95                     x => fail!("number not in the range 0..{}: {}", self.base() - 1, x),
96                 }
97             }
98         }
99     }
100 }
101
102 radix!(Binary,    2, "0b", x @  0 ...  2 => b'0' + x)
103 radix!(Octal,     8, "0o", x @  0 ...  7 => b'0' + x)
104 radix!(Decimal,  10, "",   x @  0 ...  9 => b'0' + x)
105 radix!(LowerHex, 16, "0x", x @  0 ...  9 => b'0' + x,
106                            x @ 10 ... 15 => b'a' + (x - 10))
107 radix!(UpperHex, 16, "0x", x @  0 ...  9 => b'0' + x,
108                            x @ 10 ... 15 => b'A' + (x - 10))
109
110 /// A radix with in the range of `2..36`.
111 #[deriving(Clone, PartialEq)]
112 pub struct Radix {
113     base: u8,
114 }
115
116 impl Radix {
117     fn new(base: u8) -> Radix {
118         assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
119         Radix { base: base }
120     }
121 }
122
123 impl GenericRadix for Radix {
124     fn base(&self) -> u8 { self.base }
125     fn digit(&self, x: u8) -> u8 {
126         match x {
127             x @  0 ... 9 => b'0' + x,
128             x if x < self.base() => b'a' + (x - 10),
129             x => fail!("number not in the range 0..{}: {}", self.base() - 1, x),
130         }
131     }
132 }
133
134 /// A helper type for formatting radixes.
135 pub struct RadixFmt<T, R>(T, R);
136
137 /// Constructs a radix formatter in the range of `2..36`.
138 ///
139 /// # Example
140 ///
141 /// ```
142 /// use std::fmt::radix;
143 /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
144 /// ```
145 pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
146     RadixFmt(x, Radix::new(base))
147 }
148
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) }
154             }
155         }
156     }
157 }
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)
163             }
164         }
165     }
166 }
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)
176
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)
184     }
185 }
186 integer!(int, uint)
187 integer!(i8, u8)
188 integer!(i16, u16)
189 integer!(i32, u32)
190 integer!(i64, u64)