var osha = OSHashAlgorithm()
var result = osha.hashForPath(fileName)
println(result.fileHash)
println(result.fileSize)
Created
April 18, 2015 14:54
-
-
Save omerucel/aa12e15d68656e4ce543 to your computer and use it in GitHub Desktop.
Opensubtitle hash algorithm for swift
This file contains hidden or 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
// Implemented from Objective-C version http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes#Objective-C | |
import Foundation | |
class OSHashAlgorithm: NSObject { | |
let chunkSize: Int = 65536; | |
struct VideoHash { | |
var fileHash: String | |
var fileSize: UInt64 | |
} | |
func hashForPath (path: String) -> VideoHash { | |
var fileHash = VideoHash(fileHash: "", fileSize: 0) | |
var fileHandler = NSFileHandle(forReadingAtPath: path)! | |
var fileDataBegin: NSData = fileHandler.readDataOfLength(chunkSize) | |
fileHandler.seekToEndOfFile() | |
var fileSize: UInt64 = fileHandler.offsetInFile | |
if (UInt64(chunkSize) > fileSize) { | |
return fileHash | |
} | |
fileHandler.seekToFileOffset(max(0, fileSize - UInt64(chunkSize))) | |
var fileDataEnd: NSData = fileHandler.readDataOfLength(chunkSize) | |
var hash: UInt64 = fileSize | |
var data_bytes = UnsafeBufferPointer<UInt64>( | |
start: UnsafePointer(fileDataBegin.bytes), | |
count: fileDataBegin.length/sizeof(UInt64) | |
) | |
hash = reduce(data_bytes, hash) { $0 &+ $1 } | |
data_bytes = UnsafeBufferPointer<UInt64>( | |
start: UnsafePointer(fileDataEnd.bytes), | |
count: fileDataEnd.length/sizeof(UInt64) | |
) | |
hash = reduce(data_bytes, hash) { $0 &+ $1 } | |
fileHash.fileHash = String(format:"%qx", arguments: [hash]) | |
fileHash.fileSize = fileSize | |
fileHandler.closeFile() | |
return fileHash | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment