bin_saver.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "bin_saver.h"
  2. TClassFactory<IObjectBase>* pSaverClasses;
  3. void StartRegisterSaveload() {
  4. if (!pSaverClasses)
  5. pSaverClasses = new TClassFactory<IObjectBase>;
  6. }
  7. struct SBasicChunkInit {
  8. ~SBasicChunkInit() {
  9. if (pSaverClasses)
  10. delete pSaverClasses;
  11. }
  12. } initSaver;
  13. //////////////////////////////////////////////////////////////////////////
  14. void IBinSaver::StoreObject(IObjectBase* pObject) {
  15. if (pObject) {
  16. Y_ASSERT(pSaverClasses->GetObjectTypeID(pObject) != -1 && "trying to save unregistered object");
  17. }
  18. ui64 ptrId = reinterpret_cast<ui64>(pObject) / sizeof(char);
  19. if (StableOutput) {
  20. ui32 id = 0;
  21. if (pObject) {
  22. if (!PtrIds.Get())
  23. PtrIds.Reset(new PtrIdHash);
  24. PtrIdHash::iterator pFound = PtrIds->find(pObject);
  25. if (pFound != PtrIds->end())
  26. id = pFound->second;
  27. else {
  28. id = PtrIds->ysize() + 1;
  29. PtrIds->insert(std::make_pair(pObject, id));
  30. }
  31. }
  32. ptrId = id;
  33. }
  34. DataChunk(&ptrId, sizeof(ptrId));
  35. if (!Objects.Get())
  36. Objects.Reset(new CObjectsHash);
  37. if (ptrId != 0 && Objects->find(ptrId) == Objects->end()) {
  38. ObjectQueue.push_back(pObject);
  39. (*Objects)[ptrId];
  40. int typeId = pSaverClasses->GetObjectTypeID(pObject);
  41. if (typeId == -1) {
  42. fprintf(stderr, "IBinSaver: trying to save unregistered object\n");
  43. abort();
  44. }
  45. DataChunk(&typeId, sizeof(typeId));
  46. }
  47. }
  48. IObjectBase* IBinSaver::LoadObject() {
  49. ui64 ptrId = 0;
  50. DataChunk(&ptrId, sizeof(ptrId));
  51. if (ptrId != 0) {
  52. if (!Objects.Get())
  53. Objects.Reset(new CObjectsHash);
  54. CObjectsHash::iterator pFound = Objects->find(ptrId);
  55. if (pFound != Objects->end())
  56. return pFound->second;
  57. int typeId;
  58. DataChunk(&typeId, sizeof(typeId));
  59. IObjectBase* pObj = pSaverClasses->CreateObject(typeId);
  60. Y_ASSERT(pObj != nullptr);
  61. if (pObj == nullptr) {
  62. fprintf(stderr, "IBinSaver: trying to load unregistered object\n");
  63. abort();
  64. }
  65. (*Objects)[ptrId] = pObj;
  66. ObjectQueue.push_back(pObj);
  67. return pObj;
  68. }
  69. return nullptr;
  70. }
  71. IBinSaver::~IBinSaver() {
  72. for (size_t i = 0; i < ObjectQueue.size(); ++i) {
  73. AddPolymorphicBase(1, ObjectQueue[i]);
  74. }
  75. }