1use std::io::Error;
2use std::io::Write;
3
4pub struct CrcWriter<W: Write> {
6 writer: W,
7 sum: usize,
8}
9
10impl<W: Write> CrcWriter<W> {
11 pub fn new(writer: W) -> Self {
12 Self { writer, sum: 0 }
13 }
14
15 pub fn into_inner(self) -> W {
16 self.writer
17 }
18
19 pub fn sum(&self) -> u32 {
20 (self.sum & (u32::MAX as usize)) as u32
21 }
22}
23
24impl<W: Write> Write for CrcWriter<W> {
25 fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
26 let n = self.writer.write(buf)?;
27 for x in &buf[..n] {
28 self.sum = self.sum.wrapping_add(*x as usize);
29 }
30 Ok(n)
31 }
32
33 fn flush(&mut self) -> Result<(), Error> {
34 self.writer.flush()
35 }
36}