Debian Codegraph @

Modules/_testcapi/hash.c

raw
1 #include "parts.h"
2 #include "util.h"
3
4 static PyObject *
5 hash_getfuncdef(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args))
6 {
7 // bind PyHash_GetFuncDef()
8 PyHash_FuncDef *def = PyHash_GetFuncDef();
9
10 PyObject *types = PyImport_ImportModule("types");
11 if (types == NULL) {
12 return NULL;
13 }
14
15 PyObject *result = PyObject_CallMethod(types, "SimpleNamespace", NULL);
16 Py_DECREF(types);
17 if (result == NULL) {
18 return NULL;
19 }
20
21 // ignore PyHash_FuncDef.hash
22
23 PyObject *value = PyUnicode_FromString(def->name);
24 int res = PyObject_SetAttrString(result, "name", value);
25 Py_DECREF(value);
26 if (res < 0) {
27 return NULL;
28 }
29
30 value = PyLong_FromLong(def->hash_bits);
31 res = PyObject_SetAttrString(result, "hash_bits", value);
32 Py_DECREF(value);
33 if (res < 0) {
34 return NULL;
35 }
36
37 value = PyLong_FromLong(def->seed_bits);
38 res = PyObject_SetAttrString(result, "seed_bits", value);
39 Py_DECREF(value);
40 if (res < 0) {
41 return NULL;
42 }
43
44 return result;
45 }
46
47
48 static PyObject *
49 long_from_hash(Py_hash_t hash)
50 {
51 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(hash));
52 return PyLong_FromLongLong(hash);
53 }
54
55
56 static PyObject *
57 hash_pointer(PyObject *Py_UNUSED(module), PyObject *arg)
58 {
59 void *ptr = PyLong_AsVoidPtr(arg);
60 if (ptr == NULL && PyErr_Occurred()) {
61 return NULL;
62 }
63
64 Py_hash_t hash = Py_HashPointer(ptr);
65 return long_from_hash(hash);
66 }
67
68
69 static PyObject *
70 hash_buffer(PyObject *Py_UNUSED(module), PyObject *args)
71 {
72 char *ptr;
73 Py_ssize_t len;
74 if (!PyArg_ParseTuple(args, "y#", &ptr, &len)) {
75 return NULL;
76 }
77
78 Py_hash_t hash = Py_HashBuffer(ptr, len);
79 return long_from_hash(hash);
80 }
81
82
83 static PyObject *
84 object_generichash(PyObject *Py_UNUSED(module), PyObject *arg)
85 {
86 NULLABLE(arg);
87 Py_hash_t hash = PyObject_GenericHash(arg);
88 return long_from_hash(hash);
89 }
90
91
92 static PyMethodDef test_methods[] = {
93 {"hash_getfuncdef", hash_getfuncdef, METH_NOARGS},
94 {"hash_pointer", hash_pointer, METH_O},
95 {"hash_buffer", hash_buffer, METH_VARARGS},
96 {"object_generichash", object_generichash, METH_O},
97 {NULL},
98 };
99
100 int
101 _PyTestCapi_Init_Hash(PyObject *m)
102 {
103 return PyModule_AddFunctions(m, test_methods);
104 }