Source code for autobahn.flatbuffers.number_types
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import struct
from . import packer
from .compat import NumpyRequiredForThisFeature, import_numpy
# For reference, see:
# https://docs.python.org/2/library/ctypes.html#ctypes-fundamental-data-types-2
# These classes could be collections.namedtuple instances, but those are new
# in 2.6 and we want to work towards 2.5 compatability.
[docs]
class BoolFlags(object):
[docs]
packer_type = packer.boolean
[docs]
class Uint8Flags(object):
[docs]
packer_type = packer.uint8
[docs]
class Uint16Flags(object):
[docs]
packer_type = packer.uint16
[docs]
class Uint32Flags(object):
[docs]
packer_type = packer.uint32
[docs]
class Uint64Flags(object):
[docs]
packer_type = packer.uint64
[docs]
class Int8Flags(object):
[docs]
packer_type = packer.int8
[docs]
class Int16Flags(object):
[docs]
packer_type = packer.int16
[docs]
class Int32Flags(object):
[docs]
packer_type = packer.int32
[docs]
class Int64Flags(object):
[docs]
packer_type = packer.int64
[docs]
class Float32Flags(object):
[docs]
packer_type = packer.float32
[docs]
class Float64Flags(object):
[docs]
packer_type = packer.float64
[docs]
class SOffsetTFlags(Int32Flags):
pass
[docs]
class UOffsetTFlags(Uint32Flags):
pass
[docs]
class VOffsetTFlags(Uint16Flags):
pass
[docs]
def valid_number(n, flags):
if flags.min_val is None and flags.max_val is None:
return True
return flags.min_val <= n <= flags.max_val
[docs]
def enforce_number(n, flags):
if flags.min_val is None and flags.max_val is None:
return
if not flags.min_val <= n <= flags.max_val:
raise TypeError("bad number %s for type %s" % (str(n), flags.name))
[docs]
def float32_to_uint32(n):
packed = struct.pack("<1f", n)
(converted,) = struct.unpack("<1L", packed)
return converted
[docs]
def uint32_to_float32(n):
packed = struct.pack("<1L", n)
(unpacked,) = struct.unpack("<1f", packed)
return unpacked
[docs]
def float64_to_uint64(n):
packed = struct.pack("<1d", n)
(converted,) = struct.unpack("<1Q", packed)
return converted
[docs]
def uint64_to_float64(n):
packed = struct.pack("<1Q", n)
(unpacked,) = struct.unpack("<1d", packed)
return unpacked
[docs]
def to_numpy_type(number_type):
if np is not None:
return np.dtype(number_type.name).newbyteorder("<")
else:
raise NumpyRequiredForThisFeature("Numpy was not found.")