47 lines
1.4 KiB
Plaintext
47 lines
1.4 KiB
Plaintext
class Buf:
|
|
data: char*
|
|
length: sizet
|
|
capacity: sizet
|
|
owned: bool
|
|
|
|
def __init__(self, data: char*, capacity: sizet, length: sizet = 0, owned: bool = False):
|
|
self.data = data
|
|
self.capacity = capacity
|
|
self.length = length
|
|
self.owned = owned
|
|
|
|
def clear(self):
|
|
self.length = 0
|
|
if self.data != None and self.capacity > 0: self.data[0] = 0
|
|
|
|
def write(self, src: char*, count: sizet) -> sizet:
|
|
if self.data == None: return 0
|
|
if src == None: return 0
|
|
if count == 0: return 0
|
|
avail: sizet = self.capacity - self.length
|
|
if avail <= 0: return 0
|
|
n: sizet = count if count < avail else avail
|
|
for i in range(int(n)):
|
|
self.data[self.length + i] = src[i]
|
|
self.length += n
|
|
# When exactly full (n==avail), data[capacity] would overflow by 1 byte, so guard it
|
|
if self.length < self.capacity: self.data[self.length] = 0
|
|
return n
|
|
|
|
def cstr(self) -> char*: return self.data
|
|
|
|
def reset(self):
|
|
self.length = 0
|
|
if self.data != None and self.capacity > 0: self.data[0] = 0
|
|
|
|
def __enter__(self) -> Buf*: return self
|
|
def __exit__(self): self.reset()
|
|
|
|
def free(self):
|
|
if self.owned and self.data != None:
|
|
self.data[0] = 0
|
|
self.owned = False
|
|
self.data = None
|
|
self.length = 0
|
|
self.capacity = 0
|