import six


def unpack_dd(buf, offset=0):
    """
    unpack up to 32-bits using the IDA-specific data packing format.

    Args:
      buf (bytes): the region to parse.
      offset (int): the offset into the region from which to unpack. default: 0.

    Returns:
      (int, int): the parsed dword, and the number of bytes consumed.

    Raises:
      KeyError: if the bounds of the region are exceeded.
    """
    if offset != 0:
        # this isn't particularly fast... but its more readable.
        buf = buf[offset:]

    header = six.indexbytes(buf, 0x0)
    if header & 0x80 == 0:
        return header, 1
    elif header & 0xC0 != 0xC0:
        return ((header & 0x7F) << 8) + six.indexbytes(buf, 0x1), 2
    else:
        if header & 0xE0 == 0xE0:
            hi = (six.indexbytes(buf, 0x1) << 8) + six.indexbytes(buf, 0x2)
            low = (six.indexbytes(buf, 0x3) << 8) + six.indexbytes(buf, 0x4)
            size = 5
        else:
            hi = ((header & 0x3F) << 8) + six.indexbytes(buf, 0x1)
            low = (six.indexbytes(buf, 0x2) << 8) + six.indexbytes(buf, 0x3)
            size = 4
        return (hi << 16) + low, size