Merge pull request #7 from nox/len

Return the number of bytes written from itoa::write (fixes #6)
This commit is contained in:
David Tolnay 2017-01-28 13:20:56 -08:00 committed by GitHub
commit 036a5d8e12
2 changed files with 12 additions and 9 deletions

View File

@ -9,12 +9,12 @@
use std::{io, mem, ptr, slice}; use std::{io, mem, ptr, slice};
#[inline] #[inline]
pub fn write<W: io::Write + ?Sized, V: Integer>(wr: &mut W, value: V) -> io::Result<()> { pub fn write<W: io::Write, V: Integer>(wr: W, value: V) -> io::Result<usize> {
value.write(wr) value.write(wr)
} }
pub trait Integer { pub trait Integer {
fn write<W: io::Write + ?Sized>(self, &mut W) -> io::Result<()>; fn write<W: io::Write>(self, W) -> io::Result<usize>;
} }
const DEC_DIGITS_LUT: &'static[u8] = const DEC_DIGITS_LUT: &'static[u8] =
@ -30,7 +30,7 @@ macro_rules! impl_Integer {
($($t:ident),* as $conv_fn:ident) => ($( ($($t:ident),* as $conv_fn:ident) => ($(
impl Integer for $t { impl Integer for $t {
#[allow(unused_comparisons)] #[allow(unused_comparisons)]
fn write<W: io::Write + ?Sized>(self, wr: &mut W) -> io::Result<()> { fn write<W: io::Write>(self, mut wr: W) -> io::Result<usize> {
let is_nonnegative = self >= 0; let is_nonnegative = self >= 0;
let mut n = if is_nonnegative { let mut n = if is_nonnegative {
self as $conv_fn self as $conv_fn
@ -81,9 +81,12 @@ macro_rules! impl_Integer {
} }
} }
wr.write_all(unsafe { let mut len = buf.len() - curr as usize;
slice::from_raw_parts(buf_ptr.offset(curr), buf.len() - curr as usize) try!(wr.write_all(unsafe { slice::from_raw_parts(buf_ptr.offset(curr), len) }));
}) if !is_nonnegative {
len += 1;
}
Ok(len)
} }
})*); })*);
} }

View File

@ -7,9 +7,9 @@ macro_rules! test {
$( $(
#[test] #[test]
fn $name() { fn $name() {
let mut buf = Vec::with_capacity(20); let mut buf = [b'\0'; 20];
itoa::write(&mut buf, $value).unwrap(); let len = itoa::write(&mut buf[..], $value).unwrap();
assert_eq!(buf, $expected.as_bytes()); assert_eq!(&buf[0..len], $expected.as_bytes());
} }
)* )*
} }