local L={}function L.CreateBitStream(L)local w={}w.data=L w.pos=0 local I=0 local j=0 function w.ReadBit()if I>=#w.data then return-1 end local L=bit32.band(bit32.rshift(w.data[I+1],7-j),1)j=j+1 if j==8 then j=0 I=I+1 end return L end function w.ReadBits(L)local I=0 for L=1,L,1 do local j=w.ReadBit()if j==-1 then I=-1 break end I=bit32.bor(bit32.lshift(I,1),j)end return I end function w.Align()if I>=#w.data then return end if j~=0 then j=0 I=I+1 end end return w end return L
local module = {}

function module.CreateBitStream(data)
	local stream = {}

	stream.data = data
	stream.pos = 0

	local nextByte = 0
	local nextBit = 0

	function stream.ReadBit()
		if nextByte >= #stream.data then
			return -1
		end

		local bit = bit32.band(bit32.rshift(stream.data[nextByte + 1], (7 - nextBit)), 1)
		nextBit = nextBit + 1

		if nextBit == 8 then
			nextBit = 0
			nextByte = nextByte + 1
		end

		return bit
	end

	function stream.ReadBits(length)
		local bits = 0

		for i = 1, length do
			local bit = stream.ReadBit()

			if bit == -1 then
				bits = -1
				break
			end
			bits = bit32.bor(bit32.lshift(bits, 1), bit)
		end

		return bits
	end

	function stream.Align()
		if nextByte >= #stream.data then
			return
		end

		if nextBit ~= 0 then
			nextBit = 0
			nextByte = nextByte + 1
		end
	end

	return stream
end

return module
