title: libuv allocated memory buffers re-use techniques
body: <p>i am using <a href="http://docs.libuv.org/en/v1.x/" rel="noreferrer">libuv</a> for my extensively-network-interacting application and i am concerned about which techniques of re-using allocated memory would be at the same time efficent and safe with libuv callback deferrence of execution.</p>
  
  <p>At very basic layer, exposed to libuv user, one is getting need to specify buffer allocation callback alongside with setting up a handle reader:</p>
  
  <pre><code>UV_EXTERN int uv_read_start(uv_stream_t*, uv_alloc_cb alloc_cb, uv_read_cb read_cb);
  </code></pre>
  
  <p>where <code>uv_alloc_cb</code> is</p>
  
  <pre><code>typedef void (*uv_alloc_cb)(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf);
  </code></pre>
  
  <p>But here is the problem: this memory-allocating callback is invoked each time new message is comming via handle (say, each UDP datagram from <code>uv_udp_t</code> handle is received) and stright-forward allocation of new buffer for each incoming UDP datagram seems very non-memory-wise.</p>
  
  <p>So i am asking for a common C techniques (probably, within deferred execution context introduced by libuv callback system) of having the same allocated memory be re-used when possible.</p>
  
  <p>Also, i would like to stay windows-portable, if possible.</p>
  
  <p>Notes:</p>
  
  <ul>
  <li>i am aware of this question: <a href="https://stackoverflow.com/questions/19216045/does-libuv-provide-any-facilities-to-attach-a-buffer-to-a-connection-and-re-use">Does libuv provide any facilities to attach a buffer to a connection and re use it</a> ; it's accepted answer does not answers how to actually do the memory allocation right with libuv besides stating the fact that statically-allocated buffer is no-go. Especially, it is not covering the safety (with deferred write callbacks on the same buffer, which can overlap with another read callback invocation across multiple iterations of libuv main loop) aspect of buffer attached to a handle (either via wrapper structure or handle->data context).</li>
  <li><p>Reading <a href="http://nikhilm.github.io/uvbook/filesystem.html" rel="noreferrer">http://nikhilm.github.io/uvbook/filesystem.html</a> , i have noticed the following phrase under the snip <code>uvtee/main.c - Write to pipe</code>:</p>
  
  <blockquote>
    <p>We make a copy so we can free the two buffers from the two calls to write_data independently of each other. While acceptable for a demo program like this, you’ll probably want smarter memory management, like reference counted buffers or a pool of buffers in any major application.</p>
  </blockquote>
  
  <p>but i wasn't able to find any solutions involving reference counting on libuv buffers (how this could be properly performed?) or explicit examples of pools of buffers in libuv environment (is there any libraries for that?).</p></li>
  </ul>