var_mem_mngr.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #ifndef VAR_MEM_MNGR_H
  2. #define VAR_MEM_MNGR_H
  3. #include "types.h"
  4. namespace binom {
  5. template<class T>
  6. class VarMemoryManager {
  7. friend T;
  8. friend class Variable;
  9. friend struct NamedVariable;
  10. inline size_t msize() const {return static_cast<const T*>(this)->msizeImpl();}
  11. inline byte*& ptr() {return static_cast<T*>(this)->ptrImpl();}
  12. inline void* clone() const {return static_cast<const T*>(this)->cloneImpl();}
  13. inline void destroy() {static_cast<T*>(this)->destroyImpl();}
  14. inline void mch(size_t new_size) { ptr() = tryRealloc(ptr(), new_size); }
  15. void* madd(size_t add_size) {
  16. size_t shift = msize();
  17. mch(shift + add_size);
  18. return ptr() + shift;
  19. }
  20. void msub(size_t sub_size) {
  21. mch(msize() - sub_size);
  22. }
  23. void* maddto(void* to, size_t size) {
  24. size_t pos = reinterpret_cast<byte*>(to) - ptr();
  25. size_t old_size = msize();
  26. madd(size);
  27. memmove(ptr() + pos + size, ptr() + pos, old_size - pos);
  28. return ptr() + pos;
  29. }
  30. void msubfrom(void* from, size_t size) {
  31. if(from < ptr()) throw Exception(ErrCode::binom_out_of_range);
  32. size_t old_size = msize();
  33. memmove(from, reinterpret_cast<byte*>(from) + size,
  34. old_size - (reinterpret_cast<byte*>(from) - ptr()) - size);
  35. mch(old_size - size);
  36. }
  37. };
  38. }
  39. #endif // VAR_MEM_MNGR_H