Skip to content

Implement std::io::Write on crc32fast::Hasher #30

@LikeLakers2

Description

@LikeLakers2

Hi!

In checking out various checksum algorithms (mostly because I'm messing around with generating checksums), I found that algorithms implemented via the digest crate all have a Write implementation. This can be used as described here to allow for a simple std::io::copy(&mut file, &mut digester) in order to hash what you want - rather than needing to route the data to the algorithm yourself.

However, crc32fast::Hasher has no such Write implementation, so you cannot do the same here. So my suggestion is that a Write implementation be added, so that you can do the same here.

P.S. Admittedly, writing a wrapper for this purpose is easy (see below), but I still think adding a Write impl to crc32fast::Hasher directly would be the better option.

// Note: This wrapper is actually inspired by how the `digest` crate implements
// the `Write` trait for use with `std::io::copy()`. In fact, the `Write` impl
// is nearly identical when read side-by-side.
//
// `digest`'s implementation, for comparison:
// https://docs.rs/digest/0.10.7/src/digest/core_api/wrapper.rs.html#245-261
struct Crc32Writer(crc32fast::Hasher);

impl Crc32Writer {
	fn finalize(self) -> u32 { self.0.finalize() }
}

impl std::io::Write for Crc32Writer {
	fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
		self.0.update(buf);
		Ok(buf.len())
	}
	
	fn flush(&mut self) -> std::io::Result<()> {
		Ok(())
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions