]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/num.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[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_negation)]
16
17 use fmt;
18 use iter::DoubleEndedIteratorExt;
19 use kinds::Copy;
20 use num::{Int, cast};
21 use slice::SlicePrelude;
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 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();
44         if is_positive {
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.
51                 curr -= 1;
52                 if x == zero { break };                   // No more digits left to accumulate.
53             }
54         } else {
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.
60                 curr -= 1;
61                 if x == zero { break };                   // No more digits left to accumulate.
62             }
63         }
64         f.pad_integral(is_positive, self.prefix(), buf[curr..])
65     }
66 }
67
68 /// A binary (base 2) radix
69 #[deriving(Clone, PartialEq)]
70 struct Binary;
71
72 /// An octal (base 8) radix
73 #[deriving(Clone, PartialEq)]
74 struct Octal;
75
76 /// A decimal (base 10) radix
77 #[deriving(Clone, PartialEq)]
78 struct Decimal;
79
80 /// A hexadecimal (base 16) radix, formatted with lower-case characters
81 #[deriving(Clone, PartialEq)]
82 struct LowerHex;
83
84 /// A hexadecimal (base 16) radix, formatted with upper-case characters
85 #[deriving(Clone, PartialEq)]
86 pub struct UpperHex;
87
88 macro_rules! radix {
89     ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
90         impl GenericRadix for $T {
91             fn base(&self) -> u8 { $base }
92             fn prefix(&self) -> &'static str { $prefix }
93             fn digit(&self, x: u8) -> u8 {
94                 match x {
95                     $($x => $conv,)+
96                     x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
97                 }
98             }
99         }
100     }
101 }
102
103 radix!(Binary,    2, "0b", x @  0 ...  2 => b'0' + x)
104 radix!(Octal,     8, "0o", x @  0 ...  7 => b'0' + x)
105 radix!(Decimal,  10, "",   x @  0 ...  9 => b'0' + x)
106 radix!(LowerHex, 16, "0x", x @  0 ...  9 => b'0' + x,
107                            x @ 10 ... 15 => b'a' + (x - 10))
108 radix!(UpperHex, 16, "0x", x @  0 ...  9 => b'0' + x,
109                            x @ 10 ... 15 => b'A' + (x - 10))
110
111 /// A radix with in the range of `2..36`.
112 #[deriving(Clone, PartialEq)]
113 #[unstable = "may be renamed or move to a different module"]
114 pub struct Radix {
115     base: u8,
116 }
117
118 impl Copy for Radix {}
119
120 impl Radix {
121     fn new(base: u8) -> Radix {
122         assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
123         Radix { base: base }
124     }
125 }
126
127 impl GenericRadix for Radix {
128     fn base(&self) -> u8 { self.base }
129     fn digit(&self, x: u8) -> u8 {
130         match x {
131             x @  0 ... 9 => b'0' + x,
132             x if x < self.base() => b'a' + (x - 10),
133             x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
134         }
135     }
136 }
137
138 /// A helper type for formatting radixes.
139 #[unstable = "may be renamed or move to a different module"]
140 pub struct RadixFmt<T, R>(T, R);
141
142 impl<T,R> Copy for RadixFmt<T,R> where T: Copy, R: Copy {}
143
144 /// Constructs a radix formatter in the range of `2..36`.
145 ///
146 /// # Example
147 ///
148 /// ```
149 /// use std::fmt::radix;
150 /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
151 /// ```
152 #[unstable = "may be renamed or move to a different module"]
153 pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
154     RadixFmt(x, Radix::new(base))
155 }
156
157 macro_rules! radix_fmt {
158     ($T:ty as $U:ty, $fmt:ident) => {
159         impl fmt::Show for RadixFmt<$T, Radix> {
160             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
161                 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
162             }
163         }
164     }
165 }
166 macro_rules! int_base {
167     ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
168         impl fmt::$Trait for $T {
169             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
170                 $Radix.fmt_int(*self as $U, f)
171             }
172         }
173     }
174 }
175 macro_rules! integer {
176     ($Int:ident, $Uint:ident) => {
177         int_base!(Show     for $Int as $Int   -> Decimal)
178         int_base!(Binary   for $Int as $Uint  -> Binary)
179         int_base!(Octal    for $Int as $Uint  -> Octal)
180         int_base!(LowerHex for $Int as $Uint  -> LowerHex)
181         int_base!(UpperHex for $Int as $Uint  -> UpperHex)
182         radix_fmt!($Int as $Int, fmt_int)
183
184         int_base!(Show     for $Uint as $Uint -> Decimal)
185         int_base!(Binary   for $Uint as $Uint -> Binary)
186         int_base!(Octal    for $Uint as $Uint -> Octal)
187         int_base!(LowerHex for $Uint as $Uint -> LowerHex)
188         int_base!(UpperHex for $Uint as $Uint -> UpperHex)
189         radix_fmt!($Uint as $Uint, fmt_int)
190     }
191 }
192 integer!(int, uint)
193 integer!(i8, u8)
194 integer!(i16, u16)
195 integer!(i32, u32)
196 integer!(i64, u64)