absl::Cord::GetAppendBuffer

Returns a CordBuffer, re-using potential existing capacity in this cord.

Synopsis

Declared in <absl/strings/cord.h>

CordBuffer
GetAppendBuffer(
    size_t capacity,
    size_t min_capacity = 16);

Description

Cord instances may have additional unused capacity in the last (or first) nodes of the underlying tree to facilitate amortized growth. This method allows applications to explicitly use this spare capacity if available, or create a new CordBuffer instance otherwise. If this cord has a final non-shared node with at least min_capacity available, then this method will return that buffer including its data contents. I.e.; the returned buffer will have a non-zero length, and a capacity of at least buffer.length + min_capacity. Otherwise, this method will return CordBuffer::CreateWithDefaultLimit(capacity).

Below an example of using GetAppendBuffer. Notice that in this example we use GetAppendBuffer() only on the first iteration. As we know nothing about any initial extra capacity in cord, we may be able to use the extra capacity. But as we add new buffers with fully utilized contents after that we avoid calling GetAppendBuffer() on subsequent iterations: while this works fine, it results in an unnecessary inspection of cord contents:

void AppendRandomDataToCord(absl::Cord &cord, size_t n) { bool first = true; while (n > 0) { CordBuffer buffer = first ? cord.GetAppendBuffer(n) : CordBuffer::CreateWithDefaultLimit(n); absl::Span<char> data = buffer.available_up_to(n); FillRandomValues(data.data(), data.size()); buffer.IncreaseLengthBy(data.size()); cord.Append(std::move(buffer)); n -= data.size(); first = false; } }

Return Value

A CordBuffer reusing spare capacity when available.

Parameters

NameDescription
capacityThe desired capacity of the returned buffer.
min_capacityThe minimum extra capacity required to reuse existing spare capacity.