newgrf_storage.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #ifndef NEWGRF_STORAGE_H
00013 #define NEWGRF_STORAGE_H
00014
00015 #include "core/alloc_func.hpp"
00016
00021 struct BaseStorageArray
00022 {
00024 virtual ~BaseStorageArray() {}
00025
00033 virtual void ClearChanges(bool keep_changes) = 0;
00034
00040 virtual void Store(uint pos, int32 value) = 0;
00041 };
00042
00049 template <typename TYPE, uint SIZE>
00050 struct PersistentStorageArray : BaseStorageArray {
00051 TYPE storage[SIZE];
00052 TYPE *prev_storage;
00053
00055 PersistentStorageArray() : prev_storage(NULL)
00056 {
00057 memset(this->storage, 0, sizeof(this->storage));
00058 }
00059
00061 ~PersistentStorageArray()
00062 {
00063 free(this->prev_storage);
00064 }
00065
00073 void Store(uint pos, int32 value)
00074 {
00075
00076 if (pos >= SIZE) return;
00077
00078
00079
00080 if (this->storage[pos] == value) return;
00081
00082
00083 if (this->prev_storage != NULL) {
00084 this->prev_storage = MallocT<TYPE>(SIZE);
00085 memcpy(this->prev_storage, this->storage, sizeof(this->storage));
00086
00087
00088
00089 AddChangedStorage(this);
00090 }
00091
00092 this->storage[pos] = value;
00093 }
00094
00100 TYPE Get(uint pos) const
00101 {
00102
00103 if (pos >= SIZE) return 0;
00104
00105 return this->storage[pos];
00106 }
00107
00112 void ClearChanges(bool keep_changes)
00113 {
00114 assert(this->prev_storage != NULL);
00115
00116 if (!keep_changes) {
00117 memcpy(this->storage, this->prev_storage, sizeof(this->storage));
00118 }
00119 free(this->prev_storage);
00120 }
00121 };
00122
00123
00130 template <typename TYPE, uint SIZE>
00131 struct TemporaryStorageArray : BaseStorageArray {
00132 TYPE storage[SIZE];
00133
00135 TemporaryStorageArray()
00136 {
00137 memset(this->storage, 0, sizeof(this->storage));
00138 }
00139
00145 void Store(uint pos, int32 value)
00146 {
00147
00148 if (pos >= SIZE) return;
00149
00150 this->storage[pos] = value;
00151 AddChangedStorage(this);
00152 }
00153
00159 TYPE Get(uint pos) const
00160 {
00161
00162 if (pos >= SIZE) return 0;
00163
00164 return this->storage[pos];
00165 }
00166
00167 void ClearChanges(bool keep_changes)
00168 {
00169 memset(this->storage, 0, sizeof(this->storage));
00170 }
00171 };
00172
00173 void AddChangedStorage(BaseStorageArray *storage);
00174 void ClearStorageChanges(bool keep_changes);
00175
00176 #endif