/// Safe API for formatting floating point numbers to text. /// /// ## Example /// /// ``` /// let mut buffer = ryu::Buffer::new(); /// let printed = buffer.format_finite(1.234); /// assert_eq!(printed, "1.234"); /// ``` pubstruct Buffer {
bytes: [MaybeUninit<u8>; 24],
}
impl Buffer { /// This is a cheap operation; you don't need to worry about reusing buffers /// for efficiency. #[inline] #[cfg_attr(feature = "no-panic", no_panic)] pubfn new() -> Self { let bytes = [MaybeUninit::<u8>::uninit(); 24];
Buffer { bytes }
}
/// Print a floating point number into this buffer and return a reference to /// its string representation within the buffer. /// /// # Special cases /// /// This function formats NaN as the string "NaN", positive infinity as /// "inf", and negative infinity as "-inf" to match std::fmt. /// /// If your input is known to be finite, you may get better performance by /// calling the `format_finite` method instead of `format` to avoid the /// checks for special cases. #[cfg_attr(feature = "no-panic", inline)] #[cfg_attr(feature = "no-panic", no_panic)] pubfn format<F: Float>(&mutself, f: F) -> &str { if f.is_nonfinite() {
f.format_nonfinite()
} else { self.format_finite(f)
}
}
/// Print a floating point number into this buffer and return a reference to /// its string representation within the buffer. /// /// # Special cases /// /// This function **does not** check for NaN or infinity. If the input /// number is not a finite float, the printed representation will be some /// correctly formatted but unspecified numerical value. /// /// Please check [`is_finite`] yourself before calling this function, or /// check [`is_nan`] and [`is_infinite`] and handle those cases yourself. /// /// [`is_finite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_finite /// [`is_nan`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_nan /// [`is_infinite`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_infinite #[inline] #[cfg_attr(feature = "no-panic", no_panic)] pubfn format_finite<F: Float>(&mutself, f: F) -> &str { unsafe { let n = f.write_to_ryu_buffer(self.bytes.as_mut_ptr() as *mut u8);
debug_assert!(n <= self.bytes.len()); let slice = slice::from_raw_parts(self.bytes.as_ptr() as *const u8, n);
str::from_utf8_unchecked(slice)
}
}
}
/// A floating point number, f32 or f64, that can be written into a /// [`ryu::Buffer`][Buffer]. /// /// This trait is sealed and cannot be implemented for types outside of the /// `ryu` crate. pubtrait Float: Sealed {} impl Float for f32 {} impl Float for f64 {}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.