Qt 6.x
The Qt SDK
Loading...
Searching...
No Matches
qjsnumbercoercion.h
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#ifndef QJSNUMBERCOERCION_H
5#define QJSNUMBERCOERCION_H
6
7#include <QtCore/qglobal.h>
8#include <cstring>
9
11
13{
14public:
15 static constexpr bool isInteger(double d) {
16 return equals(d, d) && equals(static_cast<int>(d), d);
17 }
18
19 static constexpr int toInteger(double d) {
20 if (!equals(d, d))
21 return 0;
22
23 const int i = static_cast<int>(d);
24 if (equals(i, d))
25 return i;
26
28 }
29
30 static constexpr bool equals(double lhs, double rhs)
31 {
34 return lhs == rhs;
36 }
37
38private:
39 constexpr QJSNumberCoercion(double dbl)
40 {
41 // the dbl == 0 path is guaranteed constexpr. The other one may or may not be, depending
42 // on whether and how the compiler inlines the memcpy.
43 // In order to declare the ctor constexpr we need one guaranteed constexpr path.
44 if (!equals(dbl, 0))
45 memcpy(&d, &dbl, sizeof(double));
46 }
47
48 constexpr int sign() const
49 {
50 return (d >> 63) ? -1 : 1;
51 }
52
53 constexpr bool isDenormal() const
54 {
55 return static_cast<int>((d << 1) >> 53) == 0;
56 }
57
58 constexpr int exponent() const
59 {
60 return static_cast<int>((d << 1) >> 53) - 1023;
61 }
62
63 constexpr quint64 significant() const
64 {
65 quint64 m = (d << 12) >> 12;
66 if (!isDenormal())
67 m |= (static_cast<quint64>(1) << 52);
68 return m;
69 }
70
71 constexpr int toInteger()
72 {
73 int e = exponent() - 52;
74 if (e < 0) {
75 if (e <= -53)
76 return 0;
77 return sign() * static_cast<int>(significant() >> -e);
78 } else {
79 if (e > 31)
80 return 0;
81 return sign() * (static_cast<int>(significant()) << e);
82 }
83 }
84
85 quint64 d = 0;
86};
87
89
90#endif // QJSNUMBERCOERCION_H
Implements the JavaScript double-to-int coercion.
static constexpr bool equals(double lhs, double rhs)
static constexpr int toInteger(double d)
static constexpr bool isInteger(double d)
double e
Combined button and popup list for selecting options.
#define QT_WARNING_POP
#define QT_WARNING_DISABLE_FLOAT_COMPARE
#define QT_WARNING_PUSH
const GLfloat * m
GLint * exponent
unsigned long long quint64
Definition qtypes.h:56