Changes between Version 63 and Version 64 of HashSourceCodes


Ignore:
Timestamp:
Jun 17, 2015, 8:30:55 AM (9 years ago)
Author:
os
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • HashSourceCodes

    v63 v64  
    19061906    }
    19071907}}}
     1908
     1909== SWIFT 2 ==
     1910{{{
     1911//  OSHash.swift
     1912//  Originally implemented from Objective-C version for Swift by omerucel 18/04/2015
     1913// http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes#Objective-C
     1914//  Updated for Swift 2 by eduo on  15/06/15.
     1915//  Copyright © 2015 Eduardo Gutierrez. All rights reserved.
     1916//
     1917
     1918import Foundation
     1919
     1920class OSHashAlgorithm: NSObject {
     1921    let chunkSize: Int = 65536;
     1922   
     1923    struct VideoHash {
     1924        var fileHash: String
     1925        var fileSize: UInt64
     1926    }
     1927   
     1928    func hashForPath (path: String) -> VideoHash {
     1929        var fileHash = VideoHash(fileHash: "", fileSize: 0)
     1930        let fileHandler = NSFileHandle(forReadingAtPath: path)!
     1931       
     1932        let fileDataBegin: NSData = fileHandler.readDataOfLength(chunkSize)
     1933        fileHandler.seekToEndOfFile()
     1934       
     1935        let fileSize: UInt64 = fileHandler.offsetInFile
     1936        if (UInt64(chunkSize) > fileSize) {
     1937            return fileHash
     1938        }
     1939       
     1940        fileHandler.seekToFileOffset(max(0, fileSize - UInt64(chunkSize)))
     1941        let fileDataEnd: NSData = fileHandler.readDataOfLength(chunkSize)
     1942       
     1943        var hash: UInt64 = fileSize
     1944       
     1945        var data_bytes = UnsafeBufferPointer<UInt64>(
     1946            start: UnsafePointer(fileDataBegin.bytes),
     1947            count: fileDataBegin.length/sizeof(UInt64)
     1948        )
     1949        hash = data_bytes.reduce(hash,combine: &+)
     1950       
     1951        data_bytes = UnsafeBufferPointer<UInt64>(
     1952            start: UnsafePointer(fileDataEnd.bytes),
     1953            count: fileDataEnd.length/sizeof(UInt64)
     1954        )
     1955        hash = data_bytes.reduce(hash,combine: &+)
     1956       
     1957        fileHash.fileHash = String(format:"%qx", arguments: [hash])
     1958        fileHash.fileSize = fileSize
     1959       
     1960        fileHandler.closeFile()
     1961        return fileHash
     1962    }
     1963}
     1964
     1965///var osha = OSHashAlgorithm()
     1966///var result = osha.hashForPath(fileName)
     1967///println(result.fileHash)
     1968///println(result.fileSize)
     1969}}}