io: introduce `hard` parameter for Sized

This commit is contained in:
Shiz 2021-08-09 06:44:13 +02:00
parent 7255a990c7
commit a2c7fb7d26
1 changed files with 18 additions and 6 deletions

View File

@ -61,9 +61,10 @@ class SizedStream:
T = TypeVar('T')
class Sized(G[T], Wrapper[T]):
def __init__(self, child: Type[T], limit: U[Pos, PossibleDynamic]) -> None:
def __init__(self, child: Type[T], limit: U[Pos, PossibleDynamic], hard=False) -> None:
super().__init__(child)
self.limit = limit
self.hard = hard
def parse(self, context: Context, stream: Stream) -> T:
limit = max(0, context.get(self.limit))
@ -73,13 +74,24 @@ class Sized(G[T], Wrapper[T]):
return value
def dump(self, context: Context, stream: Stream, value: T) -> None:
limit = max(0, context.get(self.limit))
start = stream.tell()
super().dump(context, SizedStream(stream, limit), value)
stream.seek(start + limit, os.SEEK_SET)
hard = context.get(self.hard)
if hard:
limit = max(0, context.get(self.limit))
start = stream.tell()
super().dump(context, SizedStream(stream, limit), value)
stream.seek(start + limit, os.SEEK_SET)
else:
start = stream.tell()
super().dump(context, stream, value)
size = stream.tell() - start
context.put(self.limit, size)
def sizeof(self, context: Context, value: O[T]) -> O[Pos]:
return context.peek(self.limit)
hard = context.peek(self.hard)
if hard:
return context.peek(self.limit)
else:
return super().sizeof(context, value)
class TerminatedStream: