source: cpp/frams/vm/classes/collectionobj.cpp @ 1254

Last change on this file since 1254 was 1158, checked in by Maciej Komosinski, 3 years ago

Cosmetic/minor improvements

  • Property svn:eol-style set to native
File size: 20.0 KB
RevLine 
[286]1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
[1130]2// Copyright (C) 1999-2021  Maciej Komosinski and Szymon Ulatowski.
[286]3// See LICENSE.txt for details.
[109]4
5#include "collectionobj.h"
6#include <common/nonstd_math.h> //sqrt in borland
[375]7#include <frams/util/validitychecks.h>
[1130]8#include <algorithm>
[109]9#include <frams/util/sstringutils.h>
10#ifndef NO_VMACHINE
11#include <frams/vm/vmachine.h>
12#endif
13
14#define FIELDSTRUCT VectorObject
[746]15ParamEntry vector_paramtab[] =
[109]16{
[746]17        { "Vector", 1, 15, "Vector", "Vector is a 1-dimensional array indexed by an integer value (starting from 0). "
18        "Multidimensional arrays can be simulated by putting other Vector objects into a Vector.\n"
19        "Examples:\n"
20        "\tvar v1=Vector.new();\n"
21        "\tv1.add(123);\n"
22        "\tv1.add(\"string\");\n"
23        "A short way of doing the same (square brackets create a vector):\n"
24        "\tvar v2=[123,\"string\"];\n"
25        "Simulate a 2D array:\n"
26        "\tvar v3=[[1,2,3],[4,5],[6]];\n"
27        "You can iterate directly over values of a Vector using for(...in...) loops:\n"
28        "\tfor(var element in v3) Simulator.print(element);"
29        },
30        { "clear", 0, PARAM_NOSTATIC, "Clear data", "p()", PROCEDURE(p_clear), },
31        { "size", 0, PARAM_READONLY | PARAM_NOSTATIC, "Element count", "d", GETONLY(size), },
32        { "remove", 0, PARAM_NOSTATIC, "Remove at position", "p(d position)", PROCEDURE(p_remove), },
[1158]33        { "get", 0, PARAM_READONLY | PARAM_NOSTATIC, "Get value at position", "p x(d position)", PROCEDURE(p_get), "object[position] can be always used instead of object.get(position)" },
[746]34        { "set", 0, PARAM_NOSTATIC, "Set value at position", "p(d position,x value)", PROCEDURE(p_set), "object[position]=value can be always used instead of object.set(position,value)" },
35        { "insert", 0, PARAM_NOSTATIC, "Insert value at position", "p(d position,x value)", PROCEDURE(p_insert), },
36        { "add", 0, PARAM_NOSTATIC, "Append at the end", "p(x value)", PROCEDURE(p_add), },
[1158]37        { "find", 0, PARAM_READONLY | PARAM_NOSTATIC, "Find", "p d(x value)", PROCEDURE(p_find), "returns the element index or -1 if not found" },
[1076]38        { "avg", 0, PARAM_READONLY | PARAM_NOSTATIC, "Average", "x", GETONLY(avg) },
39        { "stdev", 0, PARAM_READONLY | PARAM_NOSTATIC, "Standard deviation", "x", GETONLY(stdev), "=sqrt(sum((element[i]-avg)^2)/(size-1)) which is estimated population std.dev. from sample std.dev." },
[746]40        { "toString", 0, PARAM_READONLY | PARAM_NOSTATIC, "Textual form", "s", GETONLY(toString), },
41        { "new", 0, 0, "Create new Vector", "p oVector()", STATICPROCEDURE(p_new), },
42        { "sort", 0, PARAM_NOSTATIC, "Sort elements (in place)", "p(oFunctionReference comparator)", PROCEDURE(p_sort), "comparator can be null, giving the \"natural\" sorting order (depending on element type), otherwise it must be a function reference obtained from the 'function' operator.\n\nExample:\nfunction compareLastDigit(a,b) {return (a%10)<(b%10);}\nvar v=[16,23,35,42,54,61];\nv.sort(function compareLastDigit);" },
43        { "iterator", 0, PARAM_NOSTATIC | PARAM_READONLY, "Iterator", "o", GETONLY(iterator), },
[1158]44        { "clone", 0, PARAM_READONLY | PARAM_NOSTATIC, "Create a clone", "p oVector()", PROCEDURE(p_clone), "The resulting clone is a shallow copy (contains the same object references as the original). A deep copy can be obtained through serialization: String.deserialize(String.serialize(object));" },
[746]45        { 0, 0, 0, },
[109]46};
47#undef FIELDSTRUCT
48
49#define FIELDSTRUCT DictionaryObject
[746]50ParamEntry dictionary_paramtab[] =
[109]51{
[868]52        { "Dictionary", 1, 14, "Dictionary", "Dictionary associates stored values with string keys "
[746]53        "(\"key\" is the first argument in get/set/remove functions). Integer key can be "
54        "used to enumerate all elements (note that while iterating, the elements are returned in no particular order).\n"
55        "Examples:\n"
56        "\tvar d;\n"
57        "\td=Dictionary.new();\n"
58        "\td.set(\"name\",\"John\");\n"
59        "\td.set(\"age\",44);\n"
60        "Another way of doing the same:\n"
61        "\td={};\n"
62        "\td[\"name\"]=\"John\";\n"
63        "\td[\"age\"]=44;\n"
64        "And the most concise way:\n"
65        "\td={ \"name\":\"John\", \"age\":44 };\n"
66        "Iterating:\n"
[868]67        "\tfor(var v in d) Simulator.print(v); //values\n"
68        "\tfor(var k in d.keys) Simulator.print(k+\" is \"+d[k]); //keys\n"
69        "\tfor(var i=0;i<d.size;i++) Simulator.print(d.getKey(i)+\" is \"+d.get(i)); //by index",
[746]70        },
71        { "clear", 0, PARAM_NOSTATIC, "Clear data", "p()", PROCEDURE(p_clear), },
72        { "size", 0, PARAM_NOSTATIC | PARAM_READONLY, "Element count", "d", GETONLY(size), },
73        { "remove", 0, PARAM_NOSTATIC, "Remove", "p(x key)", PROCEDURE(p_remove), "Removes the named or indexed element (depending on the argument type: string or int)." },
[1158]74        { "get", 0, PARAM_READONLY | PARAM_NOSTATIC, "Get element", "p x(x key)", PROCEDURE(p_get), "Retrieves the named or indexed element (depending on the argument type: string or int). Accessing nonexistent keys is an error (use hasKey() if necessary).\nobject.get(key) can be shortened to object[key]." },
75        { "getKey", 0, PARAM_READONLY | PARAM_NOSTATIC, "Get a key", "p s(d index)", PROCEDURE(p_getKey), "Returns the key of the indexed element (0 <= index < size)." },
76        { "hasKey", 0, PARAM_READONLY | PARAM_NOSTATIC, "Check if key exists", "p d(s key)", PROCEDURE(p_hasKey), "Returns 1 (interpreted as true) if dictionary contains the supplied key, or 0 (false) otherwise.\nExample:\n   if (obj.hasKey(\"a\"))\n      x = obj->a;" },
[746]77        { "set", 0, PARAM_NOSTATIC, "Set element", "p x(x key,x value)", PROCEDURE(p_set), "Set element value for the specified key or index (depending on the argument type: string or int).\n"
78        "Returns the value previously associated with the given key (or index).\n"
79        "object.set(key,value) can be shortened to object[key]=value. Literal string keys can use even shorter notation: object->key=value instead of object.set(\"key\",value)\n"
80        "Note the difference in the returned value:\n"
81        "  var old_value=object.set(\"key\",new_value); //'old_value' gets the value previously associated with \"key\"\n"
82        "  var x=object[\"key\"]=new_value; //'x' becomes 'new_value', consistently with the semantics of the assignment operator. The value previously associated with \"key\" is lost." },
[1158]83        { "find", 0, PARAM_READONLY | PARAM_NOSTATIC, "Find", "p x(x value)", PROCEDURE(p_find), "Returns the element key or null if not found." },
[746]84        { "new", 0, 0, "Create a Dictionary", "p oDictionary()", STATICPROCEDURE(p_new), "Empty directory can be also created using the {} expression." },
85        { "toString", 0, PARAM_READONLY | PARAM_NOSTATIC, "Textual form", "s", GETONLY(toString), },
[1158]86        { "clone", 0, PARAM_READONLY | PARAM_NOSTATIC, "Create a clone", "p oDictionary()", PROCEDURE(p_clone), "The resulting clone is a shallow copy (contains the same object references as the original). A deep copy can be obtained through serialization: String.deserialize(String.serialize(object));" },
[746]87        { "assign", 0, PARAM_NOSTATIC, "Assign from another object", "p(x)", PROCEDURE(p_assign), "Replaces current dictionary with dictionary contents from another object." },
[868]88        { "iterator", 0, PARAM_NOSTATIC | PARAM_READONLY, "Iterator", "o", GETONLY(iterator), },
89        { "keys", 0, PARAM_NOSTATIC | PARAM_READONLY, "Keys", "o", GETONLY(keys), "Iterate over this object to get all keys: for(k in dict.keys) ..." },
[478]90
[746]91        { 0, 0, 0, },
[109]92};
93#undef FIELDSTRUCT
94
95Param VectorObject::par(vector_paramtab);
96Param DictionaryObject::par(dictionary_paramtab);
97
98/////////////////////////////////////////
99
100VectorObject::VectorObject(Pt3D &pt)
[1158]101        :owndata(1)
[109]102{
[746]103        set_or_insert(0, ExtValue(pt.x), false);
104        set_or_insert(1, ExtValue(pt.y), false);
105        set_or_insert(2, ExtValue(pt.z), false);
[109]106}
107
108void VectorObject::clear()
109{
[746]110        if (owndata)
111                for (int i = data.size() - 1; i >= 0; i--)
112                {
[849]113                        ExtValue *v = (ExtValue*)data.get(i);
114                        if (v) delete v;
[746]115                }
116        data.clear();
[109]117}
118
119void VectorObject::p_remove(PARAMPROCARGS)
120{
[746]121        int i = args->getInt();
122        if (!listIndexCheck(&data, i, "VectorObject", "remove")) return;
123        ExtValue *v = (ExtValue*)data.get(i);
124        if (v) delete v;
125        data -= i;
[109]126}
127
[746]128void VectorObject::set_or_insert(int i, const ExtValue& val, bool insert)
[109]129{
[746]130        if (i < 0) return;
131        int oldsize = data.size();
132        if (i > oldsize)
[109]133        {
[746]134                data.setSize(i);
135                while (i > oldsize)
136                        data.set(oldsize++, 0);
[109]137        }
[746]138        if (insert)
139                data.insert(i, new ExtValue(val));
140        else
[642]141        {
[746]142                ExtValue *v = (ExtValue*)data.get(i);
143                if (v) delete v;
144                data.set(i, new ExtValue(val));
[642]145        }
[109]146}
147
148void VectorObject::p_get(PARAMPROCARGS)
149{
[746]150        int i = args->getInt();
151        if (listIndexCheck(&data, i, "VectorObject", "get"))
[109]152        {
[746]153                ExtValue *v = get(i);
154                if (v)
[109]155                {
[746]156                        *ret = *v;
157                        return;
[109]158                }
159        }
[746]160        *ret = ExtValue();
[109]161}
162
163void VectorObject::get_avg(ExtValue* ret)
164{
[746]165        if (!data.size()) { ret->setEmpty(); return; }
166        double s = 0.0;
167        for (int i = data.size() - 1; i >= 0; i--)
168                s += ((ExtValue*)data.get(i))->getDouble();
169        s /= data.size();
170        ret->setDouble(s);
[109]171}
172
[464]173SString VectorObject::serialize(SerializationFormat format) const
[109]174{
[746]175        SString out = "[";
[109]176        {
[746]177                for (int i = 0; i < data.size(); i++)
[109]178                {
[746]179                        ExtValue* v = (ExtValue*)data.get(i);
180                        if (i) out += ",";
181                        if (v)
182                                out += v->serialize(format);
183                        else
184                                out += "null";
[109]185                }
186        }
[746]187        out += "]";
188        //sprintf(out.directAppend(20),"<Vector@%p>",this);out.endAppend();
189        return out;
[109]190}
191
[746]192static THREAD_LOCAL_DEF(SList, VectorObject_tostring_trace);
[109]193
194void VectorObject::get_toString(ExtValue* ret)
195{
[746]196        SString out = "[";
197        //static SListTempl<VectorObject*> trace;
198        if (tlsGetRef(VectorObject_tostring_trace).find(this) >= 0)
199                out += "...";
200        else
[109]201        {
[746]202                tlsGetRef(VectorObject_tostring_trace) += this;
203                for (int i = 0; i < data.size(); i++)
[109]204                {
[746]205                        ExtValue* v = (ExtValue*)data.get(i);
206                        if (i) out += ",";
207                        if (v)
208                                out += v->getString();
209                        else
210                                out += "null";
[109]211                }
[746]212                tlsGetRef(VectorObject_tostring_trace) -= this;
[109]213        }
[746]214        out += "]";
215        ret->setString(out);
[109]216}
217
218void VectorObject::get_stdev(ExtValue* ret)
219{
[746]220        if (!data.size()) { ret->setEmpty(); return; }
221        get_avg(ret);
222        double a = ret->getDouble();
223        double s = 0.0;
224        for (int i = data.size() - 1; i >= 0; i--)
[109]225        {
[746]226                double d = a - ((ExtValue*)data.get(i))->getDouble();
[849]227                s += d * d;
[109]228        }
[1130]229        ret->setDouble(sqrt(s / std::max(1, data.size() - 1)));
[109]230}
231
232void VectorObject::p_find(PARAMPROCARGS)
233{
[746]234        short i;
235        for (i = 0; i < data.size(); i++)
[109]236        {
[746]237                if ((*args) == (*get(i)))
238                {
239                        ret->setInt(i); return;
240                }
[109]241        }
[746]242        ret->setInt(-1);
[109]243}
244
[453]245void VectorObject::p_clone(PARAMPROCARGS)
246{
[746]247        VectorObject *c = new VectorObject;
248        c->data.setSize(data.size());
249        for (int i = 0; i < data.size(); i++)
[453]250        {
[746]251                ExtValue *v = (ExtValue*)get(i);
252                if (v)
253                        c->data.set(i, new ExtValue(*v));
[453]254        }
[746]255        ret->setObject(ExtObject(&par, c));
[453]256}
257
[109]258class VEComparator
259{
260public:
[746]261        bool operator()(const ExtValue *a, const ExtValue *b) { return a->compare(*b) == ExtValue::ResultLower; }
[109]262};
263
264#ifndef NO_VMACHINE
265class VMVEComparator
266{
267public:
[746]268        VMachine::JumpTargetObject *jto;
269        VMachine *vm;
270        VMVEComparator(VMachine::JumpTargetObject *_jto) :jto(_jto), vm(jto->vm) {}
[1158]271#ifdef QSORT_R_THIS_FIRST
[931]272        static int compare(void* _this, const void *a, const void *b);
[1041]273        bool operator()(const ExtValue *a, const ExtValue *b) { return compare(this,&a,&b) == ExtValue::ResultLower; }
[931]274#else
[930]275        static int compare(const void *a, const void *b, void* _this);
[1041]276        bool operator()(const ExtValue *a, const ExtValue *b) { return compare(&a,&b,this) == ExtValue::ResultLower; }
[931]277#endif
[109]278};
279
[1158]280#ifdef QSORT_R_THIS_FIRST
[931]281int VMVEComparator::compare(void* _this, const void *a, const void *b)
282#else
[930]283int VMVEComparator::compare(const void *a, const void *b, void* _this)
[931]284#endif
[109]285{
[930]286        VMachine *vm = ((VMVEComparator*)_this)->vm;
287        VMachine::JumpTargetObject *jto = ((VMVEComparator*)_this)->jto;
[746]288        if (!VMCode::prepareDynamicJumpTarget(jto->pc, jto->code))
289                return false;
[109]290
[930]291        vm->push(**(const ExtValue **)a);
292        vm->push(**(const ExtValue **)b);
[746]293        vm->pushNewCallState();
294        vm->jumpDynamicJumpTarget(jto->pc);
295        vm->run();
296        vm->popCallState();
[930]297        int ret;
[746]298        ExtValue& retval = vm->getValue();
299        if (retval.type == TInvalid)
[109]300        {
[930]301                ret = 0;
[746]302                logPrintf("VectorElementComparator", "", LOG_ERROR, "Comparison function returned no value");
[109]303        }
[746]304        else
[930]305                ret = (retval.getInt() != 0) ? -1 : 1;
[746]306        vm->drop(2);
307        return ret;
[109]308}
309#endif
310
311void VectorObject::p_sort(PARAMPROCARGS)
312{
313#ifndef NO_VMACHINE
[746]314        VMachine::JumpTargetObject *jto = VMachine::JumpTargetObject::fromObject(args->getObject(), false);
315        if (jto)
[109]316        {
[746]317                VMVEComparator cmp(jto);
318                ExtValue **first = (ExtValue**)&data.getref(0);
[930]319                //Originally was the same as below: std::sort(first, first + data.size(), cmp);
320                //However, std::sort() requires "strict weak ordering" and may crash (and indeed crashes, "undefined behavior") when given a non-compliant comparator.
321                //We use qsort() instead because we can't control what kind of user script comparator function will be passed to Vector.sort(), and qsort() seems to behave safely for every function.
[1041]322#ifdef __ANDROID__
323                std::sort(first, first + data.size(), cmp); //no qsort_r() or equivalent on Android (yet)
324#else
[1158]325                CALL_QSORT_R(first, data.size(), sizeof(ExtValue*), cmp.compare, &cmp);
[1041]326#endif
[109]327        }
[746]328        else
[109]329#endif
330        {
[746]331                VEComparator cmp;
332                ExtValue **first = (ExtValue**)&data.getref(0);
333                std::sort(first, first + data.size(), cmp);
[109]334        }
[746]335        ret->setEmpty();
[109]336}
337
338void VectorObject::get_iterator(ExtValue* ret)
339{
[746]340        ret->setObject(VectorIterator::makeFrom(this));
[109]341}
342
[171]343VectorObject* VectorObject::fromObject(const ExtObject& o, bool warn)
[109]344{
[746]345        return (VectorObject*)o.getTarget(par.getName(), true, warn);
[109]346}
347
348/////////////////////////////
349
350void DictionaryObject::clear()
351{
[746]352        for (HashEntryIterator it(hash); it.isValid();)
[109]353        {
[746]354                ExtValue *v = (ExtValue*)hash.remove(it);
355                if (v) delete v;
[109]356        }
[746]357        hash.clear();
358        hash.init();
[109]359}
360
361void DictionaryObject::p_find(PARAMPROCARGS)
362{
[746]363        for (HashEntryIterator it(hash); it.isValid(); it++)
[109]364        {
[852]365                if (((ExtValue*)it->value) == NULL)
366                {
367                        if (args->getType() != TUnknown) continue;
368                        ret->setString(it->key);
369                        return;
370                }
[746]371                if ((*args) == (*((ExtValue*)it->value)))
[109]372                {
[746]373                        ret->setString(it->key);
374                        return;
[109]375                }
376        }
[746]377        ret->setEmpty();
[109]378}
379
380HashEntryIterator* DictionaryObject::getIndexIterator(int i)
381{
[746]382        if (i < 0) return 0;
383        if (i >= hash.getSize()) return 0;
[109]384
[746]385        if ((!it.isValid()) || (it_index > i))
[109]386        {
[746]387                it = HashEntryIterator(hash);
388                it_index = 0;
[109]389        }
[746]390        while (it.isValid())
[109]391        {
[746]392                if (it_index == i)
393                        return &it;
394                it_index++;
395                it++;
[109]396        }
[746]397        return 0;
[109]398}
399
400void DictionaryObject::p_remove(PARAMPROCARGS)
401{
[746]402        if ((args->type == TInt) || (args->type == TDouble))
[109]403        {
[746]404                HashEntryIterator* iter = getIndexIterator(args->getInt());
405                if (iter)
[109]406                {
[746]407                        ExtValue *oldval = (ExtValue*)hash.remove(*iter);
408                        if (oldval) { *ret = *oldval; delete oldval; }
409                        else *ret = ExtValue();
[109]410                }
411        }
[746]412        else
[109]413        {
[746]414                ExtValue *oldval = (ExtValue*)hash.remove(args[0].getString());
415                if (oldval) { *ret = *oldval; delete oldval; }
416                else *ret = ExtValue();
[109]417        }
418}
419
[478]420ExtValue DictionaryObject::get(SString key)
421{
[849]422        int found = 0;
423        ExtValue *val = (ExtValue*)hash.get(key, &found);
424        if (found == 0)
425        {
426                logPrintf("Dictionary", "get", LOG_ERROR, "Key '%s' not found", key.c_str());
427                return ExtValue::invalid();
428        }
429        else
430        {
431                if (val)
432                        return *val;
433                return ExtValue::empty();
434        }
[478]435}
436
437ExtValue DictionaryObject::get(int index)
438{
[746]439        HashEntryIterator* iter = getIndexIterator(index);
440        if (iter && (*iter)->value)
441                return *((ExtValue*)(*iter)->value);
442        return ExtValue::empty();
[478]443}
444
[109]445void DictionaryObject::p_get(PARAMPROCARGS)
446{
[746]447        if ((args->type == TInt) || (args->type == TDouble))
448                *ret = get(args->getInt());
449        else
450                *ret = get(args[0].getString());
[109]451}
452
453void DictionaryObject::p_getKey(PARAMPROCARGS)
454{
[746]455        HashEntryIterator* iter = getIndexIterator(args->getInt());
456        if (iter)
[109]457        {
[746]458                *ret = (*iter)->key;
459                return;
[109]460        }
[746]461        *ret = ExtValue();
[109]462}
463
[849]464void DictionaryObject::p_hasKey(PARAMPROCARGS)
465{
466        int found = 0;
467        hash.get(args->getString(), &found);
468        ret->setInt(found);
469}
470
[746]471ExtValue DictionaryObject::set(SString key, ExtValue new_value)
[478]472{
[746]473        ExtValue ret;
474        ExtValue *new_ext = (new_value.getType() == TUnknown) ? NULL : new ExtValue(new_value);
475        ExtValue *old_ext = (ExtValue*)hash.put(key, new_ext);
476        if (old_ext) { ret = *old_ext; delete old_ext; }
477        return ret;
[478]478}
479
[109]480void DictionaryObject::p_set(PARAMPROCARGS)
481{
[746]482        *ret = set(args[1].getString(), args[0]);
[109]483}
484
[464]485SString DictionaryObject::serialize(SerializationFormat format) const
[109]486{
[746]487        SString out = "{";
[109]488        {
[746]489                for (HashEntryIterator it(hash); it.isValid();)
[109]490                {
[746]491                        out += "\"";
492                        SString q = it->key; sstringQuote(q);
493                        out += q;
494                        out += "\":";
495                        if (it->value != NULL)
496                                out += ((ExtValue*)it->value)->serialize(format);
497                        else
498                                out += "null";
499                        it++;
500                        if (it.isValid()) out += ",";
[109]501                }
502        }
[746]503        out += "}";
504        return out;
[109]505}
506
507void DictionaryObject::get_toString(ExtValue* ret)
508{
[746]509        SString out = "{";
510        //static SListTempl<DictionaryObject*> trace;
511        if (tlsGetRef(VectorObject_tostring_trace).find(this) >= 0)
512                out += "...";
513        else
[109]514        {
[746]515                tlsGetRef(VectorObject_tostring_trace) += this;
516                for (HashEntryIterator it(hash); it.isValid();)
[109]517                {
[746]518                        out += it->key;
519                        out += ":";
520                        if (it->value != NULL)
521                                out += ((ExtValue*)it->value)->getString();
522                        else
523                                out += "null";
524                        it++;
525                        if (it.isValid()) out += ",";
[109]526                }
[746]527                tlsGetRef(VectorObject_tostring_trace) -= this;
[109]528        }
[746]529        out += "}";
530        ret->setString(out);
[109]531}
532
[478]533void DictionaryObject::copyFrom(DictionaryObject *other)
[453]534{
[746]535        for (HashEntryIterator it(other->hash); it.isValid(); it++)
[453]536        {
[746]537                ExtValue *v = (ExtValue*)it->value;
538                hash.put(it->key, v ? new ExtValue(*v) : NULL);
[453]539        }
[478]540}
541
542void DictionaryObject::p_clone(PARAMPROCARGS)
543{
[746]544        DictionaryObject *c = new DictionaryObject;
545        c->copyFrom(this);
546        ret->setObject(ExtObject(&par, c));
[453]547}
548
[478]549void DictionaryObject::p_assign(PARAMPROCARGS)
550{
[746]551        clear();
552        DictionaryObject *other = DictionaryObject::fromObject(args[0].getObject(), false);
553        if (other)
[478]554                copyFrom(other);
[746]555        ret->setEmpty();
[478]556}
557
[171]558DictionaryObject* DictionaryObject::fromObject(const ExtObject& o, bool warn)
[109]559{
[746]560        return (DictionaryObject*)o.getTarget(par.getName(), true, warn);
[109]561}
562
[868]563void DictionaryObject::get_iterator(ExtValue* ret)
564{
565        ret->setObject(DictionaryIterator::makeFrom(this));
566}
567
568void DictionaryObject::get_keys(ExtValue* ret)
569{
570        ret->setObject(DictionaryIterator::makeFrom(this));
571}
572
[109]573////////////////
574
575VectorIterator::VectorIterator(VectorObject* v)
576{
[746]577        vec = v;
578        vec->incref();
579        pos = -1;
[109]580}
581
582#define FIELDSTRUCT VectorIterator
[746]583ParamEntry vectoriterator_paramtab[] =
[109]584{
[746]585        { "VectorIterator", 1, 2, "VectorIterator", "VectorIterator" },
586        { "next", 0, PARAM_READONLY | PARAM_NOSTATIC, "next", "d 0 1", GETONLY(next), },
587        { "value", 0, PARAM_READONLY | PARAM_NOSTATIC, "value", "x", GETONLY(value), },
588        { 0, 0, 0, },
[109]589};
590#undef FIELDSTRUCT
591
592ExtObject VectorIterator::makeFrom(VectorObject *v)
593{
[746]594        static Param par(vectoriterator_paramtab);
595        return ExtObject(&par, new VectorIterator(v));
[109]596}
597
598VectorIterator::~VectorIterator()
599{
[746]600        vec->decref();
[109]601}
602
603void VectorIterator::get_next(ExtValue* ret)
604{
[746]605        pos++;
606        ret->setInt((pos < vec->data.size()) ? 1 : 0);
[109]607}
608
609void VectorIterator::get_value(ExtValue* ret)
610{
[746]611        ExtValue *v = (ExtValue*)(((pos >= 0) && (pos < vec->data.size())) ? vec->data(pos) : NULL);
612        if (v)
613                *ret = *v;
614        else
615                ret->setEmpty();
[109]616}
[490]617
[868]618/////////////////
619
620#define FIELDSTRUCT DictionaryIterator
621ParamEntry dictionaryiterator_paramtab[] =
622{
623        { "DictionaryIterator", 1, 3, "DictionaryIterator", "DictionaryIterator" },
624        { "next", 0, PARAM_READONLY | PARAM_NOSTATIC, "next", "d 0 1", GETONLY(next), },
625        { "value", 0, PARAM_READONLY | PARAM_NOSTATIC, "value", "x", GETONLY(value), },
626        { "iterator", 0, PARAM_READONLY | PARAM_NOSTATIC, "keys iterator", "x", GETONLY(iterator), },
627        { 0, 0, 0, },
628};
629#undef FIELDSTRUCT
630
631DictionaryIterator::DictionaryIterator(DictionaryObject* d, bool _keys)
632        :it(d->hash)
633{
634        dic = d;
635        dic->incref();
636        initial = true;
637        keys = _keys;
638}
639
640ExtObject DictionaryIterator::makeFrom(DictionaryObject *d, bool _keys)
641{
642        static Param par(dictionaryiterator_paramtab);
643        return ExtObject(&par, new DictionaryIterator(d, _keys));
644}
645
646DictionaryIterator::~DictionaryIterator()
647{
648        dic->decref();
649}
650
651void DictionaryIterator::get_next(ExtValue* ret)
652{
653        if (initial)
654                initial = false;
655        else
656                it++;
657        ret->setInt(it.isValid());
658}
659
660void DictionaryIterator::get_value(ExtValue* ret)
661{
662        if ((!initial) && it.isValid())
663        {
664                if (keys)
665                {
666                        ret->setString(it->key);
667                }
668                else
669                {
670                        ExtValue *v = (ExtValue*)it->value;
671                        if (v == NULL)
672                                ret->setEmpty();
673                        else
674                                *ret = *v;
675                }
676        }
677        else
678                ret->setEmpty();
679}
680
681void DictionaryIterator::get_iterator(ExtValue* ret)
682{
683        ret->setObject(makeFrom(dic, true));
684}
685
686//////////////
687
[490]688// not actually needed for deserialization (vector and dict are special cases) but findDeserializableClass can be also used in other contexts
689REGISTER_DESERIALIZABLE(VectorObject)
690REGISTER_DESERIALIZABLE(DictionaryObject)
Note: See TracBrowser for help on using the repository browser.