22 #ifndef DBALLE_CORE_STRUCTBUF_H 23 #define DBALLE_CORE_STRUCTBUF_H 25 #include <wreport/error.h> 33 int make_anonymous_tmpfile();
34 void write_buffer(
int fd,
void* buf,
size_t size);
44 template<
typename T,
int bufsize=1024>
55 unsigned membuf_last = 0;
61 const T* readbuf = (
const T*)MAP_FAILED;
72 : membuf(new T[bufsize])
80 if (readbuf != MAP_FAILED)
81 munmap((
void*)readbuf, m_count *
sizeof(T));
87 size_t size()
const {
return m_count; }
95 if (readbuf != MAP_FAILED)
96 throw wreport::error_consistency(
"writing to a Structbuf that is already being read");
97 if (membuf_last == bufsize)
99 membuf[membuf_last++] = val;
106 if (tmpfile_fd == -1)
111 if (membuf_last) write_to_file();
114 readbuf = (
const T*)mmap(
nullptr, m_count *
sizeof(T), PROT_READ, MAP_SHARED, tmpfile_fd, 0);
115 if (readbuf == MAP_FAILED)
116 throw wreport::error_system(
"cannot map temporary file contents to memory");
129 if (tmpfile_fd == -1)
130 tmpfile_fd = structbuf::make_anonymous_tmpfile();
131 structbuf::write_buffer(tmpfile_fd, membuf,
sizeof(T) * membuf_last);
Buffer of simple structures that becomes file backed if it grows beyond a certain size...
Definition: structbuf.h:45
Copyright (C) 2008–2010 ARPA-SIM urpsim@smr.arpa.emr.it
Definition: cmdline.h:17
void ready_to_read()
Stop appending and get ready to read back the data.
Definition: structbuf.h:104
const T & operator[](size_t idx) const
Read back an item.
Definition: structbuf.h:121
void append(const T &val)
Append an item to the buffer.
Definition: structbuf.h:93
size_t size() const
Get the number of structures that have been added to the buffer so far.
Definition: structbuf.h:87
bool is_file_backed() const
Return true if the buffer has become file-backed.
Definition: structbuf.h:90