sbuffer.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*
  2. * MessagePack for C simple buffer implementation
  3. *
  4. * Copyright (C) 2008-2009 FURUHASHI Sadayuki
  5. *
  6. * Distributed under the Boost Software License, Version 1.0.
  7. * (See accompanying file LICENSE_1_0.txt or copy at
  8. * http://www.boost.org/LICENSE_1_0.txt)
  9. */
  10. #ifndef MSGPACK_SBUFFER_H
  11. #define MSGPACK_SBUFFER_H
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #ifdef __cplusplus
  15. extern "C" {
  16. #endif
  17. /**
  18. * @defgroup msgpack_sbuffer Simple buffer
  19. * @ingroup msgpack_buffer
  20. * @{
  21. */
  22. typedef struct msgpack_sbuffer {
  23. size_t size;
  24. char* data;
  25. size_t alloc;
  26. } msgpack_sbuffer;
  27. static inline void msgpack_sbuffer_init(msgpack_sbuffer* sbuf)
  28. {
  29. memset(sbuf, 0, sizeof(msgpack_sbuffer));
  30. }
  31. static inline void msgpack_sbuffer_destroy(msgpack_sbuffer* sbuf)
  32. {
  33. free(sbuf->data);
  34. }
  35. static inline msgpack_sbuffer* msgpack_sbuffer_new(void)
  36. {
  37. return (msgpack_sbuffer*)calloc(1, sizeof(msgpack_sbuffer));
  38. }
  39. static inline void msgpack_sbuffer_free(msgpack_sbuffer* sbuf)
  40. {
  41. if(sbuf == NULL) { return; }
  42. msgpack_sbuffer_destroy(sbuf);
  43. free(sbuf);
  44. }
  45. #ifndef MSGPACK_SBUFFER_INIT_SIZE
  46. #define MSGPACK_SBUFFER_INIT_SIZE 8192
  47. #endif
  48. static inline int msgpack_sbuffer_write(void* data, const char* buf, size_t len)
  49. {
  50. msgpack_sbuffer* sbuf = (msgpack_sbuffer*)data;
  51. if(sbuf->alloc - sbuf->size < len) {
  52. void* tmp;
  53. size_t nsize = (sbuf->alloc) ?
  54. sbuf->alloc * 2 : MSGPACK_SBUFFER_INIT_SIZE;
  55. while(nsize < sbuf->size + len) {
  56. size_t tmp_nsize = nsize * 2;
  57. if (tmp_nsize <= nsize) {
  58. nsize = sbuf->size + len;
  59. break;
  60. }
  61. nsize = tmp_nsize;
  62. }
  63. tmp = realloc(sbuf->data, nsize);
  64. if(!tmp) { return -1; }
  65. sbuf->data = (char*)tmp;
  66. sbuf->alloc = nsize;
  67. }
  68. memcpy(sbuf->data + sbuf->size, buf, len);
  69. sbuf->size += len;
  70. return 0;
  71. }
  72. static inline char* msgpack_sbuffer_release(msgpack_sbuffer* sbuf)
  73. {
  74. char* tmp = sbuf->data;
  75. sbuf->size = 0;
  76. sbuf->data = NULL;
  77. sbuf->alloc = 0;
  78. return tmp;
  79. }
  80. static inline void msgpack_sbuffer_clear(msgpack_sbuffer* sbuf)
  81. {
  82. sbuf->size = 0;
  83. }
  84. /** @} */
  85. #ifdef __cplusplus
  86. }
  87. #endif
  88. #endif /* msgpack/sbuffer.h */