Posted By

svendiego on 03/12/10


Tagged

buffer memory


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

khouser


simple encapsulated memory buffer


 / Published in: C++
 

  1. /** simple encapsulated memory buffer
  2.  
  3.   memory is freed on destructing.
  4.  
  5.   can be resized, with options copydata and zerofill
  6.  
  7.   ( no extra reserve space is kept , unlike in std::vector)
  8.  
  9.   copies forbidden
  10.  
  11. */
  12. struct mem_buffer
  13. { char * p;
  14. size_t sz;
  15. enum { copydata = 1, zerofill = 2 };
  16.  
  17. mem_buffer() : p(0) , sz(0) {}
  18. explicit mem_buffer(size_t s, int opts) : p(0) , sz(0)
  19. { resize(s,opts); }
  20.  
  21. ~mem_buffer() { free(); }
  22.  
  23. size_t size() const { return sz; }
  24. void * ptr() const { return p; }
  25.  
  26. void resize(size_t nsz, int opts)
  27. { if(nsz == sz) return;
  28. char * np = (char *) malloc(nsz);
  29. int msz = sz<nsz?sz:nsz;
  30. if(opts & copydata) memcpy(np,p,msz);
  31. if(opts & zerofill)
  32. if(!(opts & copydata))
  33. memset(np,0,nsz);
  34. else if(nsz>sz) memset(np+sz,0,nsz-sz);
  35. sz = nsz;
  36. if(p) ::free(p);
  37. p = np;
  38. }
  39.  
  40. void growto(size_t nsz, int opts)
  41. { if(size()<nsz) resize(nsz,opts); }
  42.  
  43. void growto2(size_t nsz, int opts)
  44. { if(size()<nsz) resize( nsz>2*size()?nsz:2*size() ,opts); }
  45.  
  46. void free()
  47. { if(p) ::free(p); sz=0; }
  48.  
  49. private:
  50. mem_buffer(const mem_buffer & m) {}
  51. void operator = (const mem_buffer & m) {}
  52.  
  53. };

Report this snippet  

You need to login to post a comment.