Skip to content

std: add a Writer impl for &mut [u8] #19928

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion src/libstd/io/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ use option::Option::None;
use result::Result::{Err, Ok};
use io;
use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
use slice::{mod, AsSlice, SliceExt};
use mem;
use raw;
use ptr::RawPtr;
use slice::{mod, AsSlice, SlicePrelude};
use vec::Vec;

const BUF_CAPACITY: uint = 128;
Expand Down Expand Up @@ -240,6 +243,32 @@ impl<'a> Buffer for &'a [u8] {
}
}

impl<'a> Writer for &'a mut [u8] {
#[inline]
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
if self.is_empty() { return Err(io::standard_error(io::EndOfFile)); }

let self_len = self.len();
let buf_len = buf.len();

let write_len = min(self_len, buf_len);

slice::bytes::copy_memory(*self, buf.slice_to(write_len));

unsafe {
*self = mem::transmute(raw::Slice {
data: self.as_ptr().offset(write_len as int),
len: self_len - write_len,
});
}

if buf_len > self_len {
Err(io::standard_error(io::ShortWrite(write_len)))
} else {
Ok(())
}
}
}

/// Writes to a fixed-size byte slice
///
Expand Down Expand Up @@ -426,6 +455,24 @@ mod test {
assert_eq!(writer.get_ref(), b);
}

#[test]
fn test_slice_writer() {
let mut buf = [0_u8, ..8];
{
// FIXME(#19147): this could be written without the `&mut writer`
// once that bug is fixed.
let mut writer = buf.as_mut_slice();
(&mut writer).write(&[0]).unwrap();
(&mut writer).write(&[1, 2, 3]).unwrap();
(&mut writer).write(&[4, 5, 6, 7]).unwrap();
(&mut writer).write(&[]).unwrap();

assert!(writer.write(&[1]).is_err());
}
let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7];
assert_eq!(buf.as_slice(), b);
}

#[test]
fn test_buf_writer() {
let mut buf = [0 as u8, ..9];
Expand Down