From 1571d45d25fa808a7f712e8a704c4cb5d286a673 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 4 Aug 2018 01:57:09 -0700 Subject: [PATCH] Add a safe interface --- .travis.yml | 3 --- Cargo.toml | 9 --------- src/buffer/mod.rs | 40 ++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 6 +++--- 4 files changed, 43 insertions(+), 15 deletions(-) create mode 100644 src/buffer/mod.rs diff --git a/.travis.yml b/.travis.yml index dad0860..0a830fb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,3 @@ rust: - nightly - beta - stable - -script: - - cargo test --features pretty diff --git a/Cargo.toml b/Cargo.toml index 4b07efd..62ce258 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,17 +4,8 @@ version = "0.0.0" authors = ["David Tolnay "] 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"] diff --git a/src/buffer/mod.rs b/src/buffer/mod.rs new file mode 100644 index 0000000..30839f0 --- /dev/null +++ b/src/buffer/mod.rs @@ -0,0 +1,40 @@ +use core::str; + +use pretty; + +pub struct Buffer { + bytes: [u8; 24], +} + +impl Buffer { + pub fn write(&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 {} diff --git a/src/lib.rs b/src/lib.rs index 900c688..ab8927a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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;