1
0

GrowBuf.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #ifndef NULLSOFT_UTILITY_GROWBUF_H
  2. #define NULLSOFT_UTILITY_GROWBUF_H
  3. #include <memory.h>
  4. #include <stdlib.h>
  5. class GrowBuf
  6. {
  7. public:
  8. GrowBuf() {}
  9. ~GrowBuf()
  10. {
  11. if ( m_s )
  12. free( m_s );
  13. m_s = NULL;
  14. }
  15. void reserve( size_t len )
  16. {
  17. if ( len > m_alloc )
  18. {
  19. void *ne;
  20. m_alloc = len;
  21. ne = realloc( m_s, m_alloc );
  22. if ( !ne )
  23. {
  24. ne = malloc( m_alloc );
  25. memcpy( ne, m_s, m_used );
  26. free( m_s );
  27. }
  28. m_s = ne;
  29. }
  30. }
  31. size_t add( void *data, size_t len )
  32. {
  33. if ( !len )
  34. return 0;
  35. resize( m_used + len );
  36. memcpy( (char *)get() + m_used - len, data, len );
  37. return m_used - len;
  38. }
  39. void set( void *data, size_t len )
  40. {
  41. resize( len );
  42. memcpy( (char *)get(), data, len );
  43. }
  44. void resize( size_t newlen )
  45. {
  46. m_used = newlen;
  47. if ( newlen > m_alloc )
  48. {
  49. m_alloc = newlen * 2;
  50. if ( m_alloc < 1024 )
  51. m_alloc = 1024;
  52. void *ne = realloc( m_s, m_alloc );
  53. if ( !ne )
  54. {
  55. ne = malloc( m_alloc );
  56. if ( !ne )
  57. *( (char *)ne ) = NULL;
  58. memcpy( ne, m_s, m_used );
  59. free( m_s );
  60. }
  61. m_s = ne;
  62. }
  63. }
  64. size_t getlen()
  65. {
  66. return m_used;
  67. }
  68. void *get()
  69. {
  70. return m_s;
  71. }
  72. private:
  73. void *m_s = NULL;
  74. size_t m_alloc = 0;
  75. size_t m_used = 0;
  76. };
  77. #endif