Debian Codegraph @

tests/minimext/calculate.c

raw symbols SCIP
1 // Copyright (C) 2024 Stewart Miles
2 // Licensed to the Python Software Foundation under a contributor agreement.
3 // See LICENSE.txt and CONTRIBUTORS.txt.
4
5 // Use the limited API to ensure ABI compatibility across all major Python
6 // versions starting from 3.2
7 // https://docs.python.org/3/c-api/stable.html#limited-c-api
8 #if !defined(Py_LIMITED_API)
9 #define Py_LIMITED_API 3
10 #endif // !defined(Py_LIMITED_API)
11 #define PY_SSIZE_T_CLEAN
12 #include <Python.h>
13
14 // Name and doc string for this module.
15 #define MODULE_NAME calculate
16 #define MODULE_DOCS "Calculates Fibonacci numbers."
17
18 // Convert the argument into a string.
19 #define _STRINGIFY(x) #x
20 #define STRINGIFY(x) _STRINGIFY(x)
21
22 // Calculate a Fibonacci number at the specified index of the sequence.
23 static PyObject *fib(PyObject *self, PyObject *args)
24 {
25 long int index;
26 if (!PyArg_ParseTuple(args, "l", &index)) {
27 PyErr_SetString(PyExc_ValueError, "An index must be specified.");
28 }
29
30 long int current_value = 1;
31 long int previous_value = 0;
32 index--;
33 for ( ; index > 0 ; --index) {
34 long int next_value = current_value + previous_value;
35 previous_value = current_value;
36 current_value = next_value;
37 }
38 return PyLong_FromLong(current_value);
39 }
40
41 // Exposes methods in this module.
42 static PyMethodDef methods[] =
43 {
44 {
45 "fib",
46 fib,
47 METH_VARARGS,
48 PyDoc_STR("Calculate a Fibonacci number.\n"
49 "\n"
50 ":param index: Index of the number in the Fibonacci sequence\n"
51 " to calculate.\n"
52 "\n"
53 ":returns: Fibonacci number at the specified index.\n"
54 " For example an index of 7 will return 13\n"),
55 },
56 };
57
58 #if PY_MAJOR_VERSION >= 3
59 // Defines the module.
60 static struct PyModuleDef module =
61 {
62 PyModuleDef_HEAD_INIT,
63 STRINGIFY(MODULE_NAME),
64 PyDoc_STR(MODULE_DOCS),
65 -1,
66 methods,
67 };
68 #endif // PY_MAJOR_VERSION >= 3
69
70 // Expands to the init function name.
71 #define _PYINIT_FUNCTION_NAME(prefix, name) prefix ## name
72 #define PYINIT_FUNCTION_NAME(prefix, name) _PYINIT_FUNCTION_NAME(prefix, name)
73
74 // Initialize this module.
75 #if PY_MAJOR_VERSION >= 3
76 PyMODINIT_FUNC
77 PYINIT_FUNCTION_NAME(PyInit_, MODULE_NAME)(void)
78 {
79 return PyModule_Create(&module);
80 }
81 #else
82 PyMODINIT_FUNC
83 PYINIT_FUNCTION_NAME(init, MODULE_NAME)(void)
84 {
85 // Ignore the returned module object.
86 (void)Py_InitModule(STRINGIFY(MODULE_NAME), methods);
87 }
88 #endif // PY_MAJOR_VERSION >= 3