serializer.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. //-----------------------------------------------------------------------------
  2. /**
  3. \brief Serialization general interface. Serializer API works with:
  4. - primitive types: int, float, string, bool, vector
  5. - dynamic containers: array, set, map
  6. - static arrays
  7. - complex types: classes
  8. \note Serializer provides deep serialization (it serialize class memebers and their members etc). To avoid serialization of certain class variable, use NonSerialized attribute.
  9. \par usage:
  10. @code
  11. class MyData
  12. {
  13. int m_id;
  14. autoptr map<string, float> m_values;
  15. [NonSerialized()]
  16. string m_dbg; // I don't want to serialize this variable
  17. }
  18. void Serialize(Serializer s)
  19. {
  20. int statArray[4] = {6,9,2,3};
  21. array<int> dynArray = {8,5,6,4};
  22. autoptr MyData data = new MyData();
  23. data.m_id = 965;
  24. data.m_values = map<string, float>;
  25. data.m_values.Insert("value1", 5.98);
  26. data.m_values.Insert("value2", 4.36);
  27. s.Write(10);
  28. s.Write("Hello");
  29. s.Write(statArray);
  30. s.Write(dynArray);
  31. s.Write(data);
  32. }
  33. void Deserialize(Serializer s)
  34. {
  35. int statArray[4];
  36. array<int> dynArray;
  37. MyData data;
  38. int someInt;
  39. string someString;
  40. s.Read(someInt);
  41. s.Read(someString);
  42. s.Read(statArray);
  43. s.Read(dynArray);
  44. s.Read(data);
  45. }
  46. @endcode
  47. */
  48. class Serializer: Managed
  49. {
  50. proto bool Write(void value_out);
  51. proto bool Read(void value_in);
  52. proto native bool CanWrite();
  53. proto native bool CanRead();
  54. protected void Serializer() {}
  55. protected void ~Serializer() {}
  56. };
  57. /**
  58. \brief Serializer API implementation for File IO. See Serializer for more info.
  59. \n usage:
  60. @code
  61. void TestSave()
  62. {
  63. FileSerializer file = new FileSerializer();
  64. string names[3] = {"alpha", "beta", "gama"};
  65. if (file.Open("test.save", FileMode.WRITE))
  66. {
  67. file.Write(10);
  68. file.Write("lalala");
  69. file.Write(name);
  70. file.Close();
  71. }
  72. }
  73. void TestLoad()
  74. {
  75. FileSerializer file = new FileSerializer();
  76. int intVal;
  77. string stringVal;
  78. string names[3];
  79. if (file.Open("test.save", FileMode.READ))
  80. {
  81. file.Read(intVal);
  82. file.Read(stringVal);
  83. file.Read(names);
  84. file.Close();
  85. }
  86. }
  87. @endcode
  88. */
  89. class FileSerializer: Serializer
  90. {
  91. void FileSerializer() {}
  92. void ~FileSerializer() {}
  93. proto native bool Open(string path, FileMode mode = FileMode.READ);
  94. proto native bool IsOpen();
  95. proto native void Close();
  96. }