AutoBuffer.h 646 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #pragma once
  2. #include "foundation/error.h"
  3. #include <stdlib.h>
  4. /* an automatically growing buffer */
  5. class AutoBuffer
  6. {
  7. public:
  8. AutoBuffer()
  9. {
  10. buffer=0;
  11. buffer_length=0;
  12. }
  13. ~AutoBuffer()
  14. {
  15. free(buffer);
  16. }
  17. operator void *()
  18. {
  19. return buffer;
  20. }
  21. template <class ptr_t>
  22. ptr_t Get()
  23. {
  24. return (ptr_t)buffer;
  25. }
  26. int Reserve(size_t new_size)
  27. {
  28. if (new_size <= buffer_length)
  29. return NErr_Success;
  30. void *new_buffer = realloc(buffer, new_size);
  31. if (!new_buffer)
  32. return NErr_OutOfMemory;
  33. buffer = new_buffer;
  34. buffer_length = new_size;
  35. return NErr_Success;
  36. }
  37. private:
  38. void *buffer;
  39. size_t buffer_length;
  40. };