/ Published in: C++
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** simple encapsulated memory buffer memory is freed on destructing. can be resized, with options copydata and zerofill ( no extra reserve space is kept , unlike in std::vector) copies forbidden */ struct mem_buffer { char * p; size_t sz; enum { copydata = 1, zerofill = 2 }; mem_buffer() : p(0) , sz(0) {} explicit mem_buffer(size_t s, int opts) : p(0) , sz(0) { resize(s,opts); } ~mem_buffer() { free(); } size_t size() const { return sz; } void * ptr() const { return p; } void resize(size_t nsz, int opts) { if(nsz == sz) return; char * np = (char *) malloc(nsz); int msz = sz<nsz?sz:nsz; if(opts & copydata) memcpy(np,p,msz); if(opts & zerofill) if(!(opts & copydata)) memset(np,0,nsz); else if(nsz>sz) memset(np+sz,0,nsz-sz); sz = nsz; if(p) ::free(p); p = np; } void growto(size_t nsz, int opts) { if(size()<nsz) resize(nsz,opts); } void growto2(size_t nsz, int opts) { if(size()<nsz) resize( nsz>2*size()?nsz:2*size() ,opts); } void free() { if(p) ::free(p); sz=0; } private: mem_buffer(const mem_buffer & m) {} void operator = (const mem_buffer & m) {} };