|
| 1 | +/* SPDX-License-Identifier: MIT */ |
| 2 | +/* Copyright © 2020 Max Bachmann */ |
| 3 | + |
| 4 | +#define PY_SSIZE_T_CLEAN |
| 5 | +#include <Python.h> |
| 6 | +#include <nonstd/string_view.hpp> |
| 7 | +#include <variant/variant.hpp> |
| 8 | + |
| 9 | +#if PY_VERSION_HEX < 0x030C0000 |
| 10 | +#define PY_BELOW_3_12 |
| 11 | +#endif |
| 12 | + |
| 13 | +bool valid_str(PyObject* str, const char* name) { |
| 14 | + if (!PyUnicode_Check(str)) { |
| 15 | + PyErr_Format(PyExc_TypeError, "%s must be a String or None", name); |
| 16 | + return false; |
| 17 | + } |
| 18 | + |
| 19 | + // PyUnicode_READY deprecated in Python 3.10 removed in Python 3.12 |
| 20 | +#ifdef PY_BELOW_3_12 |
| 21 | + if (PyUnicode_READY(str)) { |
| 22 | + return false; |
| 23 | + } |
| 24 | +#endif |
| 25 | + |
| 26 | +return true; |
| 27 | +} |
| 28 | + |
| 29 | +#define PY_INIT_MOD(name, doc, methods) \ |
| 30 | + static struct PyModuleDef moduledef = { \ |
| 31 | + PyModuleDef_HEAD_INIT, #name, doc, -1, methods, NULL, NULL, NULL, NULL}; \ |
| 32 | + PyMODINIT_FUNC PyInit_##name(void) { \ |
| 33 | + return PyModule_Create(&moduledef); \ |
| 34 | + } |
| 35 | + |
| 36 | +using python_string_view = mpark::variant< |
| 37 | + nonstd::basic_string_view<uint8_t>, |
| 38 | + nonstd::basic_string_view<uint16_t>, |
| 39 | + nonstd::basic_string_view<uint32_t> |
| 40 | +>; |
| 41 | + |
| 42 | +python_string_view decode_python_string(PyObject* py_str) { |
| 43 | + Py_ssize_t len = PyUnicode_GET_LENGTH(py_str); |
| 44 | + void* str = PyUnicode_DATA(py_str); |
| 45 | + |
| 46 | + int str_kind = PyUnicode_KIND(py_str); |
| 47 | + |
| 48 | + switch (str_kind) { |
| 49 | + case PyUnicode_1BYTE_KIND: |
| 50 | + return nonstd::basic_string_view<uint8_t>(static_cast<uint8_t*>(str), len); |
| 51 | + case PyUnicode_2BYTE_KIND: |
| 52 | + return nonstd::basic_string_view<uint16_t>(static_cast<uint16_t*>(str), len); |
| 53 | + default: |
| 54 | + return nonstd::basic_string_view<uint32_t>(static_cast<uint32_t*>(str), len); |
| 55 | + } |
| 56 | +} |
0 commit comments