Newer
Older
gitbucket_jkp / project / Checksums.scala
@xuwei-k xuwei-k on 1 Apr 2018 883 bytes add -Xfuture option. fix warnings
  1. import java.security.MessageDigest
  2. import scala.annotation._
  3. import sbt._
  4. import io._
  5.  
  6. object Checksums {
  7. private val bufferSize = 2048
  8.  
  9. def generate(source: File, target: File, algorithm: String): Unit =
  10. sbt.IO write (target, compute(source, algorithm))
  11.  
  12. def compute(file: File, algorithm: String): String =
  13. hex(raw(file, algorithm))
  14.  
  15. def raw(file: File, algorithm: String): Array[Byte] =
  16. (Using fileInputStream file) { is =>
  17. val md = MessageDigest getInstance algorithm
  18. val buf = new Array[Byte](bufferSize)
  19. md.reset()
  20. @tailrec
  21. def loop(): Unit = {
  22. val len = is read buf
  23. if (len != -1) {
  24. md update (buf, 0, len)
  25. loop()
  26. }
  27. }
  28. loop()
  29. md.digest()
  30. }
  31.  
  32. def hex(bytes: Array[Byte]): String =
  33. bytes map { it =>
  34. "%02x" format (it.toInt & 0xff)
  35. } mkString ""
  36. }