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

Last change on this file since 646 was 642, checked in by Maciej Komosinski, 8 years ago

Implemented insert() in FramScript? Vector class

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