# Copyright 2021 Seeky
# Licensed under GPLv2+

class BinaryBuffer:
    def __init__(self, data):
        self.data = bytearray(data[:])

    def writeat(self, offset, data):
        for i, val in enumerate(data):
            self.data[offset+i] = val
    
    def readat(self, offset, length):
        out = bytearray()
        for i in range(0, length):
            out.append(self.data[offset+i])
        return out

    def writeWord(self, offset, val):
        b = int.to_bytes(val, 4, 'big')
        self.writeat(offset, b)
    
    def writeHalfword(self, offset, val):
        b = int.to_bytes(val, 2, 'big')
        self.writeat(offset, b)

    def writeByte(self, offset, val):
        b = int.to_bytes(val, 1, 'big')
        self.writeat(offset, b)
    
    def writeStr(self, offset, str):
        i = 0
        for c in str:
            self.data[offset+i] = ord(c)
            i += 1
        self.data[offset+i] = 0

    def readWord(self, offset):
        return int.from_bytes(self.readat(offset, 4), 'big')
    
    def readHalfword(self, offset):
        return int.from_bytes(self.readat(offset, 2), 'big')
    
    def readByte(self, offset):
        return int.from_bytes(self.readat(offset, 1), 'big')
    
    def readStr(self, offset, encoding='ascii'):
        out = bytearray()
        i = 0
        while True:
            c = self.data[offset+i]
            if c == 0:
                break
            i += 1
            out.append(c)
        return out.decode(encoding=encoding)
        
