]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/num.rs
Add a doctest for the std::string::as_string method.
[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 num::{Int, cast};
20 use slice::SlicePrelude;
21
22 /// A type that represents a specific radix
23 #[doc(hidden)]
24 trait GenericRadix {
25     /// The number of digits.
26     fn base(&self) -> u8;
27
28     /// A radix-specific prefix string.
29     fn prefix(&self) -> &'static str { "" }
30
31     /// Converts an integer to corresponding radix digit.
32     fn digit(&self, x: u8) -> u8;
33
34     /// Format an integer using the radix using a formatter.
35     fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
36         // The radix can be as low as 2, so we need a buffer of at least 64
37         // characters for a base 2 number.
38         let zero = Int::zero();
39         let is_positive = x >= zero;
40         let mut buf = [0u8, ..64];
41         let mut curr = buf.len();
42         let base = cast(self.base()).unwrap();
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 = zero - (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[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 => panic!("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 #[unstable = "may be renamed or move to a different module"]
113 pub struct Radix {
114     base: u8,
115 }
116
117 impl Radix {
118     fn new(base: u8) -> Radix {
119         assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
120         Radix { base: base }
121     }
122 }
123
124 impl GenericRadix for Radix {
125     fn base(&self) -> u8 { self.base }
126     fn digit(&self, x: u8) -> u8 {
127         match x {
128             x @  0 ... 9 => b'0' + x,
129             x if x < self.base() => b'a' + (x - 10),
130             x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
131         }
132     }
133 }
134
135 /// A helper type for formatting radixes.
136 #[unstable = "may be renamed or move to a different module"]
137 pub struct RadixFmt<T, R>(T, R);
138
139 /// Constructs a radix formatter in the range of `2..36`.
140 ///
141 /// # Example
142 ///
143 /// ```
144 /// use std::fmt::radix;
145 /// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
146 /// ```
147 #[unstable = "may be renamed or move to a different module"]
148 pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
149     RadixFmt(x, Radix::new(base))
150 }
151
152 macro_rules! radix_fmt {
153     ($T:ty as $U:ty, $fmt:ident) => {
154         impl fmt::Show for RadixFmt<$T, Radix> {
155             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
156                 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
157             }
158         }
159     }
160 }
161 macro_rules! int_base {
162     ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
163         impl fmt::$Trait for $T {
164             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165                 $Radix.fmt_int(*self as $U, f)
166             }
167         }
168     }
169 }
170 macro_rules! integer {
171     ($Int:ident, $Uint:ident) => {
172         int_base!(Show     for $Int as $Int   -> Decimal)
173         int_base!(Binary   for $Int as $Uint  -> Binary)
174         int_base!(Octal    for $Int as $Uint  -> Octal)
175         int_base!(LowerHex for $Int as $Uint  -> LowerHex)
176         int_base!(UpperHex for $Int as $Uint  -> UpperHex)
177         radix_fmt!($Int as $Int, fmt_int)
178
179         int_base!(Show     for $Uint as $Uint -> Decimal)
180         int_base!(Binary   for $Uint as $Uint -> Binary)
181         int_base!(Octal    for $Uint as $Uint -> Octal)
182         int_base!(LowerHex for $Uint as $Uint -> LowerHex)
183         int_base!(UpperHex for $Uint as $Uint -> UpperHex)
184         radix_fmt!($Uint as $Uint, fmt_int)
185     }
186 }
187 integer!(int, uint)
188 integer!(i8, u8)
189 integer!(i16, u16)
190 integer!(i32, u32)
191 integer!(i64, u64)