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

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

Cosmetic/minor improvements

  • Property svn:eol-style set to native
File size: 20.0 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2021  Maciej Komosinski and Szymon Ulatowski.
3// See LICENSE.txt for details.
4
5#include "collectionobj.h"
6#include <common/nonstd_math.h> //sqrt in borland
7#include <frams/util/validitychecks.h>
8#include <algorithm>
9#include <frams/util/sstringutils.h>
10#ifndef NO_VMACHINE
11#include <frams/vm/vmachine.h>
12#endif
13
14#define FIELDSTRUCT VectorObject
15ParamEntry vector_paramtab[] =
16{
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_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)" },
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_READONLY | PARAM_NOSTATIC, "Find", "p d(x value)", PROCEDURE(p_find), "returns the element index or -1 if not found" },
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." },
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_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));" },
45        { 0, 0, 0, },
46};
47#undef FIELDSTRUCT
48
49#define FIELDSTRUCT DictionaryObject
50ParamEntry dictionary_paramtab[] =
51{
52        { "Dictionary", 1, 14, "Dictionary", "Dictionary associates stored values with string keys "
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"
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",
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)." },
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;" },
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_READONLY | 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_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));" },
87        { "assign", 0, PARAM_NOSTATIC, "Assign from another object", "p(x)", PROCEDURE(p_assign), "Replaces current dictionary with dictionary contents from another object." },
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) ..." },
90
91        { 0, 0, 0, },
92};
93#undef FIELDSTRUCT
94
95Param VectorObject::par(vector_paramtab);
96Param DictionaryObject::par(dictionary_paramtab);
97
98/////////////////////////////////////////
99
100VectorObject::VectorObject(Pt3D &pt)
101        :owndata(1)
102{
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);
106}
107
108void VectorObject::clear()
109{
110        if (owndata)
111                for (int i = data.size() - 1; i >= 0; i--)
112                {
113                        ExtValue *v = (ExtValue*)data.get(i);
114                        if (v) delete v;
115                }
116        data.clear();
117}
118
119void VectorObject::p_remove(PARAMPROCARGS)
120{
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;
126}
127
128void VectorObject::set_or_insert(int i, const ExtValue& val, bool insert)
129{
130        if (i < 0) return;
131        int oldsize = data.size();
132        if (i > oldsize)
133        {
134                data.setSize(i);
135                while (i > oldsize)
136                        data.set(oldsize++, 0);
137        }
138        if (insert)
139                data.insert(i, new ExtValue(val));
140        else
141        {
142                ExtValue *v = (ExtValue*)data.get(i);
143                if (v) delete v;
144                data.set(i, new ExtValue(val));
145        }
146}
147
148void VectorObject::p_get(PARAMPROCARGS)
149{
150        int i = args->getInt();
151        if (listIndexCheck(&data, i, "VectorObject", "get"))
152        {
153                ExtValue *v = get(i);
154                if (v)
155                {
156                        *ret = *v;
157                        return;
158                }
159        }
160        *ret = ExtValue();
161}
162
163void VectorObject::get_avg(ExtValue* ret)
164{
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);
171}
172
173SString VectorObject::serialize(SerializationFormat format) const
174{
175        SString out = "[";
176        {
177                for (int i = 0; i < data.size(); i++)
178                {
179                        ExtValue* v = (ExtValue*)data.get(i);
180                        if (i) out += ",";
181                        if (v)
182                                out += v->serialize(format);
183                        else
184                                out += "null";
185                }
186        }
187        out += "]";
188        //sprintf(out.directAppend(20),"<Vector@%p>",this);out.endAppend();
189        return out;
190}
191
192static THREAD_LOCAL_DEF(SList, VectorObject_tostring_trace);
193
194void VectorObject::get_toString(ExtValue* ret)
195{
196        SString out = "[";
197        //static SListTempl<VectorObject*> trace;
198        if (tlsGetRef(VectorObject_tostring_trace).find(this) >= 0)
199                out += "...";
200        else
201        {
202                tlsGetRef(VectorObject_tostring_trace) += this;
203                for (int i = 0; i < data.size(); i++)
204                {
205                        ExtValue* v = (ExtValue*)data.get(i);
206                        if (i) out += ",";
207                        if (v)
208                                out += v->getString();
209                        else
210                                out += "null";
211                }
212                tlsGetRef(VectorObject_tostring_trace) -= this;
213        }
214        out += "]";
215        ret->setString(out);
216}
217
218void VectorObject::get_stdev(ExtValue* ret)
219{
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--)
225        {
226                double d = a - ((ExtValue*)data.get(i))->getDouble();
227                s += d * d;
228        }
229        ret->setDouble(sqrt(s / std::max(1, data.size() - 1)));
230}
231
232void VectorObject::p_find(PARAMPROCARGS)
233{
234        short i;
235        for (i = 0; i < data.size(); i++)
236        {
237                if ((*args) == (*get(i)))
238                {
239                        ret->setInt(i); return;
240                }
241        }
242        ret->setInt(-1);
243}
244
245void VectorObject::p_clone(PARAMPROCARGS)
246{
247        VectorObject *c = new VectorObject;
248        c->data.setSize(data.size());
249        for (int i = 0; i < data.size(); i++)
250        {
251                ExtValue *v = (ExtValue*)get(i);
252                if (v)
253                        c->data.set(i, new ExtValue(*v));
254        }
255        ret->setObject(ExtObject(&par, c));
256}
257
258class VEComparator
259{
260public:
261        bool operator()(const ExtValue *a, const ExtValue *b) { return a->compare(*b) == ExtValue::ResultLower; }
262};
263
264#ifndef NO_VMACHINE
265class VMVEComparator
266{
267public:
268        VMachine::JumpTargetObject *jto;
269        VMachine *vm;
270        VMVEComparator(VMachine::JumpTargetObject *_jto) :jto(_jto), vm(jto->vm) {}
271#ifdef QSORT_R_THIS_FIRST
272        static int compare(void* _this, const void *a, const void *b);
273        bool operator()(const ExtValue *a, const ExtValue *b) { return compare(this,&a,&b) == ExtValue::ResultLower; }
274#else
275        static int compare(const void *a, const void *b, void* _this);
276        bool operator()(const ExtValue *a, const ExtValue *b) { return compare(&a,&b,this) == ExtValue::ResultLower; }
277#endif
278};
279
280#ifdef QSORT_R_THIS_FIRST
281int VMVEComparator::compare(void* _this, const void *a, const void *b)
282#else
283int VMVEComparator::compare(const void *a, const void *b, void* _this)
284#endif
285{
286        VMachine *vm = ((VMVEComparator*)_this)->vm;
287        VMachine::JumpTargetObject *jto = ((VMVEComparator*)_this)->jto;
288        if (!VMCode::prepareDynamicJumpTarget(jto->pc, jto->code))
289                return false;
290
291        vm->push(**(const ExtValue **)a);
292        vm->push(**(const ExtValue **)b);
293        vm->pushNewCallState();
294        vm->jumpDynamicJumpTarget(jto->pc);
295        vm->run();
296        vm->popCallState();
297        int ret;
298        ExtValue& retval = vm->getValue();
299        if (retval.type == TInvalid)
300        {
301                ret = 0;
302                logPrintf("VectorElementComparator", "", LOG_ERROR, "Comparison function returned no value");
303        }
304        else
305                ret = (retval.getInt() != 0) ? -1 : 1;
306        vm->drop(2);
307        return ret;
308}
309#endif
310
311void VectorObject::p_sort(PARAMPROCARGS)
312{
313#ifndef NO_VMACHINE
314        VMachine::JumpTargetObject *jto = VMachine::JumpTargetObject::fromObject(args->getObject(), false);
315        if (jto)
316        {
317                VMVEComparator cmp(jto);
318                ExtValue **first = (ExtValue**)&data.getref(0);
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.
322#ifdef __ANDROID__
323                std::sort(first, first + data.size(), cmp); //no qsort_r() or equivalent on Android (yet)
324#else
325                CALL_QSORT_R(first, data.size(), sizeof(ExtValue*), cmp.compare, &cmp);
326#endif
327        }
328        else
329#endif
330        {
331                VEComparator cmp;
332                ExtValue **first = (ExtValue**)&data.getref(0);
333                std::sort(first, first + data.size(), cmp);
334        }
335        ret->setEmpty();
336}
337
338void VectorObject::get_iterator(ExtValue* ret)
339{
340        ret->setObject(VectorIterator::makeFrom(this));
341}
342
343VectorObject* VectorObject::fromObject(const ExtObject& o, bool warn)
344{
345        return (VectorObject*)o.getTarget(par.getName(), true, warn);
346}
347
348/////////////////////////////
349
350void DictionaryObject::clear()
351{
352        for (HashEntryIterator it(hash); it.isValid();)
353        {
354                ExtValue *v = (ExtValue*)hash.remove(it);
355                if (v) delete v;
356        }
357        hash.clear();
358        hash.init();
359}
360
361void DictionaryObject::p_find(PARAMPROCARGS)
362{
363        for (HashEntryIterator it(hash); it.isValid(); it++)
364        {
365                if (((ExtValue*)it->value) == NULL)
366                {
367                        if (args->getType() != TUnknown) continue;
368                        ret->setString(it->key);
369                        return;
370                }
371                if ((*args) == (*((ExtValue*)it->value)))
372                {
373                        ret->setString(it->key);
374                        return;
375                }
376        }
377        ret->setEmpty();
378}
379
380HashEntryIterator* DictionaryObject::getIndexIterator(int i)
381{
382        if (i < 0) return 0;
383        if (i >= hash.getSize()) return 0;
384
385        if ((!it.isValid()) || (it_index > i))
386        {
387                it = HashEntryIterator(hash);
388                it_index = 0;
389        }
390        while (it.isValid())
391        {
392                if (it_index == i)
393                        return &it;
394                it_index++;
395                it++;
396        }
397        return 0;
398}
399
400void DictionaryObject::p_remove(PARAMPROCARGS)
401{
402        if ((args->type == TInt) || (args->type == TDouble))
403        {
404                HashEntryIterator* iter = getIndexIterator(args->getInt());
405                if (iter)
406                {
407                        ExtValue *oldval = (ExtValue*)hash.remove(*iter);
408                        if (oldval) { *ret = *oldval; delete oldval; }
409                        else *ret = ExtValue();
410                }
411        }
412        else
413        {
414                ExtValue *oldval = (ExtValue*)hash.remove(args[0].getString());
415                if (oldval) { *ret = *oldval; delete oldval; }
416                else *ret = ExtValue();
417        }
418}
419
420ExtValue DictionaryObject::get(SString key)
421{
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        }
435}
436
437ExtValue DictionaryObject::get(int index)
438{
439        HashEntryIterator* iter = getIndexIterator(index);
440        if (iter && (*iter)->value)
441                return *((ExtValue*)(*iter)->value);
442        return ExtValue::empty();
443}
444
445void DictionaryObject::p_get(PARAMPROCARGS)
446{
447        if ((args->type == TInt) || (args->type == TDouble))
448                *ret = get(args->getInt());
449        else
450                *ret = get(args[0].getString());
451}
452
453void DictionaryObject::p_getKey(PARAMPROCARGS)
454{
455        HashEntryIterator* iter = getIndexIterator(args->getInt());
456        if (iter)
457        {
458                *ret = (*iter)->key;
459                return;
460        }
461        *ret = ExtValue();
462}
463
464void DictionaryObject::p_hasKey(PARAMPROCARGS)
465{
466        int found = 0;
467        hash.get(args->getString(), &found);
468        ret->setInt(found);
469}
470
471ExtValue DictionaryObject::set(SString key, ExtValue new_value)
472{
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}
479
480void DictionaryObject::p_set(PARAMPROCARGS)
481{
482        *ret = set(args[1].getString(), args[0]);
483}
484
485SString DictionaryObject::serialize(SerializationFormat format) const
486{
487        SString out = "{";
488        {
489                for (HashEntryIterator it(hash); it.isValid();)
490                {
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 += ",";
501                }
502        }
503        out += "}";
504        return out;
505}
506
507void DictionaryObject::get_toString(ExtValue* ret)
508{
509        SString out = "{";
510        //static SListTempl<DictionaryObject*> trace;
511        if (tlsGetRef(VectorObject_tostring_trace).find(this) >= 0)
512                out += "...";
513        else
514        {
515                tlsGetRef(VectorObject_tostring_trace) += this;
516                for (HashEntryIterator it(hash); it.isValid();)
517                {
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 += ",";
526                }
527                tlsGetRef(VectorObject_tostring_trace) -= this;
528        }
529        out += "}";
530        ret->setString(out);
531}
532
533void DictionaryObject::copyFrom(DictionaryObject *other)
534{
535        for (HashEntryIterator it(other->hash); it.isValid(); it++)
536        {
537                ExtValue *v = (ExtValue*)it->value;
538                hash.put(it->key, v ? new ExtValue(*v) : NULL);
539        }
540}
541
542void DictionaryObject::p_clone(PARAMPROCARGS)
543{
544        DictionaryObject *c = new DictionaryObject;
545        c->copyFrom(this);
546        ret->setObject(ExtObject(&par, c));
547}
548
549void DictionaryObject::p_assign(PARAMPROCARGS)
550{
551        clear();
552        DictionaryObject *other = DictionaryObject::fromObject(args[0].getObject(), false);
553        if (other)
554                copyFrom(other);
555        ret->setEmpty();
556}
557
558DictionaryObject* DictionaryObject::fromObject(const ExtObject& o, bool warn)
559{
560        return (DictionaryObject*)o.getTarget(par.getName(), true, warn);
561}
562
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
573////////////////
574
575VectorIterator::VectorIterator(VectorObject* v)
576{
577        vec = v;
578        vec->incref();
579        pos = -1;
580}
581
582#define FIELDSTRUCT VectorIterator
583ParamEntry vectoriterator_paramtab[] =
584{
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, },
589};
590#undef FIELDSTRUCT
591
592ExtObject VectorIterator::makeFrom(VectorObject *v)
593{
594        static Param par(vectoriterator_paramtab);
595        return ExtObject(&par, new VectorIterator(v));
596}
597
598VectorIterator::~VectorIterator()
599{
600        vec->decref();
601}
602
603void VectorIterator::get_next(ExtValue* ret)
604{
605        pos++;
606        ret->setInt((pos < vec->data.size()) ? 1 : 0);
607}
608
609void VectorIterator::get_value(ExtValue* ret)
610{
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();
616}
617
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
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.