Reputation: 20075
I'm trying to rewrite a javascript file decompression routine to python. But I can't seem to get it right. The function always returns None
on python.
Here is the original JS:
var c = new Uint8Array(b),
d = 0,
e = new Uint32Array(4096),
f = new Uint32Array(4096),
g = 256,
h = a.length,
k = 0,
l = 1,
m = 0,
n = 1;
c[d++] = a[0];
for (var r = 1;; r++) {
n = r + (r >> 1);
if (n + 1 >= h) break;
var m = a[n + 1],
n = a[n],
p = r & 1 ? m << 4 | n >> 4 : (m & 15) << 8 | n;
if (p < g)
if (256 > p) m = d, n = 1, c[d++] = p;
else
for (var m = d, n = f[p], p = e[p], q = p + n; p < q;) c[d++] = c[p++];
else if (p == g) {
m = d;
n = l + 1;
p = k;
for (q = k + l; p < q;) c[d++] = c[p++];
c[d++] = c[k]
} else break;
e[g] = k;
f[g++] = l + 1;
k = m;
l = n;
g = 4096 <= g ? 256 : g
}
return d == b ? c : null
And here is my python implementation, what did I do wrong? (Improved with @le_m answer but still returning None.)
c = [0] * b
d = 0
e = [0] * 4096
f = [0] * 4096
g = 256
h = len(a)
k = 0
l = 1
m = 0
n = 1
c[d] = a[0]
d += 1
r = 1
while True:
n = r + (r >> 1)
if (n + 1) >= h:
break
m = a[n + 1]
n = a[n]
p = (m << 4 | n >> 4) if r & 1 else ((m & 15) << 8 | n)
if (p < g):
if (256 > p):
m = d
n = 1
c[d] = p
d += 1
else:
m = d
n = f[p]
p = e[p]
q = p + n
while p < q:
c[d] = c[p]
d += 1
p += 1
elif p == g:
m = d
n = 1 + 1
p = k
q = k + l
while p < q:
c[d] = c[p]
d += 1
p += 1
else:
break
e[g] = k
f[g] = l + 1
g += 1
k = m
l = n
g = 256 if 4096 <= g else g
r += 1
Upvotes: 0
Views: 39
Reputation: 20248
Just from glancing at the code, I spot the following differences:
new Uint8Array(b)
translates to [0] * b
as the typed array is initialized with zeros. Same holds for the other typed arrays.c[d++] = a[0]
translates to c[d] = a[0]
followed by d += 1
, not the other way round. Same holds for the other post-increments, too.r += 1
should go to the end of the loop body or should be initialized with 0
instead.I recommend stepping through both implementations step by step with a debugger (your browser's developer console for JavaScript) and compare the variable values.
Upvotes: 2