1// Copyright (C) 2017 Crimson AS <info@crimson.no>
2// Copyright (C) 2018 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4
5#include <private/qv4iterator_p.h>
6#include <private/qv4stringiterator_p.h>
7#include <private/qv4symbol_p.h>
8
9using namespace QV4;
10
11DEFINE_OBJECT_VTABLE(StringIteratorObject);
12
13void StringIteratorPrototype::init(ExecutionEngine *e)
14{
15 defineDefaultProperty(QStringLiteral("next"), code: method_next, argumentCount: 0);
16
17 Scope scope(e);
18 ScopedString val(scope, e->newString(s: QLatin1String("String Iterator")));
19 defineReadonlyConfigurableProperty(name: e->symbol_toStringTag(), value: val);
20}
21
22ReturnedValue StringIteratorPrototype::method_next(const FunctionObject *b, const Value *that, const Value *, int)
23{
24 Scope scope(b);
25 const StringIteratorObject *thisObject = that->as<StringIteratorObject>();
26 if (!thisObject)
27 return scope.engine->throwTypeError(message: QLatin1String("Not an String Iterator instance"));
28
29 ScopedString s(scope, thisObject->d()->iteratedString);
30 if (!s) {
31 QV4::Value undefined = Value::undefinedValue();
32 return IteratorPrototype::createIterResultObject(engine: scope.engine, value: undefined, done: true);
33 }
34
35 quint32 index = thisObject->d()->nextIndex;
36
37 QString str = s->toQString();
38 quint32 len = str.size();
39
40 if (index >= len) {
41 thisObject->d()->iteratedString.set(e: scope.engine, newVal: nullptr);
42 QV4::Value undefined = Value::undefinedValue();
43 return IteratorPrototype::createIterResultObject(engine: scope.engine, value: undefined, done: true);
44 }
45
46 QChar ch = str.at(i: index);
47 int num = 1;
48 if (ch.unicode() >= 0xd800 && ch.unicode() <= 0xdbff && index + 1 != len) {
49 ch = str.at(i: index + 1);
50 if (ch.unicode() >= 0xdc00 && ch.unicode() <= 0xdfff)
51 num = 2;
52 }
53
54 thisObject->d()->nextIndex += num;
55
56 ScopedString resultString(scope, scope.engine->newString(s: s->toQString().mid(position: index, n: num)));
57 return IteratorPrototype::createIterResultObject(engine: scope.engine, value: resultString, done: false);
58}
59
60

source code of qtdeclarative/src/qml/jsruntime/qv4stringiterator.cpp