aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/binsaver/bin_saver.cpp
blob: 9bc28d149069b86c193e52563cba3d27d9ec4e01 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "bin_saver.h"

TClassFactory<IObjectBase>* pSaverClasses;
void StartRegisterSaveload() {
    if (!pSaverClasses)
        pSaverClasses = new TClassFactory<IObjectBase>; 
}
struct SBasicChunkInit {
    ~SBasicChunkInit() {
        if (pSaverClasses)
            delete pSaverClasses;
    }
} initSaver;

//////////////////////////////////////////////////////////////////////////
void IBinSaver::StoreObject(IObjectBase* pObject) {
    if (pObject) {
        Y_ASSERT(pSaverClasses->GetObjectTypeID(pObject) != -1 && "trying to save unregistered object"); 
    }

    ui64 ptrId = ((char*)pObject) - ((char*)nullptr);
    if (StableOutput) {
        ui32 id = 0;
        if (pObject) {
            if (!PtrIds.Get())
                PtrIds.Reset(new PtrIdHash);
            PtrIdHash::iterator pFound = PtrIds->find(pObject);
            if (pFound != PtrIds->end())
                id = pFound->second;
            else {
                id = PtrIds->ysize() + 1;
                PtrIds->insert(std::make_pair(pObject, id));
            }
        }
        ptrId = id;
    }

    DataChunk(&ptrId, sizeof(ptrId));
    if (!Objects.Get())
        Objects.Reset(new CObjectsHash);
    if (ptrId != 0 && Objects->find(ptrId) == Objects->end()) {
        ObjectQueue.push_back(pObject);
        (*Objects)[ptrId];
        int typeId = pSaverClasses->GetObjectTypeID(pObject);
        if (typeId == -1) {
            fprintf(stderr, "IBinSaver: trying to save unregistered object\n");
            abort();
        }
        DataChunk(&typeId, sizeof(typeId));
    }
}

IObjectBase* IBinSaver::LoadObject() {
    ui64 ptrId = 0;
    DataChunk(&ptrId, sizeof(ptrId));
    if (ptrId != 0) {
        if (!Objects.Get())
            Objects.Reset(new CObjectsHash);
        CObjectsHash::iterator pFound = Objects->find(ptrId);
        if (pFound != Objects->end())
            return pFound->second;
        int typeId;
        DataChunk(&typeId, sizeof(typeId));
        IObjectBase* pObj = pSaverClasses->CreateObject(typeId);
        Y_ASSERT(pObj != nullptr); 
        if (pObj == nullptr) {
            fprintf(stderr, "IBinSaver: trying to load unregistered object\n");
            abort();
        }
        (*Objects)[ptrId] = pObj;
        ObjectQueue.push_back(pObj);
        return pObj;
    }
    return nullptr;
}

IBinSaver::~IBinSaver() {
    for (size_t i = 0; i < ObjectQueue.size(); ++i) {
        AddPolymorphicBase(1, ObjectQueue[i]);
    }
}