Commits

Armin Rigo committed 4b884bd

hack hack hack

Comments (0)

Files changed (6)

c/_cffi_backend.c

     if (PyBytes_Check(init) && PyBytes_GET_SIZE(init) == 1) {
         return (unsigned char)(PyBytes_AS_STRING(init)[0]);
     }
-#if PY_MAJOR_VERSION >= 3
-/*  XXX?
-    if (PyLong_Check(init)) {
-        long value = PyLong_AsLong(init);
-        if (value >= 0 && value < 256) {
-            return (unsigned char)value;
-        }
-    }
-    */
-#endif
     if (CData_Check(init) &&
            (((CDataObject *)init)->c_type->ct_flags & CT_PRIMITIVE_CHAR) &&
            (((CDataObject *)init)->c_type->ct_size == sizeof(char))) {

cffi/backend_ctypes.py

 
 if sys.version_info < (3,):
     integer_types = (int, long)
-    bytes = str
     bytechr = chr
 else:
-    integer_types = (int,)
+    unicode = str
+    integer_types = int
     xrange = range
     bytechr = lambda num: bytes([num])
 
                         return x
                     if isinstance(x, CTypesPrimitive):    # <CData <char>>
                         return x._value
-                    if sys.version_info >= (3,) and isinstance(x, int):
-                        return x
                     raise TypeError("character expected, got %s" %
                                     type(x).__name__)
 
             if kind == 'charp' or kind == 'bytep':
                 def _to_string(self, maxlen):
                     if maxlen < 0:
-                        maxlen = sys.maxint
+                        maxlen = sys.maxsize
                     p = ctypes.cast(self._as_ctype_ptr,
                                     ctypes.POINTER(ctypes.c_char))
                     n = 0
                     if isinstance(init, integer_types):
                         len1 = init
                         init = None
+                    elif kind == 'char' and isinstance(init, bytes):
+                        len1 = len(init) + 1    # extra null
                     else:
-                        extra_null = (kind == 'char' and isinstance(init, bytes))
                         init = tuple(init)
-                        len1 = len(init) + extra_null
+                        len1 = len(init)
                     self._ctype = BItem._ctype * len1
                 self._blob = self._ctype()
                 self._own = True
 
             @staticmethod
             def _initialize(blob, init):
-                init = tuple(init)
+                if isinstance(init, bytes):
+                    init = [init[i:i+1] for i in range(len(init))]
+                else:
+                    init = tuple(init)
                 if len(init) > len(blob):
                     raise IndexError("too many initializers")
                 addr = ctypes.cast(blob, ctypes.c_void_p).value
                                     "only one supported (use a dict if needed)"
                                      % (len(init),))
             if not isinstance(init, dict):
-                if isinstance(init, (bytes, str)):
+                if isinstance(init, (bytes, unicode)):
                     raise TypeError("union initializer: got a str")
                 init = tuple(init)
                 if len(init) > len(fnames):
                 p = ctypes.cast(addr + offset, PTR)
                 BField._initialize(p.contents, value)
         is_union = CTypesStructOrUnion._kind == 'union'
-        name2fieldtype = dict(zip(fnames, list(zip(btypes, bitfields))))
+        name2fieldtype = dict(zip(fnames, zip(btypes, bitfields)))
         #
         for fname, BField, bitsize in fields:
             if hasattr(CTypesStructOrUnion, fname):
                 buf = bptr._blob
                 val = bptr._blob
             else:
-                buf = bptr.XXX
+                raise TypeError(bptr)
             class Hack(ctypes.Union):
                 _fields_ = [('stupid', type(val))]
             ptr = ctypes.cast(buf, ctypes.POINTER(Hack))
     def read_variable(self, BType, name):
         try:
             ctypes_obj = BType._ctype.in_dll(self.cdll, name)
-        except AttributeError, e:
+        except AttributeError as e:
             raise NotImplementedError(e)
         return BType._from_ctypes(ctypes_obj)
 

testing/backend_tests.py

 
 if sys.version_info >= (3,):
     unicode = str
