]> git.proxmox.com Git - rustc.git/blob - src/libcore/fmt/num.rs
Merge tag 'upstream/1.0.0_beta'
[rustc.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::Iterator;
19 use num::{Int, cast};
20 use slice::SliceExt;
21 use str;
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 #[allow(deprecated)] // Int
37 fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
38 // The radix can be as low as 2, so we need a buffer of at least 64
39 // characters for a base 2 number.
40 let zero = Int::zero();
41 let is_positive = x >= zero;
42 let mut buf = [0; 64];
43 let mut curr = buf.len();
44 let base = cast(self.base()).unwrap();
45 if is_positive {
46 // Accumulate each digit of the number from the least significant
47 // to the most significant figure.
48 for byte in buf.iter_mut().rev() {
49 let n = x % base; // Get the current place value.
50 x = x / base; // Deaccumulate the number.
51 *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
52 curr -= 1;
53 if x == zero { break }; // No more digits left to accumulate.
54 }
55 } else {
56 // Do the same as above, but accounting for two's complement.
57 for byte in buf.iter_mut().rev() {
58 let n = zero - (x % base); // Get the current place value.
59 x = x / base; // Deaccumulate the number.
60 *byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
61 curr -= 1;
62 if x == zero { break }; // No more digits left to accumulate.
63 }
64 }
65 let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) };
66 f.pad_integral(is_positive, self.prefix(), buf)
67 }
68 }
69
70 /// A binary (base 2) radix
71 #[derive(Clone, PartialEq)]
72 struct Binary;
73
74 /// An octal (base 8) radix
75 #[derive(Clone, PartialEq)]
76 struct Octal;
77
78 /// A decimal (base 10) radix
79 #[derive(Clone, PartialEq)]
80 struct Decimal;
81
82 /// A hexadecimal (base 16) radix, formatted with lower-case characters
83 #[derive(Clone, PartialEq)]
84 struct LowerHex;
85
86 /// A hexadecimal (base 16) radix, formatted with upper-case characters
87 #[derive(Clone, PartialEq)]
88 struct UpperHex;
89
90 macro_rules! radix {
91 ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
92 impl GenericRadix for $T {
93 fn base(&self) -> u8 { $base }
94 fn prefix(&self) -> &'static str { $prefix }
95 fn digit(&self, x: u8) -> u8 {
96 match x {
97 $($x => $conv,)+
98 x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
99 }
100 }
101 }
102 }
103 }
104
105 radix! { Binary, 2, "0b", x @ 0 ... 2 => b'0' + x }
106 radix! { Octal, 8, "0o", x @ 0 ... 7 => b'0' + x }
107 radix! { Decimal, 10, "", x @ 0 ... 9 => b'0' + x }
108 radix! { LowerHex, 16, "0x", x @ 0 ... 9 => b'0' + x,
109 x @ 10 ... 15 => b'a' + (x - 10) }
110 radix! { UpperHex, 16, "0x", x @ 0 ... 9 => b'0' + x,
111 x @ 10 ... 15 => b'A' + (x - 10) }
112
113 /// A radix with in the range of `2..36`.
114 #[derive(Clone, Copy, PartialEq)]
115 #[unstable(feature = "core",
116 reason = "may be renamed or move to a different module")]
117 pub struct Radix {
118 base: u8,
119 }
120
121 impl Radix {
122 fn new(base: u8) -> Radix {
123 assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
124 Radix { base: base }
125 }
126 }
127
128 impl GenericRadix for Radix {
129 fn base(&self) -> u8 { self.base }
130 fn digit(&self, x: u8) -> u8 {
131 match x {
132 x @ 0 ... 9 => b'0' + x,
133 x if x < self.base() => b'a' + (x - 10),
134 x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
135 }
136 }
137 }
138
139 /// A helper type for formatting radixes.
140 #[unstable(feature = "core",
141 reason = "may be renamed or move to a different module")]
142 #[derive(Copy, Clone)]
143 pub struct RadixFmt<T, R>(T, R);
144
145 /// Constructs a radix formatter in the range of `2..36`.
146 ///
147 /// # Examples
148 ///
149 /// ```
150 /// # #![feature(core)]
151 /// use std::fmt::radix;
152 /// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
153 /// ```
154 #[unstable(feature = "core",
155 reason = "may be renamed or move to a different module")]
156 pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
157 RadixFmt(x, Radix::new(base))
158 }
159
160 macro_rules! radix_fmt {
161 ($T:ty as $U:ty, $fmt:ident) => {
162 #[stable(feature = "rust1", since = "1.0.0")]
163 impl fmt::Debug for RadixFmt<$T, Radix> {
164 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165 fmt::Display::fmt(self, f)
166 }
167 }
168 #[stable(feature = "rust1", since = "1.0.0")]
169 impl fmt::Display for RadixFmt<$T, Radix> {
170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
172 }
173 }
174 }
175 }
176 macro_rules! int_base {
177 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
178 #[stable(feature = "rust1", since = "1.0.0")]
179 impl fmt::$Trait for $T {
180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
181 $Radix.fmt_int(*self as $U, f)
182 }
183 }
184 }
185 }
186
187 macro_rules! debug {
188 ($T:ident) => {
189 #[stable(feature = "rust1", since = "1.0.0")]
190 impl fmt::Debug for $T {
191 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
192 fmt::Display::fmt(self, f)
193 }
194 }
195 }
196 }
197 macro_rules! integer {
198 ($Int:ident, $Uint:ident) => {
199 int_base! { Display for $Int as $Int -> Decimal }
200 int_base! { Binary for $Int as $Uint -> Binary }
201 int_base! { Octal for $Int as $Uint -> Octal }
202 int_base! { LowerHex for $Int as $Uint -> LowerHex }
203 int_base! { UpperHex for $Int as $Uint -> UpperHex }
204 radix_fmt! { $Int as $Int, fmt_int }
205 debug! { $Int }
206
207 int_base! { Display for $Uint as $Uint -> Decimal }
208 int_base! { Binary for $Uint as $Uint -> Binary }
209 int_base! { Octal for $Uint as $Uint -> Octal }
210 int_base! { LowerHex for $Uint as $Uint -> LowerHex }
211 int_base! { UpperHex for $Uint as $Uint -> UpperHex }
212 radix_fmt! { $Uint as $Uint, fmt_int }
213 debug! { $Uint }
214 }
215 }
216 integer! { isize, usize }
217 integer! { i8, u8 }
218 integer! { i16, u16 }
219 integer! { i32, u32 }
220 integer! { i64, u64 }