diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..ea4474cc8 --- /dev/null +++ b/.clang-format @@ -0,0 +1,40 @@ +--- +Language: Cpp +BasedOnStyle: Google +ColumnLimit: 79 +IndentWidth: 4 +StatementAttributeLikeMacros: +# Defined in Include/pyport.h +- Py_DEPRECATED +- _Py_HOT_FUNCTION +- Py_ALWAYS_INLINE +- Py_NO_INLINE +- Py_ALIGNED +- Py_GCC_ATTRIBUTE +- _Py_NO_RETURN +- _Py_FALLTHROUGH +StatementMacros: +- PyObject_HEAD +- PyObject_VAR_HEAD +- PyException_HEAD +- _PyTZINFO_HEAD +- _PyDateTime_TIMEHEAD +- _PyDateTime_DATETIMEHEAD +- _PyGenObject_HEAD +- Window_NoArgNoReturnFunction +- Window_NoArgTrueFalseFunction +- Window_NoArgNoReturnVoidFunction +- Window_NoArg2TupleReturnFunction +- Window_OneArgNoReturnVoidFunction +- Window_OneArgNoReturnFunction +- Window_TwoArgNoReturnFunction +TabWidth: 4 +UseTab: Never +WhitespaceSensitiveMacros: +- _Py_XSTRINGIFY +- Py_STRINGIFY +IndentExternBlock: NoIndent +AlwaysBreakAfterReturnType: All +BreakBeforeBraces: Linux +BinPackArguments: false +... diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e70f5d470..85a21b930 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,6 +2,8 @@ ci: autoupdate_schedule: quarterly + skip: + - clang-format repos: - repo: https://github.com/python-jsonschema/check-jsonschema.git @@ -29,15 +31,18 @@ repos: args: - --strict -- repo: https://github.com/PyCQA/flake8.git - rev: 7.2.0 +- repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.12.0 hooks: - - id: flake8 - alias: flake8-no-wps - name: flake8 WPS-excluded - additional_dependencies: - - flake8-pyi ~= 24.1.0 - - flake8-pytest-style ~= 1.7.2 + - id: ruff-check + args: ["--fix"] + exclude: >- + (?x) + ^ + tools/upgrade_pythoncapi\.py + $ + - id: ruff-format exclude: >- (?x) ^ @@ -108,7 +113,10 @@ repos: types: - file - rst - +- repo: https://github.com/cpp-linter/cpp-linter-hooks + rev: v0.8.0 + hooks: + - id: clang-format - repo: https://github.com/pre-commit/mirrors-mypy.git rev: v1.15.0 hooks: @@ -144,5 +152,4 @@ repos: - --cobertura-xml-report=.tox/.tmp/.mypy/python-3.11 - --html-report=.tox/.tmp/.mypy/python-3.11 pass_filenames: false - ... diff --git a/CHANGES/1123.contrib b/CHANGES/1123.contrib new file mode 100644 index 000000000..cf70c218b --- /dev/null +++ b/CHANGES/1123.contrib @@ -0,0 +1 @@ +Setup pre-commit hook for auto-formatting both Python and C code. diff --git a/Makefile b/Makefile index d98137831..29606109a 100644 --- a/Makefile +++ b/Makefile @@ -11,28 +11,9 @@ all: test pip install -r requirements/dev.txt @touch .install-deps - -isort-check: - @if ! isort --check $(SRC); then \ - echo "Import sort errors, run 'make fmt' to fix them!!!"; \ - isort --diff --check $(SRC); \ - false; \ - fi - -black-check: - @if ! isort --check $(SRC); then \ - echo "black errors, run 'make fmt' to fix them!!!"; \ - black -t py35 --diff --check $(SRC); \ - false; \ - fi - -lint: black-check isort-check +lint: python -Im pre_commit run --all-files --show-diff-on-failure -fmt: - black -t py35 $(SRC) - isort $(SRC) - .develop: .install-deps $(shell find multidict -type f) pip install -e . @touch .develop diff --git a/benchmarks/istr.py b/benchmarks/istr.py index 01d2ee9c1..a8110052c 100644 --- a/benchmarks/istr.py +++ b/benchmarks/istr.py @@ -48,7 +48,7 @@ def add_impl_option(cmd, args): runner = perf.Runner(add_cmdline_args=add_impl_option) parser = runner.argparser - parser.description = "Allows to measure performance of " "istr implementations" + parser.description = "Allows to measure performance of istr implementations" parser.add_argument( "--impl", choices=sorted(IMPLEMENTATIONS), diff --git a/docs/conf.py b/docs/conf.py index 6d03ec1c2..75ba2bcc0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -383,7 +383,7 @@ def _replace_missing_aiohttp_hdrs_reference( node: pending_xref, contnode: literal, ) -> "reference | None": - if (node.get('refdomain'), node.get('reftype')) != ("py", "mod"): + if (node.get("refdomain"), node.get("reftype")) != ("py", "mod"): return None ref_target = node.get("reftarget", "") @@ -401,7 +401,7 @@ def _replace_missing_aiohttp_hdrs_reference( def setup(app: Sphinx) -> dict[str, bool | str]: - app.connect('missing-reference', _replace_missing_aiohttp_hdrs_reference) + app.connect("missing-reference", _replace_missing_aiohttp_hdrs_reference) return { "version": "builtin", diff --git a/multidict/_multidict.c b/multidict/_multidict.c index 7a989eb83..8ca50491c 100644 --- a/multidict/_multidict.c +++ b/multidict/_multidict.c @@ -1,42 +1,42 @@ #include #include -#include "_multilib/pythoncapi_compat.h" - #include "_multilib/dict.h" #include "_multilib/hashtable.h" #include "_multilib/istr.h" #include "_multilib/iter.h" #include "_multilib/parser.h" +#include "_multilib/pythoncapi_compat.h" #include "_multilib/state.h" #include "_multilib/views.h" - #define MultiDict_CheckExact(state, obj) Py_IS_TYPE(obj, state->MultiDictType) -#define MultiDict_Check(state, obj) \ - (MultiDict_CheckExact(state, obj) \ - || PyObject_TypeCheck(obj, state->MultiDictType)) -#define CIMultiDict_CheckExact(state, obj) Py_IS_TYPE(obj, state->CIMultiDictType) -#define CIMultiDict_Check(state, obj) \ - (CIMultiDict_CheckExact(state, obj) \ - || PyObject_TypeCheck(obj, state->CIMultiDictType)) -#define AnyMultiDict_Check(state, obj) \ - (MultiDict_CheckExact(state, obj) \ - || CIMultiDict_CheckExact(state, obj) \ - || PyObject_TypeCheck(obj, state->MultiDictType)) -#define MultiDictProxy_CheckExact(state, obj) Py_IS_TYPE(obj, state->MultiDictProxyType) -#define MultiDictProxy_Check(state, obj) \ - (MultiDictProxy_CheckExact(state, obj) \ - || PyObject_TypeCheck(obj, state->MultiDictProxyType)) +#define MultiDict_Check(state, obj) \ + (MultiDict_CheckExact(state, obj) || \ + PyObject_TypeCheck(obj, state->MultiDictType)) +#define CIMultiDict_CheckExact(state, obj) \ + Py_IS_TYPE(obj, state->CIMultiDictType) +#define CIMultiDict_Check(state, obj) \ + (CIMultiDict_CheckExact(state, obj) || \ + PyObject_TypeCheck(obj, state->CIMultiDictType)) +#define AnyMultiDict_Check(state, obj) \ + (MultiDict_CheckExact(state, obj) || \ + CIMultiDict_CheckExact(state, obj) || \ + PyObject_TypeCheck(obj, state->MultiDictType)) +#define MultiDictProxy_CheckExact(state, obj) \ + Py_IS_TYPE(obj, state->MultiDictProxyType) +#define MultiDictProxy_Check(state, obj) \ + (MultiDictProxy_CheckExact(state, obj) || \ + PyObject_TypeCheck(obj, state->MultiDictProxyType)) #define CIMultiDictProxy_CheckExact(state, obj) \ Py_IS_TYPE(obj, state->CIMultiDictProxyType) -#define CIMultiDictProxy_Check(state, obj) \ - (CIMultiDictProxy_CheckExact(state, obj) \ - || PyObject_TypeCheck(obj, state->CIMultiDictProxyType)) -#define AnyMultiDictProxy_Check(state, obj) \ - (MultiDictProxy_CheckExact(state, obj) \ - || CIMultiDictProxy_CheckExact(state, obj) \ - || PyObject_TypeCheck(obj, state->MultiDictProxyType)) +#define CIMultiDictProxy_Check(state, obj) \ + (CIMultiDictProxy_CheckExact(state, obj) || \ + PyObject_TypeCheck(obj, state->CIMultiDictProxyType)) +#define AnyMultiDictProxy_Check(state, obj) \ + (MultiDictProxy_CheckExact(state, obj) || \ + CIMultiDictProxy_CheckExact(state, obj) || \ + PyObject_TypeCheck(obj, state->MultiDictProxyType)) /******************** Internal Methods ********************/ @@ -64,13 +64,12 @@ _multidict_getone(MultiDictObject *self, PyObject *key, PyObject *_default) } } - static inline int -_multidict_extend(MultiDictObject *self, PyObject *arg, - PyObject *kwds, const char *name, bool update) +_multidict_extend(MultiDictObject *self, PyObject *arg, PyObject *kwds, + const char *name, bool update) { mod_state *state = self->state; - PyObject *seq = NULL; + PyObject *seq = NULL; if (kwds && !PyArg_ValidateKeywordArguments(kwds)) { goto fail; @@ -78,12 +77,12 @@ _multidict_extend(MultiDictObject *self, PyObject *arg, if (arg != NULL) { if (AnyMultiDict_Check(state, arg)) { - MultiDictObject *other = (MultiDictObject*)arg; + MultiDictObject *other = (MultiDictObject *)arg; if (md_update_from_ht(self, other, update) < 0) { goto fail; } } else if (AnyMultiDictProxy_Check(state, arg)) { - MultiDictObject *other = ((MultiDictProxyObject*)arg)->md; + MultiDictObject *other = ((MultiDictProxyObject *)arg)->md; if (md_update_from_ht(self, other, update) < 0) { goto fail; } @@ -132,7 +131,6 @@ _multidict_extend(MultiDictObject *self, PyObject *arg, return -1; } - static inline Py_ssize_t _multidict_extend_parse_args(mod_state *state, PyObject *args, PyObject *kwds, const char *name, PyObject **parg) @@ -143,10 +141,11 @@ _multidict_extend_parse_args(mod_state *state, PyObject *args, PyObject *kwds, s = PyTuple_GET_SIZE(args); if (s > 1) { PyErr_Format( - PyExc_TypeError, - "%s takes from 1 to 2 positional arguments but %zd were given", - name, s + 1, NULL - ); + PyExc_TypeError, + "%s takes from 1 to 2 positional arguments but %zd were given", + name, + s + 1, + NULL); *parg = NULL; return -1; } @@ -160,12 +159,12 @@ _multidict_extend_parse_args(mod_state *state, PyObject *args, PyObject *kwds, size += PyList_GET_SIZE(*parg); } else if (PyDict_CheckExact(*parg)) { size += PyDict_GET_SIZE(*parg); - } else if (MultiDict_CheckExact(state, *parg) - || CIMultiDict_CheckExact(state, *parg)) { + } else if (MultiDict_CheckExact(state, *parg) || + CIMultiDict_CheckExact(state, *parg)) { MultiDictObject *md = (MultiDictObject *)*parg; size += md_len(md); - } else if (MultiDictProxy_CheckExact(state, *parg) - || CIMultiDictProxy_CheckExact(state, *parg)) { + } else if (MultiDictProxy_CheckExact(state, *parg) || + CIMultiDictProxy_CheckExact(state, *parg)) { MultiDictObject *md = ((MultiDictProxyObject *)*parg)->md; size += md_len(md); } else { @@ -193,18 +192,17 @@ _multidict_extend_parse_args(mod_state *state, PyObject *args, PyObject *kwds, return size; } - static inline int -_multidict_clone_fast(mod_state *state, MultiDictObject *self, - bool is_ci, PyObject *arg, PyObject *kwds) +_multidict_clone_fast(mod_state *state, MultiDictObject *self, bool is_ci, + PyObject *arg, PyObject *kwds) { int ret = 0; if (arg != NULL && kwds == NULL) { MultiDictObject *other = NULL; if (AnyMultiDict_Check(state, arg)) { - other = (MultiDictObject*)arg; + other = (MultiDictObject *)arg; } else if (AnyMultiDictProxy_Check(state, arg)) { - other = ((MultiDictProxyObject*)arg)->md; + other = ((MultiDictProxyObject *)arg)->md; } if (other != NULL && other->is_ci == is_ci) { if (md_clone_from_ht(self, other) < 0) { @@ -219,16 +217,15 @@ _multidict_clone_fast(mod_state *state, MultiDictObject *self, return ret; } - static inline PyObject * multidict_copy(MultiDictObject *self) { - PyObject * ret = PyType_GenericNew(Py_TYPE(self), NULL, NULL); + PyObject *ret = PyType_GenericNew(Py_TYPE(self), NULL, NULL); if (ret == NULL) { goto fail; } - MultiDictObject *new_md = (MultiDictObject*) ret; + MultiDictObject *new_md = (MultiDictObject *)ret; if (md_clone_from_ht(new_md, self) < 0) { goto fail; } @@ -239,29 +236,32 @@ multidict_copy(MultiDictObject *self) return NULL; } - static inline PyObject * _multidict_proxy_copy(MultiDictProxyObject *self, PyTypeObject *type) { return multidict_copy(self->md); } - /******************** Base Methods ********************/ static inline PyObject * multidict_getall(MultiDictObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { - PyObject *list = NULL, - *key = NULL, - *_default = NULL; - - if (parse2("getall", args, nargs, kwnames, 1, - "key", &key, "default", &_default) < 0) { + PyObject *list = NULL, *key = NULL, *_default = NULL; + + if (parse2("getall", + args, + nargs, + kwnames, + 1, + "key", + &key, + "default", + &_default) < 0) { return NULL; } - if (md_get_all(self, key, &list) <0) { + if (md_get_all(self, key, &list) < 0) { return NULL; } @@ -284,26 +284,37 @@ static inline PyObject * multidict_getone(MultiDictObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { - PyObject *key = NULL, - *_default = NULL; - - if (parse2("getone", args, nargs, kwnames, 1, - "key", &key, "default", &_default) < 0) { + PyObject *key = NULL, *_default = NULL; + + if (parse2("getone", + args, + nargs, + kwnames, + 1, + "key", + &key, + "default", + &_default) < 0) { return NULL; } return _multidict_getone(self, key, _default); } static inline PyObject * -multidict_get(MultiDictObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames) +multidict_get(MultiDictObject *self, PyObject *const *args, Py_ssize_t nargs, + PyObject *kwnames) { - PyObject *key = NULL, - *_default = NULL, - *ret; - - if (parse2("get", args, nargs, kwnames, 1, - "key", &key, "default", &_default) < 0) { + PyObject *key = NULL, *_default = NULL, *ret; + + if (parse2("get", + args, + nargs, + kwnames, + 1, + "key", + &key, + "default", + &_default) < 0) { return NULL; } if (_default == NULL) { @@ -335,10 +346,7 @@ multidict_values(MultiDictObject *self) static PyObject * multidict_reduce(MultiDictObject *self) { - PyObject *items = NULL, - *items_list = NULL, - *args = NULL, - *result = NULL; + PyObject *items = NULL, *items_list = NULL, *args = NULL, *result = NULL; items = multidict_itemsview_new(self); if (items == NULL) { @@ -374,8 +382,8 @@ multidict_repr(MultiDictObject *self) if (tmp > 0) { return PyUnicode_FromString("..."); } - PyObject *name = PyObject_GetAttr((PyObject *)Py_TYPE(self), - self->state->str_name); + PyObject *name = + PyObject_GetAttr((PyObject *)Py_TYPE(self), self->state->str_name); if (name == NULL) { Py_ReprLeave((PyObject *)self); return NULL; @@ -439,9 +447,9 @@ multidict_tp_richcompare(MultiDictObject *self, PyObject *other, int op) mod_state *state = self->state; if (AnyMultiDict_Check(state, other)) { - cmp = md_eq(self, (MultiDictObject*)other); + cmp = md_eq(self, (MultiDictObject *)other); } else if (AnyMultiDictProxy_Check(state, other)) { - cmp = md_eq(self, ((MultiDictProxyObject*)other)->md); + cmp = md_eq(self, ((MultiDictProxyObject *)other)->md); } else { bool fits = false; fits = PyDict_Check(other); @@ -458,7 +466,7 @@ multidict_tp_richcompare(MultiDictObject *self, PyObject *other, int op) if (fits) { cmp = md_eq_to_mapping(self, other); } else { - cmp = 0; // e.g., multidict is not equal to a list + cmp = 0; // e.g., multidict is not equal to a list } } if (cmp < 0) { @@ -475,10 +483,10 @@ multidict_tp_dealloc(MultiDictObject *self) { PyObject_GC_UnTrack(self); Py_TRASHCAN_BEGIN(self, multidict_tp_dealloc) - PyObject_ClearWeakRefs((PyObject *)self); + PyObject_ClearWeakRefs((PyObject *)self); md_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); - Py_TRASHCAN_END // there should be no code after this + Py_TRASHCAN_END // there should be no code after this } static int @@ -495,22 +503,23 @@ multidict_tp_clear(MultiDictObject *self) } PyDoc_STRVAR(multidict_getall_doc, -"Return a list of all values matching the key."); + "Return a list of all values matching the key."); -PyDoc_STRVAR(multidict_getone_doc, -"Get first value matching the key."); +PyDoc_STRVAR(multidict_getone_doc, "Get first value matching the key."); -PyDoc_STRVAR(multidict_get_doc, -"Get first value matching the key.\n\nThe method is alias for .getone()."); +PyDoc_STRVAR( + multidict_get_doc, + "Get first value matching the key.\n\nThe method is alias for .getone()."); PyDoc_STRVAR(multidict_keys_doc, -"Return a new view of the dictionary's keys."); + "Return a new view of the dictionary's keys."); -PyDoc_STRVAR(multidict_items_doc, -"Return a new view of the dictionary's items *(key, value) pairs)."); +PyDoc_STRVAR( + multidict_items_doc, + "Return a new view of the dictionary's items *(key, value) pairs)."); PyDoc_STRVAR(multidict_values_doc, -"Return a new view of the dictionary's values."); + "Return a new view of the dictionary's values."); /******************** MultiDict ********************/ @@ -519,8 +528,8 @@ multidict_tp_init(MultiDictObject *self, PyObject *args, PyObject *kwds) { mod_state *state = get_mod_state_by_def((PyObject *)self); PyObject *arg = NULL; - Py_ssize_t size = _multidict_extend_parse_args(state, args, - kwds, "MultiDict", &arg); + Py_ssize_t size = + _multidict_extend_parse_args(state, args, kwds, "MultiDict", &arg); if (size < 0) { goto fail; } @@ -546,14 +555,13 @@ multidict_tp_init(MultiDictObject *self, PyObject *args, PyObject *kwds) } static PyObject * -multidict_add(MultiDictObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames) +multidict_add(MultiDictObject *self, PyObject *const *args, Py_ssize_t nargs, + PyObject *kwnames) { - PyObject *key = NULL, - *val = NULL; + PyObject *key = NULL, *val = NULL; - if (parse2("add", args, nargs, kwnames, 2, - "key", &key, "value", &val) < 0) { + if (parse2("add", args, nargs, kwnames, 2, "key", &key, "value", &val) < + 0) { return NULL; } if (md_add(self, key, val) < 0) { @@ -567,8 +575,8 @@ static PyObject * multidict_extend(MultiDictObject *self, PyObject *args, PyObject *kwds) { PyObject *arg = NULL; - Py_ssize_t size = _multidict_extend_parse_args(self->state, args, - kwds, "extend", &arg); + Py_ssize_t size = + _multidict_extend_parse_args(self->state, args, kwds, "extend", &arg); if (size < 0) { goto fail; } @@ -601,11 +609,17 @@ static PyObject * multidict_setdefault(MultiDictObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { - PyObject *key = NULL, - *_default = NULL; - - if (parse2("setdefault", args, nargs, kwnames, 1, - "key", &key, "default", &_default) < 0) { + PyObject *key = NULL, *_default = NULL; + + if (parse2("setdefault", + args, + nargs, + kwnames, + 1, + "key", + &key, + "default", + &_default) < 0) { return NULL; } if (_default == NULL) { @@ -620,12 +634,17 @@ static PyObject * multidict_popone(MultiDictObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { - PyObject *key = NULL, - *_default = NULL, - *ret_val = NULL; - - if (parse2("popone", args, nargs, kwnames, 1, - "key", &key, "default", &_default) < 0) { + PyObject *key = NULL, *_default = NULL, *ret_val = NULL; + + if (parse2("popone", + args, + nargs, + kwnames, + 1, + "key", + &key, + "default", + &_default) < 0) { return NULL; } if (md_pop_one(self, key, &ret_val) < 0) { @@ -647,19 +666,20 @@ multidict_popone(MultiDictObject *self, PyObject *const *args, } static PyObject * -multidict_pop( - MultiDictObject *self, - PyObject *const *args, - Py_ssize_t nargs, - PyObject *kwnames -) +multidict_pop(MultiDictObject *self, PyObject *const *args, Py_ssize_t nargs, + PyObject *kwnames) { - PyObject *key = NULL, - *_default = NULL, - *ret_val = NULL; - - if (parse2("pop", args, nargs, kwnames, 1, - "key", &key, "default", &_default) < 0) { + PyObject *key = NULL, *_default = NULL, *ret_val = NULL; + + if (parse2("pop", + args, + nargs, + kwnames, + 1, + "key", + &key, + "default", + &_default) < 0) { return NULL; } if (md_pop_one(self, key, &ret_val) < 0) { @@ -684,12 +704,17 @@ static PyObject * multidict_popall(MultiDictObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { - PyObject *key = NULL, - *_default = NULL, - *ret_val = NULL; - - if (parse2("popall", args, nargs, kwnames, 1, - "key", &key, "default", &_default) < 0) { + PyObject *key = NULL, *_default = NULL, *ret_val = NULL; + + if (parse2("popall", + args, + nargs, + kwnames, + 1, + "key", + &key, + "default", + &_default) < 0) { return NULL; } if (md_pop_all(self, key, &ret_val) < 0) { @@ -720,8 +745,8 @@ static PyObject * multidict_update(MultiDictObject *self, PyObject *args, PyObject *kwds) { PyObject *arg = NULL; - Py_ssize_t size = _multidict_extend_parse_args(self->state, args, - kwds, "update", &arg); + Py_ssize_t size = + _multidict_extend_parse_args(self->state, args, kwds, "update", &arg); if (size < 0) { goto fail; } @@ -740,185 +765,135 @@ multidict_update(MultiDictObject *self, PyObject *args, PyObject *kwds) } PyDoc_STRVAR(multidict_add_doc, -"Add the key and value, not overwriting any previous value."); + "Add the key and value, not overwriting any previous value."); -PyDoc_STRVAR(multidict_copy_doc, -"Return a copy of itself."); +PyDoc_STRVAR(multidict_copy_doc, "Return a copy of itself."); PyDoc_STRVAR(multdicit_method_extend_doc, -"Extend current MultiDict with more values.\n\ + "Extend current MultiDict with more values.\n\ This method must be used instead of update."); -PyDoc_STRVAR(multidict_clear_doc, -"Remove all items from MultiDict"); +PyDoc_STRVAR(multidict_clear_doc, "Remove all items from MultiDict"); -PyDoc_STRVAR(multidict_setdefault_doc, -"Return value for key, set value to default if key is not present."); +PyDoc_STRVAR( + multidict_setdefault_doc, + "Return value for key, set value to default if key is not present."); -PyDoc_STRVAR(multidict_popone_doc, -"Remove the last occurrence of key and return the corresponding value.\n\n\ +PyDoc_STRVAR( + multidict_popone_doc, + "Remove the last occurrence of key and return the corresponding value.\n\n\ If key is not found, default is returned if given, otherwise KeyError is \ raised.\n"); -PyDoc_STRVAR(multidict_pop_doc, -"Remove the last occurrence of key and return the corresponding value.\n\n\ +PyDoc_STRVAR( + multidict_pop_doc, + "Remove the last occurrence of key and return the corresponding value.\n\n\ If key is not found, default is returned if given, otherwise KeyError is \ raised.\n"); -PyDoc_STRVAR(multidict_popall_doc, -"Remove all occurrences of key and return the list of corresponding values.\n\n\ +PyDoc_STRVAR( + multidict_popall_doc, + "Remove all occurrences of key and return the list of corresponding values.\n\n\ If key is not found, default is returned if given, otherwise KeyError is \ raised.\n"); PyDoc_STRVAR(multidict_popitem_doc, -"Remove and return an arbitrary (key, value) pair."); + "Remove and return an arbitrary (key, value) pair."); PyDoc_STRVAR(multidict_update_doc, -"Update the dictionary from *other*, overwriting existing keys."); + "Update the dictionary from *other*, overwriting existing keys."); -PyDoc_STRVAR(sizeof__doc__, -"D.__sizeof__() -> size of D in memory, in bytes"); +PyDoc_STRVAR(sizeof__doc__, "D.__sizeof__() -> size of D in memory, in bytes"); static PyObject * multidict_sizeof(MultiDictObject *self) { Py_ssize_t size = sizeof(MultiDictObject); - if (self->keys != &empty_htkeys) - size += htkeys_sizeof(self->keys); + if (self->keys != &empty_htkeys) size += htkeys_sizeof(self->keys); return PyLong_FromSsize_t(size); } - static PyMethodDef multidict_methods[] = { - { - "getall", - (PyCFunction)multidict_getall, - METH_FASTCALL | METH_KEYWORDS, - multidict_getall_doc - }, - { - "getone", - (PyCFunction)multidict_getone, - METH_FASTCALL | METH_KEYWORDS, - multidict_getone_doc - }, - { - "get", - (PyCFunction)multidict_get, - METH_FASTCALL | METH_KEYWORDS, - multidict_get_doc - }, - { - "keys", - (PyCFunction)multidict_keys, - METH_NOARGS, - multidict_keys_doc - }, - { - "items", - (PyCFunction)multidict_items, - METH_NOARGS, - multidict_items_doc - }, - { - "values", - (PyCFunction)multidict_values, - METH_NOARGS, - multidict_values_doc - }, - { - "add", - (PyCFunction)multidict_add, - METH_FASTCALL | METH_KEYWORDS, - multidict_add_doc - }, - { - "copy", - (PyCFunction)multidict_copy, - METH_NOARGS, - multidict_copy_doc - }, - { - "extend", - (PyCFunction)multidict_extend, - METH_VARARGS | METH_KEYWORDS, - multdicit_method_extend_doc - }, - { - "clear", - (PyCFunction)multidict_clear, - METH_NOARGS, - multidict_clear_doc - }, - { - "setdefault", - (PyCFunction)multidict_setdefault, - METH_FASTCALL | METH_KEYWORDS, - multidict_setdefault_doc - }, - { - "popone", - (PyCFunction)multidict_popone, - METH_FASTCALL | METH_KEYWORDS, - multidict_popone_doc - }, - { - "pop", - (PyCFunction)multidict_pop, - METH_FASTCALL | METH_KEYWORDS, - multidict_pop_doc - }, - { - "popall", - (PyCFunction)multidict_popall, - METH_FASTCALL | METH_KEYWORDS, - multidict_popall_doc - }, - { - "popitem", - (PyCFunction)multidict_popitem, - METH_NOARGS, - multidict_popitem_doc - }, - { - "update", - (PyCFunction)multidict_update, - METH_VARARGS | METH_KEYWORDS, - multidict_update_doc - }, + {"getall", + (PyCFunction)multidict_getall, + METH_FASTCALL | METH_KEYWORDS, + multidict_getall_doc}, + {"getone", + (PyCFunction)multidict_getone, + METH_FASTCALL | METH_KEYWORDS, + multidict_getone_doc}, + {"get", + (PyCFunction)multidict_get, + METH_FASTCALL | METH_KEYWORDS, + multidict_get_doc}, + {"keys", (PyCFunction)multidict_keys, METH_NOARGS, multidict_keys_doc}, + {"items", (PyCFunction)multidict_items, METH_NOARGS, multidict_items_doc}, + {"values", + (PyCFunction)multidict_values, + METH_NOARGS, + multidict_values_doc}, + {"add", + (PyCFunction)multidict_add, + METH_FASTCALL | METH_KEYWORDS, + multidict_add_doc}, + {"copy", (PyCFunction)multidict_copy, METH_NOARGS, multidict_copy_doc}, + {"extend", + (PyCFunction)multidict_extend, + METH_VARARGS | METH_KEYWORDS, + multdicit_method_extend_doc}, + {"clear", (PyCFunction)multidict_clear, METH_NOARGS, multidict_clear_doc}, + {"setdefault", + (PyCFunction)multidict_setdefault, + METH_FASTCALL | METH_KEYWORDS, + multidict_setdefault_doc}, + {"popone", + (PyCFunction)multidict_popone, + METH_FASTCALL | METH_KEYWORDS, + multidict_popone_doc}, + {"pop", + (PyCFunction)multidict_pop, + METH_FASTCALL | METH_KEYWORDS, + multidict_pop_doc}, + {"popall", + (PyCFunction)multidict_popall, + METH_FASTCALL | METH_KEYWORDS, + multidict_popall_doc}, + {"popitem", + (PyCFunction)multidict_popitem, + METH_NOARGS, + multidict_popitem_doc}, + {"update", + (PyCFunction)multidict_update, + METH_VARARGS | METH_KEYWORDS, + multidict_update_doc}, { "__reduce__", (PyCFunction)multidict_reduce, METH_NOARGS, NULL, }, - { - "__class_getitem__", - (PyCFunction)Py_GenericAlias, - METH_O | METH_CLASS, - NULL - }, + {"__class_getitem__", + (PyCFunction)Py_GenericAlias, + METH_O | METH_CLASS, + NULL}, { "__sizeof__", (PyCFunction)multidict_sizeof, METH_NOARGS, sizeof__doc__, }, - { - NULL, - NULL - } /* sentinel */ + {NULL, NULL} /* sentinel */ }; - -PyDoc_STRVAR(MultDict_doc, -"Dictionary with the support for duplicate keys."); +PyDoc_STRVAR(MultDict_doc, "Dictionary with the support for duplicate keys."); #ifndef MANAGED_WEAKREFS static PyMemberDef multidict_members[] = { - {"__weaklistoffset__", Py_T_PYSSIZET, - offsetof(MultiDictObject, weaklist), Py_READONLY}, - {NULL} /* Sentinel */ + {"__weaklistoffset__", + Py_T_PYSSIZET, + offsetof(MultiDictObject, weaklist), + Py_READONLY}, + {NULL} /* Sentinel */ }; #endif @@ -951,7 +926,7 @@ static PyType_Slot multidict_slots[] = { static PyType_Spec multidict_spec = { .name = "multidict._multidict.MultiDict", .basicsize = sizeof(MultiDictObject), - .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE + .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE #if PY_VERSION_HEX >= 0x030a00f0 | Py_TPFLAGS_IMMUTABLETYPE #endif @@ -962,7 +937,6 @@ static PyType_Spec multidict_spec = { .slots = multidict_slots, }; - /******************** CIMultiDict ********************/ static int @@ -970,8 +944,8 @@ cimultidict_tp_init(MultiDictObject *self, PyObject *args, PyObject *kwds) { mod_state *state = get_mod_state_by_def((PyObject *)self); PyObject *arg = NULL; - Py_ssize_t size = _multidict_extend_parse_args(state, args, kwds, - "CIMultiDict", &arg); + Py_ssize_t size = + _multidict_extend_parse_args(state, args, kwds, "CIMultiDict", &arg); if (size < 0) { goto fail; } @@ -996,9 +970,9 @@ cimultidict_tp_init(MultiDictObject *self, PyObject *args, PyObject *kwds) return -1; } - -PyDoc_STRVAR(CIMultDict_doc, -"Dictionary with the support for duplicate case-insensitive keys."); +PyDoc_STRVAR( + CIMultDict_doc, + "Dictionary with the support for duplicate case-insensitive keys."); static PyType_Slot cimultidict_slots[] = { {Py_tp_doc, (void *)CIMultDict_doc}, @@ -1024,44 +998,37 @@ multidict_proxy_tp_init(MultiDictProxyObject *self, PyObject *args, PyObject *kwds) { mod_state *state = get_mod_state_by_def((PyObject *)self); - PyObject *arg = NULL; - MultiDictObject *md = NULL; + PyObject *arg = NULL; + MultiDictObject *md = NULL; - if (!PyArg_UnpackTuple(args, "multidict._multidict.MultiDictProxy", - 0, 1, &arg)) - { + if (!PyArg_UnpackTuple( + args, "multidict._multidict.MultiDictProxy", 0, 1, &arg)) { return -1; } if (arg == NULL) { PyErr_Format( PyExc_TypeError, - "__init__() missing 1 required positional argument: 'arg'" - ); + "__init__() missing 1 required positional argument: 'arg'"); return -1; } if (kwds != NULL) { - PyErr_Format( - PyExc_TypeError, - "__init__() doesn't accept keyword arguments" - ); + PyErr_Format(PyExc_TypeError, + "__init__() doesn't accept keyword arguments"); return -1; } if (!AnyMultiDictProxy_Check(state, arg) && - !AnyMultiDict_Check(state, arg)) - { - PyErr_Format( - PyExc_TypeError, - "ctor requires MultiDict or MultiDictProxy instance, " - "not ", - Py_TYPE(arg)->tp_name - ); + !AnyMultiDict_Check(state, arg)) { + PyErr_Format(PyExc_TypeError, + "ctor requires MultiDict or MultiDictProxy instance, " + "not ", + Py_TYPE(arg)->tp_name); return -1; } if (AnyMultiDictProxy_Check(state, arg)) { - md = ((MultiDictProxyObject*)arg)->md; + md = ((MultiDictProxyObject *)arg)->md; } else { - md = (MultiDictObject*)arg; + md = (MultiDictObject *)arg; } Py_INCREF(md); self->md = md; @@ -1085,7 +1052,7 @@ multidict_proxy_getone(MultiDictProxyObject *self, PyObject *const *args, static PyObject * multidict_proxy_get(MultiDictProxyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames) + Py_ssize_t nargs, PyObject *kwnames) { return multidict_get(self->md, args, nargs, kwnames); } @@ -1118,9 +1085,7 @@ static PyObject * multidict_proxy_reduce(MultiDictProxyObject *self) { PyErr_Format( - PyExc_TypeError, - "can't pickle %s objects", Py_TYPE(self)->tp_name - ); + PyExc_TypeError, "can't pickle %s objects", Py_TYPE(self)->tp_name); return NULL; } @@ -1184,86 +1149,60 @@ multidict_proxy_tp_clear(MultiDictProxyObject *self) static PyObject * multidict_proxy_repr(MultiDictProxyObject *self) { - PyObject *name = PyObject_GetAttr((PyObject *)Py_TYPE(self), - self->md->state->str_name); - if (name == NULL) - return NULL; + PyObject *name = + PyObject_GetAttr((PyObject *)Py_TYPE(self), self->md->state->str_name); + if (name == NULL) return NULL; PyObject *ret = md_repr(self->md, name, true, true); Py_CLEAR(name); return ret; } - static PyMethodDef multidict_proxy_methods[] = { - { - "getall", - (PyCFunction)multidict_proxy_getall, - METH_FASTCALL | METH_KEYWORDS, - multidict_getall_doc - }, - { - "getone", - (PyCFunction)multidict_proxy_getone, - METH_FASTCALL | METH_KEYWORDS, - multidict_getone_doc - }, - { - "get", - (PyCFunction)multidict_proxy_get, - METH_FASTCALL | METH_KEYWORDS, - multidict_get_doc - }, - { - "keys", - (PyCFunction)multidict_proxy_keys, - METH_NOARGS, - multidict_keys_doc - }, - { - "items", - (PyCFunction)multidict_proxy_items, - METH_NOARGS, - multidict_items_doc - }, - { - "values", - (PyCFunction)multidict_proxy_values, - METH_NOARGS, - multidict_values_doc - }, - { - "copy", - (PyCFunction)multidict_proxy_copy, - METH_NOARGS, - multidict_copy_doc - }, - { - "__reduce__", - (PyCFunction)multidict_proxy_reduce, - METH_NOARGS, - NULL - }, - { - "__class_getitem__", - (PyCFunction)Py_GenericAlias, - METH_O | METH_CLASS, - NULL - }, - { - NULL, - NULL - } /* sentinel */ + {"getall", + (PyCFunction)multidict_proxy_getall, + METH_FASTCALL | METH_KEYWORDS, + multidict_getall_doc}, + {"getone", + (PyCFunction)multidict_proxy_getone, + METH_FASTCALL | METH_KEYWORDS, + multidict_getone_doc}, + {"get", + (PyCFunction)multidict_proxy_get, + METH_FASTCALL | METH_KEYWORDS, + multidict_get_doc}, + {"keys", + (PyCFunction)multidict_proxy_keys, + METH_NOARGS, + multidict_keys_doc}, + {"items", + (PyCFunction)multidict_proxy_items, + METH_NOARGS, + multidict_items_doc}, + {"values", + (PyCFunction)multidict_proxy_values, + METH_NOARGS, + multidict_values_doc}, + {"copy", + (PyCFunction)multidict_proxy_copy, + METH_NOARGS, + multidict_copy_doc}, + {"__reduce__", (PyCFunction)multidict_proxy_reduce, METH_NOARGS, NULL}, + {"__class_getitem__", + (PyCFunction)Py_GenericAlias, + METH_O | METH_CLASS, + NULL}, + {NULL, NULL} /* sentinel */ }; - -PyDoc_STRVAR(MultDictProxy_doc, -"Read-only proxy for MultiDict instance."); +PyDoc_STRVAR(MultDictProxy_doc, "Read-only proxy for MultiDict instance."); #ifndef MANAGED_WEAKREFS static PyMemberDef multidict_proxy_members[] = { - {"__weaklistoffset__", Py_T_PYSSIZET, - offsetof(MultiDictProxyObject, weaklist), Py_READONLY}, - {NULL} /* Sentinel */ + {"__weaklistoffset__", + Py_T_PYSSIZET, + offsetof(MultiDictProxyObject, weaklist), + Py_READONLY}, + {NULL} /* Sentinel */ }; #endif @@ -1295,7 +1234,7 @@ static PyType_Slot multidict_proxy_slots[] = { static PyType_Spec multidict_proxy_spec = { .name = "multidict._multidict.MultiDictProxy", .basicsize = sizeof(MultiDictProxyObject), - .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE + .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE #if PY_VERSION_HEX >= 0x030a00f0 | Py_TPFLAGS_IMMUTABLETYPE #endif @@ -1313,43 +1252,37 @@ cimultidict_proxy_tp_init(MultiDictProxyObject *self, PyObject *args, PyObject *kwds) { mod_state *state = get_mod_state_by_def((PyObject *)self); - PyObject *arg = NULL; - MultiDictObject *md = NULL; + PyObject *arg = NULL; + MultiDictObject *md = NULL; - if (!PyArg_UnpackTuple(args, "multidict._multidict.CIMultiDictProxy", - 1, 1, &arg)) - { + if (!PyArg_UnpackTuple( + args, "multidict._multidict.CIMultiDictProxy", 1, 1, &arg)) { return -1; } if (arg == NULL) { PyErr_Format( PyExc_TypeError, - "__init__() missing 1 required positional argument: 'arg'" - ); + "__init__() missing 1 required positional argument: 'arg'"); return -1; } if (kwds != NULL) { - PyErr_Format( - PyExc_TypeError, - "__init__() doesn't accept keyword arguments" - ); + PyErr_Format(PyExc_TypeError, + "__init__() doesn't accept keyword arguments"); return -1; } - if (!CIMultiDictProxy_Check(state, arg) - && !CIMultiDict_Check(state, arg)) { - PyErr_Format( - PyExc_TypeError, - "ctor requires CIMultiDict or CIMultiDictProxy instance, " - "not ", - Py_TYPE(arg)->tp_name - ); + if (!CIMultiDictProxy_Check(state, arg) && + !CIMultiDict_Check(state, arg)) { + PyErr_Format(PyExc_TypeError, + "ctor requires CIMultiDict or CIMultiDictProxy instance, " + "not ", + Py_TYPE(arg)->tp_name); return -1; } if (CIMultiDictProxy_Check(state, arg)) { - md = ((MultiDictProxyObject*)arg)->md; + md = ((MultiDictProxyObject *)arg)->md; } else { - md = (MultiDictObject*)arg; + md = (MultiDictObject *)arg; } Py_INCREF(md); self->md = md; @@ -1363,24 +1296,16 @@ cimultidict_proxy_copy(MultiDictProxyObject *self) return _multidict_proxy_copy(self, self->md->state->CIMultiDictType); } +PyDoc_STRVAR(CIMultDictProxy_doc, "Read-only proxy for CIMultiDict instance."); -PyDoc_STRVAR(CIMultDictProxy_doc, -"Read-only proxy for CIMultiDict instance."); - -PyDoc_STRVAR(cimultidict_proxy_copy_doc, -"Return copy of itself"); +PyDoc_STRVAR(cimultidict_proxy_copy_doc, "Return copy of itself"); static PyMethodDef cimultidict_proxy_methods[] = { - { - "copy", - (PyCFunction)cimultidict_proxy_copy, - METH_NOARGS, - cimultidict_proxy_copy_doc - }, - { - NULL, - NULL - } /* sentinel */ + {"copy", + (PyCFunction)cimultidict_proxy_copy, + METH_NOARGS, + cimultidict_proxy_copy_doc}, + {NULL, NULL} /* sentinel */ }; static PyType_Slot cimultidict_proxy_slots[] = { @@ -1407,11 +1332,11 @@ static PyObject * getversion(PyObject *self, PyObject *arg) { mod_state *state = get_mod_state(self); - MultiDictObject* md; + MultiDictObject *md; if (AnyMultiDict_Check(state, arg)) { - md = (MultiDictObject*)arg; + md = (MultiDictObject *)arg; } else if (AnyMultiDictProxy_Check(state, arg)) { - md = ((MultiDictProxyObject*)arg)->md; + md = ((MultiDictProxyObject *)arg)->md; } else { PyErr_Format(PyExc_TypeError, "unexpected type"); return NULL; @@ -1483,10 +1408,9 @@ module_free(void *mod) static PyMethodDef module_methods[] = { {"getversion", (PyCFunction)getversion, METH_O}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; - static int module_exec(PyObject *mod) { @@ -1584,7 +1508,6 @@ module_exec(PyObject *mod) return -1; } - static struct PyModuleDef_Slot module_slots[] = { {Py_mod_exec, module_exec}, #if PY_VERSION_HEX >= 0x030c00f0 @@ -1596,7 +1519,6 @@ static struct PyModuleDef_Slot module_slots[] = { {0, NULL}, }; - static PyModuleDef multidict_module = { .m_base = PyModuleDef_HEAD_INIT, .m_name = "_multidict", diff --git a/multidict/_multidict_py.py b/multidict/_multidict_py.py index 9a9cdd447..f9fa25671 100644 --- a/multidict/_multidict_py.py +++ b/multidict/_multidict_py.py @@ -1098,8 +1098,7 @@ class MultiDictProxy(_CSMixin, MultiMapping[_V]): def __init__(self, arg: Union[MultiDict[_V], "MultiDictProxy[_V]"]): if not isinstance(arg, (MultiDict, MultiDictProxy)): raise TypeError( - "ctor requires MultiDict or MultiDictProxy instance" - f", not {type(arg)}" + f"ctor requires MultiDict or MultiDictProxy instance, not {type(arg)}" ) if isinstance(arg, MultiDictProxy): self._md = arg._md diff --git a/multidict/_multilib/dict.h b/multidict/_multilib/dict.h index 77bd7ccea..2f7c83be2 100644 --- a/multidict/_multilib/dict.h +++ b/multidict/_multilib/dict.h @@ -5,15 +5,14 @@ extern "C" { #endif -#include "pythoncapi_compat.h" #include "htkeys.h" +#include "pythoncapi_compat.h" #include "state.h" #if PY_VERSION_HEX >= 0x030c00f0 #define MANAGED_WEAKREFS #endif - typedef struct { PyObject_HEAD #ifndef MANAGED_WEAKREFS @@ -25,7 +24,7 @@ typedef struct { uint64_t version; bool is_ci; - htkeys_t * keys; + htkeys_t *keys; } MultiDictObject; typedef struct { @@ -36,7 +35,6 @@ typedef struct { MultiDictObject *md; } MultiDictProxyObject; - #ifdef __cplusplus } #endif diff --git a/multidict/_multilib/hashtable.h b/multidict/_multilib/hashtable.h index b091b632e..40daf9142 100644 --- a/multidict/_multilib/hashtable.h +++ b/multidict/_multilib/hashtable.h @@ -7,55 +7,54 @@ extern "C" { #endif -#include +#include #include #include -#include +#include #include "dict.h" +#include "htkeys.h" #include "istr.h" #include "state.h" -#include "htkeys.h" - typedef struct _md_pos { Py_ssize_t pos; uint64_t version; } md_pos_t; - typedef struct _md_finder { MultiDictObject *md; htkeysiter_t iter; uint64_t version; Py_hash_t hash; - PyObject *identity; // borrowed ref + PyObject *identity; // borrowed ref } md_finder_t; - /* -The multidict's implementation is close to Python's dict except for multiple keys. +The multidict's implementation is close to Python's dict except for multiple +keys. -It starts from the empty hashtable, which grows by a power of 2 starting from 8: 8, 16, -32, 64, 128, ... The amount of items is 2/3 of the hashtable size (1/3 of the table is -never allocated). +It starts from the empty hashtable, which grows by a power of 2 starting from +8: 8, 16, 32, 64, 128, ... The amount of items is 2/3 of the hashtable size +(1/3 of the table is never allocated). -The table is resized if needed, and bulk updates (extend(), update(), and constructor -calls) pre-allocate many items at once, reducing the amount of potential hashtable -resizes. +The table is resized if needed, and bulk updates (extend(), update(), and +constructor calls) pre-allocate many items at once, reducing the amount of +potential hashtable resizes. -Item deletion puts DKIX_DUMMY special index in the hashtable. In opposite to the -standard dict, DKIX_DUMMY is never replaced with an index of the new entry except by -hashtable indices rebuild. It allows to keep the insertion order for multiple equal -keys. The index table rebuild happens on the keys table size changeing and if the number -of DKIX_DUMMY slots grows to 1/4 of the total amount. +Item deletion puts DKIX_DUMMY special index in the hashtable. In opposite to +the standard dict, DKIX_DUMMY is never replaced with an index of the new entry +except by hashtable indices rebuild. It allows to keep the insertion order for +multiple equal keys. The index table rebuild happens on the keys table size +changeing and if the number of DKIX_DUMMY slots grows to 1/4 of the total +amount. The iteration for operations like getall() is a little tricky. The next index -calculation could return the already visited index before reaching the end. To eliminate -duplicates, the code marks already visited entries by entry->hash = -1. -1 hash is an -invalid hash value that could be used as a marker. After the iteration finishes, all -marked entries are restored. Double iteration over the indices still has O(1) amortized -time, it is ok. +calculation could return the already visited index before reaching the end. To +eliminate duplicates, the code marks already visited entries by entry->hash = +-1. -1 hash is an invalid hash value that could be used as a marker. After the +iteration finishes, all marked entries are restored. Double iteration over the +indices still has O(1) amortized time, it is ok. `.add()`, `val = md[key]`, `md[key] = val`, `md.setdefault()` all have O(1). `.getall()` / `.popall()` have O(N) where N is the amount of returned items. @@ -65,7 +64,6 @@ in the left and right arguments. `.copy()` and constuction from multidict is super fast. */ - /* GROWTH_RATE. Growth rate upon hitting maximum load. * Currently set to used*3. * This means that dicts double in size when growing without deletions, @@ -76,21 +74,23 @@ in the left and right arguments. * GROWTH_RATE was set to used*2 in version 3.3.0 * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0. */ -static inline Py_ssize_t GROWTH_RATE(MultiDictObject *md) { +static inline Py_ssize_t +GROWTH_RATE(MultiDictObject *md) +{ return md->used * 3; } - -static inline int _md_check_consistency(MultiDictObject *md, bool update); -static inline int _md_dump(MultiDictObject *md); +static inline int +_md_check_consistency(MultiDictObject *md, bool update); +static inline int +_md_dump(MultiDictObject *md); #ifndef NDEBUG -# define ASSERT_CONSISTENT(md, update) assert(_md_check_consistency(md, update)) +#define ASSERT_CONSISTENT(md, update) assert(_md_check_consistency(md, update)) #else -# define ASSERT_CONSISTENT(md, update) assert(1) +#define ASSERT_CONSISTENT(md, update) assert(1) #endif - static inline int _str_cmp(PyObject *s1, PyObject *s2) { @@ -98,22 +98,19 @@ _str_cmp(PyObject *s1, PyObject *s2) if (Py_IsTrue(ret)) { Py_DECREF(ret); return 1; - } - else if (ret == NULL) { + } else if (ret == NULL) { return -1; - } - else { + } else { Py_DECREF(ret); return 0; } } - static inline PyObject * _key_to_identity(mod_state *state, PyObject *key) { if (IStr_Check(state, key)) { - return Py_NewRef(((istrobject*)key)->canonical); + return Py_NewRef(((istrobject *)key)->canonical); } if (PyUnicode_CheckExact(key)) { return Py_NewRef(key); @@ -127,12 +124,11 @@ _key_to_identity(mod_state *state, PyObject *key) return NULL; } - static inline PyObject * _ci_key_to_identity(mod_state *state, PyObject *key) { if (IStr_Check(state, key)) { - return Py_NewRef(((istrobject*)key)->canonical); + return Py_NewRef(((istrobject *)key)->canonical); } if (PyUnicode_Check(key)) { PyObject *ret = PyObject_CallMethodNoArgs(key, state->str_lower); @@ -156,7 +152,6 @@ _ci_key_to_identity(mod_state *state, PyObject *key) return NULL; } - static inline PyObject * _arg_to_key(mod_state *state, PyObject *key, PyObject *identity) { @@ -169,7 +164,6 @@ _arg_to_key(mod_state *state, PyObject *key, PyObject *identity) return NULL; } - static inline PyObject * _ci_arg_to_key(mod_state *state, PyObject *key, PyObject *identity) { @@ -185,13 +179,12 @@ _ci_arg_to_key(mod_state *state, PyObject *key, PyObject *identity) return NULL; } - static inline int _md_resize(MultiDictObject *md, uint8_t log2_newsize, bool update) { htkeys_t *oldkeys, *newkeys; - if (log2_newsize >= SIZEOF_SIZE_T*8) { + if (log2_newsize >= SIZEOF_SIZE_T * 8) { PyErr_NoMemory(); return -1; } @@ -217,8 +210,7 @@ _md_resize(MultiDictObject *md, uint8_t log2_newsize, bool update) entry_t *ep = oldentries; for (Py_ssize_t i = 0; i < numentries; i++) { if (!update) { - while (ep->identity == NULL) - ep++; + while (ep->identity == NULL) ep++; } newentries[i] = *ep++; } @@ -240,21 +232,18 @@ _md_resize(MultiDictObject *md, uint8_t log2_newsize, bool update) return 0; } - static inline int _md_resize_for_insert(MultiDictObject *md) { return _md_resize(md, calculate_log2_keysize(GROWTH_RATE(md)), false); } - static inline int _md_resize_for_update(MultiDictObject *md) { return _md_resize(md, calculate_log2_keysize(GROWTH_RATE(md)), true); } - static inline int _md_reserve(MultiDictObject *md, Py_ssize_t extra_size, bool update) { @@ -265,14 +254,12 @@ _md_reserve(MultiDictObject *md, Py_ssize_t extra_size, bool update) return 0; } - static inline int md_reserve(MultiDictObject *md, Py_ssize_t extra_size) { return _md_reserve(md, extra_size, false); } - static inline int md_init(MultiDictObject *md, mod_state *state, bool is_ci, Py_ssize_t minused) { @@ -297,20 +284,17 @@ md_init(MultiDictObject *md, mod_state *state, bool is_ci, Py_ssize_t minused) */ if (minused > USABLE_FRACTION(max_presize)) { log2_newsize = log2_max_presize; - } - else { + } else { log2_newsize = estimate_log2_keysize(minused); } new_keys = htkeys_new(log2_newsize); - if (new_keys == NULL) - return -1; + if (new_keys == NULL) return -1; md->keys = new_keys; ASSERT_CONSISTENT(md, false); return 0; } - static inline int md_clone_from_ht(MultiDictObject *md, MultiDictObject *other) { @@ -341,32 +325,26 @@ md_clone_from_ht(MultiDictObject *md, MultiDictObject *other) return 0; } - static inline PyObject * md_calc_identity(MultiDictObject *md, PyObject *key) { - if (md->is_ci) - return _ci_key_to_identity(md->state, key); + if (md->is_ci) return _ci_key_to_identity(md->state, key); return _key_to_identity(md->state, key); } - static inline PyObject * md_calc_key(MultiDictObject *md, PyObject *key, PyObject *identity) { - if (md->is_ci) - return _ci_arg_to_key(md->state, key, identity); + if (md->is_ci) return _ci_arg_to_key(md->state, key, identity); return _arg_to_key(md->state, key, identity); } - static inline Py_ssize_t md_len(MultiDictObject *md) { return md->used; } - static inline PyObject * _md_ensure_key(MultiDictObject *md, entry_t *entry) { @@ -384,10 +362,10 @@ _md_ensure_key(MultiDictObject *md, entry_t *entry) return Py_NewRef(entry->key); } - static inline int -_md_add_with_hash_steal_refs(MultiDictObject *md, Py_hash_t hash, PyObject *identity, - PyObject *key, PyObject *value) +_md_add_with_hash_steal_refs(MultiDictObject *md, Py_hash_t hash, + PyObject *identity, PyObject *key, + PyObject *value) { htkeys_t *keys = md->keys; if (keys->usable <= 0 || keys == &empty_htkeys) { @@ -415,7 +393,6 @@ _md_add_with_hash_steal_refs(MultiDictObject *md, Py_hash_t hash, PyObject *iden return 0; } - static inline int _md_add_with_hash(MultiDictObject *md, Py_hash_t hash, PyObject *identity, PyObject *key, PyObject *value) @@ -426,10 +403,9 @@ _md_add_with_hash(MultiDictObject *md, Py_hash_t hash, PyObject *identity, return _md_add_with_hash_steal_refs(md, hash, identity, key, value); } - static inline int -_md_add_for_upd_steal_refs(MultiDictObject *md, Py_hash_t hash, PyObject *identity, - PyObject *key, PyObject *value) +_md_add_for_upd_steal_refs(MultiDictObject *md, Py_hash_t hash, + PyObject *identity, PyObject *key, PyObject *value) { htkeys_t *keys = md->keys; if (keys->usable <= 0 || keys == &empty_htkeys) { @@ -456,7 +432,6 @@ _md_add_for_upd_steal_refs(MultiDictObject *md, Py_hash_t hash, PyObject *identi return 0; } - static inline int _md_add_for_upd(MultiDictObject *md, Py_hash_t hash, PyObject *identity, PyObject *key, PyObject *value) @@ -467,7 +442,6 @@ _md_add_for_upd(MultiDictObject *md, Py_hash_t hash, PyObject *identity, return _md_add_for_upd_steal_refs(md, hash, identity, key, value); } - static inline int md_add(MultiDictObject *md, PyObject *key, PyObject *value) { @@ -488,7 +462,6 @@ md_add(MultiDictObject *md, PyObject *key, PyObject *value) return -1; } - static inline int _md_del_at(MultiDictObject *md, size_t slot, entry_t *entry) { @@ -502,7 +475,6 @@ _md_del_at(MultiDictObject *md, size_t slot, entry_t *entry) return 0; } - static inline int _md_del_at_for_upd(MultiDictObject *md, size_t slot, entry_t *entry) { @@ -518,7 +490,6 @@ _md_del_at_for_upd(MultiDictObject *md, size_t slot, entry_t *entry) return 0; } - static inline int md_del(MultiDictObject *md, PyObject *key) { @@ -539,7 +510,7 @@ md_del(MultiDictObject *md, PyObject *key) entry_t *entries = htkeys_entries(md->keys); - for (;iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { + for (; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { if (iter.index < 0) { continue; } @@ -575,14 +546,12 @@ md_del(MultiDictObject *md, PyObject *key) return -1; } - static inline uint64_t md_version(MultiDictObject *md) { return md->version; } - static inline void md_init_pos(MultiDictObject *md, md_pos_t *pos) { @@ -664,7 +633,6 @@ md_init_finder(MultiDictObject *md, PyObject *identity, md_finder_t *finder) return 0; } - static inline Py_ssize_t md_finder_slot(md_finder_t *finder) { @@ -672,7 +640,6 @@ md_finder_slot(md_finder_t *finder) return finder->iter.slot; } - static inline Py_ssize_t md_finder_index(md_finder_t *finder) { @@ -681,14 +648,13 @@ md_finder_index(md_finder_t *finder) return finder->iter.index; } - static inline int md_find_next(md_finder_t *finder, PyObject **pkey, PyObject **pvalue) { int ret = 0; assert(finder->iter.keys == finder->md->keys); - if (finder->iter.keys != finder->md->keys - || finder->version != finder->md->version) { + if (finder->iter.keys != finder->md->keys || + finder->version != finder->md->version) { ret = -1; PyErr_SetString(PyExc_RuntimeError, "MultiDict is changed during iteration"); @@ -697,7 +663,7 @@ md_find_next(md_finder_t *finder, PyObject **pkey, PyObject **pvalue) entry_t *entries = htkeys_entries(finder->md->keys); - for (;finder->iter.index != DKIX_EMPTY; htkeysiter_next(&finder->iter)) { + for (; finder->iter.index != DKIX_EMPTY; htkeysiter_next(&finder->iter)) { if (finder->iter.index < 0) { continue; } @@ -740,8 +706,8 @@ md_find_next(md_finder_t *finder, PyObject **pkey, PyObject **pvalue) return ret; } - -static inline void md_finder_cleanup(md_finder_t *finder) +static inline void +md_finder_cleanup(md_finder_t *finder) { if (finder->md == NULL) { return; @@ -749,7 +715,7 @@ static inline void md_finder_cleanup(md_finder_t *finder) htkeysiter_init(&finder->iter, finder->md->keys, finder->hash); entry_t *entries = htkeys_entries(finder->md->keys); - for (;finder->iter.index != DKIX_EMPTY; htkeysiter_next(&finder->iter)) { + for (; finder->iter.index != DKIX_EMPTY; htkeysiter_next(&finder->iter)) { if (finder->iter.index < 0) { continue; } @@ -762,7 +728,6 @@ static inline void md_finder_cleanup(md_finder_t *finder) finder->md = NULL; } - static inline int md_contains(MultiDictObject *md, PyObject *key, PyObject **pret) { @@ -784,7 +749,7 @@ md_contains(MultiDictObject *md, PyObject *key, PyObject **pret) htkeysiter_init(&iter, md->keys, hash); entry_t *entries = htkeys_entries(md->keys); - for(; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { + for (; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { if (iter.index < 0) { continue; } @@ -802,8 +767,7 @@ md_contains(MultiDictObject *md, PyObject *key, PyObject **pret) } } return 1; - } - else if (tmp < 0) { + } else if (tmp < 0) { goto fail; } } @@ -821,7 +785,6 @@ md_contains(MultiDictObject *md, PyObject *key, PyObject **pret) return -1; } - static inline int md_get_one(MultiDictObject *md, PyObject *key, PyObject **ret) { @@ -839,7 +802,7 @@ md_get_one(MultiDictObject *md, PyObject *key, PyObject **ret) htkeysiter_init(&iter, md->keys, hash); entry_t *entries = htkeys_entries(md->keys); - for(; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { + for (; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { if (iter.index < 0) { continue; } @@ -852,8 +815,7 @@ md_get_one(MultiDictObject *md, PyObject *key, PyObject **ret) Py_DECREF(identity); *ret = Py_NewRef(entry->value); return 0; - } - else if (tmp < 0) { + } else if (tmp < 0) { goto fail; } } @@ -865,7 +827,6 @@ md_get_one(MultiDictObject *md, PyObject *key, PyObject **ret) return -1; } - static inline int md_get_all(MultiDictObject *md, PyObject *key, PyObject **ret) { @@ -916,7 +877,6 @@ md_get_all(MultiDictObject *md, PyObject *key, PyObject **ret) return -1; } - static inline PyObject * md_set_default(MultiDictObject *md, PyObject *key, PyObject *value) { @@ -934,7 +894,7 @@ md_set_default(MultiDictObject *md, PyObject *key, PyObject *value) htkeysiter_init(&iter, md->keys, hash); entry_t *entries = htkeys_entries(md->keys); - for(; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { + for (; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { if (iter.index < 0) { continue; } @@ -948,8 +908,7 @@ md_set_default(MultiDictObject *md, PyObject *key, PyObject *value) Py_DECREF(identity); ASSERT_CONSISTENT(md, false); return Py_NewRef(entry->value); - } - else if (tmp < 0) { + } else if (tmp < 0) { goto fail; } } @@ -966,7 +925,6 @@ md_set_default(MultiDictObject *md, PyObject *key, PyObject *value) return NULL; } - static inline int md_pop_one(MultiDictObject *md, PyObject *key, PyObject **ret) { @@ -986,7 +944,7 @@ md_pop_one(MultiDictObject *md, PyObject *key, PyObject **ret) htkeysiter_init(&iter, md->keys, hash); entry_t *entries = htkeys_entries(md->keys); - for(; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { + for (; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { if (iter.index < 0) { continue; } @@ -1006,8 +964,7 @@ md_pop_one(MultiDictObject *md, PyObject *key, PyObject **ret) md->version = NEXT_VERSION(md->state); ASSERT_CONSISTENT(md, false); return 0; - } - else if (tmp < 0) { + } else if (tmp < 0) { goto fail; } } @@ -1020,9 +977,8 @@ md_pop_one(MultiDictObject *md, PyObject *key, PyObject **ret) return -1; } - static inline int -md_pop_all(MultiDictObject *md, PyObject *key, PyObject ** ret) +md_pop_all(MultiDictObject *md, PyObject *key, PyObject **ret) { PyObject *lst = NULL; @@ -1045,7 +1001,7 @@ md_pop_all(MultiDictObject *md, PyObject *key, PyObject ** ret) htkeysiter_init(&iter, md->keys, hash); entry_t *entries = htkeys_entries(md->keys); - for(; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { + for (; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { if (iter.index < 0) { continue; } @@ -1071,8 +1027,7 @@ md_pop_all(MultiDictObject *md, PyObject *key, PyObject ** ret) goto fail; } md->version = NEXT_VERSION(md->state); - } - else if (tmp < 0) { + } else if (tmp < 0) { goto fail; } } @@ -1087,7 +1042,6 @@ md_pop_all(MultiDictObject *md, PyObject *key, PyObject ** ret) return -1; } - static inline PyObject * md_pop_item(MultiDictObject *md) { @@ -1119,7 +1073,7 @@ md_pop_item(MultiDictObject *md) htkeysiter_t iter; htkeysiter_init(&iter, md->keys, entry->hash); - for(; iter.index != pos; htkeysiter_next(&iter)) { + for (; iter.index != pos; htkeysiter_next(&iter)) { } if (_md_del_at(md, iter.slot, entry) < 0) { return NULL; @@ -1129,9 +1083,8 @@ md_pop_item(MultiDictObject *md) return ret; } - static inline int -_md_replace(MultiDictObject *md, PyObject * key, PyObject *value, +_md_replace(MultiDictObject *md, PyObject *key, PyObject *value, PyObject *identity, Py_hash_t hash) { int found = 0; @@ -1168,8 +1121,7 @@ _md_replace(MultiDictObject *md, PyObject * key, PyObject *value, goto fail; } return 0; - } - else { + } else { md->version = NEXT_VERSION(md->state); return 0; } @@ -1179,7 +1131,7 @@ _md_replace(MultiDictObject *md, PyObject * key, PyObject *value, } static inline int -md_replace(MultiDictObject *md, PyObject * key, PyObject *value) +md_replace(MultiDictObject *md, PyObject *key, PyObject *value) { PyObject *identity = md_calc_identity(md, key); if (identity == NULL) { @@ -1200,7 +1152,6 @@ md_replace(MultiDictObject *md, PyObject * key, PyObject *value) return -1; } - static inline int _md_update(MultiDictObject *md, Py_hash_t hash, PyObject *identity, PyObject *key, PyObject *value) @@ -1210,7 +1161,7 @@ _md_update(MultiDictObject *md, Py_hash_t hash, PyObject *identity, entry_t *entries = htkeys_entries(md->keys); bool found = false; - for(; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { + for (; iter.index != DKIX_EMPTY; htkeysiter_next(&iter)) { if (iter.index == DKIX_DUMMY) { continue; } @@ -1239,11 +1190,9 @@ _md_update(MultiDictObject *md, Py_hash_t hash, PyObject *identity, goto fail; } } - } - else if (tmp < 0) { + } else if (tmp < 0) { goto fail; } - } if (!found) { @@ -1358,7 +1307,7 @@ md_update_from_dict(MultiDictObject *md, PyObject *kwds, bool update) assert(PyDict_CheckExact(kwds)); // PyDict_Next returns borrowed refs - while(PyDict_Next(kwds, &pos, &key, &value)) { + while (PyDict_Next(kwds, &pos, &key, &value)) { Py_INCREF(key); identity = md_calc_identity(md, key); if (identity == NULL) { @@ -1375,8 +1324,8 @@ md_update_from_dict(MultiDictObject *md, PyObject *kwds, bool update) Py_CLEAR(identity); Py_CLEAR(key); } else { - int tmp = _md_add_with_hash_steal_refs(md, hash, identity, - key, Py_NewRef(value)); + int tmp = _md_add_with_hash_steal_refs( + md, hash, identity, key, Py_NewRef(value)); if (tmp < 0) { Py_DECREF(value); goto fail; @@ -1393,7 +1342,8 @@ md_update_from_dict(MultiDictObject *md, PyObject *kwds, bool update) return -1; } -static inline void _err_not_sequence(Py_ssize_t i) +static inline void +_err_not_sequence(Py_ssize_t i) { PyErr_Format(PyExc_TypeError, "multidict cannot convert sequence element #%zd" @@ -1401,24 +1351,29 @@ static inline void _err_not_sequence(Py_ssize_t i) i); } -static inline void _err_bad_length(Py_ssize_t i, Py_ssize_t n) +static inline void +_err_bad_length(Py_ssize_t i, Py_ssize_t n) { PyErr_Format(PyExc_ValueError, "multidict update sequence element #%zd " "has length %zd; 2 is required", - i, n); + i, + n); } -static inline void _err_cannot_fetch(Py_ssize_t i, const char * name) +static inline void +_err_cannot_fetch(Py_ssize_t i, const char *name) { PyErr_Format(PyExc_ValueError, "multidict update sequence element #%zd's " - "%s could not be fetched", name, i); + "%s could not be fetched", + name, + i); } - -static int _md_parse_item(Py_ssize_t i, PyObject *item, - PyObject **pkey, PyObject **pvalue) +static int +_md_parse_item(Py_ssize_t i, PyObject *item, PyObject **pkey, + PyObject **pvalue) { Py_ssize_t n; @@ -1466,12 +1421,11 @@ static int _md_parse_item(Py_ssize_t i, PyObject *item, return -1; } - static inline int md_update_from_seq(MultiDictObject *md, PyObject *seq, bool update) { PyObject *it = NULL; - PyObject *item = NULL; // seq[i] + PyObject *item = NULL; // seq[i] PyObject *key = NULL; PyObject *value = NULL; @@ -1480,7 +1434,7 @@ md_update_from_seq(MultiDictObject *md, PyObject *seq, bool update) Py_ssize_t i; Py_ssize_t size = -1; - enum {LIST, TUPLE, ITER} kind; + enum { LIST, TUPLE, ITER } kind; if (PyList_CheckExact(seq)) { kind = LIST; @@ -1502,36 +1456,36 @@ md_update_from_seq(MultiDictObject *md, PyObject *seq, bool update) } } - for (i = 0; ; ++i) { // i - index into seq of current element + for (i = 0;; ++i) { // i - index into seq of current element switch (kind) { - case LIST: - if (i >= size) { - goto exit; - } - item = PyList_GET_ITEM(seq, i); - if (item == NULL) { - goto fail; - } - Py_INCREF(item); - break; - case TUPLE: - if (i >= size) { - goto exit; - } - item = PyTuple_GET_ITEM(seq, i); - if (item == NULL) { - goto fail; - } - Py_INCREF(item); - break; - case ITER: - item = PyIter_Next(it); - if (item == NULL) { - if (PyErr_Occurred()) { + case LIST: + if (i >= size) { + goto exit; + } + item = PyList_GET_ITEM(seq, i); + if (item == NULL) { goto fail; } - goto exit; - } + Py_INCREF(item); + break; + case TUPLE: + if (i >= size) { + goto exit; + } + item = PyTuple_GET_ITEM(seq, i); + if (item == NULL) { + goto fail; + } + Py_INCREF(item); + break; + case ITER: + item = PyIter_Next(it); + if (item == NULL) { + if (PyErr_Occurred()) { + goto fail; + } + goto exit; + } } if (_md_parse_item(i, item, &key, &value) < 0) { @@ -1556,8 +1510,8 @@ md_update_from_seq(MultiDictObject *md, PyObject *seq, bool update) Py_CLEAR(key); Py_CLEAR(value); } else { - if (_md_add_with_hash_steal_refs(md, hash, identity, - key, value) < 0) { + if (_md_add_with_hash_steal_refs(md, hash, identity, key, value) < + 0) { goto fail; } identity = NULL; @@ -1580,7 +1534,6 @@ md_update_from_seq(MultiDictObject *md, PyObject *seq, bool update) return -1; } - static inline int md_eq(MultiDictObject *md, MultiDictObject *other) { @@ -1598,8 +1551,7 @@ md_eq(MultiDictObject *md, MultiDictObject *other) entry_t *lft_entries = htkeys_entries(md->keys); entry_t *rht_entries = htkeys_entries(other->keys); for (;;) { - if (pos1 >= md->keys->nentries - || pos2 >= other->keys->nentries) { + if (pos1 >= md->keys->nentries || pos2 >= other->keys->nentries) { return 1; } entry_t *entry1 = lft_entries + pos1; @@ -1607,7 +1559,7 @@ md_eq(MultiDictObject *md, MultiDictObject *other) pos1++; continue; } - entry_t *entry2 = rht_entries +pos2; + entry_t *entry2 = rht_entries + pos2; if (entry2->identity == NULL) { pos2++; continue; @@ -1665,7 +1617,7 @@ md_eq_to_mapping(MultiDictObject *md, PyObject *other) md_pos_t pos; md_init_pos(md, &pos); - for(;;) { + for (;;) { int ret = md_next(md, &pos, NULL, &key, &avalue); if (ret < 0) { return -1; @@ -1697,10 +1649,8 @@ md_eq_to_mapping(MultiDictObject *md, PyObject *other) return 1; } - static inline PyObject * -md_repr(MultiDictObject *md, PyObject *name, - bool show_keys, bool show_values) +md_repr(MultiDictObject *md, PyObject *name, bool show_keys, bool show_values) { PyObject *key = NULL; PyObject *value = NULL; @@ -1709,21 +1659,24 @@ md_repr(MultiDictObject *md, PyObject *name, uint64_t version = md->version; PyUnicodeWriter *writer = PyUnicodeWriter_Create(1024); - if (writer == NULL) - return NULL; + if (writer == NULL) return NULL; - if (PyUnicodeWriter_WriteChar(writer, '<') <0) + if (PyUnicodeWriter_WriteChar(writer, '<') < 0) { goto fail; - if (PyUnicodeWriter_WriteStr(writer, name) <0) + } + if (PyUnicodeWriter_WriteStr(writer, name) < 0) { goto fail; - if (PyUnicodeWriter_WriteChar(writer, '(') <0) + } + if (PyUnicodeWriter_WriteChar(writer, '(') < 0) { goto fail; + } entry_t *entries = htkeys_entries(md->keys); for (Py_ssize_t pos = 0; pos < md->keys->nentries; ++pos) { if (version != md->version) { - PyErr_SetString(PyExc_RuntimeError, "MultiDict changed during iteration"); + PyErr_SetString(PyExc_RuntimeError, + "MultiDict changed during iteration"); return NULL; } entry_t *entry = entries + pos; @@ -1734,29 +1687,37 @@ md_repr(MultiDictObject *md, PyObject *name, value = Py_NewRef(entry->value); if (comma) { - if (PyUnicodeWriter_WriteChar(writer, ',') <0) + if (PyUnicodeWriter_WriteChar(writer, ',') < 0) { goto fail; - if (PyUnicodeWriter_WriteChar(writer, ' ') <0) + } + if (PyUnicodeWriter_WriteChar(writer, ' ') < 0) { goto fail; + } } if (show_keys) { - if (PyUnicodeWriter_WriteChar(writer, '\'') <0) + if (PyUnicodeWriter_WriteChar(writer, '\'') < 0) { goto fail; + } /* Don't need to convert key to istr, the text is the same*/ - if (PyUnicodeWriter_WriteStr(writer, key) <0) + if (PyUnicodeWriter_WriteStr(writer, key) < 0) { goto fail; - if (PyUnicodeWriter_WriteChar(writer, '\'') <0) + } + if (PyUnicodeWriter_WriteChar(writer, '\'') < 0) { goto fail; + } } if (show_keys && show_values) { - if (PyUnicodeWriter_WriteChar(writer, ':') <0) + if (PyUnicodeWriter_WriteChar(writer, ':') < 0) { goto fail; - if (PyUnicodeWriter_WriteChar(writer, ' ') <0) + } + if (PyUnicodeWriter_WriteChar(writer, ' ') < 0) { goto fail; + } } if (show_values) { - if (PyUnicodeWriter_WriteRepr(writer, value) <0) + if (PyUnicodeWriter_WriteRepr(writer, value) < 0) { goto fail; + } } comma = true; @@ -1764,10 +1725,12 @@ md_repr(MultiDictObject *md, PyObject *name, Py_CLEAR(value); } - if (PyUnicodeWriter_WriteChar(writer, ')') <0) + if (PyUnicodeWriter_WriteChar(writer, ')') < 0) { goto fail; - if (PyUnicodeWriter_WriteChar(writer, '>') <0) + } + if (PyUnicodeWriter_WriteChar(writer, '>') < 0) { goto fail; + } return PyUnicodeWriter_Finish(writer); fail: Py_CLEAR(key); @@ -1776,8 +1739,6 @@ md_repr(MultiDictObject *md, PyObject *name, return NULL; } - - /***********************************************************************/ static inline int @@ -1799,7 +1760,6 @@ md_traverse(MultiDictObject *md, visitproc visit, void *arg) return 0; } - static inline int md_clear(MultiDictObject *md) { @@ -1827,14 +1787,13 @@ md_clear(MultiDictObject *md) return 0; } - static inline int _md_check_consistency(MultiDictObject *md, bool update) { -// ASSERT_WORLD_STOPPED_OR_DICT_LOCKED(op); + // ASSERT_WORLD_STOPPED_OR_DICT_LOCKED(op); #define CHECK(expr) assert(expr) -// do { if (!(expr)) { assert(0 && Py_STRINGIFY(expr)); } } while (0) + // do { if (!(expr)) { assert(0 && Py_STRINGIFY(expr)); } } while (0) htkeys_t *keys = md->keys; CHECK(keys != NULL); @@ -1850,13 +1809,13 @@ _md_check_consistency(MultiDictObject *md, bool update) CHECK(0 <= nentries && nentries <= calc_usable); CHECK(usable + nentries <= calc_usable); - for (Py_ssize_t i=0; i < htkeys_nslots(keys); i++) { + for (Py_ssize_t i = 0; i < htkeys_nslots(keys); i++) { Py_ssize_t ix = htkeys_get_index(keys, i); CHECK(DKIX_DUMMY <= ix && ix <= calc_usable); } entry_t *entries = htkeys_entries(keys); - for (Py_ssize_t i=0; i < calc_usable; i++) { + for (Py_ssize_t i = 0; i < calc_usable; i++) { entry_t *entry = &entries[i]; PyObject *identity = entry->identity; @@ -1885,20 +1844,23 @@ _md_check_consistency(MultiDictObject *md, bool update) #undef CHECK } - static inline int _md_dump(MultiDictObject *md) { htkeys_t *keys = md->keys; printf("Dump %p [%ld from %ld usable %ld nentries %ld]\n", - (void *)md, md->used, htkeys_nslots(keys), keys->usable, keys->nentries); - for (Py_ssize_t i=0; i < htkeys_nslots(keys); i++) { + (void *)md, + md->used, + htkeys_nslots(keys), + keys->usable, + keys->nentries); + for (Py_ssize_t i = 0; i < htkeys_nslots(keys); i++) { Py_ssize_t ix = htkeys_get_index(keys, i); printf(" %ld -> %ld\n", i, ix); } printf(" --------\n"); entry_t *entries = htkeys_entries(keys); - for (Py_ssize_t i=0; i < keys->nentries; i++) { + for (Py_ssize_t i = 0; i < keys->nentries; i++) { entry_t *entry = &entries[i]; PyObject *identity = entry->identity; diff --git a/multidict/_multilib/htkeys.h b/multidict/_multilib/htkeys.h index e207e7c94..a13d5fb41 100644 --- a/multidict/_multilib/htkeys.h +++ b/multidict/_multilib/htkeys.h @@ -23,22 +23,19 @@ over pair_list for, e.g., md.get() or md.pop() is safe. */ typedef struct entry { - Py_hash_t hash; - PyObject *identity; - PyObject *key; - PyObject *value; + Py_hash_t hash; + PyObject *identity; + PyObject *key; + PyObject *value; } entry_t; - -#define DKIX_EMPTY (-1) /* empty (never used) slot */ -#define DKIX_DUMMY (-2) /* deleted slot */ - +#define DKIX_EMPTY (-1) /* empty (never used) slot */ +#define DKIX_DUMMY (-2) /* deleted slot */ #define HT_LOG_MINSIZE 3 #define HT_MINSIZE 8 #define HT_PERTURB_SHIFT 5 - typedef struct _htkeys { /* Size of the hash table (indices). It must be a power of 2. */ uint8_t log2_size; @@ -65,37 +62,42 @@ typedef struct _htkeys { - 8 bytes otherwise (int64_t*) Dynamically sized, SIZEOF_VOID_P is minimum. */ - char indices[]; /* char is required to avoid strict aliasing. */ + char indices[]; /* char is required to avoid strict aliasing. */ } htkeys_t; #if SIZEOF_VOID_P > 4 -static inline Py_ssize_t htkeys_nslots(const htkeys_t *keys) +static inline Py_ssize_t +htkeys_nslots(const htkeys_t *keys) { return ((int64_t)1) << keys->log2_size; } #else -static inline Py_ssize_t htkeys_nslots(const htkeys_t *keys) +static inline Py_ssize_t +htkeys_nslots(const htkeys_t *keys) { - return 1<< keys->log2_size; + return 1 << keys->log2_size; } #endif -static inline Py_ssize_t htkeys_mask(const htkeys_t *keys) +static inline Py_ssize_t +htkeys_mask(const htkeys_t *keys) { - return htkeys_nslots(keys)-1; + return htkeys_nslots(keys) - 1; } - -static inline entry_t* htkeys_entries(const htkeys_t *dk) { - int8_t *indices = (int8_t*)(dk->indices); +static inline entry_t * +htkeys_entries(const htkeys_t *dk) +{ + int8_t *indices = (int8_t *)(dk->indices); size_t index = (size_t)1 << dk->log2_index_bytes; - return (entry_t*)(&indices[index]); + return (entry_t *)(&indices[index]); } -#define LOAD_INDEX(keys, size, idx) ((const int##size##_t*)(keys->indices))[idx] -#define STORE_INDEX(keys, size, idx, value) ((int##size##_t*)(keys->indices))[idx] = (int##size##_t)value - +#define LOAD_INDEX(keys, size, idx) \ + ((const int##size##_t *)(keys->indices))[idx] +#define STORE_INDEX(keys, size, idx, value) \ + ((int##size##_t *)(keys->indices))[idx] = (int##size##_t)value /* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */ static inline Py_ssize_t @@ -106,8 +108,7 @@ htkeys_get_index(const htkeys_t *keys, Py_ssize_t i) if (log2size < 8) { ix = LOAD_INDEX(keys, 8, i); - } - else if (log2size < 16) { + } else if (log2size < 16) { ix = LOAD_INDEX(keys, 16, i); } #if SIZEOF_VOID_P > 4 @@ -133,8 +134,7 @@ htkeys_set_index(htkeys_t *keys, Py_ssize_t i, Py_ssize_t ix) if (log2size < 8) { assert(ix <= 0x7f); STORE_INDEX(keys, 8, i, ix); - } - else if (log2size < 16) { + } else if (log2size < 16) { assert(ix <= 0x7fff); STORE_INDEX(keys, 16, i, ix); } @@ -160,12 +160,12 @@ htkeys_set_index(htkeys_t *keys, Py_ssize_t i, Py_ssize_t ix) * USABLE_FRACTION should be quick to calculate. * Fractions around 1/2 to 2/3 seem to work well in practice. */ -static inline Py_ssize_t USABLE_FRACTION(Py_ssize_t n) +static inline Py_ssize_t +USABLE_FRACTION(Py_ssize_t n) { return (n << 1) / 3; } - // Return the index of the most significant 1 bit in 'x'. This is the smallest // integer k such that x < 2**k. Equivalent to floor(log2(x)) + 1 for x != 0. static inline int @@ -176,8 +176,7 @@ _ht_bit_length(unsigned long x) // __builtin_clzl() is available since GCC 3.4. // Undefined behavior for x == 0. return (int)sizeof(unsigned long) * 8 - __builtin_clzl(x); - } - else { + } else { return 0; } #elif defined(_MSC_VER) @@ -186,15 +185,13 @@ _ht_bit_length(unsigned long x) unsigned long msb; if (_BitScanReverse(&msb, x)) { return (int)msb + 1; - } - else { + } else { return 0; } #else - const int BIT_LENGTH_TABLE[32] = { - 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 - }; + const int BIT_LENGTH_TABLE[32] = {0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, + 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}; int msb = 0; while (x >= 32) { msb += 6; @@ -211,7 +208,7 @@ calculate_log2_keysize(Py_ssize_t minsize) { #if SIZEOF_LONG == SIZEOF_SIZE_T minsize = (minsize | HT_MINSIZE) - 1; - return _ht_bit_length(minsize | (HT_MINSIZE-1)); + return _ht_bit_length(minsize | (HT_MINSIZE - 1)); #elif defined(_MSC_VER) // On 64bit Windows, sizeof(long) == 4. minsize = (minsize | HT_MINSIZE) - 1; @@ -220,9 +217,8 @@ calculate_log2_keysize(Py_ssize_t minsize) return (uint8_t)(msb + 1); #else uint8_t log2_size; - for (log2_size = HT_LOG_MINSIZE; - (((Py_ssize_t)1) << log2_size) < minsize; - log2_size++) + for (log2_size = HT_LOG_MINSIZE; (((Py_ssize_t)1) << log2_size) < minsize; + log2_size++) ; return log2_size; #endif @@ -236,10 +232,9 @@ calculate_log2_keysize(Py_ssize_t minsize) static inline uint8_t estimate_log2_keysize(Py_ssize_t n) { - return calculate_log2_keysize((n*3 + 1) / 2); + return calculate_log2_keysize((n * 3 + 1) / 2); } - /* This immutable, empty PyDictKeysObject is used for PyDict_Clear() * (which cannot fail and thus can do no allocation). * @@ -247,36 +242,39 @@ estimate_log2_keysize(Py_ssize_t n) * for the rationale of using log2_index_bytes=3 instead of 0. */ static htkeys_t empty_htkeys = { - 0, /* log2_size */ - 3, /* log2_index_bytes */ - 0, /* usable (immutable) */ - 0, /* nentries */ - {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, - DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* indices */ + 0, /* log2_size */ + 3, /* log2_index_bytes */ + 0, /* usable (immutable) */ + 0, /* nentries */ + {DKIX_EMPTY, + DKIX_EMPTY, + DKIX_EMPTY, + DKIX_EMPTY, + DKIX_EMPTY, + DKIX_EMPTY, + DKIX_EMPTY, + DKIX_EMPTY}, /* indices */ }; - static inline Py_ssize_t htkeys_sizeof(htkeys_t *keys) { - Py_ssize_t usable = USABLE_FRACTION((size_t)1<log2_size); - return (sizeof(htkeys_t) - + ((size_t)1 << keys->log2_index_bytes) - + sizeof(entry_t) * usable); + Py_ssize_t usable = USABLE_FRACTION((size_t)1 << keys->log2_size); + return (sizeof(htkeys_t) + ((size_t)1 << keys->log2_index_bytes) + + sizeof(entry_t) * usable); } -static inline htkeys_t* +static inline htkeys_t * htkeys_new(uint8_t log2_size) { assert(log2_size >= HT_LOG_MINSIZE); - Py_ssize_t usable = USABLE_FRACTION(((size_t)1)< 4 @@ -291,9 +289,8 @@ htkeys_new(uint8_t log2_size) htkeys_t *keys = NULL; /* TODO: CPython uses freelist of key objects with unicode type and log2_size == PyDict_LOG_MINSIZE */ - keys = PyMem_Malloc(sizeof(htkeys_t) - + ((size_t)1 << log2_bytes) - + sizeof(entry_t) * usable); + keys = PyMem_Malloc(sizeof(htkeys_t) + ((size_t)1 << log2_bytes) + + sizeof(entry_t) * usable); if (keys == NULL) { PyErr_NoMemory(); return NULL; @@ -304,7 +301,8 @@ htkeys_new(uint8_t log2_size) keys->nentries = 0; keys->usable = usable; memset(&keys->indices[0], 0xff, ((size_t)1 << log2_bytes)); - memset(&keys->indices[(size_t)1 << log2_bytes], 0, sizeof(entry_t) * usable); + memset( + &keys->indices[(size_t)1 << log2_bytes], 0, sizeof(entry_t) * usable); return keys; } @@ -316,7 +314,6 @@ htkeys_free(htkeys_t *dk) PyMem_Free(dk); } - static inline Py_hash_t _unicode_hash(PyObject *o) { @@ -328,7 +325,6 @@ _unicode_hash(PyObject *o) return PyUnicode_Type.tp_hash(o); } - /* Internal routine used by ht_resize() to build a hashtable of entries. */ @@ -351,14 +347,13 @@ htkeys_build_indices(htkeys_t *keys, entry_t *ep, Py_ssize_t n, bool update) size_t i = hash & mask; for (size_t perturb = hash; htkeys_get_index(keys, i) != DKIX_EMPTY;) { perturb >>= HT_PERTURB_SHIFT; - i = mask & (i*5 + perturb + 1); + i = mask & (i * 5 + perturb + 1); } htkeys_set_index(keys, i, ix); } return 0; } - /* Internal function to find slot for an item from its hash when it is known that the key is not present in the dict. */ @@ -370,13 +365,12 @@ htkeys_find_empty_slot(htkeys_t *keys, Py_hash_t hash) Py_ssize_t ix = htkeys_get_index(keys, i); for (size_t perturb = hash; ix >= 0 || ix == DKIX_DUMMY;) { perturb >>= HT_PERTURB_SHIFT; - i = (i*5 + perturb + 1) & mask; + i = (i * 5 + perturb + 1) & mask; ix = htkeys_get_index(keys, i); } return i; } - /* Iterator over slots/indexes for given hash. N.B. The iterator MIGHT return the same slot multiple times, eiter consequently (1, 2, 2, 3) @@ -396,7 +390,6 @@ typedef struct _htkeysiter { Py_ssize_t index; } htkeysiter_t; - static inline void htkeysiter_init(htkeysiter_t *iter, htkeys_t *keys, Py_hash_t hash) { @@ -411,12 +404,10 @@ static inline void htkeysiter_next(htkeysiter_t *iter) { iter->perturb >>= HT_PERTURB_SHIFT; - iter->slot = (iter->slot*5 + iter->perturb + 1) & iter->mask; + iter->slot = (iter->slot * 5 + iter->perturb + 1) & iter->mask; iter->index = htkeys_get_index(iter->keys, iter->slot); } - - #ifdef __cplusplus } #endif diff --git a/multidict/_multilib/istr.h b/multidict/_multilib/istr.h index 156b0dc04..4805849f3 100644 --- a/multidict/_multilib/istr.h +++ b/multidict/_multilib/istr.h @@ -9,7 +9,7 @@ extern "C" { typedef struct { PyUnicodeObject str; - PyObject * canonical; + PyObject *canonical; mod_state *state; } istrobject; @@ -23,7 +23,7 @@ static inline void istr_dealloc(istrobject *self) { Py_XDECREF(self->canonical); - PyUnicode_Type.tp_dealloc((PyObject*)self); + PyUnicode_Type.tp_dealloc((PyObject *)self); } static inline PyObject * @@ -42,8 +42,8 @@ istr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) PyObject *canonical = NULL; PyObject *ret = NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOO:str", - kwlist, &x, &encoding, &errors)) { + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "|OOO:str", kwlist, &x, &encoding, &errors)) { return NULL; } if (x != NULL && IStr_Check(state, x)) { @@ -58,8 +58,8 @@ istr_new(PyTypeObject *type, PyObject *args, PyObject *kwds) if (!canonical) { goto fail; } - ((istrobject*)ret)->canonical = canonical; - ((istrobject*)ret)->state = state; + ((istrobject *)ret)->canonical = canonical; + ((istrobject *)ret)->state = state; return ret; fail: Py_XDECREF(ret); @@ -88,10 +88,9 @@ istr_reduce(PyObject *self) return result; } - static PyMethodDef istr_methods[] = { {"__reduce__", (PyCFunction)istr_reduce, METH_NOARGS, NULL}, - {NULL, NULL} /* sentinel */ + {NULL, NULL} /* sentinel */ }; static PyType_Slot istr_slots[] = { @@ -105,8 +104,7 @@ static PyType_Slot istr_slots[] = { static PyType_Spec istr_spec = { .name = "multidict._multidict.istr", .basicsize = sizeof(istrobject), - .flags = (Py_TPFLAGS_DEFAULT - | Py_TPFLAGS_BASETYPE + .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE #if PY_VERSION_HEX >= 0x030a00f0 | Py_TPFLAGS_IMMUTABLETYPE #endif @@ -114,7 +112,6 @@ static PyType_Spec istr_spec = { .slots = istr_slots, }; - static inline PyObject * IStr_New(mod_state *state, PyObject *str, PyObject *canonical) { @@ -129,8 +126,8 @@ IStr_New(mod_state *state, PyObject *str, PyObject *canonical) goto ret; } Py_INCREF(canonical); - ((istrobject*)res)->canonical = canonical; - ((istrobject*)res)->state = state; + ((istrobject *)res)->canonical = canonical; + ((istrobject *)res)->state = state; ret: Py_CLEAR(args); return res; diff --git a/multidict/_multilib/iter.h b/multidict/_multilib/iter.h index 89469e61b..10460bf27 100644 --- a/multidict/_multilib/iter.h +++ b/multidict/_multilib/iter.h @@ -27,8 +27,8 @@ _init_iter(MultidictIter *it, MultiDictObject *md) static inline PyObject * multidict_items_iter_new(MultiDictObject *md) { - MultidictIter *it = PyObject_GC_New( - MultidictIter, md->state->ItemsIterType); + MultidictIter *it = + PyObject_GC_New(MultidictIter, md->state->ItemsIterType); if (it == NULL) { return NULL; } @@ -42,8 +42,8 @@ multidict_items_iter_new(MultiDictObject *md) static inline PyObject * multidict_keys_iter_new(MultiDictObject *md) { - MultidictIter *it = PyObject_GC_New( - MultidictIter, md->state->KeysIterType); + MultidictIter *it = + PyObject_GC_New(MultidictIter, md->state->KeysIterType); if (it == NULL) { return NULL; } @@ -57,8 +57,8 @@ multidict_keys_iter_new(MultiDictObject *md) static inline PyObject * multidict_values_iter_new(MultiDictObject *md) { - MultidictIter *it = PyObject_GC_New( - MultidictIter, md->state->ValuesIterType); + MultidictIter *it = + PyObject_GC_New(MultidictIter, md->state->ValuesIterType); if (it == NULL) { return NULL; } @@ -76,8 +76,7 @@ multidict_items_iter_iternext(MultidictIter *self) PyObject *value = NULL; PyObject *ret = NULL; - int res = md_next(self->md, &self->current, - NULL, &key, &value); + int res = md_next(self->md, &self->current, NULL, &key, &value); if (res < 0) { return NULL; } @@ -103,8 +102,7 @@ multidict_values_iter_iternext(MultidictIter *self) { PyObject *value = NULL; - int res = md_next(self->md, &self->current, - NULL, NULL, &value); + int res = md_next(self->md, &self->current, NULL, NULL, &value); if (res < 0) { return NULL; } @@ -121,8 +119,7 @@ multidict_keys_iter_iternext(MultidictIter *self) { PyObject *key = NULL; - int res = md_next(self->md, &self->current, - NULL, &key, NULL); + int res = md_next(self->md, &self->current, NULL, &key, NULL); if (res < 0) { return NULL; } @@ -166,16 +163,11 @@ PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef multidict_iter_methods[] = { - { - "__length_hint__", - (PyCFunction)(void(*)(void))multidict_iter_len, - METH_NOARGS, - length_hint_doc - }, - { - NULL, - NULL - } /* sentinel */ + {"__length_hint__", + (PyCFunction)(void (*)(void))multidict_iter_len, + METH_NOARGS, + length_hint_doc}, + {NULL, NULL} /* sentinel */ }; /***********************************************************************/ @@ -222,7 +214,6 @@ static PyType_Spec multidict_values_iter_spec = { .slots = multidict_values_iter_slots, }; - static PyType_Slot multidict_keys_iter_slots[] = { {Py_tp_dealloc, multidict_iter_dealloc}, {Py_tp_methods, multidict_iter_methods}, @@ -247,7 +238,7 @@ static PyType_Spec multidict_keys_iter_spec = { static inline int multidict_iter_init(PyObject *module, mod_state *state) { - PyObject * tmp; + PyObject *tmp; tmp = PyType_FromModuleAndSpec(module, &multidict_items_iter_spec, NULL); if (tmp == NULL) { return -1; diff --git a/multidict/_multilib/parser.h b/multidict/_multilib/parser.h index 301c7885c..1ff3b33d3 100644 --- a/multidict/_multilib/parser.h +++ b/multidict/_multilib/parser.h @@ -5,23 +5,26 @@ extern "C" { #endif -static inline int raise_unexpected_kwarg(const char *fname, PyObject* argname) +static inline int +raise_unexpected_kwarg(const char *fname, PyObject *argname) { PyErr_Format(PyExc_TypeError, "%.150s() got an unexpected keyword argument '%.150U'", - fname, argname); + fname, + argname); return -1; } -static inline int raise_missing_posarg(const char *fname, const char* argname) +static inline int +raise_missing_posarg(const char *fname, const char *argname) { PyErr_Format(PyExc_TypeError, "%.150s() missing 1 required positional argument: '%.150s'", - fname, argname); + fname, + argname); return -1; } - /* Parse FASTCALL|METH_KEYWORDS arguments as two args, the first arg is mandatory and the second one is optional. If the second arg is not passed it remains NULL pointer. @@ -32,19 +35,13 @@ The parser accepts three forms: 3. all named keyword args. */ -static inline int parse2(const char* fname, - PyObject*const *args, - Py_ssize_t nargs, - PyObject *kwnames, - Py_ssize_t minargs, - const char* arg1name, - PyObject **arg1, - const char* arg2name, - PyObject **arg2 -) +static inline int +parse2(const char *fname, PyObject *const *args, Py_ssize_t nargs, + PyObject *kwnames, Py_ssize_t minargs, const char *arg1name, + PyObject **arg1, const char *arg2name, PyObject **arg2) { - assert(minargs>=1); - assert(minargs<=2); + assert(minargs >= 1); + assert(minargs <= 2); if (kwnames != NULL) { Py_ssize_t kwsize = PyTuple_Size(kwnames); @@ -71,7 +68,8 @@ static inline int parse2(const char* fname, } else { return raise_unexpected_kwarg(fname, argname); } - } else if (PyUnicode_CompareWithASCIIString(argname, arg2name) == 0) { + } else if (PyUnicode_CompareWithASCIIString(argname, arg2name) == + 0) { argname = PyTuple_GetItem(kwnames, 1); if (argname == NULL) { return -1; @@ -113,13 +111,15 @@ static inline int parse2(const char* fname, } } else { if (nargs < 1) { - PyErr_Format(PyExc_TypeError, - "%.150s() missing 1 required positional argument: '%s'", - fname, arg1name); + PyErr_Format( + PyExc_TypeError, + "%.150s() missing 1 required positional argument: '%s'", + fname, + arg1name); return -1; } if (nargs < minargs || nargs > 2) { - const char* txt; + const char *txt; if (minargs == 2) { txt = "from 1 to 2 positional arguments"; } else { @@ -127,7 +127,9 @@ static inline int parse2(const char* fname, } PyErr_Format(PyExc_TypeError, "%.150s() takes %s but %zd were given", - fname, txt, nargs); + fname, + txt, + nargs); return -1; } *arg1 = args[0]; diff --git a/multidict/_multilib/pythoncapi_compat.h b/multidict/_multilib/pythoncapi_compat.h index 4b179e493..1ab42c8fa 100644 --- a/multidict/_multilib/pythoncapi_compat.h +++ b/multidict/_multilib/pythoncapi_compat.h @@ -19,49 +19,48 @@ extern "C" { #endif #include -#include // offsetof() +#include // offsetof() // Python 3.11.0b4 added PyFrame_Back() to Python.h #if PY_VERSION_HEX < 0x030b00B4 && !defined(PYPY_VERSION) -# include "frameobject.h" // PyFrameObject, PyFrame_GetBack() +#include "frameobject.h" // PyFrameObject, PyFrame_GetBack() #endif #if PY_VERSION_HEX < 0x030C00A3 -# include // T_SHORT, READONLY +#include // T_SHORT, READONLY #endif - #ifndef _Py_CAST -# define _Py_CAST(type, expr) ((type)(expr)) +#define _Py_CAST(type, expr) ((type)(expr)) #endif // Static inline functions should use _Py_NULL rather than using directly NULL // to prevent C++ compiler warnings. On C23 and newer and on C++11 and newer, // _Py_NULL is defined as nullptr. #ifndef _Py_NULL -# if (defined (__STDC_VERSION__) && __STDC_VERSION__ > 201710L) \ - || (defined(__cplusplus) && __cplusplus >= 201103) -# define _Py_NULL nullptr -# else -# define _Py_NULL NULL -# endif +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ > 201710L) || \ + (defined(__cplusplus) && __cplusplus >= 201103) +#define _Py_NULL nullptr +#else +#define _Py_NULL NULL +#endif #endif // Cast argument to PyObject* type. #ifndef _PyObject_CAST -# define _PyObject_CAST(op) _Py_CAST(PyObject*, op) +#define _PyObject_CAST(op) _Py_CAST(PyObject *, op) #endif #ifndef Py_BUILD_ASSERT -# define Py_BUILD_ASSERT(cond) \ - do { \ - (void)sizeof(char [1 - 2 * !(cond)]); \ - } while(0) +#define Py_BUILD_ASSERT(cond) \ + do { \ + (void)sizeof(char[1 - 2 * !(cond)]); \ + } while (0) #endif - // bpo-42262 added Py_NewRef() to Python 3.10.0a3 #if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_NewRef) -static inline PyObject* _Py_NewRef(PyObject *obj) +static inline PyObject * +_Py_NewRef(PyObject *obj) { Py_INCREF(obj); return obj; @@ -69,10 +68,10 @@ static inline PyObject* _Py_NewRef(PyObject *obj) #define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj)) #endif - // bpo-42262 added Py_XNewRef() to Python 3.10.0a3 #if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_XNewRef) -static inline PyObject* _Py_XNewRef(PyObject *obj) +static inline PyObject * +_Py_XNewRef(PyObject *obj) { Py_XINCREF(obj); return obj; @@ -80,103 +79,106 @@ static inline PyObject* _Py_XNewRef(PyObject *obj) #define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj)) #endif - // bpo-39573 added Py_SET_REFCNT() to Python 3.9.0a4 #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_REFCNT) -static inline void _Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) +static inline void +_Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) { ob->ob_refcnt = refcnt; } #define Py_SET_REFCNT(ob, refcnt) _Py_SET_REFCNT(_PyObject_CAST(ob), refcnt) #endif - // Py_SETREF() and Py_XSETREF() were added to Python 3.5.2. // It is excluded from the limited C API. -#if (PY_VERSION_HEX < 0x03050200 && !defined(Py_SETREF)) && !defined(Py_LIMITED_API) -#define Py_SETREF(dst, src) \ - do { \ - PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \ - PyObject *_tmp_dst = (*_tmp_dst_ptr); \ - *_tmp_dst_ptr = _PyObject_CAST(src); \ - Py_DECREF(_tmp_dst); \ +#if (PY_VERSION_HEX < 0x03050200 && !defined(Py_SETREF)) && \ + !defined(Py_LIMITED_API) +#define Py_SETREF(dst, src) \ + do { \ + PyObject **_tmp_dst_ptr = _Py_CAST(PyObject **, &(dst)); \ + PyObject *_tmp_dst = (*_tmp_dst_ptr); \ + *_tmp_dst_ptr = _PyObject_CAST(src); \ + Py_DECREF(_tmp_dst); \ } while (0) -#define Py_XSETREF(dst, src) \ - do { \ - PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \ - PyObject *_tmp_dst = (*_tmp_dst_ptr); \ - *_tmp_dst_ptr = _PyObject_CAST(src); \ - Py_XDECREF(_tmp_dst); \ +#define Py_XSETREF(dst, src) \ + do { \ + PyObject **_tmp_dst_ptr = _Py_CAST(PyObject **, &(dst)); \ + PyObject *_tmp_dst = (*_tmp_dst_ptr); \ + *_tmp_dst_ptr = _PyObject_CAST(src); \ + Py_XDECREF(_tmp_dst); \ } while (0) #endif - // bpo-43753 added Py_Is(), Py_IsNone(), Py_IsTrue() and Py_IsFalse() // to Python 3.10.0b1. #if PY_VERSION_HEX < 0x030A00B1 && !defined(Py_Is) -# define Py_Is(x, y) ((x) == (y)) +#define Py_Is(x, y) ((x) == (y)) #endif #if PY_VERSION_HEX < 0x030A00B1 && !defined(Py_IsNone) -# define Py_IsNone(x) Py_Is(x, Py_None) +#define Py_IsNone(x) Py_Is(x, Py_None) #endif -#if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && !defined(Py_IsTrue) -# define Py_IsTrue(x) Py_Is(x, Py_True) +#if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && \ + !defined(Py_IsTrue) +#define Py_IsTrue(x) Py_Is(x, Py_True) #endif -#if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && !defined(Py_IsFalse) -# define Py_IsFalse(x) Py_Is(x, Py_False) +#if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && \ + !defined(Py_IsFalse) +#define Py_IsFalse(x) Py_Is(x, Py_False) #endif - // bpo-39573 added Py_SET_TYPE() to Python 3.9.0a4 #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE) -static inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type) +static inline void +_Py_SET_TYPE(PyObject *ob, PyTypeObject *type) { ob->ob_type = type; } #define Py_SET_TYPE(ob, type) _Py_SET_TYPE(_PyObject_CAST(ob), type) #endif - // bpo-39573 added Py_SET_SIZE() to Python 3.9.0a4 #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE) -static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) +static inline void +_Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) { ob->ob_size = size; } -#define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size) +#define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject *)(ob), size) #endif - // bpo-40421 added PyFrame_GetCode() to Python 3.9.0b1 #if PY_VERSION_HEX < 0x030900B1 || defined(PYPY_VERSION) -static inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame) +static inline PyCodeObject * +PyFrame_GetCode(PyFrameObject *frame) { assert(frame != _Py_NULL); assert(frame->f_code != _Py_NULL); - return _Py_CAST(PyCodeObject*, Py_NewRef(frame->f_code)); + return _Py_CAST(PyCodeObject *, Py_NewRef(frame->f_code)); } #endif -static inline PyCodeObject* _PyFrame_GetCodeBorrow(PyFrameObject *frame) +static inline PyCodeObject * +_PyFrame_GetCodeBorrow(PyFrameObject *frame) { PyCodeObject *code = PyFrame_GetCode(frame); Py_DECREF(code); return code; } - // bpo-40421 added PyFrame_GetBack() to Python 3.9.0b1 #if PY_VERSION_HEX < 0x030900B1 && !defined(PYPY_VERSION) -static inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame) +static inline PyFrameObject * +PyFrame_GetBack(PyFrameObject *frame) { assert(frame != _Py_NULL); - return _Py_CAST(PyFrameObject*, Py_XNewRef(frame->f_back)); + return _Py_CAST(PyFrameObject *, Py_XNewRef(frame->f_back)); } #endif #if !defined(PYPY_VERSION) -static inline PyFrameObject* _PyFrame_GetBackBorrow(PyFrameObject *frame) +static inline PyFrameObject * +_PyFrame_GetBackBorrow(PyFrameObject *frame) { PyFrameObject *back = PyFrame_GetBack(frame); Py_XDECREF(back); @@ -184,10 +186,10 @@ static inline PyFrameObject* _PyFrame_GetBackBorrow(PyFrameObject *frame) } #endif - // bpo-40421 added PyFrame_GetLocals() to Python 3.11.0a7 #if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION) -static inline PyObject* PyFrame_GetLocals(PyFrameObject *frame) +static inline PyObject * +PyFrame_GetLocals(PyFrameObject *frame) { #if PY_VERSION_HEX >= 0x030400B1 if (PyFrame_FastToLocalsWithError(frame) < 0) { @@ -200,28 +202,28 @@ static inline PyObject* PyFrame_GetLocals(PyFrameObject *frame) } #endif - // bpo-40421 added PyFrame_GetGlobals() to Python 3.11.0a7 #if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION) -static inline PyObject* PyFrame_GetGlobals(PyFrameObject *frame) +static inline PyObject * +PyFrame_GetGlobals(PyFrameObject *frame) { return Py_NewRef(frame->f_globals); } #endif - // bpo-40421 added PyFrame_GetBuiltins() to Python 3.11.0a7 #if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION) -static inline PyObject* PyFrame_GetBuiltins(PyFrameObject *frame) +static inline PyObject * +PyFrame_GetBuiltins(PyFrameObject *frame) { return Py_NewRef(frame->f_builtins); } #endif - // bpo-40421 added PyFrame_GetLasti() to Python 3.11.0b1 #if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION) -static inline int PyFrame_GetLasti(PyFrameObject *frame) +static inline int +PyFrame_GetLasti(PyFrameObject *frame) { #if PY_VERSION_HEX >= 0x030A00A7 // bpo-27129: Since Python 3.10.0a7, f_lasti is an instruction offset, @@ -237,10 +239,10 @@ static inline int PyFrame_GetLasti(PyFrameObject *frame) } #endif - // gh-91248 added PyFrame_GetVar() to Python 3.12.0a2 #if PY_VERSION_HEX < 0x030C00A2 && !defined(PYPY_VERSION) -static inline PyObject* PyFrame_GetVar(PyFrameObject *frame, PyObject *name) +static inline PyObject * +PyFrame_GetVar(PyFrameObject *frame, PyObject *name) { PyObject *locals, *value; @@ -270,10 +272,9 @@ static inline PyObject* PyFrame_GetVar(PyFrameObject *frame, PyObject *name) } #endif - // gh-91248 added PyFrame_GetVarString() to Python 3.12.0a2 #if PY_VERSION_HEX < 0x030C00A2 && !defined(PYPY_VERSION) -static inline PyObject* +static inline PyObject * PyFrame_GetVarString(PyFrameObject *frame, const char *name) { PyObject *name_obj, *value; @@ -291,9 +292,9 @@ PyFrame_GetVarString(PyFrameObject *frame, const char *name) } #endif - // bpo-39947 added PyThreadState_GetInterpreter() to Python 3.9.0a5 -#if PY_VERSION_HEX < 0x030900A5 || (defined(PYPY_VERSION) && PY_VERSION_HEX < 0x030B0000) +#if PY_VERSION_HEX < 0x030900A5 || \ + (defined(PYPY_VERSION) && PY_VERSION_HEX < 0x030B0000) static inline PyInterpreterState * PyThreadState_GetInterpreter(PyThreadState *tstate) { @@ -302,10 +303,10 @@ PyThreadState_GetInterpreter(PyThreadState *tstate) } #endif - // bpo-40429 added PyThreadState_GetFrame() to Python 3.9.0b1 #if PY_VERSION_HEX < 0x030900B1 && !defined(PYPY_VERSION) -static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate) +static inline PyFrameObject * +PyThreadState_GetFrame(PyThreadState *tstate) { assert(tstate != _Py_NULL); return _Py_CAST(PyFrameObject *, Py_XNewRef(tstate->frame)); @@ -313,7 +314,7 @@ static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate) #endif #if !defined(PYPY_VERSION) -static inline PyFrameObject* +static inline PyFrameObject * _PyThreadState_GetFrameBorrow(PyThreadState *tstate) { PyFrameObject *frame = PyThreadState_GetFrame(tstate); @@ -322,10 +323,10 @@ _PyThreadState_GetFrameBorrow(PyThreadState *tstate) } #endif - // bpo-39947 added PyInterpreterState_Get() to Python 3.9.0a5 #if PY_VERSION_HEX < 0x030900A5 || defined(PYPY_VERSION) -static inline PyInterpreterState* PyInterpreterState_Get(void) +static inline PyInterpreterState * +PyInterpreterState_Get(void) { PyThreadState *tstate; PyInterpreterState *interp; @@ -342,10 +343,11 @@ static inline PyInterpreterState* PyInterpreterState_Get(void) } #endif - // bpo-39947 added PyInterpreterState_Get() to Python 3.9.0a6 -#if 0x030700A1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030900A6 && !defined(PYPY_VERSION) -static inline uint64_t PyThreadState_GetID(PyThreadState *tstate) +#if 0x030700A1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030900A6 && \ + !defined(PYPY_VERSION) +static inline uint64_t +PyThreadState_GetID(PyThreadState *tstate) { assert(tstate != _Py_NULL); return tstate->id; @@ -354,7 +356,8 @@ static inline uint64_t PyThreadState_GetID(PyThreadState *tstate) // bpo-43760 added PyThreadState_EnterTracing() to Python 3.11.0a2 #if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION) -static inline void PyThreadState_EnterTracing(PyThreadState *tstate) +static inline void +PyThreadState_EnterTracing(PyThreadState *tstate) { tstate->tracing++; #if PY_VERSION_HEX >= 0x030A00A1 @@ -367,10 +370,11 @@ static inline void PyThreadState_EnterTracing(PyThreadState *tstate) // bpo-43760 added PyThreadState_LeaveTracing() to Python 3.11.0a2 #if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION) -static inline void PyThreadState_LeaveTracing(PyThreadState *tstate) +static inline void +PyThreadState_LeaveTracing(PyThreadState *tstate) { - int use_tracing = (tstate->c_tracefunc != _Py_NULL - || tstate->c_profilefunc != _Py_NULL); + int use_tracing = + (tstate->c_tracefunc != _Py_NULL || tstate->c_profilefunc != _Py_NULL); tstate->tracing--; #if PY_VERSION_HEX >= 0x030A00A1 tstate->cframe->use_tracing = use_tracing; @@ -380,28 +384,27 @@ static inline void PyThreadState_LeaveTracing(PyThreadState *tstate) } #endif - // bpo-37194 added PyObject_CallNoArgs() to Python 3.9.0a1 // PyObject_CallNoArgs() added to PyPy 3.9.16-v7.3.11 #if !defined(PyObject_CallNoArgs) && PY_VERSION_HEX < 0x030900A1 -static inline PyObject* PyObject_CallNoArgs(PyObject *func) +static inline PyObject * +PyObject_CallNoArgs(PyObject *func) { return PyObject_CallFunctionObjArgs(func, NULL); } #endif - // bpo-39245 made PyObject_CallOneArg() public (previously called // _PyObject_CallOneArg) in Python 3.9.0a4 // PyObject_CallOneArg() added to PyPy 3.9.16-v7.3.11 #if !defined(PyObject_CallOneArg) && PY_VERSION_HEX < 0x030900A4 -static inline PyObject* PyObject_CallOneArg(PyObject *func, PyObject *arg) +static inline PyObject * +PyObject_CallOneArg(PyObject *func, PyObject *arg) { return PyObject_CallFunctionObjArgs(func, arg, NULL); } #endif - // bpo-1635741 added PyModule_AddObjectRef() to Python 3.10.0a3 #if PY_VERSION_HEX < 0x030A00A3 static inline int @@ -426,10 +429,10 @@ PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value) } #endif - // bpo-40024 added PyModule_AddType() to Python 3.9.0a5 #if PY_VERSION_HEX < 0x030900A5 -static inline int PyModule_AddType(PyObject *module, PyTypeObject *type) +static inline int +PyModule_AddType(PyObject *module, PyTypeObject *type) { const char *name, *dot; @@ -449,11 +452,11 @@ static inline int PyModule_AddType(PyObject *module, PyTypeObject *type) } #endif - // bpo-40241 added PyObject_GC_IsTracked() to Python 3.9.0a6. // bpo-4688 added _PyObject_GC_IS_TRACKED() to Python 2.7.0a2. #if PY_VERSION_HEX < 0x030900A6 && !defined(PYPY_VERSION) -static inline int PyObject_GC_IsTracked(PyObject* obj) +static inline int +PyObject_GC_IsTracked(PyObject *obj) { return (PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj)); } @@ -461,69 +464,89 @@ static inline int PyObject_GC_IsTracked(PyObject* obj) // bpo-40241 added PyObject_GC_IsFinalized() to Python 3.9.0a6. // bpo-18112 added _PyGCHead_FINALIZED() to Python 3.4.0 final. -#if PY_VERSION_HEX < 0x030900A6 && PY_VERSION_HEX >= 0x030400F0 && !defined(PYPY_VERSION) -static inline int PyObject_GC_IsFinalized(PyObject *obj) +#if PY_VERSION_HEX < 0x030900A6 && PY_VERSION_HEX >= 0x030400F0 && \ + !defined(PYPY_VERSION) +static inline int +PyObject_GC_IsFinalized(PyObject *obj) { - PyGC_Head *gc = _Py_CAST(PyGC_Head*, obj) - 1; + PyGC_Head *gc = _Py_CAST(PyGC_Head *, obj) - 1; return (PyObject_IS_GC(obj) && _PyGCHead_FINALIZED(gc)); } #endif - // bpo-39573 added Py_IS_TYPE() to Python 3.9.0a4 #if PY_VERSION_HEX < 0x030900A4 && !defined(Py_IS_TYPE) -static inline int _Py_IS_TYPE(PyObject *ob, PyTypeObject *type) { +static inline int +_Py_IS_TYPE(PyObject *ob, PyTypeObject *type) +{ return Py_TYPE(ob) == type; } #define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST(ob), type) #endif - // bpo-46906 added PyFloat_Pack2() and PyFloat_Unpack2() to Python 3.11a7. // bpo-11734 added _PyFloat_Pack2() and _PyFloat_Unpack2() to Python 3.6.0b1. // Python 3.11a2 moved _PyFloat_Pack2() and _PyFloat_Unpack2() to the internal // C API: Python 3.11a2-3.11a6 versions are not supported. -#if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION) -static inline int PyFloat_Pack2(double x, char *p, int le) -{ return _PyFloat_Pack2(x, (unsigned char*)p, le); } +#if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && \ + !defined(PYPY_VERSION) +static inline int +PyFloat_Pack2(double x, char *p, int le) +{ + return _PyFloat_Pack2(x, (unsigned char *)p, le); +} -static inline double PyFloat_Unpack2(const char *p, int le) -{ return _PyFloat_Unpack2((const unsigned char *)p, le); } +static inline double +PyFloat_Unpack2(const char *p, int le) +{ + return _PyFloat_Unpack2((const unsigned char *)p, le); +} #endif - // bpo-46906 added PyFloat_Pack4(), PyFloat_Pack8(), PyFloat_Unpack4() and // PyFloat_Unpack8() to Python 3.11a7. // Python 3.11a2 moved _PyFloat_Pack4(), _PyFloat_Pack8(), _PyFloat_Unpack4() // and _PyFloat_Unpack8() to the internal C API: Python 3.11a2-3.11a6 versions // are not supported. #if PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION) -static inline int PyFloat_Pack4(double x, char *p, int le) -{ return _PyFloat_Pack4(x, (unsigned char*)p, le); } +static inline int +PyFloat_Pack4(double x, char *p, int le) +{ + return _PyFloat_Pack4(x, (unsigned char *)p, le); +} -static inline int PyFloat_Pack8(double x, char *p, int le) -{ return _PyFloat_Pack8(x, (unsigned char*)p, le); } +static inline int +PyFloat_Pack8(double x, char *p, int le) +{ + return _PyFloat_Pack8(x, (unsigned char *)p, le); +} -static inline double PyFloat_Unpack4(const char *p, int le) -{ return _PyFloat_Unpack4((const unsigned char *)p, le); } +static inline double +PyFloat_Unpack4(const char *p, int le) +{ + return _PyFloat_Unpack4((const unsigned char *)p, le); +} -static inline double PyFloat_Unpack8(const char *p, int le) -{ return _PyFloat_Unpack8((const unsigned char *)p, le); } +static inline double +PyFloat_Unpack8(const char *p, int le) +{ + return _PyFloat_Unpack8((const unsigned char *)p, le); +} #endif - // gh-92154 added PyCode_GetCode() to Python 3.11.0b1 #if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION) -static inline PyObject* PyCode_GetCode(PyCodeObject *code) +static inline PyObject * +PyCode_GetCode(PyCodeObject *code) { return Py_NewRef(code->co_code); } #endif - // gh-95008 added PyCode_GetVarnames() to Python 3.11.0rc1 #if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION) -static inline PyObject* PyCode_GetVarnames(PyCodeObject *code) +static inline PyObject * +PyCode_GetVarnames(PyCodeObject *code) { return Py_NewRef(code->co_varnames); } @@ -531,7 +554,8 @@ static inline PyObject* PyCode_GetVarnames(PyCodeObject *code) // gh-95008 added PyCode_GetFreevars() to Python 3.11.0rc1 #if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION) -static inline PyObject* PyCode_GetFreevars(PyCodeObject *code) +static inline PyObject * +PyCode_GetFreevars(PyCodeObject *code) { return Py_NewRef(code->co_freevars); } @@ -539,35 +563,35 @@ static inline PyObject* PyCode_GetFreevars(PyCodeObject *code) // gh-95008 added PyCode_GetCellvars() to Python 3.11.0rc1 #if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION) -static inline PyObject* PyCode_GetCellvars(PyCodeObject *code) +static inline PyObject * +PyCode_GetCellvars(PyCodeObject *code) { return Py_NewRef(code->co_cellvars); } #endif - // Py_UNUSED() was added to Python 3.4.0b2. #if PY_VERSION_HEX < 0x030400B2 && !defined(Py_UNUSED) -# if defined(__GNUC__) || defined(__clang__) -# define Py_UNUSED(name) _unused_ ## name __attribute__((unused)) -# else -# define Py_UNUSED(name) _unused_ ## name -# endif +#if defined(__GNUC__) || defined(__clang__) +#define Py_UNUSED(name) _unused_##name __attribute__((unused)) +#else +#define Py_UNUSED(name) _unused_##name +#endif #endif - // gh-105922 added PyImport_AddModuleRef() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A0 -static inline PyObject* PyImport_AddModuleRef(const char *name) +static inline PyObject * +PyImport_AddModuleRef(const char *name) { return Py_XNewRef(PyImport_AddModule(name)); } #endif - // gh-105927 added PyWeakref_GetRef() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D0000 -static inline int PyWeakref_GetRef(PyObject *ref, PyObject **pobj) +static inline int +PyWeakref_GetRef(PyObject *ref, PyObject **pobj) { PyObject *obj; if (ref != NULL && !PyWeakref_Check(ref)) { @@ -590,26 +614,26 @@ static inline int PyWeakref_GetRef(PyObject *ref, PyObject **pobj) } #endif - // bpo-36974 added PY_VECTORCALL_ARGUMENTS_OFFSET to Python 3.8b1 #ifndef PY_VECTORCALL_ARGUMENTS_OFFSET -# define PY_VECTORCALL_ARGUMENTS_OFFSET (_Py_CAST(size_t, 1) << (8 * sizeof(size_t) - 1)) +#define PY_VECTORCALL_ARGUMENTS_OFFSET \ + (_Py_CAST(size_t, 1) << (8 * sizeof(size_t) - 1)) #endif // bpo-36974 added PyVectorcall_NARGS() to Python 3.8b1 #if PY_VERSION_HEX < 0x030800B1 -static inline Py_ssize_t PyVectorcall_NARGS(size_t n) +static inline Py_ssize_t +PyVectorcall_NARGS(size_t n) { return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET; } #endif - // gh-105922 added PyObject_Vectorcall() to Python 3.9.0a4 #if PY_VERSION_HEX < 0x030900A4 -static inline PyObject* -PyObject_Vectorcall(PyObject *callable, PyObject *const *args, - size_t nargsf, PyObject *kwnames) +static inline PyObject * +PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, + PyObject *kwnames) { #if PY_VERSION_HEX >= 0x030800B1 && !defined(PYPY_VERSION) // bpo-36974 added _PyObject_Vectorcall() to Python 3.8.0b1 @@ -631,8 +655,7 @@ PyObject_Vectorcall(PyObject *callable, PyObject *const *args, nposargs = (Py_ssize_t)PyVectorcall_NARGS(nargsf); if (kwnames) { nkwargs = PyTuple_GET_SIZE(kwnames); - } - else { + } else { nkwargs = 0; } @@ -641,7 +664,7 @@ PyObject_Vectorcall(PyObject *callable, PyObject *const *args, goto error; } if (nposargs) { - for (i=0; i < nposargs; i++) { + for (i = 0; i < nposargs; i++) { PyTuple_SET_ITEM(posargs, i, Py_NewRef(*args)); args++; } @@ -661,8 +684,7 @@ PyObject_Vectorcall(PyObject *callable, PyObject *const *args, goto error; } } - } - else { + } else { kwargs = NULL; } @@ -679,7 +701,6 @@ PyObject_Vectorcall(PyObject *callable, PyObject *const *args, } #endif - // gh-106521 added PyObject_GetOptionalAttr() and // PyObject_GetOptionalAttrString() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 @@ -706,7 +727,8 @@ PyObject_GetOptionalAttr(PyObject *obj, PyObject *attr_name, PyObject **result) } static inline int -PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result) +PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, + PyObject **result) { PyObject *name_obj; int rc; @@ -725,7 +747,6 @@ PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject ** } #endif - // gh-106307 added PyObject_GetOptionalAttr() and // PyMapping_GetOptionalItemString() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 @@ -744,7 +765,8 @@ PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result) } static inline int -PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result) +PyMapping_GetOptionalItemString(PyObject *obj, const char *key, + PyObject **result) { PyObject *key_obj; int rc; @@ -785,7 +807,6 @@ PyMapping_HasKeyStringWithError(PyObject *obj, const char *key) } #endif - // gh-108511 added PyObject_HasAttrWithError() and // PyObject_HasAttrStringWithError() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 @@ -808,7 +829,6 @@ PyObject_HasAttrStringWithError(PyObject *obj, const char *attr) } #endif - // gh-106004 added PyDict_GetItemRef() and PyDict_GetItemStringRef() // to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 @@ -851,7 +871,6 @@ PyDict_GetItemStringRef(PyObject *mp, const char *key, PyObject **result) } #endif - // gh-106307 added PyModule_Add() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 static inline int @@ -863,13 +882,13 @@ PyModule_Add(PyObject *mod, const char *name, PyObject *value) } #endif - // gh-108014 added Py_IsFinalizing() to Python 3.13.0a1 // bpo-1856 added _Py_Finalizing to Python 3.2.1b1. // _Py_IsFinalizing() was added to PyPy 7.3.0. -#if (0x030201B1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030D00A1) \ - && (!defined(PYPY_VERSION_NUM) || PYPY_VERSION_NUM >= 0x7030000) -static inline int Py_IsFinalizing(void) +#if (0x030201B1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030D00A1) && \ + (!defined(PYPY_VERSION_NUM) || PYPY_VERSION_NUM >= 0x7030000) +static inline int +Py_IsFinalizing(void) { #if PY_VERSION_HEX >= 0x030700A1 // _Py_IsFinalizing() was added to Python 3.7.0a1. @@ -880,10 +899,10 @@ static inline int Py_IsFinalizing(void) } #endif - // gh-108323 added PyDict_ContainsString() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 -static inline int PyDict_ContainsString(PyObject *op, const char *key) +static inline int +PyDict_ContainsString(PyObject *op, const char *key) { PyObject *key_obj = PyUnicode_FromString(key); if (key_obj == NULL) { @@ -895,10 +914,10 @@ static inline int PyDict_ContainsString(PyObject *op, const char *key) } #endif - // gh-108445 added PyLong_AsInt() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 -static inline int PyLong_AsInt(PyObject *obj) +static inline int +PyLong_AsInt(PyObject *obj) { #ifdef PYPY_VERSION long value = PyLong_AsLong(obj); @@ -917,7 +936,6 @@ static inline int PyLong_AsInt(PyObject *obj) } #endif - // gh-107073 added PyObject_VisitManagedDict() to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 static inline int @@ -945,7 +963,7 @@ PyObject_ClearManagedDict(PyObject *obj) // gh-108867 added PyThreadState_GetUnchecked() to Python 3.13.0a1 // Python 3.5.2 added _PyThreadState_UncheckedGet(). #if PY_VERSION_HEX >= 0x03050200 && PY_VERSION_HEX < 0x030D00A1 -static inline PyThreadState* +static inline PyThreadState * PyThreadState_GetUnchecked(void) { return _PyThreadState_UncheckedGet(); @@ -956,7 +974,8 @@ PyThreadState_GetUnchecked(void) // to Python 3.13.0a1 #if PY_VERSION_HEX < 0x030D00A1 static inline int -PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t str_len) +PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, + Py_ssize_t str_len) { Py_ssize_t len; const void *utf8; @@ -971,8 +990,7 @@ PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t str_ if (PyUnicode_IS_ASCII(unicode)) { utf8 = PyUnicode_DATA(unicode); len = PyUnicode_GET_LENGTH(unicode); - } - else { + } else { utf8 = PyUnicode_AsUTF8AndSize(unicode, &len); if (utf8 == NULL) { // Memory allocation failure. The API cannot report error, @@ -1025,7 +1043,6 @@ PyUnicode_EqualToUTF8(PyObject *unicode, const char *str) } #endif - // gh-111138 added PyList_Extend() and PyList_Clear() to Python 3.13.0a2 #if PY_VERSION_HEX < 0x030D00A2 static inline int @@ -1059,10 +1076,11 @@ PyDict_Pop(PyObject *dict, PyObject *key, PyObject **result) // bpo-16991 added _PyDict_Pop() to Python 3.5.0b2. // Python 3.6.0b3 changed _PyDict_Pop() first argument type to PyObject*. // Python 3.13.0a1 removed _PyDict_Pop(). -#if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x030500b2 || PY_VERSION_HEX >= 0x030D0000 +#if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x030500b2 || \ + PY_VERSION_HEX >= 0x030D0000 value = PyObject_CallMethod(dict, "pop", "O", key); #elif PY_VERSION_HEX < 0x030600b3 - value = _PyDict_Pop(_Py_CAST(PyDictObject*, dict), key, NULL); + value = _PyDict_Pop(_Py_CAST(PyDictObject *, dict), key, NULL); #else value = _PyDict_Pop(dict, key, NULL); #endif @@ -1078,8 +1096,7 @@ PyDict_Pop(PyObject *dict, PyObject *key, PyObject **result) } if (result) { *result = value; - } - else { + } else { Py_DECREF(value); } return 1; @@ -1102,43 +1119,51 @@ PyDict_PopString(PyObject *dict, const char *key, PyObject **result) } #endif - #if PY_VERSION_HEX < 0x030200A4 // Python 3.2.0a4 added Py_hash_t type typedef Py_ssize_t Py_hash_t; #endif - // gh-111545 added Py_HashPointer() to Python 3.13.0a3 #if PY_VERSION_HEX < 0x030D00A3 -static inline Py_hash_t Py_HashPointer(const void *ptr) +static inline Py_hash_t +Py_HashPointer(const void *ptr) { #if PY_VERSION_HEX >= 0x030900A4 && !defined(PYPY_VERSION) return _Py_HashPointer(ptr); #else - return _Py_HashPointer(_Py_CAST(void*, ptr)); + return _Py_HashPointer(_Py_CAST(void *, ptr)); #endif } #endif - // Python 3.13a4 added a PyTime API. // Use the private API added to Python 3.5. -#if PY_VERSION_HEX < 0x030D00A4 && PY_VERSION_HEX >= 0x03050000 +#if PY_VERSION_HEX < 0x030D00A4 && PY_VERSION_HEX >= 0x03050000 typedef _PyTime_t PyTime_t; #define PyTime_MIN _PyTime_MIN #define PyTime_MAX _PyTime_MAX -static inline double PyTime_AsSecondsDouble(PyTime_t t) -{ return _PyTime_AsSecondsDouble(t); } +static inline double +PyTime_AsSecondsDouble(PyTime_t t) +{ + return _PyTime_AsSecondsDouble(t); +} -static inline int PyTime_Monotonic(PyTime_t *result) -{ return _PyTime_GetMonotonicClockWithInfo(result, NULL); } +static inline int +PyTime_Monotonic(PyTime_t *result) +{ + return _PyTime_GetMonotonicClockWithInfo(result, NULL); +} -static inline int PyTime_Time(PyTime_t *result) -{ return _PyTime_GetSystemClockWithInfo(result, NULL); } +static inline int +PyTime_Time(PyTime_t *result) +{ + return _PyTime_GetSystemClockWithInfo(result, NULL); +} -static inline int PyTime_PerfCounter(PyTime_t *result) +static inline int +PyTime_PerfCounter(PyTime_t *result) { #if PY_VERSION_HEX >= 0x03070000 && !defined(PYPY_VERSION) return _PyTime_GetPerfCounterWithInfo(result, NULL); @@ -1211,17 +1236,16 @@ static inline int PyTime_PerfCounter(PyTime_t *result) // gh-111389 added hash constants to Python 3.13.0a5. These constants were // added first as private macros to Python 3.4.0b1 and PyPy 7.3.8. -#if (!defined(PyHASH_BITS) \ - && ((!defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x030400B1) \ - || (defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x03070000 \ - && PYPY_VERSION_NUM >= 0x07030800))) -# define PyHASH_BITS _PyHASH_BITS -# define PyHASH_MODULUS _PyHASH_MODULUS -# define PyHASH_INF _PyHASH_INF -# define PyHASH_IMAG _PyHASH_IMAG +#if (!defined(PyHASH_BITS) && \ + ((!defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x030400B1) || \ + (defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x03070000 && \ + PYPY_VERSION_NUM >= 0x07030800))) +#define PyHASH_BITS _PyHASH_BITS +#define PyHASH_MODULUS _PyHASH_MODULUS +#define PyHASH_INF _PyHASH_INF +#define PyHASH_IMAG _PyHASH_IMAG #endif - // gh-111545 added Py_GetConstant() and Py_GetConstantBorrowed() // to Python 3.13.0a6 #if PY_VERSION_HEX < 0x030D00A6 && !defined(Py_CONSTANT_NONE) @@ -1237,9 +1261,10 @@ static inline int PyTime_PerfCounter(PyTime_t *result) #define Py_CONSTANT_EMPTY_BYTES 8 #define Py_CONSTANT_EMPTY_TUPLE 9 -static inline PyObject* Py_GetConstant(unsigned int constant_id) +static inline PyObject * +Py_GetConstant(unsigned int constant_id) { - static PyObject* constants[Py_CONSTANT_EMPTY_TUPLE + 1] = {NULL}; + static PyObject *constants[Py_CONSTANT_EMPTY_TUPLE + 1] = {NULL}; if (constants[Py_CONSTANT_NONE] == NULL) { constants[Py_CONSTANT_NONE] = Py_None; @@ -1275,7 +1300,7 @@ static inline PyObject* Py_GetConstant(unsigned int constant_id) // goto dance to avoid compiler warnings about Py_FatalError() goto init_done; -fatal_error: + fatal_error: // This case should never happen Py_FatalError("Py_GetConstant() failed to get constants"); } @@ -1283,14 +1308,14 @@ static inline PyObject* Py_GetConstant(unsigned int constant_id) init_done: if (constant_id <= Py_CONSTANT_EMPTY_TUPLE) { return Py_NewRef(constants[constant_id]); - } - else { + } else { PyErr_BadInternalCall(); return NULL; } } -static inline PyObject* Py_GetConstantBorrowed(unsigned int constant_id) +static inline PyObject * +Py_GetConstantBorrowed(unsigned int constant_id) { PyObject *obj = Py_GetConstant(constant_id); Py_XDECREF(obj); @@ -1298,7 +1323,6 @@ static inline PyObject* Py_GetConstantBorrowed(unsigned int constant_id) } #endif - // gh-114329 added PyList_GetItemRef() to Python 3.13.0a4 #if PY_VERSION_HEX < 0x030D00A4 static inline PyObject * @@ -1310,7 +1334,6 @@ PyList_GetItemRef(PyObject *op, Py_ssize_t index) } #endif - // gh-114329 added PyList_GetItemRef() to Python 3.13.0a4 #if PY_VERSION_HEX < 0x030D00A4 static inline int @@ -1329,8 +1352,7 @@ PyDict_SetDefaultRef(PyObject *d, PyObject *key, PyObject *default_value, // present if (result) { *result = value; - } - else { + } else { Py_DECREF(value); } return 1; @@ -1352,26 +1374,28 @@ PyDict_SetDefaultRef(PyObject *d, PyObject *key, PyObject *default_value, #endif #if PY_VERSION_HEX < 0x030D00B3 -# define Py_BEGIN_CRITICAL_SECTION(op) { -# define Py_END_CRITICAL_SECTION() } -# define Py_BEGIN_CRITICAL_SECTION2(a, b) { -# define Py_END_CRITICAL_SECTION2() } +#define Py_BEGIN_CRITICAL_SECTION(op) { +#define Py_END_CRITICAL_SECTION() } +#define Py_BEGIN_CRITICAL_SECTION2(a, b) { +#define Py_END_CRITICAL_SECTION2() } #endif -#if PY_VERSION_HEX < 0x030E0000 && PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION) +#if PY_VERSION_HEX < 0x030E0000 && PY_VERSION_HEX >= 0x03060000 && \ + !defined(PYPY_VERSION) typedef struct PyUnicodeWriter PyUnicodeWriter; -static inline void PyUnicodeWriter_Discard(PyUnicodeWriter *writer) +static inline void +PyUnicodeWriter_Discard(PyUnicodeWriter *writer) { - _PyUnicodeWriter_Dealloc((_PyUnicodeWriter*)writer); + _PyUnicodeWriter_Dealloc((_PyUnicodeWriter *)writer); PyMem_Free(writer); } -static inline PyUnicodeWriter* PyUnicodeWriter_Create(Py_ssize_t length) +static inline PyUnicodeWriter * +PyUnicodeWriter_Create(Py_ssize_t length) { if (length < 0) { - PyErr_SetString(PyExc_ValueError, - "length must be positive"); + PyErr_SetString(PyExc_ValueError, "length must be positive"); return NULL; } @@ -1392,10 +1416,11 @@ static inline PyUnicodeWriter* PyUnicodeWriter_Create(Py_ssize_t length) return pub_writer; } -static inline PyObject* PyUnicodeWriter_Finish(PyUnicodeWriter *writer) +static inline PyObject * +PyUnicodeWriter_Finish(PyUnicodeWriter *writer) { - PyObject *str = _PyUnicodeWriter_Finish((_PyUnicodeWriter*)writer); - assert(((_PyUnicodeWriter*)writer)->buffer == NULL); + PyObject *str = _PyUnicodeWriter_Finish((_PyUnicodeWriter *)writer); + assert(((_PyUnicodeWriter *)writer)->buffer == NULL); PyMem_Free(writer); return str; } @@ -1409,7 +1434,7 @@ PyUnicodeWriter_WriteChar(PyUnicodeWriter *writer, Py_UCS4 ch) return -1; } - return _PyUnicodeWriter_WriteChar((_PyUnicodeWriter*)writer, ch); + return _PyUnicodeWriter_WriteChar((_PyUnicodeWriter *)writer, ch); } static inline int @@ -1420,7 +1445,7 @@ PyUnicodeWriter_WriteStr(PyUnicodeWriter *writer, PyObject *obj) return -1; } - int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str); + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter *)writer, str); Py_DECREF(str); return res; } @@ -1433,14 +1458,14 @@ PyUnicodeWriter_WriteRepr(PyUnicodeWriter *writer, PyObject *obj) return -1; } - int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str); + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter *)writer, str); Py_DECREF(str); return res; } static inline int -PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer, - const char *str, Py_ssize_t size) +PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer, const char *str, + Py_ssize_t size) { if (size < 0) { size = (Py_ssize_t)strlen(str); @@ -1451,14 +1476,14 @@ PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer, return -1; } - int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj); + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter *)writer, str_obj); Py_DECREF(str_obj); return res; } static inline int -PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer, - const wchar_t *str, Py_ssize_t size) +PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer, const wchar_t *str, + Py_ssize_t size) { if (size < 0) { size = (Py_ssize_t)wcslen(str); @@ -1469,7 +1494,7 @@ PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer, return -1; } - int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj); + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter *)writer, str_obj); Py_DECREF(str_obj); return res; } @@ -1491,8 +1516,8 @@ PyUnicodeWriter_WriteSubstring(PyUnicodeWriter *writer, PyObject *str, return -1; } - return _PyUnicodeWriter_WriteSubstring((_PyUnicodeWriter*)writer, str, - start, end); + return _PyUnicodeWriter_WriteSubstring( + (_PyUnicodeWriter *)writer, str, start, end); } static inline int @@ -1506,7 +1531,7 @@ PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...) return -1; } - int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str); + int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter *)writer, str); Py_DECREF(str); return res; } @@ -1514,10 +1539,12 @@ PyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...) // gh-116560 added PyLong_GetSign() to Python 3.14.0a0 #if PY_VERSION_HEX < 0x030E00A0 -static inline int PyLong_GetSign(PyObject *obj, int *sign) +static inline int +PyLong_GetSign(PyObject *obj, int *sign) { if (!PyLong_Check(obj)) { - PyErr_Format(PyExc_TypeError, "expect int, got %s", Py_TYPE(obj)->tp_name); + PyErr_Format( + PyExc_TypeError, "expect int, got %s", Py_TYPE(obj)->tp_name); return -1; } @@ -1528,52 +1555,60 @@ static inline int PyLong_GetSign(PyObject *obj, int *sign) // gh-126061 added PyLong_IsPositive/Negative/Zero() to Python in 3.14.0a2 #if PY_VERSION_HEX < 0x030E00A2 -static inline int PyLong_IsPositive(PyObject *obj) +static inline int +PyLong_IsPositive(PyObject *obj) { if (!PyLong_Check(obj)) { - PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); + PyErr_Format( + PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); return -1; } return _PyLong_Sign(obj) == 1; } -static inline int PyLong_IsNegative(PyObject *obj) +static inline int +PyLong_IsNegative(PyObject *obj) { if (!PyLong_Check(obj)) { - PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); + PyErr_Format( + PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); return -1; } return _PyLong_Sign(obj) == -1; } -static inline int PyLong_IsZero(PyObject *obj) +static inline int +PyLong_IsZero(PyObject *obj) { if (!PyLong_Check(obj)) { - PyErr_Format(PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); + PyErr_Format( + PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); return -1; } return _PyLong_Sign(obj) == 0; } #endif - // gh-124502 added PyUnicode_Equal() to Python 3.14.0a0 #if PY_VERSION_HEX < 0x030E00A0 -static inline int PyUnicode_Equal(PyObject *str1, PyObject *str2) +static inline int +PyUnicode_Equal(PyObject *str1, PyObject *str2) { if (!PyUnicode_Check(str1)) { - PyErr_Format(PyExc_TypeError, "first argument must be str, not %s", + PyErr_Format(PyExc_TypeError, + "first argument must be str, not %s", Py_TYPE(str1)->tp_name); return -1; } if (!PyUnicode_Check(str2)) { - PyErr_Format(PyExc_TypeError, "second argument must be str, not %s", + PyErr_Format(PyExc_TypeError, + "second argument must be str, not %s", Py_TYPE(str2)->tp_name); return -1; } #if PY_VERSION_HEX >= 0x030d0000 && !defined(PYPY_VERSION) - PyAPI_FUNC(int) _PyUnicode_Equal(PyObject *str1, PyObject *str2); + PyAPI_FUNC(int) _PyUnicode_Equal(PyObject * str1, PyObject * str2); return _PyUnicode_Equal(str1, str2); #elif PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION) @@ -1586,18 +1621,18 @@ static inline int PyUnicode_Equal(PyObject *str1, PyObject *str2) } #endif - // gh-121645 added PyBytes_Join() to Python 3.14.0a0 #if PY_VERSION_HEX < 0x030E00A0 -static inline PyObject* PyBytes_Join(PyObject *sep, PyObject *iterable) +static inline PyObject * +PyBytes_Join(PyObject *sep, PyObject *iterable) { return _PyBytes_Join(sep, iterable); } #endif - #if PY_VERSION_HEX < 0x030E00A0 -static inline Py_hash_t Py_HashBuffer(const void *ptr, Py_ssize_t len) +static inline Py_hash_t +Py_HashBuffer(const void *ptr, Py_ssize_t len) { #if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION) PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void *src, Py_ssize_t len); @@ -1605,7 +1640,7 @@ static inline Py_hash_t Py_HashBuffer(const void *ptr, Py_ssize_t len) return _Py_HashBytes(ptr, len); #else Py_hash_t hash; - PyObject *bytes = PyBytes_FromStringAndSize((const char*)ptr, len); + PyObject *bytes = PyBytes_FromStringAndSize((const char *)ptr, len); if (bytes == NULL) { return -1; } @@ -1616,9 +1651,9 @@ static inline Py_hash_t Py_HashBuffer(const void *ptr, Py_ssize_t len) } #endif - #if PY_VERSION_HEX < 0x030E00A0 -static inline int PyIter_NextItem(PyObject *iter, PyObject **item) +static inline int +PyIter_NextItem(PyObject *iter, PyObject **item) { iternextfunc tp_iternext; @@ -1628,7 +1663,8 @@ static inline int PyIter_NextItem(PyObject *iter, PyObject **item) tp_iternext = Py_TYPE(iter)->tp_iternext; if (tp_iternext == NULL) { *item = NULL; - PyErr_Format(PyExc_TypeError, "expected an iterator, got '%s'", + PyErr_Format(PyExc_TypeError, + "expected an iterator, got '%s'", Py_TYPE(iter)->tp_name); return -1; } @@ -1647,33 +1683,37 @@ static inline int PyIter_NextItem(PyObject *iter, PyObject **item) } #endif - #if PY_VERSION_HEX < 0x030E00A0 -static inline PyObject* PyLong_FromInt32(int32_t value) +static inline PyObject * +PyLong_FromInt32(int32_t value) { Py_BUILD_ASSERT(sizeof(long) >= 4); return PyLong_FromLong(value); } -static inline PyObject* PyLong_FromInt64(int64_t value) +static inline PyObject * +PyLong_FromInt64(int64_t value) { Py_BUILD_ASSERT(sizeof(long long) >= 8); return PyLong_FromLongLong(value); } -static inline PyObject* PyLong_FromUInt32(uint32_t value) +static inline PyObject * +PyLong_FromUInt32(uint32_t value) { Py_BUILD_ASSERT(sizeof(unsigned long) >= 4); return PyLong_FromUnsignedLong(value); } -static inline PyObject* PyLong_FromUInt64(uint64_t value) +static inline PyObject * +PyLong_FromUInt64(uint64_t value) { Py_BUILD_ASSERT(sizeof(unsigned long long) >= 8); return PyLong_FromUnsignedLongLong(value); } -static inline int PyLong_AsInt32(PyObject *obj, int32_t *pvalue) +static inline int +PyLong_AsInt32(PyObject *obj, int32_t *pvalue) { Py_BUILD_ASSERT(sizeof(int) == 4); int value = PyLong_AsInt(obj); @@ -1684,7 +1724,8 @@ static inline int PyLong_AsInt32(PyObject *obj, int32_t *pvalue) return 0; } -static inline int PyLong_AsInt64(PyObject *obj, int64_t *pvalue) +static inline int +PyLong_AsInt64(PyObject *obj, int64_t *pvalue) { Py_BUILD_ASSERT(sizeof(long long) == 8); long long value = PyLong_AsLongLong(obj); @@ -1695,7 +1736,8 @@ static inline int PyLong_AsInt64(PyObject *obj, int64_t *pvalue) return 0; } -static inline int PyLong_AsUInt32(PyObject *obj, uint32_t *pvalue) +static inline int +PyLong_AsUInt32(PyObject *obj, uint32_t *pvalue) { Py_BUILD_ASSERT(sizeof(long) >= 4); unsigned long value = PyLong_AsUnsignedLong(obj); @@ -1713,7 +1755,8 @@ static inline int PyLong_AsUInt32(PyObject *obj, uint32_t *pvalue) return 0; } -static inline int PyLong_AsUInt64(PyObject *obj, uint64_t *pvalue) +static inline int +PyLong_AsUInt64(PyObject *obj, uint64_t *pvalue) { Py_BUILD_ASSERT(sizeof(long long) == 8); unsigned long long value = PyLong_AsUnsignedLongLong(obj); @@ -1725,9 +1768,9 @@ static inline int PyLong_AsUInt64(PyObject *obj, uint64_t *pvalue) } #endif - // gh-102471 added import and export API for integers to 3.14.0a2. -#if PY_VERSION_HEX < 0x030E00A2 && PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION) +#if PY_VERSION_HEX < 0x030E00A2 && PY_VERSION_HEX >= 0x03000000 && \ + !defined(PYPY_VERSION) // Helpers to access PyLongObject internals. static inline void _PyLong_SetSignAndDigitCount(PyLongObject *op, int sign, Py_ssize_t size) @@ -1747,17 +1790,17 @@ _PyLong_DigitCount(const PyLongObject *op) #if PY_VERSION_HEX >= 0x030C0000 return (Py_ssize_t)(op->long_value.lv_tag >> 3); #else - return _PyLong_Sign((PyObject*)op) < 0 ? -Py_SIZE(op) : Py_SIZE(op); + return _PyLong_Sign((PyObject *)op) < 0 ? -Py_SIZE(op) : Py_SIZE(op); #endif } -static inline digit* +static inline digit * _PyLong_GetDigits(const PyLongObject *op) { #if PY_VERSION_HEX >= 0x030C0000 - return (digit*)(op->long_value.ob_digit); + return (digit *)(op->long_value.ob_digit); #else - return (digit*)(op->ob_digit); + return (digit *)(op->ob_digit); #endif } @@ -1778,7 +1821,7 @@ typedef struct PyLongExport { typedef struct PyLongWriter PyLongWriter; -static inline const PyLongLayout* +static inline const PyLongLayout * PyLong_GetNativeLayout(void) { static const PyLongLayout PyLong_LAYOUT = { @@ -1796,13 +1839,13 @@ PyLong_Export(PyObject *obj, PyLongExport *export_long) { if (!PyLong_Check(obj)) { memset(export_long, 0, sizeof(*export_long)); - PyErr_Format(PyExc_TypeError, "expected int, got %s", - Py_TYPE(obj)->tp_name); + PyErr_Format( + PyExc_TypeError, "expected int, got %s", Py_TYPE(obj)->tp_name); return -1; } // Fast-path: try to convert to a int64_t - PyLongObject *self = (PyLongObject*)obj; + PyLongObject *self = (PyLongObject *)obj; int overflow; #if SIZEOF_LONG == 8 long value = PyLong_AsLongAndOverflow(obj, &overflow); @@ -1820,8 +1863,7 @@ PyLong_Export(PyObject *obj, PyLongExport *export_long) export_long->ndigits = 0; export_long->digits = 0; export_long->_reserved = 0; - } - else { + } else { export_long->value = 0; export_long->negative = _PyLong_Sign(obj) < 0; export_long->ndigits = _PyLong_DigitCount(self); @@ -1837,7 +1879,7 @@ PyLong_Export(PyObject *obj, PyLongExport *export_long) static inline void PyLong_FreeExport(PyLongExport *export_long) { - PyObject *obj = (PyObject*)export_long->_reserved; + PyObject *obj = (PyObject *)export_long->_reserved; if (obj) { export_long->_reserved = 0; @@ -1845,7 +1887,7 @@ PyLong_FreeExport(PyLongExport *export_long) } } -static inline PyLongWriter* +static inline PyLongWriter * PyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits) { if (ndigits <= 0) { @@ -1858,10 +1900,10 @@ PyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits) if (obj == NULL) { return NULL; } - _PyLong_SetSignAndDigitCount(obj, negative?-1:1, ndigits); + _PyLong_SetSignAndDigitCount(obj, negative ? -1 : 1, ndigits); *digits = _PyLong_GetDigits(obj); - return (PyLongWriter*)obj; + return (PyLongWriter *)obj; } static inline void @@ -1873,11 +1915,11 @@ PyLongWriter_Discard(PyLongWriter *writer) Py_DECREF(obj); } -static inline PyObject* +static inline PyObject * PyLongWriter_Finish(PyLongWriter *writer) { PyObject *obj = (PyObject *)writer; - PyLongObject *self = (PyLongObject*)obj; + PyLongObject *self = (PyLongObject *)obj; Py_ssize_t j = _PyLong_DigitCount(self); Py_ssize_t i = j; int sign = _PyLong_Sign(obj); @@ -1885,7 +1927,7 @@ PyLongWriter_Finish(PyLongWriter *writer) assert(Py_REFCNT(obj) == 1); // Normalize and get singleton if possible - while (i > 0 && _PyLong_GetDigits(self)[i-1] == 0) { + while (i > 0 && _PyLong_GetDigits(self)[i - 1] == 0) { --i; } if (i != j) { @@ -1904,44 +1946,43 @@ PyLongWriter_Finish(PyLongWriter *writer) } #endif - #if PY_VERSION_HEX < 0x030C00A3 -# define Py_T_SHORT T_SHORT -# define Py_T_INT T_INT -# define Py_T_LONG T_LONG -# define Py_T_FLOAT T_FLOAT -# define Py_T_DOUBLE T_DOUBLE -# define Py_T_STRING T_STRING -# define _Py_T_OBJECT T_OBJECT -# define Py_T_CHAR T_CHAR -# define Py_T_BYTE T_BYTE -# define Py_T_UBYTE T_UBYTE -# define Py_T_USHORT T_USHORT -# define Py_T_UINT T_UINT -# define Py_T_ULONG T_ULONG -# define Py_T_STRING_INPLACE T_STRING_INPLACE -# define Py_T_BOOL T_BOOL -# define Py_T_OBJECT_EX T_OBJECT_EX -# define Py_T_LONGLONG T_LONGLONG -# define Py_T_ULONGLONG T_ULONGLONG -# define Py_T_PYSSIZET T_PYSSIZET - -# if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION) -# define _Py_T_NONE T_NONE -# endif - -# define Py_READONLY READONLY -# define Py_AUDIT_READ READ_RESTRICTED -# define _Py_WRITE_RESTRICTED PY_WRITE_RESTRICTED +#define Py_T_SHORT T_SHORT +#define Py_T_INT T_INT +#define Py_T_LONG T_LONG +#define Py_T_FLOAT T_FLOAT +#define Py_T_DOUBLE T_DOUBLE +#define Py_T_STRING T_STRING +#define _Py_T_OBJECT T_OBJECT +#define Py_T_CHAR T_CHAR +#define Py_T_BYTE T_BYTE +#define Py_T_UBYTE T_UBYTE +#define Py_T_USHORT T_USHORT +#define Py_T_UINT T_UINT +#define Py_T_ULONG T_ULONG +#define Py_T_STRING_INPLACE T_STRING_INPLACE +#define Py_T_BOOL T_BOOL +#define Py_T_OBJECT_EX T_OBJECT_EX +#define Py_T_LONGLONG T_LONGLONG +#define Py_T_ULONGLONG T_ULONGLONG +#define Py_T_PYSSIZET T_PYSSIZET + +#if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION) +#define _Py_T_NONE T_NONE #endif +#define Py_READONLY READONLY +#define Py_AUDIT_READ READ_RESTRICTED +#define _Py_WRITE_RESTRICTED PY_WRITE_RESTRICTED +#endif // gh-127350 added Py_fopen() and Py_fclose() to Python 3.14a4 #if PY_VERSION_HEX < 0x030E00A4 -static inline FILE* Py_fopen(PyObject *path, const char *mode) +static inline FILE * +Py_fopen(PyObject *path, const char *mode) { #if 0x030400A2 <= PY_VERSION_HEX && !defined(PYPY_VERSION) - PyAPI_FUNC(FILE*) _Py_fopen_obj(PyObject *path, const char *mode); + PyAPI_FUNC(FILE *) _Py_fopen_obj(PyObject * path, const char *mode); return _Py_fopen_obj(path, mode); #else @@ -1971,15 +2012,16 @@ static inline FILE* Py_fopen(PyObject *path, const char *mode) #endif } -static inline int Py_fclose(FILE *file) +static inline int +Py_fclose(FILE *file) { return fclose(file); } #endif - -#if 0x03090000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030E0000 && !defined(PYPY_VERSION) -static inline PyObject* +#if 0x03090000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030E0000 && \ + !defined(PYPY_VERSION) +static inline PyObject * PyConfig_Get(const char *name) { typedef enum { @@ -1999,9 +2041,11 @@ PyConfig_Get(const char *name) const char *sys_attr; } PyConfigSpec; -#define PYTHONCAPI_COMPAT_SPEC(MEMBER, TYPE, sys_attr) \ - {#MEMBER, offsetof(PyConfig, MEMBER), \ - _PyConfig_MEMBER_##TYPE, sys_attr} +#define PYTHONCAPI_COMPAT_SPEC(MEMBER, TYPE, sys_attr) \ + { \ + #MEMBER, offsetof(PyConfig, MEMBER), _PyConfig_MEMBER_##TYPE, \ + sys_attr \ + } static const PyConfigSpec config_spec[] = { PYTHONCAPI_COMPAT_SPEC(argv, WSTR_LIST, "argv"), @@ -2095,7 +2139,7 @@ PyConfig_Get(const char *name) const PyConfigSpec *spec; int found = 0; - for (size_t i=0; i < sizeof(config_spec) / sizeof(config_spec[0]); i++) { + for (size_t i = 0; i < sizeof(config_spec) / sizeof(config_spec[0]); i++) { spec = &config_spec[i]; if (strcmp(spec->name, name) == 0) { found = 1; @@ -2106,64 +2150,61 @@ PyConfig_Get(const char *name) if (spec->sys_attr != NULL) { PyObject *value = PySys_GetObject(spec->sys_attr); if (value == NULL) { - PyErr_Format(PyExc_RuntimeError, "lost sys.%s", spec->sys_attr); + PyErr_Format( + PyExc_RuntimeError, "lost sys.%s", spec->sys_attr); return NULL; } return Py_NewRef(value); } - PyAPI_FUNC(const PyConfig*) _Py_GetConfig(void); + PyAPI_FUNC(const PyConfig *) _Py_GetConfig(void); const PyConfig *config = _Py_GetConfig(); void *member = (char *)config + spec->offset; switch (spec->type) { - case _PyConfig_MEMBER_INT: - case _PyConfig_MEMBER_UINT: - { - int value = *(int *)member; - return PyLong_FromLong(value); - } - case _PyConfig_MEMBER_BOOL: - { - int value = *(int *)member; - return PyBool_FromLong(value != 0); - } - case _PyConfig_MEMBER_ULONG: - { - unsigned long value = *(unsigned long *)member; - return PyLong_FromUnsignedLong(value); - } - case _PyConfig_MEMBER_WSTR: - case _PyConfig_MEMBER_WSTR_OPT: - { - wchar_t *wstr = *(wchar_t **)member; - if (wstr != NULL) { - return PyUnicode_FromWideChar(wstr, -1); + case _PyConfig_MEMBER_INT: + case _PyConfig_MEMBER_UINT: { + int value = *(int *)member; + return PyLong_FromLong(value); } - else { - return Py_NewRef(Py_None); + case _PyConfig_MEMBER_BOOL: { + int value = *(int *)member; + return PyBool_FromLong(value != 0); } - } - case _PyConfig_MEMBER_WSTR_LIST: - { - const PyWideStringList *list = (const PyWideStringList *)member; - PyObject *tuple = PyTuple_New(list->length); - if (tuple == NULL) { - return NULL; + case _PyConfig_MEMBER_ULONG: { + unsigned long value = *(unsigned long *)member; + return PyLong_FromUnsignedLong(value); } - - for (Py_ssize_t i = 0; i < list->length; i++) { - PyObject *item = PyUnicode_FromWideChar(list->items[i], -1); - if (item == NULL) { - Py_DECREF(tuple); + case _PyConfig_MEMBER_WSTR: + case _PyConfig_MEMBER_WSTR_OPT: { + wchar_t *wstr = *(wchar_t **)member; + if (wstr != NULL) { + return PyUnicode_FromWideChar(wstr, -1); + } else { + return Py_NewRef(Py_None); + } + } + case _PyConfig_MEMBER_WSTR_LIST: { + const PyWideStringList *list = + (const PyWideStringList *)member; + PyObject *tuple = PyTuple_New(list->length); + if (tuple == NULL) { return NULL; } - PyTuple_SET_ITEM(tuple, i, item); + + for (Py_ssize_t i = 0; i < list->length; i++) { + PyObject *item = + PyUnicode_FromWideChar(list->items[i], -1); + if (item == NULL) { + Py_DECREF(tuple); + return NULL; + } + PyTuple_SET_ITEM(tuple, i, item); + } + return tuple; } - return tuple; - } - default: - Py_UNREACHABLE(); + default: + Py_UNREACHABLE(); } } @@ -2189,7 +2230,8 @@ PyConfig_GetInt(const char *name, int *value) Py_DECREF(obj); if (as_int == -1 && PyErr_Occurred()) { PyErr_Format(PyExc_OverflowError, - "config option %s value does not fit into a C int", name); + "config option %s value does not fit into a C int", + name); return -1; } @@ -2198,7 +2240,6 @@ PyConfig_GetInt(const char *name, int *value) } #endif // PY_VERSION_HEX > 0x03090000 && !defined(PYPY_VERSION) - #ifdef __cplusplus } #endif diff --git a/multidict/_multilib/state.h b/multidict/_multilib/state.h index e04c991d5..4e2610b6c 100644 --- a/multidict/_multilib/state.h +++ b/multidict/_multilib/state.h @@ -45,12 +45,11 @@ get_mod_state_by_cls(PyTypeObject *cls) return state; } - #if PY_VERSION_HEX < 0x030b0000 PyObject * PyType_GetModuleByDef(PyTypeObject *tp, PyModuleDef *def) { - PyModuleDef * mod_def; + PyModuleDef *mod_def; if (!PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE)) { goto err; } @@ -78,7 +77,7 @@ PyType_GetModuleByDef(PyTypeObject *tp, PyModuleDef *def) if (!PyType_HasFeature((PyTypeObject *)super, Py_TPFLAGS_HEAPTYPE)) { continue; } - mod = PyType_GetModule((PyTypeObject*)super); + mod = PyType_GetModule((PyTypeObject *)super); if (mod == NULL) { PyErr_Clear(); } else { @@ -95,7 +94,6 @@ PyType_GetModuleByDef(PyTypeObject *tp, PyModuleDef *def) "PyType_GetModuleByDef: No superclass of '%s' has the given module", tp->tp_name); return NULL; - } #endif @@ -118,7 +116,6 @@ get_mod_state_by_def_checked(PyObject *self, mod_state **ret) return 1; } - static inline mod_state * get_mod_state_by_def(PyObject *self) { @@ -128,13 +125,12 @@ get_mod_state_by_def(PyObject *self) return get_mod_state(mod); } - -static inline uint64_t NEXT_VERSION(mod_state *state) +static inline uint64_t +NEXT_VERSION(mod_state *state) { return ++state->global_version; } - #ifdef __cplusplus } #endif diff --git a/multidict/_multilib/views.h b/multidict/_multilib/views.h index a11eb5fc1..a15641d5b 100644 --- a/multidict/_multilib/views.h +++ b/multidict/_multilib/views.h @@ -14,12 +14,10 @@ typedef struct { MultiDictObject *md; } _Multidict_ViewObject; - #define Items_CheckExact(state, obj) Py_IS_TYPE(obj, state->ItemsViewType) #define Keys_CheckExact(state, obj) Py_IS_TYPE(obj, state->KeysViewType) #define Values_CheckExact(state, obj) Py_IS_TYPE(obj, state->ValuesViewType) - /********** Base **********/ static inline void @@ -38,7 +36,8 @@ multidict_view_dealloc(_Multidict_ViewObject *self) } static inline int -multidict_view_traverse(_Multidict_ViewObject *self, visitproc visit, void *arg) +multidict_view_traverse(_Multidict_ViewObject *self, visitproc visit, + void *arg) { Py_VISIT(self->md); return 0; @@ -58,7 +57,8 @@ multidict_view_len(_Multidict_ViewObject *self) } static inline PyObject * -multidict_view_richcompare(_Multidict_ViewObject *self, PyObject *other, int op) +multidict_view_richcompare(_Multidict_ViewObject *self, PyObject *other, + int op) { int tmp; Py_ssize_t self_size = md_len(self->md); @@ -69,10 +69,9 @@ multidict_view_richcompare(_Multidict_ViewObject *self, PyObject *other, int op) } PyObject *iter = NULL; PyObject *item = NULL; - switch(op) { + switch (op) { case Py_LT: - if (self_size >= size) - Py_RETURN_FALSE; + if (self_size >= size) Py_RETURN_FALSE; return multidict_view_richcompare(self, other, Py_LE); case Py_LE: if (self_size > size) { @@ -99,8 +98,7 @@ multidict_view_richcompare(_Multidict_ViewObject *self, PyObject *other, int op) } Py_RETURN_TRUE; case Py_EQ: - if (self_size != size) - Py_RETURN_FALSE; + if (self_size != size) Py_RETURN_FALSE; return multidict_view_richcompare(self, other, Py_LE); case Py_NE: item = multidict_view_richcompare(self, other, Py_EQ); @@ -115,8 +113,7 @@ multidict_view_richcompare(_Multidict_ViewObject *self, PyObject *other, int op) Py_RETURN_TRUE; } case Py_GT: - if (self_size <= size) - Py_RETURN_FALSE; + if (self_size <= size) Py_RETURN_FALSE; return multidict_view_richcompare(self, other, Py_GE); case Py_GE: if (self_size < size) { @@ -149,14 +146,13 @@ multidict_view_richcompare(_Multidict_ViewObject *self, PyObject *other, int op) return NULL; } - /********** Items **********/ static inline PyObject * multidict_itemsview_new(MultiDictObject *md) { - _Multidict_ViewObject *mv = PyObject_GC_New( - _Multidict_ViewObject, md->state->ItemsViewType); + _Multidict_ViewObject *mv = + PyObject_GC_New(_Multidict_ViewObject, md->state->ItemsViewType); if (mv == NULL) { return NULL; } @@ -183,7 +179,8 @@ multidict_itemsview_repr(_Multidict_ViewObject *self) if (tmp > 0) { return PyUnicode_FromString("..."); } - PyObject *name = PyObject_GetAttrString((PyObject*)Py_TYPE(self), "__name__"); + PyObject *name = + PyObject_GetAttrString((PyObject *)Py_TYPE(self), "__name__"); if (name == NULL) { Py_ReprLeave((PyObject *)self); return NULL; @@ -238,7 +235,7 @@ _multidict_itemsview_parse_item(_Multidict_ViewObject *self, PyObject *arg, } static inline int -_set_add(PyObject *set, PyObject *key, PyObject * value) +_set_add(PyObject *set, PyObject *key, PyObject *value) { PyObject *tpl = PyTuple_Pack(2, key, value); if (tpl == NULL) { @@ -274,8 +271,8 @@ multidict_itemsview_and1(_Multidict_ViewObject *self, PyObject *other) goto fail; } while ((arg = PyIter_Next(iter))) { - int tmp = _multidict_itemsview_parse_item(self, arg, - &identity, &key, &value); + int tmp = _multidict_itemsview_parse_item( + self, arg, &identity, &key, &value); if (tmp < 0) { goto fail; } else if (tmp == 0) { @@ -352,8 +349,8 @@ multidict_itemsview_and2(_Multidict_ViewObject *self, PyObject *other) goto fail; } while ((arg = PyIter_Next(iter))) { - int tmp = _multidict_itemsview_parse_item(self, arg, - &identity, &key, &value); + int tmp = _multidict_itemsview_parse_item( + self, arg, &identity, &key, &value); if (tmp < 0) { goto fail; } else if (tmp == 0) { @@ -407,7 +404,7 @@ multidict_itemsview_and2(_Multidict_ViewObject *self, PyObject *other) static inline PyObject * multidict_itemsview_and(PyObject *lft, PyObject *rht) { - mod_state * state; + mod_state *state; int tmp = get_mod_state_by_def_checked(lft, &state); if (tmp < 0) { return NULL; @@ -452,8 +449,8 @@ multidict_itemsview_or1(_Multidict_ViewObject *self, PyObject *other) goto fail; } while ((arg = PyIter_Next(iter))) { - int tmp = _multidict_itemsview_parse_item(self, arg, - &identity, &key, &value); + int tmp = _multidict_itemsview_parse_item( + self, arg, &identity, &key, &value); if (tmp < 0) { goto fail; } else if (tmp == 0) { @@ -539,8 +536,8 @@ multidict_itemsview_or2(_Multidict_ViewObject *self, PyObject *other) goto fail; } while ((arg = PyIter_Next(iter))) { - int tmp = _multidict_itemsview_parse_item(self, arg, - &identity, NULL, &value); + int tmp = _multidict_itemsview_parse_item( + self, arg, &identity, NULL, &value); if (tmp < 0) { goto fail; } else if (tmp > 0) { @@ -598,7 +595,7 @@ multidict_itemsview_or2(_Multidict_ViewObject *self, PyObject *other) static inline PyObject * multidict_itemsview_or(PyObject *lft, PyObject *rht) { - mod_state * state; + mod_state *state; int tmp = get_mod_state_by_def_checked(lft, &state); if (tmp < 0) { return NULL; @@ -619,7 +616,6 @@ multidict_itemsview_or(PyObject *lft, PyObject *rht) Py_RETURN_NOTIMPLEMENTED; } - static inline PyObject * multidict_itemsview_sub1(_Multidict_ViewObject *self, PyObject *other) { @@ -649,8 +645,8 @@ multidict_itemsview_sub1(_Multidict_ViewObject *self, PyObject *other) goto fail; } while ((arg = PyIter_Next(iter))) { - int tmp = _multidict_itemsview_parse_item(self, arg, - &identity, NULL, &value); + int tmp = _multidict_itemsview_parse_item( + self, arg, &identity, NULL, &value); if (tmp < 0) { goto fail; } else if (tmp > 0) { @@ -729,8 +725,8 @@ multidict_itemsview_sub2(_Multidict_ViewObject *self, PyObject *other) goto fail; } while ((arg = PyIter_Next(iter))) { - int tmp = _multidict_itemsview_parse_item(self, arg, - &identity, NULL, &value); + int tmp = _multidict_itemsview_parse_item( + self, arg, &identity, NULL, &value); if (tmp < 0) { goto fail; } else if (tmp == 0) { @@ -757,7 +753,7 @@ multidict_itemsview_sub2(_Multidict_ViewObject *self, PyObject *other) } Py_CLEAR(value2); } - if (tmp < 0 ) { + if (tmp < 0) { goto fail; } else if (tmp == 0) { if (PySet_Add(ret, arg) < 0) { @@ -789,7 +785,7 @@ multidict_itemsview_sub2(_Multidict_ViewObject *self, PyObject *other) static inline PyObject * multidict_itemsview_sub(PyObject *lft, PyObject *rht) { - mod_state * state; + mod_state *state; int tmp = get_mod_state_by_def_checked(lft, &state); if (tmp < 0) { return NULL; @@ -813,7 +809,7 @@ multidict_itemsview_sub(PyObject *lft, PyObject *rht) static inline PyObject * multidict_itemsview_xor(_Multidict_ViewObject *self, PyObject *other) { - mod_state * state; + mod_state *state; int tmp = get_mod_state_by_def_checked((PyObject *)self, &state); if (tmp < 0) { return NULL; @@ -942,7 +938,7 @@ multidict_itemsview_contains(_Multidict_ViewObject *self, PyObject *obj) goto done; } - done: +done: md_finder_cleanup(&finder); Py_CLEAR(identity); Py_CLEAR(key); @@ -965,8 +961,8 @@ multidict_itemsview_isdisjoint(_Multidict_ViewObject *self, PyObject *other) PyObject *value2 = NULL; while ((arg = PyIter_Next(iter))) { - int tmp = _multidict_itemsview_parse_item(self, arg, - &identity, NULL, &value); + int tmp = _multidict_itemsview_parse_item( + self, arg, &identity, NULL, &value); if (tmp < 0) { goto fail; } else if (tmp == 0) { @@ -1022,18 +1018,21 @@ multidict_itemsview_isdisjoint(_Multidict_ViewObject *self, PyObject *other) PyDoc_STRVAR(itemsview_isdisjoint_doc, "Return True if two sets have a null intersection."); - static PyMethodDef multidict_itemsview_methods[] = { - {"isdisjoint", (PyCFunction)multidict_itemsview_isdisjoint, - METH_O, itemsview_isdisjoint_doc}, - {NULL, NULL} /* sentinel */ + {"isdisjoint", + (PyCFunction)multidict_itemsview_isdisjoint, + METH_O, + itemsview_isdisjoint_doc}, + {NULL, NULL} /* sentinel */ }; static inline PyObject * -multidict_view_forbidden_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +multidict_view_forbidden_new(PyTypeObject *type, PyObject *args, + PyObject *kwargs) { PyErr_Format(PyExc_TypeError, - "cannot create '%s' instances directly", type->tp_name); + "cannot create '%s' instances directly", + type->tp_name); return NULL; } @@ -1068,14 +1067,13 @@ static PyType_Spec multidict_itemsview_spec = { .slots = multidict_itemsview_slots, }; - /********** Keys **********/ static inline PyObject * multidict_keysview_new(MultiDictObject *md) { - _Multidict_ViewObject *mv = PyObject_GC_New( - _Multidict_ViewObject, md->state->KeysViewType); + _Multidict_ViewObject *mv = + PyObject_GC_New(_Multidict_ViewObject, md->state->KeysViewType); if (mv == NULL) { return NULL; } @@ -1095,7 +1093,8 @@ multidict_keysview_iter(_Multidict_ViewObject *self) static inline PyObject * multidict_keysview_repr(_Multidict_ViewObject *self) { - PyObject *name = PyObject_GetAttrString((PyObject*)Py_TYPE(self), "__name__"); + PyObject *name = + PyObject_GetAttrString((PyObject *)Py_TYPE(self), "__name__"); if (name == NULL) { return NULL; } @@ -1200,7 +1199,7 @@ multidict_keysview_and2(_Multidict_ViewObject *self, PyObject *other) static inline PyObject * multidict_keysview_and(PyObject *lft, PyObject *rht) { - mod_state * state; + mod_state *state; int tmp = get_mod_state_by_def_checked(lft, &state); if (tmp < 0) { return NULL; @@ -1349,7 +1348,7 @@ multidict_keysview_or2(_Multidict_ViewObject *self, PyObject *other) static inline PyObject * multidict_keysview_or(PyObject *lft, PyObject *rht) { - mod_state * state; + mod_state *state; int tmp = get_mod_state_by_def_checked(lft, &state); if (tmp < 0) { return NULL; @@ -1468,7 +1467,7 @@ multidict_keysview_sub2(_Multidict_ViewObject *self, PyObject *other) static inline PyObject * multidict_keysview_sub(PyObject *lft, PyObject *rht) { - mod_state * state; + mod_state *state; int tmp = get_mod_state_by_def_checked(lft, &state); if (tmp < 0) { return NULL; @@ -1492,7 +1491,7 @@ multidict_keysview_sub(PyObject *lft, PyObject *rht) static inline PyObject * multidict_keysview_xor(_Multidict_ViewObject *self, PyObject *other) { - mod_state * state; + mod_state *state; int tmp = get_mod_state_by_def_checked((PyObject *)self, &state); if (tmp < 0) { return NULL; @@ -1585,11 +1584,12 @@ multidict_keysview_isdisjoint(_Multidict_ViewObject *self, PyObject *other) PyDoc_STRVAR(keysview_isdisjoint_doc, "Return True if two sets have a null intersection."); - static PyMethodDef multidict_keysview_methods[] = { - {"isdisjoint", (PyCFunction)multidict_keysview_isdisjoint, - METH_O, keysview_isdisjoint_doc}, - {NULL, NULL} /* sentinel */ + {"isdisjoint", + (PyCFunction)multidict_keysview_isdisjoint, + METH_O, + keysview_isdisjoint_doc}, + {NULL, NULL} /* sentinel */ }; static PyType_Slot multidict_keysview_slots[] = { @@ -1628,8 +1628,8 @@ static PyType_Spec multidict_keysview_spec = { static inline PyObject * multidict_valuesview_new(MultiDictObject *md) { - _Multidict_ViewObject *mv = PyObject_GC_New( - _Multidict_ViewObject, md->state->ValuesViewType); + _Multidict_ViewObject *mv = + PyObject_GC_New(_Multidict_ViewObject, md->state->ValuesViewType); if (mv == NULL) { return NULL; } @@ -1656,7 +1656,8 @@ multidict_valuesview_repr(_Multidict_ViewObject *self) if (tmp > 0) { return PyUnicode_FromString("..."); } - PyObject *name = PyObject_GetAttrString((PyObject*)Py_TYPE(self), "__name__"); + PyObject *name = + PyObject_GetAttrString((PyObject *)Py_TYPE(self), "__name__"); if (name == NULL) { Py_ReprLeave((PyObject *)self); return NULL; @@ -1691,11 +1692,10 @@ static PyType_Spec multidict_valuesview_spec = { .slots = multidict_valuesview_slots, }; - static inline int multidict_views_init(PyObject *module, mod_state *state) { - PyObject * tmp; + PyObject *tmp; tmp = PyType_FromModuleAndSpec(module, &multidict_itemsview_spec, NULL); if (tmp == NULL) { return -1; diff --git a/tests/test_circular_imports.py b/tests/test_circular_imports.py index f6ea323ee..75741388b 100644 --- a/tests/test_circular_imports.py +++ b/tests/test_circular_imports.py @@ -82,8 +82,10 @@ def test_no_warnings(import_path: str) -> None: # fmt: off sys.executable, "-I", - "-W", "error", - "-c", f"import {import_path!s}", + "-W", + "error", + "-c", + f"import {import_path!s}", # fmt: on ) @@ -99,8 +101,10 @@ def test_c_extension_preferred_by_default(monkeypatch: pytest.MonkeyPatch) -> No # fmt: off sys.executable, "-I", - "-W", "error", - "-c", "import multidict; raise SystemExit(int(" + "-W", + "error", + "-c", + "import multidict; raise SystemExit(int(" "multidict.istr.__module__ != 'multidict._multidict' " "or multidict.USE_EXTENSIONS is not True))", # fmt: on diff --git a/tests/test_mutable_multidict.py b/tests/test_mutable_multidict.py index 92bc95a04..671ba7130 100644 --- a/tests/test_mutable_multidict.py +++ b/tests/test_mutable_multidict.py @@ -34,8 +34,7 @@ def test__repr__( d = case_sensitive_multidict_class([("key", "one"), ("key", "two")]) expected = ( - f"<{case_sensitive_multidict_class.__name__}" - "('key': 'one', 'key': 'two')>" + f"<{case_sensitive_multidict_class.__name__}('key': 'one', 'key': 'two')>" ) assert str(d) == expected @@ -494,8 +493,7 @@ def test__repr__( d = case_insensitive_multidict_class([("KEY", "one"), ("KEY", "two")]) expected = ( - f"<{case_insensitive_multidict_class.__name__}" - "('KEY': 'one', 'KEY': 'two')>" + f"<{case_insensitive_multidict_class.__name__}('KEY': 'one', 'KEY': 'two')>" ) assert str(d) == expected diff --git a/tests/test_types.py b/tests/test_types.py index 6339006b6..65f83f66a 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -75,8 +75,7 @@ def test_create_cimultidict_proxy_from_nonmultidict( with pytest.raises( TypeError, match=( - "ctor requires CIMultiDict or CIMultiDictProxy instance, " - "not " + "ctor requires CIMultiDict or CIMultiDictProxy instance, not " ), ): multidict_module.CIMultiDictProxy({})