Replace AllocStringWriter with CVec

This commit is contained in:
jD91mZM2
2020-06-29 15:24:16 +02:00
parent 39ce623d2d
commit 56e1eceb28
3 changed files with 66 additions and 50 deletions
+7 -43
View File
@@ -104,45 +104,6 @@ impl Read for FileReader {
}
}
pub struct AllocStringWriter(pub *mut u8, pub usize);
impl Write for AllocStringWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let ptr = unsafe { realloc(self.0 as *mut c_void, self.1 + buf.len() + 1) as *mut u8 };
if ptr.is_null() {
return Err(io::Error::new(
io::ErrorKind::Other,
"AllocStringWriter::write failed to allocate",
));
}
self.0 = ptr;
unsafe {
ptr::copy_nonoverlapping(buf.as_ptr(), self.0.add(self.1), buf.len());
self.1 += buf.len();
*self.0.add(self.1) = 0;
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl fmt::Write for AllocStringWriter {
fn write_str(&mut self, s: &str) -> fmt::Result {
// can't fail
self.write(s.as_bytes()).unwrap();
Ok(())
}
}
impl WriteByte for AllocStringWriter {
fn write_u8(&mut self, byte: u8) -> fmt::Result {
// can't fail
self.write(&[byte]).unwrap();
Ok(())
}
}
pub struct StringWriter(pub *mut u8, pub usize);
impl Write for StringWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
@@ -155,11 +116,14 @@ impl Write for StringWriter {
self.0 = self.0.add(copy_size);
*self.0 = 0;
}
Ok(copy_size)
} else {
Ok(0)
}
// Pretend the entire slice was written. This is because many functions
// (like snprintf) expects a return value that reflects how many bytes
// *would have* been written. So keeping track of this information is
// good, and then if we want the *actual* written size we can just go
// `cmp::min(written, maxlen)`.
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())