+    long = int
 
 
 class BackendTests:
         assert int(p) == min
         p = ffi.cast(c_decl, max)
         assert int(p) == max
+        p = ffi.cast(c_decl, long(max))
+        assert int(p) == max
         q = ffi.cast(c_decl, min - 1)
         assert ffi.typeof(q) is ffi.typeof(p) and int(q) == max
-        if sys.version_info < (3,):
-            p = ffi.cast(c_decl, long(max))
-            assert int(p) == max
-            q = ffi.cast(c_decl, long(min - 1))
-            assert ffi.typeof(q) is ffi.typeof(p) and int(q) == max
+        q = ffi.cast(c_decl, long(min - 1))
+        assert ffi.typeof(q) is ffi.typeof(p) and int(q) == max
         assert q != p
         assert int(q) == int(p)
         assert hash(q) != hash(p)   # unlikely
         c_decl_ptr = '%s *' % c_decl
         py.test.raises(OverflowError, ffi.new, c_decl_ptr, min - 1)
         py.test.raises(OverflowError, ffi.new, c_decl_ptr, max + 1)
+        py.test.raises(OverflowError, ffi.new, c_decl_ptr, long(min - 1))
+        py.test.raises(OverflowError, ffi.new, c_decl_ptr, long(max + 1))
         assert ffi.new(c_decl_ptr, min)[0] == min
         assert ffi.new(c_decl_ptr, max)[0] == max
-        if sys.version_info < (3,):
-            py.test.raises(OverflowError, ffi.new, c_decl_ptr, long(min - 1))
-            py.test.raises(OverflowError, ffi.new, c_decl_ptr, long(max + 1))
-            assert ffi.new(c_decl_ptr, long(min))[0] == min
-            assert ffi.new(c_decl_ptr, long(max))[0] == max
+        assert ffi.new(c_decl_ptr, long(min))[0] == min
+        assert ffi.new(c_decl_ptr, long(max))[0] == max
 
     def test_new_unsupported_type(self):
         ffi = FFI(backend=self.Backend())
         assert ffi.new("char*")[0] == b'\x00'
         assert int(ffi.cast("char", 300)) == 300 - 256
         assert bool(ffi.cast("char", 0))
-        if sys.version_info < (3,):
-            py.test.raises(TypeError, ffi.new, "char*", 32)
-        else:
-            assert ffi.new("char*", 32)[0] == b' '
+        py.test.raises(TypeError, ffi.new, "char*", 32)
         py.test.raises(TypeError, ffi.new, "char*", u"x")
-        py.test.raises(TypeError, ffi.new, "char*", "foo")
+        py.test.raises(TypeError, ffi.new, "char*", b"foo")
         #
         p = ffi.new("char[]", [b'a', b'b', b'\x9c'])
         assert len(p) == 3
         x = ffi.new("char*", b"x")
         assert str(x) == repr(x)
         assert ffi.string(x) == b"x"
-        assert ffi.string(ffi.new("char*", b"\x00")) == ""
+        assert ffi.string(ffi.new("char*", b"\x00")) == b""
         py.test.raises(TypeError, ffi.new, "char*", unicode("foo"))
 
     def test_unicode_from_wchar_pointer(self):
 
     def test_string_from_char_array(self):
         ffi = FFI(backend=self.Backend())
-        p = ffi.new("char[]", "hello.")
-        p[5] = '!'
-        assert ffi.string(p) == "hello!"
-        p[6] = '?'
-        assert ffi.string(p) == "hello!?"
-        p[3] = '\x00'
-        assert ffi.string(p) == "hel"
-        assert ffi.string(p, 2) == "he"
-        py.test.raises(IndexError, "p[7] = 'X'")
+        p = ffi.new("char[]", b"hello.")
+        p[5] = b'!'
+        assert ffi.string(p) == b"hello!"
+        p[6] = b'?'
+        assert ffi.string(p) == b"hello!?"
+        p[3] = b'\x00'
+        assert ffi.string(p) == b"hel"
+        assert ffi.string(p, 2) == b"he"
+        py.test.raises(IndexError, "p[7] = b'X'")
         #
         a = ffi.new("char[]", b"hello\x00world")
         assert len(a) == 12
         p = ffi.new("wchar_t[]", u"hello.")
         p[5] = u'!'
         assert ffi.string(p) == u"hello!"
