1// Copyright (C) 2019 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 QV4STRINGTOARRAYINDEX_P_H
5#define QV4STRINGTOARRAYINDEX_P_H
6
7//
8// W A R N I N G
9// -------------
10//
11// This file is not part of the Qt API. It exists purely as an
12// implementation detail. This header file may change from version to
13// version without notice, or even be removed.
14//
15// We mean it.
16//
17
18#include <QtCore/private/qnumeric_p.h>
19#include <QtCore/qstring.h>
20#include <limits>
21
22QT_BEGIN_NAMESPACE
23
24namespace QV4 {
25
26inline uint charToUInt(const QChar *ch) { return ch->unicode(); }
27inline uint charToUInt(const char *ch) { return static_cast<unsigned char>(*ch); }
28
29template <typename T>
30uint stringToArrayIndex(const T *ch, const T *end)
31{
32 if (ch == end)
33 return std::numeric_limits<uint>::max();
34 uint i = charToUInt(ch) - '0';
35 if (i > 9)
36 return std::numeric_limits<uint>::max();
37 ++ch;
38 // reject "01", "001", ...
39 if (i == 0 && ch != end)
40 return std::numeric_limits<uint>::max();
41
42 while (ch < end) {
43 uint x = charToUInt(ch) - '0';
44 if (x > 9)
45 return std::numeric_limits<uint>::max();
46 if (qMulOverflow(v1: i, v2: uint(10), r: &i) || qAddOverflow(v1: i, v2: x, r: &i)) // i = i * 10 + x
47 return std::numeric_limits<uint>::max();
48 ++ch;
49 }
50 return i;
51}
52
53inline uint stringToArrayIndex(const QString &str)
54{
55 return stringToArrayIndex(ch: str.constData(), end: str.constData() + str.size());
56}
57
58} // namespace QV4
59
60QT_END_NAMESPACE
61
62#endif // QV4STRINGTOARRAYINDEX_P_H
63

source code of qtdeclarative/src/qml/common/qv4stringtoarrayindex_p.h