/[svn]/libgig/trunk/src/Serialization.cpp
ViewVC logotype

Diff of /libgig/trunk/src/Serialization.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 3168 by schoenebeck, Tue May 9 19:12:32 2017 UTC revision 3392 by schoenebeck, Sun Dec 3 17:49:22 2017 UTC
# Line 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    // enable implementation specific declarations in Serialization.h required to
25    // build this C++ unit, which should be ignored in the public API though
26    #define LIBGIG_SERIALIZATION_INTERNAL 1
27    
28  #include "Serialization.h"  #include "Serialization.h"
29    
30  #include <iostream>  #include <iostream>
31  #include <assert.h>  #include <assert.h>
32  #include <string.h> // for memcpy()  #include <string.h> // for memcpy()
33  #include <stdlib.h> // for atof()  #include <stdlib.h> // for atof()
34    #include <cxxabi.h>
35    
36  #include "helper.h"  #include "helper.h"
37    
# Line 44  namespace Serialization { Line 49  namespace Serialization {
49    
50      const UID NO_UID = _createNullUID();      const UID NO_UID = _createNullUID();
51    
52        /** @brief Check whether this is a valid unique identifier.
53         *
54         * Returns @c false if this UID can be considered an invalid unique
55         * identifier. This is for example the case if this UID object was not
56         * explicitly set to some certain meaningful unique identifier value, or if
57         * this UID object was intentionally assigned the constant @c NO_UID value.
58         * Both represent essentially an UID object which is all zero.
59         *
60         * Note that this class also implements the @c bool operator, both return
61         * the same boolean result.
62         */
63      bool UID::isValid() const {      bool UID::isValid() const {
64          return id != NULL && id != (void*)-1 && size;          return id != NULL && id != (void*)-1 && size;
65      }      }
# Line 51  namespace Serialization { Line 67  namespace Serialization {
67      // *************** DataType ***************      // *************** DataType ***************
68      // *      // *
69    
70        /** @brief Default constructor.
71         *
72         * Initializes a DataType object as being an "invalid" DataType object.
73         * Thus calling isValid(), after creating a DataType object with this
74         * constructor, would return @c false.
75         *
76         * To create a valid and meaningful DataType object instead, call the static
77         * function DataType::dataTypeOf() instead.
78         */
79      DataType::DataType() {      DataType::DataType() {
80          m_size = 0;          m_size = 0;
81          m_isPointer = false;          m_isPointer = false;
# Line 63  namespace Serialization { Line 88  namespace Serialization {
88          m_customTypeName = customType;          m_customTypeName = customType;
89      }      }
90    
91        /** @brief Check if this is a valid DataType object.
92         *
93         * Returns @c true if this DataType object is reflecting a valid data type.
94         * The default constructor creates DataType objects initialized to be
95         * "invalid" DataType objects by default. That way one can detect whether
96         * a DataType object was ever assigned to something meaningful.
97         *
98         * Note that this class also implements the @c bool operator, both return
99         * the same boolean result.
100         */
101      bool DataType::isValid() const {      bool DataType::isValid() const {
102          return m_size;          return m_size;
103      }      }
104    
105        /** @brief Whether this is reflecting a C/C++ pointer type.
106         *
107         * Returns @true if the respective native C/C++ object, member or variable
108         * (this DataType instance is reflecting) is a C/C++ pointer type.
109         */
110      bool DataType::isPointer() const {      bool DataType::isPointer() const {
111          return m_isPointer;          return m_isPointer;
112      }      }
113    
114        /** @brief Whether this is reflecting a C/C++ @c struct or @c class type.
115         *
116         * Returns @c true if the respective native C/C++ object, member or variable
117         * (this DataType instance is reflecting) is a C/C++ @c struct or @c class
118         * type.
119         *
120         * Note that in the following example:
121         * @code
122         * struct Foo {
123         *     int  a;
124         *     bool b;
125         * };
126         * Foo foo;
127         * Foo* pFoo;
128         * @endcode
129         * the DataType objects of both @c foo, as well as of the C/C++ pointer
130         * @c pFoo would both return @c true for isClass() here!
131         *
132         * @see isPointer()
133         */
134      bool DataType::isClass() const {      bool DataType::isClass() const {
135          return m_baseTypeName == "class";          return m_baseTypeName == "class";
136      }      }
137    
138        /** @brief Whether this is reflecting a fundamental C/C++ data type.
139         *
140         * Returns @c true if the respective native C/C++ object, member or variable
141         * (this DataType instance is reflecting) is a primitive, fundamental C/C++
142         * data type. Those are fundamental data types which are already predefined
143         * by the C/C++ language, for example: @c char, @c int, @c float, @c double,
144         * @c bool, but also @b any pointer types like @c int*, @c double**, but
145         * including pointers to user defined types like:
146         * @code
147         * struct Foo {
148         *     int  a;
149         *     bool b;
150         * };
151         * Foo* pFoo;
152         * @endcode
153         * So the DataType object of @c pFoo in the latter example would also return
154         * @c true for isPrimitive() here!
155         *
156         * @see isPointer()
157         */
158      bool DataType::isPrimitive() const {      bool DataType::isPrimitive() const {
159          return !isClass();          return !isClass();
160      }      }
161    
162        /** @brief Whether this is an integer C/C++ data type.
163         *
164         * Returns @c true if the respective native C/C++ object, member or variable
165         * (this DataType instance is reflecting) is a (fundamental, primitive)
166         * integer data type. So these are all @c int and @c unsigned @c int types
167         * of any size. It does not include floating point ("real") types though.
168         *
169         * You may use isSigned() to further check whether this data type allows
170         * negative numbers.
171         *
172         * Note that this method also returns @c true on integer pointer types!
173         *
174         * @see isPointer()
175         */
176      bool DataType::isInteger() const {      bool DataType::isInteger() const {
177          return m_baseTypeName.substr(0, 3) == "int" ||          return m_baseTypeName.substr(0, 3) == "int" ||
178                 m_baseTypeName.substr(0, 4) == "uint";                 m_baseTypeName.substr(0, 4) == "uint";
179      }      }
180    
181        /** @brief Whether this is a floating point based C/C++ data type.
182         *
183         * Returns @c true if the respective native C/C++ object, member or variable
184         * (this DataType instance is reflecting) is a (fundamental, primitive)
185         * floating point based data type. So these are currently the C/C++ @c float
186         * and @c double types. It does not include integer types though.
187         *
188         * Note that this method also returns @c true on @c float pointer and
189         * @c double pointer types!
190         *
191         * @see isPointer()
192         */
193      bool DataType::isReal() const {      bool DataType::isReal() const {
194          return m_baseTypeName.substr(0, 4) == "real";          return m_baseTypeName.substr(0, 4) == "real";
195      }      }
196    
197        /** @brief Whether this is a boolean C/C++ data type.
198         *
199         * Returns @c true if the respective native C/C++ object, member or variable
200         * (this DataType instance is reflecting) is a (fundamental, primitive)
201         * boolean data type. So this is the case for the C++ @c bool data type.
202         * It does not include integer or floating point types though.
203         *
204         * Note that this method also returns @c true on @c bool pointer types!
205         *
206         * @see isPointer()
207         */
208      bool DataType::isBool() const {      bool DataType::isBool() const {
209          return m_baseTypeName == "bool";          return m_baseTypeName == "bool";
210      }      }
211    
212        /** @brief Whether this is a C/C++ @c enum data type.
213         *
214         * Returns @c true if the respective native C/C++ object, member or variable
215         * (this DataType instance is reflecting) is a user defined enumeration
216         * data type. So this is the case for all C/C++ @c enum data types.
217         * It does not include integer (or even floating point) types though.
218         *
219         * Note that this method also returns @c true on @c enum pointer types!
220         *
221         * @see isPointer()
222         */
223      bool DataType::isEnum() const {      bool DataType::isEnum() const {
224          return m_baseTypeName == "enum";          return m_baseTypeName == "enum";
225      }      }
226    
227        /** @brief Whether this is a signed integer C/C++ data type.
228         *
229         * Returns @c true if the respective native C/C++ object, member or variable
230         * (this DataType instance is reflecting) is a (fundamental, primitive)
231         * signed integer data type. This is the case for are all @c unsigned
232         * @c int C/C++ types of any size. For all floating point ("real") based
233         * types this method returns @c false though!
234         *
235         * Note that this method also returns @c true on signed integer pointer
236         * types!
237         *
238         * @see isInteger();
239         */
240      bool DataType::isSigned() const {      bool DataType::isSigned() const {
241          return m_baseTypeName.substr(0, 3) == "int" ||          return m_baseTypeName.substr(0, 3) == "int" ||
242                 isReal();                 isReal();
243      }      }
244    
245        /** @brief Comparison for equalness.
246         *
247         * Returns @c true if the two DataType objects being compared can be
248         * considered to be "equal" C/C++ data types. They are considered to be
249         * equal if their underlying C/C++ data types are exactly identical. For
250         * example comparing @c int and @c unsigned int data types are considere to
251         * be @b not equal, since they are differently signed. Furthermore @c short
252         * @c int and @c long @c int would also not be considered to be equal, since
253         * they do have a different memory size. Additionally pointer type
254         * characteristic is compared as well. So a @c double type and @c double*
255         * type are also considered to be not equal data types and hence this method
256         * would return @c false.
257         *
258         * As an exception here, classes and structs with the same class/struct name
259         * but different sizes are also considered to be "equal". This relaxed
260         * requirement is necessary to retain backward compatiblity to older
261         * versions of the same native C++ classes/structs.
262         */
263      bool DataType::operator==(const DataType& other) const {      bool DataType::operator==(const DataType& other) const {
264          return m_baseTypeName   == other.m_baseTypeName &&          return m_baseTypeName   == other.m_baseTypeName &&
265                 m_customTypeName == other.m_customTypeName &&                 m_customTypeName == other.m_customTypeName &&
266                 m_size           == other.m_size &&                 (m_size == other.m_size || (isClass() && other.isClass())) &&
267                 m_isPointer      == other.m_isPointer;                 m_isPointer      == other.m_isPointer;
268      }      }
269    
270        /** @brief Comparison for inequalness.
271         *
272         * Returns the inverse result of what DataType::operator==() would return.
273         * So refer to the latter for more details.
274         */
275      bool DataType::operator!=(const DataType& other) const {      bool DataType::operator!=(const DataType& other) const {
276          return !operator==(other);          return !operator==(other);
277      }      }
278    
279        /** @brief Smaller than comparison.
280         *
281         * Returns @c true if this DataType object can be consider to be "smaller"
282         * than the @a other DataType object being compared with. This operator
283         * is actually quite arbitrarily implemented and may change at any time,
284         * and thus result for the same data types may change in future at any time.
285         *
286         * This operator is basically implemented for allowing this DataType class
287         * to be used with various standard template library (STL) classes, which
288         * require sorting operators to be implemented.
289         */
290      bool DataType::operator<(const DataType& other) const {      bool DataType::operator<(const DataType& other) const {
291          return m_baseTypeName  < other.m_baseTypeName ||          return m_baseTypeName  < other.m_baseTypeName ||
292                (m_baseTypeName == other.m_baseTypeName &&                (m_baseTypeName == other.m_baseTypeName &&
# Line 122  namespace Serialization { Line 297  namespace Serialization {
297                 m_isPointer < other.m_isPointer)));                 m_isPointer < other.m_isPointer)));
298      }      }
299    
300        /** @brief Greater than comparison.
301         *
302         * Returns @c true if this DataType object can be consider to be "greater"
303         * than the @a other DataType object being compared with. This operator
304         * is actually quite arbitrarily implemented and may change at any time,
305         * and thus result for the same data types may change in future at any time.
306         *
307         * This operator is basically implemented for allowing this DataType class
308         * to be used with various standard template library (STL) classes, which
309         * require sorting operators to be implemented.
310         */
311      bool DataType::operator>(const DataType& other) const {      bool DataType::operator>(const DataType& other) const {
312          return !(operator==(other) || operator<(other));          return !(operator==(other) || operator<(other));
313      }      }
314    
315        /** @brief Human readable long description for this data type.
316         *
317         * Returns a human readable long description for this data type, designed
318         * for the purpose for being displayed to the user. Note that the
319         * implementation for this method and thus the precise textual strings
320         * returned by this method, may change at any time. So you should not rely
321         * on precise strings for certain data types, and you should not use the
322         * return values of this method for comparing data types with each other.
323         *
324         * This class implements various comparison operators, so you should use
325         * them for comparing DataTypes objects instead.
326         *
327         * @see baseTypeName(), customTypeName()
328         */
329      String DataType::asLongDescr() const {      String DataType::asLongDescr() const {
         //TODO: Demangling of C++ raw type names  
330          String s = m_baseTypeName;          String s = m_baseTypeName;
331          if (!m_customTypeName.empty())          if (!m_customTypeName.empty())
332              s += " " + m_customTypeName;              s += " " + customTypeName(true);
333          if (isPointer())          if (isPointer())
334              s += " pointer";              s += " pointer";
335          return s;          return s;
336      }      }
337    
338        /** @brief The base type name of this data type.
339         *
340         * Returns a textual short string identifying the basic type of name of this
341         * data type. For example for a 32 bit signed integer data type this method
342         * would return @c "int32". For all user defined C/C++ @c enum types this
343         * method would return "enum". For all user defined C/C++ @c struct @b and
344         * @c class types this method would return "class" for both. Note that the
345         * precise user defined type name (of i.e. @c enum, @c struct and @c class
346         * types) is not included in the string returned by this method, use
347         * customTypeName() to retrieve that information instead.
348         *
349         * The precise textual strings returned by this method are guaranteed to
350         * retain equal with future versions of this framework. So you can rely on
351         * them for using the return values of this method for comparison tasks in
352         * your application. Note however that this class also implements various
353         * comparison operators.
354         *
355         * Further it is important to know that this method returns the same string
356         * for pointers and non-pointers of the same underlying data type. So in the
357         * following example:
358         * @code
359         * #include <stdint.h>
360         * uint64_t i;
361         * uint64_t* pi;
362         * @endcode
363         * this method would return for both @c i and @c pi the string @c "uint64" !
364         *
365         * @see isPointer(), customTypeName()
366         */
367        String DataType::baseTypeName() const {
368            return m_baseTypeName;
369        }
370    
371        /** @brief The user defined C/C++ data type name of this data type.
372         *
373         * Call this method on user defined C/C++ data types like @c enum, @c struct
374         * and @c class types to retrieve the user defined type name portion of
375         * those data types. Note that this method is only intended for such user
376         * defined data types. For all fundamental, primitive data types (like i.e.
377         * @c int) this method returns an empty string instead.
378         *
379         * This method takes an optional boolean argument @b demangle, which allows
380         * you define whether you are interested in the raw C++ type name or rather
381         * the demangled custom type name. By default this method returns the raw
382         * C++ type name. The raw C++ type name is the one that is actually used
383         * in the compiled binaries and should be preferred for comparions tasks.
384         * The demangled C++ type name is a human readable representation of the
385         * type name instead, which you may use for displaying the user defined type
386         * name portion to the user, however you should not use the demangled
387         * representation for comparison tasks.
388         *
389         * Note that in the following example:
390         * @code
391         * struct Foo {
392         *     int  a;
393         *     bool b;
394         * };
395         * Foo foo;
396         * Foo* pFoo;
397         * @endcode
398         * this method would return the same string for both @c foo and @c pFoo !
399         * In the latter example @c customTypeName(true) would return for both
400         * @c foo and @c pFoo the string @c "Foo" as return value of this method.
401         *
402         * @see isPointer(), baseTypeName()
403         */
404        String DataType::customTypeName(bool demangle) const {
405            if (!demangle) return m_customTypeName;
406            int status;
407            const char* result =
408                abi::__cxa_demangle(m_customTypeName.c_str(), 0, 0, &status);
409            return (status == 0) ? result : m_customTypeName;
410        }
411    
412      // *************** Member ***************      // *************** Member ***************
413      // *      // *
414    
415        /** @brief Default constructor.
416         *
417         * Initializes a Member object as being an "invalid" Member object.
418         * Thus calling isValid(), after creating a Member object with this
419         * constructor, would return @c false.
420         *
421         * You are currently not supposed to create (meaningful) Member objects on
422         * your own. This framework automatically create such Member objects for
423         * you instead.
424         *
425         * @see Object::members()
426         */
427      Member::Member() {      Member::Member() {
428          m_uid = NO_UID;          m_uid = NO_UID;
429          m_offset = 0;          m_offset = 0;
# Line 151  namespace Serialization { Line 436  namespace Serialization {
436          m_type = type;          m_type = type;
437      }      }
438    
439        /** @brief Unique identifier of this member instance.
440         *
441         * Returns the unique identifier of the original C/C++ member instance of
442         * your C++ class. It is important to know that this unique identifier is
443         * not meant to be unique for Member instances themselves, but it is rather
444         * meant to be unique for the original native C/C++ data these Member
445         * instances are representing. So that means no matter how many individual
446         * Member objects are created, as long as they are representing the same
447         * original native member variable of the same original native
448         * instance of your C++ class, then all those separately created Member
449         * objects return the same unique identifier here.
450         *
451         * @see UID for more details
452         */
453        UID Member::uid() const {
454            return m_uid;
455        }
456    
457        /** @brief Name of the member.
458         *
459         * Returns the name of the native C/C++ member variable as originally typed
460         * in its C++ source code. So in the following example:
461         * @code
462         * struct Foo {
463         *     int  a;
464         *     bool b;
465         *     double someValue;
466         * };
467         * @endcode
468         * this method would usually return @c "a" for the first member of object
469         * instances of your native C/C++ @c struct @c Foo, and this method would
470         * usually return @c "someValue" for its third member.
471         *
472         * Note that when you implement the @c serialize() method of your own C/C++
473         * clases or strucs, you are able to override defining the precise name of
474         * your members. In that case this method would of course return the member
475         * names as explicitly forced by you instead.
476         */
477        String Member::name() const {
478            return m_name;
479        }
480    
481        /** @brief Offset of member in its containing parent data structure.
482         *
483         * Returns the offset of this member (in bytes) within its containing parent
484         * user defined data structure or class. So in the following example:
485         * @code
486         * #include <stdint.h>
487         * struct Foo __attribute__ ((__packed__)) {
488         *     int32_t a;
489         *     bool b;
490         *     double c;
491         * };
492         * @endcode
493         * this method would typically return @c 0 for member @c a, @c 4 for member
494         * @c b and @c 5 for member @c c. As you have noted in the latter example,
495         * the structure @c Foo was declared to have "packed" data members. That
496         * means the compiler is instructed to add no memory spaces between the
497         * individual members. Because by default the compiler might add memory
498         * spaces between individual members to align them on certain memory address
499         * boundaries for increasing runtime performance while accessing the
500         * members. So if you declared the previous example without the "packed"
501         * attribute like:
502         * @code
503         * #include <stdint.h>
504         * struct Foo {
505         *     int32_t a;
506         *     bool b;
507         *     double c;
508         * };
509         * @endcode
510         * then this method would usually return a different offset for members
511         * @c b and @c c instead. For most 64 bit architectures this example would
512         * now still return @c 0 for member @c a, but @c 8 for member @c b and @c 16
513         * for member @c c.
514         */
515        size_t Member::offset() const {
516            return m_offset;
517        }
518    
519        /** @brief C/C++ Data type of this member.
520         *
521         * Returns the precise data type of the original native C/C++ member.
522         */
523        const DataType& Member::type() const {
524            return m_type;
525        }
526    
527        /** @brief Check if this is a valid Member object.
528         *
529         * Returns @c true if this Member object is reflecting a "valid" member
530         * object. The default constructor creates Member objects initialized to be
531         * "invalid" Member objects by default. That way one can detect whether
532         * a Member object was ever assigned to something meaningful.
533         *
534         * Note that this class also implements the @c bool operator, both return
535         * the same boolean result value.
536         */
537      bool Member::isValid() const {      bool Member::isValid() const {
538          return m_uid && !m_name.empty() && m_type;          return m_uid && !m_name.empty() && m_type;
539      }      }
540    
541        /** @brief Comparison for equalness.
542         *
543         * Returns @c true if the two Member objects being compared can be
544         * considered to be "equal" C/C++ members. They are considered to be
545         * equal if their data type, member name, their offset within their parent
546         * containing C/C++ data structure, as well as their original native C/C++
547         * instance were exactly identical.
548         */
549      bool Member::operator==(const Member& other) const {      bool Member::operator==(const Member& other) const {
550          return m_uid    == other.m_uid &&          return m_uid    == other.m_uid &&
551                 m_offset == other.m_offset &&                 m_offset == other.m_offset &&
# Line 162  namespace Serialization { Line 553  namespace Serialization {
553                 m_type   == other.m_type;                 m_type   == other.m_type;
554      }      }
555    
556        /** @brief Comparison for inequalness.
557         *
558         * Returns the inverse result of what Member::operator==() would return.
559         * So refer to the latter for more details.
560         */
561      bool Member::operator!=(const Member& other) const {      bool Member::operator!=(const Member& other) const {
562          return !operator==(other);          return !operator==(other);
563      }      }
564    
565        /** @brief Smaller than comparison.
566         *
567         * Returns @c true if this Member object can be consider to be "smaller"
568         * than the @a other Member object being compared with. This operator
569         * is actually quite arbitrarily implemented and may change at any time,
570         * and thus result for the same member representations may change in
571         * future at any time.
572         *
573         * This operator is basically implemented for allowing this DataType class
574         * to be used with various standard template library (STL) classes, which
575         * require sorting operators to be implemented.
576         */
577      bool Member::operator<(const Member& other) const {      bool Member::operator<(const Member& other) const {
578          return m_uid  < other.m_uid ||          return m_uid  < other.m_uid ||
579                (m_uid == other.m_uid &&                (m_uid == other.m_uid &&
# Line 176  namespace Serialization { Line 584  namespace Serialization {
584                 m_type < other.m_type)));                 m_type < other.m_type)));
585      }      }
586    
587        /** @brief Greater than comparison.
588         *
589         * Returns @c true if this Member object can be consider to be "greater"
590         * than the @a other Member object being compared with. This operator
591         * is actually quite arbitrarily implemented and may change at any time,
592         * and thus result for the same member representations may change in
593         * future at any time.
594         *
595         * This operator is basically implemented for allowing this DataType class
596         * to be used with various standard template library (STL) classes, which
597         * require sorting operators to be implemented.
598         */
599      bool Member::operator>(const Member& other) const {      bool Member::operator>(const Member& other) const {
600          return !(operator==(other) || operator<(other));          return !(operator==(other) || operator<(other));
601      }      }
# Line 183  namespace Serialization { Line 603  namespace Serialization {
603      // *************** Object ***************      // *************** Object ***************
604      // *      // *
605    
606        /** @brief Default constructor (for an "invalid" Object).
607         *
608         * Initializes an Object instance as being an "invalid" Object.
609         * Thus calling isValid(), after creating an Object instance with this
610         * constructor, would return @c false.
611         *
612         * Usually you are not supposed to create (meaningful) Object instances on
613         * your own. They are typically constructed by the Archive class for you.
614         *
615         * @see Archive::rootObject(), Archive::objectByUID()
616         */
617      Object::Object() {      Object::Object() {
618          m_version = 0;          m_version = 0;
619          m_minVersion = 0;          m_minVersion = 0;
620      }      }
621    
622        /** @brief Constructor for a "meaningful" Object.
623         *
624         * Initializes a "meaningful" Object instance as being. Thus calling
625         * isValid(), after creating an Object instance with this constructor,
626         * should return @c true, provided that the arguments passed to this
627         * constructor construe a valid object representation.
628         *
629         * Usually you are not supposed to create (meaningful) Object instances on
630         * your own. They are typically constructed by the Archive class for you.
631         *
632         * @see Archive::rootObject(), Archive::objectByUID()
633         *
634         * @param uidChain - unique identifier chain of the object to be constructed
635         * @param type - C/C++ data type of the actual native object this abstract
636         *               Object instance should reflect after calling this
637         *               constructor
638         */
639      Object::Object(UIDChain uidChain, DataType type) {      Object::Object(UIDChain uidChain, DataType type) {
640          m_type = type;          m_type = type;
641          m_uid  = uidChain;          m_uid  = uidChain;
# Line 196  namespace Serialization { Line 644  namespace Serialization {
644          //m_data.resize(type.size());          //m_data.resize(type.size());
645      }      }
646    
647        /** @brief Check if this is a valid Object instance.
648         *
649         * Returns @c true if this Object instance is reflecting a "valid" Object.
650         * The default constructor creates Object instances initialized to be
651         * "invalid" Objects by default. That way one can detect whether an Object
652         * instance was ever assigned to something meaningful.
653         *
654         * Note that this class also implements the @c bool operator, both return
655         * the same boolean result value.
656         */
657      bool Object::isValid() const {      bool Object::isValid() const {
658          return m_type && !m_uid.empty();          return m_type && !m_uid.empty();
659      }      }
660    
661        /** @brief Unique identifier of this Object.
662         *
663         * Returns the unique identifier for the original native C/C++ data this
664         * abstract Object instance is reflecting. If this Object is representing
665         * a C/C++ pointer (of first degree) then @c uid() (or @c uid(0) ) returns
666         * the unique identifier of the pointer itself, whereas @c uid(1) returns
667         * the unique identifier of the original C/C++ data that pointer was
668         * actually pointing to.
669         *
670         * @see UIDChain for more details about this overall topic.
671         */
672        UID Object::uid(int index) const {
673            return (index < m_uid.size()) ? m_uid[index] : NO_UID;
674        }
675    
676        /** @brief Unique identifier chain of this Object.
677         *
678         * Returns the entire unique identifier chain of this Object.
679         *
680         * @see uid() and UIDChain for more details about this overall topic.
681         */
682        const UIDChain& Object::uidChain() const {
683            return m_uid;
684        }
685    
686        /** @brief C/C++ data type this Object is reflecting.
687         *
688         * Returns the precise original C/C++ data type of the original native
689         * C/C++ object or data this Object instance is reflecting.
690         */
691        const DataType& Object::type() const {
692            return m_type;
693        }
694    
695        /** @brief Raw data of the original native C/C++ data.
696         *
697         * Returns the raw data value of the original C/C++ data this Object is
698         * reflecting. So the precise raw data value, layout and size is dependent
699         * to the precise C/C++ data type of the original native C/C++ data. However
700         * potentially required endian correction is already automatically applied
701         * for you. That means you can safely, directly C-cast the raw data returned
702         * by this method to the respective native C/C++ data type in order to
703         * access and use the value for some purpose, at least if the respective
704         * data is of any fundamental, primitive C/C++ data type, or also to a
705         * certain extent if the type is user defined @c enum type.
706         *
707         * However directly C-casting this raw data for user defined @c struct or
708         * @c class types is not possible. For those user defined data structures
709         * this method always returns empty raw data instead.
710         *
711         * Note however that there are more convenient methods in the Archive class
712         * to get the right value for the individual data types instead.
713         *
714         * @see Archive::valueAsInt(), Archive::valueAsReal(), Archive::valueAsBool(),
715         *      Archive::valueAsString()
716         */
717        const RawData& Object::rawData() const {
718            return m_data;
719        }
720    
721        /** @brief Version of original user defined C/C++ @c struct or @c class.
722         *
723         * In case this Object is reflecting a native C/C++ @c struct or @c class
724         * type, then this method returns the version of that native C/C++ @c struct
725         * or @c class layout or implementation. For primitive, fundamental C/C++
726         * data types the return value of this method has no meaning.
727         *
728         * @see Archive::setVersion() for more details about this overall topic.
729         */
730        Version Object::version() const {
731            return m_version;
732        }
733    
734        /** @brief Minimum version of original user defined C/C++ @c struct or @c class.
735         *
736         * In case this Object is reflecting a native C/C++ @c struct or @c class
737         * type, then this method returns the "minimum" version of that native C/C++
738         * @c struct or @c class layout or implementation which it may be compatible
739         * with. For primitive, fundamental C/C++ data types the return value of
740         * this method has no meaning.
741         *
742         * @see Archive::setVersion() and Archive::setMinVersion() for more details
743         *      about this overall topic.
744         */
745        Version Object::minVersion() const {
746            return m_minVersion;
747        }
748    
749        /** @brief All members of the original native C/C++ @c struct or @c class instance.
750         *
751         * In case this Object is reflecting a native C/C++ @c struct or @c class
752         * type, then this method returns all member variables of that original
753         * native C/C++ @c struct or @c class instance. For primitive, fundamental
754         * C/C++ data types this method returns an empty vector instead.
755         *
756         * Example:
757         * @code
758         * struct Foo {
759         *     int  a;
760         *     bool b;
761         *     double someValue;
762         * };
763         * @endcode
764         * Considering above's C++ code, a serialized Object representation of such
765         * a native @c Foo class would have 3 members @c a, @c b and @c someValue.
766         *
767         * Note that the respective serialize() method implementation of that
768         * fictional C++ @c struct @c Foo actually defines which members are going
769         * to be serialized and deserialized for instances of class @c Foo. So in
770         * practice the members returned by method members() here might return a
771         * different set of members as actually defined in the original C/C++ struct
772         * header declaration.
773         *
774         * The precise sequence of the members returned by this method here depends
775         * on the actual serialize() implementation of the user defined C/C++
776         * @c struct or @c class.
777         *
778         * @see Object::sequenceIndexOf() for more details about the precise order
779         *      of members returned by this method in the same way.
780         */
781        std::vector<Member>& Object::members() {
782            return m_members;
783        }
784    
785        /** @brief All members of the original native C/C++ @c struct or @c class instance (read only).
786         *
787         * Returns the same result as overridden members() method above, it just
788         * returns a read-only result instead. See above's method description for
789         * details for the return value of this method instead.
790         */
791        const std::vector<Member>& Object::members() const {
792            return m_members;
793        }
794    
795        /** @brief Comparison for equalness.
796         *
797         * Returns @c true if the two Object instances being compared can be
798         * considered to be "equal" native C/C++ object instances. They are
799         * considered to be equal if they are representing the same original
800         * C/C++ data instance, which is essentially the case if the original
801         * reflecting native C/C++ data are sharing the same memory address and
802         * memory size (thus the exact same memory space) and originally had the
803         * exact same native C/C++ types.
804         */
805      bool Object::operator==(const Object& other) const {      bool Object::operator==(const Object& other) const {
806          // ignoring all other member variables here          // ignoring all other member variables here
807          // (since UID stands for "unique" ;-) )          // (since UID stands for "unique" ;-) )
# Line 207  namespace Serialization { Line 809  namespace Serialization {
809                 m_type == other.m_type;                 m_type == other.m_type;
810      }      }
811    
812        /** @brief Comparison for inequalness.
813         *
814         * Returns the inverse result of what Object::operator==() would return.
815         * So refer to the latter for more details.
816         */
817      bool Object::operator!=(const Object& other) const {      bool Object::operator!=(const Object& other) const {
818          return !operator==(other);          return !operator==(other);
819      }      }
820    
821        /** @brief Smaller than comparison.
822         *
823         * Returns @c true if this Object instance can be consider to be "smaller"
824         * than the @a other Object instance being compared with. This operator
825         * is actually quite arbitrarily implemented and may change at any time,
826         * and thus result for the same Object representations may change in future
827         * at any time.
828         *
829         * This operator is basically implemented for allowing this DataType class
830         * to be used with various standard template library (STL) classes, which
831         * require sorting operators to be implemented.
832         */
833      bool Object::operator<(const Object& other) const {      bool Object::operator<(const Object& other) const {
834          // ignoring all other member variables here          // ignoring all other member variables here
835          // (since UID stands for "unique" ;-) )          // (since UID stands for "unique" ;-) )
# Line 219  namespace Serialization { Line 838  namespace Serialization {
838                 m_type < other.m_type);                 m_type < other.m_type);
839      }      }
840    
841        /** @brief Greater than comparison.
842         *
843         * Returns @c true if this Object instance can be consider to be "greater"
844         * than the @a other Object instance being compared with. This operator
845         * is actually quite arbitrarily implemented and may change at any time,
846         * and thus result for the same Object representations may change in future
847         * at any time.
848         *
849         * This operator is basically implemented for allowing this DataType class
850         * to be used with various standard template library (STL) classes, which
851         * require sorting operators to be implemented.
852         */
853      bool Object::operator>(const Object& other) const {      bool Object::operator>(const Object& other) const {
854          return !(operator==(other) || operator<(other));          return !(operator==(other) || operator<(other));
855      }      }
856    
857        /** @brief Check version compatibility between Object instances.
858         *
859         * Use this method to check whether the two original C/C++ instances those
860         * two Objects are reflecting, were using a C/C++ data type which are version
861         * compatible with each other. By default all C/C++ Objects are considered
862         * to be version compatible. They might only be version incompatible if you
863         * enforced a certain backward compatibility constraint with your
864         * serialize() method implementation of your custom C/C++ @c struct or
865         * @c class types.
866         *
867         * You must only call this method on two Object instances which are
868         * representing the same data type, for example if both Objects reflect
869         * instances of the same user defined C++ class. Calling this method on
870         * completely different data types does not cause an error or exception, but
871         * its result would simply be useless for any purpose.
872         *
873         * @see Archive::setVersion() for more details about this overall topic.
874         */
875      bool Object::isVersionCompatibleTo(const Object& other) const {      bool Object::isVersionCompatibleTo(const Object& other) const {
876          if (this->version() == other.version())          if (this->version() == other.version())
877              return true;              return true;
# Line 232  namespace Serialization { Line 881  namespace Serialization {
881              return other.minVersion() <= this->version();              return other.minVersion() <= this->version();
882      }      }
883    
884        void Object::setVersion(Version v) {
885            m_version = v;
886        }
887    
888        void Object::setMinVersion(Version v) {
889            m_minVersion = v;
890        }
891    
892        /** @brief Get the member of this Object with given name.
893         *
894         * In case this Object is reflecting a native C/C++ @c struct or @c class
895         * type, then this method returns the abstract reflection of the requested
896         * member variable of the original native C/C++ @c struct or @c class
897         * instance. For primitive, fundamental C/C++ data types this method always
898         * returns an "invalid" Member instance instead.
899         *
900         * Example:
901         * @code
902         * struct Foo {
903         *     int  a;
904         *     bool b;
905         *     double someValue;
906         * };
907         * @endcode
908         * Consider that you serialized the native C/C++ @c struct as shown in this
909         * example, and assuming that you implemented the respective serialize()
910         * method of this C++ @c struct to serialize all its members, then you might
911         * call memberNamed("someValue") to get the details of the third member in
912         * this example for instance. In case the passed @a name is an unknown
913         * member name, then this method will return an "invalid" Member object
914         * instead.
915         *
916         * @param name - original name of the sought serialized member variable of
917         *               this Object reflection
918         * @returns abstract reflection of the sought member variable
919         * @see Member::isValid(), Object::members()
920         */
921      Member Object::memberNamed(String name) const {      Member Object::memberNamed(String name) const {
922          for (int i = 0; i < m_members.size(); ++i)          for (int i = 0; i < m_members.size(); ++i)
923              if (m_members[i].name() == name)              if (m_members[i].name() == name)
# Line 239  namespace Serialization { Line 925  namespace Serialization {
925          return Member();          return Member();
926      }      }
927    
928        /** @brief Get the member of this Object with given unique identifier.
929         *
930         * This method behaves similar like method memberNamed() described above,
931         * but instead of searching for a member variable by name, it searches for
932         * a member with an abstract unique identifier instead. For primitive,
933         * fundamental C/C++ data types, for invalid or unknown unique identifiers,
934         * and for members which are actually not member instances of the original
935         * C/C++ @c struct or @c class instance this Object is reflecting, this
936         * method returns an "invalid" Member instance instead.
937         *
938         * @param uid - unique identifier of the member variable being sought
939         * @returns abstract reflection of the sought member variable
940         * @see Member::isValid(), Object::members(), Object::memberNamed()
941         */
942      Member Object::memberByUID(const UID& uid) const {      Member Object::memberByUID(const UID& uid) const {
943          if (!uid) return Member();          if (!uid) return Member();
944          for (int i = 0; i < m_members.size(); ++i)          for (int i = 0; i < m_members.size(); ++i)
# Line 256  namespace Serialization { Line 956  namespace Serialization {
956          }          }
957      }      }
958    
959        /** @brief Get all members of this Object with given data type.
960         *
961         * In case this Object is reflecting a native C/C++ @c struct or @c class
962         * type, then this method returns all member variables of that original
963         * native C/C++ @c struct or @c class instance which are matching the given
964         * requested data @a type. If this Object is reflecting a primitive,
965         * fundamental data type, or if there are no members of this Object with the
966         * requested precise C/C++ data type, then this method returns an empty
967         * vector instead.
968         *
969         * @param type - the precise C/C++ data type of the sought member variables
970         *               of this Object
971         * @returns vector with abstract reflections of the sought member variables
972         * @see Object::members(), Object::memberNamed()
973         */
974      std::vector<Member> Object::membersOfType(const DataType& type) const {      std::vector<Member> Object::membersOfType(const DataType& type) const {
975          std::vector<Member> v;          std::vector<Member> v;
976          for (int i = 0; i < m_members.size(); ++i) {          for (int i = 0; i < m_members.size(); ++i) {
# Line 266  namespace Serialization { Line 981  namespace Serialization {
981          return v;          return v;
982      }      }
983    
984        /** @brief Serialization/deserialization sequence number of the requested member.
985         *
986         * Returns the precise serialization/deserialization sequence number of the
987         * requested @a member variable.
988         *
989         * Example:
990         * @code
991         * struct Foo {
992         *     int  a;
993         *     bool b;
994         *     double c;
995         *
996         *     void serialize(Serialization::Archive* archive);
997         * };
998         * @endcode
999         * Assuming the declaration of the user defined native C/C++ @c struct
1000         * @c Foo above, and assuming the following implementation of serialize():
1001         * @code
1002         * #define SRLZ(member) \
1003         *   archive->serializeMember(*this, member, #member);
1004         *
1005         * void Foo::serialize(Serialization::Archive* archive) {
1006         *     SRLZ(c);
1007         *     SRLZ(a);
1008         *     SRLZ(b);
1009         * }
1010         * @endcode
1011         * then @c sequenceIndexOf(obj.memberNamed("a")) returns 1,
1012         * @c sequenceIndexOf(obj.memberNamed("b")) returns 2, and
1013         * @c sequenceIndexOf(obj.memberNamed("c")) returns 0.
1014         */
1015      int Object::sequenceIndexOf(const Member& member) const {      int Object::sequenceIndexOf(const Member& member) const {
1016          for (int i = 0; i < m_members.size(); ++i)          for (int i = 0; i < m_members.size(); ++i)
1017              if (m_members[i] == member)              if (m_members[i] == member)
# Line 276  namespace Serialization { Line 1022  namespace Serialization {
1022      // *************** Archive ***************      // *************** Archive ***************
1023      // *      // *
1024    
1025        /** @brief Create an "empty" archive.
1026         *
1027         * This default constructor creates an "empty" archive which you then
1028         * subsequently for example might fill with serialized data like:
1029         * @code
1030         * Archive a;
1031         * a.serialize(&myRootObject);
1032         * @endcode
1033         * Or:
1034         * @code
1035         * Archive a;
1036         * a << myRootObject;
1037         * @endcode
1038         * Or you might also subsequently assign an already existing non-empty
1039         * to this empty archive, which effectively clones the other
1040         * archive (deep copy) or call decode() later on to assign a previously
1041         * serialized raw data stream.
1042         */
1043      Archive::Archive() {      Archive::Archive() {
1044          m_operation = OPERATION_NONE;          m_operation = OPERATION_NONE;
1045          m_root = NO_UID;          m_root = NO_UID;
# Line 283  namespace Serialization { Line 1047  namespace Serialization {
1047          m_timeCreated = m_timeModified = LIBGIG_EPOCH_TIME;          m_timeCreated = m_timeModified = LIBGIG_EPOCH_TIME;
1048      }      }
1049    
1050        /** @brief Create and fill the archive with the given serialized raw data.
1051         *
1052         * This constructor decodes the given raw @a data and constructs a
1053         * (non-empty) Archive object according to that given serialized data
1054         * stream.
1055         *
1056         * After this constructor returned, you may then traverse the individual
1057         * objects by starting with accessing the rootObject() for example. Finally
1058         * you might call deserialize() to restore your native C++ objects with the
1059         * content of this archive.
1060         *
1061         * @param data - the previously serialized raw data stream to be decoded
1062         * @throws Exception if the provided raw @a data uses an invalid, unknown,
1063         *         incompatible or corrupt data stream or format.
1064         */
1065      Archive::Archive(const RawData& data) {      Archive::Archive(const RawData& data) {
1066          m_operation = OPERATION_NONE;          m_operation = OPERATION_NONE;
1067          m_root = NO_UID;          m_root = NO_UID;
# Line 291  namespace Serialization { Line 1070  namespace Serialization {
1070          decode(m_rawData);          decode(m_rawData);
1071      }      }
1072    
1073        /** @brief Create and fill the archive with the given serialized raw C-buffer data.
1074         *
1075         * This constructor essentially works like the constructor above, but just
1076         * uses another data type for the serialized raw data stream being passed to
1077         * this class.
1078         *
1079         * This constructor decodes the given raw @a data and constructs a
1080         * (non-empty) Archive object according to that given serialized data
1081         * stream.
1082         *
1083         * After this constructor returned, you may then traverse the individual
1084         * objects by starting with accessing the rootObject() for example. Finally
1085         * you might call deserialize() to restore your native C++ objects with the
1086         * content of this archive.
1087         *
1088         * @param data - the previously serialized raw data stream to be decoded
1089         * @param size - size of @a data in bytes
1090         * @throws Exception if the provided raw @a data uses an invalid, unknown,
1091         *         incompatible or corrupt data stream or format.
1092         */
1093      Archive::Archive(const uint8_t* data, size_t size) {      Archive::Archive(const uint8_t* data, size_t size) {
1094          m_operation = OPERATION_NONE;          m_operation = OPERATION_NONE;
1095          m_root = NO_UID;          m_root = NO_UID;
# Line 302  namespace Serialization { Line 1101  namespace Serialization {
1101      Archive::~Archive() {      Archive::~Archive() {
1102      }      }
1103    
1104        /** @brief Root C++ object of this archive.
1105         *
1106         * In case this is a non-empty Archive, then this method returns the so
1107         * called "root" C++ object. If this is an empty archive, then this method
1108         * returns an "invalid" Object instance instead.
1109         *
1110         * @see Archive::serialize() for more details about the "root" object concept.
1111         * @see Object for more details about the overall object reflection concept.
1112         * @returns reflection of the original native C++ root object
1113         */
1114      Object& Archive::rootObject() {      Object& Archive::rootObject() {
1115          return m_allObjects[m_root];          return m_allObjects[m_root];
1116      }      }
# Line 402  namespace Serialization { Line 1211  namespace Serialization {
1211          return s;          return s;
1212      }      }
1213    
1214        template<typename T>
1215        static T _primitiveObjectValueToNumber(const Object& obj) {
1216            T value = 0;
1217            const DataType& type = obj.type();
1218            const ID& id = obj.uid().id;
1219            void* ptr = obj.m_data.empty() ? (void*)id : (void*)&obj.m_data[0];
1220            if (!obj.m_data.empty())
1221                assert(type.size() == obj.m_data.size());
1222            if (type.isPrimitive() && !type.isPointer()) {
1223                if (type.isInteger() || type.isEnum()) {
1224                    if (type.isSigned()) {
1225                        if (type.size() == 1)
1226                            value = (T)*(int8_t*)ptr;
1227                        else if (type.size() == 2)
1228                            value = (T)*(int16_t*)ptr;
1229                        else if (type.size() == 4)
1230                            value = (T)*(int32_t*)ptr;
1231                        else if (type.size() == 8)
1232                            value = (T)*(int64_t*)ptr;
1233                        else
1234                            assert(false /* unknown signed int type size */);
1235                    } else {
1236                        if (type.size() == 1)
1237                            value = (T)*(uint8_t*)ptr;
1238                        else if (type.size() == 2)
1239                            value = (T)*(uint16_t*)ptr;
1240                        else if (type.size() == 4)
1241                            value = (T)*(uint32_t*)ptr;
1242                        else if (type.size() == 8)
1243                            value = (T)*(uint64_t*)ptr;
1244                        else
1245                            assert(false /* unknown unsigned int type size */);
1246                    }
1247                } else if (type.isReal()) {
1248                    if (type.size() == sizeof(float))
1249                        value = (T)*(float*)ptr;
1250                    else if (type.size() == sizeof(double))
1251                        value = (T)*(double*)ptr;
1252                    else
1253                        assert(false /* unknown floating point type */);
1254                } else if (type.isBool()) {
1255                    value = (T)*(bool*)ptr;
1256                } else {
1257                    assert(false /* unknown primitive type */);
1258                }
1259            }
1260            return value;
1261        }
1262    
1263      static String _encodePrimitiveValue(const Object& obj) {      static String _encodePrimitiveValue(const Object& obj) {
1264          return _encodeBlob( _primitiveObjectValueToString(obj) );          return _encodeBlob( _primitiveObjectValueToString(obj) );
1265      }      }
# Line 560  namespace Serialization { Line 1418  namespace Serialization {
1418          return (time_t) i;          return (time_t) i;
1419      }      }
1420    
1421      DataType _popDataTypeBlob(const char*& p, const char* end) {      static DataType _popDataTypeBlob(const char*& p, const char* end) {
1422          _Blob blob = _decodeBlob(p, end);          _Blob blob = _decodeBlob(p, end);
1423          p   = blob.p;          p   = blob.p;
1424          end = blob.end;          end = blob.end;
# Line 744  namespace Serialization { Line 1602  namespace Serialization {
1602          m_timeModified = _popTimeBlob(p, end);          m_timeModified = _popTimeBlob(p, end);
1603      }      }
1604    
1605        /** @brief Fill this archive with the given serialized raw data.
1606         *
1607         * Calling this method will decode the given raw @a data and constructs a
1608         * (non-empty) Archive object according to that given serialized @a data
1609         * stream.
1610         *
1611         * After this method returned, you may then traverse the individual
1612         * objects by starting with accessing the rootObject() for example. Finally
1613         * you might call deserialize() to restore your native C++ objects with the
1614         * content of this archive.
1615         *
1616         * @param data - the previously serialized raw data stream to be decoded
1617         * @throws Exception if the provided raw @a data uses an invalid, unknown,
1618         *         incompatible or corrupt data stream or format.
1619         */
1620      void Archive::decode(const RawData& data) {      void Archive::decode(const RawData& data) {
1621          m_rawData = data;          m_rawData = data;
1622          m_allObjects.clear();          m_allObjects.clear();
# Line 757  namespace Serialization { Line 1630  namespace Serialization {
1630          _popRootBlob(p, end);          _popRootBlob(p, end);
1631      }      }
1632    
1633        /** @brief Fill this archive with the given serialized raw C-buffer data.
1634         *
1635         * This method essentially works like the decode() method above, but just
1636         * uses another data type for the serialized raw data stream being passed to
1637         * this method.
1638         *
1639         * Calling this method will decode the given raw @a data and constructs a
1640         * (non-empty) Archive object according to that given serialized @a data
1641         * stream.
1642         *
1643         * After this method returned, you may then traverse the individual
1644         * objects by starting with accessing the rootObject() for example. Finally
1645         * you might call deserialize() to restore your native C++ objects with the
1646         * content of this archive.
1647         *
1648         * @param data - the previously serialized raw data stream to be decoded
1649         * @param size - size of @a data in bytes
1650         * @throws Exception if the provided raw @a data uses an invalid, unknown,
1651         *         incompatible or corrupt data stream or format.
1652         */
1653      void Archive::decode(const uint8_t* data, size_t size) {      void Archive::decode(const uint8_t* data, size_t size) {
1654          RawData rawData;          RawData rawData;
1655          rawData.resize(size);          rawData.resize(size);
# Line 764  namespace Serialization { Line 1657  namespace Serialization {
1657          decode(rawData);          decode(rawData);
1658      }      }
1659    
1660        /** @brief Raw data stream of this archive content.
1661         *
1662         * Call this method to get a raw data stream for the current content of this
1663         * archive, which you may use to i.e. store on disk or send vie network to
1664         * another machine for deserializing there. This method only returns a
1665         * meaningful content if this is a non-empty archive, that is if you either
1666         * serialized with this Archive object or decoded a raw data stream to this
1667         * Archive object before. If this is an empty archive instead, then this
1668         * method simply returns an empty raw data stream (of size 0) instead.
1669         *
1670         * Note that whenever you call this method, the "modified" state of this
1671         * archive will be reset to @c false.
1672         *
1673         * @see isModified()
1674         */
1675      const RawData& Archive::rawData() {      const RawData& Archive::rawData() {
1676          if (m_isModified) encode();          if (m_isModified) encode();
1677          return m_rawData;          return m_rawData;
1678      }      }
1679    
1680        /** @brief Name of the encoding format used by this Archive class.
1681         *
1682         * This method returns the name of the encoding format used to encode
1683         * serialized raw data streams.
1684         */
1685      String Archive::rawDataFormat() const {      String Archive::rawDataFormat() const {
1686          return MAGIC_START;          return MAGIC_START;
1687      }      }
1688    
1689        /** @brief Whether this archive was modified.
1690         *
1691         * This method returns the current "modified" state of this archive. When
1692         * either decoding a previously serialized raw data stream or after
1693         * serializing native C++ objects to this archive the modified state will
1694         * initially be set to @c false. However whenever you are modifying the
1695         * abstract data model of this archive afterwards, for example by removing
1696         * objects from this archive by calling remove() or removeMember(), or by
1697         * altering object values for example by calling setIntValue(), then the
1698         * "modified" state of this archive will automatically be set to @c true.
1699         *
1700         * You can reset the "modified" state explicitly at any time, by calling
1701         * rawData().
1702         */
1703      bool Archive::isModified() const {      bool Archive::isModified() const {
1704          return m_isModified;          return m_isModified;
1705      }      }
1706    
1707        /** @brief Clear content of this archive.
1708         *
1709         * Drops the entire content of this archive and thus resets this archive
1710         * back to become an empty archive.
1711         */
1712      void Archive::clear() {      void Archive::clear() {
1713          m_allObjects.clear();          m_allObjects.clear();
1714          m_operation = OPERATION_NONE;          m_operation = OPERATION_NONE;
# Line 786  namespace Serialization { Line 1718  namespace Serialization {
1718          m_timeCreated = m_timeModified = LIBGIG_EPOCH_TIME;          m_timeCreated = m_timeModified = LIBGIG_EPOCH_TIME;
1719      }      }
1720    
1721        /** @brief Optional name of this archive.
1722         *
1723         * Returns the optional name of this archive that you might have assigned
1724         * to this archive before by calling setName(). If you haven't assigned any
1725         * name to this archive before, then this method simply returns an empty
1726         * string instead.
1727         */
1728      String Archive::name() const {      String Archive::name() const {
1729          return m_name;          return m_name;
1730      }      }
1731    
1732        /** @brief Assign a name to this archive.
1733         *
1734         * You may optionally assign an arbitrary name to this archive. The name
1735         * will be stored along with the archive, that is it will encoded with the
1736         * resulting raw data stream, and accordingly it will be decoded from the
1737         * raw data stream later on.
1738         *
1739         * @param name - arbitrary new name for this archive
1740         */
1741      void Archive::setName(String name) {      void Archive::setName(String name) {
1742          if (m_name == name) return;          if (m_name == name) return;
1743          m_name = name;          m_name = name;
1744          m_isModified = true;          m_isModified = true;
1745      }      }
1746    
1747        /** @brief Optional comments for this archive.
1748         *
1749         * Returns the optional comments for this archive that you might have
1750         * assigned to this archive before by calling setComment(). If you haven't
1751         * assigned any comment to this archive before, then this method simply
1752         * returns an empty string instead.
1753         */
1754      String Archive::comment() const {      String Archive::comment() const {
1755          return m_comment;          return m_comment;
1756      }      }
1757    
1758        /** @brief Assign a comment to this archive.
1759         *
1760         * You may optionally assign arbitrary comments to this archive. The comment
1761         * will be stored along with the archive, that is it will encoded with the
1762         * resulting raw data stream, and accordingly it will be decoded from the
1763         * raw data stream later on.
1764         *
1765         * @param comment - arbitrary new comment for this archive
1766         */
1767      void Archive::setComment(String comment) {      void Archive::setComment(String comment) {
1768          if (m_comment == comment) return;          if (m_comment == comment) return;
1769          m_comment = comment;          m_comment = comment;
# Line 823  namespace Serialization { Line 1787  namespace Serialization {
1787          return *pTm;          return *pTm;
1788      }      }
1789    
1790        /** @brief Date and time when this archive was initially created.
1791         *
1792         * Returns a UTC time stamp (date and time) when this archive was initially
1793         * created.
1794         */
1795      time_t Archive::timeStampCreated() const {      time_t Archive::timeStampCreated() const {
1796          return m_timeCreated;          return m_timeCreated;
1797      }      }
1798    
1799        /** @brief Date and time when this archive was modified for the last time.
1800         *
1801         * Returns a UTC time stamp (date and time) when this archive was modified
1802         * for the last time.
1803         */
1804      time_t Archive::timeStampModified() const {      time_t Archive::timeStampModified() const {
1805          return m_timeModified;          return m_timeModified;
1806      }      }
1807    
1808        /** @brief Date and time when this archive was initially created.
1809         *
1810         * Returns a calendar time information representing the date and time when
1811         * this archive was initially created. The optional @a base parameter may
1812         * be used to define to which time zone the returned data and time shall be
1813         * related to.
1814         *
1815         * @param base - (optional) time zone the result shall relate to, by default
1816         *               UTC time (Greenwhich Mean Time) is assumed instead
1817         */
1818      tm Archive::dateTimeCreated(time_base_t base) const {      tm Archive::dateTimeCreated(time_base_t base) const {
1819          return _convertTimeStamp(m_timeCreated, base);          return _convertTimeStamp(m_timeCreated, base);
1820      }      }
1821    
1822        /** @brief Date and time when this archive was modified for the last time.
1823         *
1824         * Returns a calendar time information representing the date and time when
1825         * this archive has been modified for the last time. The optional @a base
1826         * parameter may be used to define to which time zone the returned date and
1827         * time shall be related to.
1828         *
1829         * @param base - (optional) time zone the result shall relate to, by default
1830         *               UTC time (Greenwhich Mean Time) is assumed instead
1831         */
1832      tm Archive::dateTimeModified(time_base_t base) const {      tm Archive::dateTimeModified(time_base_t base) const {
1833          return _convertTimeStamp(m_timeModified, base);          return _convertTimeStamp(m_timeModified, base);
1834      }      }
1835    
1836        /** @brief Remove a member variable from the given object.
1837         *
1838         * Removes the member variable @a member from its containing object
1839         * @a parent and sets the modified state of this archive to @c true.
1840         * If the given @a parent object does not contain the given @a member then
1841         * this method does nothing.
1842         *
1843         * This method provides a means of "partial" deserialization. By removing
1844         * either objects or members from this archive before calling deserialize(),
1845         * only the remaining objects and remaining members will be restored by this
1846         * framework, all other data of your C++ classes remain untouched.
1847         *
1848         * @param parent - Object which contains @a member
1849         * @param member - member to be removed
1850         * @see isModified() for details about the modified state.
1851         * @see Object for more details about the overall object reflection concept.
1852         */
1853      void Archive::removeMember(Object& parent, const Member& member) {      void Archive::removeMember(Object& parent, const Member& member) {
1854          parent.remove(member);          parent.remove(member);
1855          m_isModified = true;          m_isModified = true;
1856      }      }
1857    
1858        /** @brief Remove an object from this archive.
1859         *
1860         * Removes the object @obj from this archive and sets the modified state of
1861         * this archive to @c true. If the passed object is either invalid, or does
1862         * not exist in this archive, then this method does nothing.
1863         *
1864         * This method provides a means of "partial" deserialization. By removing
1865         * either objects or members from this archive before calling deserialize(),
1866         * only the remaining objects and remaining members will be restored by this
1867         * framework, all other data of your C++ classes remain untouched.
1868         *
1869         * @param obj - the object to be removed from this archive
1870         * @see isModified() for details about the modified state.
1871         * @see Object for more details about the overall object reflection concept.
1872         */
1873      void Archive::remove(const Object& obj) {      void Archive::remove(const Object& obj) {
1874          //FIXME: Should traverse from root object and remove all members associated with this object          //FIXME: Should traverse from root object and remove all members associated with this object
1875          if (!obj.uid()) return;          if (!obj.uid()) return;
# Line 851  namespace Serialization { Line 1877  namespace Serialization {
1877          m_isModified = true;          m_isModified = true;
1878      }      }
1879    
1880        /** @brief Access object by its unique identifier.
1881         *
1882         * Returns the object of this archive with the given unique identifier
1883         * @a uid. If the given @a uid is invalid, or if this archive does not
1884         * contain an object with the given unique identifier, then this method
1885         * returns an invalid object instead.
1886         *
1887         * @param uid - unique identifier of sought object
1888         * @see Object for more details about the overall object reflection concept.
1889         * @see Object::isValid() for valid/invalid objects
1890         */
1891      Object& Archive::objectByUID(const UID& uid) {      Object& Archive::objectByUID(const UID& uid) {
1892          return m_allObjects[uid];          return m_allObjects[uid];
1893      }      }
1894    
1895        /** @brief Set the current version for the given object.
1896         *
1897         * Essentially behaves like above's setVersion() method, it just uses the
1898         * abstract reflection data type instead for the respective @a object being
1899         * passed to this method. Refer to above's setVersion() documentation about
1900         * the precise behavior details of setVersion().
1901         *
1902         * @param object - object to set the current version for
1903         * @param v - new current version to set for @a object
1904         */
1905        void Archive::setVersion(Object& object, Version v) {
1906            if (!object) return;
1907            object.setVersion(v);
1908            m_isModified = true;
1909        }
1910    
1911        /** @brief Set the minimum version for the given object.
1912         *
1913         * Essentially behaves like above's setMinVersion() method, it just uses the
1914         * abstract reflection data type instead for the respective @a object being
1915         * passed to this method. Refer to above's setMinVersion() documentation
1916         * about the precise behavior details of setMinVersion().
1917         *
1918         * @param object - object to set the minimum version for
1919         * @param v - new minimum version to set for @a object
1920         */
1921        void Archive::setMinVersion(Object& object, Version v) {
1922            if (!object) return;
1923            object.setMinVersion(v);
1924            m_isModified = true;
1925        }
1926    
1927        /** @brief Set new value for given @c enum object.
1928         *
1929         * Sets the new @a value to the given @c enum @a object.
1930         *
1931         * @param object - the @c enum object to be changed
1932         * @param value - the new value to be assigned to the @a object
1933         * @throws Exception if @a object is not an @c enum type.
1934         */
1935      void Archive::setEnumValue(Object& object, uint64_t value) {      void Archive::setEnumValue(Object& object, uint64_t value) {
1936          if (!object) return;          if (!object) return;
1937          if (!object.type().isEnum())          if (!object.type().isEnum())
# Line 887  namespace Serialization { Line 1964  namespace Serialization {
1964          m_isModified = true;          m_isModified = true;
1965      }      }
1966    
1967        /** @brief Set new integer value for given integer object.
1968         *
1969         * Sets the new integer @a value to the given integer @a object. Currently
1970         * this framework handles any integer data type up to 64 bit. For larger
1971         * integer types an assertion failure will be raised.
1972         *
1973         * @param object - the integer object to be changed
1974         * @param value - the new value to be assigned to the @a object
1975         * @throws Exception if @a object is not an integer type.
1976         */
1977      void Archive::setIntValue(Object& object, int64_t value) {      void Archive::setIntValue(Object& object, int64_t value) {
1978          if (!object) return;          if (!object) return;
1979          if (!object.type().isInteger())          if (!object.type().isInteger())
# Line 926  namespace Serialization { Line 2013  namespace Serialization {
2013          m_isModified = true;          m_isModified = true;
2014      }      }
2015    
2016        /** @brief Set new floating point value for given floating point object.
2017         *
2018         * Sets the new floating point @a value to the given floating point
2019         * @a object. Currently this framework supports single precision @c float
2020         * and double precision @c double floating point data types. For all other
2021         * floating point types this method will raise an assertion failure.
2022         *
2023         * @param object - the floating point object to be changed
2024         * @param value - the new value to be assigned to the @a object
2025         * @throws Exception if @a object is not a floating point based type.
2026         */
2027      void Archive::setRealValue(Object& object, double value) {      void Archive::setRealValue(Object& object, double value) {
2028          if (!object) return;          if (!object) return;
2029          if (!object.type().isReal())          if (!object.type().isReal())
# Line 948  namespace Serialization { Line 2046  namespace Serialization {
2046          m_isModified = true;          m_isModified = true;
2047      }      }
2048    
2049        /** @brief Set new boolean value for given boolean object.
2050         *
2051         * Sets the new boolean @a value to the given boolean @a object.
2052         *
2053         * @param object - the boolean object to be changed
2054         * @param value - the new value to be assigned to the @a object
2055         * @throws Exception if @a object is not a boolean type.
2056         */
2057      void Archive::setBoolValue(Object& object, bool value) {      void Archive::setBoolValue(Object& object, bool value) {
2058          if (!object) return;          if (!object) return;
2059          if (!object.type().isBool())          if (!object.type().isBool())
# Line 965  namespace Serialization { Line 2071  namespace Serialization {
2071          m_isModified = true;          m_isModified = true;
2072      }      }
2073    
2074        /** @brief Automatically cast and assign appropriate value to object.
2075         *
2076         * This method automatically converts the given @a value from textual string
2077         * representation into the appropriate data format of the requested
2078         * @a object. So this method is a convenient way to change values of objects
2079         * in this archive with your applications in automated way, i.e. for
2080         * implementing an editor where the user is able to edit values of objects
2081         * in this archive by entering the values as text with a keyboard.
2082         *
2083         * @throws Exception if the passed @a object is not a fundamental, primitive
2084         *         data type or if the provided textual value cannot be converted
2085         *         into an appropriate value for the requested object.
2086         */
2087      void Archive::setAutoValue(Object& object, String value) {      void Archive::setAutoValue(Object& object, String value) {
2088          if (!object) return;          if (!object) return;
2089          const DataType& type = object.type();          const DataType& type = object.type();
# Line 972  namespace Serialization { Line 2091  namespace Serialization {
2091              setIntValue(object, atoll(value.c_str()));              setIntValue(object, atoll(value.c_str()));
2092          else if (type.isReal())          else if (type.isReal())
2093              setRealValue(object, atof(value.c_str()));              setRealValue(object, atof(value.c_str()));
2094          else if (type.isBool())          else if (type.isBool()) {
2095              setBoolValue(object, atof(value.c_str()));              String val = toLowerCase(value);
2096          else if (type.isEnum())              if (val == "true" || val == "yes" || val == "1")
2097                    setBoolValue(object, true);
2098                else if (val == "false" || val == "no" || val == "0")
2099                    setBoolValue(object, false);
2100                else
2101                    setBoolValue(object, atof(value.c_str()));
2102            } else if (type.isEnum())
2103              setEnumValue(object, atoll(value.c_str()));              setEnumValue(object, atoll(value.c_str()));
2104          else          else
2105              throw Exception("Not a primitive data type");              throw Exception("Not a primitive data type");
2106      }      }
2107    
2108        /** @brief Get value of object as string.
2109         *
2110         * Converts the current value of the given @a object into a textual string
2111         * and returns that string.
2112         *
2113         * @param object - object whose value shall be retrieved
2114         * @throws Exception if the given object is either invalid, or if the object
2115         *         is not a fundamental, primitive data type.
2116         */
2117      String Archive::valueAsString(const Object& object) {      String Archive::valueAsString(const Object& object) {
2118          if (!object)          if (!object)
2119              throw Exception("Invalid object");              throw Exception("Invalid object");
# Line 994  namespace Serialization { Line 2128  namespace Serialization {
2128          return _primitiveObjectValueToString(*pObject);          return _primitiveObjectValueToString(*pObject);
2129      }      }
2130    
2131        /** @brief Get integer value of object.
2132         *
2133         * Returns the current integer value of the requested integer @a object or
2134         * @c enum object.
2135         *
2136         * @param object - object whose value shall be retrieved
2137         * @throws Exception if the given object is either invalid, or if the object
2138         *         is neither an integer nor @c enum data type.
2139         */
2140        int64_t Archive::valueAsInt(const Object& object) {
2141            if (!object)
2142                throw Exception("Invalid object");
2143            if (!object.type().isInteger() && !object.type().isEnum())
2144                throw Exception("Object is neither an integer nor an enum");
2145            const Object* pObject = &object;
2146            if (object.type().isPointer()) {
2147                const Object& obj = objectByUID(object.uid(1));
2148                if (!obj) return 0;
2149                pObject = &obj;
2150            }
2151            return _primitiveObjectValueToNumber<int64_t>(*pObject);
2152        }
2153    
2154        /** @brief Get floating point value of object.
2155         *
2156         * Returns the current floating point value of the requested floating point
2157         * @a object.
2158         *
2159         * @param object - object whose value shall be retrieved
2160         * @throws Exception if the given object is either invalid, or if the object
2161         *         is not a floating point based type.
2162         */
2163        double Archive::valueAsReal(const Object& object) {
2164            if (!object)
2165                throw Exception("Invalid object");
2166            if (!object.type().isReal())
2167                throw Exception("Object is not an real type");
2168            const Object* pObject = &object;
2169            if (object.type().isPointer()) {
2170                const Object& obj = objectByUID(object.uid(1));
2171                if (!obj) return 0;
2172                pObject = &obj;
2173            }
2174            return _primitiveObjectValueToNumber<double>(*pObject);
2175        }
2176    
2177        /** @brief Get boolean value of object.
2178         *
2179         * Returns the current boolean value of the requested boolean @a object.
2180         *
2181         * @param object - object whose value shall be retrieved
2182         * @throws Exception if the given object is either invalid, or if the object
2183         *         is not a boolean data type.
2184         */
2185        bool Archive::valueAsBool(const Object& object) {
2186            if (!object)
2187                throw Exception("Invalid object");
2188            if (!object.type().isBool())
2189                throw Exception("Object is not a bool");
2190            const Object* pObject = &object;
2191            if (object.type().isPointer()) {
2192                const Object& obj = objectByUID(object.uid(1));
2193                if (!obj) return 0;
2194                pObject = &obj;
2195            }
2196            return _primitiveObjectValueToNumber<bool>(*pObject);
2197        }
2198    
2199      // *************** Archive::Syncer ***************      // *************** Archive::Syncer ***************
2200      // *      // *
2201    
# Line 1093  namespace Serialization { Line 2295  namespace Serialization {
2295      // *************** Exception ***************      // *************** Exception ***************
2296      // *      // *
2297    
2298        Exception::Exception() {
2299        }
2300    
2301        Exception::Exception(String format, ...) {
2302            va_list arg;
2303            va_start(arg, format);
2304            Message = assemble(format, arg);
2305            va_end(arg);
2306        }
2307    
2308        Exception::Exception(String format, va_list arg) {
2309            Message = assemble(format, arg);
2310        }
2311    
2312        /** @brief Print exception message to stdout.
2313         *
2314         * Prints the message of this Exception to the currently defined standard
2315         * output (that is to the terminal console for example).
2316         */
2317      void Exception::PrintMessage() {      void Exception::PrintMessage() {
2318          std::cout << "Serialization::Exception: " << Message << std::endl;          std::cout << "Serialization::Exception: " << Message << std::endl;
2319      }      }
2320    
2321        String Exception::assemble(String format, va_list arg) {
2322            char* buf = NULL;
2323            vasprintf(&buf, format.c_str(), arg);
2324            String s = buf;
2325            free(buf);
2326            return s;
2327        }
2328    
2329  } // namespace Serialization  } // namespace Serialization

Legend:
Removed from v.3168  
changed lines
  Added in v.3392

  ViewVC Help
Powered by ViewVC