Nycto / Hasher

A small Scala library for easily generating hashes (md5, sha1, sha256, sha512, crc32, bcrypt, hmacs, pbkdf2)
MIT License
186 stars 40 forks source link

Hasher on a Source delete contents #5

Closed yaghmr closed 10 years ago

yaghmr commented 10 years ago

How I can do something like:

val src = Source.fromFile("data.csv")
val currentHash = Hasher(src).crc32.hex

without empty my source iterator?. What's the correct way to calculate a Source's hash?

Nycto commented 10 years ago

In this case, the hash is generated from the content of your file, so it makes sense that it consumes the Source object. The file has to be read to build a hash.

You have two other options:

  1. Reset the Source object after you're done generating the hash
  2. Use a Tap instead of directly building the hash. This allows the digest to be constructed passively as some other piece of code reads your source. Like this:
val source = Algo.crc32.tap( Source.fromFile("data.csv") )

source.getLines.foreach( line => {
    // Application logic to process each line
    println(line)
})

println( "Hash: " + source.hash )
Nycto commented 10 years ago

As a follow up, I added a section to the Readme about this:

https://github.com/Nycto/Hasher/commit/76447dd93585a229ca2be797301d08fd29159bd8