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

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

Used std::min(), std::max() explicitly to avoid compiler confusion. Used std::size() explicitly instead of the equivalent macro

  • Property svn:eol-style set to native
File size: 19.9 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), },
33        { "get", 0, PARAM_NOSTATIC, "Get value at position", "p x(d position)", PROCEDURE(p_get), "object[position] can be always used instead of object.get(position)" },
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), },
37        { "find", 0, 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), },
44        { "clone", 0, 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));" },
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)." },
[858]74        { "get", 0, 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_NOSTATIC, "Get a key", "p s(d index)", PROCEDURE(p_getKey), "Returns the key of the indexed element (0 <= index < size)." },
[849]76        { "hasKey", 0, 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." },
83        { "find", 0, PARAM_NOSTATIC, "Find", "p x(x value)", PROCEDURE(p_find), "Returns the element key or null if not found." },
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), },
86        { "clone", 0, 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));" },
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)
[746]101        :readonly(0), 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        if (readonly) return;
122        int i = args->getInt();
123        if (!listIndexCheck(&data, i, "VectorObject", "remove")) return;
124        ExtValue *v = (ExtValue*)data.get(i);
125        if (v) delete v;
126        data -= i;
[109]127}
128
[746]129void VectorObject::set_or_insert(int i, const ExtValue& val, bool insert)
[109]130{
[746]131        if (i < 0) return;
132        int oldsize = data.size();
133        if (i > oldsize)
[109]134        {
[746]135                data.setSize(i);
136                while (i > oldsize)
137                        data.set(oldsize++, 0);
[109]138        }
[746]139        if (insert)
140                data.insert(i, new ExtValue(val));
141        else
[642]142        {
[746]143                ExtValue *v = (ExtValue*)data.get(i);
144                if (v) delete v;
145                data.set(i, new ExtValue(val));
[642]146        }
[109]147}
148
149void VectorObject::p_get(PARAMPROCARGS)
150{
[746]151        int i = args->getInt();
152        if (listIndexCheck(&data, i, "VectorObject", "get"))
[109]153        {
[746]154                ExtValue *v = get(i);
155                if (v)
[109]156                {
[746]157                        *ret = *v;
158                        return;
[109]159                }
160        }
[746]161        *ret = ExtValue();
[109]162}
163
164void VectorObject::get_avg(ExtValue* ret)
165{
[746]166        if (!data.size()) { ret->setEmpty(); return; }
167        double s = 0.0;
168        for (int i = data.size() - 1; i >= 0; i--)
169                s += ((ExtValue*)data.get(i))->getDouble();
170        s /= data.size();
171        ret->setDouble(s);
[109]172}
173
[464]174SString VectorObject::serialize(SerializationFormat format) const
[109]175{
[746]176        SString out = "[";
[109]177        {
[746]178                for (int i = 0; i < data.size(); i++)
[109]179                {
[746]180                        ExtValue* v = (ExtValue*)data.get(i);
181                        if (i) out += ",";
182                        if (v)
183                                out += v->serialize(format);
184                        else
185                                out += "null";
[109]186                }
187        }
[746]188        out += "]";
189        //sprintf(out.directAppend(20),"<Vector@%p>",this);out.endAppend();
190        return out;
[109]191}
192
[746]193static THREAD_LOCAL_DEF(SList, VectorObject_tostring_trace);
[109]194
195void VectorObject::get_toString(ExtValue* ret)
196{
[746]197        SString out = "[";
198        //static SListTempl<VectorObject*> trace;
199        if (tlsGetRef(VectorObject_tostring_trace).find(this) >= 0)
200                out += "...";
201        else
[109]202        {
[746]203                tlsGetRef(VectorObject_tostring_trace) += this;
204                for (int i = 0; i < data.size(); i++)
[109]205                {
[746]206                        ExtValue* v = (ExtValue*)data.get(i);
207                        if (i) out += ",";
208                        if (v)
209                                out += v->getString();
210                        else
211                                out += "null";
[109]212                }
[746]213                tlsGetRef(VectorObject_tostring_trace) -= this;
[109]214        }
[746]215        out += "]";
216        ret->setString(out);
[109]217}
218
219void VectorObject::get_stdev(ExtValue* ret)
220{
[746]221        if (!data.size()) { ret->setEmpty(); return; }
222        get_avg(ret);
223        double a = ret->getDouble();
224        double s = 0.0;
225        for (int i = data.size() - 1; i >= 0; i--)
[109]226        {
[746]227                double d = a - ((ExtValue*)data.get(i))->getDouble();
[849]228                s += d * d;
[109]229        }
[1130]230        ret->setDouble(sqrt(s / std::max(1, data.size() - 1)));
[109]231}
232
233void VectorObject::p_find(PARAMPROCARGS)
234{
[746]235        short i;
236        for (i = 0; i < data.size(); i++)
[109]237        {
[746]238                if ((*args) == (*get(i)))
239                {
240                        ret->setInt(i); return;
241                }
[109]242        }
[746]243        ret->setInt(-1);
[109]244}
245
[453]246void VectorObject::p_clone(PARAMPROCARGS)
247{
[746]248        VectorObject *c = new VectorObject;
249        c->data.setSize(data.size());
250        for (int i = 0; i < data.size(); i++)
[453]251        {
[746]252                ExtValue *v = (ExtValue*)get(i);
253                if (v)
254                        c->data.set(i, new ExtValue(*v));
[453]255        }
[746]256        ret->setObject(ExtObject(&par, c));
[453]257}
258
[109]259class VEComparator
260{
261public:
[746]262        bool operator()(const ExtValue *a, const ExtValue *b) { return a->compare(*b) == ExtValue::ResultLower; }
[109]263};
264
265#ifndef NO_VMACHINE
266class VMVEComparator
267{
268public:
[746]269        VMachine::JumpTargetObject *jto;
270        VMachine *vm;
271        VMVEComparator(VMachine::JumpTargetObject *_jto) :jto(_jto), vm(jto->vm) {}
[931]272#ifdef QSORT_R_USING_QSORT_S
273        static int compare(void* _this, const void *a, const void *b);
[1041]274        bool operator()(const ExtValue *a, const ExtValue *b) { return compare(this,&a,&b) == ExtValue::ResultLower; }
[931]275#else
[930]276        static int compare(const void *a, const void *b, void* _this);
[1041]277        bool operator()(const ExtValue *a, const ExtValue *b) { return compare(&a,&b,this) == ExtValue::ResultLower; }
[931]278#endif
[109]279};
280
[931]281#ifdef QSORT_R_USING_QSORT_S
282int VMVEComparator::compare(void* _this, const void *a, const void *b)
283#else
[930]284int VMVEComparator::compare(const void *a, const void *b, void* _this)
[931]285#endif
[109]286{
[930]287        VMachine *vm = ((VMVEComparator*)_this)->vm;
288        VMachine::JumpTargetObject *jto = ((VMVEComparator*)_this)->jto;
[746]289        if (!VMCode::prepareDynamicJumpTarget(jto->pc, jto->code))
290                return false;
[109]291
[930]292        vm->push(**(const ExtValue **)a);
293        vm->push(**(const ExtValue **)b);
[746]294        vm->pushNewCallState();
295        vm->jumpDynamicJumpTarget(jto->pc);
296        vm->run();
297        vm->popCallState();
[930]298        int ret;
[746]299        ExtValue& retval = vm->getValue();
300        if (retval.type == TInvalid)
[109]301        {
[930]302                ret = 0;
[746]303                logPrintf("VectorElementComparator", "", LOG_ERROR, "Comparison function returned no value");
[109]304        }
[746]305        else
[930]306                ret = (retval.getInt() != 0) ? -1 : 1;
[746]307        vm->drop(2);
308        return ret;
[109]309}
310#endif
311
312void VectorObject::p_sort(PARAMPROCARGS)
313{
314#ifndef NO_VMACHINE
[746]315        VMachine::JumpTargetObject *jto = VMachine::JumpTargetObject::fromObject(args->getObject(), false);
316        if (jto)
[109]317        {
[746]318                VMVEComparator cmp(jto);
319                ExtValue **first = (ExtValue**)&data.getref(0);
[930]320                //Originally was the same as below: std::sort(first, first + data.size(), cmp);
321                //However, std::sort() requires "strict weak ordering" and may crash (and indeed crashes, "undefined behavior") when given a non-compliant comparator.
322                //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]323#ifdef __ANDROID__
324                std::sort(first, first + data.size(), cmp); //no qsort_r() or equivalent on Android (yet)
325#else
[930]326                qsort_r(first, data.size(), sizeof(ExtValue*), cmp.compare, &cmp);
[1041]327#endif
[109]328        }
[746]329        else
[109]330#endif
331        {
[746]332                VEComparator cmp;
333                ExtValue **first = (ExtValue**)&data.getref(0);
334                std::sort(first, first + data.size(), cmp);
[109]335        }
[746]336        ret->setEmpty();
[109]337}
338
339void VectorObject::get_iterator(ExtValue* ret)
340{
[746]341        ret->setObject(VectorIterator::makeFrom(this));
[109]342}
343
[171]344VectorObject* VectorObject::fromObject(const ExtObject& o, bool warn)
[109]345{
[746]346        return (VectorObject*)o.getTarget(par.getName(), true, warn);
[109]347}
348
349/////////////////////////////
350
351void DictionaryObject::clear()
352{
[746]353        for (HashEntryIterator it(hash); it.isValid();)
[109]354        {
[746]355                ExtValue *v = (ExtValue*)hash.remove(it);
356                if (v) delete v;
[109]357        }
[746]358        hash.clear();
359        hash.init();
[109]360}
361
362void DictionaryObject::p_find(PARAMPROCARGS)
363{
[746]364        for (HashEntryIterator it(hash); it.isValid(); it++)
[109]365        {
[852]366                if (((ExtValue*)it->value) == NULL)
367                {
368                        if (args->getType() != TUnknown) continue;
369                        ret->setString(it->key);
370                        return;
371                }
[746]372                if ((*args) == (*((ExtValue*)it->value)))
[109]373                {
[746]374                        ret->setString(it->key);
375                        return;
[109]376                }
377        }
[746]378        ret->setEmpty();
[109]379}
380
381HashEntryIterator* DictionaryObject::getIndexIterator(int i)
382{
[746]383        if (i < 0) return 0;
384        if (i >= hash.getSize()) return 0;
[109]385
[746]386        if ((!it.isValid()) || (it_index > i))
[109]387        {
[746]388                it = HashEntryIterator(hash);
389                it_index = 0;
[109]390        }
[746]391        while (it.isValid())
[109]392        {
[746]393                if (it_index == i)
394                        return &it;
395                it_index++;
396                it++;
[109]397        }
[746]398        return 0;
[109]399}
400
401void DictionaryObject::p_remove(PARAMPROCARGS)
402{
[746]403        if ((args->type == TInt) || (args->type == TDouble))
[109]404        {
[746]405                HashEntryIterator* iter = getIndexIterator(args->getInt());
406                if (iter)
[109]407                {
[746]408                        ExtValue *oldval = (ExtValue*)hash.remove(*iter);
409                        if (oldval) { *ret = *oldval; delete oldval; }
410                        else *ret = ExtValue();
[109]411                }
412        }
[746]413        else
[109]414        {
[746]415                ExtValue *oldval = (ExtValue*)hash.remove(args[0].getString());
416                if (oldval) { *ret = *oldval; delete oldval; }
417                else *ret = ExtValue();
[109]418        }
419}
420
[478]421ExtValue DictionaryObject::get(SString key)
422{
[849]423        int found = 0;
424        ExtValue *val = (ExtValue*)hash.get(key, &found);
425        if (found == 0)
426        {
427                logPrintf("Dictionary", "get", LOG_ERROR, "Key '%s' not found", key.c_str());
428                return ExtValue::invalid();
429        }
430        else
431        {
432                if (val)
433                        return *val;
434                return ExtValue::empty();
435        }
[478]436}
437
438ExtValue DictionaryObject::get(int index)
439{
[746]440        HashEntryIterator* iter = getIndexIterator(index);
441        if (iter && (*iter)->value)
442                return *((ExtValue*)(*iter)->value);
443        return ExtValue::empty();
[478]444}
445
[109]446void DictionaryObject::p_get(PARAMPROCARGS)
447{
[746]448        if ((args->type == TInt) || (args->type == TDouble))
449                *ret = get(args->getInt());
450        else
451                *ret = get(args[0].getString());
[109]452}
453
454void DictionaryObject::p_getKey(PARAMPROCARGS)
455{
[746]456        HashEntryIterator* iter = getIndexIterator(args->getInt());
457        if (iter)
[109]458        {
[746]459                *ret = (*iter)->key;
460                return;
[109]461        }
[746]462        *ret = ExtValue();
[109]463}
464
[849]465void DictionaryObject::p_hasKey(PARAMPROCARGS)
466{
467        int found = 0;
468        hash.get(args->getString(), &found);
469        ret->setInt(found);
470}
471
[746]472ExtValue DictionaryObject::set(SString key, ExtValue new_value)
[478]473{
[746]474        ExtValue ret;
475        ExtValue *new_ext = (new_value.getType() == TUnknown) ? NULL : new ExtValue(new_value);
476        ExtValue *old_ext = (ExtValue*)hash.put(key, new_ext);
477        if (old_ext) { ret = *old_ext; delete old_ext; }
478        return ret;
[478]479}
480
[109]481void DictionaryObject::p_set(PARAMPROCARGS)
482{
[746]483        *ret = set(args[1].getString(), args[0]);
[109]484}
485
[464]486SString DictionaryObject::serialize(SerializationFormat format) const
[109]487{
[746]488        SString out = "{";
[109]489        {
[746]490                for (HashEntryIterator it(hash); it.isValid();)
[109]491                {
[746]492                        out += "\"";
493                        SString q = it->key; sstringQuote(q);
494                        out += q;
495                        out += "\":";
496                        if (it->value != NULL)
497                                out += ((ExtValue*)it->value)->serialize(format);
498                        else
499                                out += "null";
500                        it++;
501                        if (it.isValid()) out += ",";
[109]502                }
503        }
[746]504        out += "}";
505        return out;
[109]506}
507
508void DictionaryObject::get_toString(ExtValue* ret)
509{
[746]510        SString out = "{";
511        //static SListTempl<DictionaryObject*> trace;
512        if (tlsGetRef(VectorObject_tostring_trace).find(this) >= 0)
513                out += "...";
514        else
[109]515        {
[746]516                tlsGetRef(VectorObject_tostring_trace) += this;
517                for (HashEntryIterator it(hash); it.isValid();)
[109]518                {
[746]519                        out += it->key;
520                        out += ":";
521                        if (it->value != NULL)
522                                out += ((ExtValue*)it->value)->getString();
523                        else
524                                out += "null";
525                        it++;
526                        if (it.isValid()) out += ",";
[109]527                }
[746]528                tlsGetRef(VectorObject_tostring_trace) -= this;
[109]529        }
[746]530        out += "}";
531        ret->setString(out);
[109]532}
533
[478]534void DictionaryObject::copyFrom(DictionaryObject *other)
[453]535{
[746]536        for (HashEntryIterator it(other->hash); it.isValid(); it++)
[453]537        {
[746]538                ExtValue *v = (ExtValue*)it->value;
539                hash.put(it->key, v ? new ExtValue(*v) : NULL);
[453]540        }
[478]541}
542
543void DictionaryObject::p_clone(PARAMPROCARGS)
544{
[746]545        DictionaryObject *c = new DictionaryObject;
546        c->copyFrom(this);
547        ret->setObject(ExtObject(&par, c));
[453]548}
549
[478]550void DictionaryObject::p_assign(PARAMPROCARGS)
551{
[746]552        clear();
553        DictionaryObject *other = DictionaryObject::fromObject(args[0].getObject(), false);
554        if (other)
[478]555                copyFrom(other);
[746]556        ret->setEmpty();
[478]557}
558
[171]559DictionaryObject* DictionaryObject::fromObject(const ExtObject& o, bool warn)
[109]560{
[746]561        return (DictionaryObject*)o.getTarget(par.getName(), true, warn);
[109]562}
563
[868]564void DictionaryObject::get_iterator(ExtValue* ret)
565{
566        ret->setObject(DictionaryIterator::makeFrom(this));
567}
568
569void DictionaryObject::get_keys(ExtValue* ret)
570{
571        ret->setObject(DictionaryIterator::makeFrom(this));
572}
573
[109]574////////////////
575
576VectorIterator::VectorIterator(VectorObject* v)
577{
[746]578        vec = v;
579        vec->incref();
580        pos = -1;
[109]581}
582
583#define FIELDSTRUCT VectorIterator
[746]584ParamEntry vectoriterator_paramtab[] =
[109]585{
[746]586        { "VectorIterator", 1, 2, "VectorIterator", "VectorIterator" },
587        { "next", 0, PARAM_READONLY | PARAM_NOSTATIC, "next", "d 0 1", GETONLY(next), },
588        { "value", 0, PARAM_READONLY | PARAM_NOSTATIC, "value", "x", GETONLY(value), },
589        { 0, 0, 0, },
[109]590};
591#undef FIELDSTRUCT
592
593ExtObject VectorIterator::makeFrom(VectorObject *v)
594{
[746]595        static Param par(vectoriterator_paramtab);
596        return ExtObject(&par, new VectorIterator(v));
[109]597}
598
599VectorIterator::~VectorIterator()
600{
[746]601        vec->decref();
[109]602}
603
604void VectorIterator::get_next(ExtValue* ret)
605{
[746]606        pos++;
607        ret->setInt((pos < vec->data.size()) ? 1 : 0);
[109]608}
609
610void VectorIterator::get_value(ExtValue* ret)
611{
[746]612        ExtValue *v = (ExtValue*)(((pos >= 0) && (pos < vec->data.size())) ? vec->data(pos) : NULL);
613        if (v)
614                *ret = *v;
615        else
616                ret->setEmpty();
[109]617}
[490]618
[868]619/////////////////
620
621#define FIELDSTRUCT DictionaryIterator
622ParamEntry dictionaryiterator_paramtab[] =
623{
624        { "DictionaryIterator", 1, 3, "DictionaryIterator", "DictionaryIterator" },
625        { "next", 0, PARAM_READONLY | PARAM_NOSTATIC, "next", "d 0 1", GETONLY(next), },
626        { "value", 0, PARAM_READONLY | PARAM_NOSTATIC, "value", "x", GETONLY(value), },
627        { "iterator", 0, PARAM_READONLY | PARAM_NOSTATIC, "keys iterator", "x", GETONLY(iterator), },
628        { 0, 0, 0, },
629};
630#undef FIELDSTRUCT
631
632DictionaryIterator::DictionaryIterator(DictionaryObject* d, bool _keys)
633        :it(d->hash)
634{
635        dic = d;
636        dic->incref();
637        initial = true;
638        keys = _keys;
639}
640
641ExtObject DictionaryIterator::makeFrom(DictionaryObject *d, bool _keys)
642{
643        static Param par(dictionaryiterator_paramtab);
644        return ExtObject(&par, new DictionaryIterator(d, _keys));
645}
646
647DictionaryIterator::~DictionaryIterator()
648{
649        dic->decref();
650}
651
652void DictionaryIterator::get_next(ExtValue* ret)
653{
654        if (initial)
655                initial = false;
656        else
657                it++;
658        ret->setInt(it.isValid());
659}
660
661void DictionaryIterator::get_value(ExtValue* ret)
662{
663        if ((!initial) && it.isValid())
664        {
665                if (keys)
666                {
667                        ret->setString(it->key);
668                }
669                else
670                {
671                        ExtValue *v = (ExtValue*)it->value;
672                        if (v == NULL)
673                                ret->setEmpty();
674                        else
675                                *ret = *v;
676                }
677        }
678        else
679                ret->setEmpty();
680}
681
682void DictionaryIterator::get_iterator(ExtValue* ret)
683{
684        ret->setObject(makeFrom(dic, true));
685}
686
687//////////////
688
[490]689// not actually needed for deserialization (vector and dict are special cases) but findDeserializableClass can be also used in other contexts
690REGISTER_DESERIALIZABLE(VectorObject)
691REGISTER_DESERIALIZABLE(DictionaryObject)
Note: See TracBrowser for help on using the repository browser.