First Commit

This commit is contained in:
Hamza committed 2026-02-26 13:00:32 +01:00
commit 8a6c7106e3
1312 files changed
+425396

No files matched your search

@@ -0,0 +1,609 @@
#ifndef OSMIUM_IO_DETAIL_DEBUG_OUTPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_DEBUG_OUTPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/detail/output_format.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/detail/string_util.hpp>
#include <osmium/io/file.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/memory/item_iterator.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/changeset.hpp>
#include <osmium/osm/crc.hpp>
#include <osmium/osm/crc_zlib.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/metadata_options.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/node_ref.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/tag.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/thread/pool.hpp>
#include <osmium/util/minmax.hpp>
#include <osmium/visitor.hpp>
#include <array>
#include <cmath>
#include <cstring>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
constexpr const char* color_bold = "\x1b[1m";
constexpr const char* color_black = "\x1b[30m";
constexpr const char* color_gray = "\x1b[30;1m";
constexpr const char* color_red = "\x1b[31m";
constexpr const char* color_green = "\x1b[32m";
constexpr const char* color_yellow = "\x1b[33m";
constexpr const char* color_blue = "\x1b[34m";
constexpr const char* color_magenta = "\x1b[35m";
constexpr const char* color_cyan = "\x1b[36m";
constexpr const char* color_white = "\x1b[37m";
constexpr const char* color_backg_red = "\x1b[41m";
constexpr const char* color_backg_green = "\x1b[42m";
constexpr const char* color_reset = "\x1b[0m";
struct debug_output_options {
/// Which metadata of objects should be added?
osmium::metadata_options add_metadata;
/// Output with ANSI colors?
bool use_color = false;
/// Add CRC32 checksum to each object?
bool add_crc32 = false;
/// Write in form of a diff file?
bool format_as_diff = false;
}; // struct debug_output_options
/**
* Writes out one buffer with OSM data in Debug format.
*/
class DebugOutputBlock : public OutputBlock {
using crc_type = osmium::CRC_zlib;
debug_output_options m_options;
const char* m_utf8_prefix = "";
const char* m_utf8_suffix = "";
char m_diff_char = '\0';
void append_encoded_string(const char* data) {
append_debug_encoded_string(*m_out, data, m_utf8_prefix, m_utf8_suffix);
}
template <typename... TArgs>
void output_formatted(const char* format, TArgs... args) {
append_printf_formatted_string(*m_out, format, args...);
}
void write_color(const char* color) {
if (m_options.use_color) {
*m_out += color;
}
}
void write_diff() {
if (!m_diff_char) {
return;
}
if (m_options.use_color) {
if (m_diff_char == '-') {
*m_out += color_backg_red;
*m_out += color_white;
*m_out += color_bold;
*m_out += '-';
*m_out += color_reset;
return;
}
if (m_diff_char == '+') {
*m_out += color_backg_green;
*m_out += color_white;
*m_out += color_bold;
*m_out += '+';
*m_out += color_reset;
return;
}
}
*m_out += m_diff_char;
}
void write_string(const char* string) {
*m_out += '"';
write_color(color_blue);
append_encoded_string(string);
write_color(color_reset);
*m_out += '"';
}
void write_object_type(const char* object_type, bool visible = true) {
write_diff();
if (visible) {
write_color(color_bold);
} else {
write_color(color_white);
}
*m_out += object_type;
write_color(color_reset);
*m_out += ' ';
}
void write_fieldname(const char* name) {
write_diff();
*m_out += " ";
write_color(color_cyan);
*m_out += name;
write_color(color_reset);
*m_out += ": ";
}
void write_comment_field(const char* name) {
write_color(color_cyan);
*m_out += name;
write_color(color_reset);
*m_out += ": ";
}
void write_counter(int width, int n) {
write_color(color_white);
#pragma GCC diagnostic push
#if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ > 7)
#pragma GCC diagnostic ignored "-Wformat-truncation"
#endif
output_formatted(" %0*d: ", width, n++);
#pragma GCC diagnostic pop
write_color(color_reset);
}
void write_error(const char* msg) {
write_color(color_red);
*m_out += msg;
write_color(color_reset);
}
void write_timestamp(const osmium::Timestamp& timestamp) {
if (timestamp.valid()) {
*m_out += timestamp.to_iso();
*m_out += " (";
output_int(timestamp.seconds_since_epoch());
*m_out += ')';
} else {
write_error("NOT SET");
}
*m_out += '\n';
}
void write_meta(const osmium::OSMObject& object) {
output_int(object.id());
if (object.visible()) {
*m_out += " visible\n";
} else {
write_error(" deleted\n");
}
if (m_options.add_metadata.version()) {
write_fieldname("version");
*m_out += " ";
output_int(object.version());
*m_out += '\n';
}
if (m_options.add_metadata.changeset()) {
write_fieldname("changeset");
output_int(object.changeset());
*m_out += '\n';
}
if (m_options.add_metadata.timestamp()) {
write_fieldname("timestamp");
write_timestamp(object.timestamp());
}
if (m_options.add_metadata.user() || m_options.add_metadata.uid()) {
write_fieldname("user");
*m_out += " ";
if (m_options.add_metadata.uid()) {
output_int(object.uid());
*m_out += ' ';
}
if (m_options.add_metadata.user()) {
write_string(object.user());
}
*m_out += '\n';
}
}
void write_tags(const osmium::TagList& tags, const char* padding = "") {
if (tags.empty()) {
return;
}
write_fieldname("tags");
*m_out += padding;
*m_out += " ";
output_int(tags.size());
*m_out += '\n';
osmium::max_op<size_t> max;
for (const auto& tag : tags) {
max.update(std::strlen(tag.key()));
}
for (const auto& tag : tags) {
write_diff();
*m_out += " ";
write_string(tag.key());
auto spacing = max() - std::strlen(tag.key());
while (spacing > 0) {
*m_out += " ";
--spacing;
}
*m_out += " = ";
write_string(tag.value());
*m_out += '\n';
}
}
void write_location(const osmium::Location& location) {
write_fieldname("lon/lat");
*m_out += " ";
location.as_string_without_check(std::back_inserter(*m_out));
if (!location.valid()) {
write_error(" INVALID LOCATION!");
}
*m_out += '\n';
}
void write_box(const osmium::Box& box) {
write_fieldname("box l/b/r/t");
if (box.bottom_left().is_undefined() &&
box.top_right().is_undefined()) {
write_error("BOX NOT SET!\n");
return;
}
const auto& bl = box.bottom_left();
const auto& tr = box.top_right();
bl.as_string_without_check(std::back_inserter(*m_out));
*m_out += ' ';
tr.as_string_without_check(std::back_inserter(*m_out));
if (!box.valid()) {
write_error(" INVALID BOX!");
}
*m_out += '\n';
}
template <typename T>
void write_crc32(const T& object) {
write_fieldname("crc32");
osmium::CRC<crc_type> crc32;
crc32.update(object);
output_formatted(" %x\n", crc32().checksum());
}
void write_crc32(const osmium::Changeset& object) {
write_fieldname("crc32");
osmium::CRC<crc_type> crc32;
crc32.update(object);
output_formatted(" %x\n", crc32().checksum());
}
public:
DebugOutputBlock(osmium::memory::Buffer&& buffer, const debug_output_options& options) :
OutputBlock(std::move(buffer)),
m_options(options),
m_utf8_prefix(options.use_color ? color_red : ""),
m_utf8_suffix(options.use_color ? color_blue : "") {
}
std::string operator()() {
osmium::apply(m_input_buffer->cbegin(), m_input_buffer->cend(), *this);
std::string out;
using std::swap;
swap(out, *m_out);
return out;
}
void node(const osmium::Node& node) {
m_diff_char = m_options.format_as_diff ? node.diff_as_char() : '\0';
write_object_type("node", node.visible());
write_meta(node);
if (node.visible()) {
write_location(node.location());
}
write_tags(node.tags());
if (m_options.add_crc32) {
write_crc32(node);
}
*m_out += '\n';
}
void way(const osmium::Way& way) {
m_diff_char = m_options.format_as_diff ? way.diff_as_char() : '\0';
write_object_type("way", way.visible());
write_meta(way);
write_tags(way.tags());
write_fieldname("nodes");
*m_out += " ";
output_int(way.nodes().size());
if (way.nodes().size() < 2) {
write_error(" LESS THAN 2 NODES!\n");
} else if (way.nodes().size() > 2000) {
write_error(" MORE THAN 2000 NODES!\n");
} else if (way.nodes().is_closed()) {
*m_out += " (closed)\n";
} else {
*m_out += " (open)\n";
}
const int width = static_cast<int>(std::log10(way.nodes().size())) + 1;
int n = 0;
for (const auto& node_ref : way.nodes()) {
write_diff();
write_counter(width, n++);
output_formatted("%10lld", static_cast<long long>(node_ref.ref())); // NOLINT(google-runtime-int)
if (node_ref.location().valid()) {
*m_out += " (";
node_ref.location().as_string(std::back_inserter(*m_out));
*m_out += ')';
}
*m_out += '\n';
}
if (m_options.add_crc32) {
write_crc32(way);
}
*m_out += '\n';
}
void relation(const osmium::Relation& relation) {
static const std::array<const char*, 3> short_typename = {{ "node", "way ", "rel " }};
m_diff_char = m_options.format_as_diff ? relation.diff_as_char() : '\0';
write_object_type("relation", relation.visible());
write_meta(relation);
write_tags(relation.tags());
write_fieldname("members");
*m_out += " ";
output_int(relation.members().size());
*m_out += '\n';
const int width = static_cast<int>(std::log10(relation.members().size())) + 1;
int n = 0;
for (const auto& member : relation.members()) {
write_diff();
write_counter(width, n++);
*m_out += short_typename[item_type_to_nwr_index(member.type())];
output_formatted(" %10lld ", static_cast<long long>(member.ref())); // NOLINT(google-runtime-int)
write_string(member.role());
*m_out += '\n';
}
if (m_options.add_crc32) {
write_crc32(relation);
}
*m_out += '\n';
}
void changeset(const osmium::Changeset& changeset) {
write_object_type("changeset");
output_int(changeset.id());
*m_out += '\n';
write_fieldname("num changes");
output_int(changeset.num_changes());
if (changeset.num_changes() == 0) {
write_error(" NO CHANGES!");
}
*m_out += '\n';
write_fieldname("created at");
*m_out += ' ';
write_timestamp(changeset.created_at());
write_fieldname("closed at");
*m_out += " ";
if (changeset.closed()) {
write_timestamp(changeset.closed_at());
} else {
write_error("OPEN!\n");
}
write_fieldname("user");
*m_out += " ";
output_int(changeset.uid());
*m_out += ' ';
write_string(changeset.user());
*m_out += '\n';
write_box(changeset.bounds());
write_tags(changeset.tags(), " ");
if (changeset.num_comments() > 0) {
write_fieldname("comments");
*m_out += " ";
output_int(changeset.num_comments());
*m_out += '\n';
const int width = static_cast<int>(std::log10(changeset.num_comments())) + 1;
int n = 0;
for (const auto& comment : changeset.discussion()) {
write_counter(width, n++);
write_comment_field("date");
write_timestamp(comment.date());
output_formatted(" %*s", width, "");
write_comment_field("user");
output_int(comment.uid());
*m_out += ' ';
write_string(comment.user());
output_formatted("\n %*s", width, "");
write_comment_field("text");
write_string(comment.text());
*m_out += '\n';
}
}
if (m_options.add_crc32) {
write_crc32(changeset);
}
*m_out += '\n';
}
}; // class DebugOutputBlock
class DebugOutputFormat : public osmium::io::detail::OutputFormat {
debug_output_options m_options;
void write_fieldname(std::string& out, const char* name) const {
out += " ";
if (m_options.use_color) {
out += color_cyan;
}
out += name;
if (m_options.use_color) {
out += color_reset;
}
out += ": ";
}
public:
DebugOutputFormat(osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) :
OutputFormat(pool, output_queue) {
m_options.add_metadata = osmium::metadata_options{file.get("add_metadata")};
m_options.use_color = file.is_true("color");
m_options.add_crc32 = file.is_true("add_crc32");
m_options.format_as_diff = file.is_true("diff");
}
void write_header(const osmium::io::Header& header) final {
if (m_options.format_as_diff) {
return;
}
std::string out;
if (m_options.use_color) {
out += color_bold;
}
out += "header\n";
if (m_options.use_color) {
out += color_reset;
}
write_fieldname(out, "multiple object versions");
out += header.has_multiple_object_versions() ? "yes" : "no";
out += '\n';
write_fieldname(out, "bounding boxes");
out += '\n';
for (const auto& box : header.boxes()) {
out += " ";
box.bottom_left().as_string(std::back_inserter(out));
out += ' ';
box.top_right().as_string(std::back_inserter(out));
out += '\n';
}
write_fieldname(out, "options");
out += '\n';
for (const auto& opt : header) {
out += " ";
out += opt.first;
out += " = ";
out += opt.second;
out += '\n';
}
out += "\n=============================================\n\n";
send_to_output_queue(std::move(out));
}
void write_buffer(osmium::memory::Buffer&& buffer) final {
m_output_queue.push(m_pool.submit(DebugOutputBlock{std::move(buffer), m_options}));
}
}; // class DebugOutputFormat
// we want the register_output_format() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_debug_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::debug,
[](osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) {
return new osmium::io::detail::DebugOutputFormat(pool, file, output_queue);
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_debug_output() noexcept {
return registered_debug_output;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_DEBUG_OUTPUT_FORMAT_HPP
@@ -0,0 +1,164 @@
#ifndef OSMIUM_IO_DETAIL_IDS_OUTPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_IDS_OUTPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/detail/output_format.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/detail/string_util.hpp>
#include <osmium/io/file.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/memory/collection.hpp>
#include <osmium/memory/item_iterator.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/changeset.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/metadata_options.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/node_ref.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/tag.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/thread/pool.hpp>
#include <osmium/visitor.hpp>
#include <cstdint>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
struct ids_output_options {
bool with_type = true;
}; // struct ids_output_options
/**
* Writes out one buffer with OSM data in IDS format.
*/
class IDSOutputBlock : public OutputBlock {
ids_output_options m_options;
void write_id(char c, int64_t value) {
if (m_options.with_type) {
*m_out += c;
}
output_int(value);
*m_out += '\n';
}
public:
IDSOutputBlock(osmium::memory::Buffer&& buffer, const ids_output_options& options) :
OutputBlock(std::move(buffer)),
m_options(options) {
}
std::string operator()() {
osmium::apply(m_input_buffer->cbegin(), m_input_buffer->cend(), *this);
std::string out;
using std::swap;
swap(out, *m_out);
return out;
}
void node(const osmium::Node& node) {
write_id('n', node.id());
}
void way(const osmium::Way& way) {
write_id('w', way.id());
}
void relation(const osmium::Relation& relation) {
write_id('r', relation.id());
}
void changeset(const osmium::Changeset& changeset) {
write_id('c', changeset.id());
}
}; // class IDSOutputBlock
class IDSOutputFormat : public osmium::io::detail::OutputFormat {
ids_output_options m_options;
public:
IDSOutputFormat(osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) :
OutputFormat(pool, output_queue) {
if (file.is_false("ids_with_type")) {
m_options.with_type = false;
}
}
void write_buffer(osmium::memory::Buffer&& buffer) final {
m_output_queue.push(m_pool.submit(IDSOutputBlock{std::move(buffer), m_options}));
}
}; // class IDSOutputFormat
// we want the register_output_format() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_ids_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::ids,
[](osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) {
return new osmium::io::detail::IDSOutputFormat(pool, file, output_queue);
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_ids_output() noexcept {
return registered_ids_output;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_IDS_OUTPUT_FORMAT_HPP
@@ -0,0 +1,294 @@
#ifndef OSMIUM_IO_DETAIL_INPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_INPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/detail/queue_util.hpp>
#include <osmium/io/error.hpp>
#include <osmium/io/file.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/osm/entity_bits.hpp>
#include <osmium/thread/pool.hpp>
#include <array>
#include <exception>
#include <functional>
#include <future>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
struct parser_arguments {
osmium::thread::Pool& pool;
int fd;
future_string_queue_type& input_queue;
future_buffer_queue_type& output_queue;
std::promise<osmium::io::Header>& header_promise;
std::atomic<std::size_t>* offset_ptr;
osmium::osm_entity_bits::type read_which_entities;
osmium::io::read_meta read_metadata;
osmium::io::buffers_type buffers_kind;
bool want_buffered_pages_removed;
};
class Parser {
osmium::thread::Pool& m_pool;
future_buffer_queue_type& m_output_queue;
std::promise<osmium::io::Header>& m_header_promise;
queue_wrapper<std::string> m_input_queue;
osmium::osm_entity_bits::type m_read_which_entities;
osmium::io::read_meta m_read_metadata;
bool m_header_is_done = false;
protected:
osmium::thread::Pool& get_pool() {
return m_pool;
}
osmium::osm_entity_bits::type read_types() const noexcept {
return m_read_which_entities;
}
osmium::io::read_meta read_metadata() const noexcept {
return m_read_metadata;
}
bool header_is_done() const noexcept {
return m_header_is_done;
}
void set_header_value(const osmium::io::Header& header) {
if (!m_header_is_done) {
m_header_is_done = true;
m_header_promise.set_value(header);
}
}
void set_header_exception(const std::exception_ptr& exception) {
if (!m_header_is_done) {
m_header_is_done = true;
m_header_promise.set_exception(exception);
}
}
/**
* Wrap the buffer into a future and add it to the output queue.
*/
void send_to_output_queue(osmium::memory::Buffer&& buffer) {
add_to_queue(m_output_queue, std::move(buffer));
}
void send_to_output_queue(std::future<osmium::memory::Buffer>&& future) {
m_output_queue.push(std::move(future));
}
public:
explicit Parser(parser_arguments& args) :
m_pool(args.pool),
m_output_queue(args.output_queue),
m_header_promise(args.header_promise),
m_input_queue(args.input_queue),
m_read_which_entities(args.read_which_entities),
m_read_metadata(args.read_metadata) {
}
Parser(const Parser&) = delete;
Parser& operator=(const Parser&) = delete;
Parser(Parser&&) = delete;
Parser& operator=(Parser&&) = delete;
virtual ~Parser() noexcept = default;
virtual void run() = 0;
std::string get_input() {
return m_input_queue.pop();
}
bool input_done() const {
return m_input_queue.has_reached_end_of_data();
}
void parse() {
try {
run();
} catch (...) {
std::exception_ptr exception = std::current_exception();
set_header_exception(exception);
add_to_queue(m_output_queue, std::move(exception));
}
add_end_of_data_to_queue(m_output_queue);
}
}; // class Parser
class ParserWithBuffer : public Parser {
enum {
initial_buffer_size = 1024UL * 1024UL
};
osmium::memory::Buffer m_buffer{initial_buffer_size,
osmium::memory::Buffer::auto_grow::internal};
osmium::io::buffers_type m_buffers_kind;
osmium::item_type m_last_type = osmium::item_type::undefined;
bool is_different_type(osmium::item_type current_type) noexcept {
if (m_last_type == current_type) {
return false;
}
if (m_last_type == osmium::item_type::undefined) {
m_last_type = current_type;
return false;
}
m_last_type = current_type;
return true;
}
protected:
explicit ParserWithBuffer(parser_arguments& args) :
Parser(args),
m_buffers_kind(args.buffers_kind) {
}
osmium::memory::Buffer& buffer() noexcept {
return m_buffer;
}
void flush_nested_buffer() {
if (m_buffer.has_nested_buffers()) {
std::unique_ptr<osmium::memory::Buffer> buffer_ptr{m_buffer.get_last_nested()};
send_to_output_queue(std::move(*buffer_ptr));
}
}
void flush_final_buffer() {
if (m_buffer.committed() > 0) {
send_to_output_queue(std::move(m_buffer));
}
}
void maybe_new_buffer(osmium::item_type current_type) {
if (m_buffers_kind == buffers_type::any) {
return;
}
if (is_different_type(current_type) && m_buffer.committed() > 0) {
osmium::memory::Buffer new_buffer{initial_buffer_size,
osmium::memory::Buffer::auto_grow::internal};
using std::swap;
swap(new_buffer, m_buffer);
send_to_output_queue(std::move(new_buffer));
}
}
}; // class ParserWithBuffer
/**
* This factory class is used to create objects that decode OSM
* data written in a specified format.
*
* Do not use this class directly. Use the osmium::io::Reader
* class instead.
*/
class ParserFactory {
public:
using create_parser_type = std::function<std::unique_ptr<Parser>(parser_arguments&)>;
private:
std::array<create_parser_type, static_cast<std::size_t>(file_format::last) + 1> m_callbacks;
ParserFactory() noexcept = default;
create_parser_type& callbacks(const osmium::io::file_format format) noexcept {
return m_callbacks[static_cast<std::size_t>(format)];
}
const create_parser_type& callbacks(const osmium::io::file_format format) const noexcept {
return m_callbacks[static_cast<std::size_t>(format)];
}
public:
static ParserFactory& instance() noexcept {
static ParserFactory factory;
return factory;
}
bool register_parser(const osmium::io::file_format format, create_parser_type&& create_function) {
callbacks(format) = std::move(create_function);
return true;
}
create_parser_type get_creator_function(const osmium::io::File& file) const {
auto func = callbacks(file.format());
if (func) {
return func;
}
throw unsupported_file_format_error{
std::string{"Can not open file '"} +
file.filename() +
"' with type '" +
as_string(file.format()) +
"'. No support for reading this format in this program."};
}
}; // class ParserFactory
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_INPUT_FORMAT_HPP
+142
View File
@@ -0,0 +1,142 @@
#ifndef OSMIUM_IO_DETAIL_LZ4_HPP
#define OSMIUM_IO_DETAIL_LZ4_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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.
*/
#ifdef OSMIUM_WITH_LZ4
#include <cassert>
#include <limits>
#include <stdexcept>
#include <string>
#include <osmium/io/error.hpp>
#include <protozero/version.hpp>
#if PROTOZERO_VERSION_CODE >= 10600
# include <protozero/data_view.hpp>
#else
# include <protozero/types.hpp>
#endif
#include <lz4.h>
namespace osmium {
namespace io {
namespace detail {
constexpr inline int lz4_default_compression_level() noexcept {
return 1; // LZ4_ACCELERATION_DEFAULT
}
inline void lz4_check_compression_level(int value) {
if (value <= 0 || value > 65537 /* LZ4_ACCELERATION_MAX */) {
throw std::invalid_argument{"The 'pbf_compression_level' for lz4 compression must be between 1 and 65537."};
}
}
/**
* Compress data using lz4.
*
* Note that this function can not compress data larger than
* LZ4_MAX_INPUT_SIZE.
*
* @param input Data to compress.
* @param compression_level Compression level.
* @returns Compressed data.
*/
inline std::string lz4_compress(const std::string& input, int compression_level = lz4_default_compression_level()) { // NOLINT(google-runtime-int)
assert(input.size() < LZ4_MAX_INPUT_SIZE);
const int output_size = ::LZ4_compressBound(static_cast<int>(input.size())); // NOLINT(google-runtime-int)
std::string output(static_cast<std::size_t>(output_size), '\0');
const int result = ::LZ4_compress_fast( // NOLINT(google-runtime-int)
input.data(),
&*output.begin(),
static_cast<int>(input.size()),
output_size,
compression_level);
if (result == 0) {
throw io_error{"LZ4 compression failed"};
}
output.resize(result);
return output;
}
/**
* Uncompress data using lz4.
*
* Note that this function can not uncompress data larger than
* LZ4_MAX_INPUT_SIZE.
*
* @param input Compressed input data.
* @param raw_size Size of uncompressed data.
* @param output Uncompressed result data.
* @returns Pointer and size to incompressed data.
*/
inline protozero::data_view lz4_uncompress_string(const char* input, unsigned long input_size, unsigned long raw_size, std::string& output) { // NOLINT(google-runtime-int)
output.resize(raw_size);
const int result = ::LZ4_decompress_safe( // NOLINT(google-runtime-int)
input,
&*output.begin(),
static_cast<int>(input_size),
static_cast<int>(raw_size));
if (result < 0) {
throw io_error{"LZ4 decompression failed: invalid block"};
}
if (result != static_cast<int>(raw_size)) {
throw io_error{"LZ4 decompression failed: data size does not match"};
}
return protozero::data_view{output.data(), output.size()};
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif
#endif // OSMIUM_IO_DETAIL_LZ4_HPP
@@ -0,0 +1,651 @@
#ifndef OSMIUM_IO_DETAIL_O5M_INPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_O5M_INPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/builder/osm_object_builder.hpp>
#include <osmium/io/detail/input_format.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/error.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/entity_bits.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/thread/util.hpp>
#include <osmium/util/delta.hpp>
#include <protozero/exception.hpp>
#include <protozero/varint.hpp>
#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <future>
#include <limits>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace builder {
class Builder;
} // namespace builder
/**
* Exception thrown when the o5m deocder failed. The exception contains
* (if available) information about the place where the error happened
* and the type of error.
*/
struct o5m_error : public io_error {
explicit o5m_error(const char* what) :
io_error(std::string{"o5m format error: "} + what) {
}
}; // struct o5m_error
namespace io {
namespace detail {
// Implementation of the o5m/o5c file formats according to the
// description at https://wiki.openstreetmap.org/wiki/O5m .
class ReferenceTable {
// The following settings are from the o5m description:
enum : uint64_t {
// The maximum number of entries in this table.
number_of_entries = 15000UL,
// The size of one entry in the table.
entry_size = 256UL
};
// The maximum length of a string in the table including
// two \0 bytes.
enum {
max_length = 250U + 2U
};
// The data is stored in this string. It is default constructed
// and then resized on demand the first time something is added.
// This is done because the ReferenceTable is in a O5mParser
// object which will be copied from one thread to another. This
// way the string is still small when it is copied.
std::string m_table;
unsigned int current_entry = 0;
public:
void clear() {
current_entry = 0;
}
void add(const char* string, std::size_t size) {
assert(string);
if (m_table.empty()) {
m_table.resize(entry_size * number_of_entries);
}
if (size <= max_length) {
std::copy_n(string, size, &m_table[current_entry * entry_size]);
if (++current_entry == number_of_entries) {
current_entry = 0;
}
}
}
const char* get(uint64_t index) const {
if (m_table.empty() || index == 0 || index > number_of_entries) {
throw o5m_error{"reference to non-existing string in table"};
}
const auto entry = (current_entry + number_of_entries - index) % number_of_entries;
return &m_table[entry * entry_size];
}
}; // class ReferenceTable
class O5mParser final : public ParserWithBuffer {
osmium::io::Header m_header{};
std::string m_input{};
const char* m_data;
const char* m_end;
ReferenceTable m_reference_table;
static int64_t zvarint(const char** data, const char* end) {
return protozero::decode_zigzag64(protozero::decode_varint(data, end));
}
bool ensure_bytes_available(std::size_t need_bytes) {
if (static_cast<std::size_t>(m_end - m_data) >= need_bytes) {
return true;
}
if (input_done() && (m_input.size() < need_bytes)) {
return false;
}
m_input.erase(0, m_data - m_input.data());
while (m_input.size() < need_bytes) {
const std::string data{get_input()};
if (input_done()) {
return false;
}
m_input.append(data);
}
m_data = m_input.data();
m_end = m_input.data() + m_input.size();
return true;
}
void check_header_magic() {
static const unsigned char header_magic[] = {0xff, 0xe0, 0x04, 'o', '5'};
if (std::strncmp(reinterpret_cast<const char*>(header_magic), m_data, sizeof(header_magic)) != 0) {
throw o5m_error{"wrong header magic"};
}
m_data += sizeof(header_magic);
}
void check_file_type() {
if (*m_data == 'm') { // o5m data file
m_header.set_has_multiple_object_versions(false);
} else if (*m_data == 'c') { // o5c change file
m_header.set_has_multiple_object_versions(true);
} else {
throw o5m_error{"wrong header magic"};
}
m_data++;
}
void check_file_format_version() {
if (*m_data != '2') {
throw o5m_error{"wrong header magic"};
}
m_data++;
}
void decode_header() {
if (!ensure_bytes_available(7)) { // overall length of header
throw o5m_error{"file too short (incomplete header info)"};
}
check_header_magic();
check_file_type();
check_file_format_version();
}
void mark_header_as_done() {
set_header_value(m_header);
}
osmium::DeltaDecode<osmium::object_id_type> m_delta_id;
osmium::DeltaDecode<int64_t> m_delta_timestamp;
osmium::DeltaDecode<osmium::changeset_id_type> m_delta_changeset;
osmium::DeltaDecode<int64_t> m_delta_lon;
osmium::DeltaDecode<int64_t> m_delta_lat;
osmium::DeltaDecode<osmium::object_id_type> m_delta_way_node_id;
std::array<osmium::DeltaDecode<osmium::object_id_type>, 3> m_delta_member_ids;
void reset() {
m_reference_table.clear();
m_delta_id.clear();
m_delta_timestamp.clear();
m_delta_changeset.clear();
m_delta_lon.clear();
m_delta_lat.clear();
m_delta_way_node_id.clear();
m_delta_member_ids[0].clear();
m_delta_member_ids[1].clear();
m_delta_member_ids[2].clear();
}
const char* decode_string(const char** dataptr, const char* const end) {
assert(*dataptr != end);
if (**dataptr == 0x00) { // get inline string
++(*dataptr);
if (*dataptr == end) {
throw o5m_error{"string format error"};
}
return *dataptr;
}
// get from reference table
const auto index = protozero::decode_varint(dataptr, end);
return m_reference_table.get(index);
}
std::pair<osmium::user_id_type, const char*> decode_user(const char** dataptr, const char* const end) {
assert(*dataptr != end);
const bool update_pointer = (**dataptr == 0x00);
const char* data = decode_string(dataptr, end);
const char* start = data;
const auto uid = protozero::decode_varint(&data, end);
if (uid > std::numeric_limits<user_id_type>::max()) {
throw o5m_error{"uid out of range"};
}
if (data == end) {
throw o5m_error{"missing user name"};
}
const char* user = ++data;
if (uid == 0 && update_pointer) {
m_reference_table.add("\0\0", 2);
*dataptr = data;
return {0, ""};
}
do {
if (data == end) {
throw o5m_error{"no null byte in user name"};
}
} while (*data++);
if (update_pointer) {
m_reference_table.add(start, data - start);
*dataptr = data;
}
return {static_cast<osmium::user_id_type>(uid), user};
}
void decode_tags(osmium::builder::Builder& parent, const char** dataptr, const char* const end) {
osmium::builder::TagListBuilder builder{parent};
while (*dataptr != end) {
const bool update_pointer = (**dataptr == 0x00);
const char* data = decode_string(dataptr, end);
const char* start = data;
while (*data++) {
if (data == end) {
throw o5m_error{"no null byte in tag key"};
}
}
if (data == end) {
throw o5m_error{"no null byte in tag value"};
}
const char* value = data;
while (*data++) {
if (data == end) {
throw o5m_error{"no null byte in tag value"};
}
}
if (update_pointer) {
m_reference_table.add(start, data - start);
*dataptr = data;
}
builder.add_tag(start, value);
}
}
const char* decode_info(osmium::OSMObject& object, const char** dataptr, const char* const end) {
const char* user = "";
if (*dataptr == end) {
throw o5m_error{"premature end of file while parsing object metadata"};
}
if (**dataptr == 0x00) { // no info section
++*dataptr;
} else { // has info section
const auto version = protozero::decode_varint(dataptr, end);
if (version > std::numeric_limits<object_version_type>::max()) {
throw o5m_error{"object version too large"};
}
object.set_version(static_cast<object_version_type>(version));
const auto timestamp = m_delta_timestamp.update(zvarint(dataptr, end));
if (timestamp != 0) { // has timestamp
object.set_timestamp(timestamp);
object.set_changeset(m_delta_changeset.update(zvarint(dataptr, end)));
if (*dataptr != end) {
const auto uid_user = decode_user(dataptr, end);
object.set_uid(uid_user.first);
user = uid_user.second;
} else {
object.set_uid(user_id_type{0});
}
}
}
return user;
}
void decode_node(const char* data, const char* const end) {
osmium::builder::NodeBuilder builder{buffer()};
builder.set_id(m_delta_id.update(zvarint(&data, end)));
builder.set_user(decode_info(builder.object(), &data, end));
if (data == end) {
// no location, object is deleted
builder.set_visible(false);
builder.set_location(osmium::Location{});
} else {
const auto lon = m_delta_lon.update(zvarint(&data, end));
const auto lat = m_delta_lat.update(zvarint(&data, end));
builder.set_location(osmium::Location{lon, lat});
if (data != end) {
decode_tags(builder, &data, end);
}
}
}
void decode_way(const char* data, const char* const end) {
osmium::builder::WayBuilder builder{buffer()};
builder.set_id(m_delta_id.update(zvarint(&data, end)));
builder.set_user(decode_info(builder.object(), &data, end));
if (data == end) {
// no reference section, object is deleted
builder.set_visible(false);
} else {
const auto reference_section_length = protozero::decode_varint(&data, end);
if (reference_section_length > 0) {
const char* const end_refs = data + reference_section_length;
if (end_refs > end) {
throw o5m_error{"way nodes ref section too long"};
}
osmium::builder::WayNodeListBuilder wn_builder{builder};
while (data < end_refs) {
wn_builder.add_node_ref(m_delta_way_node_id.update(zvarint(&data, end)));
}
}
if (data != end) {
decode_tags(builder, &data, end);
}
}
}
static osmium::item_type decode_member_type(char c) {
if (c < '0' || c > '2') {
throw o5m_error{"unknown member type"};
}
return osmium::nwr_index_to_item_type(c - '0');
}
std::pair<osmium::item_type, const char*> decode_role(const char** dataptr, const char* const end) {
assert(*dataptr != end);
const bool update_pointer = (**dataptr == 0x00);
const char* data = decode_string(dataptr, end);
const char* start = data;
const auto member_type = decode_member_type(*data++);
if (data == end) {
throw o5m_error{"missing role"};
}
const char* role = data;
while (*data++) {
if (data == end) {
throw o5m_error{"no null byte in role"};
}
}
if (update_pointer) {
m_reference_table.add(start, data - start);
*dataptr = data;
}
return {member_type, role};
}
void decode_relation(const char* data, const char* const end) {
osmium::builder::RelationBuilder builder{buffer()};
builder.set_id(m_delta_id.update(zvarint(&data, end)));
builder.set_user(decode_info(builder.object(), &data, end));
if (data == end) {
// no reference section, object is deleted
builder.set_visible(false);
} else {
const auto reference_section_length = protozero::decode_varint(&data, end);
if (reference_section_length > 0) {
const char* const end_refs = data + reference_section_length;
if (end_refs > end) {
throw o5m_error{"relation format error"};
}
osmium::builder::RelationMemberListBuilder rml_builder{builder};
while (data < end_refs) {
const auto delta_id = zvarint(&data, end);
if (data == end) {
throw o5m_error{"relation member format error"};
}
const auto type_role = decode_role(&data, end);
const auto i = osmium::item_type_to_nwr_index(type_role.first);
const auto ref = m_delta_member_ids[i].update(delta_id);
rml_builder.add_member(type_role.first, ref, type_role.second);
}
}
if (data != end) {
decode_tags(builder, &data, end);
}
}
}
void decode_bbox(const char* data, const char* const end) {
const auto sw_lon = zvarint(&data, end);
const auto sw_lat = zvarint(&data, end);
const auto ne_lon = zvarint(&data, end);
const auto ne_lat = zvarint(&data, end);
m_header.add_box(osmium::Box{osmium::Location{sw_lon, sw_lat},
osmium::Location{ne_lon, ne_lat}});
}
void decode_timestamp(const char* data, const char* const end) {
const auto timestamp = osmium::Timestamp{zvarint(&data, end)}.to_iso();
m_header.set("o5m_timestamp", timestamp);
m_header.set("timestamp", timestamp);
}
enum class dataset_type : unsigned char {
node = 0x10,
way = 0x11,
relation = 0x12,
bounding_box = 0xdb,
timestamp = 0xdc,
header = 0xe0,
sync = 0xee,
jump = 0xef,
reset = 0xff
};
void decode_data() {
while (ensure_bytes_available(1)) {
const auto ds_type = static_cast<dataset_type>(*m_data++);
if (ds_type > dataset_type::jump) {
if (ds_type == dataset_type::reset) {
reset();
}
} else {
ensure_bytes_available(protozero::max_varint_length);
uint64_t length = 0;
try {
length = protozero::decode_varint(&m_data, m_end);
} catch (const protozero::end_of_buffer_exception&) {
throw o5m_error{"premature end of file"};
}
if (!ensure_bytes_available(length)) {
throw o5m_error{"premature end of file"};
}
switch (ds_type) {
case dataset_type::node:
mark_header_as_done();
if (read_types() & osmium::osm_entity_bits::node) {
maybe_new_buffer(osmium::item_type::node);
decode_node(m_data, m_data + length);
buffer().commit();
}
break;
case dataset_type::way:
mark_header_as_done();
if (read_types() & osmium::osm_entity_bits::way) {
maybe_new_buffer(osmium::item_type::way);
decode_way(m_data, m_data + length);
buffer().commit();
}
break;
case dataset_type::relation:
mark_header_as_done();
if (read_types() & osmium::osm_entity_bits::relation) {
maybe_new_buffer(osmium::item_type::relation);
decode_relation(m_data, m_data + length);
buffer().commit();
}
break;
case dataset_type::bounding_box:
decode_bbox(m_data, m_data + length);
break;
case dataset_type::timestamp:
decode_timestamp(m_data, m_data + length);
break;
default:
// ignore unknown datasets
break;
}
if (read_types() == osmium::osm_entity_bits::nothing && header_is_done()) {
break;
}
m_data += length;
flush_nested_buffer();
}
}
mark_header_as_done();
flush_final_buffer();
}
public:
explicit O5mParser(parser_arguments& args) :
ParserWithBuffer(args),
m_data(m_input.data()),
m_end(m_data) {
}
O5mParser(const O5mParser&) = delete;
O5mParser& operator=(const O5mParser&) = delete;
O5mParser(O5mParser&&) = delete;
O5mParser& operator=(O5mParser&&) = delete;
~O5mParser() noexcept override = default;
void run() override {
osmium::thread::set_thread_name("_osmium_o5m_in");
decode_header();
decode_data();
}
}; // class O5mParser
// we want the register_parser() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_o5m_parser = ParserFactory::instance().register_parser(
file_format::o5m,
[](parser_arguments& args) {
return std::unique_ptr<Parser>(new O5mParser{args});
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_o5m_parser() noexcept {
return registered_o5m_parser;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_O5M_INPUT_FORMAT_HPP
@@ -0,0 +1,172 @@
#ifndef OSMIUM_IO_DETAIL_OPL_INPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_OPL_INPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/detail/input_format.hpp>
#include <osmium/io/detail/opl_parser_functions.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/thread/util.hpp>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
// Feed data coming in blocks line by line to the OPL parser
// function. This has been broken out of the OPLParser class
// where it belongs into a standalone template function to be
// better testable.
template <typename T>
void line_by_line(T& worker) {
std::string rest;
while (!worker.input_done()) {
std::string input{worker.get_input()};
std::string::size_type ppos = 0;
if (!rest.empty()) {
ppos = input.find_first_of("\n\r");
if (ppos == std::string::npos) {
rest.append(input);
continue;
}
rest.append(input, 0, ppos);
if (!rest.empty()) {
worker.parse_line(rest.data());
rest.clear();
}
++ppos;
}
for (auto pos = input.find_first_of("\n\r", ppos);
pos != std::string::npos;
pos = input.find_first_of("\n\r", ppos)) {
const char* data = &input[ppos];
input[pos] = '\0';
if (data[0] != '\0') {
worker.parse_line(data);
}
ppos = pos + 1;
if (ppos >= input.size()) {
break;
}
}
rest.assign(input, ppos, std::string::npos);
}
if (!rest.empty()) {
worker.parse_line(rest.data());
}
}
class OPLParser final : public ParserWithBuffer {
uint64_t m_line_count = 0;
public:
explicit OPLParser(parser_arguments& args) :
ParserWithBuffer(args) {
set_header_value(osmium::io::Header{});
}
OPLParser(const OPLParser&) = delete;
OPLParser& operator=(const OPLParser&) = delete;
OPLParser(OPLParser&&) = delete;
OPLParser& operator=(OPLParser&&) = delete;
~OPLParser() noexcept override = default;
void parse_line(const char* data) {
switch (*data) {
case 'n':
maybe_new_buffer(osmium::item_type::node);
break;
case 'w':
maybe_new_buffer(osmium::item_type::way);
break;
case 'r':
maybe_new_buffer(osmium::item_type::relation);
break;
case 'c':
maybe_new_buffer(osmium::item_type::way);
break;
}
if (opl_parse_line(m_line_count, data, buffer(), read_types())) {
flush_nested_buffer();
}
++m_line_count;
}
void run() override {
osmium::thread::set_thread_name("_osmium_opl_in");
line_by_line(*this);
flush_final_buffer();
}
}; // class OPLParser
// we want the register_parser() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_opl_parser = ParserFactory::instance().register_parser(
file_format::opl,
[](parser_arguments& args) {
return std::unique_ptr<Parser>(new OPLParser{args});
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_opl_parser() noexcept {
return registered_opl_parser;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_OPL_INPUT_FORMAT_HPP
@@ -0,0 +1,321 @@
#ifndef OSMIUM_IO_DETAIL_OPL_OUTPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_OPL_OUTPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/detail/output_format.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/detail/string_util.hpp>
#include <osmium/io/file.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/memory/collection.hpp>
#include <osmium/memory/item_iterator.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/changeset.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/metadata_options.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/node_ref.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/tag.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/thread/pool.hpp>
#include <osmium/visitor.hpp>
#include <cstdint>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
struct opl_output_options {
/// Which metadata of objects should be added?
osmium::metadata_options add_metadata;
/// Should node locations be added to ways?
bool locations_on_ways = false;
/// Write in form of a diff file?
bool format_as_diff = false;
}; // struct opl_output_options
/**
* Writes out one buffer with OSM data in OPL format.
*/
class OPLOutputBlock : public OutputBlock {
opl_output_options m_options;
void append_encoded_string(const char* data) {
osmium::io::detail::append_utf8_encoded_string(*m_out, data);
}
void write_field_int(char c, int64_t value) {
*m_out += c;
output_int(value);
}
void write_field_timestamp(char c, const osmium::Timestamp& timestamp) {
*m_out += c;
*m_out += timestamp.to_iso();
}
void write_tags(const osmium::TagList& tags) {
*m_out += " T";
if (tags.empty()) {
return;
}
auto it = tags.begin();
append_encoded_string(it->key());
*m_out += '=';
append_encoded_string(it->value());
for (++it; it != tags.end(); ++it) {
*m_out += ',';
append_encoded_string(it->key());
*m_out += '=';
append_encoded_string(it->value());
}
}
void write_meta(const osmium::OSMObject& object) {
output_int(object.id());
if (m_options.add_metadata.any()) {
if (m_options.add_metadata.version()) {
*m_out += ' ';
write_field_int('v', object.version());
}
*m_out += " d";
*m_out += (object.visible() ? 'V' : 'D');
if (m_options.add_metadata.changeset()) {
*m_out += ' ';
write_field_int('c', object.changeset());
}
if (m_options.add_metadata.timestamp()) {
*m_out += ' ';
write_field_timestamp('t', object.timestamp());
}
if (m_options.add_metadata.uid()) {
*m_out += ' ';
write_field_int('i', object.uid());
}
if (m_options.add_metadata.user()) {
*m_out += " u";
append_encoded_string(object.user());
}
}
write_tags(object.tags());
}
void write_location(const osmium::Location& location, const char x, const char y) {
const bool not_undefined = !location.is_undefined();
*m_out += ' ';
*m_out += x;
if (not_undefined) {
osmium::detail::append_location_coordinate_to_string(std::back_inserter(*m_out), location.x());
}
*m_out += ' ';
*m_out += y;
if (not_undefined) {
osmium::detail::append_location_coordinate_to_string(std::back_inserter(*m_out), location.y());
}
}
void write_diff(const osmium::OSMObject& object) {
if (m_options.format_as_diff) {
*m_out += object.diff_as_char();
}
}
public:
OPLOutputBlock(osmium::memory::Buffer&& buffer, const opl_output_options& options) :
OutputBlock(std::move(buffer)),
m_options(options) {
}
std::string operator()() {
osmium::apply(m_input_buffer->cbegin(), m_input_buffer->cend(), *this);
std::string out;
using std::swap;
swap(out, *m_out);
return out;
}
void node(const osmium::Node& node) {
write_diff(node);
*m_out += 'n';
write_meta(node);
write_location(node.location(), 'x', 'y');
*m_out += '\n';
}
void write_field_ref(const osmium::NodeRef& node_ref) {
write_field_int('n', node_ref.ref());
*m_out += 'x';
if (node_ref.location()) {
node_ref.location().as_string(std::back_inserter(*m_out), 'y');
} else {
*m_out += 'y';
}
}
void way(const osmium::Way& way) {
write_diff(way);
*m_out += 'w';
write_meta(way);
*m_out += " N";
if (!way.nodes().empty()) {
const auto* it = way.nodes().cbegin();
if (m_options.locations_on_ways) {
write_field_ref(*it);
for (++it; it != way.nodes().end(); ++it) {
*m_out += ',';
write_field_ref(*it);
}
} else {
write_field_int('n', it->ref());
for (++it; it != way.nodes().end(); ++it) {
*m_out += ',';
write_field_int('n', it->ref());
}
}
}
*m_out += '\n';
}
void relation_member(const osmium::RelationMember& member) {
*m_out += item_type_to_char(member.type());
output_int(member.ref());
*m_out += '@';
append_encoded_string(member.role());
}
void relation(const osmium::Relation& relation) {
write_diff(relation);
*m_out += 'r';
write_meta(relation);
*m_out += " M";
if (!relation.members().empty()) {
auto it = relation.members().begin();
relation_member(*it);
for (++it; it != relation.members().end(); ++it) {
*m_out += ',';
relation_member(*it);
}
}
*m_out += '\n';
}
void changeset(const osmium::Changeset& changeset) {
write_field_int('c', changeset.id());
*m_out += ' ';
write_field_int('k', changeset.num_changes());
*m_out += ' ';
write_field_timestamp('s', changeset.created_at());
*m_out += ' ';
write_field_timestamp('e', changeset.closed_at());
*m_out += ' ';
write_field_int('d', changeset.num_comments());
*m_out += ' ';
write_field_int('i', changeset.uid());
*m_out += " u";
append_encoded_string(changeset.user());
write_location(changeset.bounds().bottom_left(), 'x', 'y');
write_location(changeset.bounds().top_right(), 'X', 'Y');
write_tags(changeset.tags());
*m_out += '\n';
}
}; // class OPLOutputBlock
class OPLOutputFormat : public osmium::io::detail::OutputFormat {
opl_output_options m_options;
public:
OPLOutputFormat(osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) :
OutputFormat(pool, output_queue) {
m_options.add_metadata = osmium::metadata_options{file.get("add_metadata")};
m_options.locations_on_ways = file.is_true("locations_on_ways");
m_options.format_as_diff = file.is_true("diff");
}
void write_buffer(osmium::memory::Buffer&& buffer) final {
m_output_queue.push(m_pool.submit(OPLOutputBlock{std::move(buffer), m_options}));
}
}; // class OPLOutputFormat
// we want the register_output_format() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_opl_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::opl,
[](osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) {
return new osmium::io::detail::OPLOutputFormat(pool, file, output_queue);
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_opl_output() noexcept {
return registered_opl_output;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_OPL_OUTPUT_FORMAT_HPP
@@ -0,0 +1,923 @@
#ifndef OSMIUM_IO_DETAIL_OPL_PARSER_FUNCTIONS_HPP
#define OSMIUM_IO_DETAIL_OPL_PARSER_FUNCTIONS_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/builder/osm_object_builder.hpp>
#include <osmium/io/detail/string_util.hpp>
#include <osmium/io/error.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/changeset.hpp>
#include <osmium/osm/entity_bits.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>
#include <osmium/osm/way.hpp>
#include <cstdint>
#include <cstdlib>
#include <iterator>
#include <limits>
#include <stdexcept>
#include <string>
namespace osmium {
namespace builder {
class Builder;
} // namespace builder
/**
* Exception thrown when there was a problem with parsing the OPL format
* of a file.
*/
struct opl_error : public io_error {
uint64_t line = 0;
uint64_t column = 0;
const char* data;
std::string msg;
explicit opl_error(const std::string& what, const char* d = nullptr) :
io_error(std::string("OPL error: ") + what),
data(d),
msg("OPL error: ") {
msg.append(what);
}
explicit opl_error(const char* what, const char* d = nullptr) :
io_error(std::string{"OPL error: "} + what),
data(d),
msg("OPL error: ") {
msg.append(what);
}
void set_pos(uint64_t l, uint64_t col) {
line = l;
column = col;
msg.append(" on line ");
msg.append(std::to_string(line));
msg.append(" column ");
msg.append(std::to_string(column));
}
const char* what() const noexcept override {
return msg.c_str();
}
}; // struct opl_error
namespace io {
namespace detail {
/**
* Consume consecutive space and tab characters. There must be
* at least one.
*/
inline void opl_parse_space(const char** s) {
if (**s != ' ' && **s != '\t') {
throw opl_error{"expected space or tab character", *s};
}
do {
++*s;
} while (**s == ' ' || **s == '\t');
}
/**
* Check whether s points to something else than the end of the
* string or a space or tab.
*/
inline bool opl_non_empty(const char* s) {
return *s != '\0' && *s != ' ' && *s != '\t';
}
/**
* Skip to the next space or tab character or the end of the
* string.
*/
inline const char* opl_skip_section(const char** s) noexcept {
while (opl_non_empty(*s)) {
++*s;
}
return *s;
}
/**
* Parse OPL-escaped strings with hex code with a '%' at the end.
* Appends resulting unicode character to the result string.
*
* Returns a pointer to next character that needs to be consumed.
*/
inline void opl_parse_escaped(const char** data, std::string& result) {
assert(data);
assert(*data);
const char* s = *data;
uint32_t value = 0;
const int max_length = sizeof(value) * 2 /* hex chars per byte */;
int length = 0;
while (++length <= max_length) {
if (*s == '\0') {
throw opl_error{"eol", s};
}
if (*s == '%') {
++s;
if (value == 0) {
result += '%';
} else {
append_codepoint_as_utf8(value, std::back_inserter(result));
}
*data = s;
return;
}
value <<= 4U;
if (*s >= '0' && *s <= '9') {
value += *s - '0';
} else if (*s >= 'a' && *s <= 'f') {
value += *s - 'a' + 10;
} else if (*s >= 'A' && *s <= 'F') {
value += *s - 'A' + 10;
} else {
throw opl_error{"not a hex char", s};
}
++s;
}
throw opl_error{"hex escape too long", s};
}
/**
* Parse a string up to end of string or next space, tab, comma, or
* equal sign.
*
* Appends characters to the result string.
*
* Returns a pointer to next character that needs to be consumed.
*/
inline void opl_parse_string(const char** data, std::string& result) {
assert(data);
assert(*data);
const char* s = *data;
while (true) {
if (*s == '\0' || *s == ' ' || *s == '\t' || *s == ',' || *s == '=') {
break;
}
if (*s == '%') {
++s;
opl_parse_escaped(&s, result);
} else {
result += *s;
++s;
}
}
*data = s;
}
template <typename T>
inline T opl_parse_int(const char** s) {
const bool negative = (**s == '-');
if (negative) {
++*s;
}
if (**s < '0' || **s > '9') {
throw opl_error{"expected integer", *s};
}
int64_t value = 0;
while (**s >= '0' && **s <= '9') {
if (value <= -922337203685477580) {
if ((value < -922337203685477580) || (**s > '8')) {
throw opl_error("integer too long", *s);
}
}
value *= 10;
value -= **s - '0';
++*s;
}
if (negative) {
if (value < std::numeric_limits<T>::min()) {
throw opl_error{"integer too long", *s};
}
} else {
if (value == std::numeric_limits<int64_t>::min()) {
throw opl_error{"integer too long", *s};
}
value = -value;
if (value > std::numeric_limits<T>::max()) {
throw opl_error{"integer too long", *s};
}
}
return static_cast<T>(value);
}
inline osmium::object_id_type opl_parse_id(const char** s) {
return opl_parse_int<osmium::object_id_type>(s);
}
inline osmium::changeset_id_type opl_parse_changeset_id(const char** s) {
return opl_parse_int<osmium::changeset_id_type>(s);
}
inline osmium::object_version_type opl_parse_version(const char** s) {
return opl_parse_int<osmium::object_version_type>(s);
}
inline bool opl_parse_visible(const char** data) {
if (**data == 'V') {
++*data;
return true;
}
if (**data == 'D') {
++*data;
return false;
}
throw opl_error{"invalid visible flag", *data};
}
inline osmium::user_id_type opl_parse_uid(const char** s) {
return opl_parse_int<osmium::user_id_type>(s);
}
inline osmium::Timestamp opl_parse_timestamp(const char** s) {
try {
if (**s == '\0' || **s == ' ' || **s == '\t') {
return osmium::Timestamp{};
}
osmium::Timestamp timestamp{*s};
*s += 20;
return timestamp;
} catch (const std::invalid_argument&) {
throw opl_error{"can not parse timestamp", *s};
}
}
/**
* Check if data points to given character and consume it.
* Throw error otherwise.
*/
inline void opl_parse_char(const char** data, char c) {
if (**data == c) {
++*data;
return;
}
std::string msg{"expected '"};
msg += c;
msg += "'";
throw opl_error{msg, *data};
}
/**
* Parse a list of tags in the format 'key=value,key=value,...'
*
* Tags will be added to the buffer using a TagListBuilder.
*/
inline void opl_parse_tags(const char* s, osmium::memory::Buffer& buffer, osmium::builder::Builder* parent_builder = nullptr) {
osmium::builder::TagListBuilder builder{buffer, parent_builder};
std::string key;
std::string value;
while (true) {
opl_parse_string(&s, key);
opl_parse_char(&s, '=');
opl_parse_string(&s, value);
builder.add_tag(key, value);
if (*s == ' ' || *s == '\t' || *s == '\0') {
break;
}
opl_parse_char(&s, ',');
key.clear();
value.clear();
}
}
/**
* Parse a number of nodes in the format "nID,nID,nID..."
*
* Nodes will be added to the buffer using a WayNodeListBuilder.
*/
inline void opl_parse_way_nodes(const char* s, const char* e, osmium::memory::Buffer& buffer, osmium::builder::WayBuilder* parent_builder = nullptr) {
if (s == e) {
return;
}
osmium::builder::WayNodeListBuilder builder{buffer, parent_builder};
while (s < e) {
opl_parse_char(&s, 'n');
if (s == e) {
throw opl_error{"expected integer", s};
}
const osmium::object_id_type ref = opl_parse_id(&s);
if (s == e) {
builder.add_node_ref(ref);
return;
}
osmium::Location location;
if (*s == 'x') {
++s;
location.set_lon_partial(&s);
if (*s == 'y') {
++s;
location.set_lat_partial(&s);
}
}
builder.add_node_ref(ref, location);
if (s == e) {
return;
}
opl_parse_char(&s, ',');
}
}
inline void opl_parse_node(const char** data, osmium::memory::Buffer& buffer) {
osmium::builder::NodeBuilder builder{buffer};
builder.set_id(opl_parse_id(data));
const char* tags_begin = nullptr;
bool has_version = false;
bool has_visible = false;
bool has_changeset_id = false;
bool has_timestamp = false;
bool has_uid = false;
bool has_user = false;
bool has_tags = false;
bool has_lon = false;
bool has_lat = false;
std::string user;
osmium::Location location;
while (**data) {
opl_parse_space(data);
const char c = **data;
if (c == '\0') {
break;
}
++(*data);
switch (c) {
case 'v':
if (has_version) {
throw opl_error{"Duplicate attribute: version (v)"};
}
has_version = true;
builder.set_version(opl_parse_version(data));
break;
case 'd':
if (has_visible) {
throw opl_error{"Duplicate attribute: visible (d)"};
}
has_visible = true;
builder.set_visible(opl_parse_visible(data));
break;
case 'c':
if (has_changeset_id) {
throw opl_error{"Duplicate attribute: changeset_id (c)"};
}
has_changeset_id = true;
builder.set_changeset(opl_parse_changeset_id(data));
break;
case 't':
if (has_timestamp) {
throw opl_error{"Duplicate attribute: timestamp (t)"};
}
has_timestamp = true;
builder.set_timestamp(opl_parse_timestamp(data));
break;
case 'i':
if (has_uid) {
throw opl_error{"Duplicate attribute: uid (i)"};
}
has_uid = true;
builder.set_uid(opl_parse_uid(data));
break;
case 'u':
if (has_user) {
throw opl_error{"Duplicate attribute: user (u)"};
}
has_user = true;
opl_parse_string(data, user);
break;
case 'T':
if (has_tags) {
throw opl_error{"Duplicate attribute: tags (T)"};
}
has_tags = true;
if (opl_non_empty(*data)) {
tags_begin = *data;
opl_skip_section(data);
}
break;
case 'x':
if (has_lon) {
throw opl_error{"Duplicate attribute: lon (x)"};
}
has_lon = true;
if (opl_non_empty(*data)) {
location.set_lon_partial(data);
}
break;
case 'y':
if (has_lat) {
throw opl_error{"Duplicate attribute: lat (y)"};
}
has_lat = true;
if (opl_non_empty(*data)) {
location.set_lat_partial(data);
}
break;
default:
--(*data);
throw opl_error{"unknown attribute", *data};
}
}
if (location.valid()) {
builder.set_location(location);
}
builder.set_user(user);
if (tags_begin) {
opl_parse_tags(tags_begin, buffer, &builder);
}
}
inline void opl_parse_way(const char** data, osmium::memory::Buffer& buffer) {
osmium::builder::WayBuilder builder{buffer};
builder.set_id(opl_parse_id(data));
const char* tags_begin = nullptr;
const char* nodes_begin = nullptr;
const char* nodes_end = nullptr;
bool has_version = false;
bool has_visible = false;
bool has_changeset_id = false;
bool has_timestamp = false;
bool has_uid = false;
bool has_user = false;
bool has_tags = false;
bool has_nodes = false;
std::string user;
while (**data) {
opl_parse_space(data);
const char c = **data;
if (c == '\0') {
break;
}
++(*data);
switch (c) {
case 'v':
if (has_version) {
throw opl_error{"Duplicate attribute: version (v)"};
}
has_version = true;
builder.set_version(opl_parse_version(data));
break;
case 'd':
if (has_visible) {
throw opl_error{"Duplicate attribute: visible (d)"};
}
has_visible = true;
builder.set_visible(opl_parse_visible(data));
break;
case 'c':
if (has_changeset_id) {
throw opl_error{"Duplicate attribute: changeset_id (c)"};
}
has_changeset_id = true;
builder.set_changeset(opl_parse_changeset_id(data));
break;
case 't':
if (has_timestamp) {
throw opl_error{"Duplicate attribute: timestamp (t)"};
}
has_timestamp = true;
builder.set_timestamp(opl_parse_timestamp(data));
break;
case 'i':
if (has_uid) {
throw opl_error{"Duplicate attribute: uid (i)"};
}
has_uid = true;
builder.set_uid(opl_parse_uid(data));
break;
case 'u':
if (has_user) {
throw opl_error{"Duplicate attribute: user (u)"};
}
has_user = true;
opl_parse_string(data, user);
break;
case 'T':
if (has_tags) {
throw opl_error{"Duplicate attribute: tags (T)"};
}
has_tags = true;
if (opl_non_empty(*data)) {
tags_begin = *data;
opl_skip_section(data);
}
break;
case 'N':
if (has_nodes) {
throw opl_error{"Duplicate attribute: nodes (N)"};
}
has_nodes = true;
nodes_begin = *data;
nodes_end = opl_skip_section(data);
break;
default:
--(*data);
throw opl_error{"unknown attribute", *data};
}
}
builder.set_user(user);
if (tags_begin) {
opl_parse_tags(tags_begin, buffer, &builder);
}
opl_parse_way_nodes(nodes_begin, nodes_end, buffer, &builder);
}
inline void opl_parse_relation_members(const char* s, const char* e, osmium::memory::Buffer& buffer, osmium::builder::RelationBuilder* parent_builder = nullptr) {
if (s == e) {
return;
}
osmium::builder::RelationMemberListBuilder builder{buffer, parent_builder};
while (s < e) {
const osmium::item_type type = osmium::char_to_item_type(*s);
if (type != osmium::item_type::node &&
type != osmium::item_type::way &&
type != osmium::item_type::relation) {
throw opl_error{"unknown object type", s};
}
++s;
if (s == e) {
throw opl_error{"expected integer", s};
}
const osmium::object_id_type ref = opl_parse_id(&s);
opl_parse_char(&s, '@');
if (s == e) {
builder.add_member(type, ref, "");
return;
}
std::string role;
opl_parse_string(&s, role);
builder.add_member(type, ref, role);
if (s == e) {
return;
}
opl_parse_char(&s, ',');
}
}
inline void opl_parse_relation(const char** data, osmium::memory::Buffer& buffer) {
osmium::builder::RelationBuilder builder{buffer};
builder.set_id(opl_parse_id(data));
const char* tags_begin = nullptr;
const char* members_begin = nullptr;
const char* members_end = nullptr;
bool has_version = false;
bool has_visible = false;
bool has_changeset_id = false;
bool has_timestamp = false;
bool has_uid = false;
bool has_user = false;
bool has_tags = false;
bool has_members = false;
std::string user;
while (**data) {
opl_parse_space(data);
const char c = **data;
if (c == '\0') {
break;
}
++(*data);
switch (c) {
case 'v':
if (has_version) {
throw opl_error{"Duplicate attribute: version (v)"};
}
has_version = true;
builder.set_version(opl_parse_version(data));
break;
case 'd':
if (has_visible) {
throw opl_error{"Duplicate attribute: visible (d)"};
}
has_visible = true;
builder.set_visible(opl_parse_visible(data));
break;
case 'c':
if (has_changeset_id) {
throw opl_error{"Duplicate attribute: changeset_id (c)"};
}
has_changeset_id = true;
builder.set_changeset(opl_parse_changeset_id(data));
break;
case 't':
if (has_timestamp) {
throw opl_error{"Duplicate attribute: timestamp (t)"};
}
has_timestamp = true;
builder.set_timestamp(opl_parse_timestamp(data));
break;
case 'i':
if (has_uid) {
throw opl_error{"Duplicate attribute: uid (i)"};
}
has_uid = true;
builder.set_uid(opl_parse_uid(data));
break;
case 'u':
if (has_user) {
throw opl_error{"Duplicate attribute: user (u)"};
}
has_user = true;
opl_parse_string(data, user);
break;
case 'T':
if (has_tags) {
throw opl_error{"Duplicate attribute: tags (T)"};
}
has_tags = true;
if (opl_non_empty(*data)) {
tags_begin = *data;
opl_skip_section(data);
}
break;
case 'M':
if (has_members) {
throw opl_error{"Duplicate attribute: members (M)"};
}
has_members = true;
members_begin = *data;
members_end = opl_skip_section(data);
break;
default:
--(*data);
throw opl_error{"unknown attribute", *data};
}
}
builder.set_user(user);
if (tags_begin) {
opl_parse_tags(tags_begin, buffer, &builder);
}
if (members_begin != members_end) {
opl_parse_relation_members(members_begin, members_end, buffer, &builder);
}
}
inline void opl_parse_changeset(const char** data, osmium::memory::Buffer& buffer) {
osmium::builder::ChangesetBuilder builder{buffer};
builder.set_id(opl_parse_changeset_id(data));
const char* tags_begin = nullptr;
bool has_num_changes = false;
bool has_created_at = false;
bool has_closed_at = false;
bool has_num_comments = false;
bool has_uid = false;
bool has_user = false;
bool has_tags = false;
bool has_min_x = false;
bool has_min_y = false;
bool has_max_x = false;
bool has_max_y = false;
osmium::Box box;
std::string user;
while (**data) {
opl_parse_space(data);
const char c = **data;
if (c == '\0') {
break;
}
++(*data);
switch (c) {
case 'k':
if (has_num_changes) {
throw opl_error{"Duplicate attribute: num_changes (k)"};
}
has_num_changes = true;
builder.set_num_changes(opl_parse_int<osmium::num_changes_type>(data));
break;
case 's':
if (has_created_at) {
throw opl_error{"Duplicate attribute: created_at (s)"};
}
has_created_at = true;
builder.set_created_at(opl_parse_timestamp(data));
break;
case 'e':
if (has_closed_at) {
throw opl_error{"Duplicate attribute: closed_at (e)"};
}
has_closed_at = true;
builder.set_closed_at(opl_parse_timestamp(data));
break;
case 'd':
if (has_num_comments) {
throw opl_error{"Duplicate attribute: num_comments (d)"};
}
has_num_comments = true;
builder.set_num_comments(opl_parse_int<osmium::num_comments_type>(data));
break;
case 'i':
if (has_uid) {
throw opl_error{"Duplicate attribute: uid (i)"};
}
has_uid = true;
builder.set_uid(opl_parse_uid(data));
break;
case 'u':
if (has_user) {
throw opl_error{"Duplicate attribute: user (u)"};
}
has_user = true;
opl_parse_string(data, user);
break;
case 'x':
if (has_min_x) {
throw opl_error{"Duplicate attribute: min_x (x)"};
}
has_min_x = true;
if (opl_non_empty(*data)) {
box.bottom_left().set_lon_partial(data);
}
break;
case 'y':
if (has_min_y) {
throw opl_error{"Duplicate attribute: min_y (y)"};
}
has_min_y = true;
if (opl_non_empty(*data)) {
box.bottom_left().set_lat_partial(data);
}
break;
case 'X':
if (has_max_x) {
throw opl_error{"Duplicate attribute: max_x (X)"};
}
has_max_x = true;
if (opl_non_empty(*data)) {
box.top_right().set_lon_partial(data);
}
break;
case 'Y':
if (has_max_y) {
throw opl_error{"Duplicate attribute: max_y (Y)"};
}
has_max_y = true;
if (opl_non_empty(*data)) {
box.top_right().set_lat_partial(data);
}
break;
case 'T':
if (has_tags) {
throw opl_error{"Duplicate attribute: tags (T)"};
}
has_tags = true;
if (opl_non_empty(*data)) {
tags_begin = *data;
opl_skip_section(data);
}
break;
default:
--(*data);
throw opl_error{"unknown attribute", *data};
}
}
builder.set_bounds(box);
builder.set_user(user);
if (tags_begin) {
opl_parse_tags(tags_begin, buffer, &builder);
}
}
inline bool opl_parse_line(uint64_t line_count,
const char* data,
osmium::memory::Buffer& buffer,
osmium::osm_entity_bits::type read_types = osmium::osm_entity_bits::all) {
const char* start_of_line = data;
try {
switch (*data) {
case '\0':
// ignore empty lines
break;
case '#':
// ignore lines starting with #
break;
case 'n':
if (read_types & osmium::osm_entity_bits::node) {
++data;
opl_parse_node(&data, buffer);
buffer.commit();
return true;
}
break;
case 'w':
if (read_types & osmium::osm_entity_bits::way) {
++data;
opl_parse_way(&data, buffer);
buffer.commit();
return true;
}
break;
case 'r':
if (read_types & osmium::osm_entity_bits::relation) {
++data;
opl_parse_relation(&data, buffer);
buffer.commit();
return true;
}
break;
case 'c':
if (read_types & osmium::osm_entity_bits::changeset) {
++data;
opl_parse_changeset(&data, buffer);
buffer.commit();
return true;
}
break;
default:
throw opl_error{"unknown type", data};
}
} catch (opl_error& e) {
e.set_pos(line_count, e.data ? e.data - start_of_line : 0);
throw;
}
return false;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_OPL_PARSER_FUNCTIONS_HPP
@@ -0,0 +1,241 @@
#ifndef OSMIUM_IO_DETAIL_OUTPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_OUTPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/handler.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/error.hpp>
#include <osmium/io/file.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/thread/pool.hpp>
#include <array>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace io {
class Header;
} // namespace io
namespace io {
namespace detail {
class OutputBlock : public osmium::handler::Handler {
protected:
std::shared_ptr<osmium::memory::Buffer> m_input_buffer;
std::shared_ptr<std::string> m_out;
explicit OutputBlock(osmium::memory::Buffer&& buffer) :
m_input_buffer(std::make_shared<osmium::memory::Buffer>(std::move(buffer))),
m_out(std::make_shared<std::string>()) {
}
// Simple function to convert integer to string. This is much
// faster than using sprintf, but could be further optimized.
// See https://github.com/miloyip/itoa-benchmark .
void output_int(int64_t value) {
if (value < 0) {
*m_out += '-';
value = -value;
}
char temp[20];
char* t = temp;
do {
*t++ = static_cast<char>(value % 10) + '0'; // NOLINT(bugprone-narrowing-conversions, cppcoreguidelines-narrowing-conversions)
value /= 10;
} while (value > 0);
const auto old_size = m_out->size();
m_out->resize(old_size + (t - temp));
char* data = &(*m_out)[old_size];
do {
*data++ = *--t;
} while (t != temp);
}
}; // class OutputBlock;
/**
* Virtual base class for all classes writing OSM files in different
* formats.
*
* Do not use this class or derived classes directly. Use the
* osmium::io::Writer class instead.
*/
class OutputFormat {
protected:
osmium::thread::Pool& m_pool;
future_string_queue_type& m_output_queue;
/**
* Wrap the string into a future and add it to the output
* queue.
*/
void send_to_output_queue(std::string&& data) {
add_to_queue(m_output_queue, std::move(data));
}
public:
OutputFormat(osmium::thread::Pool& pool, future_string_queue_type& output_queue) noexcept :
m_pool(pool),
m_output_queue(output_queue) {
}
OutputFormat(const OutputFormat&) = delete;
OutputFormat& operator=(const OutputFormat&) = delete;
OutputFormat(OutputFormat&&) = delete;
OutputFormat& operator=(OutputFormat&&) = delete;
virtual ~OutputFormat() noexcept = default;
virtual void write_header(const osmium::io::Header& /*header*/) {
}
virtual void write_buffer(osmium::memory::Buffer&& /*buffer*/) = 0;
virtual void write_end() {
}
}; // class OutputFormat
/**
* This factory class is used to create objects that write OSM data
* into a specified output format.
*
* Do not use this class directly. Instead use the osmium::io::Writer
* class.
*/
class OutputFormatFactory {
public:
using create_output_type = std::function<osmium::io::detail::OutputFormat*(osmium::thread::Pool&, const osmium::io::File&, future_string_queue_type&)>;
private:
std::array<create_output_type, static_cast<std::size_t>(file_format::last) + 1> m_callbacks;
OutputFormatFactory() noexcept = default;
create_output_type& callbacks(const osmium::io::file_format format) noexcept {
return m_callbacks[static_cast<std::size_t>(format)];
}
const create_output_type& callbacks(const osmium::io::file_format format) const noexcept {
return m_callbacks[static_cast<std::size_t>(format)];
}
public:
static OutputFormatFactory& instance() noexcept {
static OutputFormatFactory factory;
return factory;
}
bool register_output_format(const osmium::io::file_format format, create_output_type&& create_function) {
callbacks(format) = std::move(create_function);
return true;
}
std::unique_ptr<osmium::io::detail::OutputFormat> create_output(osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) const {
const auto func = callbacks(file.format());
if (func) {
return std::unique_ptr<osmium::io::detail::OutputFormat>((func)(pool, file, output_queue));
}
throw unsupported_file_format_error{
std::string{"Can not open file '"} +
file.filename() +
"' with type '" +
as_string(file.format()) +
"'. No support for writing this format in this program."};
}
}; // class OutputFormatFactory
class BlackholeOutputFormat final : public osmium::io::detail::OutputFormat {
public:
BlackholeOutputFormat(osmium::thread::Pool& pool, const osmium::io::File& /*file*/, future_string_queue_type& output_queue) :
OutputFormat(pool, output_queue) {
}
BlackholeOutputFormat(const BlackholeOutputFormat&) = delete;
BlackholeOutputFormat& operator=(const BlackholeOutputFormat&) = delete;
BlackholeOutputFormat(BlackholeOutputFormat&&) = delete;
BlackholeOutputFormat& operator=(BlackholeOutputFormat&&) = delete;
~BlackholeOutputFormat() noexcept override = default;
void write_buffer(osmium::memory::Buffer&& /*buffer*/) override {
}
}; // class BlackholeOutputFormat
// we want the register_output_format() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_blackhole_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::blackhole,
[](osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) {
return new osmium::io::detail::BlackholeOutputFormat(pool, file, output_queue);
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_blackhole_output() noexcept {
return registered_blackhole_output;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_OUTPUT_FORMAT_HPP
+101
View File
@@ -0,0 +1,101 @@
#ifndef OSMIUM_IO_DETAIL_PBF_HPP
#define OSMIUM_IO_DETAIL_PBF_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/error.hpp>
#include <osmium/osm/location.hpp>
#include <cstdint>
#include <string>
namespace osmium {
/**
* Exception thrown when there was a problem with parsing the PBF format of
* a file.
*/
struct pbf_error : public io_error {
explicit pbf_error(const std::string& what) :
io_error(std::string("PBF error: ") + what) {
}
explicit pbf_error(const char* what) :
io_error(std::string("PBF error: ") + what) {
}
}; // struct pbf_error
namespace io {
namespace detail {
// the maximum size of a blob header in bytes
const int max_blob_header_size = 64 * 1024; // 64 kB
// the maximum size of an uncompressed blob in bytes
const uint64_t max_uncompressed_blob_size = 32UL * 1024UL * 1024UL; // 32 MB
// resolution for longitude/latitude used for conversion
// between representation as double and as int
const int64_t lonlat_resolution = 1000L * 1000L * 1000L;
const int64_t resolution_convert = lonlat_resolution / osmium::detail::coordinate_precision;
enum class pbf_compression : uint8_t {
none = 0,
zlib = 1,
lz4 = 2
};
inline pbf_compression get_compression_type(const std::string& val) {
if (val.empty() || val == "zlib" || val == "true") {
return pbf_compression::zlib;
}
if (val == "none" || val == "false") {
return pbf_compression::none;
}
if (val == "lz4") {
return pbf_compression::lz4;
}
throw std::invalid_argument{"Unknown value for 'pbf_compression' option."};
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_PBF_HPP
@@ -0,0 +1,988 @@
#ifndef OSMIUM_IO_DETAIL_PBF_DECODER_HPP
#define OSMIUM_IO_DETAIL_PBF_DECODER_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <cstdint>
#include <cstring>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include <osmium/builder/osm_object_builder.hpp>
#include <osmium/io/detail/pbf.hpp> // IWYU pragma: export
#include <osmium/io/detail/protobuf_tags.hpp>
#include <osmium/io/detail/zlib.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/entity_bits.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/util/delta.hpp>
#ifdef OSMIUM_WITH_LZ4
# include <osmium/io/detail/lz4.hpp>
#endif
#include <protozero/iterators.hpp>
#include <protozero/pbf_message.hpp>
#include <protozero/types.hpp>
namespace osmium {
namespace builder {
class Builder;
} // namespace builder
namespace io {
namespace detail {
using protozero::data_view;
class varint_range {
const char* m_data = nullptr;
const char* m_end = nullptr;
std::uint64_t next() {
return protozero::decode_varint(&m_data, m_end);
}
public:
varint_range() = default;
explicit varint_range(const data_view& data) :
m_data(data.data()),
m_end(data.data() + data.size()) {
}
bool empty() const noexcept {
return m_data == m_end;
}
std::size_t size() const noexcept {
if (!m_data) {
return 0;
}
// We know that each varint contains exactly one byte with the most
// significant bit not set. We can use this to quickly figure out
// how many varints there are without actually decoding the varints.
return std::count_if(m_data, m_end, [](char c) noexcept {
return (static_cast<unsigned char>(c) & 0x80U) == 0;
});
}
std::int32_t next_int32() {
return static_cast<int32_t>(next());
}
std::uint32_t next_uint32() {
return static_cast<uint32_t>(next());
}
std::int32_t next_sint32() {
return protozero::decode_zigzag32(static_cast<uint32_t>(next()));
}
std::int64_t next_sint64() {
return protozero::decode_zigzag64(next());
}
}; // class varint_range
using osm_string_len_type = std::pair<const char*, osmium::string_size_type>;
class PBFPrimitiveBlockDecoder {
enum {
initial_buffer_size = 64UL * 1024UL
};
data_view m_data;
std::vector<osm_string_len_type> m_stringtable;
int64_t m_lon_offset = 0;
int64_t m_lat_offset = 0;
int64_t m_date_factor = 1000;
int32_t m_granularity = 100;
osmium::osm_entity_bits::type m_read_types;
osmium::memory::Buffer m_buffer{initial_buffer_size, osmium::memory::Buffer::auto_grow::internal};
osmium::io::read_meta m_read_metadata;
void decode_stringtable(const data_view& data) {
if (!m_stringtable.empty()) {
throw osmium::pbf_error{"more than one stringtable in pbf file"};
}
protozero::pbf_message<OSMFormat::StringTable> pbf_string_table{data};
while (pbf_string_table.next(OSMFormat::StringTable::repeated_bytes_s, protozero::pbf_wire_type::length_delimited)) {
const auto str_view = pbf_string_table.get_view();
if (str_view.size() > osmium::max_osm_string_length) {
const std::string start_of_string(str_view.data(), 20);
throw osmium::pbf_error{"overlong string (" + start_of_string + "...) in string table"};
}
m_stringtable.emplace_back(str_view.data(), static_cast<osmium::string_size_type>(str_view.size()));
}
}
void decode_primitive_block_metadata() {
protozero::pbf_message<OSMFormat::PrimitiveBlock> pbf_primitive_block{m_data};
while (pbf_primitive_block.next()) {
switch (pbf_primitive_block.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::PrimitiveBlock::required_StringTable_stringtable, protozero::pbf_wire_type::length_delimited):
decode_stringtable(pbf_primitive_block.get_view());
break;
case protozero::tag_and_type(OSMFormat::PrimitiveBlock::optional_int32_granularity, protozero::pbf_wire_type::varint):
m_granularity = pbf_primitive_block.get_int32();
break;
case protozero::tag_and_type(OSMFormat::PrimitiveBlock::optional_int32_date_granularity, protozero::pbf_wire_type::varint):
m_date_factor = pbf_primitive_block.get_int32();
break;
case protozero::tag_and_type(OSMFormat::PrimitiveBlock::optional_int64_lat_offset, protozero::pbf_wire_type::varint):
m_lat_offset = pbf_primitive_block.get_int64();
break;
case protozero::tag_and_type(OSMFormat::PrimitiveBlock::optional_int64_lon_offset, protozero::pbf_wire_type::varint):
m_lon_offset = pbf_primitive_block.get_int64();
break;
default:
pbf_primitive_block.skip();
}
}
}
void decode_primitive_block_data() {
protozero::pbf_message<OSMFormat::PrimitiveBlock> pbf_primitive_block{m_data};
while (pbf_primitive_block.next(OSMFormat::PrimitiveBlock::repeated_PrimitiveGroup_primitivegroup, protozero::pbf_wire_type::length_delimited)) {
protozero::pbf_message<OSMFormat::PrimitiveGroup> pbf_primitive_group = pbf_primitive_block.get_message();
while (pbf_primitive_group.next()) {
switch (pbf_primitive_group.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::PrimitiveGroup::repeated_Node_nodes, protozero::pbf_wire_type::length_delimited):
if (m_read_types & osmium::osm_entity_bits::node) {
decode_node(pbf_primitive_group.get_view());
m_buffer.commit();
} else {
pbf_primitive_group.skip();
}
break;
case protozero::tag_and_type(OSMFormat::PrimitiveGroup::optional_DenseNodes_dense, protozero::pbf_wire_type::length_delimited):
if (m_read_types & osmium::osm_entity_bits::node) {
if (m_read_metadata == osmium::io::read_meta::yes) {
decode_dense_nodes(pbf_primitive_group.get_view());
} else {
decode_dense_nodes_without_metadata(pbf_primitive_group.get_view());
}
m_buffer.commit();
} else {
pbf_primitive_group.skip();
}
break;
case protozero::tag_and_type(OSMFormat::PrimitiveGroup::repeated_Way_ways, protozero::pbf_wire_type::length_delimited):
if (m_read_types & osmium::osm_entity_bits::way) {
decode_way(pbf_primitive_group.get_view());
m_buffer.commit();
} else {
pbf_primitive_group.skip();
}
break;
case protozero::tag_and_type(OSMFormat::PrimitiveGroup::repeated_Relation_relations, protozero::pbf_wire_type::length_delimited):
if (m_read_types & osmium::osm_entity_bits::relation) {
decode_relation(pbf_primitive_group.get_view());
m_buffer.commit();
} else {
pbf_primitive_group.skip();
}
break;
default:
pbf_primitive_group.skip();
}
}
}
}
osm_string_len_type decode_info(const data_view& data, osmium::OSMObject& object) {
osm_string_len_type user{"", 0};
protozero::pbf_message<OSMFormat::Info> pbf_info{data};
while (pbf_info.next()) {
switch (pbf_info.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::Info::optional_int32_version, protozero::pbf_wire_type::varint):
{
const auto version = pbf_info.get_int32();
if (version < -1) {
throw osmium::pbf_error{"object version must not be negative"};
}
if (version == -1) {
object.set_version(0U);
} else {
object.set_version(static_cast<object_version_type>(version));
}
}
break;
case protozero::tag_and_type(OSMFormat::Info::optional_int64_timestamp, protozero::pbf_wire_type::varint):
object.set_timestamp(pbf_info.get_int64() * m_date_factor / 1000);
break;
case protozero::tag_and_type(OSMFormat::Info::optional_int64_changeset, protozero::pbf_wire_type::varint):
{
const auto changeset_id = pbf_info.get_int64();
if (changeset_id < -1 || changeset_id >= std::numeric_limits<changeset_id_type>::max()) {
throw osmium::pbf_error{"object changeset_id must be between 0 and 2^32-1"};
}
if (changeset_id == -1) {
object.set_changeset(0U);
} else {
object.set_changeset(static_cast<changeset_id_type>(changeset_id));
}
}
break;
case protozero::tag_and_type(OSMFormat::Info::optional_int32_uid, protozero::pbf_wire_type::varint):
object.set_uid_from_signed(pbf_info.get_int32());
break;
case protozero::tag_and_type(OSMFormat::Info::optional_uint32_user_sid, protozero::pbf_wire_type::varint):
user = m_stringtable.at(pbf_info.get_uint32());
break;
case protozero::tag_and_type(OSMFormat::Info::optional_bool_visible, protozero::pbf_wire_type::varint):
object.set_visible(pbf_info.get_bool());
break;
default:
pbf_info.skip();
}
}
return user;
}
void build_tag_list(osmium::builder::Builder& parent, varint_range& keys, varint_range& vals) {
if (keys.empty() || vals.empty()) {
return;
}
osmium::builder::TagListBuilder builder{parent};
do {
const auto& k = m_stringtable.at(keys.next_uint32());
const auto& v = m_stringtable.at(vals.next_uint32());
builder.add_tag(k.first, k.second, v.first, v.second);
} while (!keys.empty() && !vals.empty());
}
int32_t convert_pbf_lon(const int64_t c) const noexcept {
return static_cast<int32_t>((c * m_granularity + m_lon_offset) / resolution_convert);
}
int32_t convert_pbf_lat(const int64_t c) const noexcept {
return static_cast<int32_t>((c * m_granularity + m_lat_offset) / resolution_convert);
}
void decode_node(const data_view& data) {
osmium::builder::NodeBuilder builder{m_buffer};
osmium::Node& node = builder.object();
varint_range keys;
varint_range vals;
int64_t lon = std::numeric_limits<int64_t>::max();
int64_t lat = std::numeric_limits<int64_t>::max();
osm_string_len_type user{"", 0};
protozero::pbf_message<OSMFormat::Node> pbf_node{data};
while (pbf_node.next()) {
switch (pbf_node.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::Node::required_sint64_id, protozero::pbf_wire_type::varint):
node.set_id(pbf_node.get_sint64());
break;
case protozero::tag_and_type(OSMFormat::Node::packed_uint32_keys, protozero::pbf_wire_type::length_delimited):
keys = varint_range{pbf_node.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Node::packed_uint32_vals, protozero::pbf_wire_type::length_delimited):
vals = varint_range{pbf_node.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Node::optional_Info_info, protozero::pbf_wire_type::length_delimited):
if (m_read_metadata == osmium::io::read_meta::yes) {
user = decode_info(pbf_node.get_view(), builder.object());
} else {
pbf_node.skip();
}
break;
case protozero::tag_and_type(OSMFormat::Node::required_sint64_lat, protozero::pbf_wire_type::varint):
lat = pbf_node.get_sint64();
break;
case protozero::tag_and_type(OSMFormat::Node::required_sint64_lon, protozero::pbf_wire_type::varint):
lon = pbf_node.get_sint64();
break;
default:
pbf_node.skip();
}
}
if (node.visible()) {
if (lon == std::numeric_limits<int64_t>::max() ||
lat == std::numeric_limits<int64_t>::max()) {
throw osmium::pbf_error{"illegal coordinate format"};
}
node.set_location(osmium::Location{
convert_pbf_lon(lon),
convert_pbf_lat(lat)
});
}
builder.set_user(user.first, user.second);
build_tag_list(builder, keys, vals);
}
void decode_way(const data_view& data) {
osmium::builder::WayBuilder builder{m_buffer};
varint_range keys;
varint_range vals;
varint_range refs;
varint_range lats;
varint_range lons;
osm_string_len_type user{"", 0};
protozero::pbf_message<OSMFormat::Way> pbf_way{data};
while (pbf_way.next()) {
switch (pbf_way.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::Way::required_int64_id, protozero::pbf_wire_type::varint):
builder.object().set_id(pbf_way.get_int64());
break;
case protozero::tag_and_type(OSMFormat::Way::packed_uint32_keys, protozero::pbf_wire_type::length_delimited):
keys = varint_range{pbf_way.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Way::packed_uint32_vals, protozero::pbf_wire_type::length_delimited):
vals = varint_range{pbf_way.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Way::optional_Info_info, protozero::pbf_wire_type::length_delimited):
if (m_read_metadata == osmium::io::read_meta::yes) {
user = decode_info(pbf_way.get_view(), builder.object());
} else {
pbf_way.skip();
}
break;
case protozero::tag_and_type(OSMFormat::Way::packed_sint64_refs, protozero::pbf_wire_type::length_delimited):
refs = varint_range{pbf_way.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Way::packed_sint64_lat, protozero::pbf_wire_type::length_delimited):
lats = varint_range{pbf_way.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Way::packed_sint64_lon, protozero::pbf_wire_type::length_delimited):
lons = varint_range{pbf_way.get_view()};
break;
default:
pbf_way.skip();
}
}
builder.set_user(user.first, user.second);
if (!refs.empty()) {
osmium::builder::WayNodeListBuilder wnl_builder{builder};
osmium::DeltaDecode<int64_t> ref;
if (lats.empty()) {
while (!refs.empty()) {
wnl_builder.add_node_ref(ref.update(refs.next_sint64()));
}
} else {
osmium::DeltaDecode<int64_t> lon;
osmium::DeltaDecode<int64_t> lat;
while (!refs.empty() && !lons.empty() && !lats.empty()) {
wnl_builder.add_node_ref(
ref.update(refs.next_sint64()),
osmium::Location{convert_pbf_lon(lon.update(lons.next_sint64())),
convert_pbf_lat(lat.update(lats.next_sint64()))}
);
}
}
}
build_tag_list(builder, keys, vals);
}
void decode_relation(const data_view& data) {
osmium::builder::RelationBuilder builder{m_buffer};
varint_range keys;
varint_range vals;
varint_range roles;
varint_range refs;
varint_range types;
osm_string_len_type user{"", 0};
protozero::pbf_message<OSMFormat::Relation> pbf_relation{data};
while (pbf_relation.next()) {
switch (pbf_relation.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::Relation::required_int64_id, protozero::pbf_wire_type::varint):
builder.object().set_id(pbf_relation.get_int64());
break;
case protozero::tag_and_type(OSMFormat::Relation::packed_uint32_keys, protozero::pbf_wire_type::length_delimited):
keys = varint_range{pbf_relation.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Relation::packed_uint32_vals, protozero::pbf_wire_type::length_delimited):
vals = varint_range{pbf_relation.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Relation::optional_Info_info, protozero::pbf_wire_type::length_delimited):
if (m_read_metadata == osmium::io::read_meta::yes) {
user = decode_info(pbf_relation.get_view(), builder.object());
} else {
pbf_relation.skip();
}
break;
case protozero::tag_and_type(OSMFormat::Relation::packed_int32_roles_sid, protozero::pbf_wire_type::length_delimited):
roles = varint_range{pbf_relation.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Relation::packed_sint64_memids, protozero::pbf_wire_type::length_delimited):
refs = varint_range{pbf_relation.get_view()};
break;
case protozero::tag_and_type(OSMFormat::Relation::packed_MemberType_types, protozero::pbf_wire_type::length_delimited):
types = varint_range{pbf_relation.get_view()};
break;
default:
pbf_relation.skip();
}
}
builder.set_user(user.first, user.second);
if (!refs.empty()) {
osmium::builder::RelationMemberListBuilder rml_builder{builder};
osmium::DeltaDecode<int64_t> ref;
while (!roles.empty() && !refs.empty() && !types.empty()) {
const auto& r = m_stringtable.at(roles.next_int32());
const int type = types.next_int32();
if (type < 0 || type > 2) {
throw osmium::pbf_error{"unknown relation member type"};
}
rml_builder.add_member(
static_cast<osmium::item_type>(type + 1),
ref.update(refs.next_sint64()),
r.first,
r.second
);
}
}
build_tag_list(builder, keys, vals);
}
void build_tag_list_from_dense_nodes(osmium::builder::NodeBuilder& builder, varint_range& tags) {
osmium::builder::TagListBuilder tl_builder{builder};
while (!tags.empty()) {
const auto idx = tags.next_int32();
if (idx == 0) {
return;
}
const auto& k = m_stringtable.at(idx);
if (tags.empty()) {
throw osmium::pbf_error{"PBF format error"}; // this is against the spec, keys/vals must come in pairs
}
const auto& v = m_stringtable.at(tags.next_int32());
tl_builder.add_tag(k.first, k.second, v.first, v.second);
}
}
void decode_dense_nodes_without_metadata(const data_view& data) {
varint_range ids;
varint_range lats;
varint_range lons;
varint_range tags;
protozero::pbf_message<OSMFormat::DenseNodes> pbf_dense_nodes{data};
while (pbf_dense_nodes.next()) {
switch (pbf_dense_nodes.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::DenseNodes::packed_sint64_id, protozero::pbf_wire_type::length_delimited):
ids = varint_range{pbf_dense_nodes.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseNodes::packed_sint64_lat, protozero::pbf_wire_type::length_delimited):
lats = varint_range{pbf_dense_nodes.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseNodes::packed_sint64_lon, protozero::pbf_wire_type::length_delimited):
lons = varint_range{pbf_dense_nodes.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseNodes::packed_int32_keys_vals, protozero::pbf_wire_type::length_delimited):
tags = varint_range{pbf_dense_nodes.get_view()};
break;
default:
pbf_dense_nodes.skip();
}
}
osmium::DeltaDecode<int64_t> dense_id;
osmium::DeltaDecode<int64_t> dense_latitude;
osmium::DeltaDecode<int64_t> dense_longitude;
while (!ids.empty()) {
if (lons.empty() ||
lats.empty()) {
// this is against the spec, must have same number of elements
throw osmium::pbf_error{"PBF format error"};
}
{
osmium::builder::NodeBuilder builder{m_buffer};
osmium::Node& node = builder.object();
node.set_id(dense_id.update(ids.next_sint64()));
const auto lon = dense_longitude.update(lons.next_sint64());
const auto lat = dense_latitude.update(lats.next_sint64());
builder.object().set_location(osmium::Location{
convert_pbf_lon(lon),
convert_pbf_lat(lat)
});
if (!tags.empty()) {
build_tag_list_from_dense_nodes(builder, tags);
}
}
m_buffer.commit();
}
}
void decode_dense_nodes(const data_view& data) {
bool has_info = false;
varint_range ids;
varint_range lats;
varint_range lons;
varint_range tags;
varint_range versions;
varint_range timestamps;
varint_range changesets;
varint_range uids;
varint_range user_sids;
varint_range visibles;
protozero::pbf_message<OSMFormat::DenseNodes> pbf_dense_nodes{data};
while (pbf_dense_nodes.next()) {
switch (pbf_dense_nodes.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::DenseNodes::packed_sint64_id, protozero::pbf_wire_type::length_delimited):
ids = varint_range{pbf_dense_nodes.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseNodes::optional_DenseInfo_denseinfo, protozero::pbf_wire_type::length_delimited):
{
has_info = true;
protozero::pbf_message<OSMFormat::DenseInfo> pbf_dense_info{pbf_dense_nodes.get_message()};
while (pbf_dense_info.next()) {
switch (pbf_dense_info.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::DenseInfo::packed_int32_version, protozero::pbf_wire_type::length_delimited):
versions = varint_range{pbf_dense_info.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseInfo::packed_sint64_timestamp, protozero::pbf_wire_type::length_delimited):
timestamps = varint_range{pbf_dense_info.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseInfo::packed_sint64_changeset, protozero::pbf_wire_type::length_delimited):
changesets = varint_range{pbf_dense_info.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseInfo::packed_sint32_uid, protozero::pbf_wire_type::length_delimited):
uids = varint_range{pbf_dense_info.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseInfo::packed_sint32_user_sid, protozero::pbf_wire_type::length_delimited):
user_sids = varint_range{pbf_dense_info.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseInfo::packed_bool_visible, protozero::pbf_wire_type::length_delimited):
visibles = varint_range{pbf_dense_info.get_view()};
break;
default:
pbf_dense_info.skip();
}
}
}
break;
case protozero::tag_and_type(OSMFormat::DenseNodes::packed_sint64_lat, protozero::pbf_wire_type::length_delimited):
lats = varint_range{pbf_dense_nodes.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseNodes::packed_sint64_lon, protozero::pbf_wire_type::length_delimited):
lons = varint_range{pbf_dense_nodes.get_view()};
break;
case protozero::tag_and_type(OSMFormat::DenseNodes::packed_int32_keys_vals, protozero::pbf_wire_type::length_delimited):
tags = varint_range{pbf_dense_nodes.get_view()};
break;
default:
pbf_dense_nodes.skip();
}
}
osmium::DeltaDecode<int64_t> dense_id;
osmium::DeltaDecode<int64_t> dense_latitude;
osmium::DeltaDecode<int64_t> dense_longitude;
osmium::DeltaDecode<int64_t> dense_uid;
osmium::DeltaDecode<int64_t> dense_user_sid;
osmium::DeltaDecode<int64_t> dense_changeset;
osmium::DeltaDecode<int64_t> dense_timestamp;
while (!ids.empty()) {
if (lons.empty() ||
lats.empty()) {
// this is against the spec, must have same number of elements
throw osmium::pbf_error{"PBF format error"};
}
{
bool visible = true;
osmium::builder::NodeBuilder builder{m_buffer};
osmium::Node& node = builder.object();
node.set_id(dense_id.update(ids.next_sint64()));
if (has_info) {
if (!versions.empty()) {
const auto version = versions.next_int32();
if (version < -1) {
throw osmium::pbf_error{"object version must not be negative"};
}
if (version == -1) {
node.set_version(0U);
} else {
node.set_version(static_cast<osmium::object_version_type>(version));
}
}
if (!changesets.empty()) {
const auto changeset_id = dense_changeset.update(changesets.next_sint64());
if (changeset_id < -1 || changeset_id >= std::numeric_limits<changeset_id_type>::max()) {
throw osmium::pbf_error{"object changeset_id must be between 0 and 2^32-1"};
}
if (changeset_id == -1) {
node.set_changeset(0U);
} else {
node.set_changeset(static_cast<osmium::changeset_id_type>(changeset_id));
}
}
if (!timestamps.empty()) {
node.set_timestamp(dense_timestamp.update(timestamps.next_sint64()) * m_date_factor / 1000);
}
if (!uids.empty()) {
node.set_uid_from_signed(static_cast<osmium::signed_user_id_type>(dense_uid.update(uids.next_sint32())));
}
if (!visibles.empty()) {
visible = (visibles.next_int32() != 0);
}
node.set_visible(visible);
if (!user_sids.empty()) {
const auto& u = m_stringtable.at(dense_user_sid.update(user_sids.next_sint32()));
builder.set_user(u.first, u.second);
}
}
// even if the node isn't visible, there's still a record
// of its lat/lon in the dense arrays.
const auto lon = dense_longitude.update(lons.next_sint64());
const auto lat = dense_latitude.update(lats.next_sint64());
if (visible) {
builder.object().set_location(osmium::Location{
convert_pbf_lon(lon),
convert_pbf_lat(lat)
});
}
if (!tags.empty()) {
build_tag_list_from_dense_nodes(builder, tags);
}
}
m_buffer.commit();
}
}
public:
PBFPrimitiveBlockDecoder(const data_view& data, const osmium::osm_entity_bits::type read_types, const osmium::io::read_meta read_metadata) :
m_data(data),
m_read_types(read_types),
m_read_metadata(read_metadata) {
}
PBFPrimitiveBlockDecoder(const PBFPrimitiveBlockDecoder&) = delete;
PBFPrimitiveBlockDecoder& operator=(const PBFPrimitiveBlockDecoder&) = delete;
PBFPrimitiveBlockDecoder(PBFPrimitiveBlockDecoder&&) = delete;
PBFPrimitiveBlockDecoder& operator=(PBFPrimitiveBlockDecoder&&) = delete;
~PBFPrimitiveBlockDecoder() noexcept = default;
osmium::memory::Buffer operator()() {
try {
decode_primitive_block_metadata();
decode_primitive_block_data();
} catch (const std::out_of_range&) {
throw osmium::pbf_error{"string id out of range"};
}
return std::move(m_buffer);
}
}; // class PBFPrimitiveBlockDecoder
inline data_view decode_blob(const std::string& blob_data, std::string& output) {
int32_t raw_size = 0;
protozero::data_view compressed_data;
pbf_compression use_compression = pbf_compression::none;
protozero::pbf_message<FileFormat::Blob> pbf_blob{blob_data};
while (pbf_blob.next()) {
switch (pbf_blob.tag_and_type()) {
case protozero::tag_and_type(FileFormat::Blob::optional_bytes_raw, protozero::pbf_wire_type::length_delimited):
{
const auto data_len = pbf_blob.get_view();
if (data_len.size() > max_uncompressed_blob_size) {
throw osmium::pbf_error{"illegal blob size"};
}
return data_len;
}
case protozero::tag_and_type(FileFormat::Blob::optional_int32_raw_size, protozero::pbf_wire_type::varint):
raw_size = pbf_blob.get_int32();
if (raw_size <= 0 || static_cast<uint32_t>(raw_size) > max_uncompressed_blob_size) {
throw osmium::pbf_error{"illegal blob size"};
}
break;
case protozero::tag_and_type(FileFormat::Blob::optional_bytes_zlib_data, protozero::pbf_wire_type::length_delimited):
use_compression = pbf_compression::zlib;
compressed_data = pbf_blob.get_view();
break;
case protozero::tag_and_type(FileFormat::Blob::optional_bytes_lzma_data, protozero::pbf_wire_type::length_delimited):
throw osmium::pbf_error{"lzma blobs not supported"};
case protozero::tag_and_type(FileFormat::Blob::optional_bytes_lz4_data, protozero::pbf_wire_type::length_delimited):
#ifdef OSMIUM_WITH_LZ4
use_compression = pbf_compression::lz4;
compressed_data = pbf_blob.get_view();
break;
#else
throw osmium::pbf_error{"lz4 blobs not supported"};
#endif
case protozero::tag_and_type(FileFormat::Blob::optional_bytes_zstd_data, protozero::pbf_wire_type::length_delimited):
throw osmium::pbf_error{"zstd blobs not supported"};
default:
pbf_blob.skip();
}
}
if (compressed_data.empty()) {
throw osmium::pbf_error{"blob contains no data or unknown compression method"};
}
if (raw_size == 0) {
throw osmium::pbf_error{"missing raw_size in compressed blob"};
}
switch (use_compression) {
case pbf_compression::none:
break;
case pbf_compression::zlib:
return osmium::io::detail::zlib_uncompress_string(
compressed_data.data(),
static_cast<unsigned long>(compressed_data.size()), // NOLINT(google-runtime-int)
static_cast<unsigned long>(raw_size), // NOLINT(google-runtime-int)
output
);
case pbf_compression::lz4:
#ifdef OSMIUM_WITH_LZ4
return osmium::io::detail::lz4_uncompress_string(
compressed_data.data(),
static_cast<unsigned long>(compressed_data.size()), // NOLINT(google-runtime-int)
static_cast<unsigned long>(raw_size), // NOLINT(google-runtime-int)
output
);
#else
break;
#endif
}
std::abort(); // should never be here
}
inline osmium::Box decode_header_bbox(const data_view& data) {
int64_t left = std::numeric_limits<int64_t>::max();
int64_t right = std::numeric_limits<int64_t>::max();
int64_t top = std::numeric_limits<int64_t>::max();
int64_t bottom = std::numeric_limits<int64_t>::max();
protozero::pbf_message<OSMFormat::HeaderBBox> pbf_header_bbox{data};
while (pbf_header_bbox.next()) {
switch (pbf_header_bbox.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::HeaderBBox::required_sint64_left, protozero::pbf_wire_type::varint):
left = pbf_header_bbox.get_sint64();
break;
case protozero::tag_and_type(OSMFormat::HeaderBBox::required_sint64_right, protozero::pbf_wire_type::varint):
right = pbf_header_bbox.get_sint64();
break;
case protozero::tag_and_type(OSMFormat::HeaderBBox::required_sint64_top, protozero::pbf_wire_type::varint):
top = pbf_header_bbox.get_sint64();
break;
case protozero::tag_and_type(OSMFormat::HeaderBBox::required_sint64_bottom, protozero::pbf_wire_type::varint):
bottom = pbf_header_bbox.get_sint64();
break;
default:
pbf_header_bbox.skip();
}
}
if (left == std::numeric_limits<int64_t>::max() ||
right == std::numeric_limits<int64_t>::max() ||
top == std::numeric_limits<int64_t>::max() ||
bottom == std::numeric_limits<int64_t>::max()) {
throw osmium::pbf_error{"invalid bbox"};
}
osmium::Box box;
box.extend(osmium::Location{left / resolution_convert, bottom / resolution_convert});
box.extend(osmium::Location{right / resolution_convert, top / resolution_convert});
return box;
}
inline osmium::io::Header decode_header_block(const data_view& data) {
osmium::io::Header header;
int i = 0;
protozero::pbf_message<OSMFormat::HeaderBlock> pbf_header_block{data};
while (pbf_header_block.next()) {
switch (pbf_header_block.tag_and_type()) {
case protozero::tag_and_type(OSMFormat::HeaderBlock::optional_HeaderBBox_bbox, protozero::pbf_wire_type::length_delimited):
header.add_box(decode_header_bbox(pbf_header_block.get_view()));
break;
case protozero::tag_and_type(OSMFormat::HeaderBlock::repeated_string_required_features, protozero::pbf_wire_type::length_delimited):
{
auto feature = pbf_header_block.get_view();
if (!std::strncmp("OsmSchema-V0.6", feature.data(), feature.size())) {
// intentionally left blank
} else if (!std::strncmp("DenseNodes", feature.data(), feature.size())) {
header.set("pbf_dense_nodes", true);
} else if (!std::strncmp("HistoricalInformation", feature.data(), feature.size())) {
header.set_has_multiple_object_versions(true);
} else {
std::string msg{"required feature not supported: "};
msg.append(feature.data(), feature.size());
throw osmium::pbf_error{msg};
}
}
break;
case protozero::tag_and_type(OSMFormat::HeaderBlock::repeated_string_optional_features, protozero::pbf_wire_type::length_delimited): {
const auto opt = pbf_header_block.get_string();
header.set("pbf_optional_feature_" + std::to_string(i++), opt);
if (opt == "Sort.Type_then_ID") {
header.set("sorting", "Type_then_ID");
}
}
break;
case protozero::tag_and_type(OSMFormat::HeaderBlock::optional_string_writingprogram, protozero::pbf_wire_type::length_delimited):
header.set("generator", pbf_header_block.get_string());
break;
case protozero::tag_and_type(OSMFormat::HeaderBlock::optional_int64_osmosis_replication_timestamp, protozero::pbf_wire_type::varint):
{
const auto timestamp = osmium::Timestamp{pbf_header_block.get_int64()}.to_iso();
header.set("osmosis_replication_timestamp", timestamp);
header.set("timestamp", timestamp);
}
break;
case protozero::tag_and_type(OSMFormat::HeaderBlock::optional_int64_osmosis_replication_sequence_number, protozero::pbf_wire_type::varint):
header.set("osmosis_replication_sequence_number", std::to_string(pbf_header_block.get_int64()));
break;
case protozero::tag_and_type(OSMFormat::HeaderBlock::optional_string_osmosis_replication_base_url, protozero::pbf_wire_type::length_delimited):
header.set("osmosis_replication_base_url", pbf_header_block.get_string());
break;
default:
pbf_header_block.skip();
}
}
return header;
}
/**
* Decode HeaderBlock.
*
* @param header_block_data Input data
* @returns Header object
* @throws osmium::pbf_error If there was a parsing error
*/
inline osmium::io::Header decode_header(const std::string& header_block_data) {
std::string output;
return decode_header_block(decode_blob(header_block_data, output));
}
class PBFDataBlobDecoder {
std::shared_ptr<std::string> m_input_buffer;
osmium::osm_entity_bits::type m_read_types;
osmium::io::read_meta m_read_metadata;
public:
PBFDataBlobDecoder(std::string&& input_buffer, const osmium::osm_entity_bits::type read_types, const osmium::io::read_meta read_metadata) :
m_input_buffer(std::make_shared<std::string>(std::move(input_buffer))),
m_read_types(read_types),
m_read_metadata(read_metadata) {
}
osmium::memory::Buffer operator()() {
std::string output;
PBFPrimitiveBlockDecoder decoder{decode_blob(*m_input_buffer, output), m_read_types, m_read_metadata};
return decoder();
}
}; // class PBFDataBlobDecoder
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_PBF_DECODER_HPP
@@ -0,0 +1,321 @@
#ifndef OSMIUM_IO_DETAIL_PBF_INPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_PBF_INPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/detail/input_format.hpp>
#include <osmium/io/detail/pbf.hpp> // IWYU pragma: export
#include <osmium/io/detail/pbf_decoder.hpp>
#include <osmium/io/detail/protobuf_tags.hpp>
#include <osmium/io/detail/read_write.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/osm/entity_bits.hpp>
#include <osmium/thread/pool.hpp>
#include <osmium/thread/util.hpp>
#include <osmium/util/config.hpp>
#include <protozero/pbf_message.hpp>
#include <protozero/types.hpp>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
class PBFParser final : public Parser {
std::string m_input_buffer{};
std::atomic<std::size_t>* m_offset_ptr;
int m_fd;
bool m_want_buffered_pages_removed;
/**
* Make sure the input data contains at least the specified
* number of bytes.
*
* @param size Number of bytes to read
*/
void ensure_available_in_input_queue(size_t size) {
assert(m_fd == -1);
if (m_input_buffer.size() < size) {
m_input_buffer.reserve(size);
}
while (m_input_buffer.size() < size) {
const std::string new_data{get_input()};
if (input_done()) {
throw osmium::pbf_error{"truncated data (EOF encountered)"};
}
m_input_buffer += new_data;
}
}
/**
* Removes the specified number of bytes from the input data.
*
* @param size Number of bytes to remove
*/
void pop_from_input_queue(size_t size) {
assert(m_fd == -1);
m_input_buffer.erase(0, size);
}
static uint32_t get_size_in_network_byte_order(const char* d) noexcept {
return (static_cast<uint32_t>(d[3])) |
(static_cast<uint32_t>(d[2]) << 8U) |
(static_cast<uint32_t>(d[1]) << 16U) |
(static_cast<uint32_t>(d[0]) << 24U);
}
static uint32_t check_size(uint32_t size) {
if (size > static_cast<uint32_t>(max_blob_header_size)) {
throw osmium::pbf_error{"invalid BlobHeader size (> max_blob_header_size)"};
}
return size;
}
/**
* Read exactly size bytes from fd into buffer.
*
* @pre Value in size parameter must fit in unsigned int
* @returns true if size bytes could be read
* false if EOF was encountered
*/
bool read_exactly(char* buffer, std::size_t size) {
std::size_t to_read = size;
while (to_read > 0) {
auto const read_size = osmium::io::detail::reliable_read(m_fd, buffer + (size - to_read), static_cast<unsigned int>(to_read));
if (read_size == 0) { // EOF
return false;
}
to_read -= read_size;
}
*m_offset_ptr += size;
return true;
}
/**
* Read 4 bytes in network byte order from file. They contain
* the length of the following BlobHeader.
*/
uint32_t read_blob_header_size_from_file() {
if (m_fd != -1) {
std::array<char, sizeof(uint32_t)> buffer{};
if (!read_exactly(buffer.data(), buffer.size())) {
return 0; // EOF
}
return check_size(get_size_in_network_byte_order(buffer.data()));
}
uint32_t size = 0;
try {
ensure_available_in_input_queue(sizeof(size));
size = get_size_in_network_byte_order(m_input_buffer.data());
pop_from_input_queue(sizeof(size));
} catch (const osmium::pbf_error&) {
return 0; // EOF
}
if (size > static_cast<uint32_t>(max_blob_header_size)) {
throw osmium::pbf_error{"invalid BlobHeader size (> max_blob_header_size)"};
}
return size;
}
/**
* Decode the BlobHeader. Make sure it contains the expected
* type. Return the size of the following Blob.
*/
static size_t decode_blob_header(const protozero::data_view& data, const char* expected_type) {
protozero::pbf_message<FileFormat::BlobHeader> pbf_blob_header{data};
protozero::data_view blob_header_type;
size_t blob_header_datasize = 0;
while (pbf_blob_header.next()) {
switch (pbf_blob_header.tag_and_type()) {
case protozero::tag_and_type(FileFormat::BlobHeader::required_string_type, protozero::pbf_wire_type::length_delimited):
blob_header_type = pbf_blob_header.get_view();
break;
case protozero::tag_and_type(FileFormat::BlobHeader::required_int32_datasize, protozero::pbf_wire_type::varint):
blob_header_datasize = pbf_blob_header.get_int32();
break;
default:
pbf_blob_header.skip();
}
}
if (blob_header_datasize == 0) {
throw osmium::pbf_error{"PBF format error: BlobHeader.datasize missing or zero."};
}
if (std::strncmp(expected_type, blob_header_type.data(), blob_header_type.size()) != 0) {
throw osmium::pbf_error{"blob does not have expected type (OSMHeader in first blob, OSMData in following blobs)"};
}
return blob_header_datasize;
}
size_t check_type_and_get_blob_size(const char* expected_type) {
assert(expected_type);
const auto size = read_blob_header_size_from_file();
if (size == 0) { // EOF
return 0;
}
if (m_fd != -1) {
auto const buffer = read_from_input_queue_with_check(size);
const auto blob_size = decode_blob_header(protozero::data_view{buffer.data(), size}, expected_type);
return blob_size;
}
ensure_available_in_input_queue(size);
const auto blob_size = decode_blob_header(protozero::data_view{m_input_buffer.data(), size}, expected_type);
pop_from_input_queue(size);
return blob_size;
}
std::string read_from_input_queue_with_check(size_t size) {
if (size > max_uncompressed_blob_size) {
throw osmium::pbf_error{std::string{"invalid blob size: "} +
std::to_string(size)};
}
std::string buffer;
if (m_fd != -1) {
buffer.resize(size);
if (!read_exactly(&*buffer.begin(), size)) {
throw osmium::pbf_error{"unexpected EOF"};
}
} else {
ensure_available_in_input_queue(size);
buffer.append(m_input_buffer, 0, size);
pop_from_input_queue(size);
}
return buffer;
}
// Parse the header in the PBF OSMHeader blob.
void parse_header_blob() {
const auto size = check_type_and_get_blob_size("OSMHeader");
const osmium::io::Header header{decode_header(read_from_input_queue_with_check(size))};
set_header_value(header);
}
void parse_data_blobs() {
const bool use_pool = osmium::config::use_pool_threads_for_pbf_parsing();
while (const auto size = check_type_and_get_blob_size("OSMData")) {
std::string input_buffer{read_from_input_queue_with_check(size)};
PBFDataBlobDecoder data_blob_parser{std::move(input_buffer), read_types(), read_metadata()};
if (use_pool) {
send_to_output_queue(get_pool().submit(std::move(data_blob_parser)));
} else {
send_to_output_queue(data_blob_parser());
}
if (m_want_buffered_pages_removed) {
osmium::io::detail::remove_buffered_pages(m_fd, *m_offset_ptr);
}
}
}
public:
explicit PBFParser(parser_arguments& args) :
Parser(args),
m_offset_ptr(args.offset_ptr),
m_fd(args.fd),
m_want_buffered_pages_removed(args.want_buffered_pages_removed) {
}
PBFParser(const PBFParser&) = delete;
PBFParser& operator=(const PBFParser&) = delete;
PBFParser(PBFParser&&) = delete;
PBFParser& operator=(PBFParser&&) = delete;
~PBFParser() noexcept override = default;
void run() override {
osmium::thread::set_thread_name("_osmium_pbf_in");
parse_header_blob();
if (read_types() != osmium::osm_entity_bits::nothing) {
parse_data_blobs();
}
osmium::io::detail::reliable_close(m_fd);
}
}; // class PBFParser
// we want the register_parser() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_pbf_parser = ParserFactory::instance().register_parser(
file_format::pbf,
[](parser_arguments& args) {
return std::unique_ptr<Parser>(new PBFParser{args});
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_pbf_parser() noexcept {
return registered_pbf_parser;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_PBF_INPUT_FORMAT_HPP
@@ -0,0 +1,777 @@
#ifndef OSMIUM_IO_DETAIL_PBF_OUTPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_PBF_OUTPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <cassert>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <osmium/handler.hpp>
#include <osmium/io/detail/output_format.hpp>
#include <osmium/io/detail/pbf.hpp> // IWYU pragma: export
#include <osmium/io/detail/protobuf_tags.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/detail/string_table.hpp>
#include <osmium/io/detail/zlib.hpp>
#include <osmium/io/file.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/memory/item_iterator.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/metadata_options.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/node_ref.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/tag.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/thread/pool.hpp>
#include <osmium/util/delta.hpp>
#include <osmium/util/misc.hpp>
#include <osmium/visitor.hpp>
#ifdef OSMIUM_WITH_LZ4
# include <osmium/io/detail/lz4.hpp>
#endif
#include <protozero/pbf_builder.hpp>
#include <protozero/pbf_writer.hpp>
#include <protozero/types.hpp>
namespace osmium {
namespace io {
namespace detail {
struct pbf_output_options {
/// Which metadata of objects should be added?
osmium::metadata_options add_metadata;
/// Compression level used for compression
int compression_level = 0;
/**
* Which compression (if any) should be used to compress the
* PBF blobs?
*/
pbf_compression use_compression = pbf_compression::zlib;
/// Should nodes be encoded in DenseNodes?
bool use_dense_nodes = true;
/// Add the "HistoricalInformation" header flag.
bool add_historical_information_flag = false;
/// Should the visible flag be added to all OSM objects?
bool add_visible_flag = false;
/// Should node locations be added to ways?
bool locations_on_ways = false;
}; // struct pbf_output_options
/**
* Maximum number of items in a primitive block.
*
* The uncompressed length of a Blob *should* be less
* than 16 megabytes and *must* be less than 32 megabytes.
*
* A block may contain any number of entities, as long as
* the size limits for the surrounding blob are obeyed.
* However, for simplicity, the current Osmosis (0.38)
* as well as Osmium implementation always
* uses at most 8k entities in a block.
*/
enum {
max_entities_per_block = 8000
};
enum class pbf_blob_type {
header = 0,
data = 1
};
/**
* Contains the code to pack any number of nodes into a DenseNode
* structure.
*/
class DenseNodes {
std::vector<int64_t> m_ids;
std::vector<int32_t> m_versions;
std::vector<int64_t> m_timestamps;
std::vector<int64_t> m_changesets;
std::vector<int32_t> m_uids;
std::vector<int32_t> m_user_sids;
std::vector<bool> m_visibles;
std::vector<int64_t> m_lats;
std::vector<int64_t> m_lons;
std::vector<int32_t> m_tags;
StringTable* m_stringtable;
const pbf_output_options* m_options;
osmium::DeltaEncode<object_id_type, int64_t> m_delta_id;
osmium::DeltaEncode<uint32_t, int64_t> m_delta_timestamp;
osmium::DeltaEncode<changeset_id_type, int64_t> m_delta_changeset;
osmium::DeltaEncode<user_id_type, int32_t> m_delta_uid;
osmium::DeltaEncode<int32_t, int32_t> m_delta_user_sid;
osmium::DeltaEncode<int64_t, int64_t> m_delta_lat;
osmium::DeltaEncode<int64_t, int64_t> m_delta_lon;
public:
DenseNodes(StringTable* stringtable, const pbf_output_options* options) :
m_stringtable(stringtable),
m_options(options) {
m_ids.reserve(max_entities_per_block);
if (m_options->add_metadata.version()) {
m_versions.reserve(max_entities_per_block);
}
if (m_options->add_metadata.timestamp()) {
m_timestamps.reserve(max_entities_per_block);
}
if (m_options->add_metadata.changeset()) {
m_changesets.reserve(max_entities_per_block);
}
if (m_options->add_metadata.uid()) {
m_uids.reserve(max_entities_per_block);
}
if (m_options->add_metadata.user()) {
m_user_sids.reserve(max_entities_per_block);
}
if (m_options->add_visible_flag) {
m_visibles.reserve(max_entities_per_block);
}
m_lats.reserve(max_entities_per_block);
m_lons.reserve(max_entities_per_block);
}
std::size_t size() const noexcept {
return m_ids.size() * 3 * sizeof(int64_t);
}
void add_node(const osmium::Node& node) {
m_ids.push_back(m_delta_id.update(node.id()));
if (m_options->add_metadata.version()) {
assert(node.version() <= static_cast<std::size_t>(std::numeric_limits<int32_t>::max()));
m_versions.push_back(static_cast<int32_t>(node.version()));
}
if (m_options->add_metadata.timestamp()) {
m_timestamps.push_back(m_delta_timestamp.update(static_cast<uint32_t>(node.timestamp())));
}
if (m_options->add_metadata.changeset()) {
m_changesets.push_back(m_delta_changeset.update(node.changeset()));
}
if (m_options->add_metadata.uid()) {
m_uids.push_back(m_delta_uid.update(node.uid()));
}
if (m_options->add_metadata.user()) {
m_user_sids.push_back(m_delta_user_sid.update(m_stringtable->add(node.user())));
}
if (m_options->add_visible_flag) {
m_visibles.push_back(node.visible());
}
m_lats.push_back(m_delta_lat.update(node.location().y()));
m_lons.push_back(m_delta_lon.update(node.location().x()));
for (const auto& tag : node.tags()) {
m_tags.push_back(m_stringtable->add(tag.key()));
m_tags.push_back(m_stringtable->add(tag.value()));
}
m_tags.push_back(0);
}
std::string serialize() const {
std::string data;
protozero::pbf_builder<OSMFormat::DenseNodes> pbf_dense_nodes{data};
pbf_dense_nodes.add_packed_sint64(OSMFormat::DenseNodes::packed_sint64_id, m_ids.cbegin(), m_ids.cend());
if (m_options->add_metadata.any() || m_options->add_visible_flag) {
protozero::pbf_builder<OSMFormat::DenseInfo> pbf_dense_info{pbf_dense_nodes, OSMFormat::DenseNodes::optional_DenseInfo_denseinfo};
if (m_options->add_metadata.version()) {
pbf_dense_info.add_packed_int32(OSMFormat::DenseInfo::packed_int32_version, m_versions.cbegin(), m_versions.cend());
}
if (m_options->add_metadata.timestamp()) {
pbf_dense_info.add_packed_sint64(OSMFormat::DenseInfo::packed_sint64_timestamp, m_timestamps.cbegin(), m_timestamps.cend());
}
if (m_options->add_metadata.changeset()) {
pbf_dense_info.add_packed_sint64(OSMFormat::DenseInfo::packed_sint64_changeset, m_changesets.cbegin(), m_changesets.cend());
}
if (m_options->add_metadata.uid()) {
pbf_dense_info.add_packed_sint32(OSMFormat::DenseInfo::packed_sint32_uid, m_uids.cbegin(), m_uids.cend());
}
if (m_options->add_metadata.user()) {
pbf_dense_info.add_packed_sint32(OSMFormat::DenseInfo::packed_sint32_user_sid, m_user_sids.cbegin(), m_user_sids.cend());
}
if (m_options->add_visible_flag) {
pbf_dense_info.add_packed_bool(OSMFormat::DenseInfo::packed_bool_visible, m_visibles.cbegin(), m_visibles.cend());
}
}
pbf_dense_nodes.add_packed_sint64(OSMFormat::DenseNodes::packed_sint64_lat, m_lats.cbegin(), m_lats.cend());
pbf_dense_nodes.add_packed_sint64(OSMFormat::DenseNodes::packed_sint64_lon, m_lons.cbegin(), m_lons.cend());
pbf_dense_nodes.add_packed_int32(OSMFormat::DenseNodes::packed_int32_keys_vals, m_tags.cbegin(), m_tags.cend());
return data;
}
}; // class DenseNodes
class PrimitiveBlock {
std::string m_pbf_primitive_group_data;
protozero::pbf_builder<OSMFormat::PrimitiveGroup> m_pbf_primitive_group;
StringTable m_stringtable;
pbf_output_options m_options;
std::unique_ptr<DenseNodes> m_dense_nodes{};
OSMFormat::PrimitiveGroup m_type;
int m_count = 0;
public:
explicit PrimitiveBlock(const pbf_output_options& options, OSMFormat::PrimitiveGroup type, size_t bucket_count) :
m_pbf_primitive_group(m_pbf_primitive_group_data),
m_stringtable(StringTable::default_stringtable_chunk_size, bucket_count),
m_options(options),
m_type(type) {
}
std::size_t get_bucket_count() const noexcept {
return m_stringtable.get_bucket_count();
}
const std::string& group_data() {
if (m_dense_nodes) {
m_pbf_primitive_group.add_message(OSMFormat::PrimitiveGroup::optional_DenseNodes_dense, m_dense_nodes->serialize());
}
return m_pbf_primitive_group_data;
}
void write_stringtable(protozero::pbf_builder<OSMFormat::StringTable>& pbf_string_table) {
for (const char* s : m_stringtable) {
pbf_string_table.add_bytes(OSMFormat::StringTable::repeated_bytes_s, s);
}
}
protozero::pbf_builder<OSMFormat::PrimitiveGroup>& group() noexcept {
++m_count;
return m_pbf_primitive_group;
}
void add_dense_node(const osmium::Node& node) {
if (!m_dense_nodes) {
m_dense_nodes.reset(new DenseNodes{&m_stringtable, &m_options});
}
m_dense_nodes->add_node(node);
++m_count;
}
// There are two functions store_in_stringtable(_unsigned)
// here because of an inconsistency in the OSMPBF format
// specification. Both uint32 and sint32 types are used in
// the format for essentially the same thing.
int32_t store_in_stringtable(const char* s) {
return m_stringtable.add(s);
}
uint32_t store_in_stringtable_unsigned(const char* s) {
// static_cast okay, because result of add is always >= 0
return static_cast<uint32_t>(m_stringtable.add(s));
}
int count() const noexcept {
return m_count;
}
std::size_t size() const noexcept {
return m_pbf_primitive_group_data.size() +
m_stringtable.size() +
(m_dense_nodes ? m_dense_nodes->size() : 0);
}
/**
* The output buffer (block) will be filled to about
* 95% and then written to disk. This leaves more than
* enough space for the string table (which typically
* needs about 0.1 to 0.3% of the block size).
*/
enum {
max_used_blob_size = max_uncompressed_blob_size * 95U / 100U
};
bool can_add(OSMFormat::PrimitiveGroup type) const noexcept {
if (type != m_type) {
return false;
}
if (count() >= max_entities_per_block) {
return false;
}
return size() < max_used_blob_size;
}
}; // class PrimitiveBlock
class SerializeBlob {
std::shared_ptr<PrimitiveBlock> m_block{};
std::string m_msg;
int m_compression_level;
pbf_blob_type m_blob_type;
pbf_compression m_use_compression;
public:
/**
* Initialize a blob serializer.
*
* @param msg Protobuf-message containing the blob data.
* @param type Type of blob.
* @param use_compression The type of compression to use.
* @param compression_level Compression level.
*/
SerializeBlob(std::string&& msg, pbf_blob_type type, pbf_compression use_compression, int compression_level) :
m_msg(std::move(msg)),
m_compression_level(compression_level),
m_blob_type(type),
m_use_compression(use_compression) {
}
/**
* Initialize a blob serializer.
*
* @param block Pointer to PrimitiveBlock with data.
* @param type Type of blob.
* @param use_compression The type of compression to use.
* @param compression_level Compression level.
*/
SerializeBlob(std::shared_ptr<PrimitiveBlock> block, pbf_blob_type type, pbf_compression use_compression, int compression_level) :
m_block(std::move(block)),
m_compression_level(compression_level),
m_blob_type(type),
m_use_compression(use_compression) {
}
/**
* Serialize a protobuf message into a Blob, optionally apply
* compression and return it together with a BlobHeader ready
* to be written to a file.
*/
std::string operator()() {
if (m_block) {
protozero::pbf_builder<OSMFormat::PrimitiveBlock> primitive_block{m_msg};
{
protozero::pbf_builder<OSMFormat::StringTable> pbf_string_table{primitive_block, OSMFormat::PrimitiveBlock::required_StringTable_stringtable};
m_block->write_stringtable(pbf_string_table);
}
primitive_block.add_message(OSMFormat::PrimitiveBlock::repeated_PrimitiveGroup_primitivegroup, m_block->group_data());
}
assert(m_msg.size() <= max_uncompressed_blob_size);
std::string blob_data;
protozero::pbf_builder<FileFormat::Blob> pbf_blob{blob_data};
switch (m_use_compression) {
case pbf_compression::none:
pbf_blob.add_bytes(FileFormat::Blob::optional_bytes_raw, m_msg);
break;
case pbf_compression::zlib:
pbf_blob.add_int32(FileFormat::Blob::optional_int32_raw_size, static_cast<int32_t>(m_msg.size()));
pbf_blob.add_bytes(FileFormat::Blob::optional_bytes_zlib_data, osmium::io::detail::zlib_compress(m_msg, m_compression_level));
break;
case pbf_compression::lz4:
#ifdef OSMIUM_WITH_LZ4
pbf_blob.add_int32(FileFormat::Blob::optional_int32_raw_size, static_cast<int32_t>(m_msg.size()));
pbf_blob.add_bytes(FileFormat::Blob::optional_bytes_lz4_data, osmium::io::detail::lz4_compress(m_msg, m_compression_level));
break;
#else
throw osmium::pbf_error{"lz4 blobs not supported"};
#endif
}
std::string blob_header_data;
protozero::pbf_builder<FileFormat::BlobHeader> pbf_blob_header{blob_header_data};
pbf_blob_header.add_string(FileFormat::BlobHeader::required_string_type, m_blob_type == pbf_blob_type::data ? "OSMData" : "OSMHeader");
// The static_cast is okay, because the size can never
// be much larger than max_uncompressed_blob_size. This
// is due to the assert above and the fact that the zlib
// library will not grow deflated data beyond the original
// data plus a few header bytes (https://zlib.net/zlib_tech.html).
pbf_blob_header.add_int32(FileFormat::BlobHeader::required_int32_datasize, static_cast<int32_t>(blob_data.size()));
const auto size = static_cast<uint32_t>(blob_header_data.size());
// write to output: the 4-byte BlobHeader size in network
// byte order followed by the BlobHeader followed by the Blob
std::string output;
output.reserve(4 + blob_header_data.size() + blob_data.size());
output += static_cast<char>((size >> 24U) & 0xffU);
output += static_cast<char>((size >> 16U) & 0xffU);
output += static_cast<char>((size >> 8U) & 0xffU);
output += static_cast<char>( size & 0xffU);
output.append(blob_header_data);
output.append(blob_data);
return output;
}
}; // class SerializeBlob
class PBFOutputFormat : public osmium::io::detail::OutputFormat, public osmium::handler::Handler {
pbf_output_options m_options;
std::shared_ptr<PrimitiveBlock> m_primitive_block{};
std::size_t m_bucket_count = StringTable::min_bucket_count;
void store_primitive_block() {
if (!m_primitive_block || m_primitive_block->count() == 0) {
return;
}
// Remember the bucket_count of the hash in the string
// table. It will be used when initializing the string
// table for the next block.
//
// Some versions of the std library will set the bucket
// count always larger then what we set it to. We decrease
// the bucket count by one, this way the bucket will not
// grow too much.
m_bucket_count = m_primitive_block->get_bucket_count() - 1;
m_output_queue.push(m_pool.submit(
SerializeBlob{std::move(m_primitive_block),
pbf_blob_type::data,
m_options.use_compression,
m_options.compression_level}));
}
template <typename T>
void add_meta(const osmium::OSMObject& object, T& pbf_object) {
{
protozero::packed_field_uint32 field{pbf_object, static_cast<protozero::pbf_tag_type>(T::enum_type::packed_uint32_keys)};
for (const auto& tag : object.tags()) {
field.add_element(m_primitive_block->store_in_stringtable_unsigned(tag.key()));
}
}
{
protozero::packed_field_uint32 field{pbf_object, static_cast<protozero::pbf_tag_type>(T::enum_type::packed_uint32_vals)};
for (const auto& tag : object.tags()) {
field.add_element(m_primitive_block->store_in_stringtable_unsigned(tag.value()));
}
}
if (m_options.add_metadata.any() || m_options.add_visible_flag) {
protozero::pbf_builder<OSMFormat::Info> pbf_info{pbf_object, T::enum_type::optional_Info_info};
if (m_options.add_metadata.version()) {
assert(object.version() <= static_cast<std::size_t>(std::numeric_limits<int32_t>::max()));
pbf_info.add_int32(OSMFormat::Info::optional_int32_version, static_cast<int32_t>(object.version()));
}
if (m_options.add_metadata.timestamp()) {
pbf_info.add_int64(OSMFormat::Info::optional_int64_timestamp, static_cast<uint32_t>(object.timestamp()));
}
if (m_options.add_metadata.changeset()) {
pbf_info.add_int64(OSMFormat::Info::optional_int64_changeset, object.changeset());
}
if (m_options.add_metadata.uid()) {
assert(object.uid() <= static_cast<std::size_t>(std::numeric_limits<int32_t>::max()));
pbf_info.add_int32(OSMFormat::Info::optional_int32_uid, static_cast<int32_t>(object.uid()));
}
if (m_options.add_metadata.user()) {
pbf_info.add_uint32(OSMFormat::Info::optional_uint32_user_sid, m_primitive_block->store_in_stringtable_unsigned(object.user()));
}
if (m_options.add_visible_flag) {
pbf_info.add_bool(OSMFormat::Info::optional_bool_visible, object.visible());
}
}
}
void switch_primitive_block_type(OSMFormat::PrimitiveGroup type) {
if (!m_primitive_block || !m_primitive_block->can_add(type)) {
store_primitive_block();
m_primitive_block.reset(new PrimitiveBlock{m_options, type, m_bucket_count});
}
}
public:
PBFOutputFormat(osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) :
OutputFormat(pool, output_queue) {
if (!file.get("pbf_add_metadata").empty()) {
throw std::invalid_argument{"The 'pbf_add_metadata' option is deprecated. Please use 'add_metadata' instead."};
}
m_options.use_dense_nodes = file.is_not_false("pbf_dense_nodes");
m_options.use_compression = get_compression_type(file.get("pbf_compression"));
m_options.add_metadata = osmium::metadata_options{file.get("add_metadata")};
m_options.add_historical_information_flag = file.has_multiple_object_versions();
m_options.add_visible_flag = file.has_multiple_object_versions();
m_options.locations_on_ways = file.is_true("locations_on_ways");
const auto pbl = file.get("pbf_compression_level");
if (pbl.empty()) {
switch (m_options.use_compression) {
case pbf_compression::none:
break;
case pbf_compression::zlib:
m_options.compression_level = osmium::io::detail::zlib_default_compression_level();
break;
case pbf_compression::lz4:
#ifdef OSMIUM_WITH_LZ4
m_options.compression_level = osmium::io::detail::lz4_default_compression_level();
#endif
break;
}
} else {
char* end_ptr = nullptr;
const auto val = std::strtol(pbl.c_str(), &end_ptr, 10);
if (*end_ptr != '\0') {
throw std::invalid_argument{"The 'pbf_compression_level' option must be an integer."};
}
switch (m_options.use_compression) {
case pbf_compression::none:
throw std::invalid_argument{"The 'pbf_compression_level' option doesn't make sense without 'pbf_compression' set."};
case pbf_compression::zlib:
osmium::io::detail::zlib_check_compression_level(val);
break;
case pbf_compression::lz4:
#ifdef OSMIUM_WITH_LZ4
osmium::io::detail::lz4_check_compression_level(val);
#endif
break;
}
m_options.compression_level = static_cast<int>(val);
}
}
void write_header(const osmium::io::Header& header) final {
std::string data;
protozero::pbf_builder<OSMFormat::HeaderBlock> pbf_header_block{data};
if (!header.boxes().empty()) {
protozero::pbf_builder<OSMFormat::HeaderBBox> pbf_header_bbox{pbf_header_block, OSMFormat::HeaderBlock::optional_HeaderBBox_bbox};
osmium::Box box = header.joined_boxes();
pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_left, static_cast<int64_t>(box.bottom_left().lon() * lonlat_resolution));
pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_right, static_cast<int64_t>(box.top_right().lon() * lonlat_resolution));
pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_top, static_cast<int64_t>(box.top_right().lat() * lonlat_resolution));
pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_bottom, static_cast<int64_t>(box.bottom_left().lat() * lonlat_resolution));
}
pbf_header_block.add_string(OSMFormat::HeaderBlock::repeated_string_required_features, "OsmSchema-V0.6");
if (m_options.use_dense_nodes) {
pbf_header_block.add_string(OSMFormat::HeaderBlock::repeated_string_required_features, "DenseNodes");
}
if (m_options.add_historical_information_flag) {
pbf_header_block.add_string(OSMFormat::HeaderBlock::repeated_string_required_features, "HistoricalInformation");
}
if (m_options.locations_on_ways) {
pbf_header_block.add_string(OSMFormat::HeaderBlock::repeated_string_optional_features, "LocationsOnWays");
}
if (header.get("sorting") == "Type_then_ID") {
pbf_header_block.add_string(OSMFormat::HeaderBlock::repeated_string_optional_features, "Sort.Type_then_ID");
}
pbf_header_block.add_string(OSMFormat::HeaderBlock::optional_string_writingprogram, header.get("generator"));
const std::string osmosis_replication_timestamp{header.get("osmosis_replication_timestamp")};
if (!osmosis_replication_timestamp.empty()) {
const osmium::Timestamp ts{osmosis_replication_timestamp.c_str()};
pbf_header_block.add_int64(OSMFormat::HeaderBlock::optional_int64_osmosis_replication_timestamp, static_cast<uint32_t>(ts));
}
const std::string osmosis_replication_sequence_number{header.get("osmosis_replication_sequence_number")};
if (!osmosis_replication_sequence_number.empty()) {
pbf_header_block.add_int64(OSMFormat::HeaderBlock::optional_int64_osmosis_replication_sequence_number, osmium::detail::str_to_int<int64_t>(osmosis_replication_sequence_number.c_str()));
}
const std::string osmosis_replication_base_url{header.get("osmosis_replication_base_url")};
if (!osmosis_replication_base_url.empty()) {
pbf_header_block.add_string(OSMFormat::HeaderBlock::optional_string_osmosis_replication_base_url, osmosis_replication_base_url);
}
m_output_queue.push(m_pool.submit(
SerializeBlob{std::move(data),
pbf_blob_type::header,
m_options.use_compression,
m_options.compression_level}));
}
void write_buffer(osmium::memory::Buffer&& buffer) final {
osmium::apply(buffer.cbegin(), buffer.cend(), *this);
}
void write_end() final {
store_primitive_block();
}
void node(const osmium::Node& node) {
if (m_options.use_dense_nodes) {
switch_primitive_block_type(OSMFormat::PrimitiveGroup::optional_DenseNodes_dense);
m_primitive_block->add_dense_node(node);
return;
}
switch_primitive_block_type(OSMFormat::PrimitiveGroup::repeated_Node_nodes);
protozero::pbf_builder<OSMFormat::Node> pbf_node{m_primitive_block->group(), OSMFormat::PrimitiveGroup::repeated_Node_nodes};
pbf_node.add_sint64(OSMFormat::Node::required_sint64_id, node.id());
add_meta(node, pbf_node);
pbf_node.add_sint64(OSMFormat::Node::required_sint64_lat, node.location().y());
pbf_node.add_sint64(OSMFormat::Node::required_sint64_lon, node.location().x());
}
void way(const osmium::Way& way) {
switch_primitive_block_type(OSMFormat::PrimitiveGroup::repeated_Way_ways);
protozero::pbf_builder<OSMFormat::Way> pbf_way{m_primitive_block->group(), OSMFormat::PrimitiveGroup::repeated_Way_ways};
pbf_way.add_int64(OSMFormat::Way::required_int64_id, way.id());
add_meta(way, pbf_way);
{
osmium::DeltaEncode<object_id_type, int64_t> delta_id;
protozero::packed_field_sint64 field{pbf_way, static_cast<protozero::pbf_tag_type>(OSMFormat::Way::packed_sint64_refs)};
for (const auto& node_ref : way.nodes()) {
field.add_element(delta_id.update(node_ref.ref()));
}
}
if (m_options.locations_on_ways) {
{
osmium::DeltaEncode<int64_t, int64_t> delta;
protozero::packed_field_sint64 field{pbf_way, static_cast<protozero::pbf_tag_type>(OSMFormat::Way::packed_sint64_lon)};
for (const auto& node_ref : way.nodes()) {
field.add_element(delta.update(node_ref.location().x()));
}
}
{
osmium::DeltaEncode<int64_t, int64_t> delta;
protozero::packed_field_sint64 field{pbf_way, static_cast<protozero::pbf_tag_type>(OSMFormat::Way::packed_sint64_lat)};
for (const auto& node_ref : way.nodes()) {
field.add_element(delta.update(node_ref.location().y()));
}
}
}
}
void relation(const osmium::Relation& relation) {
switch_primitive_block_type(OSMFormat::PrimitiveGroup::repeated_Relation_relations);
protozero::pbf_builder<OSMFormat::Relation> pbf_relation{m_primitive_block->group(), OSMFormat::PrimitiveGroup::repeated_Relation_relations};
pbf_relation.add_int64(OSMFormat::Relation::required_int64_id, relation.id());
add_meta(relation, pbf_relation);
{
protozero::packed_field_int32 field{pbf_relation, static_cast<protozero::pbf_tag_type>(OSMFormat::Relation::packed_int32_roles_sid)};
for (const auto& member : relation.members()) {
field.add_element(m_primitive_block->store_in_stringtable(member.role()));
}
}
{
osmium::DeltaEncode<object_id_type, int64_t> delta_id;
protozero::packed_field_sint64 field{pbf_relation, static_cast<protozero::pbf_tag_type>(OSMFormat::Relation::packed_sint64_memids)};
for (const auto& member : relation.members()) {
field.add_element(delta_id.update(member.ref()));
}
}
{
protozero::packed_field_int32 field{pbf_relation, static_cast<protozero::pbf_tag_type>(OSMFormat::Relation::packed_MemberType_types)};
for (const auto& member : relation.members()) {
field.add_element(static_cast<int32_t>(osmium::item_type_to_nwr_index(member.type())));
}
}
}
}; // class PBFOutputFormat
// we want the register_output_format() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_pbf_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::pbf,
[](osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) {
return new osmium::io::detail::PBFOutputFormat{pool, file, output_queue};
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_pbf_output() noexcept {
return registered_pbf_output;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_PBF_OUTPUT_FORMAT_HPP
@@ -0,0 +1,174 @@
#ifndef OSMIUM_IO_DETAIL_PROTOBUF_TAGS_HPP
#define OSMIUM_IO_DETAIL_PROTOBUF_TAGS_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <protozero/types.hpp>
namespace osmium {
namespace io {
namespace detail {
// directly translated from
// https://github.com/openstreetmap/OSM-binary/blob/master/src/fileformat.proto
namespace FileFormat {
enum class Blob : protozero::pbf_tag_type {
optional_bytes_raw = 1,
optional_int32_raw_size = 2,
optional_bytes_zlib_data = 3,
optional_bytes_lzma_data = 4,
optional_bytes_lz4_data = 6,
optional_bytes_zstd_data = 7
};
enum class BlobHeader : protozero::pbf_tag_type {
required_string_type = 1,
optional_bytes_indexdata = 2,
required_int32_datasize = 3
};
} // namespace FileFormat
// directly translated from
// https://github.com/openstreetmap/OSM-binary/blob/master/src/osmformat.proto
namespace OSMFormat {
enum class HeaderBlock : protozero::pbf_tag_type {
optional_HeaderBBox_bbox = 1,
repeated_string_required_features = 4,
repeated_string_optional_features = 5,
optional_string_writingprogram = 16,
optional_string_source = 17,
optional_int64_osmosis_replication_timestamp = 32,
optional_int64_osmosis_replication_sequence_number = 33,
optional_string_osmosis_replication_base_url = 34
};
enum class HeaderBBox : protozero::pbf_tag_type {
required_sint64_left = 1,
required_sint64_right = 2,
required_sint64_top = 3,
required_sint64_bottom = 4
};
enum class PrimitiveBlock : protozero::pbf_tag_type {
required_StringTable_stringtable = 1,
repeated_PrimitiveGroup_primitivegroup = 2,
optional_int32_granularity = 17,
optional_int32_date_granularity = 18,
optional_int64_lat_offset = 19,
optional_int64_lon_offset = 20
};
enum class PrimitiveGroup : protozero::pbf_tag_type {
unknown = 0,
repeated_Node_nodes = 1,
optional_DenseNodes_dense = 2,
repeated_Way_ways = 3,
repeated_Relation_relations = 4,
repeated_ChangeSet_changesets = 5
};
enum class StringTable : protozero::pbf_tag_type {
repeated_bytes_s = 1
};
enum class Info : protozero::pbf_tag_type {
optional_int32_version = 1,
optional_int64_timestamp = 2,
optional_int64_changeset = 3,
optional_int32_uid = 4,
optional_uint32_user_sid = 5,
optional_bool_visible = 6
};
enum class DenseInfo : protozero::pbf_tag_type {
packed_int32_version = 1,
packed_sint64_timestamp = 2,
packed_sint64_changeset = 3,
packed_sint32_uid = 4,
packed_sint32_user_sid = 5,
packed_bool_visible = 6
};
enum class Node : protozero::pbf_tag_type {
required_sint64_id = 1,
packed_uint32_keys = 2,
packed_uint32_vals = 3,
optional_Info_info = 4,
required_sint64_lat = 8,
required_sint64_lon = 9
};
enum class DenseNodes : protozero::pbf_tag_type {
packed_sint64_id = 1,
optional_DenseInfo_denseinfo = 5,
packed_sint64_lat = 8,
packed_sint64_lon = 9,
packed_int32_keys_vals = 10
};
enum class Way : protozero::pbf_tag_type {
required_int64_id = 1,
packed_uint32_keys = 2,
packed_uint32_vals = 3,
optional_Info_info = 4,
packed_sint64_refs = 8,
packed_sint64_lat = 9,
packed_sint64_lon = 10
};
enum class Relation : protozero::pbf_tag_type {
required_int64_id = 1,
packed_uint32_keys = 2,
packed_uint32_vals = 3,
optional_Info_info = 4,
packed_int32_roles_sid = 8,
packed_sint64_memids = 9,
packed_MemberType_types = 10
};
} // namespace OSMFormat
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_PROTOBUF_TAGS_HPP
@@ -0,0 +1,155 @@
#ifndef OSMIUM_IO_DETAIL_QUEUE_UTIL_HPP
#define OSMIUM_IO_DETAIL_QUEUE_UTIL_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/memory/buffer.hpp>
#include <osmium/thread/queue.hpp>
#include <cassert>
#include <exception>
#include <future>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
template <typename T>
using future_queue_type = osmium::thread::Queue<std::future<T>>;
/**
* This type of queue contains buffers with OSM data in them.
* The "end of file" is marked by an invalid Buffer.
* The buffers are wrapped in a std::future so that they can also
* transport exceptions. The future also helps with keeping the
* data in order.
*/
using future_buffer_queue_type = future_queue_type<osmium::memory::Buffer>;
/**
* This type of queue contains OSM file data in the form it is
* stored on disk, ie encoded as XML, PBF, etc.
* The "end of file" is marked by an empty string.
* The strings are wrapped in a std::future so that they can also
* transport exceptions. The future also helps with keeping the
* data in order.
*/
using future_string_queue_type = future_queue_type<std::string>;
template <typename T>
inline void add_to_queue(future_queue_type<T>& queue, T&& data) {
std::promise<T> promise;
queue.push(promise.get_future());
promise.set_value(std::forward<T>(data));
}
template <typename T>
inline void add_to_queue(future_queue_type<T>& queue, std::exception_ptr&& exception) {
std::promise<T> promise;
queue.push(promise.get_future());
promise.set_exception(std::move(exception));
}
template <typename T>
inline void add_end_of_data_to_queue(future_queue_type<T>& queue) {
add_to_queue<T>(queue, T{});
}
inline bool at_end_of_data(const std::string& data) noexcept {
return data.empty();
}
inline bool at_end_of_data(const osmium::memory::Buffer& buffer) noexcept {
return !buffer;
}
template <typename T>
class queue_wrapper {
future_queue_type<T>& m_queue;
public:
explicit queue_wrapper(future_queue_type<T>& queue) :
m_queue(queue) {
}
queue_wrapper(const queue_wrapper&) = delete;
queue_wrapper& operator=(const queue_wrapper&) = delete;
queue_wrapper(queue_wrapper&&) = delete;
queue_wrapper& operator=(queue_wrapper&&) = delete;
~queue_wrapper() noexcept {
try {
shutdown();
} catch (...) {
}
}
void shutdown() {
m_queue.shutdown();
}
bool has_reached_end_of_data() const noexcept {
return !m_queue.in_use();
}
T pop() {
T data;
if (m_queue.in_use()) {
std::future<T> data_future;
m_queue.wait_and_pop(data_future);
if (data_future.valid()) {
data = std::move(data_future.get());
if (at_end_of_data(data)) {
m_queue.shutdown();
}
}
}
return data;
}
}; // class queue_wrapper
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_QUEUE_UTIL_HPP
@@ -0,0 +1,133 @@
#ifndef OSMIUM_IO_DETAIL_READ_THREAD_HPP
#define OSMIUM_IO_DETAIL_READ_THREAD_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/compression.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/thread/util.hpp>
#include <atomic>
#include <exception>
#include <string>
#include <thread>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
/**
* This code uses an internally managed thread to read data from
* the input file and (optionally) decompress it. The result is
* sent to the given queue. Any exceptions will also be send to
* the queue.
*/
class ReadThreadManager {
// only used in the sub-thread
osmium::io::Decompressor& m_decompressor;
future_string_queue_type& m_queue;
// used in both threads
std::atomic<bool> m_done;
// only used in the main thread
std::thread m_thread;
void run_in_thread() {
osmium::thread::set_thread_name("_osmium_read");
try {
while (!m_done) {
std::string data{m_decompressor.read()};
if (at_end_of_data(data)) {
break;
}
add_to_queue(m_queue, std::move(data));
}
m_decompressor.close();
} catch (...) {
add_to_queue(m_queue, std::current_exception());
}
add_end_of_data_to_queue(m_queue);
}
public:
ReadThreadManager(osmium::io::Decompressor& decompressor,
future_string_queue_type& queue) :
m_decompressor(decompressor),
m_queue(queue),
m_done(false),
m_thread(std::thread(&ReadThreadManager::run_in_thread, this)) {
}
ReadThreadManager(const ReadThreadManager&) = delete;
ReadThreadManager& operator=(const ReadThreadManager&) = delete;
ReadThreadManager(ReadThreadManager&&) = delete;
ReadThreadManager& operator=(ReadThreadManager&&) = delete;
~ReadThreadManager() noexcept {
try {
close();
} catch (...) {
// Ignore any exceptions because destructor must not throw.
}
}
void stop() noexcept {
m_done = true;
}
void close() {
stop();
if (m_thread.joinable()) {
m_thread.join();
}
}
}; // class ReadThreadManager
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_READ_THREAD_HPP
@@ -0,0 +1,294 @@
#ifndef OSMIUM_IO_DETAIL_READ_WRITE_HPP
#define OSMIUM_IO_DETAIL_READ_WRITE_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/writer_options.hpp>
#include <osmium/util/file.hpp>
#include <cerrno>
#include <cstddef>
#include <fcntl.h>
#include <string>
#include <system_error>
namespace osmium {
namespace io {
/**
* @brief Namespace for Osmium internal use
*/
namespace detail {
/**
* Open file for writing. If the file exists, it is truncated, if
* not, it is created. If the file name is empty or "-", no file
* is opened and the stdout file descriptor (1) is returned.
*
* @param filename Name of file to be opened.
* @param allow_overwrite If the file exists, should it be overwritten?
* @returns File descriptor of open file.
* @throws system_error if the file can't be opened.
*/
inline int open_for_writing(const std::string& filename, const osmium::io::overwrite allow_overwrite = osmium::io::overwrite::no) {
#ifdef _MSC_VER
osmium::detail::disable_invalid_parameter_handler diph;
#endif
if (filename.empty() || filename == "-") {
#ifdef _WIN32
_setmode(1, _O_BINARY);
#endif
return 1; // stdout
}
int flags = O_WRONLY | O_CREAT; // NOLINT(hicpp-signed-bitwise)
if (allow_overwrite == osmium::io::overwrite::allow) {
flags |= O_TRUNC; // NOLINT(hicpp-signed-bitwise)
} else {
flags |= O_EXCL; // NOLINT(hicpp-signed-bitwise)
}
#ifdef _WIN32
flags |= O_BINARY; // NOLINT(hicpp-signed-bitwise)
#endif
const int fd = ::open(filename.c_str(), flags, 0666);
if (fd < 0) {
throw std::system_error{errno, std::system_category(), std::string("Open failed for '") + filename + "'"};
}
return fd;
}
/**
* Open file for reading. If the file name is empty or "-", no file
* is opened and the stdin file descriptor (0) is returned.
*
* @param filename Name of file to be opened.
* @returns File descriptor of open file.
* @throws system_error if the file can't be opened.
*/
inline int open_for_reading(const std::string& filename) {
#ifdef _MSC_VER
osmium::detail::disable_invalid_parameter_handler diph;
#endif
if (filename.empty() || filename == "-") {
return 0; // stdin
}
#ifdef _WIN32
const int flags = O_RDONLY | O_BINARY;
#else
const int flags = O_RDONLY;
#endif
const int fd = ::open(filename.c_str(), flags);
if (fd < 0) {
throw std::system_error{errno, std::system_category(), std::string("Open failed for '") + filename + "'"};
}
return fd;
}
/**
* Writes the given number of bytes from the output_buffer to the file descriptor.
* This is just a wrapper around write(2), because write(2) can write less than
* the given number of bytes.
*
* @param fd File descriptor.
* @param output_buffer Buffer with data to be written. Must be at least size bytes long.
* @param size Number of bytes to write.
* @throws std::system_error On error.
*/
inline void reliable_write(const int fd, const unsigned char* output_buffer, const size_t size) {
#ifdef _MSC_VER
osmium::detail::disable_invalid_parameter_handler diph;
#endif
enum : std::size_t {
// Max 100 MByte per write
max_write = 100UL * 1024UL * 1024UL
};
size_t offset = 0;
do {
auto write_count = size - offset;
if (write_count > max_write) {
write_count = max_write;
}
int64_t length = 0;
do {
length = ::write(fd, output_buffer + offset, static_cast<unsigned int>(write_count));
if (length < 0 && errno != EINTR) {
throw std::system_error{errno, std::system_category(), "Write failed"};
}
} while (length < 0);
offset += static_cast<size_t>(length);
} while (offset < size);
}
/**
* Writes the given number of bytes from the output_buffer to the file descriptor.
* This is just a wrapper around write(2), because write(2) can write less than
* the given number of bytes.
*
* @param fd File descriptor.
* @param output_buffer Buffer with data to be written. Must be at least size bytes long.
* @param size Number of bytes to write.
* @throws std::system_error On error.
*/
inline void reliable_write(const int fd, const char* output_buffer, const size_t size) {
reliable_write(fd, reinterpret_cast<const unsigned char*>(output_buffer), size);
}
/**
* Reads a maximum of size bytes from the file descriptor into the
* input_buffer. This is just a wrapper around read(2) catching
* errors.
*
* @param fd File descriptor.
* @param input_buffer Buffer for data to be read. Must be at least size bytes long.
* @param size Maximum number of bytes to read.
* @returns the number of bytes read
* @throws std::system_error On error.
*/
inline int64_t reliable_read(const int fd, char* input_buffer, const unsigned int size) {
#ifdef _MSC_VER
osmium::detail::disable_invalid_parameter_handler diph;
#endif
int64_t nread = 0;
do {
#ifdef _WIN32
nread = _read(fd, input_buffer, size);
#else
nread = ::read(fd, input_buffer, size);
#endif
if (nread < 0 && errno != EINTR) {
throw std::system_error{errno, std::system_category(), "Read failed"};
}
} while (nread < 0);
return nread;
}
inline void reliable_fsync(const int fd) {
#ifdef _MSC_VER
osmium::detail::disable_invalid_parameter_handler diph;
#endif
#ifdef _WIN32
if (_commit(fd) != 0) {
#else
if (::fsync(fd) != 0) {
#endif
throw std::system_error{errno, std::system_category(), "Fsync failed"};
}
}
inline void reliable_close(const int fd) {
if (fd < 0) {
return;
}
#ifdef _MSC_VER
osmium::detail::disable_invalid_parameter_handler diph;
#endif
#ifdef _WIN32
if (_close(fd) != 0) {
#else
if (::close(fd) != 0) {
#endif
throw std::system_error{errno, std::system_category(), "Close failed"};
}
}
inline int reliable_dup(const int fd) {
#ifdef _MSC_VER
osmium::detail::disable_invalid_parameter_handler diph;
#endif
#ifdef _WIN32
const int fd2 = _dup(fd);
#else
const int fd2 = ::dup(fd);
#endif
if (fd2 < 0) {
throw std::system_error{errno, std::system_category(), "Dup failed"};
}
return fd2;
}
/**
* Tell the kernel to remove all pages from this file from the
* buffer cache. Used when reading a large file that will not be
* needed again soon. Keeps the buffer cache clear for other
* things.
*/
#if defined(__linux__) || defined(__FreeBSD__)
inline void remove_buffered_pages(int fd) noexcept {
if (fd > 0) {
::posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
}
#else
inline void remove_buffered_pages(int /*fd*/) noexcept {
#endif
}
/**
* Tell the kernel to remove all pages from this file up to the
* specified size from the buffer cache. Used when reading a large
* file that will not be needed again soon. Keeps the buffer cache
* clear for other things.
*/
#if defined(__linux__) || defined(__FreeBSD__)
inline void remove_buffered_pages(int fd, std::size_t size) noexcept {
constexpr const std::size_t block_size = 4096;
// Make sure to keep the last 10 blocks around, so were are
// definitely not removing something which might be needed
// again soon.
if (fd > 0 && size > 10 * block_size) {
size -= 10 * block_size;
::posix_fadvise(fd, 0, (size - 1) & ~(block_size - 1), POSIX_FADV_DONTNEED);
}
#else
inline void remove_buffered_pages(int /*fd*/, std::size_t /*size*/) noexcept {
#endif
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_READ_WRITE_HPP
@@ -0,0 +1,306 @@
#ifndef OSMIUM_IO_DETAIL_STRING_TABLE_HPP
#define OSMIUM_IO_DETAIL_STRING_TABLE_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/detail/pbf.hpp>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <list>
#include <string>
#include <unordered_map>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
/**
* class StringStore
*
* Storage of lots of strings (const char *). Memory is allocated in chunks.
* If a string is added and there is no space in the current chunk, a new
* chunk will be allocated. Strings added to the store must not be larger
* than the chunk size.
*
* All memory is released when the destructor is called. There is no other way
* to release all or part of the memory.
*
*/
class StringStore {
size_t m_chunk_size;
std::list<std::string> m_chunks;
void add_chunk() {
m_chunks.emplace_back();
m_chunks.back().reserve(m_chunk_size);
}
public:
explicit StringStore(size_t chunk_size) :
m_chunk_size(chunk_size) {
add_chunk();
}
void clear() noexcept {
assert(!m_chunks.empty());
m_chunks.erase(std::next(m_chunks.begin()), m_chunks.end());
m_chunks.front().clear();
}
/**
* Add a null terminated string to the store. This will
* automatically get more memory if we are out.
* Returns a pointer to the copy of the string we have
* allocated.
*/
const char* add(const char* string) {
const size_t len = std::strlen(string) + 1;
assert(len <= m_chunk_size);
size_t chunk_len = m_chunks.back().size();
if (chunk_len + len > m_chunks.back().capacity()) {
add_chunk();
chunk_len = 0;
}
m_chunks.back().append(string);
m_chunks.back().append(1, '\0');
return m_chunks.back().c_str() + chunk_len;
}
class const_iterator {
using it_type = std::list<std::string>::const_iterator;
it_type m_it;
const it_type m_last;
const char* m_pos;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = const char*;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
const_iterator(it_type it, it_type last) :
m_it(it),
m_last(last),
m_pos(it == last ? nullptr : m_it->c_str()) {
}
const_iterator& operator++() {
assert(m_it != m_last);
const auto* const last_pos = m_it->c_str() + m_it->size();
while (m_pos != last_pos && *m_pos) {
++m_pos;
}
if (m_pos != last_pos) {
++m_pos;
}
if (m_pos == last_pos) {
++m_it;
if (m_it != m_last) {
m_pos = m_it->c_str();
} else {
m_pos = nullptr;
}
}
return *this;
}
const_iterator operator++(int) {
const_iterator tmp{*this};
operator++();
return tmp;
}
bool operator==(const const_iterator& rhs) const {
return m_it == rhs.m_it && m_pos == rhs.m_pos;
}
bool operator!=(const const_iterator& rhs) const {
return !(*this == rhs);
}
const char* operator*() const {
assert(m_it != m_last);
assert(m_pos != nullptr);
return m_pos;
}
}; // class const_iterator
const_iterator begin() const {
if (m_chunks.front().empty()) {
return end();
}
return {m_chunks.begin(), m_chunks.end()};
}
const_iterator end() const {
return {m_chunks.end(), m_chunks.end()};
}
// These functions get you some idea how much memory was
// used.
size_t get_chunk_size() const noexcept {
return m_chunk_size;
}
size_t get_chunk_count() const noexcept {
return m_chunks.size();
}
size_t get_used_bytes_in_last_chunk() const noexcept {
return m_chunks.back().size();
}
}; // class StringStore
struct str_equal {
bool operator()(const char* lhs, const char* rhs) const noexcept {
return lhs == rhs || std::strcmp(lhs, rhs) == 0;
}
}; // struct str_equal
struct djb2_hash {
std::size_t operator()(const char* str) const noexcept {
std::size_t hash = 5381;
int c = 0;
while ((c = static_cast<signed char>(*str++))) { // NOLINT(bugprone-signed-char-misuse,cert-str34-c)
hash = ((hash << 5U) + hash) + c; /* hash * 33 + c */
}
return hash;
}
}; // struct djb2_hash
class StringTable {
// This is the maximum number of entries in a string table.
// This should never be reached in practice but we better
// make sure it doesn't. If we had max_uncompressed_blob_size
// many entries, we are sure they would never fit into a PBF
// Blob.
enum {
max_entries = static_cast<int32_t>(max_uncompressed_blob_size)
};
StringStore m_strings;
std::unordered_map<const char*, int32_t, djb2_hash, str_equal> m_index;
int32_t m_size = 0;
public:
// There is one string table per PBF primitive block. Most of
// them are really small, because most blocks are full of nodes
// with no tags. But string tables can get really large for
// ways with many tags or for large relations.
// The chosen size is enough so that 99% of all string tables
// in typical OSM files will only need a single memory
// allocation.
enum {
default_stringtable_chunk_size = 100U * 1024U
};
// Minimum bucket count for hash.
enum {
min_bucket_count = 1
};
explicit StringTable(size_t size = default_stringtable_chunk_size, size_t bucket_count = min_bucket_count) :
m_strings(size),
m_index(bucket_count) {
m_strings.add("");
}
int32_t size() const noexcept {
return m_size + 1;
}
std::size_t get_bucket_count() const noexcept {
return m_index.bucket_count();
}
int32_t add(const char* s) {
const auto f = m_index.find(s);
if (f != m_index.end()) {
return f->second;
}
const char* cs = m_strings.add(s);
m_index[cs] = ++m_size;
if (m_size > max_entries) {
throw osmium::pbf_error{"string table has too many entries"};
}
return m_size;
}
StringStore::const_iterator begin() const {
return m_strings.begin();
}
StringStore::const_iterator end() const {
return m_strings.end();
}
}; // class StringTable
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_STRING_TABLE_HPP
@@ -0,0 +1,312 @@
#ifndef OSMIUM_IO_DETAIL_STRING_UTIL_HPP
#define OSMIUM_IO_DETAIL_STRING_UTIL_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <stdexcept>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
#ifndef _MSC_VER
# define SNPRINTF std::snprintf
#else
# define SNPRINTF _snprintf
#endif
template <typename... TArgs>
inline int string_snprintf(std::string& out,
const std::size_t old_size,
const std::size_t max_size,
const char* format,
TArgs... args) {
out.resize(old_size + max_size);
return SNPRINTF(max_size ? &out[old_size] : nullptr,
max_size, format, args...);
}
#undef SNPRINTF
/**
* This is a helper function for writing printf-like formatted
* data into a std::string.
*
* @param out The data will be appended to this string.
* @param format A string with formatting instructions a la printf.
* @param args Any further arguments like in printf.
* @throws std::bad_alloc If the string needed to grow and there
* wasn't enough memory.
*/
template <typename... TArgs>
inline void append_printf_formatted_string(std::string& out,
const char* format,
TArgs... args) {
// First try to write string with the max_size, if that doesn't
// work snprintf will tell us how much space it needs. We
// reserve that much space and try again. So this will always
// work, even if the output is larger than the given max_size.
//
// Unfortunately this trick doesn't work on Windows, because
// the _snprintf() function there only returns the length it
// needs if max_size==0 and the buffer pointer is the null
// pointer. So we have to take this into account.
#ifndef _MSC_VER
static const std::size_t max_size = 100;
#else
static const std::size_t max_size = 0;
#endif
const std::size_t old_size = out.size();
const int len = string_snprintf(out,
old_size,
max_size,
format,
args...);
assert(len > 0);
if (static_cast<std::size_t>(len) >= max_size) {
#ifndef NDEBUG
const int len2 =
#endif
string_snprintf(out,
old_size,
static_cast<std::size_t>(len) + 1,
format,
args...);
assert(len2 == len);
}
out.resize(old_size + static_cast<std::size_t>(len));
}
inline uint8_t utf8_sequence_length(uint32_t first) noexcept {
if (first < 0x80U) {
return 1U;
}
if ((first >> 5U) == 0x6U) {
return 2U;
}
if ((first >> 4U) == 0xeU) {
return 3U;
}
if ((first >> 3U) == 0x1eU) {
return 4U;
}
return 0;
}
inline uint32_t next_utf8_codepoint(char const** begin, const char* end) {
const auto* it = reinterpret_cast<const uint8_t*>(*begin);
uint32_t cp = 0xffU & *it;
const auto length = utf8_sequence_length(cp);
if (length == 0) {
throw std::runtime_error{"invalid Unicode codepoint"};
}
if (std::distance(it, reinterpret_cast<const uint8_t*>(end)) < length) {
throw std::out_of_range{"incomplete Unicode codepoint"};
}
switch (length) {
case 1:
break;
case 2:
++it;
cp = ((cp << 6U) & 0x7ffU) + ((*it) & 0x3fU);
break;
case 3:
++it;
cp = ((cp << 12U) & 0xffffU) + (((0xffU & *it) << 6U) & 0xfffU);
++it;
cp += (*it) & 0x3fU;
break;
case 4:
++it;
cp = ((cp << 18U) & 0x1fffffU) + (((0xffU & *it) << 12U) & 0x3ffffU);
++it;
cp += ((0xffU & *it) << 6U) & 0xfffU;
++it;
cp += (*it) & 0x3fU;
break;
default:
break;
}
++it;
*begin = reinterpret_cast<const char*>(it);
return cp;
}
// Write out the value with exactly two hex digits.
inline void append_2_hex_digits(std::string& out, uint32_t value, const char* const hex_digits) {
out += hex_digits[(value >> 4U) & 0xfU];
out += hex_digits[ value & 0xfU];
}
// Write out the value with four or more hex digits.
inline void append_min_4_hex_digits(std::string& out, uint32_t value, const char* const hex_digits) {
auto
v = value & 0xf0000000U; if (v) { out += hex_digits[v >> 28U]; }
v = value & 0x0f000000U; if (v) { out += hex_digits[v >> 24U]; }
v = value & 0x00f00000U; if (v) { out += hex_digits[v >> 20U]; }
v = value & 0x000f0000U; if (v) { out += hex_digits[v >> 16U]; }
out += hex_digits[(value >> 12U) & 0xfU];
out += hex_digits[(value >> 8U) & 0xfU];
out += hex_digits[(value >> 4U) & 0xfU];
out += hex_digits[ value & 0xfU];
}
inline void append_utf8_encoded_string(std::string& out, const char* data) {
static const char* lookup_hex = "0123456789abcdef";
assert(data);
const char* end_ptr = data + std::strlen(data);
while (data != end_ptr) {
const char* prev = data;
const uint32_t c = next_utf8_codepoint(&data, end_ptr);
// This is a list of Unicode code points that we let
// through instead of escaping them. It is incomplete
// and can be extended later.
// Generally we don't want to let through any character
// that has special meaning in the OPL format such as
// space, comma, @, etc. and any non-printing characters.
if ((0x0021 <= c && c <= 0x0024) ||
(0x0026 <= c && c <= 0x002b) ||
(0x002d <= c && c <= 0x003c) ||
(0x003e <= c && c <= 0x003f) ||
(0x0041 <= c && c <= 0x007e) ||
(0x00a1 <= c && c <= 0x00ac) ||
(0x00ae <= c && c <= 0x05ff)) {
out.append(prev, data);
} else {
out += '%';
if (c <= 0xff) {
append_2_hex_digits(out, c, lookup_hex);
} else {
append_min_4_hex_digits(out, c, lookup_hex);
}
out += '%';
}
}
}
inline void append_xml_encoded_string(std::string& out, const char* data) {
assert(data);
for (; *data != '\0'; ++data) {
switch (*data) {
case '&': out += "&amp;"; break;
case '\"': out += "&quot;"; break;
case '\'': out += "&apos;"; break;
case '<': out += "&lt;"; break;
case '>': out += "&gt;"; break;
case '\n': out += "&#xA;"; break;
case '\r': out += "&#xD;"; break;
case '\t': out += "&#x9;"; break;
default: out += *data; break;
}
}
}
inline void append_debug_encoded_string(std::string& out, const char* data, const char* prefix, const char* suffix) {
static const char* lookup_hex = "0123456789ABCDEF";
const char* end_ptr = data + std::strlen(data);
while (data != end_ptr) {
const char* prev = data;
const uint32_t c = next_utf8_codepoint(&data, end_ptr);
// This is a list of Unicode code points that we let
// through instead of escaping them. It is incomplete
// and can be extended later.
// Generally we don't want to let through any
// non-printing characters.
if ((0x0020 <= c && c <= 0x0021) ||
(0x0023 <= c && c <= 0x003b) ||
(0x003d == c) ||
(0x003f <= c && c <= 0x007e) ||
(0x00a1 <= c && c <= 0x00ac) ||
(0x00ae <= c && c <= 0x05ff)) {
out.append(prev, data);
} else {
out.append(prefix);
out.append("<U+");
append_min_4_hex_digits(out, c, lookup_hex);
out.append(">");
out.append(suffix);
}
}
}
template <typename TOutputIterator>
TOutputIterator append_codepoint_as_utf8(uint32_t cp, TOutputIterator out) {
if (cp < 0x80UL) {
*(out++) = static_cast<char>(cp);
} else if (cp < 0x800UL) {
*(out++) = static_cast<char>( (cp >> 6U) | 0xc0U);
*(out++) = static_cast<char>(( cp & 0x3fU) | 0x80U);
} else if (cp < 0x10000UL) {
*(out++) = static_cast<char>( (cp >> 12U) | 0xe0U);
*(out++) = static_cast<char>(((cp >> 6U) & 0x3fU) | 0x80U);
*(out++) = static_cast<char>(( cp & 0x3fU) | 0x80U);
} else {
*(out++) = static_cast<char>( (cp >> 18U) | 0xf0U);
*(out++) = static_cast<char>(((cp >> 12U) & 0x3fU) | 0x80U);
*(out++) = static_cast<char>(((cp >> 6U) & 0x3fU) | 0x80U);
*(out++) = static_cast<char>(( cp & 0x3fU) | 0x80U);
}
return out;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_STRING_UTIL_HPP
@@ -0,0 +1,112 @@
#ifndef OSMIUM_IO_DETAIL_WRITE_THREAD_HPP
#define OSMIUM_IO_DETAIL_WRITE_THREAD_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/compression.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/thread/util.hpp>
#include <exception>
#include <future>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
/**
* This codes runs in its own thread, getting data from the given
* queue, (optionally) compressing it, and writing it to the output
* file.
*/
class WriteThread {
queue_wrapper<std::string> m_queue;
std::unique_ptr<osmium::io::Compressor> m_compressor;
std::promise<std::size_t> m_promise;
std::atomic_bool* m_notification;
public:
WriteThread(future_string_queue_type& input_queue,
std::unique_ptr<osmium::io::Compressor>&& compressor,
std::promise<std::size_t>&& promise,
std::atomic_bool* notification) :
m_queue(input_queue),
m_compressor(std::move(compressor)),
m_promise(std::move(promise)),
m_notification(notification) {
}
WriteThread(const WriteThread&) = delete;
WriteThread& operator=(const WriteThread&) = delete;
WriteThread(WriteThread&&) = delete;
WriteThread& operator=(WriteThread&&) = delete;
~WriteThread() noexcept = default;
void operator()() {
osmium::thread::set_thread_name("_osmium_write");
try {
while (true) {
const std::string data{m_queue.pop()};
if (at_end_of_data(data)) {
break;
}
m_compressor->write(data);
}
m_compressor->close();
m_promise.set_value(m_compressor->file_size());
} catch (...) {
m_notification->store(true);
m_promise.set_exception(std::current_exception());
m_queue.shutdown();
}
}
}; // class WriteThread
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_WRITE_THREAD_HPP
@@ -0,0 +1,802 @@
#ifndef OSMIUM_IO_DETAIL_XML_INPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_XML_INPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/builder/builder.hpp>
#include <osmium/builder/osm_object_builder.hpp>
#include <osmium/io/detail/input_format.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/error.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/changeset.hpp>
#include <osmium/osm/entity_bits.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/node_ref.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>
#include <osmium/osm/types_from_string.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/thread/util.hpp>
#include <expat.h>
#include <cassert>
#include <cstring>
#include <exception>
#include <future>
#include <limits>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
/**
* Exception thrown when the XML parser failed. The exception contains
* (if available) information about the place where the error happened
* and the type of error.
*/
struct xml_error : public io_error {
uint64_t line = 0;
uint64_t column = 0;
XML_Error error_code;
std::string error_string;
explicit xml_error(const XML_Parser& parser) :
io_error(std::string{"XML parsing error at line "}
+ std::to_string(XML_GetCurrentLineNumber(parser))
+ ", column "
+ std::to_string(XML_GetCurrentColumnNumber(parser))
+ ": "
+ XML_ErrorString(XML_GetErrorCode(parser))),
line(XML_GetCurrentLineNumber(parser)),
column(XML_GetCurrentColumnNumber(parser)),
error_code(XML_GetErrorCode(parser)),
error_string(XML_ErrorString(error_code)) {
}
explicit xml_error(const std::string& message) :
io_error(message),
error_code(),
error_string(message) {
}
}; // struct xml_error
/**
* Exception thrown when an OSM XML files contains no version attribute
* on the 'osm' element or if the version is unknown.
*/
struct format_version_error : public io_error {
std::string version;
explicit format_version_error() :
io_error("Can not read file without version (missing version attribute on osm element).") {
}
explicit format_version_error(const char* v) :
io_error(std::string{"Can not read file with version "} + v),
version(v) {
}
}; // struct format_version_error
namespace io {
namespace detail {
class XMLParser final : public ParserWithBuffer {
enum class context {
osm,
osmChange,
bounds,
create_section,
modify_section,
delete_section,
node,
way,
relation,
tag,
nd,
member,
changeset,
discussion,
comment,
text,
obj_bbox,
other
}; // enum class context
std::vector<context> m_context_stack;
osmium::io::Header m_header{};
std::unique_ptr<osmium::builder::NodeBuilder> m_node_builder{};
std::unique_ptr<osmium::builder::WayBuilder> m_way_builder{};
std::unique_ptr<osmium::builder::RelationBuilder> m_relation_builder{};
std::unique_ptr<osmium::builder::ChangesetBuilder> m_changeset_builder{};
std::unique_ptr<osmium::builder::ChangesetDiscussionBuilder> m_changeset_discussion_builder{};
std::unique_ptr<osmium::builder::TagListBuilder> m_tl_builder{};
std::unique_ptr<osmium::builder::WayNodeListBuilder> m_wnl_builder{};
std::unique_ptr<osmium::builder::RelationMemberListBuilder> m_rml_builder{};
std::string m_comment_text;
/**
* A C++ wrapper for the Expat parser that makes sure no memory
* is leaked.
*/
class ExpatXMLParser {
XML_Parser m_parser;
std::exception_ptr m_exception_ptr{}; // NOLINT(bugprone-throw-keyword-missing) see https://bugs.llvm.org/show_bug.cgi?id=52400
template <typename TFunc>
void member_wrap(XMLParser& xml_parser, TFunc&& func) noexcept {
if (m_exception_ptr) {
return;
}
try {
func(xml_parser);
} catch (...) {
m_exception_ptr = std::current_exception();
XML_StopParser(m_parser, 0);
}
}
template <typename TFunc>
static void wrap(void* data, TFunc&& func) noexcept {
assert(data);
auto& xml_parser = *static_cast<XMLParser*>(data);
xml_parser.m_expat_xml_parser->member_wrap(xml_parser, std::forward<TFunc>(func));
}
static void XMLCALL start_element_wrapper(void* data, const XML_Char* element, const XML_Char** attrs) noexcept {
wrap(data, [&](XMLParser& xml_parser) {
xml_parser.start_element(element, attrs);
});
}
static void XMLCALL end_element_wrapper(void* data, const XML_Char* element) noexcept {
wrap(data, [&](XMLParser& xml_parser) {
xml_parser.end_element(element);
});
}
static void XMLCALL character_data_wrapper(void* data, const XML_Char* text, int len) noexcept {
wrap(data, [&](XMLParser& xml_parser) {
xml_parser.characters(text, len);
});
}
// This handler is called when there are any XML entities
// declared in the OSM file. Entities are normally not used,
// but they can be misused. See
// https://en.wikipedia.org/wiki/Billion_laughs
// The handler will just throw an error.
static void entity_declaration_handler(void* data,
const XML_Char* /*entityName*/,
int /*is_parameter_entity*/,
const XML_Char* /*value*/,
int /*value_length*/,
const XML_Char* /*base*/,
const XML_Char* /*systemId*/,
const XML_Char* /*publicId*/,
const XML_Char* /*notationName*/) noexcept {
wrap(data, [&](XMLParser& /*xml_parser*/) {
throw osmium::xml_error{"XML entities are not supported"};
});
}
public:
explicit ExpatXMLParser(void* callback_object) :
m_parser(XML_ParserCreate(nullptr)) {
if (!m_parser) {
throw osmium::io_error{"Internal error: Can not create parser"};
}
XML_SetUserData(m_parser, callback_object);
XML_SetElementHandler(m_parser, start_element_wrapper, end_element_wrapper);
XML_SetCharacterDataHandler(m_parser, character_data_wrapper);
XML_SetEntityDeclHandler(m_parser, entity_declaration_handler);
}
ExpatXMLParser(const ExpatXMLParser&) = delete;
ExpatXMLParser& operator=(const ExpatXMLParser&) = delete;
ExpatXMLParser(ExpatXMLParser&&) = delete;
ExpatXMLParser& operator=(ExpatXMLParser&&) = delete;
~ExpatXMLParser() noexcept {
XML_ParserFree(m_parser);
}
void operator()(const std::string& data, bool last) {
assert(data.size() < std::numeric_limits<int>::max());
if (XML_Parse(m_parser, data.data(), static_cast<int>(data.size()), last) == XML_STATUS_ERROR) {
if (m_exception_ptr) {
std::rethrow_exception(m_exception_ptr);
}
throw osmium::xml_error{m_parser};
}
}
}; // class ExpatXMLParser
ExpatXMLParser* m_expat_xml_parser{nullptr};
template <typename T>
static void check_attributes(const XML_Char** attrs, T&& check) {
while (*attrs) {
check(attrs[0], attrs[1]);
attrs += 2;
}
}
const char* init_object(osmium::OSMObject& object, const XML_Char** attrs) {
assert(m_context_stack.size() > 1);
if (m_context_stack[m_context_stack.size() - 2] == context::delete_section) {
object.set_visible(false);
}
osmium::Location location;
const char* user = "";
check_attributes(attrs, [&location, &user, &object](const XML_Char* name, const XML_Char* value) {
if (!std::strcmp(name, "lon")) {
location.set_lon(value);
} else if (!std::strcmp(name, "lat")) {
location.set_lat(value);
} else if (!std::strcmp(name, "user")) {
user = value;
} else {
object.set_attribute(name, value);
}
});
if (location && object.type() == osmium::item_type::node) {
static_cast<osmium::Node&>(object).set_location(location);
}
return user;
}
static void init_changeset(osmium::builder::ChangesetBuilder& builder, const XML_Char** attrs) {
osmium::Box box;
check_attributes(attrs, [&builder, &box](const XML_Char* name, const XML_Char* value) {
if (!std::strcmp(name, "min_lon")) {
box.bottom_left().set_lon(value);
} else if (!std::strcmp(name, "min_lat")) {
box.bottom_left().set_lat(value);
} else if (!std::strcmp(name, "max_lon")) {
box.top_right().set_lon(value);
} else if (!std::strcmp(name, "max_lat")) {
box.top_right().set_lat(value);
} else if (!std::strcmp(name, "user")) {
builder.set_user(value);
} else {
builder.set_attribute(name, value);
}
});
builder.set_bounds(box);
}
void get_tag(osmium::builder::Builder& builder, const XML_Char** attrs) {
const char* k = "";
const char* v = "";
check_attributes(attrs, [&k, &v](const XML_Char* name, const XML_Char* value) {
if (name[0] == 'k' && name[1] == '\0') {
k = value;
} else if (name[0] == 'v' && name[1] == '\0') {
v = value;
}
});
if (!m_tl_builder) {
m_tl_builder.reset(new osmium::builder::TagListBuilder{builder});
}
m_tl_builder->add_tag(k, v);
}
void mark_header_as_done() {
set_header_value(m_header);
}
void top_level_element(const XML_Char* element, const XML_Char** attrs) {
if (!std::strcmp(element, "osm")) {
m_context_stack.push_back(context::osm);
} else if (!std::strcmp(element, "osmChange")) {
m_context_stack.push_back(context::osmChange);
m_header.set_has_multiple_object_versions(true);
} else {
throw osmium::xml_error{std::string{"Unknown top-level element: "} + element};
}
check_attributes(attrs, [this](const XML_Char* name, const XML_Char* value) {
if (!std::strcmp(name, "version")) {
m_header.set("version", value);
if (std::strcmp(value, "0.6") != 0) {
throw osmium::format_version_error{value};
}
} else if (!std::strcmp(name, "generator")) {
m_header.set("generator", value);
} else if (!std::strcmp(name, "upload")) {
m_header.set("xml_josm_upload", value);
}
// ignore other attributes
});
if (m_header.get("version").empty()) {
throw osmium::format_version_error{};
}
}
void data_level_element(const XML_Char* element, const XML_Char** attrs, bool in_change_section) {
assert(!m_node_builder);
assert(!m_way_builder);
assert(!m_relation_builder);
assert(!m_changeset_builder);
assert(!m_changeset_discussion_builder);
assert(!m_tl_builder);
assert(!m_wnl_builder);
assert(!m_rml_builder);
if (!std::strcmp(element, "node")) {
m_context_stack.push_back(context::node);
mark_header_as_done();
if (read_types() & osmium::osm_entity_bits::node) {
maybe_new_buffer(osmium::item_type::node);
m_node_builder.reset(new osmium::builder::NodeBuilder{buffer()});
m_node_builder->set_user(init_object(m_node_builder->object(), attrs));
}
return;
}
if (!std::strcmp(element, "way")) {
m_context_stack.push_back(context::way);
mark_header_as_done();
if (read_types() & osmium::osm_entity_bits::way) {
maybe_new_buffer(osmium::item_type::way);
m_way_builder.reset(new osmium::builder::WayBuilder{buffer()});
m_way_builder->set_user(init_object(m_way_builder->object(), attrs));
}
return;
}
if (!std::strcmp(element, "relation")) {
m_context_stack.push_back(context::relation);
mark_header_as_done();
if (read_types() & osmium::osm_entity_bits::relation) {
maybe_new_buffer(osmium::item_type::relation);
m_relation_builder.reset(new osmium::builder::RelationBuilder{buffer()});
m_relation_builder->set_user(init_object(m_relation_builder->object(), attrs));
}
return;
}
if (in_change_section) {
throw xml_error{"create/modify/delete sections can only contain nodes, ways, and relations"};
}
if (!std::strcmp(element, "changeset")) {
m_context_stack.push_back(context::changeset);
mark_header_as_done();
if (read_types() & osmium::osm_entity_bits::changeset) {
maybe_new_buffer(osmium::item_type::changeset);
m_changeset_builder.reset(new osmium::builder::ChangesetBuilder{buffer()});
init_changeset(*m_changeset_builder, attrs);
}
} else if (!std::strcmp(element, "create")) {
if (m_context_stack.back() != context::osmChange) {
throw xml_error{"<create> only allowed in OSM change files"};
}
m_context_stack.push_back(context::create_section);
mark_header_as_done();
} else if (!std::strcmp(element, "modify")) {
if (m_context_stack.back() != context::osmChange) {
throw xml_error{"<modify> only allowed in OSM change files"};
}
m_context_stack.push_back(context::modify_section);
mark_header_as_done();
} else if (!std::strcmp(element, "delete")) {
if (m_context_stack.back() != context::osmChange) {
throw xml_error{"<delete> only allowed in OSM change files"};
}
m_context_stack.push_back(context::delete_section);
mark_header_as_done();
} else if (!std::strcmp(element, "bounds")) {
m_context_stack.push_back(context::bounds);
osmium::Location min;
osmium::Location max;
check_attributes(attrs, [&min, &max](const XML_Char* name, const XML_Char* value) {
if (!std::strcmp(name, "minlon")) {
min.set_lon(value);
} else if (!std::strcmp(name, "minlat")) {
min.set_lat(value);
} else if (!std::strcmp(name, "maxlon")) {
max.set_lon(value);
} else if (!std::strcmp(name, "maxlat")) {
max.set_lat(value);
}
});
osmium::Box box;
box.extend(min).extend(max);
m_header.add_box(box);
} else {
m_context_stack.push_back(context::other);
}
}
void start_element(const XML_Char* element, const XML_Char** attrs) {
if (m_context_stack.empty()) {
top_level_element(element, attrs);
return;
}
switch (m_context_stack.back()) {
case context::osm:
// fallthrough
case context::osmChange:
data_level_element(element, attrs, false);
break;
case context::create_section:
// fallthrough
case context::modify_section:
// fallthrough
case context::delete_section:
data_level_element(element, attrs, true);
break;
case context::node:
if (!std::strcmp(element, "tag")) {
m_context_stack.push_back(context::tag);
if (read_types() & osmium::osm_entity_bits::node) {
get_tag(*m_node_builder, attrs);
}
} else {
throw xml_error{std::string{"Unknown element in <node>: "} + element};
}
break;
case context::way:
if (!std::strcmp(element, "nd")) {
m_context_stack.push_back(context::nd);
if (read_types() & osmium::osm_entity_bits::way) {
m_tl_builder.reset();
if (!m_wnl_builder) {
m_wnl_builder.reset(new osmium::builder::WayNodeListBuilder{*m_way_builder});
}
NodeRef nr;
check_attributes(attrs, [&nr](const XML_Char* name, const XML_Char* value) {
if (!std::strcmp(name, "ref")) {
nr.set_ref(osmium::string_to_object_id(value));
} else if (!std::strcmp(name, "lon")) {
nr.location().set_lon(value);
} else if (!std::strcmp(name, "lat")) {
nr.location().set_lat(value);
}
});
m_wnl_builder->add_node_ref(nr);
}
} else if (!std::strcmp(element, "tag")) {
m_context_stack.push_back(context::tag);
if (read_types() & osmium::osm_entity_bits::way) {
m_wnl_builder.reset();
get_tag(*m_way_builder, attrs);
}
} else if (!std::strcmp(element, "bbox") || !std::strcmp(element, "bounds")) {
m_context_stack.push_back(context::obj_bbox);
} else {
throw xml_error{std::string{"Unknown element in <way>: "} + element};
}
break;
case context::relation:
if (!std::strcmp(element, "member")) {
m_context_stack.push_back(context::member);
if (read_types() & osmium::osm_entity_bits::relation) {
m_tl_builder.reset();
if (!m_rml_builder) {
m_rml_builder.reset(new osmium::builder::RelationMemberListBuilder{*m_relation_builder});
}
item_type type = item_type::undefined;
object_id_type ref = 0;
bool ref_is_set = false;
const char* role = "";
check_attributes(attrs, [&type, &ref, &ref_is_set, &role](const XML_Char* name, const XML_Char* value) {
if (!std::strcmp(name, "type")) {
type = char_to_item_type(value[0]);
} else if (!std::strcmp(name, "ref")) {
ref = osmium::string_to_object_id(value);
ref_is_set = true;
} else if (!std::strcmp(name, "role")) {
role = static_cast<const char*>(value);
}
});
if (type != item_type::node && type != item_type::way && type != item_type::relation) {
throw osmium::xml_error{"Unknown type on relation <member>"};
}
if (!ref_is_set) {
throw osmium::xml_error{"Missing ref on relation <member>"};
}
m_rml_builder->add_member(type, ref, role);
}
} else if (!std::strcmp(element, "tag")) {
m_context_stack.push_back(context::tag);
if (read_types() & osmium::osm_entity_bits::relation) {
m_rml_builder.reset();
get_tag(*m_relation_builder, attrs);
}
} else if (!std::strcmp(element, "bbox") || !std::strcmp(element, "bounds")) {
m_context_stack.push_back(context::obj_bbox);
} else {
throw xml_error{std::string{"Unknown element in <relation>: "} + element};
}
break;
case context::tag:
throw xml_error{"No element inside <tag> allowed"};
case context::nd:
throw xml_error{"No element inside <nd> allowed"};
case context::member:
throw xml_error{"No element inside <member> allowed"};
case context::changeset:
if (!std::strcmp(element, "discussion")) {
m_context_stack.push_back(context::discussion);
if (read_types() & osmium::osm_entity_bits::changeset) {
m_tl_builder.reset();
if (!m_changeset_discussion_builder) {
m_changeset_discussion_builder.reset(new osmium::builder::ChangesetDiscussionBuilder{*m_changeset_builder});
}
}
} else if (!std::strcmp(element, "tag")) {
m_context_stack.push_back(context::tag);
if (read_types() & osmium::osm_entity_bits::changeset) {
m_changeset_discussion_builder.reset();
get_tag(*m_changeset_builder, attrs);
}
} else {
throw xml_error{std::string{"Unknown element in <changeset>: "} + element};
}
break;
case context::discussion:
if (!std::strcmp(element, "comment")) {
m_context_stack.push_back(context::comment);
if (read_types() & osmium::osm_entity_bits::changeset) {
osmium::Timestamp date;
osmium::user_id_type uid = 0;
const char* user = "";
check_attributes(attrs, [&date, &uid, &user](const XML_Char* name, const XML_Char* value) {
if (!std::strcmp(name, "date")) {
date = osmium::Timestamp{value};
} else if (!std::strcmp(name, "uid")) {
uid = osmium::string_to_uid(value);
} else if (!std::strcmp(name, "user")) {
user = static_cast<const char*>(value);
}
});
m_changeset_discussion_builder->add_comment(date, uid, user);
}
} else {
throw xml_error{std::string{"Unknown element in <discussion>: "} + element};
}
break;
case context::comment:
if (!std::strcmp(element, "text")) {
m_context_stack.push_back(context::text);
} else {
throw xml_error{std::string{"Unknown element in <comment>: "} + element};
}
break;
case context::text:
throw osmium::xml_error{"No element in <text> allowed"};
case context::bounds:
throw osmium::xml_error{"No element in <bounds> allowed"};
case context::obj_bbox:
throw osmium::xml_error{"No element in <bbox>/<bounds> allowed"};
case context::other:
throw xml_error{"xml file nested too deep"};
}
}
#ifdef NDEBUG
void end_element(const XML_Char* /*element*/) {
#else
void end_element(const XML_Char* element) {
#endif
assert(!m_context_stack.empty());
switch (m_context_stack.back()) {
case context::osm:
assert(!std::strcmp(element, "osm"));
mark_header_as_done();
break;
case context::osmChange:
assert(!std::strcmp(element, "osmChange"));
mark_header_as_done();
break;
case context::create_section:
assert(!std::strcmp(element, "create"));
break;
case context::modify_section:
assert(!std::strcmp(element, "modify"));
break;
case context::delete_section:
assert(!std::strcmp(element, "delete"));
break;
case context::node:
assert(!std::strcmp(element, "node"));
if (read_types() & osmium::osm_entity_bits::node) {
m_tl_builder.reset();
m_node_builder.reset();
buffer().commit();
flush_nested_buffer();
}
break;
case context::way:
assert(!std::strcmp(element, "way"));
if (read_types() & osmium::osm_entity_bits::way) {
m_tl_builder.reset();
m_wnl_builder.reset();
m_way_builder.reset();
buffer().commit();
flush_nested_buffer();
}
break;
case context::relation:
assert(!std::strcmp(element, "relation"));
if (read_types() & osmium::osm_entity_bits::relation) {
m_tl_builder.reset();
m_rml_builder.reset();
m_relation_builder.reset();
buffer().commit();
flush_nested_buffer();
}
break;
case context::tag:
break;
case context::nd:
break;
case context::member:
break;
case context::changeset:
assert(!std::strcmp(element, "changeset"));
if (read_types() & osmium::osm_entity_bits::changeset) {
m_tl_builder.reset();
m_changeset_discussion_builder.reset();
m_changeset_builder.reset();
buffer().commit();
flush_nested_buffer();
}
break;
case context::discussion:
assert(!std::strcmp(element, "discussion"));
break;
case context::comment:
assert(!std::strcmp(element, "comment"));
break;
case context::text:
assert(!std::strcmp(element, "text"));
if (read_types() & osmium::osm_entity_bits::changeset) {
m_changeset_discussion_builder->add_comment_text(m_comment_text);
m_comment_text.clear();
}
break;
case context::bounds:
assert(!std::strcmp(element, "bounds"));
break;
case context::obj_bbox:
assert(!std::strcmp(element, "bbox") || !std::strcmp(element, "bounds"));
break;
case context::other:
break;
}
m_context_stack.pop_back();
}
void characters(const XML_Char* text, int len) {
if ((read_types() & osmium::osm_entity_bits::changeset) &&
!m_context_stack.empty() &&
m_context_stack.back() == context::text) {
m_comment_text.append(text, len);
}
}
public:
explicit XMLParser(parser_arguments& args) :
ParserWithBuffer(args) {
}
XMLParser(const XMLParser&) = delete;
XMLParser& operator=(const XMLParser&) = delete;
XMLParser(XMLParser&&) = delete;
XMLParser& operator=(XMLParser&&) = delete;
~XMLParser() noexcept override = default;
void run() override {
osmium::thread::set_thread_name("_osmium_xml_in");
ExpatXMLParser parser{this};
m_expat_xml_parser = &parser;
while (!input_done()) {
const std::string data{get_input()};
parser(data, input_done());
if (read_types() == osmium::osm_entity_bits::nothing && header_is_done()) {
break;
}
}
mark_header_as_done();
flush_final_buffer();
}
}; // class XMLParser
// we want the register_parser() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_xml_parser = ParserFactory::instance().register_parser(
file_format::xml,
[](parser_arguments& args) {
return std::unique_ptr<Parser>(new XMLParser{args});
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_xml_parser() noexcept {
return registered_xml_parser;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_XML_INPUT_FORMAT_HPP
@@ -0,0 +1,502 @@
#ifndef OSMIUM_IO_DETAIL_XML_OUTPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_XML_OUTPUT_FORMAT_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/handler.hpp>
#include <osmium/io/detail/output_format.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/detail/string_util.hpp>
#include <osmium/io/file.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/memory/item_iterator.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/changeset.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/metadata_options.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/node_ref.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/tag.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/thread/pool.hpp>
#include <osmium/visitor.hpp>
#include <iterator>
#include <memory>
#include <string>
#include <utility>
namespace osmium {
namespace io {
namespace detail {
struct XMLWriteError {};
struct xml_output_options {
/// Which metadata of objects should be added?
osmium::metadata_options add_metadata;
/// Should the visible flag be added to all OSM objects?
bool add_visible_flag = false;
/**
* Should <create>, <modify>, <delete> "operations" be added?
* (This is used for .osc files.)
*/
bool use_change_ops = false;
/// Should node locations be added to ways?
bool locations_on_ways = false;
}; // struct xml_output_options
namespace detail {
inline void append_lat_lon_attributes(std::string& out, const char* lat, const char* lon, const osmium::Location& location) {
out += ' ';
out += lat;
out += "=\"";
osmium::detail::append_location_coordinate_to_string(std::back_inserter(out), location.y());
out += "\" ";
out += lon;
out += "=\"";
osmium::detail::append_location_coordinate_to_string(std::back_inserter(out), location.x());
out += "\"";
}
} // namespace detail
class XMLOutputBlock : public OutputBlock {
// operation (create, modify, delete) for osc files
enum class operation {
op_none = 0,
op_create = 1,
op_modify = 2,
op_delete = 3
}; // enum class operation
operation m_last_op{operation::op_none};
xml_output_options m_options;
void write_spaces(int num) {
for (; num != 0; --num) {
*m_out += ' ';
}
}
int prefix_spaces() const noexcept {
return m_options.use_change_ops ? 4 : 2;
}
void write_prefix() {
write_spaces(prefix_spaces());
}
template <typename T>
void write_attribute(const char* name, T value) {
*m_out += ' ';
*m_out += name;
*m_out += "=\"";
output_int(value);
*m_out += '"';
}
void write_meta(const osmium::OSMObject& object) {
write_attribute("id", object.id());
if (m_options.add_metadata.version() && object.version()) {
write_attribute("version", object.version());
}
if (m_options.add_metadata.timestamp() && object.timestamp()) {
*m_out += " timestamp=\"";
*m_out += object.timestamp().to_iso_all();
*m_out += "\"";
}
if (m_options.add_metadata.uid() && object.uid()) {
write_attribute("uid", object.uid());
}
if (m_options.add_metadata.user() && object.user()[0] != '\0') {
*m_out += " user=\"";
append_xml_encoded_string(*m_out, object.user());
*m_out += "\"";
}
if (m_options.add_metadata.changeset() && object.changeset()) {
write_attribute("changeset", object.changeset());
}
if (m_options.add_visible_flag) {
if (object.visible()) {
*m_out += " visible=\"true\"";
} else {
*m_out += " visible=\"false\"";
}
}
}
void write_tags(const osmium::TagList& tags, int spaces) {
for (const auto& tag : tags) {
write_spaces(spaces);
*m_out += " <tag k=\"";
append_xml_encoded_string(*m_out, tag.key());
*m_out += "\" v=\"";
append_xml_encoded_string(*m_out, tag.value());
*m_out += "\"/>\n";
}
}
void write_discussion(const osmium::ChangesetDiscussion& comments) {
*m_out += " <discussion>\n";
for (const auto& comment : comments) {
*m_out += " <comment";
write_attribute("uid", comment.uid());
*m_out += " user=\"";
append_xml_encoded_string(*m_out, comment.user());
*m_out += "\" date=\"";
*m_out += comment.date().to_iso_all();
*m_out += "\">\n";
*m_out += " <text>";
append_xml_encoded_string(*m_out, comment.text());
*m_out += "</text>\n </comment>\n";
}
*m_out += " </discussion>\n";
}
void open_close_op_tag(const operation op = operation::op_none) {
if (op == m_last_op) {
return;
}
switch (m_last_op) {
case operation::op_none:
break;
case operation::op_create:
*m_out += " </create>\n";
break;
case operation::op_modify:
*m_out += " </modify>\n";
break;
case operation::op_delete:
*m_out += " </delete>\n";
break;
}
switch (op) {
case operation::op_none:
break;
case operation::op_create:
*m_out += " <create>\n";
break;
case operation::op_modify:
*m_out += " <modify>\n";
break;
case operation::op_delete:
*m_out += " <delete>\n";
break;
}
m_last_op = op;
}
public:
XMLOutputBlock(osmium::memory::Buffer&& buffer, const xml_output_options& options) :
OutputBlock(std::move(buffer)),
m_options(options) {
}
std::string operator()() {
osmium::apply(m_input_buffer->cbegin(), m_input_buffer->cend(), *this);
if (m_options.use_change_ops) {
open_close_op_tag();
}
std::string out;
using std::swap;
swap(out, *m_out);
return out;
}
void node(const osmium::Node& node) {
if (m_options.use_change_ops) {
open_close_op_tag(node.visible() ? (node.version() == 1 ? operation::op_create : operation::op_modify) : operation::op_delete);
}
write_prefix();
*m_out += "<node";
write_meta(node);
if (node.location()) {
detail::append_lat_lon_attributes(*m_out, "lat", "lon", node.location());
}
if (node.tags().empty()) {
*m_out += "/>\n";
return;
}
*m_out += ">\n";
write_tags(node.tags(), prefix_spaces());
write_prefix();
*m_out += "</node>\n";
}
void way(const osmium::Way& way) {
if (m_options.use_change_ops) {
open_close_op_tag(way.visible() ? (way.version() == 1 ? operation::op_create : operation::op_modify) : operation::op_delete);
}
write_prefix();
*m_out += "<way";
write_meta(way);
if (way.tags().empty() && way.nodes().empty()) {
*m_out += "/>\n";
return;
}
*m_out += ">\n";
if (m_options.locations_on_ways) {
for (const auto& node_ref : way.nodes()) {
write_prefix();
*m_out += " <nd";
write_attribute("ref", node_ref.ref());
if (node_ref.location()) {
detail::append_lat_lon_attributes(*m_out, "lat", "lon", node_ref.location());
}
*m_out += "/>\n";
}
} else {
for (const auto& node_ref : way.nodes()) {
write_prefix();
*m_out += " <nd";
write_attribute("ref", node_ref.ref());
*m_out += "/>\n";
}
}
write_tags(way.tags(), prefix_spaces());
write_prefix();
*m_out += "</way>\n";
}
void relation(const osmium::Relation& relation) {
if (m_options.use_change_ops) {
open_close_op_tag(relation.visible() ? (relation.version() == 1 ? operation::op_create : operation::op_modify) : operation::op_delete);
}
write_prefix();
*m_out += "<relation";
write_meta(relation);
if (relation.tags().empty() && relation.members().empty()) {
*m_out += "/>\n";
return;
}
*m_out += ">\n";
for (const auto& member : relation.members()) {
write_prefix();
*m_out += " <member type=\"";
*m_out += item_type_to_name(member.type());
*m_out += '"';
write_attribute("ref", member.ref());
*m_out += " role=\"";
append_xml_encoded_string(*m_out, member.role());
*m_out += "\"/>\n";
}
write_tags(relation.tags(), prefix_spaces());
write_prefix();
*m_out += "</relation>\n";
}
void changeset(const osmium::Changeset& changeset) {
*m_out += " <changeset";
write_attribute("id", changeset.id());
if (changeset.created_at()) {
*m_out += " created_at=\"";
*m_out += changeset.created_at().to_iso();
*m_out += "\"";
}
if (changeset.closed_at()) {
*m_out += " closed_at=\"";
*m_out += changeset.closed_at().to_iso();
*m_out += "\" open=\"false\"";
} else {
*m_out += " open=\"true\"";
}
if (!changeset.user_is_anonymous()) {
*m_out += " user=\"";
append_xml_encoded_string(*m_out, changeset.user());
*m_out += '"';
write_attribute("uid", changeset.uid());
}
if (!changeset.bounds().bottom_left().is_undefined() ||
!changeset.bounds().top_right().is_undefined()) {
detail::append_lat_lon_attributes(*m_out, "min_lat", "min_lon", changeset.bounds().bottom_left());
detail::append_lat_lon_attributes(*m_out, "max_lat", "max_lon", changeset.bounds().top_right());
}
write_attribute("num_changes", changeset.num_changes());
write_attribute("comments_count", changeset.num_comments());
// If there are no tags and no comments, we can close the
// tag right here and are done.
if (changeset.tags().empty() && changeset.discussion().empty()) {
*m_out += "/>\n";
return;
}
*m_out += ">\n";
write_tags(changeset.tags(), 0);
if (!changeset.discussion().empty()) {
write_discussion(changeset.discussion());
}
*m_out += " </changeset>\n";
}
}; // class XMLOutputBlock
class XMLOutputFormat : public osmium::io::detail::OutputFormat, public osmium::handler::Handler {
xml_output_options m_options;
public:
XMLOutputFormat(osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) :
OutputFormat(pool, output_queue) {
m_options.add_metadata = osmium::metadata_options{file.get("add_metadata")};
m_options.use_change_ops = file.is_true("xml_change_format");
m_options.add_visible_flag = (file.has_multiple_object_versions() || file.is_true("force_visible_flag")) && !m_options.use_change_ops;
m_options.locations_on_ways = file.is_true("locations_on_ways");
}
void write_header(const osmium::io::Header& header) final {
std::string out{"<?xml version='1.0' encoding='UTF-8'?>\n"};
if (m_options.use_change_ops) {
out += "<osmChange version=\"0.6\" generator=\"";
} else {
out += "<osm version=\"0.6\"";
const std::string xml_josm_upload{header.get("xml_josm_upload")};
if (xml_josm_upload == "true" || xml_josm_upload == "false") {
out += " upload=\"";
out += xml_josm_upload;
out += "\"";
}
out += " generator=\"";
}
append_xml_encoded_string(out, header.get("generator").c_str());
out += "\">\n";
for (const auto& box : header.boxes()) {
out += " <bounds";
detail::append_lat_lon_attributes(out, "minlat", "minlon", box.bottom_left());
detail::append_lat_lon_attributes(out, "maxlat", "maxlon", box.top_right());
out += "/>\n";
}
send_to_output_queue(std::move(out));
}
void write_buffer(osmium::memory::Buffer&& buffer) final {
m_output_queue.push(m_pool.submit(XMLOutputBlock{std::move(buffer), m_options}));
}
void write_end() final {
std::string out;
if (m_options.use_change_ops) {
out += "</osmChange>\n";
} else {
out += "</osm>\n";
}
send_to_output_queue(std::move(out));
}
}; // class XMLOutputFormat
// we want the register_output_format() function to run, setting
// the variable is only a side-effect, it will never be used
const bool registered_xml_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::xml,
[](osmium::thread::Pool& pool, const osmium::io::File& file, future_string_queue_type& output_queue) {
return new osmium::io::detail::XMLOutputFormat(pool, file, output_queue);
});
// dummy function to silence the unused variable warning from above
inline bool get_registered_xml_output() noexcept {
return registered_xml_output;
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_XML_OUTPUT_FORMAT_HPP
+133
View File
@@ -0,0 +1,133 @@
#ifndef OSMIUM_IO_DETAIL_ZLIB_HPP
#define OSMIUM_IO_DETAIL_ZLIB_HPP
/*
This file is part of Osmium (https://osmcode.org/libosmium).
Copyright 2013-2023 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 <osmium/io/error.hpp>
#include <protozero/version.hpp>
#if PROTOZERO_VERSION_CODE >= 10600
# include <protozero/data_view.hpp>
#else
# include <protozero/types.hpp>
#endif
#include <zlib.h>
#include <cassert>
#include <limits>
#include <string>
namespace osmium {
namespace io {
namespace detail {
constexpr inline int zlib_default_compression_level() noexcept {
return Z_DEFAULT_COMPRESSION;
}
inline void zlib_check_compression_level(int value) {
if (value < 0 || value > 9) {
throw std::invalid_argument{"The 'pbf_compression_level' for zlib compression must be between 0 and 9."};
}
}
/**
* Compress data using zlib.
*
* Note that this function can not compress data larger than
* what fits in an unsigned long, on Windows this is usually 32bit.
*
* @param input Data to compress.
* @param compression_level Compression level.
* @returns Compressed data.
*/
inline std::string zlib_compress(const std::string& input, int compression_level = Z_DEFAULT_COMPRESSION) {
assert(input.size() < std::numeric_limits<unsigned long>::max());
unsigned long output_size = ::compressBound(static_cast<unsigned long>(input.size())); // NOLINT(google-runtime-int)
std::string output(output_size, '\0');
const auto result = ::compress2(
reinterpret_cast<unsigned char*>(&*output.begin()),
&output_size,
reinterpret_cast<const unsigned char*>(input.data()),
static_cast<unsigned long>(input.size()), // NOLINT(google-runtime-int)
compression_level);
if (result != Z_OK) {
throw io_error{std::string{"failed to compress data: "} + zError(result)};
}
output.resize(output_size);
return output;
}
/**
* Uncompress data using zlib.
*
* Note that this function can not uncompress data larger than
* what fits in an unsigned long, on Windows this is usually 32bit.
*
* @param input Compressed input data.
* @param raw_size Size of uncompressed data.
* @param output Uncompressed result data.
* @returns Pointer and size to incompressed data.
*/
inline protozero::data_view zlib_uncompress_string(const char* input, unsigned long input_size, unsigned long raw_size, std::string& output) { // NOLINT(google-runtime-int)
output.resize(raw_size);
const auto result = ::uncompress(
reinterpret_cast<unsigned char*>(&*output.begin()),
&raw_size,
reinterpret_cast<const unsigned char*>(input),
input_size);
if (result != Z_OK) {
throw io_error{std::string{"failed to uncompress data: "} + zError(result)};
}
return protozero::data_view{output.data(), output.size()};
}
} // namespace detail
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_DETAIL_ZLIB_HPP