Esempio n. 1
0
def _encode_data(entry, value, length):
    if entry.format in (Field.BINARY, Field.HEX):
        assert isinstance(value, Data)
        result = value.copy()
    elif entry.format == Field.TEXT:
        assert isinstance(value, basestring)
        try:
            result = Data(value.encode(entry.encoding))
        except UnicodeDecodeError:
            raise BadEncodingError(entry, value)
    elif entry.format == Field.INTEGER:
        assert isinstance(value, (int, long))
        if length is None:
            raise FieldDataError(entry, "Unable to encode integer field " "without explicit length")
        assert entry.encoding in [Field.BIG_ENDIAN, Field.LITTLE_ENDIAN]
        if entry.encoding == Field.BIG_ENDIAN:
            result = Data.from_int_big_endian(value, length)
        else:
            result = Data.from_int_little_endian(value, length)
    elif entry.format == Field.FLOAT:
        assert entry.encoding in [Field.BIG_ENDIAN, Field.LITTLE_ENDIAN]
        assert isinstance(value, float)
        if entry.encoding == Field.BIG_ENDIAN:
            result = Data.from_float_big_endian(value, length)
        else:
            result = Data.from_float_little_endian(value, length)
    else:
        raise Exception("Unknown field format of '%s'!" % entry.format)

    return result
Esempio n. 2
0
def _encode_unknown_variable_length_integer(entry, value, params):
    # Integers require a specific length of encoding. If one is
    # not specified, we'll try several lengths until we find one
    # that fits.
    #
    # We only consider lengths that are in the range specified by
    # the entry length to avoid choosing an out of bounds length.
    assert params is not None, "Asked to encode a variable length field " \
            "without parameters. This shouldn't happen."
    for length in get_valid_integer_lengths(entry, params):
        try:
            if entry.format != Field.INTEGER or entry.encoding == Field.BIG_ENDIAN:
                result = Data.from_int_big_endian(value, length)
                return result
            else:
                return Data.from_int_little_endian(value, length)
        except IntegerTooLongError:
            # The value didn't fit in this length... try the next
            # one.
            pass
    else:
        raise VariableIntegerTooLongError(entry, value)