tb_tempbuffer.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // ================================================================================
  2. // == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
  3. // == See tb_core.h for more information. ==
  4. // ================================================================================
  5. #ifndef TB_TEMP_BUFFER_H
  6. #define TB_TEMP_BUFFER_H
  7. namespace tb {
  8. /** TBTempBuffer manages a buffer that will be deleted on destruction.
  9. The buffer size can grow by calling Reserve or Append, but it
  10. will never shrink during the lifetime of the object.
  11. */
  12. class TBTempBuffer
  13. {
  14. public:
  15. TBTempBuffer();
  16. ~TBTempBuffer();
  17. /** Make sure the buffer has at least size bytes.
  18. Returns false on OOM. */
  19. bool Reserve(int size);
  20. /** Get a pointer to the buffer data. */
  21. char *GetData() const { return m_data; }
  22. /** Return the size of the buffer in bytes. */
  23. int GetCapacity() const { return m_data_size; }
  24. /** Append data with size bytes at the end of the buffer and
  25. increase the append position with the same amount.
  26. Returns false on OOM. */
  27. bool Append(const char *data, int size);
  28. /** Increase the append position with size bytes without
  29. writing any data. This is useful if you want to write
  30. the data later and want to make sure space is reserved.
  31. Returns false on OOM. */
  32. bool AppendSpace(int size);
  33. /** Append a null terminated string (including the null termination)
  34. at the end of the buffer. The append position will be increased
  35. with the length of the text (excluding the null termination) so
  36. multiple calls will produce a concatenated null terminated string.
  37. Returns false on OOM. */
  38. bool AppendString(const char *str);
  39. /** Append a path without the ending filename.
  40. The buffer will be null terminated and the append position will be
  41. increased with the length of the path (excluding the null termination). */
  42. bool AppendPath(const char *full_path_and_filename);
  43. /** Set the position (in bytes) in the buffer where Append should write. */
  44. void SetAppendPos(int append_pos);
  45. /** Reset the append position to 0. */
  46. void ResetAppendPos() { m_append_pos = 0; }
  47. /** Return the current append position in in bytes. */
  48. int GetAppendPos() const { return m_append_pos; }
  49. private:
  50. int GetAppendReserveSize(int needed_size) const;
  51. char *m_data;
  52. int m_data_size;
  53. int m_append_pos;
  54. };
  55. }; // namespace tb
  56. #endif // TB_TEMP_BUFFER_H