oxjs/source/Ox/js/Hash.js

98 lines
2.7 KiB
JavaScript
Raw Normal View History

2012-03-28 09:04:03 +00:00
'use strict';
/*@
2012-03-29 10:26:02 +00:00
Ox.oshash <f> Calculates oshash for a given file or blob object. Async.
2012-03-28 09:04:03 +00:00
@*/
Ox.oshash = function(file, callback) {
2012-03-29 10:26:02 +00:00
// Needs to go via string to work for files > 2GB
2012-03-28 09:04:03 +00:00
var hash = fromString(file.size.toString());
read(0);
function add(A, B) {
var a, b, c, d;
d = A[3] + B[3];
c = A[2] + B[2] + (d >> 16);
d &= 0xffff;
b = A[1] + B[1] + (c >> 16);
c &= 0xffff;
a = A[0] + B[0] + (b >> 16);
b &= 0xffff;
2012-03-29 10:26:02 +00:00
// Cut off overflow
2012-03-28 09:04:03 +00:00
a &= 0xffff;
return [a, b, c ,d];
}
function fromData(s, offset) {
offset = offset || 0;
return [
2012-03-29 10:26:02 +00:00
s.charCodeAt(offset + 6) + (s.charCodeAt(offset + 7) << 8),
s.charCodeAt(offset + 4) + (s.charCodeAt(offset + 5) << 8),
s.charCodeAt(offset + 2) + (s.charCodeAt(offset + 3) << 8),
s.charCodeAt(offset + 0) + (s.charCodeAt(offset + 1) << 8)
2012-03-28 09:04:03 +00:00
];
}
function fromString(str) {
var base = 10,
blen = 1,
i,
num,
pos,
r = [0, 0, 0, 0];
2012-03-29 10:26:02 +00:00
for (pos = 0; pos < str.length; pos++) {
2012-03-28 09:04:03 +00:00
num = parseInt(str.charAt(pos), base);
i = 0;
do {
while (i < blen) {
2012-03-29 10:26:02 +00:00
num += r[3 - i] * base;
r[3 - i++] = (num & 0xffff);
2012-03-28 09:04:03 +00:00
num >>>= 16;
}
if (num) {
blen++;
}
} while (num);
}
return r;
}
function hex(h) {
2012-03-29 10:26:02 +00:00
return (
Ox.pad(h[0].toString(16), 4)
2012-03-28 09:04:03 +00:00
+ Ox.pad(h[1].toString(16), 4)
+ Ox.pad(h[2].toString(16), 4)
2012-03-29 10:26:02 +00:00
+ Ox.pad(h[3].toString(16), 4)
).toLowerCase();
2012-03-28 09:04:03 +00:00
}
function read(offset, last) {
var blob,
block = 65536,
length = 8,
reader = new FileReader();
reader.onload = function(data) {
var s = data.target.result,
s_length = s.length - length,
i;
2012-03-29 10:26:02 +00:00
for (i = 0; i <= s_length; i += length) {
2012-03-28 09:04:03 +00:00
hash = add(hash, fromData(s, i));
}
2012-03-29 10:26:02 +00:00
if (file.size < block || last) {
2012-03-28 09:04:03 +00:00
callback(hex(hash));
} else {
read(file.size - block, true);
}
};
2012-03-29 10:26:02 +00:00
if (file.mozSlice) {
blob = file.mozSlice(offset, offset + block);
} else if (file.webkitSlice) {
blob = file.webkitSlice(offset, offset + block);
2012-03-28 09:04:03 +00:00
} else {
2012-03-29 10:26:02 +00:00
blob = file.slice(offset, offset + block);
2012-03-28 09:04:03 +00:00
}
reader.readAsBinaryString(blob);
}
};