Пример #1
0
    def __call__(cls, lib, *args, **kwargs):

        # Identify the library path.
        if istext(lib) or isbytes(lib):
            if os.sep not in lib:
                lib_path = find_library(lib).path
            else:
                lib_path = os.path.realpath(lib)
                assert os.path.isfile(lib_path),\
                    'Provided path does not point to a file'
            backend_cls = cls.backends[kwargs.get('backend', 'ctypes')]

            lib_arch = LibraryPath(lib_path).arch
            py_bitness = 64 if sys.maxsize > 2**32 else 32
            if lib_arch and py_bitness not in lib_arch:
                raise OSError("Library bitness does not match Python's")
            lib = lib_path
        else:
            from .backends import identify_library, get_library_path
            backend = identify_library(lib)
            backend_cls = cls.backends[backend]
            lib_path = get_library_path(lib, backend)

        # Check whether or not this library has already been opened.
        if lib_path in cls.libs:
            return cls.libs[lib_path]

        else:
            obj = super(CLibraryMeta, backend_cls).__call__(lib, *args,
                                                            **kwargs)
            cls.libs[lib_path] = obj
            return obj
Пример #2
0
 def join(self, iterable_of_bytes):
     errmsg = 'sequence item {0}: expected bytes, {1} found'
     if isbytes(iterable_of_bytes) or istext(iterable_of_bytes):
         raise TypeError(errmsg.format(0, type(iterable_of_bytes)))
     for i, item in enumerate(iterable_of_bytes):
         if istext(item):
             raise TypeError(errmsg.format(i, type(item)))
     return newbytes(super(newbytes, self).join(iterable_of_bytes))
Пример #3
0
    def __new__(cls, x=0, base=10):
        """
        From the Py3 int docstring:

        |  int(x=0) -> integer
        |  int(x, base=10) -> integer
        |
        |  Convert a number or string to an integer, or return 0 if no
        |  arguments are given.  If x is a number, return x.__int__().  For
        |  floating point numbers, this truncates towards zero.
        |
        |  If x is not a number or if base is given, then x must be a string,
        |  bytes, or bytearray instance representing an integer literal in the
        |  given base.  The literal can be preceded by '+' or '-' and be
        |  surrounded by whitespace.  The base defaults to 10.  Valid bases are
        |  0 and 2-36. Base 0 means to interpret the base from the string as an
        |  integer literal.
        |  >>> int('0b100', base=0)
        |  4

        """
        try:
            val = x.__int__()
        except AttributeError:
            val = x
        else:
            if not isint(val):
                raise TypeError('__int__ returned non-int ({0})'.format(
                    type(val)))

        if base != 10:
            # Explicit base
            if not (istext(val) or isbytes(val) or isinstance(val, bytearray)):
                raise TypeError(
                    "int() can't convert non-string with explicit base")
            try:
                return super(newint, cls).__new__(cls, val, base)
            except TypeError:
                return super(newint, cls).__new__(cls, newbytes(val), base)
        # After here, base is 10
        try:
            return super(newint, cls).__new__(cls, val)
        except TypeError:
            # Py2 long doesn't handle bytearray input with an explicit base, so
            # handle this here.
            # Py3: int(bytearray(b'10'), 2) == 2
            # Py2: int(bytearray(b'10'), 2) == 2 raises TypeError
            # Py2: long(bytearray(b'10'), 2) == 2 raises TypeError
            try:
                return super(newint, cls).__new__(cls, newbytes(val))
            except:
                raise TypeError("newint argument must be a string or a number,"
                                "not '{0}'".format(type(val)))
Пример #4
0
    def arg_c_type(self, arg):
        """Return the type required for the specified argument.

        Parameters
        ----------
        arg : int or unicode
            Name or index of the argument whose type should be returned.

        """
        if istext(arg) or isbytes(arg):
            arg = self.arg_inds[arg]
        return self.lib._get_type(self.sig[1][arg][1])
Пример #5
0
    def __getitem__(self, n):
        if isinstance(n, int):
            arg = self.args[n]
        elif istext(n) or isbytes(n):
            n = self.find_arg(n)
            arg = self.args[n]
        else:
            raise ValueError("Index must be int or str.")

        if n in self.guessed:
            arg = arg[0]

        return self.lib._extract_val_(arg)
    def _send_output(self, message_body=None):
        """Send the currently buffered request and clear the buffer.

        Appends an extra \\r\\n to the buffer.
        A message_body may be specified, to be appended to the request.
        """
        self._buffer.extend((bytes(b""), bytes(b"")))
        msg = bytes(b"\r\n").join(self._buffer)
        del self._buffer[:]
        # If msg and message_body are sent in a single send() call,
        # it will avoid performance problems caused by the interaction
        # between delayed ack and the Nagle algorithm.
        if isbytes(message_body):
            msg += message_body
            message_body = None
        self.send(msg)
        if message_body is not None:
            # message_body was not a string (i.e. it is a file), and
            # we must run the risk of Nagle.
            self.send(message_body)
Пример #7
0
    def __init__(self, lib, headers, prefix=None, lock_calls=False,
                 convention='cdll', backend='ctypes', **kwargs):
        # name everything using underscores to avoid name collisions with
        # library

        # Build or store the parser from the header files.
        if isinstance(headers, list):
            self._headers_ = self._build_parser(headers, kwargs)
        elif isinstance(headers, CParser):
            self._headers_ = headers
        else:
            msg = 'Expected a CParser instance or list for headers, not {}'
            raise ValueError(msg.format(type(headers)))
        self._defs_ = self._headers_.defs

        # Create or store the internal representation of the library.
        if istext(lib) or isbytes(lib):
            self._lib_ = self._link_library(lib, convention)
        else:
            self._lib_ = lib

        # Store the list of prefix.
        if prefix is None:
            self._prefix_ = []
        elif isinstance(prefix, list):
            self._prefix_ = prefix
        else:
            self._prefix_ = [prefix]

        self._lock_calls_ = lock_calls
        if lock_calls:
            self._lock_ = RLock()

        self._objs_ = {}
        for k in ['values', 'functions', 'types', 'structs', 'unions',
                  'enums']:
            self._objs_[k] = {}
        self._all_objs_ = {}
        self._structs_ = {}
        self._unions_ = {}
Пример #8
0
 def __ge__(self, other):
     if not isbytes(other):
         raise TypeError(self.unorderable_err.format(type(other)))
     return super(newbytes, self).__ge__(other)
Пример #9
0
 def test_isbytes(self):
     self.assertTrue(isbytes(self.b))
     self.assertTrue(isbytes(self.b2))
     self.assertFalse(isbytes(self.s))
     self.assertFalse(isbytes(self.s2))
Пример #10
0
 def __gt__(self, other):
     if not isbytes(other):
         raise TypeError(self.unorderable_err.format(type(other)))
     return super(newbytes, self).__gt__(other)
Пример #11
0
 def test_isbytes(self):
     self.assertTrue(isbytes(self.b))
     self.assertTrue(isbytes(self.b2))
     self.assertFalse(isbytes(self.s))
     self.assertFalse(isbytes(self.s2))
Пример #12
0
 def fix(str_in):
     if isbytes(str_in):
         str_in = bytes_to_native_str(str_in)
     return str_in