lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sun, Nov 3, 2019 at 8:36 PM Abhijit Nandy <abhijit.nandy@gmail.com> wrote:

As you are using C++:
> extern "C" {

You could, very easily, make a class for the allocator, with a save
function, it would probably save you some headaches.

Something like... ( using a couple things from std, assuming c++11 or
better )...

UNTESTED!

class lua_allocator {
   unique_ptr<char> buffer;
   char * base;
   char * top;
   char * end;
   lua_allocator(int size)
     : buf_holder(new char[size])
     , base(buffer.get())
     , top(base)
     , end(base+size)
  {}
  // Writing inline, you may need to define them outlines, depending
on the standard used.

  // Reflect to a method for easy debugging.
  static void * lua_alloc(void* userData, void* ptr, size_t oldSize,
size_t newSize)  {
    return static_cast<lua_allocator>(userData)->lua_alloc(ptr,
oldSize, newSize);
  }
  // Condensing a bit...
  void * lua_alloc (void* ptr, size_t oldSize, size_t newSize) {
    if (newSize == 0) {
        //free(ptr);
        return 0;
    }  else {
        //return realloc(ptr, newSize);
      if (ptr != NULL) {
    if (newSize>oldSize) { // Bigger.
      // Copy contents
      if (newSize > end - top)
        return nullptr;
      auto res = top;
      memcpy(top, ptr, oldSize);
      top += newSize;
      return res;
    } else {
      // Shrinking or equal.
      return ptr;
    }
      } else { // Ptr == null
    if (newSize > end - top)
      return nullptr;
    auto res = top;
    top += newSize;
    return res;
      }
    }
  }
  // Now you have it packed, you have it easier to do things like:
  void save_to(vector<char> & holder) {
    holder.resize(top-base);
    copy(base, top, holder.begin()); // Or memcpy to holder.data()
  }
  bool restore_from(const vector char & holder) {
    auto l = holder.size();
    if (l>end-base) {
      return false; // Bad save vector.
    }
    copy(holder.begin(), holder.end(), base);
    top = base + l;
    returnm true.
  }
  // And even do things like this to avoid typos
  luaState * new_state() {
    return lua_newstate(lua_alloc, this);
  }
  // The thing is C++ gives you some minimum overhead ways to save/restore it,
  // and packing things let's you experiment easily.
  // i.e., once you have this you can experiment on doing things like
delta-coding the
  // copys so you can easily go back to different places in your program.

};

Francisco Olarte.