Skip to content

Instantly share code, notes, and snippets.

@eduo
Forked from omerucel/OSHashAlgorithm.swift
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eduo/7188bb0029f3bcbf03d4 to your computer and use it in GitHub Desktop.
Save eduo/7188bb0029f3bcbf03d4 to your computer and use it in GitHub Desktop.
OpenSubtitles Hashing Algorithm in Swift 2
var osha = OSHashAlgorithm()
var result = osha.hashForPath(fileName)
println(result.fileHash)
println(result.fileSize)
// OSHash.swift
// Originally implemented from Objective-C version for Swift by omerucel 18/04/2015
// http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes#Objective-C
// Updated for Swift 2 by eduo on 15/06/15.
// Copyright © 2015 Eduardo Gutierrez. All rights reserved.
//
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)
let fileHandler = NSFileHandle(forReadingAtPath: path)!
let fileDataBegin: NSData = fileHandler.readDataOfLength(chunkSize)
fileHandler.seekToEndOfFile()
let fileSize: UInt64 = fileHandler.offsetInFile
if (UInt64(chunkSize) > fileSize) {
return fileHash
}
fileHandler.seekToFileOffset(max(0, fileSize - UInt64(chunkSize)))
let fileDataEnd: NSData = fileHandler.readDataOfLength(chunkSize)
var hash: UInt64 = fileSize
var data_bytes = UnsafeBufferPointer<UInt64>(
start: UnsafePointer(fileDataBegin.bytes),
count: fileDataBegin.length/sizeof(UInt64)
)
hash = data_bytes.reduce(hash,combine: &+)
data_bytes = UnsafeBufferPointer<UInt64>(
start: UnsafePointer(fileDataEnd.bytes),
count: fileDataEnd.length/sizeof(UInt64)
)
hash = data_bytes.reduce(hash,combine: &+)
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