Skip to content

Instantly share code, notes, and snippets.

@k0t0vich
Created September 12, 2013 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k0t0vich/6538162 to your computer and use it in GitHub Desktop.
Save k0t0vich/6538162 to your computer and use it in GitHub Desktop.
TarParser
package k0t0vich.utils.net.tar {
import flash.events.EventDispatcher;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
public class TarParser extends EventDispatcher {
private var inputStream: IDataInput;
public function TarParser(bytes: IDataInput) {
super();
this.inputStream = bytes;
}
public function read():Array {
var files: Array = new Array();
while (true) {
var e: TarFile = readFileHeader();
if (e == null)
break;
var size: uint = e.size;
if (e.size > 0) {
inputStream.readBytes(e.data, 0, size);
files.push(e);
readPad(size);
}
}
return files;
}
/**
* Parse Header and create new tar file
* struct header_posix_ustar {
char name[100];
char mode[8];
char uid[8];
char gid[8];
char size[12];
char mtime[12];
char checksum[8];
char typeflag[1];
char linkname[100];
char magic[6];
char version[2];
char uname[32];
char gname[32];
char devmajor[8];
char devminor[8];
char prefix[155];
char pad[12];
};
*/
public function readFileHeader():TarFile {
var fname: String = readUTFBytes(100);
if (!fname || fname.length == 0) {
return null;
}
var tarFile: TarFile = new TarFile(fname);
skipBytes( 8 + 8 + 8);
tarFile.size = parseOctal(12);
skipBytes(8 + 4 + 8 + 1 + 100 + 8 + 32 + 32 + 8 + 8 + 167);
return tarFile;
}
private function readPad(size: uint):void {
// read padding
var pad: uint = Math.ceil(size / 512) * 512 - size;
skipBytes(pad);
}
private function readUTFBytes(size: uint):String {
var bytes: ByteArray = new ByteArray();
inputStream.readBytes(bytes, 0, size);
var result: String = bytes.readUTFBytes(100);
return result;
}
private function skipBytes(size: uint):void {
var bytes: ByteArray = new ByteArray();
inputStream.readBytes(bytes, 0, size);
bytes.clear();
}
private function parseOctal(size: uint = 8):int {
var bytes: ByteArray = new ByteArray();
inputStream.readBytes(bytes, 0, size);
var num: int = 0;
for (var p: uint = 0; p < size; p++) {
var c: int = bytes.readByte();
if (c == 0)
break;
if (c == 32)
continue;
if (c < 48 || c > 55) {
throw new Error("Invalid octal char");
}
num = (num * 8) + (c - 48);
}
bytes.clear();
return num;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment