+static void buffer_transfer(struct buffer *buf, char *newdata, size_t newsize) {
+ if(buffer_wraps(buf)) {
+ // Old situation:
+ // [345......012]
+ // New situation:
+ // [012345......]
+ uint32_t tailsize = buf->size - buf->offset;
+ memcpy(newdata, buf->data + buf->offset, tailsize);
+ memcpy(newdata + tailsize, buf->data, buf->used - tailsize);
+ } else {
+ // Old situation:
+ // [....012345..]
+ // New situation:
+ // [012345......]
+ memcpy(newdata, buf->data + buf->offset, buf->used);
+ }
+
+ buf->offset = 0;
+ buf->size = newsize;
+}
+
+static void set_buffer_storage(struct buffer *buf, char *data, size_t size) {
+ if(size > UINT32_MAX) {
+ size = UINT32_MAX;
+ }
+
+ buf->maxsize = size;
+
+ if(data) {
+ if(buf->external) {
+ // Don't allow resizing an external buffer
+ abort();
+ }
+
+ if(size < buf->used) {
+ // Ignore requests for an external buffer if we are already using more than it can store
+ return;
+ }
+
+ // Transition from internal to external buffer
+ buffer_transfer(buf, data, size);
+ free(buf->data);
+ buf->data = data;
+ buf->external = true;
+ } else if(buf->external) {
+ // Transition from external to internal buf
+ size_t minsize = buf->used <= DEFAULT_SNDBUFSIZE ? DEFAULT_SNDBUFSIZE : buf->used;
+
+ if(minsize) {
+ data = malloc(minsize);
+
+ if(!data) {
+ // Cannot handle this
+ abort();
+ }
+
+ buffer_transfer(buf, data, minsize);
+ buf->data = data;
+ } else {
+ buf->data = NULL;
+ buf->size = 0;
+ }
+
+ buf->external = false;
+ } else {
+ // Don't do anything if the buffer wraps
+ if(buffer_wraps(buf)) {
+ return;
+ }
+
+ // Realloc internal storage
+ size_t minsize = max(DEFAULT_SNDBUFSIZE, buf->offset + buf->used);
+
+ if(minsize) {
+ data = realloc(buf->data, minsize);
+
+ if(data) {
+ buf->data = data;
+ buf->size = minsize;
+ }
+ } else {
+ free(buf->data);
+ buf->data = NULL;
+ buf->size = 0;
+ }
+ }
+}
+