Created
July 11, 2013 17:16
-
-
Save AitorATuin/5977350 to your computer and use it in GitHub Desktop.
generate checksums for blocks of a video stream in reverse order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.logikujo.CryptoI | |
import scala.annotation.tailrec | |
import Implicits._ | |
import MessageDigest.JSHA256._ | |
import scalaz._ | |
import Scalaz._ | |
import java.io.{FileInputStream => FIStream, BufferedInputStream => BFStream, RandomAccessFile} | |
import java.nio.file.{Paths, Path} | |
object Week3 { | |
abstract class Video | |
{ | |
val name: String | |
private def hash(msg: Hex):Hex = PlainMsg(msg).digest.payload | |
private def hash(msg1: Hex, msg2: Hex): Hex = PlainMsg(msg1 | msg2).digest.payload | |
def canRead: Boolean = Paths.get(name).toFile.canRead | |
lazy val positions: Validation[String, Stream[(Int,Int)]] = (canRead)? { | |
val randomBuffer = new RandomAccessFile(name, "r") | |
val len = randomBuffer.length.toInt | |
randomBuffer.close() | |
(0 to len by 1024).reverse.zipAll(List(len % 1024), 0, 1024).toStream.success[String] | |
} | ("Unable to read file".failure[Stream[(Int,Int)]]) | |
def computeHash: Validation[String,List[Hex]] = { | |
val randomBuffer = new RandomAccessFile(name, "r") | |
val readHex = ((randomBuffer:RandomAccessFile) => | |
(pos:Int, size:Int) => { | |
val a:Array[Byte] = new Array(size) | |
randomBuffer.seek(pos) | |
randomBuffer.read(a) | |
Hex(a) | |
})(randomBuffer) | |
val res = positions flatMap (s => s match { | |
case x #:: xs => xs.scanLeft(hash(readHex(x._1, x._2)))((b,a) => { | |
//if (a.isEmpty) randomBuffer.close() | |
hash(readHex(a._1, a._2), b) | |
}).toList.reverse.success[String] | |
}) | |
randomBuffer.close() | |
res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment