Add a safe interface

This commit is contained in:
David Tolnay
2018-08-04 01:57:09 -07:00
parent cd8fa5ac6c
commit 1571d45d25
4 changed files with 43 additions and 15 deletions
-3
View File
@@ -4,6 +4,3 @@ rust:
- nightly
- beta
- stable
script:
- cargo test --features pretty
-9
View File
@@ -4,17 +4,8 @@ version = "0.0.0"
authors = ["David Tolnay <dtolnay@gmail.com>"]
publish = false
[features]
pretty = []
[dependencies]
no-panic = { version = "0.1", optional = true }
[dev-dependencies]
rand = "0.5"
[package.metadata.docs.rs]
features = ["pretty"]
[package.metadata.playground]
features = ["pretty"]
+40
View File
@@ -0,0 +1,40 @@
use core::str;
use pretty;
pub struct Buffer {
bytes: [u8; 24],
}
impl Buffer {
pub fn write<F: Float>(&mut self, f: F) -> &str {
f.write_to_ryu_buffer(self)
}
}
pub trait Float: Sealed {
#[doc(hidden)]
fn write_to_ryu_buffer(self, buffer: &mut Buffer) -> &str;
}
impl Float for f32 {
fn write_to_ryu_buffer(self, buffer: &mut Buffer) -> &str {
unsafe {
let n = pretty::f2s_buffered_n(self, &mut buffer.bytes[0]);
str::from_utf8_unchecked(&buffer.bytes[..n])
}
}
}
impl Float for f64 {
fn write_to_ryu_buffer(self, buffer: &mut Buffer) -> &str {
unsafe {
let n = pretty::d2s_buffered_n(self, &mut buffer.bytes[0]);
str::from_utf8_unchecked(&buffer.bytes[..n])
}
}
}
pub trait Sealed {}
impl Sealed for f32 {}
impl Sealed for f64 {}
+3 -3
View File
@@ -14,14 +14,14 @@
#[cfg(feature = "no-panic")]
extern crate no_panic;
mod buffer;
mod common;
mod d2s;
mod d2s_full_table;
mod digit_table;
mod f2s;
mod pretty;
#[cfg(feature = "pretty")]
pub mod pretty;
pub use buffer::{Buffer, Float};
pub use d2s::d2s_buffered_n;
pub use f2s::f2s_buffered_n;