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

Last change on this file since 931 was 931, checked in by Maciej Komosinski, 9 months ago

Supported all platforms using either qsort_r() or qsort_s()

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