Mercurial > lcfOS
view python/ppci/core/bitreader.py @ 104:ed230e947dc6
Added hexviewer
author | windel |
---|---|
date | Sun, 30 Dec 2012 22:31:55 +0100 |
parents | 4a37d6992bd3 |
children | 6a303f835c6d |
line wrap: on
line source
from .errors import CompilerException import struct def bits(f): while True: Byte = f.read(1) for i in range(8): yield Byte & 0x1 Byte >>= 1 class BitReader: def __init__(self, f): self.stream = bits(f) self.curword = None def parseModule(self): if self.read(8) != ord('B') or self.read(8) != ord('C'): raise CompilerException('Invalid bitcode signature') for bitsig in [0x0, 0xC, 0xE, 0xD]: if self.read(4) != bitsig: raise CompilerException('Invalid bitcode signature') def read(self, numbits): if numbits == 8: b = self.stream.read(1) print(b) return int(b[0]) return 2 class BitstreamWriter: def __init__(self, f): self.f = f self.u32 = 0 self.curpos = 0 def Emit1(self, val): self.Emit(val, 1) def Emit(self, val, numbits): """ Emits value using numbits bits """ if numbits == 1: if val != 0: self.u32 |= (0x1 << self.curpos) self.curpos += 1 if self.curpos == 32: self.writeWord() elif numbits > 1: for i in range(numbits): if val & (1 << i) != 0: self.Emit1(1) else: self.Emit1(0) def writeWord(self): bts = struct.pack('<I', self.u32) self.f.write(bts) self.u32 = 0 self.curpos = 0 def flush(self): if self.curpos != 0: self.writeWord() class BitcodeWriter: def __init__(self): pass def WriteModule(self, module): pass def WriteModuleToFile(self, module, f): s = BitstreamWriter(f) s.Emit(ord('B'), 8) s.Emit(ord('C'), 8) s.Emit(0x0, 4) s.Emit(0xC, 4) s.Emit(0xE, 4) s.Emit(0xD, 4) self.WriteModule(module) s.flush()