-        p[6] = unichr(1234)
+        p[6] = u'\u04d2'
         assert ffi.string(p) == u"hello!\u04d2"
         p[3] = u'\x00'
         assert ffi.string(p) == u"hel"
         ffi.cdef("struct foo { const char *name; };")
         t = ffi.new("const char[]", b"testing")
         s = ffi.new("struct foo*", [t])
-        assert type(s.name) is not str
-        assert ffi.string(s.name) == "testing"
+        assert type(s.name) not in (bytes, str, unicode)
+        assert ffi.string(s.name) == b"testing"
         py.test.raises(TypeError, "s.name = None")
         s.name = ffi.NULL
         assert s.name == ffi.NULL
             seen.append(ffi.string(argv[0]))
             seen.append(ffi.string(argv[1]))
         a = ffi.callback("void(*)(char *[])", cb)
-        a([ffi.new("char[]", "foobar"), ffi.new("char[]", "baz")])
-        assert seen == ["foobar", "baz"]
+        a([ffi.new("char[]", b"foobar"), ffi.new("char[]", b"baz")])
+        assert seen == [b"foobar", b"baz"]
 
     def test_cast_float(self):
         ffi = FFI(backend=self.Backend())

testing/test_function.py

             ffi.C.fflush(ffi.NULL)
         res = fd.getvalue()
         if sys.platform == 'win32':
-            NIL = "00000000"
+            NIL = b"00000000"
         elif sys.platform.startswith('linux'):
-            NIL = "(nil)"
+            NIL = b"(nil)"
         else:
-            NIL = "0x0"    # OS/X at least
-        assert res == bytes("hello with no arguments\n"
-                            "hello, world!\n"
-                            "hello, world2!\n"
-                            "hello int 42 long 84 long long 168\n"
-                            "hello " + NIL + "\n")
+            NIL = b"0x0"    # OS/X at least
+        assert res == (b"hello with no arguments\n"
+                       b"hello, world!\n"
+                       b"hello, world2!\n"
+                       b"hello int 42 long 84 long long 168\n"
+                       b"hello " + NIL + b"\n")
 
     def test_must_specify_type_of_vararg(self):
         ffi = FFI(backend=self.Backend())

testing/test_ownlib.py

         assert len(ownlib.my_array) == 7
         if self.Backend is CTypesBackend:
             py.test.skip("not supported by the ctypes backend")
-        ownlib.my_array = range(10, 17)
+        ownlib.my_array = list(range(10, 17))
         for i in range(7):
             assert ownlib.my_array[i] == 10 + i
-        ownlib.my_array = range(7)
+        ownlib.my_array = list(range(7))
         for i in range(7):
             assert ownlib.my_array[i] == i
 
         for i in range(7):
             assert ownlib.my_array[i] == i
         py.test.raises(TypeError, len, ownlib.my_array)
-        ownlib.my_array = range(10, 17)
+        ownlib.my_array = list(range(10, 17))
         for i in range(7):
             assert ownlib.my_array[i] == 10 + i
-        ownlib.my_array = range(7)
+        ownlib.my_array = list(range(7))
         for i in range(7):
             assert ownlib.my_array[i] == i

testing/test_verify.py

     ffi = FFI()
     lib = ffi.verify()
     if hasattr(lib, '_cffi_python_module'):
-        print 'verify got a PYTHON module'
+        print('verify got a PYTHON module')
     if hasattr(lib, '_cffi_generic_module'):
-        print 'verify got a GENERIC module'
+        print('verify got a GENERIC module')
     expected_generic = (cffi.verifier._FORCE_GENERIC_ENGINE or
                         '__pypy__' in sys.builtin_module_names)
     assert hasattr(lib, '_cffi_python_module') == (not expected_generic)