由于看起来 snappy 需要一次性压缩所有内容,因此您只需将所有内容缓冲到最后。然后,您可以在最后冲洗和压缩:
use std::io::{self, Write, Cursor};
fn compress(_data: &[u8]) -> Vec<u8> {
// The best compression ever
b"compressed".as_ref().into()
}
struct SnappyCompressor<W> {
inner: W,
buffer: Vec<u8>,
}
impl<W> SnappyCompressor<W>
where W: Write
{
fn new(inner: W) -> Self {
SnappyCompressor {
inner: inner,
buffer: vec![],
}
}
}
impl<W> Write for SnappyCompressor<W>
where W: Write
{
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
self.buffer.extend(data);
Ok(data.len())
}
fn flush(&mut self) -> io::Result<()> {
let compressed = compress(&self.buffer);
self.inner.write_all(&compressed)
}
}
fn main() {
let mut output = Cursor::new(vec![]);
{
let mut compressor = SnappyCompressor::new(output.by_ref());
assert_eq!(5, compressor.write(b"hello").unwrap());
assert_eq!(5, compressor.write(b"world").unwrap());
compressor.flush().unwrap();
}
let bytes = output.into_inner();
assert_eq!(&b"compressed"[..], &bytes[..]);
}
这个解决方案有一个很大的问题——我们用它flush
来标记流的结束,但这并不是该方法的真正含义。使用纯流式压缩器可能会好得多,但有时你必须做你必须做的事情。
还有一些地雷:
- 您必须明确调用
flush
- 你不能打电话
flush
两次。
为了让用户简单地放下压缩器并完成它,您可以实现Drop
:
impl<W> Drop for SnappyCompressor<W>
where W: Write
{
fn drop(&mut self) {
self.flush().unwrap();
}
}
为了防止尝试刷新两次,您需要添加一个标志来跟踪它:
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
if self.is_flushed {
return Err(Error::new(ErrorKind::Other, "Buffer has already been compressed, cannot add more data"));
}
self.buffer.extend(data);
Ok(data.len())
}
fn flush(&mut self) -> io::Result<()> {
if self.is_flushed {
return Ok(())
}
self.is_flushed = true;
let compressed = compress(&self.buffer);
self.inner.write_all(&compressed)
}
总之,最终版本如下所示:
use std::io::{self, Write, Cursor, Error, ErrorKind};
fn compress(_data: &[u8]) -> Vec<u8> {
// The best compression ever
b"compressed".as_ref().into()
}
struct SnappyCompressor<W>
where W: Write
{
inner: W,
buffer: Vec<u8>,
is_flushed: bool,
}
impl<W> SnappyCompressor<W>
where W: Write
{
fn new(inner: W) -> Self {
SnappyCompressor {
inner: inner,
buffer: vec![],
is_flushed: false,
}
}
// fn into_inner
}
impl<W> Write for SnappyCompressor<W>
where W: Write
{
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
if self.is_flushed {
return Err(Error::new(ErrorKind::Other, "Buffer has already been compressed, cannot add more data"));
}
self.buffer.extend(data);
Ok(data.len())
}
fn flush(&mut self) -> io::Result<()> {
if self.is_flushed {
return Ok(())
}
self.is_flushed = true;
let compressed = compress(&self.buffer);
self.inner.write_all(&compressed)
}
}
impl<W> Drop for SnappyCompressor<W>
where W: Write
{
fn drop(&mut self) {
self.flush().unwrap();
}
}
fn main() {
let mut output = Cursor::new(vec![]);
{
let mut compressor = SnappyCompressor::new(output.by_ref());
assert_eq!(5, compressor.write(b"hello").unwrap());
assert_eq!(5, compressor.write(b"world").unwrap());
compressor.flush().unwrap();
}
let bytes = output.into_inner();
assert_eq!(&b"compressed"[..], &bytes[..]);
}