From e81a7e4b7c8df2cae5670a9bcf3c90c2bd8fcfa7 Mon Sep 17 00:00:00 2001 From: j <0x006A@0x2620.org> Date: Thu, 28 May 2009 19:00:30 +0200 Subject: [PATCH] add oshash --- oxlib/file.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/oxlib/file.py b/oxlib/file.py index 0d34729..0396959 100644 --- a/oxlib/file.py +++ b/oxlib/file.py @@ -1,8 +1,12 @@ # -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 # GPL 2008 +from __future__ import division import os import hashlib +import sys +import struct + def sha1sum(filename): sha1 = hashlib.sha1() @@ -14,4 +18,39 @@ def sha1sum(filename): file.close() return sha1.hexdigest() +''' + os hash - http://trac.opensubtitles.org/projects/opensubtitles/wiki/HashSourceCodes +''' +def oshash(filename): + try: + longlongformat = 'q' # long long + bytesize = struct.calcsize(longlongformat) + + f = open(filename, "rb") + + filesize = os.path.getsize(filename) + hash = filesize + + if filesize < 65536: + return "SizeError" + + for x in range(int(65536/bytesize)): + buffer = f.read(bytesize) + (l_value,)= struct.unpack(longlongformat, buffer) + hash += l_value + hash = hash & 0xFFFFFFFFFFFFFFFF #to remain as 64bit number + + + f.seek(max(0,filesize-65536),0) + for x in range(int(65536/bytesize)): + buffer = f.read(bytesize) + (l_value,)= struct.unpack(longlongformat, buffer) + hash += l_value + hash = hash & 0xFFFFFFFFFFFFFFFF + + f.close() + returnedhash = "%016x" % hash + return returnedhash + except(IOError): + return "IOError"