Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- if not docs then os.loadAPI("apis/docs.lua") end
- --Type registry
- local types = {
- ["Bits"]={colors.lightBlue,"A series of bits from 0-7. A byte would be represented by 76543210"},
- ["Byte"]={colors.yellow,"A single byte, number 0-255"},
- ["DecodedBlock"]={colors.lightBlue,"A list of decoded bytes"},
- ["HuffmanCode"]={colors.purple,"A code for decompressing values"},
- ["Bitstream"]={colors.lightBlue,"A stream of bits from the file"}
- }
- for k,v in pairs(types) do
- docs.registerType(k,v[1],v[2])
- end
- --Gets the bits from a byte, starting from least significant
- --@Arg Byte byte: The byte to unpack
- --@Returns Bits b: The bits from the byte
- local function unpackByte(byte)
- local b = {}
- for i=0,7 do
- b[i] = byte%2
- byte = math.floor(byte/2)
- end
- return b
- end
- --Takes a byte and turns it into a series of bits
- --@Arg Byte byte: A byte 0-255 to be converted
- --@OptionalArg boolean bool: If true, converts the bits to false/true instead of 0/1
- --@Returns Bits bits: A table of the bits from 0-7
- local function byteToBits(byte,bool)
- local bits = {}
- for i=0,7 do
- bits[i] = byte%2
- if bool then bits[i] = bits[i] == 1 end
- byte = math.floor(byte/2)
- end
- return bits
- end
- local function unpackBits(bytes)
- local bits = {}
- for k,v in ipairs(bytes) do
- local b = unpackByte(v)
- for i=0,7 do
- table.insert(bits,b[i])
- end
- end
- return bits
- end
- --Starting with least significant bit
- --@Arg Bits bits: The series of bits to convert to a number, with the least significant bit first and the most significant last
- --@Arg boolean littleEndian: Whether to start with least significant, or most significant
- --@Returns number num: The resultant number
- local function bitsToNum(bits,littleEndian)
- if not littleEndian then
- local num = 0
- for k,v in ipairs(bits) do
- num = num*2+v
- end
- return num
- end
- local num = 0
- local i = #bits
- while i >= 1 do
- num = num*2+bits[i]
- i = i - 1
- end
- return num
- end
- --Instantiates a new bitstream
- --@Arg table bytes: A table of the bytes to be decoded
- --@Returns Bitstream bs: The bitstream and functions to access it
- function bitStream(bytes)
- local bs = {
- pos=0
- }
- if bytes.type == "bits" then bs.bits = bytes
- else bs.bits = unpackBits(bytes) end
- --Peeks a certain amount, without incrementing position
- function bs:peekb(amount,pos)
- pos = tonumber(pos) or self.pos
- local b = {}
- amount = tonumber(amount) or 1
- for i=1,amount do
- table.insert(b,self.bits[pos+i])
- end
- return b
- end
- --Gets a series of the next few bits
- function bs:getb(amount)
- amount = tonumber(amount) or 1
- self.pos = self.pos
- return self:peekb(amount)
- end
- --Gets the next byte, discarding the remaining bits in the current byte
- --If you want to get the next byte starting at the current position, use bitsToNum(bs:getb(8))
- function bs:nextByte(bigEndian)
- local _ = self:getb((8-self.pos%8))
- return bitsToNum(self:getb(8),bigEndian)
- end
- function bs:shiftl(amount)
- amount = amount or 1
- self.pos = self.pos - amount
- end
- function bs:shiftr(amount)
- amount = amount or 1
- self.pos = self.pos + amount
- end
- --Gets the next huff code
- --@Arg HuffmanCode hufftable: The table to get the code from
- --@OptionalArg number maxLen: The maximum length to read
- --@Returns number code: The huffman code read from the bitstream
- --@Returns None nil: If there was no code found
- function bs:getHuffV(hufftable,maxLen)
- -- local num = hufftable[bitsToNum(self:peekb(maxLen),true)]
- -- local len = bit.band(num,15)
- -- self:shiftr(len)
- -- return math.floor(num/(2^4))
- for i=1,(tonumber(maxLen) or 16) do
- local num = bitsToNum(self:peekb(i),true)
- term.write(num .. " ")
- if hufftable[num] then
- self:shiftr(i)
- print()
- return hufftable[num]
- end
- end
- end
- --Gets a bitstream starting from a position in this bitstream with a predefined length
- --@Arg number len: The length of the bitstream
- --@OptionalArg number startPos: The position within the bitstream to use
- --@Returns Bitstream bs2: The new bitstream
- function bs:subBits(len,startPos)
- local bits = self:peekb(len,startPos)
- bits.type = "bits"
- return bitStream(bits)
- end
- --Gets a number from a bitstream
- --@OptionalArg number amount: The number of bits to read
- --@Returns number num: The number read from the bits, with least significant bit read first
- function bs:getn(amount,bigEndian)
- return bitsToNum(self:getb(amount),bigEndian)
- end
- return bs
- end
- --TODO: Test out, came from https://www.ietf.org/rfc/rfc1951.txt
- --@Arg table lengths: {{n=v1,len=length}...}
- --@Returns HuffmanCode h: The huffman code
- function createHuffman(lengths)
- local bl_count = {}
- local next_code = {}
- local max_bits = 0
- for k,v in ipairs(lengths) do
- bl_count[v.len] = (bl_count[v.len] or 0) + 1
- max_bits = math.max(max_bits,v.len)
- end
- local code = 0
- bl_count[0] = 0
- for i=1,max_bits do
- code = (code+(bl_count[i-1] or 0))*2 --doing a << 1; in general a<<b (a leftshifted by b) is equal to a*(2^b)
- next_code[i] = code
- end
- local h = {}
- for i,v in ipairs(lengths) do
- if v.len ~= 0 then
- h[next_code[v.len]] = v.n
- next_code[v.len] = next_code[v.len]+1
- end
- -- v = v or 0
- -- if v > 0 then
- -- local e = (i-1)*16 + v
- -- local code = next_code[v]
- -- local rcode = 0
- -- for j=1,v do
- -- rcode = rcode + bit.band(1,math.floor(code/(2^(j-1))))*(2^(v-j))
- -- end
- -- for j=0,2^max_bits-1,2^v do
- -- table[j+rcode] = e
- -- end
- -- next_code[v] = next_code[v] + 1
- -- end
- end
- return h
- end
- --Creates a huffman code from a bitstream
- --@Arg Bitstream bs: The bitstream to read from, if the table is dynamic
- --@Arg boolean isStatic: Whether the table should be static or not
- --@Returns HuffmanCode lit, HuffmanCode dist, HuffmanCode clen: The huffman codes for the literal/lengths, the distances, and the code lengths
- --@Returns HuffmanCode lit, HuffmanCode dist: If is static, no codelength table is needed
- function huffman(bs,isStatic)
- if not isStatic then
- local hlit = bs:getn(5) + 257 --Length of literal and length codes
- local hdist = bs:getn(5) + 1
- local hclen = bs:getn(4) + 4
- local order = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}
- local clen = {} --code length lengths table
- for i=1,hclen do
- local key = bs:getn(3)
- table.insert(clen,{n=order[i],len=key})
- --clen[order[i]] = key
- end
- for i=hclen+1,#order do
- --clen[order[i]] = 0
- table.insert(clen,{n=order[i],len=0})
- end
- clen = createHuffman(clen) --converting into huffman
- local prevCode = 0
- local lit = {} --literal lengths table
- local index = 0
- while index < hlit do
- local code = bs:getHuffV(clen) or 0
- if code <= 15 then --literal lengths
- table.insert(lit,{n=index,len=code})
- index = index+1
- prevCode = code
- elseif code == 16 then
- local len = bs:getn(2) + 3
- for i=1,len do
- table.insert(lit,{n=index,len=prevCode})
- index = index+1
- end
- elseif code == 17 or code == 18 then
- local len
- if code == 17 then len = 3+bs:getn(3) else len = 11+bs:getn(7) end
- for i=1,len do
- table.insert(lit,{n=index,len=0})
- index = index+1
- end
- end
- end
- lit = createHuffman(lit)
- local index = 0
- local dist = {}
- while index < hdist do
- local code = bs:getHuffV(clen) or 0
- if code <= 15 then --literal lengths
- table.insert(dist,{n=index,len=code})
- index = index+1
- prevCode = code
- elseif code == 16 then
- local len = bs:getn(2) + 3
- for i=1,len do
- table.insert(dist,{n=index,len=prevCode})
- index = index+1
- end
- elseif code == 17 or code == 18 then
- local len
- if code == 17 then len = 3+bs:getn(3) else len = 11+bs:getn(7) end
- for i=1,len do
- table.insert(dist,{n=index,len=0})
- index = index+1
- end
- end
- end
- dist = createHuffman(dist)
- return lit,dist,clen
- else
- local lengths = {}
- local counts = {144,112,24,8}
- local blens = {8,9,7,8}
- local n = 0
- for i=1,#counts do
- local blen = blens[i]
- for j=1,counts[i] do
- table.insert(lengths,{n=n,len=blen})
- n = n+1
- end
- end
- local lit = createHuffman(lengths)
- lengths = {}
- for i=0,31 do
- table.insert(lengths,{n=i,len=5})
- --lengths[i] = 5
- end
- local dist = createHuffman(lengths)
- return lit,dist
- end
- end
- --Reads a block within a bitstream
- --@Arg Bitstream bs: The bitstream to read from
- --@Returns boolean bfinal, DecodedBlock bytes: If the block is the last one, and the decoded information
- function readBlock(bs)
- local bfinal = bs:getn() == 1
- local btype = bs:getn(2)
- print(bfinal, btype)
- if btype == 3 then error("Invalid type") end
- if btype == 0 then
- local len = bs:nextByte()
- len = len + bs:nextByte()*256
- local nlen = bs:nextByte()
- nlen = nlen + bs:nextByte()*256
- local bytes = {}
- for i=1,len do
- local b = bs:nextByte()
- print(b)
- table.insert(bytes,b)
- end
- return bfinal,bytes
- end
- local bytes = {}
- local littable,disttable = huffman(bs,btype == 1)
- local code = bs:getHuffV(littable) or 0
- while code ~= 256 do
- print("code:", code)
- if code <= 255 then
- print(code)
- table.insert(bytes,code)
- else
- local nbits = 0
- local size = 3
- local dist = 1
- if code < 265 then
- size = size + code - 257
- elseif code < 285 then
- nbits = math.floor((lit-261)/4) -- lit-261 >> 2, rightshifted 2
- size = size + (bit.band(code-261,3)+4)*(2^nbits) --no clue how this formula works
- else
- size = 258
- end
- if nbits > 0 then
- size = size + bs:getn(nbits)
- end
- local v = bs:getHuffV(disttable) or 0
- if v < 4 then dist = dist + v
- else
- nbits = math.floor((v-2)/2)
- dist = dist + (bit.band(v,1)+2)*(2^nbits)
- dist = dist + bs:getb(nbits)
- end
- print("len:",size,"dist:",dist)
- local p = #bytes - dist + 1 --copying repeat sequences
- while size > 0 do
- print("prev code at p:",bytes[p])
- table.insert(bytes,bytes[p])
- p = p+1
- size = size - 1
- end
- end
- code = bs:getHuffV(littable) or 0
- end
- return bfinal,bytes
- end
- --Gets the stupid member thingie
- --@Arg File file: The file opened in rb mode to read
- --@Returns boolean false: If sussy stuff happens
- --@Returns Byte id1, Byte id2, Byte cm, number mtime, Byte xfl, byte opSys, table extra, string name, string comment, number fhcrc, table data, number crc32, number iSize
- function readMember(file)
- local name, comment = "",""
- local fhcrc
- local extra = {}
- local id1,id2 = file.read(), file.read() --bytes 1 and 2 are for the ids
- local cm = file.read() --byte 3 is for the compression method, usually 0x08
- local flgs = byteToBits(file.read(),true)
- --Ignore flgs[0] because we dont care about text/nontext. Dealing with flgs[1] FHCRC later
- local mtime = 0
- for i=0,3 do
- mtime = file.read()*(256^i)+mtime --changed to little endian
- end
- local xfl = file.read()
- local opSys = file.read()
- if flgs[2] then --FEXTRA
- local len = file.read()
- len = len+256*file.read() --changed to little endian
- while len > 0 do
- local si1 = file.read()
- local si2 = file.read()
- local sLen = file.read()
- sLen = sLen+256*file.read() --changed to little endian
- len = len - 4
- local sData = {}
- while sLen > 0 and len > 0 do
- table.insert(sData,file.read())
- sLen = sLen-1
- len = len-1
- end
- extra[si1+si2*256] = sData --little endian as well for index
- end
- end
- if flgs[3] then --FNAME
- name = ""
- local byte = file.read()
- while byte > 0 do
- name = name .. string.char(byte)
- byte = file.read()
- end
- end
- if flgs[4] then --FCOMMENT
- comment = ""
- local byte = file.read()
- while byte > 0 do
- name = name .. string.char(byte)
- byte = file.read()
- end
- end
- if flgs[1] then --dealing with FHCRC
- fhcrc = file.read()
- fhcrc = fhcrc+256*file.read() --made little endian
- end
- --Reading the data
- local data = {}
- while file.read(0) do
- table.insert(data,file.read())
- end
- local crc32 = 0
- for i=#data-7,#data-4 do
- crc32 = crc32+data[i]*256 --little endian
- end
- local iSize = 0
- for i=#data-3,#data do
- iSize = iSize+256*data[i] --little endian
- end
- return id1,id2,cm,mtime,xfl,opSys,extra,name,comment,fhcrc,data,crc32,iSize
- end
- --Gets the decoded bytes from a zipped file
- --@Arg string path: The absolute path to the gzip file
- --@Returns boolean false: If stuff went wrong or something
- --@Returns table info: A table of DecodedBytes
- function getUnzippedBytes(path)
- if not fs.exists(path) then return false end
- file = fs.open(path,"rb")
- local id1,id2,cm,mtime,xfl,opSys,extra,name,comment,fhcrc,data,crc32,iSize = readMember(file)
- file.close()
- if id1 ~= 0x1f or id2 ~= 0x8b then
- return false
- end
- if cm ~= 8 then
- return false
- end
- local bs = bitStream(data)
- local info = {}
- local isFinal,bytes = readBlock(bs)
- table.insert(info,bytes)
- while not isFinal do
- table.insert(info,bytes)
- isFinal,bytes = readBlock(bs)
- end
- return info
- end
Advertisement
Add Comment
Please, Sign In to add comment