Debian Codegraph @

third_party/rust/dtoa-short/src/lib.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 extern crate dtoa;
6
7 use std::fmt::Write;
8 use std::{fmt, str};
9
10 /// Format the given `value` into `dest` and return the notation it uses.
11 #[inline]
12 pub fn write<W: Write, V: Floating>(dest: &mut W, value: V) -> DtoaResult {
13 Floating::write(value, dest)
14 }
15
16 /// Form of the formatted floating-point number.
17 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
18 pub struct Notation {
19 /// Whether it contains a decimal point.
20 pub decimal_point: bool,
21 /// Whether it uses E-notation.
22 pub scientific: bool,
23 }
24
25 impl Notation {
26 fn integer() -> Self {
27 Notation {
28 decimal_point: false,
29 scientific: false,
30 }
31 }
32 }
33
34 /// Result of formatting the number.
35 pub type DtoaResult = Result<Notation, fmt::Error>;
36
37 pub trait Floating : dtoa::Floating {
38 fn write<W: Write>(self, dest: &mut W) -> DtoaResult;
39 }
40
41 impl Floating for f32 {
42 fn write<W: Write>(self, dest: &mut W) -> DtoaResult {
43 write_with_prec(dest, self, 6)
44 }
45 }
46
47 impl Floating for f64 {
48 fn write<W: Write>(self, dest: &mut W) -> DtoaResult {
49 write_with_prec(dest, self, 15)
50 }
51 }
52
53 // dtoa's buffer is 24 bytes, so we use the same length here. We may
54 // need to update if dtoa changes its number in the future. See
55 // https://github.com/dtolnay/dtoa/blob/
56 // 584674a70af74521ce40350dba776ea67cfcbaa7/src/dtoa.rs#L465
57 const BUFFER_SIZE: usize = 24;
58
59 fn write_with_prec<W, V>(dest: &mut W, value: V, prec: usize)
60 -> DtoaResult where W: Write, V: dtoa::Floating
61 {
62 let mut buf = [b'\0'; BUFFER_SIZE + 8];
63 let len = dtoa::write(&mut buf[1..], value).map_err(|_| fmt::Error)?;
64 let (result, notation) = restrict_prec(&mut buf[0..len + 1], prec);
65 dest.write_str(if cfg!(debug_assertions) {
66 str::from_utf8(result).unwrap()
67 } else {
68 // safety: dtoa only generates ascii.
69 unsafe { str::from_utf8_unchecked(result) }
70 })?;
71 Ok(notation)
72 }
73
74 fn restrict_prec(buf: &mut [u8], prec: usize) -> (&[u8], Notation) {
75 let len = buf.len();
76 debug_assert!(len <= BUFFER_SIZE + 1, "dtoa may have changed its buffer size");
77 // Put a leading zero to capture any carry.
78 debug_assert!(buf[0] == b'\0', "Caller must prepare an empty byte for us");
79 buf[0] = b'0';
80 // Remove the sign for now. We will put it back at the end.
81 let sign = match buf[1] {
82 s @ b'+' | s @ b'-' => {
83 buf[1] = b'0';
84 Some(s)
85 }
86 _ => None,
87 };
88 // Locate dot, exponent, and the first significant digit.
89 let mut pos_dot = None;
90 let mut pos_exp = None;
91 let mut prec_start = None;
92 for i in 1..len {
93 if buf[i] == b'.' {
94 debug_assert!(pos_dot.is_none());
95 pos_dot = Some(i);
96 } else if buf[i] == b'e' {
97 pos_exp = Some(i);
98 // We don't change exponent part, so stop here.
99 break;
100 } else if prec_start.is_none() && buf[i] != b'0' {
101 debug_assert!(buf[i] >= b'1' && buf[i] <= b'9');
102 prec_start = Some(i);
103 }
104 }
105 let prec_start = match prec_start {
106 Some(i) => i,
107 // If there is no non-zero digit at all, it is just zero.
108 None => return (&buf[0..1], Notation::integer()),
109 };
110 // Coefficient part ends at 'e' or the length.
111 let coeff_end = pos_exp.unwrap_or(len);
112 // Decimal dot is effectively at the end of coefficient part if no
113 // dot presents before that.
114 let pos_dot = pos_dot.unwrap_or(coeff_end);
115 // Find the end position of the number within the given precision.
116 let prec_end = {
117 let end = prec_start + prec;
118 if pos_dot > prec_start && pos_dot <= end {
119 end + 1
120 } else {
121 end
122 }
123 };
124 let mut new_coeff_end = coeff_end;
125 if prec_end < coeff_end {
126 // Round to the given precision.
127 let next_char = buf[prec_end];
128 new_coeff_end = prec_end;
129 if next_char >= b'5' {
130 for i in (0..prec_end).rev() {
131 if buf[i] == b'.' {
132 continue;
133 }
134 if buf[i] != b'9' {
135 buf[i] += 1;
136 new_coeff_end = i + 1;
137 break;
138 }
139 buf[i] = b'0';
140 }
141 }
142 }
143 if new_coeff_end < pos_dot {
144 // If the precision isn't enough to reach the dot, set all digits
145 // in-between to zero and keep the number until the dot.
146 for i in new_coeff_end..pos_dot {
147 buf[i] = b'0';
148 }
149 new_coeff_end = pos_dot;
150 } else {
151 // Strip any trailing zeros.
152 for i in (0..new_coeff_end).rev() {
153 if buf[i] != b'0' {
154 if buf[i] == b'.' {
155 new_coeff_end = i;
156 }
157 break;
158 }
159 new_coeff_end = i;
160 }
161 }
162 // Move exponent part if necessary.
163 let real_end = if let Some(pos_exp) = pos_exp {
164 let exp_len = len - pos_exp;
165 if new_coeff_end != pos_exp {
166 for i in 0..exp_len {
167 buf[new_coeff_end + i] = buf[pos_exp + i];
168 }
169 }
170 new_coeff_end + exp_len
171 } else {
172 new_coeff_end
173 };
174 // Add back the sign and strip the leading zero.
175 let result = if let Some(sign) = sign {
176 if buf[1] == b'0' && buf[2] != b'.' {
177 buf[1] = sign;
178 &buf[1..real_end]
179 } else {
180 debug_assert!(buf[0] == b'0');
181 buf[0] = sign;
182 &buf[0..real_end]
183 }
184 } else {
185 if buf[0] == b'0' && buf[1] != b'.' {
186 &buf[1..real_end]
187 } else {
188 &buf[0..real_end]
189 }
190 };
191 // Generate the notation info.
192 let notation = Notation {
193 decimal_point: pos_dot < new_coeff_end,
194 scientific: pos_exp.is_some(),
195 };
196 (result, notation)
197 }