Skip to content

Commit

Permalink
Merge pull request #7 from nox/len
Browse files Browse the repository at this point in the history
Return the number of bytes written from itoa::write (fixes #6)
  • Loading branch information
dtolnay authored Jan 28, 2017
2 parents b2445b6 + bd4884d commit 036a5d8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
15 changes: 9 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
use std::{io, mem, ptr, slice};

#[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)
}

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] =
Expand All @@ -30,7 +30,7 @@ macro_rules! impl_Integer {
($($t:ident),* as $conv_fn:ident) => ($(
impl Integer for $t {
#[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 mut n = if is_nonnegative {
self as $conv_fn
Expand Down Expand Up @@ -81,9 +81,12 @@ macro_rules! impl_Integer {
}
}

wr.write_all(unsafe {
slice::from_raw_parts(buf_ptr.offset(curr), buf.len() - curr as usize)
})
let mut len = 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)
}
})*);
}
Expand Down
6 changes: 3 additions & 3 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ macro_rules! test {
$(
#[test]
fn $name() {
let mut buf = Vec::with_capacity(20);
itoa::write(&mut buf, $value).unwrap();
assert_eq!(buf, $expected.as_bytes());
let mut buf = [b'\0'; 20];
let len = itoa::write(&mut buf[..], $value).unwrap();
assert_eq!(&buf[0..len], $expected.as_bytes());
}
)*
}
Expand Down

0 comments on commit 036a5d8

Please sign in to comment.