Buf.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "Buf.hpp"
  14. namespace ZeroTier {
  15. static std::atomic<uintptr_t> s_pool(0);
  16. void *Buf::operator new(std::size_t sz)
  17. {
  18. uintptr_t bb;
  19. for (;;) {
  20. bb = s_pool.exchange(~((uintptr_t)0));
  21. if (bb != ~((uintptr_t)0))
  22. break;
  23. }
  24. Buf *b;
  25. if (bb) {
  26. b = (Buf *)bb;
  27. s_pool.store(b->__nextInPool);
  28. } else {
  29. s_pool.store(0);
  30. b = (Buf *)malloc(sz);
  31. if (!b)
  32. throw std::bad_alloc();
  33. }
  34. b->__refCount.store(0);
  35. return (void *)b;
  36. }
  37. void Buf::operator delete(void *ptr)
  38. {
  39. if (ptr) {
  40. uintptr_t bb;
  41. for (;;) {
  42. bb = s_pool.exchange(~((uintptr_t)0));
  43. if (bb != ~((uintptr_t)0))
  44. break;
  45. }
  46. ((Buf *)ptr)->__nextInPool = bb;
  47. s_pool.store((uintptr_t)ptr);
  48. }
  49. }
  50. void Buf::freePool() noexcept
  51. {
  52. uintptr_t bb;
  53. for (;;) {
  54. bb = s_pool.exchange(~((uintptr_t)0));
  55. if (bb != ~((uintptr_t)0))
  56. break;
  57. }
  58. s_pool.store((uintptr_t)0);
  59. while (bb != 0) {
  60. uintptr_t next = ((Buf *)bb)->__nextInPool;
  61. free((void *)bb);
  62. bb = next;
  63. }
  64. }
  65. } // namespace ZeroTier