Author: Armin Rigo <[email protected]>
Branch: py3.6
Changeset: r97873:e7f5d75f3f87
Date: 2019-10-28 11:54 +0100
http://bitbucket.org/pypy/pypy/changeset/e7f5d75f3f87/
Log: Issue #2687
Implement pystrhex.h
diff --git a/pypy/module/cpyext/include/pystrhex.h
b/pypy/module/cpyext/include/pystrhex.h
new file mode 100644
--- /dev/null
+++ b/pypy/module/cpyext/include/pystrhex.h
@@ -0,0 +1,1 @@
+/* empty */
diff --git a/pypy/module/cpyext/moduledef.py b/pypy/module/cpyext/moduledef.py
--- a/pypy/module/cpyext/moduledef.py
+++ b/pypy/module/cpyext/moduledef.py
@@ -79,6 +79,7 @@
import pypy.module.cpyext.marshal
import pypy.module.cpyext.genobject
import pypy.module.cpyext.namespaceobject
+import pypy.module.cpyext.pystrhex
# now that all rffi_platform.Struct types are registered, configure them
api.configure_types()
diff --git a/pypy/module/cpyext/pystrhex.py b/pypy/module/cpyext/pystrhex.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/cpyext/pystrhex.py
@@ -0,0 +1,26 @@
+import sys
+from pypy.module.cpyext.api import cts
+from rpython.rlib.rstring import StringBuilder
+
[email protected]("PyObject * _Py_strhex(const char* argbuf, const Py_ssize_t arglen)")
+def _Py_strhex(space, argbuf, arglen):
+ s = strhex(argbuf, arglen)
+ return space.newutf8(s, len(s)) # contains ascii only
+
[email protected]("PyObject * _Py_strhex_bytes(const char* argbuf, const Py_ssize_t
arglen)")
+def _Py_strhex_bytes(space, argbuf, arglen):
+ s = strhex(argbuf, arglen)
+ return space.newbytes(s)
+
+hexdigits = "0123456789abcdef"
+
+def strhex(argbuf, arglen):
+ assert arglen >= 0
+ if arglen > sys.maxint / 2:
+ raise MemoryError
+ builder = StringBuilder(arglen * 2)
+ for i in range(arglen):
+ b = ord(argbuf[i])
+ builder.append(hexdigits[(b >> 4) & 0xf])
+ builder.append(hexdigits[b & 0xf])
+ return builder.build()
diff --git a/pypy/module/cpyext/test/test_pystrhex.py
b/pypy/module/cpyext/test/test_pystrhex.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/cpyext/test/test_pystrhex.py
@@ -0,0 +1,20 @@
+from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
+
+class AppTestPyStrHex(AppTestCpythonExtensionBase):
+ def test_simple(self):
+ module = self.import_extension('strhex', [
+ ("new", "METH_NOARGS",
+ """
+ static char a[] = { (char)255, 0, 65 };
+ PyObject *o1 = _Py_strhex(a, 3);
+ PyObject *o2 = _Py_strhex_bytes(a, 3);
+ return PyTuple_Pack(2, o1, o2);
+ """)],
+ prologue="""
+ #include <pystrhex.h>
+ """)
+ o1, o2 = module.new()
+ assert type(o1) is str
+ assert type(o2) is bytes
+ assert o1 == u"ff0041"
+ assert o2 == b"ff0041"
_______________________________________________
pypy-commit mailing list
[email protected]
https://mail.python.org/mailman/listinfo/pypy-commit