nghttp2_rcbuf.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (C) 2015-2018 Alibaba Group Holding Limited
  3. */
  4. #include "nghttp2_rcbuf.h"
  5. #include <string.h>
  6. #include <assert.h>
  7. #include "nghttp2_mem.h"
  8. #include "nghttp2_helper.h"
  9. int nghttp2_rcbuf_new(nghttp2_rcbuf **rcbuf_ptr, size_t size,
  10. nghttp2_mem *mem) {
  11. uint8_t *p;
  12. p = nghttp2_mem_malloc(mem, sizeof(nghttp2_rcbuf) + size);
  13. if (p == NULL) {
  14. return NGHTTP2_ERR_NOMEM;
  15. }
  16. *rcbuf_ptr = (void *)p;
  17. (*rcbuf_ptr)->mem_user_data = mem->mem_user_data;
  18. (*rcbuf_ptr)->free = mem->free;
  19. (*rcbuf_ptr)->base = p + sizeof(nghttp2_rcbuf);
  20. (*rcbuf_ptr)->len = size;
  21. (*rcbuf_ptr)->ref = 1;
  22. return 0;
  23. }
  24. int nghttp2_rcbuf_new2(nghttp2_rcbuf **rcbuf_ptr, const uint8_t *src,
  25. size_t srclen, nghttp2_mem *mem) {
  26. int rv;
  27. rv = nghttp2_rcbuf_new(rcbuf_ptr, srclen + 1, mem);
  28. if (rv != 0) {
  29. return rv;
  30. }
  31. (*rcbuf_ptr)->len = srclen;
  32. *nghttp2_cpymem((*rcbuf_ptr)->base, src, srclen) = '\0';
  33. return 0;
  34. }
  35. /*
  36. * Frees |rcbuf| itself, regardless of its reference cout.
  37. */
  38. void nghttp2_rcbuf_del(nghttp2_rcbuf *rcbuf) {
  39. nghttp2_mem_free2(rcbuf->free, rcbuf, rcbuf->mem_user_data);
  40. }
  41. void nghttp2_rcbuf_incref(nghttp2_rcbuf *rcbuf) {
  42. if (rcbuf->ref == -1) {
  43. return;
  44. }
  45. ++rcbuf->ref;
  46. }
  47. void nghttp2_rcbuf_decref(nghttp2_rcbuf *rcbuf) {
  48. if (rcbuf == NULL || rcbuf->ref == -1) {
  49. return;
  50. }
  51. assert(rcbuf->ref > 0);
  52. if (--rcbuf->ref == 0) {
  53. nghttp2_rcbuf_del(rcbuf);
  54. }
  55. }
  56. nghttp2_vec nghttp2_rcbuf_get_buf(nghttp2_rcbuf *rcbuf) {
  57. nghttp2_vec res = {rcbuf->base, rcbuf->len};
  58. return res;
  59. }
  60. int nghttp2_rcbuf_is_static(const nghttp2_rcbuf *rcbuf) {
  61. return rcbuf->ref == -1;
  62. }