num: add variable-width greedy int types

This commit is contained in:
Shiz 2021-07-04 23:34:04 +02:00
parent 4400209545
commit e71cacb8f7
2 changed files with 9 additions and 2 deletions

View File

@ -11,6 +11,7 @@ from .types.num import (
int16, uint16, int16be, int16le, uint16be, uint16le, word,
int32, uint32, int32be, int32le, uint32be, uint32le, dword,
int64, uint64, int64be, int64le, uint64be, uint64le, qword,
intbe, intle, uintbe, uintle,
float16, float16le, float16be, binary16, binary16le, binary16be, half,
float32, float32le, float32be, binary32, binary32le, binary32be, float_,
float64, float64le, float64be, binary64, binary64le, binary64be, double,

View File

@ -15,7 +15,7 @@ class Int(Type[int]):
def parse(self, context: Context, stream: Stream) -> int:
n = context.get(self.bits)
bs = stream.read(n // 8)
bs = stream.read(n // 8 if n is not None else -1)
return int.from_bytes(bs, byteorder=context.get(self.endian).to_python(), signed=context.get(self.signed))
def dump(self, context: Context, stream: Stream, value: U[int, float]) -> None:
@ -40,7 +40,8 @@ class Int(Type[int]):
def __str__(self) -> str:
endian = {Endian.Big: 'be', Endian.Little: 'le'}.get(self.endian, self.endian) if self.bits != 8 else ''
sign = {True: '', False: 'u'}.get(self.signed, self.signed)
return f'{sign}int{self.bits}{endian}'
bits = self.bits if self.bits is not None else ''
return f'{sign}int{bits}{endian}'
def __repr__(self) -> str:
return f'{__name__}.Int({self.bits!r}, endian={self.endian!r}, signed={self.signed!r})'
@ -73,6 +74,11 @@ uint64 = \
uint64le = Int(64, endian=Endian.Little, signed=False)
uint64be = Int(64, endian=Endian.Big, signed=False)
intle = Int(None, endian=Endian.Little, signed=True)
intbe = Int(None, endian=Endian.Big, signed=True)
uintle = Int(None, endian=Endian.Little, signed=False)
uintbe = Int(None, endian=Endian.Big, signed=False)
T = TypeVar('T')