Nuitka
The Python compiler
Loading...
Searching...
No Matches
HelpersFloats.c
1// Copyright 2025, Kay Hayen, mailto:kay.hayen@gmail.com find license text at end of file
2
3/* These helpers are used to work with float values.
4
5*/
6
7// This file is included from another C file, help IDEs to still parse it on
8// its own.
9#ifdef __IDE_ONLY__
10#include "nuitka/prelude.h"
11#endif
12
13PyObject *TO_FLOAT(PyObject *value) {
14 PyObject *result;
15
16#if PYTHON_VERSION < 0x300
17 if (PyString_CheckExact(value)) {
18 result = PyFloat_FromString(value, NULL);
19 }
20#else
21 if (PyUnicode_CheckExact(value)) {
22 result = PyFloat_FromString(value);
23 }
24#endif
25 else {
26 result = PyNumber_Float(value);
27 }
28
29 if (unlikely(result == NULL)) {
30 return NULL;
31 }
32
33 return result;
34}
35
36#if NUITKA_FLOAT_HAS_FREELIST
37
38static PyFloatObject *_Nuitka_AllocatePyFloatObject(PyThreadState *tstate) {
39 // This is the CPython name, spell-checker: ignore numfree
40
41#if PYTHON_VERSION < 0x3d0
42 struct _Py_float_state *state = &tstate->interp->float_state;
43 PyFloatObject **free_list = &state->free_list;
44 int *numfree = &state->numfree;
45#else
46 struct _Py_object_freelists *freelists = _Nuitka_object_freelists_GET(tstate);
47 struct _Py_float_freelist *state = &freelists->floats;
48 PyFloatObject **free_list = &state->items;
49 int *numfree = &state->numfree;
50#endif
51 PyFloatObject *result_float = *free_list;
52
53 if (result_float) {
54 (*numfree) -= 1;
55 *free_list = (PyFloatObject *)Py_TYPE(result_float);
56 } else {
57 result_float = (PyFloatObject *)NuitkaObject_Malloc(sizeof(PyFloatObject));
58 }
59
60 Py_SET_TYPE(result_float, &PyFloat_Type);
61 Nuitka_Py_NewReference((PyObject *)result_float);
62
63 assert(result_float != NULL);
64
65 return result_float;
66}
67
68PyObject *MAKE_FLOAT_FROM_DOUBLE(double value) {
69 PyThreadState *tstate = PyThreadState_GET();
70
71 PyFloatObject *result = _Nuitka_AllocatePyFloatObject(tstate);
72
73 PyFloat_SET_DOUBLE(result, value);
74 return (PyObject *)result;
75}
76
77#endif
78
79// Part of "Nuitka", an optimizing Python compiler that is compatible and
80// integrates with CPython, but also works on its own.
81//
82// Licensed under the Apache License, Version 2.0 (the "License");
83// you may not use this file except in compliance with the License.
84// You may obtain a copy of the License at
85//
86// http://www.apache.org/licenses/LICENSE-2.0
87//
88// Unless required by applicable law or agreed to in writing, software
89// distributed under the License is distributed on an "AS IS" BASIS,
90// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
91// See the License for the specific language governing permissions and
92// limitations under the License.