]> git.lizzy.rs Git - rust.git/blob - src/libcore/fmt/float.rs
auto merge of #15789 : steveklabnik/rust/guide_pointers, r=cmr
[rust.git] / src / libcore / fmt / float.rs
1 // Copyright 2013-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 #![allow(missing_doc)]
12
13 use char;
14 use collections::Collection;
15 use fmt;
16 use iter::{range, DoubleEndedIterator};
17 use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive};
18 use num::{Zero, One, cast};
19 use result::Ok;
20 use slice::{ImmutableVector, MutableVector};
21 use slice;
22 use str::StrSlice;
23
24 #[cfg(stage0)]
25 use iter::Iterator;         // NOTE(stage0): Remove after snapshot.
26 #[cfg(stage0)]
27 use option::{Some, None};   // NOTE(stage0): Remove after snapshot.
28
29 /// A flag that specifies whether to use exponential (scientific) notation.
30 pub enum ExponentFormat {
31     /// Do not use exponential notation.
32     ExpNone,
33     /// Use exponential notation with the exponent having a base of 10 and the
34     /// exponent sign being `e` or `E`. For example, 1000 would be printed
35     /// 1e3.
36     ExpDec,
37     /// Use exponential notation with the exponent having a base of 2 and the
38     /// exponent sign being `p` or `P`. For example, 8 would be printed 1p3.
39     ExpBin,
40 }
41
42 /// The number of digits used for emitting the fractional part of a number, if
43 /// any.
44 pub enum SignificantDigits {
45     /// All calculable digits will be printed.
46     ///
47     /// Note that bignums or fractions may cause a surprisingly large number
48     /// of digits to be printed.
49     DigAll,
50
51     /// At most the given number of digits will be printed, truncating any
52     /// trailing zeroes.
53     DigMax(uint),
54
55     /// Precisely the given number of digits will be printed.
56     DigExact(uint)
57 }
58
59 /// How to emit the sign of a number.
60 pub enum SignFormat {
61     /// No sign will be printed. The exponent sign will also be emitted.
62     SignNone,
63     /// `-` will be printed for negative values, but no sign will be emitted
64     /// for positive numbers.
65     SignNeg,
66     /// `+` will be printed for positive values, and `-` will be printed for
67     /// negative values.
68     SignAll,
69 }
70
71 static DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u;
72 static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u;
73
74 /**
75  * Converts a number to its string representation as a byte vector.
76  * This is meant to be a common base implementation for all numeric string
77  * conversion functions like `to_string()` or `to_str_radix()`.
78  *
79  * # Arguments
80  * - `num`           - The number to convert. Accepts any number that
81  *                     implements the numeric traits.
82  * - `radix`         - Base to use. Accepts only the values 2-36. If the exponential notation
83  *                     is used, then this base is only used for the significand. The exponent
84  *                     itself always printed using a base of 10.
85  * - `negative_zero` - Whether to treat the special value `-0` as
86  *                     `-0` or as `+0`.
87  * - `sign`          - How to emit the sign. See `SignFormat`.
88  * - `digits`        - The amount of digits to use for emitting the fractional
89  *                     part, if any. See `SignificantDigits`.
90  * - `exp_format`   - Whether or not to use the exponential (scientific) notation.
91  *                    See `ExponentFormat`.
92  * - `exp_capital`   - Whether or not to use a capital letter for the exponent sign, if
93  *                     exponential notation is desired.
94  * - `f`             - A closure to invoke with the bytes representing the
95  *                     float.
96  *
97  * # Failure
98  * - Fails if `radix` < 2 or `radix` > 36.
99  * - Fails if `radix` > 14 and `exp_format` is `ExpDec` due to conflict
100  *   between digit and exponent sign `'e'`.
101  * - Fails if `radix` > 25 and `exp_format` is `ExpBin` due to conflict
102  *   between digit and exponent sign `'p'`.
103  */
104 pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
105     num: T,
106     radix: uint,
107     negative_zero: bool,
108     sign: SignFormat,
109     digits: SignificantDigits,
110     exp_format: ExponentFormat,
111     exp_upper: bool,
112     f: |&[u8]| -> U
113 ) -> U {
114     assert!(2 <= radix && radix <= 36);
115     match exp_format {
116         ExpDec if radix >= DIGIT_E_RADIX       // decimal exponent 'e'
117           => fail!("float_to_str_bytes_common: radix {} incompatible with \
118                     use of 'e' as decimal exponent", radix),
119         ExpBin if radix >= DIGIT_P_RADIX       // binary exponent 'p'
120           => fail!("float_to_str_bytes_common: radix {} incompatible with \
121                     use of 'p' as binary exponent", radix),
122         _ => ()
123     }
124
125     let _0: T = Zero::zero();
126     let _1: T = One::one();
127
128     match num.classify() {
129         FPNaN => return f("NaN".as_bytes()),
130         FPInfinite if num > _0 => {
131             return match sign {
132                 SignAll => return f("+inf".as_bytes()),
133                 _       => return f("inf".as_bytes()),
134             };
135         }
136         FPInfinite if num < _0 => {
137             return match sign {
138                 SignNone => return f("inf".as_bytes()),
139                 _        => return f("-inf".as_bytes()),
140             };
141         }
142         _ => {}
143     }
144
145     let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity());
146     // For an f64 the exponent is in the range of [-1022, 1023] for base 2, so
147     // we may have up to that many digits. Give ourselves some extra wiggle room
148     // otherwise as well.
149     let mut buf = [0u8, ..1536];
150     let mut end = 0;
151     let radix_gen: T = cast(radix as int).unwrap();
152
153     let (num, exp) = match exp_format {
154         ExpNone => (num, 0i32),
155         ExpDec | ExpBin if num == _0 => (num, 0i32),
156         ExpDec | ExpBin => {
157             let (exp, exp_base) = match exp_format {
158                 ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()),
159                 ExpBin => (num.abs().log2().floor(), cast::<f64, T>(2.0f64).unwrap()),
160                 ExpNone => fail!("unreachable"),
161             };
162
163             (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap())
164         }
165     };
166
167     // First emit the non-fractional part, looping at least once to make
168     // sure at least a `0` gets emitted.
169     let mut deccum = num.trunc();
170     loop {
171         // Calculate the absolute value of each digit instead of only
172         // doing it once for the whole number because a
173         // representable negative number doesn't necessary have an
174         // representable additive inverse of the same type
175         // (See twos complement). But we assume that for the
176         // numbers [-35 .. 0] we always have [0 .. 35].
177         let current_digit = (deccum % radix_gen).abs();
178
179         // Decrease the deccumulator one digit at a time
180         deccum = deccum / radix_gen;
181         deccum = deccum.trunc();
182
183         let c = char::from_digit(current_digit.to_int().unwrap() as uint, radix);
184         buf[end] = c.unwrap() as u8;
185         end += 1;
186
187         // No more digits to calculate for the non-fractional part -> break
188         if deccum == _0 { break; }
189     }
190
191     // If limited digits, calculate one digit more for rounding.
192     let (limit_digits, digit_count, exact) = match digits {
193         DigAll          => (false, 0u,      false),
194         DigMax(count)   => (true,  count+1, false),
195         DigExact(count) => (true,  count+1, true)
196     };
197
198     // Decide what sign to put in front
199     match sign {
200         SignNeg | SignAll if neg => {
201             buf[end] = '-' as u8;
202             end += 1;
203         }
204         SignAll => {
205             buf[end] = '+' as u8;
206             end += 1;
207         }
208         _ => ()
209     }
210
211     buf.mut_slice_to(end).reverse();
212
213     // Remember start of the fractional digits.
214     // Points one beyond end of buf if none get generated,
215     // or at the '.' otherwise.
216     let start_fractional_digits = end;
217
218     // Now emit the fractional part, if any
219     deccum = num.fract();
220     if deccum != _0 || (limit_digits && exact && digit_count > 0) {
221         buf[end] = '.' as u8;
222         end += 1;
223         let mut dig = 0u;
224
225         // calculate new digits while
226         // - there is no limit and there are digits left
227         // - or there is a limit, it's not reached yet and
228         //   - it's exact
229         //   - or it's a maximum, and there are still digits left
230         while (!limit_digits && deccum != _0)
231            || (limit_digits && dig < digit_count && (
232                    exact
233                 || (!exact && deccum != _0)
234               )
235         ) {
236             // Shift first fractional digit into the integer part
237             deccum = deccum * radix_gen;
238
239             // Calculate the absolute value of each digit.
240             // See note in first loop.
241             let current_digit = deccum.trunc().abs();
242
243             let c = char::from_digit(current_digit.to_int().unwrap() as uint,
244                                      radix);
245             buf[end] = c.unwrap() as u8;
246             end += 1;
247
248             // Decrease the deccumulator one fractional digit at a time
249             deccum = deccum.fract();
250             dig += 1u;
251         }
252
253         // If digits are limited, and that limit has been reached,
254         // cut off the one extra digit, and depending on its value
255         // round the remaining ones.
256         if limit_digits && dig == digit_count {
257             let ascii2value = |chr: u8| {
258                 char::to_digit(chr as char, radix).unwrap()
259             };
260             let value2ascii = |val: uint| {
261                 char::from_digit(val, radix).unwrap() as u8
262             };
263
264             let extra_digit = ascii2value(buf[end - 1]);
265             end -= 1;
266             if extra_digit >= radix / 2 { // -> need to round
267                 let mut i: int = end as int - 1;
268                 loop {
269                     // If reached left end of number, have to
270                     // insert additional digit:
271                     if i < 0
272                     || buf[i as uint] == '-' as u8
273                     || buf[i as uint] == '+' as u8 {
274                         for j in range(i as uint + 1, end).rev() {
275                             buf[j + 1] = buf[j];
276                         }
277                         buf[(i + 1) as uint] = value2ascii(1);
278                         end += 1;
279                         break;
280                     }
281
282                     // Skip the '.'
283                     if buf[i as uint] == '.' as u8 { i -= 1; continue; }
284
285                     // Either increment the digit,
286                     // or set to 0 if max and carry the 1.
287                     let current_digit = ascii2value(buf[i as uint]);
288                     if current_digit < (radix - 1) {
289                         buf[i as uint] = value2ascii(current_digit+1);
290                         break;
291                     } else {
292                         buf[i as uint] = value2ascii(0);
293                         i -= 1;
294                     }
295                 }
296             }
297         }
298     }
299
300     // if number of digits is not exact, remove all trailing '0's up to
301     // and including the '.'
302     if !exact {
303         let buf_max_i = end - 1;
304
305         // index to truncate from
306         let mut i = buf_max_i;
307
308         // discover trailing zeros of fractional part
309         while i > start_fractional_digits && buf[i] == '0' as u8 {
310             i -= 1;
311         }
312
313         // Only attempt to truncate digits if buf has fractional digits
314         if i >= start_fractional_digits {
315             // If buf ends with '.', cut that too.
316             if buf[i] == '.' as u8 { i -= 1 }
317
318             // only resize buf if we actually remove digits
319             if i < buf_max_i {
320                 end = i + 1;
321             }
322         }
323     } // If exact and trailing '.', just cut that
324     else {
325         let max_i = end - 1;
326         if buf[max_i] == '.' as u8 {
327             end = max_i;
328         }
329     }
330
331     match exp_format {
332         ExpNone => {},
333         _ => {
334             buf[end] = match exp_format {
335                 ExpDec if exp_upper => 'E',
336                 ExpDec if !exp_upper => 'e',
337                 ExpBin if exp_upper => 'P',
338                 ExpBin if !exp_upper => 'p',
339                 _ => fail!("unreachable"),
340             } as u8;
341             end += 1;
342
343             struct Filler<'a> {
344                 buf: &'a mut [u8],
345                 end: &'a mut uint,
346             }
347
348             impl<'a> fmt::FormatWriter for Filler<'a> {
349                 fn write(&mut self, bytes: &[u8]) -> fmt::Result {
350                     slice::bytes::copy_memory(self.buf.mut_slice_from(*self.end),
351                                               bytes);
352                     *self.end += bytes.len();
353                     Ok(())
354                 }
355             }
356
357             let mut filler = Filler { buf: buf, end: &mut end };
358             match sign {
359                 SignNeg => {
360                     let _ = format_args!(|args| {
361                         fmt::write(&mut filler, args)
362                     }, "{:-}", exp);
363                 }
364                 SignNone | SignAll => {
365                     let _ = format_args!(|args| {
366                         fmt::write(&mut filler, args)
367                     }, "{}", exp);
368                 }
369             }
370         }
371     }
372
373     f(buf.slice_to(end))
374 }