Skip to content

Instantly share code, notes, and snippets.

@gln7

gln7/dec1.mjs Secret

Created November 29, 2024 22:18
Show Gist options
  • Save gln7/aab55674431b1c8d42a59ccf9d7cbf60 to your computer and use it in GitHub Desktop.
Save gln7/aab55674431b1c8d42a59ccf9d7cbf60 to your computer and use it in GitHub Desktop.
dec1.mjs
import { Uint8ArrayList } from 'uint8arraylist';
var ChunkType_IDENTIFIER = 0xff;
var ChunkType_COMPRESSED = 0x00;
var ChunkType_UNCOMPRESSED = 0x01;
var ChunkType_PADDING = 0xfe;
var IDENTIFIER = Buffer.from([0x73, 0x4e, 0x61, 0x50, 0x70, 0x59]);
var IDENTIFIER_FRAME = Buffer.from([0xff, 0x06, 0x00, 0x00, 0x73, 0x4e, 0x61, 0x50, 0x70, 0x59]);
function uncompress(chunk) {
var foundIdentifier = false;
var buffer = new Uint8ArrayList();
buffer.append(chunk);
var result = new Uint8ArrayList();
while (buffer.length > 0) {
if (buffer.length < 4) break;
console.log("checking chunk type=" + buffer.get(0));
var type = getChunkType(buffer.get(0));
var frameSize = getFrameSize(buffer, 1);
if (buffer.length - 4 < frameSize) {
break;
}
var data = buffer.subarray(4, 4 + frameSize);
buffer.consume(4 + frameSize);
if (!foundIdentifier && type !== ChunkType_IDENTIFIER) {
throw "malformed input: must begin with an identifier";
}
if (type === ChunkType_IDENTIFIER) {
if (!Buffer.prototype.equals.call(data, IDENTIFIER)) {
throw "malformed input: bad identifier";
}
foundIdentifier = true;
continue;
}
if (type === ChunkType_COMPRESSED) {
// result.append(uncompress(data.subarray(4)));
}
if (type === ChunkType_UNCOMPRESSED) {
console.log("got uncompressed chunk..");
result.append(data.subarray(4));
}
}
if (result.length === 0) {
return null;
}
return result;
}
function getFrameSize(buffer, offset) {
return buffer.get(offset) + (buffer.get(offset + 1) << 8) + (buffer.get(offset + 2) << 16);
}
function getChunkType(value) {
switch (value) {
case ChunkType_IDENTIFIER:
return ChunkType_IDENTIFIER;
case ChunkType_COMPRESSED:
return ChunkType_COMPRESSED;
case ChunkType_UNCOMPRESSED:
return ChunkType_UNCOMPRESSED;
case ChunkType_PADDING:
return ChunkType_PADDING;
default:
throw new Error("Unsupported snappy chunk type");
}
}
var chunk = new Uint8ArrayList();
chunk.append(Uint8Array.from([0xff,0x06,0x00,0x00,0x73,0x4e,0x61,0x50,0x70,0x59]));
var data = [0x01, 0x80, 0x00, 0x00];
for (var i = 0; i < 0x80; i+=1) {
data.push(0x41);
}
chunk.append(Uint8Array.from(data));
var result = uncompress(chunk);
console.log("Decompressed ok "+result.length + " bytes");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment