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

Last change on this file since 477 was 464, checked in by Maciej Komosinski, 9 years ago

Serialization of basic object types in JSON format

  • Property svn:eol-style set to native
File size: 13.6 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2015  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,14,"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{"add",0,PARAM_NOSTATIC,"Append at the end","p(x value)",PROCEDURE(p_add),},
36{"find",0,PARAM_NOSTATIC,"Find","p d(x value)",PROCEDURE(p_find),"returns the element index or -1 if not found"},
37{"avg",0,PARAM_READONLY | PARAM_NOSTATIC,"Average","f",GETONLY(avg)},
38{"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."},
39{"toString",0,PARAM_READONLY | PARAM_NOSTATIC,"Textual form","s",GETONLY(toString),},
40{"new",0,0,"Create new Vector","p oVector()",STATICPROCEDURE(p_new),},
41{"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);"},
42{"iterator",0,PARAM_NOSTATIC | PARAM_READONLY,"Iterator","o",GETONLY(iterator),},
43{"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));"},
44{0,0,0,},
45};
46#undef FIELDSTRUCT
47
48#define FIELDSTRUCT DictionaryObject
49ParamEntry dictionary_paramtab[]=
50{
51{"Dictionary",1,10,"Dictionary","Dictionary associates stored values with string keys "
52 "(\"key\" is the first argument in get/set/remove functions). Integer key can be "
53 "used to enumerate all elements (note that while iterating, the elements are returned in no particular order).\n"
54 "Examples:\n"
55 "\tvar d;\n"
56 "\td=Dictionary.new();\n"
57 "\td.set(\"name\",\"John\");\n"
58 "\td.set(\"age\",44);\n"
59 "Another way of doing the same:\n"
60 "\td={};\n"
61 "\td[\"name\"]=\"John\";\n"
62 "\td[\"age\"]=44;\n"
63 "And the most concise way:\n"
64 "\td={ \"name\":\"John\", \"age\":44 };\n"
65 "Iterating:\n"
66 "\tfor(var i=0;i<d.size;i++) Simulator.print(d.getKey(i)+\" is \"+d.get(i));",
67},
68{"clear",0,PARAM_NOSTATIC,"Clear data","p()",PROCEDURE(p_clear),},
69{"size",0,PARAM_NOSTATIC | PARAM_READONLY,"Element count","d",GETONLY(size),},
70{"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)."},
71{"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). null is returned for nonexistent keys.\nobject.get(key) can be shortened to 'object[key]'"},
72{"getKey",0,PARAM_NOSTATIC,"Get a key","p s(d index)",PROCEDURE(p_getKey),"Returns the key of the indexed element (0 <= index < size)"},
73{"set",0,PARAM_NOSTATIC,"Set element","p(x key,x value)",PROCEDURE(p_set),"Set element value for the specified key or index (depending on the argument type: string or int).\nobject.set(key,value) can be shortened to object[key]=value"},
74{"find",0,PARAM_NOSTATIC,"Find","p x(x value)",PROCEDURE(p_find),"Returns the element key or null if not found."},
75{"new",0,0,"Create a Dictionary","p oDictionary()",STATICPROCEDURE(p_new),"Empty directory can be also created using the {} expression."},
76{"toString",0,PARAM_READONLY | PARAM_NOSTATIC,"Textual form","s",GETONLY(toString),},
77{"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));"},
78{0,0,0,},
79};
80#undef FIELDSTRUCT
81
82Param VectorObject::par(vector_paramtab);
83Param DictionaryObject::par(dictionary_paramtab);
84
85/////////////////////////////////////////
86
87VectorObject::VectorObject(Pt3D &pt)
88        :readonly(0),owndata(1)
89{
90set(0,ExtValue(pt.x));
91set(1,ExtValue(pt.y));
92set(2,ExtValue(pt.z));
93}
94
95void VectorObject::clear()
96{
97if (owndata)
98for(int i=data.size()-1;i>=0;i--)
99        {
100        ExtValue *v=(ExtValue*)data.get(i);
101        if (v) delete v;
102        }
103data.clear();
104}
105
106void VectorObject::p_remove(PARAMPROCARGS)
107{
108if (readonly) return;
109int i=args->getInt();
110if ((i<0)||(i>=data.size())) return;
111ExtValue *v=(ExtValue*)data.get(i);
112if (v) delete v;
113data-=i;
114}
115
116void VectorObject::set(int i,const ExtValue& val)
117{
118int oldsize=data.size();
119if (i<0) return;
120ExtValue *v=(ExtValue*)data.get(i);
121if (v) delete v;
122data.set(i,new ExtValue(val));
123i--;
124while(i>=oldsize)
125        {
126        data.set(i,0);
127        i--;
128        }
129}
130
131void VectorObject::p_get(PARAMPROCARGS)
132{
133int i=args->getInt();
134if (listIndexCheck(&data,i,"VectorObject","get"))
135        {
136        ExtValue *v=get(i);
137        if (v)
138                {
139                *ret=*v;
140                return;
141                }
142        }
143*ret=ExtValue();
144}
145
146void VectorObject::get_avg(ExtValue* ret)
147{
148if (!data.size()) {ret->setEmpty(); return;}
149double s=0.0;
150for(int i=data.size()-1;i>=0;i--)
151        s+=((ExtValue*)data.get(i))->getDouble();
152s/=data.size();
153ret->setDouble(s);
154}
155
156SString VectorObject::serialize(SerializationFormat format) const
157{
158SString out="[";
159        {
160        for(int i=0;i<data.size();i++)
161                {
162                ExtValue* v=(ExtValue*)data.get(i);
163                if (i) out+=",";
164                if (v)
165                        out+=v->serialize(format);
166                else
167                        out+="null";
168                }
169        }
170out+="]";
171//sprintf(out.directAppend(20),"<Vector@%p>",this);out.endAppend();
172return out;
173}
174
175static THREAD_LOCAL_DEF(SList,VectorObject_tostring_trace);
176
177void VectorObject::get_toString(ExtValue* ret)
178{
179SString out="[";
180//static SListTempl<VectorObject*> trace;
181if (tlsGetRef(VectorObject_tostring_trace).find(this)>=0)
182        out+="...";
183else
184        {
185        tlsGetRef(VectorObject_tostring_trace)+=this;
186        for(int i=0;i<data.size();i++)
187                {
188                ExtValue* v=(ExtValue*)data.get(i);
189                if (i) out+=",";
190                if (v)
191                        out+=v->getString();
192                else
193                        out+="null";
194                }
195        tlsGetRef(VectorObject_tostring_trace)-=this;
196        }
197out+="]";
198ret->setString(out);
199}
200
201void VectorObject::get_stdev(ExtValue* ret)
202{
203if (!data.size()) {ret->setEmpty(); return;}
204get_avg(ret);
205double a=ret->getDouble();
206double s=0.0;
207for(int i=data.size()-1;i>=0;i--)
208        {
209        double d=a-((ExtValue*)data.get(i))->getDouble();
210        s+=d*d;
211        }
212ret->setDouble(sqrt(s/max(1,data.size()-1)));
213}
214
215void VectorObject::p_find(PARAMPROCARGS)
216{
217short i;
218for(i=0;i<data.size();i++)
219        {
220        if ((*args)==(*get(i)))
221                {ret->setInt(i);return;}
222        }
223ret->setInt(-1);
224}
225
226void VectorObject::p_clone(PARAMPROCARGS)
227{
228VectorObject *c=new VectorObject;
229c->data.setSize(data.size());
230for(int i=0;i<data.size();i++)
231        {
232        ExtValue *v=(ExtValue*)get(i);
233        if (v)
234                c->data.set(i,new ExtValue(*v));
235        }
236ret->setObject(ExtObject(&par,c));
237}
238
239class VEComparator
240{
241public:
242bool operator()(const ExtValue *a,const ExtValue *b) {return a->compare(*b)==ExtValue::ResultLower;}
243};
244
245#ifndef NO_VMACHINE
246class VMVEComparator
247{
248public:
249VMachine::JumpTargetObject *jto;
250VMachine *vm;
251VMVEComparator(VMachine::JumpTargetObject *_jto):jto(_jto),vm(jto->vm) {}
252bool operator()(const ExtValue *a,const ExtValue *b);
253};
254
255bool VMVEComparator::operator()(const ExtValue *a,const ExtValue *b)
256{
257if (!VMCode::prepareDynamicJumpTarget(jto->pc,jto->code))
258        return false;
259
260vm->push(*a);
261vm->push(*b);
262vm->pushNewCallState();
263vm->jumpDynamicJumpTarget(jto->pc);
264vm->run();
265vm->popCallState();
266bool ret;
267ExtValue& retval=vm->getValue();
268if (retval.type==TInvalid)
269        {
270        ret=false;
271        logPrintf("VectorElementComparator","",LOG_ERROR,"Comparison function returned no value");
272        }
273else
274        ret=(retval.getInt()!=0);
275vm->drop(2);
276return ret;
277}
278#endif
279
280void VectorObject::p_sort(PARAMPROCARGS)
281{
282#ifndef NO_VMACHINE
283VMachine::JumpTargetObject *jto=VMachine::JumpTargetObject::fromObject(args->getObject(),false);
284if (jto)
285        {
286        VMVEComparator cmp(jto);
287        ExtValue **first=(ExtValue**)&data.getref(0);
288        std::sort(first,first+data.size(),cmp);
289        }
290else
291#endif
292        {
293        VEComparator cmp;
294        ExtValue **first=(ExtValue**)&data.getref(0);
295        std::sort(first,first+data.size(),cmp);
296        }
297ret->setEmpty();
298}
299
300void VectorObject::get_iterator(ExtValue* ret)
301{
302ret->setObject(VectorIterator::makeFrom(this));
303}
304
305VectorObject* VectorObject::fromObject(const ExtObject& o, bool warn)
306{
307return (VectorObject*)o.getTarget(par.getName(),true,warn);
308}
309
310/////////////////////////////
311
312void DictionaryObject::clear()
313{
314for(HashEntryIterator it(hash);it.isValid();)
315        {
316        ExtValue *v=(ExtValue*)hash.remove(it);
317        if (v) delete v;
318        }
319hash.clear();
320hash.init();
321}
322
323void DictionaryObject::p_find(PARAMPROCARGS)
324{
325for(HashEntryIterator it(hash);it.isValid();it++)
326        {
327        if ((*args)==(*((ExtValue*)it->value)))
328                {
329                ret->setString(it->key);
330                return;
331                }
332        }
333ret->setEmpty();
334}
335
336HashEntryIterator* DictionaryObject::getIndexIterator(int i)
337{
338if (i<0) return 0;
339if (i>=hash.getSize()) return 0;
340
341if ((!it.isValid())||(it_index>i))
342        {
343        it=HashEntryIterator(hash);
344        it_index=0;
345        }
346while(it.isValid())
347        {
348        if (it_index==i)
349                return &it;
350        it_index++;
351        it++;
352        }
353return 0;
354}
355
356void DictionaryObject::p_remove(PARAMPROCARGS)
357{
358if ((args->type==TInt)||(args->type==TDouble))
359        {
360        HashEntryIterator* iter=getIndexIterator(args->getInt());
361        if (iter)
362                {
363                ExtValue *oldval=(ExtValue*)hash.remove(*iter);
364                if (oldval) {*ret=*oldval; delete oldval;} else *ret=ExtValue();
365                }
366        }
367else
368        {
369        ExtValue *oldval=(ExtValue*)hash.remove(args[0].getString());
370        if (oldval) {*ret=*oldval; delete oldval;} else *ret=ExtValue();
371        }
372}
373
374void DictionaryObject::p_get(PARAMPROCARGS)
375{
376if ((args->type==TInt)||(args->type==TDouble))
377        {
378        HashEntryIterator* iter=getIndexIterator(args->getInt());
379        if (iter && (*iter)->value)
380                {
381                *ret=*((ExtValue*)(*iter)->value);
382                return;
383                }
384        }
385else
386        {
387        ExtValue *val=(ExtValue*)hash.get(args[0].getString());
388        if (val)
389                {
390                *ret=*val;
391                return;
392                }
393        }
394*ret=ExtValue();
395}
396
397void DictionaryObject::p_getKey(PARAMPROCARGS)
398{
399HashEntryIterator* iter=getIndexIterator(args->getInt());
400if (iter)
401        {
402        *ret=(*iter)->key;
403        return;
404        }
405*ret=ExtValue();
406}
407
408void DictionaryObject::p_set(PARAMPROCARGS)
409{
410ExtValue *newval=(args[0].getType()==TUnknown)?0:new ExtValue(args[0]);
411ExtValue *oldval=(ExtValue*)hash.put(args[1].getString(),newval);
412if (oldval) {*ret=*oldval; delete oldval;} else *ret=ExtValue();
413}
414
415SString DictionaryObject::serialize(SerializationFormat format) const
416{
417SString out="{";
418        {
419        for(HashEntryIterator it(hash);it.isValid();)
420                {
421                out+="\"";
422                SString q=it->key; sstringQuote(q);
423                out+=q;
424                out+="\":";
425                if (it->value!=NULL)
426                        out+=((ExtValue*)it->value)->serialize(format);
427                else
428                        out+="null";
429                it++;
430                if (it.isValid()) out+=",";
431                }
432        }
433out+="}";
434return out;
435}
436
437void DictionaryObject::get_toString(ExtValue* ret)
438{
439SString out="{";
440//static SListTempl<DictionaryObject*> trace;
441if (tlsGetRef(VectorObject_tostring_trace).find(this)>=0)
442        out+="...";
443else
444        {
445        tlsGetRef(VectorObject_tostring_trace)+=this;
446        for(HashEntryIterator it(hash);it.isValid();)
447                {
448                out+=it->key;
449                out+=":";
450                if (it->value!=NULL)
451                        out+=((ExtValue*)it->value)->getString();
452                else
453                        out+="null";
454                it++;
455                if (it.isValid()) out+=",";
456                }
457        tlsGetRef(VectorObject_tostring_trace)-=this;
458        }
459out+="}";
460ret->setString(out);
461}
462
463void DictionaryObject::p_clone(PARAMPROCARGS)
464{
465DictionaryObject *c=new DictionaryObject;
466for(HashEntryIterator it(hash);it.isValid();it++)
467        {
468        ExtValue *v=(ExtValue*)it->value;
469        c->hash.put(it->key,v?new ExtValue(*v):NULL);
470        }
471ret->setObject(ExtObject(&par,c));
472}
473
474DictionaryObject* DictionaryObject::fromObject(const ExtObject& o, bool warn)
475{
476return (DictionaryObject*)o.getTarget(par.getName(), true, warn);
477}
478
479////////////////
480
481VectorIterator::VectorIterator(VectorObject* v)
482{
483vec=v;
484vec->incref();
485pos=-1;
486}
487
488#define FIELDSTRUCT VectorIterator
489ParamEntry vectoriterator_paramtab[]=
490{
491 {"VectorIterator",1,2,"VectorIterator","VectorIterator"},
492{"next",0,PARAM_READONLY | PARAM_NOSTATIC,"next","d 0 1",GETONLY(next),},
493{"value",0,PARAM_READONLY | PARAM_NOSTATIC,"value","x",GETONLY(value),},
494{0,0,0,},
495};
496#undef FIELDSTRUCT
497
498ExtObject VectorIterator::makeFrom(VectorObject *v)
499{
500static Param par(vectoriterator_paramtab);
501return ExtObject(&par,new VectorIterator(v));
502}
503
504VectorIterator::~VectorIterator()
505{
506vec->decref();
507}
508
509void VectorIterator::get_next(ExtValue* ret)
510{
511pos++;
512ret->setInt((pos < vec->data.size()) ? 1 : 0);
513}
514
515void VectorIterator::get_value(ExtValue* ret)
516{
517ExtValue *v=(ExtValue*) (((pos>=0)&&(pos<vec->data.size())) ? vec->data(pos) : NULL );
518if (v)
519        *ret=*v;
520else
521        ret->setEmpty();
522}
Note: See TracBrowser for help on using the repository browser.