+
+void Stream::set_backlog_size(size_t new_size)
+{
+ if (backlog_size == new_size) {
+ return;
+ }
+
+ string existing_data;
+ if (!read_tempfile_and_close(data_fd, &existing_data)) {
+ exit(1);
+ }
+
+ // Unwrap the data so it's no longer circular.
+ if (bytes_received <= backlog_size) {
+ existing_data.resize(bytes_received);
+ } else {
+ size_t pos = bytes_received % backlog_size;
+ existing_data = existing_data.substr(pos, string::npos) +
+ existing_data.substr(0, pos);
+ }
+
+ // See if we need to discard data.
+ if (new_size < existing_data.size()) {
+ size_t to_discard = existing_data.size() - new_size;
+ existing_data = existing_data.substr(to_discard, string::npos);
+ }
+
+ // Create a new, empty data file.
+ data_fd = make_tempfile("");
+ if (data_fd == -1) {
+ exit(1);
+ }
+ backlog_size = new_size;
+
+ // Now cheat a bit by rewinding, and adding all the old data back.
+ bytes_received -= existing_data.size();
+ iovec iov;
+ iov.iov_base = const_cast<char *>(existing_data.data());
+ iov.iov_len = existing_data.size();
+
+ vector<iovec> iovs;
+ iovs.push_back(iov);
+ add_data_raw(iovs);
+}