mirror of
https://github.com/roc-lang/roc.git
synced 2025-10-03 16:44:33 +00:00
Simplify Dec to_str implementation
This commit is contained in:
parent
426582906c
commit
c5f93e3c54
1 changed files with 7 additions and 14 deletions
|
@ -372,13 +372,11 @@ impl RocDec {
|
||||||
// get their leading zeros placed in bytes for us. i.e. `string = b"0012340000000000000"`
|
// get their leading zeros placed in bytes for us. i.e. `string = b"0012340000000000000"`
|
||||||
write!(string, "{:019}", self.as_i128()).unwrap();
|
write!(string, "{:019}", self.as_i128()).unwrap();
|
||||||
|
|
||||||
let is_negative = self.as_i128() < 0;
|
|
||||||
let decimal_location = string.len() - Self::DECIMAL_PLACES;
|
let decimal_location = string.len() - Self::DECIMAL_PLACES;
|
||||||
|
|
||||||
// skip trailing zeros
|
// skip trailing zeros
|
||||||
let last_nonzero_byte = string.trim_end_matches('0').len();
|
let last_nonzero_byte = string.trim_end_matches('0').len();
|
||||||
|
|
||||||
if last_nonzero_byte < decimal_location {
|
if last_nonzero_byte <= decimal_location {
|
||||||
// This means that we've removed trailing zeros and are left with an integer. Our
|
// This means that we've removed trailing zeros and are left with an integer. Our
|
||||||
// convention is to print these without a decimal point or trailing zeros, so we're done.
|
// convention is to print these without a decimal point or trailing zeros, so we're done.
|
||||||
string.truncate(decimal_location);
|
string.truncate(decimal_location);
|
||||||
|
@ -393,19 +391,14 @@ impl RocDec {
|
||||||
// push a dummy character so we have space for the decimal dot
|
// push a dummy character so we have space for the decimal dot
|
||||||
string.push('$');
|
string.push('$');
|
||||||
|
|
||||||
if decimal_location == last_nonzero_byte {
|
// Safety: at any time, the string only contains ascii characters, so it is always valid utf8
|
||||||
// never have a '.' as the last character
|
let bytes = unsafe { string.as_bytes_mut() };
|
||||||
string.truncate(last_nonzero_byte)
|
|
||||||
} else {
|
|
||||||
// Safety: at any time, the string only contains ascii characters, so it is always valid utf8
|
|
||||||
let bytes = unsafe { string.as_bytes_mut() };
|
|
||||||
|
|
||||||
// shift the fractional part by one
|
// shift the fractional part by one
|
||||||
bytes.copy_within(decimal_location..last_nonzero_byte, decimal_location + 1);
|
bytes.copy_within(decimal_location..last_nonzero_byte, decimal_location + 1);
|
||||||
|
|
||||||
// and put in the decimal dot in the right place
|
// and put in the decimal dot in the right place
|
||||||
bytes[decimal_location] = b'.';
|
bytes[decimal_location] = b'.';
|
||||||
}
|
|
||||||
|
|
||||||
string.as_str()
|
string.as_str()
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue