def writeLength(value: int) -> bytes: """ Pack a PER length indicator """ if value > 0x7f: return Uint16BE.pack(value | 0x8000) else: return Uint8.pack(value)
def writeLength(length: int) -> bytes: """ Pack structure length as expected in BER specification :param length: structure length. """ if length > 0x7f: return Uint8.pack(0x82) + Uint16BE.pack(length) else: return Uint8.pack(length)
def writeInteger(value: int) -> bytes: """ Pack a PER integer """ if value <= 0xff: return writeLength(1) + Uint8.pack(value) elif value < 0xffff: return writeLength(2) + Uint16BE.pack(value) else: return writeLength(4) + Uint32BE.pack(value)
def writeLength(value): """ Pack a PER length indicator :type value: int :return: str """ if value > 0x7f: return Uint16BE.pack(value | 0x8000) else: return Uint8.pack(value)
def writeInteger(value): """ Pack a PER integer :type value: int :return: str """ if value <= 0xff: return writeLength(1) + Uint8.pack(value) elif value < 0xffff: return writeLength(2) + Uint16BE.pack(value) else: return writeLength(4) + Uint32BE.pack(value)
def writeInteger(value): """ Pack a BER integer :type value: int :return: str """ if value <= 0xff: return writeUniversalTag(Tag.BER_TAG_INTEGER, False) + writeLength(1) + Uint8.pack(value) elif value <= 0xffff: return writeUniversalTag(Tag.BER_TAG_INTEGER, False) + writeLength(2) + Uint16BE.pack(value) else: return writeUniversalTag(Tag.BER_TAG_INTEGER, False) + writeLength(4) + Uint32BE.pack(value)
def readInteger(s: BinaryIO) -> int: """ Unpack a BER integer :param s: stream """ if not readUniversalTag(s, Tag.BER_TAG_INTEGER, False): raise ValueError("Bad integer tag") size = readLength(s) if size == 1: return Uint8.unpack(s.read(1)) elif size == 2: return Uint16BE.unpack(s.read(2)) elif size == 3: integer1 = Uint8.unpack(s.read(1)) integer2 = Uint16BE.unpack(s.read(2)) return (integer1 << 16) + integer2 elif size == 4: return Uint32BE.unpack(s.read(4)) else: raise ValueError("Wrong integer size")
def readInteger(s: BinaryIO) -> int: """ Unpack a PER integer :param s: stream @raise InvalidValue: if the size of the integer is invalid """ size = readLength(s) if size == 1: return Uint8.unpack(s.read(1)) elif size == 2: return Uint16BE.unpack(s.read(2)) elif size == 4: return Uint32BE.unpack(s.read(4)) else: raise ValueError("invalid integer size %d" % size)
def readLength(s: BinaryIO) -> int: """ Read length of BER structure Length is on 1, 2 or 3 bytes :param s: stream """ byte = Uint8.unpack(s.read(1)) if byte & 0x80: byte &= ~0x80 if byte == 1: return Uint8.unpack(s.read(1)) elif byte == 2: return Uint16BE.unpack(s.read(2)) else: raise ValueError("BER length must be 1 or 2") else: return byte