Skip to content
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

Digest should be an IO #14793

Open
straight-shoota opened this issue Jul 7, 2024 · 1 comment
Open

Digest should be an IO #14793

straight-shoota opened this issue Jul 7, 2024 · 1 comment

Comments

@straight-shoota
Copy link
Member

The Digest class behaves as a stream writer, so it would make sense to have it inherit IO.

This would allow using Digest implementations as data sink in an IO composition.
For example, in combination with IO::MultiWriter or IO::DupReader (proposed in #14792), it would be trivial to write / read to an IO, while simultaneously calculating a digest of the data.

For example, the following program prints some data to an IO, and calculates the CRC32 on the fly:

require "digest/crc32"

crc = Digest::CRC32.new
io = IO::MultiWriter.new(STDOUT, crc)

io << "Hello "
io << "Crystal!\n"

p crc.final

The Digest#update(data : Bytes) method is essentially the same as IO#write(slice : Bytes), making this similarity very obvious.

Digest even implements << which can be used in a very similar way as in IO. It's not identical, though. Digest#<< is just an alias for #update, while IO#<< implements string concatenation (it calls data.to_s(self), not write(data)).
This would probably be the most difficult problem for integrating Digest with IO, due to the different semantics of #<<.
I don't think there are any other incompatibilities.

@ysbaddaden
Copy link
Contributor

Excellent use-case!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants