osrm-backend/include/osmium/memory/buffer.hpp

758 lines
28 KiB
C++
Raw Normal View History

#ifndef OSMIUM_MEMORY_BUFFER_HPP
#define OSMIUM_MEMORY_BUFFER_HPP
/*
This file is part of Osmium (http://osmcode.org/libosmium).
Copyright 2013-2016 Jochen Topf <jochen@topf.org> and others (see README).
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstring>
#include <functional>
#include <iterator>
#include <memory>
#include <stdexcept>
#include <utility>
#include <osmium/memory/item.hpp>
#include <osmium/memory/item_iterator.hpp>
#include <osmium/osm/entity.hpp>
#include <osmium/util/compatibility.hpp>
namespace osmium {
/**
* Exception thrown by the osmium::memory::Buffer class when somebody tries
* to write data into a buffer and it doesn't fit. Buffers with internal
* memory management will not throw this exception, but increase their size.
*/
struct buffer_is_full : public std::runtime_error {
buffer_is_full() :
std::runtime_error("Osmium buffer is full") {
}
}; // struct buffer_is_full
/**
* @brief Memory management of items in buffers and iterators over this data.
*/
namespace memory {
/**
* A memory area for storing OSM objects and other items. Each item stored
* has a type and a length. See the Item class for details.
*
* Data can be added to a buffer piece by piece using reserve_space() and
* add_item(). After all data that together forms an item is added, it must
* be committed using the commit() call. Usually this is done through the
* Builder class and its derived classes.
*
* You can iterate over all items in a buffer using the iterators returned
* by begin(), end(), cbegin(), and cend().
*
* Buffers exist in two flavours, those with external memory management and
* those with internal memory management. If you already have some memory
* with data in it (for instance read from disk), you create a Buffer with
* external memory management. It is your job then to free the memory once
* the buffer isn't used any more. If you don't have memory already, you can
* create a Buffer object and have it manage the memory internally. It will
* dynamically allocate memory and free it again after use.
*
* By default, if a buffer gets full it will throw a buffer_is_full exception.
* You can use the set_full_callback() method to set a callback functor
* which will be called instead of throwing an exception. The full
* callback functionality is deprecated and will be removed in the
* future. See the documentation for set_full_callback() for alternatives.
*/
class Buffer {
public:
// This is needed so we can call std::back_inserter() on a Buffer.
using value_type = Item;
enum class auto_grow : bool {
yes = true,
no = false
}; // enum class auto_grow
private:
std::unique_ptr<unsigned char[]> m_memory;
unsigned char* m_data;
size_t m_capacity;
size_t m_written;
size_t m_committed;
auto_grow m_auto_grow {auto_grow::no};
std::function<void(Buffer&)> m_full;
public:
/**
* The constructor without any parameters creates an invalid,
* buffer, ie an empty hull of a buffer that has no actual memory
* associated with it. It can be used to signify end-of-data.
*
* Most methods of the Buffer class will not work with an invalid
* buffer.
*/
Buffer() noexcept :
m_memory(),
m_data(nullptr),
m_capacity(0),
m_written(0),
m_committed(0) {
}
/**
* Constructs a valid externally memory-managed buffer using the
* given memory and size.
*
* @param data A pointer to some already initialized data.
* @param size The size of the initialized data.
*
* @throws std::invalid_argument if the size isn't a multiple of
* the alignment.
*/
explicit Buffer(unsigned char* data, size_t size) :
m_memory(),
m_data(data),
m_capacity(size),
m_written(size),
m_committed(size) {
if (size % align_bytes != 0) {
throw std::invalid_argument("buffer size needs to be multiple of alignment");
}
}
/**
* Constructs a valid externally memory-managed buffer with the
* given capacity that already contains 'committed' bytes of data.
*
* @param data A pointer to some (possibly initialized) data.
* @param capacity The size of the memory for this buffer.
* @param committed The size of the initialized data. If this is 0, the buffer startes out empty.
*
* @throws std::invalid_argument if the capacity or committed isn't
* a multiple of the alignment.
*/
explicit Buffer(unsigned char* data, size_t capacity, size_t committed) :
m_memory(),
m_data(data),
m_capacity(capacity),
m_written(committed),
m_committed(committed) {
if (capacity % align_bytes != 0) {
throw std::invalid_argument("buffer capacity needs to be multiple of alignment");
}
if (committed % align_bytes != 0) {
throw std::invalid_argument("buffer parameter 'committed' needs to be multiple of alignment");
}
}
/**
* Constructs a valid internally memory-managed buffer with the
* given capacity.
* Will internally get dynamic memory of the required size.
* The dynamic memory will be automatically freed when the Buffer
* is destroyed.
*
* @param capacity The (initial) size of the memory for this buffer.
* @param auto_grow Should this buffer automatically grow when it
* becomes to small?
*
* @throws std::invalid_argument if the capacity isn't a multiple
* of the alignment.
*/
explicit Buffer(size_t capacity, auto_grow auto_grow = auto_grow::yes) :
m_memory(new unsigned char[capacity]),
m_data(m_memory.get()),
m_capacity(capacity),
m_written(0),
m_committed(0),
m_auto_grow(auto_grow) {
if (capacity % align_bytes != 0) {
throw std::invalid_argument("buffer capacity needs to be multiple of alignment");
}
}
// buffers can not be copied
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
// buffers can be moved
Buffer(Buffer&&) = default;
Buffer& operator=(Buffer&&) = default;
~Buffer() = default;
/**
* Return a pointer to data inside the buffer.
*
* @pre The buffer must be valid.
*/
unsigned char* data() const noexcept {
assert(m_data);
return m_data;
}
/**
* Returns the capacity of the buffer, ie how many bytes it can
* contain. Always returns 0 on invalid buffers.
*/
size_t capacity() const noexcept {
return m_capacity;
}
/**
* Returns the number of bytes already filled in this buffer.
* Always returns 0 on invalid buffers.
*/
size_t committed() const noexcept {
return m_committed;
}
/**
* Returns the number of bytes currently filled in this buffer that
* are not yet committed.
* Always returns 0 on invalid buffers.
*/
size_t written() const noexcept {
return m_written;
}
/**
* This tests if the current state of the buffer is aligned
* properly. Can be used for asserts.
*
* @pre The buffer must be valid.
*/
bool is_aligned() const noexcept {
assert(m_data);
return (m_written % align_bytes == 0) && (m_committed % align_bytes == 0);
}
/**
* Set functor to be called whenever the buffer is full
* instead of throwing buffer_is_full.
*
* The behaviour is undefined if you call this on an invalid
* buffer.
*
* @pre The buffer must be valid.
*
* @deprecated
* Callback functionality will be removed in the future. Either
* detect the buffer_is_full exception or use a buffer with
* auto_grow::yes. If you want to avoid growing buffers, check
* that the used size of the buffer (committed()) is small enough
* compared to the capacity (for instance small than 90% of the
* capacity) before adding anything to the Buffer. If the buffer
* is initialized with auto_grow::yes, it will still grow in the
* rare case that a very large object will be added taking more
* than the difference between committed() and capacity().
*/
OSMIUM_DEPRECATED void set_full_callback(std::function<void(Buffer&)> full) {
assert(m_data);
m_full = full;
}
/**
* Grow capacity of this buffer to the given size.
* This works only with internally memory-managed buffers.
* If the given size is not larger than the current capacity,
* nothing is done.
* Already written but not committed data is discarded.
*
* @pre The buffer must be valid.
*
* @param size New capacity.
*
* @throws std::logic_error if the buffer doesn't use internal
* memory management.
* @throws std::invalid_argument if the size isn't a multiple
* of the alignment.
* @throws std::bad_alloc if there isn't enough memory available.
*/
void grow(size_t size) {
assert(m_data);
if (!m_memory) {
throw std::logic_error("Can't grow Buffer if it doesn't use internal memory management.");
}
if (m_capacity < size) {
if (size % align_bytes != 0) {
throw std::invalid_argument("buffer capacity needs to be multiple of alignment");
}
std::unique_ptr<unsigned char[]> memory(new unsigned char[size]);
std::copy_n(m_memory.get(), m_capacity, memory.get());
using std::swap;
swap(m_memory, memory);
m_data = m_memory.get();
m_capacity = size;
}
}
/**
* Mark currently written bytes in the buffer as committed.
*
* @pre The buffer must be valid and aligned properly (as indicated
* by is_aligned().
*
* @returns Number of committed bytes before this commit. Can be
* used as an offset into the buffer to get to the
* object being committed by this call.
*/
size_t commit() {
assert(m_data);
assert(is_aligned());
const size_t offset = m_committed;
m_committed = m_written;
return offset;
}
/**
* Roll back changes in buffer to last committed state.
*
* @pre The buffer must be valid.
*/
void rollback() {
assert(m_data);
m_written = m_committed;
}
/**
* Clear the buffer.
*
* No-op on an invalid buffer.
*
* @returns Number of bytes in the buffer before it was cleared.
*/
size_t clear() {
const size_t committed = m_committed;
m_written = 0;
m_committed = 0;
return committed;
}
/**
* Get the data in the buffer at the given offset.
*
* @pre The buffer must be valid.
*
* @tparam T Type we want to the data to be interpreted as.
*
* @returns Reference of given type pointing to the data in the
* buffer.
*/
template <typename T>
T& get(const size_t offset) const {
assert(m_data);
return *reinterpret_cast<T*>(&m_data[offset]);
}
/**
* Reserve space of given size in buffer and return pointer to it.
* This is the only way of adding data to the buffer. You reserve
* the space and then fill it.
*
* Note that you have to eventually call commit() to actually
* commit this data.
*
* If there isn't enough space in the buffer, one of three things
* can happen:
*
* * If you have set a callback with set_full_callback(), it is
* called. After the call returns, you must have either grown
* the buffer or cleared it by calling buffer.clear(). (Usage
* of the full callback is deprecated and this functionality
* will be removed in the future. See the documentation for
* set_full_callback() for alternatives.
* * If no callback is defined and this buffer uses internal
* memory management, the buffers capacity is grown, so that
* the new data will fit.
* * Else the buffer_is_full exception is thrown.
*
* @pre The buffer must be valid.
*
* @param size Number of bytes to reserve.
*
* @returns Pointer to reserved space. Note that this pointer is
* only guaranteed to be valid until the next call to
* reserve_space().
*
* @throws osmium::buffer_is_full if the buffer is full there is
* no callback defined and the buffer isn't auto-growing.
*/
unsigned char* reserve_space(const size_t size) {
assert(m_data);
// try to flush the buffer empty first.
if (m_written + size > m_capacity && m_full) {
m_full(*this);
}
// if there's still not enough space, then try growing the buffer.
if (m_written + size > m_capacity) {
if (m_memory && (m_auto_grow == auto_grow::yes)) {
// double buffer size until there is enough space
size_t new_capacity = m_capacity * 2;
while (m_written + size > new_capacity) {
new_capacity *= 2;
}
grow(new_capacity);
} else {
throw osmium::buffer_is_full();
}
}
unsigned char* data = &m_data[m_written];
m_written += size;
return data;
}
/**
* Add an item to the buffer. The size of the item is stored inside
* the item, so we know how much memory to copy.
*
* Note that you have to eventually call commit() to actually
* commit this data.
*
* @pre The buffer must be valid.
*
* @tparam T Class of the item to be copied.
*
* @param item Reference to the item to be copied.
*
* @returns Reference to newly copied data in the buffer.
*/
template <typename T>
T& add_item(const T& item) {
assert(m_data);
unsigned char* target = reserve_space(item.padded_size());
std::copy_n(reinterpret_cast<const unsigned char*>(&item), item.padded_size(), target);
return *reinterpret_cast<T*>(target);
}
/**
* Add committed contents of the given buffer to this buffer.
*
* @pre The buffer must be valid.
*
* Note that you have to eventually call commit() to actually
* commit this data.
*
* @param buffer The source of the copy. Must be valid.
*/
void add_buffer(const Buffer& buffer) {
assert(m_data && buffer);
unsigned char* target = reserve_space(buffer.committed());
std::copy_n(buffer.data(), buffer.committed(), target);
}
/**
* Add an item to the buffer. This function is provided so that
* you can use std::back_inserter.
*
* @pre The buffer must be valid.
*
* @param item The item to be added.
*/
void push_back(const osmium::memory::Item& item) {
assert(m_data);
add_item(item);
commit();
}
/**
* An iterator that can be used to iterate over all items of
* type T in a buffer.
*/
template <typename T>
using t_iterator = osmium::memory::ItemIterator<T>;
/**
* A const iterator that can be used to iterate over all items of
* type T in a buffer.
*/
template <typename T>
using t_const_iterator = osmium::memory::ItemIterator<const T>;
/**
* An iterator that can be used to iterate over all OSMEntity
* objects in a buffer.
*/
using iterator = t_iterator<osmium::OSMEntity>;
/**
* A const iterator that can be used to iterate over all OSMEntity
* objects in a buffer.
*/
using const_iterator = t_const_iterator<osmium::OSMEntity>;
Squashed 'third_party/libosmium/' changes from 2282c84..80df1d6 80df1d6 Release v2.9.0 110dc5c Update change log. 6ad5829 Better handling of areas with duplicate segments. f5985ed Better exception message for invalid areas. fa09300 Explicit cast to make intent clear. 6f9b522 Fix name of struct stat on Windows. 6b0a47b Clean up code in data tests. aa1226c Fix progress bar. 3663a19 Extend ProgressBar class so that it works with multiple files. 40c4d5a Add version of file_size() taking a file name. 43a2fac Merge pull request #162 from osmcode/windows-build-scripts cc2305d [skip travis] 1st iteration of new build scripts 7abe4e1 Clean up disk location cache examples. 48841d5 Update change log. cf854e9 Change timestamp parser. 01aa8c7 Add examples osmium_pub_names and osmium_road_length. 483c9f2 Benchmark code cleanup. 3ffea2d Cleaned up some test code. 80f0ff7 Explicit conversion from int to bool. 0ba5918 Write space after progress bar to defend against glitches in output. 8584423 Change progress bar to take max_size on construction. d2c7585 Only call gzoffset when compiling with zlib > 1.2.4. 1b417e5 Add support for a progress report in osmium::io::Reader(). 3b4c8c8 Minor cleanup of appveyor config. d787e25 Fix OPL parser: Relation member without role at end of line. 53ca080 Make lots of variables const. d776ab2 Add to change log. eec3b62 Properly initialize m_data field. cc607e1 Take argument by const ref. be1e346 Remove unused function. 2a356ee Make lots of one-argument constructors explicit. adca74f Add comments to and cleanup up examples. 381e535 Simplify WKB code. b49efd8 Fix opl_parse_changeset_id() return type. bb52e57 Use uint64_t for line count and column to be on the safe side. 243f6a7 Use parentheses to make sure the right precedence is used. 5a7648e Consistently catch by const ref unless var needs to be non-const. e3be990 Avoid some warnings. c436d92 Do not include unistd.h on Windows. 95b228c Add dummy function to avoid warnings. f276ca3 Fixed includes and changelog update. 8c54bd9 Change timestamp error message. 27e1d5c Add OPL parser. 1d2caab Add more includes to osm.hpp to make usual osmium use simpler. 9d88361 More tests for area CRC. 4f8964d Initialize Item::m_diff member on construction. f2b648b Parse coordinates in scientific notations ourselves. b01323f More include fixes. 69f39d4 Fix some includes. 156536d Make padded_length a plain function, not a template function. 65cd1dc Extend functions to set Location lon/lat. 98b7b17 Update to protozero 1.4.2. a6420cf Add diff indicator to items and use for diff opl and debug output. 0ef02a3 Add workaround for YCM. 3a986f4 Update protozero version. 5245c5b Document osmium_count example program and add memory usage output. 796ca13 Document handler class. 2ba1c1f Add example for mercator projection and tiles. 201f744 Restrict tiles to zoom <= 30. 202291d Add member_type_string class. 494ed6e Cleaned up Tile tests. af13a8b Add documentation and range checks to Tile struct. 9df5d91 Some small changes to avoid conversion warnings. afac031 Explicit cast to avoid warning. 8188f66 Better contribution info. fa89d1d Fixed a problem limiting cache file sizes on Windows to 32 bit. 23a89df Remove obsolete info about versioning from CONTRIBUTING.md file. 115ae23 Release v2.8.0 4174b3c Style fix. 1795dcb Function wait_and_pop_with_timeout() is not needed any more. 4a3a71b Fix for possible threading problem. cc85925 Updated change log. 67bc8b1 Use unordered_map instead of map in PBF string table code. 18b7b66 Set better default for string table chunk size and document it. e6d7410 Remove dependency on sparsehash and boost program_options for examples. 14d92d6 Fix regression: Debug output of invalid location works again. ef91ce1 Bugfix: PBF String table corruption when there are many strings. 649af78 Remove DeltaEncodeIterator completely. 56e5ac2 Function getting queue sizes from environment uses default when getting 0. bfaab7d Add change log. d260339 Remove use of PROTOZERO_STRICT_API macro. c61722d Remove use of DeltaEncodeIterator simplifying code. f7c60b6 Updates for new protozero. 0bdfb9d Updated change log. bb56cbb Switch to newest protozero 1.4.0. 9e19a82 Add ccache support to CMake cnfig, better travis builds. 00d8868 Make I/O max queue sizes configurable via environment. dc7e504 Remove unused debugging code. 13f66a0 Track pop() calls and queue underruns when OSMIUM_DEBUG_QUEUE_SIZE is set. 5c2e367 Add EWKT support. 8f7c7d3 Automatically set correct SRID when creating geometries. ff11893 Better check of optional components in CMake config. 4562429 Use fallback implementation for coordinates given in scientific notation. 3bdf46e Mark enable_debug_output() as deprecated. ea1093e Update catch unit test framework. 8623f1e Release v2.7.2 e135dd8 Fix data corruption regression in mmap based indexes. adbd3b0 Do not output empty discussion tags in changeset XML output. 8126fbb Formatting. c6970fd Fix coordinate output. 3471b4b Resize output string once in output_int(). 0ddf0e7 Use our own function to convert integers to strings instead of printf. f9a1dd3 Reading and writing coordinates is now independant of locale. 8104294 Use hand-crafted function for hex output (faster than printf). 0bb452a Fix links in change log. 1862d06 Release v2.7.1 8bfe2ba Release v2.7.0 c3604f3 Use 64bit counter in area stats. 9e589b3 Update gdalcpp.hpp from upstream. fd55d9b Cleanup of OGR-related code. d0c53e0 Fix bug: Relation wasn't found correctly from member. 24145f9 Use make_iterator helper function. a8a287d Refactor count_not_removed function. (No template necessary.) 389332a Also print removed flag from member_meta. 5e7c5d0 Remove unnecessary overload of begin() and end() function in iterator_range. 2ec007f Do not add rings to invalid area, even if create_empty_areas is set. fee8b73 Optionally keep type tag in area assembler. Better doc for config. c7e1f8a Fix timer output in assembler code. 032ab40 Update change log. dcfa439 Node location store keeps track of whether node ids are ordered. 54d5eb8 Add tests for new file based index code. 4fe5b30 Use correct empty value when initializing index. 40b5c79 Static or not static, that is the question. aaa9b46 Open index file with minimum size, because zero-sized mmap is not allowed. fea2337 Fix for disk-based indexes. 428a413 More tests of corner cases for id to location index. 9d2a31b Add config option to areas assembler for only creating some areas. d11bf8d Count and report inner rings with the same tags as relation/outer rings. bde10c4 Speed up copy of tags. e4c9f87 Revert "Consistently remove some tags from area." 9cd7a03 Set areas assembly config setting create_empty_areas to true by default. 660fb63 Better ordering of OSMObjects. b4199c2 Use std::strcmp instead of just strcmp. 579c34b Better field width/precision in problem reporter. a2ebeeb Use field names with 8 characters or less in OGR problem reporter. ef523fe Switch remaining "typedef"s to "using". 19425f8 Switching from "typedef" to "using" in geom code. b13c2be More cases of switching from "typedef" to "using". 7f53977 Refactoring iterators: Not derived from std::iterator any more. 1922224 Consistently remove some tags from area. 295495f Fix check for detecting wrong role. 9aa6d46 Report more IDs in problem reporters. d7a5da7 Remove now unused spike segment reporter. 0666d66 Only report duplicate segments if they belong to the same way. 9e17f89 Improved error reporting for area assembler. e983a48 More code cleanup and docs. 927eeda Replace awkward std::pair construct by real class. d0543b9 Various area code refactorings. 0ae8f07 Do not build areas for ways with tag area=no. d4cabe7 Add some convenience functions to check for tags in TagList. 99f4be9 Add missing include. a8dda78 Travis: Only run tests if build succeeded. 9db3034 Add missing "nodes" fields. 50e9fcb Report ways that are in multiple rings as errors. 58a3669 Add some paranoia asserts. 3958c1d Use iterator_range to make equal_range results easier to use. c12c710 Add for_each_member() function to iterate over members of an mp relation. ca35452 Change argument order in create_area() functions. 4473ae1 Keep stats on multipolygons with no tags on the relation. 12c5335 Bugfix: Check that there is a problem reporter before using it. ec2afce Update change log. 5af2ec9 Use new area assembler interface in multipolygon collector. 73e3440 Some code cleanup in area code and new interface for calling assembler. 7737479 Add the number of nodes in area to problem reporter. b4f9343 Use const_iterator where possible. 02372b2 Simplify code that checks for open rings. 8d6099e Pull out location_to_ring_map into details ns and add == and < ops. 1a05042 Mixed code cleanups and added comments. 4b8d1be Ignore empty role when checking inner/outer roles on multipolygons. e22f573 Now GCC is complaining about the clang pragma... 48000c0 Add some missing includes and forward declarations. ba9504a Workaround for bug in old libc. a138265 Completely new algorithm for assembling multipolygons. 74054bd Add specialization of std::hash function for Location. 5ed4c90 Use newest gdalcpp.hpp with implicit transaction support. 676949e Add "locations_on_ways" support for OPL format, too. ce05c19 Add support for reading/writing XML/PBF files with locations on ways. 62b2ee4 Fix checksum test. bd512a8 Added "add_crc32" file option for adding CRC32 checksum to debug output. 3a100fa Incorporate locations in NodeRefs into CRC32 checksum. ac02f86 Update catch.hpp to newest version. Removed outdated info in README. 481f48b When assembling areas ignore ways containing no or only a single node. a0ae33a Fix unsigned overflow in pool.hpp. 91b8adf Fix undefined behaviour in WKB writer. 697f460 Check results of dynamic casts. f1e4571 Fix from_item_type() implementation so it also works with undefined type. 65df99b Add future_queue_type alias to simplify code. 4340e4d Removed SortedQueue implementation which was never used. cdd8f8c Add version.hpp with macros defining version of the library. ff5d42a Update to newest gdalcpp.hpp. a184f66 Update change log. 0ea76f7 Add osmium::Area::outer_rings() and inner_rings() functions. b0404b7 New ItemIteratorRange class for iteration over buffers and subitems. eff8a7c Add default type to string_to_object_id for IDs without type prefix. e877a6f Clean up code inner vs. outer ring in geometry factory. 9224be5 Disable use of XML entities in OSM files. 9d9fa08 Output operator of location shows full precision of coordinates. 9a8e7c0 Documentation fixes. git-subtree-dir: third_party/libosmium git-subtree-split: 80df1d6850bdfa661587839b77dcea0ab8fc814a
2016-10-03 13:08:59 -04:00
template <typename T>
ItemIteratorRange<T> select() {
return ItemIteratorRange<T>{m_data, m_data + m_committed};
}
template <typename T>
ItemIteratorRange<const T> select() const {
return ItemIteratorRange<const T>{m_data, m_data + m_committed};
}
/**
* Get iterator for iterating over all items of type T in the
* buffer.
*
* @pre The buffer must be valid.
*
* @returns Iterator to first item of type T in the buffer.
*/
template <typename T>
t_iterator<T> begin() {
assert(m_data);
return t_iterator<T>(m_data, m_data + m_committed);
}
/**
* Get iterator for iterating over all objects of class OSMEntity
* in the buffer.
*
* @pre The buffer must be valid.
*
* @returns Iterator to first OSMEntity in the buffer.
*/
iterator begin() {
assert(m_data);
return iterator(m_data, m_data + m_committed);
}
/**
* Get iterator for iterating over all items of type T in the
* buffer.
*
* @pre The buffer must be valid.
*
* @returns Iterator to first item of type T after given offset
* in the buffer.
*/
template <typename T>
t_iterator<T> get_iterator(size_t offset) {
assert(m_data);
return t_iterator<T>(m_data + offset, m_data + m_committed);
}
/**
* Get iterator for iterating over all objects of class OSMEntity
* in the buffer.
*
* @pre The buffer must be valid.
*
* @returns Iterator to first OSMEntity after given offset in the
* buffer.
*/
iterator get_iterator(size_t offset) {
assert(m_data);
return iterator(m_data + offset, m_data + m_committed);
}
/**
* Get iterator for iterating over all items of type T in the
* buffer.
*
* @pre The buffer must be valid.
*
* @returns End iterator.
*/
template <typename T>
t_iterator<T> end() {
assert(m_data);
return t_iterator<T>(m_data + m_committed, m_data + m_committed);
}
/**
* Get iterator for iterating over all objects of class OSMEntity
* in the buffer.
*
* @pre The buffer must be valid.
*
* @returns End iterator.
*/
iterator end() {
assert(m_data);
return iterator(m_data + m_committed, m_data + m_committed);
}
template <typename T>
t_const_iterator<T> cbegin() const {
assert(m_data);
return t_const_iterator<T>(m_data, m_data + m_committed);
}
const_iterator cbegin() const {
assert(m_data);
return const_iterator(m_data, m_data + m_committed);
}
template <typename T>
t_const_iterator<T> get_iterator(size_t offset) const {
assert(m_data);
return t_const_iterator<T>(m_data + offset, m_data + m_committed);
}
const_iterator get_iterator(size_t offset) const {
assert(m_data);
return const_iterator(m_data + offset, m_data + m_committed);
}
template <typename T>
t_const_iterator<T> cend() const {
assert(m_data);
return t_const_iterator<T>(m_data + m_committed, m_data + m_committed);
}
const_iterator cend() const {
assert(m_data);
return const_iterator(m_data + m_committed, m_data + m_committed);
}
template <typename T>
t_const_iterator<T> begin() const {
return cbegin<T>();
}
const_iterator begin() const {
return cbegin();
}
template <typename T>
t_const_iterator<T> end() const {
return cend<T>();
}
const_iterator end() const {
return cend();
}
/**
* In a bool context any valid buffer is true.
*/
explicit operator bool() const noexcept {
return m_data != nullptr;
}
void swap(Buffer& other) {
using std::swap;
swap(m_memory, other.m_memory);
swap(m_data, other.m_data);
swap(m_capacity, other.m_capacity);
swap(m_written, other.m_written);
swap(m_committed, other.m_committed);
swap(m_auto_grow, other.m_auto_grow);
swap(m_full, other.m_full);
}
/**
* Purge removed items from the buffer. This is done by moving all
* non-removed items forward in the buffer overwriting removed
* items and then correcting the m_written and m_committed numbers.
*
* Note that calling this function invalidates all iterators on
* this buffer and all offsets in this buffer.
*
* For every non-removed item that moves its position, the function
* 'moving_in_buffer' is called on the given callback object with
* the old and new offsets in the buffer where the object used to
* be and is now, respectively. This call can be used to update any
* indexes.
*
* @pre The buffer must be valid.
*/
template <typename TCallbackClass>
void purge_removed(TCallbackClass* callback) {
assert(m_data);
if (begin() == end()) {
return;
}
iterator it_write = begin();
iterator next;
for (iterator it_read = begin(); it_read != end(); it_read = next) {
next = std::next(it_read);
if (!it_read->removed()) {
if (it_read != it_write) {
assert(it_read.data() >= data());
assert(it_write.data() >= data());
size_t old_offset = static_cast<size_t>(it_read.data() - data());
size_t new_offset = static_cast<size_t>(it_write.data() - data());
callback->moving_in_buffer(old_offset, new_offset);
std::memmove(it_write.data(), it_read.data(), it_read->padded_size());
}
it_write.advance_once();
}
}
assert(it_write.data() >= data());
m_written = static_cast<size_t>(it_write.data() - data());
m_committed = m_written;
}
}; // class Buffer
inline void swap(Buffer& lhs, Buffer& rhs) {
lhs.swap(rhs);
}
/**
* Compare two buffers for equality.
*
* Buffers are equal if they are both invalid or if they are both
* valid and have the same data pointer, capacity and committed
* data.
*/
inline bool operator==(const Buffer& lhs, const Buffer& rhs) noexcept {
if (!lhs || !rhs) {
return !lhs && !rhs;
}
return lhs.data() == rhs.data() && lhs.capacity() == rhs.capacity() && lhs.committed() == rhs.committed();
}
inline bool operator!=(const Buffer& lhs, const Buffer& rhs) noexcept {
return ! (lhs == rhs);
}
} // namespace memory
} // namespace osmium
#endif // OSMIUM_MEMORY_BUFFER_HPP