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