source: cpp/frams/util/extvalue.h @ 464

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

Serialization of basic object types in JSON format

  • Property svn:eol-style set to native
File size: 9.2 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#ifndef _EXTVALUE_H_
6#define _EXTVALUE_H_
7
8#include "sstring.h"
9#include <frams/param/param.h>
10#include <common/nonstd_stl.h>
11#include <common/threads.h>
12
13#define EXTVALUEUNION
14template <int A, int B> struct CompileTimeMax { enum { val = A > B ? A : B }; };
15#define EXTVALUEUNIONSIZE CompileTimeMax<sizeof(ExtObject),sizeof(SString)>::val
16
17enum ExtPType
18{
19        TUnknown = 0, TInt, TDouble, TString, TObj, TInvalid
20};
21
22/**
23   destructable object
24   */
25class DestrBase
26{
27public:
28        int refcount;
29        DestrBase() :refcount(0) {}
30        void incref() { refcount++; }
31        void decref() { refcount--; if (refcount == 0) delete this; }
32        virtual ~DestrBase() {}
33};
34
35enum SerializationFormat { NativeSerialization, JSONSerialization };
36
37/**
38   object reference.
39   */
40class ExtObject
41{
42        int subtype;                    //< 0/1=Generic/DPC Object,  0/2=Standalone/Shared Param
43        void incref() const;
44        void decref() const;
45public:
46        union {
47                void* object;           //< generic object, will use param
48                DestrBase *dbobject;    //< object with refcounting, will be deleted if refcount goes to 0
49        };
50        union {
51                Param* param;           //< if object!=0
52                ParamInterface *paraminterface; //< if object==0
53        };
54
55        void copyFrom(const ExtObject& src)  { subtype = src.subtype; object = src.object; param = src.param; }
56
57        void* operator new(size_t s, void* mem){ return mem; }
58#ifdef _MSC_VER
59                void operator delete(void* mem, void* t) {}
60#endif
61        void* operator new(size_t s){ return malloc(sizeof(ExtObject)); }
62        void operator delete(void* mem) { free(mem); }
63        ///@param tmp_param can be used for temporary storage, the result ParamInterface* is only valid for as long as tmp_param is valid
64        ParamInterface *getParamInterface(Param &tmp_param) const  { if (subtype & 2){ tmp_param.setParamTab(param->getParamTab()); tmp_param.select(object); return &tmp_param; } return paraminterface; }
65        const char* interfaceName() const { if (isEmpty()) return "Empty"; return (subtype & 2) ? param->getName() : paraminterface->getName(); }
66        bool matchesInterfaceName(ParamInterface* pi) const { return !strcmp(interfaceName(), pi->getName()); }
67        void* getTarget() const { return (subtype & 1) ? dbobject : object; }
68        void* getTarget(const char* classname, bool through_barrier = true, bool warn = true) const;
69        void setEmpty() { decref(); subtype = 0; param = NULL; object = NULL; }
70        int isEmpty() const { return !param; }
71        static const ExtObject& empty() { static const ExtObject& e((ParamInterface*)NULL); return e; }
72        ExtObject(const ExtObject& src)      { src.incref(); copyFrom(src); }
73        void operator=(const ExtObject& src) { src.incref(); decref(); copyFrom(src); }
74        bool makeUnique();//< @return false if nothing has changed
75
76        bool operator==(const ExtObject& src) const;
77
78        SString toString() const;
79        SString serialize_inner(SerializationFormat format) const;
80        SString serialize(SerializationFormat format) const;
81
82        ExtObject(Param *p, void *o) :subtype(2), object(o), param(p){}
83        ExtObject(ParamInterface *p = 0) :subtype(0), object(0), paraminterface(p){}
84        ExtObject(Param *p, DestrBase *o) :subtype(1 + 2), dbobject(o), param(p){ incref(); }
85        ExtObject(ParamInterface *p, DestrBase *o) :subtype(1), dbobject(o), paraminterface(p){ incref(); }
86
87        ~ExtObject(){ decref(); }
88
89        class Serialization
90        {
91                std::vector<ExtObject> refs;
92                int level;
93        public:
94                Serialization() :level(0) {}
95                void begin();
96                void end();
97                int add(const ExtObject& o);
98                void replace(const ExtObject& o, const ExtObject& other);
99                void remove(const ExtObject& o);
100                const ExtObject* get(int ref);
101        };
102
103};
104
105extern THREAD_LOCAL_DECL(ExtObject::Serialization, ExtObject_serialization);
106
107class ExtValue
108{
109public:
110        ExtPType type;
111#ifdef EXTVALUEUNION
112        intptr_t data[(EXTVALUEUNIONSIZE + sizeof(intptr_t) - 1) / sizeof(intptr_t)];
113        paInt& idata() const { return (paInt&)data[0]; };
114        double& ddata() const { return *(double*)data; };
115        ExtObject& odata() const { return *(ExtObject*)data; };
116        SString& sdata() const { return *(SString*)data; };
117#else
118        union {
119                paInt i;
120                double d;
121                SString *s;
122                ExtObject *o;
123        };
124        paInt& idata() const {return (paInt&)i;};
125        double& ddata() const {return (double&)d;};
126        ExtObject& odata() const {return *o;};
127        SString& sdata() const {return *s;};
128#endif
129
130        void* operator new(size_t s, void* mem){ return mem; }
131        void* operator new(size_t s){ return ::operator new(s); }
132
133                ExtValue() :type(TUnknown){}
134        ~ExtValue() { setEmpty(); }
135        ExtValue(paInt v) { seti(v); }
136        ExtValue(double v) { setd(v); }
137        ExtValue(const SString &v) { sets(v); }
138        ExtValue(const ExtObject &srco) { seto(srco); }
139        static ExtValue invalid() { ExtValue v; v.setInvalid(); return v; }
140        static const ExtValue& empty() { static const ExtValue v; return v; }
141        static const ExtValue& zero() { static const ExtValue v(0); return v; }
142
143        enum CompareResult
144        {
145                ResultLower = -1, ResultEqual = 0, ResultHigher = 1,
146                ResultEqualUnordered,
147                ResultUnequal_RelaxedEqual,
148                ResultUnequal_RelaxedUnequal,
149                ResultMismatch_RelaxedUnequal,
150                ResultMismatch
151        };
152        // performs all script value comparisons.
153        // relaxed comparison (internal use only, not available in scripts) works like regular == with additional null~=0, notnull!~0
154        // and is used for pseudo-boolean conversion allowing for expressions like "if (null) ..."
155        CompareResult compare(const ExtValue& src) const;
156
157        enum CmpOperator { CmpFIRST, CmpEQ = CmpFIRST, CmpNE, CmpGE, CmpLE, CmpGT, CmpLT,/*relaxed (not)equal*/CmpREQ, CmpRNE };
158        static const char* cmp_op_names[];
159        struct CmpContext { const ExtValue *v1, *v2; };
160        // interpret compare() result, optional context controls error messages
161        // @return 0=false, 1=true, -1=undefined (null in script)
162        static int interpretCompare(CmpOperator op, CompareResult result, CmpContext *context = NULL);
163
164        void divInt(paInt a);
165        void divDouble(double a);
166
167        int operator==(const ExtValue& src) const;
168        void operator+=(const ExtValue& src);
169        void operator-=(const ExtValue& src);
170        void operator*=(const ExtValue& src);
171        void operator/=(const ExtValue& src);
172        void operator%=(const ExtValue& src);
173        void operator=(const ExtValue& src)
174        {
175                setr(src);
176        }
177        ExtValue(const ExtValue& src)
178                :type(TUnknown) {
179                set(src);
180        }
181        void setEmpty();
182        void setInvalid() { setEmpty(); type = TInvalid; }
183        bool makeUnique() { return (type == TObj) && odata().makeUnique(); } //< @return false if nothing has changed
184        ExtPType getType() const { return type; }
185        void *getObjectTarget(const char* classname, bool warn = true) const;
186        void setInt(paInt v) { if (type != TInt) setri(v); else idata() = v; }
187        void setDouble(double v) { if (type != TDouble) setrd(v); else ddata() = v; }
188        void setString(const SString &v) { if (type != TString) setrs(v); else sdata() = v; }
189        void setObject(const ExtObject &src) { if (type != TObj) setro(src); else odata() = src; }
190        static bool parseInt(const char* s, paInt &result, bool strict, bool error);
191        static bool parseDouble(const char* s, double &result, bool error);
192        static paInt getInt(const char* s, bool strict = false);//< @param strict=true will fail on floating point
193        static double getDouble(const char* s);
194        paInt getInt() const;
195        double getDouble() const;
196        SString getString() const;
197        const SString* getStringPtr() const;//< @return pointer to the internal sstring object or NULL if the current type is not string
198        SString serialize(SerializationFormat format) const;
199        ExtObject getObject() const;
200        bool isNull() const { return (type == TUnknown) || ((type == TObj) && odata().isEmpty()); }
201        SString typeDescription() const;//< @return human readable type name (used in error messages)
202        SString typeAndValue() const;//< @return type and value (used in error messages)
203        const char* parseNumber(const char* in, ExtPType strict_type = TUnknown);
204        const char* deserialize(const char* in);//< @return first character after the succesfully parsed string or NULL if failed
205        const char* deserialize_inner(const char* in);
206        static ParamInterface *findDeserializableClass(const char* name);
207        static PtrListTempl<ParamInterface*> &getDeserializableClasses();
208        template<typename T> class AddDeserializable
209        {
210        public:
211                AddDeserializable() { ExtValue::getDeserializableClasses() += &T::getStaticParam(); }
212        };
213
214        static SString format(SString& fmt, const ExtValue **values, int count);
215
216        ExtValue getExtType();
217
218private: // setrx - release and set, setx - assume released
219        void setr(const ExtValue& src){ setEmpty(); set(src); }
220        void set(const ExtValue& src);
221        void setri(paInt v) { setEmpty(); seti(v); }
222        void setrd(double v) { setEmpty(); setd(v); }
223        void seti(paInt v) { type = TInt; idata() = v; }
224        void setd(double v) { type = TDouble; ddata() = v; }
225#ifdef EXTVALUEUNION
226        void setrs(const SString &v) { setEmpty(); sets(v); }
227        void setro(const ExtObject &src) { setEmpty(); seto(src); }
228        void sets(const SString &v) { type = TString; new(data)SString(v); }
229        void seto(const ExtObject &src) { type = TObj; new(data)ExtObject(src); }
230#else
231        void setrs(const SString &v) {setEmpty();sets(v);}
232        void setro(const ExtObject &src) {setEmpty();seto(src);}
233        void sets(const SString &v) {type=TString;s=new SString(v);}
234        void seto(const ExtObject &src) {type=TObj;o=new ExtObject(src);}
235#endif
236
237};
238
239#define REGISTER_DESERIALIZABLE(name) ExtValue::AddDeserializable<name> deserializable_autoinit_ ## name;
240
241#endif
Note: See TracBrowser for help on using the repository browser.