From 4d4a3d02ed04d3e6cd78aeed6c7224064f050c32 Mon Sep 17 00:00:00 2001 From: Lev Dragunov Date: Tue, 15 Dec 2015 13:23:27 +0300 Subject: [PATCH 001/701] A side_road tag support for the OSRM car profile. --- profiles/car.lua | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/profiles/car.lua b/profiles/car.lua index d246934d9..30d143c4f 100644 --- a/profiles/car.lua +++ b/profiles/car.lua @@ -131,6 +131,8 @@ maxspeed_table = { traffic_signal_penalty = 2 use_turn_restrictions = true +side_road_speed_multiplier = 0.8 + local turn_penalty = 10 -- Note: this biases right-side driving. Should be -- inverted for left-driving countries. @@ -310,6 +312,14 @@ function way_function (way, result) return end + -- reduce speed on special side roads + local sideway = way:get_value_by_key("side_road") + if "yes" == sideway or + "rotary" == sideway then + result.forward_speed = result.forward_speed * side_road_speed_multiplier + result.backward_speed = result.backward_speed * side_road_speed_multiplier + end + -- reduce speed on bad surfaces local surface = way:get_value_by_key("surface") local tracktype = way:get_value_by_key("tracktype") From e6789fab6c47e132c1ab8dc84d8a66aae0217b1a Mon Sep 17 00:00:00 2001 From: Bas Couwenberg Date: Fri, 25 Dec 2015 22:26:08 +0100 Subject: [PATCH 002/701] Fix 'occured' typo, replace with 'occurred'. --- extractor/extractor.cpp | 6 +++--- extractor/restriction_parser.cpp | 2 +- extractor/scripting_environment.cpp | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/extractor/extractor.cpp b/extractor/extractor.cpp index 80bd33d1c..f442efe31 100644 --- a/extractor/extractor.cpp +++ b/extractor/extractor.cpp @@ -342,14 +342,14 @@ void extractor::SetupScriptingEnvironment(lua_State *lua_state, if (0 != luaL_dofile(lua_state, config.profile_path.string().c_str())) { std::stringstream msg; - msg << lua_tostring(lua_state, -1) << " occured in scripting block"; + msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; throw osrm::exception(msg.str()); } if (0 != luaL_dostring(lua_state, "return traffic_signal_penalty\n")) { std::stringstream msg; - msg << lua_tostring(lua_state, -1) << " occured in scripting block"; + msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; throw osrm::exception(msg.str()); } speed_profile.traffic_signal_penalty = 10 * lua_tointeger(lua_state, -1); @@ -359,7 +359,7 @@ void extractor::SetupScriptingEnvironment(lua_State *lua_state, if (0 != luaL_dostring(lua_state, "return u_turn_penalty\n")) { std::stringstream msg; - msg << lua_tostring(lua_state, -1) << " occured in scripting block"; + msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; throw osrm::exception(msg.str()); } diff --git a/extractor/restriction_parser.cpp b/extractor/restriction_parser.cpp index afb194738..a3c2a5d25 100644 --- a/extractor/restriction_parser.cpp +++ b/extractor/restriction_parser.cpp @@ -51,7 +51,7 @@ namespace int lua_error_callback(lua_State *lua_state) { std::string error_msg = lua_tostring(lua_state, -1); - throw osrm::exception("ERROR occured in profile script:\n" + error_msg); + throw osrm::exception("ERROR occurred in profile script:\n" + error_msg); } } diff --git a/extractor/scripting_environment.cpp b/extractor/scripting_environment.cpp index 7ccc08ab5..9653ca049 100644 --- a/extractor/scripting_environment.cpp +++ b/extractor/scripting_environment.cpp @@ -59,7 +59,7 @@ int lua_error_callback(lua_State *L) // This is so I can use my own function as std::string error_msg = lua_tostring(L, -1); std::ostringstream error_stream; error_stream << error_msg; - throw osrm::exception("ERROR occured in profile script:\n" + error_stream.str()); + throw osrm::exception("ERROR occurred in profile script:\n" + error_stream.str()); } } @@ -154,7 +154,7 @@ void ScriptingEnvironment::init_lua_state(lua_State *lua_state) luabind::object error_msg(luabind::from_stack(lua_state, -1)); std::ostringstream error_stream; error_stream << error_msg; - throw osrm::exception("ERROR occured in profile script:\n" + error_stream.str()); + throw osrm::exception("ERROR occurred in profile script:\n" + error_stream.str()); } } From bfc6c9b89dcbdd42b87720a66d75f242f97edb54 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sat, 2 Jan 2016 13:55:06 +0100 Subject: [PATCH 003/701] Move files in src/ include/ --- algorithms/bfs_components.hpp | 174 ------------ data_structures/lru_cache.hpp | 97 ------- data_structures/static_kdtree.hpp | 260 ------------------ data_structures/upper_bound.hpp | 77 ------ .../contractor}/contractor.hpp | 0 .../contractor}/contractor_options.hpp | 0 .../contractor}/crc32_processor.hpp | 0 .../contractor}/processing_chain.hpp | 0 .../contractor}/query_edge.hpp | 0 .../datastore}/shared_memory_factory.hpp | 0 .../engine/datafacade}/datafacade_base.hpp | 0 .../datafacade}/internal_datafacade.hpp | 0 .../engine/datafacade}/shared_barriers.hpp | 0 .../engine/datafacade}/shared_datafacade.hpp | 0 .../engine/datafacade}/shared_datatype.hpp | 0 .../descriptors}/description_factory.hpp | 0 .../engine/descriptors}/descriptor_base.hpp | 0 .../engine/descriptors}/gpx_descriptor.hpp | 0 .../engine/descriptors}/json_descriptor.hpp | 0 .../engine}/douglas_peucker.hpp | 0 .../engine}/geospatial_query.hpp | 0 .../engine}/internal_route_result.hpp | 0 .../engine/map_matching}/bayes_classifier.hpp | 0 .../map_matching}/hidden_markov_model.hpp | 0 .../engine}/object_encoder.hpp | 0 {library => include/engine}/osrm_impl.hpp | 0 .../engine}/phantom_node.hpp | 0 .../engine/plugins}/distance_table.hpp | 0 .../engine/plugins}/hello_world.hpp | 0 {plugins => include/engine/plugins}/match.hpp | 0 .../engine/plugins}/nearest.hpp | 0 .../engine/plugins}/plugin_base.hpp | 0 .../engine/plugins}/timestamp.hpp | 0 {plugins => include/engine/plugins}/trip.hpp | 0 .../engine/plugins}/viaroute.hpp | 0 .../engine}/polyline_compressor.hpp | 0 .../engine}/polyline_formatter.hpp | 0 .../engine}/route_name_extraction.hpp | 0 .../routing_algorithms}/alternative_path.hpp | 0 .../direct_shortest_path.hpp | 0 .../routing_algorithms}/many_to_many.hpp | 0 .../routing_algorithms}/map_matching.hpp | 0 .../routing_algorithms}/routing_base.hpp | 0 .../routing_algorithms}/shortest_path.hpp | 0 .../engine}/search_engine.hpp | 0 .../engine}/search_engine_data.hpp | 0 .../engine}/segment_information.hpp | 0 .../engine/trip}/trip_brute_force.hpp | 0 .../engine/trip}/trip_farthest_insertion.hpp | 0 .../engine/trip}/trip_nearest_neighbour.hpp | 0 .../engine/trip}/trip_tabu_search.hpp | 0 .../extractor}/compressed_edge_container.hpp | 0 .../extractor}/edge_based_graph_factory.hpp | 0 .../extractor}/edge_based_node.hpp | 0 .../extractor}/external_memory_node.hpp | 0 .../extractor}/extraction_containers.hpp | 0 .../extraction_helper_functions.hpp | 0 .../extractor}/extraction_node.hpp | 0 .../extractor}/extraction_way.hpp | 0 .../extractor}/extractor.hpp | 0 .../extractor}/extractor_callbacks.hpp | 0 .../extractor}/extractor_options.hpp | 0 .../first_and_last_segment_of_way.hpp | 0 .../extractor}/graph_compressor.hpp | 0 .../extractor}/import_edge.hpp | 0 .../extractor}/internal_extractor_edge.hpp | 0 .../extractor}/node_id.hpp | 0 .../extractor}/original_edge_data.hpp | 0 .../extractor}/query_node.hpp | 0 .../extractor}/raster_source.hpp | 0 .../extractor}/restriction.hpp | 0 .../extractor}/restriction_map.hpp | 0 .../extractor}/restriction_parser.hpp | 0 .../extractor}/scripting_environment.hpp | 0 .../extractor}/speed_profile.hpp | 0 .../extractor}/tarjan_scc.hpp | 0 .../extractor}/travel_mode.hpp | 0 .../extractor}/turn_instructions.hpp | 0 {server => include/server}/api_grammar.hpp | 0 {server => include/server}/connection.hpp | 0 .../server}/http/compression_type.hpp | 0 {server => include/server}/http/header.hpp | 0 {server => include/server}/http/reply.hpp | 0 {server => include/server}/http/request.hpp | 0 .../server}/request_handler.hpp | 0 {server => include/server}/request_parser.hpp | 0 {server => include/server}/server.hpp | 0 {util => include/util}/bearing.hpp | 0 .../util}/binary_heap.hpp | 0 {util => include/util}/cast.hpp | 0 {util => include/util}/compute_angle.hpp | 0 {util => include/util}/container.hpp | 0 .../util}/coordinate_calculation.hpp | 0 {util => include/util}/datastore_options.hpp | 0 .../util}/deallocating_vector.hpp | 0 {util => include/util}/debug_geometry.hpp | 0 {util => include/util}/dist_table_wrapper.hpp | 0 .../util}/dynamic_graph.hpp | 0 {util => include/util}/fingerprint.hpp | 0 .../util}/fingerprint_impl.hpp.in | 0 .../util}/fixed_point_number.hpp | 0 {util => include/util}/floating_point.hpp | 0 {util => include/util}/graph_loader.hpp | 0 {util => include/util}/graph_utils.hpp | 0 .../util}/hilbert_value.hpp | 0 {util => include/util}/ini_file.hpp | 0 {util => include/util}/integer_range.hpp | 0 .../util}/iso_8601_duration_parser.hpp | 0 {util => include/util}/json_logger.hpp | 0 {util => include/util}/json_renderer.hpp | 0 {util => include/util}/json_util.hpp | 0 {util => include/util}/lua_util.hpp | 0 {util => include/util}/make_unique.hpp | 0 .../util}/matching_debug_info.hpp | 0 .../util}/matrix_graph_wrapper.hpp | 0 {util => include/util}/mercator.hpp | 0 .../util}/node_based_graph.hpp | 0 {util => include/util}/osrm_exception.hpp | 0 {data_structures => include/util}/percent.hpp | 0 {util => include/util}/range_algorithms.hpp | 0 .../util}/range_table.hpp | 0 .../util}/rectangle.hpp | 0 {util => include/util}/routed_options.hpp | 0 .../util}/shared_memory_vector_wrapper.hpp | 0 {util => include/util}/simple_logger.hpp | 0 .../util}/static_graph.hpp | 0 .../util}/static_rtree.hpp | 0 {util => include/util}/std_hash.hpp | 0 {util => include/util}/string_util.hpp | 0 {util => include/util}/timing_util.hpp | 0 {data_structures => include/util}/tribool.hpp | 0 {util => include/util}/trigonometry_table.hpp | 0 typedefs.h => include/util/typedefs.hpp | 0 {util => include/util}/version.hpp.in | 0 {util => include/util}/xml_renderer.hpp | 0 .../util}/xor_fast_hash.hpp | 0 .../util}/xor_fast_hash_storage.hpp | 0 .../benchmarks}/static_rtree.cpp | 0 .../contractor}/contractor_options.cpp | 0 .../contractor}/processing_chain.cpp | 0 .../descriptors}/description_factory.cpp | 0 .../engine}/douglas_peucker.cpp | 0 {library => src/engine}/osrm_impl.cpp | 0 .../engine}/phantom_node.cpp | 0 .../engine}/polyline_compressor.cpp | 0 .../engine}/polyline_formatter.cpp | 0 .../engine}/route_parameters.cpp | 0 .../engine}/search_engine_data.cpp | 0 .../extractor}/compressed_edge_container.cpp | 0 .../extractor}/edge_based_graph_factory.cpp | 0 .../extractor}/external_memory_node.cpp | 0 .../extractor}/extraction_containers.cpp | 0 {extractor => src/extractor}/extractor.cpp | 0 .../extractor}/extractor_callbacks.cpp | 0 .../extractor}/extractor_options.cpp | 0 .../extractor}/graph_compressor.cpp | 0 .../extractor}/import_edge.cpp | 0 .../extractor}/raster_source.cpp | 0 .../extractor}/restriction_map.cpp | 0 .../extractor}/restriction_parser.cpp | 0 .../extractor}/scripting_environment.cpp | 0 {server => src/server}/connection.cpp | 0 {server => src/server}/http/reply.cpp | 0 {server => src/server}/request_handler.cpp | 0 {server => src/server}/request_parser.cpp | 0 {tools => src/tools}/.gitignore | 0 {tools => src/tools}/check-hsgr.cpp | 0 {tools => src/tools}/components.cpp | 0 prepare.cpp => src/tools/contract.cpp | 0 datastore.cpp => src/tools/datastore.cpp | 0 extract.cpp => src/tools/extract.cpp | 0 {tools => src/tools}/io-benchmark.cpp | 0 routed.cpp => src/tools/routed.cpp | 0 {tools => src/tools}/simpleclient.cpp | 0 {tools => src/tools}/springclean.cpp | 0 {tools => src/tools}/unlock_all_mutexes.cpp | 0 {util => src/util}/compute_angle.cpp | 0 {data_structures => src/util}/coordinate.cpp | 0 .../util}/coordinate_calculation.cpp | 0 {util => src/util}/fingerprint.cpp | 0 .../util}/hilbert_value.cpp | 0 {util => src/util}/mercator.cpp | 0 {util => src/util}/osrm_exception.cpp | 0 {util => src/util}/simple_logger.cpp | 0 184 files changed, 608 deletions(-) delete mode 100644 algorithms/bfs_components.hpp delete mode 100644 data_structures/lru_cache.hpp delete mode 100644 data_structures/static_kdtree.hpp delete mode 100644 data_structures/upper_bound.hpp rename {contractor => include/contractor}/contractor.hpp (100%) rename {contractor => include/contractor}/contractor_options.hpp (100%) rename {algorithms => include/contractor}/crc32_processor.hpp (100%) rename {contractor => include/contractor}/processing_chain.hpp (100%) rename {data_structures => include/contractor}/query_edge.hpp (100%) rename {data_structures => include/datastore}/shared_memory_factory.hpp (100%) rename {server/data_structures => include/engine/datafacade}/datafacade_base.hpp (100%) rename {server/data_structures => include/engine/datafacade}/internal_datafacade.hpp (100%) rename {server/data_structures => include/engine/datafacade}/shared_barriers.hpp (100%) rename {server/data_structures => include/engine/datafacade}/shared_datafacade.hpp (100%) rename {server/data_structures => include/engine/datafacade}/shared_datatype.hpp (100%) rename {descriptors => include/engine/descriptors}/description_factory.hpp (100%) rename {descriptors => include/engine/descriptors}/descriptor_base.hpp (100%) rename {descriptors => include/engine/descriptors}/gpx_descriptor.hpp (100%) rename {descriptors => include/engine/descriptors}/json_descriptor.hpp (100%) rename {algorithms => include/engine}/douglas_peucker.hpp (100%) rename {algorithms => include/engine}/geospatial_query.hpp (100%) rename {data_structures => include/engine}/internal_route_result.hpp (100%) rename {algorithms => include/engine/map_matching}/bayes_classifier.hpp (100%) rename {data_structures => include/engine/map_matching}/hidden_markov_model.hpp (100%) rename {algorithms => include/engine}/object_encoder.hpp (100%) rename {library => include/engine}/osrm_impl.hpp (100%) rename {data_structures => include/engine}/phantom_node.hpp (100%) rename {plugins => include/engine/plugins}/distance_table.hpp (100%) rename {plugins => include/engine/plugins}/hello_world.hpp (100%) rename {plugins => include/engine/plugins}/match.hpp (100%) rename {plugins => include/engine/plugins}/nearest.hpp (100%) rename {plugins => include/engine/plugins}/plugin_base.hpp (100%) rename {plugins => include/engine/plugins}/timestamp.hpp (100%) rename {plugins => include/engine/plugins}/trip.hpp (100%) rename {plugins => include/engine/plugins}/viaroute.hpp (100%) rename {algorithms => include/engine}/polyline_compressor.hpp (100%) rename {algorithms => include/engine}/polyline_formatter.hpp (100%) rename {algorithms => include/engine}/route_name_extraction.hpp (100%) rename {routing_algorithms => include/engine/routing_algorithms}/alternative_path.hpp (100%) rename {routing_algorithms => include/engine/routing_algorithms}/direct_shortest_path.hpp (100%) rename {routing_algorithms => include/engine/routing_algorithms}/many_to_many.hpp (100%) rename {routing_algorithms => include/engine/routing_algorithms}/map_matching.hpp (100%) rename {routing_algorithms => include/engine/routing_algorithms}/routing_base.hpp (100%) rename {routing_algorithms => include/engine/routing_algorithms}/shortest_path.hpp (100%) rename {data_structures => include/engine}/search_engine.hpp (100%) rename {data_structures => include/engine}/search_engine_data.hpp (100%) rename {data_structures => include/engine}/segment_information.hpp (100%) rename {algorithms => include/engine/trip}/trip_brute_force.hpp (100%) rename {algorithms => include/engine/trip}/trip_farthest_insertion.hpp (100%) rename {algorithms => include/engine/trip}/trip_nearest_neighbour.hpp (100%) rename {algorithms => include/engine/trip}/trip_tabu_search.hpp (100%) rename {data_structures => include/extractor}/compressed_edge_container.hpp (100%) rename {extractor => include/extractor}/edge_based_graph_factory.hpp (100%) rename {data_structures => include/extractor}/edge_based_node.hpp (100%) rename {data_structures => include/extractor}/external_memory_node.hpp (100%) rename {extractor => include/extractor}/extraction_containers.hpp (100%) rename {extractor => include/extractor}/extraction_helper_functions.hpp (100%) rename {extractor => include/extractor}/extraction_node.hpp (100%) rename {extractor => include/extractor}/extraction_way.hpp (100%) rename {extractor => include/extractor}/extractor.hpp (100%) rename {extractor => include/extractor}/extractor_callbacks.hpp (100%) rename {extractor => include/extractor}/extractor_options.hpp (100%) rename {extractor => include/extractor}/first_and_last_segment_of_way.hpp (100%) rename {algorithms => include/extractor}/graph_compressor.hpp (100%) rename {data_structures => include/extractor}/import_edge.hpp (100%) rename {extractor => include/extractor}/internal_extractor_edge.hpp (100%) rename {data_structures => include/extractor}/node_id.hpp (100%) rename {data_structures => include/extractor}/original_edge_data.hpp (100%) rename {data_structures => include/extractor}/query_node.hpp (100%) rename {data_structures => include/extractor}/raster_source.hpp (100%) rename {data_structures => include/extractor}/restriction.hpp (100%) rename {data_structures => include/extractor}/restriction_map.hpp (100%) rename {extractor => include/extractor}/restriction_parser.hpp (100%) rename {extractor => include/extractor}/scripting_environment.hpp (100%) rename {extractor => include/extractor}/speed_profile.hpp (100%) rename {algorithms => include/extractor}/tarjan_scc.hpp (100%) rename {data_structures => include/extractor}/travel_mode.hpp (100%) rename {data_structures => include/extractor}/turn_instructions.hpp (100%) rename {server => include/server}/api_grammar.hpp (100%) rename {server => include/server}/connection.hpp (100%) rename {server => include/server}/http/compression_type.hpp (100%) rename {server => include/server}/http/header.hpp (100%) rename {server => include/server}/http/reply.hpp (100%) rename {server => include/server}/http/request.hpp (100%) rename {server => include/server}/request_handler.hpp (100%) rename {server => include/server}/request_parser.hpp (100%) rename {server => include/server}/server.hpp (100%) rename {util => include/util}/bearing.hpp (100%) rename {data_structures => include/util}/binary_heap.hpp (100%) rename {util => include/util}/cast.hpp (100%) rename {util => include/util}/compute_angle.hpp (100%) rename {util => include/util}/container.hpp (100%) rename {algorithms => include/util}/coordinate_calculation.hpp (100%) rename {util => include/util}/datastore_options.hpp (100%) rename {data_structures => include/util}/deallocating_vector.hpp (100%) rename {util => include/util}/debug_geometry.hpp (100%) rename {util => include/util}/dist_table_wrapper.hpp (100%) rename {data_structures => include/util}/dynamic_graph.hpp (100%) rename {util => include/util}/fingerprint.hpp (100%) rename {util => include/util}/fingerprint_impl.hpp.in (100%) rename {data_structures => include/util}/fixed_point_number.hpp (100%) rename {util => include/util}/floating_point.hpp (100%) rename {util => include/util}/graph_loader.hpp (100%) rename {util => include/util}/graph_utils.hpp (100%) rename {data_structures => include/util}/hilbert_value.hpp (100%) rename {util => include/util}/ini_file.hpp (100%) rename {util => include/util}/integer_range.hpp (100%) rename {util => include/util}/iso_8601_duration_parser.hpp (100%) rename {util => include/util}/json_logger.hpp (100%) rename {util => include/util}/json_renderer.hpp (100%) rename {util => include/util}/json_util.hpp (100%) rename {util => include/util}/lua_util.hpp (100%) rename {util => include/util}/make_unique.hpp (100%) rename {util => include/util}/matching_debug_info.hpp (100%) rename {data_structures => include/util}/matrix_graph_wrapper.hpp (100%) rename {util => include/util}/mercator.hpp (100%) rename {data_structures => include/util}/node_based_graph.hpp (100%) rename {util => include/util}/osrm_exception.hpp (100%) rename {data_structures => include/util}/percent.hpp (100%) rename {util => include/util}/range_algorithms.hpp (100%) rename {data_structures => include/util}/range_table.hpp (100%) rename {data_structures => include/util}/rectangle.hpp (100%) rename {util => include/util}/routed_options.hpp (100%) rename {data_structures => include/util}/shared_memory_vector_wrapper.hpp (100%) rename {util => include/util}/simple_logger.hpp (100%) rename {data_structures => include/util}/static_graph.hpp (100%) rename {data_structures => include/util}/static_rtree.hpp (100%) rename {util => include/util}/std_hash.hpp (100%) rename {util => include/util}/string_util.hpp (100%) rename {util => include/util}/timing_util.hpp (100%) rename {data_structures => include/util}/tribool.hpp (100%) rename {util => include/util}/trigonometry_table.hpp (100%) rename typedefs.h => include/util/typedefs.hpp (100%) rename {util => include/util}/version.hpp.in (100%) rename {util => include/util}/xml_renderer.hpp (100%) rename {data_structures => include/util}/xor_fast_hash.hpp (100%) rename {data_structures => include/util}/xor_fast_hash_storage.hpp (100%) rename {benchmarks => src/benchmarks}/static_rtree.cpp (100%) rename {contractor => src/contractor}/contractor_options.cpp (100%) rename {contractor => src/contractor}/processing_chain.cpp (100%) rename {descriptors => src/engine/descriptors}/description_factory.cpp (100%) rename {algorithms => src/engine}/douglas_peucker.cpp (100%) rename {library => src/engine}/osrm_impl.cpp (100%) rename {data_structures => src/engine}/phantom_node.cpp (100%) rename {algorithms => src/engine}/polyline_compressor.cpp (100%) rename {algorithms => src/engine}/polyline_formatter.cpp (100%) rename {data_structures => src/engine}/route_parameters.cpp (100%) rename {data_structures => src/engine}/search_engine_data.cpp (100%) rename {data_structures => src/extractor}/compressed_edge_container.cpp (100%) rename {extractor => src/extractor}/edge_based_graph_factory.cpp (100%) rename {data_structures => src/extractor}/external_memory_node.cpp (100%) rename {extractor => src/extractor}/extraction_containers.cpp (100%) rename {extractor => src/extractor}/extractor.cpp (100%) rename {extractor => src/extractor}/extractor_callbacks.cpp (100%) rename {extractor => src/extractor}/extractor_options.cpp (100%) rename {algorithms => src/extractor}/graph_compressor.cpp (100%) rename {data_structures => src/extractor}/import_edge.cpp (100%) rename {data_structures => src/extractor}/raster_source.cpp (100%) rename {data_structures => src/extractor}/restriction_map.cpp (100%) rename {extractor => src/extractor}/restriction_parser.cpp (100%) rename {extractor => src/extractor}/scripting_environment.cpp (100%) rename {server => src/server}/connection.cpp (100%) rename {server => src/server}/http/reply.cpp (100%) rename {server => src/server}/request_handler.cpp (100%) rename {server => src/server}/request_parser.cpp (100%) rename {tools => src/tools}/.gitignore (100%) rename {tools => src/tools}/check-hsgr.cpp (100%) rename {tools => src/tools}/components.cpp (100%) rename prepare.cpp => src/tools/contract.cpp (100%) rename datastore.cpp => src/tools/datastore.cpp (100%) rename extract.cpp => src/tools/extract.cpp (100%) rename {tools => src/tools}/io-benchmark.cpp (100%) rename routed.cpp => src/tools/routed.cpp (100%) rename {tools => src/tools}/simpleclient.cpp (100%) rename {tools => src/tools}/springclean.cpp (100%) rename {tools => src/tools}/unlock_all_mutexes.cpp (100%) rename {util => src/util}/compute_angle.cpp (100%) rename {data_structures => src/util}/coordinate.cpp (100%) rename {algorithms => src/util}/coordinate_calculation.cpp (100%) rename {util => src/util}/fingerprint.cpp (100%) rename {data_structures => src/util}/hilbert_value.cpp (100%) rename {util => src/util}/mercator.cpp (100%) rename {util => src/util}/osrm_exception.cpp (100%) rename {util => src/util}/simple_logger.cpp (100%) diff --git a/algorithms/bfs_components.hpp b/algorithms/bfs_components.hpp deleted file mode 100644 index b3f536401..000000000 --- a/algorithms/bfs_components.hpp +++ /dev/null @@ -1,174 +0,0 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#ifndef BFS_COMPONENTS_HPP_ -#define BFS_COMPONENTS_HPP_ - -#include "../typedefs.h" -#include "../data_structures/restriction_map.hpp" - -#include -#include - -// Explores the components of the given graph while respecting turn restrictions -// and barriers. -template class BFSComponentExplorer -{ - public: - BFSComponentExplorer(const GraphT &dynamic_graph, - const RestrictionMap &restrictions, - const std::unordered_set &barrier_nodes) - : m_graph(dynamic_graph), m_restriction_map(restrictions), m_barrier_nodes(barrier_nodes) - { - BOOST_ASSERT(m_graph.GetNumberOfNodes() > 0); - } - - /*! - * Returns the size of the component that the node belongs to. - */ - unsigned int GetComponentSize(const NodeID node) const - { - BOOST_ASSERT(node < m_component_index_list.size()); - - return m_component_index_size[m_component_index_list[node]]; - } - - unsigned int GetNumberOfComponents() { return m_component_index_size.size(); } - - /*! - * Computes the component sizes. - */ - void run() - { - std::queue> bfs_queue; - unsigned current_component = 0; - - BOOST_ASSERT(m_component_index_list.empty()); - BOOST_ASSERT(m_component_index_size.empty()); - - unsigned num_nodes = m_graph.GetNumberOfNodes(); - - m_component_index_list.resize(num_nodes, std::numeric_limits::max()); - - BOOST_ASSERT(num_nodes > 0); - - // put unexplorered node with parent pointer into queue - for (NodeID node = 0; node < num_nodes; ++node) - { - if (std::numeric_limits::max() == m_component_index_list[node]) - { - unsigned size = ExploreComponent(bfs_queue, node, current_component); - - // push size into vector - m_component_index_size.emplace_back(size); - ++current_component; - } - } - } - - private: - /*! - * Explores the current component that starts at node using BFS. - */ - unsigned ExploreComponent(std::queue> &bfs_queue, - NodeID node, - unsigned current_component) - { - /* - Graphical representation of variables: - - u v w - *---------->*---------->* - e2 - */ - - bfs_queue.emplace(node, node); - // mark node as read - m_component_index_list[node] = current_component; - - unsigned current_component_size = 1; - - while (!bfs_queue.empty()) - { - // fetch element from BFS queue - std::pair current_queue_item = bfs_queue.front(); - bfs_queue.pop(); - - const NodeID v = current_queue_item.first; // current node - const NodeID u = current_queue_item.second; // parent - // increment size counter of current component - ++current_component_size; - if (m_barrier_nodes.find(v) != m_barrier_nodes.end()) - { - continue; - } - const NodeID to_node_of_only_restriction = - m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v); - - for (auto e2 : m_graph.GetAdjacentEdgeRange(v)) - { - const NodeID w = m_graph.GetTarget(e2); - - if (to_node_of_only_restriction != std::numeric_limits::max() && - w != to_node_of_only_restriction) - { - // At an only_-restriction but not at the right turn - continue; - } - - if (u != w) - { - // only add an edge if turn is not a U-turn except - // when it is at the end of a dead-end street. - if (!m_restriction_map.CheckIfTurnIsRestricted(u, v, w)) - { - // only add an edge if turn is not prohibited - if (std::numeric_limits::max() == m_component_index_list[w]) - { - // insert next (node, parent) only if w has - // not yet been explored - // mark node as read - m_component_index_list[w] = current_component; - bfs_queue.emplace(w, v); - } - } - } - } - } - - return current_component_size; - } - - std::vector m_component_index_list; - std::vector m_component_index_size; - - const GraphT &m_graph; - const RestrictionMap &m_restriction_map; - const std::unordered_set &m_barrier_nodes; -}; - -#endif // BFS_COMPONENTS_HPP_ diff --git a/data_structures/lru_cache.hpp b/data_structures/lru_cache.hpp deleted file mode 100644 index 155ab1ef4..000000000 --- a/data_structures/lru_cache.hpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#ifndef LRUCACHE_HPP -#define LRUCACHE_HPP - -#include -#include - -template class LRUCache -{ - private: - struct CacheEntry - { - CacheEntry(KeyT k, ValueT v) : key(k), value(v) {} - KeyT key; - ValueT value; - }; - unsigned capacity; - std::list itemsInCache; - std::unordered_map::iterator> positionMap; - - public: - explicit LRUCache(unsigned c) : capacity(c) {} - - bool Holds(KeyT key) - { - if (positionMap.find(key) != positionMap.end()) - { - return true; - } - return false; - } - - void Insert(const KeyT key, ValueT &value) - { - itemsInCache.push_front(CacheEntry(key, value)); - positionMap.insert(std::make_pair(key, itemsInCache.begin())); - if (itemsInCache.size() > capacity) - { - positionMap.erase(itemsInCache.back().key); - itemsInCache.pop_back(); - } - } - - void Insert(const KeyT key, ValueT value) - { - itemsInCache.push_front(CacheEntry(key, value)); - positionMap.insert(std::make_pair(key, itemsInCache.begin())); - if (itemsInCache.size() > capacity) - { - positionMap.erase(itemsInCache.back().key); - itemsInCache.pop_back(); - } - } - - bool Fetch(const KeyT key, ValueT &result) - { - if (Holds(key)) - { - CacheEntry e = *(positionMap.find(key)->second); - result = e.value; - - // move to front - itemsInCache.splice(itemsInCache.begin(), itemsInCache, positionMap.find(key)->second); - positionMap.find(key)->second = itemsInCache.begin(); - return true; - } - return false; - } - unsigned Size() const { return itemsInCache.size(); } -}; -#endif // LRUCACHE_HPP diff --git a/data_structures/static_kdtree.hpp b/data_structures/static_kdtree.hpp deleted file mode 100644 index 1e65dc844..000000000 --- a/data_structures/static_kdtree.hpp +++ /dev/null @@ -1,260 +0,0 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -// KD Tree coded by Christian Vetter, Monav Project - -#ifndef STATICKDTREE_HPP -#define STATICKDTREE_HPP - -#include -#include -#include -#include -#include - -namespace KDTree -{ - -#define KDTREE_BASESIZE (8) - -template class BoundingBox -{ - public: - BoundingBox() - { - for (unsigned dim = 0; dim < k; ++dim) - { - min[dim] = std::numeric_limits::min(); - max[dim] = std::numeric_limits::max(); - } - } - - T min[k]; - T max[k]; -}; - -struct NoData -{ -}; - -template class EuclidianMetric -{ - public: - double operator()(const T left[k], const T right[k]) - { - double result = 0; - for (unsigned i = 0; i < k; ++i) - { - double temp = (double)left[i] - (double)right[i]; - result += temp * temp; - } - return result; - } - - double operator()(const BoundingBox &box, const T point[k]) - { - T nearest[k]; - for (unsigned dim = 0; dim < k; ++dim) - { - if (point[dim] < box.min[dim]) - nearest[dim] = box.min[dim]; - else if (point[dim] > box.max[dim]) - nearest[dim] = box.max[dim]; - else - nearest[dim] = point[dim]; - } - return operator()(point, nearest); - } -}; - -template > -class StaticKDTree -{ - public: - struct InputPoint - { - T coordinates[k]; - Data data; - bool operator==(const InputPoint &right) - { - for (int i = 0; i < k; i++) - { - if (coordinates[i] != right.coordinates[i]) - return false; - } - return true; - } - }; - - explicit StaticKDTree(std::vector *points) - { - BOOST_ASSERT(k > 0); - BOOST_ASSERT(points->size() > 0); - size = points->size(); - kdtree = new InputPoint[size]; - for (Iterator i = 0; i != size; ++i) - { - kdtree[i] = points->at(i); - for (unsigned dim = 0; dim < k; ++dim) - { - if (kdtree[i].coordinates[dim] < boundingBox.min[dim]) - boundingBox.min[dim] = kdtree[i].coordinates[dim]; - if (kdtree[i].coordinates[dim] > boundingBox.max[dim]) - boundingBox.max[dim] = kdtree[i].coordinates[dim]; - } - } - std::stack s; - s.push(Tree(0, size, 0)); - while (!s.empty()) - { - Tree tree = s.top(); - s.pop(); - - if (tree.right - tree.left < KDTREE_BASESIZE) - continue; - - Iterator middle = tree.left + (tree.right - tree.left) / 2; - std::nth_element(kdtree + tree.left, kdtree + middle, kdtree + tree.right, - Less(tree.dimension)); - s.push(Tree(tree.left, middle, (tree.dimension + 1) % k)); - s.push(Tree(middle + 1, tree.right, (tree.dimension + 1) % k)); - } - } - - ~StaticKDTree() { delete[] kdtree; } - - bool NearestNeighbor(InputPoint *result, const InputPoint &point) - { - Metric distance; - bool found = false; - double nearestDistance = std::numeric_limits::max(); - std::stack s; - s.push(NNTree(0, size, 0, boundingBox)); - while (!s.empty()) - { - NNTree tree = s.top(); - s.pop(); - - if (distance(tree.box, point.coordinates) >= nearestDistance) - continue; - - if (tree.right - tree.left < KDTREE_BASESIZE) - { - for (unsigned i = tree.left; i < tree.right; i++) - { - double newDistance = distance(kdtree[i].coordinates, point.coordinates); - if (newDistance < nearestDistance) - { - nearestDistance = newDistance; - *result = kdtree[i]; - found = true; - } - } - continue; - } - - Iterator middle = tree.left + (tree.right - tree.left) / 2; - - double newDistance = distance(kdtree[middle].coordinates, point.coordinates); - if (newDistance < nearestDistance) - { - nearestDistance = newDistance; - *result = kdtree[middle]; - found = true; - } - - Less comperator(tree.dimension); - if (!comperator(point, kdtree[middle])) - { - NNTree first(middle + 1, tree.right, (tree.dimension + 1) % k, tree.box); - NNTree second(tree.left, middle, (tree.dimension + 1) % k, tree.box); - first.box.min[tree.dimension] = kdtree[middle].coordinates[tree.dimension]; - second.box.max[tree.dimension] = kdtree[middle].coordinates[tree.dimension]; - s.push(second); - s.push(first); - } - else - { - NNTree first(middle + 1, tree.right, (tree.dimension + 1) % k, tree.box); - NNTree second(tree.left, middle, (tree.dimension + 1) % k, tree.box); - first.box.min[tree.dimension] = kdtree[middle].coordinates[tree.dimension]; - second.box.max[tree.dimension] = kdtree[middle].coordinates[tree.dimension]; - s.push(first); - s.push(second); - } - } - return found; - } - - private: - using Iterator = unsigned; - struct Tree - { - Iterator left; - Iterator right; - unsigned dimension; - Tree() {} - Tree(Iterator l, Iterator r, unsigned d) : left(l), right(r), dimension(d) {} - }; - struct NNTree - { - Iterator left; - Iterator right; - unsigned dimension; - BoundingBox box; - NNTree() {} - NNTree(Iterator l, Iterator r, unsigned d, const BoundingBox &b) - : left(l), right(r), dimension(d), box(b) - { - } - }; - class Less - { - public: - explicit Less(unsigned d) - { - dimension = d; - BOOST_ASSERT(dimension < k); - } - - bool operator()(const InputPoint &left, const InputPoint &right) - { - BOOST_ASSERT(dimension < k); - return left.coordinates[dimension] < right.coordinates[dimension]; - } - - private: - unsigned dimension; - }; - - BoundingBox boundingBox; - InputPoint *kdtree; - Iterator size; -}; -} - -#endif // STATICKDTREE_HPP diff --git a/data_structures/upper_bound.hpp b/data_structures/upper_bound.hpp deleted file mode 100644 index 80695f2c5..000000000 --- a/data_structures/upper_bound.hpp +++ /dev/null @@ -1,77 +0,0 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#ifndef LOWER_BOUND_HPP -#define LOWER_BOUND_HPP - -#include -#include -#include -#include - -// max pq holds k elements -// insert if key is smaller than max -// if size > k then remove element -// get() always yields a bound to the k smallest element in the stream - -template class upper_bound -{ - private: - using parameter_type = - typename std::conditional::value, key_type, key_type &>::type; - - public: - upper_bound() = delete; - upper_bound(std::size_t size) : size(size) {} - - key_type get() const - { - if (queue.size() < size) - { - return std::numeric_limits::max(); - } - return queue.top(); - } - - void insert(const parameter_type key) - { - if (key < get()) - { - queue.emplace(key); - while (queue.size() > size) - { - queue.pop(); - } - } - } - - private: - std::priority_queue, std::less> queue; - const std::size_t size; -}; - -#endif // LOWER_BOUND_HPP diff --git a/contractor/contractor.hpp b/include/contractor/contractor.hpp similarity index 100% rename from contractor/contractor.hpp rename to include/contractor/contractor.hpp diff --git a/contractor/contractor_options.hpp b/include/contractor/contractor_options.hpp similarity index 100% rename from contractor/contractor_options.hpp rename to include/contractor/contractor_options.hpp diff --git a/algorithms/crc32_processor.hpp b/include/contractor/crc32_processor.hpp similarity index 100% rename from algorithms/crc32_processor.hpp rename to include/contractor/crc32_processor.hpp diff --git a/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp similarity index 100% rename from contractor/processing_chain.hpp rename to include/contractor/processing_chain.hpp diff --git a/data_structures/query_edge.hpp b/include/contractor/query_edge.hpp similarity index 100% rename from data_structures/query_edge.hpp rename to include/contractor/query_edge.hpp diff --git a/data_structures/shared_memory_factory.hpp b/include/datastore/shared_memory_factory.hpp similarity index 100% rename from data_structures/shared_memory_factory.hpp rename to include/datastore/shared_memory_factory.hpp diff --git a/server/data_structures/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp similarity index 100% rename from server/data_structures/datafacade_base.hpp rename to include/engine/datafacade/datafacade_base.hpp diff --git a/server/data_structures/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp similarity index 100% rename from server/data_structures/internal_datafacade.hpp rename to include/engine/datafacade/internal_datafacade.hpp diff --git a/server/data_structures/shared_barriers.hpp b/include/engine/datafacade/shared_barriers.hpp similarity index 100% rename from server/data_structures/shared_barriers.hpp rename to include/engine/datafacade/shared_barriers.hpp diff --git a/server/data_structures/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp similarity index 100% rename from server/data_structures/shared_datafacade.hpp rename to include/engine/datafacade/shared_datafacade.hpp diff --git a/server/data_structures/shared_datatype.hpp b/include/engine/datafacade/shared_datatype.hpp similarity index 100% rename from server/data_structures/shared_datatype.hpp rename to include/engine/datafacade/shared_datatype.hpp diff --git a/descriptors/description_factory.hpp b/include/engine/descriptors/description_factory.hpp similarity index 100% rename from descriptors/description_factory.hpp rename to include/engine/descriptors/description_factory.hpp diff --git a/descriptors/descriptor_base.hpp b/include/engine/descriptors/descriptor_base.hpp similarity index 100% rename from descriptors/descriptor_base.hpp rename to include/engine/descriptors/descriptor_base.hpp diff --git a/descriptors/gpx_descriptor.hpp b/include/engine/descriptors/gpx_descriptor.hpp similarity index 100% rename from descriptors/gpx_descriptor.hpp rename to include/engine/descriptors/gpx_descriptor.hpp diff --git a/descriptors/json_descriptor.hpp b/include/engine/descriptors/json_descriptor.hpp similarity index 100% rename from descriptors/json_descriptor.hpp rename to include/engine/descriptors/json_descriptor.hpp diff --git a/algorithms/douglas_peucker.hpp b/include/engine/douglas_peucker.hpp similarity index 100% rename from algorithms/douglas_peucker.hpp rename to include/engine/douglas_peucker.hpp diff --git a/algorithms/geospatial_query.hpp b/include/engine/geospatial_query.hpp similarity index 100% rename from algorithms/geospatial_query.hpp rename to include/engine/geospatial_query.hpp diff --git a/data_structures/internal_route_result.hpp b/include/engine/internal_route_result.hpp similarity index 100% rename from data_structures/internal_route_result.hpp rename to include/engine/internal_route_result.hpp diff --git a/algorithms/bayes_classifier.hpp b/include/engine/map_matching/bayes_classifier.hpp similarity index 100% rename from algorithms/bayes_classifier.hpp rename to include/engine/map_matching/bayes_classifier.hpp diff --git a/data_structures/hidden_markov_model.hpp b/include/engine/map_matching/hidden_markov_model.hpp similarity index 100% rename from data_structures/hidden_markov_model.hpp rename to include/engine/map_matching/hidden_markov_model.hpp diff --git a/algorithms/object_encoder.hpp b/include/engine/object_encoder.hpp similarity index 100% rename from algorithms/object_encoder.hpp rename to include/engine/object_encoder.hpp diff --git a/library/osrm_impl.hpp b/include/engine/osrm_impl.hpp similarity index 100% rename from library/osrm_impl.hpp rename to include/engine/osrm_impl.hpp diff --git a/data_structures/phantom_node.hpp b/include/engine/phantom_node.hpp similarity index 100% rename from data_structures/phantom_node.hpp rename to include/engine/phantom_node.hpp diff --git a/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp similarity index 100% rename from plugins/distance_table.hpp rename to include/engine/plugins/distance_table.hpp diff --git a/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp similarity index 100% rename from plugins/hello_world.hpp rename to include/engine/plugins/hello_world.hpp diff --git a/plugins/match.hpp b/include/engine/plugins/match.hpp similarity index 100% rename from plugins/match.hpp rename to include/engine/plugins/match.hpp diff --git a/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp similarity index 100% rename from plugins/nearest.hpp rename to include/engine/plugins/nearest.hpp diff --git a/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp similarity index 100% rename from plugins/plugin_base.hpp rename to include/engine/plugins/plugin_base.hpp diff --git a/plugins/timestamp.hpp b/include/engine/plugins/timestamp.hpp similarity index 100% rename from plugins/timestamp.hpp rename to include/engine/plugins/timestamp.hpp diff --git a/plugins/trip.hpp b/include/engine/plugins/trip.hpp similarity index 100% rename from plugins/trip.hpp rename to include/engine/plugins/trip.hpp diff --git a/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp similarity index 100% rename from plugins/viaroute.hpp rename to include/engine/plugins/viaroute.hpp diff --git a/algorithms/polyline_compressor.hpp b/include/engine/polyline_compressor.hpp similarity index 100% rename from algorithms/polyline_compressor.hpp rename to include/engine/polyline_compressor.hpp diff --git a/algorithms/polyline_formatter.hpp b/include/engine/polyline_formatter.hpp similarity index 100% rename from algorithms/polyline_formatter.hpp rename to include/engine/polyline_formatter.hpp diff --git a/algorithms/route_name_extraction.hpp b/include/engine/route_name_extraction.hpp similarity index 100% rename from algorithms/route_name_extraction.hpp rename to include/engine/route_name_extraction.hpp diff --git a/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp similarity index 100% rename from routing_algorithms/alternative_path.hpp rename to include/engine/routing_algorithms/alternative_path.hpp diff --git a/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp similarity index 100% rename from routing_algorithms/direct_shortest_path.hpp rename to include/engine/routing_algorithms/direct_shortest_path.hpp diff --git a/routing_algorithms/many_to_many.hpp b/include/engine/routing_algorithms/many_to_many.hpp similarity index 100% rename from routing_algorithms/many_to_many.hpp rename to include/engine/routing_algorithms/many_to_many.hpp diff --git a/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp similarity index 100% rename from routing_algorithms/map_matching.hpp rename to include/engine/routing_algorithms/map_matching.hpp diff --git a/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp similarity index 100% rename from routing_algorithms/routing_base.hpp rename to include/engine/routing_algorithms/routing_base.hpp diff --git a/routing_algorithms/shortest_path.hpp b/include/engine/routing_algorithms/shortest_path.hpp similarity index 100% rename from routing_algorithms/shortest_path.hpp rename to include/engine/routing_algorithms/shortest_path.hpp diff --git a/data_structures/search_engine.hpp b/include/engine/search_engine.hpp similarity index 100% rename from data_structures/search_engine.hpp rename to include/engine/search_engine.hpp diff --git a/data_structures/search_engine_data.hpp b/include/engine/search_engine_data.hpp similarity index 100% rename from data_structures/search_engine_data.hpp rename to include/engine/search_engine_data.hpp diff --git a/data_structures/segment_information.hpp b/include/engine/segment_information.hpp similarity index 100% rename from data_structures/segment_information.hpp rename to include/engine/segment_information.hpp diff --git a/algorithms/trip_brute_force.hpp b/include/engine/trip/trip_brute_force.hpp similarity index 100% rename from algorithms/trip_brute_force.hpp rename to include/engine/trip/trip_brute_force.hpp diff --git a/algorithms/trip_farthest_insertion.hpp b/include/engine/trip/trip_farthest_insertion.hpp similarity index 100% rename from algorithms/trip_farthest_insertion.hpp rename to include/engine/trip/trip_farthest_insertion.hpp diff --git a/algorithms/trip_nearest_neighbour.hpp b/include/engine/trip/trip_nearest_neighbour.hpp similarity index 100% rename from algorithms/trip_nearest_neighbour.hpp rename to include/engine/trip/trip_nearest_neighbour.hpp diff --git a/algorithms/trip_tabu_search.hpp b/include/engine/trip/trip_tabu_search.hpp similarity index 100% rename from algorithms/trip_tabu_search.hpp rename to include/engine/trip/trip_tabu_search.hpp diff --git a/data_structures/compressed_edge_container.hpp b/include/extractor/compressed_edge_container.hpp similarity index 100% rename from data_structures/compressed_edge_container.hpp rename to include/extractor/compressed_edge_container.hpp diff --git a/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp similarity index 100% rename from extractor/edge_based_graph_factory.hpp rename to include/extractor/edge_based_graph_factory.hpp diff --git a/data_structures/edge_based_node.hpp b/include/extractor/edge_based_node.hpp similarity index 100% rename from data_structures/edge_based_node.hpp rename to include/extractor/edge_based_node.hpp diff --git a/data_structures/external_memory_node.hpp b/include/extractor/external_memory_node.hpp similarity index 100% rename from data_structures/external_memory_node.hpp rename to include/extractor/external_memory_node.hpp diff --git a/extractor/extraction_containers.hpp b/include/extractor/extraction_containers.hpp similarity index 100% rename from extractor/extraction_containers.hpp rename to include/extractor/extraction_containers.hpp diff --git a/extractor/extraction_helper_functions.hpp b/include/extractor/extraction_helper_functions.hpp similarity index 100% rename from extractor/extraction_helper_functions.hpp rename to include/extractor/extraction_helper_functions.hpp diff --git a/extractor/extraction_node.hpp b/include/extractor/extraction_node.hpp similarity index 100% rename from extractor/extraction_node.hpp rename to include/extractor/extraction_node.hpp diff --git a/extractor/extraction_way.hpp b/include/extractor/extraction_way.hpp similarity index 100% rename from extractor/extraction_way.hpp rename to include/extractor/extraction_way.hpp diff --git a/extractor/extractor.hpp b/include/extractor/extractor.hpp similarity index 100% rename from extractor/extractor.hpp rename to include/extractor/extractor.hpp diff --git a/extractor/extractor_callbacks.hpp b/include/extractor/extractor_callbacks.hpp similarity index 100% rename from extractor/extractor_callbacks.hpp rename to include/extractor/extractor_callbacks.hpp diff --git a/extractor/extractor_options.hpp b/include/extractor/extractor_options.hpp similarity index 100% rename from extractor/extractor_options.hpp rename to include/extractor/extractor_options.hpp diff --git a/extractor/first_and_last_segment_of_way.hpp b/include/extractor/first_and_last_segment_of_way.hpp similarity index 100% rename from extractor/first_and_last_segment_of_way.hpp rename to include/extractor/first_and_last_segment_of_way.hpp diff --git a/algorithms/graph_compressor.hpp b/include/extractor/graph_compressor.hpp similarity index 100% rename from algorithms/graph_compressor.hpp rename to include/extractor/graph_compressor.hpp diff --git a/data_structures/import_edge.hpp b/include/extractor/import_edge.hpp similarity index 100% rename from data_structures/import_edge.hpp rename to include/extractor/import_edge.hpp diff --git a/extractor/internal_extractor_edge.hpp b/include/extractor/internal_extractor_edge.hpp similarity index 100% rename from extractor/internal_extractor_edge.hpp rename to include/extractor/internal_extractor_edge.hpp diff --git a/data_structures/node_id.hpp b/include/extractor/node_id.hpp similarity index 100% rename from data_structures/node_id.hpp rename to include/extractor/node_id.hpp diff --git a/data_structures/original_edge_data.hpp b/include/extractor/original_edge_data.hpp similarity index 100% rename from data_structures/original_edge_data.hpp rename to include/extractor/original_edge_data.hpp diff --git a/data_structures/query_node.hpp b/include/extractor/query_node.hpp similarity index 100% rename from data_structures/query_node.hpp rename to include/extractor/query_node.hpp diff --git a/data_structures/raster_source.hpp b/include/extractor/raster_source.hpp similarity index 100% rename from data_structures/raster_source.hpp rename to include/extractor/raster_source.hpp diff --git a/data_structures/restriction.hpp b/include/extractor/restriction.hpp similarity index 100% rename from data_structures/restriction.hpp rename to include/extractor/restriction.hpp diff --git a/data_structures/restriction_map.hpp b/include/extractor/restriction_map.hpp similarity index 100% rename from data_structures/restriction_map.hpp rename to include/extractor/restriction_map.hpp diff --git a/extractor/restriction_parser.hpp b/include/extractor/restriction_parser.hpp similarity index 100% rename from extractor/restriction_parser.hpp rename to include/extractor/restriction_parser.hpp diff --git a/extractor/scripting_environment.hpp b/include/extractor/scripting_environment.hpp similarity index 100% rename from extractor/scripting_environment.hpp rename to include/extractor/scripting_environment.hpp diff --git a/extractor/speed_profile.hpp b/include/extractor/speed_profile.hpp similarity index 100% rename from extractor/speed_profile.hpp rename to include/extractor/speed_profile.hpp diff --git a/algorithms/tarjan_scc.hpp b/include/extractor/tarjan_scc.hpp similarity index 100% rename from algorithms/tarjan_scc.hpp rename to include/extractor/tarjan_scc.hpp diff --git a/data_structures/travel_mode.hpp b/include/extractor/travel_mode.hpp similarity index 100% rename from data_structures/travel_mode.hpp rename to include/extractor/travel_mode.hpp diff --git a/data_structures/turn_instructions.hpp b/include/extractor/turn_instructions.hpp similarity index 100% rename from data_structures/turn_instructions.hpp rename to include/extractor/turn_instructions.hpp diff --git a/server/api_grammar.hpp b/include/server/api_grammar.hpp similarity index 100% rename from server/api_grammar.hpp rename to include/server/api_grammar.hpp diff --git a/server/connection.hpp b/include/server/connection.hpp similarity index 100% rename from server/connection.hpp rename to include/server/connection.hpp diff --git a/server/http/compression_type.hpp b/include/server/http/compression_type.hpp similarity index 100% rename from server/http/compression_type.hpp rename to include/server/http/compression_type.hpp diff --git a/server/http/header.hpp b/include/server/http/header.hpp similarity index 100% rename from server/http/header.hpp rename to include/server/http/header.hpp diff --git a/server/http/reply.hpp b/include/server/http/reply.hpp similarity index 100% rename from server/http/reply.hpp rename to include/server/http/reply.hpp diff --git a/server/http/request.hpp b/include/server/http/request.hpp similarity index 100% rename from server/http/request.hpp rename to include/server/http/request.hpp diff --git a/server/request_handler.hpp b/include/server/request_handler.hpp similarity index 100% rename from server/request_handler.hpp rename to include/server/request_handler.hpp diff --git a/server/request_parser.hpp b/include/server/request_parser.hpp similarity index 100% rename from server/request_parser.hpp rename to include/server/request_parser.hpp diff --git a/server/server.hpp b/include/server/server.hpp similarity index 100% rename from server/server.hpp rename to include/server/server.hpp diff --git a/util/bearing.hpp b/include/util/bearing.hpp similarity index 100% rename from util/bearing.hpp rename to include/util/bearing.hpp diff --git a/data_structures/binary_heap.hpp b/include/util/binary_heap.hpp similarity index 100% rename from data_structures/binary_heap.hpp rename to include/util/binary_heap.hpp diff --git a/util/cast.hpp b/include/util/cast.hpp similarity index 100% rename from util/cast.hpp rename to include/util/cast.hpp diff --git a/util/compute_angle.hpp b/include/util/compute_angle.hpp similarity index 100% rename from util/compute_angle.hpp rename to include/util/compute_angle.hpp diff --git a/util/container.hpp b/include/util/container.hpp similarity index 100% rename from util/container.hpp rename to include/util/container.hpp diff --git a/algorithms/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp similarity index 100% rename from algorithms/coordinate_calculation.hpp rename to include/util/coordinate_calculation.hpp diff --git a/util/datastore_options.hpp b/include/util/datastore_options.hpp similarity index 100% rename from util/datastore_options.hpp rename to include/util/datastore_options.hpp diff --git a/data_structures/deallocating_vector.hpp b/include/util/deallocating_vector.hpp similarity index 100% rename from data_structures/deallocating_vector.hpp rename to include/util/deallocating_vector.hpp diff --git a/util/debug_geometry.hpp b/include/util/debug_geometry.hpp similarity index 100% rename from util/debug_geometry.hpp rename to include/util/debug_geometry.hpp diff --git a/util/dist_table_wrapper.hpp b/include/util/dist_table_wrapper.hpp similarity index 100% rename from util/dist_table_wrapper.hpp rename to include/util/dist_table_wrapper.hpp diff --git a/data_structures/dynamic_graph.hpp b/include/util/dynamic_graph.hpp similarity index 100% rename from data_structures/dynamic_graph.hpp rename to include/util/dynamic_graph.hpp diff --git a/util/fingerprint.hpp b/include/util/fingerprint.hpp similarity index 100% rename from util/fingerprint.hpp rename to include/util/fingerprint.hpp diff --git a/util/fingerprint_impl.hpp.in b/include/util/fingerprint_impl.hpp.in similarity index 100% rename from util/fingerprint_impl.hpp.in rename to include/util/fingerprint_impl.hpp.in diff --git a/data_structures/fixed_point_number.hpp b/include/util/fixed_point_number.hpp similarity index 100% rename from data_structures/fixed_point_number.hpp rename to include/util/fixed_point_number.hpp diff --git a/util/floating_point.hpp b/include/util/floating_point.hpp similarity index 100% rename from util/floating_point.hpp rename to include/util/floating_point.hpp diff --git a/util/graph_loader.hpp b/include/util/graph_loader.hpp similarity index 100% rename from util/graph_loader.hpp rename to include/util/graph_loader.hpp diff --git a/util/graph_utils.hpp b/include/util/graph_utils.hpp similarity index 100% rename from util/graph_utils.hpp rename to include/util/graph_utils.hpp diff --git a/data_structures/hilbert_value.hpp b/include/util/hilbert_value.hpp similarity index 100% rename from data_structures/hilbert_value.hpp rename to include/util/hilbert_value.hpp diff --git a/util/ini_file.hpp b/include/util/ini_file.hpp similarity index 100% rename from util/ini_file.hpp rename to include/util/ini_file.hpp diff --git a/util/integer_range.hpp b/include/util/integer_range.hpp similarity index 100% rename from util/integer_range.hpp rename to include/util/integer_range.hpp diff --git a/util/iso_8601_duration_parser.hpp b/include/util/iso_8601_duration_parser.hpp similarity index 100% rename from util/iso_8601_duration_parser.hpp rename to include/util/iso_8601_duration_parser.hpp diff --git a/util/json_logger.hpp b/include/util/json_logger.hpp similarity index 100% rename from util/json_logger.hpp rename to include/util/json_logger.hpp diff --git a/util/json_renderer.hpp b/include/util/json_renderer.hpp similarity index 100% rename from util/json_renderer.hpp rename to include/util/json_renderer.hpp diff --git a/util/json_util.hpp b/include/util/json_util.hpp similarity index 100% rename from util/json_util.hpp rename to include/util/json_util.hpp diff --git a/util/lua_util.hpp b/include/util/lua_util.hpp similarity index 100% rename from util/lua_util.hpp rename to include/util/lua_util.hpp diff --git a/util/make_unique.hpp b/include/util/make_unique.hpp similarity index 100% rename from util/make_unique.hpp rename to include/util/make_unique.hpp diff --git a/util/matching_debug_info.hpp b/include/util/matching_debug_info.hpp similarity index 100% rename from util/matching_debug_info.hpp rename to include/util/matching_debug_info.hpp diff --git a/data_structures/matrix_graph_wrapper.hpp b/include/util/matrix_graph_wrapper.hpp similarity index 100% rename from data_structures/matrix_graph_wrapper.hpp rename to include/util/matrix_graph_wrapper.hpp diff --git a/util/mercator.hpp b/include/util/mercator.hpp similarity index 100% rename from util/mercator.hpp rename to include/util/mercator.hpp diff --git a/data_structures/node_based_graph.hpp b/include/util/node_based_graph.hpp similarity index 100% rename from data_structures/node_based_graph.hpp rename to include/util/node_based_graph.hpp diff --git a/util/osrm_exception.hpp b/include/util/osrm_exception.hpp similarity index 100% rename from util/osrm_exception.hpp rename to include/util/osrm_exception.hpp diff --git a/data_structures/percent.hpp b/include/util/percent.hpp similarity index 100% rename from data_structures/percent.hpp rename to include/util/percent.hpp diff --git a/util/range_algorithms.hpp b/include/util/range_algorithms.hpp similarity index 100% rename from util/range_algorithms.hpp rename to include/util/range_algorithms.hpp diff --git a/data_structures/range_table.hpp b/include/util/range_table.hpp similarity index 100% rename from data_structures/range_table.hpp rename to include/util/range_table.hpp diff --git a/data_structures/rectangle.hpp b/include/util/rectangle.hpp similarity index 100% rename from data_structures/rectangle.hpp rename to include/util/rectangle.hpp diff --git a/util/routed_options.hpp b/include/util/routed_options.hpp similarity index 100% rename from util/routed_options.hpp rename to include/util/routed_options.hpp diff --git a/data_structures/shared_memory_vector_wrapper.hpp b/include/util/shared_memory_vector_wrapper.hpp similarity index 100% rename from data_structures/shared_memory_vector_wrapper.hpp rename to include/util/shared_memory_vector_wrapper.hpp diff --git a/util/simple_logger.hpp b/include/util/simple_logger.hpp similarity index 100% rename from util/simple_logger.hpp rename to include/util/simple_logger.hpp diff --git a/data_structures/static_graph.hpp b/include/util/static_graph.hpp similarity index 100% rename from data_structures/static_graph.hpp rename to include/util/static_graph.hpp diff --git a/data_structures/static_rtree.hpp b/include/util/static_rtree.hpp similarity index 100% rename from data_structures/static_rtree.hpp rename to include/util/static_rtree.hpp diff --git a/util/std_hash.hpp b/include/util/std_hash.hpp similarity index 100% rename from util/std_hash.hpp rename to include/util/std_hash.hpp diff --git a/util/string_util.hpp b/include/util/string_util.hpp similarity index 100% rename from util/string_util.hpp rename to include/util/string_util.hpp diff --git a/util/timing_util.hpp b/include/util/timing_util.hpp similarity index 100% rename from util/timing_util.hpp rename to include/util/timing_util.hpp diff --git a/data_structures/tribool.hpp b/include/util/tribool.hpp similarity index 100% rename from data_structures/tribool.hpp rename to include/util/tribool.hpp diff --git a/util/trigonometry_table.hpp b/include/util/trigonometry_table.hpp similarity index 100% rename from util/trigonometry_table.hpp rename to include/util/trigonometry_table.hpp diff --git a/typedefs.h b/include/util/typedefs.hpp similarity index 100% rename from typedefs.h rename to include/util/typedefs.hpp diff --git a/util/version.hpp.in b/include/util/version.hpp.in similarity index 100% rename from util/version.hpp.in rename to include/util/version.hpp.in diff --git a/util/xml_renderer.hpp b/include/util/xml_renderer.hpp similarity index 100% rename from util/xml_renderer.hpp rename to include/util/xml_renderer.hpp diff --git a/data_structures/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp similarity index 100% rename from data_structures/xor_fast_hash.hpp rename to include/util/xor_fast_hash.hpp diff --git a/data_structures/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp similarity index 100% rename from data_structures/xor_fast_hash_storage.hpp rename to include/util/xor_fast_hash_storage.hpp diff --git a/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp similarity index 100% rename from benchmarks/static_rtree.cpp rename to src/benchmarks/static_rtree.cpp diff --git a/contractor/contractor_options.cpp b/src/contractor/contractor_options.cpp similarity index 100% rename from contractor/contractor_options.cpp rename to src/contractor/contractor_options.cpp diff --git a/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp similarity index 100% rename from contractor/processing_chain.cpp rename to src/contractor/processing_chain.cpp diff --git a/descriptors/description_factory.cpp b/src/engine/descriptors/description_factory.cpp similarity index 100% rename from descriptors/description_factory.cpp rename to src/engine/descriptors/description_factory.cpp diff --git a/algorithms/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp similarity index 100% rename from algorithms/douglas_peucker.cpp rename to src/engine/douglas_peucker.cpp diff --git a/library/osrm_impl.cpp b/src/engine/osrm_impl.cpp similarity index 100% rename from library/osrm_impl.cpp rename to src/engine/osrm_impl.cpp diff --git a/data_structures/phantom_node.cpp b/src/engine/phantom_node.cpp similarity index 100% rename from data_structures/phantom_node.cpp rename to src/engine/phantom_node.cpp diff --git a/algorithms/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp similarity index 100% rename from algorithms/polyline_compressor.cpp rename to src/engine/polyline_compressor.cpp diff --git a/algorithms/polyline_formatter.cpp b/src/engine/polyline_formatter.cpp similarity index 100% rename from algorithms/polyline_formatter.cpp rename to src/engine/polyline_formatter.cpp diff --git a/data_structures/route_parameters.cpp b/src/engine/route_parameters.cpp similarity index 100% rename from data_structures/route_parameters.cpp rename to src/engine/route_parameters.cpp diff --git a/data_structures/search_engine_data.cpp b/src/engine/search_engine_data.cpp similarity index 100% rename from data_structures/search_engine_data.cpp rename to src/engine/search_engine_data.cpp diff --git a/data_structures/compressed_edge_container.cpp b/src/extractor/compressed_edge_container.cpp similarity index 100% rename from data_structures/compressed_edge_container.cpp rename to src/extractor/compressed_edge_container.cpp diff --git a/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp similarity index 100% rename from extractor/edge_based_graph_factory.cpp rename to src/extractor/edge_based_graph_factory.cpp diff --git a/data_structures/external_memory_node.cpp b/src/extractor/external_memory_node.cpp similarity index 100% rename from data_structures/external_memory_node.cpp rename to src/extractor/external_memory_node.cpp diff --git a/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp similarity index 100% rename from extractor/extraction_containers.cpp rename to src/extractor/extraction_containers.cpp diff --git a/extractor/extractor.cpp b/src/extractor/extractor.cpp similarity index 100% rename from extractor/extractor.cpp rename to src/extractor/extractor.cpp diff --git a/extractor/extractor_callbacks.cpp b/src/extractor/extractor_callbacks.cpp similarity index 100% rename from extractor/extractor_callbacks.cpp rename to src/extractor/extractor_callbacks.cpp diff --git a/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp similarity index 100% rename from extractor/extractor_options.cpp rename to src/extractor/extractor_options.cpp diff --git a/algorithms/graph_compressor.cpp b/src/extractor/graph_compressor.cpp similarity index 100% rename from algorithms/graph_compressor.cpp rename to src/extractor/graph_compressor.cpp diff --git a/data_structures/import_edge.cpp b/src/extractor/import_edge.cpp similarity index 100% rename from data_structures/import_edge.cpp rename to src/extractor/import_edge.cpp diff --git a/data_structures/raster_source.cpp b/src/extractor/raster_source.cpp similarity index 100% rename from data_structures/raster_source.cpp rename to src/extractor/raster_source.cpp diff --git a/data_structures/restriction_map.cpp b/src/extractor/restriction_map.cpp similarity index 100% rename from data_structures/restriction_map.cpp rename to src/extractor/restriction_map.cpp diff --git a/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp similarity index 100% rename from extractor/restriction_parser.cpp rename to src/extractor/restriction_parser.cpp diff --git a/extractor/scripting_environment.cpp b/src/extractor/scripting_environment.cpp similarity index 100% rename from extractor/scripting_environment.cpp rename to src/extractor/scripting_environment.cpp diff --git a/server/connection.cpp b/src/server/connection.cpp similarity index 100% rename from server/connection.cpp rename to src/server/connection.cpp diff --git a/server/http/reply.cpp b/src/server/http/reply.cpp similarity index 100% rename from server/http/reply.cpp rename to src/server/http/reply.cpp diff --git a/server/request_handler.cpp b/src/server/request_handler.cpp similarity index 100% rename from server/request_handler.cpp rename to src/server/request_handler.cpp diff --git a/server/request_parser.cpp b/src/server/request_parser.cpp similarity index 100% rename from server/request_parser.cpp rename to src/server/request_parser.cpp diff --git a/tools/.gitignore b/src/tools/.gitignore similarity index 100% rename from tools/.gitignore rename to src/tools/.gitignore diff --git a/tools/check-hsgr.cpp b/src/tools/check-hsgr.cpp similarity index 100% rename from tools/check-hsgr.cpp rename to src/tools/check-hsgr.cpp diff --git a/tools/components.cpp b/src/tools/components.cpp similarity index 100% rename from tools/components.cpp rename to src/tools/components.cpp diff --git a/prepare.cpp b/src/tools/contract.cpp similarity index 100% rename from prepare.cpp rename to src/tools/contract.cpp diff --git a/datastore.cpp b/src/tools/datastore.cpp similarity index 100% rename from datastore.cpp rename to src/tools/datastore.cpp diff --git a/extract.cpp b/src/tools/extract.cpp similarity index 100% rename from extract.cpp rename to src/tools/extract.cpp diff --git a/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp similarity index 100% rename from tools/io-benchmark.cpp rename to src/tools/io-benchmark.cpp diff --git a/routed.cpp b/src/tools/routed.cpp similarity index 100% rename from routed.cpp rename to src/tools/routed.cpp diff --git a/tools/simpleclient.cpp b/src/tools/simpleclient.cpp similarity index 100% rename from tools/simpleclient.cpp rename to src/tools/simpleclient.cpp diff --git a/tools/springclean.cpp b/src/tools/springclean.cpp similarity index 100% rename from tools/springclean.cpp rename to src/tools/springclean.cpp diff --git a/tools/unlock_all_mutexes.cpp b/src/tools/unlock_all_mutexes.cpp similarity index 100% rename from tools/unlock_all_mutexes.cpp rename to src/tools/unlock_all_mutexes.cpp diff --git a/util/compute_angle.cpp b/src/util/compute_angle.cpp similarity index 100% rename from util/compute_angle.cpp rename to src/util/compute_angle.cpp diff --git a/data_structures/coordinate.cpp b/src/util/coordinate.cpp similarity index 100% rename from data_structures/coordinate.cpp rename to src/util/coordinate.cpp diff --git a/algorithms/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp similarity index 100% rename from algorithms/coordinate_calculation.cpp rename to src/util/coordinate_calculation.cpp diff --git a/util/fingerprint.cpp b/src/util/fingerprint.cpp similarity index 100% rename from util/fingerprint.cpp rename to src/util/fingerprint.cpp diff --git a/data_structures/hilbert_value.cpp b/src/util/hilbert_value.cpp similarity index 100% rename from data_structures/hilbert_value.cpp rename to src/util/hilbert_value.cpp diff --git a/util/mercator.cpp b/src/util/mercator.cpp similarity index 100% rename from util/mercator.cpp rename to src/util/mercator.cpp diff --git a/util/osrm_exception.cpp b/src/util/osrm_exception.cpp similarity index 100% rename from util/osrm_exception.cpp rename to src/util/osrm_exception.cpp diff --git a/util/simple_logger.cpp b/src/util/simple_logger.cpp similarity index 100% rename from util/simple_logger.cpp rename to src/util/simple_logger.cpp From 078f71c14411d13cd5520b772064616738298962 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sat, 2 Jan 2016 17:24:46 +0100 Subject: [PATCH 004/701] Move files in unit_tests around --- unit_tests/{algorithms => engine}/douglas_peucker.cpp | 0 unit_tests/{algorithms => engine}/geometry_string.cpp | 0 unit_tests/{algorithm_tests.cpp => engine_tests.cpp} | 2 +- .../compressed_edge_container.cpp | 0 unit_tests/{algorithms => extractor}/graph_compressor.cpp | 0 unit_tests/{data_structures => extractor}/raster_source.cpp | 0 unit_tests/{datastructure_tests.cpp => extractor_tests.cpp} | 2 +- unit_tests/{data_structures => util}/binary_heap.cpp | 0 unit_tests/{data_structures => util}/coordinate.cpp | 0 unit_tests/{algorithms => util}/duration_parsing.cpp | 0 unit_tests/{data_structures => util}/dynamic_graph.cpp | 0 unit_tests/{data_structures => util}/range_table.cpp | 0 unit_tests/{data_structures => util}/static_graph.cpp | 0 unit_tests/{data_structures => util}/static_rtree.cpp | 0 unit_tests/{algorithms => util}/string_util.cpp | 0 15 files changed, 2 insertions(+), 2 deletions(-) rename unit_tests/{algorithms => engine}/douglas_peucker.cpp (100%) rename unit_tests/{algorithms => engine}/geometry_string.cpp (100%) rename unit_tests/{algorithm_tests.cpp => engine_tests.cpp} (97%) rename unit_tests/{data_structures => extractor}/compressed_edge_container.cpp (100%) rename unit_tests/{algorithms => extractor}/graph_compressor.cpp (100%) rename unit_tests/{data_structures => extractor}/raster_source.cpp (100%) rename unit_tests/{datastructure_tests.cpp => extractor_tests.cpp} (96%) rename unit_tests/{data_structures => util}/binary_heap.cpp (100%) rename unit_tests/{data_structures => util}/coordinate.cpp (100%) rename unit_tests/{algorithms => util}/duration_parsing.cpp (100%) rename unit_tests/{data_structures => util}/dynamic_graph.cpp (100%) rename unit_tests/{data_structures => util}/range_table.cpp (100%) rename unit_tests/{data_structures => util}/static_graph.cpp (100%) rename unit_tests/{data_structures => util}/static_rtree.cpp (100%) rename unit_tests/{algorithms => util}/string_util.cpp (100%) diff --git a/unit_tests/algorithms/douglas_peucker.cpp b/unit_tests/engine/douglas_peucker.cpp similarity index 100% rename from unit_tests/algorithms/douglas_peucker.cpp rename to unit_tests/engine/douglas_peucker.cpp diff --git a/unit_tests/algorithms/geometry_string.cpp b/unit_tests/engine/geometry_string.cpp similarity index 100% rename from unit_tests/algorithms/geometry_string.cpp rename to unit_tests/engine/geometry_string.cpp diff --git a/unit_tests/algorithm_tests.cpp b/unit_tests/engine_tests.cpp similarity index 97% rename from unit_tests/algorithm_tests.cpp rename to unit_tests/engine_tests.cpp index 0a9f3fdff..1a2f88ed0 100644 --- a/unit_tests/algorithm_tests.cpp +++ b/unit_tests/engine_tests.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#define BOOST_TEST_MODULE algorithm tests +#define BOOST_TEST_MODULE engine tests #include diff --git a/unit_tests/data_structures/compressed_edge_container.cpp b/unit_tests/extractor/compressed_edge_container.cpp similarity index 100% rename from unit_tests/data_structures/compressed_edge_container.cpp rename to unit_tests/extractor/compressed_edge_container.cpp diff --git a/unit_tests/algorithms/graph_compressor.cpp b/unit_tests/extractor/graph_compressor.cpp similarity index 100% rename from unit_tests/algorithms/graph_compressor.cpp rename to unit_tests/extractor/graph_compressor.cpp diff --git a/unit_tests/data_structures/raster_source.cpp b/unit_tests/extractor/raster_source.cpp similarity index 100% rename from unit_tests/data_structures/raster_source.cpp rename to unit_tests/extractor/raster_source.cpp diff --git a/unit_tests/datastructure_tests.cpp b/unit_tests/extractor_tests.cpp similarity index 96% rename from unit_tests/datastructure_tests.cpp rename to unit_tests/extractor_tests.cpp index 850d61910..25bc11dff 100644 --- a/unit_tests/datastructure_tests.cpp +++ b/unit_tests/extractor_tests.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#define BOOST_TEST_MODULE datastructure tests +#define BOOST_TEST_MODULE extractor tests #include diff --git a/unit_tests/data_structures/binary_heap.cpp b/unit_tests/util/binary_heap.cpp similarity index 100% rename from unit_tests/data_structures/binary_heap.cpp rename to unit_tests/util/binary_heap.cpp diff --git a/unit_tests/data_structures/coordinate.cpp b/unit_tests/util/coordinate.cpp similarity index 100% rename from unit_tests/data_structures/coordinate.cpp rename to unit_tests/util/coordinate.cpp diff --git a/unit_tests/algorithms/duration_parsing.cpp b/unit_tests/util/duration_parsing.cpp similarity index 100% rename from unit_tests/algorithms/duration_parsing.cpp rename to unit_tests/util/duration_parsing.cpp diff --git a/unit_tests/data_structures/dynamic_graph.cpp b/unit_tests/util/dynamic_graph.cpp similarity index 100% rename from unit_tests/data_structures/dynamic_graph.cpp rename to unit_tests/util/dynamic_graph.cpp diff --git a/unit_tests/data_structures/range_table.cpp b/unit_tests/util/range_table.cpp similarity index 100% rename from unit_tests/data_structures/range_table.cpp rename to unit_tests/util/range_table.cpp diff --git a/unit_tests/data_structures/static_graph.cpp b/unit_tests/util/static_graph.cpp similarity index 100% rename from unit_tests/data_structures/static_graph.cpp rename to unit_tests/util/static_graph.cpp diff --git a/unit_tests/data_structures/static_rtree.cpp b/unit_tests/util/static_rtree.cpp similarity index 100% rename from unit_tests/data_structures/static_rtree.cpp rename to unit_tests/util/static_rtree.cpp diff --git a/unit_tests/algorithms/string_util.cpp b/unit_tests/util/string_util.cpp similarity index 100% rename from unit_tests/algorithms/string_util.cpp rename to unit_tests/util/string_util.cpp From d936009ea1e028f25bae4c1ab16440e895b2685b Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sat, 2 Jan 2016 14:44:47 +0100 Subject: [PATCH 005/701] DOS -> UNIX file format --- src/extractor/restriction_parser.cpp | 512 +++++++++++++-------------- 1 file changed, 256 insertions(+), 256 deletions(-) diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index a3c2a5d25..6a54cde20 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -1,256 +1,256 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#include "restriction_parser.hpp" -#include "extraction_way.hpp" - -#include "../data_structures/external_memory_node.hpp" -#include "../util/lua_util.hpp" -#include "../util/osrm_exception.hpp" -#include "../util/simple_logger.hpp" - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -namespace -{ -int lua_error_callback(lua_State *lua_state) -{ - std::string error_msg = lua_tostring(lua_state, -1); - throw osrm::exception("ERROR occurred in profile script:\n" + error_msg); -} -} - -RestrictionParser::RestrictionParser(lua_State *lua_state) : use_turn_restrictions(true) -{ - ReadUseRestrictionsSetting(lua_state); - - if (use_turn_restrictions) - { - ReadRestrictionExceptions(lua_state); - } -} - -void RestrictionParser::ReadUseRestrictionsSetting(lua_State *lua_state) -{ - if (0 == luaL_dostring(lua_state, "return use_turn_restrictions\n") && - lua_isboolean(lua_state, -1)) - { - use_turn_restrictions = lua_toboolean(lua_state, -1); - } - - if (use_turn_restrictions) - { - SimpleLogger().Write() << "Using turn restrictions"; - } - else - { - SimpleLogger().Write() << "Ignoring turn restrictions"; - } -} - -void RestrictionParser::ReadRestrictionExceptions(lua_State *lua_state) -{ - if (lua_function_exists(lua_state, "get_exceptions")) - { - luabind::set_pcall_callback(&lua_error_callback); - // get list of turn restriction exceptions - luabind::call_function(lua_state, "get_exceptions", - boost::ref(restriction_exceptions)); - const unsigned exception_count = restriction_exceptions.size(); - SimpleLogger().Write() << "Found " << exception_count - << " exceptions to turn restrictions:"; - for (const std::string &str : restriction_exceptions) - { - SimpleLogger().Write() << " " << str; - } - } - else - { - SimpleLogger().Write() << "Found no exceptions to turn restrictions"; - } -} - -/** - * Tries to parse an relation as turn restriction. This can fail for a number of - * reasons, this the return type is a boost::optional. - * - * Some restrictions can also be ignored: See the ```get_exceptions``` function - * in the corresponding profile. - */ -boost::optional -RestrictionParser::TryParse(const osmium::Relation &relation) const -{ - // return if turn restrictions should be ignored - if (!use_turn_restrictions) - { - return {}; - } - - osmium::tags::KeyPrefixFilter filter(false); - filter.add(true, "restriction"); - - const osmium::TagList &tag_list = relation.tags(); - - osmium::tags::KeyPrefixFilter::iterator fi_begin(filter, tag_list.begin(), tag_list.end()); - osmium::tags::KeyPrefixFilter::iterator fi_end(filter, tag_list.end(), tag_list.end()); - - // if it's a restriction, continue; - if (std::distance(fi_begin, fi_end) == 0) - { - return {}; - } - - // check if the restriction should be ignored - const char *except = relation.get_value_by_key("except"); - if (except != nullptr && ShouldIgnoreRestriction(except)) - { - return {}; - } - - bool is_only_restriction = false; - - for (; fi_begin != fi_end; ++fi_begin) - { - const std::string key(fi_begin->key()); - const std::string value(fi_begin->value()); - - if (value.find("only_") == 0) - { - is_only_restriction = true; - } - - // if the "restriction*" key is longer than 11 chars, it is a conditional exception (i.e. - // "restriction:") - if (key.size() > 11) - { - const auto ex_suffix = [&](const std::string &exception) - { - return boost::algorithm::ends_with(key, exception); - }; - bool is_actually_restricted = - std::any_of(begin(restriction_exceptions), end(restriction_exceptions), ex_suffix); - - if (!is_actually_restricted) - { - return {}; - } - } - } - - InputRestrictionContainer restriction_container(is_only_restriction); - - for (const auto &member : relation.members()) - { - const char *role = member.role(); - if (strcmp("from", role) != 0 && strcmp("to", role) != 0 && strcmp("via", role) != 0) - { - continue; - } - - switch (member.type()) - { - case osmium::item_type::node: - // Make sure nodes appear only in the role if a via node - if (0 == strcmp("from", role) || 0 == strcmp("to", role)) - { - continue; - } - BOOST_ASSERT(0 == strcmp("via", role)); - - // set via node id - restriction_container.restriction.via.node = member.ref(); - break; - - case osmium::item_type::way: - BOOST_ASSERT(0 == strcmp("from", role) || 0 == strcmp("to", role) || - 0 == strcmp("via", role)); - if (0 == strcmp("from", role)) - { - restriction_container.restriction.from.way = member.ref(); - } - else if (0 == strcmp("to", role)) - { - restriction_container.restriction.to.way = member.ref(); - } - // else if (0 == strcmp("via", role)) - // { - // not yet suppported - // restriction_container.restriction.via.way = member.ref(); - // } - break; - case osmium::item_type::relation: - // not yet supported, but who knows what the future holds... - break; - default: - // shouldn't ever happen - break; - } - } - return boost::make_optional(std::move(restriction_container)); -} - -bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_string) const -{ - // should this restriction be ignored? yes if there's an overlap between: - // a) the list of modes in the except tag of the restriction - // (except_tag_string), eg: except=bus;bicycle - // b) the lua profile defines a hierachy of modes, - // eg: [access, vehicle, bicycle] - - if (except_tag_string.empty()) - { - return false; - } - - // Be warned, this is quadratic work here, but we assume that - // only a few exceptions are actually defined. - std::vector exceptions; - boost::algorithm::split_regex(exceptions, except_tag_string, boost::regex("[;][ ]*")); - - return std::any_of(std::begin(exceptions), std::end(exceptions), - [&](const std::string ¤t_string) - { - if (std::end(restriction_exceptions) != - std::find(std::begin(restriction_exceptions), - std::end(restriction_exceptions), current_string)) - { - return true; - } - return false; - }); -} +/* + +Copyright (c) 2015, Project OSRM contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include "restriction_parser.hpp" +#include "extraction_way.hpp" + +#include "../data_structures/external_memory_node.hpp" +#include "../util/lua_util.hpp" +#include "../util/osrm_exception.hpp" +#include "../util/simple_logger.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace +{ +int lua_error_callback(lua_State *lua_state) +{ + std::string error_msg = lua_tostring(lua_state, -1); + throw osrm::exception("ERROR occurred in profile script:\n" + error_msg); +} +} + +RestrictionParser::RestrictionParser(lua_State *lua_state) : use_turn_restrictions(true) +{ + ReadUseRestrictionsSetting(lua_state); + + if (use_turn_restrictions) + { + ReadRestrictionExceptions(lua_state); + } +} + +void RestrictionParser::ReadUseRestrictionsSetting(lua_State *lua_state) +{ + if (0 == luaL_dostring(lua_state, "return use_turn_restrictions\n") && + lua_isboolean(lua_state, -1)) + { + use_turn_restrictions = lua_toboolean(lua_state, -1); + } + + if (use_turn_restrictions) + { + SimpleLogger().Write() << "Using turn restrictions"; + } + else + { + SimpleLogger().Write() << "Ignoring turn restrictions"; + } +} + +void RestrictionParser::ReadRestrictionExceptions(lua_State *lua_state) +{ + if (lua_function_exists(lua_state, "get_exceptions")) + { + luabind::set_pcall_callback(&lua_error_callback); + // get list of turn restriction exceptions + luabind::call_function(lua_state, "get_exceptions", + boost::ref(restriction_exceptions)); + const unsigned exception_count = restriction_exceptions.size(); + SimpleLogger().Write() << "Found " << exception_count + << " exceptions to turn restrictions:"; + for (const std::string &str : restriction_exceptions) + { + SimpleLogger().Write() << " " << str; + } + } + else + { + SimpleLogger().Write() << "Found no exceptions to turn restrictions"; + } +} + +/** + * Tries to parse an relation as turn restriction. This can fail for a number of + * reasons, this the return type is a boost::optional. + * + * Some restrictions can also be ignored: See the ```get_exceptions``` function + * in the corresponding profile. + */ +boost::optional +RestrictionParser::TryParse(const osmium::Relation &relation) const +{ + // return if turn restrictions should be ignored + if (!use_turn_restrictions) + { + return {}; + } + + osmium::tags::KeyPrefixFilter filter(false); + filter.add(true, "restriction"); + + const osmium::TagList &tag_list = relation.tags(); + + osmium::tags::KeyPrefixFilter::iterator fi_begin(filter, tag_list.begin(), tag_list.end()); + osmium::tags::KeyPrefixFilter::iterator fi_end(filter, tag_list.end(), tag_list.end()); + + // if it's a restriction, continue; + if (std::distance(fi_begin, fi_end) == 0) + { + return {}; + } + + // check if the restriction should be ignored + const char *except = relation.get_value_by_key("except"); + if (except != nullptr && ShouldIgnoreRestriction(except)) + { + return {}; + } + + bool is_only_restriction = false; + + for (; fi_begin != fi_end; ++fi_begin) + { + const std::string key(fi_begin->key()); + const std::string value(fi_begin->value()); + + if (value.find("only_") == 0) + { + is_only_restriction = true; + } + + // if the "restriction*" key is longer than 11 chars, it is a conditional exception (i.e. + // "restriction:") + if (key.size() > 11) + { + const auto ex_suffix = [&](const std::string &exception) + { + return boost::algorithm::ends_with(key, exception); + }; + bool is_actually_restricted = + std::any_of(begin(restriction_exceptions), end(restriction_exceptions), ex_suffix); + + if (!is_actually_restricted) + { + return {}; + } + } + } + + InputRestrictionContainer restriction_container(is_only_restriction); + + for (const auto &member : relation.members()) + { + const char *role = member.role(); + if (strcmp("from", role) != 0 && strcmp("to", role) != 0 && strcmp("via", role) != 0) + { + continue; + } + + switch (member.type()) + { + case osmium::item_type::node: + // Make sure nodes appear only in the role if a via node + if (0 == strcmp("from", role) || 0 == strcmp("to", role)) + { + continue; + } + BOOST_ASSERT(0 == strcmp("via", role)); + + // set via node id + restriction_container.restriction.via.node = member.ref(); + break; + + case osmium::item_type::way: + BOOST_ASSERT(0 == strcmp("from", role) || 0 == strcmp("to", role) || + 0 == strcmp("via", role)); + if (0 == strcmp("from", role)) + { + restriction_container.restriction.from.way = member.ref(); + } + else if (0 == strcmp("to", role)) + { + restriction_container.restriction.to.way = member.ref(); + } + // else if (0 == strcmp("via", role)) + // { + // not yet suppported + // restriction_container.restriction.via.way = member.ref(); + // } + break; + case osmium::item_type::relation: + // not yet supported, but who knows what the future holds... + break; + default: + // shouldn't ever happen + break; + } + } + return boost::make_optional(std::move(restriction_container)); +} + +bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_string) const +{ + // should this restriction be ignored? yes if there's an overlap between: + // a) the list of modes in the except tag of the restriction + // (except_tag_string), eg: except=bus;bicycle + // b) the lua profile defines a hierachy of modes, + // eg: [access, vehicle, bicycle] + + if (except_tag_string.empty()) + { + return false; + } + + // Be warned, this is quadratic work here, but we assume that + // only a few exceptions are actually defined. + std::vector exceptions; + boost::algorithm::split_regex(exceptions, except_tag_string, boost::regex("[;][ ]*")); + + return std::any_of(std::begin(exceptions), std::end(exceptions), + [&](const std::string ¤t_string) + { + if (std::end(restriction_exceptions) != + std::find(std::begin(restriction_exceptions), + std::end(restriction_exceptions), current_string)) + { + return true; + } + return false; + }); +} From b618a1241f3250eb945c936eb5fae50526a87b5e Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sat, 2 Jan 2016 16:11:49 +0100 Subject: [PATCH 006/701] Adapt build system --- CMakeLists.txt | 121 +++++++++++++++------------------ cmake/FingerPrint-Config.cmake | 12 ++-- 2 files changed, 59 insertions(+), 74 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b8fecc577..67bd60ded 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,8 +33,7 @@ option(ENABLE_JSON_LOGGING "Adds additional JSON debug logging to the response" option(DEBUG_GEOMETRY "Enables an option to dump GeoJSON of the final routing graph" OFF) option(BUILD_TOOLS "Build OSRM tools" OFF) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}) -include_directories(${CMAKE_CURRENT_BINARY_DIR}) +include_directories(${CMAKE_CURRENT_BINARY_DIR}/include/) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/) include_directories(SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/third_party/) include_directories(SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/third_party/libosmium/include/) @@ -46,74 +45,50 @@ add_custom_target(FingerPrintConfigure ALL ${CMAKE_COMMAND} COMMENT "Configuring revision fingerprint" VERBATIM) -add_custom_target(tests DEPENDS datastructure-tests algorithm-tests util-tests) +add_custom_target(tests DEPENDS engine-tests extractor-tests util-tests) add_custom_target(benchmarks DEPENDS rtree-bench) set(BOOST_COMPONENTS date_time filesystem iostreams program_options regex system thread unit_test_framework) configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/util/version.hpp.in - ${CMAKE_CURRENT_BINARY_DIR}/util/version.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/include/util/version.hpp.in + ${CMAKE_CURRENT_BINARY_DIR}/include/util/version.hpp ) -file(GLOB ExtractorGlob extractor/*.cpp data_structures/hilbert_value.cpp) -file(GLOB ImporterGlob data_structures/import_edge.cpp data_structures/external_memory_node.cpp data_structures/raster_source.cpp) -add_library(IMPORT OBJECT ${ImporterGlob}) -add_library(LOGGER OBJECT util/simple_logger.cpp) -add_library(PHANTOMNODE OBJECT data_structures/phantom_node.cpp) -add_library(RASTERSOURCE OBJECT data_structures/raster_source.cpp) -add_library(EXCEPTION OBJECT util/osrm_exception.cpp) -add_library(MERCATOR OBJECT util/mercator.cpp) -add_library(ANGLE OBJECT util/compute_angle.cpp) - -set(ExtractorSources extract.cpp ${ExtractorGlob}) -add_executable(osrm-extract ${ExtractorSources} $ $ $ $ $ $ $ $ $ $) - -add_library(RESTRICTION OBJECT data_structures/restriction_map.cpp) -add_library(COMPRESSEDEDGE OBJECT data_structures/compressed_edge_container.cpp) -add_library(GRAPHCOMPRESSOR OBJECT algorithms/graph_compressor.cpp) - -file(GLOB PrepareGlob contractor/*.cpp data_structures/hilbert_value.cpp {RestrictionMapGlob}) -set(PrepareSources prepare.cpp ${PrepareGlob}) -add_executable(osrm-prepare ${PrepareSources} $ $ $ $ $ $ $ $ $ $) - -file(GLOB ServerGlob server/*.cpp) -file(GLOB DescriptorGlob descriptors/*.cpp) -file(GLOB DatastructureGlob data_structures/search_engine_data.cpp data_structures/route_parameters.cpp util/bearing.cpp) -file(GLOB CoordinateGlob data_structures/coordinate.cpp algorithms/coordinate_calculation.cpp) -file(GLOB AlgorithmGlob algorithms/polyline_compressor.cpp algorithms/polyline_formatter.cpp algorithms/douglas_peucker.cpp) -file(GLOB HttpGlob server/http/*.cpp) -file(GLOB LibOSRMGlob library/*.cpp) -file(GLOB DataStructureTestsGlob unit_tests/data_structures/*.cpp data_structures/hilbert_value.cpp) -file(GLOB AlgorithmTestsGlob unit_tests/algorithms/*.cpp algorithms/graph_compressor.cpp) +file(GLOB UtilGlob src/util/*.cpp) +file(GLOB ExtractorGlob src/extractor/*.cpp) +file(GLOB ContractorGlob src/contractor/*.cpp) +file(GLOB ServerGlob src/server/*.cpp src/server/**/*.cpp) +file(GLOB EngineGlob src/engine/*.cpp src/engine/**/*.cpp) +file(GLOB ExtractorTestsGlob unit_tests/extractor/*.cpp) +file(GLOB EngineTestsGlob unit_tests/engine/*.cpp) file(GLOB UtilTestsGlob unit_tests/util/*.cpp) -set( - OSRMSources - ${LibOSRMGlob} - ${DescriptorGlob} - ${DatastructureGlob} - ${AlgorithmGlob} - ${HttpGlob} -) +add_library(UTIL OBJECT ${UtilGlob}) +add_library(EXTRACTOR OBJECT ${ExtractorGlob}) +add_library(CONTRACTOR OBJECT ${ContractorGlob}) +add_library(ENGINE OBJECT ${EngineGlob}) +add_library(SERVER OBJECT ${ServerGlob}) +add_library(GRAPH OBJECT src/extractor/external_memory_node.cpp src/extractor/import_edge.cpp) +add_library(PHANTOM OBJECT src/engine/phantom_node.cpp) -add_library(COORDINATE OBJECT ${CoordinateGlob}) -add_library(OSRM ${OSRMSources} $ $ $ $ $ $ $ $ $) +add_dependencies(UTIL FingerPrintConfigure) +set_target_properties(UTIL PROPERTIES LINKER_LANGUAGE CXX) -add_library(FINGERPRINT OBJECT util/fingerprint.cpp) -add_dependencies(FINGERPRINT FingerPrintConfigure) -add_dependencies(OSRM FingerPrintConfigure) -set_target_properties(FINGERPRINT PROPERTIES LINKER_LANGUAGE CXX) +add_executable(osrm-extract src/tools/extract.cpp $ $) +add_executable(osrm-prepare src/tools/contract.cpp $ $ $) +add_executable(osrm-routed src/tools/routed.cpp $ $ $) +add_executable(osrm-datastore src/tools/datastore.cpp $ $) +add_library(OSRM $ $ $) -add_executable(osrm-routed routed.cpp ${ServerGlob} $) -add_executable(osrm-datastore datastore.cpp $ $ $ $ $) +target_link_libraries(osrm-routed OSRM) # Unit tests -add_executable(datastructure-tests EXCLUDE_FROM_ALL unit_tests/datastructure_tests.cpp ${DataStructureTestsGlob} $ $ $ $ $ $ $ $ $) -add_executable(algorithm-tests EXCLUDE_FROM_ALL unit_tests/algorithm_tests.cpp ${AlgorithmTestsGlob} $ $ $ $ $ $) -add_executable(util-tests EXCLUDE_FROM_ALL unit_tests/util_tests.cpp ${UtilTestsGlob}) +add_executable(engine-tests EXCLUDE_FROM_ALL unit_tests/engine_tests.cpp ${EngineTestsGlob} $ $ $) +add_executable(extractor-tests EXCLUDE_FROM_ALL unit_tests/extractor_tests.cpp ${ExtractorTestsGlob} $ $) +add_executable(util-tests EXCLUDE_FROM_ALL unit_tests/util_tests.cpp ${UtilTestsGlob} $ $) # Benchmarks -add_executable(rtree-bench EXCLUDE_FROM_ALL benchmarks/static_rtree.cpp $ $ $ $ $) +add_executable(rtree-bench EXCLUDE_FROM_ALL src/benchmarks/static_rtree.cpp $ $) # Check the release mode if(NOT CMAKE_BUILD_TYPE MATCHES Debug) @@ -248,6 +223,7 @@ if(UNIX AND NOT APPLE) target_link_libraries(osrm-prepare rt) target_link_libraries(osrm-datastore rt) target_link_libraries(OSRM rt) + target_link_libraries(engine-tests rt) endif() #Check Boost @@ -262,8 +238,8 @@ target_link_libraries(osrm-extract ${Boost_LIBRARIES}) target_link_libraries(osrm-prepare ${Boost_LIBRARIES}) target_link_libraries(osrm-routed ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM) target_link_libraries(osrm-datastore ${Boost_LIBRARIES}) -target_link_libraries(datastructure-tests ${Boost_LIBRARIES}) -target_link_libraries(algorithm-tests ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM) +target_link_libraries(engine-tests ${Boost_LIBRARIES}) +target_link_libraries(extractor-tests ${Boost_LIBRARIES}) target_link_libraries(util-tests ${Boost_LIBRARIES}) target_link_libraries(rtree-bench ${Boost_LIBRARIES}) @@ -272,8 +248,9 @@ target_link_libraries(osrm-extract ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(osrm-datastore ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(osrm-prepare ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(OSRM ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(datastructure-tests ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(algorithm-tests ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(engine-tests ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(extractor-tests ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(util-tests ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(rtree-bench ${CMAKE_THREAD_LIBS_INIT}) find_package(TBB REQUIRED) @@ -284,8 +261,9 @@ target_link_libraries(osrm-datastore ${TBB_LIBRARIES}) target_link_libraries(osrm-extract ${TBB_LIBRARIES}) target_link_libraries(osrm-prepare ${TBB_LIBRARIES}) target_link_libraries(osrm-routed ${TBB_LIBRARIES}) -target_link_libraries(datastructure-tests ${TBB_LIBRARIES}) -target_link_libraries(algorithm-tests ${TBB_LIBRARIES}) +target_link_libraries(engine-tests ${TBB_LIBRARIES}) +target_link_libraries(extractor-tests ${TBB_LIBRARIES}) +target_link_libraries(util-tests ${TBB_LIBRARIES}) target_link_libraries(rtree-bench ${TBB_LIBRARIES}) include_directories(SYSTEM ${TBB_INCLUDE_DIR}) @@ -295,26 +273,31 @@ include(check_luabind) include_directories(SYSTEM ${LUABIND_INCLUDE_DIR}) target_link_libraries(osrm-extract ${LUABIND_LIBRARY}) target_link_libraries(osrm-prepare ${LUABIND_LIBRARY}) +target_link_libraries(extractor-tests ${LUABIND_LIBRARY}) if(LUAJIT_FOUND) target_link_libraries(osrm-extract ${LUAJIT_LIBRARIES}) target_link_libraries(osrm-prepare ${LUAJIT_LIBRARIES}) + target_link_libraries(extractor-tests ${LUAJIT_LIBRARY}) else() target_link_libraries(osrm-extract ${LUA_LIBRARY}) target_link_libraries(osrm-prepare ${LUA_LIBRARY}) + target_link_libraries(extractor-tests ${LUA_LIBRARY}) endif() include_directories(SYSTEM ${LUA_INCLUDE_DIR}) find_package(EXPAT REQUIRED) include_directories(SYSTEM ${EXPAT_INCLUDE_DIRS}) target_link_libraries(osrm-extract ${EXPAT_LIBRARIES}) +target_link_libraries(extractor-tests ${EXPAT_LIBRARY}) find_package(STXXL REQUIRED) include_directories(SYSTEM ${STXXL_INCLUDE_DIR}) target_link_libraries(OSRM ${STXXL_LIBRARY}) target_link_libraries(osrm-extract ${STXXL_LIBRARY}) target_link_libraries(osrm-prepare ${STXXL_LIBRARY}) -target_link_libraries(datastructure-tests ${STXXL_LIBRARY}) +target_link_libraries(extractor-tests ${STXXL_LIBRARY}) +target_link_libraries(util-tests ${STXXL_LIBRARY}) set(OpenMP_FIND_QUIETLY ON) find_package(OpenMP) @@ -326,11 +309,13 @@ endif() find_package(BZip2 REQUIRED) include_directories(SYSTEM ${BZIP_INCLUDE_DIRS}) target_link_libraries(osrm-extract ${BZIP2_LIBRARIES}) +target_link_libraries(extractor-tests ${BZIP2_LIBRARIES}) find_package(ZLIB REQUIRED) include_directories(SYSTEM ${ZLIB_INCLUDE_DIRS}) target_link_libraries(osrm-extract ${ZLIB_LIBRARY}) target_link_libraries(osrm-routed ${ZLIB_LIBRARY}) +target_link_libraries(extractor-tests ${ZLIB_LIBRARY}) if (ENABLE_JSON_LOGGING) message(STATUS "Enabling json logging") @@ -346,7 +331,7 @@ if(BUILD_TOOLS) message(STATUS "Activating OSRM internal tools") find_package(GDAL) if(GDAL_FOUND) - add_executable(osrm-components tools/components.cpp $ $ $ $ $ $ $) + add_executable(osrm-components src/tools/components.cpp $ $) target_link_libraries(osrm-components ${TBB_LIBRARIES}) include_directories(SYSTEM ${GDAL_INCLUDE_DIR}) target_link_libraries(osrm-components ${GDAL_LIBRARIES} ${Boost_LIBRARIES}) @@ -354,19 +339,19 @@ if(BUILD_TOOLS) else() message(FATAL_ERROR "libgdal and/or development headers not found") endif() - add_executable(osrm-cli tools/simpleclient.cpp $ $ $) + add_executable(osrm-cli src/tools/simpleclient.cpp) target_link_libraries(osrm-cli ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM) target_link_libraries(osrm-cli ${TBB_LIBRARIES}) - add_executable(osrm-io-benchmark tools/io-benchmark.cpp $ $) + add_executable(osrm-io-benchmark src/tools/io-benchmark.cpp $) target_link_libraries(osrm-io-benchmark ${Boost_LIBRARIES}) - add_executable(osrm-unlock-all tools/unlock_all_mutexes.cpp $ $) + add_executable(osrm-unlock-all src/tools/unlock_all_mutexes.cpp $) target_link_libraries(osrm-unlock-all ${Boost_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) if(UNIX AND NOT APPLE) target_link_libraries(osrm-unlock-all rt) endif() - add_executable(osrm-check-hsgr tools/check-hsgr.cpp $ $ $ $) + add_executable(osrm-check-hsgr src/tools/check-hsgr.cpp $ $) target_link_libraries(osrm-check-hsgr ${Boost_LIBRARIES} ${TBB_LIBRARIES}) - add_executable(osrm-springclean tools/springclean.cpp $ $ $) + add_executable(osrm-springclean src/tools/springclean.cpp $ $) target_link_libraries(osrm-springclean ${Boost_LIBRARIES}) install(TARGETS osrm-cli DESTINATION bin) diff --git a/cmake/FingerPrint-Config.cmake b/cmake/FingerPrint-Config.cmake index d36b62274..0672b3402 100644 --- a/cmake/FingerPrint-Config.cmake +++ b/cmake/FingerPrint-Config.cmake @@ -1,10 +1,10 @@ -set(OLDFILE ${OUTPUT_DIR}/util/fingerprint_impl.hpp) +set(OLDFILE ${OUTPUT_DIR}/include/util/fingerprint_impl.hpp) set(NEWFILE ${OLDFILE}.tmp) -set(INFILE ${SOURCE_DIR}/util/fingerprint_impl.hpp.in) -file(MD5 ${SOURCE_DIR}/prepare.cpp MD5PREPARE) -file(MD5 ${SOURCE_DIR}/data_structures/static_rtree.hpp MD5RTREE) -file(MD5 ${SOURCE_DIR}/util/graph_loader.hpp MD5GRAPH) -file(MD5 ${SOURCE_DIR}/server/data_structures/internal_datafacade.hpp MD5OBJECTS) +set(INFILE ${SOURCE_DIR}/include/util/fingerprint_impl.hpp.in) +file(MD5 ${SOURCE_DIR}/src/tools/contract.cpp MD5PREPARE) +file(MD5 ${SOURCE_DIR}/include/util/static_rtree.hpp MD5RTREE) +file(MD5 ${SOURCE_DIR}/include/util/graph_loader.hpp MD5GRAPH) +file(MD5 ${SOURCE_DIR}/include/engine/datafacade/internal_datafacade.hpp MD5OBJECTS) CONFIGURE_FILE(${INFILE} ${NEWFILE}) From 97585bb26afe6098aecf0f36c0b0a523436f2d2d Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sat, 2 Jan 2016 17:13:44 +0100 Subject: [PATCH 007/701] Fix include paths --- include/contractor/contractor.hpp | 22 +++++----- include/contractor/processing_chain.hpp | 12 +++--- include/contractor/query_edge.hpp | 2 +- include/datastore/shared_memory_factory.hpp | 4 +- include/engine/datafacade/datafacade_base.hpp | 18 ++++----- .../engine/datafacade/internal_datafacade.hpp | 24 +++++------ .../engine/datafacade/shared_datafacade.hpp | 16 ++++---- include/engine/datafacade/shared_datatype.hpp | 4 +- .../descriptors/description_factory.hpp | 12 +++--- .../engine/descriptors/descriptor_base.hpp | 10 ++--- include/engine/descriptors/gpx_descriptor.hpp | 6 +-- .../engine/descriptors/json_descriptor.hpp | 28 ++++++------- include/engine/douglas_peucker.hpp | 2 +- include/engine/geospatial_query.hpp | 10 ++--- include/engine/internal_route_result.hpp | 10 ++--- .../map_matching/hidden_markov_model.hpp | 2 +- include/engine/osrm_impl.hpp | 8 ++-- include/engine/phantom_node.hpp | 6 +-- include/engine/plugins/distance_table.hpp | 20 +++++----- include/engine/plugins/hello_world.hpp | 6 +-- include/engine/plugins/match.hpp | 24 +++++------ include/engine/plugins/nearest.hpp | 10 ++--- include/engine/plugins/plugin_base.hpp | 8 ++-- include/engine/plugins/timestamp.hpp | 6 +-- include/engine/plugins/trip.hpp | 30 +++++++------- include/engine/plugins/viaroute.hpp | 24 +++++------ include/engine/polyline_compressor.hpp | 2 +- include/engine/polyline_formatter.hpp | 2 +- .../routing_algorithms/alternative_path.hpp | 8 ++-- .../direct_shortest_path.hpp | 10 ++--- .../routing_algorithms/many_to_many.hpp | 6 +-- .../routing_algorithms/map_matching.hpp | 10 ++--- .../routing_algorithms/routing_base.hpp | 8 ++-- .../routing_algorithms/shortest_path.hpp | 8 ++-- include/engine/search_engine.hpp | 12 +++--- include/engine/search_engine_data.hpp | 4 +- include/engine/segment_information.hpp | 8 ++-- include/engine/trip/trip_brute_force.hpp | 8 ++-- .../engine/trip/trip_farthest_insertion.hpp | 6 +-- .../engine/trip/trip_nearest_neighbour.hpp | 8 ++-- include/engine/trip/trip_tabu_search.hpp | 6 +-- .../extractor/compressed_edge_container.hpp | 2 +- .../extractor/edge_based_graph_factory.hpp | 20 +++++----- include/extractor/edge_based_node.hpp | 6 +-- include/extractor/external_memory_node.hpp | 4 +- include/extractor/extraction_containers.hpp | 10 ++--- .../extractor/extraction_helper_functions.hpp | 4 +- include/extractor/extraction_way.hpp | 4 +- include/extractor/extractor.hpp | 6 +-- include/extractor/extractor_callbacks.hpp | 2 +- .../first_and_last_segment_of_way.hpp | 4 +- include/extractor/graph_compressor.hpp | 6 +-- include/extractor/import_edge.hpp | 4 +- include/extractor/internal_extractor_edge.hpp | 8 ++-- include/extractor/node_id.hpp | 2 +- include/extractor/original_edge_data.hpp | 6 +-- include/extractor/query_node.hpp | 4 +- include/extractor/raster_source.hpp | 2 +- include/extractor/restriction.hpp | 2 +- include/extractor/restriction_map.hpp | 6 +-- include/extractor/restriction_parser.hpp | 2 +- include/extractor/tarjan_scc.hpp | 20 +++++----- include/osrm/route_parameters.hpp | 2 +- include/server/connection.hpp | 8 ++-- include/server/http/reply.hpp | 2 +- include/server/request_parser.hpp | 6 +-- include/server/server.hpp | 8 ++-- include/util/datastore_options.hpp | 6 +-- include/util/deallocating_vector.hpp | 2 +- include/util/debug_geometry.hpp | 8 ++-- include/util/dynamic_graph.hpp | 6 +-- include/util/graph_loader.hpp | 16 ++++---- include/util/graph_utils.hpp | 2 +- include/util/json_logger.hpp | 2 +- include/util/json_renderer.hpp | 6 +-- include/util/json_util.hpp | 2 +- include/util/matching_debug_info.hpp | 8 ++-- include/util/matrix_graph_wrapper.hpp | 2 +- include/util/node_based_graph.hpp | 6 +-- include/util/range_table.hpp | 6 +-- include/util/rectangle.hpp | 4 +- include/util/routed_options.hpp | 6 +-- include/util/static_graph.hpp | 8 ++-- include/util/static_rtree.hpp | 22 +++++----- include/util/trigonometry_table.hpp | 2 +- include/util/typedefs.hpp | 2 +- include/util/xml_renderer.hpp | 4 +- include/util/xor_fast_hash_storage.hpp | 2 +- src/benchmarks/static_rtree.cpp | 12 +++--- src/contractor/contractor_options.cpp | 4 +- src/contractor/processing_chain.cpp | 28 ++++++------- .../descriptors/description_factory.cpp | 16 ++++---- src/engine/douglas_peucker.cpp | 6 +-- src/engine/osrm_impl.cpp | 36 ++++++++--------- src/engine/phantom_node.cpp | 8 ++-- src/engine/polyline_compressor.cpp | 6 +-- src/engine/polyline_formatter.cpp | 8 ++-- src/engine/route_parameters.cpp | 4 +- src/engine/search_engine_data.cpp | 4 +- src/extractor/compressed_edge_container.cpp | 4 +- src/extractor/edge_based_graph_factory.cpp | 20 +++++----- src/extractor/external_memory_node.cpp | 4 +- src/extractor/extraction_containers.cpp | 20 +++++----- src/extractor/extractor.cpp | 40 +++++++++---------- src/extractor/extractor_callbacks.cpp | 18 ++++----- src/extractor/extractor_options.cpp | 6 +-- src/extractor/graph_compressor.cpp | 14 +++---- src/extractor/import_edge.cpp | 6 +-- src/extractor/raster_source.cpp | 8 ++-- src/extractor/restriction_map.cpp | 2 +- src/extractor/restriction_parser.cpp | 12 +++--- src/extractor/scripting_environment.cpp | 22 +++++----- src/server/connection.cpp | 6 +-- src/server/http/reply.cpp | 2 +- src/server/request_handler.cpp | 24 +++++------ src/server/request_parser.cpp | 10 ++--- src/tools/check-hsgr.cpp | 14 +++---- src/tools/components.cpp | 22 +++++----- src/tools/datastore.cpp | 30 +++++++------- src/tools/io-benchmark.cpp | 6 +-- src/tools/routed.cpp | 4 +- src/tools/simpleclient.cpp | 14 +++---- src/tools/springclean.cpp | 6 +-- src/tools/unlock_all_mutexes.cpp | 4 +- src/util/compute_angle.cpp | 8 ++-- src/util/coordinate.cpp | 6 +-- src/util/coordinate_calculation.cpp | 8 ++-- src/util/hilbert_value.cpp | 4 +- src/util/mercator.cpp | 2 +- src/util/osrm_exception.cpp | 2 +- src/util/simple_logger.cpp | 2 +- unit_tests/engine/douglas_peucker.cpp | 4 +- unit_tests/engine/geometry_string.cpp | 4 +- .../extractor/compressed_edge_container.cpp | 4 +- unit_tests/extractor/graph_compressor.cpp | 12 +++--- unit_tests/extractor/raster_source.cpp | 6 +-- unit_tests/util/bearing.cpp | 4 +- unit_tests/util/binary_heap.cpp | 4 +- unit_tests/util/coordinate.cpp | 2 +- unit_tests/util/duration_parsing.cpp | 2 +- unit_tests/util/dynamic_graph.cpp | 4 +- unit_tests/util/range_table.cpp | 4 +- unit_tests/util/static_graph.cpp | 4 +- unit_tests/util/static_rtree.cpp | 14 +++---- unit_tests/util/string_util.cpp | 2 +- 145 files changed, 627 insertions(+), 627 deletions(-) diff --git a/include/contractor/contractor.hpp b/include/contractor/contractor.hpp index 07a21dc50..4ae4fcc4b 100644 --- a/include/contractor/contractor.hpp +++ b/include/contractor/contractor.hpp @@ -28,17 +28,17 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef CONTRACTOR_HPP #define CONTRACTOR_HPP -#include "../data_structures/binary_heap.hpp" -#include "../data_structures/deallocating_vector.hpp" -#include "../data_structures/dynamic_graph.hpp" -#include "../data_structures/percent.hpp" -#include "../data_structures/query_edge.hpp" -#include "../data_structures/xor_fast_hash.hpp" -#include "../data_structures/xor_fast_hash_storage.hpp" -#include "../util/integer_range.hpp" -#include "../util/simple_logger.hpp" -#include "../util/timing_util.hpp" -#include "../typedefs.h" +#include "util/binary_heap.hpp" +#include "util/deallocating_vector.hpp" +#include "util/dynamic_graph.hpp" +#include "util/percent.hpp" +#include "contractor/query_edge.hpp" +#include "util/xor_fast_hash.hpp" +#include "util/xor_fast_hash_storage.hpp" +#include "util/integer_range.hpp" +#include "util/simple_logger.hpp" +#include "util/timing_util.hpp" +#include "util/typedefs.hpp" #include diff --git a/include/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp index 0eb65553d..e303a6fc6 100644 --- a/include/contractor/processing_chain.hpp +++ b/include/contractor/processing_chain.hpp @@ -28,12 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef PROCESSING_CHAIN_HPP #define PROCESSING_CHAIN_HPP -#include "contractor.hpp" -#include "contractor_options.hpp" -#include "../data_structures/query_edge.hpp" -#include "../data_structures/static_graph.hpp" -#include "../data_structures/deallocating_vector.hpp" -#include "../data_structures/node_based_graph.hpp" +#include "contractor/contractor.hpp" +#include "contractor/contractor_options.hpp" +#include "contractor/query_edge.hpp" +#include "util/static_graph.hpp" +#include "util/deallocating_vector.hpp" +#include "util/node_based_graph.hpp" struct SpeedProfileProperties; struct EdgeBasedNode; diff --git a/include/contractor/query_edge.hpp b/include/contractor/query_edge.hpp index 1c4af03d9..86d5d63a8 100644 --- a/include/contractor/query_edge.hpp +++ b/include/contractor/query_edge.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef QUERYEDGE_HPP #define QUERYEDGE_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" #include diff --git a/include/datastore/shared_memory_factory.hpp b/include/datastore/shared_memory_factory.hpp index 7d92eaaa5..c88fc725e 100644 --- a/include/datastore/shared_memory_factory.hpp +++ b/include/datastore/shared_memory_factory.hpp @@ -28,8 +28,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SHARED_MEMORY_FACTORY_HPP #define SHARED_MEMORY_FACTORY_HPP -#include "../util/osrm_exception.hpp" -#include "../util/simple_logger.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" #include #include diff --git a/include/engine/datafacade/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp index 5c5c52296..a0d1f0e98 100644 --- a/include/engine/datafacade/datafacade_base.hpp +++ b/include/engine/datafacade/datafacade_base.hpp @@ -30,16 +30,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Exposes all data access interfaces to the algorithms via base class ptr -#include "../../data_structures/edge_based_node.hpp" -#include "../../data_structures/external_memory_node.hpp" -#include "../../data_structures/phantom_node.hpp" -#include "../../data_structures/turn_instructions.hpp" -#include "../../util/integer_range.hpp" -#include "../../util/osrm_exception.hpp" -#include "../../util/string_util.hpp" -#include "../../typedefs.h" +#include "extractor/edge_based_node.hpp" +#include "extractor/external_memory_node.hpp" +#include "engine/phantom_node.hpp" +#include "extractor/turn_instructions.hpp" +#include "util/integer_range.hpp" +#include "util/osrm_exception.hpp" +#include "util/string_util.hpp" +#include "util/typedefs.hpp" -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/include/engine/datafacade/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp index a2f74e587..82bbe30e2 100644 --- a/include/engine/datafacade/internal_datafacade.hpp +++ b/include/engine/datafacade/internal_datafacade.hpp @@ -30,20 +30,20 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // implements all data storage when shared memory is _NOT_ used -#include "datafacade_base.hpp" +#include "engine/datafacade/datafacade_base.hpp" -#include "../../algorithms/geospatial_query.hpp" -#include "../../data_structures/original_edge_data.hpp" -#include "../../data_structures/query_node.hpp" -#include "../../data_structures/query_edge.hpp" -#include "../../data_structures/shared_memory_vector_wrapper.hpp" -#include "../../data_structures/static_graph.hpp" -#include "../../data_structures/static_rtree.hpp" -#include "../../data_structures/range_table.hpp" -#include "../../util/graph_loader.hpp" -#include "../../util/simple_logger.hpp" +#include "engine/geospatial_query.hpp" +#include "extractor/original_edge_data.hpp" +#include "extractor/query_node.hpp" +#include "contractor/query_edge.hpp" +#include "util/shared_memory_vector_wrapper.hpp" +#include "util/static_graph.hpp" +#include "util/static_rtree.hpp" +#include "util/range_table.hpp" +#include "util/graph_loader.hpp" +#include "util/simple_logger.hpp" -#include +#include "osrm/coordinate.hpp" #include diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 024a8948f..dc7938cd5 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -30,15 +30,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // implements all data storage when shared memory _IS_ used -#include "datafacade_base.hpp" -#include "shared_datatype.hpp" +#include "engine/datafacade/datafacade_base.hpp" +#include "engine/datafacade/shared_datatype.hpp" -#include "../../algorithms/geospatial_query.hpp" -#include "../../data_structures/range_table.hpp" -#include "../../data_structures/static_graph.hpp" -#include "../../data_structures/static_rtree.hpp" -#include "../../util/make_unique.hpp" -#include "../../util/simple_logger.hpp" +#include "engine/geospatial_query.hpp" +#include "util/range_table.hpp" +#include "util/static_graph.hpp" +#include "util/static_rtree.hpp" +#include "util/make_unique.hpp" +#include "util/simple_logger.hpp" #include diff --git a/include/engine/datafacade/shared_datatype.hpp b/include/engine/datafacade/shared_datatype.hpp index c0ad7d45b..f012073e4 100644 --- a/include/engine/datafacade/shared_datatype.hpp +++ b/include/engine/datafacade/shared_datatype.hpp @@ -28,8 +28,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SHARED_DATA_TYPE_HPP #define SHARED_DATA_TYPE_HPP -#include "../../util/osrm_exception.hpp" -#include "../../util/simple_logger.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" #include diff --git a/include/engine/descriptors/description_factory.hpp b/include/engine/descriptors/description_factory.hpp index 985f9c1c5..0e3dc2413 100644 --- a/include/engine/descriptors/description_factory.hpp +++ b/include/engine/descriptors/description_factory.hpp @@ -28,15 +28,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DESCRIPTION_FACTORY_HPP #define DESCRIPTION_FACTORY_HPP -#include "../algorithms/douglas_peucker.hpp" -#include "../data_structures/phantom_node.hpp" -#include "../data_structures/segment_information.hpp" -#include "../data_structures/turn_instructions.hpp" +#include "engine/douglas_peucker.hpp" +#include "engine/phantom_node.hpp" +#include "engine/segment_information.hpp" +#include "extractor/turn_instructions.hpp" #include -#include -#include +#include "osrm/coordinate.hpp" +#include "osrm/json_container.hpp" #include diff --git a/include/engine/descriptors/descriptor_base.hpp b/include/engine/descriptors/descriptor_base.hpp index e85ea902f..41511a082 100644 --- a/include/engine/descriptors/descriptor_base.hpp +++ b/include/engine/descriptors/descriptor_base.hpp @@ -28,14 +28,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DESCRIPTOR_BASE_HPP #define DESCRIPTOR_BASE_HPP -#include "../algorithms/coordinate_calculation.hpp" -#include "../data_structures/internal_route_result.hpp" -#include "../data_structures/phantom_node.hpp" -#include "../typedefs.h" +#include "util/coordinate_calculation.hpp" +#include "engine/internal_route_result.hpp" +#include "engine/phantom_node.hpp" +#include "util/typedefs.hpp" #include -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/engine/descriptors/gpx_descriptor.hpp b/include/engine/descriptors/gpx_descriptor.hpp index fb4c5b9de..dd7506625 100644 --- a/include/engine/descriptors/gpx_descriptor.hpp +++ b/include/engine/descriptors/gpx_descriptor.hpp @@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GPX_DESCRIPTOR_HPP #define GPX_DESCRIPTOR_HPP -#include "descriptor_base.hpp" -#include "../util/xml_renderer.hpp" +#include "engine/descriptors/descriptor_base.hpp" +#include "util/xml_renderer.hpp" -#include +#include "osrm/json_container.hpp" #include diff --git a/include/engine/descriptors/json_descriptor.hpp b/include/engine/descriptors/json_descriptor.hpp index a4344d9bb..0e9e629a6 100644 --- a/include/engine/descriptors/json_descriptor.hpp +++ b/include/engine/descriptors/json_descriptor.hpp @@ -28,21 +28,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef JSON_DESCRIPTOR_HPP #define JSON_DESCRIPTOR_HPP -#include "descriptor_base.hpp" -#include "description_factory.hpp" -#include "../algorithms/object_encoder.hpp" -#include "../algorithms/route_name_extraction.hpp" -#include "../data_structures/segment_information.hpp" -#include "../data_structures/turn_instructions.hpp" -#include "../util/bearing.hpp" -#include "../util/cast.hpp" -#include "../util/integer_range.hpp" -#include "../util/json_renderer.hpp" -#include "../util/simple_logger.hpp" -#include "../util/string_util.hpp" -#include "../util/timing_util.hpp" +#include "engine/descriptors/descriptor_base.hpp" +#include "engine/descriptors/description_factory.hpp" +#include "engine/object_encoder.hpp" +#include "engine/route_name_extraction.hpp" +#include "engine/segment_information.hpp" +#include "extractor/turn_instructions.hpp" +#include "util/bearing.hpp" +#include "util/cast.hpp" +#include "util/integer_range.hpp" +#include "util/json_renderer.hpp" +#include "util/simple_logger.hpp" +#include "util/string_util.hpp" +#include "util/timing_util.hpp" -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/engine/douglas_peucker.hpp b/include/engine/douglas_peucker.hpp index da02982f3..7ef6bd6c2 100644 --- a/include/engine/douglas_peucker.hpp +++ b/include/engine/douglas_peucker.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DOUGLAS_PEUCKER_HPP_ #define DOUGLAS_PEUCKER_HPP_ -#include "../data_structures/segment_information.hpp" +#include "engine/segment_information.hpp" #include #include diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index 96b4fc5a2..05105554e 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -1,12 +1,12 @@ #ifndef GEOSPATIAL_QUERY_HPP #define GEOSPATIAL_QUERY_HPP -#include "coordinate_calculation.hpp" -#include "../typedefs.h" -#include "../data_structures/phantom_node.hpp" -#include "../util/bearing.hpp" +#include "util/coordinate_calculation.hpp" +#include "util/typedefs.hpp" +#include "engine/phantom_node.hpp" +#include "util/bearing.hpp" -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/include/engine/internal_route_result.hpp b/include/engine/internal_route_result.hpp index 068b63a80..be8dec223 100644 --- a/include/engine/internal_route_result.hpp +++ b/include/engine/internal_route_result.hpp @@ -28,12 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef RAW_ROUTE_DATA_H #define RAW_ROUTE_DATA_H -#include "../data_structures/phantom_node.hpp" -#include "../data_structures/travel_mode.hpp" -#include "../data_structures/turn_instructions.hpp" -#include "../typedefs.h" +#include "engine/phantom_node.hpp" +#include "extractor/travel_mode.hpp" +#include "extractor/turn_instructions.hpp" +#include "util/typedefs.hpp" -#include +#include "osrm/coordinate.hpp" #include diff --git a/include/engine/map_matching/hidden_markov_model.hpp b/include/engine/map_matching/hidden_markov_model.hpp index e3efcea08..d6e79a6eb 100644 --- a/include/engine/map_matching/hidden_markov_model.hpp +++ b/include/engine/map_matching/hidden_markov_model.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef HIDDEN_MARKOV_MODEL #define HIDDEN_MARKOV_MODEL -#include "../util/integer_range.hpp" +#include "util/integer_range.hpp" #include diff --git a/include/engine/osrm_impl.hpp b/include/engine/osrm_impl.hpp index c223449e4..b6c8928d2 100644 --- a/include/engine/osrm_impl.hpp +++ b/include/engine/osrm_impl.hpp @@ -31,11 +31,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class BasePlugin; struct RouteParameters; -#include "../data_structures/query_edge.hpp" +#include "contractor/query_edge.hpp" -#include -#include -#include +#include "osrm/json_container.hpp" +#include "osrm/libosrm_config.hpp" +#include "osrm/osrm.hpp" #include #include diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index b12c4feb6..f2255e35e 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef PHANTOM_NODES_H #define PHANTOM_NODES_H -#include "travel_mode.hpp" -#include "../typedefs.h" +#include "extractor/travel_mode.hpp" +#include "util/typedefs.hpp" -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index c4ed250c8..8009e6818 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -28,18 +28,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DISTANCE_TABLE_HPP #define DISTANCE_TABLE_HPP -#include "plugin_base.hpp" +#include "engine/plugins/plugin_base.hpp" -#include "../algorithms/object_encoder.hpp" -#include "../data_structures/query_edge.hpp" -#include "../data_structures/search_engine.hpp" -#include "../descriptors/descriptor_base.hpp" -#include "../util/json_renderer.hpp" -#include "../util/make_unique.hpp" -#include "../util/string_util.hpp" -#include "../util/timing_util.hpp" +#include "engine/object_encoder.hpp" +#include "contractor/query_edge.hpp" +#include "engine/search_engine.hpp" +#include "engine/descriptors/descriptor_base.hpp" +#include "util/json_renderer.hpp" +#include "util/make_unique.hpp" +#include "util/string_util.hpp" +#include "util/timing_util.hpp" -#include +#include "osrm/json_container.hpp" #include diff --git a/include/engine/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp index 512fb07e0..ac6aa53d9 100644 --- a/include/engine/plugins/hello_world.hpp +++ b/include/engine/plugins/hello_world.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef HELLO_WORLD_HPP #define HELLO_WORLD_HPP -#include "plugin_base.hpp" +#include "engine/plugins/plugin_base.hpp" -#include "../util/json_renderer.hpp" +#include "util/json_renderer.hpp" -#include +#include "osrm/json_container.hpp" #include diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index f1769562f..64da87856 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -28,19 +28,19 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MATCH_HPP #define MATCH_HPP -#include "plugin_base.hpp" +#include "engine/plugins/plugin_base.hpp" -#include "../algorithms/bayes_classifier.hpp" -#include "../algorithms/object_encoder.hpp" -#include "../data_structures/search_engine.hpp" -#include "../descriptors/descriptor_base.hpp" -#include "../descriptors/json_descriptor.hpp" -#include "../routing_algorithms/map_matching.hpp" -#include "../util/compute_angle.hpp" -#include "../util/integer_range.hpp" -#include "../util/json_logger.hpp" -#include "../util/json_util.hpp" -#include "../util/string_util.hpp" +#include "engine/map_matching/bayes_classifier.hpp" +#include "engine/object_encoder.hpp" +#include "engine/search_engine.hpp" +#include "engine/descriptors/descriptor_base.hpp" +#include "engine/descriptors/json_descriptor.hpp" +#include "engine/routing_algorithms/map_matching.hpp" +#include "util/compute_angle.hpp" +#include "util/integer_range.hpp" +#include "util/json_logger.hpp" +#include "util/json_util.hpp" +#include "util/string_util.hpp" #include diff --git a/include/engine/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp index 245981981..1fc66efec 100644 --- a/include/engine/plugins/nearest.hpp +++ b/include/engine/plugins/nearest.hpp @@ -28,13 +28,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef NEAREST_HPP #define NEAREST_HPP -#include "plugin_base.hpp" +#include "engine/plugins/plugin_base.hpp" -#include "../data_structures/phantom_node.hpp" -#include "../util/integer_range.hpp" -#include "../util/json_renderer.hpp" +#include "engine/phantom_node.hpp" +#include "util/integer_range.hpp" +#include "util/json_renderer.hpp" -#include +#include "osrm/json_container.hpp" #include diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index a05785a37..b623aa1f4 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef BASE_PLUGIN_HPP #define BASE_PLUGIN_HPP -#include "../data_structures/phantom_node.hpp" +#include "engine/phantom_node.hpp" -#include -#include -#include +#include "osrm/coordinate.hpp" +#include "osrm/json_container.hpp" +#include "osrm/route_parameters.hpp" #include #include diff --git a/include/engine/plugins/timestamp.hpp b/include/engine/plugins/timestamp.hpp index 899ef4670..0b1ef0772 100644 --- a/include/engine/plugins/timestamp.hpp +++ b/include/engine/plugins/timestamp.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef TIMESTAMP_PLUGIN_H #define TIMESTAMP_PLUGIN_H -#include "plugin_base.hpp" +#include "engine/plugins/plugin_base.hpp" -#include "../util/json_renderer.hpp" +#include "util/json_renderer.hpp" -#include +#include "osrm/json_container.hpp" #include diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index a69e25e77..7ca1e663b 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -28,25 +28,25 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef TRIP_HPP #define TRIP_HPP -#include "plugin_base.hpp" +#include "engine/plugins/plugin_base.hpp" -#include "../algorithms/object_encoder.hpp" -#include "../algorithms/tarjan_scc.hpp" -#include "../algorithms/trip_nearest_neighbour.hpp" -#include "../algorithms/trip_farthest_insertion.hpp" -#include "../algorithms/trip_brute_force.hpp" -#include "../data_structures/search_engine.hpp" -#include "../data_structures/matrix_graph_wrapper.hpp" // wrapper to use tarjan +#include "engine/object_encoder.hpp" +#include "extractor/tarjan_scc.hpp" +#include "engine/trip/trip_nearest_neighbour.hpp" +#include "engine/trip/trip_farthest_insertion.hpp" +#include "engine/trip/trip_brute_force.hpp" +#include "engine/search_engine.hpp" +#include "util/matrix_graph_wrapper.hpp" // wrapper to use tarjan // scc on dist table -#include "../descriptors/descriptor_base.hpp" // to make json output -#include "../descriptors/json_descriptor.hpp" // to make json output -#include "../util/make_unique.hpp" -#include "../util/timing_util.hpp" // to time runtime -//#include "../util/simple_logger.hpp" // for logging output -#include "../util/dist_table_wrapper.hpp" // to access the dist +#include "engine/descriptors/descriptor_base.hpp" // to make json output +#include "engine/descriptors/json_descriptor.hpp" // to make json output +#include "util/make_unique.hpp" +#include "util/timing_util.hpp" // to time runtime +//#include "util/simple_logger.hpp" // for logging output +#include "util/dist_table_wrapper.hpp" // to access the dist // table more easily -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index f9a6737da..43e8728c3 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -28,20 +28,20 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef VIA_ROUTE_HPP #define VIA_ROUTE_HPP -#include "plugin_base.hpp" +#include "engine/plugins/plugin_base.hpp" -#include "../algorithms/object_encoder.hpp" -#include "../data_structures/search_engine.hpp" -#include "../descriptors/descriptor_base.hpp" -#include "../descriptors/gpx_descriptor.hpp" -#include "../descriptors/json_descriptor.hpp" -#include "../util/integer_range.hpp" -#include "../util/json_renderer.hpp" -#include "../util/make_unique.hpp" -#include "../util/simple_logger.hpp" -#include "../util/timing_util.hpp" +#include "engine/object_encoder.hpp" +#include "engine/search_engine.hpp" +#include "engine/descriptors/descriptor_base.hpp" +#include "engine/descriptors/gpx_descriptor.hpp" +#include "engine/descriptors/json_descriptor.hpp" +#include "util/integer_range.hpp" +#include "util/json_renderer.hpp" +#include "util/make_unique.hpp" +#include "util/simple_logger.hpp" +#include "util/timing_util.hpp" -#include +#include "osrm/json_container.hpp" #include diff --git a/include/engine/polyline_compressor.hpp b/include/engine/polyline_compressor.hpp index a148200ca..f4c449156 100644 --- a/include/engine/polyline_compressor.hpp +++ b/include/engine/polyline_compressor.hpp @@ -30,7 +30,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. struct SegmentInformation; -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/include/engine/polyline_formatter.hpp b/include/engine/polyline_formatter.hpp index 68cc70293..9f7c60eef 100644 --- a/include/engine/polyline_formatter.hpp +++ b/include/engine/polyline_formatter.hpp @@ -30,7 +30,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. struct SegmentInformation; -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/engine/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp index 59b772edb..78f7a172b 100644 --- a/include/engine/routing_algorithms/alternative_path.hpp +++ b/include/engine/routing_algorithms/alternative_path.hpp @@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ALTERNATIVE_PATH_ROUTING_HPP #define ALTERNATIVE_PATH_ROUTING_HPP -#include "routing_base.hpp" -#include "../data_structures/search_engine_data.hpp" -#include "../util/integer_range.hpp" -#include "../util/container.hpp" +#include "engine/routing_algorithms/routing_base.hpp" +#include "engine/search_engine_data.hpp" +#include "util/integer_range.hpp" +#include "util/container.hpp" #include diff --git a/include/engine/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp index 2237d682a..3209423dd 100644 --- a/include/engine/routing_algorithms/direct_shortest_path.hpp +++ b/include/engine/routing_algorithms/direct_shortest_path.hpp @@ -31,11 +31,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "routing_base.hpp" -#include "../data_structures/search_engine_data.hpp" -#include "../util/integer_range.hpp" -#include "../util/timing_util.hpp" -#include "../typedefs.h" +#include "engine/routing_algorithms/routing_base.hpp" +#include "engine/search_engine_data.hpp" +#include "util/integer_range.hpp" +#include "util/timing_util.hpp" +#include "util/typedefs.hpp" /// This is a striped down version of the general shortest path algorithm. /// The general algorithm always computes two queries for each leg. This is only diff --git a/include/engine/routing_algorithms/many_to_many.hpp b/include/engine/routing_algorithms/many_to_many.hpp index c5dfb7ca5..e9d804a2d 100644 --- a/include/engine/routing_algorithms/many_to_many.hpp +++ b/include/engine/routing_algorithms/many_to_many.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MANY_TO_MANY_ROUTING_HPP #define MANY_TO_MANY_ROUTING_HPP -#include "routing_base.hpp" -#include "../data_structures/search_engine_data.hpp" -#include "../typedefs.h" +#include "engine/routing_algorithms/routing_base.hpp" +#include "engine/search_engine_data.hpp" +#include "util/typedefs.hpp" #include diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 430682d92..9afc2653a 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -28,12 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MAP_MATCHING_HPP #define MAP_MATCHING_HPP -#include "routing_base.hpp" +#include "engine/routing_algorithms/routing_base.hpp" -#include "../algorithms/coordinate_calculation.hpp" -#include "../data_structures/hidden_markov_model.hpp" -#include "../util/json_logger.hpp" -#include "../util/matching_debug_info.hpp" +#include "util/coordinate_calculation.hpp" +#include "engine/map_matching/hidden_markov_model.hpp" +#include "util/json_logger.hpp" +#include "util/matching_debug_info.hpp" #include diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index ecbc07e35..14c5b9c0a 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ROUTING_BASE_HPP #define ROUTING_BASE_HPP -#include "../algorithms/coordinate_calculation.hpp" -#include "../data_structures/internal_route_result.hpp" -#include "../data_structures/search_engine_data.hpp" -#include "../data_structures/turn_instructions.hpp" +#include "util/coordinate_calculation.hpp" +#include "engine/internal_route_result.hpp" +#include "engine/search_engine_data.hpp" +#include "extractor/turn_instructions.hpp" #include diff --git a/include/engine/routing_algorithms/shortest_path.hpp b/include/engine/routing_algorithms/shortest_path.hpp index 601e39460..cedeca83a 100644 --- a/include/engine/routing_algorithms/shortest_path.hpp +++ b/include/engine/routing_algorithms/shortest_path.hpp @@ -28,12 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SHORTEST_PATH_HPP #define SHORTEST_PATH_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" -#include "routing_base.hpp" +#include "engine/routing_algorithms/routing_base.hpp" -#include "../data_structures/search_engine_data.hpp" -#include "../util/integer_range.hpp" +#include "engine/search_engine_data.hpp" +#include "util/integer_range.hpp" #include diff --git a/include/engine/search_engine.hpp b/include/engine/search_engine.hpp index 5af734e77..8efc9d211 100644 --- a/include/engine/search_engine.hpp +++ b/include/engine/search_engine.hpp @@ -28,12 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SEARCH_ENGINE_HPP #define SEARCH_ENGINE_HPP -#include "search_engine_data.hpp" -#include "../routing_algorithms/alternative_path.hpp" -#include "../routing_algorithms/many_to_many.hpp" -#include "../routing_algorithms/map_matching.hpp" -#include "../routing_algorithms/shortest_path.hpp" -#include "../routing_algorithms/direct_shortest_path.hpp" +#include "engine/search_engine_data.hpp" +#include "engine/routing_algorithms/alternative_path.hpp" +#include "engine/routing_algorithms/many_to_many.hpp" +#include "engine/routing_algorithms/map_matching.hpp" +#include "engine/routing_algorithms/shortest_path.hpp" +#include "engine/routing_algorithms/direct_shortest_path.hpp" #include diff --git a/include/engine/search_engine_data.hpp b/include/engine/search_engine_data.hpp index 8c1c1619e..191447865 100644 --- a/include/engine/search_engine_data.hpp +++ b/include/engine/search_engine_data.hpp @@ -30,8 +30,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include "../typedefs.h" -#include "binary_heap.hpp" +#include "util/typedefs.hpp" +#include "util/binary_heap.hpp" struct HeapData { diff --git a/include/engine/segment_information.hpp b/include/engine/segment_information.hpp index d9cdc8160..725358b50 100644 --- a/include/engine/segment_information.hpp +++ b/include/engine/segment_information.hpp @@ -28,12 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SEGMENT_INFORMATION_HPP #define SEGMENT_INFORMATION_HPP -#include "turn_instructions.hpp" +#include "extractor/turn_instructions.hpp" -#include "../data_structures/travel_mode.hpp" -#include "../typedefs.h" +#include "extractor/travel_mode.hpp" +#include "util/typedefs.hpp" -#include +#include "osrm/coordinate.hpp" #include // Struct fits everything in one cache line diff --git a/include/engine/trip/trip_brute_force.hpp b/include/engine/trip/trip_brute_force.hpp index 601971cf7..5203deea8 100644 --- a/include/engine/trip/trip_brute_force.hpp +++ b/include/engine/trip/trip_brute_force.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef TRIP_BRUTE_FORCE_HPP #define TRIP_BRUTE_FORCE_HPP -#include "../data_structures/search_engine.hpp" -#include "../util/dist_table_wrapper.hpp" -#include "../util/simple_logger.hpp" +#include "engine/search_engine.hpp" +#include "util/dist_table_wrapper.hpp" +#include "util/simple_logger.hpp" -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/engine/trip/trip_farthest_insertion.hpp b/include/engine/trip/trip_farthest_insertion.hpp index 91f0aa417..13f301235 100644 --- a/include/engine/trip/trip_farthest_insertion.hpp +++ b/include/engine/trip/trip_farthest_insertion.hpp @@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef TRIP_FARTHEST_INSERTION_HPP #define TRIP_FARTHEST_INSERTION_HPP -#include "../data_structures/search_engine.hpp" -#include "../util/dist_table_wrapper.hpp" +#include "engine/search_engine.hpp" +#include "util/dist_table_wrapper.hpp" -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/engine/trip/trip_nearest_neighbour.hpp b/include/engine/trip/trip_nearest_neighbour.hpp index 0ae179284..e931bcda7 100644 --- a/include/engine/trip/trip_nearest_neighbour.hpp +++ b/include/engine/trip/trip_nearest_neighbour.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef TRIP_NEAREST_NEIGHBOUR_HPP #define TRIP_NEAREST_NEIGHBOUR_HPP -#include "../data_structures/search_engine.hpp" -#include "../util/simple_logger.hpp" -#include "../util/dist_table_wrapper.hpp" +#include "engine/search_engine.hpp" +#include "util/simple_logger.hpp" +#include "util/dist_table_wrapper.hpp" -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/engine/trip/trip_tabu_search.hpp b/include/engine/trip/trip_tabu_search.hpp index 32f50fc59..988d0a668 100644 --- a/include/engine/trip/trip_tabu_search.hpp +++ b/include/engine/trip/trip_tabu_search.hpp @@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef TRIP_BRUTE_FORCE_HPP #define TRIP_BRUTE_FORCE_HPP -#include "../data_structures/search_engine.hpp" -#include "../util/simple_logger.hpp" +#include "engine/search_engine.hpp" +#include "util/simple_logger.hpp" -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/extractor/compressed_edge_container.hpp b/include/extractor/compressed_edge_container.hpp index 5d94ee6de..afae26f7d 100644 --- a/include/extractor/compressed_edge_container.hpp +++ b/include/extractor/compressed_edge_container.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GEOMETRY_COMPRESSOR_HPP_ #define GEOMETRY_COMPRESSOR_HPP_ -#include "../typedefs.h" +#include "util/typedefs.hpp" #include diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 997c7ea8e..56344c018 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -30,16 +30,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EDGE_BASED_GRAPH_FACTORY_HPP_ #define EDGE_BASED_GRAPH_FACTORY_HPP_ -#include "speed_profile.hpp" -#include "../typedefs.h" -#include "../data_structures/compressed_edge_container.hpp" -#include "../data_structures/deallocating_vector.hpp" -#include "../data_structures/edge_based_node.hpp" -#include "../data_structures/original_edge_data.hpp" -#include "../data_structures/query_node.hpp" -#include "../data_structures/turn_instructions.hpp" -#include "../data_structures/node_based_graph.hpp" -#include "../data_structures/restriction_map.hpp" +#include "extractor/speed_profile.hpp" +#include "util/typedefs.hpp" +#include "extractor/compressed_edge_container.hpp" +#include "util/deallocating_vector.hpp" +#include "extractor/edge_based_node.hpp" +#include "extractor/original_edge_data.hpp" +#include "extractor/query_node.hpp" +#include "extractor/turn_instructions.hpp" +#include "util/node_based_graph.hpp" +#include "extractor/restriction_map.hpp" #include #include diff --git a/include/extractor/edge_based_node.hpp b/include/extractor/edge_based_node.hpp index 8efbf0175..cc09ed2a0 100644 --- a/include/extractor/edge_based_node.hpp +++ b/include/extractor/edge_based_node.hpp @@ -28,12 +28,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EDGE_BASED_NODE_HPP #define EDGE_BASED_NODE_HPP -#include "../data_structures/travel_mode.hpp" -#include "../typedefs.h" +#include "extractor/travel_mode.hpp" +#include "util/typedefs.hpp" #include -#include +#include "osrm/coordinate.hpp" #include diff --git a/include/extractor/external_memory_node.hpp b/include/extractor/external_memory_node.hpp index a48d1a13a..ac56d2393 100644 --- a/include/extractor/external_memory_node.hpp +++ b/include/extractor/external_memory_node.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EXTERNAL_MEMORY_NODE_HPP_ #define EXTERNAL_MEMORY_NODE_HPP_ -#include "query_node.hpp" +#include "extractor/query_node.hpp" -#include "../typedefs.h" +#include "util/typedefs.hpp" struct ExternalMemoryNode : QueryNode { diff --git a/include/extractor/extraction_containers.hpp b/include/extractor/extraction_containers.hpp index 541ad3537..f8a330edb 100644 --- a/include/extractor/extraction_containers.hpp +++ b/include/extractor/extraction_containers.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EXTRACTION_CONTAINERS_HPP #define EXTRACTION_CONTAINERS_HPP -#include "internal_extractor_edge.hpp" -#include "first_and_last_segment_of_way.hpp" -#include "scripting_environment.hpp" -#include "../data_structures/external_memory_node.hpp" -#include "../data_structures/restriction.hpp" +#include "extractor/internal_extractor_edge.hpp" +#include "extractor/first_and_last_segment_of_way.hpp" +#include "extractor/scripting_environment.hpp" +#include "extractor/external_memory_node.hpp" +#include "extractor/restriction.hpp" #include #include diff --git a/include/extractor/extraction_helper_functions.hpp b/include/extractor/extraction_helper_functions.hpp index 69ab456af..2b266d75f 100644 --- a/include/extractor/extraction_helper_functions.hpp +++ b/include/extractor/extraction_helper_functions.hpp @@ -28,8 +28,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EXTRACTION_HELPER_FUNCTIONS_HPP #define EXTRACTION_HELPER_FUNCTIONS_HPP -#include "../util/cast.hpp" -#include "../util/iso_8601_duration_parser.hpp" +#include "util/cast.hpp" +#include "util/iso_8601_duration_parser.hpp" #include #include diff --git a/include/extractor/extraction_way.hpp b/include/extractor/extraction_way.hpp index 094c10a54..c88588ef1 100644 --- a/include/extractor/extraction_way.hpp +++ b/include/extractor/extraction_way.hpp @@ -28,8 +28,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EXTRACTION_WAY_HPP #define EXTRACTION_WAY_HPP -#include "../data_structures/travel_mode.hpp" -#include "../typedefs.h" +#include "extractor/travel_mode.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/include/extractor/extractor.hpp b/include/extractor/extractor.hpp index c147f1961..45a4ee8db 100644 --- a/include/extractor/extractor.hpp +++ b/include/extractor/extractor.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EXTRACTOR_HPP #define EXTRACTOR_HPP -#include "extractor_options.hpp" -#include "edge_based_graph_factory.hpp" -#include "../algorithms/graph_compressor.hpp" +#include "extractor/extractor_options.hpp" +#include "extractor/edge_based_graph_factory.hpp" +#include "extractor/graph_compressor.hpp" class extractor { diff --git a/include/extractor/extractor_callbacks.hpp b/include/extractor/extractor_callbacks.hpp index 0026b6fb0..808119be5 100644 --- a/include/extractor/extractor_callbacks.hpp +++ b/include/extractor/extractor_callbacks.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef EXTRACTOR_CALLBACKS_HPP #define EXTRACTOR_CALLBACKS_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" #include #include diff --git a/include/extractor/first_and_last_segment_of_way.hpp b/include/extractor/first_and_last_segment_of_way.hpp index ead8b4c5c..55a096f45 100644 --- a/include/extractor/first_and_last_segment_of_way.hpp +++ b/include/extractor/first_and_last_segment_of_way.hpp @@ -28,8 +28,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef FIRST_AND_LAST_SEGMENT_OF_WAY_HPP #define FIRST_AND_LAST_SEGMENT_OF_WAY_HPP -#include "../data_structures/external_memory_node.hpp" -#include "../typedefs.h" +#include "extractor/external_memory_node.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/include/extractor/graph_compressor.hpp b/include/extractor/graph_compressor.hpp index 8096a92d6..7ddcd1402 100644 --- a/include/extractor/graph_compressor.hpp +++ b/include/extractor/graph_compressor.hpp @@ -27,10 +27,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GEOMETRY_COMPRESSOR_HPP #define GEOMETRY_COMPRESSOR_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" -#include "../extractor/speed_profile.hpp" -#include "../data_structures/node_based_graph.hpp" +#include "extractor/speed_profile.hpp" +#include "util/node_based_graph.hpp" #include #include diff --git a/include/extractor/import_edge.hpp b/include/extractor/import_edge.hpp index 449ded2a1..f436502c1 100644 --- a/include/extractor/import_edge.hpp +++ b/include/extractor/import_edge.hpp @@ -28,8 +28,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef IMPORT_EDGE_HPP #define IMPORT_EDGE_HPP -#include "../data_structures/travel_mode.hpp" -#include "../typedefs.h" +#include "extractor/travel_mode.hpp" +#include "util/typedefs.hpp" struct NodeBasedEdge { diff --git a/include/extractor/internal_extractor_edge.hpp b/include/extractor/internal_extractor_edge.hpp index 0df6e8cb8..546bb32dc 100644 --- a/include/extractor/internal_extractor_edge.hpp +++ b/include/extractor/internal_extractor_edge.hpp @@ -28,13 +28,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef INTERNAL_EXTRACTOR_EDGE_HPP #define INTERNAL_EXTRACTOR_EDGE_HPP -#include "../typedefs.h" -#include "../data_structures/travel_mode.hpp" -#include "../data_structures/import_edge.hpp" +#include "util/typedefs.hpp" +#include "extractor/travel_mode.hpp" +#include "extractor/import_edge.hpp" #include -#include +#include "osrm/coordinate.hpp" #include struct InternalExtractorEdge diff --git a/include/extractor/node_id.hpp b/include/extractor/node_id.hpp index 0671a4d9d..b17de3829 100644 --- a/include/extractor/node_id.hpp +++ b/include/extractor/node_id.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef NODE_ID_HPP #define NODE_ID_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" struct Cmp { diff --git a/include/extractor/original_edge_data.hpp b/include/extractor/original_edge_data.hpp index cbbc1b276..b2009f69b 100644 --- a/include/extractor/original_edge_data.hpp +++ b/include/extractor/original_edge_data.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ORIGINAL_EDGE_DATA_HPP #define ORIGINAL_EDGE_DATA_HPP -#include "travel_mode.hpp" -#include "turn_instructions.hpp" -#include "../typedefs.h" +#include "extractor/travel_mode.hpp" +#include "extractor/turn_instructions.hpp" +#include "util/typedefs.hpp" #include diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index 0f32a536f..2c956262e 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef QUERY_NODE_HPP #define QUERY_NODE_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" #include -#include +#include "osrm/coordinate.hpp" #include diff --git a/include/extractor/raster_source.hpp b/include/extractor/raster_source.hpp index 86c859639..d5bdc3937 100644 --- a/include/extractor/raster_source.hpp +++ b/include/extractor/raster_source.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef RASTER_SOURCE_HPP #define RASTER_SOURCE_HPP -#include "../util/osrm_exception.hpp" +#include "util/osrm_exception.hpp" #include #include diff --git a/include/extractor/restriction.hpp b/include/extractor/restriction.hpp index ecab4f921..4cfeccd1d 100644 --- a/include/extractor/restriction.hpp +++ b/include/extractor/restriction.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef RESTRICTION_HPP #define RESTRICTION_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" #include diff --git a/include/extractor/restriction_map.hpp b/include/extractor/restriction_map.hpp index dbca35651..64d65b873 100644 --- a/include/extractor/restriction_map.hpp +++ b/include/extractor/restriction_map.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef RESTRICTION_MAP_HPP #define RESTRICTION_MAP_HPP -#include "restriction.hpp" -#include "../util/std_hash.hpp" -#include "../typedefs.h" +#include "extractor/restriction.hpp" +#include "util/std_hash.hpp" +#include "util/typedefs.hpp" #include diff --git a/include/extractor/restriction_parser.hpp b/include/extractor/restriction_parser.hpp index 11f94ee21..3d19bb9ff 100644 --- a/include/extractor/restriction_parser.hpp +++ b/include/extractor/restriction_parser.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef RESTRICTION_PARSER_HPP #define RESTRICTION_PARSER_HPP -#include "../data_structures/restriction.hpp" +#include "extractor/restriction.hpp" #include diff --git a/include/extractor/tarjan_scc.hpp b/include/extractor/tarjan_scc.hpp index 59077322d..ad829d167 100644 --- a/include/extractor/tarjan_scc.hpp +++ b/include/extractor/tarjan_scc.hpp @@ -28,18 +28,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef TARJAN_SCC_HPP #define TARJAN_SCC_HPP -#include "../typedefs.h" -#include "../data_structures/deallocating_vector.hpp" -#include "../data_structures/import_edge.hpp" -#include "../data_structures/query_node.hpp" -#include "../data_structures/percent.hpp" +#include "util/typedefs.hpp" +#include "util/deallocating_vector.hpp" +#include "extractor/import_edge.hpp" +#include "extractor/query_node.hpp" +#include "util/percent.hpp" -#include "../util/integer_range.hpp" -#include "../util/simple_logger.hpp" -#include "../util/std_hash.hpp" -#include "../util/timing_util.hpp" +#include "util/integer_range.hpp" +#include "util/simple_logger.hpp" +#include "util/std_hash.hpp" +#include "util/timing_util.hpp" -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/include/osrm/route_parameters.hpp b/include/osrm/route_parameters.hpp index 6d2dda719..700c55807 100644 --- a/include/osrm/route_parameters.hpp +++ b/include/osrm/route_parameters.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef ROUTE_PARAMETERS_HPP #define ROUTE_PARAMETERS_HPP -#include +#include "coordinate.hpp" #include #include diff --git a/include/server/connection.hpp b/include/server/connection.hpp index aa6fd0544..315800d1a 100644 --- a/include/server/connection.hpp +++ b/include/server/connection.hpp @@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef CONNECTION_HPP #define CONNECTION_HPP -#include "http/compression_type.hpp" -#include "http/reply.hpp" -#include "http/request.hpp" -#include "request_parser.hpp" +#include "server/http/compression_type.hpp" +#include "server/http/reply.hpp" +#include "server/http/request.hpp" +#include "server/request_parser.hpp" #include #include diff --git a/include/server/http/reply.hpp b/include/server/http/reply.hpp index 733818c2c..7689e5ed2 100644 --- a/include/server/http/reply.hpp +++ b/include/server/http/reply.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef REPLY_HPP #define REPLY_HPP -#include "header.hpp" +#include "server/http/header.hpp" #include diff --git a/include/server/request_parser.hpp b/include/server/request_parser.hpp index 3724613a7..920876dcf 100644 --- a/include/server/request_parser.hpp +++ b/include/server/request_parser.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef REQUEST_PARSER_HPP #define REQUEST_PARSER_HPP -#include "http/compression_type.hpp" -#include "http/header.hpp" -#include "../data_structures/tribool.hpp" +#include "server/http/compression_type.hpp" +#include "server/http/header.hpp" +#include "util/tribool.hpp" #include diff --git a/include/server/server.hpp b/include/server/server.hpp index 80fae9704..48ac2686a 100644 --- a/include/server/server.hpp +++ b/include/server/server.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SERVER_HPP #define SERVER_HPP -#include "connection.hpp" -#include "request_handler.hpp" +#include "server/connection.hpp" +#include "server/request_handler.hpp" -#include "../util/integer_range.hpp" -#include "../util/simple_logger.hpp" +#include "util/integer_range.hpp" +#include "util/simple_logger.hpp" #include #include diff --git a/include/util/datastore_options.hpp b/include/util/datastore_options.hpp index 4a8320c77..ccb909f14 100644 --- a/include/util/datastore_options.hpp +++ b/include/util/datastore_options.hpp @@ -29,9 +29,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define DATASTORE_OPTIONS_HPP #include "util/version.hpp" -#include "ini_file.hpp" -#include "osrm_exception.hpp" -#include "simple_logger.hpp" +#include "util/ini_file.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" #include #include diff --git a/include/util/deallocating_vector.hpp b/include/util/deallocating_vector.hpp index 72cb0816c..c98bd3174 100644 --- a/include/util/deallocating_vector.hpp +++ b/include/util/deallocating_vector.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DEALLOCATING_VECTOR_HPP #define DEALLOCATING_VECTOR_HPP -#include "../util/integer_range.hpp" +#include "util/integer_range.hpp" #include diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index daa7e1074..bf2b26bce 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -28,8 +28,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DEBUG_GEOMETRY_H #define DEBUG_GEOMETRY_H -#include "../contractor/contractor_options.hpp" -#include "../data_structures/query_node.hpp" +#include "contractor/contractor_options.hpp" +#include "extractor/query_node.hpp" #ifndef DEBUG_GEOMETRY @@ -57,8 +57,8 @@ inline void DEBUG_TURNS_STOP() {} #include #include -#include "../include/osrm/coordinate.hpp" -#include "../algorithms/coordinate_calculation.hpp" +#include "util/coordinate.hpp" +#include "util/coordinate_calculation.hpp" boost::filesystem::ofstream debug_geometry_file; bool dg_output_debug_geometry = false; diff --git a/include/util/dynamic_graph.hpp b/include/util/dynamic_graph.hpp index 4f63c02d4..c0cf2bb4d 100644 --- a/include/util/dynamic_graph.hpp +++ b/include/util/dynamic_graph.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef DYNAMICGRAPH_HPP #define DYNAMICGRAPH_HPP -#include "deallocating_vector.hpp" -#include "../util/integer_range.hpp" -#include "../typedefs.h" +#include "util/deallocating_vector.hpp" +#include "util/integer_range.hpp" +#include "util/typedefs.hpp" #include diff --git a/include/util/graph_loader.hpp b/include/util/graph_loader.hpp index 6ddd0ebcb..b720a9bdf 100644 --- a/include/util/graph_loader.hpp +++ b/include/util/graph_loader.hpp @@ -28,14 +28,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GRAPH_LOADER_HPP #define GRAPH_LOADER_HPP -#include "fingerprint.hpp" -#include "osrm_exception.hpp" -#include "simple_logger.hpp" -#include "../data_structures/external_memory_node.hpp" -#include "../data_structures/import_edge.hpp" -#include "../data_structures/query_node.hpp" -#include "../data_structures/restriction.hpp" -#include "../typedefs.h" +#include "util/fingerprint.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" +#include "extractor/external_memory_node.hpp" +#include "extractor/import_edge.hpp" +#include "extractor/query_node.hpp" +#include "extractor/restriction.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/include/util/graph_utils.hpp b/include/util/graph_utils.hpp index 9af8dbc07..d9d2fc46e 100644 --- a/include/util/graph_utils.hpp +++ b/include/util/graph_utils.hpp @@ -1,7 +1,7 @@ #ifndef GRAPH_UTILS_HPP #define GRAPH_UTILS_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" #include #include diff --git a/include/util/json_logger.hpp b/include/util/json_logger.hpp index 8726f78d9..dbef457e6 100644 --- a/include/util/json_logger.hpp +++ b/include/util/json_logger.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef JSON_LOGGER_HPP #define JSON_LOGGER_HPP -#include +#include "osrm/json_container.hpp" #include diff --git a/include/util/json_renderer.hpp b/include/util/json_renderer.hpp index 09d7bb251..d44d507fa 100644 --- a/include/util/json_renderer.hpp +++ b/include/util/json_renderer.hpp @@ -31,10 +31,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef JSON_RENDERER_HPP #define JSON_RENDERER_HPP -#include "cast.hpp" -#include "string_util.hpp" +#include "util/cast.hpp" +#include "util/string_util.hpp" -#include +#include "osrm/json_container.hpp" namespace osrm { diff --git a/include/util/json_util.hpp b/include/util/json_util.hpp index bfb8a8bc4..0804f0a6f 100644 --- a/include/util/json_util.hpp +++ b/include/util/json_util.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef JSON_UTIL_HPP #define JSON_UTIL_HPP -#include +#include "osrm/json_container.hpp" #include #include diff --git a/include/util/matching_debug_info.hpp b/include/util/matching_debug_info.hpp index 28bc6ee3f..a21c8f6bc 100644 --- a/include/util/matching_debug_info.hpp +++ b/include/util/matching_debug_info.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MATCHING_DEBUG_INFO_HPP #define MATCHING_DEBUG_INFO_HPP -#include "json_logger.hpp" -#include "json_util.hpp" -#include "../data_structures/hidden_markov_model.hpp" +#include "util/json_logger.hpp" +#include "util/json_util.hpp" +#include "engine/map_matching/hidden_markov_model.hpp" -#include +#include "osrm/coordinate.hpp" // Provides the debug interface for introspection tools struct MatchingDebugInfo diff --git a/include/util/matrix_graph_wrapper.hpp b/include/util/matrix_graph_wrapper.hpp index f8b3e65bb..3439d6f2b 100644 --- a/include/util/matrix_graph_wrapper.hpp +++ b/include/util/matrix_graph_wrapper.hpp @@ -32,7 +32,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "../typedefs.h" +#include "util/typedefs.hpp" // This Wrapper provides all methods that are needed for TarjanSCC, when the graph is given in a // matrix representation (e.g. as output from a distance table call) diff --git a/include/util/node_based_graph.hpp b/include/util/node_based_graph.hpp index e58cfceb4..42b53d626 100644 --- a/include/util/node_based_graph.hpp +++ b/include/util/node_based_graph.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef NODE_BASED_GRAPH_HPP #define NODE_BASED_GRAPH_HPP -#include "dynamic_graph.hpp" -#include "import_edge.hpp" -#include "../util/graph_utils.hpp" +#include "util/dynamic_graph.hpp" +#include "extractor/import_edge.hpp" +#include "util/graph_utils.hpp" #include diff --git a/include/util/range_table.hpp b/include/util/range_table.hpp index e750c90a7..6de3debfd 100644 --- a/include/util/range_table.hpp +++ b/include/util/range_table.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef RANGE_TABLE_HPP #define RANGE_TABLE_HPP -#include "../util/integer_range.hpp" -#include "shared_memory_factory.hpp" -#include "shared_memory_vector_wrapper.hpp" +#include "util/integer_range.hpp" +#include "datastore/shared_memory_factory.hpp" +#include "util/shared_memory_vector_wrapper.hpp" #include #include diff --git a/include/util/rectangle.hpp b/include/util/rectangle.hpp index 7f6704a9b..f4dd5280d 100644 --- a/include/util/rectangle.hpp +++ b/include/util/rectangle.hpp @@ -28,11 +28,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef RECTANGLE_HPP #define RECTANGLE_HPP -#include "../algorithms/coordinate_calculation.hpp" +#include "util/coordinate_calculation.hpp" #include -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index bfe8e5c36..6edcefb72 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -29,9 +29,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define ROUTED_OPTIONS_HPP #include "util/version.hpp" -#include "ini_file.hpp" -#include "osrm_exception.hpp" -#include "simple_logger.hpp" +#include "util/ini_file.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" #include #include diff --git a/include/util/static_graph.hpp b/include/util/static_graph.hpp index 3b8f92738..a2fd47333 100644 --- a/include/util/static_graph.hpp +++ b/include/util/static_graph.hpp @@ -28,10 +28,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef STATIC_GRAPH_HPP #define STATIC_GRAPH_HPP -#include "percent.hpp" -#include "shared_memory_vector_wrapper.hpp" -#include "../util/integer_range.hpp" -#include "../typedefs.h" +#include "util/percent.hpp" +#include "util/shared_memory_vector_wrapper.hpp" +#include "util/integer_range.hpp" +#include "util/typedefs.hpp" #include diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 6bc367824..8483142e8 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -28,19 +28,19 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef STATIC_RTREE_HPP #define STATIC_RTREE_HPP -#include "deallocating_vector.hpp" -#include "hilbert_value.hpp" -#include "rectangle.hpp" -#include "shared_memory_factory.hpp" -#include "shared_memory_vector_wrapper.hpp" +#include "util/deallocating_vector.hpp" +#include "util/hilbert_value.hpp" +#include "util/rectangle.hpp" +#include "datastore/shared_memory_factory.hpp" +#include "util/shared_memory_vector_wrapper.hpp" -#include "../util/bearing.hpp" -#include "../util/integer_range.hpp" -#include "../util/mercator.hpp" -#include "../util/osrm_exception.hpp" -#include "../typedefs.h" +#include "util/bearing.hpp" +#include "util/integer_range.hpp" +#include "util/mercator.hpp" +#include "util/osrm_exception.hpp" +#include "util/typedefs.hpp" -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/include/util/trigonometry_table.hpp b/include/util/trigonometry_table.hpp index 234a94e56..463dbbecd 100644 --- a/include/util/trigonometry_table.hpp +++ b/include/util/trigonometry_table.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef TRIGONOMETRY_TABLE_HPP #define TRIGONOMETRY_TABLE_HPP -#include "../typedefs.h" +#include "util/typedefs.hpp" #include #include diff --git a/include/util/typedefs.hpp b/include/util/typedefs.hpp index dc77f39c7..efc15965f 100644 --- a/include/util/typedefs.hpp +++ b/include/util/typedefs.hpp @@ -29,7 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define TYPEDEFS_H #include -#include +#include "osrm/strong_typedef.hpp" #include // Necessary workaround for Windows as VS doesn't implement C99 diff --git a/include/util/xml_renderer.hpp b/include/util/xml_renderer.hpp index 44f7c2d9f..ffd155de8 100644 --- a/include/util/xml_renderer.hpp +++ b/include/util/xml_renderer.hpp @@ -28,9 +28,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef XML_RENDERER_HPP #define XML_RENDERER_HPP -#include "cast.hpp" +#include "util/cast.hpp" -#include +#include "osrm/json_container.hpp" namespace osrm { diff --git a/include/util/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp index ff65717a3..f56ff7cb1 100644 --- a/include/util/xor_fast_hash_storage.hpp +++ b/include/util/xor_fast_hash_storage.hpp @@ -28,7 +28,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef XOR_FAST_HASH_STORAGE_HPP #define XOR_FAST_HASH_STORAGE_HPP -#include "xor_fast_hash.hpp" +#include "util/xor_fast_hash.hpp" #include #include diff --git a/src/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp index ebe055cce..26b1badcb 100644 --- a/src/benchmarks/static_rtree.cpp +++ b/src/benchmarks/static_rtree.cpp @@ -25,13 +25,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../data_structures/query_node.hpp" -#include "../data_structures/static_rtree.hpp" -#include "../data_structures/edge_based_node.hpp" -#include "../algorithms/geospatial_query.hpp" -#include "../util/timing_util.hpp" +#include "extractor/query_node.hpp" +#include "util/static_rtree.hpp" +#include "extractor/edge_based_node.hpp" +#include "engine/geospatial_query.hpp" +#include "util/timing_util.hpp" -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/src/contractor/contractor_options.cpp b/src/contractor/contractor_options.cpp index d48346563..aa9a328c4 100644 --- a/src/contractor/contractor_options.cpp +++ b/src/contractor/contractor_options.cpp @@ -25,10 +25,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "contractor_options.hpp" +#include "contractor/contractor_options.hpp" #include "util/version.hpp" -#include "../util/simple_logger.hpp" +#include "util/simple_logger.hpp" #include #include diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index 2bd535093..d0d7d508d 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -25,22 +25,22 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "processing_chain.hpp" -#include "contractor.hpp" +#include "contractor/processing_chain.hpp" +#include "contractor/contractor.hpp" -#include "contractor.hpp" +#include "contractor/contractor.hpp" -#include "../data_structures/deallocating_vector.hpp" +#include "util/deallocating_vector.hpp" -#include "../algorithms/crc32_processor.hpp" -#include "../util/graph_loader.hpp" -#include "../util/integer_range.hpp" -#include "../util/lua_util.hpp" -#include "../util/osrm_exception.hpp" -#include "../util/simple_logger.hpp" -#include "../util/string_util.hpp" -#include "../util/timing_util.hpp" -#include "../typedefs.h" +#include "contractor/crc32_processor.hpp" +#include "util/graph_loader.hpp" +#include "util/integer_range.hpp" +#include "util/lua_util.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" +#include "util/string_util.hpp" +#include "util/timing_util.hpp" +#include "util/typedefs.hpp" #include @@ -55,7 +55,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "../util/debug_geometry.hpp" +#include "util/debug_geometry.hpp" Prepare::~Prepare() {} diff --git a/src/engine/descriptors/description_factory.cpp b/src/engine/descriptors/description_factory.cpp index 5086e0d17..a645987aa 100644 --- a/src/engine/descriptors/description_factory.cpp +++ b/src/engine/descriptors/description_factory.cpp @@ -25,15 +25,15 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "description_factory.hpp" +#include "engine/descriptors/description_factory.hpp" -#include "../algorithms/polyline_formatter.hpp" -#include "../algorithms/coordinate_calculation.hpp" -#include "../data_structures/internal_route_result.hpp" -#include "../data_structures/turn_instructions.hpp" -#include "../util/container.hpp" -#include "../util/integer_range.hpp" -#include "../typedefs.h" +#include "engine/polyline_formatter.hpp" +#include "util/coordinate_calculation.hpp" +#include "engine/internal_route_result.hpp" +#include "extractor/turn_instructions.hpp" +#include "util/container.hpp" +#include "util/integer_range.hpp" +#include "util/typedefs.hpp" DescriptionFactory::DescriptionFactory() : entire_length(0) { via_indices.push_back(0); } diff --git a/src/engine/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp index 280c90fa8..e95a1497b 100644 --- a/src/engine/douglas_peucker.cpp +++ b/src/engine/douglas_peucker.cpp @@ -25,12 +25,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "douglas_peucker.hpp" +#include "engine/douglas_peucker.hpp" -#include "../data_structures/segment_information.hpp" +#include "engine/segment_information.hpp" #include -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/src/engine/osrm_impl.cpp b/src/engine/osrm_impl.cpp index 3f5b62b19..04cc4a2e1 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/osrm_impl.cpp @@ -33,30 +33,30 @@ class named_mutex; } } -#include "osrm_impl.hpp" +#include "engine/osrm_impl.hpp" -#include "../plugins/distance_table.hpp" -#include "../plugins/hello_world.hpp" -#include "../plugins/nearest.hpp" -#include "../plugins/timestamp.hpp" -#include "../plugins/trip.hpp" -#include "../plugins/viaroute.hpp" -#include "../plugins/match.hpp" -#include "../server/data_structures/datafacade_base.hpp" -#include "../server/data_structures/internal_datafacade.hpp" -#include "../server/data_structures/shared_barriers.hpp" -#include "../server/data_structures/shared_datafacade.hpp" -#include "../util/make_unique.hpp" -#include "../util/routed_options.hpp" -#include "../util/simple_logger.hpp" +#include "engine/plugins/distance_table.hpp" +#include "engine/plugins/hello_world.hpp" +#include "engine/plugins/nearest.hpp" +#include "engine/plugins/timestamp.hpp" +#include "engine/plugins/trip.hpp" +#include "engine/plugins/viaroute.hpp" +#include "engine/plugins/match.hpp" +#include "engine/datafacade/datafacade_base.hpp" +#include "engine/datafacade/internal_datafacade.hpp" +#include "engine/datafacade/shared_barriers.hpp" +#include "engine/datafacade/shared_datafacade.hpp" +#include "util/make_unique.hpp" +#include "util/routed_options.hpp" +#include "util/simple_logger.hpp" #include #include #include -#include -#include -#include +#include "osrm/route_parameters.hpp" +#include "osrm/libosrm_config.hpp" +#include "osrm/osrm.hpp" #include #include diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp index 95c5bbb4a..bb1a7f383 100644 --- a/src/engine/phantom_node.cpp +++ b/src/engine/phantom_node.cpp @@ -25,12 +25,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "phantom_node.hpp" +#include "engine/phantom_node.hpp" -#include "../typedefs.h" -#include "travel_mode.hpp" +#include "util/typedefs.hpp" +#include "extractor/travel_mode.hpp" -#include +#include "osrm/coordinate.hpp" #include diff --git a/src/engine/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp index 0db75dcc6..56e6ca24e 100644 --- a/src/engine/polyline_compressor.cpp +++ b/src/engine/polyline_compressor.cpp @@ -25,10 +25,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "polyline_compressor.hpp" -#include "../data_structures/segment_information.hpp" +#include "engine/polyline_compressor.hpp" +#include "engine/segment_information.hpp" -#include +#include "osrm/coordinate.hpp" std::string PolylineCompressor::encode_vector(std::vector &numbers) const { diff --git a/src/engine/polyline_formatter.cpp b/src/engine/polyline_formatter.cpp index 670a6121f..4b6ac48fb 100644 --- a/src/engine/polyline_formatter.cpp +++ b/src/engine/polyline_formatter.cpp @@ -25,12 +25,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "polyline_formatter.hpp" +#include "engine/polyline_formatter.hpp" -#include "polyline_compressor.hpp" -#include "../data_structures/segment_information.hpp" +#include "engine/polyline_compressor.hpp" +#include "engine/segment_information.hpp" -#include +#include "osrm/coordinate.hpp" osrm::json::String PolylineFormatter::printEncodedString(const std::vector &polyline) const diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index 61789bbb4..f75324520 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -30,9 +30,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include +#include "osrm/route_parameters.hpp" -#include "../algorithms/polyline_compressor.hpp" +#include "engine/polyline_compressor.hpp" RouteParameters::RouteParameters() : zoom_level(18), print_instructions(false), alternate_route(true), geometry(true), diff --git a/src/engine/search_engine_data.cpp b/src/engine/search_engine_data.cpp index 3282a0ccb..321d814b1 100644 --- a/src/engine/search_engine_data.cpp +++ b/src/engine/search_engine_data.cpp @@ -25,9 +25,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "search_engine_data.hpp" +#include "engine/search_engine_data.hpp" -#include "binary_heap.hpp" +#include "util/binary_heap.hpp" void SearchEngineData::InitializeOrClearFirstThreadLocalStorage(const unsigned number_of_nodes) { diff --git a/src/extractor/compressed_edge_container.cpp b/src/extractor/compressed_edge_container.cpp index da916cee7..ee155d458 100644 --- a/src/extractor/compressed_edge_container.cpp +++ b/src/extractor/compressed_edge_container.cpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "compressed_edge_container.hpp" -#include "../util/simple_logger.hpp" +#include "extractor/compressed_edge_container.hpp" +#include "util/simple_logger.hpp" #include #include diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index f0c083d2d..682773a94 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -25,17 +25,17 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "edge_based_graph_factory.hpp" -#include "../algorithms/coordinate_calculation.hpp" -#include "../data_structures/percent.hpp" -#include "../util/compute_angle.hpp" -#include "../util/integer_range.hpp" -#include "../util/lua_util.hpp" -#include "../util/simple_logger.hpp" -#include "../util/timing_util.hpp" -#include "../util/osrm_exception.hpp" +#include "extractor/edge_based_graph_factory.hpp" +#include "util/coordinate_calculation.hpp" +#include "util/percent.hpp" +#include "util/compute_angle.hpp" +#include "util/integer_range.hpp" +#include "util/lua_util.hpp" +#include "util/simple_logger.hpp" +#include "util/timing_util.hpp" +#include "util/osrm_exception.hpp" -#include "../util/debug_geometry.hpp" +#include "util/debug_geometry.hpp" #include diff --git a/src/extractor/external_memory_node.cpp b/src/extractor/external_memory_node.cpp index d144f52a9..ebafbd2b7 100644 --- a/src/extractor/external_memory_node.cpp +++ b/src/extractor/external_memory_node.cpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "external_memory_node.hpp" -#include "query_node.hpp" +#include "extractor/external_memory_node.hpp" +#include "extractor/query_node.hpp" #include diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 48a626b1c..9592b9eba 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -25,18 +25,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "extraction_containers.hpp" -#include "extraction_way.hpp" +#include "extractor/extraction_containers.hpp" +#include "extractor/extraction_way.hpp" -#include "../algorithms/coordinate_calculation.hpp" -#include "../data_structures/node_id.hpp" -#include "../data_structures/range_table.hpp" +#include "util/coordinate_calculation.hpp" +#include "extractor/node_id.hpp" +#include "util/range_table.hpp" -#include "../util/osrm_exception.hpp" -#include "../util/simple_logger.hpp" -#include "../util/timing_util.hpp" -#include "../util/fingerprint.hpp" -#include "../util/lua_util.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" +#include "util/timing_util.hpp" +#include "util/fingerprint.hpp" +#include "util/lua_util.hpp" #include #include diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index f442efe31..6a2a1609d 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -25,31 +25,31 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "extractor.hpp" +#include "extractor/extractor.hpp" -#include "extraction_containers.hpp" -#include "extraction_node.hpp" -#include "extraction_way.hpp" -#include "extractor_callbacks.hpp" -#include "restriction_parser.hpp" -#include "scripting_environment.hpp" +#include "extractor/extraction_containers.hpp" +#include "extractor/extraction_node.hpp" +#include "extractor/extraction_way.hpp" +#include "extractor/extractor_callbacks.hpp" +#include "extractor/restriction_parser.hpp" +#include "extractor/scripting_environment.hpp" -#include "../data_structures/raster_source.hpp" -#include "../util/make_unique.hpp" -#include "../util/simple_logger.hpp" -#include "../util/timing_util.hpp" -#include "../util/lua_util.hpp" -#include "../util/graph_loader.hpp" +#include "extractor/raster_source.hpp" +#include "util/make_unique.hpp" +#include "util/simple_logger.hpp" +#include "util/timing_util.hpp" +#include "util/lua_util.hpp" +#include "util/graph_loader.hpp" -#include "../typedefs.h" +#include "util/typedefs.hpp" -#include "../data_structures/static_graph.hpp" -#include "../data_structures/static_rtree.hpp" -#include "../data_structures/restriction_map.hpp" -#include "../data_structures/compressed_edge_container.hpp" +#include "util/static_graph.hpp" +#include "util/static_rtree.hpp" +#include "extractor/restriction_map.hpp" +#include "extractor/compressed_edge_container.hpp" -#include "../algorithms/tarjan_scc.hpp" -#include "../algorithms/crc32_processor.hpp" +#include "extractor/tarjan_scc.hpp" +#include "contractor/crc32_processor.hpp" #include #include diff --git a/src/extractor/extractor_callbacks.cpp b/src/extractor/extractor_callbacks.cpp index 2eb1a9b46..013b20966 100644 --- a/src/extractor/extractor_callbacks.cpp +++ b/src/extractor/extractor_callbacks.cpp @@ -25,21 +25,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "extractor_callbacks.hpp" -#include "extraction_containers.hpp" -#include "extraction_node.hpp" -#include "extraction_way.hpp" +#include "extractor/extractor_callbacks.hpp" +#include "extractor/extraction_containers.hpp" +#include "extractor/extraction_node.hpp" +#include "extractor/extraction_way.hpp" -#include "../data_structures/external_memory_node.hpp" -#include "../data_structures/restriction.hpp" -#include "../util/container.hpp" -#include "../util/simple_logger.hpp" +#include "extractor/external_memory_node.hpp" +#include "extractor/restriction.hpp" +#include "util/container.hpp" +#include "util/simple_logger.hpp" #include #include -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp index b607dca95..2e0bc32b4 100644 --- a/src/extractor/extractor_options.cpp +++ b/src/extractor/extractor_options.cpp @@ -25,11 +25,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "extractor_options.hpp" +#include "extractor/extractor_options.hpp" #include "util/version.hpp" -#include "../util/ini_file.hpp" -#include "../util/simple_logger.hpp" +#include "util/ini_file.hpp" +#include "util/simple_logger.hpp" #include #include diff --git a/src/extractor/graph_compressor.cpp b/src/extractor/graph_compressor.cpp index f3b5f8dd9..c9e1d5b76 100644 --- a/src/extractor/graph_compressor.cpp +++ b/src/extractor/graph_compressor.cpp @@ -1,12 +1,12 @@ -#include "graph_compressor.hpp" +#include "extractor/graph_compressor.hpp" -#include "../data_structures/compressed_edge_container.hpp" -#include "../data_structures/dynamic_graph.hpp" -#include "../data_structures/node_based_graph.hpp" -#include "../data_structures/restriction_map.hpp" -#include "../data_structures/percent.hpp" +#include "extractor/compressed_edge_container.hpp" +#include "util/dynamic_graph.hpp" +#include "util/node_based_graph.hpp" +#include "extractor/restriction_map.hpp" +#include "util/percent.hpp" -#include "../util/simple_logger.hpp" +#include "util/simple_logger.hpp" GraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile) : speed_profile(std::move(speed_profile)) diff --git a/src/extractor/import_edge.cpp b/src/extractor/import_edge.cpp index bf2829d4e..36c409cbe 100644 --- a/src/extractor/import_edge.cpp +++ b/src/extractor/import_edge.cpp @@ -25,10 +25,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "import_edge.hpp" +#include "extractor/import_edge.hpp" -#include "travel_mode.hpp" -#include "../typedefs.h" +#include "extractor/travel_mode.hpp" +#include "util/typedefs.hpp" bool NodeBasedEdge::operator<(const NodeBasedEdge &other) const { diff --git a/src/extractor/raster_source.cpp b/src/extractor/raster_source.cpp index 9e880a218..b5f9665a6 100644 --- a/src/extractor/raster_source.cpp +++ b/src/extractor/raster_source.cpp @@ -25,12 +25,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "raster_source.hpp" +#include "extractor/raster_source.hpp" -#include "../util/simple_logger.hpp" -#include "../util/timing_util.hpp" +#include "util/simple_logger.hpp" +#include "util/timing_util.hpp" -#include +#include "osrm/coordinate.hpp" #include diff --git a/src/extractor/restriction_map.cpp b/src/extractor/restriction_map.cpp index eb685be80..b92fc707e 100644 --- a/src/extractor/restriction_map.cpp +++ b/src/extractor/restriction_map.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "restriction_map.hpp" +#include "extractor/restriction_map.hpp" RestrictionMap::RestrictionMap(const std::vector &restriction_list) : m_count(0) { diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index 6a54cde20..e3c1e3f14 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -25,13 +25,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "restriction_parser.hpp" -#include "extraction_way.hpp" +#include "extractor/restriction_parser.hpp" +#include "extractor/extraction_way.hpp" -#include "../data_structures/external_memory_node.hpp" -#include "../util/lua_util.hpp" -#include "../util/osrm_exception.hpp" -#include "../util/simple_logger.hpp" +#include "extractor/external_memory_node.hpp" +#include "util/lua_util.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" #include #include diff --git a/src/extractor/scripting_environment.cpp b/src/extractor/scripting_environment.cpp index 9653ca049..df8cb92ce 100644 --- a/src/extractor/scripting_environment.cpp +++ b/src/extractor/scripting_environment.cpp @@ -25,18 +25,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "scripting_environment.hpp" +#include "extractor/scripting_environment.hpp" -#include "extraction_helper_functions.hpp" -#include "extraction_node.hpp" -#include "extraction_way.hpp" -#include "internal_extractor_edge.hpp" -#include "../data_structures/external_memory_node.hpp" -#include "../data_structures/raster_source.hpp" -#include "../util/lua_util.hpp" -#include "../util/osrm_exception.hpp" -#include "../util/simple_logger.hpp" -#include "../typedefs.h" +#include "extractor/extraction_helper_functions.hpp" +#include "extractor/extraction_node.hpp" +#include "extractor/extraction_way.hpp" +#include "extractor/internal_extractor_edge.hpp" +#include "extractor/external_memory_node.hpp" +#include "extractor/raster_source.hpp" +#include "util/lua_util.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/src/server/connection.cpp b/src/server/connection.cpp index dbf85fd2a..ddfac1c74 100644 --- a/src/server/connection.cpp +++ b/src/server/connection.cpp @@ -25,9 +25,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "connection.hpp" -#include "request_handler.hpp" -#include "request_parser.hpp" +#include "server/connection.hpp" +#include "server/request_handler.hpp" +#include "server/request_parser.hpp" #include #include diff --git a/src/server/http/reply.cpp b/src/server/http/reply.cpp index a3d3d9624..39957add8 100644 --- a/src/server/http/reply.cpp +++ b/src/server/http/reply.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "reply.hpp" +#include "server/http/reply.hpp" #include diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index 54f039502..a506df671 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -25,21 +25,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "request_handler.hpp" +#include "server/request_handler.hpp" -#include "api_grammar.hpp" -#include "http/reply.hpp" -#include "http/request.hpp" +#include "server/api_grammar.hpp" +#include "server/http/reply.hpp" +#include "server/http/request.hpp" -#include "../util/json_renderer.hpp" -#include "../util/simple_logger.hpp" -#include "../util/string_util.hpp" -#include "../util/xml_renderer.hpp" -#include "../typedefs.h" +#include "util/json_renderer.hpp" +#include "util/simple_logger.hpp" +#include "util/string_util.hpp" +#include "util/xml_renderer.hpp" +#include "util/typedefs.hpp" -#include -#include -#include +#include "osrm/route_parameters.hpp" +#include "osrm/json_container.hpp" +#include "osrm/osrm.hpp" #include diff --git a/src/server/request_parser.cpp b/src/server/request_parser.cpp index b52d730d9..83cebb1af 100644 --- a/src/server/request_parser.cpp +++ b/src/server/request_parser.cpp @@ -25,13 +25,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "request_parser.hpp" +#include "server/request_parser.hpp" -#include "http/compression_type.hpp" -#include "http/header.hpp" -#include "http/request.hpp" +#include "server/http/compression_type.hpp" +#include "server/http/header.hpp" +#include "server/http/request.hpp" -#include "../data_structures/tribool.hpp" +#include "util/tribool.hpp" #include diff --git a/src/tools/check-hsgr.cpp b/src/tools/check-hsgr.cpp index 2418a473f..0dc8310b3 100644 --- a/src/tools/check-hsgr.cpp +++ b/src/tools/check-hsgr.cpp @@ -24,13 +24,13 @@ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../data_structures/percent.hpp" -#include "../data_structures/query_edge.hpp" -#include "../data_structures/static_graph.hpp" -#include "../util/integer_range.hpp" -#include "../util/graph_loader.hpp" -#include "../util/simple_logger.hpp" -#include "../util/osrm_exception.hpp" +#include "util/percent.hpp" +#include "contractor/query_edge.hpp" +#include "util/static_graph.hpp" +#include "util/integer_range.hpp" +#include "util/graph_loader.hpp" +#include "util/simple_logger.hpp" +#include "util/osrm_exception.hpp" #include #include diff --git a/src/tools/components.cpp b/src/tools/components.cpp index db0e52685..7634d9d8e 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -25,16 +25,16 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../typedefs.h" -#include "../algorithms/tarjan_scc.hpp" -#include "../algorithms/coordinate_calculation.hpp" -#include "../data_structures/dynamic_graph.hpp" -#include "../data_structures/static_graph.hpp" -#include "../util/fingerprint.hpp" -#include "../util/graph_loader.hpp" -#include "../util/make_unique.hpp" -#include "../util/osrm_exception.hpp" -#include "../util/simple_logger.hpp" +#include "util/typedefs.hpp" +#include "extractor/tarjan_scc.hpp" +#include "util/coordinate_calculation.hpp" +#include "util/dynamic_graph.hpp" +#include "util/static_graph.hpp" +#include "util/fingerprint.hpp" +#include "util/graph_loader.hpp" +#include "util/make_unique.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" #include @@ -46,7 +46,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #endif -#include +#include "osrm/coordinate.hpp" #include #include diff --git a/src/tools/datastore.cpp b/src/tools/datastore.cpp index 504dd3d44..42b600aa4 100644 --- a/src/tools/datastore.cpp +++ b/src/tools/datastore.cpp @@ -25,26 +25,26 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "data_structures/original_edge_data.hpp" -#include "data_structures/range_table.hpp" -#include "data_structures/query_edge.hpp" -#include "data_structures/query_node.hpp" -#include "data_structures/shared_memory_factory.hpp" -#include "data_structures/shared_memory_vector_wrapper.hpp" -#include "data_structures/static_graph.hpp" -#include "data_structures/static_rtree.hpp" -#include "data_structures/travel_mode.hpp" -#include "data_structures/turn_instructions.hpp" -#include "server/data_structures/datafacade_base.hpp" -#include "server/data_structures/shared_datatype.hpp" -#include "server/data_structures/shared_barriers.hpp" +#include "extractor/original_edge_data.hpp" +#include "util/range_table.hpp" +#include "contractor/query_edge.hpp" +#include "extractor/query_node.hpp" +#include "datastore/shared_memory_factory.hpp" +#include "util/shared_memory_vector_wrapper.hpp" +#include "util/static_graph.hpp" +#include "util/static_rtree.hpp" +#include "extractor/travel_mode.hpp" +#include "extractor/turn_instructions.hpp" +#include "engine/datafacade/datafacade_base.hpp" +#include "engine/datafacade/shared_datatype.hpp" +#include "engine/datafacade/shared_barriers.hpp" #include "util/datastore_options.hpp" #include "util/simple_logger.hpp" #include "util/osrm_exception.hpp" #include "util/fingerprint.hpp" -#include "typedefs.h" +#include "util/typedefs.hpp" -#include +#include "osrm/coordinate.hpp" using RTreeLeaf = BaseDataFacade::RTreeLeaf; using RTreeNode = StaticRTree::vector, true>::TreeNode; diff --git a/src/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp index 41e41b2b1..2de94c61b 100644 --- a/src/tools/io-benchmark.cpp +++ b/src/tools/io-benchmark.cpp @@ -26,9 +26,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "util/version.hpp" -#include "../util/osrm_exception.hpp" -#include "../util/simple_logger.hpp" -#include "../util/timing_util.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" +#include "util/timing_util.hpp" #include #include diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index b4404c12e..4d1325549 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -30,8 +30,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "util/routed_options.hpp" #include "util/simple_logger.hpp" -#include -#include +#include "osrm/osrm.hpp" +#include "osrm/libosrm_config.hpp" #ifdef __linux__ #include diff --git a/src/tools/simpleclient.cpp b/src/tools/simpleclient.cpp index 17058a641..aa3aa262e 100644 --- a/src/tools/simpleclient.cpp +++ b/src/tools/simpleclient.cpp @@ -26,14 +26,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "util/version.hpp" -#include "../util/json_renderer.hpp" -#include "../util/routed_options.hpp" -#include "../util/simple_logger.hpp" +#include "util/json_renderer.hpp" +#include "util/routed_options.hpp" +#include "util/simple_logger.hpp" -#include -#include -#include -#include +#include "osrm/json_container.hpp" +#include "osrm/libosrm_config.hpp" +#include "osrm/route_parameters.hpp" +#include "osrm/osrm.hpp" #include diff --git a/src/tools/springclean.cpp b/src/tools/springclean.cpp index 18e5711f9..296d96e5c 100644 --- a/src/tools/springclean.cpp +++ b/src/tools/springclean.cpp @@ -27,10 +27,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include "../data_structures/shared_memory_factory.hpp" -#include "../server/data_structures/shared_datatype.hpp" +#include "datastore/shared_memory_factory.hpp" +#include "engine/datafacade/shared_datatype.hpp" #include "util/version.hpp" -#include "../util/simple_logger.hpp" +#include "util/simple_logger.hpp" void delete_region(const SharedDataType region) { diff --git a/src/tools/unlock_all_mutexes.cpp b/src/tools/unlock_all_mutexes.cpp index 953254ba8..3b4c9b072 100644 --- a/src/tools/unlock_all_mutexes.cpp +++ b/src/tools/unlock_all_mutexes.cpp @@ -26,8 +26,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "util/version.hpp" -#include "../util/simple_logger.hpp" -#include "../server/data_structures/shared_barriers.hpp" +#include "util/simple_logger.hpp" +#include "engine/datafacade/shared_barriers.hpp" #include diff --git a/src/util/compute_angle.cpp b/src/util/compute_angle.cpp index 8cd8aa441..b821d7958 100644 --- a/src/util/compute_angle.cpp +++ b/src/util/compute_angle.cpp @@ -25,12 +25,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "compute_angle.hpp" +#include "util/compute_angle.hpp" -#include "trigonometry_table.hpp" -#include "../util/mercator.hpp" +#include "util/trigonometry_table.hpp" +#include "util/mercator.hpp" -#include +#include "osrm/coordinate.hpp" #include diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index 208f3eb07..63f81aadb 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -25,12 +25,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../algorithms/coordinate_calculation.hpp" +#include "util/coordinate_calculation.hpp" #ifndef NDEBUG -#include "../util/simple_logger.hpp" +#include "util/simple_logger.hpp" #endif -#include +#include "osrm/coordinate.hpp" #ifndef NDEBUG #include diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index ff7626e90..54ebaf947 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -25,14 +25,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "coordinate_calculation.hpp" +#include "util/coordinate_calculation.hpp" -#include "../util/mercator.hpp" -#include "../util/string_util.hpp" +#include "util/mercator.hpp" +#include "util/string_util.hpp" #include -#include +#include "osrm/coordinate.hpp" #include diff --git a/src/util/hilbert_value.cpp b/src/util/hilbert_value.cpp index d0d61e60a..d65354030 100644 --- a/src/util/hilbert_value.cpp +++ b/src/util/hilbert_value.cpp @@ -25,9 +25,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "hilbert_value.hpp" +#include "util/hilbert_value.hpp" -#include +#include "osrm/coordinate.hpp" uint64_t HilbertCode::operator()(const FixedPointCoordinate ¤t_coordinate) const { diff --git a/src/util/mercator.cpp b/src/util/mercator.cpp index 0ccd99981..239441aa6 100644 --- a/src/util/mercator.cpp +++ b/src/util/mercator.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "mercator.hpp" +#include "util/mercator.hpp" #include diff --git a/src/util/osrm_exception.cpp b/src/util/osrm_exception.cpp index 9738b8e36..9715cac72 100644 --- a/src/util/osrm_exception.cpp +++ b/src/util/osrm_exception.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "osrm_exception.hpp" +#include "util/osrm_exception.hpp" namespace osrm { diff --git a/src/util/simple_logger.cpp b/src/util/simple_logger.cpp index e3f4f8ed0..362dce638 100644 --- a/src/util/simple_logger.cpp +++ b/src/util/simple_logger.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "simple_logger.hpp" +#include "util/simple_logger.hpp" #ifdef _MSC_VER #include #define isatty _isatty diff --git a/unit_tests/engine/douglas_peucker.cpp b/unit_tests/engine/douglas_peucker.cpp index 8a3920976..519e90da4 100644 --- a/unit_tests/engine/douglas_peucker.cpp +++ b/unit_tests/engine/douglas_peucker.cpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../algorithms/douglas_peucker.hpp" -#include "../../data_structures/segment_information.hpp" +#include "engine/douglas_peucker.hpp" +#include "engine/segment_information.hpp" #include #include diff --git a/unit_tests/engine/geometry_string.cpp b/unit_tests/engine/geometry_string.cpp index ab9f35755..7b2dd3ccb 100644 --- a/unit_tests/engine/geometry_string.cpp +++ b/unit_tests/engine/geometry_string.cpp @@ -28,8 +28,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#include "../../algorithms/polyline_compressor.hpp" -#include "../../algorithms/coordinate_calculation.hpp" +#include "engine/polyline_compressor.hpp" +#include "util/coordinate_calculation.hpp" #include diff --git a/unit_tests/extractor/compressed_edge_container.cpp b/unit_tests/extractor/compressed_edge_container.cpp index 12d9d3f4b..4a83f0402 100644 --- a/unit_tests/extractor/compressed_edge_container.cpp +++ b/unit_tests/extractor/compressed_edge_container.cpp @@ -1,5 +1,5 @@ -#include "../../data_structures/compressed_edge_container.hpp" -#include "../../typedefs.h" +#include "extractor/compressed_edge_container.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/unit_tests/extractor/graph_compressor.cpp b/unit_tests/extractor/graph_compressor.cpp index a3407c04d..07e3b7ef7 100644 --- a/unit_tests/extractor/graph_compressor.cpp +++ b/unit_tests/extractor/graph_compressor.cpp @@ -1,9 +1,9 @@ -#include "../../algorithms/graph_compressor.hpp" -#include "../../data_structures/compressed_edge_container.hpp" -#include "../../data_structures/restriction_map.hpp" -#include "../../data_structures/node_based_graph.hpp" -#include "../../extractor/speed_profile.hpp" -#include "../../typedefs.h" +#include "extractor/graph_compressor.hpp" +#include "extractor/compressed_edge_container.hpp" +#include "extractor/restriction_map.hpp" +#include "util/node_based_graph.hpp" +#include "extractor/speed_profile.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/unit_tests/extractor/raster_source.cpp b/unit_tests/extractor/raster_source.cpp index 691cba108..0406676b9 100644 --- a/unit_tests/extractor/raster_source.cpp +++ b/unit_tests/extractor/raster_source.cpp @@ -25,9 +25,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../data_structures/raster_source.hpp" -#include "../../typedefs.h" -#include "../../util/osrm_exception.hpp" +#include "extractor/raster_source.hpp" +#include "util/typedefs.hpp" +#include "util/osrm_exception.hpp" #include diff --git a/unit_tests/util/bearing.cpp b/unit_tests/util/bearing.cpp index f0866de33..93d3eb313 100644 --- a/unit_tests/util/bearing.cpp +++ b/unit_tests/util/bearing.cpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../util/bearing.hpp" -#include "../../typedefs.h" +#include "util/bearing.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/unit_tests/util/binary_heap.cpp b/unit_tests/util/binary_heap.cpp index ee22a1fbb..6b7cf64ff 100644 --- a/unit_tests/util/binary_heap.cpp +++ b/unit_tests/util/binary_heap.cpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../data_structures/binary_heap.hpp" -#include "../../typedefs.h" +#include "util/binary_heap.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/unit_tests/util/coordinate.cpp b/unit_tests/util/coordinate.cpp index e8209763e..f153175ab 100644 --- a/unit_tests/util/coordinate.cpp +++ b/unit_tests/util/coordinate.cpp @@ -27,7 +27,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include "../../algorithms/coordinate_calculation.hpp" +#include "util/coordinate_calculation.hpp" #include diff --git a/unit_tests/util/duration_parsing.cpp b/unit_tests/util/duration_parsing.cpp index e3035dce7..d0599106a 100644 --- a/unit_tests/util/duration_parsing.cpp +++ b/unit_tests/util/duration_parsing.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../extractor/extraction_helper_functions.hpp" +#include "extractor/extraction_helper_functions.hpp" #include #include diff --git a/unit_tests/util/dynamic_graph.cpp b/unit_tests/util/dynamic_graph.cpp index df8eb21b1..585d2e471 100644 --- a/unit_tests/util/dynamic_graph.cpp +++ b/unit_tests/util/dynamic_graph.cpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../data_structures/dynamic_graph.hpp" -#include "../../typedefs.h" +#include "util/dynamic_graph.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/unit_tests/util/range_table.cpp b/unit_tests/util/range_table.cpp index 065840ba1..8d30a0876 100644 --- a/unit_tests/util/range_table.cpp +++ b/unit_tests/util/range_table.cpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../data_structures/range_table.hpp" -#include "../../typedefs.h" +#include "util/range_table.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/unit_tests/util/static_graph.cpp b/unit_tests/util/static_graph.cpp index ddadd7fdb..21c034be2 100644 --- a/unit_tests/util/static_graph.cpp +++ b/unit_tests/util/static_graph.cpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../data_structures/static_graph.hpp" -#include "../../typedefs.h" +#include "util/static_graph.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index 2539d5ffb..33c9eed74 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -25,13 +25,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../algorithms/coordinate_calculation.hpp" -#include "../../algorithms/geospatial_query.hpp" -#include "../../data_structures/static_rtree.hpp" -#include "../../data_structures/query_node.hpp" -#include "../../data_structures/edge_based_node.hpp" -#include "../../util/floating_point.hpp" -#include "../../typedefs.h" +#include "util/coordinate_calculation.hpp" +#include "engine/geospatial_query.hpp" +#include "util/static_rtree.hpp" +#include "extractor/query_node.hpp" +#include "extractor/edge_based_node.hpp" +#include "util/floating_point.hpp" +#include "util/typedefs.hpp" #include #include diff --git a/unit_tests/util/string_util.cpp b/unit_tests/util/string_util.cpp index cf82eba5b..9ec734aeb 100644 --- a/unit_tests/util/string_util.cpp +++ b/unit_tests/util/string_util.cpp @@ -25,7 +25,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "../../util/string_util.hpp" +#include "util/string_util.hpp" #include #include From 02a49c8a686de35f721360adf760140b50c2f782 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sun, 3 Jan 2016 17:03:20 +0100 Subject: [PATCH 008/701] Use local includes before system includes --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 67bd60ded..c64c5d978 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,8 +33,8 @@ option(ENABLE_JSON_LOGGING "Adds additional JSON debug logging to the response" option(DEBUG_GEOMETRY "Enables an option to dump GeoJSON of the final routing graph" OFF) option(BUILD_TOOLS "Build OSRM tools" OFF) -include_directories(${CMAKE_CURRENT_BINARY_DIR}/include/) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/) +include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}/include/) +include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/) include_directories(SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/third_party/) include_directories(SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/third_party/libosmium/include/) From facbe2c012994026cdfe6c0dc8045c2de46100fc Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sun, 3 Jan 2016 18:10:09 +0100 Subject: [PATCH 009/701] Fix test names for travis --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index c0659495b..dc0405142 100644 --- a/.travis.yml +++ b/.travis.yml @@ -139,8 +139,8 @@ script: - make --jobs=2 - make tests --jobs=2 - make benchmarks - - ./algorithm-tests - - ./datastructure-tests + - ./extractor-tests + - ./engine-tests - ./util-tests - cd .. - cucumber -p verify From 93a2e667042dcb19dd4ad723cf1b59048528c60d Mon Sep 17 00:00:00 2001 From: Mortada Mehyar Date: Sat, 26 Dec 2015 11:12:10 -0800 Subject: [PATCH 010/701] use double precision calculations instead of mixing double and float --- include/engine/geospatial_query.hpp | 26 ++--- .../routing_algorithms/map_matching.hpp | 2 +- include/osrm/coordinate.hpp | 4 +- include/util/coordinate_calculation.hpp | 22 ++--- include/util/rectangle.hpp | 10 +- src/util/coordinate.cpp | 2 +- src/util/coordinate_calculation.cpp | 94 +++++++++---------- unit_tests/util/coordinate.cpp | 8 +- unit_tests/util/static_rtree.cpp | 20 ++-- 9 files changed, 94 insertions(+), 94 deletions(-) diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index 05105554e..95a41da93 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -30,7 +30,7 @@ template class GeospatialQuery // Does not filter by small/big component! std::vector NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, - const float max_distance, + const double max_distance, const int bearing = 0, const int bearing_range = 180) { @@ -40,7 +40,7 @@ template class GeospatialQuery { return checkSegmentBearing(data, bearing, bearing_range); }, - [max_distance](const std::size_t, const float min_dist) + [max_distance](const std::size_t, const double min_dist) { return min_dist > max_distance; }); @@ -61,7 +61,7 @@ template class GeospatialQuery { return checkSegmentBearing(data, bearing, bearing_range); }, - [max_results](const std::size_t num_results, const float) + [max_results](const std::size_t num_results, const double) { return num_results >= max_results; }); @@ -99,7 +99,7 @@ template class GeospatialQuery return use_directions; }, - [&has_big_component](const std::size_t num_results, const float) + [&has_big_component](const std::size_t num_results, const double) { return num_results > 0 && has_big_component; }); @@ -132,7 +132,7 @@ template class GeospatialQuery const EdgeData &data) const { FixedPointCoordinate point_on_segment; - float ratio; + double ratio; const auto current_perpendicular_distance = coordinate_calculation::perpendicular_distance( coordinates->at(data.u), coordinates->at(data.v), input_coordinate, point_on_segment, ratio); @@ -140,7 +140,7 @@ template class GeospatialQuery auto transformed = PhantomNodeWithDistance { PhantomNode{data, point_on_segment}, current_perpendicular_distance }; - ratio = std::min(1.f, std::max(0.f, ratio)); + ratio = std::min(1.0, std::max(0.0, ratio)); if (SPECIAL_NODEID != transformed.phantom_node.forward_node_id) { @@ -148,27 +148,27 @@ template class GeospatialQuery } if (SPECIAL_NODEID != transformed.phantom_node.reverse_node_id) { - transformed.phantom_node.reverse_weight *= 1.f - ratio; + transformed.phantom_node.reverse_weight *= 1.0 - ratio; } return transformed; } std::pair checkSegmentBearing(const EdgeData &segment, - const float filter_bearing, - const float filter_bearing_range) + const int filter_bearing, + const int filter_bearing_range) { - const float forward_edge_bearing = + const double forward_edge_bearing = coordinate_calculation::bearing(coordinates->at(segment.u), coordinates->at(segment.v)); - const float backward_edge_bearing = (forward_edge_bearing + 180) > 360 + const double backward_edge_bearing = (forward_edge_bearing + 180) > 360 ? (forward_edge_bearing - 180) : (forward_edge_bearing + 180); const bool forward_bearing_valid = - bearing::CheckInBounds(forward_edge_bearing, filter_bearing, filter_bearing_range) && + bearing::CheckInBounds(std::round(forward_edge_bearing), filter_bearing, filter_bearing_range) && segment.forward_edge_based_node_id != SPECIAL_NODEID; const bool backward_bearing_valid = - bearing::CheckInBounds(backward_edge_bearing, filter_bearing, filter_bearing_range) && + bearing::CheckInBounds(std::round(backward_edge_bearing), filter_bearing, filter_bearing_range) && segment.reverse_edge_based_node_id != SPECIAL_NODEID; return std::make_pair(forward_bearing_valid, backward_bearing_valid); } diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 9afc2653a..00db48eff 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -359,7 +359,7 @@ class MapMatching final : public BasicRoutingInterface(0u, reconstructed_indices.size())) diff --git a/include/osrm/coordinate.hpp b/include/osrm/coordinate.hpp index 6318465e1..46029cbc9 100644 --- a/include/osrm/coordinate.hpp +++ b/include/osrm/coordinate.hpp @@ -34,7 +34,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace { -constexpr static const float COORDINATE_PRECISION = 1000000.f; +constexpr static const double COORDINATE_PRECISION = 1000000.0; } struct FixedPointCoordinate @@ -58,7 +58,7 @@ struct FixedPointCoordinate bool is_valid() const; bool operator==(const FixedPointCoordinate &other) const; - float bearing(const FixedPointCoordinate &other) const; + double bearing(const FixedPointCoordinate &other) const; void output(std::ostream &out) const; }; diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index 80ec7c289..0ab9fe617 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -41,41 +41,41 @@ namespace coordinate_calculation double haversine_distance(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); - float great_circle_distance(const FixedPointCoordinate &first_coordinate, + double great_circle_distance(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); - float great_circle_distance(const int lat1, const int lon1, const int lat2, const int lon2); + double great_circle_distance(const int lat1, const int lon1, const int lat2, const int lon2); void lat_or_lon_to_string(const int value, std::string &output); - float perpendicular_distance(const FixedPointCoordinate &segment_source, + double perpendicular_distance(const FixedPointCoordinate &segment_source, const FixedPointCoordinate &segment_target, const FixedPointCoordinate &query_location); - float perpendicular_distance(const FixedPointCoordinate &segment_source, + double perpendicular_distance(const FixedPointCoordinate &segment_source, const FixedPointCoordinate &segment_target, const FixedPointCoordinate &query_location, FixedPointCoordinate &nearest_location, - float &ratio); + double &ratio); - float perpendicular_distance_from_projected_coordinate( + double perpendicular_distance_from_projected_coordinate( const FixedPointCoordinate &segment_source, const FixedPointCoordinate &segment_target, const FixedPointCoordinate &query_location, const std::pair &projected_coordinate); - float perpendicular_distance_from_projected_coordinate( + double perpendicular_distance_from_projected_coordinate( const FixedPointCoordinate &segment_source, const FixedPointCoordinate &segment_target, const FixedPointCoordinate &query_location, const std::pair &projected_coordinate, FixedPointCoordinate &nearest_location, - float &ratio); + double &ratio); - float deg_to_rad(const float degree); - float rad_to_deg(const float radian); + double deg_to_rad(const double degree); + double rad_to_deg(const double radian); - float bearing(const FixedPointCoordinate &first_coordinate, + double bearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); } diff --git a/include/util/rectangle.hpp b/include/util/rectangle.hpp index f4dd5280d..9aa99ac2c 100644 --- a/include/util/rectangle.hpp +++ b/include/util/rectangle.hpp @@ -84,7 +84,7 @@ struct RectangleInt2D Contains(lower_left)); } - float GetMinDist(const FixedPointCoordinate &location) const + double GetMinDist(const FixedPointCoordinate &location) const { const bool is_contained = Contains(location); if (is_contained) @@ -117,7 +117,7 @@ struct RectangleInt2D BOOST_ASSERT(d != INVALID); - float min_dist = std::numeric_limits::max(); + double min_dist = std::numeric_limits::max(); switch (d) { case NORTH: @@ -156,14 +156,14 @@ struct RectangleInt2D break; } - BOOST_ASSERT(min_dist < std::numeric_limits::max()); + BOOST_ASSERT(min_dist < std::numeric_limits::max()); return min_dist; } - float GetMinMaxDist(const FixedPointCoordinate &location) const + double GetMinMaxDist(const FixedPointCoordinate &location) const { - float min_max_dist = std::numeric_limits::max(); + double min_max_dist = std::numeric_limits::max(); // Get minmax distance to each of the four sides const FixedPointCoordinate upper_left(max_lat, min_lon); const FixedPointCoordinate upper_right(max_lat, max_lon); diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index 63f81aadb..6124dd8fe 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -81,7 +81,7 @@ void FixedPointCoordinate::output(std::ostream &out) const out << "(" << lat / COORDINATE_PRECISION << "," << lon / COORDINATE_PRECISION << ")"; } -float FixedPointCoordinate::bearing(const FixedPointCoordinate &other) const +double FixedPointCoordinate::bearing(const FixedPointCoordinate &other) const { return coordinate_calculation::bearing(other, *this); } diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index 54ebaf947..e1975ddeb 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -40,10 +40,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace { -constexpr static const float RAD = 0.017453292519943295769236907684886f; +constexpr static const double RAD = 0.017453292519943295769236907684886; // earth radius varies between 6,356.750-6,378.135 km (3,949.901-3,963.189mi) // The IUGG value for the equatorial radius is 6378.137 km (3963.19 miles) -constexpr static const float earth_radius = 6372797.560856f; +constexpr static const double earth_radius = 6372797.560856; } namespace coordinate_calculation @@ -84,14 +84,14 @@ double haversine_distance(const FixedPointCoordinate &coordinate_1, coordinate_2.lon); } -float great_circle_distance(const FixedPointCoordinate &coordinate_1, +double great_circle_distance(const FixedPointCoordinate &coordinate_1, const FixedPointCoordinate &coordinate_2) { return great_circle_distance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, coordinate_2.lon); } -float great_circle_distance(const int lat1, +double great_circle_distance(const int lat1, const int lon1, const int lat2, const int lon2) @@ -101,32 +101,32 @@ float great_circle_distance(const int lat1, BOOST_ASSERT(lat2 != std::numeric_limits::min()); BOOST_ASSERT(lon2 != std::numeric_limits::min()); - const float float_lat1 = (lat1 / COORDINATE_PRECISION) * RAD; - const float float_lon1 = (lon1 / COORDINATE_PRECISION) * RAD; - const float float_lat2 = (lat2 / COORDINATE_PRECISION) * RAD; - const float float_lon2 = (lon2 / COORDINATE_PRECISION) * RAD; + const double float_lat1 = (lat1 / COORDINATE_PRECISION) * RAD; + const double float_lon1 = (lon1 / COORDINATE_PRECISION) * RAD; + const double float_lat2 = (lat2 / COORDINATE_PRECISION) * RAD; + const double float_lon2 = (lon2 / COORDINATE_PRECISION) * RAD; - const float x_value = (float_lon2 - float_lon1) * std::cos((float_lat1 + float_lat2) / 2.f); - const float y_value = float_lat2 - float_lat1; + const double x_value = (float_lon2 - float_lon1) * std::cos((float_lat1 + float_lat2) / 2.0); + const double y_value = float_lat2 - float_lat1; return std::hypot(x_value, y_value) * earth_radius; } -float perpendicular_distance(const FixedPointCoordinate &source_coordinate, +double perpendicular_distance(const FixedPointCoordinate &source_coordinate, const FixedPointCoordinate &target_coordinate, const FixedPointCoordinate &query_location) { - float ratio; + double ratio; FixedPointCoordinate nearest_location; return perpendicular_distance(source_coordinate, target_coordinate, query_location, nearest_location, ratio); } -float perpendicular_distance(const FixedPointCoordinate &segment_source, +double perpendicular_distance(const FixedPointCoordinate &segment_source, const FixedPointCoordinate &segment_target, const FixedPointCoordinate &query_location, FixedPointCoordinate &nearest_location, - float &ratio) + double &ratio) { return perpendicular_distance_from_projected_coordinate( segment_source, segment_target, query_location, @@ -135,13 +135,13 @@ float perpendicular_distance(const FixedPointCoordinate &segment_source, nearest_location, ratio); } -float perpendicular_distance_from_projected_coordinate( +double perpendicular_distance_from_projected_coordinate( const FixedPointCoordinate &source_coordinate, const FixedPointCoordinate &target_coordinate, const FixedPointCoordinate &query_location, const std::pair &projected_coordinate) { - float ratio; + double ratio; FixedPointCoordinate nearest_location; return perpendicular_distance_from_projected_coordinate(source_coordinate, target_coordinate, @@ -149,13 +149,13 @@ float perpendicular_distance_from_projected_coordinate( nearest_location, ratio); } -float perpendicular_distance_from_projected_coordinate( +double perpendicular_distance_from_projected_coordinate( const FixedPointCoordinate &segment_source, const FixedPointCoordinate &segment_target, const FixedPointCoordinate &query_location, const std::pair &projected_coordinate, FixedPointCoordinate &nearest_location, - float &ratio) + double &ratio) { BOOST_ASSERT(query_location.is_valid()); @@ -171,7 +171,7 @@ float perpendicular_distance_from_projected_coordinate( { const double m = (d - b) / (c - a); // slope // Projection of (x,y) on line joining (a,b) and (c,d) - p = ((x + (m * y)) + (m * m * a - m * b)) / (1.f + m * m); + p = ((x + (m * y)) + (m * m * a - m * b)) / (1.0 + m * m); q = b + m * (p - a); } else @@ -182,36 +182,36 @@ float perpendicular_distance_from_projected_coordinate( nY = (d * p - c * q) / (a * d - b * c); // discretize the result to coordinate precision. it's a hack! - if (std::abs(nY) < (1.f / COORDINATE_PRECISION)) + if (std::abs(nY) < (1.0 / COORDINATE_PRECISION)) { - nY = 0.f; + nY = 0.0; } // compute ratio ratio = - static_cast((p - nY * a) / c); // These values are actually n/m+n and m/m+n , we need + static_cast((p - nY * a) / c); // These values are actually n/m+n and m/m+n , we need // not calculate the explicit values of m an n as we // are just interested in the ratio if (std::isnan(ratio)) { - ratio = (segment_target == query_location ? 1.f : 0.f); + ratio = (segment_target == query_location ? 1.0 : 0.0); } - else if (std::abs(ratio) <= std::numeric_limits::epsilon()) + else if (std::abs(ratio) <= std::numeric_limits::epsilon()) { - ratio = 0.f; + ratio = 0.0; } - else if (std::abs(ratio - 1.f) <= std::numeric_limits::epsilon()) + else if (std::abs(ratio - 1.0) <= std::numeric_limits::epsilon()) { - ratio = 1.f; + ratio = 1.0; } // compute nearest location BOOST_ASSERT(!std::isnan(ratio)); - if (ratio <= 0.f) + if (ratio <= 0.0) { nearest_location = segment_source; } - else if (ratio >= 1.f) + else if (ratio >= 1.0) { nearest_location = segment_target; } @@ -223,9 +223,9 @@ float perpendicular_distance_from_projected_coordinate( } BOOST_ASSERT(nearest_location.is_valid()); - const float approximate_distance = + const double approximate_distance = great_circle_distance(query_location, nearest_location); - BOOST_ASSERT(0.f <= approximate_distance); + BOOST_ASSERT(0.0 <= approximate_distance); return approximate_distance; } @@ -236,36 +236,36 @@ void lat_or_lon_to_string(const int value, std::string &output) output = printInt<11, 6>(buffer, value); } -float deg_to_rad(const float degree) +double deg_to_rad(const double degree) { - return degree * (static_cast(M_PI) / 180.f); + return degree * (static_cast(M_PI) / 180.0); } -float rad_to_deg(const float radian) +double rad_to_deg(const double radian) { - return radian * (180.f * static_cast(M_1_PI)); + return radian * (180.0 * static_cast(M_1_PI)); } -float bearing(const FixedPointCoordinate &first_coordinate, +double bearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate) { - const float lon_diff = + const double lon_diff = second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION; - const float lon_delta = deg_to_rad(lon_diff); - const float lat1 = deg_to_rad(first_coordinate.lat / COORDINATE_PRECISION); - const float lat2 = deg_to_rad(second_coordinate.lat / COORDINATE_PRECISION); - const float y = std::sin(lon_delta) * std::cos(lat2); - const float x = + const double lon_delta = deg_to_rad(lon_diff); + const double lat1 = deg_to_rad(first_coordinate.lat / COORDINATE_PRECISION); + const double lat2 = deg_to_rad(second_coordinate.lat / COORDINATE_PRECISION); + const double y = std::sin(lon_delta) * std::cos(lat2); + const double x = std::cos(lat1) * std::sin(lat2) - std::sin(lat1) * std::cos(lat2) * std::cos(lon_delta); - float result = rad_to_deg(std::atan2(y, x)); - while (result < 0.f) + double result = rad_to_deg(std::atan2(y, x)); + while (result < 0.0) { - result += 360.f; + result += 360.0; } - while (result >= 360.f) + while (result >= 360.0) { - result -= 360.f; + result -= 360.0; } return result; } diff --git a/unit_tests/util/coordinate.cpp b/unit_tests/util/coordinate.cpp index f153175ab..c4f361921 100644 --- a/unit_tests/util/coordinate.cpp +++ b/unit_tests/util/coordinate.cpp @@ -40,11 +40,11 @@ BOOST_AUTO_TEST_CASE(regression_test_1347) FixedPointCoordinate v(10.001 * COORDINATE_PRECISION, -100.002 * COORDINATE_PRECISION); FixedPointCoordinate q(10.002 * COORDINATE_PRECISION, -100.001 * COORDINATE_PRECISION); - float d1 = coordinate_calculation::perpendicular_distance(u, v, q); + double d1 = coordinate_calculation::perpendicular_distance(u, v, q); - float ratio; + double ratio; FixedPointCoordinate nearest_location; - float d2 = coordinate_calculation::perpendicular_distance(u, v, q, nearest_location, ratio); + double d2 = coordinate_calculation::perpendicular_distance(u, v, q, nearest_location, ratio); - BOOST_CHECK_LE(std::abs(d1 - d2), 0.01f); + BOOST_CHECK_LE(std::abs(d1 - d2), 0.01); } diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index 33c9eed74..93b81b906 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -88,11 +88,11 @@ template class LinearSearchNN local_edges.begin(), local_edges.begin() + num_results, local_edges.end(), [this, &input_coordinate](const DataT &lhs, const DataT &rhs) { - float current_ratio = 0.; + double current_ratio = 0.; FixedPointCoordinate nearest; - const float lhs_dist = coordinate_calculation::perpendicular_distance( + const double lhs_dist = coordinate_calculation::perpendicular_distance( coords->at(lhs.u), coords->at(lhs.v), input_coordinate, nearest, current_ratio); - const float rhs_dist = coordinate_calculation::perpendicular_distance( + const double rhs_dist = coordinate_calculation::perpendicular_distance( coords->at(rhs.u), coords->at(rhs.v), input_coordinate, nearest, current_ratio); return lhs_dist < rhs_dist; }); @@ -165,7 +165,7 @@ template struct RandomGraphFixture struct GraphFixture { - GraphFixture(const std::vector> &input_coords, + GraphFixture(const std::vector> &input_coords, const std::vector> &input_edges) : coords(std::make_shared>()) { @@ -253,13 +253,13 @@ void sampling_verify_rtree(RTreeT &rtree, LinearSearchNN &lsnn, const auto lsnn_u = result_lsnn.back().u; auto lsnn_v = result_lsnn.back().v; - float current_ratio = 0.; + double current_ratio = 0.; FixedPointCoordinate nearest; - const float rtree_dist = coordinate_calculation::perpendicular_distance( + const double rtree_dist = coordinate_calculation::perpendicular_distance( coords[rtree_u], coords[rtree_v], q, nearest, current_ratio); - const float lsnn_dist = coordinate_calculation::perpendicular_distance( + const double lsnn_dist = coordinate_calculation::perpendicular_distance( coords[lsnn_u], coords[lsnn_v], q, nearest, current_ratio); - BOOST_CHECK_LE(std::abs(rtree_dist - lsnn_dist), std::numeric_limits::epsilon()); + BOOST_CHECK_LE(std::abs(rtree_dist - lsnn_dist), std::numeric_limits::epsilon()); } } @@ -324,7 +324,7 @@ BOOST_FIXTURE_TEST_CASE(construct_multiple_levels_test, TestRandomGraphFixture_M // one BB will be pruned, even if it could contain a nearer match. BOOST_AUTO_TEST_CASE(regression_test) { - using Coord = std::pair; + using Coord = std::pair; using Edge = std::pair; GraphFixture fixture( { @@ -420,7 +420,7 @@ BOOST_AUTO_TEST_CASE(rectangle_test) BOOST_AUTO_TEST_CASE(bearing_tests) { - using Coord = std::pair; + using Coord = std::pair; using Edge = std::pair; GraphFixture fixture( { From a6cb786718a9fc82c4a2468f528feb70cd465dcd Mon Sep 17 00:00:00 2001 From: Mortada Mehyar Date: Sat, 26 Dec 2015 00:06:10 -0800 Subject: [PATCH 011/701] improve comments --- include/engine/plugins/match.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 64da87856..82b1805e8 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -147,7 +147,7 @@ template class MapMatchingPlugin : public BasePlugin break; } - // sort by foward id, then by reverse id and then by distance + // sort by forward id, then by reverse id and then by distance std::sort( candidates.begin(), candidates.end(), [](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs) @@ -321,7 +321,7 @@ template class MapMatchingPlugin : public BasePlugin return Status::Error; } - // enforce maximum number of locations for performance reasons + // at least two coordinates are needed for map matching if (static_cast(input_coords.size()) < 2) { json_result.values["status_message"] = "At least two coordinates needed"; From 4ba732c88660a7eb7fb6aeac1048197e5fb662a7 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 11:15:37 +0100 Subject: [PATCH 012/701] Fix AppVayor tests --- appveyor-build.bat | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/appveyor-build.bat b/appveyor-build.bat index a1e96031c..f055c171e 100644 --- a/appveyor-build.bat +++ b/appveyor-build.bat @@ -81,11 +81,14 @@ IF %ERRORLEVEL% NEQ 0 GOTO ERROR SET PATH=%PROJECT_DIR%\osrm-deps\libs\bin;%PATH% -ECHO running datastructure-tests.exe ... -%Configuration%\datastructure-tests.exe +ECHO running engine-tests.exe ... +%Configuration%\engine-tests.exe IF %ERRORLEVEL% NEQ 0 GOTO ERROR -ECHO running algorithm-tests.exe ... -%Configuration%\algorithm-tests.exe +ECHO running extractor-tests.exe ... +%Configuration%\extractor-tests.exe +IF %ERRORLEVEL% NEQ 0 GOTO ERROR +ECHO running util-tests.exe ... +%Configuration%\util-tests.exe IF %ERRORLEVEL% NEQ 0 GOTO ERROR IF NOT "%APPVEYOR_REPO_BRANCH%"=="develop" GOTO DONE From 2d455018aeba25ab66d2f1494a6fa03bb312771f Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 4 Jan 2016 18:13:05 +0100 Subject: [PATCH 013/701] We are at 2016 for the license --- LICENCE.TXT | 2 +- cmake/FindLua52.cmake | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/LICENCE.TXT b/LICENCE.TXT index c77e5cd1b..143580ec6 100644 --- a/LICENCE.TXT +++ b/LICENCE.TXT @@ -1,4 +1,4 @@ -Copyright (c) 2015, Project OSRM contributors +Copyright (c) 2016, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, diff --git a/cmake/FindLua52.cmake b/cmake/FindLua52.cmake index d17fbf61d..4aeaf94f9 100644 --- a/cmake/FindLua52.cmake +++ b/cmake/FindLua52.cmake @@ -14,7 +14,7 @@ #============================================================================= # Copyright 2007-2009 Kitware, Inc. -# Copyright 2013 for Project-OSRM, Lua5.1 => Lua5.2 +# Copyright 2016 for Project-OSRM, Lua5.1 => Lua5.2 # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. From 685d330ee2c3358c954124f8c46372c8019f2721 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 4 Jan 2016 19:06:32 +0100 Subject: [PATCH 014/701] Remove license headers from project source files; global license --- include/contractor/contractor.hpp | 27 ------------------- include/contractor/contractor_options.hpp | 27 ------------------- include/contractor/crc32_processor.hpp | 27 ------------------- include/contractor/processing_chain.hpp | 27 ------------------- include/contractor/query_edge.hpp | 27 ------------------- include/datastore/shared_memory_factory.hpp | 27 ------------------- include/engine/datafacade/datafacade_base.hpp | 27 ------------------- .../engine/datafacade/internal_datafacade.hpp | 27 ------------------- include/engine/datafacade/shared_barriers.hpp | 27 ------------------- .../engine/datafacade/shared_datafacade.hpp | 27 ------------------- include/engine/datafacade/shared_datatype.hpp | 27 ------------------- .../descriptors/description_factory.hpp | 27 ------------------- .../engine/descriptors/descriptor_base.hpp | 27 ------------------- include/engine/descriptors/gpx_descriptor.hpp | 27 ------------------- .../engine/descriptors/json_descriptor.hpp | 27 ------------------- include/engine/douglas_peucker.hpp | 27 ------------------- include/engine/internal_route_result.hpp | 27 ------------------- .../engine/map_matching/bayes_classifier.hpp | 27 ------------------- .../map_matching/hidden_markov_model.hpp | 27 ------------------- include/engine/object_encoder.hpp | 27 ------------------- include/engine/osrm_impl.hpp | 27 ------------------- include/engine/phantom_node.hpp | 27 ------------------- include/engine/plugins/distance_table.hpp | 27 ------------------- include/engine/plugins/hello_world.hpp | 27 ------------------- include/engine/plugins/match.hpp | 27 ------------------- include/engine/plugins/nearest.hpp | 27 ------------------- include/engine/plugins/plugin_base.hpp | 27 ------------------- include/engine/plugins/timestamp.hpp | 27 ------------------- include/engine/plugins/trip.hpp | 27 ------------------- include/engine/plugins/viaroute.hpp | 27 ------------------- include/engine/polyline_compressor.hpp | 27 ------------------- include/engine/polyline_formatter.hpp | 27 ------------------- include/engine/route_name_extraction.hpp | 27 ------------------- .../routing_algorithms/alternative_path.hpp | 27 ------------------- .../direct_shortest_path.hpp | 27 ------------------- .../routing_algorithms/many_to_many.hpp | 27 ------------------- .../routing_algorithms/map_matching.hpp | 27 ------------------- .../routing_algorithms/routing_base.hpp | 27 ------------------- .../routing_algorithms/shortest_path.hpp | 27 ------------------- include/engine/search_engine.hpp | 27 ------------------- include/engine/search_engine_data.hpp | 27 ------------------- include/engine/segment_information.hpp | 27 ------------------- include/engine/trip/trip_brute_force.hpp | 27 ------------------- .../engine/trip/trip_farthest_insertion.hpp | 27 ------------------- .../engine/trip/trip_nearest_neighbour.hpp | 27 ------------------- include/engine/trip/trip_tabu_search.hpp | 27 ------------------- .../extractor/compressed_edge_container.hpp | 27 ------------------- .../extractor/edge_based_graph_factory.hpp | 27 ------------------- include/extractor/edge_based_node.hpp | 27 ------------------- include/extractor/external_memory_node.hpp | 27 ------------------- include/extractor/extraction_containers.hpp | 27 ------------------- .../extractor/extraction_helper_functions.hpp | 27 ------------------- include/extractor/extraction_node.hpp | 27 ------------------- include/extractor/extraction_way.hpp | 27 ------------------- include/extractor/extractor.hpp | 27 ------------------- include/extractor/extractor_callbacks.hpp | 27 ------------------- include/extractor/extractor_options.hpp | 27 ------------------- .../first_and_last_segment_of_way.hpp | 27 ------------------- include/extractor/graph_compressor.hpp | 26 ------------------ include/extractor/import_edge.hpp | 27 ------------------- include/extractor/internal_extractor_edge.hpp | 27 ------------------- include/extractor/node_id.hpp | 27 ------------------- include/extractor/original_edge_data.hpp | 27 ------------------- include/extractor/query_node.hpp | 27 ------------------- include/extractor/raster_source.hpp | 27 ------------------- include/extractor/restriction.hpp | 27 ------------------- include/extractor/restriction_map.hpp | 27 ------------------- include/extractor/restriction_parser.hpp | 27 ------------------- include/extractor/scripting_environment.hpp | 27 ------------------- include/extractor/tarjan_scc.hpp | 27 ------------------- include/extractor/travel_mode.hpp | 27 ------------------- include/extractor/turn_instructions.hpp | 27 ------------------- include/server/api_grammar.hpp | 27 ------------------- include/server/connection.hpp | 27 ------------------- include/server/http/compression_type.hpp | 27 ------------------- include/server/http/header.hpp | 27 ------------------- include/server/http/reply.hpp | 27 ------------------- include/server/http/request.hpp | 27 ------------------- include/server/request_handler.hpp | 27 ------------------- include/server/request_parser.hpp | 27 ------------------- include/server/server.hpp | 27 ------------------- include/util/bearing.hpp | 27 ------------------- include/util/binary_heap.hpp | 27 ------------------- include/util/cast.hpp | 27 ------------------- include/util/compute_angle.hpp | 27 ------------------- include/util/container.hpp | 27 ------------------- include/util/coordinate_calculation.hpp | 27 ------------------- include/util/datastore_options.hpp | 27 ------------------- include/util/deallocating_vector.hpp | 27 ------------------- include/util/debug_geometry.hpp | 27 ------------------- include/util/dist_table_wrapper.hpp | 27 ------------------- include/util/dynamic_graph.hpp | 27 ------------------- include/util/fingerprint.hpp | 27 ------------------- include/util/fingerprint_impl.hpp.in | 27 ------------------- include/util/fixed_point_number.hpp | 27 ------------------- include/util/floating_point.hpp | 26 ------------------ include/util/graph_loader.hpp | 27 ------------------- include/util/hilbert_value.hpp | 27 ------------------- include/util/ini_file.hpp | 27 ------------------- include/util/integer_range.hpp | 27 ------------------- include/util/iso_8601_duration_parser.hpp | 27 ------------------- include/util/json_logger.hpp | 27 ------------------- include/util/json_renderer.hpp | 27 ------------------- include/util/json_util.hpp | 27 ------------------- include/util/lua_util.hpp | 27 ------------------- include/util/make_unique.hpp | 27 ------------------- include/util/matching_debug_info.hpp | 27 ------------------- include/util/matrix_graph_wrapper.hpp | 27 ------------------- include/util/mercator.hpp | 27 ------------------- include/util/node_based_graph.hpp | 27 ------------------- include/util/osrm_exception.hpp | 27 ------------------- include/util/percent.hpp | 27 ------------------- include/util/range_algorithms.hpp | 27 ------------------- include/util/range_table.hpp | 27 ------------------- include/util/rectangle.hpp | 27 ------------------- include/util/routed_options.hpp | 27 ------------------- include/util/shared_memory_vector_wrapper.hpp | 27 ------------------- include/util/simple_logger.hpp | 27 ------------------- include/util/static_graph.hpp | 27 ------------------- include/util/static_rtree.hpp | 27 ------------------- include/util/std_hash.hpp | 27 ------------------- include/util/string_util.hpp | 27 ------------------- include/util/timing_util.hpp | 27 ------------------- include/util/tribool.hpp | 27 ------------------- include/util/trigonometry_table.hpp | 27 ------------------- include/util/typedefs.hpp | 27 ------------------- include/util/version.hpp.in | 27 ------------------- include/util/xml_renderer.hpp | 27 ------------------- include/util/xor_fast_hash.hpp | 27 ------------------- include/util/xor_fast_hash_storage.hpp | 27 ------------------- src/benchmarks/static_rtree.cpp | 27 ------------------- src/contractor/contractor_options.cpp | 27 ------------------- src/contractor/processing_chain.cpp | 27 ------------------- .../descriptors/description_factory.cpp | 27 ------------------- src/engine/douglas_peucker.cpp | 27 ------------------- src/engine/osrm_impl.cpp | 27 ------------------- src/engine/phantom_node.cpp | 27 ------------------- src/engine/polyline_compressor.cpp | 27 ------------------- src/engine/polyline_formatter.cpp | 27 ------------------- src/engine/route_parameters.cpp | 27 ------------------- src/engine/search_engine_data.cpp | 27 ------------------- src/extractor/compressed_edge_container.cpp | 27 ------------------- src/extractor/edge_based_graph_factory.cpp | 27 ------------------- src/extractor/external_memory_node.cpp | 27 ------------------- src/extractor/extraction_containers.cpp | 27 ------------------- src/extractor/extractor.cpp | 27 ------------------- src/extractor/extractor_callbacks.cpp | 27 ------------------- src/extractor/extractor_options.cpp | 27 ------------------- src/extractor/import_edge.cpp | 27 ------------------- src/extractor/raster_source.cpp | 27 ------------------- src/extractor/restriction_map.cpp | 27 ------------------- src/extractor/restriction_parser.cpp | 27 ------------------- src/extractor/scripting_environment.cpp | 27 ------------------- src/server/connection.cpp | 27 ------------------- src/server/http/reply.cpp | 27 ------------------- src/server/request_handler.cpp | 27 ------------------- src/server/request_parser.cpp | 27 ------------------- src/tools/check-hsgr.cpp | 26 ------------------ src/tools/components.cpp | 27 ------------------- src/tools/contract.cpp | 27 ------------------- src/tools/datastore.cpp | 27 ------------------- src/tools/extract.cpp | 27 ------------------- src/tools/io-benchmark.cpp | 27 ------------------- src/tools/routed.cpp | 27 ------------------- src/tools/simpleclient.cpp | 27 ------------------- src/tools/springclean.cpp | 27 ------------------- src/tools/unlock_all_mutexes.cpp | 27 ------------------- src/util/compute_angle.cpp | 27 ------------------- src/util/coordinate.cpp | 27 ------------------- src/util/coordinate_calculation.cpp | 27 ------------------- src/util/fingerprint.cpp | 27 ------------------- src/util/hilbert_value.cpp | 27 ------------------- src/util/mercator.cpp | 27 ------------------- src/util/osrm_exception.cpp | 27 ------------------- src/util/simple_logger.cpp | 27 ------------------- unit_tests/engine/douglas_peucker.cpp | 27 ------------------- unit_tests/engine/geometry_string.cpp | 27 ------------------- unit_tests/engine_tests.cpp | 27 ------------------- unit_tests/extractor/raster_source.cpp | 27 ------------------- unit_tests/extractor_tests.cpp | 27 ------------------- unit_tests/util/bearing.cpp | 27 ------------------- unit_tests/util/binary_heap.cpp | 27 ------------------- unit_tests/util/coordinate.cpp | 27 ------------------- unit_tests/util/duration_parsing.cpp | 27 ------------------- unit_tests/util/dynamic_graph.cpp | 27 ------------------- unit_tests/util/range_table.cpp | 27 ------------------- unit_tests/util/static_graph.cpp | 27 ------------------- unit_tests/util/static_rtree.cpp | 27 ------------------- unit_tests/util/string_util.cpp | 27 ------------------- unit_tests/util_tests.cpp | 27 ------------------- 190 files changed, 5127 deletions(-) diff --git a/include/contractor/contractor.hpp b/include/contractor/contractor.hpp index 4ae4fcc4b..21a75ba2a 100644 --- a/include/contractor/contractor.hpp +++ b/include/contractor/contractor.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef CONTRACTOR_HPP #define CONTRACTOR_HPP diff --git a/include/contractor/contractor_options.hpp b/include/contractor/contractor_options.hpp index 5932b78c6..982645bdc 100644 --- a/include/contractor/contractor_options.hpp +++ b/include/contractor/contractor_options.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef CONTRACTOR_OPTIONS_HPP #define CONTRACTOR_OPTIONS_HPP diff --git a/include/contractor/crc32_processor.hpp b/include/contractor/crc32_processor.hpp index a31b4ad23..df9fa9686 100644 --- a/include/contractor/crc32_processor.hpp +++ b/include/contractor/crc32_processor.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef ITERATOR_BASED_CRC32_H #define ITERATOR_BASED_CRC32_H diff --git a/include/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp index e303a6fc6..5c0713fde 100644 --- a/include/contractor/processing_chain.hpp +++ b/include/contractor/processing_chain.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef PROCESSING_CHAIN_HPP #define PROCESSING_CHAIN_HPP diff --git a/include/contractor/query_edge.hpp b/include/contractor/query_edge.hpp index 86d5d63a8..ec7e89b68 100644 --- a/include/contractor/query_edge.hpp +++ b/include/contractor/query_edge.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef QUERYEDGE_HPP #define QUERYEDGE_HPP diff --git a/include/datastore/shared_memory_factory.hpp b/include/datastore/shared_memory_factory.hpp index c88fc725e..ba72581d8 100644 --- a/include/datastore/shared_memory_factory.hpp +++ b/include/datastore/shared_memory_factory.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SHARED_MEMORY_FACTORY_HPP #define SHARED_MEMORY_FACTORY_HPP diff --git a/include/engine/datafacade/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp index a0d1f0e98..1653309b7 100644 --- a/include/engine/datafacade/datafacade_base.hpp +++ b/include/engine/datafacade/datafacade_base.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DATAFACADE_BASE_HPP #define DATAFACADE_BASE_HPP diff --git a/include/engine/datafacade/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp index 82bbe30e2..83301ab8c 100644 --- a/include/engine/datafacade/internal_datafacade.hpp +++ b/include/engine/datafacade/internal_datafacade.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef INTERNAL_DATAFACADE_HPP #define INTERNAL_DATAFACADE_HPP diff --git a/include/engine/datafacade/shared_barriers.hpp b/include/engine/datafacade/shared_barriers.hpp index e6f1234ca..3825580bc 100644 --- a/include/engine/datafacade/shared_barriers.hpp +++ b/include/engine/datafacade/shared_barriers.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SHARED_BARRIERS_HPP #define SHARED_BARRIERS_HPP diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index dc7938cd5..1debe68be 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SHARED_DATAFACADE_HPP #define SHARED_DATAFACADE_HPP diff --git a/include/engine/datafacade/shared_datatype.hpp b/include/engine/datafacade/shared_datatype.hpp index f012073e4..9cd38adab 100644 --- a/include/engine/datafacade/shared_datatype.hpp +++ b/include/engine/datafacade/shared_datatype.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SHARED_DATA_TYPE_HPP #define SHARED_DATA_TYPE_HPP diff --git a/include/engine/descriptors/description_factory.hpp b/include/engine/descriptors/description_factory.hpp index 0e3dc2413..06150e665 100644 --- a/include/engine/descriptors/description_factory.hpp +++ b/include/engine/descriptors/description_factory.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DESCRIPTION_FACTORY_HPP #define DESCRIPTION_FACTORY_HPP diff --git a/include/engine/descriptors/descriptor_base.hpp b/include/engine/descriptors/descriptor_base.hpp index 41511a082..c782f94cd 100644 --- a/include/engine/descriptors/descriptor_base.hpp +++ b/include/engine/descriptors/descriptor_base.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DESCRIPTOR_BASE_HPP #define DESCRIPTOR_BASE_HPP diff --git a/include/engine/descriptors/gpx_descriptor.hpp b/include/engine/descriptors/gpx_descriptor.hpp index dd7506625..46be3abf2 100644 --- a/include/engine/descriptors/gpx_descriptor.hpp +++ b/include/engine/descriptors/gpx_descriptor.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef GPX_DESCRIPTOR_HPP #define GPX_DESCRIPTOR_HPP diff --git a/include/engine/descriptors/json_descriptor.hpp b/include/engine/descriptors/json_descriptor.hpp index 0e9e629a6..4b8d0136f 100644 --- a/include/engine/descriptors/json_descriptor.hpp +++ b/include/engine/descriptors/json_descriptor.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef JSON_DESCRIPTOR_HPP #define JSON_DESCRIPTOR_HPP diff --git a/include/engine/douglas_peucker.hpp b/include/engine/douglas_peucker.hpp index 7ef6bd6c2..dda4ca1b7 100644 --- a/include/engine/douglas_peucker.hpp +++ b/include/engine/douglas_peucker.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DOUGLAS_PEUCKER_HPP_ #define DOUGLAS_PEUCKER_HPP_ diff --git a/include/engine/internal_route_result.hpp b/include/engine/internal_route_result.hpp index be8dec223..551cf7ea6 100644 --- a/include/engine/internal_route_result.hpp +++ b/include/engine/internal_route_result.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef RAW_ROUTE_DATA_H #define RAW_ROUTE_DATA_H diff --git a/include/engine/map_matching/bayes_classifier.hpp b/include/engine/map_matching/bayes_classifier.hpp index ea300c1a9..3fe0e5a8d 100644 --- a/include/engine/map_matching/bayes_classifier.hpp +++ b/include/engine/map_matching/bayes_classifier.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef BAYES_CLASSIFIER_HPP #define BAYES_CLASSIFIER_HPP diff --git a/include/engine/map_matching/hidden_markov_model.hpp b/include/engine/map_matching/hidden_markov_model.hpp index d6e79a6eb..8fd8c759f 100644 --- a/include/engine/map_matching/hidden_markov_model.hpp +++ b/include/engine/map_matching/hidden_markov_model.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef HIDDEN_MARKOV_MODEL #define HIDDEN_MARKOV_MODEL diff --git a/include/engine/object_encoder.hpp b/include/engine/object_encoder.hpp index 581b3967c..546d21003 100644 --- a/include/engine/object_encoder.hpp +++ b/include/engine/object_encoder.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef OBJECT_ENCODER_HPP #define OBJECT_ENCODER_HPP diff --git a/include/engine/osrm_impl.hpp b/include/engine/osrm_impl.hpp index b6c8928d2..20301efff 100644 --- a/include/engine/osrm_impl.hpp +++ b/include/engine/osrm_impl.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef OSRM_IMPL_HPP #define OSRM_IMPL_HPP diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index f2255e35e..2b37cfeda 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef PHANTOM_NODES_H #define PHANTOM_NODES_H diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index 8009e6818..6a3b52f89 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DISTANCE_TABLE_HPP #define DISTANCE_TABLE_HPP diff --git a/include/engine/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp index ac6aa53d9..8a5193962 100644 --- a/include/engine/plugins/hello_world.hpp +++ b/include/engine/plugins/hello_world.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef HELLO_WORLD_HPP #define HELLO_WORLD_HPP diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 82b1805e8..2cb178530 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef MATCH_HPP #define MATCH_HPP diff --git a/include/engine/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp index 1fc66efec..831f30a64 100644 --- a/include/engine/plugins/nearest.hpp +++ b/include/engine/plugins/nearest.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef NEAREST_HPP #define NEAREST_HPP diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index b623aa1f4..51b7cf5cc 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef BASE_PLUGIN_HPP #define BASE_PLUGIN_HPP diff --git a/include/engine/plugins/timestamp.hpp b/include/engine/plugins/timestamp.hpp index 0b1ef0772..e441b4607 100644 --- a/include/engine/plugins/timestamp.hpp +++ b/include/engine/plugins/timestamp.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TIMESTAMP_PLUGIN_H #define TIMESTAMP_PLUGIN_H diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index 7ca1e663b..56a0f19e1 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TRIP_HPP #define TRIP_HPP diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index 43e8728c3..eb68f9190 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef VIA_ROUTE_HPP #define VIA_ROUTE_HPP diff --git a/include/engine/polyline_compressor.hpp b/include/engine/polyline_compressor.hpp index f4c449156..0794c7f10 100644 --- a/include/engine/polyline_compressor.hpp +++ b/include/engine/polyline_compressor.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef POLYLINECOMPRESSOR_H_ #define POLYLINECOMPRESSOR_H_ diff --git a/include/engine/polyline_formatter.hpp b/include/engine/polyline_formatter.hpp index 9f7c60eef..b71035ae4 100644 --- a/include/engine/polyline_formatter.hpp +++ b/include/engine/polyline_formatter.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef POLYLINE_FORMATTER_HPP #define POLYLINE_FORMATTER_HPP diff --git a/include/engine/route_name_extraction.hpp b/include/engine/route_name_extraction.hpp index 00dae89c4..7684e80d7 100644 --- a/include/engine/route_name_extraction.hpp +++ b/include/engine/route_name_extraction.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTRACT_ROUTE_NAMES_H #define EXTRACT_ROUTE_NAMES_H diff --git a/include/engine/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp index 78f7a172b..37b6ced19 100644 --- a/include/engine/routing_algorithms/alternative_path.hpp +++ b/include/engine/routing_algorithms/alternative_path.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef ALTERNATIVE_PATH_ROUTING_HPP #define ALTERNATIVE_PATH_ROUTING_HPP diff --git a/include/engine/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp index 3209423dd..443055b83 100644 --- a/include/engine/routing_algorithms/direct_shortest_path.hpp +++ b/include/engine/routing_algorithms/direct_shortest_path.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DIRECT_SHORTEST_PATH_HPP #define DIRECT_SHORTEST_PATH_HPP diff --git a/include/engine/routing_algorithms/many_to_many.hpp b/include/engine/routing_algorithms/many_to_many.hpp index e9d804a2d..9dc7a674c 100644 --- a/include/engine/routing_algorithms/many_to_many.hpp +++ b/include/engine/routing_algorithms/many_to_many.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef MANY_TO_MANY_ROUTING_HPP #define MANY_TO_MANY_ROUTING_HPP diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 00db48eff..66a2b903c 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef MAP_MATCHING_HPP #define MAP_MATCHING_HPP diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index 14c5b9c0a..9afee1c44 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef ROUTING_BASE_HPP #define ROUTING_BASE_HPP diff --git a/include/engine/routing_algorithms/shortest_path.hpp b/include/engine/routing_algorithms/shortest_path.hpp index cedeca83a..6bc8fc772 100644 --- a/include/engine/routing_algorithms/shortest_path.hpp +++ b/include/engine/routing_algorithms/shortest_path.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SHORTEST_PATH_HPP #define SHORTEST_PATH_HPP diff --git a/include/engine/search_engine.hpp b/include/engine/search_engine.hpp index 8efc9d211..e705faa96 100644 --- a/include/engine/search_engine.hpp +++ b/include/engine/search_engine.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SEARCH_ENGINE_HPP #define SEARCH_ENGINE_HPP diff --git a/include/engine/search_engine_data.hpp b/include/engine/search_engine_data.hpp index 191447865..87e76604e 100644 --- a/include/engine/search_engine_data.hpp +++ b/include/engine/search_engine_data.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SEARCH_ENGINE_DATA_HPP #define SEARCH_ENGINE_DATA_HPP diff --git a/include/engine/segment_information.hpp b/include/engine/segment_information.hpp index 725358b50..880a58cb2 100644 --- a/include/engine/segment_information.hpp +++ b/include/engine/segment_information.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SEGMENT_INFORMATION_HPP #define SEGMENT_INFORMATION_HPP diff --git a/include/engine/trip/trip_brute_force.hpp b/include/engine/trip/trip_brute_force.hpp index 5203deea8..d45643059 100644 --- a/include/engine/trip/trip_brute_force.hpp +++ b/include/engine/trip/trip_brute_force.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TRIP_BRUTE_FORCE_HPP #define TRIP_BRUTE_FORCE_HPP diff --git a/include/engine/trip/trip_farthest_insertion.hpp b/include/engine/trip/trip_farthest_insertion.hpp index 13f301235..aa94b1fb0 100644 --- a/include/engine/trip/trip_farthest_insertion.hpp +++ b/include/engine/trip/trip_farthest_insertion.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TRIP_FARTHEST_INSERTION_HPP #define TRIP_FARTHEST_INSERTION_HPP diff --git a/include/engine/trip/trip_nearest_neighbour.hpp b/include/engine/trip/trip_nearest_neighbour.hpp index e931bcda7..c66e611d6 100644 --- a/include/engine/trip/trip_nearest_neighbour.hpp +++ b/include/engine/trip/trip_nearest_neighbour.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TRIP_NEAREST_NEIGHBOUR_HPP #define TRIP_NEAREST_NEIGHBOUR_HPP diff --git a/include/engine/trip/trip_tabu_search.hpp b/include/engine/trip/trip_tabu_search.hpp index 988d0a668..1eb5b6a44 100644 --- a/include/engine/trip/trip_tabu_search.hpp +++ b/include/engine/trip/trip_tabu_search.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TRIP_BRUTE_FORCE_HPP #define TRIP_BRUTE_FORCE_HPP diff --git a/include/extractor/compressed_edge_container.hpp b/include/extractor/compressed_edge_container.hpp index afae26f7d..4459f373b 100644 --- a/include/extractor/compressed_edge_container.hpp +++ b/include/extractor/compressed_edge_container.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef GEOMETRY_COMPRESSOR_HPP_ #define GEOMETRY_COMPRESSOR_HPP_ diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 56344c018..9a1b8ee40 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - // This class constructs the edge-expanded routing graph #ifndef EDGE_BASED_GRAPH_FACTORY_HPP_ diff --git a/include/extractor/edge_based_node.hpp b/include/extractor/edge_based_node.hpp index cc09ed2a0..41b836e19 100644 --- a/include/extractor/edge_based_node.hpp +++ b/include/extractor/edge_based_node.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EDGE_BASED_NODE_HPP #define EDGE_BASED_NODE_HPP diff --git a/include/extractor/external_memory_node.hpp b/include/extractor/external_memory_node.hpp index ac56d2393..8c2b7d194 100644 --- a/include/extractor/external_memory_node.hpp +++ b/include/extractor/external_memory_node.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTERNAL_MEMORY_NODE_HPP_ #define EXTERNAL_MEMORY_NODE_HPP_ diff --git a/include/extractor/extraction_containers.hpp b/include/extractor/extraction_containers.hpp index f8a330edb..b1e9b4bf0 100644 --- a/include/extractor/extraction_containers.hpp +++ b/include/extractor/extraction_containers.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTRACTION_CONTAINERS_HPP #define EXTRACTION_CONTAINERS_HPP diff --git a/include/extractor/extraction_helper_functions.hpp b/include/extractor/extraction_helper_functions.hpp index 2b266d75f..6872812fc 100644 --- a/include/extractor/extraction_helper_functions.hpp +++ b/include/extractor/extraction_helper_functions.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTRACTION_HELPER_FUNCTIONS_HPP #define EXTRACTION_HELPER_FUNCTIONS_HPP diff --git a/include/extractor/extraction_node.hpp b/include/extractor/extraction_node.hpp index e821d6ffa..46044eaf3 100644 --- a/include/extractor/extraction_node.hpp +++ b/include/extractor/extraction_node.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTRACTION_NODE_HPP #define EXTRACTION_NODE_HPP diff --git a/include/extractor/extraction_way.hpp b/include/extractor/extraction_way.hpp index c88588ef1..300518110 100644 --- a/include/extractor/extraction_way.hpp +++ b/include/extractor/extraction_way.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTRACTION_WAY_HPP #define EXTRACTION_WAY_HPP diff --git a/include/extractor/extractor.hpp b/include/extractor/extractor.hpp index 45a4ee8db..d7c49d656 100644 --- a/include/extractor/extractor.hpp +++ b/include/extractor/extractor.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTRACTOR_HPP #define EXTRACTOR_HPP diff --git a/include/extractor/extractor_callbacks.hpp b/include/extractor/extractor_callbacks.hpp index 808119be5..38fe76ec3 100644 --- a/include/extractor/extractor_callbacks.hpp +++ b/include/extractor/extractor_callbacks.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTRACTOR_CALLBACKS_HPP #define EXTRACTOR_CALLBACKS_HPP diff --git a/include/extractor/extractor_options.hpp b/include/extractor/extractor_options.hpp index 00d6f84b8..16593a0e9 100644 --- a/include/extractor/extractor_options.hpp +++ b/include/extractor/extractor_options.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef EXTRACTOR_OPTIONS_HPP #define EXTRACTOR_OPTIONS_HPP diff --git a/include/extractor/first_and_last_segment_of_way.hpp b/include/extractor/first_and_last_segment_of_way.hpp index 55a096f45..37685d3c8 100644 --- a/include/extractor/first_and_last_segment_of_way.hpp +++ b/include/extractor/first_and_last_segment_of_way.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef FIRST_AND_LAST_SEGMENT_OF_WAY_HPP #define FIRST_AND_LAST_SEGMENT_OF_WAY_HPP diff --git a/include/extractor/graph_compressor.hpp b/include/extractor/graph_compressor.hpp index 7ddcd1402..50a86a184 100644 --- a/include/extractor/graph_compressor.hpp +++ b/include/extractor/graph_compressor.hpp @@ -1,29 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ #ifndef GEOMETRY_COMPRESSOR_HPP #define GEOMETRY_COMPRESSOR_HPP diff --git a/include/extractor/import_edge.hpp b/include/extractor/import_edge.hpp index f436502c1..996f2371a 100644 --- a/include/extractor/import_edge.hpp +++ b/include/extractor/import_edge.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef IMPORT_EDGE_HPP #define IMPORT_EDGE_HPP diff --git a/include/extractor/internal_extractor_edge.hpp b/include/extractor/internal_extractor_edge.hpp index 546bb32dc..6c13950e7 100644 --- a/include/extractor/internal_extractor_edge.hpp +++ b/include/extractor/internal_extractor_edge.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef INTERNAL_EXTRACTOR_EDGE_HPP #define INTERNAL_EXTRACTOR_EDGE_HPP diff --git a/include/extractor/node_id.hpp b/include/extractor/node_id.hpp index b17de3829..27de18a67 100644 --- a/include/extractor/node_id.hpp +++ b/include/extractor/node_id.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef NODE_ID_HPP #define NODE_ID_HPP diff --git a/include/extractor/original_edge_data.hpp b/include/extractor/original_edge_data.hpp index b2009f69b..77a3bb550 100644 --- a/include/extractor/original_edge_data.hpp +++ b/include/extractor/original_edge_data.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef ORIGINAL_EDGE_DATA_HPP #define ORIGINAL_EDGE_DATA_HPP diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index 2c956262e..a4a912026 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef QUERY_NODE_HPP #define QUERY_NODE_HPP diff --git a/include/extractor/raster_source.hpp b/include/extractor/raster_source.hpp index d5bdc3937..f04574cc9 100644 --- a/include/extractor/raster_source.hpp +++ b/include/extractor/raster_source.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef RASTER_SOURCE_HPP #define RASTER_SOURCE_HPP diff --git a/include/extractor/restriction.hpp b/include/extractor/restriction.hpp index 4cfeccd1d..a64818b55 100644 --- a/include/extractor/restriction.hpp +++ b/include/extractor/restriction.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef RESTRICTION_HPP #define RESTRICTION_HPP diff --git a/include/extractor/restriction_map.hpp b/include/extractor/restriction_map.hpp index 64d65b873..5255c5e14 100644 --- a/include/extractor/restriction_map.hpp +++ b/include/extractor/restriction_map.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef RESTRICTION_MAP_HPP #define RESTRICTION_MAP_HPP diff --git a/include/extractor/restriction_parser.hpp b/include/extractor/restriction_parser.hpp index 3d19bb9ff..ee73f57ce 100644 --- a/include/extractor/restriction_parser.hpp +++ b/include/extractor/restriction_parser.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef RESTRICTION_PARSER_HPP #define RESTRICTION_PARSER_HPP diff --git a/include/extractor/scripting_environment.hpp b/include/extractor/scripting_environment.hpp index 8722aee8f..33d672340 100644 --- a/include/extractor/scripting_environment.hpp +++ b/include/extractor/scripting_environment.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SCRIPTING_ENVIRONMENT_HPP #define SCRIPTING_ENVIRONMENT_HPP diff --git a/include/extractor/tarjan_scc.hpp b/include/extractor/tarjan_scc.hpp index ad829d167..e29d0fad8 100644 --- a/include/extractor/tarjan_scc.hpp +++ b/include/extractor/tarjan_scc.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TARJAN_SCC_HPP #define TARJAN_SCC_HPP diff --git a/include/extractor/travel_mode.hpp b/include/extractor/travel_mode.hpp index 2bbe46317..66a84bbde 100644 --- a/include/extractor/travel_mode.hpp +++ b/include/extractor/travel_mode.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TRAVEL_MODE_HPP #define TRAVEL_MODE_HPP diff --git a/include/extractor/turn_instructions.hpp b/include/extractor/turn_instructions.hpp index 1ca065f68..2075d2c9c 100644 --- a/include/extractor/turn_instructions.hpp +++ b/include/extractor/turn_instructions.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TURN_INSTRUCTIONS_HPP #define TURN_INSTRUCTIONS_HPP diff --git a/include/server/api_grammar.hpp b/include/server/api_grammar.hpp index 28bd1df68..d8a2e257b 100644 --- a/include/server/api_grammar.hpp +++ b/include/server/api_grammar.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef API_GRAMMAR_HPP #define API_GRAMMAR_HPP diff --git a/include/server/connection.hpp b/include/server/connection.hpp index 315800d1a..1abbd7eb7 100644 --- a/include/server/connection.hpp +++ b/include/server/connection.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef CONNECTION_HPP #define CONNECTION_HPP diff --git a/include/server/http/compression_type.hpp b/include/server/http/compression_type.hpp index f0dc692fa..ef7e8d75b 100644 --- a/include/server/http/compression_type.hpp +++ b/include/server/http/compression_type.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef COMPRESSION_TYPE_HPP #define COMPRESSION_TYPE_HPP diff --git a/include/server/http/header.hpp b/include/server/http/header.hpp index f2598ba1e..256e0b187 100644 --- a/include/server/http/header.hpp +++ b/include/server/http/header.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef HEADER_HPP #define HEADER_HPP diff --git a/include/server/http/reply.hpp b/include/server/http/reply.hpp index 7689e5ed2..64c6e67b7 100644 --- a/include/server/http/reply.hpp +++ b/include/server/http/reply.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef REPLY_HPP #define REPLY_HPP diff --git a/include/server/http/request.hpp b/include/server/http/request.hpp index c487fba65..8b1a00df1 100644 --- a/include/server/http/request.hpp +++ b/include/server/http/request.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef REQUEST_HPP #define REQUEST_HPP diff --git a/include/server/request_handler.hpp b/include/server/request_handler.hpp index b4019db7d..16a87acb0 100644 --- a/include/server/request_handler.hpp +++ b/include/server/request_handler.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef REQUEST_HANDLER_HPP #define REQUEST_HANDLER_HPP diff --git a/include/server/request_parser.hpp b/include/server/request_parser.hpp index 920876dcf..b498add0a 100644 --- a/include/server/request_parser.hpp +++ b/include/server/request_parser.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef REQUEST_PARSER_HPP #define REQUEST_PARSER_HPP diff --git a/include/server/server.hpp b/include/server/server.hpp index 48ac2686a..f64a9f3bf 100644 --- a/include/server/server.hpp +++ b/include/server/server.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SERVER_HPP #define SERVER_HPP diff --git a/include/util/bearing.hpp b/include/util/bearing.hpp index 5f3036a85..d881b300b 100644 --- a/include/util/bearing.hpp +++ b/include/util/bearing.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef BEARING_HPP #define BEARING_HPP diff --git a/include/util/binary_heap.hpp b/include/util/binary_heap.hpp index 85703f4a6..0cd00fe22 100644 --- a/include/util/binary_heap.hpp +++ b/include/util/binary_heap.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef BINARY_HEAP_H #define BINARY_HEAP_H diff --git a/include/util/cast.hpp b/include/util/cast.hpp index a9e97d6ec..94862d2ba 100644 --- a/include/util/cast.hpp +++ b/include/util/cast.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef CAST_HPP #define CAST_HPP diff --git a/include/util/compute_angle.hpp b/include/util/compute_angle.hpp index da84cafaa..48300e4f4 100644 --- a/include/util/compute_angle.hpp +++ b/include/util/compute_angle.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef COMPUTE_ANGLE_HPP #define COMPUTE_ANGLE_HPP diff --git a/include/util/container.hpp b/include/util/container.hpp index 14b88ee68..fab0c2263 100644 --- a/include/util/container.hpp +++ b/include/util/container.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef CONTAINER_HPP #define CONTAINER_HPP diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index 0ab9fe617..d8580d77e 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef COORDINATE_CALCULATION #define COORDINATE_CALCULATION diff --git a/include/util/datastore_options.hpp b/include/util/datastore_options.hpp index ccb909f14..dc2678404 100644 --- a/include/util/datastore_options.hpp +++ b/include/util/datastore_options.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DATASTORE_OPTIONS_HPP #define DATASTORE_OPTIONS_HPP diff --git a/include/util/deallocating_vector.hpp b/include/util/deallocating_vector.hpp index c98bd3174..c6bcb08b8 100644 --- a/include/util/deallocating_vector.hpp +++ b/include/util/deallocating_vector.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DEALLOCATING_VECTOR_HPP #define DEALLOCATING_VECTOR_HPP diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index bf2b26bce..a0c1bfd42 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DEBUG_GEOMETRY_H #define DEBUG_GEOMETRY_H diff --git a/include/util/dist_table_wrapper.hpp b/include/util/dist_table_wrapper.hpp index 15550fafe..516131393 100644 --- a/include/util/dist_table_wrapper.hpp +++ b/include/util/dist_table_wrapper.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DIST_TABLE_WRAPPER_H #define DIST_TABLE_WRAPPER_H diff --git a/include/util/dynamic_graph.hpp b/include/util/dynamic_graph.hpp index c0cf2bb4d..d0c4fd082 100644 --- a/include/util/dynamic_graph.hpp +++ b/include/util/dynamic_graph.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef DYNAMICGRAPH_HPP #define DYNAMICGRAPH_HPP diff --git a/include/util/fingerprint.hpp b/include/util/fingerprint.hpp index 99576f959..f4a9f84ac 100644 --- a/include/util/fingerprint.hpp +++ b/include/util/fingerprint.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef FINGERPRINT_H #define FINGERPRINT_H diff --git a/include/util/fingerprint_impl.hpp.in b/include/util/fingerprint_impl.hpp.in index 88e8436cb..85fcebdb0 100644 --- a/include/util/fingerprint_impl.hpp.in +++ b/include/util/fingerprint_impl.hpp.in @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/osrm_exception.hpp" #include diff --git a/include/util/fixed_point_number.hpp b/include/util/fixed_point_number.hpp index c7ed257e5..0ff409fc8 100644 --- a/include/util/fixed_point_number.hpp +++ b/include/util/fixed_point_number.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef FIXED_POINT_NUMBER_HPP #define FIXED_POINT_NUMBER_HPP diff --git a/include/util/floating_point.hpp b/include/util/floating_point.hpp index 13f2d3bc4..79ec495bd 100644 --- a/include/util/floating_point.hpp +++ b/include/util/floating_point.hpp @@ -1,29 +1,3 @@ -/* -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef FLOATING_POINT_HPP #define FLOATING_POINT_HPP diff --git a/include/util/graph_loader.hpp b/include/util/graph_loader.hpp index b720a9bdf..c64048ede 100644 --- a/include/util/graph_loader.hpp +++ b/include/util/graph_loader.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef GRAPH_LOADER_HPP #define GRAPH_LOADER_HPP diff --git a/include/util/hilbert_value.hpp b/include/util/hilbert_value.hpp index 7b8bffa93..83ebd3b15 100644 --- a/include/util/hilbert_value.hpp +++ b/include/util/hilbert_value.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef HILBERT_VALUE_HPP #define HILBERT_VALUE_HPP diff --git a/include/util/ini_file.hpp b/include/util/ini_file.hpp index b42f9aef8..a99962f52 100644 --- a/include/util/ini_file.hpp +++ b/include/util/ini_file.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef INI_FILE_HPP #define INI_FILE_HPP diff --git a/include/util/integer_range.hpp b/include/util/integer_range.hpp index 02de7f8b4..9d176b8e0 100644 --- a/include/util/integer_range.hpp +++ b/include/util/integer_range.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef INTEGER_RANGE_HPP #define INTEGER_RANGE_HPP diff --git a/include/util/iso_8601_duration_parser.hpp b/include/util/iso_8601_duration_parser.hpp index 3e558cee2..aded519f9 100644 --- a/include/util/iso_8601_duration_parser.hpp +++ b/include/util/iso_8601_duration_parser.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef ISO_8601_DURATION_PARSER_HPP #define ISO_8601_DURATION_PARSER_HPP diff --git a/include/util/json_logger.hpp b/include/util/json_logger.hpp index dbef457e6..cb2511f75 100644 --- a/include/util/json_logger.hpp +++ b/include/util/json_logger.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef JSON_LOGGER_HPP #define JSON_LOGGER_HPP diff --git a/include/util/json_renderer.hpp b/include/util/json_renderer.hpp index d44d507fa..b0e7de640 100644 --- a/include/util/json_renderer.hpp +++ b/include/util/json_renderer.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - // based on // https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp diff --git a/include/util/json_util.hpp b/include/util/json_util.hpp index 0804f0a6f..d1eb7ae3f 100644 --- a/include/util/json_util.hpp +++ b/include/util/json_util.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef JSON_UTIL_HPP #define JSON_UTIL_HPP diff --git a/include/util/lua_util.hpp b/include/util/lua_util.hpp index 6dbdc8bc1..f45dbffa1 100644 --- a/include/util/lua_util.hpp +++ b/include/util/lua_util.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef LUA_UTIL_HPP #define LUA_UTIL_HPP diff --git a/include/util/make_unique.hpp b/include/util/make_unique.hpp index 83e230194..9c42ac520 100644 --- a/include/util/make_unique.hpp +++ b/include/util/make_unique.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef MAKE_UNIQUE_H_ #define MAKE_UNIQUE_H_ diff --git a/include/util/matching_debug_info.hpp b/include/util/matching_debug_info.hpp index a21c8f6bc..37f99403d 100644 --- a/include/util/matching_debug_info.hpp +++ b/include/util/matching_debug_info.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef MATCHING_DEBUG_INFO_HPP #define MATCHING_DEBUG_INFO_HPP diff --git a/include/util/matrix_graph_wrapper.hpp b/include/util/matrix_graph_wrapper.hpp index 3439d6f2b..b6aada34b 100644 --- a/include/util/matrix_graph_wrapper.hpp +++ b/include/util/matrix_graph_wrapper.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef MATRIX_GRAPH_WRAPPER_H #define MATRIX_GRAPH_WRAPPER_H diff --git a/include/util/mercator.hpp b/include/util/mercator.hpp index e994c8499..e338d9b1b 100644 --- a/include/util/mercator.hpp +++ b/include/util/mercator.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef MERCATOR_HPP #define MERCATOR_HPP diff --git a/include/util/node_based_graph.hpp b/include/util/node_based_graph.hpp index 42b53d626..e2c9e557c 100644 --- a/include/util/node_based_graph.hpp +++ b/include/util/node_based_graph.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef NODE_BASED_GRAPH_HPP #define NODE_BASED_GRAPH_HPP diff --git a/include/util/osrm_exception.hpp b/include/util/osrm_exception.hpp index 369433f34..a776f84fd 100644 --- a/include/util/osrm_exception.hpp +++ b/include/util/osrm_exception.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef OSRM_EXCEPTION_HPP #define OSRM_EXCEPTION_HPP diff --git a/include/util/percent.hpp b/include/util/percent.hpp index 392417e76..bcca00e3c 100644 --- a/include/util/percent.hpp +++ b/include/util/percent.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef PERCENT_HPP #define PERCENT_HPP diff --git a/include/util/range_algorithms.hpp b/include/util/range_algorithms.hpp index 4d01d29c8..f821bf8ef 100644 --- a/include/util/range_algorithms.hpp +++ b/include/util/range_algorithms.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef RANGE_ALGORITHMS_HPP #define RANGE_ALGORITHMS_HPP diff --git a/include/util/range_table.hpp b/include/util/range_table.hpp index 6de3debfd..1a3ed06af 100644 --- a/include/util/range_table.hpp +++ b/include/util/range_table.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef RANGE_TABLE_HPP #define RANGE_TABLE_HPP diff --git a/include/util/rectangle.hpp b/include/util/rectangle.hpp index 9aa99ac2c..1d123a05a 100644 --- a/include/util/rectangle.hpp +++ b/include/util/rectangle.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef RECTANGLE_HPP #define RECTANGLE_HPP diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index 6edcefb72..12d1e8d8a 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef ROUTED_OPTIONS_HPP #define ROUTED_OPTIONS_HPP diff --git a/include/util/shared_memory_vector_wrapper.hpp b/include/util/shared_memory_vector_wrapper.hpp index dc51cff0d..fef9c78e7 100644 --- a/include/util/shared_memory_vector_wrapper.hpp +++ b/include/util/shared_memory_vector_wrapper.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SHARED_MEMORY_VECTOR_WRAPPER_HPP #define SHARED_MEMORY_VECTOR_WRAPPER_HPP diff --git a/include/util/simple_logger.hpp b/include/util/simple_logger.hpp index df61a9deb..041225abe 100644 --- a/include/util/simple_logger.hpp +++ b/include/util/simple_logger.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef SIMPLE_LOGGER_HPP #define SIMPLE_LOGGER_HPP diff --git a/include/util/static_graph.hpp b/include/util/static_graph.hpp index a2fd47333..9ca5cf1f5 100644 --- a/include/util/static_graph.hpp +++ b/include/util/static_graph.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef STATIC_GRAPH_HPP #define STATIC_GRAPH_HPP diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 8483142e8..0c9d99522 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef STATIC_RTREE_HPP #define STATIC_RTREE_HPP diff --git a/include/util/std_hash.hpp b/include/util/std_hash.hpp index 9e78fcce4..ff5ac187b 100644 --- a/include/util/std_hash.hpp +++ b/include/util/std_hash.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef STD_HASH_HPP #define STD_HASH_HPP diff --git a/include/util/string_util.hpp b/include/util/string_util.hpp index 8075e659c..78ccfb34a 100644 --- a/include/util/string_util.hpp +++ b/include/util/string_util.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef STRING_UTIL_HPP #define STRING_UTIL_HPP diff --git a/include/util/timing_util.hpp b/include/util/timing_util.hpp index c0c59c8a6..dc6435634 100644 --- a/include/util/timing_util.hpp +++ b/include/util/timing_util.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TIMING_UTIL_HPP #define TIMING_UTIL_HPP diff --git a/include/util/tribool.hpp b/include/util/tribool.hpp index 2d4b6108d..ff9637273 100644 --- a/include/util/tribool.hpp +++ b/include/util/tribool.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TRIBOOL_HPP #define TRIBOOL_HPP diff --git a/include/util/trigonometry_table.hpp b/include/util/trigonometry_table.hpp index 463dbbecd..c02b5b78a 100644 --- a/include/util/trigonometry_table.hpp +++ b/include/util/trigonometry_table.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TRIGONOMETRY_TABLE_HPP #define TRIGONOMETRY_TABLE_HPP diff --git a/include/util/typedefs.hpp b/include/util/typedefs.hpp index efc15965f..0060a7381 100644 --- a/include/util/typedefs.hpp +++ b/include/util/typedefs.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef TYPEDEFS_H #define TYPEDEFS_H diff --git a/include/util/version.hpp.in b/include/util/version.hpp.in index 2eafd48a5..cb97dca12 100644 --- a/include/util/version.hpp.in +++ b/include/util/version.hpp.in @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef VERSION_HPP #define VERSION_HPP diff --git a/include/util/xml_renderer.hpp b/include/util/xml_renderer.hpp index ffd155de8..b9de27c4f 100644 --- a/include/util/xml_renderer.hpp +++ b/include/util/xml_renderer.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef XML_RENDERER_HPP #define XML_RENDERER_HPP diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 3af5ab1db..9e911c1f5 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef XOR_FAST_HASH_HPP #define XOR_FAST_HASH_HPP diff --git a/include/util/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp index f56ff7cb1..2754b4545 100644 --- a/include/util/xor_fast_hash_storage.hpp +++ b/include/util/xor_fast_hash_storage.hpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #ifndef XOR_FAST_HASH_STORAGE_HPP #define XOR_FAST_HASH_STORAGE_HPP diff --git a/src/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp index 26b1badcb..e8c5a81f2 100644 --- a/src/benchmarks/static_rtree.cpp +++ b/src/benchmarks/static_rtree.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/query_node.hpp" #include "util/static_rtree.hpp" #include "extractor/edge_based_node.hpp" diff --git a/src/contractor/contractor_options.cpp b/src/contractor/contractor_options.cpp index aa9a328c4..2bb8451d8 100644 --- a/src/contractor/contractor_options.cpp +++ b/src/contractor/contractor_options.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "contractor/contractor_options.hpp" #include "util/version.hpp" diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index d0d7d508d..9577b6c7f 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "contractor/processing_chain.hpp" #include "contractor/contractor.hpp" diff --git a/src/engine/descriptors/description_factory.cpp b/src/engine/descriptors/description_factory.cpp index a645987aa..e2548e1fb 100644 --- a/src/engine/descriptors/description_factory.cpp +++ b/src/engine/descriptors/description_factory.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "engine/descriptors/description_factory.hpp" #include "engine/polyline_formatter.hpp" diff --git a/src/engine/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp index e95a1497b..2be347fd8 100644 --- a/src/engine/douglas_peucker.cpp +++ b/src/engine/douglas_peucker.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "engine/douglas_peucker.hpp" #include "engine/segment_information.hpp" diff --git a/src/engine/osrm_impl.cpp b/src/engine/osrm_impl.cpp index 04cc4a2e1..84faf89da 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/osrm_impl.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - namespace boost { namespace interprocess diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp index bb1a7f383..8c4a17a7a 100644 --- a/src/engine/phantom_node.cpp +++ b/src/engine/phantom_node.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "engine/phantom_node.hpp" #include "util/typedefs.hpp" diff --git a/src/engine/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp index 56e6ca24e..bbb090152 100644 --- a/src/engine/polyline_compressor.cpp +++ b/src/engine/polyline_compressor.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "engine/polyline_compressor.hpp" #include "engine/segment_information.hpp" diff --git a/src/engine/polyline_formatter.cpp b/src/engine/polyline_formatter.cpp index 4b6ac48fb..52fa4935d 100644 --- a/src/engine/polyline_formatter.cpp +++ b/src/engine/polyline_formatter.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "engine/polyline_formatter.hpp" #include "engine/polyline_compressor.hpp" diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index f75324520..6649462bf 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include #include #include diff --git a/src/engine/search_engine_data.cpp b/src/engine/search_engine_data.cpp index 321d814b1..d96fd22da 100644 --- a/src/engine/search_engine_data.cpp +++ b/src/engine/search_engine_data.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "engine/search_engine_data.hpp" #include "util/binary_heap.hpp" diff --git a/src/extractor/compressed_edge_container.cpp b/src/extractor/compressed_edge_container.cpp index ee155d458..aa590153e 100644 --- a/src/extractor/compressed_edge_container.cpp +++ b/src/extractor/compressed_edge_container.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/compressed_edge_container.hpp" #include "util/simple_logger.hpp" diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 682773a94..5e903f788 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/edge_based_graph_factory.hpp" #include "util/coordinate_calculation.hpp" #include "util/percent.hpp" diff --git a/src/extractor/external_memory_node.cpp b/src/extractor/external_memory_node.cpp index ebafbd2b7..35dc18af1 100644 --- a/src/extractor/external_memory_node.cpp +++ b/src/extractor/external_memory_node.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/external_memory_node.hpp" #include "extractor/query_node.hpp" diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 9592b9eba..d21d61d49 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/extraction_containers.hpp" #include "extractor/extraction_way.hpp" diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 6a2a1609d..f04c4564a 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/extractor.hpp" #include "extractor/extraction_containers.hpp" diff --git a/src/extractor/extractor_callbacks.cpp b/src/extractor/extractor_callbacks.cpp index 013b20966..60b911049 100644 --- a/src/extractor/extractor_callbacks.cpp +++ b/src/extractor/extractor_callbacks.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/extractor_callbacks.hpp" #include "extractor/extraction_containers.hpp" #include "extractor/extraction_node.hpp" diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp index 2e0bc32b4..0c3d5211a 100644 --- a/src/extractor/extractor_options.cpp +++ b/src/extractor/extractor_options.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/extractor_options.hpp" #include "util/version.hpp" diff --git a/src/extractor/import_edge.cpp b/src/extractor/import_edge.cpp index 36c409cbe..deb3cb973 100644 --- a/src/extractor/import_edge.cpp +++ b/src/extractor/import_edge.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/import_edge.hpp" #include "extractor/travel_mode.hpp" diff --git a/src/extractor/raster_source.cpp b/src/extractor/raster_source.cpp index b5f9665a6..3c9abb16f 100644 --- a/src/extractor/raster_source.cpp +++ b/src/extractor/raster_source.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/raster_source.hpp" #include "util/simple_logger.hpp" diff --git a/src/extractor/restriction_map.cpp b/src/extractor/restriction_map.cpp index b92fc707e..44a6b574c 100644 --- a/src/extractor/restriction_map.cpp +++ b/src/extractor/restriction_map.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/restriction_map.hpp" RestrictionMap::RestrictionMap(const std::vector &restriction_list) : m_count(0) diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index e3c1e3f14..5a5137b64 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/restriction_parser.hpp" #include "extractor/extraction_way.hpp" diff --git a/src/extractor/scripting_environment.cpp b/src/extractor/scripting_environment.cpp index df8cb92ce..cee8be2a0 100644 --- a/src/extractor/scripting_environment.cpp +++ b/src/extractor/scripting_environment.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/scripting_environment.hpp" #include "extractor/extraction_helper_functions.hpp" diff --git a/src/server/connection.cpp b/src/server/connection.cpp index ddfac1c74..0a93e18af 100644 --- a/src/server/connection.cpp +++ b/src/server/connection.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "server/connection.hpp" #include "server/request_handler.hpp" #include "server/request_parser.hpp" diff --git a/src/server/http/reply.cpp b/src/server/http/reply.cpp index 39957add8..be6e3bfbc 100644 --- a/src/server/http/reply.cpp +++ b/src/server/http/reply.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "server/http/reply.hpp" #include diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index a506df671..aef25014a 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "server/request_handler.hpp" #include "server/api_grammar.hpp" diff --git a/src/server/request_parser.cpp b/src/server/request_parser.cpp index 83cebb1af..37d2b03b0 100644 --- a/src/server/request_parser.cpp +++ b/src/server/request_parser.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "server/request_parser.hpp" #include "server/http/compression_type.hpp" diff --git a/src/tools/check-hsgr.cpp b/src/tools/check-hsgr.cpp index 0dc8310b3..068e4b392 100644 --- a/src/tools/check-hsgr.cpp +++ b/src/tools/check-hsgr.cpp @@ -1,29 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ #include "util/percent.hpp" #include "contractor/query_edge.hpp" #include "util/static_graph.hpp" diff --git a/src/tools/components.cpp b/src/tools/components.cpp index 7634d9d8e..c7bf4fe2b 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/typedefs.hpp" #include "extractor/tarjan_scc.hpp" #include "util/coordinate_calculation.hpp" diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index aaf937690..899f1e8f8 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2013, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "contractor/processing_chain.hpp" #include "contractor/contractor_options.hpp" #include "util/simple_logger.hpp" diff --git a/src/tools/datastore.cpp b/src/tools/datastore.cpp index 42b600aa4..d0ea9a72a 100644 --- a/src/tools/datastore.cpp +++ b/src/tools/datastore.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/original_edge_data.hpp" #include "util/range_table.hpp" #include "contractor/query_edge.hpp" diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index dabc19a5c..1d34a084f 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/extractor.hpp" #include "extractor/extractor_options.hpp" #include "util/simple_logger.hpp" diff --git a/src/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp index 2de94c61b..64bc3dd53 100644 --- a/src/tools/io-benchmark.cpp +++ b/src/tools/io-benchmark.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/version.hpp" #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index 4d1325549..f14052df6 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "server/server.hpp" #include "util/version.hpp" #include "util/routed_options.hpp" diff --git a/src/tools/simpleclient.cpp b/src/tools/simpleclient.cpp index aa3aa262e..0e5460a9e 100644 --- a/src/tools/simpleclient.cpp +++ b/src/tools/simpleclient.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/version.hpp" #include "util/json_renderer.hpp" #include "util/routed_options.hpp" diff --git a/src/tools/springclean.cpp b/src/tools/springclean.cpp index 296d96e5c..40c0f8065 100644 --- a/src/tools/springclean.cpp +++ b/src/tools/springclean.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include #include "datastore/shared_memory_factory.hpp" diff --git a/src/tools/unlock_all_mutexes.cpp b/src/tools/unlock_all_mutexes.cpp index 3b4c9b072..f4c248c48 100644 --- a/src/tools/unlock_all_mutexes.cpp +++ b/src/tools/unlock_all_mutexes.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/version.hpp" #include "util/simple_logger.hpp" #include "engine/datafacade/shared_barriers.hpp" diff --git a/src/util/compute_angle.cpp b/src/util/compute_angle.cpp index b821d7958..885cb8221 100644 --- a/src/util/compute_angle.cpp +++ b/src/util/compute_angle.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/compute_angle.hpp" #include "util/trigonometry_table.hpp" diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index 6124dd8fe..5075d0670 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/coordinate_calculation.hpp" #ifndef NDEBUG diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index e1975ddeb..9ab4a32a3 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/coordinate_calculation.hpp" #include "util/mercator.hpp" diff --git a/src/util/fingerprint.cpp b/src/util/fingerprint.cpp index 8a705b0c8..2764c7bab 100644 --- a/src/util/fingerprint.cpp +++ b/src/util/fingerprint.cpp @@ -1,29 +1,2 @@ -/* - -Copyright (c) 2015, Project OSRM, Dennis Luxen, others -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/fingerprint.hpp" #include "util/fingerprint_impl.hpp" diff --git a/src/util/hilbert_value.cpp b/src/util/hilbert_value.cpp index d65354030..96e39773b 100644 --- a/src/util/hilbert_value.cpp +++ b/src/util/hilbert_value.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/hilbert_value.hpp" #include "osrm/coordinate.hpp" diff --git a/src/util/mercator.cpp b/src/util/mercator.cpp index 239441aa6..36c1a9b84 100644 --- a/src/util/mercator.cpp +++ b/src/util/mercator.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/mercator.hpp" #include diff --git a/src/util/osrm_exception.cpp b/src/util/osrm_exception.cpp index 9715cac72..475e75194 100644 --- a/src/util/osrm_exception.cpp +++ b/src/util/osrm_exception.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/osrm_exception.hpp" namespace osrm diff --git a/src/util/simple_logger.cpp b/src/util/simple_logger.cpp index 362dce638..de3d68190 100644 --- a/src/util/simple_logger.cpp +++ b/src/util/simple_logger.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/simple_logger.hpp" #ifdef _MSC_VER #include diff --git a/unit_tests/engine/douglas_peucker.cpp b/unit_tests/engine/douglas_peucker.cpp index 519e90da4..8b1c3cb58 100644 --- a/unit_tests/engine/douglas_peucker.cpp +++ b/unit_tests/engine/douglas_peucker.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "engine/douglas_peucker.hpp" #include "engine/segment_information.hpp" diff --git a/unit_tests/engine/geometry_string.cpp b/unit_tests/engine/geometry_string.cpp index 7b2dd3ccb..349c153aa 100644 --- a/unit_tests/engine/geometry_string.cpp +++ b/unit_tests/engine/geometry_string.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include #include diff --git a/unit_tests/engine_tests.cpp b/unit_tests/engine_tests.cpp index 1a2f88ed0..8154f03f6 100644 --- a/unit_tests/engine_tests.cpp +++ b/unit_tests/engine_tests.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #define BOOST_TEST_MODULE engine tests #include diff --git a/unit_tests/extractor/raster_source.cpp b/unit_tests/extractor/raster_source.cpp index 0406676b9..3f43d2f40 100644 --- a/unit_tests/extractor/raster_source.cpp +++ b/unit_tests/extractor/raster_source.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/raster_source.hpp" #include "util/typedefs.hpp" #include "util/osrm_exception.hpp" diff --git a/unit_tests/extractor_tests.cpp b/unit_tests/extractor_tests.cpp index 25bc11dff..f2b47457c 100644 --- a/unit_tests/extractor_tests.cpp +++ b/unit_tests/extractor_tests.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #define BOOST_TEST_MODULE extractor tests #include diff --git a/unit_tests/util/bearing.cpp b/unit_tests/util/bearing.cpp index 93d3eb313..ef70ce1df 100644 --- a/unit_tests/util/bearing.cpp +++ b/unit_tests/util/bearing.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/bearing.hpp" #include "util/typedefs.hpp" diff --git a/unit_tests/util/binary_heap.cpp b/unit_tests/util/binary_heap.cpp index 6b7cf64ff..4f270f168 100644 --- a/unit_tests/util/binary_heap.cpp +++ b/unit_tests/util/binary_heap.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/binary_heap.hpp" #include "util/typedefs.hpp" diff --git a/unit_tests/util/coordinate.cpp b/unit_tests/util/coordinate.cpp index c4f361921..08d00a671 100644 --- a/unit_tests/util/coordinate.cpp +++ b/unit_tests/util/coordinate.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include #include "util/coordinate_calculation.hpp" diff --git a/unit_tests/util/duration_parsing.cpp b/unit_tests/util/duration_parsing.cpp index d0599106a..b92916ad7 100644 --- a/unit_tests/util/duration_parsing.cpp +++ b/unit_tests/util/duration_parsing.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "extractor/extraction_helper_functions.hpp" #include diff --git a/unit_tests/util/dynamic_graph.cpp b/unit_tests/util/dynamic_graph.cpp index 585d2e471..416da59d0 100644 --- a/unit_tests/util/dynamic_graph.cpp +++ b/unit_tests/util/dynamic_graph.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/dynamic_graph.hpp" #include "util/typedefs.hpp" diff --git a/unit_tests/util/range_table.cpp b/unit_tests/util/range_table.cpp index 8d30a0876..01fe9448f 100644 --- a/unit_tests/util/range_table.cpp +++ b/unit_tests/util/range_table.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/range_table.hpp" #include "util/typedefs.hpp" diff --git a/unit_tests/util/static_graph.cpp b/unit_tests/util/static_graph.cpp index 21c034be2..f92a7f595 100644 --- a/unit_tests/util/static_graph.cpp +++ b/unit_tests/util/static_graph.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/static_graph.hpp" #include "util/typedefs.hpp" diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index 93b81b906..3adea4ef5 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2015, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/coordinate_calculation.hpp" #include "engine/geospatial_query.hpp" #include "util/static_rtree.hpp" diff --git a/unit_tests/util/string_util.cpp b/unit_tests/util/string_util.cpp index 9ec734aeb..1cee413b6 100644 --- a/unit_tests/util/string_util.cpp +++ b/unit_tests/util/string_util.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #include "util/string_util.hpp" #include diff --git a/unit_tests/util_tests.cpp b/unit_tests/util_tests.cpp index 26275ab6b..7b641fa90 100644 --- a/unit_tests/util_tests.cpp +++ b/unit_tests/util_tests.cpp @@ -1,30 +1,3 @@ -/* - -Copyright (c) 2014, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - #define BOOST_TEST_MODULE util tests #include From 0dda98384b7940eef6e78e8c7c2c6dacf6d6f8fa Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 5 Jan 2016 11:15:30 +0100 Subject: [PATCH 015/701] Bump license year count for headers we install, too --- include/osrm/coordinate.hpp | 2 +- include/osrm/json_container.hpp | 2 +- include/osrm/libosrm_config.hpp | 2 +- include/osrm/osrm.hpp | 2 +- include/osrm/route_parameters.hpp | 2 +- include/osrm/strong_typedef.hpp | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/include/osrm/coordinate.hpp b/include/osrm/coordinate.hpp index 46029cbc9..9c001029a 100644 --- a/include/osrm/coordinate.hpp +++ b/include/osrm/coordinate.hpp @@ -1,6 +1,6 @@ /* -Copyright (c) 2015, Project OSRM contributors +Copyright (c) 2016, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, diff --git a/include/osrm/json_container.hpp b/include/osrm/json_container.hpp index 63accb81c..d8c49b223 100644 --- a/include/osrm/json_container.hpp +++ b/include/osrm/json_container.hpp @@ -1,6 +1,6 @@ /* -Copyright (c) 2013, Project OSRM contributors +Copyright (c) 2016, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, diff --git a/include/osrm/libosrm_config.hpp b/include/osrm/libosrm_config.hpp index 677450a96..bc150077d 100644 --- a/include/osrm/libosrm_config.hpp +++ b/include/osrm/libosrm_config.hpp @@ -1,6 +1,6 @@ /* -Copyright (c) 2015, Project OSRM contributors +Copyright (c) 2016, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, diff --git a/include/osrm/osrm.hpp b/include/osrm/osrm.hpp index cbf14d3cf..892463d61 100644 --- a/include/osrm/osrm.hpp +++ b/include/osrm/osrm.hpp @@ -1,6 +1,6 @@ /* -Copyright (c) 2015, Project OSRM contributors +Copyright (c) 2016, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, diff --git a/include/osrm/route_parameters.hpp b/include/osrm/route_parameters.hpp index 700c55807..474fa03b2 100644 --- a/include/osrm/route_parameters.hpp +++ b/include/osrm/route_parameters.hpp @@ -1,6 +1,6 @@ /* -Copyright (c) 2015, Project OSRM contributors +Copyright (c) 2016, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, diff --git a/include/osrm/strong_typedef.hpp b/include/osrm/strong_typedef.hpp index c2364b053..2d535f9aa 100644 --- a/include/osrm/strong_typedef.hpp +++ b/include/osrm/strong_typedef.hpp @@ -3,7 +3,7 @@ /* -Copyright (c) 2015, Project OSRM contributors +Copyright (c) 2016, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, From 0d971a70cce19908874c979c4d3975631ed7044f Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 5 Jan 2016 11:19:18 +0100 Subject: [PATCH 016/701] Prevent comment splicing from backslash at end of line --- .../routing_algorithms/routing_base.hpp | 69 ++++++++++--------- 1 file changed, 37 insertions(+), 32 deletions(-) diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index 9afee1c44..4b22237b8 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -31,33 +31,35 @@ template class BasicRoutingInterface explicit BasicRoutingInterface(DataFacadeT *facade) : facade(facade) {} ~BasicRoutingInterface() {} - // min_edge_offset is needed in case we use multiple - // nodes as start/target nodes with different (even negative) offsets. - // In that case the termination criterion is not correct - // anymore. - // - // Example: - // forward heap: a(-100), b(0), - // reverse heap: c(0), d(100) - // - // a --- d - // \ / - // / \ - // b --- c - // - // This is equivalent to running a bi-directional Dijkstra on the following graph: - // - // a --- d - // / \ / \ - // y x z - // \ / \ / - // b --- c - // - // The graph is constructed by inserting nodes y and z that are connected to the initial nodes - // using edges (y, a) with weight -100, (y, b) with weight 0 and, - // (d, z) with weight 100, (c, z) with weight 0 corresponding. - // Since we are dealing with a graph that contains _negative_ edges, - // we need to add an offset to the termination criterion. + /* + min_edge_offset is needed in case we use multiple + nodes as start/target nodes with different (even negative) offsets. + In that case the termination criterion is not correct + anymore. + + Example: + forward heap: a(-100), b(0), + reverse heap: c(0), d(100) + + a --- d + \ / + / \ + b --- c + + This is equivalent to running a bi-directional Dijkstra on the following graph: + + a --- d + / \ / \ + y x z + \ / \ / + b --- c + + The graph is constructed by inserting nodes y and z that are connected to the initial nodes + using edges (y, a) with weight -100, (y, b) with weight 0 and, + (d, z) with weight 100, (c, z) with weight 0 corresponding. + Since we are dealing with a graph that contains _negative_ edges, + we need to add an offset to the termination criterion. + */ void RoutingStep(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, NodeID &middle_node_id, @@ -293,9 +295,12 @@ template class BasicRoutingInterface { BOOST_ASSERT(i < id_vector.size()); BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode > 0); - unpacked_path.emplace_back(PathData{ - id_vector[i], phantom_node_pair.target_phantom.name_id, TurnInstruction::NoTurn, - 0, phantom_node_pair.target_phantom.forward_travel_mode}); + unpacked_path.emplace_back( + PathData{id_vector[i], + phantom_node_pair.target_phantom.name_id, + TurnInstruction::NoTurn, + 0, + phantom_node_pair.target_phantom.forward_travel_mode}); } } @@ -493,8 +498,8 @@ template class BasicRoutingInterface // TODO check if unordered_set might be faster // sort by id and increasing by distance - auto entry_point_comparator = [](const std::pair &lhs, - const std::pair &rhs) + auto entry_point_comparator = + [](const std::pair &lhs, const std::pair &rhs) { return lhs.first < rhs.first || (lhs.first == rhs.first && lhs.second < rhs.second); }; From 4ca29dd18e95a52e22bb8302fccb383c6c853b5a Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 5 Jan 2016 11:29:25 +0100 Subject: [PATCH 017/701] Default initialize (i.e. zero initialize) variables to suppress -Wuninitialized false positive --- src/contractor/processing_chain.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index 9577b6c7f..1757e52a7 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -153,9 +153,9 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f << segment_speed_filename; io::CSVReader<3> csv_in(segment_speed_filename); csv_in.set_header("from_node", "to_node", "speed"); - uint64_t from_node_id; - uint64_t to_node_id; - unsigned speed; + uint64_t from_node_id{}; + uint64_t to_node_id{}; + unsigned speed{}; while (csv_in.read_row(from_node_id, to_node_id, speed)) { segment_speed_lookup[std::make_pair(OSMNodeID(from_node_id), OSMNodeID(to_node_id))] = speed; From 552cdbfe208e75eabc23bc78fbdf3fd197a7d264 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sun, 3 Jan 2016 18:55:42 +0100 Subject: [PATCH 018/701] Apply clang-tidy --- include/util/routed_options.hpp | 2 +- src/benchmarks/static_rtree.cpp | 2 +- src/contractor/contractor_options.cpp | 2 +- src/engine/osrm_impl.cpp | 2 +- src/engine/phantom_node.cpp | 4 +--- src/engine/route_parameters.cpp | 2 +- src/extractor/extraction_containers.cpp | 2 +- src/extractor/extractor.cpp | 4 ++-- src/extractor/extractor_options.cpp | 2 +- src/extractor/graph_compressor.cpp | 2 +- src/extractor/restriction_map.cpp | 6 +----- src/extractor/restriction_parser.cpp | 10 +++------- src/tools/contract.cpp | 2 +- src/tools/datastore.cpp | 8 ++++---- src/tools/routed.cpp | 4 ++-- src/util/coordinate.cpp | 8 ++------ 16 files changed, 24 insertions(+), 38 deletions(-) diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index 12d1e8d8a..29840b5e7 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -2,7 +2,7 @@ #define ROUTED_OPTIONS_HPP #include "util/version.hpp" -#include "util/ini_file.hpp" +#include "util/version.hpp" #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" diff --git a/src/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp index e8c5a81f2..c3967f4cd 100644 --- a/src/benchmarks/static_rtree.cpp +++ b/src/benchmarks/static_rtree.cpp @@ -6,8 +6,8 @@ #include "osrm/coordinate.hpp" -#include #include +#include // Choosen by a fair W20 dice roll (this value is completely arbitrary) constexpr unsigned RANDOM_SEED = 13; diff --git a/src/contractor/contractor_options.cpp b/src/contractor/contractor_options.cpp index 2bb8451d8..463bd7906 100644 --- a/src/contractor/contractor_options.cpp +++ b/src/contractor/contractor_options.cpp @@ -1,7 +1,7 @@ #include "contractor/contractor_options.hpp" -#include "util/version.hpp" #include "util/simple_logger.hpp" +#include "util/version.hpp" #include #include diff --git a/src/engine/osrm_impl.cpp b/src/engine/osrm_impl.cpp index 84faf89da..f9a486e75 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/osrm_impl.cpp @@ -27,9 +27,9 @@ class named_mutex; #include #include -#include "osrm/route_parameters.hpp" #include "osrm/libosrm_config.hpp" #include "osrm/osrm.hpp" +#include "osrm/route_parameters.hpp" #include #include diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp index 8c4a17a7a..689fc5ebd 100644 --- a/src/engine/phantom_node.cpp +++ b/src/engine/phantom_node.cpp @@ -1,8 +1,6 @@ #include "engine/phantom_node.hpp" - -#include "util/typedefs.hpp" #include "extractor/travel_mode.hpp" - +#include "util/typedefs.hpp" #include "osrm/coordinate.hpp" #include diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index 6649462bf..d98d963ea 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -50,7 +50,7 @@ void RouteParameters::setAllUTurns(const bool flag) } } -void RouteParameters::setDeprecatedAPIFlag(const std::string &) { deprecatedAPI = true; } +void RouteParameters::setDeprecatedAPIFlag(const std::string & /*unused*/) { deprecatedAPI = true; } void RouteParameters::setChecksum(const unsigned sum) { check_sum = sum; } diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index d21d61d49..18de02d32 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -14,8 +14,8 @@ #include #include #include -#include #include +#include #include diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index f04c4564a..496c8639e 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -18,8 +18,8 @@ #include "util/static_graph.hpp" #include "util/static_rtree.hpp" -#include "extractor/restriction_map.hpp" #include "extractor/compressed_edge_container.hpp" +#include "extractor/restriction_map.hpp" #include "extractor/tarjan_scc.hpp" #include "contractor/crc32_processor.hpp" @@ -573,7 +573,7 @@ void extractor::BuildRTree(std::vector node_based_edge_list, node_based_edge_list.resize(new_size); TIMER_START(construction); - StaticRTree(node_based_edge_list, config.rtree_nodes_output_path, + StaticRTree rtree(node_based_edge_list, config.rtree_nodes_output_path, config.rtree_leafs_output_path, internal_to_external_node_map); TIMER_STOP(construction); diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp index 0c3d5211a..685704a57 100644 --- a/src/extractor/extractor_options.cpp +++ b/src/extractor/extractor_options.cpp @@ -1,7 +1,7 @@ #include "extractor/extractor_options.hpp" -#include "util/version.hpp" #include "util/ini_file.hpp" +#include "util/version.hpp" #include "util/simple_logger.hpp" #include diff --git a/src/extractor/graph_compressor.cpp b/src/extractor/graph_compressor.cpp index c9e1d5b76..8ee098089 100644 --- a/src/extractor/graph_compressor.cpp +++ b/src/extractor/graph_compressor.cpp @@ -1,9 +1,9 @@ #include "extractor/graph_compressor.hpp" #include "extractor/compressed_edge_container.hpp" +#include "extractor/restriction_map.hpp" #include "util/dynamic_graph.hpp" #include "util/node_based_graph.hpp" -#include "extractor/restriction_map.hpp" #include "util/percent.hpp" #include "util/simple_logger.hpp" diff --git a/src/extractor/restriction_map.cpp b/src/extractor/restriction_map.cpp index 44a6b574c..c104d19d8 100644 --- a/src/extractor/restriction_map.cpp +++ b/src/extractor/restriction_map.cpp @@ -149,9 +149,5 @@ bool RestrictionMap::CheckIfTurnIsRestricted(const NodeID node_u, // check of node is the start of any restriction bool RestrictionMap::IsSourceNode(const NodeID node) const { - if (m_restriction_start_nodes.find(node) == m_restriction_start_nodes.end()) - { - return false; - } - return true; + return m_restriction_start_nodes.find(node) != m_restriction_start_nodes.end(); } diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index 5a5137b64..85f93dce4 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -9,9 +9,9 @@ #include #include #include +#include #include #include -#include #include #include @@ -218,12 +218,8 @@ bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_st return std::any_of(std::begin(exceptions), std::end(exceptions), [&](const std::string ¤t_string) { - if (std::end(restriction_exceptions) != + return std::end(restriction_exceptions) != std::find(std::begin(restriction_exceptions), - std::end(restriction_exceptions), current_string)) - { - return true; - } - return false; + std::end(restriction_exceptions), current_string); }); } diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index 899f1e8f8..f5f994bcb 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -8,8 +8,8 @@ #include #include -#include #include +#include int main(int argc, char *argv[]) try { diff --git a/src/tools/datastore.cpp b/src/tools/datastore.cpp index d0ea9a72a..262e095ce 100644 --- a/src/tools/datastore.cpp +++ b/src/tools/datastore.cpp @@ -6,15 +6,15 @@ #include "util/shared_memory_vector_wrapper.hpp" #include "util/static_graph.hpp" #include "util/static_rtree.hpp" +#include "engine/datafacade/datafacade_base.hpp" #include "extractor/travel_mode.hpp" #include "extractor/turn_instructions.hpp" -#include "engine/datafacade/datafacade_base.hpp" #include "engine/datafacade/shared_datatype.hpp" #include "engine/datafacade/shared_barriers.hpp" #include "util/datastore_options.hpp" -#include "util/simple_logger.hpp" -#include "util/osrm_exception.hpp" #include "util/fingerprint.hpp" +#include "util/osrm_exception.hpp" +#include "util/simple_logger.hpp" #include "util/typedefs.hpp" #include "osrm/coordinate.hpp" @@ -33,8 +33,8 @@ using QueryGraph = StaticGraph; #include #include -#include #include +#include // delete a shared memory region. report warning if it could not be deleted void delete_region(const SharedDataType region) diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index f14052df6..c95233c81 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -1,5 +1,5 @@ #include "server/server.hpp" -#include "util/version.hpp" +#include "util/ini_file.hpp" #include "util/routed_options.hpp" #include "util/simple_logger.hpp" @@ -17,8 +17,8 @@ #include #include #include -#include #include +#include #ifdef _WIN32 boost::function0 console_ctrl_function; diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index 5075d0670..f5799cb08 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -36,12 +36,8 @@ FixedPointCoordinate::FixedPointCoordinate(int lat, int lon) : lat(lat), lon(lon bool FixedPointCoordinate::is_valid() const { - if (lat > 90 * COORDINATE_PRECISION || lat < -90 * COORDINATE_PRECISION || - lon > 180 * COORDINATE_PRECISION || lon < -180 * COORDINATE_PRECISION) - { - return false; - } - return true; + return !(lat > 90 * COORDINATE_PRECISION || lat < -90 * COORDINATE_PRECISION || + lon > 180 * COORDINATE_PRECISION || lon < -180 * COORDINATE_PRECISION); } bool FixedPointCoordinate::operator==(const FixedPointCoordinate &other) const From 9852b147f818d746d50d32fe06b5b8d15df611d0 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 5 Jan 2016 11:56:51 +0100 Subject: [PATCH 019/701] Bump libosmium version to 2.5.4 in update script --- scripts/update_depdendencies.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/update_depdendencies.sh b/scripts/update_depdendencies.sh index e443cfa5f..8e2757249 100755 --- a/scripts/update_depdendencies.sh +++ b/scripts/update_depdendencies.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash OSMIUM_REPO=https://github.com/osmcode/libosmium.git -OSMIUM_TAG=v2.3.0 +OSMIUM_TAG=v2.5.4 VARIANT_REPO=https://github.com/mapbox/variant.git VARIANT_TAG=v1.0 From afdf8e7b21fbaf597e91d9d8a7542635e60ee9a1 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 5 Jan 2016 12:00:40 +0100 Subject: [PATCH 020/701] Squashed 'third_party/libosmium/' changes from c43f8db..0ff2780 0ff2780 Release v2.5.4 3f1583a Remove workaround for MSVC missing constexpr support. 2a6c80b Rewrite expressions to avoid warnings on MSVC. 9b0602a Make two functions non-constexpr that can't be. ca1e501 Make NodeRef constructor, accessors and comparison ops constexpr. fb48312 Disable some problematic clang_tidy checks. d2d2812 Only do clang_tidy checks on files that are configured to be built. 5af55bb Always use braces after while() and if(). aebb6e3 No else after return. 65a3bf6 Better clang-tidy config. 3a965fa Add typedef Buffer::value_type needed when using std::back_inserter. c20ac26 Add lots of explicits to constructors. 1d12e09 Add clang-tidy make target. 052b1ee Add benchmark programs to files checked with cppcheck. 9ccbb49 Use only "final", not "override final". 0b9df1f User 'override' instead of 'virtual' in overridden functions. 1d0c1c6 Remove unnecessary get() call. 705391b Use consistent namespace closing comment. 25c1f38 Only use "final" on overridden methods, not "override". 8da2553 Setting CMAKE_EXPORT_COMPILE_COMMANDS works only after project() command. 5fec437 Use newest protozero library (v1.2.3). a3d759b Overloaded version of add_tag() with std::pair of strings. 1b4bcf9 Add function to add tag to tag list from existing tag. 7087e62 Update gdalcpp.hpp header to v1.1.1. 0008e8c Update change log. 39fe3a5 Add conversion and comparison operators to Timestamp. e6643a7 Update gdalcpp. 650280f Bugfix: Improved segment intersection function. 1b20597 Make operator bool explicit for (Typed)MemoryMapping. b580b25 Merge pull request #136 from tomhughes/ruby a7c6737 The multipolygon test only needs the ruby interpreter 4a0a9e7 Make conversion from Buffer to bool noexcept. 7cdabbe Set thread name in o5m input format. 6a17a8d Break out computation of thread pool size into function and test it. 1950853 Allow initializing a Timestamp from any integral type. 4103198 Fix link in change log. dc2ed89 Release v2.5.3 a2816b7 Fix end_of_time() Timestamp, add constructor taking std::string&. 3f5eb8e Updated changelog. 9b75c14 Cleanup and better docs for DiffObject and related classes. d0beead Better documentation for NodeRef and NodeRefList classes. 0192292 Cleanup/doc/test osmium::util::Options. b3db055 Use header with forward declarations. 8b3fe16 Improved documentation. cd2ce38 Remove unused typedef Buffer::value_type. 87c9b32 Cleanup and test Buffer::add_buffer() function. e519278 Improved documentation for osmium::memory::Buffer. d721d43 Deprecate set_full_callback(). Better doc for deprecated functions. 58b5fd1 Remove DataFile class which was never used anywhere. 30b806e Simplify some tests. 62958df Update change log. a8a2e68 Merge pull request #134 from zerebubuth/buffer-size-checks 987faab Move some code belonging into there into relations::Collector. da31175 When the buffer isn't big enough, even when empty, to reserve the space that's being requested then it shouldn't reserve it anyway. 5d2f949 Swap the growth flag and any "full" callback as well as all the other members when swapping this buffer object. 1845aa9 The assertions prior to dereference are more strict than the conversion to bool. However, conversion to bool is often used as a predicate for whether dereference is okay, so the behaviour is easier to understand if they match. abdfee1 Remove unused m_want_types in relations collector. 95b387f "Officially" mark two constructors as deprecated. 1d0da5f Release v2.5.2 31c3eaf Copy iterator around less often. 83c93d0 Do not check the write_future for exceptions on every item. 1c805ea Add counting of push() calls on queue in debug mode. aa869c0 Release v2.5.1 212578b Fix documentation of Writer constructor. 0445dd8 Add new header file with forward declarations of commonly used classes. 4b6baac Optionally include external library headers. 712a6d1 Update change log. fc78d04 Update style rules. b590fe3 Unify use of 'typename' in templates. Unify spacing of ellipsis operator. 8c450ac Move osmium/io/overwrite.hpp to writer_options.hpp. 08eed02 Move DEPRECATED macro into compatibility.hpp. b72eb8d Release v2.5.0 5aeba6b Better formatting for invalid timestamps on debug output. 6772413 Add valid() function on Timestamp. 7549b05 Update change log. 84119b0 Add option to fsync files after they are written. db1bd92 Make optional parameters on Writer work in any order. 3482e3e Remove boilerplate. Add explicits to constructors. cf389c6 Rename the wrap() function to the better ensure_cleanup(). 678049e Use reference instead of pointer for decompressor. 7189d28 More consistent use and naming of Function templates. 3d66deb Use const& for parameter that's not changed. 88d65fb Fix warning with a cast. 03e8c9f Fix some misc issues found by cppcheck. 4848676 Options to cppcheck to check everything (--force) and ignore assert. 5f89a8c Add lots of assert() calls to Buffer implementation. c990b43 Use a wrapper function in Writer for error handling. 04d9e3e Refactor of writer to work properly in all error cases. 6daf2d3 Throw when reading from Reader after eof or error. Use io_error everywhere. 713a189 Rename OutputFormat::close() to write_end(). 7905add Refactor Reader/Writer code. c050a05 Make thread_handler class movable. 8e661a2 Make DeltaEncode/Decode more generic and fix signedness issues. da712a9 Fixed a few signedness issues. dc04e67 Avoid possible narrowing conversion. abd44af Make a variable static that should be. 7039fa6 Avoid global variable. 9e9fc0f Add a noreturn attribute. a681a2c Do not pass Timestamp class through forwarding. d37b717 Clean up status handling in Reader and Writer. 3b1f0d8 Add at_end_of_data() helper function to get self-documenting code. bf3cc8c Add add_end_of_data_to_queue() helper function. 94bdd09 Fix test. 531db80 Use valid() on future instead of an extra bool. 7f328b3 Make RVO work for pop() function. c1d726d Add some static_cast_with_assert paranoia checks. 5a064f7 Make sure DeltaDecode/DeltaEncode classes work for all integer types. c69a701 Fix some integer types. 2b2cfc9 Remove extra semicolons at end of function definitions. 2b74aa6 Use workaround for GCC unused variable warning for index::map, too. f7fb94d Different way of supression unused-variable warning. c0813e6 Better handling of threads. 963ff8e Move internal buffer from OutputIterator into Writer. 698d027 Update change log. 24270dd Remove unused variables. 64d6363 Remove unnecessarily fully-qualified name. 5ccacc7 Add support for reading o5m and o5c files. b603904 Fix up includes. 6013a27 Remove pessimizing move. a19e4cf Use queue_wrapper in Reader, too. 74a5174 Refactor thread creation for WriteThread. c480b33 Fix test code. e135597 Do not use promise in two threads at once. 6fa16ca Refactor input format code. 53fc576 More robust implementation of writer/writer_thread. 1285316 Put some queue handling into new wrapper class. a1e6e6f Rename osmium/io/detail/util.hpp to queue_util.hpp. f42d6fc New add_to_queue() helper functions. 3db9b49 Simplify read thread handling. a903561 Move any exception in read thread through queue. ee977cb Add more tests for reader code. 99aaa45 Factor out input handling in classes derived from Parser. 7afa03c Wrap access to m_read_types in InputFormat. f6c5971 Wrap sending to output queue in InputFormat. 26f4170 Consolidate header handling in InputFormat. a0aa3ed Remove unnecessary inline declaration. 894e84a Declare a bunch of destructors noexcept and use consistent comments. 6c49b43 Add hack to append_printf_formatted_string() so it works on Windows. 20c3f20 Remove a move that prevented copy elision. 8192a4c Pull low-level string formatting out of debug output and test it. 190aa46 Move low-level string formatting/encoding functions into own header. 3e35441 Add Option::is_not_false() helper, use and test it. 0a90339 Updated some comments. a44066f Make naming of output format options more consistent and document them. a59b60b Run serialization of PBF blobs in worker threads speeding up PBF writer. 18a739f Remove unused m_file attribute from OutputFormat class. 9b5d3b7 Various output option related cleanups. 36772a0 Consistent ordering of methods in *InputFormat classes. c04a51f Factor out common code in output formats. ebc53d4 Do not use "explicit" on constructors with more than one argument. e1dfcfc Make all destructors in io/detail noexcept. cfd7970 Use consistent handling of output options in all outputs. c4e71f0 Better implementation for output_formatted() and tests for it. 899a061 Extract common code from output formats. b226ae4 Factor out common code from *OutputBlock classes. fe4b287 Cleanup WriteThread class. af421df Consistent naming of queue typedefs. e8253c4 Add missing include. 9f71cd3 Refactor management of read thread into its own class. 4c96e16 Refactor Reader/InputFormat. fa02e6c Refactor input format code. d14ea27 Extract common code from PBF/XMLParser into new Parser class. fe7acd3 Better handling of failures when parsing header. 2e3b6cd Remove unnecessary include of . 3bd18b8 Factor out common code in input format. 2915604 Only get promise and future once, even if header() is called multiple times. cfc980c Make output buffer for XML parser smaller. 4c1ffa7 Orderly shutdown in io::Reader. 8c7aa32 Remember whether the input queue was exhausted. 535bb6a Function call in new thread can be void. e0d5448 Factor out some helper function for queue cleanup. 5a4c6b5 Use std::thread directly for input instead of std::async. c1bdf4f Move common code from InputFormat child classed into base class. 89caa6e Report failures in input_format through the queue. 8f4d300 Rename (m_)queue to (m_)output_queue. 8fc1f5b Reorder XMLParser class making check_attributes() private. df381d7 Make sure we always send end-of-file from PBF parser. 1a178b0 Factor out construction of PBFDataBlobDecoder. cb34f76 Factor out read_from_input_queue_with_check() method. 21b51cc Factor out parse_data_blobs() method. dc957a8 Make some variables const. 1c2812c Make methods private that don't need to be public. 81e5625 Refactor out parse_header_blob() function. f9e5760 Fix test: New signature of XMLParser constructor. 43746d3 Add copy constructor to PBFParser. 8524780 Rename variables and other changes for clarity. 3e9627b Removed now superfluous parameters from InputFormat class. 7eac5cf Simplify input format class. 3ea2ace Set max queue size only in one place. 77ab086 Formatting. ceee837 Use std::async instead of "raw" std::thread for pbf input. 6cafb45 Move and rename PromiseKeeper class: Now in thread/util.hpp. 06eff29 Set thread name for xml parser thread. bd485cd Refactoring of threading code for input. fc03bf6 Make sure (de)compression classes clean up properly. 27af4ea Use special function to shut down pool workers instead of an atomic. 84297b3 Bugfix: auto and std::minmax() don't mix well. 597ecc4 Always use std::swap() in the idiomatic form. 10dd14f Remove threading test that fails when machine is too busy. 2072786 Use reserve() to spead up dumping indexes. 66a344b Declare some index functions noexcept, especially destructors. a0586da Use map::find() instead of awkward try-catch block. d38a7f1 Do not run make tasks in parallel. cd33daa Do not use clever YAML aliases, instead copy dependencies explicitely 4ad6e43 Integrate more compiler and os versions b2c519b Check return code of close() system call and throw. 369057b Update protozero to current 1.2.2. d1db14b Collect debug output options into struct. 54667dd More consistent debug output of way nodes, relation members and changeset comments. 67e1513 Add some paranoia checks to xml parser. 69de191 Refactoring in xml reader: New function check_attributes(). c67f3f3 Add support for changeset discussions (comments). 9c5531c Merge pull request #121 from DerDakon/cmake-find-no-components 44be1a7 Add helper functions to make input iterator ranges and output iterators. 76e2b91 Merge pull request #130 from alex85k/master 5a4fa6b remove assertion messageboxes in tests on Windows bac5a77 Updated change log. 7e7bba4 Updated included protozero library to 1.2.0. 1ae370d Merge pull request #122 from zerebubuth/pbf-decode-non-visible-node-locations 5897468 Merge branch 'master' of github.com:osmcode/libosmium 7f2de1b Bugfix: Delta iterator handling. 65d31e9 Try ; as cmake list separator. 3a9dbc2 Add PBF libraries, now that the test reads PBF too. Thanks @tomhughes for pointing this out. 9a22ea1 Add test case for reading deleted / non-visible nodes in history files. 36098a8 Decode lat/lon even for non-visible nodes. 8279fd1 kick off AppVeyor to test new binary deps package with gdal200 c8244f7 FindOsmium: prevent errors in list(REMOVE_DUPLICATES) when no components are requested a02806a Use https URL to travis. a1b7015 Fix some includes. 468e4d8 Remove pessimizing std::move. 427d2e0 Do iwyu check on header files in alphabetical order. be9a996 Release v2.4.1 95a3bc8 Fixed CRC calculation of tags and changesets. 4e157e3 Release v2.4.0 3da68f0 Fixed setting of binary mode on Windows. 81aa057 Use binary mode for memory mapped file on Windows. 986cb7e Set stdout to binary mode on windows before writing to files. 27d02eb Bugfix: Do not dereference end iterator. e96eeaf Updated change log. 64a55ce FindOsmium: let FPHSA handle all the additionally required things e152057 FindOsmium: pass the proper module name to FPHSA a4acce3 Remove restriction on master branch in appveyor config. 10c8265 FindOsmium: simplify the fallback code for sparsetable::size_type 190ed47 remove the correct include dir from OSMIUM_INCLUDE_DIRS aaa99c1 avoid that FindOsmium finds a random include dir 6406010 Add a magic define fixing a boost problem. 2fa6674 Remove superfluous file paths from cmake config. e081a51 Merge pull request #114 from DerDakon/do-not-cache-version 20e1a24 Use external gdalcpp wrapper for compatibility with GDAL 2. 3b7cc86 Fix initialization order in DeltaEncodeIterator. 0954b0f Fix possibly uninitialized variable. f081942 Take byte swap functions out of CRC class. e085aae Fix byte swap, add test cases for crc. e648b62 Merge pull request #116 from DerDakon/yml-simplify 7912897 properly put bzip2 library in the CMake cache e0ea72b use less variables when defining the test environment cf8ff6c do not cache the version string 38234cd Remove pragmas disabling warnings from gdal includes. 82d8c30 Include headers of external libraries as "system libraries". f721b86 Update protozero to version 1.1.0. a29ef82 Add some magic to enable folding on travis output. 18b2418 Removed toogr examples. They are in their own repository now. 89c8220 AppVeyor: 1st try with VS2015 93a1626 Added recent changes to change log. ce4b45e Bugfix: Program hanging when opening unknown file type. 06ad6ef Rename add_string() to store_in_stringtable() and use right return type. 869058d Add explicit conversion that always works. 0b28f2c Add missing check in TagListBuilder add_tag() overload. 51fa9c0 Check in builder that key/value of a tag is not too long. 9b1da20 Check that string table isn't overflowing. 2c732c6 Add some extra paranoia checks and type conversions to pbf writer. f92096a Fix integer size. a47ddb4 Force conversion to smaller int type, because we know it must fit. f150ff1 Rename variable that was hiding parameter name. ab92064 Use correct size_t as return type. 2f2bf68 Check that roles are no longer than max allowed string length. 4a7df68 Check strings for max length in PBF input. e4b8bb0 Explicit conversion to bool. d18352d Make conversion from double to integer explicit. git-subtree-dir: third_party/libosmium git-subtree-split: 0ff278001f6e0bc79040add736452bef3aa4ff06 --- .travis.yml | 179 ++++- CHANGELOG.md | 137 +++- CMakeLists.txt | 156 ++++- CONTRIBUTING.md | 45 +- README.md | 14 +- appveyor.yml | 31 +- cmake/FindOsmium.cmake | 64 +- cmake/iwyu.sh | 2 +- examples/CMakeLists.txt | 27 +- examples/osmium_filter_discussions.cpp | 72 ++ examples/osmium_toogr.cpp | 244 ------- examples/osmium_toogr2.cpp | 331 --------- examples/osmium_toogr2_exp.cpp | 305 --------- include/gdalcpp.hpp | 406 +++++++++++ include/osmium/area/assembler.hpp | 4 + .../osmium/area/detail/node_ref_segment.hpp | 68 +- include/osmium/area/detail/proto_ring.hpp | 9 +- include/osmium/area/detail/segment_list.hpp | 2 + .../osmium/area/multipolygon_collector.hpp | 34 +- .../area/problem_reporter_exception.hpp | 2 +- include/osmium/area/problem_reporter_ogr.hpp | 134 +--- .../osmium/area/problem_reporter_stream.hpp | 2 +- include/osmium/builder/builder.hpp | 4 +- include/osmium/builder/osm_object_builder.hpp | 162 ++++- include/osmium/diff_handler.hpp | 3 +- include/osmium/diff_iterator.hpp | 54 +- include/osmium/diff_visitor.hpp | 14 +- include/osmium/dynamic_handler.hpp | 35 +- include/osmium/experimental/flex_reader.hpp | 18 +- include/osmium/fwd.hpp | 70 ++ include/osmium/geom/coordinates.hpp | 1 - include/osmium/geom/factory.hpp | 25 +- include/osmium/geom/geojson.hpp | 12 +- include/osmium/geom/geos.hpp | 2 +- include/osmium/geom/ogr.hpp | 32 +- include/osmium/geom/rapid_geojson.hpp | 4 +- include/osmium/geom/tile.hpp | 6 +- include/osmium/geom/wkb.hpp | 10 +- include/osmium/geom/wkt.hpp | 12 +- include/osmium/handler.hpp | 19 +- include/osmium/handler/chain.hpp | 10 +- .../handler/node_locations_for_ways.hpp | 2 +- include/osmium/index/bool_vector.hpp | 4 +- .../index/detail/create_map_with_fd.hpp | 17 +- .../osmium/index/detail/mmap_vector_anon.hpp | 2 + .../osmium/index/detail/mmap_vector_base.hpp | 6 +- .../osmium/index/detail/mmap_vector_file.hpp | 8 +- include/osmium/index/detail/vector_map.hpp | 36 +- .../osmium/index/detail/vector_multimap.hpp | 14 +- include/osmium/index/index.hpp | 2 +- include/osmium/index/map.hpp | 21 +- include/osmium/index/map/dummy.hpp | 12 +- include/osmium/index/map/sparse_mem_map.hpp | 23 +- include/osmium/index/map/sparse_mem_table.hpp | 15 +- include/osmium/index/multimap.hpp | 2 +- include/osmium/index/multimap/hybrid.hpp | 24 +- .../index/multimap/sparse_mem_multimap.hpp | 14 +- include/osmium/io/any_input.hpp | 1 + include/osmium/io/bzip2_compression.hpp | 79 ++- include/osmium/io/compression.hpp | 101 ++- .../osmium/io/detail/debug_output_format.hpp | 235 +++---- include/osmium/io/detail/input_format.hpp | 155 +++-- include/osmium/io/detail/o5m_input_format.hpp | 636 ++++++++++++++++++ .../osmium/io/detail/opl_output_format.hpp | 133 ++-- include/osmium/io/detail/output_format.hpp | 66 +- include/osmium/io/detail/pbf.hpp | 9 +- include/osmium/io/detail/pbf_decoder.hpp | 55 +- include/osmium/io/detail/pbf_input_format.hpp | 189 ++---- .../osmium/io/detail/pbf_output_format.hpp | 332 +++++---- include/osmium/io/detail/queue_util.hpp | 157 +++++ include/osmium/io/detail/read_thread.hpp | 95 ++- include/osmium/io/detail/read_write.hpp | 70 +- include/osmium/io/detail/string_table.hpp | 31 +- include/osmium/io/detail/string_util.hpp | 206 ++++++ include/osmium/io/detail/write_thread.hpp | 59 +- include/osmium/io/detail/xml_input_format.hpp | 562 +++++++--------- .../osmium/io/detail/xml_output_format.hpp | 273 ++++---- include/osmium/io/detail/zlib.hpp | 5 +- include/osmium/io/error.hpp | 16 +- include/osmium/io/file.hpp | 8 +- include/osmium/io/gzip_compression.hpp | 72 +- include/osmium/io/input_iterator.hpp | 40 +- include/osmium/io/o5m_input.hpp | 45 ++ include/osmium/io/output_iterator.hpp | 68 +- include/osmium/io/overwrite.hpp | 17 +- include/osmium/io/reader.hpp | 162 +++-- include/osmium/io/writer.hpp | 281 ++++++-- include/osmium/io/writer_options.hpp | 60 ++ include/osmium/memory/buffer.hpp | 285 ++++++-- include/osmium/memory/collection.hpp | 6 +- include/osmium/memory/item.hpp | 6 +- include/osmium/memory/item_iterator.hpp | 22 +- include/osmium/object_pointer_collection.hpp | 2 +- include/osmium/osm/area.hpp | 3 +- include/osmium/osm/box.hpp | 8 +- include/osmium/osm/changeset.hpp | 135 +++- include/osmium/osm/crc.hpp | 53 +- include/osmium/osm/diff_object.hpp | 147 +++- include/osmium/osm/entity.hpp | 2 +- include/osmium/osm/item_type.hpp | 17 +- include/osmium/osm/location.hpp | 18 +- include/osmium/osm/node.hpp | 4 +- include/osmium/osm/node_ref.hpp | 100 ++- include/osmium/osm/node_ref_list.hpp | 33 +- include/osmium/osm/object.hpp | 18 +- include/osmium/osm/relation.hpp | 12 +- include/osmium/osm/segment.hpp | 8 +- include/osmium/osm/tag.hpp | 5 +- include/osmium/osm/timestamp.hpp | 124 +++- include/osmium/osm/types.hpp | 4 + include/osmium/osm/types_from_string.hpp | 83 ++- include/osmium/osm/way.hpp | 4 +- include/osmium/relations/collector.hpp | 177 ++--- .../osmium/relations/detail/member_meta.hpp | 2 +- include/osmium/tags/filter.hpp | 8 +- include/osmium/tags/taglist.hpp | 6 +- include/osmium/thread/function_wrapper.hpp | 30 +- include/osmium/thread/pool.hpp | 57 +- include/osmium/thread/queue.hpp | 11 +- include/osmium/thread/util.hpp | 37 +- include/osmium/util/compatibility.hpp | 12 +- include/osmium/util/config.hpp | 2 +- include/osmium/util/data_file.hpp | 194 ------ include/osmium/util/delta.hpp | 71 +- include/osmium/util/double.hpp | 8 +- include/osmium/util/file.hpp | 6 +- include/osmium/util/memory_mapping.hpp | 40 +- include/osmium/util/options.hpp | 76 ++- include/osmium/visitor.hpp | 38 +- include/protozero/byteswap.hpp | 34 +- include/protozero/config.hpp | 57 ++ include/protozero/pbf_builder.hpp | 28 +- include/protozero/pbf_message.hpp | 44 ++ include/protozero/pbf_reader.hpp | 46 +- include/protozero/pbf_writer.hpp | 17 +- include/protozero/varint.hpp | 4 - include/protozero/version.hpp | 22 + scripts/travis_install.sh | 20 - scripts/travis_script.sh | 29 - test/CMakeLists.txt | 10 +- test/data-tests/CMakeLists.txt | 6 +- test/data-tests/testdata-multipolygon.cpp | 171 +---- test/data-tests/testdata-overview.cpp | 154 +---- test/data-tests/testdata-xml.cpp | 35 +- test/t/area/test_node_ref_segment.cpp | 14 + test/t/basic/test_changeset.cpp | 62 +- test/t/basic/test_crc.cpp | 21 + test/t/basic/test_node.cpp | 6 +- test/t/basic/test_object_comparisons.cpp | 44 +- test/t/basic/test_relation.cpp | 15 +- test/t/basic/test_timestamp.cpp | 27 +- test/t/basic/test_way.cpp | 4 +- test/t/buffer/test_buffer_basics.cpp | 34 + test/t/buffer/test_buffer_node.cpp | 78 ++- test/t/geom/test_tile_data.hpp | 4 +- test/t/io/deleted_nodes.osh | 5 + test/t/io/deleted_nodes.osh.pbf | Bin 0 -> 189 bytes test/t/io/test_output_utils.cpp | 153 +++++ test/t/io/test_reader.cpp | 105 ++- .../test_reader_with_mock_decompression.cpp | 145 ++++ test/t/io/test_reader_with_mock_parser.cpp | 123 ++++ test/t/io/test_string_table.cpp | 6 +- test/t/io/test_writer.cpp | 117 ++++ .../io/test_writer_with_mock_compression.cpp | 99 +++ test/t/io/test_writer_with_mock_encoder.cpp | 105 +++ test/t/tags/test_tag_list.cpp | 11 + test/t/thread/test_pool.cpp | 62 +- test/t/util/test_data_file.cpp | 81 --- test/t/util/test_delta.cpp | 34 +- test/t/util/test_file.cpp | 2 + test/t/util/test_options.cpp | 49 +- 171 files changed, 7150 insertions(+), 3988 deletions(-) create mode 100644 examples/osmium_filter_discussions.cpp delete mode 100644 examples/osmium_toogr.cpp delete mode 100644 examples/osmium_toogr2.cpp delete mode 100644 examples/osmium_toogr2_exp.cpp create mode 100644 include/gdalcpp.hpp create mode 100644 include/osmium/fwd.hpp create mode 100644 include/osmium/io/detail/o5m_input_format.hpp create mode 100644 include/osmium/io/detail/queue_util.hpp create mode 100644 include/osmium/io/detail/string_util.hpp create mode 100644 include/osmium/io/o5m_input.hpp create mode 100644 include/osmium/io/writer_options.hpp delete mode 100644 include/osmium/util/data_file.hpp create mode 100644 include/protozero/config.hpp create mode 100644 include/protozero/version.hpp delete mode 100755 scripts/travis_install.sh delete mode 100755 scripts/travis_script.sh create mode 100644 test/t/buffer/test_buffer_basics.cpp create mode 100644 test/t/io/deleted_nodes.osh create mode 100644 test/t/io/deleted_nodes.osh.pbf create mode 100644 test/t/io/test_output_utils.cpp create mode 100644 test/t/io/test_reader_with_mock_decompression.cpp create mode 100644 test/t/io/test_reader_with_mock_parser.cpp create mode 100644 test/t/io/test_writer.cpp create mode 100644 test/t/io/test_writer_with_mock_compression.cpp create mode 100644 test/t/io/test_writer_with_mock_encoder.cpp delete mode 100644 test/t/util/test_data_file.cpp diff --git a/.travis.yml b/.travis.yml index 6ebdd7167..ac0d270e2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,46 +9,151 @@ language: cpp sudo: false matrix: - include: - - os: linux - compiler: clang - env: BUILD_TYPE=Dev - - os: linux - compiler: clang - env: BUILD_TYPE=Release - - os: linux - compiler: gcc - env: BUILD_TYPE=Dev - - os: linux - compiler: gcc - env: BUILD_TYPE=Release - - os: osx - compiler: clang - env: BUILD_TYPE=Dev - - os: osx - compiler: clang - env: BUILD_TYPE=Release + include: + + # 1/ Linux Clang Builds + - os: linux + compiler: clang + addons: + apt: + sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['clang-3.5', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='clang++-3.5' BUILD_TYPE='Release' + + - os: linux + compiler: clang + addons: + apt: + sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['clang-3.5', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='clang++-3.5' BUILD_TYPE='Dev' + + + - os: linux + compiler: clang + addons: + apt: + sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['clang-3.6', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='clang++-3.6' BUILD_TYPE='Release' + + - os: linux + compiler: clang + addons: + apt: + sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['clang-3.6', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='clang++-3.6' BUILD_TYPE='Dev' + + + - os: linux + compiler: clang + addons: + apt: + sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['clang-3.7', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='clang++-3.7' BUILD_TYPE='Release' + + - os: linux + compiler: clang + addons: + apt: + sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['clang-3.7', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='clang++-3.7' BUILD_TYPE='Dev' + + + # 2/ Linux GCC Builds + - os: linux + compiler: gcc + addons: + apt: + sources: ['ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['g++-4.8', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='g++-4.8' COMPILER_FLAGS='-Wno-return-type' BUILD_TYPE='Release' + + - os: linux + compiler: gcc + addons: + apt: + sources: ['ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['g++-4.8', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='g++-4.8' COMPILER_FLAGS='-Wno-return-type' BUILD_TYPE='Dev' + + + - os: linux + compiler: gcc + addons: + apt: + sources: ['ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['g++-4.9', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='g++-4.9' BUILD_TYPE='Release' + + - os: linux + compiler: gcc + addons: + apt: + sources: ['ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['g++-4.9', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='g++-4.9' BUILD_TYPE='Dev' + + + - os: linux + compiler: gcc + addons: + apt: + sources: ['ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['g++-5', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='g++-5' BUILD_TYPE='Release' + + - os: linux + compiler: gcc + addons: + apt: + sources: ['ubuntu-toolchain-r-test', 'boost-latest'] + packages: ['g++-5', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] + env: COMPILER='g++-5' BUILD_TYPE='Dev' + + + # 3/ OSX Clang Builds + - os: osx + osx_image: xcode6.4 + compiler: clang + env: COMPILER='clang++' BUILD_TYPE='Dev' + + - os: osx + osx_image: xcode6.4 + compiler: clang + env: COMPILER='clang++' BUILD_TYPE='Release' + + + - os: osx + osx_image: xcode7 + compiler: clang + env: COMPILER='clang++' BUILD_TYPE='Dev' + + - os: osx + osx_image: xcode7 + compiler: clang + env: COMPILER='clang++' BUILD_TYPE='Release' -# http://docs.travis-ci.com/user/apt/ -addons: - apt: - sources: - - boost-latest - - ubuntu-toolchain-r-test - packages: - - g++-4.8 - - gcc-4.8 - - libboost1.55-dev - - libboost-program-options1.55-dev - - libgdal-dev - - libgeos++-dev - - libproj-dev - - libsparsehash-dev - - spatialite-bin install: - - scripts/travis_install.sh + - DEPS_DIR="${TRAVIS_BUILD_DIR}/deps" + - mkdir -p ${DEPS_DIR} && cd ${DEPS_DIR} + - git clone --quiet --depth 1 https://github.com/osmcode/osm-testdata.git + - | + if [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then + brew remove gdal + brew install cmake boost google-sparsehash gdal + fi + +before_script: + - cd ${TRAVIS_BUILD_DIR} + - mkdir build && cd build + - CXX=${COMPILER} CXXFLAGS=${COMPILER_FLAGS} cmake -LA .. -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DOSM_TESTDATA="${TRAVIS_BUILD_DIR}/deps/osm-testdata" script: - - scripts/travis_script.sh + - make VERBOSE=1 + - ctest --output-on-failure diff --git a/CHANGELOG.md b/CHANGELOG.md index 22eb06aac..e9377b656 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,132 @@ This project adheres to [Semantic Versioning](http://semver.org/). ### Fixed + +## [2.5.4] - 2015-12-03 + +### Changed + +- Included gdalcpp.hpp header was updated to version 1.1.1. +- Included protozero library was updated to version 1.2.3. +- Workarounds for missing constexpr support in Visual Studio removed. All + constexpr features we need are supported now. +- Some code cleanup after running clang-tidy on the code. +- Re-added `Buffer::value_type` typedef. Turns out it is needed when using + `std::back_inserter` on the Buffer. + +### Fixed + +- Bugs with Timestamp code on 32 bit platforms. This necessitated + some changes in Timestamp which might lead to changes in user + code. +- Bug in segment intersection code (which appeared on i686 platform). + + +## [2.5.3] - 2015-11-17 + +### Added + +- `osmium::make_diff_iterator()` helper function. + +### Changed + +- Deprecated `osmium::Buffer::set_full_callback()`. +- Removed DataFile class which was never used anywhere. +- Removed unused and obscure `Buffer::value_type` typedef. + +### Fixed + +- Possible overrun in Buffer when using the full-callback. +- Incorrect swapping of Buffer. + + +## [2.5.2] - 2015-11-06 + +# Fixed + +- Writing data through an OutputIterator was extremly slow due to + lock contention. + + +## [2.5.1] - 2015-11-05 + +### Added + +- Header `osmium/fwd.hpp` with forward declarations of the most commonly + used Osmium classes. + +### Changed + +- Moved `osmium/io/overwrite.hpp` to `osmium/io/writer_options.hpp` + If you still include the old file, you'll get a warning. + + +## [2.5.0] - 2015-11-04 + +### Added + +- Helper functions to make input iterator ranges and output iterators. +- Add support for reading o5m and o5c files. +- Option for osmium::io::Writer to fsync file after writing. +- Lots of internal asserts() and other robustness checks. + +### Changed + +- Updated included protozero library to version 1.2.0. +- Complete overhaul of the I/O system making it much more robust against + wrong data and failures during I/O operations. +- Speed up PBF writing by running parts of it in parallel. +- OutputIterator doesn't hold an internal buffer any more, but it uses + one in Writer. Calling flush() on the OutputIterator isn't needed any + more. +- Reader now throws when trying to read after eof or an error. +- I/O functions that used to throw std::runtime_error now throw + osmium::io_error or derived. +- Optional parameters on osmium::io::Writer now work in any order. + +### Fixed + +- PBF reader now decodes locations of invisible nodes properly. +- Invalid Delta encode iterator dereference. +- Lots of includes fixed to include (only) what's used. +- Dangling reference in area assembly code. + + +## [2.4.1] - 2015-08-29 + +### Fixed + +- CRC calculation of tags and changesets. + + +## [2.4.0] - 2015-08-29 + +### Added + +- Checks that user names, member roles and tag keys and values are not longer + than 256 * 4 bytes. That is the maximum length 256 Unicode characters + can have in UTF-8 encoding. +- Support for GDAL 2. GDAL 1 still works. + +### Changed + +- Improved CMake build scripts. +- Updated internal version of Protozero to 1.1.0. +- Removed `toogr*` examples. They are in their own repository now. + See https://github.com/osmcode/osm-gis-export. +- Files about to be memory-mapped (for instance index files) are now set + to binary mode on Windows so the application doesn't have to do this. + +### Fixed + +- Hanging program when trying to open file with an unknown file format. +- Building problems with old boost versions. +- Initialization errors in PBF writer. +- Bug in byte swap code. +- Output on Windows now always uses binary mode, even when writing to + stdout, so OSM xml and opl files always use LF line endings. + + ## [2.3.0] - 2015-08-18 ### Added @@ -108,8 +234,15 @@ This project adheres to [Semantic Versioning](http://semver.org/). Doxygen (up to version 1.8.8). This version contains a workaround to fix this. -[unreleased]: https://github.com/osmcode/libosmium/compare/v2.3.0...HEAD -[2.3.0]: https://github.com/osmcode/libosmium/compare/v2.3.0...v2.3.0 +[unreleased]: https://github.com/osmcode/libosmium/compare/v2.5.4...HEAD +[2.5.4]: https://github.com/osmcode/libosmium/compare/v2.5.3...v2.5.4 +[2.5.3]: https://github.com/osmcode/libosmium/compare/v2.5.2...v2.5.3 +[2.5.2]: https://github.com/osmcode/libosmium/compare/v2.5.1...v2.5.2 +[2.5.1]: https://github.com/osmcode/libosmium/compare/v2.5.0...v2.5.1 +[2.5.0]: https://github.com/osmcode/libosmium/compare/v2.4.1...v2.5.0 +[2.4.1]: https://github.com/osmcode/libosmium/compare/v2.4.0...v2.4.1 +[2.4.0]: https://github.com/osmcode/libosmium/compare/v2.3.0...v2.4.0 +[2.3.0]: https://github.com/osmcode/libosmium/compare/v2.2.0...v2.3.0 [2.2.0]: https://github.com/osmcode/libosmium/compare/v2.1.0...v2.2.0 [2.1.0]: https://github.com/osmcode/libosmium/compare/v2.0.0...v2.1.0 diff --git a/CMakeLists.txt b/CMakeLists.txt index fba967a4e..0764915ea 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,8 +9,6 @@ cmake_minimum_required(VERSION 2.8 FATAL_ERROR) list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - #----------------------------------------------------------------------------- # @@ -26,13 +24,13 @@ set(CMAKE_CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo;MinSizeRel;Dev;Cover project(libosmium) set(LIBOSMIUM_VERSION_MAJOR 2) -set(LIBOSMIUM_VERSION_MINOR 3) -set(LIBOSMIUM_VERSION_PATCH 0) +set(LIBOSMIUM_VERSION_MINOR 5) +set(LIBOSMIUM_VERSION_PATCH 4) set(LIBOSMIUM_VERSION - "${LIBOSMIUM_VERSION_MAJOR}.${LIBOSMIUM_VERSION_MINOR}.${LIBOSMIUM_VERSION_PATCH}" - CACHE STRING - "Libosmium version") + "${LIBOSMIUM_VERSION_MAJOR}.${LIBOSMIUM_VERSION_MINOR}.${LIBOSMIUM_VERSION_PATCH}") + +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) #----------------------------------------------------------------------------- @@ -56,6 +54,10 @@ option(BUILD_HEADERS "compile every header file on its own" ${dev_build}) option(BUILD_BENCHMARKS "compile benchmark programs" ${dev_build}) option(BUILD_DATA_TESTS "compile data tests, please run them with ctest" ${dev_build}) +option(INSTALL_GDALCPP "also install gdalcpp headers" OFF) +option(INSTALL_PROTOZERO "also install protozero headers" OFF) +option(INSTALL_UTFCPP "also install utfcpp headers" OFF) + #----------------------------------------------------------------------------- # @@ -118,29 +120,39 @@ find_package(Boost 1.38) mark_as_advanced(CLEAR BOOST_ROOT) if(Boost_FOUND) - include_directories(${Boost_INCLUDE_DIRS}) + include_directories(SYSTEM ${Boost_INCLUDE_DIRS}) else() set(BOOST_ROOT "NOT FOUND: please choose" CACHE PATH "") message(FATAL_ERROR "PLEASE, specify the directory where the Boost library is installed in BOOST_ROOT") endif() -set(OSMIUM_INCLUDE_DIR include) +# set OSMIUM_INCLUDE_DIR so FindOsmium will not set anything different +set(OSMIUM_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include") + +include_directories(${OSMIUM_INCLUDE_DIR}) + find_package(Osmium COMPONENTS io gdal geos proj sparsehash) -include_directories(${OSMIUM_INCLUDE_DIRS}) + +# The find_package put the directory where it found the libosmium includes +# into OSMIUM_INCLUDE_DIRS. We remove it again, because we want to make +# sure to use our own include directory already set up above. +list(FIND OSMIUM_INCLUDE_DIRS "${OSMIUM_INCLUDE_DIR}" _own_index) +list(REMOVE_AT OSMIUM_INCLUDE_DIRS ${_own_index}) +set(_own_index) + +include_directories(SYSTEM ${OSMIUM_INCLUDE_DIRS}) if(MSVC) find_path(GETOPT_INCLUDE_DIR getopt.h) find_library(GETOPT_LIBRARY NAMES wingetopt) if(GETOPT_INCLUDE_DIR AND GETOPT_LIBRARY) - include_directories(${GETOPT_INCLUDE_DIR}) + include_directories(SYSTEM ${GETOPT_INCLUDE_DIR}) list(APPEND OSMIUM_LIBRARIES ${GETOPT_LIBRARY}) else() set(GETOPT_MISSING 1) endif() endif() -include_directories(include) - #----------------------------------------------------------------------------- # @@ -205,6 +217,7 @@ if(CMAKE_BUILD_TYPE STREQUAL "Dev") add_definitions(-Werror) endif() add_definitions(${OSMIUM_WARNING_OPTIONS}) +# add_definitions(${OSMIUM_WARNING_OPTIONS} ${OSMIUM_DRACONIC_CLANG_OPTIONS} -Wno-documentation -Wno-format-nonliteral -Wno-deprecated -Wno-covered-switch-default -Wno-shadow) endif() # Force RelWithDebInfo build type if none was given @@ -256,19 +269,21 @@ find_program(CPPCHECK cppcheck) if(CPPCHECK) message(STATUS "Looking for cppcheck - found") set(CPPCHECK_OPTIONS - --enable=warning,style,performance,portability,information,missingInclude) + --enable=warning,style,performance,portability,information,missingInclude --force -Uassert) # cpp doesn't find system includes for some reason, suppress that report set(CPPCHECK_OPTIONS ${CPPCHECK_OPTIONS} --suppress=missingIncludeSystem) file(GLOB_RECURSE ALL_INCLUDES include/osmium/*.hpp) file(GLOB ALL_EXAMPLES examples/*.cpp) + file(GLOB ALL_BENCHMARKS benchmarks/*.cpp) file(GLOB ALL_UNIT_TESTS test/t/*/test_*.cpp) file(GLOB ALL_DATA_TESTS test/data-tests/*.cpp) if(Osmium_DEBUG) message(STATUS "Checking includes : ${ALL_INCLUDES}") message(STATUS "Checking example code : ${ALL_EXAMPLES}") + message(STATUS "Checking benchmarks : ${ALL_BENCHMARKS}") message(STATUS "Checking unit test code: ${ALL_UNIT_TESTS}") message(STATUS "Checking data test code: ${ALL_DATA_TESTS}") endif() @@ -276,6 +291,7 @@ if(CPPCHECK) set(CPPCHECK_FILES ${ALL_INCLUDES} ${ALL_EXAMPLES} + ${ALL_BENCHMARKS} ${ALL_UNIT_TESTS} ${ALL_DATA_TESTS}) @@ -288,7 +304,7 @@ if(CPPCHECK) else() message(STATUS "Looking for cppcheck - not found") message(STATUS " Build target 'cppcheck' will not be available.") -endif(CPPCHECK) +endif() #----------------------------------------------------------------------------- @@ -345,11 +361,115 @@ if(BUILD_HEADERS) endforeach() endif() + +#----------------------------------------------------------------------------- +# +# Optional "clang-tidy" target +# +#----------------------------------------------------------------------------- +message(STATUS "Looking for clang-tidy") +find_program(CLANG_TIDY NAMES clang-tidy clang-tidy-3.9 clang-tidy-3.8 clang-tidy-3.7 clang-tidy-3.6 clang-tidy-3.5) + +if(CLANG_TIDY) + message(STATUS "Looking for clang-tidy - found") + + if(BUILD_EXAMPLES) + file(GLOB CT_ALL_EXAMPLES examples/*.cpp) + endif() + + if(BUILD_TESTING) + file(GLOB CT_ALL_UNIT_TESTS test/t/*/test_*.cpp) + endif() + + if(BUILD_HEADERS) + file(GLOB_RECURSE CT_ALL_INCLUDES ${CMAKE_BINARY_DIR}/header_check/osmium__*.cpp) + endif() + + if(BUILD_BENCHMARKS) + file(GLOB CT_ALL_BENCHMARKS benchmarks/*.cpp) + endif() + + if(BUILD_DATA_TESTS) + file(GLOB CT_ALL_DATA_TESTS test/data-tests/*.cpp) + endif() + + if(Osmium_DEBUG) + message(STATUS "Checking example code : ${CT_ALL_EXAMPLES}") + message(STATUS "Checking unit test code: ${CT_ALL_UNIT_TESTS}") + message(STATUS "Checking includes : ${CT_ALL_INCLUDES}") + message(STATUS "Checking benchmarks : ${CT_ALL_BENCHMARKS}") + message(STATUS "Checking data test code: ${CT_ALL_DATA_TESTS}") + endif() + + set(CT_CHECK_FILES + ${CT_ALL_EXAMPLES} + ${CT_ALL_UNIT_TESTS} + ${CT_ALL_INCLUDES} + ${CT_ALL_BENCHMARKS} + ${CT_ALL_DATA_TESTS}) + + # For a list of check options, see: + # http://clang.llvm.org/extra/clang-tidy/checks/list.html + + list(APPEND CT_CHECKS "cert-*" + "-cert-err60-cpp") # even the std lib doesn't do this + + # disabled, because it is slow +# list(APPEND CT_CHECKS "clang-analyzer-*") + + list(APPEND CT_CHECKS "google-*" + "-google-explicit-constructor" + "-google-readability-casting" + "-google-readability-function") + + list(APPEND CT_CHECKS "llvm-*" + "-llvm-include-order") + + list(APPEND CT_CHECKS "misc-*" + "-misc-argument-comment") + + list(APPEND CT_CHECKS "modernize-*") + + list(APPEND CT_CHECKS "readability-*" + "-readability-identifier-naming" + "-readability-named-parameter") + + string(REPLACE ";" "," ALL_CHECKS "${CT_CHECKS}") + + add_custom_target(clang-tidy + ${CLANG_TIDY} + -p ${CMAKE_BINARY_DIR} + -header-filter='include/osmium/.*' + -checks="${ALL_CHECKS}" + ${CT_CHECK_FILES} + ) +else() + message(STATUS "Looking for clang-tidy - not found") + message(STATUS " Build target 'clang-tidy' will not be available.") +endif() + +#----------------------------------------------------------------------------- +# +# Installation +# +# External libraries are only installed if the options are set in case they +# are installed from somewhere else. +# +#----------------------------------------------------------------------------- install(DIRECTORY include/osmium DESTINATION include) -# We only have a copy of this file so we can use older boost versions which -# don't have it. We probably don't want to install it. -#install(FILES include/boost_unicode_iterator.hpp DESTINATION include) +if(INSTALL_GDALCPP) + install(include/gdalcpp.hpp DESTINATION include) +endif() + +if(INSTALL_PROTOZERO) + install(DIRECTORY include/protozero DESTINATION include) +endif() + +if(INSTALL_UTFCPP) + install(include/utf8.hpp DESTINATION include) + install(DIRECTORY include/utf8 DESTINATION include) +endif() #----------------------------------------------------------------------------- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 323c84744..1064b94de 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,22 +36,21 @@ different. * Class names begin with uppercase chars and use CamelCase. Smaller helper classes are usually defined as struct and have lowercase names. * Macros (and only macros) are all uppercase. Use macros sparingly, usually - a constexpr is better. + a simple (maybe constexpr) inline function is better. Undef macros after use + if possible. +* Macros should only be used for controlling which parts of the code should be + included when compiling or to avoid major code repetitions. * Variables, attributes, and function names are lowercase with `underscores_between_words`. * Class attribute names start with `m_` (member). -* Template parameters are single uppercase letters or start with uppercase `T` - and use CamelCase. -* Typedefs have `names_like_this_type` which end in `_type`. -* Macros should only be used for controlling which parts of the code should be - included when compiling. * Use `descriptive_variable_names`, exceptions are well-established conventions like `i` for a loop variable. Iterators are usually called `it`. * Declare variables where they are first used (C++ style), not at the beginning of a function (old C style). * Names from external namespaces (even `std`) are always mentioned explicitly. Do not use `using` (except for `std::swap`). This way we can't even by - accident pollute the namespace of the code including Osmium. + accident pollute the namespace of the code using Osmium. +* Always use the standard swap idiom: `using std::swap; swap(foo, bar);`. * `#include` directives appear in three "blocks" after the copyright notice. The blocks are separated by blank lines. First block contains `#include`s for standard C/C++ includes, second block for any external libs used, third @@ -64,8 +63,20 @@ different. * All files have suffix `.hpp`. * Closing } of all classes and namespaces should have a trailing comment with the name of the class/namespace. -* All constructors with one or more arguments should be declared "explicit" - unless there is a reason for them not to be. Document that reason. +* All constructors with one (or more arguments if they have a default) should + be declared "explicit" unless there is a reason for them not to be. Document + that reason. +* If a class has any of the special methods (copy/move constructor/assigment, + destructor) it should have all of them, possibly marking them as default or + deleted. +* Typedefs have `names_like_this_type` which end in `_type`. Typedefs should + use the new `using foo_type = bar` syntax instead of the old + `typedef bar foo_type`. +* Template parameters are single uppercase letters or start with uppercase `T` + and use CamelCase. +* Always use `typename` in templates, not `class`: `template `. +* The ellipsis in variadic template never has a space to the left of it and + always has a space to the right: `template ` etc. Keep to the indentation and other styles used in the code. Use `make indent` in the toplevel directory to fix indentation and styling. It calls `astyle` @@ -81,15 +92,15 @@ about which compilers support which feature and what operating system versions or distributions have which versions of these compilers installed. GCC 4.6 - too old, not supported (Ubuntu 12.04 LTS) -GCC 4.7.2 - can probably not be supported (Debian wheezy/stable) -GCC 4.7.3 - works -GCC 4.8 - works -clang 3.0 - too old, not supported (Debian wheezy/stable, Ubuntu 12.04 LTS) -clang 3.2 - works +GCC 4.7.2 - can probably not be supported (Debian wheezy) +GCC 4.7.3 - probably works +GCC 4.8 - works and is supported from here on +clang 3.0 - too old, not supported (Debian wheezy, Ubuntu 12.04 LTS) +clang 3.2 - probably works +clang 3.5 - works and is supported from here on -C++11 features you should not use: -* Inherited Constructors (works only in GCC 4.8+ and clang 3.3+, not in Visual - Studio) +Use `include/osmium/util/compatibility.hpp` if there are compatibility problems +between compilers due to different C++11 support. ## Checking your code diff --git a/README.md b/README.md index 9676d80b7..68fc2f61b 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ http://osmcode.org/libosmium A fast and flexible C++ library for working with OpenStreetMap data. -[![Build Status](https://secure.travis-ci.org/osmcode/libosmium.png)](http://travis-ci.org/osmcode/libosmium) +[![Build Status](https://secure.travis-ci.org/osmcode/libosmium.png)](https://travis-ci.org/osmcode/libosmium) [![Build status](https://ci.appveyor.com/api/projects/status/mkbg6e6stdgq7c1b?svg=true)](https://ci.appveyor.com/project/Mapbox/libosmium) Libosmium is developed on Linux, but also works on OSX and Windows (with some @@ -27,9 +27,15 @@ you need for your programs. For details see the [list of dependencies](https://github.com/osmcode/libosmium/wiki/Libosmium-dependencies). -The [protozero](https://github.com/mapbox/protozero) and -[utf8-cpp](http://utfcpp.sourceforge.net/) header-only libraries are included -in the libosmium repository. +The following external (header-only) libraries are included in the libosmium +repository: +* [gdalcpp](https://github.com/joto/gdalcpp) +* [protozero](https://github.com/mapbox/protozero) +* [utfcpp](http://utfcpp.sourceforge.net/) + +If you want (some of) those libraries to be installed along with libosmium +itself when calling `make install`, you have to use the CMake options +`INSTALL_GDALCPP`, `INSTALL_PROTOZERO`, and/or `INSTALL_UTFCPP`. ## Directories diff --git a/appveyor.yml b/appveyor.yml index a05c396cc..8244d98e7 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,16 +9,10 @@ environment: - config: Dev - config: RelWithDebInfo -# branches to build -branches: - # whitelist - only: - - master - shallow_clone: true # Operating system (build VM template) -os: Visual Studio 2014 CTP4 +os: Visual Studio 2015 # scripts that are called at very beginning, before repo cloning init: @@ -46,6 +40,8 @@ install: - set PATH=%LODEPSDIR%\expat\lib;%PATH% #libtiff.dll - set PATH=%LODEPSDIR%\libtiff\lib;%PATH% + #jpeg.dll + - set PATH=%LODEPSDIR%\jpeg\lib;%PATH% #zlibwapi.dll - set PATH=%LODEPSDIR%\zlib\lib;%PATH% #convert backslashes in bzip2 path to forward slashes @@ -71,27 +67,16 @@ build_script: # This will produce lots of LNK4099 warnings which can be ignored. # Unfortunately they can't be disabled, see # http://stackoverflow.com/questions/661606/visual-c-how-to-disable-specific-linker-warnings - - cmake .. -LA -G "Visual Studio 14 Win64" + - cmake -LA -G "Visual Studio 14 Win64" -DOsmium_DEBUG=TRUE -DCMAKE_BUILD_TYPE=%config% -DBUILD_HEADERS=OFF -DBOOST_ROOT=%LODEPSDIR%\boost - -DBoost_PROGRAM_OPTIONS_LIBRARY=%LODEPSDIR%\boost\lib\libboost_program_options-vc140-mt-1_57.lib + -DBoost_PROGRAM_OPTIONS_LIBRARY=%LODEPSDIR%\boost\lib\libboost_program_options-vc140-mt-1_58.lib -DZLIB_LIBRARY=%LODEPSDIR%\zlib\lib\zlibwapi.lib - -DZLIB_INCLUDE_DIR=%LODEPSDIR%\zlib\include - -DEXPAT_LIBRARY=%LODEPSDIR%\expat\lib\libexpat.lib - -DEXPAT_INCLUDE_DIR=%LODEPSDIR%\expat\include - -DBZIP2_LIBRARIES=%LIBBZIP2% - -DBZIP2_INCLUDE_DIR=%LODEPSDIR%\bzip2\include - -DGDAL_LIBRARY=%LODEPSDIR%\gdal\lib\gdal_i.lib - -DGDAL_INCLUDE_DIR=%LODEPSDIR%\gdal\include - -DGEOS_LIBRARY=%LODEPSDIR%\geos\lib\geos.lib - -DGEOS_INCLUDE_DIR=%LODEPSDIR%\geos\include - -DPROJ_LIBRARY=%LODEPSDIR%\proj\lib\proj.lib - -DPROJ_INCLUDE_DIR=%LODEPSDIR%\proj\include - -DSPARSEHASH_INCLUDE_DIR=%LODEPSDIR%\sparsehash\include - -DGETOPT_LIBRARY=%LODEPSDIR%\wingetopt\lib\wingetopt.lib - -DGETOPT_INCLUDE_DIR=%LODEPSDIR%\wingetopt\include + -DBZIP2_LIBRARY_RELEASE=%LIBBZIP2% + -DCMAKE_PREFIX_PATH=%LODEPSDIR%\zlib;%LODEPSDIR%\expat;%LODEPSDIR%\bzip2;%LODEPSDIR%\geos;%LODEPSDIR%\gdal;%LODEPSDIR%\proj;%LODEPSDIR%\sparsehash;%LODEPSDIR%\wingetopt + .. - msbuild libosmium.sln /p:Configuration=%config% /toolsversion:14.0 /p:Platform=x64 /p:PlatformToolset=v140 #- cmake .. -LA -G "NMake Makefiles" # -DOsmium_DEBUG=TRUE diff --git a/cmake/FindOsmium.cmake b/cmake/FindOsmium.cmake index bb140718b..fba8ffb92 100644 --- a/cmake/FindOsmium.cmake +++ b/cmake/FindOsmium.cmake @@ -19,7 +19,7 @@ # Then add the following in your CMakeLists.txt: # # find_package(Osmium REQUIRED COMPONENTS ) -# include_directories(${OSMIUM_INCLUDE_DIRS}) +# include_directories(SYSTEM ${OSMIUM_INCLUDE_DIRS}) # # For the substitute a space separated list of one or more of the # following components: @@ -56,31 +56,13 @@ find_path(OSMIUM_INCLUDE_DIR osmium/osm.hpp PATH_SUFFIXES include PATHS ../libosmium - ../../libosmium - libosmium ~/Library/Frameworks /Library/Frameworks - /usr/local - /usr/ /opt/local # DarwinPorts /opt ) -# Handle the QUIETLY and REQUIRED arguments and set OSMIUM_FOUND to TRUE if -# all listed variables are TRUE. -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(OSMIUM REQUIRED_VARS OSMIUM_INCLUDE_DIR) - -# Copy the results to the output variables. -if(OSMIUM_FOUND) - set(OSMIUM_INCLUDE_DIRS ${OSMIUM_INCLUDE_DIR}) -else() - set(OSMIUM_INCLUDE_DIRS "") -endif() - -if(Osmium_FIND_REQUIRED AND NOT OSMIUM_FOUND) - message(FATAL_ERROR "Can not find libosmium headers, please install them or configure the paths") -endif() +set(OSMIUM_INCLUDE_DIRS "${OSMIUM_INCLUDE_DIR}") #---------------------------------------------------------------------- # @@ -113,6 +95,7 @@ if(Osmium_USE_PBF) find_package(ZLIB) find_package(Threads) + list(APPEND OSMIUM_EXTRA_FIND_VARS ZLIB_FOUND Threads_FOUND) if(ZLIB_FOUND AND Threads_FOUND) list(APPEND OSMIUM_PBF_LIBRARIES ${ZLIB_LIBRARIES} @@ -125,7 +108,6 @@ if(Osmium_USE_PBF) ${ZLIB_INCLUDE_DIR} ) else() - set(_missing_libraries 1) message(WARNING "Osmium: Can not find some libraries for PBF input/output, please install them or configure the paths.") endif() endif() @@ -138,6 +120,7 @@ if(Osmium_USE_XML) find_package(ZLIB) find_package(Threads) + list(APPEND OSMIUM_EXTRA_FIND_VARS EXPAT_FOUND BZIP2_FOUND ZLIB_FOUND Threads_FOUND) if(EXPAT_FOUND AND BZIP2_FOUND AND ZLIB_FOUND AND Threads_FOUND) list(APPEND OSMIUM_XML_LIBRARIES ${EXPAT_LIBRARIES} @@ -151,7 +134,6 @@ if(Osmium_USE_XML) ${ZLIB_INCLUDE_DIR} ) else() - set(_missing_libraries 1) message(WARNING "Osmium: Can not find some libraries for XML input/output, please install them or configure the paths.") endif() endif() @@ -172,12 +154,12 @@ if(Osmium_USE_GEOS) find_path(GEOS_INCLUDE_DIR geos/geom.h) find_library(GEOS_LIBRARY NAMES geos) + list(APPEND OSMIUM_EXTRA_FIND_VARS GEOS_INCLUDE_DIR GEOS_LIBRARY) if(GEOS_INCLUDE_DIR AND GEOS_LIBRARY) SET(GEOS_FOUND 1) list(APPEND OSMIUM_LIBRARIES ${GEOS_LIBRARY}) list(APPEND OSMIUM_INCLUDE_DIRS ${GEOS_INCLUDE_DIR}) else() - set(_missing_libraries 1) message(WARNING "Osmium: GEOS library is required but not found, please install it or configure the paths.") endif() endif() @@ -187,11 +169,11 @@ endif() if(Osmium_USE_GDAL) find_package(GDAL) + list(APPEND OSMIUM_EXTRA_FIND_VARS GDAL_FOUND) if(GDAL_FOUND) list(APPEND OSMIUM_LIBRARIES ${GDAL_LIBRARIES}) list(APPEND OSMIUM_INCLUDE_DIRS ${GDAL_INCLUDE_DIRS}) else() - set(_missing_libraries 1) message(WARNING "Osmium: GDAL library is required but not found, please install it or configure the paths.") endif() endif() @@ -202,12 +184,12 @@ if(Osmium_USE_PROJ) find_path(PROJ_INCLUDE_DIR proj_api.h) find_library(PROJ_LIBRARY NAMES proj) + list(APPEND OSMIUM_EXTRA_FIND_VARS PROJ_INCLUDE_DIR PROJ_LIBRARY) if(PROJ_INCLUDE_DIR AND PROJ_LIBRARY) set(PROJ_FOUND 1) list(APPEND OSMIUM_LIBRARIES ${PROJ_LIBRARY}) list(APPEND OSMIUM_INCLUDE_DIRS ${PROJ_INCLUDE_DIR}) else() - set(_missing_libraries 1) message(WARNING "Osmium: PROJ.4 library is required but not found, please install it or configure the paths.") endif() endif() @@ -217,21 +199,19 @@ endif() if(Osmium_USE_SPARSEHASH) find_path(SPARSEHASH_INCLUDE_DIR google/sparsetable) + list(APPEND OSMIUM_EXTRA_FIND_VARS SPARSEHASH_INCLUDE_DIR) if(SPARSEHASH_INCLUDE_DIR) # Find size of sparsetable::size_type. This does not work on older # CMake versions because they can do this check only in C, not in C++. - include(CheckTypeSize) - set(CMAKE_REQUIRED_INCLUDES ${SPARSEHASH_INCLUDE_DIR}) - set(CMAKE_EXTRA_INCLUDE_FILES "google/sparsetable") - check_type_size("google::sparsetable::size_type" SPARSETABLE_SIZE_TYPE LANGUAGE CXX) - set(CMAKE_EXTRA_INCLUDE_FILES) - set(CMAKE_REQUIRED_INCLUDES) - - # Falling back to checking size_t if google::sparsetable::size_type - # could not be checked. - if(SPARSETABLE_SIZE_TYPE STREQUAL "") - check_type_size("void*" VOID_PTR_SIZE) - set(SPARSETABLE_SIZE_TYPE ${VOID_PTR_SIZE}) + if (NOT CMAKE_VERSION VERSION_LESS 3.0) + include(CheckTypeSize) + set(CMAKE_REQUIRED_INCLUDES ${SPARSEHASH_INCLUDE_DIR}) + set(CMAKE_EXTRA_INCLUDE_FILES "google/sparsetable") + check_type_size("google::sparsetable::size_type" SPARSETABLE_SIZE_TYPE LANGUAGE CXX) + set(CMAKE_EXTRA_INCLUDE_FILES) + set(CMAKE_REQUIRED_INCLUDES) + else() + set(SPARSETABLE_SIZE_TYPE ${CMAKE_SIZEOF_VOID_P}) endif() # Sparsetable::size_type must be at least 8 bytes (64bit), otherwise @@ -244,7 +224,6 @@ if(Osmium_USE_SPARSEHASH) message(WARNING "Osmium: Disabled Google SparseHash library on 32bit system (size_type=${SPARSETABLE_SIZE_TYPE}).") endif() else() - set(_missing_libraries 1) message(WARNING "Osmium: Google SparseHash library is required but not found, please install it or configure the paths.") endif() endif() @@ -274,9 +253,14 @@ endif() # Check that all required libraries are available # #---------------------------------------------------------------------- -if(Osmium_FIND_REQUIRED AND _missing_libraries) - message(FATAL_ERROR "Required library or libraries missing. Aborting.") +if (OSMIUM_EXTRA_FIND_VARS) + list(REMOVE_DUPLICATES OSMIUM_EXTRA_FIND_VARS) endif() +# Handle the QUIETLY and REQUIRED arguments and set OSMIUM_FOUND to TRUE if +# all listed variables are TRUE. +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Osmium REQUIRED_VARS OSMIUM_INCLUDE_DIR ${OSMIUM_EXTRA_FIND_VARS}) +unset(OSMIUM_EXTRA_FIND_VARS) #---------------------------------------------------------------------- # diff --git a/cmake/iwyu.sh b/cmake/iwyu.sh index f7d8a15e8..ceea106c3 100755 --- a/cmake/iwyu.sh +++ b/cmake/iwyu.sh @@ -16,7 +16,7 @@ echo "INCLUDE WHAT YOU USE REPORT:" >$log allok=yes -for file in `find include/osmium -name \*.hpp`; do +for file in `find include/osmium -name \*.hpp | sort`; do mkdir -p `dirname build/check_reports/$file` ifile="build/check_reports/${file%.hpp}.iwyu" $cmdline $file >$ifile 2>&1 diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index c9f59603d..a04a843f2 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -14,12 +14,10 @@ set(EXAMPLES count create_node_cache debug + filter_discussions index read serdump - toogr - toogr2 - toogr2_exp use_node_cache CACHE STRING "Example programs" ) @@ -30,7 +28,7 @@ set(EXAMPLES # Examples depending on wingetopt # #----------------------------------------------------------------------------- -set(GETOPT_EXAMPLES area_test convert serdump toogr toogr2 toogr2_exp) +set(GETOPT_EXAMPLES area_test convert serdump) if(NOT GETOPT_MISSING) foreach(example ${GETOPT_EXAMPLES}) list(APPEND EXAMPLE_LIBS_${example} ${GETOPT_LIBRARY}) @@ -74,27 +72,6 @@ else() endif() -#----------------------------------------------------------------------------- -# -# Examples depending on GDAL/PROJ.4/SparseHash -# -#----------------------------------------------------------------------------- -set(OGR_EXAMPLES toogr toogr2 toogr2_exp) - -if(GDAL_FOUND AND PROJ_FOUND AND SPARSEHASH_FOUND) - foreach(example ${OGR_EXAMPLES}) - list(APPEND EXAMPLE_LIBS_${example} ${GDAL_LIBRARIES}) - list(APPEND EXAMPLE_LIBS_${example} ${PROJ_LIBRARIES}) - endforeach() -else() - message(STATUS "Configuring examples - Skipping examples because GDAL and/or Proj.4 and/or SparseHash not found:") - foreach(example ${OGR_EXAMPLES}) - message(STATUS " - osmium_${example}") - list(REMOVE_ITEM EXAMPLES ${example}) - endforeach() -endif() - - #----------------------------------------------------------------------------- # # Configure examples diff --git a/examples/osmium_filter_discussions.cpp b/examples/osmium_filter_discussions.cpp new file mode 100644 index 000000000..bba25b752 --- /dev/null +++ b/examples/osmium_filter_discussions.cpp @@ -0,0 +1,72 @@ +/* + + Read OSM changesets with discussions from a changeset dump like the one + you get from http://planet.osm.org/planet/discussions-latest.osm.bz2 + and write out only those changesets which have discussions (ie comments). + + The code in this example file is released into the Public Domain. + +*/ + +#include // for std::copy_if +#include // for std::cout, std::cerr + +// we want to read OSM files in XML format +// (other formats don't support full changesets, so only XML is needed here) +#include +#include + +// we want to write OSM files in XML format +#include +#include + +// we want to support any compressioon (.gz2 and .bz2) +#include + +int main(int argc, char* argv[]) { + if (argc != 3) { + std::cout << "Usage: " << argv[0] << " INFILE OUTFILE\n"; + exit(1); + } + + // The input file, deduce file format from file suffix + osmium::io::File infile(argv[1]); + + // The output file, force class XML OSM file format + osmium::io::File outfile(argv[2], "osm"); + + // Initialize Reader for the input file. + // Read only changesets (will ignore nodes, ways, and + // relations if there are any). + osmium::io::Reader reader(infile, osmium::osm_entity_bits::changeset); + + // Get the header from the input file + osmium::io::Header header = reader.header(); + + // Initialize writer for the output file. Use the header from the input + // file for the output file. This will copy over some header information. + // The last parameter will tell the writer that it is allowed to overwrite + // an existing file. Without it, it will refuse to do so. + osmium::io::Writer writer(outfile, header, osmium::io::overwrite::allow); + + // Create range of input iterators that will iterator over all changesets + // delivered from input file through the "reader". + auto input_range = osmium::io::make_input_iterator_range(reader); + + // Create an output iterator writing through the "writer" object to the + // output file. + auto output_iterator = osmium::io::make_output_iterator(writer); + + // Copy all changesets from input to output that have at least one comment. + std::copy_if(input_range.begin(), input_range.end(), output_iterator, [](const osmium::Changeset& changeset) { + return changeset.num_comments() > 0; + }); + + // Explicitly close the writer and reader. Will throw an exception if + // there is a problem. If you wait for the destructor to close the writer + // and reader, you will not notice the problem, because destructors must + // not throw. + writer.close(); + reader.close(); +} + diff --git a/examples/osmium_toogr.cpp b/examples/osmium_toogr.cpp deleted file mode 100644 index 7c5a965c5..000000000 --- a/examples/osmium_toogr.cpp +++ /dev/null @@ -1,244 +0,0 @@ -/* - - This is an example tool that converts OSM data to some output format - like Spatialite or Shapefiles using the OGR library. - - The code in this example file is released into the Public Domain. - -*/ - -#include -#include - -#include -#include -#include - -#include -#include -#include - -typedef osmium::index::map::Dummy index_neg_type; -typedef osmium::index::map::Map index_pos_type; - -typedef osmium::handler::NodeLocationsForWays location_handler_type; - -class MyOGRHandler : public osmium::handler::Handler { - - OGRDataSource* m_data_source; - OGRLayer* m_layer_point; - OGRLayer* m_layer_linestring; - - osmium::geom::OGRFactory<> m_factory; - -public: - - MyOGRHandler(const std::string& driver_name, const std::string& filename) { - - OGRRegisterAll(); - - OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str()); - if (!driver) { - std::cerr << driver_name << " driver not available.\n"; - exit(1); - } - - CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); - const char* options[] = { "SPATIALITE=TRUE", nullptr }; - m_data_source = driver->CreateDataSource(filename.c_str(), const_cast(options)); - if (!m_data_source) { - std::cerr << "Creation of output file failed.\n"; - exit(1); - } - - OGRSpatialReference sparef; - sparef.SetWellKnownGeogCS("WGS84"); - m_layer_point = m_data_source->CreateLayer("postboxes", &sparef, wkbPoint, nullptr); - if (!m_layer_point) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_point_field_id("id", OFTReal); - layer_point_field_id.SetWidth(10); - - if (m_layer_point->CreateField(&layer_point_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_point_field_operator("operator", OFTString); - layer_point_field_operator.SetWidth(30); - - if (m_layer_point->CreateField(&layer_point_field_operator) != OGRERR_NONE) { - std::cerr << "Creating operator field failed.\n"; - exit(1); - } - - /* Transactions might make things faster, then again they might not. - Feel free to experiment and benchmark and report back. */ - m_layer_point->StartTransaction(); - - m_layer_linestring = m_data_source->CreateLayer("roads", &sparef, wkbLineString, nullptr); - if (!m_layer_linestring) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_linestring_field_id("id", OFTReal); - layer_linestring_field_id.SetWidth(10); - - if (m_layer_linestring->CreateField(&layer_linestring_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_linestring_field_type("type", OFTString); - layer_linestring_field_type.SetWidth(30); - - if (m_layer_linestring->CreateField(&layer_linestring_field_type) != OGRERR_NONE) { - std::cerr << "Creating type field failed.\n"; - exit(1); - } - - m_layer_linestring->StartTransaction(); - } - - ~MyOGRHandler() { - m_layer_linestring->CommitTransaction(); - m_layer_point->CommitTransaction(); - OGRDataSource::DestroyDataSource(m_data_source); - OGRCleanupAll(); - } - - void node(const osmium::Node& node) { - const char* amenity = node.tags().get_value_by_key("amenity"); - if (amenity && !strcmp(amenity, "post_box")) { - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_point->GetLayerDefn()); - std::unique_ptr ogr_point = m_factory.create_point(node); - feature->SetGeometry(ogr_point.get()); - feature->SetField("id", static_cast(node.id())); - feature->SetField("operator", node.tags().get_value_by_key("operator")); - - if (m_layer_point->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); - } - } - - void way(const osmium::Way& way) { - const char* highway = way.tags().get_value_by_key("highway"); - if (highway) { - try { - std::unique_ptr ogr_linestring = m_factory.create_linestring(way); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_linestring->GetLayerDefn()); - feature->SetGeometry(ogr_linestring.get()); - feature->SetField("id", static_cast(way.id())); - feature->SetField("type", highway); - - if (m_layer_linestring->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); - } catch (osmium::geometry_error&) { - std::cerr << "Ignoring illegal geometry for way " << way.id() << ".\n"; - } - } - } - -}; - -/* ================================================== */ - -void print_help() { - std::cout << "osmium_toogr [OPTIONS] [INFILE [OUTFILE]]\n\n" \ - << "If INFILE is not given stdin is assumed.\n" \ - << "If OUTFILE is not given 'ogr_out' is used.\n" \ - << "\nOptions:\n" \ - << " -h, --help This help message\n" \ - << " -l, --location_store=TYPE Set location store\n" \ - << " -f, --format=FORMAT Output OGR format (Default: 'SQLite')\n" \ - << " -L See available location stores\n"; -} - -int main(int argc, char* argv[]) { - const auto& map_factory = osmium::index::MapFactory::instance(); - - static struct option long_options[] = { - {"help", no_argument, 0, 'h'}, - {"format", required_argument, 0, 'f'}, - {"location_store", required_argument, 0, 'l'}, - {"list_location_stores", no_argument, 0, 'L'}, - {0, 0, 0, 0} - }; - - std::string output_format { "SQLite" }; - std::string location_store { "sparse_mem_array" }; - - while (true) { - int c = getopt_long(argc, argv, "hf:l:L", long_options, 0); - if (c == -1) { - break; - } - - switch (c) { - case 'h': - print_help(); - exit(0); - case 'f': - output_format = optarg; - break; - case 'l': - location_store = optarg; - break; - case 'L': - std::cout << "Available map types:\n"; - for (const auto& map_type : map_factory.map_types()) { - std::cout << " " << map_type << "\n"; - } - exit(0); - default: - exit(1); - } - } - - std::string input_filename; - std::string output_filename("ogr_out"); - int remaining_args = argc - optind; - if (remaining_args > 2) { - std::cerr << "Usage: " << argv[0] << " [OPTIONS] [INFILE [OUTFILE]]" << std::endl; - exit(1); - } else if (remaining_args == 2) { - input_filename = argv[optind]; - output_filename = argv[optind+1]; - } else if (remaining_args == 1) { - input_filename = argv[optind]; - } else { - input_filename = "-"; - } - - osmium::io::Reader reader(input_filename); - - std::unique_ptr index_pos = map_factory.create_map(location_store); - index_neg_type index_neg; - location_handler_type location_handler(*index_pos, index_neg); - location_handler.ignore_errors(); - - MyOGRHandler ogr_handler(output_format, output_filename); - - osmium::apply(reader, location_handler, ogr_handler); - reader.close(); - - int locations_fd = open("locations.dump", O_WRONLY | O_CREAT, 0644); - if (locations_fd < 0) { - throw std::system_error(errno, std::system_category(), "Open failed"); - } - index_pos->dump_as_list(locations_fd); - close(locations_fd); -} - diff --git a/examples/osmium_toogr2.cpp b/examples/osmium_toogr2.cpp deleted file mode 100644 index e1b505688..000000000 --- a/examples/osmium_toogr2.cpp +++ /dev/null @@ -1,331 +0,0 @@ -/* - - This is an example tool that converts OSM data to some output format - like Spatialite or Shapefiles using the OGR library. - - This version does multipolygon handling (in contrast to the osmium_toogr - example which doesn't). - - The code in this example file is released into the Public Domain. - -*/ - -#include -#include - -// usually you only need one or two of these -#include -#include - -#include -#include -#include -#include - -#include -//#include -#include -#include -#include - -typedef osmium::index::map::Dummy index_neg_type; - -typedef osmium::index::map::SparseMemArray index_pos_type; - -typedef osmium::handler::NodeLocationsForWays location_handler_type; - -class MyOGRHandler : public osmium::handler::Handler { - - OGRDataSource* m_data_source; - OGRLayer* m_layer_point; - OGRLayer* m_layer_linestring; - OGRLayer* m_layer_polygon; - - // Choose one of the following: - - // 1. Use WGS84, do not project coordinates. - //osmium::geom::OGRFactory<> m_factory {}; - - // 2. Project coordinates into "Web Mercator". - osmium::geom::OGRFactory m_factory; - - // 3. Use any projection that the proj library can handle. - // (Initialize projection with EPSG code or proj string). - // In addition you need to link with "-lproj" and add - // #include . - //osmium::geom::OGRFactory m_factory {osmium::geom::Projection(3857)}; - -public: - - MyOGRHandler(const std::string& driver_name, const std::string& filename) { - - OGRRegisterAll(); - - OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str()); - if (!driver) { - std::cerr << driver_name << " driver not available.\n"; - exit(1); - } - - CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); - const char* options[] = { "SPATIALITE=TRUE", nullptr }; - m_data_source = driver->CreateDataSource(filename.c_str(), const_cast(options)); - if (!m_data_source) { - std::cerr << "Creation of output file failed.\n"; - exit(1); - } - - OGRSpatialReference sparef; - sparef.importFromProj4(m_factory.proj_string().c_str()); - - m_layer_point = m_data_source->CreateLayer("postboxes", &sparef, wkbPoint, nullptr); - if (!m_layer_point) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_point_field_id("id", OFTReal); - layer_point_field_id.SetWidth(10); - - if (m_layer_point->CreateField(&layer_point_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_point_field_operator("operator", OFTString); - layer_point_field_operator.SetWidth(30); - - if (m_layer_point->CreateField(&layer_point_field_operator) != OGRERR_NONE) { - std::cerr << "Creating operator field failed.\n"; - exit(1); - } - - /* Transactions might make things faster, then again they might not. - Feel free to experiment and benchmark and report back. */ - m_layer_point->StartTransaction(); - - m_layer_linestring = m_data_source->CreateLayer("roads", &sparef, wkbLineString, nullptr); - if (!m_layer_linestring) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_linestring_field_id("id", OFTReal); - layer_linestring_field_id.SetWidth(10); - - if (m_layer_linestring->CreateField(&layer_linestring_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_linestring_field_type("type", OFTString); - layer_linestring_field_type.SetWidth(30); - - if (m_layer_linestring->CreateField(&layer_linestring_field_type) != OGRERR_NONE) { - std::cerr << "Creating type field failed.\n"; - exit(1); - } - - m_layer_linestring->StartTransaction(); - - m_layer_polygon = m_data_source->CreateLayer("buildings", &sparef, wkbMultiPolygon, nullptr); - if (!m_layer_polygon) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_polygon_field_id("id", OFTInteger); - layer_polygon_field_id.SetWidth(10); - - if (m_layer_polygon->CreateField(&layer_polygon_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_polygon_field_type("type", OFTString); - layer_polygon_field_type.SetWidth(30); - - if (m_layer_polygon->CreateField(&layer_polygon_field_type) != OGRERR_NONE) { - std::cerr << "Creating type field failed.\n"; - exit(1); - } - - m_layer_polygon->StartTransaction(); - } - - ~MyOGRHandler() { - m_layer_polygon->CommitTransaction(); - m_layer_linestring->CommitTransaction(); - m_layer_point->CommitTransaction(); - OGRDataSource::DestroyDataSource(m_data_source); - OGRCleanupAll(); - } - - void node(const osmium::Node& node) { - const char* amenity = node.tags()["amenity"]; - if (amenity && !strcmp(amenity, "post_box")) { - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_point->GetLayerDefn()); - std::unique_ptr ogr_point = m_factory.create_point(node); - feature->SetGeometry(ogr_point.get()); - feature->SetField("id", static_cast(node.id())); - feature->SetField("operator", node.tags()["operator"]); - - if (m_layer_point->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); - } - } - - void way(const osmium::Way& way) { - const char* highway = way.tags()["highway"]; - if (highway) { - try { - std::unique_ptr ogr_linestring = m_factory.create_linestring(way); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_linestring->GetLayerDefn()); - feature->SetGeometry(ogr_linestring.get()); - feature->SetField("id", static_cast(way.id())); - feature->SetField("type", highway); - - if (m_layer_linestring->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); - } catch (osmium::geometry_error&) { - std::cerr << "Ignoring illegal geometry for way " << way.id() << ".\n"; - } - } - } - - void area(const osmium::Area& area) { - const char* building = area.tags()["building"]; - if (building) { - try { - std::unique_ptr ogr_polygon = m_factory.create_multipolygon(area); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_polygon->GetLayerDefn()); - feature->SetGeometry(ogr_polygon.get()); - feature->SetField("id", static_cast(area.id())); - feature->SetField("type", building); - - std::string type = ""; - if (area.from_way()) { - type += "w"; - } else { - type += "r"; - } - feature->SetField("type", type.c_str()); - - if (m_layer_polygon->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); - } catch (osmium::geometry_error&) { - std::cerr << "Ignoring illegal geometry for area " << area.id() << " created from " << (area.from_way() ? "way" : "relation") << " with id=" << area.orig_id() << ".\n"; - } - } - } - -}; - -/* ================================================== */ - -void print_help() { - std::cout << "osmium_toogr [OPTIONS] [INFILE [OUTFILE]]\n\n" \ - << "If INFILE is not given stdin is assumed.\n" \ - << "If OUTFILE is not given 'ogr_out' is used.\n" \ - << "\nOptions:\n" \ - << " -h, --help This help message\n" \ - << " -d, --debug Enable debug output\n" \ - << " -f, --format=FORMAT Output OGR format (Default: 'SQLite')\n"; -} - -int main(int argc, char* argv[]) { - static struct option long_options[] = { - {"help", no_argument, 0, 'h'}, - {"debug", no_argument, 0, 'd'}, - {"format", required_argument, 0, 'f'}, - {0, 0, 0, 0} - }; - - std::string output_format("SQLite"); - bool debug = false; - - while (true) { - int c = getopt_long(argc, argv, "hdf:", long_options, 0); - if (c == -1) { - break; - } - - switch (c) { - case 'h': - print_help(); - exit(0); - case 'd': - debug = true; - break; - case 'f': - output_format = optarg; - break; - default: - exit(1); - } - } - - std::string input_filename; - std::string output_filename("ogr_out"); - int remaining_args = argc - optind; - if (remaining_args > 2) { - std::cerr << "Usage: " << argv[0] << " [OPTIONS] [INFILE [OUTFILE]]" << std::endl; - exit(1); - } else if (remaining_args == 2) { - input_filename = argv[optind]; - output_filename = argv[optind+1]; - } else if (remaining_args == 1) { - input_filename = argv[optind]; - } else { - input_filename = "-"; - } - - osmium::area::Assembler::config_type assembler_config; - assembler_config.enable_debug_output(debug); - osmium::area::MultipolygonCollector collector(assembler_config); - - std::cerr << "Pass 1...\n"; - osmium::io::Reader reader1(input_filename); - collector.read_relations(reader1); - reader1.close(); - std::cerr << "Pass 1 done\n"; - - index_pos_type index_pos; - index_neg_type index_neg; - location_handler_type location_handler(index_pos, index_neg); - location_handler.ignore_errors(); - - MyOGRHandler ogr_handler(output_format, output_filename); - - std::cerr << "Pass 2...\n"; - osmium::io::Reader reader2(input_filename); - - osmium::apply(reader2, location_handler, ogr_handler, collector.handler([&ogr_handler](const osmium::memory::Buffer& area_buffer) { - osmium::apply(area_buffer, ogr_handler); - })); - - reader2.close(); - std::cerr << "Pass 2 done\n"; - - std::vector incomplete_relations = collector.get_incomplete_relations(); - if (!incomplete_relations.empty()) { - std::cerr << "Warning! Some member ways missing for these multipolygon relations:"; - for (const auto* relation : incomplete_relations) { - std::cerr << " " << relation->id(); - } - std::cerr << "\n"; - } -} - diff --git a/examples/osmium_toogr2_exp.cpp b/examples/osmium_toogr2_exp.cpp deleted file mode 100644 index db8d5cf4e..000000000 --- a/examples/osmium_toogr2_exp.cpp +++ /dev/null @@ -1,305 +0,0 @@ -/* - - This is an example tool that converts OSM data to some output format - like Spatialite or Shapefiles using the OGR library. - - This version does multipolygon handling (in contrast to the osmium_toogr - example which doesn't). - - This version (..._exp) uses a new experimental unsupported interface. - - The code in this example file is released into the Public Domain. - -*/ - -#include -#include - -#include - -#include - -#include -//#include -#include -#include -#include -#include - -typedef osmium::index::map::SparseMemArray index_type; -typedef osmium::handler::NodeLocationsForWays location_handler_type; - -class MyOGRHandler : public osmium::handler::Handler { - - OGRDataSource* m_data_source; - OGRLayer* m_layer_point; - OGRLayer* m_layer_linestring; - OGRLayer* m_layer_polygon; - - // Choose one of the following: - - // 1. Use WGS84, do not project coordinates. - //osmium::geom::OGRFactory<> m_factory {}; - - // 2. Project coordinates into "Web Mercator". - osmium::geom::OGRFactory m_factory; - - // 3. Use any projection that the proj library can handle. - // (Initialize projection with EPSG code or proj string). - // In addition you need to link with "-lproj" and add - // #include . - //osmium::geom::OGRFactory m_factory {osmium::geom::Projection(3857)}; - -public: - - MyOGRHandler(const std::string& driver_name, const std::string& filename) { - - OGRRegisterAll(); - - OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str()); - if (!driver) { - std::cerr << driver_name << " driver not available.\n"; - exit(1); - } - - CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); - const char* options[] = { "SPATIALITE=TRUE", nullptr }; - m_data_source = driver->CreateDataSource(filename.c_str(), const_cast(options)); - if (!m_data_source) { - std::cerr << "Creation of output file failed.\n"; - exit(1); - } - - OGRSpatialReference sparef; - sparef.importFromProj4(m_factory.proj_string().c_str()); - - m_layer_point = m_data_source->CreateLayer("postboxes", &sparef, wkbPoint, nullptr); - if (!m_layer_point) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_point_field_id("id", OFTReal); - layer_point_field_id.SetWidth(10); - - if (m_layer_point->CreateField(&layer_point_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_point_field_operator("operator", OFTString); - layer_point_field_operator.SetWidth(30); - - if (m_layer_point->CreateField(&layer_point_field_operator) != OGRERR_NONE) { - std::cerr << "Creating operator field failed.\n"; - exit(1); - } - - /* Transactions might make things faster, then again they might not. - Feel free to experiment and benchmark and report back. */ - m_layer_point->StartTransaction(); - - m_layer_linestring = m_data_source->CreateLayer("roads", &sparef, wkbLineString, nullptr); - if (!m_layer_linestring) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_linestring_field_id("id", OFTReal); - layer_linestring_field_id.SetWidth(10); - - if (m_layer_linestring->CreateField(&layer_linestring_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_linestring_field_type("type", OFTString); - layer_linestring_field_type.SetWidth(30); - - if (m_layer_linestring->CreateField(&layer_linestring_field_type) != OGRERR_NONE) { - std::cerr << "Creating type field failed.\n"; - exit(1); - } - - m_layer_linestring->StartTransaction(); - - m_layer_polygon = m_data_source->CreateLayer("buildings", &sparef, wkbMultiPolygon, nullptr); - if (!m_layer_polygon) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_polygon_field_id("id", OFTInteger); - layer_polygon_field_id.SetWidth(10); - - if (m_layer_polygon->CreateField(&layer_polygon_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_polygon_field_type("type", OFTString); - layer_polygon_field_type.SetWidth(30); - - if (m_layer_polygon->CreateField(&layer_polygon_field_type) != OGRERR_NONE) { - std::cerr << "Creating type field failed.\n"; - exit(1); - } - - m_layer_polygon->StartTransaction(); - } - - ~MyOGRHandler() { - m_layer_polygon->CommitTransaction(); - m_layer_linestring->CommitTransaction(); - m_layer_point->CommitTransaction(); - OGRDataSource::DestroyDataSource(m_data_source); - OGRCleanupAll(); - } - - void node(const osmium::Node& node) { - const char* amenity = node.tags()["amenity"]; - if (amenity && !strcmp(amenity, "post_box")) { - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_point->GetLayerDefn()); - std::unique_ptr ogr_point = m_factory.create_point(node); - feature->SetGeometry(ogr_point.get()); - feature->SetField("id", static_cast(node.id())); - feature->SetField("operator", node.tags()["operator"]); - - if (m_layer_point->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); - } - } - - void way(const osmium::Way& way) { - const char* highway = way.tags()["highway"]; - if (highway) { - try { - std::unique_ptr ogr_linestring = m_factory.create_linestring(way); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_linestring->GetLayerDefn()); - feature->SetGeometry(ogr_linestring.get()); - feature->SetField("id", static_cast(way.id())); - feature->SetField("type", highway); - - if (m_layer_linestring->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); - } catch (osmium::geometry_error&) { - std::cerr << "Ignoring illegal geometry for way " << way.id() << ".\n"; - } - } - } - - void area(const osmium::Area& area) { - const char* building = area.tags()["building"]; - if (building) { - try { - std::unique_ptr ogr_polygon = m_factory.create_multipolygon(area); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_polygon->GetLayerDefn()); - feature->SetGeometry(ogr_polygon.get()); - feature->SetField("id", static_cast(area.id())); - feature->SetField("type", building); - - std::string type = ""; - if (area.from_way()) { - type += "w"; - } else { - type += "r"; - } - feature->SetField("type", type.c_str()); - - if (m_layer_polygon->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); - } catch (osmium::geometry_error&) { - std::cerr << "Ignoring illegal geometry for area " << area.id() << " created from " << (area.from_way() ? "way" : "relation") << " with id=" << area.orig_id() << ".\n"; - } - } - } - -}; - -/* ================================================== */ - -void print_help() { - std::cout << "osmium_toogr [OPTIONS] [INFILE [OUTFILE]]\n\n" \ - << "If INFILE is not given stdin is assumed.\n" \ - << "If OUTFILE is not given 'ogr_out' is used.\n" \ - << "\nOptions:\n" \ - << " -h, --help This help message\n" \ - << " -f, --format=FORMAT Output OGR format (Default: 'SQLite')\n"; -} - -int main(int argc, char* argv[]) { - static struct option long_options[] = { - {"help", no_argument, 0, 'h'}, - {"format", required_argument, 0, 'f'}, - {0, 0, 0, 0} - }; - - std::string output_format("SQLite"); - - while (true) { - int c = getopt_long(argc, argv, "hf:", long_options, 0); - if (c == -1) { - break; - } - - switch (c) { - case 'h': - print_help(); - exit(0); - case 'f': - output_format = optarg; - break; - default: - exit(1); - } - } - - std::string input_filename; - std::string output_filename("ogr_out"); - int remaining_args = argc - optind; - if (remaining_args > 2) { - std::cerr << "Usage: " << argv[0] << " [OPTIONS] [INFILE [OUTFILE]]" << std::endl; - exit(1); - } else if (remaining_args == 2) { - input_filename = argv[optind]; - output_filename = argv[optind+1]; - } else if (remaining_args == 1) { - input_filename = argv[optind]; - } else { - input_filename = "-"; - } - - index_type index_pos; - location_handler_type location_handler(index_pos); - osmium::experimental::FlexReader exr(input_filename, location_handler, osmium::osm_entity_bits::object); - - MyOGRHandler ogr_handler(output_format, output_filename); - - while (auto buffer = exr.read()) { - osmium::apply(buffer, ogr_handler); - } - - exr.close(); - - std::vector incomplete_relations = exr.collector().get_incomplete_relations(); - if (!incomplete_relations.empty()) { - std::cerr << "Warning! Some member ways missing for these multipolygon relations:"; - for (const auto* relation : incomplete_relations) { - std::cerr << " " << relation->id(); - } - std::cerr << "\n"; - } -} - diff --git a/include/gdalcpp.hpp b/include/gdalcpp.hpp new file mode 100644 index 000000000..1502f2f0c --- /dev/null +++ b/include/gdalcpp.hpp @@ -0,0 +1,406 @@ +#ifndef GDALCPP_HPP +#define GDALCPP_HPP + +/* + +C++11 wrapper classes for GDAL/OGR. + +Version 1.1.1 + +https://github.com/joto/gdalcpp + +Copyright 2015 Jochen Topf + +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 +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace gdalcpp { + +#if GDAL_VERSION_MAJOR >= 2 + using gdal_driver_type = GDALDriver; + using gdal_dataset_type = GDALDataset; +#else + using gdal_driver_type = OGRSFDriver; + using gdal_dataset_type = OGRDataSource; +#endif + + /** + * Exception thrown for all errors in this class. + */ + class gdal_error : public std::runtime_error { + + std::string m_driver; + std::string m_dataset; + std::string m_layer; + std::string m_field; + OGRErr m_error; + + public: + + gdal_error(const std::string& message, + OGRErr error, + const std::string& driver = "", + const std::string& dataset = "", + const std::string& layer = "", + const std::string& field = "") : + std::runtime_error(message), + m_driver(driver), + m_dataset(dataset), + m_layer(layer), + m_field(field), + m_error(error) { + } + + const std::string& driver() const { + return m_driver; + } + + const std::string& dataset() const { + return m_dataset; + } + + const std::string& layer() const { + return m_layer; + } + + const std::string& field() const { + return m_field; + } + + OGRErr error() const { + return m_error; + } + + }; // class gdal_error + + namespace detail { + + struct init_wrapper { + init_wrapper() { OGRRegisterAll(); } + ~init_wrapper() { OGRCleanupAll(); } + }; + + struct init_library { + init_library() { + static init_wrapper iw; + } + }; + + class Driver : private init_library { + + gdal_driver_type* m_driver; + + public: + + Driver(const std::string& driver_name) : + init_library(), +#if GDAL_VERSION_MAJOR >= 2 + m_driver(GetGDALDriverManager()->GetDriverByName(driver_name.c_str())) { +#else + m_driver(OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str())) { +#endif + if (!m_driver) { + throw gdal_error(std::string("unknown driver: '") + driver_name + "'", OGRERR_NONE, driver_name); + } + } + + gdal_driver_type& get() const { + return *m_driver; + } + + }; // struct Driver + + struct Options { + + std::vector m_options; + std::unique_ptr m_ptrs; + + Options(const std::vector& options) : + m_options(options), + m_ptrs(new const char*[options.size()+1]) { + std::transform(m_options.begin(), m_options.end(), m_ptrs.get(), [&](const std::string& s) { + return s.data(); + }); + m_ptrs[options.size()] = nullptr; + } + + char** get() const { + return const_cast(m_ptrs.get()); + } + + }; // struct Options + + } // namespace detail + + class SRS { + + OGRSpatialReference m_spatial_reference; + + public: + + SRS() : + m_spatial_reference() { + auto result = m_spatial_reference.SetWellKnownGeogCS("WGS84"); + if (result != OGRERR_NONE) { + throw gdal_error(std::string("can not initialize spatial reference system WGS84"), result); + } + } + + explicit SRS(int epsg) : + m_spatial_reference() { + auto result = m_spatial_reference.importFromEPSG(epsg); + if (result != OGRERR_NONE) { + throw gdal_error(std::string("can not initialize spatial reference system for EPSG:") + std::to_string(epsg), result); + } + } + + explicit SRS(const char* name) : + m_spatial_reference() { + auto result = m_spatial_reference.importFromProj4(name); + if (result != OGRERR_NONE) { + throw gdal_error(std::string("can not initialize spatial reference system '") + name + "'", result); + } + } + + explicit SRS(const std::string& name) : + m_spatial_reference() { + auto result = m_spatial_reference.importFromProj4(name.c_str()); + if (result != OGRERR_NONE) { + throw gdal_error(std::string("can not initialize spatial reference system '") + name + "'", result); + } + } + + explicit SRS(const OGRSpatialReference& spatial_reference) : + m_spatial_reference(spatial_reference) { + } + + OGRSpatialReference& get() { + return m_spatial_reference; + } + + const OGRSpatialReference& get() const { + return m_spatial_reference; + } + + }; // class SRS + + class Dataset { + + struct gdal_dataset_deleter { + + void operator()(gdal_dataset_type* ds) { +#if GDAL_VERSION_MAJOR >= 2 + GDALClose(ds); +#else + OGRDataSource::DestroyDataSource(ds); +#endif + } + + }; // struct gdal_dataset_deleter + + std::string m_driver_name; + std::string m_dataset_name; + detail::Options m_options; + SRS m_srs; + std::unique_ptr m_dataset; + + public: + + Dataset(const std::string& driver_name, const std::string& dataset_name, const SRS& srs = SRS{}, const std::vector& options = {}) : + m_driver_name(driver_name), + m_dataset_name(dataset_name), + m_options(options), + m_srs(srs), +#if GDAL_VERSION_MAJOR >= 2 + m_dataset(detail::Driver(driver_name).get().Create(dataset_name.c_str(), 0, 0, 0, GDT_Unknown, m_options.get())) { +#else + m_dataset(detail::Driver(driver_name).get().CreateDataSource(dataset_name.c_str(), m_options.get())) { +#endif + if (!m_dataset) { + throw gdal_error(std::string("failed to create dataset '") + dataset_name + "'", OGRERR_NONE, driver_name, dataset_name); + } + } + + const std::string& driver_name() const { + return m_driver_name; + } + + const std::string& dataset_name() const { + return m_dataset_name; + } + + gdal_dataset_type& get() const { + return *m_dataset; + } + + SRS& srs() { + return m_srs; + } + + void exec(const char* sql) { + auto result = m_dataset->ExecuteSQL(sql, nullptr, nullptr); + if (result) { + m_dataset->ReleaseResultSet(result); + } + } + + void exec(const std::string& sql) { + exec(sql.c_str()); + } + + + Dataset& start_transaction() { +#if GDAL_VERSION_MAJOR >= 2 + m_dataset->StartTransaction(); +#endif + return *this; + } + + Dataset& commit_transaction() { +#if GDAL_VERSION_MAJOR >= 2 + m_dataset->CommitTransaction(); +#endif + return *this; + } + + }; // class Dataset + + class Layer { + + detail::Options m_options; + Dataset& m_dataset; + OGRLayer* m_layer; + + public: + + Layer(Dataset& dataset, const std::string& layer_name, OGRwkbGeometryType type, const std::vector& options = {}) : + m_options(options), + m_dataset(dataset), + m_layer(dataset.get().CreateLayer(layer_name.c_str(), &dataset.srs().get(), type, m_options.get())) { + if (!m_layer) { + throw gdal_error(std::string("failed to create layer '") + layer_name + "'", OGRERR_NONE, + dataset.driver_name(), dataset.dataset_name(), layer_name); + } + } + + OGRLayer& get() { + return *m_layer; + } + + const OGRLayer& get() const { + return *m_layer; + } + + Dataset& dataset() const { + return m_dataset; + } + + const char* name() const { + return m_layer->GetName(); + } + + Layer& add_field(const std::string& field_name, OGRFieldType type, int width, int precision=0) { + OGRFieldDefn field(field_name.c_str(), type); + field.SetWidth(width); + field.SetPrecision(precision); + + if (m_layer->CreateField(&field) != OGRERR_NONE) { + throw gdal_error(std::string("failed to create field '") + field_name + "' in layer '" + name() + "'", OGRERR_NONE, + m_dataset.driver_name(), m_dataset.dataset_name(), name(), field_name); + } + + return *this; + } + + Layer& start_transaction() { + OGRErr result = m_layer->StartTransaction(); + if (result != OGRERR_NONE) { + throw gdal_error(std::string("starting transaction on layer '") + name() + "' failed", result, m_dataset.driver_name(), m_dataset.dataset_name(), name()); + } + return *this; + } + + Layer& commit_transaction() { + OGRErr result = m_layer->CommitTransaction(); + if (result != OGRERR_NONE) { + throw gdal_error(std::string("committing transaction on layer '") + name() + "' failed", result, m_dataset.driver_name(), m_dataset.dataset_name(), name()); + } + return *this; + } + + }; // class Layer + + class Feature { + + Layer& m_layer; + OGRFeature m_feature; + + public: + + Feature(Layer& layer, std::unique_ptr&& geometry) : + m_layer(layer), + m_feature(m_layer.get().GetLayerDefn()) { + OGRErr result = m_feature.SetGeometryDirectly(geometry.release()); + if (result != OGRERR_NONE) { + throw gdal_error(std::string("setting feature geometry in layer '") + m_layer.name() + "' failed", result, m_layer.dataset().driver_name(), m_layer.dataset().dataset_name()); + } + } + + void add_to_layer() { + OGRErr result = m_layer.get().CreateFeature(&m_feature); + if (result != OGRERR_NONE) { + throw gdal_error(std::string("creating feature in layer '") + m_layer.name() + "' failed", result, m_layer.dataset().driver_name(), m_layer.dataset().dataset_name()); + } + } + + template + Feature& set_field(int n, T&& arg) { + m_feature.SetField(n, std::forward(arg)); + return *this; + } + + template + Feature& set_field(const char* name, T&& arg) { + m_feature.SetField(name, std::forward(arg)); + return *this; + } + + }; // class Feature + +} // namespace gdalcpp + +#endif // GDALCPP_HPP diff --git a/include/osmium/area/assembler.hpp b/include/osmium/area/assembler.hpp index f17299109..87feea29e 100644 --- a/include/osmium/area/assembler.hpp +++ b/include/osmium/area/assembler.hpp @@ -34,9 +34,13 @@ DEALINGS IN THE SOFTWARE. */ #include +#include +#include #include #include #include +#include +#include #include #include diff --git a/include/osmium/area/detail/node_ref_segment.hpp b/include/osmium/area/detail/node_ref_segment.hpp index 43569a865..aab5b8fa3 100644 --- a/include/osmium/area/detail/node_ref_segment.hpp +++ b/include/osmium/area/detail/node_ref_segment.hpp @@ -113,7 +113,7 @@ namespace osmium { return m_second; } - bool to_left_of(const osmium::Location location) const { + bool to_left_of(const osmium::Location& location) const { // std::cerr << "segment " << first() << "--" << second() << " to_left_of(" << location << "\n"; if (first().location() == location || second().location() == location) { @@ -195,8 +195,8 @@ namespace osmium { } inline bool y_range_overlap(const NodeRefSegment& s1, const NodeRefSegment& s2) { - auto m1 = std::minmax(s1.first().location().y(), s1.second().location().y()); - auto m2 = std::minmax(s2.first().location().y(), s2.second().location().y()); + const std::pair m1 = std::minmax(s1.first().location().y(), s1.second().location().y()); + const std::pair m2 = std::minmax(s2.first().location().y(), s2.second().location().y()); if (m1.first > m2.second || m2.first > m1.second) { return false; } @@ -204,19 +204,25 @@ namespace osmium { } /** - * Calculate the intersection between to NodeRefSegments. The result is returned - * as a Location. Note that because the Location uses integers with limited - * precision internally, the result might be slightly different than the - * numerically correct location. + * Calculate the intersection between two NodeRefSegments. The + * result is returned as a Location. Note that because the Location + * uses integers with limited precision internally, the result + * might be slightly different than the numerically correct + * location. * - * If the segments touch in one of their endpoints, it doesn't count as an - * intersection. + * This function uses integer arithmentic as much as possible and + * will not work if the segments are longer than about half the + * planet. This shouldn't happen with real data, so it isn't a big + * problem. * - * If the segments intersect not in a single point but in multiple points, ie - * if they overlap, this is NOT detected. + * If the segments touch in one of their endpoints, it doesn't + * count as an intersection. * - * @returns Undefined osmium::Location if there is no intersection or a defined - * Location if the segments intersect. + * If the segments intersect not in a single point but in multiple + * points, ie if they overlap, this is NOT detected. + * + * @returns Undefined osmium::Location if there is no intersection + * or a defined Location if the segments intersect. */ inline osmium::Location calculate_intersection(const NodeRefSegment& s1, const NodeRefSegment& s2) { if (s1.first().location() == s2.first().location() || @@ -226,26 +232,32 @@ namespace osmium { return osmium::Location(); } - auto d = (static_cast(s2.second().y()) - static_cast(s2.first().y())) * - (static_cast(s1.second().x()) - static_cast(s1.first().x())) - - (static_cast(s2.second().x()) - static_cast(s2.first().x())) * - (static_cast(s1.second().y()) - static_cast(s1.first().y())); + int64_t s1ax = s1.first().x(); + int64_t s1ay = s1.first().y(); + int64_t s1bx = s1.second().x(); + int64_t s1by = s1.second().y(); + int64_t s2ax = s2.first().x(); + int64_t s2ay = s2.first().y(); + int64_t s2bx = s2.second().x(); + int64_t s2by = s2.second().y(); + + int64_t d = (s2by - s2ay) * (s1bx - s1ax) - + (s2bx - s2ax) * (s1by - s1ay); if (d != 0) { - double denom = ((s2.second().lat() - s2.first().lat())*(s1.second().lon() - s1.first().lon())) - - ((s2.second().lon() - s2.first().lon())*(s1.second().lat() - s1.first().lat())); + int64_t na = (s2bx - s2ax) * (s1ay - s2ay) - + (s2by - s2ay) * (s1ax - s2ax); - double nume_a = ((s2.second().lon() - s2.first().lon())*(s1.first().lat() - s2.first().lat())) - - ((s2.second().lat() - s2.first().lat())*(s1.first().lon() - s2.first().lon())); + int64_t nb = (s1bx - s1ax) * (s1ay - s2ay) - + (s1by - s1ay) * (s1ax - s2ax); - double nume_b = ((s1.second().lon() - s1.first().lon())*(s1.first().lat() - s2.first().lat())) - - ((s1.second().lat() - s1.first().lat())*(s1.first().lon() - s2.first().lon())); + if ((d > 0 && na >= 0 && na <= d && nb >= 0 && nb <= d) || + (d < 0 && na <= 0 && na >= d && nb <= 0 && nb >= d)) { + + double ua = double(na) / d; + int32_t ix = int32_t(s1ax + ua*(s1bx - s1ax)); + int32_t iy = int32_t(s1ay + ua*(s1by - s1ay)); - if ((denom > 0 && nume_a >= 0 && nume_a <= denom && nume_b >= 0 && nume_b <= denom) || - (denom < 0 && nume_a <= 0 && nume_a >= denom && nume_b <= 0 && nume_b >= denom)) { - double ua = nume_a / denom; - double ix = s1.first().lon() + ua*(s1.second().lon() - s1.first().lon()); - double iy = s1.first().lat() + ua*(s1.second().lat() - s1.first().lat()); return osmium::Location(ix, iy); } } diff --git a/include/osmium/area/detail/proto_ring.hpp b/include/osmium/area/detail/proto_ring.hpp index c0f545c98..162e2896d 100644 --- a/include/osmium/area/detail/proto_ring.hpp +++ b/include/osmium/area/detail/proto_ring.hpp @@ -34,12 +34,14 @@ DEALINGS IN THE SOFTWARE. */ #include -#include +#include +#include #include -#include +#include #include #include +#include #include #include @@ -148,7 +150,8 @@ namespace osmium { } void swap_segments(ProtoRing& other) { - std::swap(m_segments, other.m_segments); + using std::swap; + swap(m_segments, other.m_segments); } void add_inner_ring(ProtoRing* ring) { diff --git a/include/osmium/area/detail/segment_list.hpp b/include/osmium/area/detail/segment_list.hpp index ca6071ede..289ecf0c9 100644 --- a/include/osmium/area/detail/segment_list.hpp +++ b/include/osmium/area/detail/segment_list.hpp @@ -41,6 +41,8 @@ DEALINGS IN THE SOFTWARE. #include #include #include +#include +#include #include #include diff --git a/include/osmium/area/multipolygon_collector.hpp b/include/osmium/area/multipolygon_collector.hpp index bf2a4ce86..2881597b0 100644 --- a/include/osmium/area/multipolygon_collector.hpp +++ b/include/osmium/area/multipolygon_collector.hpp @@ -53,7 +53,7 @@ namespace osmium { namespace relations { class RelationMeta; - } + } // namespace relations /** * @brief Code related to the building of areas (multipolygons) from relations. @@ -71,7 +71,7 @@ namespace osmium { * * @tparam TAssembler Multipolygon Assembler class. */ - template + template class MultipolygonCollector : public osmium::relations::Collector, false, true, false> { typedef typename osmium::relations::Collector, false, true, false> collector_type; @@ -87,7 +87,8 @@ namespace osmium { void flush_output_buffer() { if (this->callback()) { osmium::memory::Buffer buffer(initial_output_buffer_size); - std::swap(buffer, m_output_buffer); + using std::swap; + swap(buffer, m_output_buffer); this->callback()(std::move(buffer)); } } @@ -176,28 +177,6 @@ namespace osmium { } catch (osmium::invalid_location&) { // XXX ignore } - - // clear member metas - for (const auto& member : relation.members()) { - if (member.ref() != 0) { - auto& mmv = this->member_meta(member.type()); - auto range = std::equal_range(mmv.begin(), mmv.end(), osmium::relations::MemberMeta(member.ref())); - assert(range.first != range.second); - - // if this is the last time this object was needed - // then mark it as removed - if (osmium::relations::count_not_removed(range.first, range.second) == 1) { - this->get_member(range.first->buffer_offset()).set_removed(true); - } - - for (auto it = range.first; it != range.second; ++it) { - if (!it->removed() && relation.id() == this->get_relation(it->relation_pos()).id()) { - it->remove(); - break; - } - } - } - } } void flush() { @@ -206,7 +185,10 @@ namespace osmium { osmium::memory::Buffer read() { osmium::memory::Buffer buffer(initial_output_buffer_size, osmium::memory::Buffer::auto_grow::yes); - std::swap(buffer, m_output_buffer); + + using std::swap; + swap(buffer, m_output_buffer); + return buffer; } diff --git a/include/osmium/area/problem_reporter_exception.hpp b/include/osmium/area/problem_reporter_exception.hpp index 5e743c6d8..7c9a5e393 100644 --- a/include/osmium/area/problem_reporter_exception.hpp +++ b/include/osmium/area/problem_reporter_exception.hpp @@ -54,7 +54,7 @@ namespace osmium { ProblemReporterStream(m_sstream) { } - virtual ~ProblemReporterException() = default; + ~ProblemReporterException() override = default; void report_duplicate_node(osmium::object_id_type node_id1, osmium::object_id_type node_id2, osmium::Location location) override { m_sstream.str(); diff --git a/include/osmium/area/problem_reporter_ogr.hpp b/include/osmium/area/problem_reporter_ogr.hpp index c437a3f57..68fae3bb8 100644 --- a/include/osmium/area/problem_reporter_ogr.hpp +++ b/include/osmium/area/problem_reporter_ogr.hpp @@ -42,34 +42,12 @@ DEALINGS IN THE SOFTWARE. * @attention If you include this file, you'll need to link with `libgdal`. */ -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4458) -#else -# pragma GCC diagnostic push -# ifdef __clang__ -# pragma GCC diagnostic ignored "-Wdocumentation-unknown-command" -# endif -# pragma GCC diagnostic ignored "-Wfloat-equal" -# pragma GCC diagnostic ignored "-Wold-style-cast" -# pragma GCC diagnostic ignored "-Wpadded" -# pragma GCC diagnostic ignored "-Wredundant-decls" -# pragma GCC diagnostic ignored "-Wshadow" -#endif - -#include -#include - -#ifdef _MSC_VER -# pragma warning(pop) -#else -# pragma GCC diagnostic pop -#endif - #include -#include + +#include #include +#include #include #include #include @@ -86,24 +64,15 @@ namespace osmium { osmium::geom::OGRFactory<> m_ogr_factory; - OGRDataSource* m_data_source; - - OGRLayer* m_layer_perror; - OGRLayer* m_layer_lerror; + gdalcpp::Layer m_layer_perror; + gdalcpp::Layer m_layer_lerror; void write_point(const char* problem_type, osmium::object_id_type id1, osmium::object_id_type id2, osmium::Location location) { - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_perror->GetLayerDefn()); - std::unique_ptr ogr_point = m_ogr_factory.create_point(location); - feature->SetGeometry(ogr_point.get()); - feature->SetField("id1", static_cast(id1)); - feature->SetField("id2", static_cast(id2)); - feature->SetField("problem_type", problem_type); - - if (m_layer_perror->CreateFeature(feature) != OGRERR_NONE) { - std::runtime_error("Failed to create feature on layer 'perrors'"); - } - - OGRFeature::DestroyFeature(feature); + gdalcpp::Feature feature(m_layer_perror, m_ogr_factory.create_point(location)); + feature.set_field("id1", static_cast(id1)); + feature.set_field("id2", static_cast(id2)); + feature.set_field("problem_type", problem_type); + feature.add_to_layer(); } void write_line(const char* problem_type, osmium::object_id_type id1, osmium::object_id_type id2, osmium::Location loc1, osmium::Location loc2) { @@ -112,83 +81,30 @@ namespace osmium { std::unique_ptr ogr_linestring = std::unique_ptr(new OGRLineString()); ogr_linestring->addPoint(ogr_point1.get()); ogr_linestring->addPoint(ogr_point2.get()); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_lerror->GetLayerDefn()); - feature->SetGeometry(ogr_linestring.get()); - feature->SetField("id1", static_cast(id1)); - feature->SetField("id2", static_cast(id2)); - feature->SetField("problem_type", problem_type); - if (m_layer_lerror->CreateFeature(feature) != OGRERR_NONE) { - std::runtime_error("Failed to create feature on layer 'lerrors'"); - } - - OGRFeature::DestroyFeature(feature); + gdalcpp::Feature feature(m_layer_lerror, std::move(ogr_linestring)); + feature.set_field("id1", static_cast(id1)); + feature.set_field("id2", static_cast(id2)); + feature.set_field("problem_type", problem_type); + feature.add_to_layer(); } public: - explicit ProblemReporterOGR(OGRDataSource* data_source) : - m_data_source(data_source) { + explicit ProblemReporterOGR(gdalcpp::Dataset& dataset) : + m_layer_perror(dataset, "perrors", wkbPoint), + m_layer_lerror(dataset, "lerrors", wkbLineString) { - OGRSpatialReference sparef; - sparef.SetWellKnownGeogCS("WGS84"); + m_layer_perror.add_field("id1", OFTReal, 10); + m_layer_perror.add_field("id2", OFTReal, 10); + m_layer_perror.add_field("problem_type", OFTString, 30); - m_layer_perror = m_data_source->CreateLayer("perrors", &sparef, wkbPoint, nullptr); - if (!m_layer_perror) { - std::runtime_error("Layer creation failed for layer 'perrors'"); - } - - OGRFieldDefn layer_perror_field_id1("id1", OFTReal); - layer_perror_field_id1.SetWidth(10); - - if (m_layer_perror->CreateField(&layer_perror_field_id1) != OGRERR_NONE) { - std::runtime_error("Creating field 'id1' failed for layer 'perrors'"); - } - - OGRFieldDefn layer_perror_field_id2("id2", OFTReal); - layer_perror_field_id2.SetWidth(10); - - if (m_layer_perror->CreateField(&layer_perror_field_id2) != OGRERR_NONE) { - std::runtime_error("Creating field 'id2' failed for layer 'perrors'"); - } - - OGRFieldDefn layer_perror_field_problem_type("problem_type", OFTString); - layer_perror_field_problem_type.SetWidth(30); - - if (m_layer_perror->CreateField(&layer_perror_field_problem_type) != OGRERR_NONE) { - std::runtime_error("Creating field 'problem_type' failed for layer 'perrors'"); - } - - /**************/ - - m_layer_lerror = m_data_source->CreateLayer("lerrors", &sparef, wkbLineString, nullptr); - if (!m_layer_lerror) { - std::runtime_error("Layer creation failed for layer 'lerrors'"); - } - - OGRFieldDefn layer_lerror_field_id1("id1", OFTReal); - layer_lerror_field_id1.SetWidth(10); - - if (m_layer_lerror->CreateField(&layer_lerror_field_id1) != OGRERR_NONE) { - std::runtime_error("Creating field 'id1' failed for layer 'lerrors'"); - } - - OGRFieldDefn layer_lerror_field_id2("id2", OFTReal); - layer_lerror_field_id2.SetWidth(10); - - if (m_layer_lerror->CreateField(&layer_lerror_field_id2) != OGRERR_NONE) { - std::runtime_error("Creating field 'id2' failed for layer 'lerrors'"); - } - - OGRFieldDefn layer_lerror_field_problem_type("problem_type", OFTString); - layer_lerror_field_problem_type.SetWidth(30); - - if (m_layer_lerror->CreateField(&layer_lerror_field_problem_type) != OGRERR_NONE) { - std::runtime_error("Creating field 'problem_type' failed for layer 'lerrors'"); - } + m_layer_lerror.add_field("id1", OFTReal, 10); + m_layer_lerror.add_field("id2", OFTReal, 10); + m_layer_lerror.add_field("problem_type", OFTString, 30); } - virtual ~ProblemReporterOGR() = default; + ~ProblemReporterOGR() override = default; void report_duplicate_node(osmium::object_id_type node_id1, osmium::object_id_type node_id2, osmium::Location location) override { write_point("duplicate_node", node_id1, node_id2, location); diff --git a/include/osmium/area/problem_reporter_stream.hpp b/include/osmium/area/problem_reporter_stream.hpp index ddcb343e8..b6a004cdf 100644 --- a/include/osmium/area/problem_reporter_stream.hpp +++ b/include/osmium/area/problem_reporter_stream.hpp @@ -54,7 +54,7 @@ namespace osmium { m_out(&out) { } - virtual ~ProblemReporterStream() = default; + ~ProblemReporterStream() override = default; void header(const char* msg) { *m_out << "DATA PROBLEM: " << msg << " on " << item_type_to_char(m_object_type) << m_object_id << ": "; diff --git a/include/osmium/builder/builder.hpp b/include/osmium/builder/builder.hpp index 4424d88e1..63eb4bb2d 100644 --- a/include/osmium/builder/builder.hpp +++ b/include/osmium/builder/builder.hpp @@ -134,7 +134,7 @@ namespace osmium { * Reserve space for an object of class T in buffer and return * pointer to it. */ - template + template T* reserve_space_for() { assert(m_buffer.is_aligned()); return reinterpret_cast(m_buffer.reserve_space(sizeof(T))); @@ -182,7 +182,7 @@ namespace osmium { }; // class Builder - template + template class ObjectBuilder : public Builder { static_assert(std::is_base_of::value, "ObjectBuilder can only build objects derived from osmium::memory::Item"); diff --git a/include/osmium/builder/osm_object_builder.hpp b/include/osmium/builder/osm_object_builder.hpp index 074076ce6..82b4b23ce 100644 --- a/include/osmium/builder/osm_object_builder.hpp +++ b/include/osmium/builder/osm_object_builder.hpp @@ -33,9 +33,11 @@ DEALINGS IN THE SOFTWARE. */ +#include #include #include #include +#include #include #include @@ -53,7 +55,7 @@ namespace osmium { namespace memory { class Buffer; - } + } // namespace memory namespace builder { @@ -76,6 +78,12 @@ namespace osmium { * @param value Tag value (0-terminated string). */ void add_tag(const char* key, const char* value) { + if (std::strlen(key) > osmium::max_osm_string_length) { + throw std::length_error("OSM tag key is too long"); + } + if (std::strlen(value) > osmium::max_osm_string_length) { + throw std::length_error("OSM tag value is too long"); + } add_size(append(key) + append(value)); } @@ -87,8 +95,15 @@ namespace osmium { * @param value Pointer to tag value. * @param value_length Length of value (not including the \0 byte). */ - void add_tag(const char* key, const string_size_type key_length, const char* value, const string_size_type value_length) { - add_size(append(key, key_length) + append_zero() + append(value, value_length) + append_zero()); + void add_tag(const char* key, const size_t key_length, const char* value, const size_t value_length) { + if (key_length > osmium::max_osm_string_length) { + throw std::length_error("OSM tag key is too long"); + } + if (value_length > osmium::max_osm_string_length) { + throw std::length_error("OSM tag value is too long"); + } + add_size(append(key, osmium::memory::item_size_type(key_length)) + append_zero() + + append(value, osmium::memory::item_size_type(value_length)) + append_zero()); } /** @@ -98,13 +113,46 @@ namespace osmium { * @param value Tag value. */ void add_tag(const std::string& key, const std::string& value) { - add_size(append(key.data(), static_cast_with_assert(key.size() + 1)) + - append(value.data(), static_cast_with_assert(value.size() + 1))); + if (key.size() > osmium::max_osm_string_length) { + throw std::length_error("OSM tag key is too long"); + } + if (value.size() > osmium::max_osm_string_length) { + throw std::length_error("OSM tag value is too long"); + } + add_size(append(key.data(), osmium::memory::item_size_type(key.size()) + 1) + + append(value.data(), osmium::memory::item_size_type(value.size()) + 1)); + } + + /** + * Add tag to buffer. + * + * @param tag Tag. + */ + void add_tag(const osmium::Tag& tag) { + add_size(append(tag.key()) + append(tag.value())); + } + + /** + * Add tag to buffer. + * + * @param tag Pair of key/value 0-terminated strings. + */ + void add_tag(const std::pair& tag) { + add_tag(tag.first, tag.second); + } + + /** + * Add tag to buffer. + * + * @param tag Pair of std::string references. + */ + void add_tag(const std::pair& tag) { + add_tag(tag.first, tag.second); } }; // class TagListBuilder - template + template class NodeRefListBuilder : public ObjectBuilder { public: @@ -122,7 +170,7 @@ namespace osmium { static_cast(this)->add_size(sizeof(osmium::NodeRef)); } - void add_node_ref(const object_id_type ref, const osmium::Location location = Location()) { + void add_node_ref(const object_id_type ref, const osmium::Location& location = Location{}) { add_node_ref(NodeRef(ref, location)); } @@ -141,35 +189,17 @@ namespace osmium { * will be set. * @param role The role. * @param length Length of role (without \0 termination). + * @throws std:length_error If role is longer than osmium::max_osm_string_length */ - void add_role(osmium::RelationMember& member, const char* role, const string_size_type length) { - member.set_role_size(length + 1); - add_size(append(role, length) + append_zero()); + void add_role(osmium::RelationMember& member, const char* role, const size_t length) { + if (length > osmium::max_osm_string_length) { + throw std::length_error("OSM relation member role is too long"); + } + member.set_role_size(osmium::string_size_type(length) + 1); + add_size(append(role, osmium::memory::item_size_type(length)) + append_zero()); add_padding(true); } - /** - * Add role to buffer. - * - * @param member Relation member object where the length of the role - * will be set. - * @param role \0-terminated role. - */ - void add_role(osmium::RelationMember& member, const char* role) { - add_role(member, role, static_cast_with_assert(std::strlen(role))); - } - - /** - * Add role to buffer. - * - * @param member Relation member object where the length of the role - * will be set. - * @param role Role. - */ - void add_role(osmium::RelationMember& member, const std::string& role) { - add_role(member, role.data(), static_cast_with_assert(role.size())); - } - public: explicit RelationMemberListBuilder(osmium::memory::Buffer& buffer, Builder* parent = nullptr) : @@ -190,8 +220,10 @@ namespace osmium { * @param full_member Optional pointer to the member object. If it * is available a copy will be added to the * relation. + * @throws std:length_error If role_length is greater than + * osmium::max_osm_string_length */ - void add_member(osmium::item_type type, object_id_type ref, const char* role, const string_size_type role_length, const osmium::OSMObject* full_member = nullptr) { + void add_member(osmium::item_type type, object_id_type ref, const char* role, const size_t role_length, const osmium::OSMObject* full_member = nullptr) { osmium::RelationMember* member = reserve_space_for(); new (member) osmium::RelationMember(ref, type, full_member != nullptr); add_size(sizeof(RelationMember)); @@ -210,9 +242,10 @@ namespace osmium { * @param full_member Optional pointer to the member object. If it * is available a copy will be added to the * relation. + * @throws std:length_error If role is longer than osmium::max_osm_string_length */ void add_member(osmium::item_type type, object_id_type ref, const char* role, const osmium::OSMObject* full_member = nullptr) { - add_member(type, ref, role, strlen(role), full_member); + add_member(type, ref, role, std::strlen(role), full_member); } /** @@ -224,6 +257,7 @@ namespace osmium { * @param full_member Optional pointer to the member object. If it * is available a copy will be added to the * relation. + * @throws std:length_error If role is longer than osmium::max_osm_string_length */ void add_member(osmium::item_type type, object_id_type ref, const std::string& role, const osmium::OSMObject* full_member = nullptr) { add_member(type, ref, role.data(), role.size(), full_member); @@ -231,7 +265,65 @@ namespace osmium { }; // class RelationMemberListBuilder - template + class ChangesetDiscussionBuilder : public ObjectBuilder { + + osmium::ChangesetComment* m_comment = nullptr; + + void add_user(osmium::ChangesetComment& comment, const char* user, const size_t length) { + if (length > osmium::max_osm_string_length) { + throw std::length_error("OSM user name is too long"); + } + comment.set_user_size(osmium::string_size_type(length) + 1); + add_size(append(user, osmium::memory::item_size_type(length)) + append_zero()); + } + + void add_text(osmium::ChangesetComment& comment, const char* text, const size_t length) { + // XXX There is no limit on the length of a comment text. We + // limit it here to 2^16-2 characters, because that's all that + // will fit into our internal data structure. This is not ideal, + // and will have to be discussed and cleared up. + if (length > std::numeric_limits::max() - 1) { + throw std::length_error("OSM changeset comment is too long"); + } + comment.set_text_size(osmium::string_size_type(length) + 1); + add_size(append(text, osmium::memory::item_size_type(length)) + append_zero()); + add_padding(true); + } + + public: + + explicit ChangesetDiscussionBuilder(osmium::memory::Buffer& buffer, Builder* parent = nullptr) : + ObjectBuilder(buffer, parent) { + } + + ~ChangesetDiscussionBuilder() { + assert(!m_comment && "You have to always call both add_comment() and then add_comment_text() in that order for each comment!"); + add_padding(); + } + + void add_comment(osmium::Timestamp date, osmium::user_id_type uid, const char* user) { + assert(!m_comment && "You have to always call both add_comment() and then add_comment_text() in that order for each comment!"); + m_comment = reserve_space_for(); + new (m_comment) osmium::ChangesetComment(date, uid); + add_size(sizeof(ChangesetComment)); + add_user(*m_comment, user, std::strlen(user)); + } + + void add_comment_text(const char* text) { + assert(m_comment && "You have to always call both add_comment() and then add_comment_text() in that order for each comment!"); + add_text(*m_comment, text, std::strlen(text)); + m_comment = nullptr; + } + + void add_comment_text(const std::string& text) { + assert(m_comment && "You have to always call both add_comment() and then add_comment_text() in that order for each comment!"); + add_text(*m_comment, text.c_str(), text.size()); + m_comment = nullptr; + } + + }; // class ChangesetDiscussionBuilder + + template class OSMObjectBuilder : public ObjectBuilder { public: diff --git a/include/osmium/diff_handler.hpp b/include/osmium/diff_handler.hpp index 4f9b3a1a0..06d8a93ed 100644 --- a/include/osmium/diff_handler.hpp +++ b/include/osmium/diff_handler.hpp @@ -46,8 +46,7 @@ namespace osmium { public: - DiffHandler() { - } + DiffHandler() = default; void node(const osmium::DiffNode&) const { } diff --git a/include/osmium/diff_iterator.hpp b/include/osmium/diff_iterator.hpp index 0ddf7ff7a..6725fecc8 100644 --- a/include/osmium/diff_iterator.hpp +++ b/include/osmium/diff_iterator.hpp @@ -43,7 +43,12 @@ namespace osmium { class OSMObject; - template + /** + * An input iterator wrapping any iterator over OSMObjects. When + * dereferenced it will yield DiffObject objects pointing to the + * underlying OSMObjects. + */ + template class DiffIterator : public std::iterator { static_assert(std::is_base_of::value, "TBasicIterator::value_type must derive from osmium::OSMObject"); @@ -56,37 +61,29 @@ namespace osmium { mutable osmium::DiffObject m_diff; - void set_diff() const { + void set_diff() const noexcept { assert(m_curr != m_end); - TBasicIterator prev = m_prev; - if (prev->type() != m_curr->type() || prev->id() != m_curr->id()) { - prev = m_curr; - } + bool use_curr_for_prev = m_prev->type() != m_curr->type() || m_prev->id() != m_curr->id(); + bool use_curr_for_next = m_next == m_end || m_next->type() != m_curr->type() || m_next->id() != m_curr->id(); - TBasicIterator next = m_next; - if (next == m_end || next->type() != m_curr->type() || next->id() != m_curr->id()) { - next = m_curr; - } - - m_diff = osmium::DiffObject(*prev, *m_curr, *next); + m_diff = std::move(osmium::DiffObject{ + *(use_curr_for_prev ? m_curr : m_prev), + *m_curr, + *(use_curr_for_next ? m_curr : m_next) + }); } public: - explicit DiffIterator(TBasicIterator begin, TBasicIterator end) : + DiffIterator(TBasicIterator begin, TBasicIterator end) : m_prev(begin), m_curr(begin), m_next(begin == end ? begin : ++begin), - m_end(end) { + m_end(std::move(end)), + m_diff() { } - DiffIterator(const DiffIterator&) = default; - DiffIterator& operator=(const DiffIterator&) = default; - - DiffIterator(DiffIterator&&) = default; - DiffIterator& operator=(DiffIterator&&) = default; - DiffIterator& operator++() { m_prev = std::move(m_curr); m_curr = m_next; @@ -104,26 +101,35 @@ namespace osmium { return tmp; } - bool operator==(const DiffIterator& rhs) const { + bool operator==(const DiffIterator& rhs) const noexcept { return m_curr == rhs.m_curr && m_end == rhs.m_end; } - bool operator!=(const DiffIterator& rhs) const { + bool operator!=(const DiffIterator& rhs) const noexcept { return !(*this == rhs); } - reference operator*() const { + reference operator*() const noexcept { set_diff(); return m_diff; } - pointer operator->() const { + pointer operator->() const noexcept { set_diff(); return &m_diff; } }; // class DiffIterator + /** + * Create a DiffIterator based on the given iterators. + */ + template + inline DiffIterator make_diff_iterator(TBasicIterator begin, + TBasicIterator end) { + return DiffIterator{begin, end}; + } + } // namespace osmium #endif // OSMIUM_DIFF_ITERATOR_HPP diff --git a/include/osmium/diff_visitor.hpp b/include/osmium/diff_visitor.hpp index 5e72a7bb7..ac16a8ed4 100644 --- a/include/osmium/diff_visitor.hpp +++ b/include/osmium/diff_visitor.hpp @@ -43,7 +43,7 @@ namespace osmium { namespace detail { - template + template inline void apply_diff_iterator_recurse(const osmium::DiffObject& diff, THandler& handler) { switch (diff.type()) { case osmium::item_type::node: @@ -60,7 +60,7 @@ namespace osmium { } } - template + template inline void apply_diff_iterator_recurse(const osmium::DiffObject& diff, THandler& handler, TRest&... more) { apply_diff_iterator_recurse(diff, handler); apply_diff_iterator_recurse(diff, more...); @@ -68,9 +68,9 @@ namespace osmium { } // namespace detail - template + template inline void apply_diff(TIterator it, TIterator end, THandlers&... handlers) { - typedef osmium::DiffIterator diff_iterator; + using diff_iterator = osmium::DiffIterator; diff_iterator dit(it, end); diff_iterator dend(end, end); @@ -82,19 +82,19 @@ namespace osmium { class OSMObject; - template + template inline void apply_diff(TSource& source, THandlers&... handlers) { apply_diff(osmium::io::InputIterator {source}, osmium::io::InputIterator {}, handlers...); } - template + template inline void apply_diff(osmium::memory::Buffer& buffer, THandlers&... handlers) { apply_diff(buffer.begin(), buffer.end(), handlers...); } - template + template inline void apply_diff(const osmium::memory::Buffer& buffer, THandlers&... handlers) { apply_diff(buffer.cbegin(), buffer.cend(), handlers...); } diff --git a/include/osmium/dynamic_handler.hpp b/include/osmium/dynamic_handler.hpp index 9d0bd66f5..7077554ff 100644 --- a/include/osmium/dynamic_handler.hpp +++ b/include/osmium/dynamic_handler.hpp @@ -36,16 +36,11 @@ DEALINGS IN THE SOFTWARE. #include #include +#include #include namespace osmium { - class Node; - class Way; - class Relation; - class Area; - class Changeset; - namespace handler { namespace detail { @@ -83,11 +78,11 @@ namespace osmium { // to either call handler style functions or visitor style operator(). #define OSMIUM_DYNAMIC_HANDLER_DISPATCH(_name_, _type_) \ -template \ +template \ auto _name_##_dispatch(THandler& handler, const osmium::_type_& object, int) -> decltype(handler._name_(object), void()) { \ handler._name_(object); \ } \ -template \ +template \ auto _name_##_dispatch(THandler& handler, const osmium::_type_& object, long) -> decltype(handler(object), void()) { \ handler(object); \ } @@ -98,47 +93,47 @@ auto _name_##_dispatch(THandler& handler, const osmium::_type_& object, long) -> OSMIUM_DYNAMIC_HANDLER_DISPATCH(changeset, Changeset) OSMIUM_DYNAMIC_HANDLER_DISPATCH(area, Area) - template + template auto flush_dispatch(THandler& handler, int) -> decltype(handler.flush(), void()) { handler.flush(); } - template + template void flush_dispatch(THandler&, long) {} - template + template class HandlerWrapper : public HandlerWrapperBase { THandler m_handler; public: - template + template HandlerWrapper(TArgs&&... args) : m_handler(std::forward(args)...) { } - void node(const osmium::Node& node) override final { + void node(const osmium::Node& node) final { node_dispatch(m_handler, node, 0); } - void way(const osmium::Way& way) override final { + void way(const osmium::Way& way) final { way_dispatch(m_handler, way, 0); } - void relation(const osmium::Relation& relation) override final { + void relation(const osmium::Relation& relation) final { relation_dispatch(m_handler, relation, 0); } - void area(const osmium::Area& area) override final { + void area(const osmium::Area& area) final { area_dispatch(m_handler, area, 0); } - void changeset(const osmium::Changeset& changeset) override final { + void changeset(const osmium::Changeset& changeset) final { changeset_dispatch(m_handler, changeset, 0); } - void flush() override final { + void flush() final { flush_dispatch(m_handler, 0); } @@ -157,7 +152,7 @@ auto _name_##_dispatch(THandler& handler, const osmium::_type_& object, long) -> m_impl(impl_ptr(new osmium::handler::detail::HandlerWrapperBase)) { } - template + template void set(TArgs&&... args) { m_impl = impl_ptr(new osmium::handler::detail::HandlerWrapper(std::forward(args)...)); } @@ -188,7 +183,7 @@ auto _name_##_dispatch(THandler& handler, const osmium::_type_& object, long) -> }; // class DynamicHandler - } // namspace handler + } // namespace handler } // namespace osmium diff --git a/include/osmium/experimental/flex_reader.hpp b/include/osmium/experimental/flex_reader.hpp index f00a5ecaf..c1d235746 100644 --- a/include/osmium/experimental/flex_reader.hpp +++ b/include/osmium/experimental/flex_reader.hpp @@ -33,10 +33,18 @@ DEALINGS IN THE SOFTWARE. */ -#include -#include -#include +#include +#include + #include +#include +#include +#include +#include +#include +#include +#include +#include namespace osmium { @@ -45,7 +53,7 @@ namespace osmium { */ namespace experimental { - template + template class FlexReader { bool m_with_areas; @@ -104,7 +112,7 @@ namespace osmium { return buffer; } - osmium::io::Header header() const { + osmium::io::Header header() { return m_reader.header(); } diff --git a/include/osmium/fwd.hpp b/include/osmium/fwd.hpp new file mode 100644 index 000000000..bfcb5f57f --- /dev/null +++ b/include/osmium/fwd.hpp @@ -0,0 +1,70 @@ +#ifndef OSMIUM_FWD_HPP +#define OSMIUM_FWD_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2015 Jochen Topf 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. + +*/ + +/** + * + * @file + * + * This file contains forward declarations for commonly used Osmium classes. + * + */ + +namespace osmium { + + class Area; + class Box; + class Changeset; + class ChangesetComment; + class ChangesetDiscussion; + class InnerRing; + class Location; + class Node; + class NodeRef; + class NodeRefList; + class OSMEntity; + class OSMObject; + class OuterRing; + class Relation; + class RelationMemberList; + class Segment; + class Tag; + class TagList; + class Timestamp; + class Way; + class WayNodeList; + +} // namespace osmium + +#endif // OSMIUM_FWD_HPP diff --git a/include/osmium/geom/coordinates.hpp b/include/osmium/geom/coordinates.hpp index 2bad57e0d..6544e68aa 100644 --- a/include/osmium/geom/coordinates.hpp +++ b/include/osmium/geom/coordinates.hpp @@ -33,7 +33,6 @@ DEALINGS IN THE SOFTWARE. */ -#include #include #include diff --git a/include/osmium/geom/factory.hpp b/include/osmium/geom/factory.hpp index 9be050d25..19375806b 100644 --- a/include/osmium/geom/factory.hpp +++ b/include/osmium/geom/factory.hpp @@ -61,7 +61,7 @@ namespace osmium { public: - geometry_error(const std::string& message, const char* object_type = "", osmium::object_id_type id = 0) : + explicit geometry_error(const std::string& message, const char* object_type = "", osmium::object_id_type id = 0) : std::runtime_error(message), m_message(message), m_id(id) { @@ -89,7 +89,7 @@ namespace osmium { return m_id; } - virtual const char* what() const noexcept override { + const char* what() const noexcept override { return m_message.c_str(); } @@ -142,7 +142,7 @@ namespace osmium { /** * Geometry factory. */ - template + template class GeometryFactory { /** @@ -166,8 +166,8 @@ namespace osmium { /** * Constructor for default initialized projection. */ - template - GeometryFactory(TArgs&&... args) : + template + explicit GeometryFactory(TArgs&&... args) : m_projection(), m_impl(std::forward(args)...) { } @@ -176,12 +176,13 @@ namespace osmium { * Constructor for explicitly initialized projection. Note that the * projection is moved into the GeometryFactory. */ - template - GeometryFactory(TProjection&& projection, TArgs&&... args) : + template + explicit GeometryFactory(TProjection&& projection, TArgs&&... args) : m_projection(std::move(projection)), m_impl(std::forward(args)...) { } + typedef TProjection projection_type; typedef typename TGeomImpl::point_type point_type; typedef typename TGeomImpl::linestring_type linestring_type; typedef typename TGeomImpl::polygon_type polygon_type; @@ -198,7 +199,7 @@ namespace osmium { /* Point */ - point_type create_point(const osmium::Location location) const { + point_type create_point(const osmium::Location& location) const { return m_impl.make_point(m_projection(location)); } @@ -226,7 +227,7 @@ namespace osmium { m_impl.linestring_start(); } - template + template size_t fill_linestring(TIter it, TIter end) { size_t num_points = 0; for (; it != end; ++it, ++num_points) { @@ -235,7 +236,7 @@ namespace osmium { return num_points; } - template + template size_t fill_linestring_unique(TIter it, TIter end) { size_t num_points = 0; osmium::Location last_location; @@ -300,7 +301,7 @@ namespace osmium { m_impl.polygon_start(); } - template + template size_t fill_polygon(TIter it, TIter end) { size_t num_points = 0; for (; it != end; ++it, ++num_points) { @@ -309,7 +310,7 @@ namespace osmium { return num_points; } - template + template size_t fill_polygon_unique(TIter it, TIter end) { size_t num_points = 0; osmium::Location last_location; diff --git a/include/osmium/geom/geojson.hpp b/include/osmium/geom/geojson.hpp index 7d5953535..e5b5a9cfc 100644 --- a/include/osmium/geom/geojson.hpp +++ b/include/osmium/geom/geojson.hpp @@ -88,7 +88,10 @@ namespace osmium { linestring_type linestring_finish(size_t /* num_points */) { assert(!m_str.empty()); std::string str; - std::swap(str, m_str); + + using std::swap; + swap(str, m_str); + str.back() = ']'; str += "}"; return str; @@ -134,7 +137,10 @@ namespace osmium { multipolygon_type multipolygon_finish() { assert(!m_str.empty()); std::string str; - std::swap(str, m_str); + + using std::swap; + swap(str, m_str); + str.back() = ']'; str += "}"; return str; @@ -144,7 +150,7 @@ namespace osmium { } // namespace detail - template + template using GeoJSONFactory = GeometryFactory; } // namespace geom diff --git a/include/osmium/geom/geos.hpp b/include/osmium/geom/geos.hpp index 771b08736..49b1fd7c0 100644 --- a/include/osmium/geom/geos.hpp +++ b/include/osmium/geom/geos.hpp @@ -228,7 +228,7 @@ namespace osmium { } // namespace detail - template + template using GEOSFactory = GeometryFactory; } // namespace geom diff --git a/include/osmium/geom/ogr.hpp b/include/osmium/geom/ogr.hpp index f33971c7d..4d5995cf7 100644 --- a/include/osmium/geom/ogr.hpp +++ b/include/osmium/geom/ogr.hpp @@ -47,35 +47,7 @@ DEALINGS IN THE SOFTWARE. #include #include -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable : 4458) -# pragma warning(disable : 4251) -#else -# pragma GCC diagnostic push -# ifdef __clang__ -# pragma GCC diagnostic ignored "-Wdocumentation-unknown-command" -# endif -# pragma GCC diagnostic ignored "-Wfloat-equal" -# pragma GCC diagnostic ignored "-Wold-style-cast" -# pragma GCC diagnostic ignored "-Wpadded" -# pragma GCC diagnostic ignored "-Wredundant-decls" -# pragma GCC diagnostic ignored "-Wshadow" -#endif - -/* Strictly speaking the following include would be enough here, - but everybody using this file will very likely need the other includes, - so we are adding them here, so that not everybody will need all those - pragmas to disable warnings. */ -//#include -#include -#include - -#ifdef _MSC_VER -# pragma warning(pop) -#else -# pragma GCC diagnostic pop -#endif +#include #include #include @@ -196,7 +168,7 @@ namespace osmium { } // namespace detail - template + template using OGRFactory = GeometryFactory; } // namespace geom diff --git a/include/osmium/geom/rapid_geojson.hpp b/include/osmium/geom/rapid_geojson.hpp index a3d46870c..87e479bf1 100644 --- a/include/osmium/geom/rapid_geojson.hpp +++ b/include/osmium/geom/rapid_geojson.hpp @@ -46,7 +46,7 @@ namespace osmium { * A geometry factory implementation that can be used with the * RapidJSON (https://github.com/miloyip/rapidjson) JSON writer. */ - template + template class RapidGeoJSONFactoryImpl { TWriter* m_writer; @@ -180,7 +180,7 @@ namespace osmium { } // namespace detail - template + template using RapidGeoJSONFactory = GeometryFactory, TProjection>; } // namespace geom diff --git a/include/osmium/geom/tile.hpp b/include/osmium/geom/tile.hpp index 9cd0b282b..6ca068262 100644 --- a/include/osmium/geom/tile.hpp +++ b/include/osmium/geom/tile.hpp @@ -67,10 +67,10 @@ namespace osmium { explicit Tile(uint32_t zoom, const osmium::Location& location) : z(zoom) { osmium::geom::Coordinates c = lonlat_to_mercator(location); - const int32_t n = 1LL << zoom; + const int32_t n = 1 << zoom; const double scale = detail::max_coordinate_epsg3857 * 2 / n; - x = detail::restrict_to_range((c.x + detail::max_coordinate_epsg3857) / scale, 0, n-1); - y = detail::restrict_to_range((detail::max_coordinate_epsg3857 - c.y) / scale, 0, n-1); + x = uint32_t(detail::restrict_to_range(int32_t((c.x + detail::max_coordinate_epsg3857) / scale), 0, n-1)); + y = uint32_t(detail::restrict_to_range(int32_t((detail::max_coordinate_epsg3857 - c.y) / scale), 0, n-1)); } }; // struct Tile diff --git a/include/osmium/geom/wkb.hpp b/include/osmium/geom/wkb.hpp index a290c02d0..49833e66b 100644 --- a/include/osmium/geom/wkb.hpp +++ b/include/osmium/geom/wkb.hpp @@ -188,7 +188,9 @@ namespace osmium { linestring_type linestring_finish(size_t num_points) { set_size(m_linestring_size_offset, num_points); std::string data; - std::swap(data, m_data); + + using std::swap; + swap(data, m_data); if (m_out_type == out_type::hex) { return convert_to_hex(data); @@ -246,7 +248,9 @@ namespace osmium { multipolygon_type multipolygon_finish() { set_size(m_multipolygon_size_offset, m_polygons); std::string data; - std::swap(data, m_data); + + using std::swap; + swap(data, m_data); if (m_out_type == out_type::hex) { return convert_to_hex(data); @@ -259,7 +263,7 @@ namespace osmium { } // namespace detail - template + template using WKBFactory = GeometryFactory; } // namespace geom diff --git a/include/osmium/geom/wkt.hpp b/include/osmium/geom/wkt.hpp index 4fea96baa..9cf5371a9 100644 --- a/include/osmium/geom/wkt.hpp +++ b/include/osmium/geom/wkt.hpp @@ -86,7 +86,10 @@ namespace osmium { linestring_type linestring_finish(size_t /* num_points */) { assert(!m_str.empty()); std::string str; - std::swap(str, m_str); + + using std::swap; + swap(str, m_str); + str.back() = ')'; return str; } @@ -131,7 +134,10 @@ namespace osmium { multipolygon_type multipolygon_finish() { assert(!m_str.empty()); std::string str; - std::swap(str, m_str); + + using std::swap; + swap(str, m_str); + str.back() = ')'; return str; } @@ -140,7 +146,7 @@ namespace osmium { } // namespace detail - template + template using WKTFactory = GeometryFactory; } // namespace geom diff --git a/include/osmium/handler.hpp b/include/osmium/handler.hpp index 34d878511..47e997efc 100644 --- a/include/osmium/handler.hpp +++ b/include/osmium/handler.hpp @@ -33,19 +33,9 @@ DEALINGS IN THE SOFTWARE. */ -namespace osmium { +#include - class OSMObject; - class Node; - class Way; - class Relation; - class Area; - class Changeset; - class TagList; - class WayNodeList; - class RelationMemberList; - class OuterRing; - class InnerRing; +namespace osmium { /** * @brief Osmium handlers provide callbacks for OSM objects @@ -89,12 +79,15 @@ namespace osmium { void inner_ring(const osmium::InnerRing&) const { } + void changeset_discussion(const osmium::ChangesetDiscussion&) const { + } + void flush() const { } }; // class Handler - } // namspace handler + } // namespace handler } // namespace osmium diff --git a/include/osmium/handler/chain.hpp b/include/osmium/handler/chain.hpp index 1af3962fd..4f3291ca6 100644 --- a/include/osmium/handler/chain.hpp +++ b/include/osmium/handler/chain.hpp @@ -38,14 +38,14 @@ DEALINGS IN THE SOFTWARE. #include #define OSMIUM_CHAIN_HANDLER_CALL(_func_, _type_) \ - template \ + template \ struct call_ ## _func_ { \ void operator()(THandlers& handlers, osmium::_type_& object) { \ std::get(handlers)._func_(object); \ call_ ## _func_()(handlers, object); \ } \ }; \ - template \ + template \ struct call_ ## _func_ { \ void operator()(THandlers&, osmium::_type_&) {} \ }; @@ -64,13 +64,13 @@ namespace osmium { * This handler allows chaining of any number of handlers into a single * handler. */ - template + template class ChainHandler : public osmium::handler::Handler { typedef std::tuple handlers_type; handlers_type m_handlers; - template + template struct call_flush { void operator()(THandlers& handlers) { std::get(handlers).flush(); @@ -78,7 +78,7 @@ namespace osmium { } }; // struct call_flush - template + template struct call_flush { void operator()(THandlers&) {} }; // struct call_flush diff --git a/include/osmium/handler/node_locations_for_ways.hpp b/include/osmium/handler/node_locations_for_ways.hpp index 9b9fcbf3f..8d31310c3 100644 --- a/include/osmium/handler/node_locations_for_ways.hpp +++ b/include/osmium/handler/node_locations_for_ways.hpp @@ -60,7 +60,7 @@ namespace osmium { * get(id) methods. * @tparam TStorageNegIDs Same but for negative IDs. */ - template + template class NodeLocationsForWays : public osmium::handler::Handler { static_assert(std::is_base_of, TStoragePosIDs>::value, "Index class must be derived from osmium::index::map::Map"); diff --git a/include/osmium/index/bool_vector.hpp b/include/osmium/index/bool_vector.hpp index 94e1f7268..04850a5fc 100644 --- a/include/osmium/index/bool_vector.hpp +++ b/include/osmium/index/bool_vector.hpp @@ -56,11 +56,13 @@ namespace osmium { public: BoolVector() = default; + BoolVector(const BoolVector&) = default; BoolVector(BoolVector&&) = default; BoolVector& operator=(const BoolVector&) = default; BoolVector& operator=(BoolVector&&) = default; - ~BoolVector() = default; + + ~BoolVector() noexcept = default; void set(T id, bool value = true) { if (m_bits.size() <= id) { diff --git a/include/osmium/index/detail/create_map_with_fd.hpp b/include/osmium/index/detail/create_map_with_fd.hpp index 5ccbfc809..a2e6b768a 100644 --- a/include/osmium/index/detail/create_map_with_fd.hpp +++ b/include/osmium/index/detail/create_map_with_fd.hpp @@ -47,19 +47,18 @@ namespace osmium { namespace detail { - template + template inline T* create_map_with_fd(const std::vector& config) { if (config.size() == 1) { return new T(); - } else { - assert(config.size() > 1); - const std::string& filename = config[1]; - int fd = ::open(filename.c_str(), O_CREAT | O_RDWR, 0644); - if (fd == -1) { - throw std::runtime_error(std::string("can't open file '") + filename + "': " + strerror(errno)); - } - return new T(fd); } + assert(config.size() > 1); + const std::string& filename = config[1]; + int fd = ::open(filename.c_str(), O_CREAT | O_RDWR, 0644); + if (fd == -1) { + throw std::runtime_error(std::string("can't open file '") + filename + "': " + strerror(errno)); + } + return new T(fd); } } // namespace detail diff --git a/include/osmium/index/detail/mmap_vector_anon.hpp b/include/osmium/index/detail/mmap_vector_anon.hpp index fc016261e..12a18036b 100644 --- a/include/osmium/index/detail/mmap_vector_anon.hpp +++ b/include/osmium/index/detail/mmap_vector_anon.hpp @@ -54,6 +54,8 @@ namespace osmium { mmap_vector_base() { } + ~mmap_vector_anon() noexcept = default; + }; // class mmap_vector_anon } // namespace detail diff --git a/include/osmium/index/detail/mmap_vector_base.hpp b/include/osmium/index/detail/mmap_vector_base.hpp index 9b6476812..e5f28e9b9 100644 --- a/include/osmium/index/detail/mmap_vector_base.hpp +++ b/include/osmium/index/detail/mmap_vector_base.hpp @@ -60,7 +60,7 @@ namespace osmium { public: - explicit mmap_vector_base(int fd, size_t capacity, size_t size = 0) : + mmap_vector_base(int fd, size_t capacity, size_t size = 0) : m_size(size), m_mapping(capacity, osmium::util::MemoryMapping::mapping_mode::write_shared, fd) { } @@ -70,6 +70,8 @@ namespace osmium { m_mapping(capacity) { } + ~mmap_vector_base() noexcept = default; + typedef T value_type; typedef T& reference; typedef const T& const_reference; @@ -78,8 +80,6 @@ namespace osmium { typedef T* iterator; typedef const T* const_iterator; - ~mmap_vector_base() = default; - void close() { m_mapping.unmap(); } diff --git a/include/osmium/index/detail/mmap_vector_file.hpp b/include/osmium/index/detail/mmap_vector_file.hpp index 1dadbcb45..54ef5137e 100644 --- a/include/osmium/index/detail/mmap_vector_file.hpp +++ b/include/osmium/index/detail/mmap_vector_file.hpp @@ -50,17 +50,21 @@ namespace osmium { public: - explicit mmap_vector_file() : mmap_vector_base( + mmap_vector_file() : + mmap_vector_base( osmium::detail::create_tmp_file(), osmium::detail::mmap_vector_size_increment) { } - explicit mmap_vector_file(int fd) : mmap_vector_base( + explicit mmap_vector_file(int fd) : + mmap_vector_base( fd, osmium::util::file_size(fd) / sizeof(T), osmium::util::file_size(fd) / sizeof(T)) { } + ~mmap_vector_file() noexcept = default; + }; // class mmap_vector_file } // namespace detail diff --git a/include/osmium/index/detail/vector_map.hpp b/include/osmium/index/detail/vector_map.hpp index 9c1cf4ed8..2a13061e2 100644 --- a/include/osmium/index/detail/vector_map.hpp +++ b/include/osmium/index/detail/vector_map.hpp @@ -48,7 +48,7 @@ namespace osmium { namespace map { - template + template class VectorBasedDenseMap : public Map { TVector m_vector; @@ -68,20 +68,20 @@ namespace osmium { m_vector(fd) { } - ~VectorBasedDenseMap() = default; + ~VectorBasedDenseMap() noexcept final = default; - void reserve(const size_t size) override final { + void reserve(const size_t size) final { m_vector.reserve(size); } - void set(const TId id, const TValue value) override final { + void set(const TId id, const TValue value) final { if (size() <= id) { m_vector.resize(id+1); } m_vector[id] = value; } - const TValue get(const TId id) const override final { + const TValue get(const TId id) const final { try { const TValue& value = m_vector.at(id); if (value == osmium::index::empty_value()) { @@ -93,7 +93,7 @@ namespace osmium { } } - size_t size() const override final { + size_t size() const final { return m_vector.size(); } @@ -101,16 +101,16 @@ namespace osmium { return m_vector.size() * sizeof(element_type); } - size_t used_memory() const override final { + size_t used_memory() const final { return sizeof(TValue) * size(); } - void clear() override final { + void clear() final { m_vector.clear(); m_vector.shrink_to_fit(); } - void dump_as_array(const int fd) override final { + void dump_as_array(const int fd) final { osmium::io::detail::reliable_write(fd, reinterpret_cast(m_vector.data()), byte_size()); } @@ -161,17 +161,17 @@ namespace osmium { m_vector() { } - VectorBasedSparseMap(int fd) : + explicit VectorBasedSparseMap(int fd) : m_vector(fd) { } - ~VectorBasedSparseMap() override final = default; + ~VectorBasedSparseMap() final = default; - void set(const TId id, const TValue value) override final { + void set(const TId id, const TValue value) final { m_vector.push_back(element_type(id, value)); } - const TValue get(const TId id) const override final { + const TValue get(const TId id) const final { const element_type element { id, osmium::index::empty_value() @@ -186,7 +186,7 @@ namespace osmium { } } - size_t size() const override final { + size_t size() const final { return m_vector.size(); } @@ -194,20 +194,20 @@ namespace osmium { return m_vector.size() * sizeof(element_type); } - size_t used_memory() const override final { + size_t used_memory() const final { return sizeof(element_type) * size(); } - void clear() override final { + void clear() final { m_vector.clear(); m_vector.shrink_to_fit(); } - void sort() override final { + void sort() final { std::sort(m_vector.begin(), m_vector.end()); } - void dump_as_list(const int fd) override final { + void dump_as_list(const int fd) final { osmium::io::detail::reliable_write(fd, reinterpret_cast(m_vector.data()), byte_size()); } diff --git a/include/osmium/index/detail/vector_multimap.hpp b/include/osmium/index/detail/vector_multimap.hpp index 1d875fcba..789fc9499 100644 --- a/include/osmium/index/detail/vector_multimap.hpp +++ b/include/osmium/index/detail/vector_multimap.hpp @@ -75,9 +75,9 @@ namespace osmium { m_vector(fd) { } - ~VectorBasedSparseMultimap() = default; + ~VectorBasedSparseMultimap() noexcept final = default; - void set(const TId id, const TValue value) override final { + void set(const TId id, const TValue value) final { m_vector.push_back(element_type(id, value)); } @@ -105,7 +105,7 @@ namespace osmium { }); } - size_t size() const override final { + size_t size() const final { return m_vector.size(); } @@ -113,16 +113,16 @@ namespace osmium { return m_vector.size() * sizeof(element_type); } - size_t used_memory() const override final { + size_t used_memory() const final { return sizeof(element_type) * size(); } - void clear() override final { + void clear() final { m_vector.clear(); m_vector.shrink_to_fit(); } - void sort() override final { + void sort() final { std::sort(m_vector.begin(), m_vector.end()); } @@ -147,7 +147,7 @@ namespace osmium { ); } - void dump_as_list(const int fd) override final { + void dump_as_list(const int fd) final { osmium::io::detail::reliable_write(fd, reinterpret_cast(m_vector.data()), byte_size()); } diff --git a/include/osmium/index/index.hpp b/include/osmium/index/index.hpp index f415192d2..78c142d82 100644 --- a/include/osmium/index/index.hpp +++ b/include/osmium/index/index.hpp @@ -89,7 +89,7 @@ namespace osmium { * the full range, so the max value is a good "empty" value. */ template <> - inline OSMIUM_CONSTEXPR size_t empty_value() { + inline constexpr size_t empty_value() { return std::numeric_limits::max(); } diff --git a/include/osmium/index/map.hpp b/include/osmium/index/map.hpp index 61af672cd..68a9c201c 100644 --- a/include/osmium/index/map.hpp +++ b/include/osmium/index/map.hpp @@ -84,7 +84,8 @@ namespace osmium { template class Map { - static_assert(std::is_integral::value && std::is_unsigned::value, "TId template parameter for class Map must be unsigned integral type"); + static_assert(std::is_integral::value && std::is_unsigned::value, + "TId template parameter for class Map must be unsigned integral type"); Map(const Map&) = delete; Map& operator=(const Map&) = delete; @@ -104,7 +105,7 @@ namespace osmium { Map() = default; - virtual ~Map() = default; + virtual ~Map() noexcept = default; virtual void reserve(const size_t) { // default implementation is empty @@ -147,10 +148,16 @@ namespace osmium { // default implementation is empty } + // This function could usually be const in derived classes, + // but not always. It could, for instance, sort internal data. + // This is why it is not declared const here. virtual void dump_as_list(const int /*fd*/) { throw std::runtime_error("can't dump as list"); } + // This function could usually be const in derived classes, + // but not always. It could, for instance, sort internal data. + // This is why it is not declared const here. virtual void dump_as_array(const int /*fd*/) { throw std::runtime_error("can't dump as array"); } @@ -252,12 +259,14 @@ namespace osmium { #define OSMIUM_CONCATENATE_DETAIL_(x, y) x##y #define OSMIUM_CONCATENATE_(x, y) OSMIUM_CONCATENATE_DETAIL_(x, y) -#define OSMIUM_MAKE_UNIQUE_(x) OSMIUM_CONCATENATE_(x, __COUNTER__) #define REGISTER_MAP(id, value, klass, name) \ -namespace { \ - const bool OSMIUM_MAKE_UNIQUE_(registered_index_map_##name) = osmium::index::register_map(#name); \ -} +namespace osmium { namespace index { namespace detail { \ + const bool OSMIUM_CONCATENATE_(registered_, name) = osmium::index::register_map(#name); \ + inline bool OSMIUM_CONCATENATE_(get_registered_, name)() noexcept { \ + return OSMIUM_CONCATENATE_(registered_, name); \ + } \ +} } } } // namespace index diff --git a/include/osmium/index/map/dummy.hpp b/include/osmium/index/map/dummy.hpp index de05d1d69..d6a360e56 100644 --- a/include/osmium/index/map/dummy.hpp +++ b/include/osmium/index/map/dummy.hpp @@ -56,25 +56,25 @@ namespace osmium { Dummy() = default; - ~Dummy() override final = default; + ~Dummy() noexcept final = default; - void set(const TId, const TValue) override final { + void set(const TId, const TValue) final { // intentionally left blank } - const TValue get(const TId id) const override final { + const TValue get(const TId id) const final { not_found_error(id); } - size_t size() const override final { + size_t size() const final { return 0; } - size_t used_memory() const override final { + size_t used_memory() const final { return 0; } - void clear() override final { + void clear() final { } }; // class Dummy diff --git a/include/osmium/index/map/sparse_mem_map.hpp b/include/osmium/index/map/sparse_mem_map.hpp index 2b9048b3b..d001b6791 100644 --- a/include/osmium/index/map/sparse_mem_map.hpp +++ b/include/osmium/index/map/sparse_mem_map.hpp @@ -71,36 +71,37 @@ namespace osmium { SparseMemMap() = default; - ~SparseMemMap() override final = default; + ~SparseMemMap() noexcept final = default; - void set(const TId id, const TValue value) override final { + void set(const TId id, const TValue value) final { m_elements[id] = value; } - const TValue get(const TId id) const override final { - try { - return m_elements.at(id); - } catch (std::out_of_range&) { + const TValue get(const TId id) const final { + auto it = m_elements.find(id); + if (it == m_elements.end()) { not_found_error(id); } + return it->second; } - size_t size() const override final { + size_t size() const noexcept final { return m_elements.size(); } - size_t used_memory() const override final { + size_t used_memory() const noexcept final { return element_size * m_elements.size(); } - void clear() override final { + void clear() final { m_elements.clear(); } - void dump_as_list(const int fd) override final { + void dump_as_list(const int fd) final { typedef typename std::map::value_type t; std::vector v; - std::copy(m_elements.begin(), m_elements.end(), std::back_inserter(v)); + v.reserve(m_elements.size()); + std::copy(m_elements.cbegin(), m_elements.cend(), std::back_inserter(v)); osmium::io::detail::reliable_write(fd, reinterpret_cast(v.data()), sizeof(t) * v.size()); } diff --git a/include/osmium/index/map/sparse_mem_table.hpp b/include/osmium/index/map/sparse_mem_table.hpp index 09ee81bbc..797a9265e 100644 --- a/include/osmium/index/map/sparse_mem_table.hpp +++ b/include/osmium/index/map/sparse_mem_table.hpp @@ -88,16 +88,16 @@ namespace osmium { m_elements(grow_size) { } - ~SparseMemTable() override final = default; + ~SparseMemTable() noexcept final = default; - void set(const TId id, const TValue value) override final { + void set(const TId id, const TValue value) final { if (id >= m_elements.size()) { m_elements.resize(id + m_grow_size); } m_elements[id] = value; } - const TValue get(const TId id) const override final { + const TValue get(const TId id) const final { if (id >= m_elements.size()) { not_found_error(id); } @@ -107,22 +107,23 @@ namespace osmium { return m_elements[id]; } - size_t size() const override final { + size_t size() const final { return m_elements.size(); } - size_t used_memory() const override final { + size_t used_memory() const final { // unused elements use 1 bit, used elements sizeof(TValue) bytes // http://google-sparsehash.googlecode.com/svn/trunk/doc/sparsetable.html return (m_elements.size() / 8) + (m_elements.num_nonempty() * sizeof(TValue)); } - void clear() override final { + void clear() final { m_elements.clear(); } - void dump_as_list(const int fd) override final { + void dump_as_list(const int fd) final { std::vector> v; + v.reserve(m_elements.size()); int n = 0; for (const TValue value : m_elements) { if (value != osmium::index::empty_value()) { diff --git a/include/osmium/index/multimap.hpp b/include/osmium/index/multimap.hpp index c817b6fb6..a7e1aadb3 100644 --- a/include/osmium/index/multimap.hpp +++ b/include/osmium/index/multimap.hpp @@ -118,7 +118,7 @@ namespace osmium { }; // class Multimap - } // namespace map + } // namespace multimap } // namespace index diff --git a/include/osmium/index/multimap/hybrid.hpp b/include/osmium/index/multimap/hybrid.hpp index ac2d96452..e13ee680f 100644 --- a/include/osmium/index/multimap/hybrid.hpp +++ b/include/osmium/index/multimap/hybrid.hpp @@ -62,16 +62,18 @@ namespace osmium { public: - explicit HybridIterator(typename main_map_type::iterator begin_main, - typename main_map_type::iterator end_main, - typename extra_map_type::iterator begin_extra, - typename extra_map_type::iterator end_extra) : + HybridIterator(typename main_map_type::iterator begin_main, + typename main_map_type::iterator end_main, + typename extra_map_type::iterator begin_extra, + typename extra_map_type::iterator end_extra) : m_begin_main(begin_main), m_end_main(end_main), m_begin_extra(begin_extra), m_end_extra(end_extra) { } + ~HybridIterator() noexcept = default; + HybridIterator& operator++() { if (m_begin_main == m_end_main) { ++m_begin_extra; @@ -134,11 +136,13 @@ namespace osmium { m_extra() { } - size_t size() const override final { + ~Hybrid() noexcept = default; + + size_t size() const final { return m_main.size() + m_extra.size(); } - size_t used_memory() const override final { + size_t used_memory() const final { return m_main.used_memory() + m_extra.used_memory(); } @@ -150,7 +154,7 @@ namespace osmium { m_main.set(id, value); } - void set(const TId id, const TValue value) override final { + void set(const TId id, const TValue value) final { m_extra.set(id, value); } @@ -175,17 +179,17 @@ namespace osmium { m_main.sort(); } - void dump_as_list(const int fd) override final { + void dump_as_list(const int fd) final { consolidate(); m_main.dump_as_list(fd); } - void clear() override final { + void clear() final { m_main.clear(); m_extra.clear(); } - void sort() override final { + void sort() final { m_main.sort(); } diff --git a/include/osmium/index/multimap/sparse_mem_multimap.hpp b/include/osmium/index/multimap/sparse_mem_multimap.hpp index 5b4715279..84cb640d9 100644 --- a/include/osmium/index/multimap/sparse_mem_multimap.hpp +++ b/include/osmium/index/multimap/sparse_mem_multimap.hpp @@ -78,13 +78,13 @@ namespace osmium { SparseMemMultimap() = default; - ~SparseMemMultimap() noexcept override final = default; + ~SparseMemMultimap() noexcept final = default; void unsorted_set(const TId id, const TValue value) { m_elements.emplace(id, value); } - void set(const TId id, const TValue value) override final { + void set(const TId id, const TValue value) final { m_elements.emplace(id, value); } @@ -114,15 +114,15 @@ namespace osmium { return m_elements.end(); } - size_t size() const override final { + size_t size() const final { return m_elements.size(); } - size_t used_memory() const override final { + size_t used_memory() const final { return element_size * m_elements.size(); } - void clear() override final { + void clear() final { m_elements.clear(); } @@ -130,12 +130,12 @@ namespace osmium { // intentionally left blank } - void dump_as_list(const int fd) override final { + void dump_as_list(const int fd) final { std::vector v; + v.reserve(m_elements.size()); for (const auto& element : m_elements) { v.emplace_back(element.first, element.second); } -// std::copy(m_elements.cbegin(), m_elements.cend(), std::back_inserter(v)); std::sort(v.begin(), v.end()); osmium::io::detail::reliable_write(fd, reinterpret_cast(v.data()), sizeof(element_type) * v.size()); } diff --git a/include/osmium/io/any_input.hpp b/include/osmium/io/any_input.hpp index d16d069a5..36f43b785 100644 --- a/include/osmium/io/any_input.hpp +++ b/include/osmium/io/any_input.hpp @@ -47,5 +47,6 @@ DEALINGS IN THE SOFTWARE. #include // IWYU pragma: export #include // IWYU pragma: export +#include // IWYU pragma: export #endif // OSMIUM_IO_ANY_INPUT_HPP diff --git a/include/osmium/io/bzip2_compression.hpp b/include/osmium/io/bzip2_compression.hpp index e961a87ab..fc0e33c53 100644 --- a/include/osmium/io/bzip2_compression.hpp +++ b/include/osmium/io/bzip2_compression.hpp @@ -55,7 +55,9 @@ DEALINGS IN THE SOFTWARE. #endif #include +#include #include +#include #include #include @@ -65,13 +67,13 @@ namespace osmium { * Exception thrown when there are problems compressing or * decompressing bzip2 files. */ - struct bzip2_error : public std::runtime_error { + struct bzip2_error : public io_error { int bzip2_error_code; int system_errno; bzip2_error(const std::string& what, int error_code) : - std::runtime_error(what), + io_error(what), bzip2_error_code(error_code), system_errno(error_code == BZ_IO_ERROR ? errno : 0) { } @@ -105,8 +107,8 @@ namespace osmium { public: - explicit Bzip2Compressor(int fd) : - Compressor(), + explicit Bzip2Compressor(int fd, fsync sync) : + Compressor(sync), m_file(fdopen(dup(fd), "wb")), m_bzerror(BZ_OK), m_bzfile(::BZ2_bzWriteOpen(&m_bzerror, m_file, 6, 0, 0)) { @@ -115,11 +117,15 @@ namespace osmium { } } - ~Bzip2Compressor() override final { - close(); + ~Bzip2Compressor() noexcept final { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. + } } - void write(const std::string& data) override final { + void write(const std::string& data) final { int error; ::BZ2_bzWrite(&error, m_bzfile, const_cast(data.data()), static_cast_with_assert(data.size())); if (error != BZ_OK && error != BZ_STREAM_END) { @@ -127,13 +133,18 @@ namespace osmium { } } - void close() override final { + void close() final { if (m_bzfile) { int error; ::BZ2_bzWriteClose(&error, m_bzfile, 0, nullptr, nullptr); m_bzfile = nullptr; if (m_file) { - fclose(m_file); + if (do_fsync()) { + osmium::io::detail::reliable_fsync(::fileno(m_file)); + } + if (fclose(m_file) != 0) { + throw std::system_error(errno, std::system_category(), "Close failed"); + } } if (error != BZ_OK) { detail::throw_bzip2_error(m_bzfile, "write close failed", error); @@ -152,7 +163,7 @@ namespace osmium { public: - Bzip2Decompressor(int fd) : + explicit Bzip2Decompressor(int fd) : Decompressor(), m_file(fdopen(dup(fd), "rb")), m_bzerror(BZ_OK), @@ -162,11 +173,15 @@ namespace osmium { } } - ~Bzip2Decompressor() override final { - close(); + ~Bzip2Decompressor() noexcept final { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. + } } - std::string read() override final { + std::string read() final { std::string buffer; if (!m_stream_end) { @@ -203,13 +218,15 @@ namespace osmium { return buffer; } - void close() override final { + void close() final { if (m_bzfile) { int error; ::BZ2_bzReadClose(&error, m_bzfile); m_bzfile = nullptr; if (m_file) { - fclose(m_file); + if (fclose(m_file) != 0) { + throw std::system_error(errno, std::system_category(), "Close failed"); + } } if (error != BZ_OK) { detail::throw_bzip2_error(m_bzfile, "read close failed", error); @@ -240,11 +257,15 @@ namespace osmium { } } - ~Bzip2BufferDecompressor() override final { - BZ2_bzDecompressEnd(&m_bzstream); + ~Bzip2BufferDecompressor() noexcept final { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. + } } - std::string read() override final { + std::string read() final { std::string output; if (m_buffer) { @@ -270,22 +291,28 @@ namespace osmium { return output; } + void close() final { + BZ2_bzDecompressEnd(&m_bzstream); + } + }; // class Bzip2BufferDecompressor - namespace { + namespace detail { -// we want the register_compression() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" + // we want the register_compression() function to run, setting + // the variable is only a side-effect, it will never be used const bool registered_bzip2_compression = osmium::io::CompressionFactory::instance().register_compression(osmium::io::file_compression::bzip2, - [](int fd) { return new osmium::io::Bzip2Compressor(fd); }, + [](int fd, fsync sync) { return new osmium::io::Bzip2Compressor(fd, sync); }, [](int fd) { return new osmium::io::Bzip2Decompressor(fd); }, [](const char* buffer, size_t size) { return new osmium::io::Bzip2BufferDecompressor(buffer, size); } ); -#pragma GCC diagnostic pop - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_bzip2_compression() noexcept { + return registered_bzip2_compression; + } + + } // namespace detail } // namespace io diff --git a/include/osmium/io/compression.hpp b/include/osmium/io/compression.hpp index 252976181..b337503ca 100644 --- a/include/osmium/io/compression.hpp +++ b/include/osmium/io/compression.hpp @@ -40,6 +40,7 @@ DEALINGS IN THE SOFTWARE. #include #include #include +#include #include #ifndef _MSC_VER @@ -49,7 +50,9 @@ DEALINGS IN THE SOFTWARE. #endif #include +#include #include +#include #include namespace osmium { @@ -58,11 +61,21 @@ namespace osmium { class Compressor { + fsync m_fsync; + + protected: + + bool do_fsync() const { + return m_fsync == fsync::yes; + } + public: - Compressor() = default; + explicit Compressor(fsync sync) : + m_fsync(sync) { + } - virtual ~Compressor() { + virtual ~Compressor() noexcept { } virtual void write(const std::string& data) = 0; @@ -85,13 +98,12 @@ namespace osmium { Decompressor(Decompressor&&) = delete; Decompressor& operator=(Decompressor&&) = delete; - virtual ~Decompressor() { + virtual ~Decompressor() noexcept { } virtual std::string read() = 0; - virtual void close() { - } + virtual void close() = 0; }; // class Decompressor @@ -106,13 +118,16 @@ namespace osmium { public: - typedef std::function create_compressor_type; + typedef std::function create_compressor_type; typedef std::function create_decompressor_type_fd; typedef std::function create_decompressor_type_buffer; private: - typedef std::map> compression_map_type; + typedef std::map> compression_map_type; compression_map_type m_callbacks; @@ -128,7 +143,7 @@ namespace osmium { std::string error_message {"Support for compression '"}; error_message += as_string(compression); error_message += "' not compiled into this binary."; - throw std::runtime_error(error_message); + throw unsupported_file_format_error(error_message); } public: @@ -144,15 +159,20 @@ namespace osmium { create_decompressor_type_fd create_decompressor_fd, create_decompressor_type_buffer create_decompressor_buffer) { - compression_map_type::value_type cc(compression, std::make_tuple(create_compressor, create_decompressor_fd, create_decompressor_buffer)); + compression_map_type::value_type cc(compression, + std::make_tuple(create_compressor, + create_decompressor_fd, + create_decompressor_buffer)); + return m_callbacks.insert(cc).second; } - std::unique_ptr create_compressor(osmium::io::file_compression compression, int fd) { + template + std::unique_ptr create_compressor(osmium::io::file_compression compression, TArgs&&... args) { auto it = m_callbacks.find(compression); if (it != m_callbacks.end()) { - return std::unique_ptr(std::get<0>(it->second)(fd)); + return std::unique_ptr(std::get<0>(it->second)(std::forward(args)...)); } error(compression); @@ -186,23 +206,31 @@ namespace osmium { public: - NoCompressor(int fd) : - Compressor(), + NoCompressor(int fd, fsync sync) : + Compressor(sync), m_fd(fd) { } - ~NoCompressor() override final { - close(); + ~NoCompressor() noexcept final { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. + } } - void write(const std::string& data) override final { + void write(const std::string& data) final { osmium::io::detail::reliable_write(m_fd, data.data(), data.size()); } - void close() override final { + void close() final { if (m_fd >= 0) { - ::close(m_fd); + int fd = m_fd; m_fd = -1; + if (do_fsync()) { + osmium::io::detail::reliable_fsync(fd); + } + osmium::io::detail::reliable_close(fd); } } @@ -216,7 +244,7 @@ namespace osmium { public: - NoDecompressor(int fd) : + explicit NoDecompressor(int fd) : Decompressor(), m_fd(fd), m_buffer(nullptr), @@ -230,11 +258,15 @@ namespace osmium { m_buffer_size(size) { } - ~NoDecompressor() override final { - close(); + ~NoDecompressor() noexcept final { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. + } } - std::string read() override final { + std::string read() final { std::string buffer; if (m_buffer) { @@ -249,35 +281,38 @@ namespace osmium { if (nread < 0) { throw std::system_error(errno, std::system_category(), "Read failed"); } - buffer.resize(nread); + buffer.resize(std::string::size_type(nread)); } return buffer; } - void close() override final { + void close() final { if (m_fd >= 0) { - ::close(m_fd); + int fd = m_fd; m_fd = -1; + osmium::io::detail::reliable_close(fd); } } }; // class NoDecompressor - namespace { + namespace detail { -// we want the register_compression() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" + // we want the register_compression() function to run, setting + // the variable is only a side-effect, it will never be used const bool registered_no_compression = osmium::io::CompressionFactory::instance().register_compression(osmium::io::file_compression::none, - [](int fd) { return new osmium::io::NoCompressor(fd); }, + [](int fd, fsync sync) { return new osmium::io::NoCompressor(fd, sync); }, [](int fd) { return new osmium::io::NoDecompressor(fd); }, [](const char* buffer, size_t size) { return new osmium::io::NoDecompressor(buffer, size); } ); -#pragma GCC diagnostic pop - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_no_compression() noexcept { + return registered_no_compression; + } + + } // namespace detail } // namespace io diff --git a/include/osmium/io/detail/debug_output_format.hpp b/include/osmium/io/detail/debug_output_format.hpp index efecc5833..f1766dea6 100644 --- a/include/osmium/io/detail/debug_output_format.hpp +++ b/include/osmium/io/detail/debug_output_format.hpp @@ -33,7 +33,6 @@ DEALINGS IN THE SOFTWARE. */ -#include #include #include #include @@ -41,14 +40,10 @@ DEALINGS IN THE SOFTWARE. #include #include #include -#include #include #include #include -#include - -#include #include #include #include @@ -87,65 +82,32 @@ namespace osmium { constexpr const char* color_white = "\x1b[37m"; constexpr const char* color_reset = "\x1b[0m"; + struct debug_output_options { + + /// Should metadata of objects be added? + bool add_metadata; + + /// Output with ANSI colors? + bool use_color; + + }; + /** * Writes out one buffer with OSM data in Debug format. */ - class DebugOutputBlock : public osmium::handler::Handler { + class DebugOutputBlock : public OutputBlock { - static constexpr size_t tmp_buffer_size = 50; + debug_output_options m_options; - std::shared_ptr m_input_buffer; - - std::shared_ptr m_out; - - char m_tmp_buffer[tmp_buffer_size+1]; - - bool m_add_metadata; - bool m_use_color; - - template - void output_formatted(const char* format, TArgs&&... args) { -#ifndef NDEBUG - int len = -#endif -#ifndef _MSC_VER - snprintf(m_tmp_buffer, tmp_buffer_size, format, std::forward(args)...); -#else - _snprintf(m_tmp_buffer, tmp_buffer_size, format, std::forward(args)...); -#endif - assert(len > 0 && static_cast(len) < tmp_buffer_size); - *m_out += m_tmp_buffer; - } + const char* m_utf8_prefix = ""; + const char* m_utf8_suffix = ""; void append_encoded_string(const char* data) { - const char* end = data + std::strlen(data); - - while (data != end) { - const char* last = data; - uint32_t c = utf8::next(data, end); - - // 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)) { - m_out->append(last, data); - } else { - write_color(color_red); - output_formatted("", c); - write_color(color_blue); - } - } + append_debug_encoded_string(*m_out, data, m_utf8_prefix, m_utf8_suffix); } void write_color(const char* color) { - if (m_use_color) { + if (m_options.use_color) { *m_out += color; } } @@ -177,15 +139,38 @@ namespace osmium { *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); + output_formatted(" %0*d: ", width, n++); + 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(); + output_formatted(" (%d)", timestamp.seconds_since_epoch()); + } else { + write_error("NOT SET"); + } + *m_out += '\n'; + } + void write_meta(const osmium::OSMObject& object) { output_formatted("%" PRId64 "\n", object.id()); - if (m_add_metadata) { + if (m_options.add_metadata) { write_fieldname("version"); output_formatted(" %d", object.version()); if (object.visible()) { @@ -196,8 +181,7 @@ namespace osmium { write_fieldname("changeset"); output_formatted("%d\n", object.changeset()); write_fieldname("timestamp"); - *m_out += object.timestamp().to_iso(); - output_formatted(" (%d)\n", object.timestamp()); + write_timestamp(object.timestamp()); write_fieldname("user"); output_formatted(" %d ", object.uid()); write_string(object.user()); @@ -211,14 +195,14 @@ namespace osmium { *m_out += padding; output_formatted(" %d\n", tags.size()); - osmium::max_op max; + osmium::max_op max; for (const auto& tag : tags) { max.update(std::strlen(tag.key())); } for (const auto& tag : tags) { *m_out += " "; write_string(tag.key()); - int spacing = max() - std::strlen(tag.key()); + auto spacing = max() - std::strlen(tag.key()); while (spacing--) { *m_out += " "; } @@ -255,12 +239,11 @@ namespace osmium { public: - explicit DebugOutputBlock(osmium::memory::Buffer&& buffer, bool add_metadata, bool use_color) : - m_input_buffer(std::make_shared(std::move(buffer))), - m_out(std::make_shared()), - m_tmp_buffer(), - m_add_metadata(add_metadata), - m_use_color(use_color) { + 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 : "") { } DebugOutputBlock(const DebugOutputBlock&) = default; @@ -269,13 +252,15 @@ namespace osmium { DebugOutputBlock(DebugOutputBlock&&) = default; DebugOutputBlock& operator=(DebugOutputBlock&&) = default; - ~DebugOutputBlock() = default; + ~DebugOutputBlock() noexcept = default; std::string operator()() { osmium::apply(m_input_buffer->cbegin(), m_input_buffer->cend(), *this); std::string out; - std::swap(out, *m_out); + using std::swap; + swap(out, *m_out); + return out; } @@ -313,7 +298,8 @@ namespace osmium { int width = int(log10(way.nodes().size())) + 1; int n = 0; for (const auto& node_ref : way.nodes()) { - output_formatted(" %0*d: %10" PRId64, width, n++, node_ref.ref()); + write_counter(width, n++); + output_formatted("%10" PRId64, node_ref.ref()); if (node_ref.location().valid()) { output_formatted(" (%.7f,%.7f)", node_ref.location().lon_without_check(), node_ref.location().lat_without_check()); } @@ -335,7 +321,7 @@ namespace osmium { int width = int(log10(relation.members().size())) + 1; int n = 0; for (const auto& member : relation.members()) { - output_formatted(" %0*d: ", width, n++); + write_counter(width, n++); *m_out += short_typename[item_type_to_nwr_index(member.type())]; output_formatted(" %10" PRId64 " ", member.ref()); write_string(member.role()); @@ -348,24 +334,26 @@ namespace osmium { void changeset(const osmium::Changeset& changeset) { write_object_type("changeset"); output_formatted("%d\n", changeset.id()); + write_fieldname("num changes"); output_formatted("%d", changeset.num_changes()); if (changeset.num_changes() == 0) { write_error(" NO CHANGES!"); } *m_out += '\n'; + write_fieldname("created at"); *m_out += ' '; - *m_out += changeset.created_at().to_iso(); - output_formatted(" (%d)\n", changeset.created_at()); + write_timestamp(changeset.created_at()); + write_fieldname("closed at"); *m_out += " "; if (changeset.closed()) { - *m_out += changeset.closed_at().to_iso(); - output_formatted(" (%d)\n", changeset.closed_at()); + write_timestamp(changeset.closed_at()); } else { write_error("OPEN!\n"); } + write_fieldname("user"); output_formatted(" %d ", changeset.uid()); write_string(changeset.user()); @@ -374,51 +362,73 @@ namespace osmium { write_box(changeset.bounds()); write_tags(changeset.tags(), " "); + if (changeset.num_comments() > 0) { + write_fieldname("comments"); + output_formatted(" %d\n", changeset.num_comments()); + + int width = int(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_formatted("%d ", comment.uid()); + write_string(comment.user()); + output_formatted("\n %*s", width, ""); + + write_comment_field("text"); + write_string(comment.text()); + *m_out += '\n'; + } + } + *m_out += '\n'; } - }; // DebugOutputBlock + }; // class DebugOutputBlock class DebugOutputFormat : public osmium::io::detail::OutputFormat { - bool m_add_metadata; - bool m_use_color; - - public: - - DebugOutputFormat(const osmium::io::File& file, data_queue_type& output_queue) : - OutputFormat(file, output_queue), - m_add_metadata(file.get("add_metadata") != "false"), - m_use_color(file.get("color") == "true") { - } - - DebugOutputFormat(const DebugOutputFormat&) = delete; - DebugOutputFormat& operator=(const DebugOutputFormat&) = delete; - - void write_buffer(osmium::memory::Buffer&& buffer) override final { - m_output_queue.push(osmium::thread::Pool::instance().submit(DebugOutputBlock{std::move(buffer), m_add_metadata, m_use_color})); - } + debug_output_options m_options; void write_fieldname(std::string& out, const char* name) { out += " "; - if (m_use_color) { + if (m_options.use_color) { out += color_cyan; } out += name; - if (m_use_color) { + if (m_options.use_color) { out += color_reset; } out += ": "; } - void write_header(const osmium::io::Header& header) override final { + public: + + DebugOutputFormat(const osmium::io::File& file, future_string_queue_type& output_queue) : + OutputFormat(output_queue), + m_options() { + m_options.add_metadata = file.is_not_false("add_metadata"); + m_options.use_color = file.is_true("color"); + } + + DebugOutputFormat(const DebugOutputFormat&) = delete; + DebugOutputFormat& operator=(const DebugOutputFormat&) = delete; + + ~DebugOutputFormat() noexcept final = default; + + void write_header(const osmium::io::Header& header) final { std::string out; - if (m_use_color) { + if (m_options.use_color) { out += color_bold; } out += "header\n"; - if (m_use_color) { + if (m_options.use_color) { out += color_reset; } @@ -445,33 +455,26 @@ namespace osmium { } out += "\n=============================================\n\n"; - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(std::move(out)); + send_to_output_queue(std::move(out)); } - void close() override final { - std::string out; - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(out); + void write_buffer(osmium::memory::Buffer&& buffer) final { + m_output_queue.push(osmium::thread::Pool::instance().submit(DebugOutputBlock{std::move(buffer), m_options})); } }; // class DebugOutputFormat - namespace { + // 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, + [](const osmium::io::File& file, future_string_queue_type& output_queue) { + return new osmium::io::detail::DebugOutputFormat(file, output_queue); + }); -// we want the register_output_format() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" - const bool registered_debug_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::debug, - [](const osmium::io::File& file, data_queue_type& output_queue) { - return new osmium::io::detail::DebugOutputFormat(file, output_queue); - }); -#pragma GCC diagnostic pop - - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_debug_output() noexcept { + return registered_debug_output; + } } // namespace detail diff --git a/include/osmium/io/detail/input_format.hpp b/include/osmium/io/detail/input_format.hpp index 03e1190c3..d26b1ee92 100644 --- a/include/osmium/io/detail/input_format.hpp +++ b/include/osmium/io/detail/input_format.hpp @@ -33,13 +33,16 @@ DEALINGS IN THE SOFTWARE. */ +#include #include +#include #include #include #include #include #include +#include #include #include #include @@ -48,106 +51,156 @@ DEALINGS IN THE SOFTWARE. namespace osmium { - namespace thread { - template class Queue; - } // namespace thread - namespace io { namespace detail { - /** - * Virtual base class for all classes reading OSM files in different - * formats. - * - * Do not use this class or derived classes directly. Use the - * osmium::io::Reader class instead. - */ - class InputFormat { + class Parser { + + future_buffer_queue_type& m_output_queue; + std::promise& m_header_promise; + queue_wrapper m_input_queue; + osmium::osm_entity_bits::type m_read_types; + bool m_header_is_done; protected: - osmium::io::File m_file; - osmium::osm_entity_bits::type m_read_which_entities; - osmium::io::Header m_header; - - explicit InputFormat(const osmium::io::File& file, osmium::osm_entity_bits::type read_which_entities) : - m_file(file), - m_read_which_entities(read_which_entities) { - m_header.set_has_multiple_object_versions(m_file.has_multiple_object_versions()); + std::string get_input() { + return m_input_queue.pop(); } - InputFormat(const InputFormat&) = delete; - InputFormat(InputFormat&&) = delete; + bool input_done() const { + return m_input_queue.has_reached_end_of_data(); + } - InputFormat& operator=(const InputFormat&) = delete; - InputFormat& operator=(InputFormat&&) = delete; + osmium::osm_entity_bits::type read_types() const { + return m_read_types; + } + + bool header_is_done() const { + 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&& future) { + m_output_queue.push(std::move(future)); + } public: - virtual ~InputFormat() { + Parser(future_string_queue_type& input_queue, + future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_types) : + m_output_queue(output_queue), + m_header_promise(header_promise), + m_input_queue(input_queue), + m_read_types(read_types), + m_header_is_done(false) { } - virtual osmium::memory::Buffer read() = 0; + Parser(const Parser&) = delete; + Parser& operator=(const Parser&) = delete; - virtual void close() { + Parser(Parser&&) = delete; + Parser& operator=(Parser&&) = delete; + + virtual ~Parser() noexcept = default; + + virtual void run() = 0; + + 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); } - virtual osmium::io::Header header() { - return m_header; - } - - }; // class InputFormat + }; // class Parser /** - * This factory class is used to create objects that read OSM data - * written in a specified format. + * This factory class is used to create objects that decode OSM + * data written in a specified format. * - * Do not use this class directly. Instead use the osmium::io::Reader - * class. + * Do not use this class directly. Use the osmium::io::Reader + * class instead. */ - class InputFormatFactory { + class ParserFactory { public: - typedef std::function&)> create_input_type; + typedef std::function< + std::unique_ptr( + future_string_queue_type&, + future_buffer_queue_type&, + std::promise& header_promise, + osmium::osm_entity_bits::type read_which_entities + ) + > create_parser_type; private: - typedef std::map map_type; + typedef std::map map_type; map_type m_callbacks; - InputFormatFactory() : + ParserFactory() : m_callbacks() { } public: - static InputFormatFactory& instance() { - static InputFormatFactory factory; + static ParserFactory& instance() { + static ParserFactory factory; return factory; } - bool register_input_format(osmium::io::file_format format, create_input_type create_function) { + bool register_parser(osmium::io::file_format format, create_parser_type create_function) { if (! m_callbacks.insert(map_type::value_type(format, create_function)).second) { return false; } return true; } - std::unique_ptr create_input(const osmium::io::File& file, osmium::osm_entity_bits::type read_which_entities, osmium::thread::Queue& input_queue) { - file.check(); - + create_parser_type get_creator_function(const osmium::io::File& file) { auto it = m_callbacks.find(file.format()); - if (it != m_callbacks.end()) { - return std::unique_ptr((it->second)(file, read_which_entities, input_queue)); + if (it == m_callbacks.end()) { + 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."); } - - throw std::runtime_error(std::string("Support for input format '") + as_string(file.format()) + "' not compiled into this binary."); + return it->second; } - }; // class InputFormatFactory + }; // class ParserFactory } // namespace detail diff --git a/include/osmium/io/detail/o5m_input_format.hpp b/include/osmium/io/detail/o5m_input_format.hpp new file mode 100644 index 000000000..0318432e8 --- /dev/null +++ b/include/osmium/io/detail/o5m_input_format.hpp @@ -0,0 +1,636 @@ +#ifndef OSMIUM_IO_DETAIL_O5M_INPUT_FORMAT_HPP +#define OSMIUM_IO_DETAIL_O5M_INPUT_FORMAT_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2015 Jochen Topf 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 +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace osmium { + + /** + * 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 http://wiki.openstreetmap.org/wiki/O5m . + + class ReferenceTable { + + // The following settings are from the o5m description: + + // The maximum number of entries in this table. + const uint64_t number_of_entries = 15000; + + // The size of one entry in the table. + const unsigned int entry_size = 256; + + // The maximum length of a string in the table including + // two \0 bytes. + const unsigned int max_length = 250 + 2; + + // 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, size_t size) { + 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"); + } + auto entry = (current_entry + number_of_entries - index) % number_of_entries; + return &m_table[entry * entry_size]; + } + + }; // class ReferenceTable + + class O5mParser : public Parser { + + static constexpr int buffer_size = 2 * 1000 * 1000; + + osmium::io::Header m_header; + + osmium::memory::Buffer m_buffer; + + 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(size_t need_bytes) { + if ((m_end - m_data) >= long(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) { + 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(header_magic), m_data, sizeof(header_magic))) { + 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::util::DeltaDecode m_delta_id; + + osmium::util::DeltaDecode m_delta_timestamp; + osmium::util::DeltaDecode m_delta_changeset; + osmium::util::DeltaDecode m_delta_lon; + osmium::util::DeltaDecode m_delta_lat; + + osmium::util::DeltaDecode m_delta_way_node_id; + osmium::util::DeltaDecode m_delta_member_ids[3]; + + 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) { + if (**dataptr == 0x00) { // get inline string + (*dataptr)++; + if (*dataptr == end) { + throw o5m_error("string format error"); + } + return *dataptr; + } else { // get from reference table + auto index = protozero::decode_varint(dataptr, end); + return m_reference_table.get(index); + } + } + + std::pair decode_user(const char** dataptr, const char* const end) { + bool update_pointer = (**dataptr == 0x00); + const char* data = decode_string(dataptr, end); + const char* start = data; + + auto uid = protozero::decode_varint(&data, end); + + 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 std::make_pair(0, ""); + } + + while (*data++) { + if (data == end) { + throw o5m_error("no null byte in user name"); + } + } + + if (update_pointer) { + m_reference_table.add(start, data - start); + *dataptr = data; + } + + return std::make_pair(static_cast_with_assert(uid), user); + } + + void decode_tags(osmium::builder::Builder* builder, const char** dataptr, const char* const end) { + osmium::builder::TagListBuilder tl_builder(m_buffer, builder); + + while(*dataptr != end) { + 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"); + } + } + + 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; + } + + tl_builder.add_tag(start, value); + } + } + + const char* decode_info(osmium::OSMObject& object, const char** dataptr, const char* const end) { + const char* user = ""; + + if (**dataptr == 0x00) { // no info section + ++*dataptr; + } else { // has info section + object.set_version(static_cast_with_assert(protozero::decode_varint(dataptr, end))); + 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) { + 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(m_buffer); + osmium::Node& node = builder.object(); + + node.set_id(m_delta_id.update(zvarint(&data, end))); + + builder.add_user(decode_info(node, &data, end)); + + if (data == end) { + // no location, object is deleted + builder.object().set_visible(false); + builder.object().set_location(osmium::Location{}); + } else { + auto lon = m_delta_lon.update(zvarint(&data, end)); + auto lat = m_delta_lat.update(zvarint(&data, end)); + builder.object().set_location(osmium::Location{lon, lat}); + + if (data != end) { + decode_tags(&builder, &data, end); + } + } + + m_buffer.commit(); + } + + void decode_way(const char* data, const char* const end) { + osmium::builder::WayBuilder builder(m_buffer); + osmium::Way& way = builder.object(); + + way.set_id(m_delta_id.update(zvarint(&data, end))); + + builder.add_user(decode_info(way, &data, end)); + + if (data == end) { + // no reference section, object is deleted + builder.object().set_visible(false); + } else { + 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(m_buffer, &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); + } + } + + m_buffer.commit(); + } + + 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 decode_role(const char** dataptr, const char* const end) { + bool update_pointer = (**dataptr == 0x00); + const char* data = decode_string(dataptr, end); + const char* start = data; + + 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 std::make_pair(member_type, role); + } + + void decode_relation(const char* data, const char* const end) { + osmium::builder::RelationBuilder builder(m_buffer); + osmium::Relation& relation = builder.object(); + + relation.set_id(m_delta_id.update(zvarint(&data, end))); + + builder.add_user(decode_info(relation, &data, end)); + + if (data == end) { + // no reference section, object is deleted + builder.object().set_visible(false); + } else { + 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(m_buffer, &builder); + + while (data < end_refs) { + auto delta_id = zvarint(&data, end); + if (data == end) { + throw o5m_error("relation member format error"); + } + auto type_role = decode_role(&data, end); + auto i = osmium::item_type_to_nwr_index(type_role.first); + 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); + } + } + + m_buffer.commit(); + } + + void decode_bbox(const char* data, const char* const end) { + auto sw_lon = zvarint(&data, end); + auto sw_lat = zvarint(&data, end); + auto ne_lon = zvarint(&data, end); + 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) { + auto timestamp = osmium::Timestamp(zvarint(&data, end)).to_iso(); + m_header.set("o5m_timestamp", timestamp); + m_header.set("timestamp", timestamp); + } + + void flush() { + osmium::memory::Buffer buffer(buffer_size); + using std::swap; + swap(m_buffer, buffer); + send_to_output_queue(std::move(buffer)); + } + + 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)) { + dataset_type ds_type = 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 (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) { + decode_node(m_data, m_data + length); + } + break; + case dataset_type::way: + mark_header_as_done(); + if (read_types() & osmium::osm_entity_bits::way) { + decode_way(m_data, m_data + length); + } + break; + case dataset_type::relation: + mark_header_as_done(); + if (read_types() & osmium::osm_entity_bits::relation) { + decode_relation(m_data, m_data + length); + } + 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; + + if (m_buffer.committed() > buffer_size / 10 * 9) { + flush(); + } + } + } + + if (m_buffer.committed()) { + flush(); + } + + mark_header_as_done(); + } + + public: + + O5mParser(future_string_queue_type& input_queue, + future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_types) : + Parser(input_queue, output_queue, header_promise, read_types), + m_header(), + m_buffer(buffer_size), + m_input(), + m_data(m_input.data()), + m_end(m_data) { + } + + ~O5mParser() noexcept final = default; + + void run() final { + 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, + [](future_string_queue_type& input_queue, + future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_which_entities) { + return std::unique_ptr(new O5mParser(input_queue, output_queue, header_promise, read_which_entities)); + }); + + // 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 diff --git a/include/osmium/io/detail/opl_output_format.hpp b/include/osmium/io/detail/opl_output_format.hpp index a3103d9bf..2d863ea82 100644 --- a/include/osmium/io/detail/opl_output_format.hpp +++ b/include/osmium/io/detail/opl_output_format.hpp @@ -33,7 +33,6 @@ DEALINGS IN THE SOFTWARE. */ -#include #include #include #include @@ -41,14 +40,10 @@ DEALINGS IN THE SOFTWARE. #include #include #include -#include #include #include #include -#include - -#include #include #include #include @@ -74,71 +69,27 @@ namespace osmium { namespace detail { + struct opl_output_options { + + /// Should metadata of objects be added? + bool add_metadata; + + }; + /** * Writes out one buffer with OSM data in OPL format. */ - class OPLOutputBlock : public osmium::handler::Handler { + class OPLOutputBlock : public OutputBlock { - static constexpr size_t tmp_buffer_size = 100; - - std::shared_ptr m_input_buffer; - - std::shared_ptr m_out; - - char m_tmp_buffer[tmp_buffer_size+1]; - - bool m_add_metadata; - - template - void output_formatted(const char* format, TArgs&&... args) { -#ifndef NDEBUG - int len = -#endif -#ifndef _MSC_VER - snprintf(m_tmp_buffer, tmp_buffer_size, format, std::forward(args)...); -#else - _snprintf(m_tmp_buffer, tmp_buffer_size, format, std::forward(args)...); -#endif - assert(len > 0 && static_cast(len) < tmp_buffer_size); - *m_out += m_tmp_buffer; - } + opl_output_options m_options; void append_encoded_string(const char* data) { - const char* end = data + std::strlen(data); - - while (data != end) { - const char* last = data; - uint32_t c = utf8::next(data, end); - - // 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)) { - m_out->append(last, data); - } else { - *m_out += '%'; - if (c <= 0xff) { - output_formatted("%02x", c); - } else { - output_formatted("%04x", c); - } - *m_out += '%'; - } - } + osmium::io::detail::append_utf8_encoded_string(*m_out, data); } void write_meta(const osmium::OSMObject& object) { output_formatted("%" PRId64, object.id()); - if (m_add_metadata) { + if (m_options.add_metadata) { output_formatted(" v%d d", object.version()); *m_out += (object.visible() ? 'V' : 'D'); output_formatted(" c%d t", object.changeset()); @@ -160,7 +111,7 @@ namespace osmium { } } - void write_location(const osmium::Location location, const char x, const char y) { + void write_location(const osmium::Location& location, const char x, const char y) { if (location) { output_formatted(" %c%.7f %c%.7f", x, location.lon_without_check(), y, location.lat_without_check()); } else { @@ -173,11 +124,9 @@ namespace osmium { public: - explicit OPLOutputBlock(osmium::memory::Buffer&& buffer, bool add_metadata) : - m_input_buffer(std::make_shared(std::move(buffer))), - m_out(std::make_shared()), - m_tmp_buffer(), - m_add_metadata(add_metadata) { + OPLOutputBlock(osmium::memory::Buffer&& buffer, const opl_output_options& options) : + OutputBlock(std::move(buffer)), + m_options(options) { } OPLOutputBlock(const OPLOutputBlock&) = default; @@ -186,13 +135,15 @@ namespace osmium { OPLOutputBlock(OPLOutputBlock&&) = default; OPLOutputBlock& operator=(OPLOutputBlock&&) = default; - ~OPLOutputBlock() = default; + ~OPLOutputBlock() noexcept = default; std::string operator()() { osmium::apply(m_input_buffer->cbegin(), m_input_buffer->cend(), *this); std::string out; - std::swap(out, *m_out); + using std::swap; + swap(out, *m_out); + return out; } @@ -244,7 +195,7 @@ namespace osmium { *m_out += changeset.created_at().to_iso(); *m_out += " e"; *m_out += changeset.closed_at().to_iso(); - output_formatted(" i%d u", changeset.uid()); + output_formatted(" d%d i%d u", changeset.num_comments(), changeset.uid()); append_encoded_string(changeset.user()); write_location(changeset.bounds().bottom_left(), 'x', 'y'); write_location(changeset.bounds().top_right(), 'X', 'Y'); @@ -264,48 +215,42 @@ namespace osmium { *m_out += '\n'; } - }; // OPLOutputBlock + }; // class OPLOutputBlock class OPLOutputFormat : public osmium::io::detail::OutputFormat { - bool m_add_metadata; + opl_output_options m_options; public: - OPLOutputFormat(const osmium::io::File& file, data_queue_type& output_queue) : - OutputFormat(file, output_queue), - m_add_metadata(file.get("add_metadata") != "false") { + OPLOutputFormat(const osmium::io::File& file, future_string_queue_type& output_queue) : + OutputFormat(output_queue), + m_options() { + m_options.add_metadata = file.is_not_false("add_metadata"); } OPLOutputFormat(const OPLOutputFormat&) = delete; OPLOutputFormat& operator=(const OPLOutputFormat&) = delete; - void write_buffer(osmium::memory::Buffer&& buffer) override final { - m_output_queue.push(osmium::thread::Pool::instance().submit(OPLOutputBlock{std::move(buffer), m_add_metadata})); - } + ~OPLOutputFormat() noexcept final = default; - void close() override final { - std::string out; - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(out); + void write_buffer(osmium::memory::Buffer&& buffer) final { + m_output_queue.push(osmium::thread::Pool::instance().submit(OPLOutputBlock{std::move(buffer), m_options})); } }; // class OPLOutputFormat - namespace { + // 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, + [](const osmium::io::File& file, future_string_queue_type& output_queue) { + return new osmium::io::detail::OPLOutputFormat(file, output_queue); + }); -// we want the register_output_format() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" - const bool registered_opl_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::opl, - [](const osmium::io::File& file, data_queue_type& output_queue) { - return new osmium::io::detail::OPLOutputFormat(file, output_queue); - }); -#pragma GCC diagnostic pop - - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_opl_output() noexcept { + return registered_opl_output; + } } // namespace detail diff --git a/include/osmium/io/detail/output_format.hpp b/include/osmium/io/detail/output_format.hpp index 529a1890f..4c38c4d1e 100644 --- a/include/osmium/io/detail/output_format.hpp +++ b/include/osmium/io/detail/output_format.hpp @@ -34,29 +34,48 @@ DEALINGS IN THE SOFTWARE. */ #include -#include #include #include #include #include #include +#include +#include +#include #include #include -#include -#include +#include namespace osmium { - namespace memory { - class Buffer; - } + namespace io { + class Header; + } // namespace io namespace io { namespace detail { - typedef osmium::thread::Queue> data_queue_type; + class OutputBlock : public osmium::handler::Handler { + + protected: + + std::shared_ptr m_input_buffer; + + std::shared_ptr m_out; + + explicit OutputBlock(osmium::memory::Buffer&& buffer) : + m_input_buffer(std::make_shared(std::move(buffer))), + m_out(std::make_shared()) { + } + + template + void output_formatted(const char* format, TArgs&&... args) { + append_printf_formatted_string(*m_out, format, std::forward(args)...); + } + + }; // class OutputBlock; /** * Virtual base class for all classes writing OSM files in different @@ -69,13 +88,19 @@ namespace osmium { protected: - osmium::io::File m_file; - data_queue_type& m_output_queue; + 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: - explicit OutputFormat(const osmium::io::File& file, data_queue_type& output_queue) : - m_file(file), + explicit OutputFormat(future_string_queue_type& output_queue) : m_output_queue(output_queue) { } @@ -85,15 +110,15 @@ namespace osmium { OutputFormat& operator=(const OutputFormat&) = delete; OutputFormat& operator=(OutputFormat&&) = delete; - virtual ~OutputFormat() { - } + virtual ~OutputFormat() noexcept = default; virtual void write_header(const osmium::io::Header&) { } virtual void write_buffer(osmium::memory::Buffer&&) = 0; - virtual void close() = 0; + virtual void write_end() { + } }; // class OutputFormat @@ -108,7 +133,7 @@ namespace osmium { public: - typedef std::function create_output_type; + typedef std::function create_output_type; private: @@ -134,15 +159,18 @@ namespace osmium { return true; } - std::unique_ptr create_output(const osmium::io::File& file, data_queue_type& output_queue) { - file.check(); - + std::unique_ptr create_output(const osmium::io::File& file, future_string_queue_type& output_queue) { auto it = m_callbacks.find(file.format()); if (it != m_callbacks.end()) { return std::unique_ptr((it->second)(file, output_queue)); } - throw std::runtime_error(std::string("Support for output format '") + as_string(file.format()) + "' not compiled into this binary."); + 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 diff --git a/include/osmium/io/detail/pbf.hpp b/include/osmium/io/detail/pbf.hpp index 15e457a12..13d552910 100644 --- a/include/osmium/io/detail/pbf.hpp +++ b/include/osmium/io/detail/pbf.hpp @@ -33,6 +33,7 @@ DEALINGS IN THE SOFTWARE. */ +#include #include // needed for htonl and ntohl @@ -53,11 +54,11 @@ namespace osmium { */ struct pbf_error : public io_error { - pbf_error(const std::string& what) : + explicit pbf_error(const std::string& what) : io_error(std::string("PBF error: ") + what) { } - pbf_error(const char* what) : + explicit pbf_error(const char* what) : io_error(std::string("PBF error: ") + what) { } @@ -79,9 +80,9 @@ namespace osmium { const int64_t resolution_convert = lonlat_resolution / osmium::Location::coordinate_precision; - } + } // namespace detail - } + } // namespace io } // namespace osmium diff --git a/include/osmium/io/detail/pbf_decoder.hpp b/include/osmium/io/detail/pbf_decoder.hpp index 79e899ff8..09e09bf02 100644 --- a/include/osmium/io/detail/pbf_decoder.hpp +++ b/include/osmium/io/detail/pbf_decoder.hpp @@ -37,8 +37,12 @@ DEALINGS IN THE SOFTWARE. #include #include #include -#include #include +#include +#include +#include +#include +#include #include @@ -62,13 +66,14 @@ namespace osmium { namespace detail { using ptr_len_type = std::pair; + using osm_string_len_type = std::pair; class PBFPrimitiveBlockDecoder { static constexpr size_t initial_buffer_size = 2 * 1024 * 1024; ptr_len_type m_data; - std::vector m_stringtable; + std::vector m_stringtable; int64_t m_lon_offset = 0; int64_t m_lat_offset = 0; @@ -86,7 +91,11 @@ namespace osmium { protozero::pbf_message pbf_string_table(data); while (pbf_string_table.next(OSMFormat::StringTable::repeated_bytes_s)) { - m_stringtable.push_back(pbf_string_table.get_data()); + auto str_len = pbf_string_table.get_data(); + if (str_len.second > osmium::max_osm_string_length) { + throw osmium::pbf_error("overlong string in string table"); + } + m_stringtable.emplace_back(str_len.first, osmium::string_size_type(str_len.second)); } } @@ -156,8 +165,8 @@ namespace osmium { } } - ptr_len_type decode_info(const ptr_len_type& data, osmium::OSMObject& object) { - ptr_len_type user = std::make_pair("", 0); + osm_string_len_type decode_info(const ptr_len_type& data, osmium::OSMObject& object) { + osm_string_len_type user = std::make_pair("", 0); protozero::pbf_message pbf_info(data); while (pbf_info.next()) { @@ -220,7 +229,7 @@ namespace osmium { } int32_t convert_pbf_coordinate(int64_t c) const { - return (c * m_granularity + m_lon_offset) / resolution_convert; + return int32_t((c * m_granularity + m_lon_offset) / resolution_convert); } void decode_node(const ptr_len_type& data) { @@ -232,7 +241,7 @@ namespace osmium { int64_t lon = std::numeric_limits::max(); int64_t lat = std::numeric_limits::max(); - ptr_len_type user = { "", 0 }; + osm_string_len_type user = { "", 0 }; protozero::pbf_message pbf_node(data); while (pbf_node.next()) { @@ -285,7 +294,7 @@ namespace osmium { kv_type vals; std::pair refs; - ptr_len_type user = { "", 0 }; + osm_string_len_type user = { "", 0 }; protozero::pbf_message pbf_way(data); while (pbf_way.next()) { @@ -334,7 +343,7 @@ namespace osmium { std::pair refs; std::pair types; - ptr_len_type user = { "", 0 }; + osm_string_len_type user = { "", 0 }; protozero::pbf_message pbf_relation(data); while (pbf_relation.next()) { @@ -512,7 +521,7 @@ namespace osmium { // this is against the spec, must have same number of elements throw osmium::pbf_error("PBF format error"); } - visible = *visibles.first++; + visible = (*visibles.first++) != 0; } node.set_visible(visible); @@ -522,10 +531,14 @@ namespace osmium { builder.add_user(""); } + // 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.first++); + const auto lat = dense_latitude.update(*lats.first++); if (visible) { builder.object().set_location(osmium::Location( - convert_pbf_coordinate(dense_longitude.update(*lons.first++)), - convert_pbf_coordinate(dense_latitude.update(*lats.first++)) + convert_pbf_coordinate(lon), + convert_pbf_coordinate(lat) )); } @@ -552,7 +565,7 @@ namespace osmium { public: - explicit PBFPrimitiveBlockDecoder(const ptr_len_type& data, osmium::osm_entity_bits::type read_types) : + PBFPrimitiveBlockDecoder(const ptr_len_type& data, osmium::osm_entity_bits::type read_types) : m_data(data), m_read_types(read_types) { } @@ -563,7 +576,7 @@ namespace osmium { PBFPrimitiveBlockDecoder(PBFPrimitiveBlockDecoder&&) = delete; PBFPrimitiveBlockDecoder& operator=(PBFPrimitiveBlockDecoder&&) = delete; - ~PBFPrimitiveBlockDecoder() = default; + ~PBFPrimitiveBlockDecoder() noexcept = default; osmium::memory::Buffer operator()() { try { @@ -579,8 +592,8 @@ namespace osmium { }; // class PBFPrimitiveBlockDecoder inline ptr_len_type decode_blob(const std::string& blob_data, std::string& output) { - int32_t raw_size; - std::pair zlib_data; + int32_t raw_size = 0; + std::pair zlib_data = {nullptr, 0}; protozero::pbf_message pbf_blob(blob_data); while (pbf_blob.next()) { @@ -609,7 +622,7 @@ namespace osmium { } } - if (zlib_data.second != 0) { + if (zlib_data.second != 0 && raw_size != 0) { return osmium::io::detail::zlib_uncompress_string( zlib_data.first, static_cast(zlib_data.second), @@ -694,7 +707,11 @@ namespace osmium { header.set("generator", pbf_header_block.get_string()); break; case OSMFormat::HeaderBlock::optional_int64_osmosis_replication_timestamp: - header.set("osmosis_replication_timestamp", osmium::Timestamp(pbf_header_block.get_int64()).to_iso()); + { + auto timestamp = osmium::Timestamp(pbf_header_block.get_int64()).to_iso(); + header.set("osmosis_replication_timestamp", timestamp); + header.set("timestamp", timestamp); + } break; case OSMFormat::HeaderBlock::optional_int64_osmosis_replication_sequence_number: header.set("osmosis_replication_sequence_number", std::to_string(pbf_header_block.get_int64())); @@ -741,7 +758,7 @@ namespace osmium { PBFDataBlobDecoder(PBFDataBlobDecoder&&) = default; PBFDataBlobDecoder& operator=(PBFDataBlobDecoder&&) = default; - ~PBFDataBlobDecoder() = default; + ~PBFDataBlobDecoder() noexcept = default; osmium::memory::Buffer operator()() { std::string output; diff --git a/include/osmium/io/detail/pbf_input_format.hpp b/include/osmium/io/detail/pbf_input_format.hpp index 7817d27d1..e9d0e71d1 100644 --- a/include/osmium/io/detail/pbf_input_format.hpp +++ b/include/osmium/io/detail/pbf_input_format.hpp @@ -34,17 +34,12 @@ DEALINGS IN THE SOFTWARE. */ #include -#include #include -#include #include #include #include -#include #include -#include #include -#include #include #include #include @@ -58,40 +53,22 @@ DEALINGS IN THE SOFTWARE. #include #include #include -#include #include -#include #include -#include #include #include #include -#include #include -#include #include namespace osmium { namespace io { - class File; - namespace detail { - /** - * Class for parsing PBF files. - */ - class PBFInputFormat : public osmium::io::detail::InputFormat { + class PBFParser : public Parser { - typedef osmium::thread::Queue> queue_type; - - bool m_use_thread_pool; - bool m_eof { false }; - queue_type m_queue; - std::atomic m_quit_input_thread; - std::thread m_reader; - osmium::thread::Queue& m_input_queue; std::string m_input_buffer; /** @@ -103,9 +80,8 @@ namespace osmium { */ std::string read_from_input_queue(size_t size) { while (m_input_buffer.size() < size) { - std::string new_data; - m_input_queue.wait_and_pop(new_data); - if (new_data.empty()) { + std::string new_data = get_input(); + if (input_done()) { throw osmium::pbf_error("truncated data (EOF encountered)"); } m_input_buffer += new_data; @@ -113,7 +89,10 @@ namespace osmium { std::string output { m_input_buffer.substr(size) }; m_input_buffer.resize(size); - std::swap(output, m_input_buffer); + + using std::swap; + swap(output, m_input_buffer); + return output; } @@ -125,7 +104,7 @@ namespace osmium { uint32_t size_in_network_byte_order; try { - std::string input_data = read_from_input_queue(sizeof(size_in_network_byte_order)); + const std::string input_data = read_from_input_queue(sizeof(size_in_network_byte_order)); size_in_network_byte_order = *reinterpret_cast(input_data.data()); } catch (osmium::pbf_error&) { return 0; // EOF @@ -174,125 +153,85 @@ namespace osmium { size_t check_type_and_get_blob_size(const char* expected_type) { assert(expected_type); - auto size = read_blob_header_size_from_file(); + const auto size = read_blob_header_size_from_file(); if (size == 0) { // EOF return 0; } - std::string blob_header = read_from_input_queue(size); + const std::string blob_header = read_from_input_queue(size); return decode_blob_header(protozero::pbf_message(blob_header), expected_type); } - void parse_osm_data(osmium::osm_entity_bits::type read_types) { - osmium::thread::set_thread_name("_osmium_pbf_in"); - - while (auto size = check_type_and_get_blob_size("OSMData")) { - std::string input_buffer = read_from_input_queue(size); - if (input_buffer.size() > max_uncompressed_blob_size) { - throw osmium::pbf_error(std::string("invalid blob size: " + std::to_string(input_buffer.size()))); - } - - if (m_use_thread_pool) { - m_queue.push(osmium::thread::Pool::instance().submit(PBFDataBlobDecoder{ std::move(input_buffer), read_types })); - } else { - std::promise promise; - m_queue.push(promise.get_future()); - PBFDataBlobDecoder data_blob_parser{ std::move(input_buffer), read_types }; - promise.set_value(data_blob_parser()); - } - - if (m_quit_input_thread) { - return; - } + 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))); } - - // Send an empty buffer to signal the reader that we are - // done. - std::promise promise; - m_queue.push(promise.get_future()); - promise.set_value(osmium::memory::Buffer{}); + return read_from_input_queue(size); } - void signal_input_thread_to_quit() { - m_quit_input_thread = true; + // Parse the header in the PBF OSMHeader blob. + void parse_header_blob() { + osmium::io::Header header; + const auto size = check_type_and_get_blob_size("OSMHeader"); + header = decode_header(read_from_input_queue_with_check(size)); + set_header_value(header); + } + + void parse_data_blobs() { + 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() }; + + if (osmium::config::use_pool_threads_for_pbf_parsing()) { + send_to_output_queue(osmium::thread::Pool::instance().submit(std::move(data_blob_parser))); + } else { + send_to_output_queue(data_blob_parser()); + } + } } public: - /** - * Instantiate PBF Parser - * - * @param file osmium::io::File instance describing file to be read from. - * @param read_which_entities Which types of OSM entities (nodes, ways, relations, changesets) should be parsed? - * @param input_queue String queue where data is read from. - */ - PBFInputFormat(const osmium::io::File& file, osmium::osm_entity_bits::type read_which_entities, osmium::thread::Queue& input_queue) : - osmium::io::detail::InputFormat(file, read_which_entities), - m_use_thread_pool(osmium::config::use_pool_threads_for_pbf_parsing()), - m_queue(20, "pbf_parser_results"), // XXX - m_quit_input_thread(false), - m_input_queue(input_queue), + PBFParser(future_string_queue_type& input_queue, + future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_types) : + Parser(input_queue, output_queue, header_promise, read_types), m_input_buffer() { + } - // handle OSMHeader - const auto size = check_type_and_get_blob_size("OSMHeader"); - m_header = decode_header(read_from_input_queue(size)); + ~PBFParser() noexcept final = default; - if (m_read_which_entities != osmium::osm_entity_bits::nothing) { - m_reader = std::thread(&PBFInputFormat::parse_osm_data, this, m_read_which_entities); + void run() final { + osmium::thread::set_thread_name("_osmium_pbf_in"); + + parse_header_blob(); + + if (read_types() != osmium::osm_entity_bits::nothing) { + parse_data_blobs(); } } - ~PBFInputFormat() { - signal_input_thread_to_quit(); - if (m_reader.joinable()) { - m_reader.join(); - } - } + }; // class PBFParser - /** - * Returns the next buffer with OSM data read from the PBF - * file. Blocks if data is not available yet. - * Returns an empty buffer at end of input. - */ - osmium::memory::Buffer read() override { - osmium::memory::Buffer buffer; - if (m_eof) { - return buffer; - } + // 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, + [](future_string_queue_type& input_queue, + future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_which_entities) { + return std::unique_ptr(new PBFParser(input_queue, output_queue, header_promise, read_which_entities)); + }); - std::future buffer_future; - m_queue.wait_and_pop(buffer_future); - - try { - buffer = std::move(buffer_future.get()); - if (!buffer) { - m_eof = true; - } - return buffer; - } catch (...) { - m_eof = true; - signal_input_thread_to_quit(); - throw; - } - } - - }; // class PBFInputFormat - - namespace { - -// we want the register_input_format() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" - const bool registered_pbf_input = osmium::io::detail::InputFormatFactory::instance().register_input_format(osmium::io::file_format::pbf, - [](const osmium::io::File& file, osmium::osm_entity_bits::type read_which_entities, osmium::thread::Queue& input_queue) { - return new osmium::io::detail::PBFInputFormat(file, read_which_entities, input_queue); - }); -#pragma GCC diagnostic pop - - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_pbf_parser() noexcept { + return registered_pbf_parser; + } } // namespace detail diff --git a/include/osmium/io/detail/pbf_output_format.hpp b/include/osmium/io/detail/pbf_output_format.hpp index 8d8a079b4..88c1cf489 100644 --- a/include/osmium/io/detail/pbf_output_format.hpp +++ b/include/osmium/io/detail/pbf_output_format.hpp @@ -34,19 +34,18 @@ DEALINGS IN THE SOFTWARE. */ #include -#include +#include #include #include #include -#include #include #include -#include #include -#include #include #include +// needed for older boost libraries +#define BOOST_RESULT_OF_USE_DECLTYPE #include #include @@ -71,6 +70,7 @@ DEALINGS IN THE SOFTWARE. #include #include #include +#include #include #include #include @@ -81,6 +81,32 @@ namespace osmium { namespace detail { + struct pbf_output_options { + + /// Should nodes be encoded in DenseNodes? + bool use_dense_nodes; + + /** + * Should the PBF blobs contain zlib compressed data? + * + * The zlib compression is optional, it's possible to store the + * blobs in raw format. Disabling the compression can improve + * the writing speed a little but the output will be 2x to 3x + * bigger. + */ + bool use_compression; + + /// Should metadata of objects be written? + bool add_metadata; + + /// Add the "HistoricalInformation" header flag. + bool add_historical_information_flag; + + /// Should the visible flag be added to all OSM objects? + bool add_visible_flag; + + }; + /** * Maximum number of items in a primitive block. * @@ -104,43 +130,81 @@ namespace osmium { return static_cast(std::round(lonlat * lonlat_resolution / location_granularity)); } - /** - * Serialize a protobuf message into a Blob, optionally apply compression - * and return it together with a BlobHeader ready to be written to a file. - * - * @param type Type-string used in the BlobHeader. - * @param msg Protobuf-message. - * @param use_compression Should the output be compressed using zlib? - */ - inline std::string serialize_blob(const std::string& type, const std::string& msg, bool use_compression) { - std::string blob_data; - protozero::pbf_builder pbf_blob(blob_data); + enum class pbf_blob_type { + header = 0, + data = 1 + }; - if (use_compression) { - pbf_blob.add_int32(FileFormat::Blob::optional_int32_raw_size, msg.size()); - pbf_blob.add_bytes(FileFormat::Blob::optional_bytes_zlib_data, osmium::io::detail::zlib_compress(msg)); - } else { - pbf_blob.add_bytes(FileFormat::Blob::optional_bytes_raw, msg); + class SerializeBlob { + + std::string m_msg; + + pbf_blob_type m_blob_type; + + bool m_use_compression; + + public: + + /** + * Initialize a blob serializer. + * + * @param msg Protobuf-message containing the blob data + * @param type Type of blob. + * @param use_compression Should the output be compressed using + * zlib? + */ + SerializeBlob(std::string&& msg, pbf_blob_type type, bool use_compression) : + m_msg(std::move(msg)), + m_blob_type(type), + m_use_compression(use_compression) { } - std::string blob_header_data; - protozero::pbf_builder pbf_blob_header(blob_header_data); + /** + * 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()() { + assert(m_msg.size() <= max_uncompressed_blob_size); - pbf_blob_header.add_string(FileFormat::BlobHeader::required_string_type, type); - pbf_blob_header.add_int32(FileFormat::BlobHeader::required_int32_datasize, blob_data.size()); + std::string blob_data; + protozero::pbf_builder pbf_blob(blob_data); - uint32_t sz = htonl(static_cast_with_assert(blob_header_data.size())); + if (m_use_compression) { + pbf_blob.add_int32(FileFormat::Blob::optional_int32_raw_size, int32_t(m_msg.size())); + pbf_blob.add_bytes(FileFormat::Blob::optional_bytes_zlib_data, osmium::io::detail::zlib_compress(m_msg)); + } else { + pbf_blob.add_bytes(FileFormat::Blob::optional_bytes_raw, m_msg); + } - // write to output: the 4-byte BlobHeader-Size followed by the BlobHeader followed by the Blob - std::string output; - output.reserve(sizeof(sz) + blob_header_data.size() + blob_data.size()); - output.append(reinterpret_cast(&sz), sizeof(sz)); - output.append(blob_header_data); - output.append(blob_data); + std::string blob_header_data; + protozero::pbf_builder pbf_blob_header(blob_header_data); - return output; - } + pbf_blob_header.add_string(FileFormat::BlobHeader::required_string_type, m_blob_type == pbf_blob_type::data ? "OSMData" : "OSMHeader"); + pbf_blob_header.add_int32(FileFormat::BlobHeader::required_int32_datasize, static_cast_with_assert(blob_data.size())); + uint32_t sz = htonl(static_cast_with_assert(blob_header_data.size())); + + // write to output: the 4-byte BlobHeader-Size followed by the BlobHeader followed by the Blob + std::string output; + output.reserve(sizeof(sz) + blob_header_data.size() + blob_data.size()); + output.append(reinterpret_cast(&sz), sizeof(sz)); + output.append(blob_header_data); + output.append(blob_data); + + return output; + } + + }; // class SerializeBlob + + /** + * Contains the code to pack any number of nodes into a DenseNode + * structure. + * + * Because this needs to allocate a lot of memory on the heap, + * only one object of this class will be created and then re-used + * after calling clear() on it. + */ class DenseNodes { StringTable& m_stringtable; @@ -158,27 +222,26 @@ namespace osmium { std::vector m_lons; std::vector m_tags; - osmium::util::DeltaEncode m_delta_id; + osmium::util::DeltaEncode m_delta_id; - osmium::util::DeltaEncode m_delta_timestamp; - osmium::util::DeltaEncode m_delta_changeset; - osmium::util::DeltaEncode m_delta_uid; - osmium::util::DeltaEncode m_delta_user_sid; + osmium::util::DeltaEncode m_delta_timestamp; + osmium::util::DeltaEncode m_delta_changeset; + osmium::util::DeltaEncode m_delta_uid; + osmium::util::DeltaEncode m_delta_user_sid; - osmium::util::DeltaEncode m_delta_lat; - osmium::util::DeltaEncode m_delta_lon; + osmium::util::DeltaEncode m_delta_lat; + osmium::util::DeltaEncode m_delta_lon; - bool m_add_metadata; - bool m_add_visible; + const pbf_output_options& m_options; public: - DenseNodes(StringTable& stringtable, bool add_metadata, bool add_visible) : + DenseNodes(StringTable& stringtable, const pbf_output_options& options) : m_stringtable(stringtable), - m_add_metadata(add_metadata), - m_add_visible(add_visible) { + m_options(options) { } + /// Clear object for re-use. Keep the allocated memory. void clear() { m_ids.clear(); @@ -211,13 +274,13 @@ namespace osmium { void add_node(const osmium::Node& node) { m_ids.push_back(m_delta_id.update(node.id())); - if (m_add_metadata) { - m_versions.push_back(node.version()); - m_timestamps.push_back(m_delta_timestamp.update(node.timestamp())); + if (m_options.add_metadata) { + m_versions.push_back(static_cast_with_assert(node.version())); + m_timestamps.push_back(m_delta_timestamp.update(uint32_t(node.timestamp()))); m_changesets.push_back(m_delta_changeset.update(node.changeset())); m_uids.push_back(m_delta_uid.update(node.uid())); m_user_sids.push_back(m_delta_user_sid.update(m_stringtable.add(node.user()))); - if (m_add_visible) { + if (m_options.add_visible_flag) { m_visibles.push_back(node.visible()); } } @@ -226,8 +289,8 @@ namespace osmium { m_lons.push_back(m_delta_lon.update(lonlat2int(node.location().lon_without_check()))); 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(static_cast_with_assert(m_stringtable.add(tag.key()))); + m_tags.push_back(static_cast_with_assert(m_stringtable.add(tag.value()))); } m_tags.push_back(0); } @@ -238,7 +301,7 @@ namespace osmium { pbf_dense_nodes.add_packed_sint64(OSMFormat::DenseNodes::packed_sint64_id, m_ids.cbegin(), m_ids.cend()); - if (m_add_metadata) { + if (m_options.add_metadata) { protozero::pbf_builder pbf_dense_info(pbf_dense_nodes, OSMFormat::DenseNodes::optional_DenseInfo_denseinfo); pbf_dense_info.add_packed_int32(OSMFormat::DenseInfo::packed_int32_version, m_versions.cbegin(), m_versions.cend()); pbf_dense_info.add_packed_sint64(OSMFormat::DenseInfo::packed_sint64_timestamp, m_timestamps.cbegin(), m_timestamps.cend()); @@ -246,7 +309,7 @@ namespace osmium { pbf_dense_info.add_packed_sint32(OSMFormat::DenseInfo::packed_sint32_uid, m_uids.cbegin(), m_uids.cend()); pbf_dense_info.add_packed_sint32(OSMFormat::DenseInfo::packed_sint32_user_sid, m_user_sids.cbegin(), m_user_sids.cend()); - if (m_add_visible) { + if (m_options.add_visible_flag) { pbf_dense_info.add_packed_bool(OSMFormat::DenseInfo::packed_bool_visible, m_visibles.cbegin(), m_visibles.cend()); } } @@ -272,11 +335,11 @@ namespace osmium { public: - PrimitiveBlock(bool add_metadata, bool add_visible) : + explicit PrimitiveBlock(const pbf_output_options& options) : m_pbf_primitive_group_data(), m_pbf_primitive_group(m_pbf_primitive_group_data), m_stringtable(), - m_dense_nodes(m_stringtable, add_metadata, add_visible), + m_dense_nodes(m_stringtable, options), m_type(OSMFormat::PrimitiveGroup::unknown), m_count(0) { } @@ -312,7 +375,7 @@ namespace osmium { ++m_count; } - size_t add_string(const char* s) { + uint32_t store_in_stringtable(const char* s) { return m_stringtable.add(s); } @@ -350,24 +413,7 @@ namespace osmium { class PBFOutputFormat : public osmium::io::detail::OutputFormat, public osmium::handler::Handler { - /// Should nodes be encoded in DenseNodes? - bool m_use_dense_nodes; - - /** - * Should the PBF blobs contain zlib compressed data? - * - * The zlib compression is optional, it's possible to store the - * blobs in raw format. Disabling the compression can improve - * the writing speed a little but the output will be 2x to 3x - * bigger. - */ - bool m_use_compression; - - /// Should metadata of objects be written? - bool m_add_metadata; - - /// Should the visible flag be added to objects? - bool m_add_visible; + pbf_output_options m_options; PrimitiveBlock m_primitive_block; @@ -386,20 +432,22 @@ namespace osmium { primitive_block.add_message(OSMFormat::PrimitiveBlock::repeated_PrimitiveGroup_primitivegroup, m_primitive_block.group_data()); - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(serialize_blob("OSMData", primitive_block_data, m_use_compression)); + m_output_queue.push(osmium::thread::Pool::instance().submit( + SerializeBlob{std::move(primitive_block_data), + pbf_blob_type::data, + m_options.use_compression} + )); } template void add_meta(const osmium::OSMObject& object, T& pbf_object) { const osmium::TagList& tags = object.tags(); - auto map_tag_key = [this](const osmium::Tag& tag) -> size_t { - return m_primitive_block.add_string(tag.key()); + auto map_tag_key = [this](const osmium::Tag& tag) -> uint32_t { + return m_primitive_block.store_in_stringtable(tag.key()); }; - auto map_tag_value = [this](const osmium::Tag& tag) -> size_t { - return m_primitive_block.add_string(tag.value()); + auto map_tag_value = [this](const osmium::Tag& tag) -> uint32_t { + return m_primitive_block.store_in_stringtable(tag.value()); }; pbf_object.add_packed_uint32(T::enum_type::packed_uint32_keys, @@ -410,39 +458,46 @@ namespace osmium { boost::make_transform_iterator(tags.begin(), map_tag_value), boost::make_transform_iterator(tags.end(), map_tag_value)); - if (m_add_metadata) { + if (m_options.add_metadata) { protozero::pbf_builder pbf_info(pbf_object, T::enum_type::optional_Info_info); - pbf_info.add_int32(OSMFormat::Info::optional_int32_version, object.version()); - pbf_info.add_int64(OSMFormat::Info::optional_int64_timestamp, object.timestamp()); + pbf_info.add_int32(OSMFormat::Info::optional_int32_version, static_cast_with_assert(object.version())); + pbf_info.add_int64(OSMFormat::Info::optional_int64_timestamp, uint32_t(object.timestamp())); pbf_info.add_int64(OSMFormat::Info::optional_int64_changeset, object.changeset()); - pbf_info.add_int32(OSMFormat::Info::optional_int32_uid, object.uid()); - pbf_info.add_uint32(OSMFormat::Info::optional_uint32_user_sid, m_primitive_block.add_string(object.user())); - if (m_add_visible) { + pbf_info.add_int32(OSMFormat::Info::optional_int32_uid, static_cast_with_assert(object.uid())); + pbf_info.add_uint32(OSMFormat::Info::optional_uint32_user_sid, m_primitive_block.store_in_stringtable(object.user())); + if (m_options.add_visible_flag) { pbf_info.add_bool(OSMFormat::Info::optional_bool_visible, object.visible()); } } } - PBFOutputFormat(const PBFOutputFormat&) = delete; - PBFOutputFormat& operator=(const PBFOutputFormat&) = delete; + void switch_primitive_block_type(OSMFormat::PrimitiveGroup type) { + if (!m_primitive_block.can_add(type)) { + store_primitive_block(); + m_primitive_block.reset(type); + } + } public: - explicit PBFOutputFormat(const osmium::io::File& file, data_queue_type& output_queue) : - OutputFormat(file, output_queue), - m_use_dense_nodes(file.get("pbf_dense_nodes") != "false"), - m_use_compression(file.get("pbf_compression") != "none" && file.get("pbf_compression") != "false"), - m_add_metadata(file.get("pbf_add_metadata") != "false" && file.get("add_metadata") != "false"), - m_add_visible(file.has_multiple_object_versions()), - m_primitive_block(m_add_metadata, m_add_visible) { + PBFOutputFormat(const osmium::io::File& file, future_string_queue_type& output_queue) : + OutputFormat(output_queue), + m_options(), + m_primitive_block(m_options) { + m_options.use_dense_nodes = file.is_not_false("pbf_dense_nodes"); + m_options.use_compression = file.get("pbf_compression") != "none" && file.is_not_false("pbf_compression"); + m_options.add_metadata = file.is_not_false("pbf_add_metadata") && file.is_not_false("add_metadata"); + m_options.add_historical_information_flag = file.has_multiple_object_versions(); + m_options.add_visible_flag = file.has_multiple_object_versions(); } - void write_buffer(osmium::memory::Buffer&& buffer) override final { - osmium::apply(buffer.cbegin(), buffer.cend(), *this); - } + PBFOutputFormat(const PBFOutputFormat&) = delete; + PBFOutputFormat& operator=(const PBFOutputFormat&) = delete; - void write_header(const osmium::io::Header& header) override final { + ~PBFOutputFormat() noexcept final = default; + + void write_header(const osmium::io::Header& header) final { std::string data; protozero::pbf_builder pbf_header_block(data); @@ -450,19 +505,19 @@ namespace osmium { protozero::pbf_builder 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, box.bottom_left().lon() * lonlat_resolution); - pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_right, box.top_right().lon() * lonlat_resolution); - pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_top, box.top_right().lat() * lonlat_resolution); - pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_bottom, box.bottom_left().lat() * lonlat_resolution); + pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_left, int64_t(box.bottom_left().lon() * lonlat_resolution)); + pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_right, int64_t(box.top_right().lon() * lonlat_resolution)); + pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_top, int64_t(box.top_right().lat() * lonlat_resolution)); + pbf_header_bbox.add_sint64(OSMFormat::HeaderBBox::required_sint64_bottom, int64_t(box.bottom_left().lat() * lonlat_resolution)); } pbf_header_block.add_string(OSMFormat::HeaderBlock::repeated_string_required_features, "OsmSchema-V0.6"); - if (m_use_dense_nodes) { + if (m_options.use_dense_nodes) { pbf_header_block.add_string(OSMFormat::HeaderBlock::repeated_string_required_features, "DenseNodes"); } - if (m_file.has_multiple_object_versions()) { + if (m_options.add_historical_information_flag) { pbf_header_block.add_string(OSMFormat::HeaderBlock::repeated_string_required_features, "HistoricalInformation"); } @@ -471,7 +526,7 @@ namespace osmium { std::string osmosis_replication_timestamp = header.get("osmosis_replication_timestamp"); if (!osmosis_replication_timestamp.empty()) { osmium::Timestamp ts(osmosis_replication_timestamp.c_str()); - pbf_header_block.add_int64(OSMFormat::HeaderBlock::optional_int64_osmosis_replication_timestamp, ts); + pbf_header_block.add_int64(OSMFormat::HeaderBlock::optional_int64_osmosis_replication_timestamp, uint32_t(ts)); } std::string osmosis_replication_sequence_number = header.get("osmosis_replication_sequence_number"); @@ -484,20 +539,23 @@ namespace osmium { pbf_header_block.add_string(OSMFormat::HeaderBlock::optional_string_osmosis_replication_base_url, osmosis_replication_base_url); } - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(serialize_blob("OSMHeader", data, m_use_compression)); + m_output_queue.push(osmium::thread::Pool::instance().submit( + SerializeBlob{std::move(data), + pbf_blob_type::header, + m_options.use_compression} + )); } - void switch_primitive_block_type(OSMFormat::PrimitiveGroup type) { - if (!m_primitive_block.can_add(type)) { - store_primitive_block(); - m_primitive_block.reset(type); - } + 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_use_dense_nodes) { + if (m_options.use_dense_nodes) { switch_primitive_block_type(OSMFormat::PrimitiveGroup::optional_DenseNodes_dense); m_primitive_block.add_dense_node(node); return; @@ -538,8 +596,8 @@ namespace osmium { pbf_relation.add_int64(OSMFormat::Relation::required_int64_id, relation.id()); add_meta(relation, pbf_relation); - auto map_member_role = [this](const osmium::RelationMember& member) -> size_t { - return m_primitive_block.add_string(member.role()); + auto map_member_role = [this](const osmium::RelationMember& member) -> uint32_t { + return m_primitive_block.store_in_stringtable(member.role()); }; pbf_relation.add_packed_int32(OSMFormat::Relation::packed_int32_roles_sid, boost::make_transform_iterator(relation.members().begin(), map_member_role), @@ -554,41 +612,27 @@ namespace osmium { it_type last { members.cend(), members.cend(), map_member_ref }; pbf_relation.add_packed_sint64(OSMFormat::Relation::packed_sint64_memids, first, last); - static auto map_member_type = [](const osmium::RelationMember& member) noexcept -> int { - return osmium::item_type_to_nwr_index(member.type()); + static auto map_member_type = [](const osmium::RelationMember& member) noexcept -> int32_t { + return int32_t(osmium::item_type_to_nwr_index(member.type())); }; pbf_relation.add_packed_int32(OSMFormat::Relation::packed_MemberType_types, boost::make_transform_iterator(relation.members().begin(), map_member_type), boost::make_transform_iterator(relation.members().end(), map_member_type)); } - /** - * Finalize the writing process, flush any open primitive - * blocks to the file and close the file. - */ - void close() override final { - store_primitive_block(); - - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(std::string()); - } - }; // class PBFOutputFormat - namespace { + // 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, + [](const osmium::io::File& file, future_string_queue_type& output_queue) { + return new osmium::io::detail::PBFOutputFormat(file, output_queue); + }); -// we want the register_output_format() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" - const bool registered_pbf_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::pbf, - [](const osmium::io::File& file, data_queue_type& output_queue) { - return new osmium::io::detail::PBFOutputFormat(file, output_queue); - }); -#pragma GCC diagnostic pop - - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_pbf_output() noexcept { + return registered_pbf_output; + } } // namespace detail diff --git a/include/osmium/io/detail/queue_util.hpp b/include/osmium/io/detail/queue_util.hpp new file mode 100644 index 000000000..6c9f071bc --- /dev/null +++ b/include/osmium/io/detail/queue_util.hpp @@ -0,0 +1,157 @@ +#ifndef OSMIUM_IO_DETAIL_QUEUE_UTIL_HPP +#define OSMIUM_IO_DETAIL_QUEUE_UTIL_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2015 Jochen Topf 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 +#include +#include +#include + +#include +#include + +namespace osmium { + + namespace io { + + namespace detail { + + /** + * 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 = osmium::thread::Queue>; + + /** + * 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. + */ + using string_queue_type = osmium::thread::Queue; + + /** + * 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 = osmium::thread::Queue>; + + template + inline void add_to_queue(osmium::thread::Queue>& queue, T&& data) { + std::promise promise; + queue.push(promise.get_future()); + promise.set_value(std::forward(data)); + } + + template + inline void add_to_queue(osmium::thread::Queue>& queue, std::exception_ptr&& exception) { + std::promise promise; + queue.push(promise.get_future()); + promise.set_exception(std::move(exception)); + } + + template + inline void add_end_of_data_to_queue(osmium::thread::Queue>& queue) { + add_to_queue(queue, T{}); + } + + inline bool at_end_of_data(const std::string& data) { + return data.empty(); + } + + inline bool at_end_of_data(osmium::memory::Buffer& buffer) { + return !buffer; + } + + template + class queue_wrapper { + + using queue_type = osmium::thread::Queue>; + + queue_type& m_queue; + bool m_has_reached_end_of_data; + + public: + + explicit queue_wrapper(queue_type& queue) : + m_queue(queue), + m_has_reached_end_of_data(false) { + } + + ~queue_wrapper() noexcept { + drain(); + } + + void drain() { + while (!m_has_reached_end_of_data) { + try { + pop(); + } catch (...) { + // Ignore any exceptions. + } + } + } + + bool has_reached_end_of_data() const noexcept { + return m_has_reached_end_of_data; + } + + T pop() { + T data; + if (!m_has_reached_end_of_data) { + std::future data_future; + m_queue.wait_and_pop(data_future); + data = std::move(data_future.get()); + if (at_end_of_data(data)) { + m_has_reached_end_of_data = true; + } + } + return data; + } + + }; // class queue_wrapper + + } // namespace detail + + } // namespace io + +} // namespace osmium + +#endif // OSMIUM_IO_DETAIL_QUEUE_UTIL_HPP diff --git a/include/osmium/io/detail/read_thread.hpp b/include/osmium/io/detail/read_thread.hpp index bce4f5507..6f96c0b65 100644 --- a/include/osmium/io/detail/read_thread.hpp +++ b/include/osmium/io/detail/read_thread.hpp @@ -34,14 +34,13 @@ DEALINGS IN THE SOFTWARE. */ #include -#include -#include +#include #include #include #include #include -#include +#include #include namespace osmium { @@ -50,52 +49,80 @@ namespace osmium { namespace detail { - class ReadThread { + /** + * 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 { - osmium::thread::Queue& m_queue; - osmium::io::Decompressor* m_decompressor; + // only used in the sub-thread + osmium::io::Decompressor& m_decompressor; + future_string_queue_type& m_queue; - // If this is set in the main thread, we have to wrap up at the - // next possible moment. - std::atomic& m_done; + // used in both threads + std::atomic m_done; - public: + // only used in the main thread + std::thread m_thread; - explicit ReadThread(osmium::thread::Queue& queue, osmium::io::Decompressor* decompressor, std::atomic& done) : - m_queue(queue), - m_decompressor(decompressor), - m_done(done) { - } - - bool operator()() { - osmium::thread::set_thread_name("_osmium_input"); + void run_in_thread() { + osmium::thread::set_thread_name("_osmium_read"); try { while (!m_done) { - std::string data {m_decompressor->read()}; - if (data.empty()) { - m_queue.push(std::move(data)); + std::string data {m_decompressor.read()}; + if (at_end_of_data(data)) { break; } - m_queue.push(std::move(data)); - while (m_queue.size() > 10 && !m_done) { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - } + add_to_queue(m_queue, std::move(data)); } - m_decompressor->close(); + m_decompressor.close(); } catch (...) { - // If there is an exception in this thread, we make sure - // to push an empty string onto the queue to signal the - // end-of-data to the reading thread so that it will not - // hang. Then we re-throw the exception. - m_queue.push(std::string()); - throw; + add_to_queue(m_queue, std::current_exception()); } - return true; + + add_end_of_data_to_queue(m_queue); } - }; // class ReadThread + 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 diff --git a/include/osmium/io/detail/read_write.hpp b/include/osmium/io/detail/read_write.hpp index 9863bd719..6db6d8aa8 100644 --- a/include/osmium/io/detail/read_write.hpp +++ b/include/osmium/io/detail/read_write.hpp @@ -35,6 +35,7 @@ DEALINGS IN THE SOFTWARE. #include #include +#include #include #include #include @@ -45,7 +46,7 @@ DEALINGS IN THE SOFTWARE. # include #endif -#include +#include namespace osmium { @@ -68,23 +69,26 @@ namespace osmium { */ inline int open_for_writing(const std::string& filename, osmium::io::overwrite allow_overwrite = osmium::io::overwrite::no) { if (filename == "" || filename == "-") { - return 1; // stdout - } else { - int flags = O_WRONLY | O_CREAT; - if (allow_overwrite == osmium::io::overwrite::allow) { - flags |= O_TRUNC; - } else { - flags |= O_EXCL; - } #ifdef _WIN32 - flags |= O_BINARY; + _setmode(1, _O_BINARY); #endif - 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; + return 1; // stdout } + + int flags = O_WRONLY | O_CREAT; + if (allow_overwrite == osmium::io::overwrite::allow) { + flags |= O_TRUNC; + } else { + flags |= O_EXCL; + } +#ifdef _WIN32 + flags |= O_BINARY; +#endif + 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; } /** @@ -98,17 +102,17 @@ namespace osmium { inline int open_for_reading(const std::string& filename) { if (filename == "" || filename == "-") { return 0; // stdin - } else { - int flags = O_RDONLY; -#ifdef _WIN32 - flags |= O_BINARY; -#endif - 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; } + + int flags = O_RDONLY; +#ifdef _WIN32 + flags |= O_BINARY; +#endif + 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; } /** @@ -151,6 +155,22 @@ namespace osmium { reliable_write(fd, reinterpret_cast(output_buffer), size); } + inline void reliable_fsync(const int fd) { +#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 (::close(fd) != 0) { + throw std::system_error(errno, std::system_category(), "Close failed"); + } + } + } // namespace detail } // namespace io diff --git a/include/osmium/io/detail/string_table.hpp b/include/osmium/io/detail/string_table.hpp index ae9d5f0ce..1cb142d00 100644 --- a/include/osmium/io/detail/string_table.hpp +++ b/include/osmium/io/detail/string_table.hpp @@ -34,6 +34,7 @@ DEALINGS IN THE SOFTWARE. */ #include +#include #include #include #include @@ -41,6 +42,8 @@ DEALINGS IN THE SOFTWARE. #include #include +#include + namespace osmium { namespace io { @@ -72,7 +75,7 @@ namespace osmium { public: - StringStore(size_t chunk_size) : + explicit StringStore(size_t chunk_size) : m_chunk_size(chunk_size), m_chunks() { add_chunk(); @@ -172,15 +175,15 @@ namespace osmium { // These functions get you some idea how much memory was // used. - int get_chunk_size() const noexcept { + size_t get_chunk_size() const noexcept { return m_chunk_size; } - int get_chunk_count() const noexcept { + size_t get_chunk_count() const noexcept { return m_chunks.size(); } - int get_used_bytes_in_last_chunk() const noexcept { + size_t get_used_bytes_in_last_chunk() const noexcept { return m_chunks.front().size(); } @@ -196,9 +199,16 @@ namespace osmium { 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. + static constexpr const uint32_t max_entries = max_uncompressed_blob_size; + StringStore m_strings; std::map m_index; - size_t m_size; + uint32_t m_size; public: @@ -216,18 +226,23 @@ namespace osmium { m_strings.add(""); } - size_t size() const noexcept { + uint32_t size() const noexcept { return m_size + 1; } - size_t add(const char* s) { + uint32_t add(const char* s) { auto f = m_index.find(s); if (f != m_index.end()) { - return f->second; + return uint32_t(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; } diff --git a/include/osmium/io/detail/string_util.hpp b/include/osmium/io/detail/string_util.hpp new file mode 100644 index 000000000..672266a92 --- /dev/null +++ b/include/osmium/io/detail/string_util.hpp @@ -0,0 +1,206 @@ +#ifndef OSMIUM_IO_DETAIL_STRING_UTIL_HPP +#define OSMIUM_IO_DETAIL_STRING_UTIL_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2015 Jochen Topf 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 +#include +#include +#include +#include + +#include + +namespace osmium { + + namespace io { + + namespace detail { + +#ifndef _MSC_VER +# define SNPRINTF std::snprintf +#else +# define SNPRINTF _snprintf +#endif + + template + inline int string_snprintf(std::string& out, + size_t old_size, + size_t max_size, + const char* format, + TArgs&&... args) { + out.resize(old_size + max_size); + + return SNPRINTF(max_size ? const_cast(out.c_str()) + old_size : nullptr, + max_size, + format, + std::forward(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 + 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 size_t max_size = 100; +#else + static const size_t max_size = 0; +#endif + + size_t old_size = out.size(); + + int len = string_snprintf(out, + old_size, + max_size, + format, + std::forward(args)...); + assert(len > 0); + + if (size_t(len) >= max_size) { + int len2 = string_snprintf(out, + old_size, + size_t(len) + 1, + format, + std::forward(args)...); + assert(len2 == len); + } + + out.resize(old_size + size_t(len)); + } + + inline void append_utf8_encoded_string(std::string& out, const char* data) { + const char* end = data + std::strlen(data); + + while (data != end) { + const char* last = data; + uint32_t c = utf8::next(data, end); + + // 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(last, data); + } else { + out += '%'; + if (c <= 0xff) { + append_printf_formatted_string(out, "%02x", c); + } else { + append_printf_formatted_string(out, "%04x", c); + } + out += '%'; + } + } + } + + inline void append_xml_encoded_string(std::string& out, const char* data) { + for (; *data != '\0'; ++data) { + switch(*data) { + case '&': out += "&"; break; + case '\"': out += """; break; + case '\'': out += "'"; break; + case '<': out += "<"; break; + case '>': out += ">"; break; + case '\n': out += " "; break; + case '\r': out += " "; break; + case '\t': out += " "; break; + default: out += *data; break; + } + } + } + + inline void append_debug_encoded_string(std::string& out, const char* data, const char* prefix, const char* suffix) { + const char* end = data + std::strlen(data); + + while (data != end) { + const char* last = data; + uint32_t c = utf8::next(data, end); + + // 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(last, data); + } else { + out.append(prefix); + append_printf_formatted_string(out, "", c); + out.append(suffix); + } + } + } + + } // namespace detail + + } // namespace io + +} // namespace osmium + +#endif // OSMIUM_IO_DETAIL_STRING_UTIL_HPP diff --git a/include/osmium/io/detail/write_thread.hpp b/include/osmium/io/detail/write_thread.hpp index fad22ed69..81ab1947f 100644 --- a/include/osmium/io/detail/write_thread.hpp +++ b/include/osmium/io/detail/write_thread.hpp @@ -33,11 +33,13 @@ DEALINGS IN THE SOFTWARE. */ +#include +#include #include #include #include -#include +#include #include namespace osmium { @@ -46,33 +48,52 @@ namespace osmium { 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 { - typedef osmium::io::detail::data_queue_type data_queue_type; - - data_queue_type& m_input_queue; - osmium::io::Compressor* m_compressor; + queue_wrapper m_queue; + std::unique_ptr m_compressor; + std::promise m_promise; public: - explicit WriteThread(data_queue_type& input_queue, osmium::io::Compressor* compressor) : - m_input_queue(input_queue), - m_compressor(compressor) { + WriteThread(future_string_queue_type& input_queue, + std::unique_ptr&& compressor, + std::promise&& promise) : + m_queue(input_queue), + m_compressor(std::move(compressor)), + m_promise(std::move(promise)) { } - bool operator()() { - osmium::thread::set_thread_name("_osmium_output"); + WriteThread(const WriteThread&) = delete; + WriteThread& operator=(const WriteThread&) = delete; - std::future data_future; - std::string data; - do { - m_input_queue.wait_and_pop(data_future); - data = data_future.get(); - m_compressor->write(data); - } while (!data.empty()); + WriteThread(WriteThread&&) = delete; + WriteThread& operator=(WriteThread&&) = delete; - m_compressor->close(); - return true; + ~WriteThread() noexcept = default; + + void operator()() { + osmium::thread::set_thread_name("_osmium_write"); + + try { + while (true) { + std::string data = m_queue.pop(); + if (at_end_of_data(data)) { + break; + } + m_compressor->write(data); + } + m_compressor->close(); + m_promise.set_value(true); + } catch (...) { + m_promise.set_exception(std::current_exception()); + m_queue.drain(); + } } }; // class WriteThread diff --git a/include/osmium/io/detail/xml_input_format.hpp b/include/osmium/io/detail/xml_input_format.hpp index b0f3da339..11d3cba08 100644 --- a/include/osmium/io/detail/xml_input_format.hpp +++ b/include/osmium/io/detail/xml_input_format.hpp @@ -33,21 +33,14 @@ DEALINGS IN THE SOFTWARE. */ -#include #include -#include #include #include #include #include #include -#include #include -#include -#include -#include #include -#include #include #include @@ -55,6 +48,7 @@ DEALINGS IN THE SOFTWARE. #include #include #include +#include #include #include #include @@ -130,23 +124,11 @@ namespace osmium { namespace io { - class File; - namespace detail { - /** - * Once the header is fully parsed this exception will be thrown if - * the caller is not interested in anything else except the header. - * It will break off the parsing at this point. - * - * This exception is never seen by user code, it is caught internally. - */ - class ParserIsDone : std::exception { - }; + class XMLParser : public Parser { - class XMLParser { - - static constexpr int buffer_size = 10 * 1000 * 1000; + static constexpr int buffer_size = 2 * 1000 * 1000; enum class context { root, @@ -155,6 +137,9 @@ namespace osmium { way, relation, changeset, + discussion, + comment, + comment_text, ignored_node, ignored_way, ignored_relation, @@ -175,29 +160,22 @@ namespace osmium { osmium::memory::Buffer m_buffer; - std::unique_ptr m_node_builder; - std::unique_ptr m_way_builder; - std::unique_ptr m_relation_builder; - std::unique_ptr m_changeset_builder; + std::unique_ptr m_node_builder; + std::unique_ptr m_way_builder; + std::unique_ptr m_relation_builder; + std::unique_ptr m_changeset_builder; + std::unique_ptr m_changeset_discussion_builder; - std::unique_ptr m_tl_builder; - std::unique_ptr m_wnl_builder; - std::unique_ptr m_rml_builder; + std::unique_ptr m_tl_builder; + std::unique_ptr m_wnl_builder; + std::unique_ptr m_rml_builder; - osmium::thread::Queue& m_input_queue; - osmium::thread::Queue& m_queue; - std::promise& m_header_promise; - - osmium::osm_entity_bits::type m_read_types; - - std::atomic& m_done; - - bool m_header_is_done; + std::string m_comment_text; /** * A C++ wrapper for the Expat parser that makes sure no memory is leaked. */ - template + template class ExpatXMLParser { XML_Parser m_parser; @@ -210,15 +188,20 @@ namespace osmium { static_cast(data)->end_element(element); } + static void XMLCALL character_data_wrapper(void* data, const XML_Char* text, int len) { + static_cast(data)->characters(text, len); + } + public: - ExpatXMLParser(T* callback_object) : + explicit ExpatXMLParser(T* 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); } ExpatXMLParser(const ExpatXMLParser&) = delete; @@ -227,7 +210,7 @@ namespace osmium { ExpatXMLParser& operator=(const ExpatXMLParser&) = delete; ExpatXMLParser& operator=(ExpatXMLParser&&) = delete; - ~ExpatXMLParser() { + ~ExpatXMLParser() noexcept { XML_ParserFree(m_parser); } @@ -239,126 +222,14 @@ namespace osmium { }; // class ExpatXMLParser - /** - * A helper class that makes sure a promise is kept. It stores - * a reference to some piece of data and to a promise and, on - * destruction, sets the value of the promise from the data. - */ - template - class PromiseKeeper { - - T& m_data; - std::promise& m_promise; - bool m_done; - - public: - - PromiseKeeper(T& data, std::promise& promise) : - m_data(data), - m_promise(promise), - m_done(false) { + template + static void check_attributes(const XML_Char** attrs, T check) { + while (*attrs) { + check(attrs[0], attrs[1]); + attrs += 2; } - - void fullfill_promise() { - if (!m_done) { - m_promise.set_value(m_data); - m_done = true; - } - } - - ~PromiseKeeper() { - fullfill_promise(); - } - - }; // class PromiseKeeper - - public: - - explicit XMLParser(osmium::thread::Queue& input_queue, osmium::thread::Queue& queue, std::promise& header_promise, osmium::osm_entity_bits::type read_types, std::atomic& done) : - m_context(context::root), - m_last_context(context::root), - m_in_delete_section(false), - m_header(), - m_buffer(buffer_size), - m_node_builder(), - m_way_builder(), - m_relation_builder(), - m_changeset_builder(), - m_tl_builder(), - m_wnl_builder(), - m_rml_builder(), - m_input_queue(input_queue), - m_queue(queue), - m_header_promise(header_promise), - m_read_types(read_types), - m_done(done), - m_header_is_done(false) { } - /** - * The copy constructor is needed for storing XMLParser in a std::function. - * The copy will look the same as if it has been initialized with the - * same parameters as the original. Any state changes in the original will - * not be reflected in the copy. - */ - XMLParser(const XMLParser& other) : - m_context(context::root), - m_last_context(context::root), - m_in_delete_section(false), - m_header(), - m_buffer(buffer_size), - m_node_builder(), - m_way_builder(), - m_relation_builder(), - m_changeset_builder(), - m_tl_builder(), - m_wnl_builder(), - m_rml_builder(), - m_input_queue(other.m_input_queue), - m_queue(other.m_queue), - m_header_promise(other.m_header_promise), - m_read_types(other.m_read_types), - m_done(other.m_done), - m_header_is_done(other.m_header_is_done) { - } - - XMLParser(XMLParser&&) = default; - - XMLParser& operator=(const XMLParser&) = delete; - - XMLParser& operator=(XMLParser&&) = default; - - ~XMLParser() = default; - - bool operator()() { - ExpatXMLParser parser(this); - PromiseKeeper promise_keeper(m_header, m_header_promise); - bool last; - do { - std::string data; - m_input_queue.wait_and_pop(data); - last = data.empty(); - try { - parser(data, last); - if (m_header_is_done) { - promise_keeper.fullfill_promise(); - } - } catch (ParserIsDone&) { - return true; - } catch (...) { - m_queue.push(osmium::memory::Buffer()); // empty buffer to signify eof - throw; - } - } while (!last && !m_done); - if (m_buffer.committed() > 0) { - m_queue.push(std::move(m_buffer)); - } - m_queue.push(osmium::memory::Buffer()); // empty buffer to signify eof - return true; - } - - private: - const char* init_object(osmium::OSMObject& object, const XML_Char** attrs) { const char* user = ""; @@ -367,17 +238,18 @@ namespace osmium { } osmium::Location location; - for (int count = 0; attrs[count]; count += 2) { - if (!strcmp(attrs[count], "lon")) { - location.set_lon(std::atof(attrs[count+1])); // XXX doesn't detect garbage after the number - } else if (!strcmp(attrs[count], "lat")) { - location.set_lat(std::atof(attrs[count+1])); // XXX doesn't detect garbage after the number - } else if (!strcmp(attrs[count], "user")) { - user = attrs[count+1]; + + check_attributes(attrs, [&location, &user, &object](const XML_Char* name, const XML_Char* value) { + if (!strcmp(name, "lon")) { + location.set_lon(std::atof(value)); // XXX doesn't detect garbage after the number + } else if (!strcmp(name, "lat")) { + location.set_lat(std::atof(value)); // XXX doesn't detect garbage after the number + } else if (!strcmp(name, "user")) { + user = value; } else { - object.set_attribute(attrs[count], attrs[count+1]); + object.set_attribute(name, value); } - } + }); if (location && object.type() == osmium::item_type::node) { static_cast(object).set_location(location); @@ -392,21 +264,21 @@ namespace osmium { osmium::Location min; osmium::Location max; - for (int count = 0; attrs[count]; count += 2) { - if (!strcmp(attrs[count], "min_lon")) { - min.set_lon(atof(attrs[count+1])); - } else if (!strcmp(attrs[count], "min_lat")) { - min.set_lat(atof(attrs[count+1])); - } else if (!strcmp(attrs[count], "max_lon")) { - max.set_lon(atof(attrs[count+1])); - } else if (!strcmp(attrs[count], "max_lat")) { - max.set_lat(atof(attrs[count+1])); - } else if (!strcmp(attrs[count], "user")) { - user = attrs[count+1]; + check_attributes(attrs, [&min, &max, &user, &new_changeset](const XML_Char* name, const XML_Char* value) { + if (!strcmp(name, "min_lon")) { + min.set_lon(atof(value)); + } else if (!strcmp(name, "min_lat")) { + min.set_lat(atof(value)); + } else if (!strcmp(name, "max_lon")) { + max.set_lon(atof(value)); + } else if (!strcmp(name, "max_lat")) { + max.set_lat(atof(value)); + } else if (!strcmp(name, "user")) { + user = value; } else { - new_changeset.set_attribute(attrs[count], attrs[count+1]); + new_changeset.set_attribute(name, value); } - } + }); new_changeset.bounds().extend(min); new_changeset.bounds().extend(max); @@ -414,32 +286,24 @@ namespace osmium { builder->add_user(user); } - void check_tag(osmium::builder::Builder* builder, const XML_Char* element, const XML_Char** attrs) { - if (!strcmp(element, "tag")) { - m_wnl_builder.reset(); - m_rml_builder.reset(); - - const char* key = ""; - const char* value = ""; - for (int count = 0; attrs[count]; count += 2) { - if (attrs[count][0] == 'k' && attrs[count][1] == 0) { - key = attrs[count+1]; - } else if (attrs[count][0] == 'v' && attrs[count][1] == 0) { - value = attrs[count+1]; - } + 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 = std::unique_ptr(new osmium::builder::TagListBuilder(m_buffer, builder)); - } - m_tl_builder->add_tag(key, value); + }); + if (!m_tl_builder) { + m_tl_builder = std::unique_ptr(new osmium::builder::TagListBuilder(m_buffer, builder)); } + m_tl_builder->add_tag(k, v); } - void header_is_done() { - m_header_is_done = true; - if (m_read_types == osmium::osm_entity_bits::nothing) { - throw ParserIsDone(); - } + void mark_header_as_done() { + set_header_value(m_header); } void start_element(const XML_Char* element, const XML_Char** attrs) { @@ -449,16 +313,16 @@ namespace osmium { if (!strcmp(element, "osmChange")) { m_header.set_has_multiple_object_versions(true); } - for (int count = 0; attrs[count]; count += 2) { - if (!strcmp(attrs[count], "version")) { - m_header.set("version", attrs[count+1]); - if (strcmp(attrs[count+1], "0.6")) { - throw osmium::format_version_error(attrs[count+1]); + check_attributes(attrs, [this](const XML_Char* name, const XML_Char* value) { + if (!strcmp(name, "version")) { + m_header.set("version", value); + if (strcmp(value, "0.6")) { + throw osmium::format_version_error(value); } - } else if (!strcmp(attrs[count], "generator")) { - m_header.set("generator", attrs[count+1]); + } else if (!strcmp(name, "generator")) { + m_header.set("generator", value); } - } + }); if (m_header.get("version") == "") { throw osmium::format_version_error(); } @@ -470,8 +334,8 @@ namespace osmium { case context::top: assert(!m_tl_builder); if (!strcmp(element, "node")) { - header_is_done(); - if (m_read_types & osmium::osm_entity_bits::node) { + mark_header_as_done(); + if (read_types() & osmium::osm_entity_bits::node) { m_node_builder = std::unique_ptr(new osmium::builder::NodeBuilder(m_buffer)); m_node_builder->add_user(init_object(m_node_builder->object(), attrs)); m_context = context::node; @@ -479,8 +343,8 @@ namespace osmium { m_context = context::ignored_node; } } else if (!strcmp(element, "way")) { - header_is_done(); - if (m_read_types & osmium::osm_entity_bits::way) { + mark_header_as_done(); + if (read_types() & osmium::osm_entity_bits::way) { m_way_builder = std::unique_ptr(new osmium::builder::WayBuilder(m_buffer)); m_way_builder->add_user(init_object(m_way_builder->object(), attrs)); m_context = context::way; @@ -488,8 +352,8 @@ namespace osmium { m_context = context::ignored_way; } } else if (!strcmp(element, "relation")) { - header_is_done(); - if (m_read_types & osmium::osm_entity_bits::relation) { + mark_header_as_done(); + if (read_types() & osmium::osm_entity_bits::relation) { m_relation_builder = std::unique_ptr(new osmium::builder::RelationBuilder(m_buffer)); m_relation_builder->add_user(init_object(m_relation_builder->object(), attrs)); m_context = context::relation; @@ -497,8 +361,8 @@ namespace osmium { m_context = context::ignored_relation; } } else if (!strcmp(element, "changeset")) { - header_is_done(); - if (m_read_types & osmium::osm_entity_bits::changeset) { + mark_header_as_done(); + if (read_types() & osmium::osm_entity_bits::changeset) { m_changeset_builder = std::unique_ptr(new osmium::builder::ChangesetBuilder(m_buffer)); init_changeset(m_changeset_builder.get(), attrs); m_context = context::changeset; @@ -508,17 +372,17 @@ namespace osmium { } else if (!strcmp(element, "bounds")) { osmium::Location min; osmium::Location max; - for (int count = 0; attrs[count]; count += 2) { - if (!strcmp(attrs[count], "minlon")) { - min.set_lon(atof(attrs[count+1])); - } else if (!strcmp(attrs[count], "minlat")) { - min.set_lat(atof(attrs[count+1])); - } else if (!strcmp(attrs[count], "maxlon")) { - max.set_lon(atof(attrs[count+1])); - } else if (!strcmp(attrs[count], "maxlat")) { - max.set_lat(atof(attrs[count+1])); + check_attributes(attrs, [&min, &max](const XML_Char* name, const XML_Char* value) { + if (!strcmp(name, "minlon")) { + min.set_lon(atof(value)); + } else if (!strcmp(name, "minlat")) { + min.set_lat(atof(value)); + } else if (!strcmp(name, "maxlon")) { + max.set_lon(atof(value)); + } else if (!strcmp(name, "maxlat")) { + max.set_lat(atof(value)); } - } + }); osmium::Box box; box.extend(min).extend(max); m_header.add_box(box); @@ -529,7 +393,9 @@ namespace osmium { case context::node: m_last_context = context::node; m_context = context::in_object; - check_tag(m_node_builder.get(), element, attrs); + if (!strcmp(element, "tag")) { + get_tag(m_node_builder.get(), attrs); + } break; case context::way: m_last_context = context::way; @@ -541,13 +407,14 @@ namespace osmium { m_wnl_builder = std::unique_ptr(new osmium::builder::WayNodeListBuilder(m_buffer, m_way_builder.get())); } - for (int count = 0; attrs[count]; count += 2) { - if (!strcmp(attrs[count], "ref")) { - m_wnl_builder->add_node_ref(osmium::string_to_object_id(attrs[count+1])); + check_attributes(attrs, [this](const XML_Char* name, const XML_Char* value) { + if (!strcmp(name, "ref")) { + m_wnl_builder->add_node_ref(osmium::string_to_object_id(value)); } - } - } else { - check_tag(m_way_builder.get(), element, attrs); + }); + } else if (!strcmp(element, "tag")) { + m_wnl_builder.reset(); + get_tag(m_way_builder.get(), attrs); } break; case context::relation: @@ -560,28 +427,68 @@ namespace osmium { m_rml_builder = std::unique_ptr(new osmium::builder::RelationMemberListBuilder(m_buffer, m_relation_builder.get())); } - char type = 'x'; - object_id_type ref = 0; + item_type type = item_type::undefined; + object_id_type ref = 0; const char* role = ""; - for (int count = 0; attrs[count]; count += 2) { - if (!strcmp(attrs[count], "type")) { - type = static_cast(attrs[count+1][0]); - } else if (!strcmp(attrs[count], "ref")) { - ref = osmium::string_to_object_id(attrs[count+1]); - } else if (!strcmp(attrs[count], "role")) { - role = static_cast(attrs[count+1]); + check_attributes(attrs, [&type, &ref, &role](const XML_Char* name, const XML_Char* value) { + if (!strcmp(name, "type")) { + type = char_to_item_type(value[0]); + } else if (!strcmp(name, "ref")) { + ref = osmium::string_to_object_id(value); + } else if (!strcmp(name, "role")) { + role = static_cast(value); } + }); + if (type != item_type::node && type != item_type::way && type != item_type::relation) { + throw osmium::xml_error("Unknown type on relation member"); } - // XXX assert type, ref, role are set - m_rml_builder->add_member(char_to_item_type(type), ref, role); - } else { - check_tag(m_relation_builder.get(), element, attrs); + if (ref == 0) { + throw osmium::xml_error("Missing ref on relation member"); + } + m_rml_builder->add_member(type, ref, role); + } else if (!strcmp(element, "tag")) { + m_rml_builder.reset(); + get_tag(m_relation_builder.get(), attrs); } break; case context::changeset: m_last_context = context::changeset; - m_context = context::in_object; - check_tag(m_changeset_builder.get(), element, attrs); + if (!strcmp(element, "discussion")) { + m_context = context::discussion; + m_tl_builder.reset(); + if (!m_changeset_discussion_builder) { + m_changeset_discussion_builder = std::unique_ptr(new osmium::builder::ChangesetDiscussionBuilder(m_buffer, m_changeset_builder.get())); + } + } else if (!strcmp(element, "tag")) { + m_context = context::in_object; + m_changeset_discussion_builder.reset(); + get_tag(m_changeset_builder.get(), attrs); + } + break; + case context::discussion: + if (!strcmp(element, "comment")) { + m_context = context::comment; + 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 (!strcmp(name, "date")) { + date = osmium::Timestamp(value); + } else if (!strcmp(name, "uid")) { + uid = osmium::string_to_user_id(value); + } else if (!strcmp(name, "user")) { + user = static_cast(value); + } + }); + m_changeset_discussion_builder->add_comment(date, uid, user); + } + break; + case context::comment: + if (!strcmp(element, "text")) { + m_context = context::comment_text; + } + break; + case context::comment_text: break; case context::ignored_node: break; @@ -604,7 +511,7 @@ namespace osmium { break; case context::top: if (!strcmp(element, "osm") || !strcmp(element, "osmChange")) { - header_is_done(); + mark_header_as_done(); m_context = context::root; } else if (!strcmp(element, "delete")) { m_in_delete_section = false; @@ -639,11 +546,25 @@ namespace osmium { case context::changeset: assert(!strcmp(element, "changeset")); m_tl_builder.reset(); + m_changeset_discussion_builder.reset(); m_changeset_builder.reset(); m_buffer.commit(); m_context = context::top; flush_buffer(); break; + case context::discussion: + assert(!strcmp(element, "discussion")); + m_context = context::changeset; + break; + case context::comment: + assert(!strcmp(element, "comment")); + m_context = context::discussion; + break; + case context::comment_text: + assert(!strcmp(element, "text")); + m_context = context::comment; + m_changeset_discussion_builder->add_comment_text(m_comment_text); + break; case context::in_object: m_context = m_last_context; break; @@ -670,85 +591,84 @@ namespace osmium { } } + void characters(const XML_Char* text, int len) { + if (m_context == context::comment_text) { + m_comment_text.append(text, len); + } else { + m_comment_text.resize(0); + } + } + void flush_buffer() { - if (m_buffer.capacity() - m_buffer.committed() < 1000 * 1000) { - m_queue.push(std::move(m_buffer)); + if (m_buffer.committed() > buffer_size / 10 * 9) { + send_to_output_queue(std::move(m_buffer)); osmium::memory::Buffer buffer(buffer_size); - std::swap(m_buffer, buffer); + using std::swap; + swap(m_buffer, buffer); + } + } + + public: + + XMLParser(future_string_queue_type& input_queue, + future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_types) : + Parser(input_queue, output_queue, header_promise, read_types), + m_context(context::root), + m_last_context(context::root), + m_in_delete_section(false), + m_header(), + m_buffer(buffer_size), + m_node_builder(), + m_way_builder(), + m_relation_builder(), + m_changeset_builder(), + m_changeset_discussion_builder(), + m_tl_builder(), + m_wnl_builder(), + m_rml_builder() { + } + + ~XMLParser() noexcept final = default; + + void run() final { + osmium::thread::set_thread_name("_osmium_xml_in"); + + ExpatXMLParser parser(this); + + while (!input_done()) { + 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(); + + if (m_buffer.committed() > 0) { + send_to_output_queue(std::move(m_buffer)); } } }; // class XMLParser - class XMLInputFormat : public osmium::io::detail::InputFormat { + // 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, + [](future_string_queue_type& input_queue, + future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_which_entities) { + return std::unique_ptr(new XMLParser(input_queue, output_queue, header_promise, read_which_entities)); + }); - static constexpr size_t max_queue_size = 100; - - osmium::thread::Queue m_queue; - std::atomic m_done; - std::promise m_header_promise; - std::future m_parser_future; - - public: - - /** - * Instantiate XML Parser - * - * @param file osmium::io::File instance describing file to be read from. - * @param read_which_entities Which types of OSM entities (nodes, ways, relations, changesets) should be parsed? - * @param input_queue String queue where data is read from. - */ - explicit XMLInputFormat(const osmium::io::File& file, osmium::osm_entity_bits::type read_which_entities, osmium::thread::Queue& input_queue) : - osmium::io::detail::InputFormat(file, read_which_entities), - m_queue(max_queue_size, "xml_parser_results"), - m_done(false), - m_header_promise(), - m_parser_future(std::async(std::launch::async, XMLParser(input_queue, m_queue, m_header_promise, read_which_entities, m_done))) { - } - - ~XMLInputFormat() { - try { - close(); - } catch (...) { - // ignore any exceptions at this point because destructor should not throw - } - } - - virtual osmium::io::Header header() override final { - osmium::thread::check_for_exception(m_parser_future); - return m_header_promise.get_future().get(); - } - - osmium::memory::Buffer read() override { - osmium::memory::Buffer buffer; - if (!m_done || !m_queue.empty()) { - m_queue.wait_and_pop(buffer); - } - - osmium::thread::check_for_exception(m_parser_future); - return buffer; - } - - void close() override { - m_done = true; - osmium::thread::wait_until_done(m_parser_future); - } - - }; // class XMLInputFormat - - namespace { - -// we want the register_input_format() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" - const bool registered_xml_input = osmium::io::detail::InputFormatFactory::instance().register_input_format(osmium::io::file_format::xml, - [](const osmium::io::File& file, osmium::osm_entity_bits::type read_which_entities, osmium::thread::Queue& input_queue) { - return new osmium::io::detail::XMLInputFormat(file, read_which_entities, input_queue); - }); -#pragma GCC diagnostic pop - - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_xml_parser() noexcept { + return registered_xml_parser; + } } // namespace detail diff --git a/include/osmium/io/detail/xml_output_format.hpp b/include/osmium/io/detail/xml_output_format.hpp index 2a381d5ab..3d7878c8e 100644 --- a/include/osmium/io/detail/xml_output_format.hpp +++ b/include/osmium/io/detail/xml_output_format.hpp @@ -33,20 +33,17 @@ DEALINGS IN THE SOFTWARE. */ -#include -#include +#include #include #include #include #include #include #include -#include #include #include #include -#include #include #include #include @@ -75,45 +72,23 @@ namespace osmium { struct XMLWriteError {}; - namespace { + struct xml_output_options { - void xml_string(std::string& out, const char* in) { - for (; *in != '\0'; ++in) { - switch(*in) { - case '&': out += "&"; break; - case '\"': out += """; break; - case '\'': out += "'"; break; - case '<': out += "<"; break; - case '>': out += ">"; break; - case '\n': out += " "; break; - case '\r': out += " "; break; - case '\t': out += " "; break; - default: out += *in; break; - } - } - } + /// Should metadata of objects be added? + bool add_metadata; - const size_t tmp_buffer_size = 100; + /// Should the visible flag be added to all OSM objects? + bool add_visible_flag; - template - void oprintf(std::string& out, const char* format, T value) { - char buffer[tmp_buffer_size+1]; - size_t max_size = sizeof(buffer)/sizeof(char); -#ifndef NDEBUG - int len = -#endif -#ifndef _MSC_VER - snprintf(buffer, max_size, format, value); -#else - _snprintf(buffer, max_size, format, value); -#endif - assert(len > 0 && static_cast(len) < max_size); - out += buffer; - } + /** + * Should , , "operations" be added? + * (This is used for .osc files.) + */ + bool use_change_ops; - } // anonymous namespace + }; - class XMLOutputBlock : public osmium::handler::Handler { + class XMLOutputBlock : public OutputBlock { // operation (create, modify, delete) for osc files enum class operation { @@ -123,15 +98,9 @@ namespace osmium { op_delete = 3 }; // enum class operation - std::shared_ptr m_input_buffer; - - std::shared_ptr m_out; - operation m_last_op {operation::op_none}; - const bool m_add_metadata; - const bool m_write_visible_flag; - const bool m_write_change_ops; + xml_output_options m_options; void write_spaces(int num) { for (; num != 0; --num) { @@ -139,20 +108,20 @@ namespace osmium { } } + int prefix_spaces() { + return m_options.use_change_ops ? 4 : 2; + } + void write_prefix() { - if (m_write_change_ops) { - write_spaces(4); - } else { - write_spaces(2); - } + write_spaces(prefix_spaces()); } void write_meta(const osmium::OSMObject& object) { - oprintf(*m_out, " id=\"%" PRId64 "\"", object.id()); + output_formatted(" id=\"%" PRId64 "\"", object.id()); - if (m_add_metadata) { + if (m_options.add_metadata) { if (object.version()) { - oprintf(*m_out, " version=\"%d\"", object.version()); + output_formatted(" version=\"%d\"", object.version()); } if (object.timestamp()) { @@ -162,16 +131,16 @@ namespace osmium { } if (!object.user_is_anonymous()) { - oprintf(*m_out, " uid=\"%d\" user=\"", object.uid()); - xml_string(*m_out, object.user()); + output_formatted(" uid=\"%d\" user=\"", object.uid()); + append_xml_encoded_string(*m_out, object.user()); *m_out += "\""; } if (object.changeset()) { - oprintf(*m_out, " changeset=\"%d\"", object.changeset()); + output_formatted(" changeset=\"%d\"", object.changeset()); } - if (m_write_visible_flag) { + if (m_options.add_visible_flag) { if (object.visible()) { *m_out += " visible=\"true\""; } else { @@ -181,17 +150,31 @@ namespace osmium { } } - void write_tags(const osmium::TagList& tags) { + void write_tags(const osmium::TagList& tags, int spaces) { for (const auto& tag : tags) { - write_prefix(); + write_spaces(spaces); *m_out += " \n"; } } + void write_discussion(const osmium::ChangesetDiscussion& comments) { + for (const auto& comment : comments) { + output_formatted(" \n"; + *m_out += " "; + append_xml_encoded_string(*m_out, comment.text()); + *m_out += "\n \n"; + } + *m_out += " \n"; + } + void open_close_op_tag(const operation op = operation::op_none) { if (op == m_last_op) { return; @@ -230,12 +213,9 @@ namespace osmium { public: - explicit XMLOutputBlock(osmium::memory::Buffer&& buffer, bool add_metadata, bool write_visible_flag, bool write_change_ops) : - m_input_buffer(std::make_shared(std::move(buffer))), - m_out(std::make_shared()), - m_add_metadata(add_metadata), - m_write_visible_flag(write_visible_flag && !write_change_ops), - m_write_change_ops(write_change_ops) { + XMLOutputBlock(osmium::memory::Buffer&& buffer, const xml_output_options& options) : + OutputBlock(std::move(buffer)), + m_options(options) { } XMLOutputBlock(const XMLOutputBlock&) = default; @@ -244,22 +224,24 @@ namespace osmium { XMLOutputBlock(XMLOutputBlock&&) = default; XMLOutputBlock& operator=(XMLOutputBlock&&) = default; - ~XMLOutputBlock() = default; + ~XMLOutputBlock() noexcept = default; std::string operator()() { osmium::apply(m_input_buffer->cbegin(), m_input_buffer->cend(), *this); - if (m_write_change_ops) { + if (m_options.use_change_ops) { open_close_op_tag(); } std::string out; - std::swap(out, *m_out); + using std::swap; + swap(out, *m_out); + return out; } void node(const osmium::Node& node) { - if (m_write_change_ops) { + if (m_options.use_change_ops) { open_close_op_tag(node.visible() ? (node.version() == 1 ? operation::op_create : operation::op_modify) : operation::op_delete); } @@ -283,14 +265,14 @@ namespace osmium { *m_out += ">\n"; - write_tags(node.tags()); + write_tags(node.tags(), prefix_spaces()); write_prefix(); *m_out += "\n"; } void way(const osmium::Way& way) { - if (m_write_change_ops) { + if (m_options.use_change_ops) { open_close_op_tag(way.visible() ? (way.version() == 1 ? operation::op_create : operation::op_modify) : operation::op_delete); } @@ -307,17 +289,17 @@ namespace osmium { for (const auto& node_ref : way.nodes()) { write_prefix(); - oprintf(*m_out, " \n", node_ref.ref()); + output_formatted(" \n", node_ref.ref()); } - write_tags(way.tags()); + write_tags(way.tags(), prefix_spaces()); write_prefix(); *m_out += "\n"; } void relation(const osmium::Relation& relation) { - if (m_write_change_ops) { + if (m_options.use_change_ops) { open_close_op_tag(relation.visible() ? (relation.version() == 1 ? operation::op_create : operation::op_modify) : operation::op_delete); } @@ -336,22 +318,21 @@ namespace osmium { write_prefix(); *m_out += " \n"; } - write_tags(relation.tags()); + write_tags(relation.tags(), prefix_spaces()); write_prefix(); *m_out += "\n"; } void changeset(const osmium::Changeset& changeset) { - write_prefix(); - *m_out += " 0) { + *m_out += " \n"; + write_discussion(changeset.discussion()); + } + + *m_out += " \n"; } }; // class XMLOutputBlock class XMLOutputFormat : public osmium::io::detail::OutputFormat, public osmium::handler::Handler { - bool m_add_metadata; - bool m_write_visible_flag; + xml_output_options m_options; public: - XMLOutputFormat(const osmium::io::File& file, data_queue_type& output_queue) : - OutputFormat(file, output_queue), - m_add_metadata(file.get("add_metadata") != "false"), - m_write_visible_flag(file.has_multiple_object_versions() || m_file.is_true("force_visible_flag")) { + XMLOutputFormat(const osmium::io::File& file, future_string_queue_type& output_queue) : + OutputFormat(output_queue), + m_options() { + m_options.add_metadata = file.is_not_false("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; } XMLOutputFormat(const XMLOutputFormat&) = delete; XMLOutputFormat& operator=(const XMLOutputFormat&) = delete; - ~XMLOutputFormat() override final { - } + ~XMLOutputFormat() noexcept final = default; - void write_buffer(osmium::memory::Buffer&& buffer) override final { - m_output_queue.push(osmium::thread::Pool::instance().submit(XMLOutputBlock{std::move(buffer), m_add_metadata, m_write_visible_flag, m_file.is_true("xml_change_format")})); - } - - void write_header(const osmium::io::Header& header) override final { + void write_header(const osmium::io::Header& header) final { std::string out = "\n"; - if (m_file.is_true("xml_change_format")) { + if (m_options.use_change_ops) { out += "\n"; } else { out += "\n"; } + append_xml_encoded_string(out, header.get("generator").c_str()); + out += "\">\n"; for (const auto& box : header.boxes()) { out += " \n", box.top_right().lat()); + append_printf_formatted_string(out, " minlon=\"%.7f\"", box.bottom_left().lon()); + append_printf_formatted_string(out, " minlat=\"%.7f\"", box.bottom_left().lat()); + append_printf_formatted_string(out, " maxlon=\"%.7f\"", box.top_right().lon()); + append_printf_formatted_string(out, " maxlat=\"%.7f\"/>\n", box.top_right().lat()); } - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(std::move(out)); + send_to_output_queue(std::move(out)); } - void close() override final { - { - std::string out; - if (m_file.is_true("xml_change_format")) { - out += "\n"; - } else { - out += "\n"; - } + void write_buffer(osmium::memory::Buffer&& buffer) final { + m_output_queue.push(osmium::thread::Pool::instance().submit(XMLOutputBlock{std::move(buffer), m_options})); + } - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(std::move(out)); + void write_end() final { + std::string out; + + if (m_options.use_change_ops) { + out += "\n"; + } else { + out += "\n"; } - std::promise promise; - m_output_queue.push(promise.get_future()); - promise.set_value(std::string()); + send_to_output_queue(std::move(out)); } }; // class XMLOutputFormat - namespace { + // 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, + [](const osmium::io::File& file, future_string_queue_type& output_queue) { + return new osmium::io::detail::XMLOutputFormat(file, output_queue); + }); -// we want the register_output_format() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" - const bool registered_xml_output = osmium::io::detail::OutputFormatFactory::instance().register_output_format(osmium::io::file_format::xml, - [](const osmium::io::File& file, data_queue_type& output_queue) { - return new osmium::io::detail::XMLOutputFormat(file, output_queue); - }); -#pragma GCC diagnostic pop - - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_xml_output() noexcept { + return registered_xml_output; + } } // namespace detail - } // namespace output + } // namespace io } // namespace osmium diff --git a/include/osmium/io/detail/zlib.hpp b/include/osmium/io/detail/zlib.hpp index fc0baf344..4d86168d2 100644 --- a/include/osmium/io/detail/zlib.hpp +++ b/include/osmium/io/detail/zlib.hpp @@ -39,6 +39,7 @@ DEALINGS IN THE SOFTWARE. #include +#include #include namespace osmium { @@ -69,7 +70,7 @@ namespace osmium { ); if (result != Z_OK) { - throw std::runtime_error(std::string("failed to compress data: ") + zError(result)); + throw io_error(std::string("failed to compress data: ") + zError(result)); } output.resize(output_size); @@ -99,7 +100,7 @@ namespace osmium { ); if (result != Z_OK) { - throw std::runtime_error(std::string("failed to uncompress data: ") + zError(result)); + throw io_error(std::string("failed to uncompress data: ") + zError(result)); } return std::make_pair(output.data(), output.size()); diff --git a/include/osmium/io/error.hpp b/include/osmium/io/error.hpp index 07652bc59..6b5c677c0 100644 --- a/include/osmium/io/error.hpp +++ b/include/osmium/io/error.hpp @@ -43,16 +43,28 @@ namespace osmium { */ struct io_error : public std::runtime_error { - io_error(const std::string& what) : + explicit io_error(const std::string& what) : std::runtime_error(what) { } - io_error(const char* what) : + explicit io_error(const char* what) : std::runtime_error(what) { } }; // struct io_error + struct unsupported_file_format_error : public io_error { + + explicit unsupported_file_format_error(const std::string& what) : + io_error(what) { + } + + explicit unsupported_file_format_error(const char* what) : + io_error(what) { + } + + }; // struct unsupported_file_format_error + } // namespace osmium #endif // OSMIUM_IO_ERROR_HPP diff --git a/include/osmium/io/file.hpp b/include/osmium/io/file.hpp index 3bbfacc6d..87fcc3707 100644 --- a/include/osmium/io/file.hpp +++ b/include/osmium/io/file.hpp @@ -39,6 +39,7 @@ DEALINGS IN THE SOFTWARE. #include #include +#include #include #include #include @@ -255,9 +256,9 @@ namespace osmium { * Check file format etc. for consistency and throw exception if * there is a problem. * - * @throws std::runtime_error + * @throws osmium::io_error */ - void check() const { + const File& check() const { if (m_file_format == file_format::unknown) { std::string msg = "Could not detect file format"; if (!m_format_string.empty()) { @@ -273,8 +274,9 @@ namespace osmium { msg += "'"; } msg += "."; - throw std::runtime_error(msg); + throw io_error(msg); } + return *this; } file_format format() const noexcept { diff --git a/include/osmium/io/gzip_compression.hpp b/include/osmium/io/gzip_compression.hpp index 204bfd521..184787539 100644 --- a/include/osmium/io/gzip_compression.hpp +++ b/include/osmium/io/gzip_compression.hpp @@ -49,7 +49,9 @@ DEALINGS IN THE SOFTWARE. #include #include +#include #include +#include #include #include @@ -59,13 +61,13 @@ namespace osmium { * Exception thrown when there are problems compressing or * decompressing gzip files. */ - struct gzip_error : public std::runtime_error { + struct gzip_error : public io_error { int gzip_error_code; int system_errno; gzip_error(const std::string& what, int error_code) : - std::runtime_error(what), + io_error(what), gzip_error_code(error_code), system_errno(error_code == Z_ERRNO ? errno : 0) { } @@ -93,23 +95,29 @@ namespace osmium { class GzipCompressor : public Compressor { + int m_fd; gzFile m_gzfile; public: - explicit GzipCompressor(int fd) : - Compressor(), + explicit GzipCompressor(int fd, fsync sync) : + Compressor(sync), + m_fd(dup(fd)), m_gzfile(::gzdopen(fd, "w")) { if (!m_gzfile) { detail::throw_gzip_error(m_gzfile, "write initialization failed"); } } - ~GzipCompressor() override final { - close(); + ~GzipCompressor() noexcept final { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. + } } - void write(const std::string& data) override final { + void write(const std::string& data) final { if (!data.empty()) { int nwrite = ::gzwrite(m_gzfile, data.data(), static_cast_with_assert(data.size())); if (nwrite == 0) { @@ -118,13 +126,17 @@ namespace osmium { } } - void close() override final { + void close() final { if (m_gzfile) { int result = ::gzclose(m_gzfile); m_gzfile = nullptr; if (result != Z_OK) { detail::throw_gzip_error(m_gzfile, "write close failed", result); } + if (do_fsync()) { + osmium::io::detail::reliable_fsync(m_fd); + } + osmium::io::detail::reliable_close(m_fd); } } @@ -144,11 +156,15 @@ namespace osmium { } } - ~GzipDecompressor() override final { - close(); + ~GzipDecompressor() noexcept final { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. + } } - std::string read() override final { + std::string read() final { std::string buffer(osmium::io::Decompressor::input_buffer_size, '\0'); int nread = ::gzread(m_gzfile, const_cast(buffer.data()), static_cast_with_assert(buffer.size())); if (nread < 0) { @@ -158,7 +174,7 @@ namespace osmium { return buffer; } - void close() override final { + void close() final { if (m_gzfile) { int result = ::gzclose(m_gzfile); m_gzfile = nullptr; @@ -194,11 +210,15 @@ namespace osmium { } } - ~GzipBufferDecompressor() override final { - inflateEnd(&m_zstream); + ~GzipBufferDecompressor() noexcept final { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. + } } - std::string read() override final { + std::string read() final { std::string output; if (m_buffer) { @@ -227,22 +247,28 @@ namespace osmium { return output; } + void close() final { + inflateEnd(&m_zstream); + } + }; // class GzipBufferDecompressor - namespace { + namespace detail { -// we want the register_compression() function to run, setting the variable -// is only a side-effect, it will never be used -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-variable" + // we want the register_compression() function to run, setting + // the variable is only a side-effect, it will never be used const bool registered_gzip_compression = osmium::io::CompressionFactory::instance().register_compression(osmium::io::file_compression::gzip, - [](int fd) { return new osmium::io::GzipCompressor(fd); }, + [](int fd, fsync sync) { return new osmium::io::GzipCompressor(fd, sync); }, [](int fd) { return new osmium::io::GzipDecompressor(fd); }, [](const char* buffer, size_t size) { return new osmium::io::GzipBufferDecompressor(buffer, size); } ); -#pragma GCC diagnostic pop - } // anonymous namespace + // dummy function to silence the unused variable warning from above + inline bool get_registered_gzip_compression() noexcept { + return registered_gzip_compression; + } + + } // namespace detail } // namespace io diff --git a/include/osmium/io/input_iterator.hpp b/include/osmium/io/input_iterator.hpp index f6197299d..864776303 100644 --- a/include/osmium/io/input_iterator.hpp +++ b/include/osmium/io/input_iterator.hpp @@ -52,7 +52,7 @@ namespace osmium { * source. It hides all the buffer handling and makes the contents of a * source accessible as a normal STL input iterator. */ - template + template class InputIterator { static_assert(std::is_base_of::value, "TItem must derive from osmium::buffer::Item"); @@ -133,6 +133,44 @@ namespace osmium { }; // class InputIterator + template + class InputIteratorRange { + + InputIterator m_begin; + InputIterator m_end; + + public: + + InputIteratorRange(InputIterator&& begin, + InputIterator&& end) : + m_begin(std::move(begin)), + m_end(std::move(end)) { + } + + InputIterator begin() const noexcept { + return m_begin; + } + + InputIterator end() const noexcept { + return m_end; + } + + const InputIterator cbegin() const noexcept { + return m_begin; + } + + const InputIterator cend() const noexcept { + return m_end; + } + + }; // class InputIteratorRange + + template + InputIteratorRange make_input_iterator_range(TSource& source) { + using it_type = InputIterator; + return InputIteratorRange(it_type{source}, it_type{}); + } + } // namespace io } // namespace osmium diff --git a/include/osmium/io/o5m_input.hpp b/include/osmium/io/o5m_input.hpp new file mode 100644 index 000000000..b63f72853 --- /dev/null +++ b/include/osmium/io/o5m_input.hpp @@ -0,0 +1,45 @@ +#ifndef OSMIUM_IO_O5M_INPUT_HPP +#define OSMIUM_IO_O5M_INPUT_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2015 Jochen Topf 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. + +*/ + +/** + * @file + * + * Include this file if you want to read OSM o5m and o5c files. + */ + +#include // IWYU pragma: export +#include // IWYU pragma: export + +#endif // OSMIUM_IO_O5M_INPUT_HPP diff --git a/include/osmium/io/output_iterator.hpp b/include/osmium/io/output_iterator.hpp index 608852fa9..1cf1d1dcb 100644 --- a/include/osmium/io/output_iterator.hpp +++ b/include/osmium/io/output_iterator.hpp @@ -40,6 +40,7 @@ DEALINGS IN THE SOFTWARE. #include #include +#include namespace osmium { @@ -49,30 +50,26 @@ namespace osmium { namespace io { - template + template class OutputIterator : public std::iterator { - struct buffer_wrapper { - - osmium::memory::Buffer buffer; - - buffer_wrapper(size_t buffer_size) : - buffer(buffer_size, osmium::memory::Buffer::auto_grow::no) { - } - - }; // struct buffer_wrapper - - static constexpr size_t default_buffer_size = 10 * 1024 * 1024; - TDest* m_destination; - std::shared_ptr m_buffer_wrapper; - public: - explicit OutputIterator(TDest& destination, const size_t buffer_size = default_buffer_size) : - m_destination(&destination), - m_buffer_wrapper(std::make_shared(buffer_size)) { + explicit OutputIterator(TDest& destination) : + m_destination(&destination) { + } + + /** + * @deprecated + * Use of buffer size argument on OutputIterator + * constructor is deprecated. Call Writer::set_buffer_size() + * instead if you want to change the default. + */ + OSMIUM_DEPRECATED OutputIterator(TDest& destination, const size_t buffer_size) : + m_destination(&destination) { + destination.set_buffer_size(buffer_size); } OutputIterator(const OutputIterator&) = default; @@ -83,19 +80,17 @@ namespace osmium { ~OutputIterator() = default; - void flush() { - osmium::memory::Buffer buffer(m_buffer_wrapper->buffer.capacity(), osmium::memory::Buffer::auto_grow::no); - std::swap(m_buffer_wrapper->buffer, buffer); - (*m_destination)(std::move(buffer)); + /** + * @deprecated + * Calling OutputIterator::flush() is usually not + * needed any more. Call flush() on the Writer instead if needed. + */ + OSMIUM_DEPRECATED void flush() { + m_destination->flush(); } OutputIterator& operator=(const osmium::memory::Item& item) { - try { - m_buffer_wrapper->buffer.push_back(item); - } catch (osmium::buffer_is_full&) { - flush(); - m_buffer_wrapper->buffer.push_back(item); - } + (*m_destination)(item); return *this; } @@ -117,6 +112,23 @@ namespace osmium { }; // class OutputIterator + template + OutputIterator make_output_iterator(TDest& destination) { + return OutputIterator{destination}; + } + + /** + * @deprecated + * Use of buffer size argument on make_output_iterator is deprecated. + * Call Writer::set_buffer_size() instead if you want to change the + * default. + */ + template + OSMIUM_DEPRECATED OutputIterator make_output_iterator(TDest& destination, const size_t buffer_size) { + destination.set_buffer_size(buffer_size); + return OutputIterator{destination}; + } + } // namespace io } // namespace osmium diff --git a/include/osmium/io/overwrite.hpp b/include/osmium/io/overwrite.hpp index e33894bd8..f9fbc71af 100644 --- a/include/osmium/io/overwrite.hpp +++ b/include/osmium/io/overwrite.hpp @@ -33,20 +33,7 @@ DEALINGS IN THE SOFTWARE. */ -namespace osmium { - - namespace io { - - /** - * Allow overwriting of existing file. - */ - enum class overwrite : bool { - no = false, - allow = true - }; - - } // namespace io - -} // namespace osmium +#pragma message("Including overwrite.hpp is deprecated, #include instead.") +#include #endif // OSMIUM_IO_OVERWRITE_HPP diff --git a/include/osmium/io/reader.hpp b/include/osmium/io/reader.hpp index c68a8e180..fd2a6d240 100644 --- a/include/osmium/io/reader.hpp +++ b/include/osmium/io/reader.hpp @@ -33,10 +33,10 @@ DEALINGS IN THE SOFTWARE. */ -#include #include #include #include +#include #include #include #include @@ -55,12 +55,13 @@ DEALINGS IN THE SOFTWARE. #include #include #include +#include +#include #include #include #include #include #include -#include namespace osmium { @@ -74,17 +75,46 @@ namespace osmium { */ class Reader { + static constexpr size_t max_input_queue_size = 20; // XXX + static constexpr size_t max_osmdata_queue_size = 20; // XXX + osmium::io::File m_file; osmium::osm_entity_bits::type m_read_which_entities; - std::atomic m_input_done; + + enum class status { + okay = 0, // normal reading + error = 1, // some error occurred while reading + closed = 2, // close() called successfully after eof + eof = 3 // eof of file was reached without error + } m_status; + int m_childpid; - osmium::thread::Queue m_input_queue; + detail::future_string_queue_type m_input_queue; std::unique_ptr m_decompressor; - std::future m_read_future; - std::unique_ptr m_input; + osmium::io::detail::ReadThreadManager m_read_thread_manager; + + detail::future_buffer_queue_type m_osmdata_queue; + detail::queue_wrapper m_osmdata_queue_wrapper; + + std::future m_header_future; + osmium::io::Header m_header; + + osmium::thread::thread_handler m_thread; + + // This function will run in a separate thread. + static void parser_thread(const osmium::io::File& file, + detail::future_string_queue_type& input_queue, + detail::future_buffer_queue_type& osmdata_queue, + std::promise&& header_promise, + osmium::osm_entity_bits::type read_which_entities) { + std::promise promise = std::move(header_promise); + auto creator = detail::ParserFactory::instance().get_creator_function(file); + auto parser = creator(input_queue, osmdata_queue, promise, read_which_entities); + parser->parse(); + } #ifndef _WIN32 /** @@ -149,7 +179,7 @@ namespace osmium { #ifndef _WIN32 return execute("curl", filename, childpid); #else - throw std::runtime_error("Reading OSM files from the network currently not supported on Windows."); + throw io_error("Reading OSM files from the network currently not supported on Windows."); #endif } else { return osmium::io::detail::open_for_reading(filename); @@ -168,16 +198,23 @@ namespace osmium { * parsed. */ explicit Reader(const osmium::io::File& file, osmium::osm_entity_bits::type read_which_entities = osmium::osm_entity_bits::all) : - m_file(file), + m_file(file.check()), m_read_which_entities(read_which_entities), - m_input_done(false), + m_status(status::okay), m_childpid(0), - m_input_queue(20, "raw_input"), // XXX + m_input_queue(max_input_queue_size, "raw_input"), m_decompressor(m_file.buffer() ? osmium::io::CompressionFactory::instance().create_decompressor(file.compression(), m_file.buffer(), m_file.buffer_size()) : osmium::io::CompressionFactory::instance().create_decompressor(file.compression(), open_input_file_or_url(m_file.filename(), &m_childpid))), - m_read_future(std::async(std::launch::async, detail::ReadThread(m_input_queue, m_decompressor.get(), m_input_done))), - m_input(osmium::io::detail::InputFormatFactory::instance().create_input(m_file, m_read_which_entities, m_input_queue)) { + m_read_thread_manager(*m_decompressor, m_input_queue), + m_osmdata_queue(max_osmdata_queue_size, "parser_results"), + m_osmdata_queue_wrapper(m_osmdata_queue), + m_header_future(), + m_header(), + m_thread() { + std::promise header_promise; + m_header_future = header_promise.get_future(); + m_thread = osmium::thread::thread_handler{parser_thread, std::ref(m_file), std::ref(m_input_queue), std::ref(m_osmdata_queue), std::move(header_promise), read_which_entities}; } explicit Reader(const std::string& filename, osmium::osm_entity_bits::type read_types = osmium::osm_entity_bits::all) : @@ -191,27 +228,37 @@ namespace osmium { Reader(const Reader&) = delete; Reader& operator=(const Reader&) = delete; - ~Reader() { + Reader(Reader&&) = default; + Reader& operator=(Reader&&) = default; + + ~Reader() noexcept { try { close(); - } - catch (...) { + } catch (...) { + // Ignore any exceptions because destructor must not throw. } } /** * Close down the Reader. A call to this is optional, because the * destructor of Reader will also call this. But if you don't call - * this function first, the destructor might throw an exception - * which is not good. + * this function first, you might miss an exception, because the + * destructor is not allowed to throw. * - * @throws Some form of std::runtime_error when there is a problem. + * @throws Some form of osmium::io_error when there is a problem. */ void close() { - // Signal to input child process that it should wrap up. - m_input_done = true; + m_status = status::closed; - m_input->close(); + m_read_thread_manager.stop(); + + m_osmdata_queue_wrapper.drain(); + + try { + m_read_thread_manager.close(); + } catch (...) { + // Ignore any exceptions. + } #ifndef _WIN32 if (m_childpid) { @@ -226,15 +273,32 @@ namespace osmium { m_childpid = 0; } #endif - - osmium::thread::wait_until_done(m_read_future); } /** * Get the header data from the file. + * + * @returns Header. + * @throws Some form of osmium::io_error if there is an error. */ - osmium::io::Header header() const { - return m_input->header(); + osmium::io::Header header() { + if (m_status == status::error) { + throw io_error("Can not get header from reader when in status 'error'"); + } + + try { + if (m_header_future.valid()) { + m_header = m_header_future.get(); + if (m_read_which_entities == osmium::osm_entity_bits::nothing) { + m_status = status::eof; + } + } + } catch (...) { + close(); + m_status = status::error; + throw; + } + return m_header; } /** @@ -245,32 +309,36 @@ namespace osmium { * constructed. * * @returns Buffer. - * @throws Some form of std::runtime_error if there is an error. + * @throws Some form of osmium::io_error if there is an error. */ osmium::memory::Buffer read() { - // If an exception happened in the input thread, re-throw - // it in this (the main) thread. - osmium::thread::check_for_exception(m_read_future); + osmium::memory::Buffer buffer; - if (m_read_which_entities == osmium::osm_entity_bits::nothing || m_input_done) { - // If the caller didn't want anything but the header, it will - // always get an empty buffer here. - return osmium::memory::Buffer(); + if (m_status != status::okay || + m_read_which_entities == osmium::osm_entity_bits::nothing) { + throw io_error("Can not read from reader when in status 'closed', 'eof', or 'error'"); } - // m_input->read() can return an invalid buffer to signal EOF, - // or a valid buffer with or without data. A valid buffer - // without data is not an error, it just means we have to - // keep getting the next buffer until there is one with data. - while (true) { - osmium::memory::Buffer buffer = m_input->read(); - if (!buffer) { - m_input_done = true; - return buffer; - } - if (buffer.committed() > 0) { - return buffer; + try { + // m_input_format.read() can return an invalid buffer to signal EOF, + // or a valid buffer with or without data. A valid buffer + // without data is not an error, it just means we have to + // keep getting the next buffer until there is one with data. + while (true) { + buffer = m_osmdata_queue_wrapper.pop(); + if (detail::at_end_of_data(buffer)) { + m_status = status::eof; + m_read_thread_manager.close(); + return buffer; + } + if (buffer.committed() > 0) { + return buffer; + } } + } catch (...) { + close(); + m_status = status::error; + throw; } } @@ -279,7 +347,7 @@ namespace osmium { * data has been read. It is also set by calling close(). */ bool eof() const { - return m_input_done; + return m_status == status::eof || m_status == status::closed; } }; // class Reader @@ -292,7 +360,7 @@ namespace osmium { * unless you are working with small OSM files and/or have lots of * RAM. */ - template + template osmium::memory::Buffer read_file(TArgs&&... args) { osmium::memory::Buffer buffer(1024*1024, osmium::memory::Buffer::auto_grow::yes); diff --git a/include/osmium/io/writer.hpp b/include/osmium/io/writer.hpp index 64afe2066..7cd133d0e 100644 --- a/include/osmium/io/writer.hpp +++ b/include/osmium/io/writer.hpp @@ -33,17 +33,23 @@ DEALINGS IN THE SOFTWARE. */ +#include +#include #include +#include #include +#include #include #include #include +#include #include #include +#include #include #include -#include +#include #include #include @@ -54,21 +60,112 @@ namespace osmium { /** * This is the user-facing interface for writing OSM files. Instantiate * an object of this class with a file name or osmium::io::File object - * and optionally the data for the header and then call operator() on it - * to write Buffers. Call close() to finish up. + * and optionally the data for the header and then call operator() on + * it to write Buffers or Items. + * + * The writer uses multithreading internally to do the actual encoding + * of the data into the intended format, possible compress the data and + * then write it out. But this is intentionally hidden from the user + * of this class who can use it without knowing those details. + * + * If you are done call the close() method to finish up. Only if you + * don't get an exception from the close() method, you can be sure + * the data is written correctly (modulo operating system buffering). + * The destructor of this class will also do the right thing if you + * forget to call close(), but because the destructor can't throw you + * will not get informed about any problems. + * + * The writer is usually used to write complete blocks of data stored + * in osmium::memory::Buffers. But you can also write single + * osmium::memory::Items. In this case the Writer uses an internal + * Buffer. */ class Writer { + static constexpr size_t default_buffer_size = 10 * 1024 * 1024; + osmium::io::File m_file; - osmium::io::detail::data_queue_type m_output_queue; + detail::future_string_queue_type m_output_queue; std::unique_ptr m_output; - std::unique_ptr m_compressor; + osmium::memory::Buffer m_buffer; + + size_t m_buffer_size; std::future m_write_future; + osmium::thread::thread_handler m_thread; + + enum class status { + okay = 0, // normal writing + error = 1, // some error occurred while writing + closed = 2 // close() called successfully + } m_status; + + // This function will run in a separate thread. + static void write_thread(detail::future_string_queue_type& output_queue, + std::unique_ptr&& compressor, + std::promise&& write_promise) { + detail::WriteThread write_thread{output_queue, + std::move(compressor), + std::move(write_promise)}; + write_thread(); + } + + void do_write(osmium::memory::Buffer&& buffer) { + if (buffer && buffer.committed() > 0) { + m_output->write_buffer(std::move(buffer)); + } + } + + void do_flush() { + osmium::thread::check_for_exception(m_write_future); + if (m_buffer && m_buffer.committed() > 0) { + osmium::memory::Buffer buffer{m_buffer_size, + osmium::memory::Buffer::auto_grow::no}; + using std::swap; + swap(m_buffer, buffer); + + m_output->write_buffer(std::move(buffer)); + } + } + + template + void ensure_cleanup(TFunction func, TArgs&&... args) { + if (m_status != status::okay) { + throw io_error("Can not write to writer when in status 'closed' or 'error'"); + } + + try { + func(std::forward(args)...); + } catch (...) { + m_status = status::error; + detail::add_to_queue(m_output_queue, std::current_exception()); + detail::add_end_of_data_to_queue(m_output_queue); + throw; + } + } + + struct options_type { + osmium::io::Header header; + overwrite allow_overwrite = overwrite::no; + fsync sync = fsync::no; + }; + + static void set_option(options_type& options, const osmium::io::Header& header) { + options.header = header; + } + + static void set_option(options_type& options, overwrite value) { + options.allow_overwrite = value; + } + + static void set_option(options_type& options, fsync value) { + options.sync = value; + } + public: /** @@ -76,64 +173,166 @@ namespace osmium { * header to it. * * @param file File (contains name and format info) to open. - * @param header Optional header data. If this is not given sensible - * defaults will be used. See the default constructor - * of osmium::io::Header for details. - * @param allow_overwrite Allow overwriting of existing file? Can be - * osmium::io::overwrite::allow or osmium::io::overwrite::no - * (default). + * @param args All further arguments are optional and can appear + * in any order: * - * @throws std::runtime_error If the file could not be opened. + * * osmium::io::Header: Optional header data. If this is + * not given, a default constructed osmium::io::Header + * object will be used. + * + * * osmium::io::overwrite: Allow overwriting of existing file? + * Can be osmium::io::overwrite::allow or + * osmium::io::overwrite::no (default). + * + * * osmium::io::fsync: Should fsync be called on the file + * before closing it? Can be osmium::io::fsync::yes or + * osmium::io::fsync::no (default). + * + * @throws osmium::io_error If there was an error. * @throws std::system_error If the file could not be opened. */ - explicit Writer(const osmium::io::File& file, const osmium::io::Header& header = osmium::io::Header(), overwrite allow_overwrite = overwrite::no) : - m_file(file), + template + explicit Writer(const osmium::io::File& file, TArgs&&... args) : + m_file(file.check()), m_output_queue(20, "raw_output"), // XXX m_output(osmium::io::detail::OutputFormatFactory::instance().create_output(m_file, m_output_queue)), - m_compressor(osmium::io::CompressionFactory::instance().create_compressor(file.compression(), osmium::io::detail::open_for_writing(m_file.filename(), allow_overwrite))), - m_write_future(std::async(std::launch::async, detail::WriteThread(m_output_queue, m_compressor.get()))) { - assert(!m_file.buffer()); - m_output->write_header(header); + m_buffer(), + m_buffer_size(default_buffer_size), + m_write_future(), + m_thread(), + m_status(status::okay) { + assert(!m_file.buffer()); // XXX can't handle pseudo-files + + options_type options; + (void)std::initializer_list{ + (set_option(options, args), 0)... + }; + + std::unique_ptr compressor = + CompressionFactory::instance().create_compressor(file.compression(), + osmium::io::detail::open_for_writing(m_file.filename(), options.allow_overwrite), + options.sync); + + std::promise write_promise; + m_write_future = write_promise.get_future(); + m_thread = osmium::thread::thread_handler{write_thread, std::ref(m_output_queue), std::move(compressor), std::move(write_promise)}; + + ensure_cleanup([&](){ + m_output->write_header(options.header); + }); } - explicit Writer(const std::string& filename, const osmium::io::Header& header = osmium::io::Header(), overwrite allow_overwrite = overwrite::no) : - Writer(osmium::io::File(filename), header, allow_overwrite) { + template + explicit Writer(const std::string& filename, TArgs&&... args) : + Writer(osmium::io::File(filename), std::forward(args)...) { } - explicit Writer(const char* filename, const osmium::io::Header& header = osmium::io::Header(), overwrite allow_overwrite = overwrite::no) : - Writer(osmium::io::File(filename), header, allow_overwrite) { + template + explicit Writer(const char* filename, TArgs&&... args) : + Writer(osmium::io::File(filename), std::forward(args)...) { } Writer(const Writer&) = delete; Writer& operator=(const Writer&) = delete; - ~Writer() { - close(); - } + Writer(Writer&&) = default; + Writer& operator=(Writer&&) = default; - /** - * Write contents of a buffer to the output file. - * - * @throws Some form of std::runtime_error when there is a problem. - */ - void operator()(osmium::memory::Buffer&& buffer) { - osmium::thread::check_for_exception(m_write_future); - if (buffer.committed() > 0) { - m_output->write_buffer(std::move(buffer)); + ~Writer() noexcept { + try { + close(); + } catch (...) { + // Ignore any exceptions because destructor must not throw. } } /** - * Flush writes to output file and closes it. If you do not - * call this, the destructor of Writer will also do the same - * thing. But because this call might thrown an exception, - * it is better to call close() explicitly. + * Get the currently configured size of the internal buffer. + */ + size_t buffer_size() const noexcept { + return m_buffer_size; + } + + /** + * Set the size of the internal buffer. This will only take effect + * if you have not yet written anything or after the next flush(). + */ + void set_buffer_size(size_t size) noexcept { + m_buffer_size = size; + } + + /** + * Flush the internal buffer if it contains any data. This is + * usually not needed as the buffer gets flushed on close() + * automatically. * - * @throws Some form of std::runtime_error when there is a problem. + * @throws Some form of osmium::io_error when there is a problem. + */ + void flush() { + ensure_cleanup([&](){ + do_flush(); + }); + } + + /** + * Write contents of a buffer to the output file. The buffer is + * moved into this function and will be in an undefined moved-from + * state afterwards. + * + * @param buffer Buffer that is being written out. + * @throws Some form of osmium::io_error when there is a problem. + */ + void operator()(osmium::memory::Buffer&& buffer) { + ensure_cleanup([&](){ + do_flush(); + do_write(std::move(buffer)); + }); + } + + /** + * Add item to the internal buffer for eventual writing to the + * output file. + * + * @param item Item to write (usually an OSM object). + * @throws Some form of osmium::io_error when there is a problem. + */ + void operator()(const osmium::memory::Item& item) { + ensure_cleanup([&](){ + if (!m_buffer) { + m_buffer = osmium::memory::Buffer{m_buffer_size, + osmium::memory::Buffer::auto_grow::no}; + } + try { + m_buffer.push_back(item); + } catch (osmium::buffer_is_full&) { + do_flush(); + m_buffer.push_back(item); + } + }); + } + + /** + * Flushes internal buffer and closes output file. If you do not + * call this, the destructor of Writer will also do the same + * thing. But because this call might throw an exception, which + * the destructor will ignore, it is better to call close() + * explicitly. + * + * @throws Some form of osmium::io_error when there is a problem. */ void close() { - m_output->close(); - osmium::thread::wait_until_done(m_write_future); + if (m_status == status::okay) { + ensure_cleanup([&](){ + do_write(std::move(m_buffer)); + m_output->write_end(); + m_status = status::closed; + detail::add_end_of_data_to_queue(m_output_queue); + }); + } + + if (m_write_future.valid()) { + m_write_future.get(); + } } }; // class Writer diff --git a/include/osmium/io/writer_options.hpp b/include/osmium/io/writer_options.hpp new file mode 100644 index 000000000..ef1955312 --- /dev/null +++ b/include/osmium/io/writer_options.hpp @@ -0,0 +1,60 @@ +#ifndef OSMIUM_IO_WRITER_OPTIONS_HPP +#define OSMIUM_IO_WRITER_OPTIONS_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2015 Jochen Topf 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. + +*/ + +namespace osmium { + + namespace io { + + /** + * Allow overwriting of existing file? + */ + enum class overwrite : bool { + no = false, + allow = true + }; + + /** + * Should writer do an fsync before closing the file? + */ + enum class fsync : bool { + no = false, + yes = true + }; + + } // namespace io + +} // namespace osmium + +#endif // OSMIUM_IO_WRITER_OPTIONS_HPP diff --git a/include/osmium/memory/buffer.hpp b/include/osmium/memory/buffer.hpp index d800c685c..bc6e9f8b9 100644 --- a/include/osmium/memory/buffer.hpp +++ b/include/osmium/memory/buffer.hpp @@ -46,6 +46,7 @@ DEALINGS IN THE SOFTWARE. #include #include #include +#include namespace osmium { @@ -89,12 +90,17 @@ namespace osmium { * * By default, if a buffer gets full it will throw a buffer_is_full exception. * You can use the set_full_callback() method to set a callback functor - * which will be called instead of throwing an exception. + * which will be called instead of throwing an exception. The full + * callback functionality is deprecated and will be removed in the + * future. See the documentation for set_full_callback() for alternatives. */ class Buffer { public: + // This is needed so we can call std::back_inserter() on a Buffer. + using value_type = Item; + enum class auto_grow : bool { yes = true, no = false @@ -112,12 +118,13 @@ namespace osmium { public: - typedef Item value_type; - /** - * The constructor without any parameters creates a non-initialized + * The constructor without any parameters creates an invalid, * buffer, ie an empty hull of a buffer that has no actual memory - * associated with it. It can be used to signify end-of-input. + * associated with it. It can be used to signify end-of-data. + * + * Most methods of the Buffer class will not work with an invalid + * buffer. */ Buffer() noexcept : m_memory(), @@ -128,12 +135,14 @@ namespace osmium { } /** - * Constructs an externally memory-managed buffer using the given - * memory and size. + * Constructs a valid externally memory-managed buffer using the + * given memory and size. * * @param data A pointer to some already initialized data. * @param size The size of the initialized data. - * @throws std::invalid_argument When the size isn't a multiple of the alignment. + * + * @throws std::invalid_argument if the size isn't a multiple of + * the alignment. */ explicit Buffer(unsigned char* data, size_t size) : m_memory(), @@ -147,13 +156,15 @@ namespace osmium { } /** - * Constructs an externally memory-managed buffer with the given - * capacity that already contains 'committed' bytes of data. + * Constructs a valid externally memory-managed buffer with the + * given capacity that already contains 'committed' bytes of data. * * @param data A pointer to some (possibly initialized) data. * @param capacity The size of the memory for this buffer. * @param committed The size of the initialized data. If this is 0, the buffer startes out empty. - * @throws std::invalid_argument When the capacity or committed isn't a multiple of the alignment. + * + * @throws std::invalid_argument if the capacity or committed isn't + * a multiple of the alignment. */ explicit Buffer(unsigned char* data, size_t capacity, size_t committed) : m_memory(), @@ -170,10 +181,18 @@ namespace osmium { } /** - * Create an internally memory-managed buffer with the given capacity. - * different in that it internally gets dynamic memory of the - * required size. The dynamic memory will be automatically - * freed when the Buffer is destroyed. + * Constructs a valid internally memory-managed buffer with the + * given capacity. + * Will internally get dynamic memory of the required size. + * The dynamic memory will be automatically freed when the Buffer + * is destroyed. + * + * @param capacity The (initial) size of the memory for this buffer. + * @param auto_grow Should this buffer automatically grow when it + * becomes to small? + * + * @throws std::invalid_argument if the capacity isn't a multiple + * of the alignment. */ explicit Buffer(size_t capacity, auto_grow auto_grow = auto_grow::yes) : m_memory(capacity), @@ -199,13 +218,17 @@ namespace osmium { /** * Return a pointer to data inside the buffer. + * + * @pre The buffer must be valid. */ unsigned char* data() const noexcept { + assert(m_data); return m_data; } /** - * Returns the capacity of the buffer, ie how many bytes it can contain. + * Returns the capacity of the buffer, ie how many bytes it can + * contain. Always returns 0 on invalid buffers. */ size_t capacity() const noexcept { return m_capacity; @@ -213,6 +236,7 @@ namespace osmium { /** * Returns the number of bytes already filled in this buffer. + * Always returns 0 on invalid buffers. */ size_t committed() const noexcept { return m_committed; @@ -221,6 +245,7 @@ namespace osmium { /** * Returns the number of bytes currently filled in this buffer that * are not yet committed. + * Always returns 0 on invalid buffers. */ size_t written() const noexcept { return m_written; @@ -229,28 +254,57 @@ namespace osmium { /** * This tests if the current state of the buffer is aligned * properly. Can be used for asserts. + * + * @pre The buffer must be valid. */ bool is_aligned() const noexcept { + assert(m_data); return (m_written % align_bytes == 0) && (m_committed % align_bytes == 0); } /** * Set functor to be called whenever the buffer is full * instead of throwing buffer_is_full. + * + * The behaviour is undefined if you call this on an invalid + * buffer. + * + * @pre The buffer must be valid. + * + * @deprecated + * Callback functionality will be removed in the future. Either + * detect the buffer_is_full exception or use a buffer with + * auto_grow::yes. If you want to avoid growing buffers, check + * that the used size of the buffer (committed()) is small enough + * compared to the capacity (for instance small than 90% of the + * capacity) before adding anything to the Buffer. If the buffer + * is initialized with auto_grow::yes, it will still grow in the + * rare case that a very large object will be added taking more + * than the difference between committed() and capacity(). */ - void set_full_callback(std::function full) { + OSMIUM_DEPRECATED void set_full_callback(std::function full) { + assert(m_data); m_full = full; } /** * Grow capacity of this buffer to the given size. * This works only with internally memory-managed buffers. - * If the given size is not larger than the current capacity, nothing is done. + * If the given size is not larger than the current capacity, + * nothing is done. * Already written but not committed data is discarded. * + * @pre The buffer must be valid. + * * @param size New capacity. + * + * @throws std::logic_error if the buffer doesn't use internal + * memory management. + * @throws std::invalid_argument if the size isn't a multiple + * of the alignment. */ void grow(size_t size) { + assert(m_data); if (m_memory.empty()) { throw std::logic_error("Can't grow Buffer if it doesn't use internal memory management."); } @@ -267,9 +321,15 @@ namespace osmium { /** * Mark currently written bytes in the buffer as committed. * - * @returns Last number of committed bytes before this commit. + * @pre The buffer must be valid and aligned properly (as indicated + * by is_aligned(). + * + * @returns Number of committed bytes before this commit. Can be + * used as an offset into the buffer to get to the + * object being committed by this call. */ size_t commit() { + assert(m_data); assert(is_aligned()); const size_t offset = m_committed; @@ -279,14 +339,19 @@ namespace osmium { /** * Roll back changes in buffer to last committed state. + * + * @pre The buffer must be valid. */ void rollback() { + assert(m_data); m_written = m_committed; } /** * Clear the buffer. * + * No-op on an invalid buffer. + * * @returns Number of bytes in the buffer before it was cleared. */ size_t clear() { @@ -299,11 +364,16 @@ namespace osmium { /** * Get the data in the buffer at the given offset. * + * @pre The buffer must be valid. + * * @tparam T Type we want to the data to be interpreted as. - * @returns Reference of given type pointing to the data in the buffer. + * + * @returns Reference of given type pointing to the data in the + * buffer. */ - template + template T& get(const size_t offset) const { + assert(m_data); return *reinterpret_cast(&m_data[offset]); } @@ -320,23 +390,35 @@ namespace osmium { * * * If you have set a callback with set_full_callback(), it is * called. After the call returns, you must have either grown - * the buffer or cleared it by calling buffer.clear(). + * the buffer or cleared it by calling buffer.clear(). (Usage + * of the full callback is deprecated and this functionality + * will be removed in the future. See the documentation for + * set_full_callback() for alternatives. * * If no callback is defined and this buffer uses internal * memory management, the buffers capacity is grown, so that * the new data will fit. * * Else the buffer_is_full exception is thrown. * + * @pre The buffer must be valid. + * * @param size Number of bytes to reserve. + * * @returns Pointer to reserved space. Note that this pointer is - * only guaranteed to be valid until the next call to - * reserve_space(). - * @throws osmium::buffer_is_full Might be thrown if the buffer is full. + * only guaranteed to be valid until the next call to + * reserve_space(). + * + * @throws osmium::buffer_is_full if the buffer is full there is + * no callback defined and the buffer isn't auto-growing. */ unsigned char* reserve_space(const size_t size) { + assert(m_data); + // try to flush the buffer empty first. + if (m_written + size > m_capacity && m_full) { + m_full(*this); + } + // if there's still not enough space, then try growing the buffer. if (m_written + size > m_capacity) { - if (m_full) { - m_full(*this); - } else if (!m_memory.empty() && (m_auto_grow == auto_grow::yes)) { + if (!m_memory.empty() && (m_auto_grow == auto_grow::yes)) { // double buffer size until there is enough space size_t new_capacity = m_capacity * 2; while (m_written + size > new_capacity) { @@ -359,12 +441,17 @@ namespace osmium { * Note that you have to eventually call commit() to actually * commit this data. * + * @pre The buffer must be valid. + * * @tparam T Class of the item to be copied. + * * @param item Reference to the item to be copied. + * * @returns Reference to newly copied data in the buffer. */ - template + template T& add_item(const T& item) { + assert(m_data); unsigned char* target = reserve_space(item.padded_size()); std::copy_n(reinterpret_cast(&item), item.padded_size(), target); return *reinterpret_cast(target); @@ -373,91 +460,176 @@ namespace osmium { /** * Add committed contents of the given buffer to this buffer. * + * @pre The buffer must be valid. + * * Note that you have to eventually call commit() to actually * commit this data. + * + * @param buffer The source of the copy. Must be valid. */ void add_buffer(const Buffer& buffer) { + assert(m_data && buffer); unsigned char* target = reserve_space(buffer.committed()); - std::copy_n(reinterpret_cast(buffer.data()), buffer.committed(), target); + std::copy_n(buffer.data(), buffer.committed(), target); } /** * Add an item to the buffer. This function is provided so that * you can use std::back_inserter. + * + * @pre The buffer must be valid. + * + * @param item The item to be added. */ void push_back(const osmium::memory::Item& item) { + assert(m_data); add_item(item); commit(); } /** - * These iterators can be used to iterate over all items in - * a buffer. + * An iterator that can be used to iterate over all items of + * type T in a buffer. */ - template + template using t_iterator = osmium::memory::ItemIterator; - template + /** + * A const iterator that can be used to iterate over all items of + * type T in a buffer. + */ + template using t_const_iterator = osmium::memory::ItemIterator; - typedef t_iterator iterator; - typedef t_const_iterator const_iterator; + /** + * An iterator that can be used to iterate over all OSMEntity + * objects in a buffer. + */ + using iterator = t_iterator; - template + /** + * A const iterator that can be used to iterate over all OSMEntity + * objects in a buffer. + */ + using const_iterator = t_const_iterator; + + /** + * Get iterator for iterating over all items of type T in the + * buffer. + * + * @pre The buffer must be valid. + * + * @returns Iterator to first item of type T in the buffer. + */ + template t_iterator begin() { + assert(m_data); return t_iterator(m_data, m_data + m_committed); } + /** + * Get iterator for iterating over all objects of class OSMEntity + * in the buffer. + * + * @pre The buffer must be valid. + * + * @returns Iterator to first OSMEntity in the buffer. + */ iterator begin() { + assert(m_data); return iterator(m_data, m_data + m_committed); } - template + /** + * Get iterator for iterating over all items of type T in the + * buffer. + * + * @pre The buffer must be valid. + * + * @returns Iterator to first item of type T after given offset + * in the buffer. + */ + template t_iterator get_iterator(size_t offset) { + assert(m_data); return t_iterator(m_data + offset, m_data + m_committed); } + /** + * Get iterator for iterating over all objects of class OSMEntity + * in the buffer. + * + * @pre The buffer must be valid. + * + * @returns Iterator to first OSMEntity after given offset in the + * buffer. + */ iterator get_iterator(size_t offset) { + assert(m_data); return iterator(m_data + offset, m_data + m_committed); } - template + /** + * Get iterator for iterating over all items of type T in the + * buffer. + * + * @pre The buffer must be valid. + * + * @returns End iterator. + */ + template t_iterator end() { + assert(m_data); return t_iterator(m_data + m_committed, m_data + m_committed); } + /** + * Get iterator for iterating over all objects of class OSMEntity + * in the buffer. + * + * @pre The buffer must be valid. + * + * @returns End iterator. + */ iterator end() { + assert(m_data); return iterator(m_data + m_committed, m_data + m_committed); } - template + template t_const_iterator cbegin() const { + assert(m_data); return t_const_iterator(m_data, m_data + m_committed); } const_iterator cbegin() const { + assert(m_data); return const_iterator(m_data, m_data + m_committed); } - template + template t_const_iterator get_iterator(size_t offset) const { + assert(m_data); return t_const_iterator(m_data + offset, m_data + m_committed); } const_iterator get_iterator(size_t offset) const { + assert(m_data); return const_iterator(m_data + offset, m_data + m_committed); } - template + template t_const_iterator cend() const { + assert(m_data); return t_const_iterator(m_data + m_committed, m_data + m_committed); } const_iterator cend() const { + assert(m_data); return const_iterator(m_data + m_committed, m_data + m_committed); } - template + template t_const_iterator begin() const { return cbegin(); } @@ -466,7 +638,7 @@ namespace osmium { return cbegin(); } - template + template t_const_iterator end() const { return cend(); } @@ -476,9 +648,9 @@ namespace osmium { } /** - * In a bool context any initialized buffer is true. + * In a bool context any valid buffer is true. */ - explicit operator bool() const { + explicit operator bool() const noexcept { return m_data != nullptr; } @@ -490,6 +662,8 @@ namespace osmium { swap(lhs.m_capacity, rhs.m_capacity); swap(lhs.m_written, rhs.m_written); swap(lhs.m_committed, rhs.m_committed); + swap(lhs.m_auto_grow, rhs.m_auto_grow); + swap(lhs.m_full, rhs.m_full); } /** @@ -497,17 +671,20 @@ namespace osmium { * non-removed items forward in the buffer overwriting removed * items and then correcting the m_written and m_committed numbers. * - * Note that calling this function invalidates all iterators on this - * buffer and all offsets in this buffer. + * Note that calling this function invalidates all iterators on + * this buffer and all offsets in this buffer. * * For every non-removed item that moves its position, the function * 'moving_in_buffer' is called on the given callback object with * the old and new offsets in the buffer where the object used to * be and is now, respectively. This call can be used to update any * indexes. + * + * @pre The buffer must be valid. */ - template + template void purge_removed(TCallbackClass* callback) { + assert(m_data); if (begin() == end()) { return; } @@ -537,7 +714,17 @@ namespace osmium { }; // class Buffer + /** + * Compare two buffers for equality. + * + * Buffers are equal if they are both invalid or if they are both + * valid and have the same data pointer, capacity and committed + * data. + */ inline bool operator==(const Buffer& lhs, const Buffer& rhs) noexcept { + if (!lhs || !rhs) { + return !lhs && !rhs; + } return lhs.data() == rhs.data() && lhs.capacity() == rhs.capacity() && lhs.committed() == rhs.committed(); } diff --git a/include/osmium/memory/collection.hpp b/include/osmium/memory/collection.hpp index 5cf3cc6e1..3878b9a3a 100644 --- a/include/osmium/memory/collection.hpp +++ b/include/osmium/memory/collection.hpp @@ -43,7 +43,7 @@ namespace osmium { namespace memory { - template + template class CollectionIterator : public std::iterator { // This data_type is either 'unsigned char*' or 'const unsigned char*' depending @@ -59,7 +59,7 @@ namespace osmium { m_data(nullptr) { } - CollectionIterator(data_type data) noexcept : + explicit CollectionIterator(data_type data) noexcept : m_data(data) { } @@ -101,7 +101,7 @@ namespace osmium { }; // class CollectionIterator - template + template class Collection : public Item { public: diff --git a/include/osmium/memory/item.hpp b/include/osmium/memory/item.hpp index dc544049a..f95ce8807 100644 --- a/include/osmium/memory/item.hpp +++ b/include/osmium/memory/item.hpp @@ -43,7 +43,7 @@ namespace osmium { namespace builder { class Builder; - } + } // namespace builder namespace memory { @@ -102,10 +102,10 @@ namespace osmium { uint16_t m_removed : 1; uint16_t m_padding : 15; - template + template friend class CollectionIterator; - template + template friend class ItemIterator; friend class osmium::builder::Builder; diff --git a/include/osmium/memory/item_iterator.hpp b/include/osmium/memory/item_iterator.hpp index 3e5b5fa8b..87af56830 100644 --- a/include/osmium/memory/item_iterator.hpp +++ b/include/osmium/memory/item_iterator.hpp @@ -38,29 +38,17 @@ DEALINGS IN THE SOFTWARE. #include #include +#include #include #include namespace osmium { - class Node; - class Way; - class Relation; - class Area; - class Changeset; - class OSMObject; - class OSMEntity; - class TagList; - class WayNodeList; - class RelationMemberList; - class InnerRing; - class OuterRing; - namespace memory { namespace detail { - template + template inline bool type_is_compatible(osmium::item_type) noexcept { return true; } @@ -127,7 +115,7 @@ namespace osmium { } // namespace detail - template + template class ItemIterator : public std::iterator { static_assert(std::is_base_of::value, "TMember must derive from osmium::memory::Item"); @@ -160,7 +148,7 @@ namespace osmium { advance_to_next_item_of_right_type(); } - template + template ItemIterator cast() const { return ItemIterator(m_data, m_end); } @@ -217,7 +205,7 @@ namespace osmium { } explicit operator bool() const { - return m_data != nullptr; + return (m_data != nullptr) && (m_data != m_end); } template diff --git a/include/osmium/object_pointer_collection.hpp b/include/osmium/object_pointer_collection.hpp index 752470305..85566b6a4 100644 --- a/include/osmium/object_pointer_collection.hpp +++ b/include/osmium/object_pointer_collection.hpp @@ -84,7 +84,7 @@ namespace osmium { /** * Sort objects according to the given order functor. */ - template + template void sort(TCompare&& compare) { std::sort(m_objects.begin(), m_objects.end(), std::forward(compare)); } diff --git a/include/osmium/osm/area.hpp b/include/osmium/osm/area.hpp index 3e129d0fb..7fb2a798b 100644 --- a/include/osmium/osm/area.hpp +++ b/include/osmium/osm/area.hpp @@ -48,7 +48,7 @@ namespace osmium { namespace builder { template class ObjectBuilder; - } + } // namespace builder /** * An outer ring of an Area. @@ -167,6 +167,7 @@ namespace osmium { case osmium::item_type::way_node_list: case osmium::item_type::relation_member_list: case osmium::item_type::relation_member_list_with_full_members: + case osmium::item_type::changeset_discussion: assert(false && "Children of Area can only be outer/inner_ring and tag_list."); break; } diff --git a/include/osmium/osm/box.hpp b/include/osmium/osm/box.hpp index 631f91911..155f5e902 100644 --- a/include/osmium/osm/box.hpp +++ b/include/osmium/osm/box.hpp @@ -154,14 +154,14 @@ namespace osmium { * Box is valid, ie. defined and inside usual bounds * (-180<=lon<=180, -90<=lat<=90). */ - OSMIUM_CONSTEXPR bool valid() const noexcept { + constexpr bool valid() const noexcept { return bottom_left().valid() && top_right().valid(); } /** * Access bottom-left location. */ - OSMIUM_CONSTEXPR Location bottom_left() const noexcept { + constexpr Location bottom_left() const noexcept { return m_bottom_left; } @@ -175,7 +175,7 @@ namespace osmium { /** * Access top-right location. */ - OSMIUM_CONSTEXPR Location top_right() const noexcept { + constexpr Location top_right() const noexcept { return m_top_right; } @@ -216,7 +216,7 @@ namespace osmium { * Boxes are equal if both locations are equal. Undefined boxes will * compare equal. */ - inline OSMIUM_CONSTEXPR bool operator==(const Box& lhs, const Box& rhs) noexcept { + inline constexpr bool operator==(const Box& lhs, const Box& rhs) noexcept { return lhs.bottom_left() == rhs.bottom_left() && lhs.top_right() == rhs.top_right(); } diff --git a/include/osmium/osm/changeset.hpp b/include/osmium/osm/changeset.hpp index 07bc0dd95..db3f717da 100644 --- a/include/osmium/osm/changeset.hpp +++ b/include/osmium/osm/changeset.hpp @@ -48,8 +48,102 @@ DEALINGS IN THE SOFTWARE. namespace osmium { namespace builder { - template class ObjectBuilder; - } + class ChangesetDiscussionBuilder; + template class ObjectBuilder; + } // namespace builder + + class Changeset; + + class ChangesetComment : public osmium::memory::detail::ItemHelper { + + friend class osmium::builder::ChangesetDiscussionBuilder; + + osmium::Timestamp m_date; + osmium::user_id_type m_uid {0}; + string_size_type m_user_size; + string_size_type m_text_size; + + ChangesetComment(const ChangesetComment&) = delete; + ChangesetComment(ChangesetComment&&) = delete; + + ChangesetComment& operator=(const ChangesetComment&) = delete; + ChangesetComment& operator=(ChangesetComment&&) = delete; + + unsigned char* endpos() { + return data() + osmium::memory::padded_length(sizeof(ChangesetComment) + m_user_size + m_text_size); + } + + const unsigned char* endpos() const { + return data() + osmium::memory::padded_length(sizeof(ChangesetComment) + m_user_size + m_text_size); + } + + template + friend class osmium::memory::CollectionIterator; + + unsigned char* next() { + return endpos(); + } + + unsigned const char* next() const { + return endpos(); + } + + void set_user_size(string_size_type size) noexcept { + m_user_size = size; + } + + void set_text_size(string_size_type size) noexcept { + m_text_size = size; + } + + public: + + static constexpr item_type collection_type = item_type::changeset_discussion; + + ChangesetComment(osmium::Timestamp date, osmium::user_id_type uid) noexcept : + m_date(date), + m_uid(uid), + m_user_size(0), + m_text_size(0) { + } + + osmium::Timestamp date() const noexcept { + return m_date; + } + + osmium::user_id_type uid() const noexcept { + return m_uid; + } + + const char* user() const noexcept { + return reinterpret_cast(data() + sizeof(ChangesetComment)); + } + + const char* text() const noexcept { + return reinterpret_cast(data() + sizeof(ChangesetComment) + m_user_size); + } + + }; // class ChangesetComment + + class ChangesetDiscussion : public osmium::memory::Collection { + + friend class osmium::builder::ObjectBuilder; + + public: + + typedef size_t size_type; + + ChangesetDiscussion() : + osmium::memory::Collection() { + } + + size_type size() const noexcept { + return static_cast(std::distance(begin(), end())); + } + + }; // class ChangesetDiscussion + + static_assert(sizeof(ChangesetDiscussion) % osmium::memory::align_bytes == 0, "Class osmium::ChangesetDiscussion has wrong size to be aligned properly!"); /** * \brief An OSM Changeset, a group of changes made by a single user over @@ -62,13 +156,16 @@ namespace osmium { friend class osmium::builder::ObjectBuilder; + osmium::Box m_bounds; osmium::Timestamp m_created_at; osmium::Timestamp m_closed_at; - osmium::Box m_bounds; changeset_id_type m_id {0}; num_changes_type m_num_changes {0}; + num_comments_type m_num_comments {0}; user_id_type m_uid {0}; string_size_type m_user_size; + int16_t m_padding1 {0}; + int32_t m_padding2 {0}; Changeset() : OSMEntity(sizeof(Changeset), osmium::item_type::changeset) { @@ -188,7 +285,7 @@ namespace osmium { * @param timestamp Timestamp * @returns Reference to changeset to make calls chainable. */ - Changeset& set_created_at(const osmium::Timestamp timestamp) { + Changeset& set_created_at(const osmium::Timestamp& timestamp) { m_created_at = timestamp; return *this; } @@ -199,7 +296,7 @@ namespace osmium { * @param timestamp Timestamp * @returns Reference to changeset to make calls chainable. */ - Changeset& set_closed_at(const osmium::Timestamp timestamp) { + Changeset& set_closed_at(const osmium::Timestamp& timestamp) { m_closed_at = timestamp; return *this; } @@ -216,10 +313,26 @@ namespace osmium { } /// Set the number of changes in this changeset - Changeset& set_num_changes(const char* num_changes) noexcept { + Changeset& set_num_changes(const char* num_changes) { return set_num_changes(osmium::string_to_num_changes(num_changes)); } + /// Get the number of comments in this changeset + num_comments_type num_comments() const noexcept { + return m_num_comments; + } + + /// Set the number of comments in this changeset + Changeset& set_num_comments(num_comments_type num_comments) noexcept { + m_num_comments = num_comments; + return *this; + } + + /// Set the number of comments in this changeset + Changeset& set_num_comments(const char* num_comments) { + return set_num_comments(osmium::string_to_num_comments(num_comments)); + } + /** * Get the bounding box of this changeset. * @@ -260,6 +373,8 @@ namespace osmium { set_id(value); } else if (!strcmp(attr, "num_changes")) { set_num_changes(value); + } else if (!strcmp(attr, "comments_count")) { + set_num_comments(value); } else if (!strcmp(attr, "created_at")) { set_created_at(osmium::Timestamp(value)); } else if (!strcmp(attr, "closed_at")) { @@ -296,6 +411,14 @@ namespace osmium { return cend(); } + ChangesetDiscussion& discussion() { + return osmium::detail::subitem_of_type(begin(), end()); + } + + const ChangesetDiscussion& discussion() const { + return osmium::detail::subitem_of_type(cbegin(), cend()); + } + }; // class Changeset static_assert(sizeof(Changeset) % osmium::memory::align_bytes == 0, "Class osmium::Changeset has wrong size to be aligned properly!"); diff --git a/include/osmium/osm/crc.hpp b/include/osmium/osm/crc.hpp index eefa4a13e..f5e01e47b 100644 --- a/include/osmium/osm/crc.hpp +++ b/include/osmium/osm/crc.hpp @@ -46,10 +46,9 @@ DEALINGS IN THE SOFTWARE. namespace osmium { - template - class CRC { + namespace util { - static inline uint16_t byte_swap_16(uint16_t value) noexcept { + inline uint16_t byte_swap_16(uint16_t value) noexcept { # if defined(__GNUC__) || defined(__clang__) return __builtin_bswap16(value); # else @@ -57,27 +56,32 @@ namespace osmium { # endif } - static inline uint32_t byte_swap_32(uint32_t value) noexcept { + inline uint32_t byte_swap_32(uint32_t value) noexcept { # if defined(__GNUC__) || defined(__clang__) return __builtin_bswap32(value); # else return (value >> 24) | - ((value >> 8) & 0x0000FF00) | - ((value << 8) & 0x00FF0000) | + ((value >> 8) & 0x0000FF00) | + ((value << 8) & 0x00FF0000) | (value << 24); # endif } - static inline uint64_t byte_swap_64(uint64_t value) noexcept { + inline uint64_t byte_swap_64(uint64_t value) noexcept { # if defined(__GNUC__) || defined(__clang__) return __builtin_bswap64(value); # else uint64_t val1 = byte_swap_32(value & 0xFFFFFFFF); uint64_t val2 = byte_swap_32(value >> 32); - return (val1 << 32) & val2; + return (val1 << 32) | val2; # endif } + } // namespace util + + template + class CRC { + TCRC m_crc; public: @@ -90,37 +94,37 @@ namespace osmium { return m_crc; } - void update_bool(bool value) { + void update_bool(const bool value) { m_crc.process_byte(value); } - void update_int8(uint8_t value) { + void update_int8(const uint8_t value) { m_crc.process_byte(value); } - void update_int16(uint16_t value) { + void update_int16(const uint16_t value) { #if __BYTE_ORDER == __LITTLE_ENDIAN m_crc.process_bytes(&value, sizeof(uint16_t)); #else - uint16_t v = byte_swap_16(value); + uint16_t v = osmium::util::byte_swap_16(value); m_crc.process_bytes(&v, sizeof(uint16_t)); #endif } - void update_int32(uint32_t value) { + void update_int32(const uint32_t value) { #if __BYTE_ORDER == __LITTLE_ENDIAN m_crc.process_bytes(&value, sizeof(uint32_t)); #else - uint32_t v = byte_swap_32(value); + uint32_t v = osmium::util::byte_swap_32(value); m_crc.process_bytes(&v, sizeof(uint32_t)); #endif } - void update_int64(uint64_t value) { + void update_int64(const uint64_t value) { #if __BYTE_ORDER == __LITTLE_ENDIAN m_crc.process_bytes(&value, sizeof(uint64_t)); #else - uint64_t v = byte_swap_64(value); + uint64_t v = osmium::util::byte_swap_64(value); m_crc.process_bytes(&v, sizeof(uint64_t)); #endif } @@ -156,7 +160,10 @@ namespace osmium { } void update(const TagList& tags) { - m_crc.process_bytes(tags.data(), tags.byte_size()); + for (const Tag& tag : tags) { + update_string(tag.key()); + update_string(tag.value()); + } } void update(const osmium::RelationMember& member) { @@ -206,14 +213,26 @@ namespace osmium { } } + void update(const osmium::ChangesetDiscussion& discussion) { + for (const auto& comment : discussion) { + update(comment.date()); + update_int32(comment.uid()); + update_string(comment.user()); + update_string(comment.text()); + } + } + void update(const osmium::Changeset& changeset) { update_int64(changeset.id()); update(changeset.created_at()); update(changeset.closed_at()); update(changeset.bounds()); update_int32(changeset.num_changes()); + update_int32(changeset.num_comments()); update_int32(changeset.uid()); update_string(changeset.user()); + update(changeset.tags()); + update(changeset.discussion()); } }; // class CRC diff --git a/include/osmium/osm/diff_object.hpp b/include/osmium/osm/diff_object.hpp index 1e053fdda..d9872eaea 100644 --- a/include/osmium/osm/diff_object.hpp +++ b/include/osmium/osm/diff_object.hpp @@ -33,6 +33,9 @@ DEALINGS IN THE SOFTWARE. */ +#include + +#include #include #include #include @@ -40,75 +43,158 @@ DEALINGS IN THE SOFTWARE. namespace osmium { - class Node; - class Way; - class Relation; - + /** + * A DiffObject holds pointers to three OSMObjects, the current object, + * the previous, and the next. They always have the same type (Node, Way, + * or Relation) and the same ID, but may have different versions. + * + * It is used when iterating over OSM files with history data to make + * working with versioned OSM objects easier. Because you have access to + * the previous and next objects as well as the current one, comparisons + * between object versions is easy. + * + * If the current object is the first version available, the previous + * pointer must be the same as the current one. If the current object is + * the last version available, the next pointer must be the same as the + * current one. + * + * DiffObjects are immutable. + */ class DiffObject { - protected: - - osmium::OSMObject* m_prev; - osmium::OSMObject* m_curr; - osmium::OSMObject* m_next; + const osmium::OSMObject* m_prev; + const osmium::OSMObject* m_curr; + const osmium::OSMObject* m_next; public: + /** + * Default construct an empty DiffObject. Most methods of this class + * can not be called on empty DiffObjects. + */ DiffObject() noexcept : m_prev(nullptr), m_curr(nullptr), m_next(nullptr) { } - explicit DiffObject(osmium::OSMObject& prev, osmium::OSMObject& curr, osmium::OSMObject& next) noexcept : + /** + * Construct a non-empty DiffObject from the given OSMObjects. All + * OSMObjects must be of the same type (Node, Way, or Relation) and + * have the same ID. + */ + DiffObject(const osmium::OSMObject& prev, const osmium::OSMObject& curr, const osmium::OSMObject& next) noexcept : m_prev(&prev), m_curr(&curr), m_next(&next) { + assert(prev.type() == curr.type() && curr.type() == next.type()); + assert(prev.id() == curr.id() && curr.id() == next.id()); } - DiffObject(const DiffObject&) = default; - DiffObject& operator=(const DiffObject&) = default; - - DiffObject(DiffObject&&) = default; - DiffObject& operator=(DiffObject&&) = default; + /** + * Check whether the DiffObject was created empty. + */ + bool empty() const noexcept { + return m_prev == nullptr; + } + /** + * Get the previous object stored. + * + * @pre DiffObject must not be empty. + */ const osmium::OSMObject& prev() const noexcept { + assert(m_prev && m_curr && m_next); return *m_prev; } + /** + * Get the current object stored. + * + * @pre DiffObject must not be empty. + */ const osmium::OSMObject& curr() const noexcept { + assert(m_prev && m_curr && m_next); return *m_curr; } + /** + * Get the next object stored. + * + * @pre DiffObject must not be empty. + */ const osmium::OSMObject& next() const noexcept { + assert(m_prev && m_curr && m_next); return *m_next; } + /** + * Is the current object version the first (with this type and ID)? + * + * @pre DiffObject must not be empty. + */ bool first() const noexcept { + assert(m_prev && m_curr && m_next); return m_prev == m_curr; } + /** + * Is the current object version the last (with this type and ID)? + * + * @pre DiffObject must not be empty. + */ bool last() const noexcept { + assert(m_prev && m_curr && m_next); return m_curr == m_next; } + /** + * Return the type of the current object. + * + * @pre DiffObject must not be empty. + */ osmium::item_type type() const noexcept { + assert(m_prev && m_curr && m_next); return m_curr->type(); } + /** + * Return the ID of the current object. + * + * @pre DiffObject must not be empty. + */ osmium::object_id_type id() const noexcept { + assert(m_prev && m_curr && m_next); return m_curr->id(); } + /** + * Return the version of the current object. + * + * @pre DiffObject must not be empty. + */ osmium::object_version_type version() const noexcept { + assert(m_prev && m_curr && m_next); return m_curr->version(); } + /** + * Return the changeset ID of the current object. + * + * @pre DiffObject must not be empty. + */ osmium::changeset_id_type changeset() const noexcept { + assert(m_prev && m_curr && m_next); return m_curr->changeset(); } + /** + * Return the timestamp when the current object version was created. + * + * @pre DiffObject must not be empty. + */ const osmium::Timestamp start_time() const noexcept { + assert(m_prev && m_curr && m_next); return m_curr->timestamp(); } @@ -118,8 +204,11 @@ namespace osmium { * is valid. If this is the last version of the object, this will * return a special "end of time" timestamp that is guaranteed to * be larger than any normal timestamp. + * + * @pre DiffObject must not be empty. */ const osmium::Timestamp end_time() const noexcept { + assert(m_prev && m_curr && m_next); return last() ? osmium::end_of_time() : m_next->timestamp(); } @@ -129,8 +218,11 @@ namespace osmium { * * This is a bit more complex than you'd think, because we have to * handle the case properly where the start_time() == end_time(). + * + * @pre DiffObject must not be empty. */ bool is_between(const osmium::Timestamp& from, const osmium::Timestamp& to) const noexcept { + assert(m_prev && m_curr && m_next); return start_time() < to && ((start_time() != end_time() && end_time() > from) || (start_time() == end_time() && end_time() >= from)); @@ -138,45 +230,42 @@ namespace osmium { /** * Current object version is visible at the given timestamp. + * + * @pre DiffObject must not be empty. */ bool is_visible_at(const osmium::Timestamp& timestamp) const noexcept { + assert(m_prev && m_curr && m_next); return start_time() <= timestamp && end_time() > timestamp && m_curr->visible(); } }; // class DiffObject - template + template class DiffObjectDerived : public DiffObject { public: - DiffObjectDerived(T& prev, T& curr, T& next) noexcept : + DiffObjectDerived(const T& prev, const T& curr, const T& next) noexcept : DiffObject(prev, curr, next) { } - DiffObjectDerived(const DiffObjectDerived&) = default; - DiffObjectDerived& operator=(const DiffObjectDerived&) = default; - - DiffObjectDerived(DiffObjectDerived&&) = default; - DiffObjectDerived& operator=(DiffObjectDerived&&) = default; - const T& prev() const noexcept { - return *static_cast(m_prev); + return static_cast(DiffObject::prev()); } const T& curr() const noexcept { - return *static_cast(m_curr); + return static_cast(DiffObject::curr()); } const T& next() const noexcept { - return *static_cast(m_next); + return static_cast(DiffObject::next()); } }; // class DiffObjectDerived - typedef DiffObjectDerived DiffNode; - typedef DiffObjectDerived DiffWay; - typedef DiffObjectDerived DiffRelation; + using DiffNode = DiffObjectDerived; + using DiffWay = DiffObjectDerived; + using DiffRelation = DiffObjectDerived; } // namespace osmium diff --git a/include/osmium/osm/entity.hpp b/include/osmium/osm/entity.hpp index ce292c8d6..c7f70553c 100644 --- a/include/osmium/osm/entity.hpp +++ b/include/osmium/osm/entity.hpp @@ -41,7 +41,7 @@ namespace osmium { namespace detail { - template + template inline TSubitem& subitem_of_type(TIter it, TIter end) { for (; it != end; ++it) { if (it->type() == TSubitem::itemtype) { diff --git a/include/osmium/osm/item_type.hpp b/include/osmium/osm/item_type.hpp index 54975e326..95826bc98 100644 --- a/include/osmium/osm/item_type.hpp +++ b/include/osmium/osm/item_type.hpp @@ -53,13 +53,18 @@ namespace osmium { relation_member_list = 0x13, relation_member_list_with_full_members = 0x23, outer_ring = 0x40, - inner_ring = 0x41 + inner_ring = 0x41, + changeset_discussion = 0x80 }; // enum class item_type /** * Return item_type for index: * 0 -> node, 1 -> way, 2 -> relation + * + * @param i Index. Must be between 0 and 2. + * + * @returns Item type. */ inline item_type nwr_index_to_item_type(unsigned int i) noexcept { assert(i <= 2); @@ -69,6 +74,10 @@ namespace osmium { /** * Return index for item_type: * node -> 0, way -> 1, relation -> 2 + * + * @param type Item type. Must be node, way, or relation. + * + * @returns Index. */ inline unsigned int item_type_to_nwr_index(item_type type) noexcept { unsigned int i = static_cast(type); @@ -102,6 +111,8 @@ namespace osmium { return item_type::outer_ring; case 'I': return item_type::inner_ring; + case 'D': + return item_type::changeset_discussion; default: return item_type::undefined; } @@ -136,6 +147,8 @@ namespace osmium { return 'O'; case item_type::inner_ring: return 'I'; + case item_type::changeset_discussion: + return 'D'; } } @@ -165,6 +178,8 @@ namespace osmium { return "outer_ring"; case item_type::inner_ring: return "inner_ring"; + case item_type::changeset_discussion: + return "changeset_discussion"; } } #pragma GCC diagnostic pop diff --git a/include/osmium/osm/location.hpp b/include/osmium/osm/location.hpp index 0d4fdc13d..f79117e0a 100644 --- a/include/osmium/osm/location.hpp +++ b/include/osmium/osm/location.hpp @@ -52,11 +52,11 @@ namespace osmium { */ struct invalid_location : public std::range_error { - invalid_location(const std::string& what) : + explicit invalid_location(const std::string& what) : std::range_error(what) { } - invalid_location(const char* what) : + explicit invalid_location(const char* what) : std::range_error(what) { } @@ -95,7 +95,7 @@ namespace osmium { return static_cast(std::round(c * coordinate_precision)); } - static OSMIUM_CONSTEXPR double fix_to_double(const int32_t c) noexcept { + static constexpr double fix_to_double(const int32_t c) noexcept { return static_cast(c) / coordinate_precision; } @@ -238,11 +238,11 @@ namespace osmium { /** * Locations are equal if both coordinates are equal. */ - inline OSMIUM_CONSTEXPR bool operator==(const Location& lhs, const Location& rhs) noexcept { + inline constexpr bool operator==(const Location& lhs, const Location& rhs) noexcept { return lhs.x() == rhs.x() && lhs.y() == rhs.y(); } - inline OSMIUM_CONSTEXPR bool operator!=(const Location& lhs, const Location& rhs) noexcept { + inline constexpr bool operator!=(const Location& lhs, const Location& rhs) noexcept { return ! (lhs == rhs); } @@ -251,19 +251,19 @@ namespace osmium { * the y coordinate. If either of the locations is * undefined the result is undefined. */ - inline OSMIUM_CONSTEXPR bool operator<(const Location& lhs, const Location& rhs) noexcept { + inline constexpr bool operator<(const Location& lhs, const Location& rhs) noexcept { return (lhs.x() == rhs.x() && lhs.y() < rhs.y()) || lhs.x() < rhs.x(); } - inline OSMIUM_CONSTEXPR bool operator>(const Location& lhs, const Location& rhs) noexcept { + inline constexpr bool operator>(const Location& lhs, const Location& rhs) noexcept { return rhs < lhs; } - inline OSMIUM_CONSTEXPR bool operator<=(const Location& lhs, const Location& rhs) noexcept { + inline constexpr bool operator<=(const Location& lhs, const Location& rhs) noexcept { return ! (rhs < lhs); } - inline OSMIUM_CONSTEXPR bool operator>=(const Location& lhs, const Location& rhs) noexcept { + inline constexpr bool operator>=(const Location& lhs, const Location& rhs) noexcept { return ! (lhs < rhs); } diff --git a/include/osmium/osm/node.hpp b/include/osmium/osm/node.hpp index 123bfc4fa..1ff7d1c28 100644 --- a/include/osmium/osm/node.hpp +++ b/include/osmium/osm/node.hpp @@ -41,8 +41,8 @@ DEALINGS IN THE SOFTWARE. namespace osmium { namespace builder { - template class ObjectBuilder; - } + template class ObjectBuilder; + } // namespace builder class Node : public OSMObject { diff --git a/include/osmium/osm/node_ref.hpp b/include/osmium/osm/node_ref.hpp index 72359cd0f..e1c9c12e1 100644 --- a/include/osmium/osm/node_ref.hpp +++ b/include/osmium/osm/node_ref.hpp @@ -54,15 +54,21 @@ namespace osmium { public: - NodeRef(const osmium::object_id_type ref = 0, const osmium::Location& location = Location()) noexcept : + constexpr NodeRef(const osmium::object_id_type ref = 0, const osmium::Location& location = Location()) noexcept : m_ref(ref), m_location(location) { } - osmium::object_id_type ref() const noexcept { + /** + * Get reference ID of this NodeRef. + */ + constexpr osmium::object_id_type ref() const noexcept { return m_ref; } + /** + * Get absolute value of the reference ID of this NodeRef. + */ osmium::unsigned_object_id_type positive_ref() const noexcept { return static_cast(std::abs(m_ref)); } @@ -74,31 +80,60 @@ namespace osmium { return m_location; } - osmium::Location location() const noexcept { + /** + * Get location of this NodeRef. + */ + constexpr osmium::Location location() const noexcept { return m_location; } + /** + * Get longitude of the location in this NodeRef. + * + * @throws osmium::invalid_location if the location is not set. + */ double lon() const { return m_location.lon(); } + /** + * Get latitude of the location in this NodeRef. + * + * @throws osmium::invalid_location if the location is not set. + */ double lat() const { return m_location.lat(); } - int32_t x() const noexcept { + /** + * Get internal x value of the location in this NodeRef. + */ + constexpr int32_t x() const noexcept { return m_location.x(); } - int32_t y() const noexcept { + /** + * Get internal y value of the location in this NodeRef. + */ + constexpr int32_t y() const noexcept { return m_location.y(); } + /** + * Set the referenced ID. + * + * @returns Reference to this NodeRef for chaining calls. + */ NodeRef& set_ref(const osmium::object_id_type ref) noexcept { m_ref = ref; return *this; } + /** + * Set the location. + * + * @returns Reference to this NodeRef for chaining calls. + */ NodeRef& set_location(const osmium::Location& location) noexcept { m_location = location; return *this; @@ -106,27 +141,50 @@ namespace osmium { }; // class NodeRef - inline bool operator==(const NodeRef& lhs, const NodeRef& rhs) noexcept { + /** + * Compare two NodeRefs. They are equal if they reference the same Node ID. + */ + inline constexpr bool operator==(const NodeRef& lhs, const NodeRef& rhs) noexcept { return lhs.ref() == rhs.ref(); } - inline bool operator!=(const NodeRef& lhs, const NodeRef& rhs) noexcept { + /** + * Compare two NodeRefs. They are not equal if they reference different + * Node IDs. + */ + inline constexpr bool operator!=(const NodeRef& lhs, const NodeRef& rhs) noexcept { return ! (lhs == rhs); } - inline bool operator<(const NodeRef& lhs, const NodeRef& rhs) noexcept { + /** + * Compare two NodeRefs. NodeRefs are ordered according to the Node ID + * they reference. + */ + inline constexpr bool operator<(const NodeRef& lhs, const NodeRef& rhs) noexcept { return lhs.ref() < rhs.ref(); } - inline bool operator>(const NodeRef& lhs, const NodeRef& rhs) noexcept { + /** + * Compare two NodeRefs. NodeRefs are ordered according to the Node ID + * they reference. + */ + inline constexpr bool operator>(const NodeRef& lhs, const NodeRef& rhs) noexcept { return rhs < lhs; } - inline bool operator<=(const NodeRef& lhs, const NodeRef& rhs) noexcept { + /** + * Compare two NodeRefs. NodeRefs are ordered according to the Node ID + * they reference. + */ + inline constexpr bool operator<=(const NodeRef& lhs, const NodeRef& rhs) noexcept { return ! (rhs < lhs); } - inline bool operator>=(const NodeRef& lhs, const NodeRef& rhs) noexcept { + /** + * Compare two NodeRefs. NodeRefs are ordered according to the Node ID + * they reference. + */ + inline constexpr bool operator>=(const NodeRef& lhs, const NodeRef& rhs) noexcept { return ! (lhs < rhs); } @@ -139,32 +197,32 @@ namespace osmium { } /** - * Functor to compare NodeRefs by Location instead of id. + * Functor to compare NodeRefs by Location instead of ID. */ struct location_equal { - bool operator()(const NodeRef& lhs, const NodeRef& rhs) const noexcept { + constexpr bool operator()(const NodeRef& lhs, const NodeRef& rhs) const noexcept { return lhs.location() == rhs.location(); } - typedef NodeRef first_argument_type; - typedef NodeRef second_argument_type; - typedef bool result_type; + using first_argument_type = NodeRef; + using second_argument_type = NodeRef; + using result_type = bool; }; // struct location_equal /** - * Functor to compare NodeRefs by Location instead of id. + * Functor to compare NodeRefs by Location instead of ID. */ struct location_less { - bool operator()(const NodeRef& lhs, const NodeRef& rhs) const noexcept { + constexpr bool operator()(const NodeRef& lhs, const NodeRef& rhs) const noexcept { return lhs.location() < rhs.location(); } - typedef NodeRef first_argument_type; - typedef NodeRef second_argument_type; - typedef bool result_type; + using first_argument_type = NodeRef; + using second_argument_type = NodeRef; + using result_type = bool; }; // struct location_less diff --git a/include/osmium/osm/node_ref_list.hpp b/include/osmium/osm/node_ref_list.hpp index f0dfedbc1..f990b88c0 100644 --- a/include/osmium/osm/node_ref_list.hpp +++ b/include/osmium/osm/node_ref_list.hpp @@ -44,29 +44,29 @@ DEALINGS IN THE SOFTWARE. namespace osmium { /** - * A vector of NodeRef objects. Usually this is not instantiated directly, - * but one of its subclasses are used. + * An ordered collection of NodeRef objects. Usually this is not + * instantiated directly, but one of its subclasses are used. */ class NodeRefList : public osmium::memory::Item { public: - NodeRefList(osmium::item_type itemtype) noexcept : + explicit NodeRefList(osmium::item_type itemtype) noexcept : osmium::memory::Item(sizeof(NodeRefList), itemtype) { } /** - * Checks whether the node list is empty. + * Checks whether the collection is empty. */ bool empty() const noexcept { return sizeof(NodeRefList) == byte_size(); } /** - * Returns the number of nodes in the list. + * Returns the number of NodeRefs in the collection. */ size_t size() const noexcept { - auto size_node_refs = osmium::memory::Item::byte_size() - sizeof(NodeRefList); + auto size_node_refs = byte_size() - sizeof(NodeRefList); assert(size_node_refs % sizeof(NodeRef) == 0); return size_node_refs / sizeof(NodeRef); } @@ -74,8 +74,9 @@ namespace osmium { /** * Access specified element. * - * @param n Get this element of the list. * @pre @code n < size() @endcode + * + * @param n Get the n-th element of the collection. */ const NodeRef& operator[](size_t n) const noexcept { assert(n < size()); @@ -104,16 +105,18 @@ namespace osmium { } /** - * Checks whether the first and last node in the list have the same ID. + * Checks whether the first and last node in the collection have the + * same ID. The locations are not checked. * * @pre @code !empty() @endcode */ bool is_closed() const noexcept { - return front().ref() == back().ref(); + return ends_have_same_id(); } /** - * Checks whether the first and last node in the list have the same ID. + * Checks whether the first and last node in the collection have the + * same ID. The locations are not checked. * * @pre @code !empty() @endcode */ @@ -122,8 +125,8 @@ namespace osmium { } /** - * Checks whether the first and last node in the list have the same - * location. The ID is not checked. + * Checks whether the first and last node in the collection have the + * same location. The IDs are not checked. * * @pre @code !empty() @endcode * @pre @code front().location() && back().location() @endcode @@ -133,9 +136,9 @@ namespace osmium { return front().location() == back().location(); } - typedef NodeRef* iterator; - typedef const NodeRef* const_iterator; - typedef std::reverse_iterator const_reverse_iterator; + using iterator = NodeRef*; + using const_iterator = const NodeRef*; + using const_reverse_iterator = std::reverse_iterator; /// Returns an iterator to the beginning. iterator begin() noexcept { diff --git a/include/osmium/osm/object.hpp b/include/osmium/osm/object.hpp index 8c745ce9b..c0f46adbd 100644 --- a/include/osmium/osm/object.hpp +++ b/include/osmium/osm/object.hpp @@ -281,7 +281,7 @@ namespace osmium { * @param timestamp Timestamp * @returns Reference to object to make calls chainable. */ - OSMObject& set_timestamp(const osmium::Timestamp timestamp) noexcept { + OSMObject& set_timestamp(const osmium::Timestamp& timestamp) noexcept { m_timestamp = timestamp; return *this; } @@ -355,38 +355,38 @@ namespace osmium { return cend(); } - template + template using t_iterator = osmium::memory::ItemIterator; - template + template using t_const_iterator = osmium::memory::ItemIterator; - template + template t_iterator begin() { return t_iterator(subitems_position(), next()); } - template + template t_iterator end() { return t_iterator(next(), next()); } - template + template t_const_iterator cbegin() const { return t_const_iterator(subitems_position(), next()); } - template + template t_const_iterator cend() const { return t_const_iterator(next(), next()); } - template + template t_const_iterator begin() const { return cbegin(); } - template + template t_const_iterator end() const { return cend(); } diff --git a/include/osmium/osm/relation.hpp b/include/osmium/osm/relation.hpp index 99a4f4cd1..eec51193d 100644 --- a/include/osmium/osm/relation.hpp +++ b/include/osmium/osm/relation.hpp @@ -47,9 +47,9 @@ DEALINGS IN THE SOFTWARE. namespace osmium { namespace builder { - template class ObjectBuilder; + template class ObjectBuilder; class RelationMemberListBuilder; - } + } // namespace builder class RelationMember : public osmium::memory::detail::ItemHelper { @@ -74,23 +74,21 @@ namespace osmium { return data() + osmium::memory::padded_length(sizeof(RelationMember) + m_role_size); } - template + template friend class osmium::memory::CollectionIterator; unsigned char* next() { if (full_member()) { return endpos() + reinterpret_cast(endpos())->byte_size(); - } else { - return endpos(); } + return endpos(); } unsigned const char* next() const { if (full_member()) { return endpos() + reinterpret_cast(endpos())->byte_size(); - } else { - return endpos(); } + return endpos(); } void set_role_size(string_size_type size) noexcept { diff --git a/include/osmium/osm/segment.hpp b/include/osmium/osm/segment.hpp index f3a82c97f..fe43102fc 100644 --- a/include/osmium/osm/segment.hpp +++ b/include/osmium/osm/segment.hpp @@ -65,12 +65,12 @@ namespace osmium { ~Segment() = default; /// Return first Location of Segment. - OSMIUM_CONSTEXPR osmium::Location first() const noexcept { + constexpr osmium::Location first() const noexcept { return m_first; } /// Return second Location of Segment. - OSMIUM_CONSTEXPR osmium::Location second() const noexcept { + constexpr osmium::Location second() const noexcept { return m_second; } @@ -84,11 +84,11 @@ namespace osmium { }; // class Segment /// Segments are equal if both their locations are equal - inline OSMIUM_CONSTEXPR bool operator==(const Segment& lhs, const Segment& rhs) noexcept { + inline constexpr bool operator==(const Segment& lhs, const Segment& rhs) noexcept { return lhs.first() == rhs.first() && lhs.second() == rhs.second(); } - inline OSMIUM_CONSTEXPR bool operator!=(const Segment& lhs, const Segment& rhs) noexcept { + inline constexpr bool operator!=(const Segment& lhs, const Segment& rhs) noexcept { return ! (lhs == rhs); } diff --git a/include/osmium/osm/tag.hpp b/include/osmium/osm/tag.hpp index 2e93ede24..4eba2210e 100644 --- a/include/osmium/osm/tag.hpp +++ b/include/osmium/osm/tag.hpp @@ -53,7 +53,7 @@ namespace osmium { Tag& operator=(const Tag&) = delete; Tag& operator=(Tag&&) = delete; - template + template friend class osmium::memory::CollectionIterator; static unsigned char* after_null(unsigned char* ptr) { @@ -122,9 +122,8 @@ namespace osmium { }); if (result == cend()) { return default_value; - } else { - return result->value(); } + return result->value(); } const char* operator[](const char* key) const noexcept { diff --git a/include/osmium/osm/timestamp.hpp b/include/osmium/osm/timestamp.hpp index 390f0e745..651b43f68 100644 --- a/include/osmium/osm/timestamp.hpp +++ b/include/osmium/osm/timestamp.hpp @@ -47,17 +47,18 @@ namespace osmium { /** * A timestamp. Internal representation is an unsigned 32bit integer - * holding seconds since epoch, so this will overflow in 2038. + * holding seconds since epoch (1970-01-01T00:00:00Z), so this will + * overflow in 2106. We can use an unsigned integer here, because the + * OpenStreetMap project was started long after 1970, so there will + * never be dates before that. */ class Timestamp { // length of ISO timestamp string yyyy-mm-ddThh:mm:ssZ\0 static constexpr int timestamp_length = 20 + 1; - /** - * The timestamp format for OSM timestamps in strftime(3) format. - * This is the ISO-Format yyyy-mm-ddThh:mm:ssZ - */ + // The timestamp format for OSM timestamps in strftime(3) format. + // This is the ISO-Format "yyyy-mm-ddThh:mm:ssZ". static const char* timestamp_format() { static const char f[timestamp_length] = "%Y-%m-%dT%H:%M:%SZ"; return f; @@ -67,19 +68,32 @@ namespace osmium { public: + /** + * Default construct an invalid Timestamp. + */ constexpr Timestamp() noexcept : m_timestamp(0) { } - // Not "explicit" so that conversions from time_t work - // like in node.timestamp(123); - constexpr Timestamp(time_t timestamp) noexcept : - m_timestamp(static_cast(timestamp)) { + /** + * Construct a Timestamp from any integer type containing the seconds + * since the epoch. This will not check for overruns, you have to + * make sure the value fits into a uint32_t which is used internally + * in the Timestamp. + * + * The constructor is not declared "explicit" so that conversions + * like @code node.set_timestamp(123); @endcode work. + */ + template ::value, int>::type = 0> + constexpr Timestamp(T timestamp) noexcept : + m_timestamp(uint32_t(timestamp)) { } /** - * Construct timestamp from ISO date/time string. - * Throws std::invalid_argument, if the timestamp can not be parsed. + * Construct timestamp from ISO date/time string in the format + * "yyyy-mm-ddThh:mm:ssZ". + * + * @throws std::invalid_argument if the timestamp can not be parsed. */ explicit Timestamp(const char* timestamp) { #ifndef _WIN32 @@ -105,16 +119,51 @@ namespace osmium { #endif } + /** + * Construct timestamp from ISO date/time string in the format + * "yyyy-mm-ddThh:mm:ssZ". + * + * @throws std::invalid_argument if the timestamp can not be parsed. + */ + explicit Timestamp(const std::string& timestamp) : + Timestamp(timestamp.c_str()) { + } + + /** + * Returns true if this timestamp is valid (ie set to something other + * than 0). + */ + bool valid() const noexcept { + return m_timestamp != 0; + } + + /// Explicit conversion into bool. + explicit constexpr operator bool() const noexcept { + return m_timestamp != 0; + } + + /// Explicit conversion into time_t. constexpr time_t seconds_since_epoch() const noexcept { - return static_cast(m_timestamp); - } - - constexpr operator time_t() const noexcept { - return static_cast(m_timestamp); + return time_t(m_timestamp); } + /// Explicit conversion into uint32_t. explicit constexpr operator uint32_t() const noexcept { - return m_timestamp; + return uint32_t(m_timestamp); + } + + /// Explicit conversion into uint64_t. + explicit constexpr operator uint64_t() const noexcept { + return uint64_t(m_timestamp); + } + + /** + * Implicit conversion into time_t. + * + * @deprecated You should call seconds_since_epoch() explicitly instead. + */ + OSMIUM_DEPRECATED constexpr operator time_t() const noexcept { + return static_cast(m_timestamp); } template @@ -128,7 +177,8 @@ namespace osmium { } /** - * Return UTC Unix time as string in ISO date/time format. + * Return UTC Unix time as string in ISO date/time + * ("yyyy-mm-ddThh:mm:ssZ") format. */ std::string to_iso() const { std::string s; @@ -156,12 +206,20 @@ namespace osmium { }; // class Timestamp - inline OSMIUM_CONSTEXPR Timestamp start_of_time() noexcept { + /** + * A special Timestamp guaranteed to be ordered before any other valid + * Timestamp. + */ + inline constexpr Timestamp start_of_time() noexcept { return Timestamp(1); } - inline OSMIUM_CONSTEXPR Timestamp end_of_time() noexcept { - return Timestamp(std::numeric_limits::max()); + /** + * A special Timestamp guaranteed to be ordered after any other valid + * Timestamp. + */ + inline constexpr Timestamp end_of_time() noexcept { + return Timestamp(std::numeric_limits::max()); } template @@ -170,6 +228,30 @@ namespace osmium { return out; } + inline bool operator==(const Timestamp& lhs, const Timestamp& rhs) noexcept { + return uint32_t(lhs) == uint32_t(rhs); + } + + inline bool operator!=(const Timestamp& lhs, const Timestamp& rhs) noexcept { + return !(lhs == rhs); + } + + inline bool operator<(const Timestamp& lhs, const Timestamp& rhs) noexcept { + return uint32_t(lhs) < uint32_t(rhs); + } + + inline bool operator>(const Timestamp& lhs, const Timestamp& rhs) noexcept { + return rhs < lhs; + } + + inline bool operator<=(const Timestamp& lhs, const Timestamp& rhs) noexcept { + return ! (rhs < lhs); + } + + inline bool operator>=(const Timestamp& lhs, const Timestamp& rhs) noexcept { + return ! (lhs < rhs); + } + template <> inline osmium::Timestamp min_op_start_value() { return end_of_time(); diff --git a/include/osmium/osm/types.hpp b/include/osmium/osm/types.hpp index b3414e594..e4250d966 100644 --- a/include/osmium/osm/types.hpp +++ b/include/osmium/osm/types.hpp @@ -49,6 +49,7 @@ namespace osmium { typedef uint32_t user_id_type; ///< Type for OSM user IDs. typedef int32_t signed_user_id_type; ///< Type for signed OSM user IDs. typedef uint32_t num_changes_type; ///< Type for changeset num_changes. + typedef uint32_t num_comments_type; ///< Type for changeset num_comments. /** * Size for strings in OSM data such as user names, tag keys, roles, etc. @@ -57,6 +58,9 @@ namespace osmium { */ typedef uint16_t string_size_type; + // maximum of 256 characters of max 4 bytes each (in UTF-8 encoding) + constexpr const int max_osm_string_length = 256 * 4; + } // namespace osmium #endif // OSMIUM_OSM_TYPES_HPP diff --git a/include/osmium/osm/types_from_string.hpp b/include/osmium/osm/types_from_string.hpp index b8de14c90..67ab2c157 100644 --- a/include/osmium/osm/types_from_string.hpp +++ b/include/osmium/osm/types_from_string.hpp @@ -43,9 +43,19 @@ DEALINGS IN THE SOFTWARE. #include #include +#include namespace osmium { + /** + * Convert string with object id to object_id_type. + * + * @pre input must not be nullptr. + * + * @param input Input string. + * + * @throws std::range_error if the value is out of range. + */ inline object_id_type string_to_object_id(const char* input) { assert(input); if (*input != '\0' && !std::isspace(*input)) { @@ -58,6 +68,19 @@ namespace osmium { throw std::range_error(std::string("illegal id: '") + input + "'"); } + /** + * Parse string with object type identifier followed by object id. This + * reads strings like "n1234" and "w10". + * + * @pre input must not be nullptr. + * + * @param input Input string. + * @param types Allowed types. Must not be osmium::osm_entity_bits::nothing. + * + * @returns std::pair of type and id. + * + * @throws std::range_error if the value is out of range. + */ inline std::pair string_to_object_id(const char* input, osmium::osm_entity_bits::type types) { assert(input); assert(types != osmium::osm_entity_bits::nothing); @@ -75,7 +98,7 @@ namespace osmium { namespace detail { - inline long string_to_ulong(const char* input, const char *name) { + inline unsigned long string_to_ulong(const char* input, const char *name) { if (*input != '\0' && *input != '-' && !std::isspace(*input)) { char* end; auto value = std::strtoul(input, &end, 10); @@ -88,27 +111,77 @@ namespace osmium { } // namespace detail + /** + * Convert string with object version to object_version_type. + * + * @pre input must not be nullptr. + * + * @param input Input string. + * + * @throws std::range_error if the value is out of range. + */ inline object_version_type string_to_object_version(const char* input) { assert(input); - return static_cast(detail::string_to_ulong(input, "version")); + return static_cast_with_assert(detail::string_to_ulong(input, "version")); } + /** + * Convert string with object version to object_version_type. + * + * @pre input must not be nullptr. + * + * @param input Input string. + * + * @throws std::range_error if the value is out of range. + */ inline changeset_id_type string_to_changeset_id(const char* input) { assert(input); - return static_cast(detail::string_to_ulong(input, "changeset")); + return static_cast_with_assert(detail::string_to_ulong(input, "changeset")); } + /** + * Convert string with user id to signed_user_id_type. + * + * @pre input must not be nullptr. + * + * @param input Input string. + * + * @throws std::range_error if the value is out of range. + */ inline signed_user_id_type string_to_user_id(const char* input) { assert(input); if (input[0] == '-' && input[1] == '1' && input[2] == '\0') { return -1; } - return static_cast(detail::string_to_ulong(input, "user id")); + return static_cast_with_assert(detail::string_to_ulong(input, "user id")); } + /** + * Convert string with number of changes to num_changes_type. + * + * @pre input must not be nullptr. + * + * @param input Input string. + * + * @throws std::range_error if the value is out of range. + */ inline num_changes_type string_to_num_changes(const char* input) { assert(input); - return static_cast(detail::string_to_ulong(input, "value for num changes")); + return static_cast_with_assert(detail::string_to_ulong(input, "value for num changes")); + } + + /** + * Convert string with number of comments to num_comments_type. + * + * @pre input must not be nullptr. + * + * @param input Input string. + * + * @throws std::range_error if the value is out of range. + */ + inline num_comments_type string_to_num_comments(const char* input) { + assert(input); + return static_cast_with_assert(detail::string_to_ulong(input, "value for num comments")); } } // namespace osmium diff --git a/include/osmium/osm/way.hpp b/include/osmium/osm/way.hpp index 3c5f1f6dc..90cde8c3c 100644 --- a/include/osmium/osm/way.hpp +++ b/include/osmium/osm/way.hpp @@ -43,8 +43,8 @@ DEALINGS IN THE SOFTWARE. namespace osmium { namespace builder { - template class ObjectBuilder; - } + template class ObjectBuilder; + } // namespace builder /** * List of node references (id and location) in a way. diff --git a/include/osmium/relations/collector.hpp b/include/osmium/relations/collector.hpp index 40e377393..7d27b3398 100644 --- a/include/osmium/relations/collector.hpp +++ b/include/osmium/relations/collector.hpp @@ -39,9 +39,10 @@ DEALINGS IN THE SOFTWARE. #include #include #include -#include +//#include #include +#include #include #include #include // IWYU pragma: keep @@ -55,9 +56,6 @@ DEALINGS IN THE SOFTWARE. namespace osmium { - class Node; - class Way; - /** * @brief Code related to the assembly of OSM relations */ @@ -91,7 +89,7 @@ namespace osmium { * * @tparam TRelations Are we interested in member relations? */ - template + template class Collector { /** @@ -124,82 +122,15 @@ namespace osmium { TCollector& m_collector; - /** - * This variable is initialized with the number of different - * kinds of OSM objects we are interested in. If we only need - * way members (for instance for the multipolygon collector) - * it is intialized with 1 for instance. If node and way - * members are needed, it is initialized with 2. - * - * In the after_* methods of this handler, it is decremented - * and once it reaches 0, we know we have all members available - * that we are ever going to get. - */ - int m_want_types; - - /** - * Find this object in the member vectors and add it to all - * relations that need it. - * - * @returns true if the member was added to at least one - * relation and false otherwise - */ - bool find_and_add_object(const osmium::OSMObject& object) { - auto& mmv = m_collector.member_meta(object.type()); - auto range = std::equal_range(mmv.begin(), mmv.end(), MemberMeta(object.id())); - - if (osmium::relations::count_not_removed(range.first, range.second) == 0) { - // nothing found - return false; - } - - { - m_collector.members_buffer().add_item(object); - const size_t member_offset = m_collector.members_buffer().commit(); - - for (auto it = range.first; it != range.second; ++it) { - it->set_buffer_offset(member_offset); - } - } - - for (auto it = range.first; it != range.second; ++it) { - MemberMeta& member_meta = *it; - if (member_meta.removed()) { - break; - } - assert(member_meta.member_id() == object.id()); - assert(member_meta.relation_pos() < m_collector.m_relations.size()); - RelationMeta& relation_meta = m_collector.m_relations[member_meta.relation_pos()]; -// std::cerr << " => " << member_meta.member_pos() << " < " << m_collector.get_relation(relation_meta).members().size() << " (id=" << m_collector.get_relation(relation_meta).id() << ")\n"; - assert(member_meta.member_pos() < m_collector.get_relation(relation_meta).members().size()); -// std::cerr << " add way " << member_meta.member_id() << " to rel " << m_collector.get_relation(relation_meta).id() << " at pos " << member_meta.member_pos() << "\n"; - relation_meta.got_one_member(); - if (relation_meta.has_all_members()) { - const size_t relation_offset = member_meta.relation_pos(); - m_collector.complete_relation(relation_meta); - m_collector.m_relations[relation_offset] = RelationMeta(); - m_collector.possibly_purge_removed_members(); - } - } - - // Remove MemberMetas that were marked as removed. - mmv.erase(std::remove_if(mmv.begin(), mmv.end(), [](MemberMeta& mm) { - return mm.removed(); - }), mmv.end()); - - return true; - } - public: HandlerPass2(TCollector& collector) noexcept : - m_collector(collector), - m_want_types((TNodes?1:0) + (TWays?1:0) + (TRelations?1:0)) { + m_collector(collector) { } void node(const osmium::Node& node) { if (TNodes) { - if (! find_and_add_object(node)) { + if (! m_collector.find_and_add_object(node)) { m_collector.node_not_in_any_relation(node); } } @@ -207,7 +138,7 @@ namespace osmium { void way(const osmium::Way& way) { if (TWays) { - if (! find_and_add_object(way)) { + if (! m_collector.find_and_add_object(way)) { m_collector.way_not_in_any_relation(way); } } @@ -215,7 +146,7 @@ namespace osmium { void relation(const osmium::Relation& relation) { if (TRelations) { - if (! find_and_add_object(relation)) { + if (! m_collector.find_and_add_object(relation)) { m_collector.relation_not_in_any_relation(relation); } } @@ -227,6 +158,8 @@ namespace osmium { }; // class HandlerPass2 + private: + HandlerPass2 m_handler_pass2; // All relations we are interested in will be kept in this buffer @@ -375,6 +308,8 @@ namespace osmium { return m_members_buffer.get(offset); } + private: + /** * Tell the Collector that you are interested in this relation * and want it kept until all members have been assembled and @@ -424,6 +359,84 @@ namespace osmium { std::sort(m_member_meta[2].begin(), m_member_meta[2].end()); } + /** + * Find this object in the member vectors and add it to all + * relations that need it. + * + * @returns true if the member was added to at least one + * relation and false otherwise + */ + bool find_and_add_object(const osmium::OSMObject& object) { + auto& mmv = member_meta(object.type()); + auto range = std::equal_range(mmv.begin(), mmv.end(), MemberMeta(object.id())); + + if (osmium::relations::count_not_removed(range.first, range.second) == 0) { + // nothing found + return false; + } + + { + members_buffer().add_item(object); + const size_t member_offset = members_buffer().commit(); + + for (auto it = range.first; it != range.second; ++it) { + it->set_buffer_offset(member_offset); + } + } + + for (auto it = range.first; it != range.second; ++it) { + MemberMeta& member_meta = *it; + if (member_meta.removed()) { + break; + } + assert(member_meta.member_id() == object.id()); + assert(member_meta.relation_pos() < m_relations.size()); + RelationMeta& relation_meta = m_relations[member_meta.relation_pos()]; +// std::cerr << " => " << member_meta.member_pos() << " < " << get_relation(relation_meta).members().size() << " (id=" << get_relation(relation_meta).id() << ")\n"; + assert(member_meta.member_pos() < get_relation(relation_meta).members().size()); +// std::cerr << " add way " << member_meta.member_id() << " to rel " << get_relation(relation_meta).id() << " at pos " << member_meta.member_pos() << "\n"; + relation_meta.got_one_member(); + if (relation_meta.has_all_members()) { + const size_t relation_offset = member_meta.relation_pos(); + static_cast(this)->complete_relation(relation_meta); + clear_member_metas(relation_meta); + m_relations[relation_offset] = RelationMeta(); + possibly_purge_removed_members(); + } + } + + // Remove MemberMetas that were marked as removed. + mmv.erase(std::remove_if(mmv.begin(), mmv.end(), [](MemberMeta& mm) { + return mm.removed(); + }), mmv.end()); + + return true; + } + + void clear_member_metas(const osmium::relations::RelationMeta& relation_meta) { + const osmium::Relation& relation = get_relation(relation_meta); + for (const auto& member : relation.members()) { + if (member.ref() != 0) { + auto& mmv = member_meta(member.type()); + auto range = std::equal_range(mmv.begin(), mmv.end(), MemberMeta(member.ref())); + assert(range.first != range.second); + + // if this is the last time this object was needed + // then mark it as removed + if (osmium::relations::count_not_removed(range.first, range.second) == 1) { + get_member(range.first->buffer_offset()).set_removed(true); + } + + for (auto it = range.first; it != range.second; ++it) { + if (!it->removed() && relation.id() == get_relation(it->relation_pos()).id()) { + it->remove(); + break; + } + } + } + } + } + public: uint64_t used_memory() const { @@ -474,14 +487,14 @@ namespace osmium { return range.first->buffer_offset(); } - template + template void read_relations(TIter begin, TIter end) { HandlerPass1 handler(*static_cast(this)); osmium::apply(begin, end, handler); sort_member_meta(); } - template + template void read_relations(TSource& source) { read_relations(std::begin(source), std::end(source)); source.close(); @@ -490,7 +503,7 @@ namespace osmium { void moving_in_buffer(size_t old_offset, size_t new_offset) { const osmium::OSMObject& object = m_members_buffer.get(old_offset); auto& mmv = member_meta(object.type()); - auto range = std::equal_range(mmv.begin(), mmv.end(), osmium::relations::MemberMeta(object.id())); + auto range = std::equal_range(mmv.begin(), mmv.end(), MemberMeta(object.id())); for (auto it = range.first; it != range.second; ++it) { assert(it->buffer_offset() == old_offset); it->set_buffer_offset(new_offset); @@ -506,13 +519,15 @@ namespace osmium { void possibly_purge_removed_members() { ++m_count_complete; if (m_count_complete > 10000) { // XXX - const size_t size_before = m_members_buffer.committed(); +// const size_t size_before = m_members_buffer.committed(); m_members_buffer.purge_removed(this); +/* const size_t size_after = m_members_buffer.committed(); double percent = static_cast(size_before - size_after); percent /= size_before; percent *= 100; -// std::cerr << "PURGE (size before=" << size_before << " after=" << size_after << " purged=" << (size_before - size_after) << " / " << static_cast(percent) << "%)\n"; + std::cerr << "PURGE (size before=" << size_before << " after=" << size_after << " purged=" << (size_before - size_after) << " / " << static_cast(percent) << "%)\n"; +*/ m_count_complete = 0; } } diff --git a/include/osmium/relations/detail/member_meta.hpp b/include/osmium/relations/detail/member_meta.hpp index a45088eab..ea86734ea 100644 --- a/include/osmium/relations/detail/member_meta.hpp +++ b/include/osmium/relations/detail/member_meta.hpp @@ -144,7 +144,7 @@ namespace osmium { * @param begin Begin of iterator range * @param end End of iterator range */ - template + template inline typename std::iterator_traits::difference_type count_not_removed(TIter begin, TIter end) { return std::count_if(begin, end, [](MemberMeta& mm) { return !mm.removed(); diff --git a/include/osmium/tags/filter.hpp b/include/osmium/tags/filter.hpp index 3c1946c54..0d3fc4ee2 100644 --- a/include/osmium/tags/filter.hpp +++ b/include/osmium/tags/filter.hpp @@ -46,7 +46,7 @@ namespace osmium { namespace tags { - template + template struct match_key { bool operator()(const TKey& rule_key, const char* tag_key) { return rule_key == tag_key; @@ -59,7 +59,7 @@ namespace osmium { } }; // struct match_key_prefix - template + template struct match_value { bool operator()(const TValue& rule_value, const char* tag_value) { return rule_value == tag_value; @@ -73,7 +73,7 @@ namespace osmium { } }; // struct match_value - template , class TValueComp=match_value> + template , typename TValueComp=match_value> class Filter { typedef TKey key_type; @@ -115,7 +115,7 @@ namespace osmium { m_default_result(default_result) { } - template ::value, int>::type = 0> + template ::value, int>::type = 0> Filter& add(bool result, const key_type& key, const value_type& value) { m_rules.emplace_back(result, false, key, value); return *this; diff --git a/include/osmium/tags/taglist.hpp b/include/osmium/tags/taglist.hpp index d7c78dc79..8fc9c68cd 100644 --- a/include/osmium/tags/taglist.hpp +++ b/include/osmium/tags/taglist.hpp @@ -45,17 +45,17 @@ namespace osmium { */ namespace tags { - template + template inline bool match_any_of(const osmium::TagList& tag_list, TFilter&& filter) { return std::any_of(tag_list.cbegin(), tag_list.cend(), std::forward(filter)); } - template + template inline bool match_all_of(const osmium::TagList& tag_list, TFilter&& filter) { return std::all_of(tag_list.cbegin(), tag_list.cend(), std::forward(filter)); } - template + template inline bool match_none_of(const osmium::TagList& tag_list, TFilter&& filter) { return std::none_of(tag_list.cbegin(), tag_list.cend(), std::forward(filter)); } diff --git a/include/osmium/thread/function_wrapper.hpp b/include/osmium/thread/function_wrapper.hpp index fe0a49257..2fc0b7e22 100644 --- a/include/osmium/thread/function_wrapper.hpp +++ b/include/osmium/thread/function_wrapper.hpp @@ -50,7 +50,9 @@ namespace osmium { struct impl_base { virtual ~impl_base() = default; - virtual void call() = 0; + virtual bool call() { + return true; + } }; // struct impl_base @@ -58,28 +60,38 @@ namespace osmium { template struct impl_type : impl_base { + F m_functor; - impl_type(F&& functor) : - m_functor(std::move(functor)) { + explicit impl_type(F&& functor) : + m_functor(std::forward(functor)) { } - void call() override { + bool call() override { m_functor(); + return false; } + }; // struct impl_type public: // Constructor must not be "explicit" for wrapper // to work seemlessly. - template - function_wrapper(F&& f) : - impl(new impl_type(std::move(f))) { + template + function_wrapper(TFunction&& f) : + impl(new impl_type(std::forward(f))) { } - void operator()() { - impl->call(); + // The integer parameter is only used to signal that we want + // the special function wrapper that makes the worker thread + // shut down. + function_wrapper(int) : + impl(new impl_base()) { + } + + bool operator()() { + return impl->call(); } function_wrapper() = default; diff --git a/include/osmium/thread/pool.hpp b/include/osmium/thread/pool.hpp index 391603108..f7b4f4038 100644 --- a/include/osmium/thread/pool.hpp +++ b/include/osmium/thread/pool.hpp @@ -54,6 +54,32 @@ namespace osmium { */ namespace thread { + namespace detail { + + // Maximum number of allowed pool threads (just to keep the user + // from setting something silly). + constexpr const int max_pool_threads = 256; + + inline int get_pool_size(int num_threads, int user_setting, unsigned hardware_concurrency) { + if (num_threads == 0) { + num_threads = user_setting ? user_setting : -2; + } + + if (num_threads < 0) { + num_threads += hardware_concurrency; + } + + if (num_threads < 1) { + num_threads = 1; + } else if (num_threads > max_pool_threads) { + num_threads = max_pool_threads; + } + + return num_threads; + } + + } // namespace detail + /** * Thread pool. */ @@ -83,7 +109,6 @@ namespace osmium { }; // class thread_joiner - std::atomic m_done; osmium::thread::Queue m_work_queue; std::vector m_threads; thread_joiner m_joiner; @@ -91,11 +116,15 @@ namespace osmium { void worker_thread() { osmium::thread::set_thread_name("_osmium_worker"); - while (!m_done) { + while (true) { function_wrapper task; m_work_queue.wait_and_pop_with_timeout(task); if (task) { - task(); + if (task()) { + // The called tasks returns true only when the + // worker thread should shut down. + return; + } } } } @@ -113,26 +142,17 @@ namespace osmium { * In all cases the minimum number of threads in the pool is 1. */ explicit Pool(int num_threads, size_t max_queue_size) : - m_done(false), m_work_queue(max_queue_size, "work"), m_threads(), m_joiner(m_threads), - m_num_threads(num_threads) { - - if (m_num_threads == 0) { - m_num_threads = osmium::config::get_pool_threads(); - } - - if (m_num_threads <= 0) { - m_num_threads = std::max(1, static_cast(std::thread::hardware_concurrency()) + m_num_threads); - } + m_num_threads(detail::get_pool_size(num_threads, osmium::config::get_pool_threads(), std::thread::hardware_concurrency())) { try { for (int i = 0; i < m_num_threads; ++i) { m_threads.push_back(std::thread(&Pool::worker_thread, this)); } } catch (...) { - m_done = true; + shutdown_all_workers(); throw; } } @@ -147,8 +167,15 @@ namespace osmium { return pool; } + void shutdown_all_workers() { + for (int i = 0; i < m_num_threads; ++i) { + // The special function wrapper makes a worker shut down. + m_work_queue.push(function_wrapper{0}); + } + } + ~Pool() { - m_done = true; + shutdown_all_workers(); m_work_queue.shutdown(); } diff --git a/include/osmium/thread/queue.hpp b/include/osmium/thread/queue.hpp index 76ad9a020..65b18475c 100644 --- a/include/osmium/thread/queue.hpp +++ b/include/osmium/thread/queue.hpp @@ -75,6 +75,9 @@ namespace osmium { /// The largest size the queue has been so far. size_t m_largest_size; + /// The number of times push() was called on the queue. + std::atomic m_push_counter; + /// The number of times the queue was full and a thread pushing /// to the queue was blocked. std::atomic m_full_counter; @@ -89,7 +92,7 @@ namespace osmium { * 0 for an unlimited size. * @param name Optional name for this queue. (Used for debugging.) */ - Queue(size_t max_size = 0, const std::string& name = "") : + explicit Queue(size_t max_size = 0, const std::string& name = "") : m_max_size(max_size), m_name(name), m_mutex(), @@ -99,6 +102,7 @@ namespace osmium { #ifdef OSMIUM_DEBUG_QUEUE_SIZE , m_largest_size(0), + m_push_counter(0), m_full_counter(0) #endif { @@ -107,7 +111,7 @@ namespace osmium { ~Queue() { shutdown(); #ifdef OSMIUM_DEBUG_QUEUE_SIZE - std::cerr << "queue '" << m_name << "' with max_size=" << m_max_size << " had largest size " << m_largest_size << " and was full " << m_full_counter << " times\n"; + std::cerr << "queue '" << m_name << "' with max_size=" << m_max_size << " had largest size " << m_largest_size << " and was full " << m_full_counter << " times in " << m_push_counter << " push() calls\n"; #endif } @@ -116,6 +120,9 @@ namespace osmium { * call will block if the queue is full. */ void push(T value) { +#ifdef OSMIUM_DEBUG_QUEUE_SIZE + ++m_push_counter; +#endif if (m_max_size) { while (size() >= m_max_size) { std::this_thread::sleep_for(full_queue_sleep_duration); diff --git a/include/osmium/thread/util.hpp b/include/osmium/thread/util.hpp index ca4f6dd53..a20e618a0 100644 --- a/include/osmium/thread/util.hpp +++ b/include/osmium/thread/util.hpp @@ -49,7 +49,7 @@ namespace osmium { * the exception stored in the future if there was one. Otherwise it * will just return. */ - template + template inline void check_for_exception(std::future& future) { if (future.valid() && future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { future.get(); @@ -60,7 +60,7 @@ namespace osmium { * Wait until the given future becomes ready. Will block if the future * is not ready. Can be called more than once unlike future.get(). */ - template + template inline void wait_until_done(std::future& future) { if (future.valid()) { future.get(); @@ -71,15 +71,44 @@ namespace osmium { * Set name of current thread for debugging. This only works on Linux. */ #ifdef __linux__ - inline void set_thread_name(const char* name) { + inline void set_thread_name(const char* name) noexcept { prctl(PR_SET_NAME, name, 0, 0, 0); } #else - inline void set_thread_name(const char*) { + inline void set_thread_name(const char*) noexcept { // intentionally left blank } #endif + class thread_handler { + + std::thread m_thread; + + public: + + thread_handler() : + m_thread() { + } + + template + explicit thread_handler(TFunction&& f, TArgs&&... args) : + m_thread(std::forward(f), std::forward(args)...) { + } + + thread_handler(const thread_handler&) = delete; + thread_handler& operator=(const thread_handler&) = delete; + + thread_handler(thread_handler&&) = default; + thread_handler& operator=(thread_handler&&) = default; + + ~thread_handler() { + if (m_thread.joinable()) { + m_thread.join(); + } + } + + }; // class thread_handler + } // namespace thread } // namespace osmium diff --git a/include/osmium/util/compatibility.hpp b/include/osmium/util/compatibility.hpp index 90d85c502..27adca7b7 100644 --- a/include/osmium/util/compatibility.hpp +++ b/include/osmium/util/compatibility.hpp @@ -34,14 +34,20 @@ DEALINGS IN THE SOFTWARE. */ // Workarounds for MSVC which doesn't support -// * constexpr in all cases yet // * [[noreturn]] #ifdef _MSC_VER -# define OSMIUM_CONSTEXPR # define OSMIUM_NORETURN __declspec(noreturn) #else -# define OSMIUM_CONSTEXPR constexpr # define OSMIUM_NORETURN [[noreturn]] #endif +// [[deprecated]] is only available in C++14, use this for the time being +#ifdef __GNUC__ +# define OSMIUM_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +# define OSMIUM_DEPRECATED __declspec(deprecated) +#else +# define OSMIUM_DEPRECATED +#endif + #endif // OSMIUM_UTIL_COMPATIBILITY_HPP diff --git a/include/osmium/util/config.hpp b/include/osmium/util/config.hpp index 3285eedbb..e31cd6a9b 100644 --- a/include/osmium/util/config.hpp +++ b/include/osmium/util/config.hpp @@ -49,7 +49,7 @@ namespace osmium { if (env) { return std::atoi(env); } - return -2; + return 0; } inline bool use_pool_threads_for_pbf_parsing() { diff --git a/include/osmium/util/data_file.hpp b/include/osmium/util/data_file.hpp deleted file mode 100644 index 22bf1910a..000000000 --- a/include/osmium/util/data_file.hpp +++ /dev/null @@ -1,194 +0,0 @@ -#ifndef OSMIUM_UTIL_DATA_FILE_HPP -#define OSMIUM_UTIL_DATA_FILE_HPP - -/* - -This file is part of Osmium (http://osmcode.org/libosmium). - -Copyright 2013-2015 Jochen Topf 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 -#include -#include -#include -#include -#include - -#ifdef _WIN32 -# include -# include -#endif - -#include - -namespace osmium { - - namespace util { - - /** - * Class wrapper for convenient access to some low-level file - * functions. - */ - class DataFile { - - FILE* m_file; - - public: - - /** - * Create and open a temporary file. It is removed after opening. - * - * @throws std::system_error if something went wrong. - */ - DataFile() : - m_file(::tmpfile()) { - if (!m_file) { - throw std::system_error(errno, std::system_category(), "tmpfile failed"); - } - } - - /** - * Create and open a temporary file with the specified size. It - * is removed after opening. - * - * @throws std::system_error if something went wrong. - */ - explicit DataFile(size_t size) : - DataFile() { - grow(size); - } - - /** - * Create and open a named file. - * - * @param filename the name of the file - * @param writable should the file be writable? - * @throws std::system_error if something went wrong. - */ - DataFile(const char* filename, bool writable) : - m_file(::fopen(filename, writable ? "wb+" : "rb" )) { - if (!m_file) { - throw std::system_error(errno, std::system_category(), "fopen failed"); - } - } - - /** - * Create and open a named file. - * - * @param filename the name of the file - * @param writable should the file be writable? - * @throws std::system_error if something went wrong. - */ - DataFile(const std::string& filename, bool writable) : - DataFile(filename.c_str(), writable) { - } - - /** - * In boolean context the DataFile class returns true if the file - * is open. - */ - operator bool() const noexcept { - return m_file != nullptr; - } - - /** - * Close the file. - * - * Does nothing if the file is already closed. - * - * @throws std::system_error if file could not be closed - */ - void close() { - if (m_file) { - if (::fclose(m_file) != 0) { - throw std::system_error(errno, std::system_category(), "fclose failed"); - } - m_file = nullptr; - } - } - - ~DataFile() noexcept { - try { - close(); - } catch (std::system_error&) { - // ignore - } - } - - /** - * Get file descriptor of underlying file. - * - * @throws std::runtime_errro if file is not open - * @throws std::system_error if fileno(3) call failed - */ - int fd() const { - if (!m_file) { - throw std::runtime_error("no open file"); - } - - int fd = ::fileno(m_file); - - if (fd == -1) { - throw std::system_error(errno, std::system_category(), "fileno failed"); - } - - return fd; - } - - /** - * Ask the operating system for the size of this file. - * - * @throws std::system_error if fstat(2) call failed - */ - size_t size() const { - return osmium::util::file_size(fd()); - } - - /** - * Grow file to given size. - * - * If the file is large enough already, nothing is done. - * The file is never shrunk. - * - * @throws std::system_error if ftruncate(2) call failed - */ - void grow(size_t new_size) const { - if (size() < new_size) { - osmium::util::resize_file(fd(), new_size); - } - } - - }; // class DataFile - - } // namespace util - -} // namespace osmium - - -#endif // OSMIUM_UTIL_DATA_FILE_HPP diff --git a/include/osmium/util/delta.hpp b/include/osmium/util/delta.hpp index 0c77e5242..558a1d4f9 100644 --- a/include/osmium/util/delta.hpp +++ b/include/osmium/util/delta.hpp @@ -37,6 +37,8 @@ DEALINGS IN THE SOFTWARE. #include #include +#include + namespace osmium { namespace util { @@ -44,25 +46,39 @@ namespace osmium { /** * Helper class for delta encoding. */ - template + template class DeltaEncode { - T m_value; + static_assert(std::is_integral::value, + "DeltaEncode value type must be some integer"); + + static_assert(std::is_integral::value && std::is_signed::value, + "DeltaEncode delta type must be some signed integer"); + + TValue m_value; public: - DeltaEncode(T value = 0) : + using value_type = TValue; + using delta_type = TDelta; + + explicit DeltaEncode(TValue value = 0) : m_value(value) { } - void clear() { + void clear() noexcept { m_value = 0; } - T update(T new_value) { + TValue value() const noexcept { + return m_value; + } + + TDelta update(TValue new_value) noexcept { using std::swap; swap(m_value, new_value); - return m_value - new_value; + return static_cast_with_assert(m_value) - + static_cast_with_assert(new_value); } }; // class DeltaEncode @@ -70,52 +86,63 @@ namespace osmium { /** * Helper class for delta decoding. */ - template + template class DeltaDecode { - T m_value; + static_assert(std::is_integral::value, + "DeltaDecode value type must be some integer"); + + static_assert(std::is_integral::value && std::is_signed::value, + "DeltaDecode delta type must be some signed integer"); + + TValue m_value; public: + using value_type = TValue; + using delta_type = TDelta; + DeltaDecode() : m_value(0) { } - void clear() { + void clear() noexcept { m_value = 0; } - T update(T delta) { - m_value += delta; + TValue update(TDelta delta) noexcept { + m_value = static_cast_with_assert( + static_cast_with_assert(m_value) + delta); return m_value; } }; // class DeltaDecode - template + template class DeltaEncodeIterator : public std::iterator { - typedef TValue value_type; - TBaseIterator m_it; TBaseIterator m_end; - value_type m_delta; - DeltaEncode m_value; TTransform m_trans; + DeltaEncode m_value; + TDelta m_delta; public: + using value_type = TValue; + using delta_type = TDelta; + DeltaEncodeIterator(TBaseIterator first, TBaseIterator last, TTransform& trans) : m_it(first), m_end(last), - m_delta(m_trans(m_it)), - m_value(m_delta), - m_trans(trans) { + m_trans(trans), + m_value(m_it != m_end ? m_trans(m_it) : 0), + m_delta(static_cast_with_assert(m_value.value())) { } DeltaEncodeIterator& operator++() { - if (m_it != m_end) { - m_delta = m_value.update(m_trans(++m_it)); + if (++m_it != m_end) { + m_delta = m_value.update(m_trans(m_it)); } return *this; } @@ -126,7 +153,7 @@ namespace osmium { return tmp; } - value_type operator*() { + TDelta operator*() { return m_delta; } diff --git a/include/osmium/util/double.hpp b/include/osmium/util/double.hpp index 85a250807..e0701394c 100644 --- a/include/osmium/util/double.hpp +++ b/include/osmium/util/double.hpp @@ -68,8 +68,12 @@ namespace osmium { #endif assert(len > 0 && len < max_double_length); - while (buffer[len-1] == '0') --len; - if (buffer[len-1] == '.') --len; + while (buffer[len-1] == '0') { + --len; + } + if (buffer[len-1] == '.') { + --len; + } return std::copy_n(buffer, len, iterator); } diff --git a/include/osmium/util/file.hpp b/include/osmium/util/file.hpp index 461f4e642..39e01af83 100644 --- a/include/osmium/util/file.hpp +++ b/include/osmium/util/file.hpp @@ -52,6 +52,8 @@ DEALINGS IN THE SOFTWARE. # define ftruncate _chsize_s #endif +#include + namespace osmium { namespace util { @@ -92,7 +94,7 @@ namespace osmium { * @throws std::system_error If ftruncate(2) call failed */ inline void resize_file(int fd, size_t new_size) { - if (::ftruncate(fd, new_size) != 0) { + if (::ftruncate(fd, static_cast_with_assert(new_size)) != 0) { throw std::system_error(errno, std::system_category(), "ftruncate failed"); } } @@ -108,7 +110,7 @@ namespace osmium { return si.dwPageSize; #else // Unix implementation - return ::sysconf(_SC_PAGESIZE); + return size_t(::sysconf(_SC_PAGESIZE)); #endif } diff --git a/include/osmium/util/memory_mapping.hpp b/include/osmium/util/memory_mapping.hpp index e48aff282..b187c3c80 100644 --- a/include/osmium/util/memory_mapping.hpp +++ b/include/osmium/util/memory_mapping.hpp @@ -38,11 +38,13 @@ DEALINGS IN THE SOFTWARE. #include #include +#include #include #ifndef _WIN32 # include #else +# include # include # include # include @@ -85,6 +87,9 @@ namespace osmium { * On Unix systems this wraps the mmap(), munmap(), and the mremap() * system calls. On Windows it wraps the CreateFileMapping(), * CloseHandle(), MapViewOfFile(), and UnmapViewOfFile() functions. + * + * On Windows the file will be set to binary mode before the memory + * mapping. */ class MemoryMapping { @@ -169,7 +174,8 @@ private: * created, otherwise a mapping based on the file descriptor will * be created. * - * @pre size > 0 or mode == write_shared oder write_private + * @pre @code size > 0 @endcode or + * @code mode == write_shared || mode == write_private @endcode * * @param size Size of the mapping in bytes * @param mode Mapping mode: readonly, or writable (shared or private) @@ -179,8 +185,12 @@ private: */ MemoryMapping(size_t size, mapping_mode mode, int fd=-1, off_t offset=0); - /// DEPRECATED: For backwards compatibility - MemoryMapping(size_t size, bool writable=true, int fd=-1, off_t offset=0) : + /** + * @deprecated + * For backwards compatibility only. Use the constructor taking + * a mapping_mode as second argument instead. + */ + OSMIUM_DEPRECATED MemoryMapping(size_t size, bool writable=true, int fd=-1, off_t offset=0) : MemoryMapping(size, writable ? mapping_mode::write_shared : mapping_mode::readonly, fd, offset) { } @@ -209,7 +219,7 @@ private: try { unmap(); } catch (std::system_error&) { - // ignore + // Ignore any exceptions because destructor must not throw. } } @@ -228,8 +238,9 @@ private: * systems it will unmap and remap the memory. This can only be * done for file-based mappings, not anonymous mappings! * - * @param new_size Number of bytes to resize to - * @throws std::system_error if the remapping fails + * @param new_size Number of bytes to resize to (must be > 0). + * + * @throws std::system_error if the remapping fails. */ void resize(size_t new_size); @@ -237,7 +248,7 @@ private: * In a boolean context a MemoryMapping is true when it is a valid * existing mapping. */ - operator bool() const noexcept { + explicit operator bool() const noexcept { return is_valid(); } @@ -349,8 +360,12 @@ private: m_mapping(sizeof(T) * size, mode, fd, sizeof(T) * offset) { } - /// DEPRECATED: For backwards compatibility - TypedMemoryMapping(size_t size, bool writable, int fd, off_t offset = 0) : + /** + * @deprecated + * For backwards compatibility only. Use the constructor taking + * a mapping_mode as second argument instead. + */ + OSMIUM_DEPRECATED TypedMemoryMapping(size_t size, bool writable, int fd, off_t offset = 0) : m_mapping(sizeof(T) * size, writable ? MemoryMapping::mapping_mode::write_shared : MemoryMapping::mapping_mode::readonly, fd, sizeof(T) * offset) { } @@ -375,7 +390,7 @@ private: * Releases the mapping by calling unmap(). Will never throw. * Call unmap() instead if you want to be notified of any error. */ - ~TypedMemoryMapping() = default; + ~TypedMemoryMapping() noexcept = default; /** * Unmap a mapping. If the mapping is not valid, it will do @@ -405,7 +420,7 @@ private: * In a boolean context a TypedMemoryMapping is true when it is * a valid existing mapping. */ - operator bool() const noexcept { + explicit operator bool() const noexcept { return !!m_mapping; } @@ -655,6 +670,9 @@ inline HANDLE osmium::util::MemoryMapping::get_handle() const noexcept { } inline HANDLE osmium::util::MemoryMapping::create_file_mapping() const noexcept { + if (m_fd != -1) { + _setmode(m_fd, _O_BINARY); + } return CreateFileMapping(get_handle(), nullptr, get_protection(), osmium::util::dword_hi(static_cast(m_size) + m_offset), osmium::util::dword_lo(static_cast(m_size) + m_offset), nullptr); } diff --git a/include/osmium/util/options.hpp b/include/osmium/util/options.hpp index fea075230..1019c8bbf 100644 --- a/include/osmium/util/options.hpp +++ b/include/osmium/util/options.hpp @@ -47,46 +47,65 @@ namespace osmium { * as a base class. Options are stored and retrieved by key using the * different set() and get() methods. * + * Both keys and values are stored as strings. The values "true", + * "yes", "false", and "no" are interpreted as boolean values in some + * functions. + * * You can iterate over all set options. Dereferencing an iterator * yields a std::pair of the key and value strings. */ class Options { - typedef std::map option_map; + using option_map = std::map; option_map m_options; public: - typedef option_map::iterator iterator; - typedef option_map::const_iterator const_iterator; - typedef option_map::value_type value_type; + using iterator = option_map::iterator; + using const_iterator = option_map::const_iterator; + using value_type = option_map::value_type; + /** + * Construct empty option set. + */ Options() = default; + /** + * Construct option set from initializer list: + * @code + * Options options{ { "foo", "true" }, { "bar", "17" } }; + * @endcode + */ explicit Options(const std::initializer_list& values) : m_options(values) { } - Options(const Options&) = default; - Options& operator=(const Options&) = default; - - Options(Options&&) = default; - Options& operator=(Options&&) = default; - - ~Options() = default; - + /** + * Set option 'key' to 'value'. + */ void set(const std::string& key, const std::string& value) { m_options[key] = value; } + /** + * Set option 'key' to 'value'. + */ void set(const std::string& key, const char* value) { m_options[key] = value; } + /** + * Set option 'key' to 'value'. + */ void set(const std::string& key, bool value) { m_options[key] = value ? "true" : "false"; } + /** + * Set option from string in the form 'key=value'. If the string + * contains no equal sign, the whole string is the key and it will + * be set to "true". + */ void set(std::string data) { size_t pos = data.find_first_of('='); if (pos == std::string::npos) { @@ -99,7 +118,7 @@ namespace osmium { } /** - * Get value of "key" option. If not set the default_value (or + * Get value of "key" option. If not set, the default_value (or * empty string) is returned. */ std::string get(const std::string& key, const std::string& default_value="") const noexcept { @@ -112,36 +131,67 @@ namespace osmium { /** * Is this option set to a true value ("true" or "yes")? + * Will return false if the value is unset. */ bool is_true(const std::string& key) const noexcept { std::string value = get(key); return (value == "true" || value == "yes"); } + /** + * Is this option not set to a false value ("false" or "no")? + * Will return true if the value is unset. + */ + bool is_not_false(const std::string& key) const noexcept { + std::string value = get(key); + return !(value == "false" || value == "no"); + } + + /** + * The number of options set. + */ size_t size() const noexcept { return m_options.size(); } + /** + * Returns an iterator to the beginning. + */ iterator begin() noexcept { return m_options.begin(); } + /** + * Returns an iterator to the end. + */ iterator end() noexcept { return m_options.end(); } + /** + * Returns an iterator to the beginning. + */ const_iterator begin() const noexcept { return m_options.cbegin(); } + /** + * Returns an iterator to the end. + */ const_iterator end() const noexcept { return m_options.cend(); } + /** + * Returns an iterator to the beginning. + */ const_iterator cbegin() const noexcept { return m_options.cbegin(); } + /** + * Returns a iterator to the end. + */ const_iterator cend() const noexcept { return m_options.cend(); } diff --git a/include/osmium/visitor.hpp b/include/osmium/visitor.hpp index 0250f11d4..c76eb17df 100644 --- a/include/osmium/visitor.hpp +++ b/include/osmium/visitor.hpp @@ -35,6 +35,7 @@ DEALINGS IN THE SOFTWARE. #include +#include #include // IWYU pragma: keep #include #include @@ -43,22 +44,16 @@ DEALINGS IN THE SOFTWARE. namespace osmium { - class TagList; - class WayNodeList; - class RelationMemberList; - class OuterRing; - class InnerRing; - namespace memory { class Item; - } + } // namespace memory namespace detail { template using ConstIfConst = typename std::conditional::value, typename std::add_const::type, U>::type; - template + template inline void apply_item_recurse(TItem& item, THandler& handler) { switch (item.type()) { case osmium::item_type::undefined: @@ -98,10 +93,13 @@ namespace osmium { case osmium::item_type::inner_ring: handler.inner_ring(static_cast&>(item)); break; + case osmium::item_type::changeset_discussion: + handler.changeset_discussion(static_cast&>(item)); + break; } } - template + template inline void apply_item_recurse(const osmium::OSMEntity& item, THandler& handler) { switch (item.type()) { case osmium::item_type::node: @@ -128,7 +126,7 @@ namespace osmium { } } - template + template inline void apply_item_recurse(osmium::OSMEntity& item, THandler& handler) { switch (item.type()) { case osmium::item_type::node: @@ -155,7 +153,7 @@ namespace osmium { } } - template + template inline void apply_item_recurse(const osmium::OSMObject& item, THandler& handler) { switch (item.type()) { case osmium::item_type::node: @@ -179,7 +177,7 @@ namespace osmium { } } - template + template inline void apply_item_recurse(osmium::OSMObject& item, THandler& handler) { switch (item.type()) { case osmium::item_type::node: @@ -203,18 +201,18 @@ namespace osmium { } } - template + template inline void apply_item_recurse(TItem& item, THandler& handler, TRest&... more) { apply_item_recurse(item, handler); apply_item_recurse(item, more...); } - template + template inline void flush_recurse(THandler& handler) { handler.flush(); } - template + template inline void flush_recurse(THandler& handler, TRest&... more) { flush_recurse(handler); flush_recurse(more...); @@ -222,17 +220,17 @@ namespace osmium { } // namespace detail - template + template inline void apply_item(const osmium::memory::Item& item, THandlers&... handlers) { detail::apply_item_recurse(item, handlers...); } - template + template inline void apply_item(osmium::memory::Item& item, THandlers&... handlers) { detail::apply_item_recurse(item, handlers...); } - template + template inline void apply(TIterator it, TIterator end, THandlers&... handlers) { for (; it != end; ++it) { detail::apply_item_recurse(*it, handlers...); @@ -240,12 +238,12 @@ namespace osmium { detail::flush_recurse(handlers...); } - template + template inline void apply(TContainer& c, THandlers&... handlers) { apply(std::begin(c), std::end(c), handlers...); } - template + template inline void apply(const osmium::memory::Buffer& buffer, THandlers&... handlers) { apply(buffer.cbegin(), buffer.cend(), handlers...); } diff --git a/include/protozero/byteswap.hpp b/include/protozero/byteswap.hpp index d019c28c5..a018c1c17 100644 --- a/include/protozero/byteswap.hpp +++ b/include/protozero/byteswap.hpp @@ -10,30 +10,51 @@ documentation. *****************************************************************************/ +/** + * @file byteswap.hpp + * + * @brief Contains functions to swap bytes in values (for different endianness). + */ + +#include #include +#include + namespace protozero { +/** + * Swap N byte value between endianness formats. This template function must + * be specialized to actually work. + */ template inline void byteswap(const char* /*data*/, char* /*result*/) { - assert(false); -} - -template <> -inline void byteswap<1>(const char* data, char* result) { - result[0] = data[0]; + static_assert(N == 1, "Can only swap 4 or 8 byte values"); } +/** + * Swap 4 byte value (int32_t, uint32_t, float) between endianness formats. + */ template <> inline void byteswap<4>(const char* data, char* result) { +#ifdef PROTOZERO_USE_BUILTIN_BSWAP + *reinterpret_cast(result) = __builtin_bswap32(*reinterpret_cast(data)); +#else result[3] = data[0]; result[2] = data[1]; result[1] = data[2]; result[0] = data[3]; +#endif } +/** + * Swap 8 byte value (int64_t, uint64_t, double) between endianness formats. + */ template <> inline void byteswap<8>(const char* data, char* result) { +#ifdef PROTOZERO_USE_BUILTIN_BSWAP + *reinterpret_cast(result) = __builtin_bswap64(*reinterpret_cast(data)); +#else result[7] = data[0]; result[6] = data[1]; result[5] = data[2]; @@ -42,6 +63,7 @@ inline void byteswap<8>(const char* data, char* result) { result[2] = data[5]; result[1] = data[6]; result[0] = data[7]; +#endif } } // end namespace protozero diff --git a/include/protozero/config.hpp b/include/protozero/config.hpp new file mode 100644 index 000000000..4086994fb --- /dev/null +++ b/include/protozero/config.hpp @@ -0,0 +1,57 @@ +#ifndef PROTOZERO_CONFIG_HPP +#define PROTOZERO_CONFIG_HPP + +/***************************************************************************** + +protozero - Minimalistic protocol buffer decoder and encoder in C++. + +This file is from https://github.com/mapbox/protozero where you can find more +documentation. + +*****************************************************************************/ + +#include + +/** + * @file config.hpp + * + * @brief Contains macro checks for different configurations. + */ + +#define PROTOZERO_LITTLE_ENDIAN 1234 +#define PROTOZERO_BIG_ENDIAN 4321 + +// Find out which byte order the machine has. +#if defined(__BYTE_ORDER) +# if (__BYTE_ORDER == __LITTLE_ENDIAN) +# define PROTOZERO_BYTE_ORDER PROTOZERO_LITTLE_ENDIAN +# endif +# if (__BYTE_ORDER == __BIG_ENDIAN) +# define PROTOZERO_BYTE_ORDER PROTOZERO_BIG_ENDIAN +# endif +#else +// This probably isn't a very good default, but might do until we figure +// out something better. +# define PROTOZERO_BYTE_ORDER PROTOZERO_LITTLE_ENDIAN +#endif + +// On some ARM machines and depending on compiler settings access to unaligned +// floating point values will result in a SIGBUS. Do not use the bare pointers +// in this case. +#if PROTOZERO_BYTE_ORDER == PROTOZERO_LITTLE_ENDIAN +# if !defined(__arm__) && !defined(_M_ARM) +# define PROTOZERO_USE_BARE_POINTER_FOR_PACKED_FIXED +# endif +#endif + +// Check whether __builtin_bswap is available +#if defined(__GNUC__) || defined(__clang__) +# define PROTOZERO_USE_BUILTIN_BSWAP +#endif + +// Wrapper for assert() used for testing +#ifndef protozero_assert +# define protozero_assert(x) assert(x) +#endif + +#endif // PROTOZERO_CONFIG_HPP diff --git a/include/protozero/pbf_builder.hpp b/include/protozero/pbf_builder.hpp index d49a7ba59..063fa9cb9 100644 --- a/include/protozero/pbf_builder.hpp +++ b/include/protozero/pbf_builder.hpp @@ -10,6 +10,12 @@ documentation. *****************************************************************************/ +/** + * @file pbf_builder.hpp + * + * @brief Contains the pbf_builder template class. + */ + #include #include @@ -17,10 +23,22 @@ documentation. namespace protozero { +/** + * The pbf_builder is used to write PBF formatted messages into a buffer. It + * is based on the pbf_writer class and has all the same methods. The + * difference is that whereever the pbf_writer class takes an integer tag, + * this template class takes a tag of the template type T. + * + * Almost all methods in this class can throw an std::bad_alloc exception if + * the std::string used as a buffer wants to resize. + * + * Read the tutorial to understand how this class is used. + */ template class pbf_builder : public pbf_writer { - static_assert(std::is_same::type>::value, "T must be enum with underlying type protozero::pbf_tag_type"); + static_assert(std::is_same::type>::value, + "T must be enum with underlying type protozero::pbf_tag_type"); public: @@ -35,6 +53,7 @@ public: pbf_writer(parent_writer, pbf_tag_type(tag)) { } +/// @cond INTERNAL #define PROTOZERO_WRITER_WRAP_ADD_SCALAR(name, type) \ inline void add_##name(T tag, type value) { \ pbf_writer::add_##name(pbf_tag_type(tag), value); \ @@ -55,6 +74,9 @@ public: PROTOZERO_WRITER_WRAP_ADD_SCALAR(float, float) PROTOZERO_WRITER_WRAP_ADD_SCALAR(double, double) +#undef PROTOZERO_WRITER_WRAP_ADD_SCALAR +/// @endcond + inline void add_bytes(T tag, const char* value, size_t size) { pbf_writer::add_bytes(pbf_tag_type(tag), value, size); } @@ -83,6 +105,7 @@ public: pbf_writer::add_message(pbf_tag_type(tag), value); } +/// @cond INTERNAL #define PROTOZERO_WRITER_WRAP_ADD_PACKED(name) \ template \ inline void add_packed_##name(T tag, InputIterator first, InputIterator last) { \ @@ -104,6 +127,9 @@ public: PROTOZERO_WRITER_WRAP_ADD_PACKED(float) PROTOZERO_WRITER_WRAP_ADD_PACKED(double) +#undef PROTOZERO_WRITER_WRAP_ADD_PACKED +/// @endcond + }; } // end namespace protozero diff --git a/include/protozero/pbf_message.hpp b/include/protozero/pbf_message.hpp index af29a00f4..7fef06f81 100644 --- a/include/protozero/pbf_message.hpp +++ b/include/protozero/pbf_message.hpp @@ -10,6 +10,12 @@ documentation. *****************************************************************************/ +/** + * @file pbf_message.hpp + * + * @brief Contains the pbf_message class. + */ + #include #include @@ -17,6 +23,44 @@ documentation. namespace protozero { +/** + * This class represents a protobuf message. Either a top-level message or + * a nested sub-message. Top-level messages can be created from any buffer + * with a pointer and length: + * + * @code + * enum class Message : protozero::pbf_tag_type { + * ... + * }; + * + * std::string buffer; + * // fill buffer... + * pbf_message message(buffer.data(), buffer.size()); + * @endcode + * + * Sub-messages are created using get_message(): + * + * @code + * enum class SubMessage : protozero::pbf_tag_type { + * ... + * }; + * + * pbf_message message(...); + * message.next(); + * pbf_message submessage = message.get_message(); + * @endcode + * + * All methods of the pbf_message class except get_bytes() and get_string() + * provide the strong exception guarantee, ie they either succeed or do not + * change the pbf_message object they are called on. Use the get_data() method + * instead of get_bytes() or get_string(), if you need this guarantee. + * + * This template class is based on the pbf_reader class and has all the same + * methods. The difference is that whereever the pbf_reader class takes an + * integer tag, this template class takes a tag of the template type T. + * + * Read the tutorial to understand how this class is used. + */ template class pbf_message : public pbf_reader { diff --git a/include/protozero/pbf_reader.hpp b/include/protozero/pbf_reader.hpp index 1c5ed0d70..aced901c6 100644 --- a/include/protozero/pbf_reader.hpp +++ b/include/protozero/pbf_reader.hpp @@ -16,7 +16,6 @@ documentation. * @brief Contains the pbf_reader class. */ -#include #include #include #include @@ -24,19 +23,15 @@ documentation. #include #include -#include +#include #include +#include #include -#if __BYTE_ORDER != __LITTLE_ENDIAN +#if PROTOZERO_BYTE_ORDER != PROTOZERO_LITTLE_ENDIAN # include #endif -/// Wrapper for assert() used for testing -#ifndef protozero_assert -# define protozero_assert(x) assert(x) -#endif - namespace protozero { /** @@ -77,19 +72,27 @@ class pbf_reader { // The tag of the current field. pbf_tag_type m_tag = 0; + // Copy N bytes from src to dest on little endian machines, on big endian + // swap the bytes in the process. + template + static void copy_or_byteswap(const char* src, void* dest) noexcept { +#if PROTOZERO_BYTE_ORDER == PROTOZERO_LITTLE_ENDIAN + memcpy(dest, src, N); +#else + byteswap(src, reinterpret_cast(dest)); +#endif + } + template inline T get_fixed() { T result; skip_bytes(sizeof(T)); -#if __BYTE_ORDER == __LITTLE_ENDIAN - memcpy(&result, m_data - sizeof(T), sizeof(T)); -#else - byteswap(m_data - sizeof(T), reinterpret_cast(&result)); -#endif + copy_or_byteswap(m_data - sizeof(T), &result); return result; } -#if __BYTE_ORDER == __LITTLE_ENDIAN +#ifdef PROTOZERO_USE_BARE_POINTER_FOR_PACKED_FIXED + template inline std::pair packed_fixed() { protozero_assert(tag() != 0 && "call next() before accessing field value"); @@ -128,7 +131,7 @@ class pbf_reader { T operator*() { T result; - byteswap(m_data, reinterpret_cast(&result)); + copy_or_byteswap(m_data , &result); return result; } @@ -161,6 +164,7 @@ class pbf_reader { return std::make_pair(const_fixed_iterator(m_data-len, m_data), const_fixed_iterator(m_data, m_data)); } + #endif template inline T get_varint(); @@ -866,8 +870,16 @@ bool pbf_reader::next() { protozero_assert(((m_tag > 0 && m_tag < 19000) || (m_tag > 19999 && m_tag <= ((1 << 29) - 1))) && "tag out of range"); m_wire_type = pbf_wire_type(value & 0x07); -// XXX do we want this check? or should it throw an exception? -// protozero_assert((m_wire_type <=2 || m_wire_type == 5) && "illegal wire type"); + switch (m_wire_type) { + case pbf_wire_type::varint: + case pbf_wire_type::fixed64: + case pbf_wire_type::length_delimited: + case pbf_wire_type::fixed32: + break; + default: + throw unknown_pbf_wire_type_exception(); + } + return true; } diff --git a/include/protozero/pbf_writer.hpp b/include/protozero/pbf_writer.hpp index 53cbfdf1c..2b78cb889 100644 --- a/include/protozero/pbf_writer.hpp +++ b/include/protozero/pbf_writer.hpp @@ -16,7 +16,6 @@ documentation. * @brief Contains the pbf_writer class. */ -#include #include #include #include @@ -24,18 +23,14 @@ documentation. #include #include +#include #include #include -#if __BYTE_ORDER != __LITTLE_ENDIAN +#if PROTOZERO_BYTE_ORDER != PROTOZERO_LITTLE_ENDIAN # include #endif -/// Wrapper for assert() used for testing -#ifndef protozero_assert -# define protozero_assert(x) assert(x) -#endif - namespace protozero { /** @@ -71,7 +66,7 @@ class pbf_writer { inline void add_fixed(T value) { protozero_assert(m_pos == 0 && "you can't add fields to a parent pbf_writer if there is an existing pbf_writer for a submessage"); protozero_assert(m_data); -#if __BYTE_ORDER == __LITTLE_ENDIAN +#if PROTOZERO_BYTE_ORDER == PROTOZERO_LITTLE_ENDIAN m_data->append(reinterpret_cast(&value), sizeof(T)); #else auto size = m_data->size(); @@ -229,7 +224,9 @@ public: */ inline void add_bool(pbf_tag_type tag, bool value) { add_field(tag, pbf_wire_type::varint); - add_fixed(value); + protozero_assert(m_pos == 0 && "you can't add fields to a parent pbf_writer if there is an existing pbf_writer for a submessage"); + protozero_assert(m_data); + m_data->append(1, value); } /** @@ -378,7 +375,7 @@ public: inline void add_bytes(pbf_tag_type tag, const char* value, size_t size) { protozero_assert(m_pos == 0 && "you can't add fields to a parent pbf_writer if there is an existing pbf_writer for a submessage"); protozero_assert(m_data); - assert(size <= std::numeric_limits::max()); + protozero_assert(size <= std::numeric_limits::max()); add_length_varint(tag, pbf_length_type(size)); m_data->append(value, size); } diff --git a/include/protozero/varint.hpp b/include/protozero/varint.hpp index bc9c3296d..27536fd39 100644 --- a/include/protozero/varint.hpp +++ b/include/protozero/varint.hpp @@ -16,10 +16,6 @@ documentation. * @brief Contains low-level varint and zigzag encoding and decoding functions. */ -#if __BYTE_ORDER != __LITTLE_ENDIAN -# error "This code only works on little endian machines." -#endif - #include #include diff --git a/include/protozero/version.hpp b/include/protozero/version.hpp new file mode 100644 index 000000000..4f129acc6 --- /dev/null +++ b/include/protozero/version.hpp @@ -0,0 +1,22 @@ +#ifndef PROTOZERO_VERSION_HPP +#define PROTOZERO_VERSION_HPP + +/***************************************************************************** + +protozero - Minimalistic protocol buffer decoder and encoder in C++. + +This file is from https://github.com/mapbox/protozero where you can find more +documentation. + +*****************************************************************************/ + +#define PROTOZERO_VERSION_MAJOR 1 +#define PROTOZERO_VERSION_MINOR 2 +#define PROTOZERO_VERSION_PATCH 3 + +#define PROTOZERO_VERSION_CODE (PROTOZERO_VERSION_MAJOR * 10000 + PROTOZERO_VERSION_MINOR * 100 + PROTOZERO_VERSION_PATCH) + +#define PROTOZERO_VERSION_STRING "1.2.3" + + +#endif // PROTOZERO_VERSION_HPP diff --git a/scripts/travis_install.sh b/scripts/travis_install.sh deleted file mode 100755 index 119e9fd15..000000000 --- a/scripts/travis_install.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/sh -# -# travis_install.sh -# - -if [ "$TRAVIS_OS_NAME" = "osx" ]; then - - brew install google-sparsehash || true - - brew install --without-python boost || true - - # workaround for gdal homebrew problem - brew remove gdal - brew install gdal - -fi - -cd .. -git clone --quiet --depth 1 https://github.com/osmcode/osm-testdata.git - diff --git a/scripts/travis_script.sh b/scripts/travis_script.sh deleted file mode 100755 index 75b3b3657..000000000 --- a/scripts/travis_script.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/sh -# -# travis_script.sh -# - -mkdir build -cd build - -# GCC ignores the pragmas in the code that disable the "return-type" warning -# selectively, so use this workaround. -if [ "${CXX}" = "g++" ]; then - WORKAROUND="-DCMAKE_CXX_FLAGS=-Wno-return-type" -else - WORKAROUND="" -fi - -if [ "${CXX}" = "g++" ]; then - CXX=g++-4.8 - CC=gcc-4.8 -fi - -cmake -LA \ - -DCMAKE_BUILD_TYPE=${BUILD_TYPE} \ - ${WORKAROUND} \ - .. - -make VERBOSE=1 -ctest --output-on-failure - diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 00474577a..f57416120 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -106,6 +106,7 @@ add_unit_test(basic test_timestamp) add_unit_test(basic test_types_from_string) add_unit_test(basic test_way) +add_unit_test(buffer test_buffer_basics) add_unit_test(buffer test_buffer_node) add_unit_test(buffer test_buffer_purge) @@ -133,9 +134,15 @@ add_unit_test(index test_id_to_location ENABLE_IF ${SPARSEHASH_FOUND}) add_unit_test(io test_bzip2 ENABLE_IF ${BZIP2_FOUND} LIBS ${BZIP2_LIBRARIES}) add_unit_test(io test_file_formats) -add_unit_test(io test_reader LIBS "${OSMIUM_XML_LIBRARIES}") +add_unit_test(io test_reader LIBS "${OSMIUM_XML_LIBRARIES};${OSMIUM_PBF_LIBRARIES}") +add_unit_test(io test_reader_with_mock_decompression ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES}) +add_unit_test(io test_reader_with_mock_parser ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT}) +add_unit_test(io test_output_utils) add_unit_test(io test_output_iterator ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT}) add_unit_test(io test_string_table) +add_unit_test(io test_writer ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES}) +add_unit_test(io test_writer_with_mock_compression ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES}) +add_unit_test(io test_writer_with_mock_encoder ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES}) add_unit_test(tags test_filter) add_unit_test(tags test_operators) @@ -144,7 +151,6 @@ add_unit_test(tags test_tag_list) add_unit_test(thread test_pool ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT}) add_unit_test(util test_cast_with_assert) -add_unit_test(util test_data_file) add_unit_test(util test_delta) add_unit_test(util test_double) add_unit_test(util test_file) diff --git a/test/data-tests/CMakeLists.txt b/test/data-tests/CMakeLists.txt index 89aead98e..a36c31cfd 100644 --- a/test/data-tests/CMakeLists.txt +++ b/test/data-tests/CMakeLists.txt @@ -88,11 +88,11 @@ set_tests_properties(testdata-overview PROPERTIES # #----------------------------------------------------------------------------- -find_package(Ruby 1.9) +find_program(RUBY ruby) find_package(Gem COMPONENTS json) find_program(SPATIALITE spatialite) -if(RUBY_FOUND AND GEM_json_FOUND AND SPATIALITE) +if(RUBY AND GEM_json_FOUND AND SPATIALITE) add_executable(testdata-multipolygon testdata-multipolygon.cpp) target_link_libraries(testdata-multipolygon ${OSMIUM_XML_LIBRARIES} @@ -102,7 +102,7 @@ if(RUBY_FOUND AND GEM_json_FOUND AND SPATIALITE) add_test(NAME testdata-multipolygon COMMAND ${CMAKE_COMMAND} -D OSM_TESTDATA=${OSM_TESTDATA} - -D RUBY=${RUBY_EXECUTABLE} + -D RUBY=${RUBY} -P ${CMAKE_CURRENT_SOURCE_DIR}/run-testdata-multipolygon.cmake) set_tests_properties(testdata-multipolygon PROPERTIES LABELS "data;slow") diff --git a/test/data-tests/testdata-multipolygon.cpp b/test/data-tests/testdata-multipolygon.cpp index 0fd0d9849..cf4fc521a 100644 --- a/test/data-tests/testdata-multipolygon.cpp +++ b/test/data-tests/testdata-multipolygon.cpp @@ -3,6 +3,8 @@ #include #include +#include + #include #include @@ -41,10 +43,9 @@ inline tagmap_type create_map(const osmium::TagList& taglist) { class TestHandler : public osmium::handler::Handler { - OGRDataSource* m_data_source; - OGRLayer* m_layer_point; - OGRLayer* m_layer_linestring; - OGRLayer* m_layer_polygon; + gdalcpp::Layer m_layer_point; + gdalcpp::Layer m_layer_lines; + gdalcpp::Layer m_layer_mpoly; osmium::geom::OGRFactory<> m_ogr_factory; osmium::geom::WKTFactory<> m_wkt_factory; @@ -55,84 +56,20 @@ class TestHandler : public osmium::handler::Handler { public: - TestHandler(OGRDataSource* data_source) : - m_data_source(data_source), + explicit TestHandler(gdalcpp::Dataset& dataset) : + m_layer_point(dataset, "points", wkbPoint), + m_layer_lines(dataset, "lines", wkbLineString), + m_layer_mpoly(dataset, "multipolygons", wkbMultiPolygon), m_out("multipolygon-tests.json") { - OGRSpatialReference sparef; - sparef.SetWellKnownGeogCS("WGS84"); + m_layer_point.add_field("id", OFTReal, 10); + m_layer_point.add_field("type", OFTString, 30); - /**************/ + m_layer_lines.add_field("id", OFTReal, 10); + m_layer_lines.add_field("type", OFTString, 30); - m_layer_point = m_data_source->CreateLayer("points", &sparef, wkbPoint, nullptr); - if (!m_layer_point) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_point_field_id("id", OFTReal); - layer_point_field_id.SetWidth(10); - - if (m_layer_point->CreateField(&layer_point_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_point_field_type("type", OFTString); - layer_point_field_type.SetWidth(30); - - if (m_layer_point->CreateField(&layer_point_field_type) != OGRERR_NONE) { - std::cerr << "Creating type field failed.\n"; - exit(1); - } - - /**************/ - - m_layer_linestring = m_data_source->CreateLayer("lines", &sparef, wkbLineString, nullptr); - if (!m_layer_linestring) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_linestring_field_id("id", OFTReal); - layer_linestring_field_id.SetWidth(10); - - if (m_layer_linestring->CreateField(&layer_linestring_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_linestring_field_type("type", OFTString); - layer_linestring_field_type.SetWidth(30); - - if (m_layer_linestring->CreateField(&layer_linestring_field_type) != OGRERR_NONE) { - std::cerr << "Creating type field failed.\n"; - exit(1); - } - - /**************/ - - m_layer_polygon = m_data_source->CreateLayer("multipolygons", &sparef, wkbMultiPolygon, nullptr); - if (!m_layer_polygon) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_polygon_field_id("id", OFTInteger); - layer_polygon_field_id.SetWidth(10); - - if (m_layer_polygon->CreateField(&layer_polygon_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_polygon_field_from_type("from_type", OFTString); - layer_polygon_field_from_type.SetWidth(1); - - if (m_layer_polygon->CreateField(&layer_polygon_field_from_type) != OGRERR_NONE) { - std::cerr << "Creating from_type field failed.\n"; - exit(1); - } + m_layer_mpoly.add_field("id", OFTReal, 10); + m_layer_mpoly.add_field("from_type", OFTString, 1); } ~TestHandler() { @@ -140,34 +77,18 @@ public: } void node(const osmium::Node& node) { - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_point->GetLayerDefn()); - std::unique_ptr ogr_point = m_ogr_factory.create_point(node); - feature->SetGeometry(ogr_point.get()); - feature->SetField("id", static_cast(node.id())); - feature->SetField("type", node.tags().get_value_by_key("type")); - - if (m_layer_point->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); + gdalcpp::Feature feature(m_layer_point, m_ogr_factory.create_point(node)); + feature.set_field("id", static_cast(node.id())); + feature.set_field("type", node.tags().get_value_by_key("type")); + feature.add_to_layer(); } void way(const osmium::Way& way) { try { - std::unique_ptr ogr_linestring = m_ogr_factory.create_linestring(way); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_linestring->GetLayerDefn()); - feature->SetGeometry(ogr_linestring.get()); - feature->SetField("id", static_cast(way.id())); - feature->SetField("type", way.tags().get_value_by_key("type")); - - if (m_layer_linestring->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); + gdalcpp::Feature feature(m_layer_lines, m_ogr_factory.create_linestring(way)); + feature.set_field("id", static_cast(way.id())); + feature.set_field("type", way.tags().get_value_by_key("type")); + feature.add_to_layer(); } catch (osmium::geometry_error&) { std::cerr << "Ignoring illegal geometry for way " << way.id() << ".\n"; } @@ -200,10 +121,8 @@ public: m_out << "INVALID\"\n}"; } try { - std::unique_ptr ogr_polygon = m_ogr_factory.create_multipolygon(area); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_polygon->GetLayerDefn()); - feature->SetGeometry(ogr_polygon.get()); - feature->SetField("id", static_cast(area.orig_id())); + gdalcpp::Feature feature(m_layer_mpoly, m_ogr_factory.create_multipolygon(area)); + feature.set_field("id", static_cast(area.orig_id())); std::string from_type; if (area.from_way()) { @@ -211,14 +130,8 @@ public: } else { from_type = "r"; } - feature->SetField("from_type", from_type.c_str()); - - if (m_layer_polygon->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); + feature.set_field("from_type", from_type.c_str()); + feature.add_to_layer(); } catch (osmium::geometry_error&) { std::cerr << "Ignoring illegal geometry for area " << area.id() << " created from " << (area.from_way() ? "way" : "relation") << " with id=" << area.orig_id() << ".\n"; } @@ -228,26 +141,6 @@ public: /* ================================================== */ -OGRDataSource* initialize_database(const std::string& output_format, const std::string& output_filename) { - OGRRegisterAll(); - - OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(output_format.c_str()); - if (!driver) { - std::cerr << output_format << " driver not available.\n"; - exit(1); - } - - CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); - const char* options[] = { "SPATIALITE=TRUE", nullptr }; - OGRDataSource* data_source = driver->CreateDataSource(output_filename.c_str(), const_cast(options)); - if (!data_source) { - std::cerr << "Creation of output file failed.\n"; - exit(1); - } - - return data_source; -} - int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " INFILE\n"; @@ -258,9 +151,10 @@ int main(int argc, char* argv[]) { std::string input_filename(argv[1]); std::string output_filename("multipolygon.db"); - OGRDataSource* data_source = initialize_database(output_format, output_filename); + CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); + gdalcpp::Dataset dataset{output_format, output_filename, gdalcpp::SRS{}, { "SPATIALITE=TRUE" }}; - osmium::area::ProblemReporterOGR problem_reporter(data_source); + osmium::area::ProblemReporterOGR problem_reporter(dataset); osmium::area::Assembler::config_type assembler_config(&problem_reporter); assembler_config.enable_debug_output(); osmium::area::MultipolygonCollector collector(assembler_config); @@ -275,7 +169,7 @@ int main(int argc, char* argv[]) { location_handler_type location_handler(index); location_handler.ignore_errors(); - TestHandler test_handler(data_source); + TestHandler test_handler(dataset); std::cerr << "Pass 2...\n"; osmium::io::Reader reader2(input_filename); @@ -284,8 +178,5 @@ int main(int argc, char* argv[]) { })); reader2.close(); std::cerr << "Pass 2 done\n"; - - OGRDataSource::DestroyDataSource(data_source); - OGRCleanupAll(); } diff --git a/test/data-tests/testdata-overview.cpp b/test/data-tests/testdata-overview.cpp index 2d63dc684..43d672dd1 100644 --- a/test/data-tests/testdata-overview.cpp +++ b/test/data-tests/testdata-overview.cpp @@ -2,6 +2,8 @@ #include +#include + #include #include @@ -15,154 +17,53 @@ typedef osmium::handler::NodeLocationsForWays location_handler_type; class TestOverviewHandler : public osmium::handler::Handler { - OGRDataSource* m_data_source; - - OGRLayer* m_layer_nodes; - OGRLayer* m_layer_labels; - OGRLayer* m_layer_ways; + gdalcpp::Layer m_layer_nodes; + gdalcpp::Layer m_layer_labels; + gdalcpp::Layer m_layer_ways; osmium::geom::OGRFactory<> m_factory; public: - TestOverviewHandler(const std::string& driver_name, const std::string& filename) { + explicit TestOverviewHandler(gdalcpp::Dataset& dataset) : + m_layer_nodes(dataset, "nodes", wkbPoint), + m_layer_labels(dataset, "labels", wkbPoint), + m_layer_ways(dataset, "ways", wkbLineString) { - OGRRegisterAll(); + m_layer_nodes.add_field("id", OFTReal, 10); - OGRSFDriver* driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver_name.c_str()); - if (!driver) { - std::cerr << driver_name << " driver not available.\n"; - exit(1); - } + m_layer_labels.add_field("id", OFTReal, 10); + m_layer_labels.add_field("label", OFTString, 30); - CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); - const char* options[] = { "SPATIALITE=TRUE", nullptr }; - m_data_source = driver->CreateDataSource(filename.c_str(), const_cast(options)); - if (!m_data_source) { - std::cerr << "Creation of output file failed.\n"; - exit(1); - } - - OGRSpatialReference sparef; - sparef.SetWellKnownGeogCS("WGS84"); - - // nodes layer - - m_layer_nodes = m_data_source->CreateLayer("nodes", &sparef, wkbPoint, nullptr); - if (!m_layer_nodes) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_nodes_field_id("id", OFTReal); - layer_nodes_field_id.SetWidth(10); - - if (m_layer_nodes->CreateField(&layer_nodes_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - // labels layer - - m_layer_labels = m_data_source->CreateLayer("labels", &sparef, wkbPoint, nullptr); - if (!m_layer_labels) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_labels_field_id("id", OFTReal); - layer_labels_field_id.SetWidth(10); - - if (m_layer_labels->CreateField(&layer_labels_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_labels_field_label("label", OFTString); - layer_labels_field_label.SetWidth(30); - - if (m_layer_labels->CreateField(&layer_labels_field_label) != OGRERR_NONE) { - std::cerr << "Creating label field failed.\n"; - exit(1); - } - - // ways layer - - m_layer_ways = m_data_source->CreateLayer("ways", &sparef, wkbLineString, nullptr); - if (!m_layer_ways) { - std::cerr << "Layer creation failed.\n"; - exit(1); - } - - OGRFieldDefn layer_way_field_id("id", OFTReal); - layer_way_field_id.SetWidth(10); - - if (m_layer_ways->CreateField(&layer_way_field_id) != OGRERR_NONE) { - std::cerr << "Creating id field failed.\n"; - exit(1); - } - - OGRFieldDefn layer_way_field_test("test", OFTInteger); - layer_way_field_test.SetWidth(3); - - if (m_layer_ways->CreateField(&layer_way_field_test) != OGRERR_NONE) { - std::cerr << "Creating test field failed.\n"; - exit(1); - } - } - - ~TestOverviewHandler() { - OGRDataSource::DestroyDataSource(m_data_source); - OGRCleanupAll(); + m_layer_ways.add_field("id", OFTReal, 10); + m_layer_ways.add_field("test", OFTInteger, 3); } void node(const osmium::Node& node) { const char* label = node.tags().get_value_by_key("label"); if (label) { - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_labels->GetLayerDefn()); - std::unique_ptr ogr_point = m_factory.create_point(node); - feature->SetGeometry(ogr_point.get()); - feature->SetField("id", static_cast(node.id())); - feature->SetField("label", label); - - if (m_layer_labels->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); + gdalcpp::Feature feature(m_layer_labels, m_factory.create_point(node)); + feature.set_field("id", static_cast(node.id())); + feature.set_field("label", label); + feature.add_to_layer(); } else { - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_nodes->GetLayerDefn()); - std::unique_ptr ogr_point = m_factory.create_point(node); - feature->SetGeometry(ogr_point.get()); - feature->SetField("id", static_cast(node.id())); - - if (m_layer_nodes->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - OGRFeature::DestroyFeature(feature); + gdalcpp::Feature feature(m_layer_nodes, m_factory.create_point(node)); + feature.set_field("id", static_cast(node.id())); + feature.add_to_layer(); } } void way(const osmium::Way& way) { try { - std::unique_ptr ogr_linestring = m_factory.create_linestring(way); - OGRFeature* feature = OGRFeature::CreateFeature(m_layer_ways->GetLayerDefn()); - feature->SetGeometry(ogr_linestring.get()); - feature->SetField("id", static_cast(way.id())); + gdalcpp::Feature feature(m_layer_ways, m_factory.create_linestring(way)); + feature.set_field("id", static_cast(way.id())); const char* test = way.tags().get_value_by_key("test"); if (test) { - feature->SetField("test", test); + feature.set_field("test", test); } - if (m_layer_ways->CreateFeature(feature) != OGRERR_NONE) { - std::cerr << "Failed to create feature.\n"; - exit(1); - } - - OGRFeature::DestroyFeature(feature); + feature.add_to_layer(); } catch (osmium::geometry_error&) { std::cerr << "Ignoring illegal geometry for way " << way.id() << ".\n"; } @@ -183,13 +84,16 @@ int main(int argc, char* argv[]) { std::string output_filename("testdata-overview.db"); ::unlink(output_filename.c_str()); + CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); + gdalcpp::Dataset dataset(output_format, output_filename, gdalcpp::SRS{}, { "SPATIALITE=TRUE" }); + osmium::io::Reader reader(input_filename); index_type index; location_handler_type location_handler(index); location_handler.ignore_errors(); - TestOverviewHandler handler(output_format, output_filename); + TestOverviewHandler handler(dataset); osmium::apply(reader, location_handler, handler); reader.close(); diff --git a/test/data-tests/testdata-xml.cpp b/test/data-tests/testdata-xml.cpp index 8102759d1..b5a0e9028 100644 --- a/test/data-tests/testdata-xml.cpp +++ b/test/data-tests/testdata-xml.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -72,24 +73,27 @@ std::string read_gz_file(const char* test_id, const char* suffix) { header_buffer_type parse_xml(std::string input) { - osmium::thread::Queue input_queue; - osmium::thread::Queue output_queue; + osmium::io::detail::future_string_queue_type input_queue; + osmium::io::detail::future_buffer_queue_type output_queue; std::promise header_promise; - std::atomic done {false}; - input_queue.push(input); - input_queue.push(std::string()); // EOF marker + std::future header_future = header_promise.get_future(); - osmium::io::detail::XMLParser parser(input_queue, output_queue, header_promise, osmium::osm_entity_bits::all, done); - parser(); + osmium::io::detail::add_to_queue(input_queue, std::move(input)); + osmium::io::detail::add_to_queue(input_queue, std::string{}); + + osmium::io::detail::XMLParser parser(input_queue, output_queue, header_promise, osmium::osm_entity_bits::all); + parser.parse(); header_buffer_type result; - result.header = header_promise.get_future().get(); - output_queue.wait_and_pop(result.buffer); + result.header = header_future.get(); + std::future future_buffer; + output_queue.wait_and_pop(future_buffer); + result.buffer = future_buffer.get(); if (result.buffer) { - osmium::memory::Buffer buffer; - output_queue.wait_and_pop(buffer); - assert(!buffer); + std::future future_buffer2; + output_queue.wait_and_pop(future_buffer2); + assert(!future_buffer2.get()); } return result; @@ -534,9 +538,10 @@ TEST_CASE("Reading OSM XML 200") { osmium::io::Header header = reader.header(); REQUIRE(header.get("generator") == "testdata"); - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(0 == buffer.committed()); - REQUIRE(! buffer); + REQUIRE_THROWS({ + reader.read(); + }); + reader.close(); } diff --git a/test/t/area/test_node_ref_segment.cpp b/test/t/area/test_node_ref_segment.cpp index 309768744..3261c24e1 100644 --- a/test/t/area/test_node_ref_segment.cpp +++ b/test/t/area/test_node_ref_segment.cpp @@ -52,6 +52,20 @@ TEST_CASE("NodeRefSegmentClass") { REQUIRE(calculate_intersection(s1, s7) == osmium::Location()); } + SECTION("intersection of very long segments") { + NodeRefSegment s1({ 1, {90.0, 90.0}}, { 2, {-90.0, -90.0}}, nullptr, nullptr); + NodeRefSegment s2({ 1, {-90.0, 90.0}}, { 2, {90.0, -90.0}}, nullptr, nullptr); + REQUIRE(calculate_intersection(s1, s2) == osmium::Location(0.0, 0.0)); + + NodeRefSegment s3({ 1, {-90.0, -90.0}}, { 2, {90.0, 90.0}}, nullptr, nullptr); + NodeRefSegment s4({ 1, {-90.0, 90.0}}, { 2, {90.0, -90.0}}, nullptr, nullptr); + REQUIRE(calculate_intersection(s3, s4) == osmium::Location(0.0, 0.0)); + + NodeRefSegment s5({ 1, {-90.0000001, -90.0}}, { 2, {90.0, 90.0}}, nullptr, nullptr); + NodeRefSegment s6({ 1, {-90.0, 90.0}}, { 2, {90.0, -90.0}}, nullptr, nullptr); + REQUIRE(calculate_intersection(s5, s6) == osmium::Location(0.0, 0.0)); + } + SECTION("to_left_of") { osmium::Location loc { 2.0, 2.0 }; diff --git a/test/t/basic/test_changeset.cpp b/test/t/basic/test_changeset.cpp index fc9f1bdee..d1f3fde87 100644 --- a/test/t/basic/test_changeset.cpp +++ b/test/t/basic/test_changeset.cpp @@ -21,11 +21,13 @@ TEST_CASE("Basic Changeset") { .set_created_at(100) .set_closed_at(200) .set_num_changes(7) + .set_num_comments(3) .set_uid(9); REQUIRE(42 == cs1.id()); REQUIRE(9 == cs1.uid()); REQUIRE(7 == cs1.num_changes()); + REQUIRE(3 == cs1.num_comments()); REQUIRE(true == cs1.closed()); REQUIRE(osmium::Timestamp(100) == cs1.created_at()); REQUIRE(osmium::Timestamp(200) == cs1.closed_at()); @@ -33,7 +35,7 @@ TEST_CASE("Basic Changeset") { REQUIRE(std::string("user") == cs1.user()); crc32.update(cs1); - REQUIRE(crc32().checksum() == 0xf44aff25); + REQUIRE(crc32().checksum() == 0x502e8c0e); osmium::Changeset& cs2 = buffer_add_changeset(buffer, "user", @@ -42,11 +44,13 @@ TEST_CASE("Basic Changeset") { cs2.set_id(43) .set_created_at(120) .set_num_changes(21) + .set_num_comments(osmium::num_comments_type(0)) .set_uid(9); REQUIRE(43 == cs2.id()); REQUIRE(9 == cs2.uid()); REQUIRE(21 == cs2.num_changes()); + REQUIRE(0 == cs2.num_comments()); REQUIRE(false == cs2.closed()); REQUIRE(osmium::Timestamp(120) == cs2.created_at()); REQUIRE(osmium::Timestamp() == cs2.closed_at()); @@ -61,3 +65,59 @@ TEST_CASE("Basic Changeset") { REQUIRE(false == (cs1 >= cs2)); } + +TEST_CASE("Create changeset without helper") { + osmium::memory::Buffer buffer(10 * 1000); + osmium::builder::ChangesetBuilder builder(buffer); + + osmium::Changeset& cs1 = builder.object(); + cs1.set_id(42) + .set_created_at(100) + .set_closed_at(200) + .set_num_changes(7) + .set_num_comments(2) + .set_uid(9); + + builder.add_user("user"); + add_tags(buffer, builder, { + {"key1", "val1"}, + {"key2", "val2"} + }); + + { + osmium::builder::ChangesetDiscussionBuilder disc_builder(buffer, &builder); + disc_builder.add_comment(osmium::Timestamp(300), 10, "user2"); + disc_builder.add_comment_text("foo"); + disc_builder.add_comment(osmium::Timestamp(400), 9, "user"); + disc_builder.add_comment_text("bar"); + } + + buffer.commit(); + + REQUIRE(42 == cs1.id()); + REQUIRE(9 == cs1.uid()); + REQUIRE(7 == cs1.num_changes()); + REQUIRE(2 == cs1.num_comments()); + REQUIRE(true == cs1.closed()); + REQUIRE(osmium::Timestamp(100) == cs1.created_at()); + REQUIRE(osmium::Timestamp(200) == cs1.closed_at()); + REQUIRE(2 == cs1.tags().size()); + REQUIRE(std::string("user") == cs1.user()); + + auto cit = cs1.discussion().begin(); + + REQUIRE(cit != cs1.discussion().end()); + REQUIRE(cit->date() == osmium::Timestamp(300)); + REQUIRE(cit->uid() == 10); + REQUIRE(std::string("user2") == cit->user()); + REQUIRE(std::string("foo") == cit->text()); + + REQUIRE(++cit != cs1.discussion().end()); + REQUIRE(cit->date() == osmium::Timestamp(400)); + REQUIRE(cit->uid() == 9); + REQUIRE(std::string("user") == cit->user()); + REQUIRE(std::string("bar") == cit->text()); + + REQUIRE(++cit == cs1.discussion().end()); +} + diff --git a/test/t/basic/test_crc.cpp b/test/t/basic/test_crc.cpp index aab1013f4..fcd50a13c 100644 --- a/test/t/basic/test_crc.cpp +++ b/test/t/basic/test_crc.cpp @@ -24,6 +24,27 @@ TEST_CASE("CRC of basic datatypes") { REQUIRE(crc32().checksum() == 0x8fe62899); } + SECTION("Int16") { + crc32.update_int16(0x0123U); + crc32.update_int16(0x1234U); + + REQUIRE(crc32().checksum() == 0xda923744); + } + + SECTION("Int32") { + crc32.update_int32(0x01234567UL); + crc32.update_int32(0x12345678UL); + + REQUIRE(crc32().checksum() == 0x9b4e2af3); + } + + SECTION("Int64") { + crc32.update_int64(0x0123456789abcdefULL); + crc32.update_int64(0x123456789abcdef0ULL); + + REQUIRE(crc32().checksum() == 0x6d8b7267); + } + SECTION("String") { const char* str = "foobar"; crc32.update_string(str); diff --git a/test/t/basic/test_node.cpp b/test/t/basic/test_node.cpp index db5b4cd53..9f8b181fe 100644 --- a/test/t/basic/test_node.cpp +++ b/test/t/basic/test_node.cpp @@ -37,12 +37,12 @@ SECTION("node_builder") { REQUIRE(333 == node.changeset()); REQUIRE(21 == node.uid()); REQUIRE(std::string("foo") == node.user()); - REQUIRE(123 == node.timestamp()); + REQUIRE(123 == uint32_t(node.timestamp())); REQUIRE(osmium::Location(3.5, 4.7) == node.location()); REQUIRE(2 == node.tags().size()); crc32.update(node); - REQUIRE(crc32().checksum() == 0xc696802f); + REQUIRE(crc32().checksum() == 0x7dc553f9); node.set_visible(false); REQUIRE(false == node.visible()); @@ -61,7 +61,7 @@ SECTION("node_default_attributes") { REQUIRE(0 == node.changeset()); REQUIRE(0 == node.uid()); REQUIRE(std::string("") == node.user()); - REQUIRE(0 == node.timestamp()); + REQUIRE(0 == uint32_t(node.timestamp())); REQUIRE(osmium::Location() == node.location()); REQUIRE(0 == node.tags().size()); } diff --git a/test/t/basic/test_object_comparisons.cpp b/test/t/basic/test_object_comparisons.cpp index 2bfdcad90..ec9e6fae8 100644 --- a/test/t/basic/test_object_comparisons.cpp +++ b/test/t/basic/test_object_comparisons.cpp @@ -31,20 +31,20 @@ TEST_CASE("Object_Comparisons") { node1.set_version(1); node2.set_id(15); node2.set_version(2); - REQUIRE(true == (node1 < node2)); - REQUIRE(false == (node1 > node2)); + REQUIRE(node1 < node2); + REQUIRE_FALSE(node1 > node2); node1.set_id(20); node1.set_version(1); node2.set_id(20); node2.set_version(2); - REQUIRE(true == (node1 < node2)); - REQUIRE(false == (node1 > node2)); + REQUIRE(node1 < node2); + REQUIRE_FALSE(node1 > node2); node1.set_id(-10); node1.set_version(2); node2.set_id(-15); node2.set_version(1); - REQUIRE(true == (node1 < node2)); - REQUIRE(false == (node1 > node2)); + REQUIRE(node1 < node2); + REQUIRE_FALSE(node1 > node2); } SECTION("order_types") { @@ -122,26 +122,26 @@ TEST_CASE("Object_Comparisons") { const osmium::Way& way = static_cast(*(++it)); const osmium::Relation& relation = static_cast(*(++it)); - REQUIRE(true == (node1 < node2)); - REQUIRE(true == (node2 < way)); - REQUIRE(false == (node2 > way)); - REQUIRE(true == (way < relation)); - REQUIRE(true == (node1 < relation)); + REQUIRE(node1 < node2); + REQUIRE(node2 < way); + REQUIRE_FALSE(node2 > way); + REQUIRE(way < relation); + REQUIRE(node1 < relation); - REQUIRE(true == osmium::object_order_type_id_version()(node1, node2)); - REQUIRE(true == osmium::object_order_type_id_reverse_version()(node2, node1)); - REQUIRE(true == osmium::object_order_type_id_version()(node1, way)); - REQUIRE(true == osmium::object_order_type_id_reverse_version()(node1, way)); + REQUIRE(osmium::object_order_type_id_version()(node1, node2)); + REQUIRE(osmium::object_order_type_id_reverse_version()(node2, node1)); + REQUIRE(osmium::object_order_type_id_version()(node1, way)); + REQUIRE(osmium::object_order_type_id_reverse_version()(node1, way)); - REQUIRE(false == osmium::object_equal_type_id_version()(node1, node2)); - REQUIRE(true == osmium::object_equal_type_id_version()(node2, node3)); + REQUIRE_FALSE(osmium::object_equal_type_id_version()(node1, node2)); + REQUIRE(osmium::object_equal_type_id_version()(node2, node3)); - REQUIRE(true == osmium::object_equal_type_id()(node1, node2)); - REQUIRE(true == osmium::object_equal_type_id()(node2, node3)); + REQUIRE(osmium::object_equal_type_id()(node1, node2)); + REQUIRE(osmium::object_equal_type_id()(node2, node3)); - REQUIRE(false == osmium::object_equal_type_id_version()(node1, way)); - REQUIRE(false == osmium::object_equal_type_id_version()(node1, relation)); - REQUIRE(false == osmium::object_equal_type_id()(node1, relation)); + REQUIRE_FALSE(osmium::object_equal_type_id_version()(node1, way)); + REQUIRE_FALSE(osmium::object_equal_type_id_version()(node1, relation)); + REQUIRE_FALSE(osmium::object_equal_type_id()(node1, relation)); } } diff --git a/test/t/basic/test_relation.cpp b/test/t/basic/test_relation.cpp index fd5c7b4ad..66b201c90 100644 --- a/test/t/basic/test_relation.cpp +++ b/test/t/basic/test_relation.cpp @@ -36,7 +36,7 @@ TEST_CASE("Build relation") { REQUIRE(333 == relation.changeset()); REQUIRE(21 == relation.uid()); REQUIRE(std::string("foo") == relation.user()); - REQUIRE(123 == relation.timestamp()); + REQUIRE(123 == uint32_t(relation.timestamp())); REQUIRE(2 == relation.tags().size()); REQUIRE(3 == relation.members().size()); @@ -61,5 +61,16 @@ TEST_CASE("Build relation") { } crc32.update(relation); - REQUIRE(crc32().checksum() == 0xebcd836d); + REQUIRE(crc32().checksum() == 0x2c2352e); } + +TEST_CASE("Member role too long") { + osmium::memory::Buffer buffer(10000); + + osmium::builder::RelationMemberListBuilder builder(buffer); + + const char role[2000] = ""; + builder.add_member(osmium::item_type::node, 1, role, 1024); + REQUIRE_THROWS(builder.add_member(osmium::item_type::node, 1, role, 1025)); +} + diff --git a/test/t/basic/test_timestamp.cpp b/test/t/basic/test_timestamp.cpp index f015730ea..f80ffcf5f 100644 --- a/test/t/basic/test_timestamp.cpp +++ b/test/t/basic/test_timestamp.cpp @@ -8,34 +8,45 @@ TEST_CASE("Timestamp") { SECTION("can be default initialized to invalid value") { osmium::Timestamp t; - REQUIRE(0 == t); + REQUIRE(0 == uint32_t(t)); REQUIRE("" == t.to_iso()); + REQUIRE_FALSE(t.valid()); } SECTION("invalid value is zero") { osmium::Timestamp t(static_cast(0)); - REQUIRE(0 == t); + REQUIRE(0 == uint32_t(t)); REQUIRE("" == t.to_iso()); + REQUIRE_FALSE(t.valid()); } SECTION("can be initialized from time_t") { osmium::Timestamp t(static_cast(1)); - REQUIRE(1 == t); + REQUIRE(1 == uint32_t(t)); REQUIRE("1970-01-01T00:00:01Z" == t.to_iso()); + REQUIRE(t.valid()); + } + + SECTION("can be initialized from const char*") { + osmium::Timestamp t("2000-01-01T00:00:00Z"); + REQUIRE("2000-01-01T00:00:00Z" == t.to_iso()); + REQUIRE(t.valid()); } SECTION("can be initialized from string") { - osmium::Timestamp t("2000-01-01T00:00:00Z"); + std::string s = "2000-01-01T00:00:00Z"; + osmium::Timestamp t(s); REQUIRE("2000-01-01T00:00:00Z" == t.to_iso()); + REQUIRE(t.valid()); } SECTION("throws if initialized from bad string") { REQUIRE_THROWS_AS(osmium::Timestamp("x"), std::invalid_argument); } - SECTION("can be implicitly cast to time_t") { + SECTION("can be explicitly cast to time_t") { osmium::Timestamp t(4242); - time_t x = t; + time_t x = t.seconds_since_epoch(); REQUIRE(x == 4242); } @@ -50,6 +61,10 @@ TEST_CASE("Timestamp") { osmium::Timestamp t1(10); osmium::Timestamp t2(50); REQUIRE(t1 < t2); + REQUIRE(t1 > osmium::start_of_time()); + REQUIRE(t2 > osmium::start_of_time()); + REQUIRE(t1 < osmium::end_of_time()); + REQUIRE(t2 < osmium::end_of_time()); } SECTION("can be written to stream") { diff --git a/test/t/basic/test_way.cpp b/test/t/basic/test_way.cpp index 7c7bc2148..370cd0105 100644 --- a/test/t/basic/test_way.cpp +++ b/test/t/basic/test_way.cpp @@ -36,7 +36,7 @@ SECTION("way_builder") { REQUIRE(333 == way.changeset()); REQUIRE(21 == way.uid()); REQUIRE(std::string("foo") == way.user()); - REQUIRE(123 == way.timestamp()); + REQUIRE(123 == uint32_t(way.timestamp())); REQUIRE(2 == way.tags().size()); REQUIRE(3 == way.nodes().size()); REQUIRE(1 == way.nodes()[0].ref()); @@ -45,7 +45,7 @@ SECTION("way_builder") { REQUIRE(! way.is_closed()); crc32.update(way); - REQUIRE(crc32().checksum() == 0x20fe7a30); + REQUIRE(crc32().checksum() == 0x7676d0c2); } SECTION("closed_way") { diff --git a/test/t/buffer/test_buffer_basics.cpp b/test/t/buffer/test_buffer_basics.cpp new file mode 100644 index 000000000..ffe725168 --- /dev/null +++ b/test/t/buffer/test_buffer_basics.cpp @@ -0,0 +1,34 @@ +#include "catch.hpp" + +#include + +TEST_CASE("Buffer basics") { + + osmium::memory::Buffer invalid_buffer1; + osmium::memory::Buffer invalid_buffer2; + osmium::memory::Buffer empty_buffer1(1024); + osmium::memory::Buffer empty_buffer2(2048); + + REQUIRE(!invalid_buffer1); + REQUIRE(!invalid_buffer2); + REQUIRE(empty_buffer1); + REQUIRE(empty_buffer2); + + REQUIRE(invalid_buffer1 == invalid_buffer2); + REQUIRE(invalid_buffer1 != empty_buffer1); + REQUIRE(empty_buffer1 != empty_buffer2); + + REQUIRE(invalid_buffer1.capacity() == 0); + REQUIRE(invalid_buffer1.written() == 0); + REQUIRE(invalid_buffer1.committed() == 0); + + REQUIRE(empty_buffer1.capacity() == 1024); + REQUIRE(empty_buffer1.written() == 0); + REQUIRE(empty_buffer1.committed() == 0); + + REQUIRE(empty_buffer2.capacity() == 2048); + REQUIRE(empty_buffer2.written() == 0); + REQUIRE(empty_buffer2.committed() == 0); + +} + diff --git a/test/t/buffer/test_buffer_node.cpp b/test/t/buffer/test_buffer_node.cpp index 9bc8f701d..ba2431b80 100644 --- a/test/t/buffer/test_buffer_node.cpp +++ b/test/t/buffer/test_buffer_node.cpp @@ -9,7 +9,7 @@ void check_node_1(osmium::Node& node) { REQUIRE(true == node.visible()); REQUIRE(333 == node.changeset()); REQUIRE(21 == node.uid()); - REQUIRE(123 == node.timestamp()); + REQUIRE(123 == uint32_t(node.timestamp())); REQUIRE(osmium::Location(3.5, 4.7) == node.location()); REQUIRE(std::string("testuser") == node.user()); @@ -28,7 +28,7 @@ void check_node_2(osmium::Node& node) { REQUIRE(true == node.visible()); REQUIRE(333 == node.changeset()); REQUIRE(21 == node.uid()); - REQUIRE(123 == node.timestamp()); + REQUIRE(123 == uint32_t(node.timestamp())); REQUIRE(osmium::Location(3.5, 4.7) == node.location()); REQUIRE(std::string("testuser") == node.user()); @@ -56,13 +56,14 @@ void check_node_2(osmium::Node& node) { REQUIRE(2 == n); } -TEST_CASE("Buffer_Node") { +TEST_CASE("Node in Buffer") { - SECTION("buffer_node") { - constexpr size_t buffer_size = 10000; - unsigned char data[buffer_size]; + constexpr size_t buffer_size = 10000; + unsigned char data[buffer_size]; - osmium::memory::Buffer buffer(data, buffer_size, 0); + osmium::memory::Buffer buffer(data, buffer_size, 0); + + SECTION("Add node to buffer") { { // add node 1 @@ -132,4 +133,67 @@ TEST_CASE("Buffer_Node") { } + SECTION("Add buffer to another one") { + + { + // add node 1 + osmium::builder::NodeBuilder node_builder(buffer); + osmium::Node& node = node_builder.object(); + REQUIRE(osmium::item_type::node == node.type()); + + node.set_id(1); + node.set_version(3); + node.set_visible(true); + node.set_changeset(333); + node.set_uid(21); + node.set_timestamp(123); + node.set_location(osmium::Location(3.5, 4.7)); + + node_builder.add_user("testuser"); + + buffer.commit(); + } + + osmium::memory::Buffer buffer2(buffer_size, osmium::memory::Buffer::auto_grow::yes); + + buffer2.add_buffer(buffer); + buffer2.commit(); + + REQUIRE(buffer.committed() == buffer2.committed()); + const osmium::Node& node = buffer2.get(0); + REQUIRE(node.id() == 1); + REQUIRE(123 == uint32_t(node.timestamp())); + } + + SECTION("Use back_inserter on buffer") { + + { + // add node 1 + osmium::builder::NodeBuilder node_builder(buffer); + osmium::Node& node = node_builder.object(); + REQUIRE(osmium::item_type::node == node.type()); + + node.set_id(1); + node.set_version(3); + node.set_visible(true); + node.set_changeset(333); + node.set_uid(21); + node.set_timestamp(123); + node.set_location(osmium::Location(3.5, 4.7)); + + node_builder.add_user("testuser"); + + buffer.commit(); + } + + osmium::memory::Buffer buffer2(buffer_size, osmium::memory::Buffer::auto_grow::yes); + + std::copy(buffer.begin(), buffer.end(), std::back_inserter(buffer2)); + + REQUIRE(buffer.committed() == buffer2.committed()); + const osmium::Node& node = buffer2.get(0); + REQUIRE(node.id() == 1); + REQUIRE(123 == uint32_t(node.timestamp())); + } } + diff --git a/test/t/geom/test_tile_data.hpp b/test/t/geom/test_tile_data.hpp index e5c0953c0..8a22cfa51 100644 --- a/test/t/geom/test_tile_data.hpp +++ b/test/t/geom/test_tile_data.hpp @@ -1,5 +1,7 @@ -std::string s = R"(127.4864358 16.8380041 223904 118630 18 +#include + +static std::string s = R"(127.4864358 16.8380041 223904 118630 18 163.1103174 39.4760232 121 48 7 -4.1372725 -22.5105386 31 36 6 98.7193066 -36.2312406 1 1 1 diff --git a/test/t/io/deleted_nodes.osh b/test/t/io/deleted_nodes.osh new file mode 100644 index 000000000..639e05149 --- /dev/null +++ b/test/t/io/deleted_nodes.osh @@ -0,0 +1,5 @@ + + + + + diff --git a/test/t/io/deleted_nodes.osh.pbf b/test/t/io/deleted_nodes.osh.pbf new file mode 100644 index 0000000000000000000000000000000000000000..8a94870d14ad3d7a17b0a79dc1441cf51afa3ba1 GIT binary patch literal 189 zcmV;u07Cx&000dN2~Sf^NM&JUWpWr!5JDPCc$`z>^DoW~PR>ZpP1FrD&@)rwa!JiA zPW8)ANi9|q^~fwP$uG)GPR#MlOUp0HO)SaG&ue1j$uG{$EX~z7)HBjE1OU}a74rZ9 z01FBSPg6}qVRT^_PY_NTOL&~);^Jc9Vk<39Es8f3auBlPVq#*_lHp=vWE5gMu=MJE rE(R$kCI%%S)&gQ9CI&_)u7Cgk|L6a^boV!YFC=yl69WSPqA(XSe-ljE literal 0 HcmV?d00001 diff --git a/test/t/io/test_output_utils.cpp b/test/t/io/test_output_utils.cpp new file mode 100644 index 000000000..a76068348 --- /dev/null +++ b/test/t/io/test_output_utils.cpp @@ -0,0 +1,153 @@ + +#include "catch.hpp" + +#include + +#include + +TEST_CASE("output formatted") { + + std::string out; + + SECTION("small results") { + osmium::io::detail::append_printf_formatted_string(out, "%d", 17); + REQUIRE(out == "17"); + } + + SECTION("several parameters") { + osmium::io::detail::append_printf_formatted_string(out, "%d %s", 17, "foo"); + REQUIRE(out == "17 foo"); + + } + + SECTION("string already containing something") { + out += "foo"; + osmium::io::detail::append_printf_formatted_string(out, " %d", 23); + REQUIRE(out == "foo 23"); + } + + SECTION("large results") { + const char* str = + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; + + osmium::io::detail::append_printf_formatted_string(out, "%s", str); + + REQUIRE(out == str); + } + +} + +TEST_CASE("UTF8 encoding") { + + std::string out; + + SECTION("append to string") { + out += "1234"; + osmium::io::detail::append_utf8_encoded_string(out, "abc"); + REQUIRE(out == "1234abc"); + } + + SECTION("don't encode alphabetic characters") { + const char* s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + osmium::io::detail::append_utf8_encoded_string(out, s); + REQUIRE(out == s); + } + + SECTION("don't encode numeric characters") { + const char* s = "0123456789"; + osmium::io::detail::append_utf8_encoded_string(out, s); + REQUIRE(out == s); + } + + SECTION("don't encode lots of often used characters characters") { + const char* s = ".-;:_#+"; + osmium::io::detail::append_utf8_encoded_string(out, s); + REQUIRE(out == s); + } + + SECTION("encode characters that are special in OPL") { + osmium::io::detail::append_utf8_encoded_string(out, " \n,=@"); + REQUIRE(out == "%20%%0a%%2c%%3d%%40%"); + } + +// workaround for missing support for u8 string literals on Windows +#if !defined(_MSC_VER) + + SECTION("encode multibyte character") { + osmium::io::detail::append_utf8_encoded_string(out, u8"\u30dc_\U0001d11e_\U0001f6eb"); + REQUIRE(out == "%30dc%_%1d11e%_%1f6eb%"); + } + +#endif + +} + +TEST_CASE("html encoding") { + + std::string out; + + SECTION("do not encode normal characters") { + const char* s = "abc123,.-"; + osmium::io::detail::append_xml_encoded_string(out, s); + REQUIRE(out == s); + } + + SECTION("encode special XML characters") { + const char* s = "& \" \' < > \n \r \t"; + osmium::io::detail::append_xml_encoded_string(out, s); + REQUIRE(out == "& " ' < > "); + } + +} + +TEST_CASE("debug encoding") { + + std::string out; + + SECTION("do not encode normal characters") { + const char* s = "abc123,.-"; + osmium::io::detail::append_debug_encoded_string(out, s, "[", "]"); + REQUIRE(out == s); + } + + SECTION("encode some unicode characters") { + const char* s = u8"\n_\u30dc_\U0001d11e_\U0001f6eb"; + osmium::io::detail::append_debug_encoded_string(out, s, "[", "]"); + REQUIRE(out == "[]_[]_[]_[]"); + } + +} + +TEST_CASE("encoding of non-printable characters in the first 127 characters") { + + std::locale cloc("C"); + char s[] = "a\0"; + + for (char c = 1; c < 0x7f; ++c) { + std::string out; + s[0] = c; + + SECTION("utf8 encode") { + osmium::io::detail::append_utf8_encoded_string(out, s); + + if (!std::isprint(c, cloc)) { + REQUIRE(out[0] == '%'); + } + } + + SECTION("debug encode") { + osmium::io::detail::append_debug_encoded_string(out, s, "", ""); + + if (!std::isprint(c, cloc)) { + REQUIRE(out[0] == '<'); + } + } + + } + +} + diff --git a/test/t/io/test_reader.cpp b/test/t/io/test_reader.cpp index 9a06d8408..a83af52ab 100644 --- a/test/t/io/test_reader.cpp +++ b/test/t/io/test_reader.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -17,6 +18,27 @@ struct CountHandler : public osmium::handler::Handler { }; // class CountHandler +struct ZeroPositionNodeCountHandler : public osmium::handler::Handler { + + // number of nodes seen at zero position, or visible with undefined + // location. + int count = 0; + int total_count = 0; // total number of nodes seen + const osmium::Location zero = osmium::Location(int32_t(0), int32_t(0)); + + void node(osmium::Node &n) { + // no nodes in the history file have a zero location, and + // no visible nodes should have an undefined location. + if ((n.location() == zero) || + (n.visible() && !n.location())) { + ++count; + } + ++total_count; + } + +}; // class ZeroPositionNodeCountHandler + + TEST_CASE("Reader") { SECTION("reader can be initialized with file") { @@ -34,7 +56,7 @@ TEST_CASE("Reader") { osmium::apply(reader, handler); } - SECTION("should return invalid buffer after eof") { + SECTION("should throw after eof") { osmium::io::File file(with_data_dir("t/io/data.osm")); osmium::io::Reader reader(file); @@ -45,9 +67,9 @@ TEST_CASE("Reader") { REQUIRE(reader.eof()); - // extra read always returns invalid buffer - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(!buffer); + REQUIRE_THROWS_AS({ + reader.read(); + }, osmium::io_error); } SECTION("should not hang when apply() is called twice on reader") { @@ -56,7 +78,9 @@ TEST_CASE("Reader") { osmium::handler::Handler handler; osmium::apply(reader, handler); - osmium::apply(reader, handler); + REQUIRE_THROWS_AS({ + osmium::apply(reader, handler); + }, osmium::io_error); } SECTION("should work with a buffer with uncompressed data") { @@ -113,5 +137,76 @@ TEST_CASE("Reader") { REQUIRE(handler.count == 1); } + SECTION("should decode zero node positions in history (XML)") { + osmium::io::Reader reader(with_data_dir("t/io/deleted_nodes.osh"), + osmium::osm_entity_bits::node); + ZeroPositionNodeCountHandler handler; + + REQUIRE(handler.count == 0); + REQUIRE(handler.total_count == 0); + + osmium::apply(reader, handler); + + REQUIRE(handler.count == 0); + REQUIRE(handler.total_count == 2); + } + + SECTION("should decode zero node positions in history (PBF)") { + osmium::io::Reader reader(with_data_dir("t/io/deleted_nodes.osh.pbf"), + osmium::osm_entity_bits::node); + ZeroPositionNodeCountHandler handler; + + REQUIRE(handler.count == 0); + REQUIRE(handler.total_count == 0); + + osmium::apply(reader, handler); + + REQUIRE(handler.count == 0); + REQUIRE(handler.total_count == 2); + } + +} + +TEST_CASE("Reader failure modes") { + + SECTION("should fail with nonexistent file") { + REQUIRE_THROWS({ + osmium::io::Reader reader(with_data_dir("t/io/nonexistent-file.osm")); + }); + } + + SECTION("should fail with nonexistent file (gz)") { + REQUIRE_THROWS({ + osmium::io::Reader reader(with_data_dir("t/io/nonexistent-file.osm.gz")); + }); + } + + SECTION("should fail with nonexistent file (pbf)") { + REQUIRE_THROWS({ + osmium::io::Reader reader(with_data_dir("t/io/nonexistent-file.osm.pbf")); + }); + } + + SECTION("should work when there is an exception in main thread before getting header") { + try { + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + REQUIRE(!reader.eof()); + throw std::runtime_error("foo"); + } catch (...) { + } + + } + + SECTION("should work when there is an exception in main thread while reading") { + try { + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + REQUIRE(!reader.eof()); + auto header = reader.header(); + throw std::runtime_error("foo"); + } catch (...) { + } + + } + } diff --git a/test/t/io/test_reader_with_mock_decompression.cpp b/test/t/io/test_reader_with_mock_decompression.cpp new file mode 100644 index 000000000..566295aff --- /dev/null +++ b/test/t/io/test_reader_with_mock_decompression.cpp @@ -0,0 +1,145 @@ + +#include "catch.hpp" +#include "utils.hpp" + +#include + +#include +#include + +// The MockDecompressor behaves like other Decompressor classes, but "invents" +// OSM data in XML format that can be read. Through a parameter to the +// constructor it can be instructed to throw an exception in specific parts +// of its code. This is then used to test the internals of the Reader. + +class MockDecompressor : public osmium::io::Decompressor { + + std::string m_fail_in; + int m_read_count = 0; + +public: + + MockDecompressor(const std::string& fail_in) : + Decompressor(), + m_fail_in(fail_in) { + if (m_fail_in == "constructor") { + throw std::runtime_error("error constructor"); + } + } + + ~MockDecompressor() noexcept final = default; + + void add_node(std::string& s, int i) { + s += "\n"; + } + + std::string read() final { + std::string buffer; + ++m_read_count; + + if (m_read_count == 1) { + if (m_fail_in == "first read") { + throw std::runtime_error("error first read"); + } else { + buffer += "\n\n"; + for (int i = 0; i < 1000; ++i) { + add_node(buffer, i); + } + } + } else if (m_read_count == 2) { + if (m_fail_in == "second read") { + throw std::runtime_error("error second read"); + } else { + for (int i = 1000; i < 2000; ++i) { + add_node(buffer, i); + } + } + } else if (m_read_count == 3) { + buffer += ""; + } + + return buffer; + } + + void close() final { + if (m_fail_in == "close") { + throw std::runtime_error("error close"); + } + } + +}; // class MockDecompressor + +TEST_CASE("Test Reader using MockDecompressor") { + + std::string fail_in; + + osmium::io::CompressionFactory::instance().register_compression(osmium::io::file_compression::gzip, + [](int, osmium::io::fsync) { return nullptr; }, + [&](int) { return new MockDecompressor(fail_in); }, + [](const char*, size_t) { return nullptr; } + ); + + SECTION("fail in constructor") { + fail_in = "constructor"; + + try { + osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); + REQUIRE(false); + } catch (std::runtime_error& e) { + REQUIRE(std::string{e.what()} == "error constructor"); + } + } + + SECTION("fail in first read") { + fail_in = "first read"; + + try { + osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); + reader.read(); + REQUIRE(false); + } catch (std::runtime_error& e) { + REQUIRE(std::string{e.what()} == "error first read"); + } + } + + SECTION("fail in second read") { + fail_in = "second read"; + + try { + osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); + reader.read(); + reader.read(); + REQUIRE(false); + } catch (std::runtime_error& e) { + REQUIRE(std::string{e.what()} == "error second read"); + } + } + + SECTION("fail in close") { + fail_in = "close"; + + try { + osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); + reader.read(); + reader.read(); + reader.read(); + reader.close(); + REQUIRE(false); + } catch (std::runtime_error& e) { + REQUIRE(std::string{e.what()} == "error close"); + } + } + + SECTION("not failing") { + fail_in = "not"; + + osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); + reader.read(); + reader.close(); + REQUIRE(true); + } + +} + diff --git a/test/t/io/test_reader_with_mock_parser.cpp b/test/t/io/test_reader_with_mock_parser.cpp new file mode 100644 index 000000000..7c7dcddba --- /dev/null +++ b/test/t/io/test_reader_with_mock_parser.cpp @@ -0,0 +1,123 @@ + +#include "catch.hpp" +#include "utils.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class MockParser : public osmium::io::detail::Parser { + + std::string m_fail_in; + +public: + + MockParser(osmium::io::detail::future_string_queue_type& input_queue, + osmium::io::detail::future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_types, + const std::string& fail_in) : + Parser(input_queue, output_queue, header_promise, read_types), + m_fail_in(fail_in) { + } + + osmium::memory::Buffer create_testdata() { + osmium::memory::Buffer buffer(1000); + + { + osmium::builder::NodeBuilder nb(buffer); + nb.add_user("foo"); + } + buffer.commit(); + + return buffer; + } + + void run() final { + osmium::thread::set_thread_name("_osmium_mock_in"); + + if (m_fail_in == "header") { + throw std::runtime_error("error in header"); + } + + set_header_value(osmium::io::Header{}); + + send_to_output_queue(create_testdata()); + + if (m_fail_in == "read") { + throw std::runtime_error("error in read"); + } + } + +}; // class MockParser + +TEST_CASE("Test Reader using MockParser") { + + std::string fail_in; + + osmium::io::detail::ParserFactory::instance().register_parser( + osmium::io::file_format::xml, + [&](osmium::io::detail::future_string_queue_type& input_queue, + osmium::io::detail::future_buffer_queue_type& output_queue, + std::promise& header_promise, + osmium::osm_entity_bits::type read_which_entities) { + return std::unique_ptr(new MockParser(input_queue, output_queue, header_promise, read_which_entities, fail_in)); + }); + + SECTION("no failure") { + fail_in = ""; + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + auto header = reader.header(); + REQUIRE(reader.read()); + REQUIRE(!reader.read()); + REQUIRE(reader.eof()); + reader.close(); + } + + SECTION("throw in header") { + fail_in = "header"; + try { + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + reader.header(); + } catch (std::runtime_error& e) { + REQUIRE(std::string{e.what()} == "error in header"); + } + } + + SECTION("throw in read") { + fail_in = "read"; + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + reader.header(); + try { + reader.read(); + } catch (std::runtime_error& e) { + REQUIRE(std::string{e.what()} == "error in read"); + } + reader.close(); + } + + SECTION("throw in user code") { + fail_in = ""; + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + reader.header(); + try { + throw std::runtime_error("error in user code"); + } catch (std::runtime_error& e) { + REQUIRE(std::string{e.what()} == "error in user code"); + } + REQUIRE(reader.read()); + REQUIRE(!reader.read()); + REQUIRE(reader.eof()); + reader.close(); + } + +} + diff --git a/test/t/io/test_string_table.cpp b/test/t/io/test_string_table.cpp index 7fedfcfca..ab977e8bc 100644 --- a/test/t/io/test_string_table.cpp +++ b/test/t/io/test_string_table.cpp @@ -33,9 +33,9 @@ TEST_CASE("String store") { } SECTION("add zero-length string and longer strings") { - const char* s1 = ss.add(""); - const char* s2 = ss.add("xxx"); - const char* s3 = ss.add("yyyyy"); + ss.add(""); + ss.add("xxx"); + ss.add("yyyyy"); auto it = ss.begin(); REQUIRE(std::string(*it++) == ""); diff --git a/test/t/io/test_writer.cpp b/test/t/io/test_writer.cpp new file mode 100644 index 000000000..45593cf60 --- /dev/null +++ b/test/t/io/test_writer.cpp @@ -0,0 +1,117 @@ +#include "catch.hpp" +#include "utils.hpp" + +#include + +#include +#include +#include +#include +#include + +TEST_CASE("Writer") { + + osmium::io::Header header; + header.set("generator", "test_writer.cpp"); + + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + osmium::memory::Buffer buffer = reader.read(); + REQUIRE(buffer); + REQUIRE(buffer.committed() > 0); + auto num = std::distance(buffer.cbegin(), buffer.cend()); + REQUIRE(num > 0); + REQUIRE(buffer.cbegin()->id() == 1); + + std::string filename; + + SECTION("Empty writes") { + + SECTION("Empty buffer") { + filename = "test-writer-out-empty-buffer.osm"; + osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); + osmium::memory::Buffer empty_buffer(1024); + writer(std::move(empty_buffer)); + writer.close(); + } + + SECTION("Invalid buffer") { + filename = "test-writer-out-invalid-buffer.osm"; + osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); + osmium::memory::Buffer invalid_buffer; + writer(std::move(invalid_buffer)); + writer.close(); + } + + osmium::io::Reader reader_check(filename); + osmium::memory::Buffer buffer_check = reader_check.read(); + REQUIRE(!buffer_check); + } + + SECTION("Successfull writes") { + + SECTION("Writer buffer") { + filename = "test-writer-out-buffer.osm"; + osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); + writer(std::move(buffer)); + writer.close(); + + REQUIRE_THROWS_AS({ + writer(osmium::memory::Buffer{}); + }, osmium::io_error); + } + + SECTION("Writer item") { + filename = "test-writer-out-item.osm"; + osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); + for (const auto& item : buffer) { + writer(item); + } + writer.close(); + } + + SECTION("Writer output iterator") { + filename = "test-writer-out-iterator.osm"; + osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); + auto it = osmium::io::make_output_iterator(writer); + std::copy(buffer.cbegin(), buffer.cend(), it); + writer.close(); + } + + osmium::io::Reader reader_check(filename); + osmium::memory::Buffer buffer_check = reader_check.read(); + REQUIRE(buffer_check); + REQUIRE(buffer_check.committed() > 0); + REQUIRE(std::distance(buffer_check.cbegin(), buffer_check.cend()) == num); + REQUIRE(buffer_check.cbegin()->id() == 1); + + } + + SECTION("Interrupted write") { + + int error = 0; + try { + + SECTION("fail after open") { + filename = "test-writer-out-fail1.osm"; + osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); + throw 1; + } + + SECTION("fail after write") { + filename = "test-writer-out-fail2.osm"; + osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); + writer(std::move(buffer)); + throw 2; + } + + } catch (int e) { + error = e; + } + + REQUIRE(error > 0); + + } + +} + + diff --git a/test/t/io/test_writer_with_mock_compression.cpp b/test/t/io/test_writer_with_mock_compression.cpp new file mode 100644 index 000000000..c2d3bbd49 --- /dev/null +++ b/test/t/io/test_writer_with_mock_compression.cpp @@ -0,0 +1,99 @@ + +#include "catch.hpp" +#include "utils.hpp" + +#include +#include + +#include +#include +#include + +class MockCompressor : public osmium::io::Compressor { + + std::string m_fail_in; + +public: + + MockCompressor(const std::string& fail_in) : + Compressor(osmium::io::fsync::no), + m_fail_in(fail_in) { + if (m_fail_in == "constructor") { + throw std::logic_error("constructor"); + } + } + + ~MockCompressor() noexcept final = default; + + void write(const std::string&) final { + if (m_fail_in == "write") { + throw std::logic_error("write"); + } + } + + void close() final { + if (m_fail_in == "close") { + throw std::logic_error("close"); + } + } + +}; // class MockCompressor + +TEST_CASE("Write with mock compressor") { + + std::string fail_in; + + osmium::io::CompressionFactory::instance().register_compression(osmium::io::file_compression::gzip, + [&](int, osmium::io::fsync) { return new MockCompressor(fail_in); }, + [](int) { return nullptr; }, + [](const char*, size_t) { return nullptr; } + ); + + osmium::io::Header header; + header.set("generator", "test_writer_with_mock_compression.cpp"); + + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + osmium::memory::Buffer buffer = reader.read(); + REQUIRE(buffer); + REQUIRE(buffer.committed() > 0); + auto num = std::distance(buffer.cbegin(), buffer.cend()); + REQUIRE(num > 0); + + SECTION("fail on construction") { + + fail_in = "constructor"; + + REQUIRE_THROWS_AS({ + osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm.gz", header, osmium::io::overwrite::allow); + writer(std::move(buffer)); + writer.close(); + }, std::logic_error); + + } + + SECTION("fail on write") { + + fail_in = "write"; + + REQUIRE_THROWS_AS({ + osmium::io::Writer writer("test-writer-mock-fail-on-write.osm.gz", header, osmium::io::overwrite::allow); + writer(std::move(buffer)); + writer.close(); + }, std::logic_error); + + } + + SECTION("fail on close") { + + fail_in = "close"; + + REQUIRE_THROWS_AS({ + osmium::io::Writer writer("test-writer-mock-fail-on-close.osm.gz", header, osmium::io::overwrite::allow); + writer(std::move(buffer)); + writer.close(); + }, std::logic_error); + + } + +} + diff --git a/test/t/io/test_writer_with_mock_encoder.cpp b/test/t/io/test_writer_with_mock_encoder.cpp new file mode 100644 index 000000000..a43d59183 --- /dev/null +++ b/test/t/io/test_writer_with_mock_encoder.cpp @@ -0,0 +1,105 @@ + +#include "catch.hpp" +#include "utils.hpp" + +#include +#include + +#include +#include +#include +#include +#include + +class MockOutputFormat : public osmium::io::detail::OutputFormat { + + std::string m_fail_in; + +public: + + MockOutputFormat(const osmium::io::File&, osmium::io::detail::future_string_queue_type& output_queue, const std::string& fail_in) : + OutputFormat(output_queue), + m_fail_in(fail_in) { + } + + void write_header(const osmium::io::Header&) final { + if (m_fail_in == "header") { + throw std::logic_error("header"); + } + send_to_output_queue(std::string{"header"}); + } + + void write_buffer(osmium::memory::Buffer&&) final { + if (m_fail_in == "write") { + throw std::logic_error("write"); + } + send_to_output_queue(std::string{"write"}); + } + + void write_end() final { + if (m_fail_in == "write_end") { + throw std::logic_error("write_end"); + } + send_to_output_queue(std::string{"end"}); + } + +}; // class MockOutputFormat + +TEST_CASE("Test Writer with MockOutputFormat") { + + std::string fail_in; + + osmium::io::detail::OutputFormatFactory::instance().register_output_format( + osmium::io::file_format::xml, + [&](const osmium::io::File& file, osmium::io::detail::future_string_queue_type& output_queue) { + return new MockOutputFormat(file, output_queue, fail_in); + }); + + osmium::io::Header header; + header.set("generator", "test_writer_with_mock_encoder.cpp"); + + osmium::io::Reader reader(with_data_dir("t/io/data.osm")); + osmium::memory::Buffer buffer = reader.read(); + REQUIRE(buffer); + REQUIRE(buffer.committed() > 0); + auto num = std::distance(buffer.cbegin(), buffer.cend()); + REQUIRE(num > 0); + + SECTION("error in header") { + + fail_in = "header"; + + REQUIRE_THROWS_AS({ + osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow); + writer(std::move(buffer)); + writer.close(); + }, std::logic_error); + + } + + SECTION("error in write") { + + fail_in = "write"; + + REQUIRE_THROWS_AS({ + osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow); + writer(std::move(buffer)); + writer.close(); + }, std::logic_error); + + } + + SECTION("error in write_end") { + + fail_in = "write_end"; + + REQUIRE_THROWS_AS({ + osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow); + writer(std::move(buffer)); + writer.close(); + }, std::logic_error); + + } + +} + diff --git a/test/t/tags/test_tag_list.cpp b/test/t/tags/test_tag_list.cpp index 77523e796..295f51af8 100644 --- a/test/t/tags/test_tag_list.cpp +++ b/test/t/tags/test_tag_list.cpp @@ -100,3 +100,14 @@ TEST_CASE("empty keys and values are okay") { REQUIRE(std::string("") == tl.get_value_by_key("empty value")); REQUIRE(std::string("empty key") == tl.get_value_by_key("")); } + +TEST_CASE("tag key or value is too long") { + osmium::memory::Buffer buffer(10240); + osmium::builder::TagListBuilder builder(buffer); + + const char kv[2000] = ""; + builder.add_tag(kv, 1, kv, 1000); + REQUIRE_THROWS(builder.add_tag(kv, 1500, kv, 1)); + REQUIRE_THROWS(builder.add_tag(kv, 1, kv, 1500)); +} + diff --git a/test/t/thread/test_pool.cpp b/test/t/thread/test_pool.cpp index 5fa6bbab5..c1047db49 100644 --- a/test/t/thread/test_pool.cpp +++ b/test/t/thread/test_pool.cpp @@ -5,14 +5,7 @@ #include #include - -static std::atomic result; - -struct test_job_ok { - void operator()() const { - result = 1; - } -}; +#include struct test_job_with_result { int operator()() const { @@ -21,44 +14,55 @@ struct test_job_with_result { }; struct test_job_throw { - void operator()() const { + OSMIUM_NORETURN void operator()() const { throw std::runtime_error("exception in pool thread"); } }; +TEST_CASE("number of threads in pool") { + + // hardcoded setting + REQUIRE(osmium::thread::detail::get_pool_size( 1, 0, 2) == 1); + REQUIRE(osmium::thread::detail::get_pool_size( 4, 0, 2) == 4); + REQUIRE(osmium::thread::detail::get_pool_size( 4, 0, 4) == 4); + REQUIRE(osmium::thread::detail::get_pool_size(16, 0, 4) == 16); + REQUIRE(osmium::thread::detail::get_pool_size(16, 0, 16) == 16); + REQUIRE(osmium::thread::detail::get_pool_size( 8, 4, 2) == 8); + REQUIRE(osmium::thread::detail::get_pool_size( 8, 16, 2) == 8); + REQUIRE(osmium::thread::detail::get_pool_size(-2, 16, 2) == 1); + REQUIRE(osmium::thread::detail::get_pool_size(-2, 16, 8) == 6); + + // user decides through OSMIUM_POOL_THREADS env variable + REQUIRE(osmium::thread::detail::get_pool_size( 0, 0, 2) == 1); + REQUIRE(osmium::thread::detail::get_pool_size( 0, -2, 4) == 2); + REQUIRE(osmium::thread::detail::get_pool_size( 0, -1, 8) == 7); + REQUIRE(osmium::thread::detail::get_pool_size( 0, 0, 16) == 14); + REQUIRE(osmium::thread::detail::get_pool_size( 0, 1, 16) == 1); + REQUIRE(osmium::thread::detail::get_pool_size( 0, 2, 16) == 2); + REQUIRE(osmium::thread::detail::get_pool_size( 0, 4, 16) == 4); + REQUIRE(osmium::thread::detail::get_pool_size( 0, 8, 16) == 8); + + // outliers + REQUIRE(osmium::thread::detail::get_pool_size(-100, 0, 16) == 1); + REQUIRE(osmium::thread::detail::get_pool_size(1000, 0, 16) == 256); + +} + TEST_CASE("thread") { + auto& pool = osmium::thread::Pool::instance(); + SECTION("can get access to thread pool") { - auto& pool = osmium::thread::Pool::instance(); REQUIRE(pool.queue_empty()); } SECTION("can send job to thread pool") { - auto& pool = osmium::thread::Pool::instance(); - result = 0; - auto future = pool.submit(test_job_ok {}); - - // wait a bit for the other thread to get a chance to run - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - - REQUIRE(result == 1); - - future.get(); - - REQUIRE(true); - } - - SECTION("can send job to thread pool") { - auto& pool = osmium::thread::Pool::instance(); auto future = pool.submit(test_job_with_result {}); REQUIRE(future.get() == 42); } SECTION("can throw from job in thread pool") { - auto& pool = osmium::thread::Pool::instance(); - result = 0; - auto future = pool.submit(test_job_throw {}); REQUIRE_THROWS_AS(future.get(), std::runtime_error); diff --git a/test/t/util/test_data_file.cpp b/test/t/util/test_data_file.cpp deleted file mode 100644 index 3f432f943..000000000 --- a/test/t/util/test_data_file.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -TEST_CASE("temporary file") { - - SECTION("create/open") { - osmium::util::DataFile file; - - REQUIRE(!!file); - int fd = file.fd(); - - REQUIRE(fd > 0); - - const char buf[] = "foobar"; - REQUIRE(::write(fd, buf, sizeof(buf)) == sizeof(buf)); - - file.close(); - - REQUIRE(!file); - } - -} - -TEST_CASE("named file") { - - SECTION("create/open") { - { - osmium::util::DataFile file("test.data", true); - - REQUIRE(!!file); - int fd = file.fd(); - - REQUIRE(fd > 0); - - REQUIRE(file.size() == 0); - - const char buf[] = "foobar"; - REQUIRE(::write(fd, buf, sizeof(buf) - 1) == sizeof(buf) - 1); - - file.close(); - - REQUIRE(!file); - } - { - osmium::util::DataFile file("test.data", false); - - REQUIRE(!!file); - int fd = file.fd(); - - REQUIRE(fd > 0); - - REQUIRE(file.size() == 6); - - char buf[10]; - int len = ::read(fd, buf, sizeof(buf)); - - REQUIRE(len == 6); - REQUIRE(!strncmp(buf, "foobar", 6)); - - file.close(); - - REQUIRE(!file); - REQUIRE(unlink("test.data") == 0); - } - } - - SECTION("grow file") { - osmium::util::DataFile file("test.data", true); - - REQUIRE(!!file); - - REQUIRE(file.size() == 0); - file.grow(10); - REQUIRE(file.size() == 10); - } - -} - diff --git a/test/t/util/test_delta.cpp b/test/t/util/test_delta.cpp index cebcca8ed..667c9b443 100644 --- a/test/t/util/test_delta.cpp +++ b/test/t/util/test_delta.cpp @@ -4,24 +4,50 @@ #include -TEST_CASE("delta encode") { +TEST_CASE("delta encode int") { osmium::util::DeltaEncode x; SECTION("int") { REQUIRE(x.update(17) == 17); REQUIRE(x.update(10) == -7); + REQUIRE(x.update(-10) == -20); } } -TEST_CASE("delta decode") { +TEST_CASE("delta decode int") { osmium::util::DeltaDecode x; SECTION("int") { REQUIRE(x.update(17) == 17); REQUIRE(x.update(10) == 27); + REQUIRE(x.update(-40) == -13); + } + +} + +TEST_CASE("delta encode unsigned int") { + + osmium::util::DeltaEncode x; + + SECTION("int") { + REQUIRE(x.update(17) == 17); + REQUIRE(x.update(10) == -7); + REQUIRE(x.update(0) == -10); + } + +} + +TEST_CASE("delta decode unsigned int") { + + osmium::util::DeltaDecode x; + + SECTION("int") { + REQUIRE(x.update(17) == 17); + REQUIRE(x.update(10) == 27); + REQUIRE(x.update(-15) == 12); } } @@ -30,13 +56,13 @@ TEST_CASE("delta encode and decode") { std::vector a = { 5, -9, 22, 13, 0, 23 }; - osmium::util::DeltaEncode de; + osmium::util::DeltaEncode de; std::vector b; for (int x : a) { b.push_back(de.update(x)); } - osmium::util::DeltaDecode dd; + osmium::util::DeltaDecode dd; std::vector c; for (int x : b) { c.push_back(dd.update(x)); diff --git a/test/t/util/test_file.cpp b/test/t/util/test_file.cpp index 2787261a5..475f28596 100644 --- a/test/t/util/test_file.cpp +++ b/test/t/util/test_file.cpp @@ -3,6 +3,7 @@ #include #ifdef _WIN32 +#include // https://msdn.microsoft.com/en-us/library/ksazx244.aspx // https://msdn.microsoft.com/en-us/library/a9yf33zb.aspx class DoNothingInvalidParameterHandler { @@ -23,6 +24,7 @@ public: DoNothingInvalidParameterHandler() : old_handler(_set_invalid_parameter_handler(invalid_parameter_handler)) { + _CrtSetReportMode(_CRT_ASSERT, 0); } ~DoNothingInvalidParameterHandler() { diff --git a/test/t/util/test_options.cpp b/test/t/util/test_options.cpp index 969f20103..8cba0950b 100644 --- a/test/t/util/test_options.cpp +++ b/test/t/util/test_options.cpp @@ -6,43 +6,76 @@ TEST_CASE("Options") { - SECTION("set_simple") { - osmium::util::Options o; + osmium::util::Options o; + + SECTION("set a single value from string") { o.set("foo", "bar"); REQUIRE("bar" == o.get("foo")); REQUIRE("" == o.get("empty")); REQUIRE("default" == o.get("empty", "default")); + REQUIRE(!o.is_true("foo")); REQUIRE(!o.is_true("empty")); + + REQUIRE(o.is_not_false("foo")); + REQUIRE(o.is_not_false("empty")); + REQUIRE(1 == o.size()); } - SECTION("set_from_bool") { - osmium::util::Options o; + SECTION("set values from booleans") { o.set("t", true); o.set("f", false); REQUIRE("true" == o.get("t")); REQUIRE("false" == o.get("f")); REQUIRE("" == o.get("empty")); + REQUIRE(o.is_true("t")); REQUIRE(!o.is_true("f")); + + REQUIRE(o.is_not_false("t")); + REQUIRE(!o.is_not_false("f")); + REQUIRE(2 == o.size()); } - SECTION("set_from_single_string_with_equals") { - osmium::util::Options o; + SECTION("set value from string with equal sign") { o.set("foo=bar"); REQUIRE("bar" == o.get("foo")); REQUIRE(1 == o.size()); } - SECTION("set_from_single_string_without_equals") { - osmium::util::Options o; + SECTION("set value from string without equal sign") { o.set("foo"); REQUIRE("true" == o.get("foo")); + REQUIRE(o.is_true("foo")); + REQUIRE(o.is_not_false("foo")); + REQUIRE(1 == o.size()); } } +TEST_CASE("Options with initializer list") { + + osmium::util::Options o{ { "foo", "true" }, { "bar", "17" } }; + + REQUIRE(o.get("foo") == "true"); + REQUIRE(o.get("bar") == "17"); + REQUIRE(o.is_true("foo")); + REQUIRE_FALSE(o.is_true("bar")); + REQUIRE(o.size() == 2); + + SECTION("Change existing value") { + o.set("foo", "false"); + REQUIRE_FALSE(o.is_true("foo")); + } + + SECTION("Add new value") { + o.set("new", "something"); + REQUIRE_FALSE(o.is_true("new")); + REQUIRE(o.get("new") == "something"); + } +} + From 028ca5c9d9031e634ff9ee44749ed678c828eecf Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 5 Jan 2016 12:04:04 +0100 Subject: [PATCH 021/701] Apply clang-format --- include/contractor/contractor.hpp | 164 ++++++++++-------- include/contractor/contractor_options.hpp | 6 +- .../engine/datafacade/internal_datafacade.hpp | 19 +- .../engine/datafacade/shared_datafacade.hpp | 27 +-- include/engine/datafacade/shared_datatype.hpp | 3 +- .../engine/descriptors/json_descriptor.hpp | 24 ++- include/engine/geospatial_query.hpp | 16 +- .../map_matching/hidden_markov_model.hpp | 2 +- include/engine/phantom_node.hpp | 3 +- include/engine/plugins/distance_table.hpp | 8 +- include/engine/plugins/hello_world.hpp | 2 +- include/engine/plugins/nearest.hpp | 2 +- include/engine/plugins/plugin_base.hpp | 8 +- include/engine/plugins/timestamp.hpp | 2 +- include/engine/plugins/trip.hpp | 18 +- include/engine/plugins/viaroute.hpp | 2 +- include/engine/polyline_compressor.hpp | 2 +- .../direct_shortest_path.hpp | 14 +- .../routing_algorithms/many_to_many.hpp | 15 +- .../routing_algorithms/map_matching.hpp | 19 +- .../routing_algorithms/routing_base.hpp | 13 +- .../routing_algorithms/shortest_path.hpp | 67 +++---- include/engine/search_engine.hpp | 6 +- include/engine/segment_information.hpp | 9 +- .../extractor/compressed_edge_container.hpp | 2 +- .../extractor/edge_based_graph_factory.hpp | 17 +- include/extractor/edge_based_node.hpp | 6 +- include/extractor/extraction_containers.hpp | 9 +- .../first_and_last_segment_of_way.hpp | 18 +- include/extractor/graph_compressor.hpp | 22 +-- include/extractor/import_edge.hpp | 36 ++-- include/extractor/internal_extractor_edge.hpp | 36 ++-- include/extractor/query_node.hpp | 12 +- include/extractor/restriction.hpp | 2 +- include/extractor/restriction_map.hpp | 2 +- include/extractor/speed_profile.hpp | 14 +- include/osrm/route_parameters.hpp | 6 +- include/osrm/strong_typedef.hpp | 57 +++--- include/server/api_grammar.hpp | 50 +++--- include/util/binary_heap.hpp | 7 +- include/util/coordinate_calculation.hpp | 61 ++++--- include/util/datastore_options.hpp | 4 +- include/util/deallocating_vector.hpp | 19 +- include/util/debug_geometry.hpp | 138 +++++++++------ include/util/dynamic_graph.hpp | 3 +- include/util/fingerprint.hpp | 2 - include/util/graph_utils.hpp | 16 +- include/util/integer_range.hpp | 5 +- include/util/json_logger.hpp | 11 +- include/util/node_based_graph.hpp | 30 ++-- include/util/range_table.hpp | 3 +- include/util/static_graph.hpp | 6 +- include/util/static_rtree.hpp | 16 +- src/benchmarks/static_rtree.cpp | 8 +- src/contractor/contractor_options.cpp | 36 ++-- src/contractor/processing_chain.cpp | 23 +-- .../descriptors/description_factory.cpp | 36 ++-- src/engine/osrm_impl.cpp | 13 +- src/engine/phantom_node.cpp | 6 +- src/engine/polyline_compressor.cpp | 15 +- src/engine/route_parameters.cpp | 15 +- src/extractor/compressed_edge_container.cpp | 15 +- src/extractor/edge_based_graph_factory.cpp | 117 +++++++------ src/extractor/extraction_containers.cpp | 116 +++++++------ src/extractor/extractor.cpp | 2 +- src/extractor/extractor_callbacks.cpp | 42 +++-- src/extractor/extractor_options.cpp | 44 ++--- src/extractor/graph_compressor.cpp | 28 ++- src/extractor/import_edge.cpp | 8 +- src/extractor/restriction_map.cpp | 3 +- src/extractor/restriction_parser.cpp | 4 +- src/extractor/scripting_environment.cpp | 123 +++++++------ src/server/request_handler.cpp | 9 +- src/server/request_parser.cpp | 39 ++--- src/tools/routed.cpp | 4 +- src/util/coordinate.cpp | 2 +- src/util/coordinate_calculation.cpp | 58 +++---- unit_tests/engine/douglas_peucker.cpp | 6 +- unit_tests/engine/geometry_string.cpp | 14 +- unit_tests/extractor/graph_compressor.cpp | 20 ++- unit_tests/util/bearing.cpp | 1 - unit_tests/util/dynamic_graph.cpp | 9 +- unit_tests/util/static_graph.cpp | 9 +- unit_tests/util/static_rtree.cpp | 5 +- 84 files changed, 988 insertions(+), 903 deletions(-) diff --git a/include/contractor/contractor.hpp b/include/contractor/contractor.hpp index 21a75ba2a..fa6dce2ed 100644 --- a/include/contractor/contractor.hpp +++ b/include/contractor/contractor.hpp @@ -130,15 +130,14 @@ class Contractor }; public: - template Contractor(int nodes, ContainerT &input_edge_list) - : Contractor(nodes, input_edge_list, {}, {}) + template + Contractor(int nodes, ContainerT &input_edge_list) + : Contractor(nodes, input_edge_list, {}, {}) { } template - Contractor(int nodes, - ContainerT &input_edge_list, - std::vector &&node_levels_) + Contractor(int nodes, ContainerT &input_edge_list, std::vector &&node_levels_) : node_levels(std::move(node_levels_)) { std::vector edges; @@ -317,8 +316,8 @@ class Contractor std::cout << "initializing elimination PQ ..." << std::flush; tbb::parallel_for(tbb::blocked_range(0, number_of_nodes, PQGrainSize), - [this, &node_priorities, &node_data, &thread_data_list]( - const tbb::blocked_range &range) + [this, &node_priorities, &node_data, + &thread_data_list](const tbb::blocked_range &range) { ContractorThreadData *data = thread_data_list.getThreadData(); for (int x = range.begin(), end = range.end(); x != end; ++x) @@ -360,7 +359,7 @@ class Contractor for (const auto new_node_id : osrm::irange(0, remaining_nodes.size())) { - auto& node = remaining_nodes[new_node_id]; + auto &node = remaining_nodes[new_node_id]; BOOST_ASSERT(node_priorities.size() > node.id); new_node_priority[new_node_id] = node_priorities[node.id]; } @@ -368,7 +367,7 @@ class Contractor // build forward and backward renumbering map and remap ids in remaining_nodes for (const auto new_node_id : osrm::irange(0, remaining_nodes.size())) { - auto& node = remaining_nodes[new_node_id]; + auto &node = remaining_nodes[new_node_id]; // create renumbering maps in both directions orig_node_id_from_new_node_id_map[new_node_id] = node.id; new_node_id_from_orig_id_map[node.id] = new_node_id; @@ -392,8 +391,7 @@ class Contractor // node is not yet contracted. // add (renumbered) outgoing edges to new DynamicGraph. ContractorEdge new_edge = {new_node_id_from_orig_id_map[source], - new_node_id_from_orig_id_map[target], - data}; + new_node_id_from_orig_id_map[target], data}; new_edge.data.is_original_via_node_ID = true; BOOST_ASSERT_MSG(UINT_MAX != new_node_id_from_orig_id_map[source], @@ -430,39 +428,44 @@ class Contractor thread_data_list.number_of_nodes = contractor_graph->GetNumberOfNodes(); } - tbb::parallel_for(tbb::blocked_range(0, remaining_nodes.size(), IndependentGrainSize), - [this, &node_priorities, &remaining_nodes, &thread_data_list]( - const tbb::blocked_range &range) - { - ContractorThreadData *data = thread_data_list.getThreadData(); - // determine independent node set - for (auto i = range.begin(), end = range.end(); i != end; ++i) - { - const NodeID node = remaining_nodes[i].id; - remaining_nodes[i].is_independent = - this->IsNodeIndependent(node_priorities, data, node); - } - }); + tbb::parallel_for( + tbb::blocked_range(0, remaining_nodes.size(), IndependentGrainSize), + [this, &node_priorities, &remaining_nodes, + &thread_data_list](const tbb::blocked_range &range) + { + ContractorThreadData *data = thread_data_list.getThreadData(); + // determine independent node set + for (auto i = range.begin(), end = range.end(); i != end; ++i) + { + const NodeID node = remaining_nodes[i].id; + remaining_nodes[i].is_independent = + this->IsNodeIndependent(node_priorities, data, node); + } + }); // sort all remaining nodes to the beginning of the sequence - const auto begin_independent_nodes = stable_partition(remaining_nodes.begin(), remaining_nodes.end(), - [](RemainingNodeData node_data) - { - return !node_data.is_independent; - }); - auto begin_independent_nodes_idx = std::distance(remaining_nodes.begin(), begin_independent_nodes); + const auto begin_independent_nodes = stable_partition( + remaining_nodes.begin(), remaining_nodes.end(), [](RemainingNodeData node_data) + { + return !node_data.is_independent; + }); + auto begin_independent_nodes_idx = + std::distance(remaining_nodes.begin(), begin_independent_nodes); auto end_independent_nodes_idx = remaining_nodes.size(); if (!use_cached_node_priorities) { // write out contraction level tbb::parallel_for( - tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, ContractGrainSize), - [this, remaining_nodes, flushed_contractor, current_level](const tbb::blocked_range &range) + tbb::blocked_range(begin_independent_nodes_idx, + end_independent_nodes_idx, ContractGrainSize), + [this, remaining_nodes, flushed_contractor, + current_level](const tbb::blocked_range &range) { if (flushed_contractor) { - for (int position = range.begin(), end = range.end(); position != end; ++position) + for (int position = range.begin(), end = range.end(); position != end; + ++position) { const NodeID x = remaining_nodes[position].id; node_levels[orig_node_id_from_new_node_id_map[x]] = current_level; @@ -470,7 +473,8 @@ class Contractor } else { - for (int position = range.begin(), end = range.end(); position != end; ++position) + for (int position = range.begin(), end = range.end(); position != end; + ++position) { const NodeID x = remaining_nodes[position].id; node_levels[x] = current_level; @@ -480,24 +484,29 @@ class Contractor } // contract independent nodes - tbb::parallel_for( - tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, ContractGrainSize), - [this, &remaining_nodes, &thread_data_list](const tbb::blocked_range &range) - { - ContractorThreadData *data = thread_data_list.getThreadData(); - for (int position = range.begin(), end = range.end(); position != end; ++position) - { - const NodeID x = remaining_nodes[position].id; - this->ContractNode(data, x); - } - }); + tbb::parallel_for(tbb::blocked_range(begin_independent_nodes_idx, + end_independent_nodes_idx, + ContractGrainSize), + [this, &remaining_nodes, + &thread_data_list](const tbb::blocked_range &range) + { + ContractorThreadData *data = thread_data_list.getThreadData(); + for (int position = range.begin(), end = range.end(); + position != end; ++position) + { + const NodeID x = remaining_nodes[position].id; + this->ContractNode(data, x); + } + }); tbb::parallel_for( - tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, DeleteGrainSize), + tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, + DeleteGrainSize), [this, &remaining_nodes, &thread_data_list](const tbb::blocked_range &range) { ContractorThreadData *data = thread_data_list.getThreadData(); - for (int position = range.begin(), end = range.end(); position != end; ++position) + for (int position = range.begin(), end = range.end(); position != end; + ++position) { const NodeID x = remaining_nodes[position].id; this->DeleteIncomingEdges(data, x); @@ -542,12 +551,14 @@ class Contractor if (!use_cached_node_priorities) { tbb::parallel_for( - tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, NeighboursGrainSize), - [this, &node_priorities, &remaining_nodes, &node_data, &thread_data_list]( - const tbb::blocked_range &range) + tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, + NeighboursGrainSize), + [this, &node_priorities, &remaining_nodes, &node_data, + &thread_data_list](const tbb::blocked_range &range) { ContractorThreadData *data = thread_data_list.getThreadData(); - for (int position = range.begin(), end = range.end(); position != end; ++position) + for (int position = range.begin(), end = range.end(); position != end; + ++position) { NodeID x = remaining_nodes[position].id; this->UpdateNodeNeighbours(node_priorities, node_data, data, x); @@ -589,32 +600,31 @@ class Contractor if (remaining_nodes.size() > 2) { - if (orig_node_id_from_new_node_id_map.size() > 0) - { - tbb::parallel_for( - tbb::blocked_range(0, remaining_nodes.size(), InitGrainSize), - [this, &remaining_nodes](const tbb::blocked_range &range) - { - for (int x = range.begin(), end = range.end(); x != end; ++x) - { - const auto orig_id = remaining_nodes[x].id; - is_core_node[orig_node_id_from_new_node_id_map[orig_id]] = true; - } - }); - } - else - { - tbb::parallel_for( - tbb::blocked_range(0, remaining_nodes.size(), InitGrainSize), - [this, &remaining_nodes](const tbb::blocked_range &range) - { - for (int x = range.begin(), end = range.end(); x != end; ++x) - { - const auto orig_id = remaining_nodes[x].id; - is_core_node[orig_id] = true; - } - }); - } + if (orig_node_id_from_new_node_id_map.size() > 0) + { + tbb::parallel_for(tbb::blocked_range(0, remaining_nodes.size(), InitGrainSize), + [this, &remaining_nodes](const tbb::blocked_range &range) + { + for (int x = range.begin(), end = range.end(); x != end; ++x) + { + const auto orig_id = remaining_nodes[x].id; + is_core_node[orig_node_id_from_new_node_id_map[orig_id]] = + true; + } + }); + } + else + { + tbb::parallel_for(tbb::blocked_range(0, remaining_nodes.size(), InitGrainSize), + [this, &remaining_nodes](const tbb::blocked_range &range) + { + for (int x = range.begin(), end = range.end(); x != end; ++x) + { + const auto orig_id = remaining_nodes[x].id; + is_core_node[orig_id] = true; + } + }); + } } else { diff --git a/include/contractor/contractor_options.hpp b/include/contractor/contractor_options.hpp index 982645bdc..c64681fa9 100644 --- a/include/contractor/contractor_options.hpp +++ b/include/contractor/contractor_options.hpp @@ -31,9 +31,9 @@ struct ContractorConfig unsigned requested_num_threads; - //A percentage of vertices that will be contracted for the hierarchy. - //Offers a trade-off between preprocessing and query time. - //The remaining vertices form the core of the hierarchy + // A percentage of vertices that will be contracted for the hierarchy. + // Offers a trade-off between preprocessing and query time. + // The remaining vertices form the core of the hierarchy //(e.g. 0.8 contracts 80 percent of the hierarchy, leaving a core of 20%) double core_factor; diff --git a/include/engine/datafacade/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp index 83301ab8c..35f2e223b 100644 --- a/include/engine/datafacade/internal_datafacade.hpp +++ b/include/engine/datafacade/internal_datafacade.hpp @@ -232,7 +232,8 @@ template class InternalDataFacade final : public BaseDataFacad m_geospatial_query.reset(); } - explicit InternalDataFacade(const std::unordered_map &server_paths) + explicit InternalDataFacade( + const std::unordered_map &server_paths) { // cache end iterator to quickly check .find against const auto end_it = end(server_paths); @@ -331,7 +332,6 @@ template class InternalDataFacade final : public BaseDataFacad return m_travel_mode_list.at(id); } - std::vector NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, const float max_distance, @@ -344,7 +344,8 @@ template class InternalDataFacade final : public BaseDataFacad BOOST_ASSERT(m_geospatial_query.get()); } - return m_geospatial_query->NearestPhantomNodesInRange(input_coordinate, max_distance, bearing, bearing_range); + return m_geospatial_query->NearestPhantomNodesInRange(input_coordinate, max_distance, + bearing, bearing_range); } std::vector @@ -359,7 +360,8 @@ template class InternalDataFacade final : public BaseDataFacad BOOST_ASSERT(m_geospatial_query.get()); } - return m_geospatial_query->NearestPhantomNodes(input_coordinate, max_results, bearing, bearing_range); + return m_geospatial_query->NearestPhantomNodes(input_coordinate, max_results, bearing, + bearing_range); } std::pair @@ -373,10 +375,10 @@ template class InternalDataFacade final : public BaseDataFacad BOOST_ASSERT(m_geospatial_query.get()); } - return m_geospatial_query->NearestPhantomNodeWithAlternativeFromBigComponent(input_coordinate, bearing, bearing_range); + return m_geospatial_query->NearestPhantomNodeWithAlternativeFromBigComponent( + input_coordinate, bearing, bearing_range); } - unsigned GetCheckSum() const override final { return m_check_sum; } unsigned GetNameIndexFromEdgeID(const unsigned id) const override final @@ -408,10 +410,7 @@ template class InternalDataFacade final : public BaseDataFacad return m_via_node_list.at(id); } - virtual std::size_t GetCoreSize() const override final - { - return m_is_core_node.size(); - } + virtual std::size_t GetCoreSize() const override final { return m_is_core_node.size(); } virtual bool IsCoreNode(const NodeID id) const override final { diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 1debe68be..225056f89 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -96,7 +96,8 @@ template class SharedDataFacade final : public BaseDataFacade< osrm::make_unique( tree_ptr, data_layout->num_entries[SharedDataLayout::R_SEARCH_TREE], file_index_path, m_coordinate_list))); - m_geospatial_query.reset(new SharedGeospatialQuery(*m_static_rtree->second, m_coordinate_list)); + m_geospatial_query.reset( + new SharedGeospatialQuery(*m_static_rtree->second, m_coordinate_list)); } void LoadGraph() @@ -179,11 +180,10 @@ template class SharedDataFacade final : public BaseDataFacade< return; } - unsigned *core_marker_ptr = data_layout->GetBlockPtr( - shared_memory, SharedDataLayout::CORE_MARKER); + unsigned *core_marker_ptr = + data_layout->GetBlockPtr(shared_memory, SharedDataLayout::CORE_MARKER); typename ShM::vector is_core_node( - core_marker_ptr, - data_layout->num_entries[SharedDataLayout::CORE_MARKER]); + core_marker_ptr, data_layout->num_entries[SharedDataLayout::CORE_MARKER]); m_is_core_node.swap(is_core_node); } @@ -215,7 +215,8 @@ template class SharedDataFacade final : public BaseDataFacade< SharedDataFacade() { data_timestamp_ptr = (SharedDataTimestamp *)SharedMemoryFactory::Get( - CURRENT_REGIONS, sizeof(SharedDataTimestamp), false, false)->Ptr(); + CURRENT_REGIONS, sizeof(SharedDataTimestamp), false, false) + ->Ptr(); CURRENT_LAYOUT = LAYOUT_NONE; CURRENT_DATA = DATA_NONE; CURRENT_TIMESTAMP = 0; @@ -369,7 +370,8 @@ template class SharedDataFacade final : public BaseDataFacade< BOOST_ASSERT(m_geospatial_query.get()); } - return m_geospatial_query->NearestPhantomNodesInRange(input_coordinate, max_distance, bearing, bearing_range); + return m_geospatial_query->NearestPhantomNodesInRange(input_coordinate, max_distance, + bearing, bearing_range); } std::vector @@ -384,7 +386,8 @@ template class SharedDataFacade final : public BaseDataFacade< BOOST_ASSERT(m_geospatial_query.get()); } - return m_geospatial_query->NearestPhantomNodes(input_coordinate, max_results, bearing, bearing_range); + return m_geospatial_query->NearestPhantomNodes(input_coordinate, max_results, bearing, + bearing_range); } std::pair @@ -398,7 +401,8 @@ template class SharedDataFacade final : public BaseDataFacade< BOOST_ASSERT(m_geospatial_query.get()); } - return m_geospatial_query->NearestPhantomNodeWithAlternativeFromBigComponent(input_coordinate, bearing, bearing_range); + return m_geospatial_query->NearestPhantomNodeWithAlternativeFromBigComponent( + input_coordinate, bearing, bearing_range); } unsigned GetCheckSum() const override final { return m_check_sum; } @@ -437,10 +441,7 @@ template class SharedDataFacade final : public BaseDataFacade< return false; } - virtual std::size_t GetCoreSize() const override final - { - return m_is_core_node.size(); - } + virtual std::size_t GetCoreSize() const override final { return m_is_core_node.size(); } std::string GetTimestamp() const override final { return m_timestamp; } }; diff --git a/include/engine/datafacade/shared_datatype.hpp b/include/engine/datafacade/shared_datatype.hpp index 9cd38adab..187d9b6cb 100644 --- a/include/engine/datafacade/shared_datatype.hpp +++ b/include/engine/datafacade/shared_datatype.hpp @@ -95,8 +95,7 @@ struct SharedDataLayout // special bit encoding if (bid == GEOMETRIES_INDICATORS || bid == CORE_MARKER) { - return (num_entries[bid] / 32 + 1) * - entry_size[bid]; + return (num_entries[bid] / 32 + 1) * entry_size[bid]; } return num_entries[bid] * entry_size[bid]; diff --git a/include/engine/descriptors/json_descriptor.hpp b/include/engine/descriptors/json_descriptor.hpp index 4b8d0136f..b5eda81a8 100644 --- a/include/engine/descriptors/json_descriptor.hpp +++ b/include/engine/descriptors/json_descriptor.hpp @@ -38,14 +38,13 @@ template class JSONDescriptor final : public BaseDescriptor< int length; unsigned position; }; + private: std::vector shortest_path_segments, alternative_path_segments; ExtractRouteNames GenerateRouteNames; public: - explicit JSONDescriptor(DataFacadeT *facade) : facade(facade) - { - } + explicit JSONDescriptor(DataFacadeT *facade) : facade(facade) {} virtual void SetConfig(const DescriptorConfig &c) override final { config = c; } @@ -108,7 +107,8 @@ template class JSONDescriptor final : public BaseDescriptor< } if (config.instructions) { - osrm::json::Array json_route_instructions = BuildTextualDescription(description_factory, shortest_path_segments); + osrm::json::Array json_route_instructions = + BuildTextualDescription(description_factory, shortest_path_segments); json_result.values["route_instructions"] = json_route_instructions; } description_factory.BuildRouteSummary(description_factory.get_entire_length(), @@ -185,7 +185,8 @@ template class JSONDescriptor final : public BaseDescriptor< osrm::json::Array json_current_alt_instructions; if (config.instructions) { - json_current_alt_instructions = BuildTextualDescription(alternate_description_factory, alternative_path_segments); + json_current_alt_instructions = BuildTextualDescription( + alternate_description_factory, alternative_path_segments); json_alt_instructions.values.push_back(json_current_alt_instructions); json_result.values["alternative_instructions"] = json_alt_instructions; } @@ -240,7 +241,7 @@ template class JSONDescriptor final : public BaseDescriptor< json_result.values["hint_data"] = BuildHintData(raw_route); } - inline osrm::json::Object BuildHintData(const InternalRouteResult& raw_route) const + inline osrm::json::Object BuildHintData(const InternalRouteResult &raw_route) const { osrm::json::Object json_hint_object; json_hint_object.values["checksum"] = facade->GetCheckSum(); @@ -260,8 +261,9 @@ template class JSONDescriptor final : public BaseDescriptor< return json_hint_object; } - inline osrm::json::Array BuildTextualDescription(const DescriptionFactory &description_factory, - std::vector &route_segments_list) const + inline osrm::json::Array + BuildTextualDescription(const DescriptionFactory &description_factory, + std::vector &route_segments_list) const { osrm::json::Array json_instruction_array; // Segment information has following format: @@ -270,7 +272,11 @@ template class JSONDescriptor final : public BaseDescriptor< struct RoundAbout { - RoundAbout() : start_index(std::numeric_limits::max()), name_id(INVALID_NAMEID), leave_at_exit(std::numeric_limits::max()) {} + RoundAbout() + : start_index(std::numeric_limits::max()), name_id(INVALID_NAMEID), + leave_at_exit(std::numeric_limits::max()) + { + } int start_index; unsigned name_id; int leave_at_exit; diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index 95a41da93..a236df18b 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -129,7 +129,7 @@ template class GeospatialQuery } PhantomNodeWithDistance MakePhantomNode(const FixedPointCoordinate &input_coordinate, - const EdgeData &data) const + const EdgeData &data) const { FixedPointCoordinate point_on_segment; double ratio; @@ -137,8 +137,8 @@ template class GeospatialQuery coordinates->at(data.u), coordinates->at(data.v), input_coordinate, point_on_segment, ratio); - auto transformed = - PhantomNodeWithDistance { PhantomNode{data, point_on_segment}, current_perpendicular_distance }; + auto transformed = PhantomNodeWithDistance{PhantomNode{data, point_on_segment}, + current_perpendicular_distance}; ratio = std::min(1.0, std::max(0.0, ratio)); @@ -161,14 +161,16 @@ template class GeospatialQuery coordinate_calculation::bearing(coordinates->at(segment.u), coordinates->at(segment.v)); const double backward_edge_bearing = (forward_edge_bearing + 180) > 360 - ? (forward_edge_bearing - 180) - : (forward_edge_bearing + 180); + ? (forward_edge_bearing - 180) + : (forward_edge_bearing + 180); const bool forward_bearing_valid = - bearing::CheckInBounds(std::round(forward_edge_bearing), filter_bearing, filter_bearing_range) && + bearing::CheckInBounds(std::round(forward_edge_bearing), filter_bearing, + filter_bearing_range) && segment.forward_edge_based_node_id != SPECIAL_NODEID; const bool backward_bearing_valid = - bearing::CheckInBounds(std::round(backward_edge_bearing), filter_bearing, filter_bearing_range) && + bearing::CheckInBounds(std::round(backward_edge_bearing), filter_bearing, + filter_bearing_range) && segment.reverse_edge_based_node_id != SPECIAL_NODEID; return std::make_pair(forward_bearing_valid, backward_bearing_valid); } diff --git a/include/engine/map_matching/hidden_markov_model.hpp b/include/engine/map_matching/hidden_markov_model.hpp index 8fd8c759f..ef91fca09 100644 --- a/include/engine/map_matching/hidden_markov_model.hpp +++ b/include/engine/map_matching/hidden_markov_model.hpp @@ -72,7 +72,7 @@ template struct HiddenMarkovModel breakage.resize(candidates_list.size()); for (const auto i : osrm::irange(0u, candidates_list.size())) { - const auto& num_candidates = candidates_list[i].size(); + const auto &num_candidates = candidates_list[i].size(); // add empty vectors if (num_candidates > 0) { diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index 2b37cfeda..484526674 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -61,7 +61,8 @@ struct PhantomNode int forward_offset; int reverse_offset; unsigned packed_geometry_id; - struct ComponentType { + struct ComponentType + { uint32_t id : 31; bool is_tiny : 1; } component; diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index 6a3b52f89..4c664c845 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -41,7 +41,7 @@ template class DistanceTablePlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + osrm::json::Object &json_result) override final { if (!check_all_coordinates(route_parameters.coordinates)) { @@ -132,7 +132,8 @@ template class DistanceTablePlugin final : public BasePlugin if (!phantom_node_source_out_iter->first.is_valid(facade->GetNumberOfNodes())) { json_result.values["status_message"] = - std::string("Could not find a matching segment for coordinate ") + std::to_string(i); + std::string("Could not find a matching segment for coordinate ") + + std::to_string(i); return Status::NoSegment; } @@ -154,7 +155,8 @@ template class DistanceTablePlugin final : public BasePlugin if (!phantom_node_target_out_iter->first.is_valid(facade->GetNumberOfNodes())) { json_result.values["status_message"] = - std::string("Could not find a matching segment for coordinate ") + std::to_string(i); + std::string("Could not find a matching segment for coordinate ") + + std::to_string(i); return Status::NoSegment; } phantom_node_target_out_iter++; diff --git a/include/engine/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp index 8a5193962..d3ecdf990 100644 --- a/include/engine/plugins/hello_world.hpp +++ b/include/engine/plugins/hello_world.hpp @@ -20,7 +20,7 @@ class HelloWorldPlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &routeParameters, - osrm::json::Object &json_result) override final + osrm::json::Object &json_result) override final { std::string temp_string; json_result.values["title"] = "Hello World"; diff --git a/include/engine/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp index 831f30a64..e22a91e65 100644 --- a/include/engine/plugins/nearest.hpp +++ b/include/engine/plugins/nearest.hpp @@ -23,7 +23,7 @@ template class NearestPlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + osrm::json::Object &json_result) override final { // check number of parameters if (route_parameters.coordinates.empty() || diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index 51b7cf5cc..d7fe94983 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -16,10 +16,10 @@ class BasePlugin public: enum class Status : int { - Ok = 200, - EmptyResult = 207, - NoSegment = 208, - Error = 400 + Ok = 200, + EmptyResult = 207, + NoSegment = 208, + Error = 400 }; BasePlugin() {} diff --git a/include/engine/plugins/timestamp.hpp b/include/engine/plugins/timestamp.hpp index e441b4607..beb02caac 100644 --- a/include/engine/plugins/timestamp.hpp +++ b/include/engine/plugins/timestamp.hpp @@ -18,7 +18,7 @@ template class TimestampPlugin final : public BasePlugin } const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + osrm::json::Object &json_result) override final { (void)route_parameters; // unused diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index 56a0f19e1..c1eae77e1 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -9,15 +9,15 @@ #include "engine/trip/trip_farthest_insertion.hpp" #include "engine/trip/trip_brute_force.hpp" #include "engine/search_engine.hpp" -#include "util/matrix_graph_wrapper.hpp" // wrapper to use tarjan - // scc on dist table -#include "engine/descriptors/descriptor_base.hpp" // to make json output -#include "engine/descriptors/json_descriptor.hpp" // to make json output +#include "util/matrix_graph_wrapper.hpp" // wrapper to use tarjan + // scc on dist table +#include "engine/descriptors/descriptor_base.hpp" // to make json output +#include "engine/descriptors/json_descriptor.hpp" // to make json output #include "util/make_unique.hpp" -#include "util/timing_util.hpp" // to time runtime +#include "util/timing_util.hpp" // to time runtime //#include "util/simple_logger.hpp" // for logging output #include "util/dist_table_wrapper.hpp" // to access the dist - // table more easily + // table more easily #include "osrm/json_container.hpp" #include @@ -74,7 +74,8 @@ template class RoundTripPlugin final : public BasePlugin const int range = input_bearings.size() > 0 ? (input_bearings[i].second ? *input_bearings[i].second : 10) : 180; - auto results = facade->NearestPhantomNodes(route_parameters.coordinates[i], 1, bearing, range); + auto results = + facade->NearestPhantomNodes(route_parameters.coordinates[i], 1, bearing, range); if (results.empty()) { break; @@ -222,7 +223,7 @@ template class RoundTripPlugin final : public BasePlugin } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + osrm::json::Object &json_result) override final { if (max_locations_trip > 0 && (static_cast(route_parameters.coordinates.size()) > max_locations_trip)) @@ -357,7 +358,6 @@ template class RoundTripPlugin final : public BasePlugin trip.values.push_back(std::move(scc_trip)); } - if (trip.values.empty()) { json_result.values["status_message"] = "Cannot find trips"; diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index eb68f9190..b79b28833 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -49,7 +49,7 @@ template class ViaRoutePlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + osrm::json::Object &json_result) override final { if (max_locations_viaroute > 0 && (static_cast(route_parameters.coordinates.size()) > max_locations_viaroute)) diff --git a/include/engine/polyline_compressor.hpp b/include/engine/polyline_compressor.hpp index 0794c7f10..7d04b1d10 100644 --- a/include/engine/polyline_compressor.hpp +++ b/include/engine/polyline_compressor.hpp @@ -17,7 +17,7 @@ class PolylineCompressor public: std::string get_encoded_string(const std::vector &polyline) const; - + std::vector decode_string(const std::string &geometry_string) const; }; diff --git a/include/engine/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp index 443055b83..37b5a4a23 100644 --- a/include/engine/routing_algorithms/direct_shortest_path.hpp +++ b/include/engine/routing_algorithms/direct_shortest_path.hpp @@ -40,10 +40,11 @@ class DirectShortestPathRouting final // Get distance to next pair of target nodes. BOOST_ASSERT_MSG(1 == phantom_nodes_vector.size(), - "Direct Shortest Path Query only accepts a single source and target pair. Multiple ones have been specified."); - const auto& phantom_node_pair = phantom_nodes_vector.front(); - const auto& source_phantom = phantom_node_pair.source_phantom; - const auto& target_phantom = phantom_node_pair.target_phantom; + "Direct Shortest Path Query only accepts a single source and target pair. " + "Multiple ones have been specified."); + const auto &phantom_node_pair = phantom_nodes_vector.front(); + const auto &source_phantom = phantom_node_pair.source_phantom; + const auto &target_phantom = phantom_node_pair.target_phantom; engine_working_data.InitializeOrClearFirstThreadLocalStorage( super::facade->GetNumberOfNodes()); @@ -94,7 +95,6 @@ class DirectShortestPathRouting final forward_core_heap.Clear(); reverse_core_heap.Clear(); - super::SearchWithCore(forward_heap, reverse_heap, forward_core_heap, reverse_core_heap, distance, packed_leg); } @@ -120,8 +120,8 @@ class DirectShortestPathRouting final raw_route_data.target_traversed_in_reverse.push_back( (packed_leg.back() != phantom_node_pair.target_phantom.forward_node_id)); - super::UnpackPath(packed_leg.begin(), packed_leg.end(), phantom_node_pair, raw_route_data.unpacked_path_segments.front()); - + super::UnpackPath(packed_leg.begin(), packed_leg.end(), phantom_node_pair, + raw_route_data.unpacked_path_segments.front()); } }; diff --git a/include/engine/routing_algorithms/many_to_many.hpp b/include/engine/routing_algorithms/many_to_many.hpp index 9dc7a674c..fb6981892 100644 --- a/include/engine/routing_algorithms/many_to_many.hpp +++ b/include/engine/routing_algorithms/many_to_many.hpp @@ -40,7 +40,8 @@ class ManyToManyRouting final ~ManyToManyRouting() {} std::shared_ptr> - operator()(const std::vector &phantom_sources_array, const std::vector &phantom_targets_array) const + operator()(const std::vector &phantom_sources_array, + const std::vector &phantom_targets_array) const { const auto number_of_sources = phantom_sources_array.size(); const auto number_of_targets = phantom_targets_array.size(); @@ -63,14 +64,12 @@ class ManyToManyRouting final if (SPECIAL_NODEID != phantom.forward_node_id) { - query_heap.Insert(phantom.forward_node_id, - phantom.GetForwardWeightPlusOffset(), + query_heap.Insert(phantom.forward_node_id, phantom.GetForwardWeightPlusOffset(), phantom.forward_node_id); } if (SPECIAL_NODEID != phantom.reverse_node_id) { - query_heap.Insert(phantom.reverse_node_id, - phantom.GetReverseWeightPlusOffset(), + query_heap.Insert(phantom.reverse_node_id, phantom.GetReverseWeightPlusOffset(), phantom.reverse_node_id); } @@ -91,14 +90,12 @@ class ManyToManyRouting final if (SPECIAL_NODEID != phantom.forward_node_id) { - query_heap.Insert(phantom.forward_node_id, - -phantom.GetForwardWeightPlusOffset(), + query_heap.Insert(phantom.forward_node_id, -phantom.GetForwardWeightPlusOffset(), phantom.forward_node_id); } if (SPECIAL_NODEID != phantom.reverse_node_id) { - query_heap.Insert(phantom.reverse_node_id, - -phantom.GetReverseWeightPlusOffset(), + query_heap.Insert(phantom.reverse_node_id, -phantom.GetReverseWeightPlusOffset(), phantom.reverse_node_id); } diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 66a2b903c..1fec8e323 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -50,7 +50,7 @@ class MapMatching final : public BasicRoutingInterface& timestamps) const + unsigned GetMedianSampleTime(const std::vector ×tamps) const { BOOST_ASSERT(timestamps.size() > 1); @@ -60,7 +60,7 @@ class MapMatching final : public BasicRoutingInterface will not be a difference. auto first_elem = std::next(sample_times.begin()); - auto median = first_elem + std::distance(first_elem, sample_times.end())/2; + auto median = first_elem + std::distance(first_elem, sample_times.end()) / 2; std::nth_element(first_elem, median, sample_times.end()); return *median; } @@ -83,7 +83,8 @@ class MapMatching final : public BasicRoutingInterface 1; - const auto median_sample_time = [&]() { + const auto median_sample_time = [&]() + { if (use_timestamps) { return std::max(1u, GetMedianSampleTime(trace_timestamps)); @@ -94,7 +95,8 @@ class MapMatching final : public BasicRoutingInterface(0u, prev_viterbi.size())) @@ -244,7 +247,8 @@ class MapMatching final : public BasicRoutingInterface osrm::matching::SUSPICIOUS_DISTANCE_DELTA; + current_suspicious[s_prime] = + d_t > osrm::matching::SUSPICIOUS_DISTANCE_DELTA; model.breakage[t] = false; } } @@ -286,8 +290,7 @@ class MapMatching final : public BasicRoutingInterface class BasicRoutingInterface { BOOST_ASSERT(i < id_vector.size()); BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode > 0); - unpacked_path.emplace_back( - PathData{id_vector[i], - phantom_node_pair.target_phantom.name_id, - TurnInstruction::NoTurn, - 0, - phantom_node_pair.target_phantom.forward_travel_mode}); + unpacked_path.emplace_back(PathData{ + id_vector[i], phantom_node_pair.target_phantom.name_id, TurnInstruction::NoTurn, + 0, phantom_node_pair.target_phantom.forward_travel_mode}); } } @@ -498,8 +495,8 @@ template class BasicRoutingInterface // TODO check if unordered_set might be faster // sort by id and increasing by distance - auto entry_point_comparator = - [](const std::pair &lhs, const std::pair &rhs) + auto entry_point_comparator = [](const std::pair &lhs, + const std::pair &rhs) { return lhs.first < rhs.first || (lhs.first == rhs.first && lhs.second < rhs.second); }; diff --git a/include/engine/routing_algorithms/shortest_path.hpp b/include/engine/routing_algorithms/shortest_path.hpp index 6bc8fc772..a9b50afe4 100644 --- a/include/engine/routing_algorithms/shortest_path.hpp +++ b/include/engine/routing_algorithms/shortest_path.hpp @@ -86,17 +86,17 @@ class ShortestPathRouting final // | ^target // ------^ void SearchLoop(QueryHeap &forward_heap, - QueryHeap &reverse_heap, - const bool search_forward_node, - const bool search_reverse_node, - const PhantomNode &source_phantom, - const PhantomNode &target_phantom, - const int total_distance_to_forward, - const int total_distance_to_reverse, - int &new_total_distance_to_forward, - int &new_total_distance_to_reverse, - std::vector &leg_packed_path_forward, - std::vector &leg_packed_path_reverse) const + QueryHeap &reverse_heap, + const bool search_forward_node, + const bool search_reverse_node, + const PhantomNode &source_phantom, + const PhantomNode &target_phantom, + const int total_distance_to_forward, + const int total_distance_to_reverse, + int &new_total_distance_to_forward, + int &new_total_distance_to_reverse, + std::vector &leg_packed_path_forward, + std::vector &leg_packed_path_reverse) const { BOOST_ASSERT(source_phantom.forward_node_id == target_phantom.forward_node_id); BOOST_ASSERT(source_phantom.reverse_node_id == target_phantom.reverse_node_id); @@ -110,11 +110,12 @@ class ShortestPathRouting final for (const auto edge : super::facade->GetAdjacentEdgeRange(node_id)) { - const auto& data = super::facade->GetEdgeData(edge); + const auto &data = super::facade->GetEdgeData(edge); if (data.forward) { auto target = super::facade->GetTarget(edge); - auto offset = total_distance_to_forward + data.distance - source_phantom.GetForwardWeightPlusOffset(); + auto offset = total_distance_to_forward + data.distance - + source_phantom.GetForwardWeightPlusOffset(); forward_heap.Insert(target, offset, target); } @@ -147,11 +148,12 @@ class ShortestPathRouting final for (const auto edge : super::facade->GetAdjacentEdgeRange(node_id)) { - const auto& data = super::facade->GetEdgeData(edge); + const auto &data = super::facade->GetEdgeData(edge); if (data.forward) { auto target = super::facade->GetTarget(edge); - auto offset = total_distance_to_reverse + data.distance - source_phantom.GetReverseWeightPlusOffset(); + auto offset = total_distance_to_reverse + data.distance - + source_phantom.GetReverseWeightPlusOffset(); forward_heap.Insert(target, offset, target); } @@ -174,7 +176,6 @@ class ShortestPathRouting final leg_packed_path_reverse.push_back(node_id); std::reverse(leg_packed_path_reverse.begin(), leg_packed_path_reverse.end()); } - } // searches shortest path between: @@ -290,8 +291,10 @@ class ShortestPathRouting final int total_distance_to_forward = 0; int total_distance_to_reverse = 0; - bool search_from_forward_node = phantom_nodes_vector.front().source_phantom.forward_node_id != SPECIAL_NODEID; - bool search_from_reverse_node = phantom_nodes_vector.front().source_phantom.reverse_node_id != SPECIAL_NODEID; + bool search_from_forward_node = + phantom_nodes_vector.front().source_phantom.forward_node_id != SPECIAL_NODEID; + bool search_from_reverse_node = + phantom_nodes_vector.front().source_phantom.reverse_node_id != SPECIAL_NODEID; std::vector prev_packed_leg_to_forward; std::vector prev_packed_leg_to_reverse; @@ -315,30 +318,33 @@ class ShortestPathRouting final const auto &source_phantom = phantom_node_pair.source_phantom; const auto &target_phantom = phantom_node_pair.target_phantom; - BOOST_ASSERT(current_leg + 1 < uturn_indicators.size()); const bool allow_u_turn_at_via = uturn_indicators[current_leg + 1]; bool search_to_forward_node = target_phantom.forward_node_id != SPECIAL_NODEID; bool search_to_reverse_node = target_phantom.reverse_node_id != SPECIAL_NODEID; - BOOST_ASSERT(!search_from_forward_node || source_phantom.forward_node_id != SPECIAL_NODEID); - BOOST_ASSERT(!search_from_reverse_node || source_phantom.reverse_node_id != SPECIAL_NODEID); + BOOST_ASSERT(!search_from_forward_node || + source_phantom.forward_node_id != SPECIAL_NODEID); + BOOST_ASSERT(!search_from_reverse_node || + source_phantom.reverse_node_id != SPECIAL_NODEID); if (source_phantom.forward_node_id == target_phantom.forward_node_id && - source_phantom.GetForwardWeightPlusOffset() > target_phantom.GetForwardWeightPlusOffset()) + source_phantom.GetForwardWeightPlusOffset() > + target_phantom.GetForwardWeightPlusOffset()) { search_to_forward_node = search_from_reverse_node; } if (source_phantom.reverse_node_id == target_phantom.reverse_node_id && - source_phantom.GetReverseWeightPlusOffset() > target_phantom.GetReverseWeightPlusOffset()) + source_phantom.GetReverseWeightPlusOffset() > + target_phantom.GetReverseWeightPlusOffset()) { search_to_reverse_node = search_from_forward_node; } BOOST_ASSERT(search_from_forward_node || search_from_reverse_node); - if(search_to_reverse_node || search_to_forward_node) + if (search_to_reverse_node || search_to_forward_node) { if (allow_u_turn_at_via) { @@ -347,7 +353,8 @@ class ShortestPathRouting final search_to_reverse_node, source_phantom, target_phantom, total_distance_to_forward, total_distance_to_reverse, new_total_distance_to_forward, packed_leg_to_forward); - // if only the reverse node is valid (e.g. when using the match plugin) we actually need to move + // if only the reverse node is valid (e.g. when using the match plugin) we + // actually need to move if (target_phantom.forward_node_id == SPECIAL_NODEID) { BOOST_ASSERT(target_phantom.reverse_node_id != SPECIAL_NODEID); @@ -367,7 +374,8 @@ class ShortestPathRouting final search_from_reverse_node, search_to_forward_node, search_to_reverse_node, source_phantom, target_phantom, total_distance_to_forward, total_distance_to_reverse, new_total_distance_to_forward, - new_total_distance_to_reverse, packed_leg_to_forward, packed_leg_to_reverse); + new_total_distance_to_reverse, packed_leg_to_forward, + packed_leg_to_reverse); } } else @@ -377,9 +385,10 @@ class ShortestPathRouting final BOOST_ASSERT(search_from_reverse_node == search_to_reverse_node); BOOST_ASSERT(search_from_forward_node == search_to_forward_node); SearchLoop(forward_heap, reverse_heap, search_from_forward_node, - search_from_reverse_node, source_phantom, target_phantom, total_distance_to_forward, - total_distance_to_reverse, new_total_distance_to_forward, - new_total_distance_to_reverse, packed_leg_to_forward, packed_leg_to_reverse); + search_from_reverse_node, source_phantom, target_phantom, + total_distance_to_forward, total_distance_to_reverse, + new_total_distance_to_forward, new_total_distance_to_reverse, + packed_leg_to_forward, packed_leg_to_reverse); } // No path found for both target nodes? diff --git a/include/engine/search_engine.hpp b/include/engine/search_engine.hpp index e705faa96..aec2a735a 100644 --- a/include/engine/search_engine.hpp +++ b/include/engine/search_engine.hpp @@ -24,12 +24,10 @@ template class SearchEngine MapMatching map_matching; explicit SearchEngine(DataFacadeT *facade) - : facade(facade), - shortest_path(facade, engine_working_data), + : facade(facade), shortest_path(facade, engine_working_data), direct_shortest_path(facade, engine_working_data), alternative_path(facade, engine_working_data), - distance_table(facade, engine_working_data), - map_matching(facade, engine_working_data) + distance_table(facade, engine_working_data), map_matching(facade, engine_working_data) { static_assert(!std::is_pointer::value, "don't instantiate with ptr type"); static_assert(std::is_object::value, diff --git a/include/engine/segment_information.hpp b/include/engine/segment_information.hpp index 880a58cb2..eaedec78d 100644 --- a/include/engine/segment_information.hpp +++ b/include/engine/segment_information.hpp @@ -32,8 +32,8 @@ struct SegmentInformation const bool is_via_location, const TravelMode travel_mode) : location(std::move(location)), name_id(name_id), duration(duration), length(length), - pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), travel_mode(travel_mode), - necessary(necessary), is_via_location(is_via_location) + pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), + travel_mode(travel_mode), necessary(necessary), is_via_location(is_via_location) { } @@ -44,8 +44,9 @@ struct SegmentInformation const TurnInstruction turn_instruction, const TravelMode travel_mode) : location(std::move(location)), name_id(name_id), duration(duration), length(length), - pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), travel_mode(travel_mode), - necessary(turn_instruction != TurnInstruction::NoTurn), is_via_location(false) + pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), + travel_mode(travel_mode), necessary(turn_instruction != TurnInstruction::NoTurn), + is_via_location(false) { } }; diff --git a/include/extractor/compressed_edge_container.hpp b/include/extractor/compressed_edge_container.hpp index 4459f373b..cfac68eff 100644 --- a/include/extractor/compressed_edge_container.hpp +++ b/include/extractor/compressed_edge_container.hpp @@ -26,7 +26,7 @@ class CompressedEdgeContainer void PrintStatistics() const; void SerializeInternalVector(const std::string &path) const; unsigned GetPositionForID(const EdgeID edge_id) const; - const EdgeBucket& GetBucketReference(const EdgeID edge_id) const; + const EdgeBucket &GetBucketReference(const EdgeID edge_id) const; NodeID GetFirstEdgeTargetID(const EdgeID edge_id) const; NodeID GetLastEdgeSourceID(const EdgeID edge_id) const; diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 9a1b8ee40..5a2b259f2 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -63,27 +63,29 @@ class EdgeBasedGraphFactory unsigned GetHighestEdgeID(); - TurnInstruction AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w, const double angle) const; + TurnInstruction + AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w, const double angle) const; int GetTurnPenalty(double angle, lua_State *lua_state) const; private: using EdgeData = NodeBasedDynamicGraph::EdgeData; - //! maps index from m_edge_based_node_list to ture/false if the node is an entry point to the graph + //! maps index from m_edge_based_node_list to ture/false if the node is an entry point to the + //! graph std::vector m_edge_based_node_is_startpoint; //! list of edge based nodes (compressed segments) std::vector m_edge_based_node_list; DeallocatingVector m_edge_based_edge_list; unsigned m_max_edge_id; - const std::vector& m_node_info_list; + const std::vector &m_node_info_list; std::shared_ptr m_node_based_graph; std::shared_ptr m_restriction_map; - const std::unordered_set& m_barrier_nodes; - const std::unordered_set& m_traffic_lights; - const CompressedEdgeContainer& m_compressed_edge_container; + const std::unordered_set &m_barrier_nodes; + const std::unordered_set &m_traffic_lights; + const CompressedEdgeContainer &m_compressed_edge_container; SpeedProfileProperties speed_profile; @@ -103,13 +105,12 @@ class EdgeBasedGraphFactory const std::string &edge_segment_lookup_filename, const std::string &edge_fixed_penalties_filename, const bool generate_edge_lookup); -#endif +#endif void InsertEdgeBasedNode(const NodeID u, const NodeID v); void FlushVectorToStream(std::ofstream &edge_data_file, std::vector &original_edge_data_vector) const; - }; #endif /* EDGE_BASED_GRAPH_FACTORY_HPP_ */ diff --git a/include/extractor/edge_based_node.hpp b/include/extractor/edge_based_node.hpp index 41b836e19..3ea715a89 100644 --- a/include/extractor/edge_based_node.hpp +++ b/include/extractor/edge_based_node.hpp @@ -19,7 +19,8 @@ struct EdgeBasedNode u(SPECIAL_NODEID), v(SPECIAL_NODEID), name_id(0), forward_weight(INVALID_EDGE_WEIGHT >> 1), reverse_weight(INVALID_EDGE_WEIGHT >> 1), forward_offset(0), reverse_offset(0), packed_geometry_id(SPECIAL_EDGEID), - component{INVALID_COMPONENTID, false}, fwd_segment_position(std::numeric_limits::max()), + component{INVALID_COMPONENTID, false}, + fwd_segment_position(std::numeric_limits::max()), forward_travel_mode(TRAVEL_MODE_INACCESSIBLE), backward_travel_mode(TRAVEL_MODE_INACCESSIBLE) { @@ -74,7 +75,8 @@ struct EdgeBasedNode int forward_offset; // prefix sum of the weight up the edge TODO: short must suffice int reverse_offset; // prefix sum of the weight from the edge TODO: short must suffice unsigned packed_geometry_id; // if set, then the edge represents a packed geometry - struct { + struct + { unsigned id : 31; bool is_tiny : 1; } component; diff --git a/include/extractor/extraction_containers.hpp b/include/extractor/extraction_containers.hpp index b1e9b4bf0..83a8978f5 100644 --- a/include/extractor/extraction_containers.hpp +++ b/include/extractor/extraction_containers.hpp @@ -29,10 +29,11 @@ class ExtractionContainers void PrepareRestrictions(); void PrepareEdges(lua_State *segment_state); - void WriteNodes(std::ofstream& file_out_stream) const; - void WriteRestrictions(const std::string& restrictions_file_name) const; - void WriteEdges(std::ofstream& file_out_stream) const; - void WriteNames(const std::string& names_file_name) const; + void WriteNodes(std::ofstream &file_out_stream) const; + void WriteRestrictions(const std::string &restrictions_file_name) const; + void WriteEdges(std::ofstream &file_out_stream) const; + void WriteNames(const std::string &names_file_name) const; + public: using STXXLNodeIDVector = stxxl::vector; using STXXLNodeVector = stxxl::vector; diff --git a/include/extractor/first_and_last_segment_of_way.hpp b/include/extractor/first_and_last_segment_of_way.hpp index 37685d3c8..fa5b5b65c 100644 --- a/include/extractor/first_and_last_segment_of_way.hpp +++ b/include/extractor/first_and_last_segment_of_way.hpp @@ -16,10 +16,8 @@ struct FirstAndLastSegmentOfWay OSMNodeID last_segment_target_id; FirstAndLastSegmentOfWay() - : way_id(SPECIAL_OSM_WAYID), - first_segment_source_id(SPECIAL_OSM_NODEID), - first_segment_target_id(SPECIAL_OSM_NODEID), - last_segment_source_id(SPECIAL_OSM_NODEID), + : way_id(SPECIAL_OSM_WAYID), first_segment_source_id(SPECIAL_OSM_NODEID), + first_segment_target_id(SPECIAL_OSM_NODEID), last_segment_source_id(SPECIAL_OSM_NODEID), last_segment_target_id(SPECIAL_OSM_NODEID) { } @@ -32,19 +30,11 @@ struct FirstAndLastSegmentOfWay static FirstAndLastSegmentOfWay min_value() { - return {MIN_OSM_WAYID, - MIN_OSM_NODEID, - MIN_OSM_NODEID, - MIN_OSM_NODEID, - MIN_OSM_NODEID}; + return {MIN_OSM_WAYID, MIN_OSM_NODEID, MIN_OSM_NODEID, MIN_OSM_NODEID, MIN_OSM_NODEID}; } static FirstAndLastSegmentOfWay max_value() { - return {MAX_OSM_WAYID, - MAX_OSM_NODEID, - MAX_OSM_NODEID, - MAX_OSM_NODEID, - MAX_OSM_NODEID}; + return {MAX_OSM_WAYID, MAX_OSM_NODEID, MAX_OSM_NODEID, MAX_OSM_NODEID, MAX_OSM_NODEID}; } }; diff --git a/include/extractor/graph_compressor.hpp b/include/extractor/graph_compressor.hpp index 50a86a184..7b9cd5a73 100644 --- a/include/extractor/graph_compressor.hpp +++ b/include/extractor/graph_compressor.hpp @@ -16,19 +16,19 @@ class GraphCompressor { using EdgeData = NodeBasedDynamicGraph::EdgeData; -public: - GraphCompressor(SpeedProfileProperties speed_profile); + public: + GraphCompressor(SpeedProfileProperties speed_profile); - void Compress(const std::unordered_set& barrier_nodes, - const std::unordered_set& traffic_lights, - RestrictionMap& restriction_map, - NodeBasedDynamicGraph& graph, - CompressedEdgeContainer& geometry_compressor); -private: + void Compress(const std::unordered_set &barrier_nodes, + const std::unordered_set &traffic_lights, + RestrictionMap &restriction_map, + NodeBasedDynamicGraph &graph, + CompressedEdgeContainer &geometry_compressor); - void PrintStatistics(unsigned original_number_of_nodes, - unsigned original_number_of_edges, - const NodeBasedDynamicGraph& graph) const; + private: + void PrintStatistics(unsigned original_number_of_nodes, + unsigned original_number_of_edges, + const NodeBasedDynamicGraph &graph) const; SpeedProfileProperties speed_profile; }; diff --git a/include/extractor/import_edge.hpp b/include/extractor/import_edge.hpp index 996f2371a..9fe4a8b50 100644 --- a/include/extractor/import_edge.hpp +++ b/include/extractor/import_edge.hpp @@ -37,18 +37,30 @@ struct NodeBasedEdge struct NodeBasedEdgeWithOSM : NodeBasedEdge { explicit NodeBasedEdgeWithOSM(OSMNodeID source, - OSMNodeID target, - NodeID name_id, - EdgeWeight weight, - bool forward, - bool backward, - bool roundabout, - bool access_restricted, - bool startpoint, - TravelMode travel_mode, - bool is_split) - : NodeBasedEdge(SPECIAL_NODEID, SPECIAL_NODEID, name_id, weight, forward, backward, roundabout, access_restricted, startpoint, travel_mode, is_split), - osm_source_id(source), osm_target_id(target) {} + OSMNodeID target, + NodeID name_id, + EdgeWeight weight, + bool forward, + bool backward, + bool roundabout, + bool access_restricted, + bool startpoint, + TravelMode travel_mode, + bool is_split) + : NodeBasedEdge(SPECIAL_NODEID, + SPECIAL_NODEID, + name_id, + weight, + forward, + backward, + roundabout, + access_restricted, + startpoint, + travel_mode, + is_split), + osm_source_id(source), osm_target_id(target) + { + } OSMNodeID osm_source_id; OSMNodeID osm_target_id; diff --git a/include/extractor/internal_extractor_edge.hpp b/include/extractor/internal_extractor_edge.hpp index 6c13950e7..b5c8e031a 100644 --- a/include/extractor/internal_extractor_edge.hpp +++ b/include/extractor/internal_extractor_edge.hpp @@ -13,7 +13,8 @@ struct InternalExtractorEdge { // specify the type of the weight data - enum class WeightType : char { + enum class WeightType : char + { INVALID, SPEED, EDGE_DURATION, @@ -23,9 +24,7 @@ struct InternalExtractorEdge struct WeightData { - WeightData() : duration(0.0), type(WeightType::INVALID) - { - } + WeightData() : duration(0.0), type(WeightType::INVALID) {} union { @@ -36,8 +35,17 @@ struct InternalExtractorEdge }; explicit InternalExtractorEdge() - : result(MIN_OSM_NODEID, MIN_OSM_NODEID, 0, 0, false, false, false, false, true, - TRAVEL_MODE_INACCESSIBLE, false) + : result(MIN_OSM_NODEID, + MIN_OSM_NODEID, + 0, + 0, + false, + false, + false, + false, + true, + TRAVEL_MODE_INACCESSIBLE, + false) { } @@ -74,17 +82,16 @@ struct InternalExtractorEdge // coordinate of the source node FixedPointCoordinate source_coordinate; - // necessary static util functions for stxxl's sorting static InternalExtractorEdge min_osm_value() { - return InternalExtractorEdge(MIN_OSM_NODEID, MIN_OSM_NODEID, 0, WeightData(), false, false, false, - false, true, TRAVEL_MODE_INACCESSIBLE, false); + return InternalExtractorEdge(MIN_OSM_NODEID, MIN_OSM_NODEID, 0, WeightData(), false, false, + false, false, true, TRAVEL_MODE_INACCESSIBLE, false); } static InternalExtractorEdge max_osm_value() { - return InternalExtractorEdge(MAX_OSM_NODEID, MAX_OSM_NODEID, 0, WeightData(), false, - false, false, false, true, TRAVEL_MODE_INACCESSIBLE, false); + return InternalExtractorEdge(MAX_OSM_NODEID, MAX_OSM_NODEID, 0, WeightData(), false, false, + false, false, true, TRAVEL_MODE_INACCESSIBLE, false); } static InternalExtractorEdge min_internal_value() @@ -101,7 +108,6 @@ struct InternalExtractorEdge v.result.target = std::numeric_limits::max(); return v; } - }; struct CmpEdgeByInternalStartThenInternalTargetID @@ -109,9 +115,9 @@ struct CmpEdgeByInternalStartThenInternalTargetID using value_type = InternalExtractorEdge; bool operator()(const InternalExtractorEdge &lhs, const InternalExtractorEdge &rhs) const { - return (lhs.result.source < rhs.result.source) || - ((lhs.result.source == rhs.result.source) && - (lhs.result.target < rhs.result.target)); + return (lhs.result.source < rhs.result.source) || + ((lhs.result.source == rhs.result.source) && + (lhs.result.target < rhs.result.target)); } value_type max_value() { return InternalExtractorEdge::max_internal_value(); } diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index a4a912026..b32d92d64 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -12,9 +12,11 @@ struct QueryNode { using key_type = OSMNodeID; // type of NodeID - using value_type = int; // type of lat,lons + using value_type = int; // type of lat,lons - explicit QueryNode(int lat, int lon, OSMNodeID node_id) : lat(lat), lon(lon), node_id(node_id) {} + explicit QueryNode(int lat, int lon, OSMNodeID node_id) : lat(lat), lon(lon), node_id(node_id) + { + } QueryNode() : lat(std::numeric_limits::max()), lon(std::numeric_limits::max()), node_id(SPECIAL_OSM_NODEID) @@ -28,15 +30,13 @@ struct QueryNode static QueryNode min_value() { return QueryNode(static_cast(-90 * COORDINATE_PRECISION), - static_cast(-180 * COORDINATE_PRECISION), - MIN_OSM_NODEID); + static_cast(-180 * COORDINATE_PRECISION), MIN_OSM_NODEID); } static QueryNode max_value() { return QueryNode(static_cast(90 * COORDINATE_PRECISION), - static_cast(180 * COORDINATE_PRECISION), - MAX_OSM_NODEID); + static_cast(180 * COORDINATE_PRECISION), MAX_OSM_NODEID); } value_type operator[](const std::size_t n) const diff --git a/include/extractor/restriction.hpp b/include/extractor/restriction.hpp index a64818b55..5b22691dd 100644 --- a/include/extractor/restriction.hpp +++ b/include/extractor/restriction.hpp @@ -52,7 +52,7 @@ struct TurnRestriction /** * This is just a wrapper around TurnRestriction used in the extractor. - * + * * Could be merged with TurnRestriction. For now the type-destiction makes sense * as the format in which the restriction is presented in the extractor and in the * preprocessing is different. (see restriction_parser.cpp) diff --git a/include/extractor/restriction_map.hpp b/include/extractor/restriction_map.hpp index 5255c5e14..81c9d425a 100644 --- a/include/extractor/restriction_map.hpp +++ b/include/extractor/restriction_map.hpp @@ -64,7 +64,7 @@ template <> struct hash class RestrictionMap { public: - RestrictionMap() : m_count(0) {}; + RestrictionMap() : m_count(0){}; RestrictionMap(const std::vector &restriction_list); // Replace end v with w in each turn restriction containing u as via node diff --git a/include/extractor/speed_profile.hpp b/include/extractor/speed_profile.hpp index 534ccce34..ec8ecd6d4 100644 --- a/include/extractor/speed_profile.hpp +++ b/include/extractor/speed_profile.hpp @@ -3,14 +3,14 @@ struct SpeedProfileProperties { - SpeedProfileProperties() - : traffic_signal_penalty(0), u_turn_penalty(0), has_turn_penalty_function(false) - { - } + SpeedProfileProperties() + : traffic_signal_penalty(0), u_turn_penalty(0), has_turn_penalty_function(false) + { + } - int traffic_signal_penalty; - int u_turn_penalty; - bool has_turn_penalty_function; + int traffic_signal_penalty; + int u_turn_penalty; + bool has_turn_penalty_function; }; #endif diff --git a/include/osrm/route_parameters.hpp b/include/osrm/route_parameters.hpp index 474fa03b2..7b72f0334 100644 --- a/include/osrm/route_parameters.hpp +++ b/include/osrm/route_parameters.hpp @@ -72,7 +72,9 @@ struct RouteParameters void addTimestamp(const unsigned timestamp); - void addBearing(const boost::fusion::vector> &received_bearing, boost::spirit::qi::unused_type unused, bool& pass); + void addBearing(const boost::fusion::vector> &received_bearing, + boost::spirit::qi::unused_type unused, + bool &pass); void setLanguage(const std::string &language); @@ -106,7 +108,7 @@ struct RouteParameters std::string language; std::vector hints; std::vector timestamps; - std::vector>> bearings; + std::vector>> bearings; std::vector uturns; std::vector coordinates; std::vector is_destination; diff --git a/include/osrm/strong_typedef.hpp b/include/osrm/strong_typedef.hpp index 2d535f9aa..7acc78509 100644 --- a/include/osrm/strong_typedef.hpp +++ b/include/osrm/strong_typedef.hpp @@ -36,33 +36,34 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * etc. Also clarifies what this random "int" value is * being used for. */ -#define OSRM_STRONG_TYPEDEF(From, To) \ - class To final { \ - static_assert(std::is_arithmetic(), ""); \ - From x; \ - \ - public: \ - To() = default; \ - explicit To(const From x_) : x(x_) {} \ - explicit operator From&() { return x; } \ - explicit operator const From&() const { return x; } \ - bool operator <(const To &z_) const { return x < static_cast(z_) ; } \ - bool operator >(const To &z_) const { return x > static_cast(z_) ; } \ - bool operator <=(const To &z_) const { return x <= static_cast(z_) ; } \ - bool operator >=(const To &z_) const { return x >= static_cast(z_) ; } \ - bool operator ==(const To &z_) const { return x == static_cast(z_) ; } \ - bool operator !=(const To &z_) const { return x != static_cast(z_) ; } \ - }; \ - inline From To##_to_##From(To to) { return static_cast(to); } \ - namespace std { \ - template <> \ - struct hash \ - { \ - std::size_t operator()(const To& k) const \ - { \ - return std::hash()(static_cast(k)); \ - } \ - }; \ - } +#define OSRM_STRONG_TYPEDEF(From, To) \ + class To final \ + { \ + static_assert(std::is_arithmetic(), ""); \ + From x; \ + \ + public: \ + To() = default; \ + explicit To(const From x_) : x(x_) {} \ + explicit operator From &() { return x; } \ + explicit operator const From &() const { return x; } \ + bool operator<(const To &z_) const { return x < static_cast(z_); } \ + bool operator>(const To &z_) const { return x > static_cast(z_); } \ + bool operator<=(const To &z_) const { return x <= static_cast(z_); } \ + bool operator>=(const To &z_) const { return x >= static_cast(z_); } \ + bool operator==(const To &z_) const { return x == static_cast(z_); } \ + bool operator!=(const To &z_) const { return x != static_cast(z_); } \ + }; \ + inline From To##_to_##From(To to) { return static_cast(to); } \ + namespace std \ + { \ + template <> struct hash \ + { \ + std::size_t operator()(const To &k) const \ + { \ + return std::hash()(static_cast(k)); \ + } \ + }; \ + } #endif // OSRM_STRONG_TYPEDEF_HPP diff --git a/include/server/api_grammar.hpp b/include/server/api_grammar.hpp index d8a2e257b..d7b7875fd 100644 --- a/include/server/api_grammar.hpp +++ b/include/server/api_grammar.hpp @@ -11,19 +11,21 @@ template struct APIGrammar : qi::grammar> string[boost::bind(&HandlerT::setService, handler, ::_1)] >> - -query; - query = ('?') >> +(zoom | output | jsonp | checksum | uturns | location_with_options | destination_with_options | source_with_options | cmp | - language | instruction | geometry | alt_route | old_API | num_results | - matching_beta | gps_precision | classify | locs); + api_call = + qi::lit('/') >> string[boost::bind(&HandlerT::setService, handler, ::_1)] >> -query; + query = ('?') >> +(zoom | output | jsonp | checksum | uturns | location_with_options | + destination_with_options | source_with_options | cmp | language | + instruction | geometry | alt_route | old_API | num_results | + matching_beta | gps_precision | classify | locs); // all combinations of timestamp, uturn, hint and bearing without duplicates t_u = (u >> -timestamp) | (timestamp >> -u); t_h = (hint >> -timestamp) | (timestamp >> -hint); u_h = (u >> -hint) | (hint >> -u); t_u_h = (hint >> -t_u) | (u >> -t_h) | (timestamp >> -u_h); - location_options = (bearing >> -t_u_h) | (t_u_h >> -bearing) | // - (u >> bearing >> -t_h) | (timestamp >> bearing >> -u_h) | (hint >> bearing >> t_u) | // - (t_h >> bearing >> -u) | (u_h >> bearing >> -timestamp) | (t_u >> bearing >> -hint); + location_options = + (bearing >> -t_u_h) | (t_u_h >> -bearing) | // + (u >> bearing >> -t_h) | (timestamp >> bearing >> -u_h) | (hint >> bearing >> t_u) | // + (t_h >> bearing >> -u) | (u_h >> bearing >> -timestamp) | (t_u >> bearing >> -hint); location_with_options = location >> -location_options; source_with_options = source >> -location_options; destination_with_options = destination >> -location_options; @@ -45,17 +47,19 @@ template struct APIGrammar : qi::grammar> qi::lit(',') >> qi::double_)[boost::bind(&HandlerT::addCoordinate, handler, ::_1)]; destination = (-qi::lit('&')) >> qi::lit("dst") >> '=' >> - (qi::double_ >> qi::lit(',') >> - qi::double_)[boost::bind(&HandlerT::addDestination, handler, ::_1)]; + (qi::double_ >> qi::lit(',') >> + qi::double_)[boost::bind(&HandlerT::addDestination, handler, ::_1)]; source = (-qi::lit('&')) >> qi::lit("src") >> '=' >> - (qi::double_ >> qi::lit(',') >> - qi::double_)[boost::bind(&HandlerT::addSource, handler, ::_1)]; + (qi::double_ >> qi::lit(',') >> + qi::double_)[boost::bind(&HandlerT::addSource, handler, ::_1)]; hint = (-qi::lit('&')) >> qi::lit("hint") >> '=' >> stringwithDot[boost::bind(&HandlerT::addHint, handler, ::_1)]; timestamp = (-qi::lit('&')) >> qi::lit("t") >> '=' >> - qi::uint_[boost::bind(&HandlerT::addTimestamp, handler, ::_1)]; + qi::uint_[boost::bind(&HandlerT::addTimestamp, handler, ::_1)]; bearing = (-qi::lit('&')) >> qi::lit("b") >> '=' >> - (qi::int_ >> -(qi::lit(',') >> qi::int_ | qi::attr(10)))[boost::bind(&HandlerT::addBearing, handler, ::_1, ::_2, ::_3)]; + (qi::int_ >> + -(qi::lit(',') >> qi::int_ | + qi::attr(10)))[boost::bind(&HandlerT::addBearing, handler, ::_1, ::_2, ::_3)]; u = (-qi::lit('&')) >> qi::lit("u") >> '=' >> qi::bool_[boost::bind(&HandlerT::setUTurn, handler, ::_1)]; uturns = (-qi::lit('&')) >> qi::lit("uturns") >> '=' >> @@ -69,13 +73,13 @@ template struct APIGrammar : qi::grammar> qi::lit("num_results") >> '=' >> qi::short_[boost::bind(&HandlerT::setNumberOfResults, handler, ::_1)]; matching_beta = (-qi::lit('&')) >> qi::lit("matching_beta") >> '=' >> - qi::float_[boost::bind(&HandlerT::setMatchingBeta, handler, ::_1)]; + qi::float_[boost::bind(&HandlerT::setMatchingBeta, handler, ::_1)]; gps_precision = (-qi::lit('&')) >> qi::lit("gps_precision") >> '=' >> - qi::float_[boost::bind(&HandlerT::setGPSPrecision, handler, ::_1)]; + qi::float_[boost::bind(&HandlerT::setGPSPrecision, handler, ::_1)]; classify = (-qi::lit('&')) >> qi::lit("classify") >> '=' >> - qi::bool_[boost::bind(&HandlerT::setClassify, handler, ::_1)]; + qi::bool_[boost::bind(&HandlerT::setClassify, handler, ::_1)]; locs = (-qi::lit('&')) >> qi::lit("locs") >> '=' >> - stringforPolyline[boost::bind(&HandlerT::getCoordinatesFromGeometry, handler, ::_1)]; + stringforPolyline[boost::bind(&HandlerT::getCoordinatesFromGeometry, handler, ::_1)]; string = +(qi::char_("a-zA-Z")); stringwithDot = +(qi::char_("a-zA-Z0-9_.-")); @@ -84,10 +88,12 @@ template struct APIGrammar : qi::grammar api_call, query, location_options, location_with_options, destination_with_options, source_with_options, t_u, t_h, u_h, t_u_h; - qi::rule service, zoom, output, string, jsonp, checksum, location, destination, source, - hint, timestamp, bearing, stringwithDot, stringwithPercent, language, geometry, cmp, alt_route, u, - uturns, old_API, num_results, matching_beta, gps_precision, classify, locs, instruction, stringforPolyline; + qi::rule api_call, query, location_options, location_with_options, + destination_with_options, source_with_options, t_u, t_h, u_h, t_u_h; + qi::rule service, zoom, output, string, jsonp, checksum, location, + destination, source, hint, timestamp, bearing, stringwithDot, stringwithPercent, language, + geometry, cmp, alt_route, u, uturns, old_API, num_results, matching_beta, gps_precision, + classify, locs, instruction, stringforPolyline; HandlerT *handler; }; diff --git a/include/util/binary_heap.hpp b/include/util/binary_heap.hpp index 0cd00fe22..4b2ba07a2 100644 --- a/include/util/binary_heap.hpp +++ b/include/util/binary_heap.hpp @@ -162,9 +162,10 @@ class BinaryHeap return inserted_nodes[heap[1].index].node; } - Weight MinKey() const { - BOOST_ASSERT(heap.size() > 1); - return heap[1].weight; + Weight MinKey() const + { + BOOST_ASSERT(heap.size() > 1); + return heap[1].weight; } NodeID DeleteMin() diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index d8580d77e..dc4092005 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -8,48 +8,47 @@ struct FixedPointCoordinate; namespace coordinate_calculation { - double - haversine_distance(const int lat1, const int lon1, const int lat2, const int lon2); +double haversine_distance(const int lat1, const int lon1, const int lat2, const int lon2); - double haversine_distance(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate); +double haversine_distance(const FixedPointCoordinate &first_coordinate, + const FixedPointCoordinate &second_coordinate); - double great_circle_distance(const FixedPointCoordinate &first_coordinate, +double great_circle_distance(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); - double great_circle_distance(const int lat1, const int lon1, const int lat2, const int lon2); +double great_circle_distance(const int lat1, const int lon1, const int lat2, const int lon2); - void lat_or_lon_to_string(const int value, std::string &output); +void lat_or_lon_to_string(const int value, std::string &output); - double perpendicular_distance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location); +double perpendicular_distance(const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location); - double perpendicular_distance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - FixedPointCoordinate &nearest_location, - double &ratio); +double perpendicular_distance(const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + FixedPointCoordinate &nearest_location, + double &ratio); - double perpendicular_distance_from_projected_coordinate( - const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate); +double perpendicular_distance_from_projected_coordinate( + const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + const std::pair &projected_coordinate); - double perpendicular_distance_from_projected_coordinate( - const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate, - FixedPointCoordinate &nearest_location, - double &ratio); +double perpendicular_distance_from_projected_coordinate( + const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + const std::pair &projected_coordinate, + FixedPointCoordinate &nearest_location, + double &ratio); - double deg_to_rad(const double degree); - double rad_to_deg(const double radian); +double deg_to_rad(const double degree); +double rad_to_deg(const double radian); - double bearing(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate); +double bearing(const FixedPointCoordinate &first_coordinate, + const FixedPointCoordinate &second_coordinate); } #endif // COORDINATE_CALCULATION diff --git a/include/util/datastore_options.hpp b/include/util/datastore_options.hpp index dc2678404..8426fa13b 100644 --- a/include/util/datastore_options.hpp +++ b/include/util/datastore_options.hpp @@ -14,7 +14,9 @@ #include // generate boost::program_options object for the routing part -bool GenerateDataStoreOptions(const int argc, const char *argv[], std::unordered_map &paths) +bool GenerateDataStoreOptions(const int argc, + const char *argv[], + std::unordered_map &paths) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); diff --git a/include/util/deallocating_vector.hpp b/include/util/deallocating_vector.hpp index c6bcb08b8..a486db371 100644 --- a/include/util/deallocating_vector.hpp +++ b/include/util/deallocating_vector.hpp @@ -20,14 +20,15 @@ template struct ConstDeallocatingVectorIteratorState { } explicit ConstDeallocatingVectorIteratorState(const std::size_t idx, - const std::vector *input_list) + const std::vector *input_list) : index(idx), bucket_list(input_list) { } std::size_t index; const std::vector *bucket_list; - ConstDeallocatingVectorIteratorState &operator=(const ConstDeallocatingVectorIteratorState &other) + ConstDeallocatingVectorIteratorState & + operator=(const ConstDeallocatingVectorIteratorState &other) { index = other.index; bucket_list = other.bucket_list; @@ -210,11 +211,10 @@ class DeallocatingVectorRemoveIterator } }; -template -class DeallocatingVector; +template class DeallocatingVector; -template -void swap(DeallocatingVector& lhs, DeallocatingVector& rhs); +template +void swap(DeallocatingVector &lhs, DeallocatingVector &rhs); template class DeallocatingVector @@ -236,7 +236,8 @@ class DeallocatingVector ~DeallocatingVector() { clear(); } - friend void swap<>(DeallocatingVector& lhs, DeallocatingVector& rhs); + friend void swap<>(DeallocatingVector &lhs, + DeallocatingVector &rhs); void swap(DeallocatingVector &other) { @@ -367,8 +368,8 @@ class DeallocatingVector } }; -template -void swap(DeallocatingVector& lhs, DeallocatingVector& rhs) +template +void swap(DeallocatingVector &lhs, DeallocatingVector &rhs) { lhs.swap(rhs); } diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index a0c1bfd42..d4cd06871 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -7,18 +7,32 @@ #ifndef DEBUG_GEOMETRY inline void DEBUG_GEOMETRY_START(ContractorConfig & /* config */) {} -inline void DEBUG_GEOMETRY_EDGE(int /* new_segment_weight */ , double /* segment_length */, - OSMNodeID /* previous_osm_node_id */, OSMNodeID /* this_osm_node_id */) {} +inline void DEBUG_GEOMETRY_EDGE(int /* new_segment_weight */, + double /* segment_length */, + OSMNodeID /* previous_osm_node_id */, + OSMNodeID /* this_osm_node_id */) +{ +} inline void DEBUG_GEOMETRY_STOP() {} inline void DEBUG_TURNS_START(const std::string & /* debug_turns_filename */) {} -inline void DEBUG_TURN( const NodeID /* node */, const std::vector& /* m_node_info_list */, - const FixedPointCoordinate & /* first_coordinate */, const int /* turn_angle */, - const int /* turn_penalty */) {} -inline void DEBUG_UTURN( const NodeID /* node */, const std::vector& /* m_node_info_list */, - const int /* uturn_penalty */ ) {} -inline void DEBUG_SIGNAL( const NodeID /* node */, const std::vector& /* m_node_info_list */, - const int /* signal_penalty */ ) {} +inline void DEBUG_TURN(const NodeID /* node */, + const std::vector & /* m_node_info_list */, + const FixedPointCoordinate & /* first_coordinate */, + const int /* turn_angle */, + const int /* turn_penalty */) +{ +} +inline void DEBUG_UTURN(const NodeID /* node */, + const std::vector & /* m_node_info_list */, + const int /* uturn_penalty */) +{ +} +inline void DEBUG_SIGNAL(const NodeID /* node */, + const std::vector & /* m_node_info_list */, + const int /* signal_penalty */) +{ +} inline void DEBUG_TURNS_STOP() {} @@ -59,26 +73,27 @@ inline void DEBUG_GEOMETRY_START(const ContractorConfig &config) } } -inline void DEBUG_GEOMETRY_EDGE(int new_segment_weight, double segment_length, OSMNodeID previous_osm_node_id, OSMNodeID this_osm_node_id) +inline void DEBUG_GEOMETRY_EDGE(int new_segment_weight, + double segment_length, + OSMNodeID previous_osm_node_id, + OSMNodeID this_osm_node_id) { if (dg_output_debug_geometry) { if (!dg_first_debug_geometry) debug_geometry_file << "," << std::endl; - debug_geometry_file - << "{ \"type\":\"Feature\",\"properties\":{\"original\":false, " - "\"weight\":" - << new_segment_weight / 10.0 << ",\"speed\":" - << static_cast( - std::floor((segment_length / new_segment_weight) * 10. * 3.6)) - << ","; + debug_geometry_file << "{ \"type\":\"Feature\",\"properties\":{\"original\":false, " + "\"weight\":" + << new_segment_weight / 10.0 << ",\"speed\":" + << static_cast( + std::floor((segment_length / new_segment_weight) * 10. * 3.6)) + << ","; debug_geometry_file << "\"from_node\": " << previous_osm_node_id << ", \"to_node\": " << this_osm_node_id << ","; debug_geometry_file << "\"timestamp\": \"" << dg_time_buffer << "\"},"; - debug_geometry_file - << "\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[!!" - << previous_osm_node_id << "!!],[!!" << this_osm_node_id << "!!]]}}" - << std::endl; + debug_geometry_file << "\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[!!" + << previous_osm_node_id << "!!],[!!" << this_osm_node_id << "!!]]}}" + << std::endl; dg_first_debug_geometry = false; } } @@ -92,66 +107,80 @@ inline void DEBUG_GEOMETRY_STOP() } } - -inline void DEBUG_TURNS_START(const std::string & debug_turns_path) -{ +inline void DEBUG_TURNS_START(const std::string &debug_turns_path) +{ dg_output_turn_debug = debug_turns_path != ""; - if (dg_output_turn_debug) + if (dg_output_turn_debug) { dg_debug_turns_file.open(debug_turns_path); dg_debug_turns_file << "{\"type\":\"FeatureCollection\", \"features\":[" << std::endl; } -} +} -inline void DEBUG_SIGNAL( - const NodeID node, - const std::vector& m_node_info_list, - const int traffic_signal_penalty) +inline void DEBUG_SIGNAL(const NodeID node, + const std::vector &m_node_info_list, + const int traffic_signal_penalty) { if (dg_output_turn_debug) { const QueryNode &nodeinfo = m_node_info_list[node]; - if (!dg_first_turn_debug) dg_debug_turns_file << "," << std::endl; - dg_debug_turns_file << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"trafficlights\",\"cost\":" << traffic_signal_penalty/10. << "},"; - dg_debug_turns_file << " \"geometry\":{\"type\":\"Point\",\"coordinates\":[" << std::setprecision(12) << nodeinfo.lon/COORDINATE_PRECISION << "," << nodeinfo.lat/COORDINATE_PRECISION << "]}}"; + if (!dg_first_turn_debug) + dg_debug_turns_file << "," << std::endl; + dg_debug_turns_file + << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"trafficlights\",\"cost\":" + << traffic_signal_penalty / 10. << "},"; + dg_debug_turns_file << " \"geometry\":{\"type\":\"Point\",\"coordinates\":[" + << std::setprecision(12) << nodeinfo.lon / COORDINATE_PRECISION << "," + << nodeinfo.lat / COORDINATE_PRECISION << "]}}"; dg_first_turn_debug = false; } } -inline void DEBUG_UTURN( - const NodeID node, - const std::vector& m_node_info_list, - const int traffic_signal_penalty) +inline void DEBUG_UTURN(const NodeID node, + const std::vector &m_node_info_list, + const int traffic_signal_penalty) { if (dg_output_turn_debug) { const QueryNode &nodeinfo = m_node_info_list[node]; - if (!dg_first_turn_debug) dg_debug_turns_file << "," << std::endl; - dg_debug_turns_file << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"trafficlights\",\"cost\":" << traffic_signal_penalty/10. << "},"; - dg_debug_turns_file << " \"geometry\":{\"type\":\"Point\",\"coordinates\":[" << std::setprecision(12) << nodeinfo.lon/COORDINATE_PRECISION << "," << nodeinfo.lat/COORDINATE_PRECISION << "]}}"; + if (!dg_first_turn_debug) + dg_debug_turns_file << "," << std::endl; + dg_debug_turns_file + << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"trafficlights\",\"cost\":" + << traffic_signal_penalty / 10. << "},"; + dg_debug_turns_file << " \"geometry\":{\"type\":\"Point\",\"coordinates\":[" + << std::setprecision(12) << nodeinfo.lon / COORDINATE_PRECISION << "," + << nodeinfo.lat / COORDINATE_PRECISION << "]}}"; dg_first_turn_debug = false; } } - -inline void DEBUG_TURN( - const NodeID node, - const std::vector& m_node_info_list, - const FixedPointCoordinate & first_coordinate, - const int turn_angle, - const int turn_penalty) +inline void DEBUG_TURN(const NodeID node, + const std::vector &m_node_info_list, + const FixedPointCoordinate &first_coordinate, + const int turn_angle, + const int turn_penalty) { - if (turn_penalty > 0 && dg_output_turn_debug) + if (turn_penalty > 0 && dg_output_turn_debug) { const QueryNode &v = m_node_info_list[node]; - const float bearing_uv = coordinate_calculation::bearing(first_coordinate,v); - float uvw_normal = bearing_uv + turn_angle/2; - while (uvw_normal >= 360.) { uvw_normal -= 360.; } + const float bearing_uv = coordinate_calculation::bearing(first_coordinate, v); + float uvw_normal = bearing_uv + turn_angle / 2; + while (uvw_normal >= 360.) + { + uvw_normal -= 360.; + } - if (!dg_first_turn_debug) dg_debug_turns_file << "," << std::endl; - dg_debug_turns_file << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"turn\",\"cost\":" << turn_penalty/10. << ",\"turn_angle\":" << static_cast(turn_angle) << ",\"normal\":" << static_cast(uvw_normal) << "},"; - dg_debug_turns_file << " \"geometry\":{\"type\":\"Point\",\"coordinates\":[" << std::setprecision(12) << v.lon/COORDINATE_PRECISION << "," << v.lat/COORDINATE_PRECISION << "]}}"; + if (!dg_first_turn_debug) + dg_debug_turns_file << "," << std::endl; + dg_debug_turns_file << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"turn\",\"cost\":" + << turn_penalty / 10. + << ",\"turn_angle\":" << static_cast(turn_angle) + << ",\"normal\":" << static_cast(uvw_normal) << "},"; + dg_debug_turns_file << " \"geometry\":{\"type\":\"Point\",\"coordinates\":[" + << std::setprecision(12) << v.lon / COORDINATE_PRECISION << "," + << v.lat / COORDINATE_PRECISION << "]}}"; dg_first_turn_debug = false; } } @@ -167,5 +196,4 @@ inline void DEBUG_TURNS_STOP() #endif // DEBUG_GEOMETRY - #endif // DEBUG_GEOMETRY_H diff --git a/include/util/dynamic_graph.hpp b/include/util/dynamic_graph.hpp index d0c4fd082..4dd2f0022 100644 --- a/include/util/dynamic_graph.hpp +++ b/include/util/dynamic_graph.hpp @@ -64,7 +64,8 @@ template class DynamicGraph template DynamicGraph(const NodeIterator nodes, const ContainerT &graph) { // we need to cast here because DeallocatingVector does not have a valid const iterator - BOOST_ASSERT(std::is_sorted(const_cast(graph).begin(), const_cast(graph).end())); + BOOST_ASSERT(std::is_sorted(const_cast(graph).begin(), + const_cast(graph).end())); number_of_nodes = nodes; number_of_edges = static_cast(graph.size()); diff --git a/include/util/fingerprint.hpp b/include/util/fingerprint.hpp index f4a9f84ac..bb58fe697 100644 --- a/include/util/fingerprint.hpp +++ b/include/util/fingerprint.hpp @@ -25,10 +25,8 @@ class FingerPrint // initialize to {6ba7b810-9dad-11d1-80b4-00c04fd430c8} boost::uuids::uuid named_uuid; - }; static_assert(std::is_trivial::value, "FingerPrint needs to be trivial."); - #endif /* FingerPrint_H */ diff --git a/include/util/graph_utils.hpp b/include/util/graph_utils.hpp index d9d2fc46e..7c907ff22 100644 --- a/include/util/graph_utils.hpp +++ b/include/util/graph_utils.hpp @@ -7,20 +7,20 @@ #include /// This function checks if the graph (consisting of directed edges) is undirected -template -bool isUndirectedGraph(const GraphT& graph) +template bool isUndirectedGraph(const GraphT &graph) { for (auto source = 0u; source < graph.GetNumberOfNodes(); ++source) { for (auto edge = graph.BeginEdges(source); edge < graph.EndEdges(source); ++edge) { - const auto& data = graph.GetEdgeData(edge); + const auto &data = graph.GetEdgeData(edge); auto target = graph.GetTarget(edge); BOOST_ASSERT(target != SPECIAL_NODEID); bool found_reverse = false; - for (auto rev_edge = graph.BeginEdges(target); rev_edge < graph.EndEdges(target); ++rev_edge) + for (auto rev_edge = graph.BeginEdges(target); rev_edge < graph.EndEdges(target); + ++rev_edge) { auto rev_target = graph.GetTarget(rev_edge); BOOST_ASSERT(rev_target != SPECIAL_NODEID); @@ -44,7 +44,6 @@ bool isUndirectedGraph(const GraphT& graph) return true; } - /// Since DynamicGraph assumes directed edges we have to make sure we transformed /// the compressed edge format into single directed edges. We do this to make sure /// every node also knows its incoming edges, not only its outgoing edges and use the reversed=true @@ -60,13 +59,14 @@ bool isUndirectedGraph(const GraphT& graph) /// (a <-- b gets reducted to b --> a) /// 2. a --> b will be transformed to a --> b and b <-- a /// 3. a <-> b will be transformed to a --> b and b --> a -template -std::vector directedEdgesFromCompressed(const std::vector& input_edge_list, FunctorT copy_data) +template +std::vector directedEdgesFromCompressed(const std::vector &input_edge_list, + FunctorT copy_data) { std::vector output_edge_list; OutputEdgeT edge; - for (const auto& input_edge : input_edge_list) + for (const auto &input_edge : input_edge_list) { // edges that are not forward get converted by flipping the end points BOOST_ASSERT(input_edge.forward); diff --git a/include/util/integer_range.hpp b/include/util/integer_range.hpp index 9d176b8e0..6c27b55dc 100644 --- a/include/util/integer_range.hpp +++ b/include/util/integer_range.hpp @@ -28,10 +28,7 @@ template class range const range &end() const noexcept { return *this; } Integer front() const noexcept { return iter; } Integer back() const noexcept { return last - 1; } - std::size_t size() const noexcept - { - return static_cast(last - iter); - } + std::size_t size() const noexcept { return static_cast(last - iter); } // Iterator functions bool operator!=(const range &) const noexcept { return iter < last; } diff --git a/include/util/json_logger.hpp b/include/util/json_logger.hpp index cb2511f75..cb3333f70 100644 --- a/include/util/json_logger.hpp +++ b/include/util/json_logger.hpp @@ -20,7 +20,7 @@ class Logger using MapT = std::unordered_map; public: - static Logger* get() + static Logger *get() { static Logger logger; @@ -40,7 +40,7 @@ class Logger return nullptr; } - void initialize(const std::string& name) + void initialize(const std::string &name) { if (!map.get()) { @@ -49,15 +49,10 @@ class Logger (*map)[name] = Object(); } - void render(const std::string& name, Object& obj) const - { - obj.values["debug"] = map->at(name); - } + void render(const std::string &name, Object &obj) const { obj.values["debug"] = map->at(name); } boost::thread_specific_ptr map; }; - - } } diff --git a/include/util/node_based_graph.hpp b/include/util/node_based_graph.hpp index e2c9e557c..51842ebbe 100644 --- a/include/util/node_based_graph.hpp +++ b/include/util/node_based_graph.hpp @@ -13,17 +13,22 @@ struct NodeBasedEdgeData { NodeBasedEdgeData() : distance(INVALID_EDGE_WEIGHT), edge_id(SPECIAL_NODEID), - name_id(std::numeric_limits::max()), access_restricted(false), - reversed(false), roundabout(false), travel_mode(TRAVEL_MODE_INACCESSIBLE) + name_id(std::numeric_limits::max()), access_restricted(false), reversed(false), + roundabout(false), travel_mode(TRAVEL_MODE_INACCESSIBLE) { } - NodeBasedEdgeData(int distance, unsigned edge_id, unsigned name_id, - bool access_restricted, bool reversed, - bool roundabout, bool startpoint, TravelMode travel_mode) + NodeBasedEdgeData(int distance, + unsigned edge_id, + unsigned name_id, + bool access_restricted, + bool reversed, + bool roundabout, + bool startpoint, + TravelMode travel_mode) : distance(distance), edge_id(edge_id), name_id(name_id), - access_restricted(access_restricted), reversed(reversed), - roundabout(roundabout), startpoint(startpoint), travel_mode(travel_mode) + access_restricted(access_restricted), reversed(reversed), roundabout(roundabout), + startpoint(startpoint), travel_mode(travel_mode) { } @@ -49,10 +54,12 @@ using NodeBasedDynamicGraph = DynamicGraph; /// Since DynamicGraph expects directed edges, we need to insert /// two edges for undirected edges. inline std::shared_ptr -NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, const std::vector &input_edge_list) +NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, + const std::vector &input_edge_list) { - auto edges_list = directedEdgesFromCompressed(input_edge_list, - [](NodeBasedDynamicGraph::InputEdge& output_edge, const NodeBasedEdge& input_edge) + auto edges_list = directedEdgesFromCompressed( + input_edge_list, + [](NodeBasedDynamicGraph::InputEdge &output_edge, const NodeBasedEdge &input_edge) { output_edge.data.distance = static_cast(input_edge.weight); BOOST_ASSERT(output_edge.data.distance > 0); @@ -62,8 +69,7 @@ NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, const std::vector class RangeTable } // construct table from length vector - template - explicit RangeTable(const VectorT &lengths) + template explicit RangeTable(const VectorT &lengths) { const unsigned number_of_blocks = [&lengths]() { diff --git a/include/util/static_graph.hpp b/include/util/static_graph.hpp index 9ca5cf1f5..e8270409f 100644 --- a/include/util/static_graph.hpp +++ b/include/util/static_graph.hpp @@ -60,10 +60,10 @@ template class StaticGraph return osrm::irange(BeginEdges(node), EndEdges(node)); } - template - StaticGraph(const int nodes, const ContainerT &graph) + template StaticGraph(const int nodes, const ContainerT &graph) { - BOOST_ASSERT(std::is_sorted(const_cast(graph).begin(), const_cast(graph).end())); + BOOST_ASSERT(std::is_sorted(const_cast(graph).begin(), + const_cast(graph).end())); number_of_nodes = nodes; number_of_edges = static_cast(graph.size()); diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 0c9d99522..57444f549 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -319,7 +319,7 @@ class StaticRTree // Override filter and terminator for the desired behaviour. std::vector Nearest(const FixedPointCoordinate &input_coordinate, - const std::size_t max_results) + const std::size_t max_results) { return Nearest(input_coordinate, [](const EdgeDataT &) @@ -335,8 +335,8 @@ class StaticRTree // Override filter and terminator for the desired behaviour. template std::vector Nearest(const FixedPointCoordinate &input_coordinate, - const FilterT filter, - const TerminationT terminate) + const FilterT filter, + const TerminationT terminate) { std::vector results; std::pair projected_coordinate = { @@ -345,7 +345,7 @@ class StaticRTree // initialize queue with root element std::priority_queue traversal_queue; - traversal_queue.push(QueryCandidate {0.f, m_search_tree[0]}); + traversal_queue.push(QueryCandidate{0.f, m_search_tree[0]}); while (!traversal_queue.empty()) { @@ -377,7 +377,6 @@ class StaticRTree // inspecting an actual road segment const auto ¤t_segment = current_query_node.node.template get(); - auto use_segment = filter(current_segment); if (!use_segment.first && !use_segment.second) { @@ -422,7 +421,8 @@ class StaticRTree // distance must be non-negative BOOST_ASSERT(0.f <= current_perpendicular_distance); - traversal_queue.push(QueryCandidate {current_perpendicular_distance, std::move(current_edge)}); + traversal_queue.push( + QueryCandidate{current_perpendicular_distance, std::move(current_edge)}); } } @@ -437,7 +437,7 @@ class StaticRTree const auto &child_tree_node = m_search_tree[child_id]; const auto &child_rectangle = child_tree_node.minimum_bounding_rectangle; const float lower_bound_to_element = child_rectangle.GetMinDist(input_coordinate); - traversal_queue.push(QueryCandidate {lower_bound_to_element, m_search_tree[child_id]}); + traversal_queue.push(QueryCandidate{lower_bound_to_element, m_search_tree[child_id]}); } } @@ -449,7 +449,7 @@ class StaticRTree } if (!leaves_stream.good()) { - throw osrm::exception("Could not read from leaf file."); + throw osrm::exception("Could not read from leaf file."); } const uint64_t seek_pos = sizeof(uint64_t) + leaf_id * sizeof(LeafNode); leaves_stream.seekg(seek_pos); diff --git a/src/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp index c3967f4cd..9be36d015 100644 --- a/src/benchmarks/static_rtree.cpp +++ b/src/benchmarks/static_rtree.cpp @@ -42,7 +42,7 @@ FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path &nodes template void BenchmarkQuery(const std::vector &queries, - const std::string& name, + const std::string &name, QueryT query) { std::cout << "Running " << name << " with " << queries.size() << " coordinates: " << std::flush; @@ -91,11 +91,13 @@ void Benchmark(BenchStaticRTree &rtree, BenchQuery &geo_query, unsigned num_quer { return geo_query.NearestPhantomNodesInRange(q, 1000); }); - BenchmarkQuery(queries, "PhantomNode query (1 result)", [&geo_query](const FixedPointCoordinate &q) + BenchmarkQuery(queries, "PhantomNode query (1 result)", + [&geo_query](const FixedPointCoordinate &q) { return geo_query.NearestPhantomNodes(q, 1); }); - BenchmarkQuery(queries, "PhantomNode query (10 result)", [&geo_query](const FixedPointCoordinate &q) + BenchmarkQuery(queries, "PhantomNode query (10 result)", + [&geo_query](const FixedPointCoordinate &q) { return geo_query.NearestPhantomNodes(q, 10); }); diff --git a/src/contractor/contractor_options.cpp b/src/contractor/contractor_options.cpp index 463bd7906..d25bb71fd 100644 --- a/src/contractor/contractor_options.cpp +++ b/src/contractor/contractor_options.cpp @@ -14,8 +14,9 @@ ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &cont // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( - "config,c", boost::program_options::value(&contractor_config.config_file_path) - ->default_value("contractor.ini"), + "config,c", + boost::program_options::value(&contractor_config.config_file_path) + ->default_value("contractor.ini"), "Path to a configuration file."); // declare a group of options that will be allowed both on command line and in config file @@ -29,26 +30,29 @@ ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &cont boost::program_options::value(&contractor_config.requested_num_threads) ->default_value(tbb::task_scheduler_init::default_num_threads()), "Number of threads to use")( - "core,k", boost::program_options::value(&contractor_config.core_factor) - ->default_value(1.0),"Percentage of the graph (in vertices) to contract [0..1]")( - "segment-speed-file", boost::program_options::value(&contractor_config.segment_speed_lookup_path), - "Lookup file containing nodeA,nodeB,speed data to adjust edge weights")( - "level-cache,o", - boost::program_options::value(&contractor_config.use_cached_priority)->default_value(false), + "core,k", + boost::program_options::value(&contractor_config.core_factor)->default_value(1.0), + "Percentage of the graph (in vertices) to contract [0..1]")( + "segment-speed-file", + boost::program_options::value(&contractor_config.segment_speed_lookup_path), + "Lookup file containing nodeA,nodeB,speed data to adjust edge weights")( + "level-cache,o", boost::program_options::value(&contractor_config.use_cached_priority) + ->default_value(false), "Use .level file to retain the contaction level for each node from the last run."); #ifdef DEBUG_GEOMETRY config_options.add_options()( - "debug-geometry", boost::program_options::value(&contractor_config.debug_geometry_path) - ,"Write out edge-weight debugging geometry data in GeoJSON format to this file"); + "debug-geometry", + boost::program_options::value(&contractor_config.debug_geometry_path), + "Write out edge-weight debugging geometry data in GeoJSON format to this file"); #endif // hidden options, will be allowed both on command line and in config file, but will not be // shown to the user boost::program_options::options_description hidden_options("Hidden options"); - hidden_options.add_options()( - "input,i", boost::program_options::value(&contractor_config.osrm_input_path), - "Input file in .osm, .osm.bz2 or .osm.pbf format"); + hidden_options.add_options()("input,i", boost::program_options::value( + &contractor_config.osrm_input_path), + "Input file in .osm, .osm.bz2 or .osm.pbf format"); // positional option boost::program_options::positional_options_description positional_options; @@ -110,6 +114,8 @@ void ContractorOptions::GenerateOutputFilesNames(ContractorConfig &contractor_co contractor_config.core_output_path = contractor_config.osrm_input_path.string() + ".core"; contractor_config.graph_output_path = contractor_config.osrm_input_path.string() + ".hsgr"; contractor_config.edge_based_graph_path = contractor_config.osrm_input_path.string() + ".ebg"; - contractor_config.edge_segment_lookup_path = contractor_config.osrm_input_path.string() + ".edge_segment_lookup"; - contractor_config.edge_penalty_path = contractor_config.osrm_input_path.string() + ".edge_penalties"; + contractor_config.edge_segment_lookup_path = + contractor_config.osrm_input_path.string() + ".edge_segment_lookup"; + contractor_config.edge_penalty_path = + contractor_config.osrm_input_path.string() + ".edge_penalties"; } diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index 1757e52a7..7e814ded7 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -43,9 +43,9 @@ int Prepare::Run() "changing EdgeBasedEdge type has influence on memory consumption!"); #endif - if (config.core_factor > 1.0 || config.core_factor < 0) + if (config.core_factor > 1.0 || config.core_factor < 0) { - throw osrm::exception("Core factor must be between 0.0 to 1.0 (inclusive)"); + throw osrm::exception("Core factor must be between 0.0 to 1.0 (inclusive)"); } TIMER_START(preparing); @@ -158,7 +158,8 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f unsigned speed{}; while (csv_in.read_row(from_node_id, to_node_id, speed)) { - segment_speed_lookup[std::make_pair(OSMNodeID(from_node_id), OSMNodeID(to_node_id))] = speed; + segment_speed_lookup[std::make_pair(OSMNodeID(from_node_id), OSMNodeID(to_node_id))] = + speed; } } @@ -169,7 +170,7 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f for (; number_of_edges > 0; --number_of_edges) { EdgeBasedEdge inbuffer; - input_stream.read((char *) &inbuffer, sizeof(EdgeBasedEdge)); + input_stream.read((char *)&inbuffer, sizeof(EdgeBasedEdge)); if (update_edge_weights) { @@ -211,22 +212,16 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f (segment_length * 10.) / (speed_iter->second / 3.6) + .5))); new_weight += new_segment_weight; - DEBUG_GEOMETRY_EDGE( - new_segment_weight, - segment_length, - previous_osm_node_id, - this_osm_node_id); + DEBUG_GEOMETRY_EDGE(new_segment_weight, segment_length, previous_osm_node_id, + this_osm_node_id); } else { // If no lookup found, use the original weight value for this segment new_weight += segment_weight; - DEBUG_GEOMETRY_EDGE( - segment_weight, - segment_length, - previous_osm_node_id, - this_osm_node_id); + DEBUG_GEOMETRY_EDGE(segment_weight, segment_length, previous_osm_node_id, + this_osm_node_id); } previous_osm_node_id = this_osm_node_id; diff --git a/src/engine/descriptors/description_factory.cpp b/src/engine/descriptors/description_factory.cpp index e2548e1fb..4c4f5696a 100644 --- a/src/engine/descriptors/description_factory.cpp +++ b/src/engine/descriptors/description_factory.cpp @@ -195,26 +195,28 @@ void DescriptionFactory::Run(const unsigned zoom_level) // fix what needs to be fixed else unsigned necessary_segments = 0; // a running index that counts the necessary pieces - osrm::for_each_pair( - path_description, [&](SegmentInformation &first, const SegmentInformation &second) - { - if (!first.necessary) - { - return; - } + osrm::for_each_pair(path_description, + [&](SegmentInformation &first, const SegmentInformation &second) + { + if (!first.necessary) + { + return; + } - if (first.is_via_location) - { // mark the end of a leg (of several segments) - via_indices.push_back(necessary_segments); - } + if (first.is_via_location) + { // mark the end of a leg (of several segments) + via_indices.push_back(necessary_segments); + } - const double post_turn_bearing = coordinate_calculation::bearing(first.location, second.location); - const double pre_turn_bearing = coordinate_calculation::bearing(second.location, first.location); - first.post_turn_bearing = static_cast(post_turn_bearing * 10); - first.pre_turn_bearing = static_cast(pre_turn_bearing * 10); + const double post_turn_bearing = + coordinate_calculation::bearing(first.location, second.location); + const double pre_turn_bearing = + coordinate_calculation::bearing(second.location, first.location); + first.post_turn_bearing = static_cast(post_turn_bearing * 10); + first.pre_turn_bearing = static_cast(pre_turn_bearing * 10); - ++necessary_segments; - }); + ++necessary_segments; + }); via_indices.push_back(necessary_segments); BOOST_ASSERT(via_indices.size() >= 2); diff --git a/src/engine/osrm_impl.cpp b/src/engine/osrm_impl.cpp index f9a486e75..72003eb5d 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/osrm_impl.cpp @@ -36,7 +36,7 @@ class named_mutex; #include #include -OSRM::OSRM_impl::OSRM_impl(LibOSRMConfig& lib_config) +OSRM::OSRM_impl::OSRM_impl(LibOSRMConfig &lib_config) { if (lib_config.use_shared_memory) { @@ -58,10 +58,10 @@ OSRM::OSRM_impl::OSRM_impl(LibOSRMConfig& lib_config) RegisterPlugin(new MapMatchingPlugin>( query_data_facade, lib_config.max_locations_map_matching)); RegisterPlugin(new TimestampPlugin>(query_data_facade)); - RegisterPlugin(new ViaRoutePlugin>(query_data_facade, - lib_config.max_locations_viaroute)); - RegisterPlugin(new RoundTripPlugin>(query_data_facade, - lib_config.max_locations_trip)); + RegisterPlugin(new ViaRoutePlugin>( + query_data_facade, lib_config.max_locations_viaroute)); + RegisterPlugin(new RoundTripPlugin>( + query_data_facade, lib_config.max_locations_trip)); } void OSRM::OSRM_impl::RegisterPlugin(BasePlugin *raw_plugin_ptr) @@ -71,7 +71,8 @@ void OSRM::OSRM_impl::RegisterPlugin(BasePlugin *raw_plugin_ptr) plugin_map[plugin_ptr->GetDescriptor()] = std::move(plugin_ptr); } -int OSRM::OSRM_impl::RunQuery(const RouteParameters &route_parameters, osrm::json::Object &json_result) +int OSRM::OSRM_impl::RunQuery(const RouteParameters &route_parameters, + osrm::json::Object &json_result) { const auto &plugin_iterator = plugin_map.find(route_parameters.service); diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp index 689fc5ebd..bc960bb58 100644 --- a/src/engine/phantom_node.cpp +++ b/src/engine/phantom_node.cpp @@ -22,9 +22,9 @@ PhantomNode::PhantomNode(NodeID forward_node_id, : forward_node_id(forward_node_id), reverse_node_id(reverse_node_id), name_id(name_id), forward_weight(forward_weight), reverse_weight(reverse_weight), forward_offset(forward_offset), reverse_offset(reverse_offset), - packed_geometry_id(packed_geometry_id), component{component_id, is_tiny_component}, location(location), - fwd_segment_position(fwd_segment_position), forward_travel_mode(forward_travel_mode), - backward_travel_mode(backward_travel_mode) + packed_geometry_id(packed_geometry_id), component{component_id, is_tiny_component}, + location(location), fwd_segment_position(fwd_segment_position), + forward_travel_mode(forward_travel_mode), backward_travel_mode(backward_travel_mode) { } diff --git a/src/engine/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp index bbb090152..2cb7935f7 100644 --- a/src/engine/polyline_compressor.cpp +++ b/src/engine/polyline_compressor.cpp @@ -62,16 +62,17 @@ PolylineCompressor::get_encoded_string(const std::vector &po return encode_vector(delta_numbers); } -std::vector PolylineCompressor::decode_string(const std::string &geometry_string) const +std::vector +PolylineCompressor::decode_string(const std::string &geometry_string) const { std::vector new_coordinates; int index = 0, len = geometry_string.size(); int lat = 0, lng = 0; - - while (index < len) + + while (index < len) { int b, shift = 0, result = 0; - do + do { b = geometry_string.at(index++) - 63; result |= (b & 0x1f) << shift; @@ -82,7 +83,7 @@ std::vector PolylineCompressor::decode_string(const std::s shift = 0; result = 0; - do + do { b = geometry_string.at(index++) - 63; result |= (b & 0x1f) << shift; @@ -92,8 +93,8 @@ std::vector PolylineCompressor::decode_string(const std::s lng += dlng; FixedPointCoordinate p; - p.lat = COORDINATE_PRECISION * (((double) lat / 1E6)); - p.lon = COORDINATE_PRECISION * (((double) lng / 1E6)); + p.lat = COORDINATE_PRECISION * (((double)lat / 1E6)); + p.lon = COORDINATE_PRECISION * (((double)lng / 1E6)); new_coordinates.push_back(p); } diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index d98d963ea..7138362fd 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -91,14 +91,17 @@ void RouteParameters::addTimestamp(const unsigned timestamp) void RouteParameters::addBearing( const boost::fusion::vector> &received_bearing, - boost::spirit::qi::unused_type /* unused */, bool& pass) + boost::spirit::qi::unused_type /* unused */, + bool &pass) { pass = false; const int bearing = boost::fusion::at_c<0>(received_bearing); const boost::optional range = boost::fusion::at_c<1>(received_bearing); - if (bearing < 0 || bearing > 359) return; - if (range && (*range < 0 || *range > 180)) return; - bearings.emplace_back(std::make_pair(bearing,range)); + if (bearing < 0 || bearing > 359) + return; + if (range && (*range < 0 || *range > 180)) + return; + bearings.emplace_back(std::make_pair(bearing, range)); pass = true; } @@ -133,8 +136,7 @@ void RouteParameters::addDestination( uturns.push_back(uturn_default); } -void RouteParameters::addSource( - const boost::fusion::vector &received_coordinates) +void RouteParameters::addSource(const boost::fusion::vector &received_coordinates) { coordinates.emplace_back( static_cast(COORDINATE_PRECISION * boost::fusion::at_c<0>(received_coordinates)), @@ -149,4 +151,3 @@ void RouteParameters::getCoordinatesFromGeometry(const std::string &geometry_str PolylineCompressor pc; coordinates = pc.decode_string(geometry_string); } - diff --git a/src/extractor/compressed_edge_container.cpp b/src/extractor/compressed_edge_container.cpp index aa590153e..2b9c5146f 100644 --- a/src/extractor/compressed_edge_container.cpp +++ b/src/extractor/compressed_edge_container.cpp @@ -84,11 +84,11 @@ void CompressedEdgeContainer::SerializeInternalVector(const std::string &path) c } void CompressedEdgeContainer::CompressEdge(const EdgeID edge_id_1, - const EdgeID edge_id_2, - const NodeID via_node_id, - const NodeID target_node_id, - const EdgeWeight weight1, - const EdgeWeight weight2) + const EdgeID edge_id_2, + const NodeID via_node_id, + const NodeID target_node_id, + const EdgeWeight weight1, + const EdgeWeight weight2) { // remove super-trivial geometries BOOST_ASSERT(SPECIAL_EDGEID != edge_id_1); @@ -182,7 +182,8 @@ void CompressedEdgeContainer::PrintStatistics() const } SimpleLogger().Write() << "Geometry successfully removed:" - "\n compressed edges: " << compressed_edges + "\n compressed edges: " + << compressed_edges << "\n compressed geometries: " << compressed_geometries << "\n longest chain length: " << longest_chain_length << "\n cmpr ratio: " << ((float)compressed_edges / @@ -192,7 +193,7 @@ void CompressedEdgeContainer::PrintStatistics() const std::max((uint64_t)1, compressed_edges); } -const CompressedEdgeContainer::EdgeBucket& +const CompressedEdgeContainer::EdgeBucket & CompressedEdgeContainer::GetBucketReference(const EdgeID edge_id) const { const unsigned index = m_edge_id_to_list_index_map.at(edge_id); diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 5e903f788..b357ccb65 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -24,7 +24,8 @@ EdgeBasedGraphFactory::EdgeBasedGraphFactory( std::shared_ptr restriction_map, const std::vector &node_info_list, SpeedProfileProperties speed_profile) - : m_max_edge_id(0), m_node_info_list(node_info_list), m_node_based_graph(std::move(node_based_graph)), + : m_max_edge_id(0), m_node_info_list(node_info_list), + m_node_based_graph(std::move(node_based_graph)), m_restriction_map(std::move(restriction_map)), m_barrier_nodes(barrier_nodes), m_traffic_lights(traffic_lights), m_compressed_edge_container(compressed_edge_container), speed_profile(std::move(speed_profile)) @@ -59,13 +60,9 @@ void EdgeBasedGraphFactory::GetStartPointMarkers(std::vector &node_is_star swap(m_edge_based_node_is_startpoint, node_is_startpoint); } -unsigned EdgeBasedGraphFactory::GetHighestEdgeID() -{ - return m_max_edge_id; -} +unsigned EdgeBasedGraphFactory::GetHighestEdgeID() { return m_max_edge_id; } -void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, - const NodeID node_v) +void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeID node_v) { // merge edges together into one EdgeBasedNode BOOST_ASSERT(node_u != SPECIAL_NODEID); @@ -83,8 +80,7 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const EdgeData &reverse_data = m_node_based_graph->GetEdgeData(edge_id_2); - if (forward_data.edge_id == SPECIAL_NODEID && - reverse_data.edge_id == SPECIAL_NODEID) + if (forward_data.edge_id == SPECIAL_NODEID && reverse_data.edge_id == SPECIAL_NODEID) { return; } @@ -96,8 +92,8 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, BOOST_ASSERT(m_compressed_edge_container.HasEntryForID(edge_id_2)); // reconstruct geometry and put in each individual edge with its offset - const auto& forward_geometry = m_compressed_edge_container.GetBucketReference(edge_id_1); - const auto& reverse_geometry = m_compressed_edge_container.GetBucketReference(edge_id_2); + const auto &forward_geometry = m_compressed_edge_container.GetBucketReference(edge_id_1); + const auto &reverse_geometry = m_compressed_edge_container.GetBucketReference(edge_id_2); BOOST_ASSERT(forward_geometry.size() == reverse_geometry.size()); BOOST_ASSERT(0 != forward_geometry.size()); const unsigned geometry_size = static_cast(forward_geometry.size()); @@ -140,13 +136,13 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, // build edges m_edge_based_node_list.emplace_back( - forward_data.edge_id, reverse_data.edge_id, - current_edge_source_coordinate_id, current_edge_target_coordinate_id, - forward_data.name_id, forward_geometry[i].second, + forward_data.edge_id, reverse_data.edge_id, current_edge_source_coordinate_id, + current_edge_target_coordinate_id, forward_data.name_id, forward_geometry[i].second, reverse_geometry[geometry_size - 1 - i].second, forward_dist_prefix_sum[i], reverse_dist_prefix_sum[i], m_compressed_edge_container.GetPositionForID(edge_id_1), false, INVALID_COMPONENTID, i, forward_data.travel_mode, reverse_data.travel_mode); - m_edge_based_node_is_startpoint.push_back(forward_data.startpoint || reverse_data.startpoint); + m_edge_based_node_is_startpoint.push_back(forward_data.startpoint || + reverse_data.startpoint); current_edge_source_coordinate_id = current_edge_target_coordinate_id; BOOST_ASSERT(m_edge_based_node_list.back().IsCompressed()); @@ -187,10 +183,11 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, reverse_data.edge_id != SPECIAL_NODEID); m_edge_based_node_list.emplace_back( - forward_data.edge_id, reverse_data.edge_id, node_u, node_v, - forward_data.name_id, forward_data.distance, reverse_data.distance, 0, 0, SPECIAL_EDGEID, - false, INVALID_COMPONENTID, 0, forward_data.travel_mode, reverse_data.travel_mode); - m_edge_based_node_is_startpoint.push_back(forward_data.startpoint || reverse_data.startpoint); + forward_data.edge_id, reverse_data.edge_id, node_u, node_v, forward_data.name_id, + forward_data.distance, reverse_data.distance, 0, 0, SPECIAL_EDGEID, false, + INVALID_COMPONENTID, 0, forward_data.travel_mode, reverse_data.travel_mode); + m_edge_based_node_is_startpoint.push_back(forward_data.startpoint || + reverse_data.startpoint); BOOST_ASSERT(!m_edge_based_node_list.back().IsCompressed()); } } @@ -232,13 +229,11 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename, TIMER_START(generate_edges); #ifdef DEBUG_GEOMETRY - GenerateEdgeExpandedEdges(original_edge_data_filename, lua_state, - edge_segment_lookup_filename,edge_penalty_filename, - generate_edge_lookup, debug_turns_path); + GenerateEdgeExpandedEdges(original_edge_data_filename, lua_state, edge_segment_lookup_filename, + edge_penalty_filename, generate_edge_lookup, debug_turns_path); #else - GenerateEdgeExpandedEdges(original_edge_data_filename, lua_state, - edge_segment_lookup_filename,edge_penalty_filename, - generate_edge_lookup); + GenerateEdgeExpandedEdges(original_edge_data_filename, lua_state, edge_segment_lookup_filename, + edge_penalty_filename, generate_edge_lookup); #endif TIMER_STOP(generate_edges); @@ -249,7 +244,6 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename, SimpleLogger().Write() << "Generating edges: " << TIMER_SEC(generate_edges) << "s"; } - /// Renumbers all _forward_ edges and sets the edge_id. /// A specific numbering is not important. Any unique ID will do. /// Returns the number of edge based nodes. @@ -328,14 +322,16 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() /// Actually it also generates OriginalEdgeData and serializes them... #ifdef DEBUG_GEOMETRY void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( - const std::string &original_edge_data_filename, lua_State *lua_state, + const std::string &original_edge_data_filename, + lua_State *lua_state, const std::string &edge_segment_lookup_filename, const std::string &edge_fixed_penalties_filename, - const bool generate_edge_lookup, + const bool generate_edge_lookup, const std::string &debug_turns_path) #else void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( - const std::string &original_edge_data_filename, lua_State *lua_state, + const std::string &original_edge_data_filename, + lua_State *lua_state, const std::string &edge_segment_lookup_filename, const std::string &edge_fixed_penalties_filename, const bool generate_edge_lookup) @@ -378,7 +374,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( for (const auto node_u : osrm::irange(0u, m_node_based_graph->GetNumberOfNodes())) { - //progress.printStatus(node_u); + // progress.printStatus(node_u); for (const EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(node_u)) { if (m_node_based_graph->GetEdgeData(e1).reversed) @@ -475,7 +471,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( distance += speed_profile.u_turn_penalty; DEBUG_UTURN(node_v, m_node_info_list, speed_profile.u_turn_penalty); - } + } DEBUG_TURN(node_v, m_node_info_list, first_coordinate, turn_angle, turn_penalty); @@ -489,7 +485,8 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( } original_edge_data_vector.emplace_back( - (edge_is_compressed ? m_compressed_edge_container.GetPositionForID(e1) : node_v), + (edge_is_compressed ? m_compressed_edge_container.GetPositionForID(e1) + : node_v), edge_data1.name_id, turn_instruction, edge_is_compressed, edge_data2.travel_mode); @@ -503,12 +500,11 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( BOOST_ASSERT(SPECIAL_NODEID != edge_data1.edge_id); BOOST_ASSERT(SPECIAL_NODEID != edge_data2.edge_id); - // NOTE: potential overflow here if we hit 2^32 routable edges BOOST_ASSERT(m_edge_based_edge_list.size() <= std::numeric_limits::max()); m_edge_based_edge_list.emplace_back(edge_data1.edge_id, edge_data2.edge_id, - m_edge_based_edge_list.size(), distance, true, false); - + m_edge_based_edge_list.size(), distance, true, + false); // Here is where we write out the mapping between the edge-expanded edges, and // the node-based edges that are originally used to calculate the `distance` @@ -525,26 +521,36 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( if (generate_edge_lookup) { unsigned fixed_penalty = distance - edge_data1.distance; - edge_penalty_file.write(reinterpret_cast(&fixed_penalty), sizeof(fixed_penalty)); + edge_penalty_file.write(reinterpret_cast(&fixed_penalty), + sizeof(fixed_penalty)); if (edge_is_compressed) { - const auto node_based_edges = m_compressed_edge_container.GetBucketReference(e1); + const auto node_based_edges = + m_compressed_edge_container.GetBucketReference(e1); NodeID previous = node_u; - const unsigned node_count = node_based_edges.size()+1; - edge_segment_file.write(reinterpret_cast(&node_count), sizeof(node_count)); + const unsigned node_count = node_based_edges.size() + 1; + edge_segment_file.write(reinterpret_cast(&node_count), + sizeof(node_count)); const QueryNode &first_node = m_node_info_list[previous]; - edge_segment_file.write(reinterpret_cast(&first_node.node_id), sizeof(first_node.node_id)); + edge_segment_file.write(reinterpret_cast(&first_node.node_id), + sizeof(first_node.node_id)); for (auto target_node : node_based_edges) { const QueryNode &from = m_node_info_list[previous]; const QueryNode &to = m_node_info_list[target_node.first]; - const double segment_length = coordinate_calculation::great_circle_distance(from.lat, from.lon, to.lat, to.lon); + const double segment_length = + coordinate_calculation::great_circle_distance(from.lat, from.lon, + to.lat, to.lon); - edge_segment_file.write(reinterpret_cast(&to.node_id), sizeof(to.node_id)); - edge_segment_file.write(reinterpret_cast(&segment_length), sizeof(segment_length)); - edge_segment_file.write(reinterpret_cast(&target_node.second), sizeof(target_node.second)); + edge_segment_file.write(reinterpret_cast(&to.node_id), + sizeof(to.node_id)); + edge_segment_file.write(reinterpret_cast(&segment_length), + sizeof(segment_length)); + edge_segment_file.write( + reinterpret_cast(&target_node.second), + sizeof(target_node.second)); previous = target_node.first; } } @@ -553,12 +559,19 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( static const unsigned node_count = 2; const QueryNode from = m_node_info_list[node_u]; const QueryNode to = m_node_info_list[node_v]; - const double segment_length = coordinate_calculation::great_circle_distance(from.lat, from.lon, to.lat, to.lon); - edge_segment_file.write(reinterpret_cast(&node_count), sizeof(node_count)); - edge_segment_file.write(reinterpret_cast(&from.node_id), sizeof(from.node_id)); - edge_segment_file.write(reinterpret_cast(&to.node_id), sizeof(to.node_id)); - edge_segment_file.write(reinterpret_cast(&segment_length), sizeof(segment_length)); - edge_segment_file.write(reinterpret_cast(&edge_data1.distance), sizeof(edge_data1.distance)); + const double segment_length = coordinate_calculation::great_circle_distance( + from.lat, from.lon, to.lat, to.lon); + edge_segment_file.write(reinterpret_cast(&node_count), + sizeof(node_count)); + edge_segment_file.write(reinterpret_cast(&from.node_id), + sizeof(from.node_id)); + edge_segment_file.write(reinterpret_cast(&to.node_id), + sizeof(to.node_id)); + edge_segment_file.write(reinterpret_cast(&segment_length), + sizeof(segment_length)); + edge_segment_file.write( + reinterpret_cast(&edge_data1.distance), + sizeof(edge_data1.distance)); } } } @@ -592,7 +605,8 @@ int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) co try { // call lua profile to compute turn penalty - double penalty = luabind::call_function(lua_state, "turn_function", 180. - angle); + double penalty = + luabind::call_function(lua_state, "turn_function", 180. - angle); return static_cast(penalty); } catch (const luabind::error &er) @@ -659,4 +673,3 @@ TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID node_u, return TurnInstructionsClass::GetTurnDirectionOfInstruction(angle); } - diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 18de02d32..994a6c93f 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -86,7 +86,7 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name, } } -void ExtractionContainers::WriteNames(const std::string& names_file_name) const +void ExtractionContainers::WriteNames(const std::string &names_file_name) const { std::cout << "[extractor] writing street name index ... " << std::flush; TIMER_START(write_name_index); @@ -105,7 +105,6 @@ void ExtractionContainers::WriteNames(const std::string& names_file_name) const name_file_stream.write((char *)&total_length, sizeof(unsigned)); - // write all chars consecutively char write_buffer[WRITE_BLOCK_BUFFER_SIZE]; unsigned buffer_len = 0; @@ -183,12 +182,12 @@ void ExtractionContainers::PrepareNodes() } if (internal_id > std::numeric_limits::max()) { - throw osrm::exception("There are too many nodes remaining after filtering, OSRM only supports 2^32 unique nodes"); + throw osrm::exception("There are too many nodes remaining after filtering, OSRM only " + "supports 2^32 unique nodes"); } max_internal_node_id = boost::numeric_cast(internal_id); TIMER_STOP(id_map); std::cout << "ok, after " << TIMER_SEC(id_map) << "s" << std::endl; - } void ExtractionContainers::PrepareEdges(lua_State *segment_state) @@ -213,7 +212,8 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) { if (edge_iterator->result.osm_source_id < node_iterator->node_id) { - SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << edge_iterator->result.source; + SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " + << edge_iterator->result.source; edge_iterator->result.source = SPECIAL_NODEID; ++edge_iterator; continue; @@ -261,8 +261,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) // Sort Edges by target std::cout << "[extractor] Sorting edges by target ... " << std::flush; TIMER_START(sort_edges_by_target); - stxxl::sort(all_edges_list.begin(), all_edges_list.end(), CmpEdgeByOSMTargetID(), - stxxl_memory); + stxxl::sort(all_edges_list.begin(), all_edges_list.end(), CmpEdgeByOSMTargetID(), stxxl_memory); TIMER_STOP(sort_edges_by_target); std::cout << "ok, after " << TIMER_SEC(sort_edges_by_target) << "s" << std::endl; @@ -285,7 +284,9 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) if (edge_iterator->result.osm_target_id < node_iterator->node_id) { - SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << OSMNodeID_to_uint64_t(edge_iterator->result.osm_target_id); + SimpleLogger().Write(LogLevel::logWARNING) + << "Found invalid node reference " + << OSMNodeID_to_uint64_t(edge_iterator->result.osm_target_id); edge_iterator->result.target = SPECIAL_NODEID; ++edge_iterator; continue; @@ -308,30 +309,28 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) if (lua_function_exists(segment_state, "segment_function")) { luabind::call_function( - segment_state, "segment_function", - boost::cref(edge_iterator->source_coordinate), - boost::cref(*node_iterator), - distance, - boost::ref(edge_iterator->weight_data)); + segment_state, "segment_function", boost::cref(edge_iterator->source_coordinate), + boost::cref(*node_iterator), distance, boost::ref(edge_iterator->weight_data)); } - const double weight = [distance](const InternalExtractorEdge::WeightData& data) { + const double weight = [distance](const InternalExtractorEdge::WeightData &data) + { switch (data.type) { - case InternalExtractorEdge::WeightType::EDGE_DURATION: - case InternalExtractorEdge::WeightType::WAY_DURATION: - return data.duration * 10.; - break; - case InternalExtractorEdge::WeightType::SPEED: - return (distance * 10.) / (data.speed / 3.6); - break; - case InternalExtractorEdge::WeightType::INVALID: - osrm::exception("invalid weight type"); + case InternalExtractorEdge::WeightType::EDGE_DURATION: + case InternalExtractorEdge::WeightType::WAY_DURATION: + return data.duration * 10.; + break; + case InternalExtractorEdge::WeightType::SPEED: + return (distance * 10.) / (data.speed / 3.6); + break; + case InternalExtractorEdge::WeightType::INVALID: + osrm::exception("invalid weight type"); } return -1.0; }(edge_iterator->weight_data); - auto& edge = edge_iterator->result; + auto &edge = edge_iterator->result; edge.weight = std::max(1, static_cast(std::floor(weight + .5))); // assign new node id @@ -368,7 +367,8 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) // Sort edges by start. std::cout << "[extractor] Sorting edges by renumbered start ... " << std::flush; TIMER_START(sort_edges_by_renumbered_start); - stxxl::sort(all_edges_list.begin(), all_edges_list.end(), CmpEdgeByInternalStartThenInternalTargetID(), stxxl_memory); + stxxl::sort(all_edges_list.begin(), all_edges_list.end(), + CmpEdgeByInternalStartThenInternalTargetID(), stxxl_memory); TIMER_STOP(sort_edges_by_renumbered_start); std::cout << "ok, after " << TIMER_SEC(sort_edges_by_renumbered_start) << "s" << std::endl; @@ -400,11 +400,13 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) while (all_edges_list[i].result.source == source && all_edges_list[i].result.target == target) { - if (all_edges_list[i].result.forward && all_edges_list[i].result.weight < min_forward_weight) + if (all_edges_list[i].result.forward && + all_edges_list[i].result.weight < min_forward_weight) { min_forward_idx = i; } - if (all_edges_list[i].result.backward && all_edges_list[i].result.weight < min_backward_weight) + if (all_edges_list[i].result.backward && + all_edges_list[i].result.weight < min_backward_weight) { min_backward_idx = i; } @@ -413,8 +415,10 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) i++; } - BOOST_ASSERT(min_forward_idx == std::numeric_limits::max() || min_forward_idx < i); - BOOST_ASSERT(min_backward_idx == std::numeric_limits::max() || min_backward_idx < i); + BOOST_ASSERT(min_forward_idx == std::numeric_limits::max() || + min_forward_idx < i); + BOOST_ASSERT(min_backward_idx == std::numeric_limits::max() || + min_backward_idx < i); BOOST_ASSERT(min_backward_idx != std::numeric_limits::max() || min_forward_idx != std::numeric_limits::max()); @@ -457,7 +461,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) } } -void ExtractionContainers::WriteEdges(std::ofstream& file_out_stream) const +void ExtractionContainers::WriteEdges(std::ofstream &file_out_stream) const { std::cout << "[extractor] Writing used edges ... " << std::flush; TIMER_START(write_edges); @@ -468,7 +472,7 @@ void ExtractionContainers::WriteEdges(std::ofstream& file_out_stream) const auto start_position = file_out_stream.tellp(); file_out_stream.write((char *)&used_edges_counter_buffer, sizeof(unsigned)); - for (const auto& edge : all_edges_list) + for (const auto &edge : all_edges_list) { if (edge.result.source == SPECIAL_NODEID || edge.result.target == SPECIAL_NODEID) { @@ -478,7 +482,7 @@ void ExtractionContainers::WriteEdges(std::ofstream& file_out_stream) const // IMPORTANT: here, we're using slicing to only write the data from the base // class of NodeBasedEdgeWithOSM NodeBasedEdge tmp = edge.result; - file_out_stream.write((char*) &tmp, sizeof(NodeBasedEdge)); + file_out_stream.write((char *)&tmp, sizeof(NodeBasedEdge)); used_edges_counter++; } @@ -500,7 +504,7 @@ void ExtractionContainers::WriteEdges(std::ofstream& file_out_stream) const SimpleLogger().Write() << "Processed " << used_edges_counter << " edges"; } -void ExtractionContainers::WriteNodes(std::ofstream& file_out_stream) const +void ExtractionContainers::WriteNodes(std::ofstream &file_out_stream) const { // write dummy value, will be overwritten later std::cout << "[extractor] setting number of nodes ... " << std::flush; @@ -537,11 +541,10 @@ void ExtractionContainers::WriteNodes(std::ofstream& file_out_stream) const TIMER_STOP(write_nodes); std::cout << "ok, after " << TIMER_SEC(write_nodes) << "s" << std::endl; - SimpleLogger().Write() << "Processed " << max_internal_node_id << " nodes"; } -void ExtractionContainers::WriteRestrictions(const std::string& path) const +void ExtractionContainers::WriteRestrictions(const std::string &path) const { // serialize restrictions std::ofstream restrictions_out_stream; @@ -578,11 +581,11 @@ void ExtractionContainers::PrepareRestrictions() TIMER_STOP(sort_ways); std::cout << "ok, after " << TIMER_SEC(sort_ways) << "s" << std::endl; - std::cout << "[extractor] Sorting " << restrictions_list.size() - << " restriction. by from... " << std::flush; + std::cout << "[extractor] Sorting " << restrictions_list.size() << " restriction. by from... " + << std::flush; TIMER_START(sort_restrictions); - stxxl::sort(restrictions_list.begin(), restrictions_list.end(), - CmpRestrictionContainerByFrom(), stxxl_memory); + stxxl::sort(restrictions_list.begin(), restrictions_list.end(), CmpRestrictionContainerByFrom(), + stxxl_memory); TIMER_STOP(sort_restrictions); std::cout << "ok, after " << TIMER_SEC(sort_restrictions) << "s" << std::endl; @@ -596,15 +599,18 @@ void ExtractionContainers::PrepareRestrictions() while (way_start_and_end_iterator != way_start_end_id_list_end && restrictions_iterator != restrictions_list_end) { - if (way_start_and_end_iterator->way_id < OSMWayID(restrictions_iterator->restriction.from.way)) + if (way_start_and_end_iterator->way_id < + OSMWayID(restrictions_iterator->restriction.from.way)) { ++way_start_and_end_iterator; continue; } - if (way_start_and_end_iterator->way_id > OSMWayID(restrictions_iterator->restriction.from.way)) + if (way_start_and_end_iterator->way_id > + OSMWayID(restrictions_iterator->restriction.from.way)) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " << restrictions_iterator->restriction.from.way; + SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " + << restrictions_iterator->restriction.from.way; restrictions_iterator->restriction.from.node = SPECIAL_NODEID; ++restrictions_iterator; continue; @@ -617,9 +623,10 @@ void ExtractionContainers::PrepareRestrictions() // check if via is actually valid, if not invalidate auto via_id_iter = external_to_internal_node_id_map.find(via_node_id); - if(via_id_iter == external_to_internal_node_id_map.end()) + if (via_id_iter == external_to_internal_node_id_map.end()) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid node: " << restrictions_iterator->restriction.via.node; + SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid node: " + << restrictions_iterator->restriction.via.node; restrictions_iterator->restriction.via.node = SPECIAL_NODEID; ++restrictions_iterator; continue; @@ -629,7 +636,7 @@ void ExtractionContainers::PrepareRestrictions() { // assign new from node id auto id_iter = external_to_internal_node_id_map.find( - OSMNodeID(way_start_and_end_iterator->first_segment_target_id)); + OSMNodeID(way_start_and_end_iterator->first_segment_target_id)); BOOST_ASSERT(id_iter != external_to_internal_node_id_map.end()); restrictions_iterator->restriction.from.node = id_iter->second; } @@ -637,7 +644,7 @@ void ExtractionContainers::PrepareRestrictions() { // assign new from node id auto id_iter = external_to_internal_node_id_map.find( - OSMNodeID(way_start_and_end_iterator->last_segment_source_id)); + OSMNodeID(way_start_and_end_iterator->last_segment_source_id)); BOOST_ASSERT(id_iter != external_to_internal_node_id_map.end()); restrictions_iterator->restriction.from.node = id_iter->second; } @@ -649,8 +656,8 @@ void ExtractionContainers::PrepareRestrictions() std::cout << "[extractor] Sorting restrictions. by to ... " << std::flush; TIMER_START(sort_restrictions_to); - stxxl::sort(restrictions_list.begin(), restrictions_list.end(), - CmpRestrictionContainerByTo(), stxxl_memory); + stxxl::sort(restrictions_list.begin(), restrictions_list.end(), CmpRestrictionContainerByTo(), + stxxl_memory); TIMER_STOP(sort_restrictions_to); std::cout << "ok, after " << TIMER_SEC(sort_restrictions_to) << "s" << std::endl; @@ -664,7 +671,8 @@ void ExtractionContainers::PrepareRestrictions() while (way_start_and_end_iterator != way_start_end_id_list_end_ && restrictions_iterator != restrictions_list_end_) { - if (way_start_and_end_iterator->way_id < OSMWayID(restrictions_iterator->restriction.to.way)) + if (way_start_and_end_iterator->way_id < + OSMWayID(restrictions_iterator->restriction.to.way)) { ++way_start_and_end_iterator; continue; @@ -675,9 +683,11 @@ void ExtractionContainers::PrepareRestrictions() ++restrictions_iterator; continue; } - if (way_start_and_end_iterator->way_id > OSMWayID(restrictions_iterator->restriction.to.way)) + if (way_start_and_end_iterator->way_id > + OSMWayID(restrictions_iterator->restriction.to.way)) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " << restrictions_iterator->restriction.to.way; + SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " + << restrictions_iterator->restriction.to.way; restrictions_iterator->restriction.to.way = SPECIAL_NODEID; ++restrictions_iterator; continue; @@ -694,14 +704,14 @@ void ExtractionContainers::PrepareRestrictions() if (OSMNodeID(way_start_and_end_iterator->first_segment_source_id) == via_node_id) { auto to_id_iter = external_to_internal_node_id_map.find( - OSMNodeID(way_start_and_end_iterator->first_segment_target_id)); + OSMNodeID(way_start_and_end_iterator->first_segment_target_id)); BOOST_ASSERT(to_id_iter != external_to_internal_node_id_map.end()); restrictions_iterator->restriction.to.node = to_id_iter->second; } else if (OSMNodeID(way_start_and_end_iterator->last_segment_target_id) == via_node_id) { auto to_id_iter = external_to_internal_node_id_map.find( - OSMNodeID(way_start_and_end_iterator->last_segment_source_id)); + OSMNodeID(way_start_and_end_iterator->last_segment_source_id)); BOOST_ASSERT(to_id_iter != external_to_internal_node_id_map.end()); restrictions_iterator->restriction.to.node = to_id_iter->second; } diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 496c8639e..40ac02f3c 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -574,7 +574,7 @@ void extractor::BuildRTree(std::vector node_based_edge_list, TIMER_START(construction); StaticRTree rtree(node_based_edge_list, config.rtree_nodes_output_path, - config.rtree_leafs_output_path, internal_to_external_node_map); + config.rtree_leafs_output_path, internal_to_external_node_map); TIMER_STOP(construction); SimpleLogger().Write() << "finished r-tree construction in " << TIMER_SEC(construction) diff --git a/src/extractor/extractor_callbacks.cpp b/src/extractor/extractor_callbacks.cpp index 60b911049..9b740c6dd 100644 --- a/src/extractor/extractor_callbacks.cpp +++ b/src/extractor/extractor_callbacks.cpp @@ -36,9 +36,7 @@ void ExtractorCallbacks::ProcessNode(const osmium::Node &input_node, external_memory.all_nodes_list.push_back( {static_cast(input_node.location().lat() * COORDINATE_PRECISION), static_cast(input_node.location().lon() * COORDINATE_PRECISION), - OSMNodeID(input_node.id()), - result_node.barrier, - result_node.traffic_lights}); + OSMNodeID(input_node.id()), result_node.barrier, result_node.traffic_lights}); } void ExtractorCallbacks::ProcessRestriction( @@ -130,7 +128,8 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (string_map.end() == string_map_iterator) { auto name_length = std::min(255u, parsed_way.name.size()); - std::copy(parsed_way.name.c_str(), parsed_way.name.c_str() + name_length, std::back_inserter(external_memory.name_char_data)); + std::copy(parsed_way.name.c_str(), parsed_way.name.c_str() + name_length, + std::back_inserter(external_memory.name_char_data)); external_memory.name_lengths.push_back(name_length); string_map.insert(std::make_pair(parsed_way.name, name_id)); } @@ -164,18 +163,17 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { external_memory.all_edges_list.push_back(InternalExtractorEdge( - OSMNodeID(first_node.ref()), OSMNodeID(last_node.ref()), name_id, - backward_weight_data, true, false, parsed_way.roundabout, - parsed_way.is_access_restricted, parsed_way.is_startpoint, - parsed_way.backward_travel_mode, false)); + OSMNodeID(first_node.ref()), OSMNodeID(last_node.ref()), + name_id, backward_weight_data, true, false, + parsed_way.roundabout, parsed_way.is_access_restricted, + parsed_way.is_startpoint, parsed_way.backward_travel_mode, + false)); }); external_memory.way_start_end_id_list.push_back( - {OSMWayID(input_way.id()), - OSMNodeID(input_way.nodes().back().ref()), + {OSMWayID(input_way.id()), OSMNodeID(input_way.nodes().back().ref()), OSMNodeID(input_way.nodes()[input_way.nodes().size() - 2].ref()), - OSMNodeID(input_way.nodes()[1].ref()), - OSMNodeID(input_way.nodes()[0].ref())}); + OSMNodeID(input_way.nodes()[1].ref()), OSMNodeID(input_way.nodes()[0].ref())}); } else { @@ -185,9 +183,10 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { external_memory.all_edges_list.push_back(InternalExtractorEdge( - OSMNodeID(first_node.ref()), OSMNodeID(last_node.ref()), name_id, forward_weight_data, - true, !forward_only, parsed_way.roundabout, - parsed_way.is_access_restricted, parsed_way.is_startpoint, parsed_way.forward_travel_mode, + OSMNodeID(first_node.ref()), OSMNodeID(last_node.ref()), + name_id, forward_weight_data, true, !forward_only, + parsed_way.roundabout, parsed_way.is_access_restricted, + parsed_way.is_startpoint, parsed_way.forward_travel_mode, split_edge)); }); if (split_edge) @@ -198,17 +197,16 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { external_memory.all_edges_list.push_back(InternalExtractorEdge( - OSMNodeID(first_node.ref()), OSMNodeID(last_node.ref()), name_id, backward_weight_data, false, - true, parsed_way.roundabout, parsed_way.is_access_restricted, - parsed_way.is_startpoint, parsed_way.backward_travel_mode, true)); + OSMNodeID(first_node.ref()), OSMNodeID(last_node.ref()), name_id, + backward_weight_data, false, true, parsed_way.roundabout, + parsed_way.is_access_restricted, parsed_way.is_startpoint, + parsed_way.backward_travel_mode, true)); }); } external_memory.way_start_end_id_list.push_back( - {OSMWayID(input_way.id()), - OSMNodeID(input_way.nodes().back().ref()), + {OSMWayID(input_way.id()), OSMNodeID(input_way.nodes().back().ref()), OSMNodeID(input_way.nodes()[input_way.nodes().size() - 2].ref()), - OSMNodeID(input_way.nodes()[1].ref()), - OSMNodeID(input_way.nodes()[0].ref())}); + OSMNodeID(input_way.nodes()[1].ref()), OSMNodeID(input_way.nodes()[0].ref())}); } } diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp index 685704a57..16bc3de53 100644 --- a/src/extractor/extractor_options.cpp +++ b/src/extractor/extractor_options.cpp @@ -21,32 +21,37 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac boost::program_options::value(&extractor_config.restrictions_path), "Restrictions file in .osrm.restrictions format")( */ - "config,c", boost::program_options::value( - &extractor_config.config_file_path)->default_value("extractor.ini"), + "config,c", + boost::program_options::value(&extractor_config.config_file_path) + ->default_value("extractor.ini"), "Path to a configuration file."); // declare a group of options that will be allowed both on command line and in config file boost::program_options::options_description config_options("Configuration"); - config_options.add_options()("profile,p", - boost::program_options::value( - &extractor_config.profile_path)->default_value("profile.lua"), - "Path to LUA routing profile")( + config_options.add_options()( + "profile,p", + boost::program_options::value(&extractor_config.profile_path) + ->default_value("profile.lua"), + "Path to LUA routing profile")( "threads,t", boost::program_options::value(&extractor_config.requested_num_threads) ->default_value(tbb::task_scheduler_init::default_num_threads()), "Number of threads to use")( - "generate-edge-lookup",boost::program_options::value( - &extractor_config.generate_edge_lookup)->implicit_value(true)->default_value(false), - "Generate a lookup table for internal edge-expanded-edge IDs to OSM node pairs")( + "generate-edge-lookup", + boost::program_options::value(&extractor_config.generate_edge_lookup) + ->implicit_value(true) + ->default_value(false), + "Generate a lookup table for internal edge-expanded-edge IDs to OSM node pairs")( "small-component-size", boost::program_options::value(&extractor_config.small_component_size) ->default_value(1000), - "Number of nodes required before a strongly-connected-componennt is considered big (affects nearest neighbor snapping)"); + "Number of nodes required before a strongly-connected-componennt is considered big " + "(affects nearest neighbor snapping)"); #ifdef DEBUG_GEOMETRY - config_options.add_options()("debug-turns", - boost::program_options::value(&extractor_config.debug_turns_path), - "Write out GeoJSON with turn penalty data"); + config_options.add_options()("debug-turns", boost::program_options::value( + &extractor_config.debug_turns_path), + "Write out GeoJSON with turn penalty data"); #endif // DEBUG_GEOMETRY // hidden options, will be allowed both on command line and in config file, but will not be @@ -56,7 +61,6 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac &extractor_config.input_path), "Input file in .osm, .osm.bz2 or .osm.pbf format"); - // positional option boost::program_options::positional_options_description positional_options; positional_options.add("input", 1); @@ -98,8 +102,8 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac // parse config file if (boost::filesystem::is_regular_file(extractor_config.config_file_path)) { - SimpleLogger().Write() - << "Reading options from: " << extractor_config.config_file_path.string(); + SimpleLogger().Write() << "Reading options from: " + << extractor_config.config_file_path.string(); std::string ini_file_contents = read_file_lower_content(extractor_config.config_file_path); std::stringstream config_stream(ini_file_contents); @@ -181,8 +185,8 @@ void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_confi extractor_config.edge_graph_output_path.replace(pos, 5, ".osrm.ebg"); extractor_config.rtree_nodes_output_path.replace(pos, 5, ".osrm.ramIndex"); extractor_config.rtree_leafs_output_path.replace(pos, 5, ".osrm.fileIndex"); - extractor_config.edge_segment_lookup_path.replace(pos,5, ".osrm.edge_segment_lookup"); - extractor_config.edge_penalty_path.replace(pos,5, ".osrm.edge_penalties"); + extractor_config.edge_segment_lookup_path.replace(pos, 5, ".osrm.edge_segment_lookup"); + extractor_config.edge_penalty_path.replace(pos, 5, ".osrm.edge_penalties"); } } else @@ -197,7 +201,7 @@ void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_confi extractor_config.edge_graph_output_path.replace(pos, 8, ".osrm.ebg"); extractor_config.rtree_nodes_output_path.replace(pos, 8, ".osrm.ramIndex"); extractor_config.rtree_leafs_output_path.replace(pos, 8, ".osrm.fileIndex"); - extractor_config.edge_segment_lookup_path.replace(pos,8, ".osrm.edge_segment_lookup"); - extractor_config.edge_penalty_path.replace(pos,8, ".osrm.edge_penalties"); + extractor_config.edge_segment_lookup_path.replace(pos, 8, ".osrm.edge_segment_lookup"); + extractor_config.edge_penalty_path.replace(pos, 8, ".osrm.edge_penalties"); } } diff --git a/src/extractor/graph_compressor.cpp b/src/extractor/graph_compressor.cpp index 8ee098089..751c10eb0 100644 --- a/src/extractor/graph_compressor.cpp +++ b/src/extractor/graph_compressor.cpp @@ -13,12 +13,11 @@ GraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile) { } - -void GraphCompressor::Compress(const std::unordered_set& barrier_nodes, - const std::unordered_set& traffic_lights, - RestrictionMap& restriction_map, - NodeBasedDynamicGraph& graph, - CompressedEdgeContainer& geometry_compressor) +void GraphCompressor::Compress(const std::unordered_set &barrier_nodes, + const std::unordered_set &traffic_lights, + RestrictionMap &restriction_map, + NodeBasedDynamicGraph &graph, + CompressedEdgeContainer &geometry_compressor) { const unsigned original_number_of_nodes = graph.GetNumberOfNodes(); const unsigned original_number_of_edges = graph.GetNumberOfEdges(); @@ -64,12 +63,10 @@ void GraphCompressor::Compress(const std::unordered_set& barrier_nodes, const bool reverse_edge_order = graph.GetEdgeData(graph.BeginEdges(node_v)).reversed; const EdgeID forward_e2 = graph.BeginEdges(node_v) + reverse_edge_order; BOOST_ASSERT(SPECIAL_EDGEID != forward_e2); - BOOST_ASSERT(forward_e2 >= graph.BeginEdges(node_v) && - forward_e2 < graph.EndEdges(node_v)); + BOOST_ASSERT(forward_e2 >= graph.BeginEdges(node_v) && forward_e2 < graph.EndEdges(node_v)); const EdgeID reverse_e2 = graph.BeginEdges(node_v) + 1 - reverse_edge_order; BOOST_ASSERT(SPECIAL_EDGEID != reverse_e2); - BOOST_ASSERT(reverse_e2 >= graph.BeginEdges(node_v) && - reverse_e2 < graph.EndEdges(node_v)); + BOOST_ASSERT(reverse_e2 >= graph.BeginEdges(node_v) && reverse_e2 < graph.EndEdges(node_v)); const EdgeData &fwd_edge_data2 = graph.GetEdgeData(forward_e2); const EdgeData &rev_edge_data2 = graph.GetEdgeData(reverse_e2); @@ -103,7 +100,8 @@ void GraphCompressor::Compress(const std::unordered_set& barrier_nodes, continue; } - if (fwd_edge_data1.IsCompatibleTo(fwd_edge_data2) && rev_edge_data1.IsCompatibleTo(rev_edge_data2)) + if (fwd_edge_data1.IsCompatibleTo(fwd_edge_data2) && + rev_edge_data1.IsCompatibleTo(rev_edge_data2)) { BOOST_ASSERT(graph.GetEdgeData(forward_e1).name_id == graph.GetEdgeData(reverse_e1).name_id); @@ -130,10 +128,8 @@ void GraphCompressor::Compress(const std::unordered_set& barrier_nodes, graph.GetEdgeData(reverse_e1).distance += rev_edge_data2.distance; if (has_node_penalty) { - graph.GetEdgeData(forward_e1).distance += - speed_profile.traffic_signal_penalty; - graph.GetEdgeData(reverse_e1).distance += - speed_profile.traffic_signal_penalty; + graph.GetEdgeData(forward_e1).distance += speed_profile.traffic_signal_penalty; + graph.GetEdgeData(reverse_e1).distance += speed_profile.traffic_signal_penalty; } // extend e1's to targets of e2's @@ -167,7 +163,7 @@ void GraphCompressor::Compress(const std::unordered_set& barrier_nodes, void GraphCompressor::PrintStatistics(unsigned original_number_of_nodes, unsigned original_number_of_edges, - const NodeBasedDynamicGraph& graph) const + const NodeBasedDynamicGraph &graph) const { unsigned new_node_count = 0; diff --git a/src/extractor/import_edge.cpp b/src/extractor/import_edge.cpp index deb3cb973..999559219 100644 --- a/src/extractor/import_edge.cpp +++ b/src/extractor/import_edge.cpp @@ -22,8 +22,8 @@ bool NodeBasedEdge::operator<(const NodeBasedEdge &other) const NodeBasedEdge::NodeBasedEdge() : source(SPECIAL_NODEID), target(SPECIAL_NODEID), name_id(0), weight(0), forward(false), - backward(false), roundabout(false), - access_restricted(false), startpoint(true), is_split(false), travel_mode(false) + backward(false), roundabout(false), access_restricted(false), startpoint(true), + is_split(false), travel_mode(false) { } @@ -39,8 +39,8 @@ NodeBasedEdge::NodeBasedEdge(NodeID source, TravelMode travel_mode, bool is_split) : source(source), target(target), name_id(name_id), weight(weight), forward(forward), - backward(backward), roundabout(roundabout), - access_restricted(access_restricted), startpoint(startpoint), is_split(is_split), travel_mode(travel_mode) + backward(backward), roundabout(roundabout), access_restricted(access_restricted), + startpoint(startpoint), is_split(is_split), travel_mode(travel_mode) { } diff --git a/src/extractor/restriction_map.cpp b/src/extractor/restriction_map.cpp index c104d19d8..f5f84446e 100644 --- a/src/extractor/restriction_map.cpp +++ b/src/extractor/restriction_map.cpp @@ -15,7 +15,8 @@ RestrictionMap::RestrictionMap(const std::vector &restriction_l m_no_turn_via_node_set.insert(restriction.via.node); // This explicit downcasting is also OK for the same reason. - RestrictionSource restriction_source = {static_cast(restriction.from.node), static_cast(restriction.via.node)}; + RestrictionSource restriction_source = {static_cast(restriction.from.node), + static_cast(restriction.via.node)}; std::size_t index; auto restriction_iter = m_restriction_map.find(restriction_source); diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index 85f93dce4..6aa5bd0c6 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -219,7 +219,7 @@ bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_st [&](const std::string ¤t_string) { return std::end(restriction_exceptions) != - std::find(std::begin(restriction_exceptions), - std::end(restriction_exceptions), current_string); + std::find(std::begin(restriction_exceptions), + std::end(restriction_exceptions), current_string); }); } diff --git a/src/extractor/scripting_environment.cpp b/src/extractor/scripting_environment.cpp index cee8be2a0..14198d8ae 100644 --- a/src/extractor/scripting_environment.cpp +++ b/src/extractor/scripting_environment.cpp @@ -52,75 +52,70 @@ void ScriptingEnvironment::init_lua_state(lua_State *lua_state) luaAddScriptFolderToLoadPath(lua_state, file_name.c_str()); // Add our function to the state's global scope - luabind::module(lua_state)[ - luabind::def("print", LUA_print), - luabind::def("durationIsValid", durationIsValid), - luabind::def("parseDuration", parseDuration), - luabind::class_("sources") - .def(luabind::constructor<>()) - .def("load", &SourceContainer::loadRasterSource) - .def("query", &SourceContainer::getRasterDataFromSource) - .def("interpolate", &SourceContainer::getRasterInterpolateFromSource), - luabind::class_("constants") - .enum_("enums")[luabind::value("precision", COORDINATE_PRECISION)], + luabind::module(lua_state) + [luabind::def("print", LUA_print), + luabind::def("durationIsValid", durationIsValid), + luabind::def("parseDuration", parseDuration), + luabind::class_("sources") + .def(luabind::constructor<>()) + .def("load", &SourceContainer::loadRasterSource) + .def("query", &SourceContainer::getRasterDataFromSource) + .def("interpolate", &SourceContainer::getRasterInterpolateFromSource), + luabind::class_("constants") + .enum_("enums")[luabind::value("precision", COORDINATE_PRECISION)], - luabind::class_>("vector") - .def("Add", static_cast::*)(const std::string &)>( - &std::vector::push_back)), + luabind::class_>("vector") + .def("Add", static_cast::*)(const std::string &)>( + &std::vector::push_back)), - luabind::class_("Location") - .def("lat", &osmium::Location::lat) - .def("lon", &osmium::Location::lon), + luabind::class_("Location") + .def("lat", &osmium::Location::lat) + .def("lon", &osmium::Location::lon), - luabind::class_("Node") - // .def("tags", &osmium::Node::tags) - .def("location", &osmium::Node::location) - .def("get_value_by_key", &osmium::Node::get_value_by_key) - .def("get_value_by_key", &get_value_by_key) - .def("id", &osmium::Node::id), + luabind::class_("Node") + // .def("tags", &osmium::Node::tags) + .def("location", &osmium::Node::location) + .def("get_value_by_key", &osmium::Node::get_value_by_key) + .def("get_value_by_key", &get_value_by_key) + .def("id", &osmium::Node::id), - luabind::class_("ResultNode") - .def_readwrite("traffic_lights", &ExtractionNode::traffic_lights) - .def_readwrite("barrier", &ExtractionNode::barrier), + luabind::class_("ResultNode") + .def_readwrite("traffic_lights", &ExtractionNode::traffic_lights) + .def_readwrite("barrier", &ExtractionNode::barrier), - luabind::class_("ResultWay") - // .def(luabind::constructor<>()) - .def_readwrite("forward_speed", &ExtractionWay::forward_speed) - .def_readwrite("backward_speed", &ExtractionWay::backward_speed) - .def_readwrite("name", &ExtractionWay::name) - .def_readwrite("roundabout", &ExtractionWay::roundabout) - .def_readwrite("is_access_restricted", &ExtractionWay::is_access_restricted) - .def_readwrite("is_startpoint", &ExtractionWay::is_startpoint) - .def_readwrite("duration", &ExtractionWay::duration) - .property("forward_mode", &ExtractionWay::get_forward_mode, - &ExtractionWay::set_forward_mode) - .property("backward_mode", &ExtractionWay::get_backward_mode, - &ExtractionWay::set_backward_mode) - .enum_("constants")[ - luabind::value("notSure", 0), - luabind::value("oneway", 1), - luabind::value("bidirectional", 2), - luabind::value("opposite", 3) - ], - luabind::class_("Way") - .def("get_value_by_key", &osmium::Way::get_value_by_key) - .def("get_value_by_key", &get_value_by_key) - .def("id", &osmium::Way::id), - luabind::class_("EdgeSource") - .property("source_coordinate", &InternalExtractorEdge::source_coordinate) - .property("weight_data", &InternalExtractorEdge::weight_data), - luabind::class_("WeightData") - .def_readwrite("speed", &InternalExtractorEdge::WeightData::speed), - luabind::class_("EdgeTarget") - .property("lat", &ExternalMemoryNode::lat) - .property("lon", &ExternalMemoryNode::lon), - luabind::class_("Coordinate") - .property("lat", &FixedPointCoordinate::lat) - .property("lon", &FixedPointCoordinate::lon), - luabind::class_("RasterDatum") - .property("datum", &RasterDatum::datum) - .def("invalid_data", &RasterDatum::get_invalid) - ]; + luabind::class_("ResultWay") + // .def(luabind::constructor<>()) + .def_readwrite("forward_speed", &ExtractionWay::forward_speed) + .def_readwrite("backward_speed", &ExtractionWay::backward_speed) + .def_readwrite("name", &ExtractionWay::name) + .def_readwrite("roundabout", &ExtractionWay::roundabout) + .def_readwrite("is_access_restricted", &ExtractionWay::is_access_restricted) + .def_readwrite("is_startpoint", &ExtractionWay::is_startpoint) + .def_readwrite("duration", &ExtractionWay::duration) + .property("forward_mode", &ExtractionWay::get_forward_mode, + &ExtractionWay::set_forward_mode) + .property("backward_mode", &ExtractionWay::get_backward_mode, + &ExtractionWay::set_backward_mode) + .enum_("constants")[luabind::value("notSure", 0), luabind::value("oneway", 1), + luabind::value("bidirectional", 2), luabind::value("opposite", 3)], + luabind::class_("Way") + .def("get_value_by_key", &osmium::Way::get_value_by_key) + .def("get_value_by_key", &get_value_by_key) + .def("id", &osmium::Way::id), + luabind::class_("EdgeSource") + .property("source_coordinate", &InternalExtractorEdge::source_coordinate) + .property("weight_data", &InternalExtractorEdge::weight_data), + luabind::class_("WeightData") + .def_readwrite("speed", &InternalExtractorEdge::WeightData::speed), + luabind::class_("EdgeTarget") + .property("lat", &ExternalMemoryNode::lat) + .property("lon", &ExternalMemoryNode::lon), + luabind::class_("Coordinate") + .property("lat", &FixedPointCoordinate::lat) + .property("lon", &FixedPointCoordinate::lon), + luabind::class_("RasterDatum") + .property("datum", &RasterDatum::datum) + .def("invalid_data", &RasterDatum::get_invalid)]; if (0 != luaL_dofile(lua_state, file_name.c_str())) { diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index aef25014a..00d1d8f23 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -77,7 +77,8 @@ void RequestHandler::handle_request(const http::request ¤t_request, if (!route_parameters.jsonp_parameter.empty()) { // prepend response with jsonp parameter const std::string json_p = (route_parameters.jsonp_parameter + "("); - current_reply.content.insert(current_reply.content.end(), json_p.begin(), json_p.end()); + current_reply.content.insert(current_reply.content.end(), json_p.begin(), + json_p.end()); } const int return_code = routing_machine->RunQuery(route_parameters, json_result); @@ -101,7 +102,8 @@ void RequestHandler::handle_request(const http::request ¤t_request, current_reply.status = http::reply::bad_request; json_result.values["status"] = http::reply::bad_request; - json_result.values["status_message"] = "Query string malformed close to position " + std::to_string(position); + json_result.values["status_message"] = + "Query string malformed close to position " + std::to_string(position); } current_reply.headers.emplace_back("Access-Control-Allow-Origin", "*"); @@ -141,7 +143,8 @@ void RequestHandler::handle_request(const http::request ¤t_request, } catch (const std::exception &e) { - current_reply = http::reply::stock_reply(http::reply::internal_server_error);; + current_reply = http::reply::stock_reply(http::reply::internal_server_error); + ; SimpleLogger().Write(logWARNING) << "[server error] code: " << e.what() << ", uri: " << current_request.uri; } diff --git a/src/server/request_parser.cpp b/src/server/request_parser.cpp index 37d2b03b0..818ed44b3 100644 --- a/src/server/request_parser.cpp +++ b/src/server/request_parser.cpp @@ -15,8 +15,7 @@ namespace http RequestParser::RequestParser() : state(internal_state::method_start), current_header({"", ""}), - selected_compression(no_compression), is_post_header(false), - content_length(0) + selected_compression(no_compression), is_post_header(false), content_length(0) { } @@ -32,8 +31,8 @@ RequestParser::parse(request ¤t_request, char *begin, char *end) } } osrm::tribool result = osrm::tribool::indeterminate; - - if(state == internal_state::post_request && content_length <= 0) + + if (state == internal_state::post_request && content_length <= 0) { result = osrm::tribool::yes; } @@ -49,7 +48,7 @@ osrm::tribool RequestParser::consume(request ¤t_request, const char input) { return osrm::tribool::no; } - if(input == 'P') + if (input == 'P') { state = internal_state::post_O; return osrm::tribool::indeterminate; @@ -57,25 +56,25 @@ osrm::tribool RequestParser::consume(request ¤t_request, const char input) state = internal_state::method; return osrm::tribool::indeterminate; case internal_state::post_O: - if(input == 'O') + if (input == 'O') { - state = internal_state::post_S; - return osrm::tribool::indeterminate; + state = internal_state::post_S; + return osrm::tribool::indeterminate; } return osrm::tribool::no; case internal_state::post_S: - if(input == 'S') + if (input == 'S') { - state = internal_state::post_T; - return osrm::tribool::indeterminate; + state = internal_state::post_T; + return osrm::tribool::indeterminate; } return osrm::tribool::no; case internal_state::post_T: - if(input == 'T') + if (input == 'T') { - is_post_header = true; - state = internal_state::method; - return osrm::tribool::indeterminate; + is_post_header = true; + state = internal_state::method; + return osrm::tribool::indeterminate; } return osrm::tribool::no; case internal_state::post_request: @@ -216,7 +215,7 @@ osrm::tribool RequestParser::consume(request ¤t_request, const char input) } if (boost::iequals(current_header.name, "Content-Length")) { - try + try { content_length = std::stoi(current_header.value); } @@ -305,10 +304,10 @@ osrm::tribool RequestParser::consume(request ¤t_request, const char input) { if (is_post_header) { - if (content_length > 0) - { - current_request.uri.push_back('?'); - } + if (content_length > 0) + { + current_request.uri.push_back('?'); + } state = internal_state::post_request; return osrm::tribool::indeterminate; } diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index c95233c81..90b9637fb 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -50,8 +50,8 @@ int main(int argc, const char *argv[]) try LibOSRMConfig lib_config; const unsigned init_result = GenerateServerProgramOptions( argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, - lib_config.use_shared_memory, trial_run, lib_config.max_locations_trip, lib_config.max_locations_viaroute, - lib_config.max_locations_distance_table, + lib_config.use_shared_memory, trial_run, lib_config.max_locations_trip, + lib_config.max_locations_viaroute, lib_config.max_locations_distance_table, lib_config.max_locations_map_matching); if (init_result == INIT_OK_DO_NOT_START_ENGINE) { diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index f5799cb08..e008fff6d 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -37,7 +37,7 @@ FixedPointCoordinate::FixedPointCoordinate(int lat, int lon) : lat(lat), lon(lon bool FixedPointCoordinate::is_valid() const { return !(lat > 90 * COORDINATE_PRECISION || lat < -90 * COORDINATE_PRECISION || - lon > 180 * COORDINATE_PRECISION || lon < -180 * COORDINATE_PRECISION); + lon > 180 * COORDINATE_PRECISION || lon < -180 * COORDINATE_PRECISION); } bool FixedPointCoordinate::operator==(const FixedPointCoordinate &other) const diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index 9ab4a32a3..d52172ba2 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -22,10 +22,7 @@ constexpr static const double earth_radius = 6372797.560856; namespace coordinate_calculation { -double haversine_distance(const int lat1, - const int lon1, - const int lat2, - const int lon2) +double haversine_distance(const int lat1, const int lon1, const int lat2, const int lon2) { BOOST_ASSERT(lat1 != std::numeric_limits::min()); BOOST_ASSERT(lon1 != std::numeric_limits::min()); @@ -51,23 +48,20 @@ double haversine_distance(const int lat1, } double haversine_distance(const FixedPointCoordinate &coordinate_1, - const FixedPointCoordinate &coordinate_2) + const FixedPointCoordinate &coordinate_2) { return haversine_distance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, - coordinate_2.lon); -} - -double great_circle_distance(const FixedPointCoordinate &coordinate_1, - const FixedPointCoordinate &coordinate_2) -{ - return great_circle_distance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, coordinate_2.lon); } -double great_circle_distance(const int lat1, - const int lon1, - const int lat2, - const int lon2) +double great_circle_distance(const FixedPointCoordinate &coordinate_1, + const FixedPointCoordinate &coordinate_2) +{ + return great_circle_distance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, + coordinate_2.lon); +} + +double great_circle_distance(const int lat1, const int lon1, const int lat2, const int lon2) { BOOST_ASSERT(lat1 != std::numeric_limits::min()); BOOST_ASSERT(lon1 != std::numeric_limits::min()); @@ -85,8 +79,8 @@ double great_circle_distance(const int lat1, } double perpendicular_distance(const FixedPointCoordinate &source_coordinate, - const FixedPointCoordinate &target_coordinate, - const FixedPointCoordinate &query_location) + const FixedPointCoordinate &target_coordinate, + const FixedPointCoordinate &query_location) { double ratio; FixedPointCoordinate nearest_location; @@ -96,10 +90,10 @@ double perpendicular_distance(const FixedPointCoordinate &source_coordinate, } double perpendicular_distance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - FixedPointCoordinate &nearest_location, - double &ratio) + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + FixedPointCoordinate &nearest_location, + double &ratio) { return perpendicular_distance_from_projected_coordinate( segment_source, segment_target, query_location, @@ -161,8 +155,8 @@ double perpendicular_distance_from_projected_coordinate( } // compute ratio - ratio = - static_cast((p - nY * a) / c); // These values are actually n/m+n and m/m+n , we need + ratio = static_cast((p - nY * a) / + c); // These values are actually n/m+n and m/m+n , we need // not calculate the explicit values of m an n as we // are just interested in the ratio if (std::isnan(ratio)) @@ -196,8 +190,7 @@ double perpendicular_distance_from_projected_coordinate( } BOOST_ASSERT(nearest_location.is_valid()); - const double approximate_distance = - great_circle_distance(query_location, nearest_location); + const double approximate_distance = great_circle_distance(query_location, nearest_location); BOOST_ASSERT(0.0 <= approximate_distance); return approximate_distance; } @@ -209,18 +202,12 @@ void lat_or_lon_to_string(const int value, std::string &output) output = printInt<11, 6>(buffer, value); } -double deg_to_rad(const double degree) -{ - return degree * (static_cast(M_PI) / 180.0); -} +double deg_to_rad(const double degree) { return degree * (static_cast(M_PI) / 180.0); } -double rad_to_deg(const double radian) -{ - return radian * (180.0 * static_cast(M_1_PI)); -} +double rad_to_deg(const double radian) { return radian * (180.0 * static_cast(M_1_PI)); } double bearing(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate) + const FixedPointCoordinate &second_coordinate) { const double lon_diff = second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION; @@ -242,5 +229,4 @@ double bearing(const FixedPointCoordinate &first_coordinate, } return result; } - } diff --git a/unit_tests/engine/douglas_peucker.cpp b/unit_tests/engine/douglas_peucker.cpp index 8b1c3cb58..827ce5016 100644 --- a/unit_tests/engine/douglas_peucker.cpp +++ b/unit_tests/engine/douglas_peucker.cpp @@ -25,10 +25,8 @@ BOOST_AUTO_TEST_CASE(all_necessary_test) * / \ * x x */ - std::vector info = {getTestInfo(5, 5, true), - getTestInfo(6, 6, true), - getTestInfo(10, 10, true), - getTestInfo(5, 15, true)}; + std::vector info = {getTestInfo(5, 5, true), getTestInfo(6, 6, true), + getTestInfo(10, 10, true), getTestInfo(5, 15, true)}; DouglasPeucker dp; for (unsigned z = 0; z < DOUGLAS_PEUCKER_THRESHOLDS.size(); z++) { diff --git a/unit_tests/engine/geometry_string.cpp b/unit_tests/engine/geometry_string.cpp index 349c153aa..7e5e07c2c 100644 --- a/unit_tests/engine/geometry_string.cpp +++ b/unit_tests/engine/geometry_string.cpp @@ -23,7 +23,7 @@ BOOST_AUTO_TEST_CASE(geometry_string) FixedPointCoordinate coord3(10.02 * COORDINATE_PRECISION, 10.2 * COORDINATE_PRECISION); FixedPointCoordinate coord4(10.03 * COORDINATE_PRECISION, 10.3 * COORDINATE_PRECISION); FixedPointCoordinate coord5(10.04 * COORDINATE_PRECISION, 10.4 * COORDINATE_PRECISION); - + // Put the test coordinates into the vector for comparison std::vector cmp_coords; cmp_coords.emplace_back(coord1); @@ -34,14 +34,14 @@ BOOST_AUTO_TEST_CASE(geometry_string) BOOST_CHECK_EQUAL(cmp_coords.size(), coords.size()); - for(unsigned i = 0; i < cmp_coords.size(); ++i) + for (unsigned i = 0; i < cmp_coords.size(); ++i) { - const double cmp1_lat = coords.at(i).lat; - const double cmp2_lat = cmp_coords.at(i).lat; + const double cmp1_lat = coords.at(i).lat; + const double cmp2_lat = cmp_coords.at(i).lat; BOOST_CHECK_CLOSE(cmp1_lat, cmp2_lat, 0.0001); - - const double cmp1_lon = coords.at(i).lon; - const double cmp2_lon = cmp_coords.at(i).lon; + + const double cmp1_lon = coords.at(i).lon; + const double cmp2_lon = cmp_coords.at(i).lon; BOOST_CHECK_CLOSE(cmp1_lon, cmp2_lon, 0.0001); } } diff --git a/unit_tests/extractor/graph_compressor.cpp b/unit_tests/extractor/graph_compressor.cpp index 07e3b7ef7..e4cd1ddbb 100644 --- a/unit_tests/extractor/graph_compressor.cpp +++ b/unit_tests/extractor/graph_compressor.cpp @@ -27,7 +27,8 @@ BOOST_AUTO_TEST_CASE(long_road_test) using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { - // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, travel_mode + // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, + // travel_mode {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {1, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {1, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, @@ -35,8 +36,7 @@ BOOST_AUTO_TEST_CASE(long_road_test) {2, 3, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {3, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {3, 4, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, - {4, 3, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT} - }; + {4, 3, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}}; BOOST_ASSERT(edges[0].data.IsCompatibleTo(edges[2].data)); BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[4].data)); @@ -69,7 +69,8 @@ BOOST_AUTO_TEST_CASE(loop_test) using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { - // source, target, distance, edge_id, name_id, access_restricted, forward, backward, roundabout, travel_mode + // source, target, distance, edge_id, name_id, access_restricted, forward, backward, + // roundabout, travel_mode {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {0, 5, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {1, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, @@ -126,7 +127,8 @@ BOOST_AUTO_TEST_CASE(t_intersection) using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { - // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, travel_mode + // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, + // travel_mode {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {1, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {1, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, @@ -164,7 +166,8 @@ BOOST_AUTO_TEST_CASE(street_name_changes) using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { - // source, target, distance, edge_id, name_id, access_restricted, forward, backward, roundabout, travel_mode + // source, target, distance, edge_id, name_id, access_restricted, forward, backward, + // roundabout, travel_mode {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {1, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {1, 2, 1, SPECIAL_EDGEID, 1, false, false, false, true, TRAVEL_MODE_DEFAULT}, @@ -196,9 +199,10 @@ BOOST_AUTO_TEST_CASE(direction_changes) using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { - // source, target, distance, edge_id, name_id, access_restricted, reverse, roundabout, travel_mode + // source, target, distance, edge_id, name_id, access_restricted, reverse, roundabout, + // travel_mode {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, - {1, 0, 1, SPECIAL_EDGEID, 0, false, true, false, true, TRAVEL_MODE_DEFAULT}, + {1, 0, 1, SPECIAL_EDGEID, 0, false, true, false, true, TRAVEL_MODE_DEFAULT}, {1, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, {2, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, }; diff --git a/unit_tests/util/bearing.cpp b/unit_tests/util/bearing.cpp index ef70ce1df..90664b27d 100644 --- a/unit_tests/util/bearing.cpp +++ b/unit_tests/util/bearing.cpp @@ -29,7 +29,6 @@ BOOST_AUTO_TEST_CASE(bearing_range_test) BOOST_CHECK_EQUAL(false, bearing::CheckInBounds(354, 5, 10)); BOOST_CHECK_EQUAL(false, bearing::CheckInBounds(16, 5, 10)); - // Checking other cases of wraparound BOOST_CHECK_EQUAL(true, bearing::CheckInBounds(359, -5, 10)); BOOST_CHECK_EQUAL(false, bearing::CheckInBounds(344, -5, 10)); diff --git a/unit_tests/util/dynamic_graph.cpp b/unit_tests/util/dynamic_graph.cpp index 416da59d0..44f69eb76 100644 --- a/unit_tests/util/dynamic_graph.cpp +++ b/unit_tests/util/dynamic_graph.cpp @@ -27,12 +27,9 @@ BOOST_AUTO_TEST_CASE(find_test) * <-4- */ std::vector input_edges = { - TestInputEdge{0, 1, TestData{1}}, - TestInputEdge{3, 0, TestData{2}}, - TestInputEdge{3, 0, TestData{5}}, - TestInputEdge{3, 4, TestData{3}}, - TestInputEdge{4, 3, TestData{4}} - }; + TestInputEdge{0, 1, TestData{1}}, TestInputEdge{3, 0, TestData{2}}, + TestInputEdge{3, 0, TestData{5}}, TestInputEdge{3, 4, TestData{3}}, + TestInputEdge{4, 3, TestData{4}}}; TestDynamicGraph simple_graph(5, input_edges); auto eit = simple_graph.FindEdge(0, 1); diff --git a/unit_tests/util/static_graph.cpp b/unit_tests/util/static_graph.cpp index f92a7f595..f9b69f629 100644 --- a/unit_tests/util/static_graph.cpp +++ b/unit_tests/util/static_graph.cpp @@ -102,12 +102,9 @@ BOOST_AUTO_TEST_CASE(find_test) * <-4- */ std::vector input_edges = { - TestInputEdge{0, 1, TestData{1}}, - TestInputEdge{3, 0, TestData{2}}, - TestInputEdge{3, 0, TestData{5}}, - TestInputEdge{3, 4, TestData{3}}, - TestInputEdge{4, 3, TestData{4}} - }; + TestInputEdge{0, 1, TestData{1}}, TestInputEdge{3, 0, TestData{2}}, + TestInputEdge{3, 0, TestData{5}}, TestInputEdge{3, 4, TestData{3}}, + TestInputEdge{4, 3, TestData{4}}}; TestStaticGraph simple_graph(5, input_edges); auto eit = simple_graph.FindEdge(0, 1); diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index 3adea4ef5..2d5771621 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -203,7 +203,10 @@ void simple_verify_rtree(RTreeT &rtree, } template -void sampling_verify_rtree(RTreeT &rtree, LinearSearchNN &lsnn, const std::vector& coords, unsigned num_samples) +void sampling_verify_rtree(RTreeT &rtree, + LinearSearchNN &lsnn, + const std::vector &coords, + unsigned num_samples) { std::mt19937 g(RANDOM_SEED); std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT); From a8957d75b992a5120a9b6e15854ade2de3d01d9b Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sun, 3 Jan 2016 19:11:26 +0100 Subject: [PATCH 022/701] Add simple cncc file --- .cncc.style | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .cncc.style diff --git a/.cncc.style b/.cncc.style new file mode 100644 index 000000000..bdece58d9 --- /dev/null +++ b/.cncc.style @@ -0,0 +1,14 @@ +# Kind-specific patterns to check AST nodes against. Both python-clang and +# libclang docs explain CursorKind, with differences in detail. See also: +# - https://github.com/llvm-mirror/clang/blob/aca4fe314a55cacae29e1548cb7bfd2119c6df4c/bindings/python/clang/cindex.py#L599 +# - http://clang.llvm.org/doxygen/group__CINDEX.html#gaaccc432245b4cd9f2d470913f9ef0013 +# - https://docs.python.org/2/library/re.html#regular-expression-syntax + +class_decl: '^([A-Z]+[a-z]+)+$' +struct_decl: '^([A-Z]+[a-z]+)+$' +field_decl: '^[a-z_]+$' +var_decl: '^[a-z]+[a-z0-9_]*$' +parm_decl: '^[a-z]*[a-z0-9_]*$' +namespace: '^[a-z_]*$' +cxx_method: '^([A-Z]+[a-z]+)+$' +function_decl: '^[a-z]+([A-Z]+[a-z]+)*$' From 3568de2c6cdd64af5391e4c7ff54b1c71c67d070 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 11:36:21 +0100 Subject: [PATCH 023/701] Fix missing include --- include/osrm/route_parameters.hpp | 48 +++++++++++++++---------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/include/osrm/route_parameters.hpp b/include/osrm/route_parameters.hpp index 7b72f0334..66b03ea65 100644 --- a/include/osrm/route_parameters.hpp +++ b/include/osrm/route_parameters.hpp @@ -40,55 +40,55 @@ struct RouteParameters { RouteParameters(); - void setZoomLevel(const short level); + void SetZoomLevel(const short level); - void setNumberOfResults(const short number); + void SetNumberOfResults(const short number); - void setAlternateRouteFlag(const bool flag); + void SetAlternateRouteFlag(const bool flag); - void setUTurn(const bool flag); + void SetUTurn(const bool flag); - void setAllUTurns(const bool flag); + void SetAllUTurns(const bool flag); - void setClassify(const bool classify); + void SetClassify(const bool classify); - void setMatchingBeta(const double beta); + void SetMatchingBeta(const double beta); - void setGPSPrecision(const double precision); + void SetGPSPrecision(const double precision); - void setDeprecatedAPIFlag(const std::string &); + void SetDeprecatedAPIFlag(const std::string &); - void setChecksum(const unsigned check_sum); + void SetChecksum(const unsigned check_sum); - void setInstructionFlag(const bool flag); + void SetInstructionFlag(const bool flag); - void setService(const std::string &service); + void SetService(const std::string &service); - void setOutputFormat(const std::string &format); + void SetOutputFormat(const std::string &format); - void setJSONpParameter(const std::string ¶meter); + void SetJSONpParameter(const std::string ¶meter); - void addHint(const std::string &hint); + void AddHint(const std::string &hint); - void addTimestamp(const unsigned timestamp); + void AddTimestamp(const unsigned timestamp); - void addBearing(const boost::fusion::vector> &received_bearing, + void AddBearing(const boost::fusion::vector> &received_bearing, boost::spirit::qi::unused_type unused, bool &pass); - void setLanguage(const std::string &language); + void SetLanguage(const std::string &language); - void setGeometryFlag(const bool flag); + void SetGeometryFlag(const bool flag); - void setCompressionFlag(const bool flag); + void SetCompressionFlag(const bool flag); - void addCoordinate(const boost::fusion::vector &received_coordinates); + void AddCoordinate(const boost::fusion::vector &received_coordinates); - void addDestination(const boost::fusion::vector &received_coordinates); + void AddDestination(const boost::fusion::vector &received_coordinates); - void addSource(const boost::fusion::vector &received_coordinates); + void AddSource(const boost::fusion::vector &received_coordinates); - void getCoordinatesFromGeometry(const std::string &geometry_string); + void SetCoordinatesFromGeometry(const std::string &geometry_string); short zoom_level; bool print_instructions; From b209952ce0798681142296f04766f6f2a5d59c80 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 11:36:45 +0100 Subject: [PATCH 024/701] Fix naming of methodes for RouteParameters --- include/server/api_grammar.hpp | 48 ++++++++++++++++----------------- include/util/routed_options.hpp | 2 +- src/engine/route_parameters.cpp | 48 ++++++++++++++++----------------- 3 files changed, 49 insertions(+), 49 deletions(-) diff --git a/include/server/api_grammar.hpp b/include/server/api_grammar.hpp index d7b7875fd..f4d937c68 100644 --- a/include/server/api_grammar.hpp +++ b/include/server/api_grammar.hpp @@ -12,7 +12,7 @@ template struct APIGrammar : qi::grammar> string[boost::bind(&HandlerT::setService, handler, ::_1)] >> -query; + qi::lit('/') >> string[boost::bind(&HandlerT::SetService, handler, ::_1)] >> -query; query = ('?') >> +(zoom | output | jsonp | checksum | uturns | location_with_options | destination_with_options | source_with_options | cmp | language | instruction | geometry | alt_route | old_API | num_results | @@ -30,56 +30,56 @@ template struct APIGrammar : qi::grammar> -location_options; destination_with_options = destination >> -location_options; zoom = (-qi::lit('&')) >> qi::lit('z') >> '=' >> - qi::short_[boost::bind(&HandlerT::setZoomLevel, handler, ::_1)]; + qi::short_[boost::bind(&HandlerT::SetZoomLevel, handler, ::_1)]; output = (-qi::lit('&')) >> qi::lit("output") >> '=' >> - string[boost::bind(&HandlerT::setOutputFormat, handler, ::_1)]; + string[boost::bind(&HandlerT::SetOutputFormat, handler, ::_1)]; jsonp = (-qi::lit('&')) >> qi::lit("jsonp") >> '=' >> - stringwithPercent[boost::bind(&HandlerT::setJSONpParameter, handler, ::_1)]; + stringwithPercent[boost::bind(&HandlerT::SetJSONpParameter, handler, ::_1)]; checksum = (-qi::lit('&')) >> qi::lit("checksum") >> '=' >> - qi::uint_[boost::bind(&HandlerT::setChecksum, handler, ::_1)]; + qi::uint_[boost::bind(&HandlerT::SetChecksum, handler, ::_1)]; instruction = (-qi::lit('&')) >> qi::lit("instructions") >> '=' >> - qi::bool_[boost::bind(&HandlerT::setInstructionFlag, handler, ::_1)]; + qi::bool_[boost::bind(&HandlerT::SetInstructionFlag, handler, ::_1)]; geometry = (-qi::lit('&')) >> qi::lit("geometry") >> '=' >> - qi::bool_[boost::bind(&HandlerT::setGeometryFlag, handler, ::_1)]; + qi::bool_[boost::bind(&HandlerT::SetGeometryFlag, handler, ::_1)]; cmp = (-qi::lit('&')) >> qi::lit("compression") >> '=' >> - qi::bool_[boost::bind(&HandlerT::setCompressionFlag, handler, ::_1)]; + qi::bool_[boost::bind(&HandlerT::SetCompressionFlag, handler, ::_1)]; location = (-qi::lit('&')) >> qi::lit("loc") >> '=' >> (qi::double_ >> qi::lit(',') >> - qi::double_)[boost::bind(&HandlerT::addCoordinate, handler, ::_1)]; + qi::double_)[boost::bind(&HandlerT::AddCoordinate, handler, ::_1)]; destination = (-qi::lit('&')) >> qi::lit("dst") >> '=' >> (qi::double_ >> qi::lit(',') >> - qi::double_)[boost::bind(&HandlerT::addDestination, handler, ::_1)]; + qi::double_)[boost::bind(&HandlerT::AddDestination, handler, ::_1)]; source = (-qi::lit('&')) >> qi::lit("src") >> '=' >> (qi::double_ >> qi::lit(',') >> - qi::double_)[boost::bind(&HandlerT::addSource, handler, ::_1)]; + qi::double_)[boost::bind(&HandlerT::AddSource, handler, ::_1)]; hint = (-qi::lit('&')) >> qi::lit("hint") >> '=' >> - stringwithDot[boost::bind(&HandlerT::addHint, handler, ::_1)]; + stringwithDot[boost::bind(&HandlerT::AddHint, handler, ::_1)]; timestamp = (-qi::lit('&')) >> qi::lit("t") >> '=' >> - qi::uint_[boost::bind(&HandlerT::addTimestamp, handler, ::_1)]; + qi::uint_[boost::bind(&HandlerT::AddTimestamp, handler, ::_1)]; bearing = (-qi::lit('&')) >> qi::lit("b") >> '=' >> (qi::int_ >> -(qi::lit(',') >> qi::int_ | - qi::attr(10)))[boost::bind(&HandlerT::addBearing, handler, ::_1, ::_2, ::_3)]; + qi::attr(10)))[boost::bind(&HandlerT::AddBearing, handler, ::_1, ::_2, ::_3)]; u = (-qi::lit('&')) >> qi::lit("u") >> '=' >> - qi::bool_[boost::bind(&HandlerT::setUTurn, handler, ::_1)]; + qi::bool_[boost::bind(&HandlerT::SetUTurn, handler, ::_1)]; uturns = (-qi::lit('&')) >> qi::lit("uturns") >> '=' >> - qi::bool_[boost::bind(&HandlerT::setAllUTurns, handler, ::_1)]; + qi::bool_[boost::bind(&HandlerT::SetAllUTurns, handler, ::_1)]; language = (-qi::lit('&')) >> qi::lit("hl") >> '=' >> - string[boost::bind(&HandlerT::setLanguage, handler, ::_1)]; + string[boost::bind(&HandlerT::SetLanguage, handler, ::_1)]; alt_route = (-qi::lit('&')) >> qi::lit("alt") >> '=' >> - qi::bool_[boost::bind(&HandlerT::setAlternateRouteFlag, handler, ::_1)]; + qi::bool_[boost::bind(&HandlerT::SetAlternateRouteFlag, handler, ::_1)]; old_API = (-qi::lit('&')) >> qi::lit("geomformat") >> '=' >> - string[boost::bind(&HandlerT::setDeprecatedAPIFlag, handler, ::_1)]; + string[boost::bind(&HandlerT::SetDeprecatedAPIFlag, handler, ::_1)]; num_results = (-qi::lit('&')) >> qi::lit("num_results") >> '=' >> - qi::short_[boost::bind(&HandlerT::setNumberOfResults, handler, ::_1)]; + qi::short_[boost::bind(&HandlerT::SetNumberOfResults, handler, ::_1)]; matching_beta = (-qi::lit('&')) >> qi::lit("matching_beta") >> '=' >> - qi::float_[boost::bind(&HandlerT::setMatchingBeta, handler, ::_1)]; + qi::float_[boost::bind(&HandlerT::SetMatchingBeta, handler, ::_1)]; gps_precision = (-qi::lit('&')) >> qi::lit("gps_precision") >> '=' >> - qi::float_[boost::bind(&HandlerT::setGPSPrecision, handler, ::_1)]; + qi::float_[boost::bind(&HandlerT::SetGPSPrecision, handler, ::_1)]; classify = (-qi::lit('&')) >> qi::lit("classify") >> '=' >> - qi::bool_[boost::bind(&HandlerT::setClassify, handler, ::_1)]; + qi::bool_[boost::bind(&HandlerT::SetClassify, handler, ::_1)]; locs = (-qi::lit('&')) >> qi::lit("locs") >> '=' >> - stringforPolyline[boost::bind(&HandlerT::getCoordinatesFromGeometry, handler, ::_1)]; + stringforPolyline[boost::bind(&HandlerT::SetCoordinatesFromGeometry, handler, ::_1)]; string = +(qi::char_("a-zA-Z")); stringwithDot = +(qi::char_("a-zA-Z0-9_.-")); diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index 29840b5e7..8085c3aa5 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -1,7 +1,7 @@ #ifndef ROUTED_OPTIONS_HPP #define ROUTED_OPTIONS_HPP -#include "util/version.hpp" +#include "util/ini_file.hpp" #include "util/version.hpp" #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index 7138362fd..c0c1290fb 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -14,7 +14,7 @@ RouteParameters::RouteParameters() { } -void RouteParameters::setZoomLevel(const short level) +void RouteParameters::SetZoomLevel(const short level) { if (18 >= level && 0 <= level) { @@ -22,7 +22,7 @@ void RouteParameters::setZoomLevel(const short level) } } -void RouteParameters::setNumberOfResults(const short number) +void RouteParameters::SetNumberOfResults(const short number) { if (number > 0 && number <= 100) { @@ -30,16 +30,16 @@ void RouteParameters::setNumberOfResults(const short number) } } -void RouteParameters::setAlternateRouteFlag(const bool flag) { alternate_route = flag; } +void RouteParameters::SetAlternateRouteFlag(const bool flag) { alternate_route = flag; } -void RouteParameters::setUTurn(const bool flag) +void RouteParameters::SetUTurn(const bool flag) { // the API grammar should make sure this never happens BOOST_ASSERT(!uturns.empty()); uturns.back() = flag; } -void RouteParameters::setAllUTurns(const bool flag) +void RouteParameters::SetAllUTurns(const bool flag) { // if the flag flips the default, then we erase everything. if (flag) @@ -50,28 +50,28 @@ void RouteParameters::setAllUTurns(const bool flag) } } -void RouteParameters::setDeprecatedAPIFlag(const std::string & /*unused*/) { deprecatedAPI = true; } +void RouteParameters::SetDeprecatedAPIFlag(const std::string & /*unused*/) { deprecatedAPI = true; } -void RouteParameters::setChecksum(const unsigned sum) { check_sum = sum; } +void RouteParameters::SetChecksum(const unsigned sum) { check_sum = sum; } -void RouteParameters::setInstructionFlag(const bool flag) { print_instructions = flag; } +void RouteParameters::SetInstructionFlag(const bool flag) { print_instructions = flag; } -void RouteParameters::setService(const std::string &service_string) { service = service_string; } +void RouteParameters::SetService(const std::string &service_string) { service = service_string; } -void RouteParameters::setClassify(const bool flag) { classify = flag; } +void RouteParameters::SetClassify(const bool flag) { classify = flag; } -void RouteParameters::setMatchingBeta(const double beta) { matching_beta = beta; } +void RouteParameters::SetMatchingBeta(const double beta) { matching_beta = beta; } -void RouteParameters::setGPSPrecision(const double precision) { gps_precision = precision; } +void RouteParameters::SetGPSPrecision(const double precision) { gps_precision = precision; } -void RouteParameters::setOutputFormat(const std::string &format) { output_format = format; } +void RouteParameters::SetOutputFormat(const std::string &format) { output_format = format; } -void RouteParameters::setJSONpParameter(const std::string ¶meter) +void RouteParameters::SetJSONpParameter(const std::string ¶meter) { jsonp_parameter = parameter; } -void RouteParameters::addHint(const std::string &hint) +void RouteParameters::AddHint(const std::string &hint) { hints.resize(coordinates.size()); if (!hints.empty()) @@ -80,7 +80,7 @@ void RouteParameters::addHint(const std::string &hint) } } -void RouteParameters::addTimestamp(const unsigned timestamp) +void RouteParameters::AddTimestamp(const unsigned timestamp) { timestamps.resize(coordinates.size()); if (!timestamps.empty()) @@ -89,7 +89,7 @@ void RouteParameters::addTimestamp(const unsigned timestamp) } } -void RouteParameters::addBearing( +void RouteParameters::AddBearing( const boost::fusion::vector> &received_bearing, boost::spirit::qi::unused_type /* unused */, bool &pass) @@ -105,16 +105,16 @@ void RouteParameters::addBearing( pass = true; } -void RouteParameters::setLanguage(const std::string &language_string) +void RouteParameters::SetLanguage(const std::string &language_string) { language = language_string; } -void RouteParameters::setGeometryFlag(const bool flag) { geometry = flag; } +void RouteParameters::SetGeometryFlag(const bool flag) { geometry = flag; } -void RouteParameters::setCompressionFlag(const bool flag) { compression = flag; } +void RouteParameters::SetCompressionFlag(const bool flag) { compression = flag; } -void RouteParameters::addCoordinate( +void RouteParameters::AddCoordinate( const boost::fusion::vector &received_coordinates) { coordinates.emplace_back( @@ -125,7 +125,7 @@ void RouteParameters::addCoordinate( uturns.push_back(uturn_default); } -void RouteParameters::addDestination( +void RouteParameters::AddDestination( const boost::fusion::vector &received_coordinates) { coordinates.emplace_back( @@ -136,7 +136,7 @@ void RouteParameters::addDestination( uturns.push_back(uturn_default); } -void RouteParameters::addSource(const boost::fusion::vector &received_coordinates) +void RouteParameters::AddSource(const boost::fusion::vector &received_coordinates) { coordinates.emplace_back( static_cast(COORDINATE_PRECISION * boost::fusion::at_c<0>(received_coordinates)), @@ -146,7 +146,7 @@ void RouteParameters::addSource(const boost::fusion::vector &rec uturns.push_back(uturn_default); } -void RouteParameters::getCoordinatesFromGeometry(const std::string &geometry_string) +void RouteParameters::SetCoordinatesFromGeometry(const std::string &geometry_string) { PolylineCompressor pc; coordinates = pc.decode_string(geometry_string); From ccd3872bf1218282731dac0ac04669f437c3876f Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 11:44:23 +0100 Subject: [PATCH 025/701] Fix naming in ScriptingEnvironment --- include/extractor/scripting_environment.hpp | 4 ++-- src/extractor/extractor.cpp | 6 +++--- src/extractor/restriction_parser.cpp | 7 +++---- src/extractor/scripting_environment.cpp | 14 +++++++------- 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/include/extractor/scripting_environment.hpp b/include/extractor/scripting_environment.hpp index 33d672340..3b1ff785a 100644 --- a/include/extractor/scripting_environment.hpp +++ b/include/extractor/scripting_environment.hpp @@ -21,10 +21,10 @@ class ScriptingEnvironment ScriptingEnvironment() = delete; explicit ScriptingEnvironment(const std::string &file_name); - lua_State *get_lua_state(); + lua_State *GetLuaState(); private: - void init_lua_state(lua_State *lua_state); + void InitLuaState(lua_State *lua_state); std::mutex init_mutex; std::string file_name; tbb::enumerable_thread_specific> script_contexts; diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 40ac02f3c..4038b3ec9 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -99,7 +99,7 @@ int extractor::run() SimpleLogger().Write() << "Parsing in progress.."; TIMER_START(parsing); - lua_State *segment_state = scripting_environment.get_lua_state(); + lua_State *segment_state = scripting_environment.GetLuaState(); if (lua_function_exists(segment_state, "source_function")) { @@ -135,7 +135,7 @@ int extractor::run() tbb::concurrent_vector> resulting_restrictions; // setup restriction parser - const RestrictionParser restriction_parser(scripting_environment.get_lua_state()); + const RestrictionParser restriction_parser(scripting_environment.GetLuaState()); while (const osmium::memory::Buffer buffer = reader.read()) { @@ -158,7 +158,7 @@ int extractor::run() { ExtractionNode result_node; ExtractionWay result_way; - lua_State *local_state = scripting_environment.get_lua_state(); + lua_State *local_state = scripting_environment.GetLuaState(); for (auto x = range.begin(), end = range.end(); x != end; ++x) { diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index 6aa5bd0c6..bb631894c 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -19,9 +19,8 @@ #include #include -namespace -{ -int lua_error_callback(lua_State *lua_state) +namespace { +int luaErrorCallback(lua_State *lua_state) { std::string error_msg = lua_tostring(lua_state, -1); throw osrm::exception("ERROR occurred in profile script:\n" + error_msg); @@ -60,7 +59,7 @@ void RestrictionParser::ReadRestrictionExceptions(lua_State *lua_state) { if (lua_function_exists(lua_state, "get_exceptions")) { - luabind::set_pcall_callback(&lua_error_callback); + luabind::set_pcall_callback(&luaErrorCallback); // get list of turn restriction exceptions luabind::call_function(lua_state, "get_exceptions", boost::ref(restriction_exceptions)); diff --git a/src/extractor/scripting_environment.cpp b/src/extractor/scripting_environment.cpp index 14198d8ae..f4fae0da3 100644 --- a/src/extractor/scripting_environment.cpp +++ b/src/extractor/scripting_environment.cpp @@ -26,10 +26,10 @@ auto get_value_by_key(T const &object, const char *key) -> decltype(object.get_v return object.get_value_by_key(key, ""); } -int lua_error_callback(lua_State *L) // This is so I can use my own function as an -// exception handler, pcall_log() +// Error handler +int luaErrorCallback(lua_State *state) { - std::string error_msg = lua_tostring(L, -1); + std::string error_msg = lua_tostring(state, -1); std::ostringstream error_stream; error_stream << error_msg; throw osrm::exception("ERROR occurred in profile script:\n" + error_stream.str()); @@ -41,7 +41,7 @@ ScriptingEnvironment::ScriptingEnvironment(const std::string &file_name) : file_ SimpleLogger().Write() << "Using script " << file_name; } -void ScriptingEnvironment::init_lua_state(lua_State *lua_state) +void ScriptingEnvironment::InitLuaState(lua_State *lua_state) { typedef double (osmium::Location::*location_member_ptr_type)() const; @@ -126,7 +126,7 @@ void ScriptingEnvironment::init_lua_state(lua_State *lua_state) } } -lua_State *ScriptingEnvironment::get_lua_state() +lua_State *ScriptingEnvironment::GetLuaState() { std::lock_guard lock(init_mutex); bool initialized = false; @@ -135,9 +135,9 @@ lua_State *ScriptingEnvironment::get_lua_state() { std::shared_ptr state(luaL_newstate(), lua_close); ref = state; - init_lua_state(ref.get()); + InitLuaState(ref.get()); } - luabind::set_pcall_callback(&lua_error_callback); + luabind::set_pcall_callback(&luaErrorCallback); return ref.get(); } From 5b0e2e487a98a83a32459f4adc77c17783ac346a Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 12:11:02 +0100 Subject: [PATCH 026/701] Fix naming in components tool --- src/tools/components.cpp | 52 ++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/src/tools/components.cpp b/src/tools/components.cpp index c7bf4fe2b..0acec14a7 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -40,7 +40,7 @@ struct TarjanEdgeData using TarjanGraph = StaticGraph; using TarjanEdge = TarjanGraph::InputEdge; -void DeleteFileIfExists(const std::string &file_name) +void deleteFileIfExists(const std::string &file_name) { if (boost::filesystem::exists(file_name)) { @@ -49,7 +49,7 @@ void DeleteFileIfExists(const std::string &file_name) } } -std::size_t LoadGraph(const char *path, +std::size_t loadGraph(const char *path, std::vector &coordinate_list, std::vector &graph_edge_list) { @@ -110,7 +110,7 @@ int main(int argc, char *argv[]) } std::vector graph_edge_list; - auto number_of_nodes = LoadGraph(argv[1], coordinate_list, graph_edge_list); + auto number_of_nodes = loadGraph(argv[1], coordinate_list, graph_edge_list); tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); const auto graph = std::make_shared(number_of_nodes, graph_edge_list); @@ -129,34 +129,34 @@ int main(int argc, char *argv[]) TIMER_START(SCC_RUN_SETUP); // remove files from previous run if exist - DeleteFileIfExists("component.dbf"); - DeleteFileIfExists("component.shx"); - DeleteFileIfExists("component.shp"); + deleteFileIfExists("component.dbf"); + deleteFileIfExists("component.shx"); + deleteFileIfExists("component.shp"); Percent percentage(graph->GetNumberOfNodes()); OGRRegisterAll(); - const char *pszDriverName = "ESRI Shapefile"; - OGRSFDriver *poDriver = - OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); - if (nullptr == poDriver) + const char *psz_driver_name = "ESRI Shapefile"; + auto *po_driver = + OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(psz_driver_name); + if (nullptr == po_driver) { throw osrm::exception("ESRI Shapefile driver not available"); } - OGRDataSource *poDS = poDriver->CreateDataSource("component.shp", nullptr); + auto *po_datasource = po_driver->CreateDataSource("component.shp", nullptr); - if (nullptr == poDS) + if (nullptr == po_datasource) { throw osrm::exception("Creation of output file failed"); } - OGRSpatialReference *poSRS = new OGRSpatialReference(); - poSRS->importFromEPSG(4326); + auto *po_srs = new OGRSpatialReference(); + po_srs->importFromEPSG(4326); - OGRLayer *poLayer = poDS->CreateLayer("component", poSRS, wkbLineString, nullptr); + auto *po_layer = po_datasource->CreateLayer("component", po_srs, wkbLineString, nullptr); - if (nullptr == poLayer) + if (nullptr == po_layer) { throw osrm::exception("Layer creation failed."); } @@ -192,26 +192,26 @@ int main(int argc, char *argv[]) // edges that end on bollard nodes may actually be in two distinct components if (size_of_containing_component < 1000) { - OGRLineString lineString; - lineString.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION, - coordinate_list[source].lat / COORDINATE_PRECISION); - lineString.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION, + OGRLineString line_string; + line_string.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION, + coordinate_list[source].lat / COORDINATE_PRECISION); + line_string.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION, coordinate_list[target].lat / COORDINATE_PRECISION); - OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn()); + OGRFeature *po_feature = OGRFeature::CreateFeature(po_layer->GetLayerDefn()); - poFeature->SetGeometry(&lineString); - if (OGRERR_NONE != poLayer->CreateFeature(poFeature)) + po_feature->SetGeometry(&line_string); + if (OGRERR_NONE != po_layer->CreateFeature(po_feature)) { throw osrm::exception("Failed to create feature in shapefile."); } - OGRFeature::DestroyFeature(poFeature); + OGRFeature::DestroyFeature(po_feature); } } } } - OGRSpatialReference::DestroySpatialReference(poSRS); - OGRDataSource::DestroyDataSource(poDS); + OGRSpatialReference::DestroySpatialReference(po_srs); + OGRDataSource::DestroyDataSource(po_datasource); TIMER_STOP(SCC_OUTPUT); SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. << "s"; From 9956988938625400960b650e32a6b8129a144dc6 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 12:15:38 +0100 Subject: [PATCH 027/701] Fix naming in datstore --- src/tools/datastore.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/tools/datastore.cpp b/src/tools/datastore.cpp index 262e095ce..899fba4c7 100644 --- a/src/tools/datastore.cpp +++ b/src/tools/datastore.cpp @@ -37,7 +37,7 @@ using QueryGraph = StaticGraph; #include // delete a shared memory region. report warning if it could not be deleted -void delete_region(const SharedDataType region) +void deleteRegion(const SharedDataType region) { if (SharedMemory::RegionExists(region) && !SharedMemory::Remove(region)) { @@ -552,8 +552,8 @@ int main(const int argc, const char *argv[]) try data_timestamp_ptr->layout = layout_region; data_timestamp_ptr->data = data_region; data_timestamp_ptr->timestamp += 1; - delete_region(previous_data_region); - delete_region(previous_layout_region); + deleteRegion(previous_data_region); + deleteRegion(previous_layout_region); SimpleLogger().Write() << "all data loaded"; shared_layout_ptr->PrintInformation(); From b35254ec78751a9e50356434562f90903ce0b832 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 12:15:51 +0100 Subject: [PATCH 028/701] Fix naming in io-benchmark --- src/tools/io-benchmark.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp index 64bc3dd53..b29e78e85 100644 --- a/src/tools/io-benchmark.cpp +++ b/src/tools/io-benchmark.cpp @@ -27,7 +27,7 @@ struct Statistics double min, max, med, mean, dev; }; -void RunStatistics(std::vector &timings_vector, Statistics &stats) +void runStatistics(std::vector &timings_vector, Statistics &stats) { std::sort(timings_vector.begin(), timings_vector.end()); stats.min = timings_vector.front(); @@ -220,7 +220,7 @@ int main(int argc, char *argv[]) random_csv << i << ", " << timing_results_raw_random[i] << std::endl; } random_csv.close(); - RunStatistics(timing_results_raw_random, stats); + runStatistics(timing_results_raw_random, stats); SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed << "min: " << stats.min << "ms, " @@ -290,7 +290,7 @@ int main(int argc, char *argv[]) seq_csv << i << ", " << timing_results_raw_seq[i] << std::endl; } seq_csv.close(); - RunStatistics(timing_results_raw_seq, stats); + runStatistics(timing_results_raw_seq, stats); SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed << "min: " << stats.min << "ms, " << "mean: " << stats.mean << "ms, " From befb66775967c2c6918b1fead8166d470ca06c35 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 12:40:53 +0100 Subject: [PATCH 029/701] Fix naming of routed --- src/tools/routed.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index 90b9637fb..4890fa694 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -65,21 +65,21 @@ int main(int argc, const char *argv[]) try #ifdef __linux__ struct MemoryLocker final { - explicit MemoryLocker(bool shouldLock_) : shouldLock(shouldLock_) + explicit MemoryLocker(bool should_lock) : should_lock(should_lock) { - if (shouldLock && -1 == mlockall(MCL_CURRENT | MCL_FUTURE)) + if (should_lock && -1 == mlockall(MCL_CURRENT | MCL_FUTURE)) { - couldLock = false; + could_lock = false; SimpleLogger().Write(logWARNING) << "memory could not be locked to RAM"; } } ~MemoryLocker() { - if (shouldLock && couldLock) + if (should_lock && could_lock) (void)munlockall(); } - bool shouldLock = false, couldLock = true; - } memoryLocker(lib_config.use_shared_memory); + bool should_lock = false, could_lock = true; + } memory_locker(lib_config.use_shared_memory); #endif SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; From e8bc69aa013939d89cc584d484fdc7235f12e2cf Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 12:46:25 +0100 Subject: [PATCH 030/701] Fix naming in springclean --- src/tools/springclean.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/tools/springclean.cpp b/src/tools/springclean.cpp index 40c0f8065..2535478a5 100644 --- a/src/tools/springclean.cpp +++ b/src/tools/springclean.cpp @@ -5,7 +5,7 @@ #include "util/version.hpp" #include "util/simple_logger.hpp" -void delete_region(const SharedDataType region) +void deleteRegion(const SharedDataType region) { if (SharedMemory::RegionExists(region) && !SharedMemory::Remove(region)) { @@ -38,11 +38,11 @@ void delete_region(const SharedDataType region) void springclean() { SimpleLogger().Write() << "spring-cleaning all shared memory regions"; - delete_region(DATA_1); - delete_region(LAYOUT_1); - delete_region(DATA_2); - delete_region(LAYOUT_2); - delete_region(CURRENT_REGIONS); + deleteRegion(DATA_1); + deleteRegion(LAYOUT_1); + deleteRegion(DATA_2); + deleteRegion(LAYOUT_2); + deleteRegion(CURRENT_REGIONS); } int main() From 4312013552df2bdeca8bb7bddf144d27725fbe8a Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 13:30:03 +0100 Subject: [PATCH 031/701] Fix naming in coordinate_calculation --- include/engine/descriptors/gpx_descriptor.hpp | 15 ++- include/engine/geospatial_query.hpp | 2 +- include/engine/plugins/match.hpp | 4 +- .../routing_algorithms/map_matching.hpp | 2 +- .../routing_algorithms/routing_base.hpp | 4 +- include/util/coordinate_calculation.hpp | 58 +++++---- include/util/rectangle.hpp | 32 ++--- include/util/static_rtree.hpp | 2 +- .../descriptors/description_factory.cpp | 2 +- src/extractor/edge_based_graph_factory.cpp | 4 +- src/extractor/extraction_containers.cpp | 2 +- src/tools/components.cpp | 2 +- src/util/coordinate_calculation.cpp | 115 ++++++++---------- unit_tests/util/coordinate.cpp | 4 +- unit_tests/util/static_rtree.cpp | 24 ++-- 15 files changed, 137 insertions(+), 135 deletions(-) diff --git a/include/engine/descriptors/gpx_descriptor.hpp b/include/engine/descriptors/gpx_descriptor.hpp index 46be3abf2..b4bd06756 100644 --- a/include/engine/descriptors/gpx_descriptor.hpp +++ b/include/engine/descriptors/gpx_descriptor.hpp @@ -3,17 +3,28 @@ #include "engine/descriptors/descriptor_base.hpp" #include "util/xml_renderer.hpp" +#include "util/string_util.hpp" #include "osrm/json_container.hpp" #include + + template class GPXDescriptor final : public BaseDescriptor { private: DescriptorConfig config; DataFacadeT *facade; + template + void fixedIntToString(const int value, std::string &output) + { + char buffer[digits]; + buffer[digits-1] = 0; // zero termination + output = printInt<11, 6>(buffer, value); + } + void AddRoutePoint(const FixedPointCoordinate &coordinate, osrm::json::Array &json_route) { osrm::json::Object json_lat; @@ -22,10 +33,10 @@ template class GPXDescriptor final : public BaseDescriptor(coordinate.lat, tmp); json_lat.values["_lat"] = tmp; - coordinate_calculation::lat_or_lon_to_string(coordinate.lon, tmp); + fixedIntToString<12>(coordinate.lon, tmp); json_lon.values["_lon"] = tmp; json_row.values.push_back(json_lat); diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index a236df18b..fddacf2ca 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -133,7 +133,7 @@ template class GeospatialQuery { FixedPointCoordinate point_on_segment; double ratio; - const auto current_perpendicular_distance = coordinate_calculation::perpendicular_distance( + const auto current_perpendicular_distance = coordinate_calculation::perpendicularDistance( coordinates->at(data.u), coordinates->at(data.v), input_coordinate, point_on_segment, ratio); diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 2cb178530..2f5dc688d 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -76,7 +76,7 @@ template class MapMatchingPlugin : public BasePlugin double query_radius = 10 * gps_precision; double last_distance = - coordinate_calculation::haversine_distance(input_coords[0], input_coords[1]); + coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]); sub_trace_lengths.resize(input_coords.size()); sub_trace_lengths[0] = 0; @@ -85,7 +85,7 @@ template class MapMatchingPlugin : public BasePlugin bool allow_uturn = false; if (0 < current_coordinate) { - last_distance = coordinate_calculation::haversine_distance( + last_distance = coordinate_calculation::haversineDistance( input_coords[current_coordinate - 1], input_coords[current_coordinate]); sub_trace_lengths[current_coordinate] += diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 1fec8e323..905dc611a 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -196,7 +196,7 @@ class MapMatching final : public BasicRoutingInterface(0u, prev_viterbi.size())) diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index a8678d167..86ae3bea1 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -648,11 +648,11 @@ template class BasicRoutingInterface for (const auto &p : unpacked_path) { current_coordinate = facade->GetCoordinateOfNode(p.node); - distance += coordinate_calculation::haversine_distance(previous_coordinate, + distance += coordinate_calculation::haversineDistance(previous_coordinate, current_coordinate); previous_coordinate = current_coordinate; } - distance += coordinate_calculation::haversine_distance(previous_coordinate, + distance += coordinate_calculation::haversineDistance(previous_coordinate, target_phantom.location); } return distance; diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index dc4092005..7faabdbc6 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -8,44 +8,42 @@ struct FixedPointCoordinate; namespace coordinate_calculation { -double haversine_distance(const int lat1, const int lon1, const int lat2, const int lon2); +double haversineDistance(const int lat1, const int lon1, const int lat2, const int lon2); -double haversine_distance(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate); +double haversineDistance(const FixedPointCoordinate &first_coordinate, + const FixedPointCoordinate &second_coordinate); -double great_circle_distance(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate); +double greatCircleDistance(const FixedPointCoordinate &first_coordinate, + const FixedPointCoordinate &second_coordinate); -double great_circle_distance(const int lat1, const int lon1, const int lat2, const int lon2); +double greatCircleDistance(const int lat1, const int lon1, const int lat2, const int lon2); -void lat_or_lon_to_string(const int value, std::string &output); +double perpendicularDistance(const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location); -double perpendicular_distance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location); +double perpendicularDistance(const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + FixedPointCoordinate &nearest_location, + double &ratio); -double perpendicular_distance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - FixedPointCoordinate &nearest_location, - double &ratio); +double +perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + const std::pair &projected_coordinate); -double perpendicular_distance_from_projected_coordinate( - const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate); +double +perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + const std::pair &projected_coordinate, + FixedPointCoordinate &nearest_location, + double &ratio); -double perpendicular_distance_from_projected_coordinate( - const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate, - FixedPointCoordinate &nearest_location, - double &ratio); - -double deg_to_rad(const double degree); -double rad_to_deg(const double radian); +double degToRad(const double degree); +double radToDeg(const double radian); double bearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); diff --git a/include/util/rectangle.hpp b/include/util/rectangle.hpp index 1d123a05a..b8977dfc3 100644 --- a/include/util/rectangle.hpp +++ b/include/util/rectangle.hpp @@ -94,35 +94,35 @@ struct RectangleInt2D switch (d) { case NORTH: - min_dist = coordinate_calculation::great_circle_distance( + min_dist = coordinate_calculation::greatCircleDistance( location, FixedPointCoordinate(max_lat, location.lon)); break; case SOUTH: - min_dist = coordinate_calculation::great_circle_distance( + min_dist = coordinate_calculation::greatCircleDistance( location, FixedPointCoordinate(min_lat, location.lon)); break; case WEST: - min_dist = coordinate_calculation::great_circle_distance( + min_dist = coordinate_calculation::greatCircleDistance( location, FixedPointCoordinate(location.lat, min_lon)); break; case EAST: - min_dist = coordinate_calculation::great_circle_distance( + min_dist = coordinate_calculation::greatCircleDistance( location, FixedPointCoordinate(location.lat, max_lon)); break; case NORTH_EAST: - min_dist = coordinate_calculation::great_circle_distance( + min_dist = coordinate_calculation::greatCircleDistance( location, FixedPointCoordinate(max_lat, max_lon)); break; case NORTH_WEST: - min_dist = coordinate_calculation::great_circle_distance( + min_dist = coordinate_calculation::greatCircleDistance( location, FixedPointCoordinate(max_lat, min_lon)); break; case SOUTH_EAST: - min_dist = coordinate_calculation::great_circle_distance( + min_dist = coordinate_calculation::greatCircleDistance( location, FixedPointCoordinate(min_lat, max_lon)); break; case SOUTH_WEST: - min_dist = coordinate_calculation::great_circle_distance( + min_dist = coordinate_calculation::greatCircleDistance( location, FixedPointCoordinate(min_lat, min_lon)); break; default: @@ -145,23 +145,23 @@ struct RectangleInt2D min_max_dist = std::min( min_max_dist, - std::max(coordinate_calculation::great_circle_distance(location, upper_left), - coordinate_calculation::great_circle_distance(location, upper_right))); + std::max(coordinate_calculation::greatCircleDistance(location, upper_left), + coordinate_calculation::greatCircleDistance(location, upper_right))); min_max_dist = std::min( min_max_dist, - std::max(coordinate_calculation::great_circle_distance(location, upper_right), - coordinate_calculation::great_circle_distance(location, lower_right))); + std::max(coordinate_calculation::greatCircleDistance(location, upper_right), + coordinate_calculation::greatCircleDistance(location, lower_right))); min_max_dist = std::min(min_max_dist, - std::max(coordinate_calculation::great_circle_distance(location, lower_right), - coordinate_calculation::great_circle_distance(location, lower_left))); + std::max(coordinate_calculation::greatCircleDistance(location, lower_right), + coordinate_calculation::greatCircleDistance(location, lower_left))); min_max_dist = std::min(min_max_dist, - std::max(coordinate_calculation::great_circle_distance(location, lower_left), - coordinate_calculation::great_circle_distance(location, upper_left))); + std::max(coordinate_calculation::greatCircleDistance(location, lower_left), + coordinate_calculation::greatCircleDistance(location, upper_left))); return min_max_dist; } diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 57444f549..ef8f9e839 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -415,7 +415,7 @@ class StaticRTree { auto ¤t_edge = current_leaf_node.objects[i]; const float current_perpendicular_distance = - coordinate_calculation::perpendicular_distance_from_projected_coordinate( + coordinate_calculation::perpendicularDistanceFromProjectedCoordinate( m_coordinate_list->at(current_edge.u), m_coordinate_list->at(current_edge.v), input_coordinate, projected_coordinate); // distance must be non-negative diff --git a/src/engine/descriptors/description_factory.cpp b/src/engine/descriptors/description_factory.cpp index 4c4f5696a..9e6fafa7e 100644 --- a/src/engine/descriptors/description_factory.cpp +++ b/src/engine/descriptors/description_factory.cpp @@ -100,7 +100,7 @@ void DescriptionFactory::Run(const unsigned zoom_level) { // move down names by one, q&d hack path_description[i - 1].name_id = path_description[i].name_id; - path_description[i].length = coordinate_calculation::great_circle_distance( + path_description[i].length = coordinate_calculation::greatCircleDistance( path_description[i - 1].location, path_description[i].location); } diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index b357ccb65..896f84e7f 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -541,7 +541,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( const QueryNode &from = m_node_info_list[previous]; const QueryNode &to = m_node_info_list[target_node.first]; const double segment_length = - coordinate_calculation::great_circle_distance(from.lat, from.lon, + coordinate_calculation::greatCircleDistance(from.lat, from.lon, to.lat, to.lon); edge_segment_file.write(reinterpret_cast(&to.node_id), @@ -559,7 +559,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( static const unsigned node_count = 2; const QueryNode from = m_node_info_list[node_u]; const QueryNode to = m_node_info_list[node_v]; - const double segment_length = coordinate_calculation::great_circle_distance( + const double segment_length = coordinate_calculation::greatCircleDistance( from.lat, from.lon, to.lat, to.lon); edge_segment_file.write(reinterpret_cast(&node_count), sizeof(node_count)); diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 994a6c93f..80fe2ac5f 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -302,7 +302,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) BOOST_ASSERT(edge_iterator->source_coordinate.lat != std::numeric_limits::min()); BOOST_ASSERT(edge_iterator->source_coordinate.lon != std::numeric_limits::min()); - const double distance = coordinate_calculation::great_circle_distance( + const double distance = coordinate_calculation::greatCircleDistance( edge_iterator->source_coordinate.lat, edge_iterator->source_coordinate.lon, node_iterator->lat, node_iterator->lon); diff --git a/src/tools/components.cpp b/src/tools/components.cpp index 0acec14a7..411fca66d 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -177,7 +177,7 @@ int main(int argc, char *argv[]) if (source < target || SPECIAL_EDGEID == graph->FindEdge(target, source)) { total_network_length += - 100 * coordinate_calculation::great_circle_distance( + 100 * coordinate_calculation::greatCircleDistance( coordinate_list[source].lat, coordinate_list[source].lon, coordinate_list[target].lat, coordinate_list[target].lon); diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index d52172ba2..6213ba7e6 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -22,7 +22,7 @@ constexpr static const double earth_radius = 6372797.560856; namespace coordinate_calculation { -double haversine_distance(const int lat1, const int lon1, const int lat2, const int lon2) +double haversineDistance(const int lat1, const int lon1, const int lat2, const int lon2) { BOOST_ASSERT(lat1 != std::numeric_limits::min()); BOOST_ASSERT(lon1 != std::numeric_limits::min()); @@ -38,30 +38,30 @@ double haversine_distance(const int lat1, const int lon1, const int lat2, const const double dlat2 = lt2 * (RAD); const double dlong2 = ln2 * (RAD); - const double dLong = dlong1 - dlong2; - const double dLat = dlat1 - dlat2; + const double dlong = dlong1 - dlong2; + const double dlat = dlat1 - dlat2; - const double aHarv = std::pow(std::sin(dLat / 2.0), 2.0) + - std::cos(dlat1) * std::cos(dlat2) * std::pow(std::sin(dLong / 2.), 2); - const double cHarv = 2. * std::atan2(std::sqrt(aHarv), std::sqrt(1.0 - aHarv)); - return earth_radius * cHarv; + const double aharv = std::pow(std::sin(dlat / 2.0), 2.0) + + std::cos(dlat1) * std::cos(dlat2) * std::pow(std::sin(dlong / 2.), 2); + const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv)); + return earth_radius * charv; } -double haversine_distance(const FixedPointCoordinate &coordinate_1, - const FixedPointCoordinate &coordinate_2) +double haversineDistance(const FixedPointCoordinate &coordinate_1, + const FixedPointCoordinate &coordinate_2) { - return haversine_distance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, - coordinate_2.lon); + return haversineDistance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, + coordinate_2.lon); } -double great_circle_distance(const FixedPointCoordinate &coordinate_1, - const FixedPointCoordinate &coordinate_2) +double greatCircleDistance(const FixedPointCoordinate &coordinate_1, + const FixedPointCoordinate &coordinate_2) { - return great_circle_distance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, - coordinate_2.lon); + return greatCircleDistance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, + coordinate_2.lon); } -double great_circle_distance(const int lat1, const int lon1, const int lat2, const int lon2) +double greatCircleDistance(const int lat1, const int lon1, const int lat2, const int lon2) { BOOST_ASSERT(lat1 != std::numeric_limits::min()); BOOST_ASSERT(lon1 != std::numeric_limits::min()); @@ -78,51 +78,51 @@ double great_circle_distance(const int lat1, const int lon1, const int lat2, con return std::hypot(x_value, y_value) * earth_radius; } -double perpendicular_distance(const FixedPointCoordinate &source_coordinate, - const FixedPointCoordinate &target_coordinate, - const FixedPointCoordinate &query_location) +double perpendicularDistance(const FixedPointCoordinate &source_coordinate, + const FixedPointCoordinate &target_coordinate, + const FixedPointCoordinate &query_location) { double ratio; FixedPointCoordinate nearest_location; - return perpendicular_distance(source_coordinate, target_coordinate, query_location, - nearest_location, ratio); + return perpendicularDistance(source_coordinate, target_coordinate, query_location, + nearest_location, ratio); } -double perpendicular_distance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - FixedPointCoordinate &nearest_location, - double &ratio) +double perpendicularDistance(const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + FixedPointCoordinate &nearest_location, + double &ratio) { - return perpendicular_distance_from_projected_coordinate( + return perpendicularDistanceFromProjectedCoordinate( segment_source, segment_target, query_location, {mercator::lat2y(query_location.lat / COORDINATE_PRECISION), query_location.lon / COORDINATE_PRECISION}, nearest_location, ratio); } -double perpendicular_distance_from_projected_coordinate( - const FixedPointCoordinate &source_coordinate, - const FixedPointCoordinate &target_coordinate, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate) +double +perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &source_coordinate, + const FixedPointCoordinate &target_coordinate, + const FixedPointCoordinate &query_location, + const std::pair &projected_coordinate) { double ratio; FixedPointCoordinate nearest_location; - return perpendicular_distance_from_projected_coordinate(source_coordinate, target_coordinate, - query_location, projected_coordinate, - nearest_location, ratio); + return perpendicularDistanceFromProjectedCoordinate(source_coordinate, target_coordinate, + query_location, projected_coordinate, + nearest_location, ratio); } -double perpendicular_distance_from_projected_coordinate( - const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate, - FixedPointCoordinate &nearest_location, - double &ratio) +double +perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment_source, + const FixedPointCoordinate &segment_target, + const FixedPointCoordinate &query_location, + const std::pair &projected_coordinate, + FixedPointCoordinate &nearest_location, + double &ratio) { BOOST_ASSERT(query_location.is_valid()); @@ -133,7 +133,7 @@ double perpendicular_distance_from_projected_coordinate( const double b = segment_source.lon / COORDINATE_PRECISION; const double c = mercator::lat2y(segment_target.lat / COORDINATE_PRECISION); const double d = segment_target.lon / COORDINATE_PRECISION; - double p, q /*,mX*/, nY; + double p, q /*,mX*/, new_y; if (std::abs(a - c) > std::numeric_limits::epsilon()) { const double m = (d - b) / (c - a); // slope @@ -146,16 +146,16 @@ double perpendicular_distance_from_projected_coordinate( p = c; q = y; } - nY = (d * p - c * q) / (a * d - b * c); + new_y = (d * p - c * q) / (a * d - b * c); // discretize the result to coordinate precision. it's a hack! - if (std::abs(nY) < (1.0 / COORDINATE_PRECISION)) + if (std::abs(new_y) < (1.0 / COORDINATE_PRECISION)) { - nY = 0.0; + new_y = 0.0; } // compute ratio - ratio = static_cast((p - nY * a) / + ratio = static_cast((p - new_y * a) / c); // These values are actually n/m+n and m/m+n , we need // not calculate the explicit values of m an n as we // are just interested in the ratio @@ -190,34 +190,27 @@ double perpendicular_distance_from_projected_coordinate( } BOOST_ASSERT(nearest_location.is_valid()); - const double approximate_distance = great_circle_distance(query_location, nearest_location); + const double approximate_distance = greatCircleDistance(query_location, nearest_location); BOOST_ASSERT(0.0 <= approximate_distance); return approximate_distance; } -void lat_or_lon_to_string(const int value, std::string &output) -{ - char buffer[12]; - buffer[11] = 0; // zero termination - output = printInt<11, 6>(buffer, value); -} +double degToRad(const double degree) { return degree * (static_cast(M_PI) / 180.0); } -double deg_to_rad(const double degree) { return degree * (static_cast(M_PI) / 180.0); } - -double rad_to_deg(const double radian) { return radian * (180.0 * static_cast(M_1_PI)); } +double radToDeg(const double radian) { return radian * (180.0 * static_cast(M_1_PI)); } double bearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate) { const double lon_diff = second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION; - const double lon_delta = deg_to_rad(lon_diff); - const double lat1 = deg_to_rad(first_coordinate.lat / COORDINATE_PRECISION); - const double lat2 = deg_to_rad(second_coordinate.lat / COORDINATE_PRECISION); + const double lon_delta = degToRad(lon_diff); + const double lat1 = degToRad(first_coordinate.lat / COORDINATE_PRECISION); + const double lat2 = degToRad(second_coordinate.lat / COORDINATE_PRECISION); const double y = std::sin(lon_delta) * std::cos(lat2); const double x = std::cos(lat1) * std::sin(lat2) - std::sin(lat1) * std::cos(lat2) * std::cos(lon_delta); - double result = rad_to_deg(std::atan2(y, x)); + double result = radToDeg(std::atan2(y, x)); while (result < 0.0) { result += 360.0; diff --git a/unit_tests/util/coordinate.cpp b/unit_tests/util/coordinate.cpp index 08d00a671..e636d2f8f 100644 --- a/unit_tests/util/coordinate.cpp +++ b/unit_tests/util/coordinate.cpp @@ -13,11 +13,11 @@ BOOST_AUTO_TEST_CASE(regression_test_1347) FixedPointCoordinate v(10.001 * COORDINATE_PRECISION, -100.002 * COORDINATE_PRECISION); FixedPointCoordinate q(10.002 * COORDINATE_PRECISION, -100.001 * COORDINATE_PRECISION); - double d1 = coordinate_calculation::perpendicular_distance(u, v, q); + double d1 = coordinate_calculation::perpendicularDistance(u, v, q); double ratio; FixedPointCoordinate nearest_location; - double d2 = coordinate_calculation::perpendicular_distance(u, v, q, nearest_location, ratio); + double d2 = coordinate_calculation::perpendicularDistance(u, v, q, nearest_location, ratio); BOOST_CHECK_LE(std::abs(d1 - d2), 0.01); } diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index 2d5771621..9e0cc9520 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -63,9 +63,9 @@ template class LinearSearchNN { double current_ratio = 0.; FixedPointCoordinate nearest; - const double lhs_dist = coordinate_calculation::perpendicular_distance( + const double lhs_dist = coordinate_calculation::perpendicularDistance( coords->at(lhs.u), coords->at(lhs.v), input_coordinate, nearest, current_ratio); - const double rhs_dist = coordinate_calculation::perpendicular_distance( + const double rhs_dist = coordinate_calculation::perpendicularDistance( coords->at(rhs.u), coords->at(rhs.v), input_coordinate, nearest, current_ratio); return lhs_dist < rhs_dist; }); @@ -231,9 +231,9 @@ void sampling_verify_rtree(RTreeT &rtree, double current_ratio = 0.; FixedPointCoordinate nearest; - const double rtree_dist = coordinate_calculation::perpendicular_distance( + const double rtree_dist = coordinate_calculation::perpendicularDistance( coords[rtree_u], coords[rtree_v], q, nearest, current_ratio); - const double lsnn_dist = coordinate_calculation::perpendicular_distance( + const double lsnn_dist = coordinate_calculation::perpendicularDistance( coords[lsnn_u], coords[lsnn_v], q, nearest, current_ratio); BOOST_CHECK_LE(std::abs(rtree_dist - lsnn_dist), std::numeric_limits::epsilon()); } @@ -358,30 +358,30 @@ void TestRectangle(double width, double height, double center_lat, double center /* Distance to line segments of rectangle */ BOOST_CHECK_EQUAL(rect.GetMinDist(north), - coordinate_calculation::great_circle_distance( + coordinate_calculation::greatCircleDistance( north, FixedPointCoordinate(rect.max_lat, north.lon))); BOOST_CHECK_EQUAL(rect.GetMinDist(south), - coordinate_calculation::great_circle_distance( + coordinate_calculation::greatCircleDistance( south, FixedPointCoordinate(rect.min_lat, south.lon))); BOOST_CHECK_EQUAL(rect.GetMinDist(west), - coordinate_calculation::great_circle_distance( + coordinate_calculation::greatCircleDistance( west, FixedPointCoordinate(west.lat, rect.min_lon))); BOOST_CHECK_EQUAL(rect.GetMinDist(east), - coordinate_calculation::great_circle_distance( + coordinate_calculation::greatCircleDistance( east, FixedPointCoordinate(east.lat, rect.max_lon))); /* Distance to corner points */ BOOST_CHECK_EQUAL(rect.GetMinDist(north_east), - coordinate_calculation::great_circle_distance( + coordinate_calculation::greatCircleDistance( north_east, FixedPointCoordinate(rect.max_lat, rect.max_lon))); BOOST_CHECK_EQUAL(rect.GetMinDist(north_west), - coordinate_calculation::great_circle_distance( + coordinate_calculation::greatCircleDistance( north_west, FixedPointCoordinate(rect.max_lat, rect.min_lon))); BOOST_CHECK_EQUAL(rect.GetMinDist(south_east), - coordinate_calculation::great_circle_distance( + coordinate_calculation::greatCircleDistance( south_east, FixedPointCoordinate(rect.min_lat, rect.max_lon))); BOOST_CHECK_EQUAL(rect.GetMinDist(south_west), - coordinate_calculation::great_circle_distance( + coordinate_calculation::greatCircleDistance( south_west, FixedPointCoordinate(rect.min_lat, rect.min_lon))); } From 4f7369ed025b6be9abc8cb39709630c47cf3cb67 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 19:55:35 +0100 Subject: [PATCH 032/701] Fix naming in FixedPointCoordinate --- include/engine/datafacade/shared_datafacade.hpp | 2 +- include/engine/plugins/nearest.hpp | 2 +- include/engine/plugins/plugin_base.hpp | 2 +- include/osrm/coordinate.hpp | 12 +++--------- src/engine/phantom_node.cpp | 4 ++-- src/util/coordinate.cpp | 12 ++++-------- src/util/coordinate_calculation.cpp | 4 ++-- 7 files changed, 14 insertions(+), 24 deletions(-) diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 225056f89..91d917f96 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -270,7 +270,7 @@ template class SharedDataFacade final : public BaseDataFacade< SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { - if (!GetCoordinateOfNode(i).is_valid()) + if (!GetCoordinateOfNode(i).IsValid()) { SimpleLogger().Write() << "coordinate " << i << " not valid"; } diff --git a/include/engine/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp index e22a91e65..8db98ae40 100644 --- a/include/engine/plugins/nearest.hpp +++ b/include/engine/plugins/nearest.hpp @@ -27,7 +27,7 @@ template class NearestPlugin final : public BasePlugin { // check number of parameters if (route_parameters.coordinates.empty() || - !route_parameters.coordinates.front().is_valid()) + !route_parameters.coordinates.front().IsValid()) { return Status::Error; } diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index d7fe94983..7301d44c6 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -33,7 +33,7 @@ class BasePlugin if (min > coordinates.size() || std::any_of(std::begin(coordinates), std::end(coordinates), [](const FixedPointCoordinate &coordinate) { - return !coordinate.is_valid(); + return !coordinate.IsValid(); })) { return false; diff --git a/include/osrm/coordinate.hpp b/include/osrm/coordinate.hpp index 9c001029a..2ff3705ae 100644 --- a/include/osrm/coordinate.hpp +++ b/include/osrm/coordinate.hpp @@ -55,17 +55,11 @@ struct FixedPointCoordinate "coordinate types incompatible"); } - bool is_valid() const; + bool IsValid() const; bool operator==(const FixedPointCoordinate &other) const; - - double bearing(const FixedPointCoordinate &other) const; - void output(std::ostream &out) const; + friend std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate); }; -inline std::ostream &operator<<(std::ostream &out_stream, FixedPointCoordinate const &coordinate) -{ - coordinate.output(out_stream); - return out_stream; -} +std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate); #endif /* COORDINATE_HPP_ */ diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp index bc960bb58..7281d57bf 100644 --- a/src/engine/phantom_node.cpp +++ b/src/engine/phantom_node.cpp @@ -65,12 +65,12 @@ bool PhantomNode::is_compressed() const { return (forward_offset != 0) || (rever bool PhantomNode::is_valid(const unsigned number_of_nodes) const { - return location.is_valid() && + return location.IsValid() && ((forward_node_id < number_of_nodes) || (reverse_node_id < number_of_nodes)) && ((forward_weight != INVALID_EDGE_WEIGHT) || (reverse_weight != INVALID_EDGE_WEIGHT)) && (component.id != INVALID_COMPONENTID) && (name_id != INVALID_NAMEID); } -bool PhantomNode::is_valid() const { return location.is_valid() && (name_id != INVALID_NAMEID); } +bool PhantomNode::is_valid() const { return location.IsValid() && (name_id != INVALID_NAMEID); } bool PhantomNode::operator==(const PhantomNode &other) const { return location == other.location; } diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index e008fff6d..0092b01cf 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -34,7 +34,7 @@ FixedPointCoordinate::FixedPointCoordinate(int lat, int lon) : lat(lat), lon(lon #endif } -bool FixedPointCoordinate::is_valid() const +bool FixedPointCoordinate::IsValid() const { return !(lat > 90 * COORDINATE_PRECISION || lat < -90 * COORDINATE_PRECISION || lon > 180 * COORDINATE_PRECISION || lon < -180 * COORDINATE_PRECISION); @@ -45,12 +45,8 @@ bool FixedPointCoordinate::operator==(const FixedPointCoordinate &other) const return lat == other.lat && lon == other.lon; } -void FixedPointCoordinate::output(std::ostream &out) const +std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate) { - out << "(" << lat / COORDINATE_PRECISION << "," << lon / COORDINATE_PRECISION << ")"; -} - -double FixedPointCoordinate::bearing(const FixedPointCoordinate &other) const -{ - return coordinate_calculation::bearing(other, *this); + out << "(" << static_cast(coordinate.lat / COORDINATE_PRECISION) << "," << static_cast(coordinate.lon / COORDINATE_PRECISION) << ")"; + return out; } diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index 6213ba7e6..2e6a3137e 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -124,7 +124,7 @@ perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment FixedPointCoordinate &nearest_location, double &ratio) { - BOOST_ASSERT(query_location.is_valid()); + BOOST_ASSERT(query_location.IsValid()); // initialize values const double x = projected_coordinate.first; @@ -188,7 +188,7 @@ perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment nearest_location.lat = static_cast(mercator::y2lat(p) * COORDINATE_PRECISION); nearest_location.lon = static_cast(q * COORDINATE_PRECISION); } - BOOST_ASSERT(nearest_location.is_valid()); + BOOST_ASSERT(nearest_location.IsValid()); const double approximate_distance = greatCircleDistance(query_location, nearest_location); BOOST_ASSERT(0.0 <= approximate_distance); From f4e82a879b31f9cd34676983a7be77251a43350c Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 20:33:59 +0100 Subject: [PATCH 033/701] Fix naming in static_rtree benchmark --- src/benchmarks/static_rtree.cpp | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp index 9be36d015..db43bf20e 100644 --- a/src/benchmarks/static_rtree.cpp +++ b/src/benchmarks/static_rtree.cpp @@ -21,7 +21,7 @@ using FixedPointCoordinateListPtr = std::shared_ptr::vector, false>; using BenchQuery = GeospatialQuery; -FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path &nodes_file) +FixedPointCoordinateListPtr loadCoordinates(const boost::filesystem::path &nodes_file) { boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary); @@ -41,7 +41,7 @@ FixedPointCoordinateListPtr LoadCoordinates(const boost::filesystem::path &nodes } template -void BenchmarkQuery(const std::vector &queries, +void benchmarkQuery(const std::vector &queries, const std::string &name, QueryT query) { @@ -61,7 +61,7 @@ void BenchmarkQuery(const std::vector &queries, << ")" << std::endl; } -void Benchmark(BenchStaticRTree &rtree, BenchQuery &geo_query, unsigned num_queries) +void benchmark(BenchStaticRTree &rtree, BenchQuery &geo_query, unsigned num_queries) { std::mt19937 mt_rand(RANDOM_SEED); std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT); @@ -72,31 +72,31 @@ void Benchmark(BenchStaticRTree &rtree, BenchQuery &geo_query, unsigned num_quer queries.emplace_back(lat_udist(mt_rand), lon_udist(mt_rand)); } - BenchmarkQuery(queries, "raw RTree queries (1 result)", [&rtree](const FixedPointCoordinate &q) + benchmarkQuery(queries, "raw RTree queries (1 result)", [&rtree](const FixedPointCoordinate &q) { return rtree.Nearest(q, 1); }); - BenchmarkQuery(queries, "raw RTree queries (10 results)", + benchmarkQuery(queries, "raw RTree queries (10 results)", [&rtree](const FixedPointCoordinate &q) { return rtree.Nearest(q, 10); }); - BenchmarkQuery(queries, "big component alternative queries", + benchmarkQuery(queries, "big component alternative queries", [&geo_query](const FixedPointCoordinate &q) { return geo_query.NearestPhantomNodeWithAlternativeFromBigComponent(q); }); - BenchmarkQuery(queries, "max distance 1000", [&geo_query](const FixedPointCoordinate &q) + benchmarkQuery(queries, "max distance 1000", [&geo_query](const FixedPointCoordinate &q) { return geo_query.NearestPhantomNodesInRange(q, 1000); }); - BenchmarkQuery(queries, "PhantomNode query (1 result)", + benchmarkQuery(queries, "PhantomNode query (1 result)", [&geo_query](const FixedPointCoordinate &q) { return geo_query.NearestPhantomNodes(q, 1); }); - BenchmarkQuery(queries, "PhantomNode query (10 result)", + benchmarkQuery(queries, "PhantomNode query (10 result)", [&geo_query](const FixedPointCoordinate &q) { return geo_query.NearestPhantomNodes(q, 10); @@ -112,16 +112,16 @@ int main(int argc, char **argv) return 1; } - const char *ramPath = argv[1]; - const char *filePath = argv[2]; - const char *nodesPath = argv[3]; + const char *ram_path = argv[1]; + const char *file_path = argv[2]; + const char *nodes_path = argv[3]; - auto coords = LoadCoordinates(nodesPath); + auto coords = loadCoordinates(nodes_path); - BenchStaticRTree rtree(ramPath, filePath, coords); + BenchStaticRTree rtree(ram_path, file_path, coords); BenchQuery query(rtree, coords); - Benchmark(rtree, query, 10000); + benchmark(rtree, query, 10000); return 0; } From 707931125e5f888edf011f5d330cb5067e7f1035 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 4 Jan 2016 23:07:22 +0100 Subject: [PATCH 034/701] Remove unnecceary pre-define --- src/engine/osrm_impl.cpp | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/engine/osrm_impl.cpp b/src/engine/osrm_impl.cpp index 72003eb5d..0be92a777 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/osrm_impl.cpp @@ -1,11 +1,3 @@ -namespace boost -{ -namespace interprocess -{ -class named_mutex; -} -} - #include "engine/osrm_impl.hpp" #include "engine/plugins/distance_table.hpp" From 1da1fa5a3174c8cc95b1b25e71323c9fc41fcad4 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 5 Jan 2016 12:41:16 +0100 Subject: [PATCH 035/701] Fix naming in PhantomNode --- include/engine/phantom_node.hpp | 6 +++--- include/engine/plugins/match.hpp | 4 ++-- include/engine/plugins/plugin_base.hpp | 2 +- include/engine/routing_algorithms/direct_shortest_path.hpp | 4 ++-- src/engine/phantom_node.cpp | 6 +++--- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index 484526674..17dd6d19a 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -81,13 +81,13 @@ struct PhantomNode int GetReverseWeightPlusOffset() const; - bool is_bidirected() const; + bool IsBidirected() const; - bool is_compressed() const; + bool IsCompressed() const; bool is_valid(const unsigned numberOfNodes) const; - bool is_valid() const; + bool IsValid() const; bool operator==(const PhantomNode &other) const; }; diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 2f5dc688d..cd3ad1159 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -353,8 +353,8 @@ template class MapMatchingPlugin : public BasePlugin { current_phantom_node_pair.source_phantom = sub.nodes[i]; current_phantom_node_pair.target_phantom = sub.nodes[i + 1]; - BOOST_ASSERT(current_phantom_node_pair.source_phantom.is_valid()); - BOOST_ASSERT(current_phantom_node_pair.target_phantom.is_valid()); + BOOST_ASSERT(current_phantom_node_pair.source_phantom.IsValid()); + BOOST_ASSERT(current_phantom_node_pair.target_phantom.IsValid()); raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair); } search_engine_ptr->shortest_path( diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index 7301d44c6..5dffedd01 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -68,7 +68,7 @@ class BasePlugin const auto fallback_to_big_component = [](const std::pair &phantom_pair) { - if (phantom_pair.first.component.is_tiny && phantom_pair.second.is_valid() && + if (phantom_pair.first.component.is_tiny && phantom_pair.second.IsValid() && !phantom_pair.second.component.is_tiny) { return phantom_pair.second; diff --git a/include/engine/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp index 37b5a4a23..42bc357ff 100644 --- a/include/engine/routing_algorithms/direct_shortest_path.hpp +++ b/include/engine/routing_algorithms/direct_shortest_path.hpp @@ -53,8 +53,8 @@ class DirectShortestPathRouting final forward_heap.Clear(); reverse_heap.Clear(); - BOOST_ASSERT(source_phantom.is_valid()); - BOOST_ASSERT(target_phantom.is_valid()); + BOOST_ASSERT(source_phantom.IsValid()); + BOOST_ASSERT(target_phantom.IsValid()); if (source_phantom.forward_node_id != SPECIAL_NODEID) { diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp index 7281d57bf..670ffe706 100644 --- a/src/engine/phantom_node.cpp +++ b/src/engine/phantom_node.cpp @@ -56,12 +56,12 @@ int PhantomNode::GetReverseWeightPlusOffset() const return reverse_offset + reverse_weight; } -bool PhantomNode::is_bidirected() const +bool PhantomNode::IsBidirected() const { return (forward_node_id != SPECIAL_NODEID) && (reverse_node_id != SPECIAL_NODEID); } -bool PhantomNode::is_compressed() const { return (forward_offset != 0) || (reverse_offset != 0); } +bool PhantomNode::IsCompressed() const { return (forward_offset != 0) || (reverse_offset != 0); } bool PhantomNode::is_valid(const unsigned number_of_nodes) const { @@ -71,6 +71,6 @@ bool PhantomNode::is_valid(const unsigned number_of_nodes) const (component.id != INVALID_COMPONENTID) && (name_id != INVALID_NAMEID); } -bool PhantomNode::is_valid() const { return location.IsValid() && (name_id != INVALID_NAMEID); } +bool PhantomNode::IsValid() const { return location.IsValid() && (name_id != INVALID_NAMEID); } bool PhantomNode::operator==(const PhantomNode &other) const { return location == other.location; } From 42b1eaa2404c5cf30b9e276dca39f81273171097 Mon Sep 17 00:00:00 2001 From: Mathias Gug Date: Tue, 5 Jan 2016 11:44:24 -0500 Subject: [PATCH 036/701] Use OSRM versions for Debian package version. --- cmake/CPackDebianConfig.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/CPackDebianConfig.cmake b/cmake/CPackDebianConfig.cmake index bd434ee9e..323c3fe80 100644 --- a/cmake/CPackDebianConfig.cmake +++ b/cmake/CPackDebianConfig.cmake @@ -7,9 +7,9 @@ INCLUDE(FindDebArch) SET(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.md") SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENCE.TXT") SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CPACK_RESOURCE_FILE_README}") -SET(CPACK_PACKAGE_VERSION_MAJOR "0") -SET(CPACK_PACKAGE_VERSION_MINOR "4") -SET(CPACK_PACKAGE_VERSION_PATCH "3") +SET(CPACK_PACKAGE_VERSION_MAJOR ${OSRM_VERSION_MAJOR}) +SET(CPACK_PACKAGE_VERSION_MINOR ${OSRM_VERSION_MINOR}) +SET(CPACK_PACKAGE_VERSION_PATCH ${OSRM_VERSION_PATCH}) SET(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}") From dcfa81f983504f35cb25c5f8f76ca073c7461c71 Mon Sep 17 00:00:00 2001 From: Mathias Gug Date: Tue, 5 Jan 2016 14:15:55 -0500 Subject: [PATCH 037/701] Add debian revision. --- cmake/CPackDebianConfig.cmake | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/cmake/CPackDebianConfig.cmake b/cmake/CPackDebianConfig.cmake index 323c3fe80..88ba7767d 100644 --- a/cmake/CPackDebianConfig.cmake +++ b/cmake/CPackDebianConfig.cmake @@ -7,15 +7,13 @@ INCLUDE(FindDebArch) SET(CPACK_RESOURCE_FILE_README "${CMAKE_SOURCE_DIR}/README.md") SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENCE.TXT") SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CPACK_RESOURCE_FILE_README}") -SET(CPACK_PACKAGE_VERSION_MAJOR ${OSRM_VERSION_MAJOR}) -SET(CPACK_PACKAGE_VERSION_MINOR ${OSRM_VERSION_MINOR}) -SET(CPACK_PACKAGE_VERSION_PATCH ${OSRM_VERSION_PATCH}) - -SET(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.${CPACK_PACKAGE_VERSION_PATCH}") +SET(CPACK_PACKAGE_UPSTREAM_VERSION "${OSRM_VERSION_MAJOR}.${OSRM_VERSION_MINOR}.${OSRM_VERSION_PATCH}") +SET(CPACK_PACKAGE_DEBIAN_REVISION "1") +SET(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_UPSTREAM_VERSION-${CPACK_PACKAGE_DEBIAN_REVISION}") string(TOLOWER "${CMAKE_PROJECT_NAME}" LOWER_PROJECT_NAME) SET(CPACK_PACKAGE_FILE_NAME "${LOWER_PROJECT_NAME}_${CPACK_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") -SET(CPACK_SOURCE_PACKAGE_FILE_NAME "${LOWER_PROJECT_NAME}_${CPACK_PACKAGE_VERSION}_orig") +SET(CPACK_SOURCE_PACKAGE_FILE_NAME "${LOWER_PROJECT_NAME}_${CPACK_PACKAGE_UPSTREAM_VERSION}_orig") SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Open Source Routing Machine (OSRM).") SET(CPACK_PACKAGE_DESCRIPTION "Open Source Routing Machine (OSRM) is a routing engine.") @@ -27,7 +25,7 @@ SET(CPACK_INCLUDE_TOPLEVEL_DIRECTORY "FALSE") SET(CPACK_GENERATOR "DEB") SET(CPACK_DEBIAN_PACKAGE_NAME "${CPACK_PACKAGE_NAME}${VERSION_SUFFIX}") -SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}${CPACK_PACKAGE_REVISION}") +SET(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "Dennis Luxen ") SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") SET(CPACK_DEBIAN_PACKAGE_SECTION "devel") From c1709da6bf13566779060120cf07017e3d8782a0 Mon Sep 17 00:00:00 2001 From: Mathias Gug Date: Tue, 5 Jan 2016 14:25:14 -0500 Subject: [PATCH 038/701] Fix typo. --- cmake/CPackDebianConfig.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/CPackDebianConfig.cmake b/cmake/CPackDebianConfig.cmake index 88ba7767d..84b80a6bc 100644 --- a/cmake/CPackDebianConfig.cmake +++ b/cmake/CPackDebianConfig.cmake @@ -9,7 +9,7 @@ SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENCE.TXT") SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CPACK_RESOURCE_FILE_README}") SET(CPACK_PACKAGE_UPSTREAM_VERSION "${OSRM_VERSION_MAJOR}.${OSRM_VERSION_MINOR}.${OSRM_VERSION_PATCH}") SET(CPACK_PACKAGE_DEBIAN_REVISION "1") -SET(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_UPSTREAM_VERSION-${CPACK_PACKAGE_DEBIAN_REVISION}") +SET(CPACK_PACKAGE_VERSION "${CPACK_PACKAGE_UPSTREAM_VERSION}-${CPACK_PACKAGE_DEBIAN_REVISION}") string(TOLOWER "${CMAKE_PROJECT_NAME}" LOWER_PROJECT_NAME) SET(CPACK_PACKAGE_FILE_NAME "${LOWER_PROJECT_NAME}_${CPACK_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") From cb37c0d135d724d58fe1e295352b4b46d6d0d2d3 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 6 Jan 2016 12:32:19 +0100 Subject: [PATCH 039/701] Use FindOsmium.cmake to handle libosmium's buildsystem integration --- CMakeLists.txt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c64c5d978..518d4fac5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -36,7 +36,6 @@ option(BUILD_TOOLS "Build OSRM tools" OFF) include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}/include/) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/) include_directories(SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/third_party/) -include_directories(SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/third_party/libosmium/include/) add_custom_target(FingerPrintConfigure ALL ${CMAKE_COMMAND} "-DOUTPUT_DIR=${CMAKE_CURRENT_BINARY_DIR}" @@ -226,7 +225,14 @@ if(UNIX AND NOT APPLE) target_link_libraries(engine-tests rt) endif() -#Check Boost +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/third_party/libosmium/cmake") +set(OSMIUM_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third_party/libosmium/include") +find_package(Osmium REQUIRED COMPONENTS io) +include_directories(SYSTEM ${OSMIUM_INCLUDE_DIRS}) + +target_link_libraries(osrm-extract ${OSMIUM_LIBRARIES}) +target_link_libraries(extractor-tests ${OSMIUM_LIBRARIES}) + find_package(Boost 1.49.0 COMPONENTS ${BOOST_COMPONENTS} REQUIRED) if(NOT Boost_FOUND) message(FATAL_ERROR "Fatal error: Boost (version >= 1.49.0) required.\n") From 95d1efb7f8876c7fb3ccb3d283d07ce921358232 Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Wed, 6 Jan 2016 14:42:31 -0800 Subject: [PATCH 040/701] Disable via test that fails on OSX so that we can test everything else on Travis on OSX. --- .travis.yml | 16 ++++++++-------- features/step_definitions/hooks.rb | 11 +++++++++++ features/testbot/via.feature | 2 ++ 3 files changed, 21 insertions(+), 8 deletions(-) create mode 100644 features/step_definitions/hooks.rb diff --git a/.travis.yml b/.travis.yml index dc0405142..5d8e5fa8a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -92,15 +92,15 @@ matrix: # compiler: clang # env: COMPILER='clang++' BUILD_TYPE='Release' BUILD_SHARED_LIBS=ON - #- os: osx - # osx_image: xcode7 - # compiler: clang - # env: COMPILER='clang++' BUILD_TYPE='Debug' + - os: osx + osx_image: xcode7 + compiler: clang + env: COMPILER='clang++' BUILD_TYPE='Debug' - #- os: osx - # osx_image: xcode7 - # compiler: clang - # env: COMPILER='clang++' BUILD_TYPE='Release' + - os: osx + osx_image: xcode7 + compiler: clang + env: COMPILER='clang++' BUILD_TYPE='Release' #- os: osx # osx_image: xcode7 diff --git a/features/step_definitions/hooks.rb b/features/step_definitions/hooks.rb new file mode 100644 index 000000000..2ad821a9a --- /dev/null +++ b/features/step_definitions/hooks.rb @@ -0,0 +1,11 @@ +Before '@ignore-platform-windows' do + skip_this_scenario +end + +Before '@ignore-platform-unix' do + skip_this_scenario +end + +Before '@ignore-platform-mac' do + skip_this_scenario +end diff --git a/features/testbot/via.feature b/features/testbot/via.feature index a88b0f4b4..4a7c96328 100644 --- a/features/testbot/via.feature +++ b/features/testbot/via.feature @@ -93,6 +93,8 @@ Feature: Via points | 1,3,2 | ab,bc,cd,cd,de,ef,fa,ab,bc | 1600m +-1 | head,straight,straight,via,right,right,right,right,straight,destination | | 3,2,1 | cd,de,ef,fa,ab,bc,bc,cd,de,ef,fa,ab | 2400m +-1 | head,right,right,right,right,straight,via,straight,right,right,right,right,destination | + # TODO: Remove this ignore when https://github.com/Project-OSRM/osrm-backend/issues/1863 gets fixed + @ignore-platform-mac Scenario: Via points on ring on the same oneway # xa it to avoid only having a single ring, which cna trigger edge cases Given the node map From 811e29ff1b669d33e9302b56e687abd10177af45 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 7 Jan 2016 11:35:35 +0100 Subject: [PATCH 041/701] Add cmath to geospatial_query --- include/engine/geospatial_query.hpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index fddacf2ca..b572b8f79 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -8,9 +8,10 @@ #include "osrm/coordinate.hpp" -#include -#include #include +#include +#include +#include // Implements complex queries on top of an RTree and builds PhantomNodes from it. // From d3ef5209155d16e215aa8a1e53a6a88724b3ab38 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 7 Jan 2016 15:20:32 +0100 Subject: [PATCH 042/701] Print message about ccache usage from cmake --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 518d4fac5..5ea4fa687 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -426,6 +426,7 @@ endif() if(${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang" OR ${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU") find_program(CCACHE_FOUND ccache) if(CCACHE_FOUND) + message(STATUS "Using ccache to speed up incremental builds") set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) set(ENV{CCACHE_CPP2} "true") From fa4ba42f15985782d41ba2e4ab4803d85aca61d6 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 7 Jan 2016 16:30:54 +0100 Subject: [PATCH 043/701] Use a sane gps_precision multipler --- include/engine/plugins/match.hpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index cd3ad1159..bb786c1b8 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -24,8 +24,6 @@ template class MapMatchingPlugin : public BasePlugin { - constexpr static const unsigned max_number_of_candidates = 10; - std::shared_ptr> search_engine_ptr; using ClassifierT = BayesClassifier; @@ -74,7 +72,9 @@ template class MapMatchingPlugin : public BasePlugin { osrm::matching::CandidateLists candidates_lists; - double query_radius = 10 * gps_precision; + // assuming the gps_precision is the standart-diviation of normal distribution that models + // GPS noise (in this model) this should give us the correct candidate with >0.95 + double query_radius = 3 * gps_precision; double last_distance = coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]); From efd33b295a2d6be87b02e51390be30ee25e548ba Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Mon, 4 Jan 2016 10:19:25 +0100 Subject: [PATCH 044/701] Refactor guidance generation --- include/engine/api_response_generator.hpp | 294 ++++++++++++++ .../descriptors/description_factory.hpp | 69 ---- .../engine/descriptors/descriptor_base.hpp | 60 --- include/engine/descriptors/gpx_descriptor.hpp | 78 ---- .../engine/descriptors/json_descriptor.hpp | 379 ------------------ .../engine/guidance/segment_compression.hpp | 66 +++ include/engine/guidance/segment_list.hpp | 326 +++++++++++++++ .../guidance/textual_route_annotation.hpp | 134 +++++++ include/engine/internal_route_result.hpp | 4 + include/engine/plugins/distance_table.hpp | 6 - include/engine/plugins/hello_world.hpp | 2 - include/engine/plugins/match.hpp | 53 +-- include/engine/plugins/nearest.hpp | 3 - include/engine/plugins/timestamp.hpp | 2 - include/engine/plugins/trip.hpp | 26 +- include/engine/plugins/viaroute.hpp | 28 +- include/engine/route_name_extraction.hpp | 13 +- .../descriptors/description_factory.cpp | 224 ----------- 18 files changed, 861 insertions(+), 906 deletions(-) create mode 100644 include/engine/api_response_generator.hpp delete mode 100644 include/engine/descriptors/description_factory.hpp delete mode 100644 include/engine/descriptors/descriptor_base.hpp delete mode 100644 include/engine/descriptors/gpx_descriptor.hpp delete mode 100644 include/engine/descriptors/json_descriptor.hpp create mode 100644 include/engine/guidance/segment_compression.hpp create mode 100644 include/engine/guidance/segment_list.hpp create mode 100644 include/engine/guidance/textual_route_annotation.hpp delete mode 100644 src/engine/descriptors/description_factory.cpp diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp new file mode 100644 index 000000000..d70eae3f8 --- /dev/null +++ b/include/engine/api_response_generator.hpp @@ -0,0 +1,294 @@ +#ifndef ENGINE_GUIDANCE_API_RESPONSE_GENERATOR_HPP_ +#define ENGINE_GUIDANCE_API_RESPONSE_GENERATOR_HPP_ + +#include "guidance/segment_list.hpp" +#include "guidance/textual_route_annotation.hpp" + +#include "engine/douglas_peucker.hpp" +#include "engine/internal_route_result.hpp" +#include "engine/object_encoder.hpp" +#include "engine/phantom_node.hpp" +#include "engine/polyline_formatter.hpp" +#include "engine/route_name_extraction.hpp" +#include "engine/segment_information.hpp" +#include "extractor/turn_instructions.hpp" +#include "osrm/coordinate.hpp" +#include "osrm/json_container.hpp" +#include "osrm/route_parameters.hpp" +#include "util/integer_range.hpp" +#include "util/typedefs.hpp" + +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace osrm +{ +namespace engine +{ +namespace detail +{ +struct Segment +{ + uint32_t name_id; + int32_t length; + std::size_t position; +}; +} // namespace detail + +template class ApiResponseGenerator +{ + public: + using DataFacade = DataFacadeT; + using Segments = guidance::SegmentList; + using Segment = detail::Segment; + using RouteNameExtractor = ExtractRouteNames; + + ApiResponseGenerator(DataFacade *facade); + + // This runs a full annotation, according to config. + // The output is tailored to the viaroute plugin. + void DescribeRoute(const RouteParameters &config, + const InternalRouteResult &raw_route, + osrm::json::Object &json_result); + + // The following functions allow access to the different parts of the Describe Route + // functionality. + // For own responses, they can be used to generate only subsets of the information. + // In the normal situation, Describe Route is the desired usecase. + + // generate an overview of a raw route + osrm::json::Object SummarizeRoute(const InternalRouteResult &raw_route, + const Segments &segment_list) const; + + // create an array containing all via-points/-indices used in the query + osrm::json::Array ListViaPoints(const InternalRouteResult &raw_route) const; + osrm::json::Array ListViaIndices(const Segments &segment_list) const; + + osrm::json::Value GetGeometry(const bool return_encoded, const Segments &segments) const; + + // TODO this dedicated creation seems unnecessary? Only used for route names + std::vector BuildRouteSegments(const Segments &segment_list) const; + + // adds checksum and locations + osrm::json::Object BuildHintData(const InternalRouteResult &raw_route) const; + + private: + // data access to translate ids back into names + DataFacade *facade; +}; + +template +ApiResponseGenerator::ApiResponseGenerator(DataFacadeT *facade_) + : facade(facade_) +{ +} + +template +void ApiResponseGenerator::DescribeRoute(const RouteParameters &config, + const InternalRouteResult &raw_route, + osrm::json::Object &json_result) +{ + if( not raw_route.is_valid() ){ + return; + } + const constexpr bool ALLOW_SIMPLIFICATION = true; + const constexpr bool EXTRACT_ROUTE = false; + const constexpr bool EXTRACT_ALTERNATIVE = true; + Segments segment_list(raw_route, EXTRACT_ROUTE, config.zoom_level, ALLOW_SIMPLIFICATION, + facade); + json_result.values["route_summary"] = SummarizeRoute(raw_route, segment_list); + json_result.values["via_points"] = ListViaPoints(raw_route); + json_result.values["via_indices"] = ListViaIndices(segment_list); + + if (config.geometry) + { + json_result.values["route_geometry"] = GetGeometry(config.compression, segment_list); + } + + if (config.print_instructions) + { + json_result.values["route_instructions"] = + guidance::AnnotateRoute(segment_list.Get(), facade); + } + + RouteNames route_names; + RouteNameExtractor generate_route_names; + + if (raw_route.has_alternative()) + { + Segments alternate_segment_list(raw_route, EXTRACT_ALTERNATIVE, config.zoom_level, + ALLOW_SIMPLIFICATION, facade); + + // Alternative Route Summaries are stored in an array to (down the line) allow multiple + // alternatives + osrm::json::Array json_alternate_route_summary_array; + json_alternate_route_summary_array.values.emplace_back( + SummarizeRoute(raw_route, alternate_segment_list)); + json_result.values["alternative_summaries"] = json_alternate_route_summary_array; + json_result.values["alternative_indices"] = ListViaIndices(alternate_segment_list); + + if (config.geometry) + { + auto alternate_geometry_string = + GetGeometry(config.compression, alternate_segment_list); + osrm::json::Array json_alternate_geometries_array; + json_alternate_geometries_array.values.emplace_back(std::move(alternate_geometry_string)); + json_result.values["alternative_geometries"] = json_alternate_geometries_array; + } + + if (config.print_instructions) + { + osrm::json::Array json_alternate_annotations_array; + json_alternate_annotations_array.values.emplace_back( + guidance::AnnotateRoute(alternate_segment_list.Get(), facade)); + json_result.values["alternative_instructions"] = json_alternate_annotations_array; + } + + // generate names for both the main path and the alternative route + auto path_segments = BuildRouteSegments(segment_list); + auto alternate_segments = BuildRouteSegments(alternate_segment_list); + route_names = generate_route_names(path_segments, alternate_segments, facade); + + osrm::json::Array json_alternate_names_array; + osrm::json::Array json_alternate_names; + json_alternate_names.values.push_back(route_names.alternative_path_name_1); + json_alternate_names.values.push_back(route_names.alternative_path_name_2); + json_alternate_names_array.values.emplace_back(std::move(json_alternate_names)); + json_result.values["alternative_names"] = json_alternate_names_array; + json_result.values["found_alternative"] = osrm::json::True(); + } + else + { + json_result.values["found_alternative"] = osrm::json::False(); + // generate names for the main route on its own + auto path_segments = BuildRouteSegments(segment_list); + std::vector alternate_segments; + route_names = generate_route_names(path_segments, alternate_segments, facade); + } + + osrm::json::Array json_route_names; + json_route_names.values.push_back(route_names.shortest_path_name_1); + json_route_names.values.push_back(route_names.shortest_path_name_2); + json_result.values["route_name"] = json_route_names; + + json_result.values["hint_data"] = BuildHintData(raw_route); +} + +template +osrm::json::Object +ApiResponseGenerator::SummarizeRoute(const InternalRouteResult &raw_route, + const Segments &segment_list) const +{ + osrm::json::Object json_route_summary; + if (not raw_route.segment_end_coordinates.empty()) + { + const auto start_name_id = raw_route.segment_end_coordinates.front().source_phantom.name_id; + json_route_summary.values["start_point"] = facade->get_name_for_id(start_name_id); + const auto destination_name_id = raw_route.segment_end_coordinates.back().target_phantom.name_id; + json_route_summary.values["end_point"] = facade->get_name_for_id(destination_name_id); + } + json_route_summary.values["total_time"] = segment_list.GetDuration(); + json_route_summary.values["total_distance"] = segment_list.GetDistance(); + return json_route_summary; +} + +template +osrm::json::Array +ApiResponseGenerator::ListViaPoints(const InternalRouteResult &raw_route) const +{ + osrm::json::Array json_via_points_array; + osrm::json::Array json_first_coordinate; + json_first_coordinate.values.emplace_back( + raw_route.segment_end_coordinates.front().source_phantom.location.lat / + COORDINATE_PRECISION); + json_first_coordinate.values.emplace_back( + raw_route.segment_end_coordinates.front().source_phantom.location.lon / + COORDINATE_PRECISION); + json_via_points_array.values.emplace_back(std::move(json_first_coordinate)); + for (const PhantomNodes &nodes : raw_route.segment_end_coordinates) + { + std::string tmp; + osrm::json::Array json_coordinate; + json_coordinate.values.emplace_back(nodes.target_phantom.location.lat / COORDINATE_PRECISION); + json_coordinate.values.emplace_back(nodes.target_phantom.location.lon / COORDINATE_PRECISION); + json_via_points_array.values.emplace_back(std::move(json_coordinate)); + } + return json_via_points_array; +} + +template +osrm::json::Array +ApiResponseGenerator::ListViaIndices(const Segments &segment_list) const +{ + osrm::json::Array via_indices; + via_indices.values.insert(via_indices.values.end(), segment_list.GetViaIndices().begin(), + segment_list.GetViaIndices().end()); + return via_indices; +} + +template +osrm::json::Value ApiResponseGenerator::GetGeometry(const bool return_encoded, const Segments &segments) const +{ + if (return_encoded) + return PolylineFormatter().printEncodedString(segments.Get()); + else + return PolylineFormatter().printUnencodedString(segments.Get()); +} + +template +std::vector +ApiResponseGenerator::BuildRouteSegments(const Segments &segment_list) const +{ + std::vector result; + for (const auto &segment : segment_list.Get()) + { + const auto current_turn = segment.turn_instruction; + if (TurnInstructionsClass::TurnIsNecessary(current_turn) and + (TurnInstruction::EnterRoundAbout != current_turn)) + { + + detail::Segment seg = {segment.name_id, static_cast(segment.length), + static_cast(result.size())}; + result.emplace_back(std::move(seg)); + } + } + return result; +} + +template +osrm::json::Object +ApiResponseGenerator::BuildHintData(const InternalRouteResult &raw_route) const +{ + osrm::json::Object json_hint_object; + json_hint_object.values["checksum"] = facade->GetCheckSum(); + osrm::json::Array json_location_hint_array; + std::string hint; + for (const auto i : osrm::irange(0, raw_route.segment_end_coordinates.size())) + { + ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates[i].source_phantom, hint); + json_location_hint_array.values.push_back(hint); + } + ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates.back().target_phantom, hint); + json_location_hint_array.values.emplace_back(std::move(hint)); + json_hint_object.values["locations"] = json_location_hint_array; + + return json_hint_object; +} + +template +ApiResponseGenerator MakeApiResponseGenerator(DataFacadeT *facade){ + return ApiResponseGenerator(facade); +} + +} // namespace engine +} // namespace osrm + +#endif //ENGINE_GUIDANCE_API_RESPONSE_GENERATOR_HPP_ diff --git a/include/engine/descriptors/description_factory.hpp b/include/engine/descriptors/description_factory.hpp deleted file mode 100644 index 06150e665..000000000 --- a/include/engine/descriptors/description_factory.hpp +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef DESCRIPTION_FACTORY_HPP -#define DESCRIPTION_FACTORY_HPP - -#include "engine/douglas_peucker.hpp" -#include "engine/phantom_node.hpp" -#include "engine/segment_information.hpp" -#include "extractor/turn_instructions.hpp" - -#include - -#include "osrm/coordinate.hpp" -#include "osrm/json_container.hpp" - -#include - -#include -#include - -struct PathData; -/* This class is fed with all way segments in consecutive order - * and produces the description plus the encoded polyline */ - -class DescriptionFactory -{ - DouglasPeucker polyline_generalizer; - PhantomNode start_phantom, target_phantom; - - double DegreeToRadian(const double degree) const; - double RadianToDegree(const double degree) const; - - std::vector via_indices; - - double entire_length; - - public: - struct RouteSummary - { - unsigned distance; - EdgeWeight duration; - unsigned source_name_id; - unsigned target_name_id; - RouteSummary() : distance(0), duration(0), source_name_id(0), target_name_id(0) {} - - void BuildDurationAndLengthStrings(const double raw_distance, const unsigned raw_duration) - { - // compute distance/duration for route summary - distance = static_cast(std::round(raw_distance)); - duration = static_cast(std::round(raw_duration / 10.)); - } - } summary; - - // I know, declaring this public is considered bad. I'm lazy - std::vector path_description; - DescriptionFactory(); - void AppendSegment(const FixedPointCoordinate &coordinate, const PathData &data); - void BuildRouteSummary(const double distance, const unsigned time); - void SetStartSegment(const PhantomNode &start_phantom, const bool traversed_in_reverse); - void SetEndSegment(const PhantomNode &start_phantom, - const bool traversed_in_reverse, - const bool is_via_location = false); - osrm::json::Value AppendGeometryString(const bool return_encoded); - std::vector const &GetViaIndices() const; - - double get_entire_length() const { return entire_length; } - - void Run(const unsigned zoom_level); -}; - -#endif /* DESCRIPTION_FACTORY_HPP */ diff --git a/include/engine/descriptors/descriptor_base.hpp b/include/engine/descriptors/descriptor_base.hpp deleted file mode 100644 index c782f94cd..000000000 --- a/include/engine/descriptors/descriptor_base.hpp +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef DESCRIPTOR_BASE_HPP -#define DESCRIPTOR_BASE_HPP - -#include "util/coordinate_calculation.hpp" -#include "engine/internal_route_result.hpp" -#include "engine/phantom_node.hpp" -#include "util/typedefs.hpp" - -#include - -#include "osrm/json_container.hpp" - -#include -#include -#include - -struct DescriptorTable : public std::unordered_map -{ - unsigned get_id(const std::string &key) - { - auto iter = find(key); - if (iter != end()) - { - return iter->second; - } - return 0; - } -}; - -struct DescriptorConfig -{ - DescriptorConfig() : instructions(true), geometry(true), encode_geometry(true), zoom_level(18) - { - } - - template - DescriptorConfig(const OtherT &other) - : instructions(other.print_instructions), geometry(other.geometry), - encode_geometry(other.compression), zoom_level(other.zoom_level) - { - BOOST_ASSERT(zoom_level >= 0); - } - - bool instructions; - bool geometry; - bool encode_geometry; - short zoom_level; -}; - -template class BaseDescriptor -{ - public: - BaseDescriptor() {} - // Maybe someone can explain the pure virtual destructor thing to me (dennis) - virtual ~BaseDescriptor() {} - virtual void Run(const InternalRouteResult &raw_route, osrm::json::Object &json_result) = 0; - virtual void SetConfig(const DescriptorConfig &c) = 0; -}; - -#endif // DESCRIPTOR_BASE_HPP diff --git a/include/engine/descriptors/gpx_descriptor.hpp b/include/engine/descriptors/gpx_descriptor.hpp deleted file mode 100644 index b4bd06756..000000000 --- a/include/engine/descriptors/gpx_descriptor.hpp +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef GPX_DESCRIPTOR_HPP -#define GPX_DESCRIPTOR_HPP - -#include "engine/descriptors/descriptor_base.hpp" -#include "util/xml_renderer.hpp" -#include "util/string_util.hpp" - -#include "osrm/json_container.hpp" - -#include - - - -template class GPXDescriptor final : public BaseDescriptor -{ - private: - DescriptorConfig config; - DataFacadeT *facade; - - template - void fixedIntToString(const int value, std::string &output) - { - char buffer[digits]; - buffer[digits-1] = 0; // zero termination - output = printInt<11, 6>(buffer, value); - } - - void AddRoutePoint(const FixedPointCoordinate &coordinate, osrm::json::Array &json_route) - { - osrm::json::Object json_lat; - osrm::json::Object json_lon; - osrm::json::Array json_row; - - std::string tmp; - - fixedIntToString<12>(coordinate.lat, tmp); - json_lat.values["_lat"] = tmp; - - fixedIntToString<12>(coordinate.lon, tmp); - json_lon.values["_lon"] = tmp; - - json_row.values.push_back(json_lat); - json_row.values.push_back(json_lon); - osrm::json::Object entry; - entry.values["rtept"] = json_row; - json_route.values.push_back(entry); - } - - public: - explicit GPXDescriptor(DataFacadeT *facade) : facade(facade) {} - - virtual void SetConfig(const DescriptorConfig &c) final { config = c; } - - virtual void Run(const InternalRouteResult &raw_route, osrm::json::Object &json_result) final - { - osrm::json::Array json_route; - if (raw_route.shortest_path_length != INVALID_EDGE_WEIGHT) - { - AddRoutePoint(raw_route.segment_end_coordinates.front().source_phantom.location, - json_route); - - for (const std::vector &path_data_vector : raw_route.unpacked_path_segments) - { - for (const PathData &path_data : path_data_vector) - { - const FixedPointCoordinate current_coordinate = - facade->GetCoordinateOfNode(path_data.node); - AddRoutePoint(current_coordinate, json_route); - } - } - AddRoutePoint(raw_route.segment_end_coordinates.back().target_phantom.location, - json_route); - } - // osrm::json::gpx_render(reply.content, json_route); - json_result.values["route"] = json_route; - } -}; -#endif // GPX_DESCRIPTOR_HPP diff --git a/include/engine/descriptors/json_descriptor.hpp b/include/engine/descriptors/json_descriptor.hpp deleted file mode 100644 index b5eda81a8..000000000 --- a/include/engine/descriptors/json_descriptor.hpp +++ /dev/null @@ -1,379 +0,0 @@ -#ifndef JSON_DESCRIPTOR_HPP -#define JSON_DESCRIPTOR_HPP - -#include "engine/descriptors/descriptor_base.hpp" -#include "engine/descriptors/description_factory.hpp" -#include "engine/object_encoder.hpp" -#include "engine/route_name_extraction.hpp" -#include "engine/segment_information.hpp" -#include "extractor/turn_instructions.hpp" -#include "util/bearing.hpp" -#include "util/cast.hpp" -#include "util/integer_range.hpp" -#include "util/json_renderer.hpp" -#include "util/simple_logger.hpp" -#include "util/string_util.hpp" -#include "util/timing_util.hpp" - -#include "osrm/json_container.hpp" - -#include -#include -#include - -template class JSONDescriptor final : public BaseDescriptor -{ - private: - DataFacadeT *facade; - DescriptorConfig config; - DescriptionFactory description_factory, alternate_description_factory; - FixedPointCoordinate current; - - public: - struct Segment - { - Segment() : name_id(INVALID_NAMEID), length(-1), position(0) {} - Segment(unsigned n, int l, unsigned p) : name_id(n), length(l), position(p) {} - unsigned name_id; - int length; - unsigned position; - }; - - private: - std::vector shortest_path_segments, alternative_path_segments; - ExtractRouteNames GenerateRouteNames; - - public: - explicit JSONDescriptor(DataFacadeT *facade) : facade(facade) {} - - virtual void SetConfig(const DescriptorConfig &c) override final { config = c; } - - unsigned DescribeLeg(const std::vector &route_leg, - const PhantomNodes &leg_phantoms, - const bool target_traversed_in_reverse, - const bool is_via_leg) - { - unsigned added_element_count = 0; - // Get all the coordinates for the computed route - FixedPointCoordinate current_coordinate; - for (const PathData &path_data : route_leg) - { - current_coordinate = facade->GetCoordinateOfNode(path_data.node); - description_factory.AppendSegment(current_coordinate, path_data); - ++added_element_count; - } - description_factory.SetEndSegment(leg_phantoms.target_phantom, target_traversed_in_reverse, - is_via_leg); - ++added_element_count; - BOOST_ASSERT((route_leg.size() + 1) == added_element_count); - return added_element_count; - } - - virtual void Run(const InternalRouteResult &raw_route, - osrm::json::Object &json_result) override final - { - if (INVALID_EDGE_WEIGHT == raw_route.shortest_path_length) - { - // We do not need to do much, if there is no route ;-) - return; - } - - // check if first segment is non-zero - BOOST_ASSERT(raw_route.unpacked_path_segments.size() == - raw_route.segment_end_coordinates.size()); - - description_factory.SetStartSegment( - raw_route.segment_end_coordinates.front().source_phantom, - raw_route.source_traversed_in_reverse.front()); - - // for each unpacked segment add the leg to the description - for (const auto i : osrm::irange(0, raw_route.unpacked_path_segments.size())) - { -#ifndef NDEBUG - const int added_segments = -#endif - DescribeLeg(raw_route.unpacked_path_segments[i], - raw_route.segment_end_coordinates[i], - raw_route.target_traversed_in_reverse[i], raw_route.is_via_leg(i)); - BOOST_ASSERT(0 < added_segments); - } - description_factory.Run(config.zoom_level); - - if (config.geometry) - { - osrm::json::Value route_geometry = - description_factory.AppendGeometryString(config.encode_geometry); - json_result.values["route_geometry"] = route_geometry; - } - if (config.instructions) - { - osrm::json::Array json_route_instructions = - BuildTextualDescription(description_factory, shortest_path_segments); - json_result.values["route_instructions"] = json_route_instructions; - } - description_factory.BuildRouteSummary(description_factory.get_entire_length(), - raw_route.shortest_path_length); - osrm::json::Object json_route_summary; - json_route_summary.values["total_distance"] = description_factory.summary.distance; - json_route_summary.values["total_time"] = description_factory.summary.duration; - json_route_summary.values["start_point"] = - facade->get_name_for_id(description_factory.summary.source_name_id); - json_route_summary.values["end_point"] = - facade->get_name_for_id(description_factory.summary.target_name_id); - json_result.values["route_summary"] = json_route_summary; - - BOOST_ASSERT(!raw_route.segment_end_coordinates.empty()); - - osrm::json::Array json_via_points_array; - osrm::json::Array json_first_coordinate; - json_first_coordinate.values.push_back( - raw_route.segment_end_coordinates.front().source_phantom.location.lat / - COORDINATE_PRECISION); - json_first_coordinate.values.push_back( - raw_route.segment_end_coordinates.front().source_phantom.location.lon / - COORDINATE_PRECISION); - json_via_points_array.values.push_back(json_first_coordinate); - for (const PhantomNodes &nodes : raw_route.segment_end_coordinates) - { - std::string tmp; - osrm::json::Array json_coordinate; - json_coordinate.values.push_back(nodes.target_phantom.location.lat / - COORDINATE_PRECISION); - json_coordinate.values.push_back(nodes.target_phantom.location.lon / - COORDINATE_PRECISION); - json_via_points_array.values.push_back(json_coordinate); - } - json_result.values["via_points"] = json_via_points_array; - - osrm::json::Array json_via_indices_array; - - std::vector const &shortest_leg_end_indices = description_factory.GetViaIndices(); - json_via_indices_array.values.insert(json_via_indices_array.values.end(), - shortest_leg_end_indices.begin(), - shortest_leg_end_indices.end()); - json_result.values["via_indices"] = json_via_indices_array; - - // only one alternative route is computed at this time, so this is hardcoded - if (INVALID_EDGE_WEIGHT != raw_route.alternative_path_length) - { - json_result.values["found_alternative"] = osrm::json::True(); - BOOST_ASSERT(!raw_route.alt_source_traversed_in_reverse.empty()); - alternate_description_factory.SetStartSegment( - raw_route.segment_end_coordinates.front().source_phantom, - raw_route.alt_source_traversed_in_reverse.front()); - // Get all the coordinates for the computed route - for (const PathData &path_data : raw_route.unpacked_alternative) - { - current = facade->GetCoordinateOfNode(path_data.node); - alternate_description_factory.AppendSegment(current, path_data); - } - alternate_description_factory.SetEndSegment( - raw_route.segment_end_coordinates.back().target_phantom, - raw_route.alt_source_traversed_in_reverse.back()); - alternate_description_factory.Run(config.zoom_level); - - if (config.geometry) - { - osrm::json::Value alternate_geometry_string = - alternate_description_factory.AppendGeometryString(config.encode_geometry); - osrm::json::Array json_alternate_geometries_array; - json_alternate_geometries_array.values.push_back(alternate_geometry_string); - json_result.values["alternative_geometries"] = json_alternate_geometries_array; - } - // Generate instructions for each alternative (simulated here) - osrm::json::Array json_alt_instructions; - osrm::json::Array json_current_alt_instructions; - if (config.instructions) - { - json_current_alt_instructions = BuildTextualDescription( - alternate_description_factory, alternative_path_segments); - json_alt_instructions.values.push_back(json_current_alt_instructions); - json_result.values["alternative_instructions"] = json_alt_instructions; - } - alternate_description_factory.BuildRouteSummary( - alternate_description_factory.get_entire_length(), - raw_route.alternative_path_length); - - osrm::json::Object json_alternate_route_summary; - osrm::json::Array json_alternate_route_summary_array; - json_alternate_route_summary.values["total_distance"] = - alternate_description_factory.summary.distance; - json_alternate_route_summary.values["total_time"] = - alternate_description_factory.summary.duration; - json_alternate_route_summary.values["start_point"] = - facade->get_name_for_id(alternate_description_factory.summary.source_name_id); - json_alternate_route_summary.values["end_point"] = - facade->get_name_for_id(alternate_description_factory.summary.target_name_id); - json_alternate_route_summary_array.values.push_back(json_alternate_route_summary); - json_result.values["alternative_summaries"] = json_alternate_route_summary_array; - - std::vector const &alternate_leg_end_indices = - alternate_description_factory.GetViaIndices(); - osrm::json::Array json_altenative_indices_array; - json_altenative_indices_array.values.insert(json_altenative_indices_array.values.end(), - alternate_leg_end_indices.begin(), - alternate_leg_end_indices.end()); - json_result.values["alternative_indices"] = json_altenative_indices_array; - } - else - { - json_result.values["found_alternative"] = osrm::json::False(); - } - - // Get Names for both routes - RouteNames route_names = - GenerateRouteNames(shortest_path_segments, alternative_path_segments, facade); - osrm::json::Array json_route_names; - json_route_names.values.push_back(route_names.shortest_path_name_1); - json_route_names.values.push_back(route_names.shortest_path_name_2); - json_result.values["route_name"] = json_route_names; - - if (INVALID_EDGE_WEIGHT != raw_route.alternative_path_length) - { - osrm::json::Array json_alternate_names_array; - osrm::json::Array json_alternate_names; - json_alternate_names.values.push_back(route_names.alternative_path_name_1); - json_alternate_names.values.push_back(route_names.alternative_path_name_2); - json_alternate_names_array.values.push_back(json_alternate_names); - json_result.values["alternative_names"] = json_alternate_names_array; - } - - json_result.values["hint_data"] = BuildHintData(raw_route); - } - - inline osrm::json::Object BuildHintData(const InternalRouteResult &raw_route) const - { - osrm::json::Object json_hint_object; - json_hint_object.values["checksum"] = facade->GetCheckSum(); - osrm::json::Array json_location_hint_array; - std::string hint; - for (const auto i : osrm::irange(0, raw_route.segment_end_coordinates.size())) - { - ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates[i].source_phantom, - hint); - json_location_hint_array.values.push_back(hint); - } - ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates.back().target_phantom, - hint); - json_location_hint_array.values.push_back(hint); - json_hint_object.values["locations"] = json_location_hint_array; - - return json_hint_object; - } - - inline osrm::json::Array - BuildTextualDescription(const DescriptionFactory &description_factory, - std::vector &route_segments_list) const - { - osrm::json::Array json_instruction_array; - // Segment information has following format: - //["instruction id","streetname",length,position,time,"length","earth_direction",azimuth] - unsigned necessary_segments_running_index = 0; - - struct RoundAbout - { - RoundAbout() - : start_index(std::numeric_limits::max()), name_id(INVALID_NAMEID), - leave_at_exit(std::numeric_limits::max()) - { - } - int start_index; - unsigned name_id; - int leave_at_exit; - } round_about; - - round_about.leave_at_exit = 0; - round_about.name_id = 0; - std::string temp_dist, temp_length, temp_duration, temp_bearing, temp_instruction; - - // Fetch data from Factory and generate a string from it. - for (const SegmentInformation &segment : description_factory.path_description) - { - osrm::json::Array json_instruction_row; - TurnInstruction current_instruction = segment.turn_instruction; - if (TurnInstructionsClass::TurnIsNecessary(current_instruction)) - { - if (TurnInstruction::EnterRoundAbout == current_instruction) - { - round_about.name_id = segment.name_id; - round_about.start_index = necessary_segments_running_index; - } - else - { - std::string current_turn_instruction; - if (TurnInstruction::LeaveRoundAbout == current_instruction) - { - temp_instruction = std::to_string( - cast::enum_to_underlying(TurnInstruction::EnterRoundAbout)); - current_turn_instruction += temp_instruction; - current_turn_instruction += "-"; - temp_instruction = std::to_string(round_about.leave_at_exit + 1); - current_turn_instruction += temp_instruction; - round_about.leave_at_exit = 0; - } - else - { - temp_instruction = - std::to_string(cast::enum_to_underlying(current_instruction)); - current_turn_instruction += temp_instruction; - } - json_instruction_row.values.push_back(current_turn_instruction); - - json_instruction_row.values.push_back(facade->get_name_for_id(segment.name_id)); - json_instruction_row.values.push_back(std::round(segment.length)); - json_instruction_row.values.push_back(necessary_segments_running_index); - json_instruction_row.values.push_back(std::round(segment.duration / 10.)); - json_instruction_row.values.push_back( - std::to_string(static_cast(segment.length)) + "m"); - - // post turn bearing - const double post_turn_bearing_value = (segment.post_turn_bearing / 10.); - json_instruction_row.values.push_back(bearing::get(post_turn_bearing_value)); - json_instruction_row.values.push_back( - static_cast(round(post_turn_bearing_value))); - - json_instruction_row.values.push_back(segment.travel_mode); - - // pre turn bearing - const double pre_turn_bearing_value = (segment.pre_turn_bearing / 10.); - json_instruction_row.values.push_back(bearing::get(pre_turn_bearing_value)); - json_instruction_row.values.push_back( - static_cast(round(pre_turn_bearing_value))); - - json_instruction_array.values.push_back(json_instruction_row); - - route_segments_list.emplace_back( - segment.name_id, static_cast(segment.length), - static_cast(route_segments_list.size())); - } - } - else if (TurnInstruction::StayOnRoundAbout == current_instruction) - { - ++round_about.leave_at_exit; - } - if (segment.necessary) - { - ++necessary_segments_running_index; - } - } - - osrm::json::Array json_last_instruction_row; - temp_instruction = - std::to_string(cast::enum_to_underlying(TurnInstruction::ReachedYourDestination)); - json_last_instruction_row.values.push_back(temp_instruction); - json_last_instruction_row.values.push_back(""); - json_last_instruction_row.values.push_back(0); - json_last_instruction_row.values.push_back(necessary_segments_running_index - 1); - json_last_instruction_row.values.push_back(0); - json_last_instruction_row.values.push_back("0m"); - json_last_instruction_row.values.push_back(bearing::get(0.0)); - json_last_instruction_row.values.push_back(0.); - json_last_instruction_row.values.push_back(bearing::get(0.0)); - json_last_instruction_row.values.push_back(0.); - json_instruction_array.values.push_back(json_last_instruction_row); - - return json_instruction_array; - } -}; - -#endif /* JSON_DESCRIPTOR_H_ */ diff --git a/include/engine/guidance/segment_compression.hpp b/include/engine/guidance/segment_compression.hpp new file mode 100644 index 000000000..7981dbcaa --- /dev/null +++ b/include/engine/guidance/segment_compression.hpp @@ -0,0 +1,66 @@ +#ifndef ENGINE_GUIDANCE_PROCESSING_SEGMENT_COMPRESSION_HPP_ +#define ENGINE_GUIDANCE_PROCESSING_SEGMENT_COMPRESSION_HPP_ + +#include "engine/segment_inforamtion.hpp" + +#include + +namespace osrm +{ +namespace engine +{ +namespace guidance +{ + +/* + Simplify turn instructions + Input : + 10. Turn left on B 36 for 20 km + 11. Continue on B 35; B 36 for 2 km + 12. Continue on B 36 for 13 km + + Output: + 10. Turn left on B 36 for 35 km +*/ + +inline void CombineSimilarSegments(std::vector &segments) +{ + // TODO: rework to check only end and start of string. + // stl string is way to expensive + // unsigned lastTurn = 0; + // for(unsigned i = 1; i < path_description.size(); ++i) { + // string1 = sEngine.GetEscapedNameForNameID(path_description[i].name_id); + // if(TurnInstruction::GoStraight == path_description[i].turn_instruction) { + // if(std::string::npos != string0.find(string1+";") + // || std::string::npos != string0.find(";"+string1) + // || std::string::npos != string0.find(string1+" ;") + // || std::string::npos != string0.find("; "+string1) + // ){ + // SimpleLogger().Write() << "->next correct: " << string0 << " contains " << + // string1; + // for(; lastTurn != i; ++lastTurn) + // path_description[lastTurn].name_id = path_description[i].name_id; + // path_description[i].turn_instruction = TurnInstruction::NoTurn; + // } else if(std::string::npos != string1.find(string0+";") + // || std::string::npos != string1.find(";"+string0) + // || std::string::npos != string1.find(string0+" ;") + // || std::string::npos != string1.find("; "+string0) + // ){ + // SimpleLogger().Write() << "->prev correct: " << string1 << " contains " << + // string0; + // path_description[i].name_id = path_description[i-1].name_id; + // path_description[i].turn_instruction = TurnInstruction::NoTurn; + // } + // } + // if (TurnInstruction::NoTurn != path_description[i].turn_instruction) { + // lastTurn = i; + // } + // string0 = string1; + // } + // +} +} // namespace guidance +} // namespace engine +} // namespace osrm + +#endif //ENGINE_GUIDANCE_PROCESSING_SEGMENT_COMPRESSION_HPP_ diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp new file mode 100644 index 000000000..97c059c2c --- /dev/null +++ b/include/engine/guidance/segment_list.hpp @@ -0,0 +1,326 @@ +#ifndef ENGINE_GUIDANCE_SEGMENT_LIST_HPP_ +#define ENGINE_GUIDANCE_SEGMENT_LIST_HPP_ + +#include "osrm/coordinate.hpp" + +#include "engine/douglas_peucker.hpp" +#include "engine/internal_route_result.hpp" +#include "engine/phantom_node.hpp" +#include "engine/segment_information.hpp" + +#include "extractor/turn_instructions.hpp" + +#include + +#include +#include +#include +#include + +// transfers the internal edge based data structures to a more useable format +namespace osrm +{ +namespace engine +{ +namespace guidance +{ +template class SegmentList +{ + public: + using DataFacade = DataFacadeT; + SegmentList(const InternalRouteResult &raw_route, + const bool extract_alternative, + const unsigned zoom_level, + const bool allow_simplification, + const DataFacade *facade); + + const std::vector &GetViaIndices() const; + std::uint32_t GetDistance() const; + std::uint32_t GetDuration() const; + + const std::vector &Get() const; + + private: + void InitRoute(const PhantomNode &phantom_node, const bool traversed_in_reverse); + void AddLeg(const std::vector &leg_data, + const PhantomNode &target_node, + const bool traversed_in_reverse, + const bool is_via_leg, + const DataFacade *facade); + + void AppendSegment(const FixedPointCoordinate &coordinate, const PathData &path_point); + void Finalize(const bool extract_alternative, + const InternalRouteResult &raw_route, + const unsigned zoom_level, + const bool allow_simplification); + + // journey length in tenth of a second + std::uint32_t total_distance; + // journey distance in meter (TODO: verify) + std::uint32_t total_duration; + + // segments that are required to keep + std::vector via_indices; + + // a list of node based segments + std::vector segments; +}; + +template +SegmentList::SegmentList(const InternalRouteResult &raw_route, + const bool extract_alternative, + const unsigned zoom_level, + const bool allow_simplification, + const DataFacade *facade) + : total_distance(0), total_duration(0) +{ + if (not raw_route.is_valid()) + { + return; + } + + if (extract_alternative) + { + BOOST_ASSERT(raw_route.has_alternative()); + InitRoute(raw_route.segment_end_coordinates.front().source_phantom, + raw_route.alt_source_traversed_in_reverse.front()); + AddLeg(raw_route.unpacked_alternative, + raw_route.segment_end_coordinates.back().target_phantom, + raw_route.alt_source_traversed_in_reverse.back(), false, facade); + } + else + { + InitRoute(raw_route.segment_end_coordinates.front().source_phantom, + raw_route.source_traversed_in_reverse.front()); + for (std::size_t raw_index = 0; raw_index < raw_route.segment_end_coordinates.size(); + ++raw_index) + { + AddLeg(raw_route.unpacked_path_segments[raw_index], + raw_route.segment_end_coordinates[raw_index].target_phantom, + raw_route.target_traversed_in_reverse[raw_index], + raw_route.is_via_leg(raw_index), facade); + } + } + + if (not allow_simplification) + { + // to prevent any simplifications, we mark all segments as necessary + for (auto &segment : segments) + { + segment.necessary = true; + } + } + + Finalize(extract_alternative, raw_route, zoom_level, allow_simplification); +} + +template +void SegmentList::InitRoute(const PhantomNode &node, const bool traversed_in_reverse) +{ + const auto segment_duration = + (traversed_in_reverse ? node.reverse_weight : node.forward_weight); + const auto travel_mode = + (traversed_in_reverse ? node.backward_travel_mode : node.forward_travel_mode); + + AppendSegment(node.location, PathData(0, node.name_id, TurnInstruction::HeadOn, + segment_duration, travel_mode)); +} + +template +void SegmentList::AddLeg(const std::vector &leg_data, + const PhantomNode &target_node, + const bool traversed_in_reverse, + const bool is_via_leg, + const DataFacade *facade) +{ + for (const PathData &path_data : leg_data) + { + AppendSegment(facade->GetCoordinateOfNode(path_data.node), path_data); + } + + const EdgeWeight segment_duration = + (traversed_in_reverse ? target_node.reverse_weight : target_node.forward_weight); + const TravelMode travel_mode = + (traversed_in_reverse ? target_node.backward_travel_mode : target_node.forward_travel_mode); + segments.emplace_back(target_node.location, target_node.name_id, segment_duration, 0.f, + is_via_leg ? TurnInstruction::ReachViaLocation : TurnInstruction::NoTurn, + true, true, travel_mode); +} + +template std::uint32_t SegmentList::GetDistance() const +{ + return total_distance; +} +template std::uint32_t SegmentList::GetDuration() const +{ + return total_duration; +} + +template +std::vector const &SegmentList::GetViaIndices() const +{ + return via_indices; +} + +template +std::vector const &SegmentList::Get() const +{ + return segments; +} + +template +void SegmentList::AppendSegment(const FixedPointCoordinate &coordinate, + const PathData &path_point) +{ + // if the start location is on top of a node, the first movement might be zero-length, + // in which case we dont' add a new description, but instead update the existing one + if ((1 == segments.size()) and (segments.front().location == coordinate)) + { + if (path_point.segment_duration > 0) + { + segments.front().name_id = path_point.name_id; + segments.front().travel_mode = path_point.travel_mode; + } + return; + } + + // make sure mode changes are announced, even when there otherwise is no turn + const auto getTurn = [](const PathData &path_point, const TravelMode previous_mode) + { + if (TurnInstruction::NoTurn == path_point.turn_instruction and + previous_mode != path_point.travel_mode and path_point.segment_duration > 0) + { + return TurnInstruction::GoStraight; + } + return path_point.turn_instruction; + }; + + // TODO check why we require .front() here + const auto turn = segments.size() ? getTurn(path_point, segments.front().travel_mode) + : path_point.turn_instruction; + + segments.emplace_back(coordinate, path_point.name_id, path_point.segment_duration, 0.f, turn, + path_point.travel_mode); +} + +template +void SegmentList::Finalize(const bool extract_alternative, + const InternalRouteResult &raw_route, + const unsigned zoom_level, + const bool allow_simplification) +{ + if (segments.empty()) + return; + + segments[0].length = 0.f; + for (const auto i : osrm::irange(1, segments.size())) + { + // move down names by one, q&d hack + segments[i - 1].name_id = segments[i].name_id; + segments[i].length = coordinate_calculation::greatCircleDistance(segments[i - 1].location, + segments[i].location); + } + + float segment_length = 0.; + EdgeWeight segment_duration = 0; + std::size_t segment_start_index = 0; + + double path_length = 0; + + for (const auto i : osrm::irange(1, segments.size())) + { + path_length += segments[i].length; + segment_length += segments[i].length; + segment_duration += segments[i].duration; + segments[segment_start_index].length = segment_length; + segments[segment_start_index].duration = segment_duration; + + if (TurnInstruction::NoTurn != segments[i].turn_instruction) + { + BOOST_ASSERT(segments[i].necessary); + segment_length = 0; + segment_duration = 0; + segment_start_index = i; + } + } + + total_distance = static_cast(std::round(path_length)); + total_duration = static_cast(std::round( + (extract_alternative ? raw_route.alternative_path_length : raw_route.shortest_path_length) / + 10.)); + + auto start_phantom = raw_route.segment_end_coordinates.front().source_phantom; + auto target_phantom = raw_route.segment_end_coordinates.back().target_phantom; + + // Post-processing to remove empty or nearly empty path segments + if (segments.size() > 2 && std::numeric_limits::epsilon() > segments.back().length && + !(segments.end() - 2)->is_via_location) + { + segments.pop_back(); + segments.back().necessary = true; + segments.back().turn_instruction = TurnInstruction::NoTurn; + target_phantom.name_id = + (segments.end() - 2) + ->name_id; // TODO check whether this -2 is desired after the pop-back + } + + if (segments.size() > 2 && std::numeric_limits::epsilon() > segments.front().length && + !(segments.begin() + 1)->is_via_location) + { + segments.erase(segments.begin()); + segments.front().turn_instruction = TurnInstruction::HeadOn; + segments.front().necessary = true; + start_phantom.name_id = segments.front().name_id; + } + + if (allow_simplification) + { + DouglasPeucker polyline_generalizer; + polyline_generalizer.Run(segments.begin(), segments.end(), zoom_level); + } + + std::uint32_t necessary_segments = 0; // a running index that counts the necessary pieces + via_indices.push_back(0); + const auto markNecessarySegments = [this, &necessary_segments](SegmentInformation &first, + const SegmentInformation &second) + { + if (!first.necessary) + return; + + // mark the end of a leg (of several segments) + if (first.is_via_location) + via_indices.push_back(necessary_segments); + + const double post_turn_bearing = + coordinate_calculation::bearing(first.location, second.location); + const double pre_turn_bearing = + coordinate_calculation::bearing(second.location, first.location); + first.post_turn_bearing = static_cast(post_turn_bearing * 10); + first.pre_turn_bearing = static_cast(pre_turn_bearing * 10); + + ++necessary_segments; + }; + + // calculate which segments are necessary and update segments for bearings + osrm::for_each_pair(segments, markNecessarySegments); + via_indices.push_back(necessary_segments); + + BOOST_ASSERT(via_indices.size() >= 2); +} + +template +SegmentList MakeSegmentList(const InternalRouteResult &raw_route, + const bool extract_alternative, + const unsigned zoom_level, + const bool allow_simplification, + const DataFacadeT *facade) +{ + return SegmentList(raw_route, extract_alternative, zoom_level, + allow_simplification, facade); +} + +} // namespace guidance +} // namespace engine +} // namespace osrm + +#endif // ENGINE_GUIDANCE_SEGMENT_LIST_HPP_ diff --git a/include/engine/guidance/textual_route_annotation.hpp b/include/engine/guidance/textual_route_annotation.hpp new file mode 100644 index 000000000..97329a8e9 --- /dev/null +++ b/include/engine/guidance/textual_route_annotation.hpp @@ -0,0 +1,134 @@ +#ifndef ENGINE_GUIDANCE_TEXTUAL_ROUTE_ANNOTATIONS_HPP_ +#define ENGINE_GUIDANCE_TEXTUAL_ROUTE_ANNOTATIONS_HPP_ + +#include "engine/segment_information.hpp" +#include "engine/guidance/segment_list.hpp" +#include "extractor/turn_instructions.hpp" +#include "osrm/json_container.hpp" +#include "util/bearing.hpp" +#include "util/cast.hpp" + +#include + +#include +#include +#include +#include + +namespace osrm +{ +namespace engine +{ +namespace guidance +{ +template< typename DataFacadeT > +inline osrm::json::Array +AnnotateRoute(const std::vector &route_segments, DataFacadeT* facade) +{ + osrm::json::Array json_instruction_array; + if( route_segments.empty() ) + return json_instruction_array; + // Segment information has following format: + //["instruction id","streetname",length,position,time,"length","earth_direction",azimuth] + std::int32_t necessary_segments_running_index = 0; + + struct RoundAbout + { + std::int32_t start_index; + std::uint32_t name_id; + std::int32_t leave_at_exit; + } round_about; + + round_about = {std::numeric_limits::max(), 0, 0}; + std::string temp_dist, temp_length, temp_duration, temp_bearing, temp_instruction; + + //Generate annotations for every segment + for (const SegmentInformation &segment : route_segments) + { + osrm::json::Array json_instruction_row; + TurnInstruction current_instruction = segment.turn_instruction; + if (TurnInstructionsClass::TurnIsNecessary(current_instruction)) + { + if (TurnInstruction::EnterRoundAbout == current_instruction) + { + round_about.name_id = segment.name_id; + round_about.start_index = necessary_segments_running_index; + } + else + { + std::string current_turn_instruction; + if (TurnInstruction::LeaveRoundAbout == current_instruction) + { + temp_instruction = + std::to_string(cast::enum_to_underlying(TurnInstruction::EnterRoundAbout)); + current_turn_instruction += temp_instruction; + current_turn_instruction += "-"; + temp_instruction = std::to_string(round_about.leave_at_exit + 1); + current_turn_instruction += temp_instruction; + round_about.leave_at_exit = 0; + } + else + { + temp_instruction = + std::to_string(cast::enum_to_underlying(current_instruction)); + current_turn_instruction += temp_instruction; + } + json_instruction_row.values.emplace_back(std::move(current_turn_instruction)); + + json_instruction_row.values.push_back(facade->get_name_for_id(segment.name_id)); + json_instruction_row.values.push_back(std::round(segment.length)); + json_instruction_row.values.push_back(necessary_segments_running_index); + json_instruction_row.values.push_back(std::round(segment.duration / 10.)); + json_instruction_row.values.push_back( + std::to_string(static_cast(segment.length)) + "m"); + + // post turn bearing + const double post_turn_bearing_value = (segment.post_turn_bearing / 10.); + json_instruction_row.values.push_back(bearing::get(post_turn_bearing_value)); + json_instruction_row.values.push_back( + static_cast(std::round(post_turn_bearing_value))); + + json_instruction_row.values.push_back(segment.travel_mode); + + // pre turn bearing + const double pre_turn_bearing_value = (segment.pre_turn_bearing / 10.); + json_instruction_row.values.push_back(bearing::get(pre_turn_bearing_value)); + json_instruction_row.values.push_back( + static_cast(std::round(pre_turn_bearing_value))); + + json_instruction_array.values.push_back(json_instruction_row); + } + } + else if (TurnInstruction::StayOnRoundAbout == current_instruction) + { + ++round_about.leave_at_exit; + } + if (segment.necessary) + { + ++necessary_segments_running_index; + } + } + + osrm::json::Array json_last_instruction_row; + temp_instruction = + std::to_string(cast::enum_to_underlying(TurnInstruction::ReachedYourDestination)); + json_last_instruction_row.values.emplace_back( std::move(temp_instruction)); + json_last_instruction_row.values.push_back(""); + json_last_instruction_row.values.push_back(0); + json_last_instruction_row.values.push_back(necessary_segments_running_index - 1); + json_last_instruction_row.values.push_back(0); + json_last_instruction_row.values.push_back("0m"); + json_last_instruction_row.values.push_back(bearing::get(0.0)); + json_last_instruction_row.values.push_back(0.); + json_last_instruction_row.values.push_back(bearing::get(0.0)); + json_last_instruction_row.values.push_back(0.); + json_instruction_array.values.emplace_back(std::move(json_last_instruction_row)); + + return json_instruction_array; +} + +} // namespace guidance +} // namespace engine +} // namespace osrm + +#endif diff --git a/include/engine/internal_route_result.hpp b/include/engine/internal_route_result.hpp index 551cf7ea6..0ff802fe8 100644 --- a/include/engine/internal_route_result.hpp +++ b/include/engine/internal_route_result.hpp @@ -46,6 +46,10 @@ struct InternalRouteResult int shortest_path_length; int alternative_path_length; + bool is_valid() const { return INVALID_EDGE_WEIGHT != shortest_path_length; } + + bool has_alternative() const { return INVALID_EDGE_WEIGHT != alternative_path_length; } + bool is_via_leg(const std::size_t leg) const { return (leg != unpacked_path_segments.size() - 1); diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index 4c664c845..11151ae4c 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -4,21 +4,15 @@ #include "engine/plugins/plugin_base.hpp" #include "engine/object_encoder.hpp" -#include "contractor/query_edge.hpp" #include "engine/search_engine.hpp" -#include "engine/descriptors/descriptor_base.hpp" -#include "util/json_renderer.hpp" #include "util/make_unique.hpp" #include "util/string_util.hpp" -#include "util/timing_util.hpp" - #include "osrm/json_container.hpp" #include #include #include -#include #include #include diff --git a/include/engine/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp index d3ecdf990..3208b9b91 100644 --- a/include/engine/plugins/hello_world.hpp +++ b/include/engine/plugins/hello_world.hpp @@ -3,8 +3,6 @@ #include "engine/plugins/plugin_base.hpp" -#include "util/json_renderer.hpp" - #include "osrm/json_container.hpp" #include diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index bb786c1b8..54819e88f 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -6,8 +6,9 @@ #include "engine/map_matching/bayes_classifier.hpp" #include "engine/object_encoder.hpp" #include "engine/search_engine.hpp" -#include "engine/descriptors/descriptor_base.hpp" -#include "engine/descriptors/json_descriptor.hpp" +#include "engine/guidance/textual_route_annotation.hpp" +#include "engine/guidance/segment_list.hpp" +#include "engine/api_response_generator.hpp" #include "engine/routing_algorithms/map_matching.hpp" #include "util/compute_angle.hpp" #include "util/integer_range.hpp" @@ -185,55 +186,37 @@ template class MapMatchingPlugin : public BasePlugin subtrace.values["confidence"] = sub.confidence; } - JSONDescriptor json_descriptor(facade); - json_descriptor.SetConfig(route_parameters); + auto response_generator = osrm::engine::MakeApiResponseGenerator(facade); - subtrace.values["hint_data"] = json_descriptor.BuildHintData(raw_route); + subtrace.values["hint_data"] = response_generator.BuildHintData(raw_route); if (route_parameters.geometry || route_parameters.print_instructions) { - DescriptionFactory factory; - FixedPointCoordinate current_coordinate; - factory.SetStartSegment(raw_route.segment_end_coordinates.front().source_phantom, - raw_route.source_traversed_in_reverse.front()); - for (const auto i : - osrm::irange(0, raw_route.unpacked_path_segments.size())) - { - for (const PathData &path_data : raw_route.unpacked_path_segments[i]) - { - current_coordinate = facade->GetCoordinateOfNode(path_data.node); - factory.AppendSegment(current_coordinate, path_data); - } - factory.SetEndSegment(raw_route.segment_end_coordinates[i].target_phantom, - raw_route.target_traversed_in_reverse[i], - raw_route.is_via_leg(i)); - } - - factory.Run(route_parameters.zoom_level); - - // we need because we don't run path simplification - for (auto &segment : factory.path_description) - { - segment.necessary = true; - } + using SegmentList = osrm::engine::guidance::SegmentList; + //Passing false to extract_alternative extracts the route. + const constexpr bool EXTRACT_ROUTE = false; + // by passing false to segment_list, we skip the douglas peucker simplification + // and mark all segments as necessary within the generation process + const constexpr bool NO_ROUTE_SIMPLIFICATION = false; + SegmentList segment_list(raw_route, EXTRACT_ROUTE, route_parameters.zoom_level, + NO_ROUTE_SIMPLIFICATION, facade); if (route_parameters.geometry) { subtrace.values["geometry"] = - factory.AppendGeometryString(route_parameters.compression); + response_generator.GetGeometry(route_parameters.compression, segment_list); } if (route_parameters.print_instructions) { - std::vector::Segment> temp_segments; subtrace.values["instructions"] = - json_descriptor.BuildTextualDescription(factory, temp_segments); + osrm::engine::guidance::AnnotateRoute( + segment_list.Get(), facade); } - factory.BuildRouteSummary(factory.get_entire_length(), raw_route.shortest_path_length); osrm::json::Object json_route_summary; - json_route_summary.values["total_distance"] = factory.summary.distance; - json_route_summary.values["total_time"] = factory.summary.duration; + json_route_summary.values["total_distance"] = segment_list.GetDistance(); + json_route_summary.values["total_time"] = segment_list.GetDuration(); subtrace.values["route_summary"] = json_route_summary; } diff --git a/include/engine/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp index 8db98ae40..28443dcf1 100644 --- a/include/engine/plugins/nearest.hpp +++ b/include/engine/plugins/nearest.hpp @@ -2,11 +2,8 @@ #define NEAREST_HPP #include "engine/plugins/plugin_base.hpp" - #include "engine/phantom_node.hpp" #include "util/integer_range.hpp" -#include "util/json_renderer.hpp" - #include "osrm/json_container.hpp" #include diff --git a/include/engine/plugins/timestamp.hpp b/include/engine/plugins/timestamp.hpp index beb02caac..b479f01fc 100644 --- a/include/engine/plugins/timestamp.hpp +++ b/include/engine/plugins/timestamp.hpp @@ -3,8 +3,6 @@ #include "engine/plugins/plugin_base.hpp" -#include "util/json_renderer.hpp" - #include "osrm/json_container.hpp" #include diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index c1eae77e1..9ef2909bc 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -9,17 +9,12 @@ #include "engine/trip/trip_farthest_insertion.hpp" #include "engine/trip/trip_brute_force.hpp" #include "engine/search_engine.hpp" -#include "util/matrix_graph_wrapper.hpp" // wrapper to use tarjan - // scc on dist table -#include "engine/descriptors/descriptor_base.hpp" // to make json output -#include "engine/descriptors/json_descriptor.hpp" // to make json output +#include "util/matrix_graph_wrapper.hpp" // wrapper to use tarjan scc on dist table +#include "engine/api_response_generator.hpp" #include "util/make_unique.hpp" -#include "util/timing_util.hpp" // to time runtime -//#include "util/simple_logger.hpp" // for logging output -#include "util/dist_table_wrapper.hpp" // to access the dist - // table more easily - +#include "util/dist_table_wrapper.hpp" // to access the dist table more easily #include "osrm/json_container.hpp" + #include #include @@ -284,7 +279,6 @@ template class RoundTripPlugin final : public BasePlugin std::vector> route_result; route_result.reserve(scc.GetNumberOfComponents()); - TIMER_START(TRIP_TIMER); // run Trip computation for every SCC for (std::size_t k = 0; k < scc.GetNumberOfComponents(); ++k) { @@ -337,24 +331,20 @@ template class RoundTripPlugin final : public BasePlugin comp_route.push_back(ComputeRoute(phantom_node_list, route_parameters, elem)); } - TIMER_STOP(TRIP_TIMER); - // prepare JSON output // create a json object for every trip osrm::json::Array trip; for (std::size_t i = 0; i < route_result.size(); ++i) { - std::unique_ptr> descriptor = - osrm::make_unique>(facade); - descriptor->SetConfig(route_parameters); - osrm::json::Object scc_trip; + // annotate comp_route[i] as a json trip + auto generator = osrm::engine::MakeApiResponseGenerator(facade); + generator.DescribeRoute(route_parameters, comp_route[i], scc_trip); + // set permutation output SetLocPermutationOutput(route_result[i], scc_trip); // set viaroute output - descriptor->Run(comp_route[i], scc_trip); - trip.values.push_back(std::move(scc_trip)); } diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index b79b28833..6b432e55d 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -3,17 +3,14 @@ #include "engine/plugins/plugin_base.hpp" +#include "engine/api_response_generator.hpp" #include "engine/object_encoder.hpp" #include "engine/search_engine.hpp" -#include "engine/descriptors/descriptor_base.hpp" -#include "engine/descriptors/gpx_descriptor.hpp" -#include "engine/descriptors/json_descriptor.hpp" #include "util/integer_range.hpp" #include "util/json_renderer.hpp" #include "util/make_unique.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" - #include "osrm/json_container.hpp" #include @@ -26,7 +23,6 @@ template class ViaRoutePlugin final : public BasePlugin { private: - DescriptorTable descriptor_table; std::string descriptor_string; std::unique_ptr> search_engine_ptr; DataFacadeT *facade; @@ -38,10 +34,6 @@ template class ViaRoutePlugin final : public BasePlugin max_locations_viaroute(max_locations_viaroute) { search_engine_ptr = osrm::make_unique>(facade); - - descriptor_table.emplace("json", 0); - descriptor_table.emplace("gpx", 1); - // descriptor_table.emplace("geojson", 2); } virtual ~ViaRoutePlugin() {} @@ -139,22 +131,8 @@ template class ViaRoutePlugin final : public BasePlugin bool no_route = INVALID_EDGE_WEIGHT == raw_route.shortest_path_length; - std::unique_ptr> descriptor; - switch (descriptor_table.get_id(route_parameters.output_format)) - { - case 1: - descriptor = osrm::make_unique>(facade); - break; - // case 2: - // descriptor = osrm::make_unique>(); - // break; - default: - descriptor = osrm::make_unique>(facade); - break; - } - - descriptor->SetConfig(route_parameters); - descriptor->Run(raw_route, json_result); + auto generator = osrm::engine::MakeApiResponseGenerator(facade); + generator.DescribeRoute(route_parameters, raw_route, json_result); // we can only know this after the fact, different SCC ids still // allow for connection in one direction. diff --git a/include/engine/route_name_extraction.hpp b/include/engine/route_name_extraction.hpp index 7684e80d7..97e1919bb 100644 --- a/include/engine/route_name_extraction.hpp +++ b/include/engine/route_name_extraction.hpp @@ -23,6 +23,7 @@ template struct ExtractRouteNames const unsigned blocked_name_id) const { SegmentT result_segment; + result_segment.name_id = blocked_name_id; //make sure we get a valid name result_segment.length = 0; for (const SegmentT &segment : segment_list) @@ -123,11 +124,13 @@ template struct ExtractRouteNames route_names.shortest_path_name_1 = facade->get_name_for_id(shortest_segment_1.name_id); route_names.shortest_path_name_2 = facade->get_name_for_id(shortest_segment_2.name_id); - route_names.alternative_path_name_1 = - facade->get_name_for_id(alternative_segment_1.name_id); - route_names.alternative_path_name_2 = - facade->get_name_for_id(alternative_segment_2.name_id); - + if (not alternative_path_segments.empty()) + { + route_names.alternative_path_name_1 = + facade->get_name_for_id(alternative_segment_1.name_id); + route_names.alternative_path_name_2 = + facade->get_name_for_id(alternative_segment_2.name_id); + } return route_names; } }; diff --git a/src/engine/descriptors/description_factory.cpp b/src/engine/descriptors/description_factory.cpp deleted file mode 100644 index 9e6fafa7e..000000000 --- a/src/engine/descriptors/description_factory.cpp +++ /dev/null @@ -1,224 +0,0 @@ -#include "engine/descriptors/description_factory.hpp" - -#include "engine/polyline_formatter.hpp" -#include "util/coordinate_calculation.hpp" -#include "engine/internal_route_result.hpp" -#include "extractor/turn_instructions.hpp" -#include "util/container.hpp" -#include "util/integer_range.hpp" -#include "util/typedefs.hpp" - -DescriptionFactory::DescriptionFactory() : entire_length(0) { via_indices.push_back(0); } - -std::vector const &DescriptionFactory::GetViaIndices() const { return via_indices; } - -void DescriptionFactory::SetStartSegment(const PhantomNode &source, const bool traversed_in_reverse) -{ - start_phantom = source; - const EdgeWeight segment_duration = - (traversed_in_reverse ? source.reverse_weight : source.forward_weight); - const TravelMode travel_mode = - (traversed_in_reverse ? source.backward_travel_mode : source.forward_travel_mode); - AppendSegment(source.location, PathData(0, source.name_id, TurnInstruction::HeadOn, - segment_duration, travel_mode)); - BOOST_ASSERT(path_description.back().duration == segment_duration); -} - -void DescriptionFactory::SetEndSegment(const PhantomNode &target, - const bool traversed_in_reverse, - const bool is_via_location) -{ - target_phantom = target; - const EdgeWeight segment_duration = - (traversed_in_reverse ? target.reverse_weight : target.forward_weight); - const TravelMode travel_mode = - (traversed_in_reverse ? target.backward_travel_mode : target.forward_travel_mode); - path_description.emplace_back(target.location, target.name_id, segment_duration, 0.f, - is_via_location ? TurnInstruction::ReachViaLocation - : TurnInstruction::NoTurn, - true, true, travel_mode); - BOOST_ASSERT(path_description.back().duration == segment_duration); -} - -void DescriptionFactory::AppendSegment(const FixedPointCoordinate &coordinate, - const PathData &path_point) -{ - // if the start location is on top of a node, the first movement might be zero-length, - // in which case we dont' add a new description, but instead update the existing one - if ((1 == path_description.size()) && (path_description.front().location == coordinate)) - { - if (path_point.segment_duration > 0) - { - path_description.front().name_id = path_point.name_id; - path_description.front().travel_mode = path_point.travel_mode; - } - return; - } - - // make sure mode changes are announced, even when there otherwise is no turn - const TurnInstruction turn = [&]() -> TurnInstruction - { - if (TurnInstruction::NoTurn == path_point.turn_instruction && - path_description.front().travel_mode != path_point.travel_mode && - path_point.segment_duration > 0) - { - return TurnInstruction::GoStraight; - } - return path_point.turn_instruction; - }(); - - path_description.emplace_back(coordinate, path_point.name_id, path_point.segment_duration, 0.f, - turn, path_point.travel_mode); -} - -osrm::json::Value DescriptionFactory::AppendGeometryString(const bool return_encoded) -{ - if (return_encoded) - { - return PolylineFormatter().printEncodedString(path_description); - } - return PolylineFormatter().printUnencodedString(path_description); -} - -void DescriptionFactory::BuildRouteSummary(const double distance, const unsigned time) -{ - summary.source_name_id = start_phantom.name_id; - summary.target_name_id = target_phantom.name_id; - summary.BuildDurationAndLengthStrings(distance, time); -} - -void DescriptionFactory::Run(const unsigned zoom_level) -{ - if (path_description.empty()) - { - return; - } - - /** starts at index 1 */ - path_description[0].length = 0.f; - for (const auto i : osrm::irange(1, path_description.size())) - { - // move down names by one, q&d hack - path_description[i - 1].name_id = path_description[i].name_id; - path_description[i].length = coordinate_calculation::greatCircleDistance( - path_description[i - 1].location, path_description[i].location); - } - - /*Simplify turn instructions - Input : - 10. Turn left on B 36 for 20 km - 11. Continue on B 35; B 36 for 2 km - 12. Continue on B 36 for 13 km - - becomes: - 10. Turn left on B 36 for 35 km - */ - // TODO: rework to check only end and start of string. - // stl string is way to expensive - - // unsigned lastTurn = 0; - // for(unsigned i = 1; i < path_description.size(); ++i) { - // string1 = sEngine.GetEscapedNameForNameID(path_description[i].name_id); - // if(TurnInstruction::GoStraight == path_description[i].turn_instruction) { - // if(std::string::npos != string0.find(string1+";") - // || std::string::npos != string0.find(";"+string1) - // || std::string::npos != string0.find(string1+" ;") - // || std::string::npos != string0.find("; "+string1) - // ){ - // SimpleLogger().Write() << "->next correct: " << string0 << " contains " << - // string1; - // for(; lastTurn != i; ++lastTurn) - // path_description[lastTurn].name_id = path_description[i].name_id; - // path_description[i].turn_instruction = TurnInstruction::NoTurn; - // } else if(std::string::npos != string1.find(string0+";") - // || std::string::npos != string1.find(";"+string0) - // || std::string::npos != string1.find(string0+" ;") - // || std::string::npos != string1.find("; "+string0) - // ){ - // SimpleLogger().Write() << "->prev correct: " << string1 << " contains " << - // string0; - // path_description[i].name_id = path_description[i-1].name_id; - // path_description[i].turn_instruction = TurnInstruction::NoTurn; - // } - // } - // if (TurnInstruction::NoTurn != path_description[i].turn_instruction) { - // lastTurn = i; - // } - // string0 = string1; - // } - // - - float segment_length = 0.; - EdgeWeight segment_duration = 0; - std::size_t segment_start_index = 0; - - for (const auto i : osrm::irange(1, path_description.size())) - { - entire_length += path_description[i].length; - segment_length += path_description[i].length; - segment_duration += path_description[i].duration; - path_description[segment_start_index].length = segment_length; - path_description[segment_start_index].duration = segment_duration; - - if (TurnInstruction::NoTurn != path_description[i].turn_instruction) - { - BOOST_ASSERT(path_description[i].necessary); - segment_length = 0; - segment_duration = 0; - segment_start_index = i; - } - } - - // Post-processing to remove empty or nearly empty path segments - if (path_description.size() > 2 && - std::numeric_limits::epsilon() > path_description.back().length && - !(path_description.end() - 2)->is_via_location) - { - path_description.pop_back(); - path_description.back().necessary = true; - path_description.back().turn_instruction = TurnInstruction::NoTurn; - target_phantom.name_id = (path_description.end() - 2)->name_id; - } - - if (path_description.size() > 2 && - std::numeric_limits::epsilon() > path_description.front().length && - !(path_description.begin() + 1)->is_via_location) - { - path_description.erase(path_description.begin()); - path_description.front().turn_instruction = TurnInstruction::HeadOn; - path_description.front().necessary = true; - start_phantom.name_id = path_description.front().name_id; - } - - // Generalize poly line - polyline_generalizer.Run(path_description.begin(), path_description.end(), zoom_level); - - // fix what needs to be fixed else - unsigned necessary_segments = 0; // a running index that counts the necessary pieces - osrm::for_each_pair(path_description, - [&](SegmentInformation &first, const SegmentInformation &second) - { - if (!first.necessary) - { - return; - } - - if (first.is_via_location) - { // mark the end of a leg (of several segments) - via_indices.push_back(necessary_segments); - } - - const double post_turn_bearing = - coordinate_calculation::bearing(first.location, second.location); - const double pre_turn_bearing = - coordinate_calculation::bearing(second.location, first.location); - first.post_turn_bearing = static_cast(post_turn_bearing * 10); - first.pre_turn_bearing = static_cast(pre_turn_bearing * 10); - - ++necessary_segments; - }); - - via_indices.push_back(necessary_segments); - BOOST_ASSERT(via_indices.size() >= 2); - return; -} From efc9007cbfef1875d2970f5084a7c514aa55bd7b Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 7 Jan 2016 22:49:03 +0100 Subject: [PATCH 045/701] Remore start_phantom/target_phantom because they are useless here --- include/engine/guidance/segment_list.hpp | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index 97c059c2c..d034df6ee 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -7,11 +7,13 @@ #include "engine/internal_route_result.hpp" #include "engine/phantom_node.hpp" #include "engine/segment_information.hpp" - +#include "util/integer_range.hpp" +#include "util/coordinate_calculation.hpp" #include "extractor/turn_instructions.hpp" #include +#include #include #include #include @@ -249,9 +251,6 @@ void SegmentList::Finalize(const bool extract_alternative, (extract_alternative ? raw_route.alternative_path_length : raw_route.shortest_path_length) / 10.)); - auto start_phantom = raw_route.segment_end_coordinates.front().source_phantom; - auto target_phantom = raw_route.segment_end_coordinates.back().target_phantom; - // Post-processing to remove empty or nearly empty path segments if (segments.size() > 2 && std::numeric_limits::epsilon() > segments.back().length && !(segments.end() - 2)->is_via_location) @@ -259,9 +258,6 @@ void SegmentList::Finalize(const bool extract_alternative, segments.pop_back(); segments.back().necessary = true; segments.back().turn_instruction = TurnInstruction::NoTurn; - target_phantom.name_id = - (segments.end() - 2) - ->name_id; // TODO check whether this -2 is desired after the pop-back } if (segments.size() > 2 && std::numeric_limits::epsilon() > segments.front().length && @@ -270,7 +266,6 @@ void SegmentList::Finalize(const bool extract_alternative, segments.erase(segments.begin()); segments.front().turn_instruction = TurnInstruction::HeadOn; segments.front().necessary = true; - start_phantom.name_id = segments.front().name_id; } if (allow_simplification) From 6b18e4f7e903e7532dd59fd52cf94b83cef05141 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 5 Jan 2016 16:51:13 +0100 Subject: [PATCH 046/701] Add namespace around all files --- include/contractor/contractor.hpp | 48 +++--- include/contractor/contractor_options.hpp | 8 + include/contractor/crc32_processor.hpp | 8 + include/contractor/processing_chain.hpp | 31 ++-- include/contractor/query_edge.hpp | 8 + include/datastore/shared_memory_factory.hpp | 32 ++-- include/engine/api_response_generator.hpp | 60 +++---- include/engine/datafacade/datafacade_base.hpp | 27 +++- .../engine/datafacade/internal_datafacade.hpp | 91 ++++++----- include/engine/datafacade/shared_barriers.hpp | 11 ++ .../engine/datafacade/shared_datafacade.hpp | 121 +++++++------- include/engine/datafacade/shared_datatype.hpp | 51 +++--- include/engine/douglas_peucker.hpp | 8 + include/engine/geospatial_query.hpp | 28 ++-- include/engine/guidance/segment_list.hpp | 31 ++-- .../guidance/textual_route_annotation.hpp | 32 ++-- include/engine/internal_route_result.hpp | 18 ++- .../engine/map_matching/bayes_classifier.hpp | 11 ++ .../map_matching/hidden_markov_model.hpp | 25 +-- include/engine/object_encoder.hpp | 8 + include/engine/osrm_impl.hpp | 37 ++++- include/engine/phantom_node.hpp | 22 ++- include/engine/plugins/distance_table.hpp | 31 ++-- include/engine/plugins/hello_world.hpp | 23 ++- include/engine/plugins/match.hpp | 70 ++++---- include/engine/plugins/nearest.hpp | 23 ++- include/engine/plugins/plugin_base.hpp | 17 +- include/engine/plugins/timestamp.hpp | 13 +- include/engine/plugins/trip.hpp | 41 +++-- include/engine/plugins/viaroute.hpp | 21 ++- include/engine/polyline_compressor.hpp | 14 +- include/engine/polyline_formatter.hpp | 16 +- include/engine/route_name_extraction.hpp | 8 + .../routing_algorithms/alternative_path.hpp | 35 ++-- .../direct_shortest_path.hpp | 11 ++ .../routing_algorithms/many_to_many.hpp | 11 ++ .../routing_algorithms/map_matching.hpp | 55 ++++--- .../routing_algorithms/routing_base.hpp | 29 +++- .../routing_algorithms/shortest_path.hpp | 13 +- include/engine/search_engine.hpp | 18 ++- include/engine/search_engine_data.hpp | 10 +- include/engine/segment_information.hpp | 29 ++-- include/engine/trip/trip_brute_force.hpp | 12 +- .../engine/trip/trip_farthest_insertion.hpp | 13 +- .../engine/trip/trip_nearest_neighbour.hpp | 13 +- include/engine/trip/trip_tabu_search.hpp | 7 +- .../extractor/compressed_edge_container.hpp | 8 + .../extractor/edge_based_graph_factory.hpp | 18 ++- include/extractor/edge_based_node.hpp | 16 +- include/extractor/external_memory_node.hpp | 8 + include/extractor/extraction_containers.hpp | 8 + .../extractor/extraction_helper_functions.hpp | 16 +- include/extractor/extraction_node.hpp | 9 ++ include/extractor/extraction_way.hpp | 8 + include/extractor/extractor.hpp | 16 +- include/extractor/extractor_callbacks.hpp | 18 ++- include/extractor/extractor_options.hpp | 8 + .../first_and_last_segment_of_way.hpp | 8 + include/extractor/graph_compressor.hpp | 14 +- include/extractor/import_edge.hpp | 8 + include/extractor/internal_extractor_edge.hpp | 10 +- include/extractor/node_id.hpp | 8 + include/extractor/original_edge_data.hpp | 8 + include/extractor/query_node.hpp | 8 + include/extractor/raster_source.hpp | 14 +- include/extractor/restriction.hpp | 8 + include/extractor/restriction_map.hpp | 23 ++- include/extractor/restriction_parser.hpp | 9 ++ include/extractor/scripting_environment.hpp | 8 + include/extractor/speed_profile.hpp | 8 + include/extractor/tarjan_scc.hpp | 14 +- include/extractor/travel_mode.hpp | 14 +- include/extractor/turn_instructions.hpp | 8 + include/osrm/coordinate.hpp | 12 +- include/osrm/json_container.hpp | 11 ++ include/osrm/libosrm_config.hpp | 5 + include/osrm/osrm.hpp | 17 +- include/osrm/route_parameters.hpp | 11 ++ include/osrm/strong_typedef.hpp | 5 + include/server/api_grammar.hpp | 8 + include/server/connection.hpp | 17 +- include/server/http/compression_type.hpp | 7 + include/server/http/header.hpp | 8 + include/server/http/reply.hpp | 8 + include/server/http/request.hpp | 8 +- include/server/request_handler.hpp | 20 ++- include/server/request_parser.hpp | 21 ++- include/server/server.hpp | 16 +- include/util/bearing.hpp | 8 + include/util/binary_heap.hpp | 8 + include/util/cast.hpp | 8 + include/util/compute_angle.hpp | 8 + include/util/container.hpp | 5 + include/util/coordinate_calculation.hpp | 12 +- include/util/datastore_options.hpp | 24 ++- include/util/deallocating_vector.hpp | 10 +- include/util/debug_geometry.hpp | 39 +++-- include/util/dist_table_wrapper.hpp | 8 + include/util/dynamic_graph.hpp | 26 +-- include/util/fingerprint.hpp | 8 + include/util/fingerprint_impl.hpp.in | 16 +- include/util/fixed_point_number.hpp | 5 + include/util/floating_point.hpp | 5 + include/util/graph_loader.hpp | 28 ++-- include/util/graph_utils.hpp | 8 + include/util/hilbert_value.hpp | 8 + include/util/ini_file.hpp | 8 + include/util/integer_range.hpp | 4 + include/util/iso_8601_duration_parser.hpp | 8 + include/util/json_logger.hpp | 6 +- include/util/json_renderer.hpp | 4 + include/util/json_util.hpp | 26 +-- include/util/lua_util.hpp | 8 + include/util/make_unique.hpp | 6 + include/util/matching_debug_info.hpp | 54 ++++--- include/util/matrix_graph_wrapper.hpp | 10 +- include/util/mercator.hpp | 8 + include/util/node_based_graph.hpp | 16 +- include/util/osrm_exception.hpp | 6 + include/util/percent.hpp | 8 + include/util/range_algorithms.hpp | 4 + include/util/range_table.hpp | 12 +- include/util/rectangle.hpp | 8 + include/util/routed_options.hpp | 28 ++-- include/util/shared_memory_vector_wrapper.hpp | 8 + include/util/simple_logger.hpp | 8 + include/util/static_graph.hpp | 20 ++- include/util/static_rtree.hpp | 24 ++- include/util/string_util.hpp | 8 + include/util/timing_util.hpp | 8 + include/util/tribool.hpp | 5 + include/util/trigonometry_table.hpp | 8 + include/util/typedefs.hpp | 3 +- include/util/xml_renderer.hpp | 5 + include/util/xor_fast_hash.hpp | 8 + include/util/xor_fast_hash_storage.hpp | 8 + src/benchmarks/static_rtree.cpp | 28 ++-- src/contractor/contractor_options.cpp | 13 +- src/contractor/processing_chain.cpp | 134 ++++++++-------- src/engine/douglas_peucker.cpp | 13 +- src/engine/osrm_impl.cpp | 51 +++--- src/engine/phantom_node.cpp | 13 +- src/engine/polyline_compressor.cpp | 15 +- src/engine/polyline_formatter.cpp | 17 +- src/engine/route_parameters.cpp | 7 + src/engine/search_engine_data.cpp | 7 + src/extractor/compressed_edge_container.cpp | 9 +- src/extractor/edge_based_graph_factory.cpp | 71 +++++---- src/extractor/external_memory_node.cpp | 7 + src/extractor/extraction_containers.cpp | 47 +++--- src/extractor/extractor.cpp | 101 ++++++------ src/extractor/extractor_callbacks.cpp | 19 ++- src/extractor/extractor_options.cpp | 19 ++- src/extractor/graph_compressor.cpp | 21 ++- src/extractor/import_edge.cpp | 7 + src/extractor/raster_source.cpp | 19 ++- src/extractor/restriction_map.cpp | 7 + src/extractor/restriction_parser.cpp | 21 ++- src/extractor/scripting_environment.cpp | 23 ++- src/server/connection.cpp | 25 +-- src/server/http/reply.cpp | 6 + src/server/request_handler.cpp | 25 +-- src/server/request_parser.cpp | 149 +++++++++--------- src/tools/check-hsgr.cpp | 42 +++-- src/tools/components.cpp | 79 +++++----- src/tools/contract.cpp | 36 +++-- src/tools/datastore.cpp | 112 +++++++------ src/tools/extract.cpp | 28 ++-- src/tools/io-benchmark.cpp | 113 ++++++------- src/tools/routed.cpp | 48 +++--- src/tools/simpleclient.cpp | 30 ++-- src/tools/springclean.cpp | 37 +++-- src/tools/unlock_all_mutexes.cpp | 10 +- src/util/compute_angle.cpp | 7 + src/util/coordinate.cpp | 7 + src/util/coordinate_calculation.cpp | 7 + src/util/hilbert_value.cpp | 7 + src/util/mercator.cpp | 7 + src/util/osrm_exception.cpp | 10 +- src/util/simple_logger.cpp | 7 + unit_tests/engine/douglas_peucker.cpp | 5 +- unit_tests/engine/geometry_string.cpp | 23 ++- .../extractor/compressed_edge_container.cpp | 3 + unit_tests/extractor/graph_compressor.cpp | 20 +-- unit_tests/extractor/raster_source.cpp | 7 +- unit_tests/util/bearing.cpp | 5 +- unit_tests/util/binary_heap.cpp | 3 + unit_tests/util/coordinate.cpp | 3 + unit_tests/util/duration_parsing.cpp | 33 ++-- unit_tests/util/dynamic_graph.cpp | 3 + unit_tests/util/range_table.cpp | 7 +- unit_tests/util/static_graph.cpp | 3 + unit_tests/util/static_rtree.cpp | 17 +- unit_tests/util/string_util.cpp | 3 + 194 files changed, 2648 insertions(+), 1245 deletions(-) diff --git a/include/contractor/contractor.hpp b/include/contractor/contractor.hpp index fa6dce2ed..29f0f22dd 100644 --- a/include/contractor/contractor.hpp +++ b/include/contractor/contractor.hpp @@ -26,6 +26,11 @@ #include #include +namespace osrm +{ +namespace contractor +{ + class Contractor { @@ -65,12 +70,12 @@ class Contractor ContractorHeapData(short h, bool t) : hop(h), target(t) {} }; - using ContractorGraph = DynamicGraph; - // using ContractorHeap = BinaryHeap; + // using ContractorHeap = util::BinaryHeap // >; using ContractorHeap = - BinaryHeap>; + util::BinaryHeap>; using ContractorEdge = ContractorGraph::InputEdge; struct ContractorThreadData @@ -151,7 +156,7 @@ class Contractor #ifndef NDEBUG if (static_cast(std::max(diter->weight, 1)) > 24 * 60 * 60 * 10) { - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "Edge weight large -> " << static_cast(std::max(diter->weight, 1)) << " : " << static_cast(diter->source) << " -> " @@ -253,11 +258,11 @@ class Contractor // } // } // - // SimpleLogger().Write() << "edges at node with id " << highestNode << " has degree + // util::SimpleLogger().Write() << "edges at node with id " << highestNode << " has degree // " << maxdegree; // for(unsigned i = contractor_graph->BeginEdges(highestNode); i < // contractor_graph->EndEdges(highestNode); ++i) { - // SimpleLogger().Write() << " ->(" << highestNode << "," << + // util::SimpleLogger().Write() << " ->(" << highestNode << "," << // contractor_graph->GetTarget(i) // << "); via: " << contractor_graph->GetEdgeData(i).via; // } @@ -281,7 +286,7 @@ class Contractor constexpr size_t DeleteGrainSize = 1; const NodeID number_of_nodes = contractor_graph->GetNumberOfNodes(); - Percent p(number_of_nodes); + util::Percent p(number_of_nodes); ThreadDataContainer thread_data_list(number_of_nodes); @@ -340,7 +345,7 @@ class Contractor if (!flushed_contractor && (number_of_contracted_nodes > static_cast(number_of_nodes * 0.65 * core_factor))) { - DeallocatingVector new_edge_set; // this one is not explicitely + util::DeallocatingVector new_edge_set; // this one is not explicitely // cleared since it goes out of // scope anywa std::cout << " [flush " << number_of_contracted_nodes << " nodes] " << std::flush; @@ -357,7 +362,7 @@ class Contractor // remaining graph std::vector new_node_id_from_orig_id_map(number_of_nodes, UINT_MAX); - for (const auto new_node_id : osrm::irange(0, remaining_nodes.size())) + for (const auto new_node_id : util::irange(0, remaining_nodes.size())) { auto &node = remaining_nodes[new_node_id]; BOOST_ASSERT(node_priorities.size() > node.id); @@ -365,7 +370,7 @@ class Contractor } // build forward and backward renumbering map and remap ids in remaining_nodes - for (const auto new_node_id : osrm::irange(0, remaining_nodes.size())) + for (const auto new_node_id : util::irange(0, remaining_nodes.size())) { auto &node = remaining_nodes[new_node_id]; // create renumbering maps in both directions @@ -375,7 +380,7 @@ class Contractor } // walk over all nodes for (const auto source : - osrm::irange(0, contractor_graph->GetNumberOfNodes())) + util::irange(0, contractor_graph->GetNumberOfNodes())) { for (auto current_edge : contractor_graph->GetAdjacentEdgeRange(source)) { @@ -389,7 +394,7 @@ class Contractor else { // node is not yet contracted. - // add (renumbered) outgoing edges to new DynamicGraph. + // add (renumbered) outgoing edges to new util::DynamicGraph. ContractorEdge new_edge = {new_node_id_from_orig_id_map[source], new_node_id_from_orig_id_map[target], data}; @@ -590,7 +595,7 @@ class Contractor // avgdegree /= std::max((unsigned)1,(unsigned)remaining_nodes.size() ); // quaddegree /= std::max((unsigned)1,(unsigned)remaining_nodes.size() ); // - // SimpleLogger().Write() << "rest: " << remaining_nodes.size() << ", max: " + // util::SimpleLogger().Write() << "rest: " << remaining_nodes.size() << ", max: " // << maxdegree << ", min: " << mindegree << ", avg: " << avgdegree << ", // quad: " << quaddegree; @@ -633,7 +638,7 @@ class Contractor is_core_node.clear(); } - SimpleLogger().Write() << "[core] " << remaining_nodes.size() << " nodes " + util::SimpleLogger().Write() << "[core] " << remaining_nodes.size() << " nodes " << contractor_graph->GetNumberOfEdges() << " edges." << std::endl; thread_data_list.data.clear(); @@ -649,15 +654,15 @@ class Contractor out_node_levels.swap(node_levels); } - template inline void GetEdges(DeallocatingVector &edges) + template inline void GetEdges(util::DeallocatingVector &edges) { - Percent p(contractor_graph->GetNumberOfNodes()); - SimpleLogger().Write() << "Getting edges of minimized graph"; + util::Percent p(contractor_graph->GetNumberOfNodes()); + util::SimpleLogger().Write() << "Getting edges of minimized graph"; const NodeID number_of_nodes = contractor_graph->GetNumberOfNodes(); if (contractor_graph->GetNumberOfNodes()) { Edge new_edge; - for (const auto node : osrm::irange(0u, number_of_nodes)) + for (const auto node : util::irange(0u, number_of_nodes)) { p.printStatus(node); for (auto edge : contractor_graph->GetAdjacentEdgeRange(node)) @@ -940,7 +945,7 @@ class Contractor std::sort(neighbours.begin(), neighbours.end()); neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); - for (const auto i : osrm::irange(0, neighbours.size())) + for (const auto i : util::irange(0, neighbours.size())) { contractor_graph->DeleteEdgesTo(neighbours[i], node); } @@ -1060,7 +1065,10 @@ class Contractor std::vector orig_node_id_from_new_node_id_map; std::vector node_levels; std::vector is_core_node; - XORFastHash fast_hash; + util::XORFastHash fast_hash; }; +} +} + #endif // CONTRACTOR_HPP diff --git a/include/contractor/contractor_options.hpp b/include/contractor/contractor_options.hpp index c64681fa9..cb29d82f3 100644 --- a/include/contractor/contractor_options.hpp +++ b/include/contractor/contractor_options.hpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace contractor +{ + enum class return_code : unsigned { ok, @@ -51,4 +56,7 @@ struct ContractorOptions static void GenerateOutputFilesNames(ContractorConfig &extractor_config); }; +} +} + #endif // EXTRACTOR_OPTIONS_HPP diff --git a/include/contractor/crc32_processor.hpp b/include/contractor/crc32_processor.hpp index df9fa9686..827cdda0a 100644 --- a/include/contractor/crc32_processor.hpp +++ b/include/contractor/crc32_processor.hpp @@ -9,6 +9,11 @@ #include +namespace osrm +{ +namespace contractor +{ + class IteratorbasedCRC32 { public: @@ -115,4 +120,7 @@ struct RangebasedCRC32 IteratorbasedCRC32 crc32; }; +} +} + #endif /* ITERATOR_BASED_CRC32_H */ diff --git a/include/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp index 5c0713fde..d1bc08e24 100644 --- a/include/contractor/processing_chain.hpp +++ b/include/contractor/processing_chain.hpp @@ -8,14 +8,22 @@ #include "util/deallocating_vector.hpp" #include "util/node_based_graph.hpp" -struct SpeedProfileProperties; -struct EdgeBasedNode; -struct lua_State; - #include #include +struct lua_State; + +namespace osrm +{ +namespace extractor +{ +struct SpeedProfileProperties; +struct EdgeBasedNode; +} +namespace contractor +{ + /** \brief class of 'prepare' utility. */ @@ -32,26 +40,29 @@ class Prepare protected: void ContractGraph(const unsigned max_edge_id, - DeallocatingVector &edge_based_edge_list, - DeallocatingVector &contracted_edge_list, + util::DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &contracted_edge_list, std::vector &is_core_node, std::vector &node_levels) const; void WriteCoreNodeMarker(std::vector &&is_core_node) const; void WriteNodeLevels(std::vector &&node_levels) const; void ReadNodeLevels(std::vector &contraction_order) const; std::size_t WriteContractedGraph(unsigned number_of_edge_based_nodes, - const DeallocatingVector &contracted_edge_list); + const util::DeallocatingVector &contracted_edge_list); void FindComponents(unsigned max_edge_id, - const DeallocatingVector &edges, - std::vector &nodes) const; + const util::DeallocatingVector &edges, + std::vector &nodes) const; private: ContractorConfig config; std::size_t LoadEdgeExpandedGraph(const std::string &edge_based_graph_path, - DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &edge_based_edge_list, const std::string &edge_segment_lookup_path, const std::string &edge_penalty_path, const std::string &segment_speed_path); }; +} +} + #endif // PROCESSING_CHAIN_HPP diff --git a/include/contractor/query_edge.hpp b/include/contractor/query_edge.hpp index ec7e89b68..75949c4dd 100644 --- a/include/contractor/query_edge.hpp +++ b/include/contractor/query_edge.hpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace contractor +{ + struct QueryEdge { NodeID source; @@ -49,4 +54,7 @@ struct QueryEdge } }; +} +} + #endif // QUERYEDGE_HPP diff --git a/include/datastore/shared_memory_factory.hpp b/include/datastore/shared_memory_factory.hpp index ba72581d8..37ae802c4 100644 --- a/include/datastore/shared_memory_factory.hpp +++ b/include/datastore/shared_memory_factory.hpp @@ -24,6 +24,11 @@ #include #include +namespace osrm +{ +namespace datastore +{ + struct OSRMLockFile { boost::filesystem::path operator()() @@ -58,10 +63,10 @@ class SharedMemory { if (m_initialized) { - SimpleLogger().Write(logDEBUG) << "automatic memory deallocation"; + util::SimpleLogger().Write(logDEBUG) << "automatic memory deallocation"; if (!boost::interprocess::xsi_shared_memory::remove(m_shmid)) { - SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid; + util::SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid; } } } @@ -103,14 +108,14 @@ class SharedMemory { if (ENOMEM == errno) { - SimpleLogger().Write(logWARNING) << "could not lock shared memory to RAM"; + util::SimpleLogger().Write(logWARNING) << "could not lock shared memory to RAM"; } } #endif region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write); remover.SetID(shm.get_shmid()); - SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; + util::SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; } } @@ -157,7 +162,7 @@ class SharedMemory bool ret = false; try { - SimpleLogger().Write(logDEBUG) << "deallocating prev memory"; + util::SimpleLogger().Write(logDEBUG) << "deallocating prev memory"; boost::interprocess::xsi_shared_memory xsi(boost::interprocess::open_only, key); ret = boost::interprocess::xsi_shared_memory::remove(xsi.get_shmid()); } @@ -202,10 +207,10 @@ class SharedMemory { if (m_initialized) { - SimpleLogger().Write(logDEBUG) << "automatic memory deallocation"; + util::SimpleLogger().Write(logDEBUG) << "automatic memory deallocation"; if (!boost::interprocess::shared_memory_object::remove(m_shmid)) { - SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid; + util::SimpleLogger().Write(logDEBUG) << "could not deallocate id " << m_shmid; } } } @@ -242,7 +247,7 @@ class SharedMemory region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write); remover.SetID(key); - SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; + util::SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; } } @@ -292,7 +297,7 @@ class SharedMemory bool ret = false; try { - SimpleLogger().Write(logDEBUG) << "deallocating prev memory"; + util::SimpleLogger().Write(logDEBUG) << "deallocating prev memory"; ret = boost::interprocess::shared_memory_object::remove(key); } catch (const boost::interprocess::interprocess_exception &e) @@ -328,7 +333,7 @@ template class SharedMemoryFactory_tmpl { if (0 == size) { - throw osrm::exception("lock file does not exist, exiting"); + throw util::exception("lock file does not exist, exiting"); } else { @@ -340,9 +345,9 @@ template class SharedMemoryFactory_tmpl } catch (const boost::interprocess::interprocess_exception &e) { - SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " + util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " << e.get_error_code(); - throw osrm::exception(e.what()); + throw util::exception(e.what()); } } @@ -352,4 +357,7 @@ template class SharedMemoryFactory_tmpl using SharedMemoryFactory = SharedMemoryFactory_tmpl<>; +} +} + #endif // SHARED_MEMORY_FACTORY_HPP diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index d70eae3f8..02dbf70f0 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -57,7 +57,7 @@ template class ApiResponseGenerator // The output is tailored to the viaroute plugin. void DescribeRoute(const RouteParameters &config, const InternalRouteResult &raw_route, - osrm::json::Object &json_result); + util::json::Object &json_result); // The following functions allow access to the different parts of the Describe Route // functionality. @@ -65,20 +65,20 @@ template class ApiResponseGenerator // In the normal situation, Describe Route is the desired usecase. // generate an overview of a raw route - osrm::json::Object SummarizeRoute(const InternalRouteResult &raw_route, + util::json::Object SummarizeRoute(const InternalRouteResult &raw_route, const Segments &segment_list) const; // create an array containing all via-points/-indices used in the query - osrm::json::Array ListViaPoints(const InternalRouteResult &raw_route) const; - osrm::json::Array ListViaIndices(const Segments &segment_list) const; + util::json::Array ListViaPoints(const InternalRouteResult &raw_route) const; + util::json::Array ListViaIndices(const Segments &segment_list) const; - osrm::json::Value GetGeometry(const bool return_encoded, const Segments &segments) const; + util::json::Value GetGeometry(const bool return_encoded, const Segments &segments) const; // TODO this dedicated creation seems unnecessary? Only used for route names std::vector BuildRouteSegments(const Segments &segment_list) const; // adds checksum and locations - osrm::json::Object BuildHintData(const InternalRouteResult &raw_route) const; + util::json::Object BuildHintData(const InternalRouteResult &raw_route) const; private: // data access to translate ids back into names @@ -94,7 +94,7 @@ ApiResponseGenerator::ApiResponseGenerator(DataFacadeT *facade_) template void ApiResponseGenerator::DescribeRoute(const RouteParameters &config, const InternalRouteResult &raw_route, - osrm::json::Object &json_result) + util::json::Object &json_result) { if( not raw_route.is_valid() ){ return; @@ -129,7 +129,7 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con // Alternative Route Summaries are stored in an array to (down the line) allow multiple // alternatives - osrm::json::Array json_alternate_route_summary_array; + util::json::Array json_alternate_route_summary_array; json_alternate_route_summary_array.values.emplace_back( SummarizeRoute(raw_route, alternate_segment_list)); json_result.values["alternative_summaries"] = json_alternate_route_summary_array; @@ -139,14 +139,14 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con { auto alternate_geometry_string = GetGeometry(config.compression, alternate_segment_list); - osrm::json::Array json_alternate_geometries_array; + util::json::Array json_alternate_geometries_array; json_alternate_geometries_array.values.emplace_back(std::move(alternate_geometry_string)); json_result.values["alternative_geometries"] = json_alternate_geometries_array; } if (config.print_instructions) { - osrm::json::Array json_alternate_annotations_array; + util::json::Array json_alternate_annotations_array; json_alternate_annotations_array.values.emplace_back( guidance::AnnotateRoute(alternate_segment_list.Get(), facade)); json_result.values["alternative_instructions"] = json_alternate_annotations_array; @@ -157,24 +157,24 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con auto alternate_segments = BuildRouteSegments(alternate_segment_list); route_names = generate_route_names(path_segments, alternate_segments, facade); - osrm::json::Array json_alternate_names_array; - osrm::json::Array json_alternate_names; + util::json::Array json_alternate_names_array; + util::json::Array json_alternate_names; json_alternate_names.values.push_back(route_names.alternative_path_name_1); json_alternate_names.values.push_back(route_names.alternative_path_name_2); json_alternate_names_array.values.emplace_back(std::move(json_alternate_names)); json_result.values["alternative_names"] = json_alternate_names_array; - json_result.values["found_alternative"] = osrm::json::True(); + json_result.values["found_alternative"] = util::json::True(); } else { - json_result.values["found_alternative"] = osrm::json::False(); + json_result.values["found_alternative"] = util::json::False(); // generate names for the main route on its own auto path_segments = BuildRouteSegments(segment_list); std::vector alternate_segments; route_names = generate_route_names(path_segments, alternate_segments, facade); } - osrm::json::Array json_route_names; + util::json::Array json_route_names; json_route_names.values.push_back(route_names.shortest_path_name_1); json_route_names.values.push_back(route_names.shortest_path_name_2); json_result.values["route_name"] = json_route_names; @@ -183,11 +183,11 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con } template -osrm::json::Object +util::json::Object ApiResponseGenerator::SummarizeRoute(const InternalRouteResult &raw_route, const Segments &segment_list) const { - osrm::json::Object json_route_summary; + util::json::Object json_route_summary; if (not raw_route.segment_end_coordinates.empty()) { const auto start_name_id = raw_route.segment_end_coordinates.front().source_phantom.name_id; @@ -201,11 +201,11 @@ ApiResponseGenerator::SummarizeRoute(const InternalRouteResult &raw } template -osrm::json::Array +util::json::Array ApiResponseGenerator::ListViaPoints(const InternalRouteResult &raw_route) const { - osrm::json::Array json_via_points_array; - osrm::json::Array json_first_coordinate; + util::json::Array json_via_points_array; + util::json::Array json_first_coordinate; json_first_coordinate.values.emplace_back( raw_route.segment_end_coordinates.front().source_phantom.location.lat / COORDINATE_PRECISION); @@ -216,7 +216,7 @@ ApiResponseGenerator::ListViaPoints(const InternalRouteResult &raw_ for (const PhantomNodes &nodes : raw_route.segment_end_coordinates) { std::string tmp; - osrm::json::Array json_coordinate; + util::json::Array json_coordinate; json_coordinate.values.emplace_back(nodes.target_phantom.location.lat / COORDINATE_PRECISION); json_coordinate.values.emplace_back(nodes.target_phantom.location.lon / COORDINATE_PRECISION); json_via_points_array.values.emplace_back(std::move(json_coordinate)); @@ -225,17 +225,17 @@ ApiResponseGenerator::ListViaPoints(const InternalRouteResult &raw_ } template -osrm::json::Array +util::json::Array ApiResponseGenerator::ListViaIndices(const Segments &segment_list) const { - osrm::json::Array via_indices; + util::json::Array via_indices; via_indices.values.insert(via_indices.values.end(), segment_list.GetViaIndices().begin(), segment_list.GetViaIndices().end()); return via_indices; } template -osrm::json::Value ApiResponseGenerator::GetGeometry(const bool return_encoded, const Segments &segments) const +util::json::Value ApiResponseGenerator::GetGeometry(const bool return_encoded, const Segments &segments) const { if (return_encoded) return PolylineFormatter().printEncodedString(segments.Get()); @@ -251,8 +251,8 @@ ApiResponseGenerator::BuildRouteSegments(const Segments &segment_li for (const auto &segment : segment_list.Get()) { const auto current_turn = segment.turn_instruction; - if (TurnInstructionsClass::TurnIsNecessary(current_turn) and - (TurnInstruction::EnterRoundAbout != current_turn)) + if (extractor::TurnInstructionsClass::TurnIsNecessary(current_turn) and + (extractor::TurnInstruction::EnterRoundAbout != current_turn)) { detail::Segment seg = {segment.name_id, static_cast(segment.length), @@ -264,14 +264,14 @@ ApiResponseGenerator::BuildRouteSegments(const Segments &segment_li } template -osrm::json::Object +util::json::Object ApiResponseGenerator::BuildHintData(const InternalRouteResult &raw_route) const { - osrm::json::Object json_hint_object; + util::json::Object json_hint_object; json_hint_object.values["checksum"] = facade->GetCheckSum(); - osrm::json::Array json_location_hint_array; + util::json::Array json_location_hint_array; std::string hint; - for (const auto i : osrm::irange(0, raw_route.segment_end_coordinates.size())) + for (const auto i : util::irange(0, raw_route.segment_end_coordinates.size())) { ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates[i].source_phantom, hint); json_location_hint_array.values.push_back(hint); diff --git a/include/engine/datafacade/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp index 1653309b7..ab419bf19 100644 --- a/include/engine/datafacade/datafacade_base.hpp +++ b/include/engine/datafacade/datafacade_base.hpp @@ -17,12 +17,19 @@ #include #include -using EdgeRange = osrm::range; +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + +using EdgeRange = util::range; template class BaseDataFacade { public: - using RTreeLeaf = EdgeBasedNode; + using RTreeLeaf = extractor::EdgeBasedNode; using EdgeData = EdgeDataT; BaseDataFacade() {} virtual ~BaseDataFacade() {} @@ -53,7 +60,7 @@ template class BaseDataFacade FindEdgeIndicateIfReverse(const NodeID from, const NodeID to, bool &result) const = 0; // node and edge information access - virtual FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const = 0; + virtual util::FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const = 0; virtual bool EdgeIsCompressed(const unsigned id) const = 0; @@ -62,24 +69,24 @@ template class BaseDataFacade virtual void GetUncompressedGeometry(const unsigned id, std::vector &result_nodes) const = 0; - virtual TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const = 0; + virtual extractor::TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const = 0; - virtual TravelMode GetTravelModeForEdgeID(const unsigned id) const = 0; + virtual extractor::TravelMode GetTravelModeForEdgeID(const unsigned id) const = 0; virtual std::vector - NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) = 0; virtual std::vector - NearestPhantomNodes(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) = 0; virtual std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, const int bearing = 0, const int bearing_range = 180) = 0; @@ -96,4 +103,8 @@ template class BaseDataFacade virtual std::string GetTimestamp() const = 0; }; +} +} +} + #endif // DATAFACADE_BASE_HPP diff --git a/include/engine/datafacade/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp index 35f2e223b..ba43513da 100644 --- a/include/engine/datafacade/internal_datafacade.hpp +++ b/include/engine/datafacade/internal_datafacade.hpp @@ -22,15 +22,22 @@ #include +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + template class InternalDataFacade final : public BaseDataFacade { private: using super = BaseDataFacade; - using QueryGraph = StaticGraph; + using QueryGraph = util::StaticGraph; using InputEdge = typename QueryGraph::InputEdge; using RTreeLeaf = typename super::RTreeLeaf; - using InternalRTree = StaticRTree::vector, false>; + using InternalRTree = util::StaticRTree::vector, false>; using InternalGeospatialQuery = GeospatialQuery; InternalDataFacade() {} @@ -40,32 +47,32 @@ template class InternalDataFacade final : public BaseDataFacad std::unique_ptr m_query_graph; std::string m_timestamp; - std::shared_ptr::vector> m_coordinate_list; - ShM::vector m_via_node_list; - ShM::vector m_name_ID_list; - ShM::vector m_turn_instruction_list; - ShM::vector m_travel_mode_list; - ShM::vector m_names_char_list; - ShM::vector m_edge_is_compressed; - ShM::vector m_geometry_indices; - ShM::vector m_geometry_list; - ShM::vector m_is_core_node; + std::shared_ptr::vector> m_coordinate_list; + util::ShM::vector m_via_node_list; + util::ShM::vector m_name_ID_list; + util::ShM::vector m_turn_instruction_list; + util::ShM::vector m_travel_mode_list; + util::ShM::vector m_names_char_list; + util::ShM::vector m_edge_is_compressed; + util::ShM::vector m_geometry_indices; + util::ShM::vector m_geometry_list; + util::ShM::vector m_is_core_node; boost::thread_specific_ptr m_static_rtree; boost::thread_specific_ptr m_geospatial_query; boost::filesystem::path ram_index_path; boost::filesystem::path file_index_path; - RangeTable<16, false> m_name_table; + util::RangeTable<16, false> m_name_table; void LoadTimestamp(const boost::filesystem::path ×tamp_path) { if (boost::filesystem::exists(timestamp_path)) { - SimpleLogger().Write() << "Loading Timestamp"; + util::SimpleLogger().Write() << "Loading Timestamp"; boost::filesystem::ifstream timestamp_stream(timestamp_path); if (!timestamp_stream) { - SimpleLogger().Write(logWARNING) << timestamp_path << " not found"; + util::SimpleLogger().Write(logWARNING) << timestamp_path << " not found"; } getline(timestamp_stream, m_timestamp); timestamp_stream.close(); @@ -82,22 +89,22 @@ template class InternalDataFacade final : public BaseDataFacad void LoadGraph(const boost::filesystem::path &hsgr_path) { - typename ShM::vector node_list; - typename ShM::vector edge_list; + typename util::ShM::vector node_list; + typename util::ShM::vector edge_list; - SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); + util::SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); m_number_of_nodes = readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); // BOOST_ASSERT_MSG(0 != edge_list.size(), "edge list empty"); - SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() + util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() << " edges"; m_query_graph = std::unique_ptr(new QueryGraph(node_list, edge_list)); BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); BOOST_ASSERT_MSG(0 == edge_list.size(), "edge list not flushed"); - SimpleLogger().Write() << "Data checksum is " << m_check_sum; + util::SimpleLogger().Write() << "Data checksum is " << m_check_sum; } void LoadNodeAndEdgeInformation(const boost::filesystem::path &nodes_file, @@ -105,15 +112,15 @@ template class InternalDataFacade final : public BaseDataFacad { boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary); - QueryNode current_node; + extractor::QueryNode current_node; unsigned number_of_coordinates = 0; nodes_input_stream.read((char *)&number_of_coordinates, sizeof(unsigned)); m_coordinate_list = - std::make_shared>(number_of_coordinates); + std::make_shared>(number_of_coordinates); for (unsigned i = 0; i < number_of_coordinates; ++i) { - nodes_input_stream.read((char *)¤t_node, sizeof(QueryNode)); - m_coordinate_list->at(i) = FixedPointCoordinate(current_node.lat, current_node.lon); + nodes_input_stream.read((char *)¤t_node, sizeof(extractor::QueryNode)); + m_coordinate_list->at(i) = util::FixedPointCoordinate(current_node.lat, current_node.lon); BOOST_ASSERT((std::abs(m_coordinate_list->at(i).lat) >> 30) == 0); BOOST_ASSERT((std::abs(m_coordinate_list->at(i).lon) >> 30) == 0); } @@ -130,10 +137,10 @@ template class InternalDataFacade final : public BaseDataFacad unsigned compressed = 0; - OriginalEdgeData current_edge_data; + extractor::OriginalEdgeData current_edge_data; for (unsigned i = 0; i < number_of_edges; ++i) { - edges_input_stream.read((char *)&(current_edge_data), sizeof(OriginalEdgeData)); + edges_input_stream.read((char *)&(current_edge_data), sizeof(extractor::OriginalEdgeData)); m_via_node_list[i] = current_edge_data.via_node; m_name_ID_list[i] = current_edge_data.name_id; m_turn_instruction_list[i] = current_edge_data.turn_instruction; @@ -220,7 +227,7 @@ template class InternalDataFacade final : public BaseDataFacad name_stream.read((char *)&m_names_char_list[0], number_of_chars * sizeof(char)); if (0 == m_names_char_list.size()) { - SimpleLogger().Write(logWARNING) << "list of street names is empty"; + util::SimpleLogger().Write(logWARNING) << "list of street names is empty"; } name_stream.close(); } @@ -242,29 +249,29 @@ template class InternalDataFacade final : public BaseDataFacad { const auto it = server_paths.find(path); if (it == end_it || !boost::filesystem::is_regular_file(it->second)) - throw osrm::exception("no valid " + path + " file given in ini file"); + throw util::exception("no valid " + path + " file given in ini file"); return it->second; }; ram_index_path = file_for("ramindex"); file_index_path = file_for("fileindex"); - SimpleLogger().Write() << "loading graph data"; + util::SimpleLogger().Write() << "loading graph data"; LoadGraph(file_for("hsgrdata")); - SimpleLogger().Write() << "loading edge information"; + util::SimpleLogger().Write() << "loading edge information"; LoadNodeAndEdgeInformation(file_for("nodesdata"), file_for("edgesdata")); - SimpleLogger().Write() << "loading core information"; + util::SimpleLogger().Write() << "loading core information"; LoadCoreInformation(file_for("coredata")); - SimpleLogger().Write() << "loading geometries"; + util::SimpleLogger().Write() << "loading geometries"; LoadGeometries(file_for("geometries")); - SimpleLogger().Write() << "loading timestamp"; + util::SimpleLogger().Write() << "loading timestamp"; LoadTimestamp(file_for("timestamp")); - SimpleLogger().Write() << "loading street names"; + util::SimpleLogger().Write() << "loading street names"; LoadStreetNames(file_for("namesdata")); } @@ -312,7 +319,7 @@ template class InternalDataFacade final : public BaseDataFacad } // node and edge information access - FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const override final + util::FixedPointCoordinate GetCoordinateOfNode(const unsigned id) const override final { return m_coordinate_list->at(id); }; @@ -322,18 +329,18 @@ template class InternalDataFacade final : public BaseDataFacad return m_edge_is_compressed.at(id); } - TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const override final + extractor::TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const override final { return m_turn_instruction_list.at(id); } - TravelMode GetTravelModeForEdgeID(const unsigned id) const override final + extractor::TravelMode GetTravelModeForEdgeID(const unsigned id) const override final { return m_travel_mode_list.at(id); } std::vector - NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) override final @@ -349,7 +356,7 @@ template class InternalDataFacade final : public BaseDataFacad } std::vector - NearestPhantomNodes(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) override final @@ -365,7 +372,7 @@ template class InternalDataFacade final : public BaseDataFacad } std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, const int bearing = 0, const int bearing_range = 180) override final { @@ -438,4 +445,8 @@ template class InternalDataFacade final : public BaseDataFacad std::string GetTimestamp() const override final { return m_timestamp; } }; +} +} +} + #endif // INTERNAL_DATAFACADE_HPP diff --git a/include/engine/datafacade/shared_barriers.hpp b/include/engine/datafacade/shared_barriers.hpp index 3825580bc..4eb7d5371 100644 --- a/include/engine/datafacade/shared_barriers.hpp +++ b/include/engine/datafacade/shared_barriers.hpp @@ -4,6 +4,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + struct SharedBarriers { @@ -30,4 +37,8 @@ struct SharedBarriers int number_of_queries; }; +} +} +} + #endif // SHARED_BARRIERS_HPP diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 91d917f96..536cc230e 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -19,19 +19,26 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + template class SharedDataFacade final : public BaseDataFacade { private: using EdgeData = EdgeDataT; using super = BaseDataFacade; - using QueryGraph = StaticGraph; - using GraphNode = typename StaticGraph::NodeArrayEntry; - using GraphEdge = typename StaticGraph::EdgeArrayEntry; - using NameIndexBlock = typename RangeTable<16, true>::BlockT; + using QueryGraph = util::StaticGraph; + using GraphNode = typename QueryGraph::NodeArrayEntry; + using GraphEdge = typename QueryGraph::EdgeArrayEntry; + using NameIndexBlock = typename util::RangeTable<16, true>::BlockT; using InputEdge = typename QueryGraph::InputEdge; using RTreeLeaf = typename super::RTreeLeaf; - using SharedRTree = StaticRTree::vector, true>; + using SharedRTree = util::StaticRTree::vector, true>; using SharedGeospatialQuery = GeospatialQuery; using TimeStampedRTreePair = std::pair>; using RTreeNode = typename SharedRTree::TreeNode; @@ -46,33 +53,33 @@ template class SharedDataFacade final : public BaseDataFacade< unsigned m_check_sum; std::unique_ptr m_query_graph; - std::unique_ptr m_layout_memory; - std::unique_ptr m_large_memory; + std::unique_ptr m_layout_memory; + std::unique_ptr m_large_memory; std::string m_timestamp; - std::shared_ptr::vector> m_coordinate_list; - ShM::vector m_via_node_list; - ShM::vector m_name_ID_list; - ShM::vector m_turn_instruction_list; - ShM::vector m_travel_mode_list; - ShM::vector m_names_char_list; - ShM::vector m_name_begin_indices; - ShM::vector m_edge_is_compressed; - ShM::vector m_geometry_indices; - ShM::vector m_geometry_list; - ShM::vector m_is_core_node; + std::shared_ptr::vector> m_coordinate_list; + util::ShM::vector m_via_node_list; + util::ShM::vector m_name_ID_list; + util::ShM::vector m_turn_instruction_list; + util::ShM::vector m_travel_mode_list; + util::ShM::vector m_names_char_list; + util::ShM::vector m_name_begin_indices; + util::ShM::vector m_edge_is_compressed; + util::ShM::vector m_geometry_indices; + util::ShM::vector m_geometry_list; + util::ShM::vector m_is_core_node; boost::thread_specific_ptr>> m_static_rtree; boost::thread_specific_ptr m_geospatial_query; boost::filesystem::path file_index_path; - std::shared_ptr> m_name_table; + std::shared_ptr> m_name_table; void LoadChecksum() { m_check_sum = *data_layout->GetBlockPtr(shared_memory, SharedDataLayout::HSGR_CHECKSUM); - SimpleLogger().Write() << "set checksum: " << m_check_sum; + util::SimpleLogger().Write() << "set checksum: " << m_check_sum; } void LoadTimestamp() @@ -93,7 +100,7 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->GetBlockPtr(shared_memory, SharedDataLayout::R_SEARCH_TREE); m_static_rtree.reset(new TimeStampedRTreePair( CURRENT_TIMESTAMP, - osrm::make_unique( + util::make_unique( tree_ptr, data_layout->num_entries[SharedDataLayout::R_SEARCH_TREE], file_index_path, m_coordinate_list))); m_geospatial_query.reset( @@ -108,9 +115,9 @@ template class SharedDataFacade final : public BaseDataFacade< GraphEdge *graph_edges_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GRAPH_EDGE_LIST); - typename ShM::vector node_list( + typename util::ShM::vector node_list( graph_nodes_ptr, data_layout->num_entries[SharedDataLayout::GRAPH_NODE_LIST]); - typename ShM::vector edge_list( + typename util::ShM::vector edge_list( graph_edges_ptr, data_layout->num_entries[SharedDataLayout::GRAPH_EDGE_LIST]); m_query_graph.reset(new QueryGraph(node_list, edge_list)); } @@ -118,27 +125,27 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadNodeAndEdgeInformation() { - FixedPointCoordinate *coordinate_list_ptr = data_layout->GetBlockPtr( + util::FixedPointCoordinate *coordinate_list_ptr = data_layout->GetBlockPtr( shared_memory, SharedDataLayout::COORDINATE_LIST); - m_coordinate_list = osrm::make_unique::vector>( + m_coordinate_list = util::make_unique::vector>( coordinate_list_ptr, data_layout->num_entries[SharedDataLayout::COORDINATE_LIST]); - TravelMode *travel_mode_list_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::TRAVEL_MODE); - typename ShM::vector travel_mode_list( + extractor::TravelMode *travel_mode_list_ptr = + data_layout->GetBlockPtr(shared_memory, SharedDataLayout::TRAVEL_MODE); + typename util::ShM::vector travel_mode_list( travel_mode_list_ptr, data_layout->num_entries[SharedDataLayout::TRAVEL_MODE]); m_travel_mode_list.swap(travel_mode_list); - TurnInstruction *turn_instruction_list_ptr = data_layout->GetBlockPtr( + extractor::TurnInstruction *turn_instruction_list_ptr = data_layout->GetBlockPtr( shared_memory, SharedDataLayout::TURN_INSTRUCTION); - typename ShM::vector turn_instruction_list( + typename util::ShM::vector turn_instruction_list( turn_instruction_list_ptr, data_layout->num_entries[SharedDataLayout::TURN_INSTRUCTION]); m_turn_instruction_list.swap(turn_instruction_list); unsigned *name_id_list_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_ID_LIST); - typename ShM::vector name_id_list( + typename util::ShM::vector name_id_list( name_id_list_ptr, data_layout->num_entries[SharedDataLayout::NAME_ID_LIST]); m_name_ID_list.swap(name_id_list); } @@ -147,7 +154,7 @@ template class SharedDataFacade final : public BaseDataFacade< { NodeID *via_node_list_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::VIA_NODE_LIST); - typename ShM::vector via_node_list( + typename util::ShM::vector via_node_list( via_node_list_ptr, data_layout->num_entries[SharedDataLayout::VIA_NODE_LIST]); m_via_node_list.swap(via_node_list); } @@ -158,16 +165,16 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_OFFSETS); NameIndexBlock *blocks_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_BLOCKS); - typename ShM::vector name_offsets( + typename util::ShM::vector name_offsets( offsets_ptr, data_layout->num_entries[SharedDataLayout::NAME_OFFSETS]); - typename ShM::vector name_blocks( + typename util::ShM::vector name_blocks( blocks_ptr, data_layout->num_entries[SharedDataLayout::NAME_BLOCKS]); char *names_list_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_CHAR_LIST); - typename ShM::vector names_char_list( + typename util::ShM::vector names_char_list( names_list_ptr, data_layout->num_entries[SharedDataLayout::NAME_CHAR_LIST]); - m_name_table = osrm::make_unique>( + m_name_table = util::make_unique>( name_offsets, name_blocks, static_cast(names_char_list.size())); m_names_char_list.swap(names_char_list); @@ -182,7 +189,7 @@ template class SharedDataFacade final : public BaseDataFacade< unsigned *core_marker_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::CORE_MARKER); - typename ShM::vector is_core_node( + typename util::ShM::vector is_core_node( core_marker_ptr, data_layout->num_entries[SharedDataLayout::CORE_MARKER]); m_is_core_node.swap(is_core_node); } @@ -191,20 +198,20 @@ template class SharedDataFacade final : public BaseDataFacade< { unsigned *geometries_compressed_ptr = data_layout->GetBlockPtr( shared_memory, SharedDataLayout::GEOMETRIES_INDICATORS); - typename ShM::vector edge_is_compressed( + typename util::ShM::vector edge_is_compressed( geometries_compressed_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_INDICATORS]); m_edge_is_compressed.swap(edge_is_compressed); unsigned *geometries_index_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GEOMETRIES_INDEX); - typename ShM::vector geometry_begin_indices( + typename util::ShM::vector geometry_begin_indices( geometries_index_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_INDEX]); m_geometry_indices.swap(geometry_begin_indices); unsigned *geometries_list_ptr = data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GEOMETRIES_LIST); - typename ShM::vector geometry_list( + typename util::ShM::vector geometry_list( geometries_list_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_LIST]); m_geometry_list.swap(geometry_list); } @@ -214,7 +221,7 @@ template class SharedDataFacade final : public BaseDataFacade< SharedDataFacade() { - data_timestamp_ptr = (SharedDataTimestamp *)SharedMemoryFactory::Get( + data_timestamp_ptr = (SharedDataTimestamp *)datastore::SharedMemoryFactory::Get( CURRENT_REGIONS, sizeof(SharedDataTimestamp), false, false) ->Ptr(); CURRENT_LAYOUT = LAYOUT_NONE; @@ -232,18 +239,18 @@ template class SharedDataFacade final : public BaseDataFacade< CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) { // release the previous shared memory segments - SharedMemory::Remove(CURRENT_LAYOUT); - SharedMemory::Remove(CURRENT_DATA); + datastore::SharedMemory::Remove(CURRENT_LAYOUT); + datastore::SharedMemory::Remove(CURRENT_DATA); CURRENT_LAYOUT = data_timestamp_ptr->layout; CURRENT_DATA = data_timestamp_ptr->data; CURRENT_TIMESTAMP = data_timestamp_ptr->timestamp; - m_layout_memory.reset(SharedMemoryFactory::Get(CURRENT_LAYOUT)); + m_layout_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_LAYOUT)); data_layout = (SharedDataLayout *)(m_layout_memory->Ptr()); - m_large_memory.reset(SharedMemoryFactory::Get(CURRENT_DATA)); + m_large_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_DATA)); shared_memory = (char *)(m_large_memory->Ptr()); const char *file_index_ptr = @@ -251,8 +258,8 @@ template class SharedDataFacade final : public BaseDataFacade< file_index_path = boost::filesystem::path(file_index_ptr); if (!boost::filesystem::exists(file_index_path)) { - SimpleLogger().Write(logDEBUG) << "Leaf file name " << file_index_path.string(); - throw osrm::exception("Could not load leaf index file. " + util::SimpleLogger().Write(logDEBUG) << "Leaf file name " << file_index_path.string(); + throw util::exception("Could not load leaf index file. " "Is any data loaded into shared memory?"); } @@ -267,12 +274,12 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->PrintInformation(); - SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); + util::SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { if (!GetCoordinateOfNode(i).IsValid()) { - SimpleLogger().Write() << "coordinate " << i << " not valid"; + util::SimpleLogger().Write() << "coordinate " << i << " not valid"; } } } @@ -322,7 +329,7 @@ template class SharedDataFacade final : public BaseDataFacade< } // node and edge information access - FixedPointCoordinate GetCoordinateOfNode(const NodeID id) const override final + util::FixedPointCoordinate GetCoordinateOfNode(const NodeID id) const override final { return m_coordinate_list->at(id); }; @@ -348,18 +355,18 @@ template class SharedDataFacade final : public BaseDataFacade< return m_via_node_list.at(id); } - TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const override final + extractor::TurnInstruction GetTurnInstructionForEdgeID(const unsigned id) const override final { return m_turn_instruction_list.at(id); } - TravelMode GetTravelModeForEdgeID(const unsigned id) const override final + extractor::TravelMode GetTravelModeForEdgeID(const unsigned id) const override final { return m_travel_mode_list.at(id); } std::vector - NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) override final @@ -375,7 +382,7 @@ template class SharedDataFacade final : public BaseDataFacade< } std::vector - NearestPhantomNodes(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) override final @@ -391,7 +398,7 @@ template class SharedDataFacade final : public BaseDataFacade< } std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, const int bearing = 0, const int bearing_range = 180) override final { @@ -446,4 +453,8 @@ template class SharedDataFacade final : public BaseDataFacade< std::string GetTimestamp() const override final { return m_timestamp; } }; +} +} +} + #endif // SHARED_DATAFACADE_HPP diff --git a/include/engine/datafacade/shared_datatype.hpp b/include/engine/datafacade/shared_datatype.hpp index 187d9b6cb..b576008cc 100644 --- a/include/engine/datafacade/shared_datatype.hpp +++ b/include/engine/datafacade/shared_datatype.hpp @@ -8,6 +8,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace datafacade +{ + namespace { // Added at the start and end of each block as sanity check @@ -46,41 +53,41 @@ struct SharedDataLayout void PrintInformation() const { - SimpleLogger().Write(logDEBUG) << "NAME_OFFSETS " + util::SimpleLogger().Write(logDEBUG) << "NAME_OFFSETS " << ": " << GetBlockSize(NAME_OFFSETS); - SimpleLogger().Write(logDEBUG) << "NAME_BLOCKS " + util::SimpleLogger().Write(logDEBUG) << "NAME_BLOCKS " << ": " << GetBlockSize(NAME_BLOCKS); - SimpleLogger().Write(logDEBUG) << "NAME_CHAR_LIST " + util::SimpleLogger().Write(logDEBUG) << "NAME_CHAR_LIST " << ": " << GetBlockSize(NAME_CHAR_LIST); - SimpleLogger().Write(logDEBUG) << "NAME_ID_LIST " + util::SimpleLogger().Write(logDEBUG) << "NAME_ID_LIST " << ": " << GetBlockSize(NAME_ID_LIST); - SimpleLogger().Write(logDEBUG) << "VIA_NODE_LIST " + util::SimpleLogger().Write(logDEBUG) << "VIA_NODE_LIST " << ": " << GetBlockSize(VIA_NODE_LIST); - SimpleLogger().Write(logDEBUG) << "GRAPH_NODE_LIST " + util::SimpleLogger().Write(logDEBUG) << "GRAPH_NODE_LIST " << ": " << GetBlockSize(GRAPH_NODE_LIST); - SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST " + util::SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST " << ": " << GetBlockSize(GRAPH_EDGE_LIST); - SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST " + util::SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST " << ": " << GetBlockSize(COORDINATE_LIST); - SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION " + util::SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION " << ": " << GetBlockSize(TURN_INSTRUCTION); - SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE " + util::SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE " << ": " << GetBlockSize(TRAVEL_MODE); - SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE " + util::SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE " << ": " << GetBlockSize(R_SEARCH_TREE); - SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX " + util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX " << ": " << GetBlockSize(GEOMETRIES_INDEX); - SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST " + util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST " << ": " << GetBlockSize(GEOMETRIES_LIST); - SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDICATORS" + util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDICATORS" << ": " << GetBlockSize(GEOMETRIES_INDICATORS); - SimpleLogger().Write(logDEBUG) << "HSGR_CHECKSUM " + util::SimpleLogger().Write(logDEBUG) << "HSGR_CHECKSUM " << ": " << GetBlockSize(HSGR_CHECKSUM); - SimpleLogger().Write(logDEBUG) << "TIMESTAMP " + util::SimpleLogger().Write(logDEBUG) << "TIMESTAMP " << ": " << GetBlockSize(TIMESTAMP); - SimpleLogger().Write(logDEBUG) << "FILE_INDEX_PATH " + util::SimpleLogger().Write(logDEBUG) << "FILE_INDEX_PATH " << ": " << GetBlockSize(FILE_INDEX_PATH); - SimpleLogger().Write(logDEBUG) << "CORE_MARKER " + util::SimpleLogger().Write(logDEBUG) << "CORE_MARKER " << ": " << GetBlockSize(CORE_MARKER); } @@ -135,11 +142,11 @@ struct SharedDataLayout bool end_canary_alive = std::equal(CANARY, CANARY + sizeof(CANARY), end_canary_ptr); if (!start_canary_alive) { - throw osrm::exception("Start canary of block corrupted."); + throw util::exception("Start canary of block corrupted."); } if (!end_canary_alive) { - throw osrm::exception("End canary of block corrupted."); + throw util::exception("End canary of block corrupted."); } } @@ -165,4 +172,8 @@ struct SharedDataTimestamp unsigned timestamp; }; +} +} +} + #endif /* SHARED_DATA_TYPE_HPP */ diff --git a/include/engine/douglas_peucker.hpp b/include/engine/douglas_peucker.hpp index dda4ca1b7..c7e8dd0b2 100644 --- a/include/engine/douglas_peucker.hpp +++ b/include/engine/douglas_peucker.hpp @@ -8,6 +8,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + /* This class object computes the bitvector of indicating generalized input * points according to the (Ramer-)Douglas-Peucker algorithm. * @@ -51,4 +56,7 @@ class DouglasPeucker void Run(std::vector &input_geometry, const unsigned zoom_level); }; +} +} + #endif /* DOUGLAS_PEUCKER_HPP_ */ diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index b572b8f79..efd8c2603 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -13,6 +13,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + // Implements complex queries on top of an RTree and builds PhantomNodes from it. // // Only holds a weak reference on the RTree! @@ -30,7 +35,7 @@ template class GeospatialQuery // Returns nearest PhantomNodes in the given bearing range within max_distance. // Does not filter by small/big component! std::vector - NearestPhantomNodesInRange(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, const double max_distance, const int bearing = 0, const int bearing_range = 180) @@ -52,7 +57,7 @@ template class GeospatialQuery // Returns max_results nearest PhantomNodes in the given bearing range. // Does not filter by small/big component! std::vector - NearestPhantomNodes(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) @@ -73,7 +78,7 @@ template class GeospatialQuery // Returns the nearest phantom node. If this phantom node is not from a big component // a second phantom node is return that is the nearest coordinate in a big component. std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const FixedPointCoordinate &input_coordinate, + NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, const int bearing = 0, const int bearing_range = 180) { @@ -117,7 +122,7 @@ template class GeospatialQuery private: std::vector - MakePhantomNodes(const FixedPointCoordinate &input_coordinate, + MakePhantomNodes(const util::FixedPointCoordinate &input_coordinate, const std::vector &results) const { std::vector distance_and_phantoms(results.size()); @@ -129,12 +134,12 @@ template class GeospatialQuery return distance_and_phantoms; } - PhantomNodeWithDistance MakePhantomNode(const FixedPointCoordinate &input_coordinate, + PhantomNodeWithDistance MakePhantomNode(const util::FixedPointCoordinate &input_coordinate, const EdgeData &data) const { - FixedPointCoordinate point_on_segment; + util::FixedPointCoordinate point_on_segment; double ratio; - const auto current_perpendicular_distance = coordinate_calculation::perpendicularDistance( + const auto current_perpendicular_distance = util::coordinate_calculation::perpendicularDistance( coordinates->at(data.u), coordinates->at(data.v), input_coordinate, point_on_segment, ratio); @@ -159,18 +164,18 @@ template class GeospatialQuery const int filter_bearing_range) { const double forward_edge_bearing = - coordinate_calculation::bearing(coordinates->at(segment.u), coordinates->at(segment.v)); + util::coordinate_calculation::bearing(coordinates->at(segment.u), coordinates->at(segment.v)); const double backward_edge_bearing = (forward_edge_bearing + 180) > 360 ? (forward_edge_bearing - 180) : (forward_edge_bearing + 180); const bool forward_bearing_valid = - bearing::CheckInBounds(std::round(forward_edge_bearing), filter_bearing, + util::bearing::CheckInBounds(std::round(forward_edge_bearing), filter_bearing, filter_bearing_range) && segment.forward_edge_based_node_id != SPECIAL_NODEID; const bool backward_bearing_valid = - bearing::CheckInBounds(std::round(backward_edge_bearing), filter_bearing, + util::bearing::CheckInBounds(std::round(backward_edge_bearing), filter_bearing, filter_bearing_range) && segment.reverse_edge_based_node_id != SPECIAL_NODEID; return std::make_pair(forward_bearing_valid, backward_bearing_valid); @@ -180,4 +185,7 @@ template class GeospatialQuery const std::shared_ptr coordinates; }; +} +} + #endif diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index d034df6ee..ff42b77e6 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -9,6 +9,7 @@ #include "engine/segment_information.hpp" #include "util/integer_range.hpp" #include "util/coordinate_calculation.hpp" +#include "util/container.hpp" #include "extractor/turn_instructions.hpp" #include @@ -124,7 +125,7 @@ void SegmentList::InitRoute(const PhantomNode &node, const bool tra const auto travel_mode = (traversed_in_reverse ? node.backward_travel_mode : node.forward_travel_mode); - AppendSegment(node.location, PathData(0, node.name_id, TurnInstruction::HeadOn, + AppendSegment(node.location, PathData(0, node.name_id, extractor::TurnInstruction::HeadOn, segment_duration, travel_mode)); } @@ -142,10 +143,10 @@ void SegmentList::AddLeg(const std::vector &leg_data, const EdgeWeight segment_duration = (traversed_in_reverse ? target_node.reverse_weight : target_node.forward_weight); - const TravelMode travel_mode = + const extractor::TravelMode travel_mode = (traversed_in_reverse ? target_node.backward_travel_mode : target_node.forward_travel_mode); segments.emplace_back(target_node.location, target_node.name_id, segment_duration, 0.f, - is_via_leg ? TurnInstruction::ReachViaLocation : TurnInstruction::NoTurn, + is_via_leg ? extractor::TurnInstruction::ReachViaLocation : extractor::TurnInstruction::NoTurn, true, true, travel_mode); } @@ -187,12 +188,12 @@ void SegmentList::AppendSegment(const FixedPointCoordinate &coordin } // make sure mode changes are announced, even when there otherwise is no turn - const auto getTurn = [](const PathData &path_point, const TravelMode previous_mode) + const auto getTurn = [](const PathData &path_point, const extractor::TravelMode previous_mode) { - if (TurnInstruction::NoTurn == path_point.turn_instruction and + if (extractor::TurnInstruction::NoTurn == path_point.turn_instruction and previous_mode != path_point.travel_mode and path_point.segment_duration > 0) { - return TurnInstruction::GoStraight; + return extractor::TurnInstruction::GoStraight; } return path_point.turn_instruction; }; @@ -215,11 +216,11 @@ void SegmentList::Finalize(const bool extract_alternative, return; segments[0].length = 0.f; - for (const auto i : osrm::irange(1, segments.size())) + for (const auto i : util::irange(1, segments.size())) { // move down names by one, q&d hack segments[i - 1].name_id = segments[i].name_id; - segments[i].length = coordinate_calculation::greatCircleDistance(segments[i - 1].location, + segments[i].length = util::coordinate_calculation::greatCircleDistance(segments[i - 1].location, segments[i].location); } @@ -229,7 +230,7 @@ void SegmentList::Finalize(const bool extract_alternative, double path_length = 0; - for (const auto i : osrm::irange(1, segments.size())) + for (const auto i : util::irange(1, segments.size())) { path_length += segments[i].length; segment_length += segments[i].length; @@ -237,7 +238,7 @@ void SegmentList::Finalize(const bool extract_alternative, segments[segment_start_index].length = segment_length; segments[segment_start_index].duration = segment_duration; - if (TurnInstruction::NoTurn != segments[i].turn_instruction) + if (extractor::TurnInstruction::NoTurn != segments[i].turn_instruction) { BOOST_ASSERT(segments[i].necessary); segment_length = 0; @@ -257,14 +258,14 @@ void SegmentList::Finalize(const bool extract_alternative, { segments.pop_back(); segments.back().necessary = true; - segments.back().turn_instruction = TurnInstruction::NoTurn; + segments.back().turn_instruction = extractor::TurnInstruction::NoTurn; } if (segments.size() > 2 && std::numeric_limits::epsilon() > segments.front().length && !(segments.begin() + 1)->is_via_location) { segments.erase(segments.begin()); - segments.front().turn_instruction = TurnInstruction::HeadOn; + segments.front().turn_instruction = extractor::TurnInstruction::HeadOn; segments.front().necessary = true; } @@ -287,9 +288,9 @@ void SegmentList::Finalize(const bool extract_alternative, via_indices.push_back(necessary_segments); const double post_turn_bearing = - coordinate_calculation::bearing(first.location, second.location); + util::coordinate_calculation::bearing(first.location, second.location); const double pre_turn_bearing = - coordinate_calculation::bearing(second.location, first.location); + util::coordinate_calculation::bearing(second.location, first.location); first.post_turn_bearing = static_cast(post_turn_bearing * 10); first.pre_turn_bearing = static_cast(pre_turn_bearing * 10); @@ -297,7 +298,7 @@ void SegmentList::Finalize(const bool extract_alternative, }; // calculate which segments are necessary and update segments for bearings - osrm::for_each_pair(segments, markNecessarySegments); + util::for_each_pair(segments, markNecessarySegments); via_indices.push_back(necessary_segments); BOOST_ASSERT(via_indices.size() >= 2); diff --git a/include/engine/guidance/textual_route_annotation.hpp b/include/engine/guidance/textual_route_annotation.hpp index 97329a8e9..5a13428ba 100644 --- a/include/engine/guidance/textual_route_annotation.hpp +++ b/include/engine/guidance/textual_route_annotation.hpp @@ -22,10 +22,10 @@ namespace engine namespace guidance { template< typename DataFacadeT > -inline osrm::json::Array +inline util::json::Array AnnotateRoute(const std::vector &route_segments, DataFacadeT* facade) { - osrm::json::Array json_instruction_array; + util::json::Array json_instruction_array; if( route_segments.empty() ) return json_instruction_array; // Segment information has following format: @@ -45,11 +45,11 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT //Generate annotations for every segment for (const SegmentInformation &segment : route_segments) { - osrm::json::Array json_instruction_row; - TurnInstruction current_instruction = segment.turn_instruction; - if (TurnInstructionsClass::TurnIsNecessary(current_instruction)) + util::json::Array json_instruction_row; + extractor::TurnInstruction current_instruction = segment.turn_instruction; + if (extractor::TurnInstructionsClass::TurnIsNecessary(current_instruction)) { - if (TurnInstruction::EnterRoundAbout == current_instruction) + if (extractor::TurnInstruction::EnterRoundAbout == current_instruction) { round_about.name_id = segment.name_id; round_about.start_index = necessary_segments_running_index; @@ -57,10 +57,10 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT else { std::string current_turn_instruction; - if (TurnInstruction::LeaveRoundAbout == current_instruction) + if (extractor::TurnInstruction::LeaveRoundAbout == current_instruction) { temp_instruction = - std::to_string(cast::enum_to_underlying(TurnInstruction::EnterRoundAbout)); + std::to_string(util::cast::enum_to_underlying(extractor::TurnInstruction::EnterRoundAbout)); current_turn_instruction += temp_instruction; current_turn_instruction += "-"; temp_instruction = std::to_string(round_about.leave_at_exit + 1); @@ -70,7 +70,7 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT else { temp_instruction = - std::to_string(cast::enum_to_underlying(current_instruction)); + std::to_string(util::cast::enum_to_underlying(current_instruction)); current_turn_instruction += temp_instruction; } json_instruction_row.values.emplace_back(std::move(current_turn_instruction)); @@ -84,7 +84,7 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT // post turn bearing const double post_turn_bearing_value = (segment.post_turn_bearing / 10.); - json_instruction_row.values.push_back(bearing::get(post_turn_bearing_value)); + json_instruction_row.values.push_back(util::bearing::get(post_turn_bearing_value)); json_instruction_row.values.push_back( static_cast(std::round(post_turn_bearing_value))); @@ -92,14 +92,14 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT // pre turn bearing const double pre_turn_bearing_value = (segment.pre_turn_bearing / 10.); - json_instruction_row.values.push_back(bearing::get(pre_turn_bearing_value)); + json_instruction_row.values.push_back(util::bearing::get(pre_turn_bearing_value)); json_instruction_row.values.push_back( static_cast(std::round(pre_turn_bearing_value))); json_instruction_array.values.push_back(json_instruction_row); } } - else if (TurnInstruction::StayOnRoundAbout == current_instruction) + else if (extractor::TurnInstruction::StayOnRoundAbout == current_instruction) { ++round_about.leave_at_exit; } @@ -109,18 +109,18 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT } } - osrm::json::Array json_last_instruction_row; + util::json::Array json_last_instruction_row; temp_instruction = - std::to_string(cast::enum_to_underlying(TurnInstruction::ReachedYourDestination)); + std::to_string(util::cast::enum_to_underlying(extractor::TurnInstruction::ReachedYourDestination)); json_last_instruction_row.values.emplace_back( std::move(temp_instruction)); json_last_instruction_row.values.push_back(""); json_last_instruction_row.values.push_back(0); json_last_instruction_row.values.push_back(necessary_segments_running_index - 1); json_last_instruction_row.values.push_back(0); json_last_instruction_row.values.push_back("0m"); - json_last_instruction_row.values.push_back(bearing::get(0.0)); + json_last_instruction_row.values.push_back(util::bearing::get(0.0)); json_last_instruction_row.values.push_back(0.); - json_last_instruction_row.values.push_back(bearing::get(0.0)); + json_last_instruction_row.values.push_back(util::bearing::get(0.0)); json_last_instruction_row.values.push_back(0.); json_instruction_array.values.emplace_back(std::move(json_last_instruction_row)); diff --git a/include/engine/internal_route_result.hpp b/include/engine/internal_route_result.hpp index 0ff802fe8..d4536b405 100644 --- a/include/engine/internal_route_result.hpp +++ b/include/engine/internal_route_result.hpp @@ -10,19 +10,24 @@ #include +namespace osrm +{ +namespace engine +{ + struct PathData { PathData() : node(SPECIAL_NODEID), name_id(INVALID_EDGE_WEIGHT), segment_duration(INVALID_EDGE_WEIGHT), - turn_instruction(TurnInstruction::NoTurn), travel_mode(TRAVEL_MODE_INACCESSIBLE) + turn_instruction(extractor::TurnInstruction::NoTurn), travel_mode(TRAVEL_MODE_INACCESSIBLE) { } PathData(NodeID node, unsigned name_id, - TurnInstruction turn_instruction, + extractor::TurnInstruction turn_instruction, EdgeWeight segment_duration, - TravelMode travel_mode) + extractor::TravelMode travel_mode) : node(node), name_id(name_id), segment_duration(segment_duration), turn_instruction(turn_instruction), travel_mode(travel_mode) { @@ -30,8 +35,8 @@ struct PathData NodeID node; unsigned name_id; EdgeWeight segment_duration; - TurnInstruction turn_instruction; - TravelMode travel_mode : 4; + extractor::TurnInstruction turn_instruction; + extractor::TravelMode travel_mode : 4; }; struct InternalRouteResult @@ -61,4 +66,7 @@ struct InternalRouteResult } }; +} +} + #endif // RAW_ROUTE_DATA_H diff --git a/include/engine/map_matching/bayes_classifier.hpp b/include/engine/map_matching/bayes_classifier.hpp index 3fe0e5a8d..af2c60b29 100644 --- a/include/engine/map_matching/bayes_classifier.hpp +++ b/include/engine/map_matching/bayes_classifier.hpp @@ -6,6 +6,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace map_matching +{ + struct NormalDistribution { NormalDistribution(const double mean, const double standard_deviation) @@ -88,4 +95,8 @@ class BayesClassifier double negative_apriori_probability; }; +} +} +} + #endif // BAYES_CLASSIFIER_HPP diff --git a/include/engine/map_matching/hidden_markov_model.hpp b/include/engine/map_matching/hidden_markov_model.hpp index ef91fca09..f7528d61a 100644 --- a/include/engine/map_matching/hidden_markov_model.hpp +++ b/include/engine/map_matching/hidden_markov_model.hpp @@ -12,14 +12,15 @@ namespace osrm { -namespace matching +namespace engine { +namespace map_matching +{ + static const double log_2_pi = std::log(2. * M_PI); static const double IMPOSSIBLE_LOG_PROB = -std::numeric_limits::infinity(); static const double MINIMAL_LOG_PROB = std::numeric_limits::lowest(); static const std::size_t INVALID_STATE = std::numeric_limits::max(); -} // namespace matching -} // namespace osrm // closures to precompute log -> only simple floating point operations struct EmissionLogProbability @@ -33,7 +34,7 @@ struct EmissionLogProbability double operator()(const double distance) const { - return -0.5 * (osrm::matching::log_2_pi + (distance / sigma_z) * (distance / sigma_z)) - + return -0.5 * (log_2_pi + (distance / sigma_z) * (distance / sigma_z)) - log_sigma_z; } }; @@ -70,7 +71,7 @@ template struct HiddenMarkovModel suspicious.resize(candidates_list.size()); pruned.resize(candidates_list.size()); breakage.resize(candidates_list.size()); - for (const auto i : osrm::irange(0u, candidates_list.size())) + for (const auto i : util::irange(0u, candidates_list.size())) { const auto &num_candidates = candidates_list[i].size(); // add empty vectors @@ -92,9 +93,9 @@ template struct HiddenMarkovModel BOOST_ASSERT(viterbi.size() == parents.size() && parents.size() == path_lengths.size() && path_lengths.size() == pruned.size() && pruned.size() == breakage.size()); - for (const auto t : osrm::irange(initial_timestamp, viterbi.size())) + for (const auto t : util::irange(initial_timestamp, viterbi.size())) { - std::fill(viterbi[t].begin(), viterbi[t].end(), osrm::matching::IMPOSSIBLE_LOG_PROB); + std::fill(viterbi[t].begin(), viterbi[t].end(), IMPOSSIBLE_LOG_PROB); std::fill(parents[t].begin(), parents[t].end(), std::make_pair(0u, 0u)); std::fill(path_lengths[t].begin(), path_lengths[t].end(), 0); std::fill(suspicious[t].begin(), suspicious[t].end(), true); @@ -110,13 +111,13 @@ template struct HiddenMarkovModel { BOOST_ASSERT(initial_timestamp < num_points); - for (const auto s : osrm::irange(0u, viterbi[initial_timestamp].size())) + for (const auto s : util::irange(0u, viterbi[initial_timestamp].size())) { viterbi[initial_timestamp][s] = emission_log_probability(candidates_list[initial_timestamp][s].distance); parents[initial_timestamp][s] = std::make_pair(initial_timestamp, s); pruned[initial_timestamp][s] = - viterbi[initial_timestamp][s] < osrm::matching::MINIMAL_LOG_PROB; + viterbi[initial_timestamp][s] < MINIMAL_LOG_PROB; suspicious[initial_timestamp][s] = false; breakage[initial_timestamp] = @@ -128,7 +129,7 @@ template struct HiddenMarkovModel if (initial_timestamp >= num_points) { - return osrm::matching::INVALID_STATE; + return INVALID_STATE; } BOOST_ASSERT(initial_timestamp > 0); @@ -140,4 +141,8 @@ template struct HiddenMarkovModel } }; +} +} +} + #endif // HIDDEN_MARKOV_MODEL diff --git a/include/engine/object_encoder.hpp b/include/engine/object_encoder.hpp index 546d21003..b97dbc509 100644 --- a/include/engine/object_encoder.hpp +++ b/include/engine/object_encoder.hpp @@ -11,6 +11,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + struct ObjectEncoder { using base64_t = boost::archive::iterators::base64_from_binary< @@ -59,4 +64,7 @@ struct ObjectEncoder } }; +} +} + #endif /* OBJECT_ENCODER_HPP */ diff --git a/include/engine/osrm_impl.hpp b/include/engine/osrm_impl.hpp index 20301efff..c37135102 100644 --- a/include/engine/osrm_impl.hpp +++ b/include/engine/osrm_impl.hpp @@ -1,9 +1,6 @@ #ifndef OSRM_IMPL_HPP #define OSRM_IMPL_HPP -class BasePlugin; -struct RouteParameters; - #include "contractor/query_edge.hpp" #include "osrm/json_container.hpp" @@ -14,31 +11,55 @@ struct RouteParameters; #include #include +namespace osrm +{ + +namespace util +{ +namespace json +{ +struct Object; +} +} + +namespace engine +{ +struct RouteParameters; +namespace plugins +{ +class BasePlugin; +} + +namespace datafacade +{ struct SharedBarriers; template class BaseDataFacade; +} class OSRM::OSRM_impl final { private: - using PluginMap = std::unordered_map>; + using PluginMap = std::unordered_map>; public: OSRM_impl(LibOSRMConfig &lib_config); OSRM_impl(const OSRM_impl &) = delete; - int RunQuery(const RouteParameters &route_parameters, osrm::json::Object &json_result); + int RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result); private: - void RegisterPlugin(BasePlugin *plugin); + void RegisterPlugin(plugins::BasePlugin *plugin); PluginMap plugin_map; // will only be initialized if shared memory is used - std::unique_ptr barrier; + std::unique_ptr barrier; // base class pointer to the objects - BaseDataFacade *query_data_facade; + datafacade::BaseDataFacade *query_data_facade; // decrease number of concurrent queries void decrease_concurrent_query_count(); // increase number of concurrent queries void increase_concurrent_query_count(); }; +} +} #endif // OSRM_IMPL_HPP diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index 17dd6d19a..585d2edcd 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -10,6 +10,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + struct PhantomNode { PhantomNode(NodeID forward_node_id, @@ -22,14 +27,14 @@ struct PhantomNode unsigned packed_geometry_id, bool is_tiny_component, unsigned component_id, - FixedPointCoordinate &location, + util::FixedPointCoordinate &location, unsigned short fwd_segment_position, - TravelMode forward_travel_mode, - TravelMode backward_travel_mode); + extractor::TravelMode forward_travel_mode, + extractor::TravelMode backward_travel_mode); PhantomNode(); - template PhantomNode(const OtherT &other, const FixedPointCoordinate &foot_point) + template PhantomNode(const OtherT &other, const util::FixedPointCoordinate &foot_point) { forward_node_id = other.forward_edge_based_node_id; reverse_node_id = other.reverse_edge_based_node_id; @@ -70,12 +75,12 @@ struct PhantomNode #ifndef _MSC_VER static_assert(sizeof(ComponentType) == 4, "ComponentType needs to 4 bytes big"); #endif - FixedPointCoordinate location; + util::FixedPointCoordinate location; unsigned short fwd_segment_position; // note 4 bits would suffice for each, // but the saved byte would be padding anyway - TravelMode forward_travel_mode; - TravelMode backward_travel_mode; + extractor::TravelMode forward_travel_mode; + extractor::TravelMode backward_travel_mode; int GetForwardWeightPlusOffset() const; @@ -133,4 +138,7 @@ inline std::ostream &operator<<(std::ostream &out, const PhantomNode &pn) return out; } +} +} + #endif // PHANTOM_NODES_H diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index 11151ae4c..d72253909 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -16,6 +16,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class DistanceTablePlugin final : public BasePlugin { private: @@ -27,7 +34,7 @@ template class DistanceTablePlugin final : public BasePlugin : max_locations_distance_table(max_locations_distance_table), descriptor_string("table"), facade(facade) { - search_engine_ptr = osrm::make_unique>(facade); + search_engine_ptr = util::make_unique>(facade); } virtual ~DistanceTablePlugin() {} @@ -35,7 +42,7 @@ template class DistanceTablePlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { if (!check_all_coordinates(route_parameters.coordinates)) { @@ -82,7 +89,7 @@ template class DistanceTablePlugin final : public BasePlugin std::vector phantom_node_target_vector(number_of_destination); auto phantom_node_source_out_iter = phantom_node_source_vector.begin(); auto phantom_node_target_out_iter = phantom_node_target_vector.begin(); - for (const auto i : osrm::irange(0u, route_parameters.coordinates.size())) + for (const auto i : util::irange(0u, route_parameters.coordinates.size())) { if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) @@ -176,10 +183,10 @@ template class DistanceTablePlugin final : public BasePlugin return Status::EmptyResult; } - osrm::json::Array matrix_json_array; - for (const auto row : osrm::irange(0, number_of_sources)) + util::json::Array matrix_json_array; + for (const auto row : util::irange(0, number_of_sources)) { - osrm::json::Array json_row; + util::json::Array json_row; auto row_begin_iterator = result_table->begin() + (row * number_of_destination); auto row_end_iterator = result_table->begin() + ((row + 1) * number_of_destination); json_row.values.insert(json_row.values.end(), row_begin_iterator, row_end_iterator); @@ -187,19 +194,19 @@ template class DistanceTablePlugin final : public BasePlugin } json_result.values["distance_table"] = matrix_json_array; - osrm::json::Array target_coord_json_array; + util::json::Array target_coord_json_array; for (const auto &phantom : snapped_target_phantoms) { - osrm::json::Array json_coord; + util::json::Array json_coord; json_coord.values.push_back(phantom.location.lat / COORDINATE_PRECISION); json_coord.values.push_back(phantom.location.lon / COORDINATE_PRECISION); target_coord_json_array.values.push_back(json_coord); } json_result.values["destination_coordinates"] = target_coord_json_array; - osrm::json::Array source_coord_json_array; + util::json::Array source_coord_json_array; for (const auto &phantom : snapped_source_phantoms) { - osrm::json::Array json_coord; + util::json::Array json_coord; json_coord.values.push_back(phantom.location.lat / COORDINATE_PRECISION); json_coord.values.push_back(phantom.location.lon / COORDINATE_PRECISION); source_coord_json_array.values.push_back(json_coord); @@ -213,4 +220,8 @@ template class DistanceTablePlugin final : public BasePlugin DataFacadeT *facade; }; +} +} +} + #endif // DISTANCE_TABLE_HPP diff --git a/include/engine/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp index 3208b9b91..38a62b37c 100644 --- a/include/engine/plugins/hello_world.hpp +++ b/include/engine/plugins/hello_world.hpp @@ -7,6 +7,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + class HelloWorldPlugin final : public BasePlugin { private: @@ -18,7 +25,7 @@ class HelloWorldPlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &routeParameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { std::string temp_string; json_result.values["title"] = "Hello World"; @@ -41,12 +48,12 @@ class HelloWorldPlugin final : public BasePlugin temp_string = std::to_string(routeParameters.coordinates.size()); json_result.values["location_count"] = temp_string; - osrm::json::Array json_locations; + util::json::Array json_locations; unsigned counter = 0; - for (const FixedPointCoordinate &coordinate : routeParameters.coordinates) + for (const util::FixedPointCoordinate &coordinate : routeParameters.coordinates) { - osrm::json::Object json_location; - osrm::json::Array json_coordinates; + util::json::Object json_location; + util::json::Array json_coordinates; json_coordinates.values.push_back( static_cast(coordinate.lat / COORDINATE_PRECISION)); @@ -59,7 +66,7 @@ class HelloWorldPlugin final : public BasePlugin json_result.values["locations"] = json_locations; json_result.values["hint_count"] = routeParameters.hints.size(); - osrm::json::Array json_hints; + util::json::Array json_hints; counter = 0; for (const std::string ¤t_hint : routeParameters.hints) { @@ -74,4 +81,8 @@ class HelloWorldPlugin final : public BasePlugin std::string descriptor_string; }; +} +} +} + #endif // HELLO_WORLD_HPP diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 54819e88f..9df0aa2af 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -23,11 +23,21 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class MapMatchingPlugin : public BasePlugin { std::shared_ptr> search_engine_ptr; - using ClassifierT = BayesClassifier; + using SubMatching = routing_algorithms::SubMatching; + using SubMatchingList = routing_algorithms::SubMatchingList; + using CandidateLists = routing_algorithms::CandidateLists; + using ClassifierT = map_matching::BayesClassifier; using TraceClassification = ClassifierT::ClassificationT; public: @@ -36,8 +46,8 @@ template class MapMatchingPlugin : public BasePlugin max_locations_map_matching(max_locations_map_matching), // the values where derived from fitting a laplace distribution // to the values of manually classified traces - classifier(LaplaceDistribution(0.005986, 0.016646), - LaplaceDistribution(0.054385, 0.458432), + classifier(map_matching::LaplaceDistribution(0.005986, 0.016646), + map_matching::LaplaceDistribution(0.054385, 0.458432), 0.696774) // valid apriori probability { search_engine_ptr = std::make_shared>(facade); @@ -65,28 +75,28 @@ template class MapMatchingPlugin : public BasePlugin return label_with_confidence; } - osrm::matching::CandidateLists getCandidates( - const std::vector &input_coords, + CandidateLists getCandidates( + const std::vector &input_coords, const std::vector>> &input_bearings, const double gps_precision, std::vector &sub_trace_lengths) { - osrm::matching::CandidateLists candidates_lists; + CandidateLists candidates_lists; // assuming the gps_precision is the standart-diviation of normal distribution that models // GPS noise (in this model) this should give us the correct candidate with >0.95 double query_radius = 3 * gps_precision; double last_distance = - coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]); + util::coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]); sub_trace_lengths.resize(input_coords.size()); sub_trace_lengths[0] = 0; - for (const auto current_coordinate : osrm::irange(0, input_coords.size())) + for (const auto current_coordinate : util::irange(0, input_coords.size())) { bool allow_uturn = false; if (0 < current_coordinate) { - last_distance = coordinate_calculation::haversineDistance( + last_distance = util::coordinate_calculation::haversineDistance( input_coords[current_coordinate - 1], input_coords[current_coordinate]); sub_trace_lengths[current_coordinate] += @@ -95,7 +105,7 @@ template class MapMatchingPlugin : public BasePlugin if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate) { - double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates( + double turn_angle = util::ComputeAngle::OfThreeFixedPointCoordinates( input_coords[current_coordinate - 1], input_coords[current_coordinate], input_coords[current_coordinate + 1]); @@ -146,7 +156,7 @@ template class MapMatchingPlugin : public BasePlugin if (!allow_uturn) { const auto compact_size = candidates.size(); - for (const auto i : osrm::irange(0, compact_size)) + for (const auto i : util::irange(0, compact_size)) { // Split edge if it is bidirectional and append reverse direction to end of list if (candidates[i].phantom_node.forward_node_id != SPECIAL_NODEID && @@ -175,24 +185,24 @@ template class MapMatchingPlugin : public BasePlugin return candidates_lists; } - osrm::json::Object submatchingToJSON(const osrm::matching::SubMatching &sub, + util::json::Object submatchingToJSON(const SubMatching &sub, const RouteParameters &route_parameters, const InternalRouteResult &raw_route) { - osrm::json::Object subtrace; + util::json::Object subtrace; if (route_parameters.classify) { subtrace.values["confidence"] = sub.confidence; } - auto response_generator = osrm::engine::MakeApiResponseGenerator(facade); + auto response_generator = MakeApiResponseGenerator(facade); subtrace.values["hint_data"] = response_generator.BuildHintData(raw_route); if (route_parameters.geometry || route_parameters.print_instructions) { - using SegmentList = osrm::engine::guidance::SegmentList; + using SegmentList = guidance::SegmentList; //Passing false to extract_alternative extracts the route. const constexpr bool EXTRACT_ROUTE = false; // by passing false to segment_list, we skip the douglas peucker simplification @@ -210,28 +220,28 @@ template class MapMatchingPlugin : public BasePlugin if (route_parameters.print_instructions) { subtrace.values["instructions"] = - osrm::engine::guidance::AnnotateRoute( + guidance::AnnotateRoute( segment_list.Get(), facade); } - osrm::json::Object json_route_summary; + util::json::Object json_route_summary; json_route_summary.values["total_distance"] = segment_list.GetDistance(); json_route_summary.values["total_time"] = segment_list.GetDuration(); subtrace.values["route_summary"] = json_route_summary; } - subtrace.values["indices"] = osrm::json::make_array(sub.indices); + subtrace.values["indices"] = util::json::make_array(sub.indices); - osrm::json::Array points; + util::json::Array points; for (const auto &node : sub.nodes) { points.values.emplace_back( - osrm::json::make_array(node.location.lat / COORDINATE_PRECISION, + util::json::make_array(node.location.lat / COORDINATE_PRECISION, node.location.lon / COORDINATE_PRECISION)); } subtrace.values["matched_points"] = points; - osrm::json::Array names; + util::json::Array names; for (const auto &node : sub.nodes) { names.values.emplace_back(facade->get_name_for_id(node.name_id)); @@ -242,7 +252,7 @@ template class MapMatchingPlugin : public BasePlugin } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) final override + util::json::Object &json_result) final override { // enforce maximum number of locations for performance reasons if (max_locations_map_matching > 0 && @@ -296,16 +306,16 @@ template class MapMatchingPlugin : public BasePlugin } // setup logging if enabled - if (osrm::json::Logger::get()) - osrm::json::Logger::get()->initialize("matching"); + if (util::json::Logger::get()) + util::json::Logger::get()->initialize("matching"); // call the actual map matching - osrm::matching::SubMatchingList sub_matchings; + SubMatchingList sub_matchings; search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps, route_parameters.matching_beta, route_parameters.gps_precision, sub_matchings); - osrm::json::Array matchings; + util::json::Array matchings; for (auto &sub : sub_matchings) { // classify result @@ -349,8 +359,8 @@ template class MapMatchingPlugin : public BasePlugin matchings.values.emplace_back(submatchingToJSON(sub, route_parameters, raw_route)); } - if (osrm::json::Logger::get()) - osrm::json::Logger::get()->render("matching", json_result); + if (util::json::Logger::get()) + util::json::Logger::get()->render("matching", json_result); json_result.values["matchings"] = matchings; if (sub_matchings.empty()) @@ -370,4 +380,8 @@ template class MapMatchingPlugin : public BasePlugin ClassifierT classifier; }; +} +} +} + #endif // MATCH_HPP diff --git a/include/engine/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp index 28443dcf1..03604b1dc 100644 --- a/include/engine/plugins/nearest.hpp +++ b/include/engine/plugins/nearest.hpp @@ -8,6 +8,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + /* * This Plugin locates the nearest point on a street in the road network for a given coordinate. */ @@ -20,7 +27,7 @@ template class NearestPlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { // check number of parameters if (route_parameters.coordinates.empty() || @@ -58,15 +65,15 @@ template class NearestPlugin final : public BasePlugin json_result.values["status_message"] = "Found nearest edge"; if (number_of_results > 1) { - osrm::json::Array results; + util::json::Array results; auto vector_length = phantom_node_vector.size(); for (const auto i : - osrm::irange(0, std::min(number_of_results, vector_length))) + util::irange(0, std::min(number_of_results, vector_length))) { const auto &node = phantom_node_vector[i].phantom_node; - osrm::json::Array json_coordinate; - osrm::json::Object result; + util::json::Array json_coordinate; + util::json::Object result; json_coordinate.values.push_back(node.location.lat / COORDINATE_PRECISION); json_coordinate.values.push_back(node.location.lon / COORDINATE_PRECISION); result.values["mapped coordinate"] = json_coordinate; @@ -77,7 +84,7 @@ template class NearestPlugin final : public BasePlugin } else { - osrm::json::Array json_coordinate; + util::json::Array json_coordinate; json_coordinate.values.push_back( phantom_node_vector.front().phantom_node.location.lat / COORDINATE_PRECISION); json_coordinate.values.push_back( @@ -95,4 +102,8 @@ template class NearestPlugin final : public BasePlugin std::string descriptor_string; }; +} +} +} + #endif /* NEAREST_HPP */ diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index 5dffedd01..a2c7eba8c 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -11,6 +11,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + class BasePlugin { public: @@ -26,12 +33,12 @@ class BasePlugin // Maybe someone can explain the pure virtual destructor thing to me (dennis) virtual ~BasePlugin() {} virtual const std::string GetDescriptor() const = 0; - virtual Status HandleRequest(const RouteParameters &, osrm::json::Object &) = 0; - virtual bool check_all_coordinates(const std::vector &coordinates, + virtual Status HandleRequest(const RouteParameters &, util::json::Object &) = 0; + virtual bool check_all_coordinates(const std::vector &coordinates, const unsigned min = 2) const final { if (min > coordinates.size() || std::any_of(std::begin(coordinates), std::end(coordinates), - [](const FixedPointCoordinate &coordinate) + [](const util::FixedPointCoordinate &coordinate) { return !coordinate.IsValid(); })) @@ -106,4 +113,8 @@ class BasePlugin } }; +} +} +} + #endif /* BASE_PLUGIN_HPP */ diff --git a/include/engine/plugins/timestamp.hpp b/include/engine/plugins/timestamp.hpp index b479f01fc..1ec3d0a62 100644 --- a/include/engine/plugins/timestamp.hpp +++ b/include/engine/plugins/timestamp.hpp @@ -7,6 +7,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class TimestampPlugin final : public BasePlugin { public: @@ -16,7 +23,7 @@ template class TimestampPlugin final : public BasePlugin } const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { (void)route_parameters; // unused @@ -30,4 +37,8 @@ template class TimestampPlugin final : public BasePlugin std::string descriptor_string; }; +} +} +} + #endif /* TIMESTAMP_PLUGIN_H */ diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index 9ef2909bc..54632fdcd 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -25,6 +25,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class RoundTripPlugin final : public BasePlugin { private: @@ -37,7 +44,7 @@ template class RoundTripPlugin final : public BasePlugin explicit RoundTripPlugin(DataFacadeT *facade, int max_locations_trip) : descriptor_string("trip"), facade(facade), max_locations_trip(max_locations_trip) { - search_engine_ptr = osrm::make_unique>(facade); + search_engine_ptr = util::make_unique>(facade); } const std::string GetDescriptor() const override final { return descriptor_string; } @@ -51,7 +58,7 @@ template class RoundTripPlugin final : public BasePlugin phantom_node_list.reserve(route_parameters.coordinates.size()); // find phantom nodes for all input coords - for (const auto i : osrm::irange(0, route_parameters.coordinates.size())) + for (const auto i : util::irange(0, route_parameters.coordinates.size())) { // if client hints are helpful, encode hints if (checksum_OK && i < route_parameters.hints.size() && @@ -129,7 +136,7 @@ template class RoundTripPlugin final : public BasePlugin // identifies and splits the graph in its strongly connected components (scc) // and returns an SCC_Component SCC_Component SplitUnaccessibleLocations(const std::size_t number_of_locations, - const DistTableWrapper &result_table) + const util::DistTableWrapper &result_table) { if (std::find(std::begin(result_table), std::end(result_table), INVALID_EDGE_WEIGHT) == @@ -142,9 +149,9 @@ template class RoundTripPlugin final : public BasePlugin } // Run TarjanSCC - auto wrapper = std::make_shared>(result_table.GetTable(), + auto wrapper = std::make_shared>(result_table.GetTable(), number_of_locations); - auto scc = TarjanSCC>(wrapper); + auto scc = extractor::TarjanSCC>(wrapper); scc.run(); const auto number_of_components = scc.get_number_of_components(); @@ -174,9 +181,9 @@ template class RoundTripPlugin final : public BasePlugin } void SetLocPermutationOutput(const std::vector &permutation, - osrm::json::Object &json_result) + util::json::Object &json_result) { - osrm::json::Array json_permutation; + util::json::Array json_permutation; json_permutation.values.insert(std::end(json_permutation.values), std::begin(permutation), std::end(permutation)); json_result.values["permutation"] = json_permutation; @@ -218,7 +225,7 @@ template class RoundTripPlugin final : public BasePlugin } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { if (max_locations_trip > 0 && (static_cast(route_parameters.coordinates.size()) > max_locations_trip)) @@ -259,7 +266,7 @@ template class RoundTripPlugin final : public BasePlugin const auto number_of_locations = phantom_node_list.size(); // compute the distance table of all phantom nodes - const auto result_table = DistTableWrapper( + const auto result_table = util::DistTableWrapper( *search_engine_ptr->distance_table(phantom_node_list, phantom_node_list), number_of_locations); @@ -295,16 +302,16 @@ template class RoundTripPlugin final : public BasePlugin if (component_size < BF_MAX_FEASABLE) { scc_route = - osrm::trip::BruteForceTrip(start, end, number_of_locations, result_table); + trip::BruteForceTrip(start, end, number_of_locations, result_table); } else { - scc_route = osrm::trip::FarthestInsertionTrip(start, end, number_of_locations, + scc_route = trip::FarthestInsertionTrip(start, end, number_of_locations, result_table); } // use this output if debugging of route is needed: - // SimpleLogger().Write() << "Route #" << k << ": " << [&scc_route]() + // util::SimpleLogger().Write() << "Route #" << k << ": " << [&scc_route]() // { // std::string s = ""; // for (auto x : scc_route) @@ -333,13 +340,13 @@ template class RoundTripPlugin final : public BasePlugin // prepare JSON output // create a json object for every trip - osrm::json::Array trip; + util::json::Array trip; for (std::size_t i = 0; i < route_result.size(); ++i) { - osrm::json::Object scc_trip; + util::json::Object scc_trip; // annotate comp_route[i] as a json trip - auto generator = osrm::engine::MakeApiResponseGenerator(facade); + auto generator = MakeApiResponseGenerator(facade); generator.DescribeRoute(route_parameters, comp_route[i], scc_trip); // set permutation output @@ -360,4 +367,8 @@ template class RoundTripPlugin final : public BasePlugin } }; +} +} +} + #endif // TRIP_HPP diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index 6b432e55d..8e58c00f9 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -20,6 +20,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace plugins +{ + template class ViaRoutePlugin final : public BasePlugin { private: @@ -33,7 +40,7 @@ template class ViaRoutePlugin final : public BasePlugin : descriptor_string("viaroute"), facade(facade), max_locations_viaroute(max_locations_viaroute) { - search_engine_ptr = osrm::make_unique>(facade); + search_engine_ptr = util::make_unique>(facade); } virtual ~ViaRoutePlugin() {} @@ -41,7 +48,7 @@ template class ViaRoutePlugin final : public BasePlugin const std::string GetDescriptor() const override final { return descriptor_string; } Status HandleRequest(const RouteParameters &route_parameters, - osrm::json::Object &json_result) override final + util::json::Object &json_result) override final { if (max_locations_viaroute > 0 && (static_cast(route_parameters.coordinates.size()) > max_locations_viaroute)) @@ -70,7 +77,7 @@ template class ViaRoutePlugin final : public BasePlugin std::vector phantom_node_pair_list(route_parameters.coordinates.size()); const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum()); - for (const auto i : osrm::irange(0, route_parameters.coordinates.size())) + for (const auto i : util::irange(0, route_parameters.coordinates.size())) { if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) @@ -108,7 +115,7 @@ template class ViaRoutePlugin final : public BasePlugin { raw_route.segment_end_coordinates.push_back(PhantomNodes{first_node, second_node}); }; - osrm::for_each_pair(snapped_phantoms, build_phantom_pairs); + util::for_each_pair(snapped_phantoms, build_phantom_pairs); if (1 == raw_route.segment_end_coordinates.size()) { @@ -131,7 +138,7 @@ template class ViaRoutePlugin final : public BasePlugin bool no_route = INVALID_EDGE_WEIGHT == raw_route.shortest_path_length; - auto generator = osrm::engine::MakeApiResponseGenerator(facade); + auto generator = MakeApiResponseGenerator(facade); generator.DescribeRoute(route_parameters, raw_route, json_result); // we can only know this after the fact, different SCC ids still @@ -160,4 +167,8 @@ template class ViaRoutePlugin final : public BasePlugin } }; +} +} +} + #endif // VIA_ROUTE_HPP diff --git a/include/engine/polyline_compressor.hpp b/include/engine/polyline_compressor.hpp index 7d04b1d10..5d26a14fa 100644 --- a/include/engine/polyline_compressor.hpp +++ b/include/engine/polyline_compressor.hpp @@ -1,13 +1,18 @@ #ifndef POLYLINECOMPRESSOR_H_ #define POLYLINECOMPRESSOR_H_ -struct SegmentInformation; - #include "osrm/coordinate.hpp" #include #include +namespace osrm +{ +namespace engine +{ + +struct SegmentInformation; + class PolylineCompressor { private: @@ -18,7 +23,10 @@ class PolylineCompressor public: std::string get_encoded_string(const std::vector &polyline) const; - std::vector decode_string(const std::string &geometry_string) const; + std::vector decode_string(const std::string &geometry_string) const; }; +} +} + #endif /* POLYLINECOMPRESSOR_H_ */ diff --git a/include/engine/polyline_formatter.hpp b/include/engine/polyline_formatter.hpp index b71035ae4..861fec01f 100644 --- a/include/engine/polyline_formatter.hpp +++ b/include/engine/polyline_formatter.hpp @@ -1,18 +1,26 @@ #ifndef POLYLINE_FORMATTER_HPP #define POLYLINE_FORMATTER_HPP -struct SegmentInformation; - #include "osrm/json_container.hpp" #include #include +namespace osrm +{ +namespace engine +{ + +struct SegmentInformation; + struct PolylineFormatter { - osrm::json::String printEncodedString(const std::vector &polyline) const; + util::json::String printEncodedString(const std::vector &polyline) const; - osrm::json::Array printUnencodedString(const std::vector &polyline) const; + util::json::Array printUnencodedString(const std::vector &polyline) const; }; +} +} + #endif /* POLYLINE_FORMATTER_HPP */ diff --git a/include/engine/route_name_extraction.hpp b/include/engine/route_name_extraction.hpp index 97e1919bb..df6a8ac89 100644 --- a/include/engine/route_name_extraction.hpp +++ b/include/engine/route_name_extraction.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace engine +{ + struct RouteNames { std::string shortest_path_name_1; @@ -135,4 +140,7 @@ template struct ExtractRouteNames } }; +} +} + #endif // EXTRACT_ROUTE_NAMES_H diff --git a/include/engine/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp index 37b6ced19..ec82818f8 100644 --- a/include/engine/routing_algorithms/alternative_path.hpp +++ b/include/engine/routing_algorithms/alternative_path.hpp @@ -13,6 +13,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace routing_algorithms +{ + const double VIAPATH_ALPHA = 0.10; const double VIAPATH_EPSILON = 0.15; // alternative at most 15% longer const double VIAPATH_GAMMA = 0.75; // alternative shares at most 75% with the shortest. @@ -81,7 +88,7 @@ class AlternativeRouting final if (phantom_node_pair.source_phantom.forward_node_id != SPECIAL_NODEID) { - // SimpleLogger().Write(logDEBUG) << "fwd-a insert: " << + // util::SimpleLogger().Write(logDEBUG) << "fwd-a insert: " << // phantom_node_pair.source_phantom.forward_node_id << ", w: " << // -phantom_node_pair.source_phantom.GetForwardWeightPlusOffset(); forward_heap1.Insert(phantom_node_pair.source_phantom.forward_node_id, @@ -90,7 +97,7 @@ class AlternativeRouting final } if (phantom_node_pair.source_phantom.reverse_node_id != SPECIAL_NODEID) { - // SimpleLogger().Write(logDEBUG) << "fwd-b insert: " << + // util::SimpleLogger().Write(logDEBUG) << "fwd-b insert: " << // phantom_node_pair.source_phantom.reverse_node_id << ", w: " << // -phantom_node_pair.source_phantom.GetReverseWeightPlusOffset(); forward_heap1.Insert(phantom_node_pair.source_phantom.reverse_node_id, @@ -100,7 +107,7 @@ class AlternativeRouting final if (phantom_node_pair.target_phantom.forward_node_id != SPECIAL_NODEID) { - // SimpleLogger().Write(logDEBUG) << "rev-a insert: " << + // util::SimpleLogger().Write(logDEBUG) << "rev-a insert: " << // phantom_node_pair.target_phantom.forward_node_id << ", w: " << // phantom_node_pair.target_phantom.GetForwardWeightPlusOffset(); reverse_heap1.Insert(phantom_node_pair.target_phantom.forward_node_id, @@ -109,7 +116,7 @@ class AlternativeRouting final } if (phantom_node_pair.target_phantom.reverse_node_id != SPECIAL_NODEID) { - // SimpleLogger().Write(logDEBUG) << "rev-b insert: " << + // util::SimpleLogger().Write(logDEBUG) << "rev-b insert: " << // phantom_node_pair.target_phantom.reverse_node_id << ", w: " << // phantom_node_pair.target_phantom.GetReverseWeightPlusOffset(); reverse_heap1.Insert(phantom_node_pair.target_phantom.reverse_node_id, @@ -141,7 +148,7 @@ class AlternativeRouting final return; } - osrm::sort_unique_resize(via_node_candidate_list); + util::sort_unique_resize(via_node_candidate_list); std::vector packed_forward_path; std::vector packed_reverse_path; @@ -204,10 +211,10 @@ class AlternativeRouting final } } - // SimpleLogger().Write(logDEBUG) << "fwd_search_space size: " << + // util::SimpleLogger().Write(logDEBUG) << "fwd_search_space size: " << // forward_search_space.size() << ", marked " << approximated_forward_sharing.size() << " // nodes"; - // SimpleLogger().Write(logDEBUG) << "rev_search_space size: " << + // util::SimpleLogger().Write(logDEBUG) << "rev_search_space size: " << // reverse_search_space.size() << ", marked " << approximated_reverse_sharing.size() << " // nodes"; @@ -403,7 +410,7 @@ class AlternativeRouting final // First partially unpack s-->v until paths deviate, note length of common path. const int64_t s_v_min_path_size = static_cast(std::min(packed_s_v_path.size(), packed_shortest_path.size())) - 1; - for (const int64_t current_node : osrm::irange(0, s_v_min_path_size)) + for (const int64_t current_node : util::irange(0, s_v_min_path_size)) { if (packed_s_v_path[current_node] == packed_shortest_path[current_node] && packed_s_v_path[current_node + 1] == packed_shortest_path[current_node + 1]) @@ -519,7 +526,7 @@ class AlternativeRouting final // //compute forward sharing // while( (packed_alternate_path[aindex] == packed_shortest_path[aindex]) && // (packed_alternate_path[aindex+1] == packed_shortest_path[aindex+1]) ) { - // // SimpleLogger().Write() << "retrieving edge (" << + // // util::SimpleLogger().Write() << "retrieving edge (" << // packed_alternate_path[aindex] << "," << packed_alternate_path[aindex+1] << ")"; // EdgeID edgeID = facade->FindEdgeInEitherDirection(packed_alternate_path[aindex], // packed_alternate_path[aindex+1]); @@ -557,7 +564,7 @@ class AlternativeRouting final const NodeID node = forward_heap.DeleteMin(); const int distance = forward_heap.GetKey(node); // const NodeID parentnode = forward_heap.GetData(node).parent; - // SimpleLogger().Write() << (is_forward_directed ? "[fwd] " : "[rev] ") << "settled edge (" + // util::SimpleLogger().Write() << (is_forward_directed ? "[fwd] " : "[rev] ") << "settled edge (" // << parentnode << "," << node << "), dist: " << distance; const int scaled_distance = @@ -581,10 +588,10 @@ class AlternativeRouting final { *middle_node = node; *upper_bound_to_shortest_path_distance = new_distance; - // SimpleLogger().Write() << "accepted middle_node " << *middle_node << " at + // util::SimpleLogger().Write() << "accepted middle_node " << *middle_node << " at // distance " << new_distance; // } else { - // SimpleLogger().Write() << "discarded middle_node " << *middle_node << " + // util::SimpleLogger().Write() << "discarded middle_node " << *middle_node << " // at distance " << new_distance; } } @@ -840,4 +847,8 @@ class AlternativeRouting final } }; +} +} +} + #endif /* ALTERNATIVE_PATH_ROUTING_HPP */ diff --git a/include/engine/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp index 42bc357ff..7c935928c 100644 --- a/include/engine/routing_algorithms/direct_shortest_path.hpp +++ b/include/engine/routing_algorithms/direct_shortest_path.hpp @@ -10,6 +10,13 @@ #include "util/timing_util.hpp" #include "util/typedefs.hpp" +namespace osrm +{ +namespace engine +{ +namespace routing_algorithms +{ + /// This is a striped down version of the general shortest path algorithm. /// The general algorithm always computes two queries for each leg. This is only /// necessary in case of vias, where the directions of the start node is constrainted @@ -125,4 +132,8 @@ class DirectShortestPathRouting final } }; +} +} +} + #endif /* DIRECT_SHORTEST_PATH_HPP */ diff --git a/include/engine/routing_algorithms/many_to_many.hpp b/include/engine/routing_algorithms/many_to_many.hpp index fb6981892..c8311783f 100644 --- a/include/engine/routing_algorithms/many_to_many.hpp +++ b/include/engine/routing_algorithms/many_to_many.hpp @@ -12,6 +12,13 @@ #include #include +namespace osrm +{ +namespace engine +{ +namespace routing_algorithms +{ + template class ManyToManyRouting final : public BasicRoutingInterface> @@ -226,4 +233,8 @@ class ManyToManyRouting final return false; } }; +} +} +} + #endif diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 905dc611a..23edcedb5 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -19,7 +19,9 @@ namespace osrm { -namespace matching +namespace engine +{ +namespace routing_algorithms { struct SubMatching @@ -32,15 +34,12 @@ struct SubMatching using CandidateList = std::vector; using CandidateLists = std::vector; -using HMM = HiddenMarkovModel; +using HMM = map_matching::HiddenMarkovModel; using SubMatchingList = std::vector; constexpr static const unsigned MAX_BROKEN_STATES = 10; - constexpr static const double MAX_SPEED = 180 / 3.6; // 180km -> m/s constexpr static const unsigned SUSPICIOUS_DISTANCE_DELTA = 100; -} -} // implements a hidden markov model map matching algorithm template @@ -71,12 +70,12 @@ class MapMatching final : public BasicRoutingInterface &trace_coordinates, + void operator()(const CandidateLists &candidates_list, + const std::vector &trace_coordinates, const std::vector &trace_timestamps, const double matching_beta, const double gps_precision, - osrm::matching::SubMatchingList &sub_matchings) const + SubMatchingList &sub_matchings) const { BOOST_ASSERT(candidates_list.size() == trace_coordinates.size()); BOOST_ASSERT(candidates_list.size() > 1); @@ -94,12 +93,12 @@ class MapMatching final : public BasicRoutingInterface split_points; std::vector prev_unbroken_timestamps; prev_unbroken_timestamps.reserve(candidates_list.size()); @@ -149,16 +148,16 @@ class MapMatching final : public BasicRoutingInterface - osrm::matching::MAX_BROKEN_STATES); + MAX_BROKEN_STATES); } if (trace_split) { std::size_t split_index = t; - if (breakage_begin != osrm::matching::INVALID_STATE) + if (breakage_begin != map_matching::INVALID_STATE) { split_index = breakage_begin; - breakage_begin = osrm::matching::INVALID_STATE; + breakage_begin = map_matching::INVALID_STATE; } split_points.push_back(split_index); @@ -166,7 +165,7 @@ class MapMatching final : public BasicRoutingInterface stop viterbi calculation - if (new_start == osrm::matching::INVALID_STATE) + if (new_start == map_matching::INVALID_STATE) { break; } @@ -196,17 +195,17 @@ class MapMatching final : public BasicRoutingInterface(0u, prev_viterbi.size())) + for (const auto s : util::irange(0u, prev_viterbi.size())) { if (prev_pruned[s]) { continue; } - for (const auto s_prime : osrm::irange(0u, current_viterbi.size())) + for (const auto s_prime : util::irange(0u, current_viterbi.size())) { // how likely is candidate s_prime at time t to be emitted? // FIXME this can be pre-computed @@ -248,7 +247,7 @@ class MapMatching final : public BasicRoutingInterface osrm::matching::SUSPICIOUS_DISTANCE_DELTA; + d_t > SUSPICIOUS_DISTANCE_DELTA; model.breakage[t] = false; } } @@ -282,7 +281,7 @@ class MapMatching final : public BasicRoutingInterface= sub_matching_begin && @@ -338,7 +337,7 @@ class MapMatching final : public BasicRoutingInterface(0u, reconstructed_indices.size())) + for (const auto i : util::irange(0u, reconstructed_indices.size())) { const auto timestamp_index = reconstructed_indices[i].first; const auto location_index = reconstructed_indices[i].second; @@ -357,6 +356,10 @@ class MapMatching final : public BasicRoutingInterface +namespace osrm +{ +namespace engine +{ + SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_1; SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_1; SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_2; @@ -17,6 +22,10 @@ SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_2; SearchEngineData::SearchEngineHeapPtr SearchEngineData::forward_heap_3; SearchEngineData::SearchEngineHeapPtr SearchEngineData::reverse_heap_3; +namespace routing_algorithms +{ + + template class BasicRoutingInterface { private: @@ -222,8 +231,8 @@ template class BasicRoutingInterface { BOOST_ASSERT_MSG(!ed.shortcut, "original edge flagged as shortcut"); unsigned name_index = facade->GetNameIndexFromEdgeID(ed.id); - const TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id); - const TravelMode travel_mode = facade->GetTravelModeForEdgeID(ed.id); + const extractor::TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id); + const extractor::TravelMode travel_mode = facade->GetTravelModeForEdgeID(ed.id); if (!facade->EdgeIsCompressed(ed.id)) { @@ -251,7 +260,7 @@ template class BasicRoutingInterface for (std::size_t i = start_index; i < end_index; ++i) { unpacked_path.emplace_back(id_vector[i], name_index, - TurnInstruction::NoTurn, 0, travel_mode); + extractor::TurnInstruction::NoTurn, 0, travel_mode); } unpacked_path.back().turn_instruction = turn_instruction; unpacked_path.back().segment_duration = ed.distance; @@ -296,7 +305,7 @@ template class BasicRoutingInterface BOOST_ASSERT(i < id_vector.size()); BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode > 0); unpacked_path.emplace_back(PathData{ - id_vector[i], phantom_node_pair.target_phantom.name_id, TurnInstruction::NoTurn, + id_vector[i], phantom_node_pair.target_phantom.name_id, extractor::TurnInstruction::NoTurn, 0, phantom_node_pair.target_phantom.forward_travel_mode}); } } @@ -642,21 +651,25 @@ template class BasicRoutingInterface nodes.target_phantom = target_phantom; UnpackPath(packed_leg.begin(), packed_leg.end(), nodes, unpacked_path); - FixedPointCoordinate previous_coordinate = source_phantom.location; - FixedPointCoordinate current_coordinate; + util::FixedPointCoordinate previous_coordinate = source_phantom.location; + util::FixedPointCoordinate current_coordinate; distance = 0; for (const auto &p : unpacked_path) { current_coordinate = facade->GetCoordinateOfNode(p.node); - distance += coordinate_calculation::haversineDistance(previous_coordinate, + distance += util::coordinate_calculation::haversineDistance(previous_coordinate, current_coordinate); previous_coordinate = current_coordinate; } - distance += coordinate_calculation::haversineDistance(previous_coordinate, + distance += util::coordinate_calculation::haversineDistance(previous_coordinate, target_phantom.location); } return distance; } }; +} +} +} + #endif // ROUTING_BASE_HPP diff --git a/include/engine/routing_algorithms/shortest_path.hpp b/include/engine/routing_algorithms/shortest_path.hpp index a9b50afe4..8a057d42d 100644 --- a/include/engine/routing_algorithms/shortest_path.hpp +++ b/include/engine/routing_algorithms/shortest_path.hpp @@ -10,6 +10,13 @@ #include +namespace osrm +{ +namespace engine +{ +namespace routing_algorithms +{ + template class ShortestPathRouting final : public BasicRoutingInterface> @@ -262,7 +269,7 @@ class ShortestPathRouting final raw_route_data.shortest_path_length = shortest_path_length; - for (const auto current_leg : osrm::irange(0, packed_leg_begin.size() - 1)) + for (const auto current_leg : util::irange(0, packed_leg_begin.size() - 1)) { auto leg_begin = total_packed_path.begin() + packed_leg_begin[current_leg]; auto leg_end = total_packed_path.begin() + packed_leg_begin[current_leg + 1]; @@ -515,4 +522,8 @@ class ShortestPathRouting final } }; +} +} +} + #endif /* SHORTEST_PATH_HPP */ diff --git a/include/engine/search_engine.hpp b/include/engine/search_engine.hpp index aec2a735a..fefc90368 100644 --- a/include/engine/search_engine.hpp +++ b/include/engine/search_engine.hpp @@ -10,6 +10,11 @@ #include +namespace osrm +{ +namespace engine +{ + template class SearchEngine { private: @@ -17,11 +22,11 @@ template class SearchEngine SearchEngineData engine_working_data; public: - ShortestPathRouting shortest_path; - DirectShortestPathRouting direct_shortest_path; - AlternativeRouting alternative_path; - ManyToManyRouting distance_table; - MapMatching map_matching; + routing_algorithms::ShortestPathRouting shortest_path; + routing_algorithms::DirectShortestPathRouting direct_shortest_path; + routing_algorithms::AlternativeRouting alternative_path; + routing_algorithms::ManyToManyRouting distance_table; + routing_algorithms::MapMatching map_matching; explicit SearchEngine(DataFacadeT *facade) : facade(facade), shortest_path(facade, engine_working_data), @@ -37,4 +42,7 @@ template class SearchEngine ~SearchEngine() {} }; +} +} + #endif // SEARCH_ENGINE_HPP diff --git a/include/engine/search_engine_data.hpp b/include/engine/search_engine_data.hpp index 87e76604e..2e5b59da5 100644 --- a/include/engine/search_engine_data.hpp +++ b/include/engine/search_engine_data.hpp @@ -6,6 +6,11 @@ #include "util/typedefs.hpp" #include "util/binary_heap.hpp" +namespace osrm +{ +namespace engine +{ + struct HeapData { NodeID parent; @@ -14,7 +19,7 @@ struct HeapData struct SearchEngineData { - using QueryHeap = BinaryHeap>; + using QueryHeap = util::BinaryHeap>; using SearchEngineHeapPtr = boost::thread_specific_ptr; static SearchEngineHeapPtr forward_heap_1; @@ -31,4 +36,7 @@ struct SearchEngineData void InitializeOrClearThirdThreadLocalStorage(const unsigned number_of_nodes); }; +} +} + #endif // SEARCH_ENGINE_DATA_HPP diff --git a/include/engine/segment_information.hpp b/include/engine/segment_information.hpp index eaedec78d..527726f92 100644 --- a/include/engine/segment_information.hpp +++ b/include/engine/segment_information.hpp @@ -2,53 +2,60 @@ #define SEGMENT_INFORMATION_HPP #include "extractor/turn_instructions.hpp" - #include "extractor/travel_mode.hpp" #include "util/typedefs.hpp" #include "osrm/coordinate.hpp" #include +namespace osrm +{ +namespace engine +{ + // Struct fits everything in one cache line struct SegmentInformation { - FixedPointCoordinate location; + util::FixedPointCoordinate location; NodeID name_id; EdgeWeight duration; float length; short pre_turn_bearing; // more than enough [0..3600] fits into 12 bits short post_turn_bearing; - TurnInstruction turn_instruction; - TravelMode travel_mode; + extractor::TurnInstruction turn_instruction; + extractor::TravelMode travel_mode; bool necessary; bool is_via_location; - explicit SegmentInformation(FixedPointCoordinate location, + explicit SegmentInformation(util::FixedPointCoordinate location, const NodeID name_id, const EdgeWeight duration, const float length, - const TurnInstruction turn_instruction, + const extractor::TurnInstruction turn_instruction, const bool necessary, const bool is_via_location, - const TravelMode travel_mode) + const extractor::TravelMode travel_mode) : location(std::move(location)), name_id(name_id), duration(duration), length(length), pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), travel_mode(travel_mode), necessary(necessary), is_via_location(is_via_location) { } - explicit SegmentInformation(FixedPointCoordinate location, + explicit SegmentInformation(util::FixedPointCoordinate location, const NodeID name_id, const EdgeWeight duration, const float length, - const TurnInstruction turn_instruction, - const TravelMode travel_mode) + const extractor::TurnInstruction turn_instruction, + const extractor::TravelMode travel_mode) : location(std::move(location)), name_id(name_id), duration(duration), length(length), pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), - travel_mode(travel_mode), necessary(turn_instruction != TurnInstruction::NoTurn), + travel_mode(travel_mode), necessary(turn_instruction != extractor::TurnInstruction::NoTurn), is_via_location(false) { } }; +} +} + #endif /* SEGMENT_INFORMATION_HPP */ diff --git a/include/engine/trip/trip_brute_force.hpp b/include/engine/trip/trip_brute_force.hpp index d45643059..5cecabcac 100644 --- a/include/engine/trip/trip_brute_force.hpp +++ b/include/engine/trip/trip_brute_force.hpp @@ -16,11 +16,13 @@ namespace osrm { +namespace engine +{ namespace trip { // computes the distance of a given permutation -EdgeWeight ReturnDistance(const DistTableWrapper &dist_table, +EdgeWeight ReturnDistance(const util::DistTableWrapper &dist_table, const std::vector &location_order, const EdgeWeight min_route_dist, const std::size_t component_size) @@ -44,7 +46,7 @@ template std::vector BruteForceTrip(const NodeIDIterator start, const NodeIDIterator end, const std::size_t number_of_locations, - const DistTableWrapper &dist_table) + const util::DistTableWrapper &dist_table) { (void)number_of_locations; // unused @@ -76,6 +78,8 @@ std::vector BruteForceTrip(const NodeIDIterator start, return route; } -} // end namespace trip -} // end namespace osrm +} +} +} + #endif // TRIP_BRUTE_FORCE_HPP diff --git a/include/engine/trip/trip_farthest_insertion.hpp b/include/engine/trip/trip_farthest_insertion.hpp index aa94b1fb0..2e3b401a4 100644 --- a/include/engine/trip/trip_farthest_insertion.hpp +++ b/include/engine/trip/trip_farthest_insertion.hpp @@ -15,6 +15,8 @@ namespace osrm { +namespace engine +{ namespace trip { @@ -23,7 +25,7 @@ namespace trip using NodeIDIter = std::vector::iterator; std::pair GetShortestRoundTrip(const NodeID new_loc, - const DistTableWrapper &dist_table, + const util::DistTableWrapper &dist_table, const std::size_t number_of_locations, std::vector &route) { @@ -76,7 +78,7 @@ std::vector FindRoute(const std::size_t &number_of_locations, const std::size_t &component_size, const NodeIDIterator &start, const NodeIDIterator &end, - const DistTableWrapper &dist_table, + const util::DistTableWrapper &dist_table, const NodeID &start1, const NodeID &start2) { @@ -138,7 +140,7 @@ template std::vector FarthestInsertionTrip(const NodeIDIterator &start, const NodeIDIterator &end, const std::size_t number_of_locations, - const DistTableWrapper &dist_table) + const util::DistTableWrapper &dist_table) { ////////////////////////////////////////////////////////////////////////////////////////////////// // START FARTHEST INSERTION HERE @@ -189,7 +191,8 @@ std::vector FarthestInsertionTrip(const NodeIDIterator &start, return FindRoute(number_of_locations, component_size, start, end, dist_table, max_from, max_to); } -} // end namespace trip -} // end namespace osrm +} +} +} #endif // TRIP_FARTHEST_INSERTION_HPP diff --git a/include/engine/trip/trip_nearest_neighbour.hpp b/include/engine/trip/trip_nearest_neighbour.hpp index c66e611d6..a7a5baeb3 100644 --- a/include/engine/trip/trip_nearest_neighbour.hpp +++ b/include/engine/trip/trip_nearest_neighbour.hpp @@ -15,13 +15,16 @@ namespace osrm { +namespace engine +{ namespace trip { + template std::vector NearestNeighbourTrip(const NodeIDIterator &start, const NodeIDIterator &end, const std::size_t number_of_locations, - const DistTableWrapper &dist_table) + const util::DistTableWrapper &dist_table) { ////////////////////////////////////////////////////////////////////////////////////////////////// // START GREEDY NEAREST NEIGHBOUR HERE @@ -90,6 +93,8 @@ std::vector NearestNeighbourTrip(const NodeIDIterator &start, return route; } -} // end namespace trip -} // end namespace osrm -#endif // TRIP_NEAREST_NEIGHBOUR_HPP \ No newline at end of file +} +} +} + +#endif // TRIP_NEAREST_NEIGHBOUR_HPP diff --git a/include/engine/trip/trip_tabu_search.hpp b/include/engine/trip/trip_tabu_search.hpp index 1eb5b6a44..d92763616 100644 --- a/include/engine/trip/trip_tabu_search.hpp +++ b/include/engine/trip/trip_tabu_search.hpp @@ -14,6 +14,8 @@ namespace osrm { +namespace engine +{ namespace trip { @@ -32,6 +34,9 @@ void TabuSearchTrip(const PhantomNodeArray &phantom_node_vector, std::vector &min_loc_permutation) { } + } } -#endif // TRIP_BRUTE_FORCE_HPP \ No newline at end of file +} + +#endif // TRIP_BRUTE_FORCE_HPP diff --git a/include/extractor/compressed_edge_container.hpp b/include/extractor/compressed_edge_container.hpp index cfac68eff..47146162c 100644 --- a/include/extractor/compressed_edge_container.hpp +++ b/include/extractor/compressed_edge_container.hpp @@ -8,6 +8,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + class CompressedEdgeContainer { public: @@ -39,4 +44,7 @@ class CompressedEdgeContainer std::unordered_map m_edge_id_to_list_index_map; }; +} +} + #endif // GEOMETRY_COMPRESSOR_HPP_ diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 5a2b259f2..47aeecdcb 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -27,13 +27,18 @@ struct lua_State; +namespace osrm +{ +namespace extractor +{ + class EdgeBasedGraphFactory { public: EdgeBasedGraphFactory() = delete; EdgeBasedGraphFactory(const EdgeBasedGraphFactory &) = delete; - explicit EdgeBasedGraphFactory(std::shared_ptr node_based_graph, + explicit EdgeBasedGraphFactory(std::shared_ptr node_based_graph, const CompressedEdgeContainer &compressed_edge_container, const std::unordered_set &barrier_nodes, const std::unordered_set &traffic_lights, @@ -56,7 +61,7 @@ class EdgeBasedGraphFactory const bool generate_edge_lookup); #endif - void GetEdgeBasedEdges(DeallocatingVector &edges); + void GetEdgeBasedEdges(util::DeallocatingVector &edges); void GetEdgeBasedNodes(std::vector &nodes); void GetStartPointMarkers(std::vector &node_is_startpoint); @@ -69,18 +74,18 @@ class EdgeBasedGraphFactory int GetTurnPenalty(double angle, lua_State *lua_state) const; private: - using EdgeData = NodeBasedDynamicGraph::EdgeData; + using EdgeData = util::NodeBasedDynamicGraph::EdgeData; //! maps index from m_edge_based_node_list to ture/false if the node is an entry point to the //! graph std::vector m_edge_based_node_is_startpoint; //! list of edge based nodes (compressed segments) std::vector m_edge_based_node_list; - DeallocatingVector m_edge_based_edge_list; + util::DeallocatingVector m_edge_based_edge_list; unsigned m_max_edge_id; const std::vector &m_node_info_list; - std::shared_ptr m_node_based_graph; + std::shared_ptr m_node_based_graph; std::shared_ptr m_restriction_map; const std::unordered_set &m_barrier_nodes; @@ -113,4 +118,7 @@ class EdgeBasedGraphFactory std::vector &original_edge_data_vector) const; }; +} +} + #endif /* EDGE_BASED_GRAPH_FACTORY_HPP_ */ diff --git a/include/extractor/edge_based_node.hpp b/include/extractor/edge_based_node.hpp index 3ea715a89..aee2d6a34 100644 --- a/include/extractor/edge_based_node.hpp +++ b/include/extractor/edge_based_node.hpp @@ -10,7 +10,12 @@ #include -/// This is what StaticRTree serialized and stores on disk +namespace osrm +{ +namespace extractor +{ + +/// This is what util::StaticRTree serialized and stores on disk /// It is generated in EdgeBasedGraphFactory. struct EdgeBasedNode { @@ -53,10 +58,10 @@ struct EdgeBasedNode (reverse_edge_based_node_id != SPECIAL_NODEID)); } - static inline FixedPointCoordinate Centroid(const FixedPointCoordinate &a, - const FixedPointCoordinate &b) + static inline util::FixedPointCoordinate Centroid(const util::FixedPointCoordinate &a, + const util::FixedPointCoordinate &b) { - FixedPointCoordinate centroid; + util::FixedPointCoordinate centroid; // The coordinates of the midpoint are given by: centroid.lat = (a.lat + b.lat) / 2; centroid.lon = (a.lon + b.lon) / 2; @@ -85,4 +90,7 @@ struct EdgeBasedNode TravelMode backward_travel_mode : 4; }; +} +} + #endif // EDGE_BASED_NODE_HPP diff --git a/include/extractor/external_memory_node.hpp b/include/extractor/external_memory_node.hpp index 8c2b7d194..544e59fdc 100644 --- a/include/extractor/external_memory_node.hpp +++ b/include/extractor/external_memory_node.hpp @@ -5,6 +5,11 @@ #include "util/typedefs.hpp" +namespace osrm +{ +namespace extractor +{ + struct ExternalMemoryNode : QueryNode { ExternalMemoryNode(int lat, int lon, OSMNodeID id, bool barrier, bool traffic_light); @@ -27,4 +32,7 @@ struct ExternalMemoryNodeSTXXLCompare value_type min_value(); }; +} +} + #endif /* EXTERNAL_MEMORY_NODE_HPP_ */ diff --git a/include/extractor/extraction_containers.hpp b/include/extractor/extraction_containers.hpp index 83a8978f5..53177e0d6 100644 --- a/include/extractor/extraction_containers.hpp +++ b/include/extractor/extraction_containers.hpp @@ -10,6 +10,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + /** * Uses external memory containers from stxxl to store all the data that * is collected by the extractor callbacks. @@ -61,4 +66,7 @@ class ExtractionContainers lua_State *segment_state); }; +} +} + #endif /* EXTRACTION_CONTAINERS_HPP */ diff --git a/include/extractor/extraction_helper_functions.hpp b/include/extractor/extraction_helper_functions.hpp index 6872812fc..82a493b77 100644 --- a/include/extractor/extraction_helper_functions.hpp +++ b/include/extractor/extraction_helper_functions.hpp @@ -12,6 +12,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + bool simple_duration_is_valid(const std::string &s) { boost::regex simple_format( @@ -29,8 +34,8 @@ bool simple_duration_is_valid(const std::string &s) bool iso_8601_duration_is_valid(const std::string &s) { - iso_8601_grammar iso_parser; - const bool result = qi::parse(s.begin(), s.end(), iso_parser); + util::iso_8601_grammar iso_parser; + const bool result = boost::spirit::qi::parse(s.begin(), s.end(), iso_parser); // check if the was an error with the request if (result && (0 != iso_parser.get_duration())) @@ -81,8 +86,8 @@ unsigned parseDuration(const std::string &s) } else if (iso_8601_duration_is_valid(s)) { - iso_8601_grammar iso_parser; - qi::parse(s.begin(), s.end(), iso_parser); + util::iso_8601_grammar iso_parser; + boost::spirit::qi::parse(s.begin(), s.end(), iso_parser); return iso_parser.get_duration(); } @@ -90,4 +95,7 @@ unsigned parseDuration(const std::string &s) return std::numeric_limits::max(); } +} +} + #endif // EXTRACTION_HELPER_FUNCTIONS_HPP diff --git a/include/extractor/extraction_node.hpp b/include/extractor/extraction_node.hpp index 46044eaf3..82826e717 100644 --- a/include/extractor/extraction_node.hpp +++ b/include/extractor/extraction_node.hpp @@ -1,6 +1,11 @@ #ifndef EXTRACTION_NODE_HPP #define EXTRACTION_NODE_HPP +namespace osrm +{ +namespace extractor +{ + struct ExtractionNode { ExtractionNode() : traffic_lights(false), barrier(false) {} @@ -8,4 +13,8 @@ struct ExtractionNode bool traffic_lights; bool barrier; }; + +} +} + #endif // EXTRACTION_NODE_HPP diff --git a/include/extractor/extraction_way.hpp b/include/extractor/extraction_way.hpp index 300518110..f54b5fe77 100644 --- a/include/extractor/extraction_way.hpp +++ b/include/extractor/extraction_way.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + /** * This struct is the direct result of the call to ```way_function``` * in the lua based profile. @@ -99,4 +104,7 @@ struct ExtractionWay TravelMode backward_travel_mode : 4; }; +} +} + #endif // EXTRACTION_WAY_HPP diff --git a/include/extractor/extractor.hpp b/include/extractor/extractor.hpp index d7c49d656..c9faca9d5 100644 --- a/include/extractor/extractor.hpp +++ b/include/extractor/extractor.hpp @@ -5,6 +5,11 @@ #include "extractor/edge_based_graph_factory.hpp" #include "extractor/graph_compressor.hpp" +namespace osrm +{ +namespace extractor +{ + class extractor { public: @@ -18,22 +23,25 @@ class extractor BuildEdgeExpandedGraph(std::vector &internal_to_external_node_map, std::vector &node_based_edge_list, std::vector &node_is_startpoint, - DeallocatingVector &edge_based_edge_list); + util::DeallocatingVector &edge_based_edge_list); void WriteNodeMapping(const std::vector &internal_to_external_node_map); void FindComponents(unsigned max_edge_id, - const DeallocatingVector &edges, + const util::DeallocatingVector &edges, std::vector &nodes) const; void BuildRTree(std::vector node_based_edge_list, std::vector node_is_startpoint, const std::vector &internal_to_external_node_map); std::shared_ptr LoadRestrictionMap(); - std::shared_ptr + std::shared_ptr LoadNodeBasedGraph(std::unordered_set &barrier_nodes, std::unordered_set &traffic_lights, std::vector &internal_to_external_node_map); void WriteEdgeBasedGraph(std::string const &output_file_filename, size_t const max_edge_id, - DeallocatingVector const &edge_based_edge_list); + util::DeallocatingVector const &edge_based_edge_list); }; +} +} + #endif /* EXTRACTOR_HPP */ diff --git a/include/extractor/extractor_callbacks.hpp b/include/extractor/extractor_callbacks.hpp index 38fe76ec3..a862f936c 100644 --- a/include/extractor/extractor_callbacks.hpp +++ b/include/extractor/extractor_callbacks.hpp @@ -7,17 +7,22 @@ #include #include -struct ExternalMemoryNode; -class ExtractionContainers; -struct InputRestrictionContainer; -struct ExtractionNode; -struct ExtractionWay; namespace osmium { class Node; class Way; } +namespace osrm +{ +namespace extractor +{ + +class ExtractionContainers; +struct InputRestrictionContainer; +struct ExtractionNode; +struct ExtractionWay; + /** * This class is uses by the extractor with the results of the * osmium based parsing and the customization through the lua profile. @@ -47,4 +52,7 @@ class ExtractorCallbacks void ProcessWay(const osmium::Way ¤t_way, const ExtractionWay &result_way); }; +} +} + #endif /* EXTRACTOR_CALLBACKS_HPP */ diff --git a/include/extractor/extractor_options.hpp b/include/extractor/extractor_options.hpp index 16593a0e9..05949f52f 100644 --- a/include/extractor/extractor_options.hpp +++ b/include/extractor/extractor_options.hpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace extractor +{ + enum class return_code : unsigned { ok, @@ -48,4 +53,7 @@ struct ExtractorOptions static void GenerateOutputFilesNames(ExtractorConfig &extractor_config); }; +} +} + #endif // EXTRACTOR_OPTIONS_HPP diff --git a/include/extractor/first_and_last_segment_of_way.hpp b/include/extractor/first_and_last_segment_of_way.hpp index fa5b5b65c..d4ea8e457 100644 --- a/include/extractor/first_and_last_segment_of_way.hpp +++ b/include/extractor/first_and_last_segment_of_way.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + struct FirstAndLastSegmentOfWay { OSMWayID way_id; @@ -49,4 +54,7 @@ struct FirstAndLastSegmentOfWayStxxlCompare value_type min_value() { return FirstAndLastSegmentOfWay::min_value(); } }; +} +} + #endif /* FIRST_AND_LAST_SEGMENT_OF_WAY_HPP */ diff --git a/include/extractor/graph_compressor.hpp b/include/extractor/graph_compressor.hpp index 7b9cd5a73..56496aefd 100644 --- a/include/extractor/graph_compressor.hpp +++ b/include/extractor/graph_compressor.hpp @@ -9,12 +9,17 @@ #include #include +namespace osrm +{ +namespace extractor +{ + class CompressedEdgeContainer; class RestrictionMap; class GraphCompressor { - using EdgeData = NodeBasedDynamicGraph::EdgeData; + using EdgeData = util::NodeBasedDynamicGraph::EdgeData; public: GraphCompressor(SpeedProfileProperties speed_profile); @@ -22,15 +27,18 @@ class GraphCompressor void Compress(const std::unordered_set &barrier_nodes, const std::unordered_set &traffic_lights, RestrictionMap &restriction_map, - NodeBasedDynamicGraph &graph, + util::NodeBasedDynamicGraph &graph, CompressedEdgeContainer &geometry_compressor); private: void PrintStatistics(unsigned original_number_of_nodes, unsigned original_number_of_edges, - const NodeBasedDynamicGraph &graph) const; + const util::NodeBasedDynamicGraph &graph) const; SpeedProfileProperties speed_profile; }; +} +} + #endif diff --git a/include/extractor/import_edge.hpp b/include/extractor/import_edge.hpp index 9fe4a8b50..095c9f95a 100644 --- a/include/extractor/import_edge.hpp +++ b/include/extractor/import_edge.hpp @@ -4,6 +4,11 @@ #include "extractor/travel_mode.hpp" #include "util/typedefs.hpp" +namespace osrm +{ +namespace extractor +{ + struct NodeBasedEdge { bool operator<(const NodeBasedEdge &e) const; @@ -90,4 +95,7 @@ struct EdgeBasedEdge bool backward : 1; }; +} +} + #endif /* IMPORT_EDGE_HPP */ diff --git a/include/extractor/internal_extractor_edge.hpp b/include/extractor/internal_extractor_edge.hpp index b5c8e031a..2d3447fda 100644 --- a/include/extractor/internal_extractor_edge.hpp +++ b/include/extractor/internal_extractor_edge.hpp @@ -10,6 +10,11 @@ #include "osrm/coordinate.hpp" #include +namespace osrm +{ +namespace extractor +{ + struct InternalExtractorEdge { // specify the type of the weight data @@ -80,7 +85,7 @@ struct InternalExtractorEdge // intermediate edge weight WeightData weight_data; // coordinate of the source node - FixedPointCoordinate source_coordinate; + util::FixedPointCoordinate source_coordinate; // necessary static util functions for stxxl's sorting static InternalExtractorEdge min_osm_value() @@ -148,4 +153,7 @@ struct CmpEdgeByOSMTargetID value_type min_value() { return InternalExtractorEdge::min_osm_value(); } }; +} +} + #endif // INTERNAL_EXTRACTOR_EDGE_HPP diff --git a/include/extractor/node_id.hpp b/include/extractor/node_id.hpp index 27de18a67..f27fd656c 100644 --- a/include/extractor/node_id.hpp +++ b/include/extractor/node_id.hpp @@ -3,6 +3,11 @@ #include "util/typedefs.hpp" +namespace osrm +{ +namespace extractor +{ + struct Cmp { using value_type = OSMNodeID; @@ -11,4 +16,7 @@ struct Cmp value_type min_value() { return MIN_OSM_NODEID; } }; +} +} + #endif // NODE_ID_HPP diff --git a/include/extractor/original_edge_data.hpp b/include/extractor/original_edge_data.hpp index 77a3bb550..dd9273bb9 100644 --- a/include/extractor/original_edge_data.hpp +++ b/include/extractor/original_edge_data.hpp @@ -7,6 +7,11 @@ #include +namespace osrm +{ +namespace extractor +{ + struct OriginalEdgeData { explicit OriginalEdgeData(NodeID via_node, @@ -33,4 +38,7 @@ struct OriginalEdgeData TravelMode travel_mode; }; +} +} + #endif // ORIGINAL_EDGE_DATA_HPP diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index b32d92d64..512aeaca3 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -9,6 +9,11 @@ #include +namespace osrm +{ +namespace extractor +{ + struct QueryNode { using key_type = OSMNodeID; // type of NodeID @@ -55,4 +60,7 @@ struct QueryNode } }; +} +} + #endif // QUERY_NODE_HPP diff --git a/include/extractor/raster_source.hpp b/include/extractor/raster_source.hpp index f04574cc9..a4707253c 100644 --- a/include/extractor/raster_source.hpp +++ b/include/extractor/raster_source.hpp @@ -13,6 +13,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + /** \brief Small wrapper around raster source queries to optionally provide results gracefully, depending on source bounds @@ -40,7 +45,7 @@ class RasterGrid boost::filesystem::ifstream stream(filepath); if (!stream) { - throw osrm::exception("Unable to open raster file."); + throw util::exception("Unable to open raster file."); } stream.seekg(0, std::ios_base::end); @@ -65,13 +70,13 @@ class RasterGrid } catch (std::exception const &ex) { - throw osrm::exception( + throw util::exception( std::string("Failed to read from raster source with exception: ") + ex.what()); } if (!r || itr != end) { - throw osrm::exception("Failed to parse raster source correctly."); + throw util::exception("Failed to parse raster source correctly."); } } @@ -145,4 +150,7 @@ class SourceContainer std::unordered_map LoadedSourcePaths; }; +} +} + #endif /* RASTER_SOURCE_HPP */ diff --git a/include/extractor/restriction.hpp b/include/extractor/restriction.hpp index 5b22691dd..690d92b2b 100644 --- a/include/extractor/restriction.hpp +++ b/include/extractor/restriction.hpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace extractor +{ + struct TurnRestriction { union WayOrNode @@ -104,4 +109,7 @@ struct CmpRestrictionContainerByTo value_type min_value() const { return InputRestrictionContainer::min_value(); } }; +} +} + #endif // RESTRICTION_HPP diff --git a/include/extractor/restriction_map.hpp b/include/extractor/restriction_map.hpp index 81c9d425a..e5a6a12ba 100644 --- a/include/extractor/restriction_map.hpp +++ b/include/extractor/restriction_map.hpp @@ -12,6 +12,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + struct RestrictionSource { NodeID start_node; @@ -37,26 +42,33 @@ struct RestrictionTarget return (lhs.target_node == rhs.target_node && lhs.is_only == rhs.is_only); } }; +} +} namespace std { -template <> struct hash +template <> struct hash { - size_t operator()(const RestrictionSource &r_source) const + size_t operator()(const osrm::extractor::RestrictionSource &r_source) const { return hash_val(r_source.start_node, r_source.via_node); } }; -template <> struct hash +template <> struct hash { - size_t operator()(const RestrictionTarget &r_target) const + size_t operator()(const osrm::extractor::RestrictionTarget &r_target) const { return hash_val(r_target.target_node, r_target.is_only); } }; } + +namespace osrm +{ +namespace extractor +{ /** \brief Efficent look up if an edge is the start + via node of a TurnRestriction EdgeBasedEdgeFactory decides by it if edges are inserted or geometry is compressed @@ -146,4 +158,7 @@ class RestrictionMap std::unordered_set m_no_turn_via_node_set; }; +} +} + #endif // RESTRICTION_MAP_HPP diff --git a/include/extractor/restriction_parser.hpp b/include/extractor/restriction_parser.hpp index ee73f57ce..2bbad8268 100644 --- a/include/extractor/restriction_parser.hpp +++ b/include/extractor/restriction_parser.hpp @@ -14,6 +14,12 @@ namespace osmium class Relation; } + +namespace osrm +{ +namespace extractor +{ + /** * Parses the relations that represents turn restrictions. * @@ -47,4 +53,7 @@ class RestrictionParser bool use_turn_restrictions; }; +} +} + #endif /* RESTRICTION_PARSER_HPP */ diff --git a/include/extractor/scripting_environment.hpp b/include/extractor/scripting_environment.hpp index 3b1ff785a..0f1342b62 100644 --- a/include/extractor/scripting_environment.hpp +++ b/include/extractor/scripting_environment.hpp @@ -8,6 +8,11 @@ struct lua_State; +namespace osrm +{ +namespace extractor +{ + /** * Creates a lua context and binds osmium way, node and relation objects and * ExtractionWay and ExtractionNode to lua objects. @@ -30,4 +35,7 @@ class ScriptingEnvironment tbb::enumerable_thread_specific> script_contexts; }; +} +} + #endif /* SCRIPTING_ENVIRONMENT_HPP */ diff --git a/include/extractor/speed_profile.hpp b/include/extractor/speed_profile.hpp index ec8ecd6d4..65c4141b5 100644 --- a/include/extractor/speed_profile.hpp +++ b/include/extractor/speed_profile.hpp @@ -1,6 +1,11 @@ #ifndef SPEED_PROFILE_PROPERTIES_HPP #define SPEED_PROFILE_PROPERTIES_HPP +namespace osrm +{ +namespace extractor +{ + struct SpeedProfileProperties { SpeedProfileProperties() @@ -13,4 +18,7 @@ struct SpeedProfileProperties bool has_turn_penalty_function; }; +} +} + #endif diff --git a/include/extractor/tarjan_scc.hpp b/include/extractor/tarjan_scc.hpp index e29d0fad8..a8b8eb6ba 100644 --- a/include/extractor/tarjan_scc.hpp +++ b/include/extractor/tarjan_scc.hpp @@ -22,6 +22,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + template class TarjanSCC { struct TarjanStackFrame @@ -66,7 +71,7 @@ template class TarjanSCC unsigned component_index = 0, size_of_current_component = 0; unsigned index = 0; std::vector processing_node_before_recursion(max_node_id, true); - for (const NodeID node : osrm::irange(0u, max_node_id)) + for (const NodeID node : util::irange(0u, max_node_id)) { if (SPECIAL_NODEID == components_index[node]) { @@ -141,7 +146,7 @@ template class TarjanSCC if (size_of_current_component > 1000) { - SimpleLogger().Write() << "large component [" << component_index + util::SimpleLogger().Write() << "large component [" << component_index << "]=" << size_of_current_component; } @@ -153,7 +158,7 @@ template class TarjanSCC } TIMER_STOP(SCC_RUN); - SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN) / 1000. << "s"; + util::SimpleLogger().Write() << "SCC run took: " << TIMER_MSEC(SCC_RUN) / 1000. << "s"; size_one_counter = std::count_if(component_size_vector.begin(), component_size_vector.end(), [](unsigned value) @@ -174,4 +179,7 @@ template class TarjanSCC unsigned get_component_id(const NodeID node) const { return components_index[node]; } }; +} +} + #endif /* TARJAN_SCC_HPP */ diff --git a/include/extractor/travel_mode.hpp b/include/extractor/travel_mode.hpp index 66a84bbde..62fc03b92 100644 --- a/include/extractor/travel_mode.hpp +++ b/include/extractor/travel_mode.hpp @@ -1,10 +1,18 @@ #ifndef TRAVEL_MODE_HPP #define TRAVEL_MODE_HPP -namespace +namespace osrm { +namespace extractor +{ + using TravelMode = unsigned char; -static const TravelMode TRAVEL_MODE_INACCESSIBLE = 0; -static const TravelMode TRAVEL_MODE_DEFAULT = 1; + +} +} + +namespace { +static const osrm::extractor::TravelMode TRAVEL_MODE_INACCESSIBLE = 0; +static const osrm::extractor::TravelMode TRAVEL_MODE_DEFAULT = 1; } #endif /* TRAVEL_MODE_HPP */ diff --git a/include/extractor/turn_instructions.hpp b/include/extractor/turn_instructions.hpp index 2075d2c9c..ca3623504 100644 --- a/include/extractor/turn_instructions.hpp +++ b/include/extractor/turn_instructions.hpp @@ -1,6 +1,11 @@ #ifndef TURN_INSTRUCTIONS_HPP #define TURN_INSTRUCTIONS_HPP +namespace osrm +{ +namespace extractor +{ + enum class TurnInstruction : unsigned char { NoTurn = 0, @@ -75,4 +80,7 @@ struct TurnInstructionsClass } }; +} +} + #endif /* TURN_INSTRUCTIONS_HPP */ diff --git a/include/osrm/coordinate.hpp b/include/osrm/coordinate.hpp index 2ff3705ae..b36d57ca6 100644 --- a/include/osrm/coordinate.hpp +++ b/include/osrm/coordinate.hpp @@ -32,10 +32,13 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -namespace +namespace osrm { + constexpr static const double COORDINATE_PRECISION = 1000000.0; -} + +namespace util +{ struct FixedPointCoordinate { @@ -61,5 +64,10 @@ struct FixedPointCoordinate }; std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate); +} + +using util::FixedPointCoordinate; + +} #endif /* COORDINATE_HPP_ */ diff --git a/include/osrm/json_container.hpp b/include/osrm/json_container.hpp index d8c49b223..7c8377d32 100644 --- a/include/osrm/json_container.hpp +++ b/include/osrm/json_container.hpp @@ -40,6 +40,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace osrm { + +namespace util +{ + namespace json { @@ -92,5 +96,12 @@ struct Array }; } // namespace JSON +} // namespace util + +namespace json { + using namespace osrm::util::json; +} + } // namespace osrm + #endif // JSON_CONTAINER_HPP diff --git a/include/osrm/libosrm_config.hpp b/include/osrm/libosrm_config.hpp index bc150077d..4606e6003 100644 --- a/include/osrm/libosrm_config.hpp +++ b/include/osrm/libosrm_config.hpp @@ -33,6 +33,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +namespace osrm +{ + struct LibOSRMConfig { std::unordered_map server_paths; @@ -43,4 +46,6 @@ struct LibOSRMConfig bool use_shared_memory = true; }; +} + #endif // SERVER_CONFIG_HPP diff --git a/include/osrm/osrm.hpp b/include/osrm/osrm.hpp index 892463d61..695403d73 100644 --- a/include/osrm/osrm.hpp +++ b/include/osrm/osrm.hpp @@ -30,17 +30,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -struct LibOSRMConfig; -struct RouteParameters; - namespace osrm { + +struct LibOSRMConfig; + +namespace util +{ namespace json { struct Object; } } +namespace engine { +struct RouteParameters; class OSRM { private: @@ -50,7 +54,12 @@ class OSRM public: OSRM(LibOSRMConfig &lib_config); ~OSRM(); // needed because we need to define it with the implementation of OSRM_impl - int RunQuery(const RouteParameters &route_parameters, osrm::json::Object &json_result); + int RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result); }; +} + +using engine::OSRM; + +} #endif // OSRM_HPP diff --git a/include/osrm/route_parameters.hpp b/include/osrm/route_parameters.hpp index 66b03ea65..f7bc2a261 100644 --- a/include/osrm/route_parameters.hpp +++ b/include/osrm/route_parameters.hpp @@ -36,6 +36,11 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +namespace osrm +{ +namespace engine +{ + struct RouteParameters { RouteParameters(); @@ -115,4 +120,10 @@ struct RouteParameters std::vector is_source; }; +} + +using engine::RouteParameters; + +} + #endif // ROUTE_PARAMETERS_HPP diff --git a/include/osrm/strong_typedef.hpp b/include/osrm/strong_typedef.hpp index 7acc78509..f4c80865e 100644 --- a/include/osrm/strong_typedef.hpp +++ b/include/osrm/strong_typedef.hpp @@ -31,6 +31,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include +namespace osrm +{ + /* Creates strongly typed wrappers around scalar types. * Useful for stopping accidental assignment of lats to lons, * etc. Also clarifies what this random "int" value is @@ -66,4 +69,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. }; \ } +} + #endif // OSRM_STRONG_TYPEDEF_HPP diff --git a/include/server/api_grammar.hpp b/include/server/api_grammar.hpp index f4d937c68..7a04d884b 100644 --- a/include/server/api_grammar.hpp +++ b/include/server/api_grammar.hpp @@ -5,6 +5,11 @@ #include #include +namespace osrm +{ +namespace server +{ + namespace qi = boost::spirit::qi; template struct APIGrammar : qi::grammar @@ -98,4 +103,7 @@ template struct APIGrammar : qi::grammar T *get_pointer(std::shared_ptr &p) { return p.get(); } #endif -class RequestHandler; - -namespace http +namespace osrm { +namespace server +{ + +class RequestHandler; /// Represents a single connection from a client. class Connection : public std::enable_shared_from_this @@ -51,18 +53,19 @@ class Connection : public std::enable_shared_from_this void handle_write(const boost::system::error_code &e); std::vector compress_buffers(const std::vector &uncompressed_data, - const compression_type compression_type); + const http::compression_type compression_type); boost::asio::io_service::strand strand; boost::asio::ip::tcp::socket TCP_socket; RequestHandler &request_handler; RequestParser request_parser; boost::array incoming_data_buffer; - request current_request; - reply current_reply; + http::request current_request; + http::reply current_reply; std::vector compressed_output; }; -} // namespace http +} +} #endif // CONNECTION_HPP diff --git a/include/server/http/compression_type.hpp b/include/server/http/compression_type.hpp index ef7e8d75b..2a71cfa54 100644 --- a/include/server/http/compression_type.hpp +++ b/include/server/http/compression_type.hpp @@ -1,6 +1,10 @@ #ifndef COMPRESSION_TYPE_HPP #define COMPRESSION_TYPE_HPP +namespace osrm +{ +namespace server +{ namespace http { @@ -10,6 +14,9 @@ enum compression_type gzip_rfc1952, deflate_rfc1951 }; + +} +} } #endif // COMPRESSION_TYPE_HPP diff --git a/include/server/http/header.hpp b/include/server/http/header.hpp index 256e0b187..da43412bb 100644 --- a/include/server/http/header.hpp +++ b/include/server/http/header.hpp @@ -4,8 +4,13 @@ #include #include +namespace osrm +{ +namespace server +{ namespace http { + struct header { // explicitly use default copy c'tor as adding move c'tor @@ -22,6 +27,9 @@ struct header std::string name; std::string value; }; + +} +} } #endif // HEADER_HPP diff --git a/include/server/http/reply.hpp b/include/server/http/reply.hpp index 64c6e67b7..15ca91a13 100644 --- a/include/server/http/reply.hpp +++ b/include/server/http/reply.hpp @@ -7,8 +7,13 @@ #include +namespace osrm +{ +namespace server +{ namespace http { + class reply { public: @@ -33,6 +38,9 @@ class reply std::string status_to_string(reply::status_type status); boost::asio::const_buffer status_to_buffer(reply::status_type status); }; + +} +} } #endif // REPLY_HPP diff --git a/include/server/http/request.hpp b/include/server/http/request.hpp index 8b1a00df1..0e6fb7d59 100644 --- a/include/server/http/request.hpp +++ b/include/server/http/request.hpp @@ -5,6 +5,10 @@ #include +namespace osrm +{ +namespace server +{ namespace http { @@ -16,6 +20,8 @@ struct request boost::asio::ip::address endpoint; }; -} // namespace http +} +} +} #endif // REQUEST_HPP diff --git a/include/server/request_handler.hpp b/include/server/request_handler.hpp index 16a87acb0..66d2cd2b1 100644 --- a/include/server/request_handler.hpp +++ b/include/server/request_handler.hpp @@ -3,9 +3,16 @@ #include -template struct APIGrammar; -struct RouteParameters; +namespace osrm +{ +namespace engine +{ class OSRM; +struct RouteParameters; +} +namespace server +{ +template struct APIGrammar; namespace http { @@ -17,16 +24,19 @@ class RequestHandler { public: - using APIGrammarParser = APIGrammar; + using APIGrammarParser = APIGrammar; RequestHandler(); RequestHandler(const RequestHandler &) = delete; void handle_request(const http::request ¤t_request, http::reply ¤t_reply); - void RegisterRoutingMachine(OSRM *osrm); + void RegisterRoutingMachine(engine::OSRM *osrm); private: - OSRM *routing_machine; + engine::OSRM *routing_machine; }; +} +} + #endif // REQUEST_HANDLER_HPP diff --git a/include/server/request_parser.hpp b/include/server/request_parser.hpp index b498add0a..b4df13162 100644 --- a/include/server/request_parser.hpp +++ b/include/server/request_parser.hpp @@ -7,21 +7,27 @@ #include -namespace http +namespace osrm +{ +namespace server { +namespace http +{ struct request; +} + class RequestParser { public: RequestParser(); - std::tuple - parse(request ¤t_request, char *begin, char *end); + std::tuple + parse(http::request ¤t_request, char *begin, char *end); private: - osrm::tribool consume(request ¤t_request, const char input); + util::tribool consume(http::request ¤t_request, const char input); bool is_char(const int character) const; @@ -60,12 +66,13 @@ class RequestParser post_request } state; - header current_header; - compression_type selected_compression; + http::header current_header; + http::compression_type selected_compression; bool is_post_header; int content_length; }; -} // namespace http +} +} #endif // REQUEST_PARSER_HPP diff --git a/include/server/server.hpp b/include/server/server.hpp index f64a9f3bf..2d40a45b8 100644 --- a/include/server/server.hpp +++ b/include/server/server.hpp @@ -18,6 +18,11 @@ #include #include +namespace osrm +{ +namespace server +{ + class Server { public: @@ -25,7 +30,7 @@ class Server static std::shared_ptr CreateServer(std::string &ip_address, int ip_port, unsigned requested_num_threads) { - SimpleLogger().Write() << "http 1.1 compression handled by zlib version " << zlibVersion(); + util::SimpleLogger().Write() << "http 1.1 compression handled by zlib version " << zlibVersion(); const unsigned hardware_threads = std::max(1u, std::thread::hardware_concurrency()); const unsigned real_num_threads = std::min(hardware_threads, requested_num_threads); return std::make_shared(ip_address, ip_port, real_num_threads); @@ -33,7 +38,7 @@ class Server explicit Server(const std::string &address, const int port, const unsigned thread_pool_size) : thread_pool_size(thread_pool_size), acceptor(io_service), - new_connection(std::make_shared(io_service, request_handler)) + new_connection(std::make_shared(io_service, request_handler)) { const auto port_string = std::to_string(port); @@ -75,7 +80,7 @@ class Server if (!e) { new_connection->start(); - new_connection = std::make_shared(io_service, request_handler); + new_connection = std::make_shared(io_service, request_handler); acceptor.async_accept( new_connection->socket(), boost::bind(&Server::HandleAccept, this, boost::asio::placeholders::error)); @@ -85,8 +90,11 @@ class Server unsigned thread_pool_size; boost::asio::io_service io_service; boost::asio::ip::tcp::acceptor acceptor; - std::shared_ptr new_connection; + std::shared_ptr new_connection; RequestHandler request_handler; }; +} +} + #endif // SERVER_HPP diff --git a/include/util/bearing.hpp b/include/util/bearing.hpp index d881b300b..190e97a08 100644 --- a/include/util/bearing.hpp +++ b/include/util/bearing.hpp @@ -4,6 +4,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace bearing { inline std::string get(const double heading) @@ -86,4 +91,7 @@ inline bool CheckInBounds(const int A, const int B, const int range) } } +} +} + #endif // BEARING_HPP diff --git a/include/util/binary_heap.hpp b/include/util/binary_heap.hpp index 4b2ba07a2..c7d57505f 100644 --- a/include/util/binary_heap.hpp +++ b/include/util/binary_heap.hpp @@ -10,6 +10,11 @@ #include #include +namespace osrm +{ +namespace util +{ + template class ArrayStorage { public: @@ -286,4 +291,7 @@ class BinaryHeap } }; +} +} + #endif // BINARY_HEAP_H diff --git a/include/util/cast.hpp b/include/util/cast.hpp index 94862d2ba..479eaa2a4 100644 --- a/include/util/cast.hpp +++ b/include/util/cast.hpp @@ -9,6 +9,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace cast { template @@ -39,4 +44,7 @@ template inline std::string to_string_with_preci } } +} +} + #endif // CAST_HPP diff --git a/include/util/compute_angle.hpp b/include/util/compute_angle.hpp index 48300e4f4..40f820d9e 100644 --- a/include/util/compute_angle.hpp +++ b/include/util/compute_angle.hpp @@ -1,6 +1,11 @@ #ifndef COMPUTE_ANGLE_HPP #define COMPUTE_ANGLE_HPP +namespace osrm +{ +namespace util +{ + struct FixedPointCoordinate; struct ComputeAngle @@ -12,4 +17,7 @@ struct ComputeAngle const FixedPointCoordinate &third) noexcept; }; +} +} + #endif // COMPUTE_ANGLE_HPP diff --git a/include/util/container.hpp b/include/util/container.hpp index fab0c2263..e901af90d 100644 --- a/include/util/container.hpp +++ b/include/util/container.hpp @@ -7,6 +7,9 @@ namespace osrm { +namespace util +{ + namespace detail { // Culled by SFINAE if reserve does not exist or is not accessible @@ -81,4 +84,6 @@ void append_to_container(Container &&container, T value, Args &&... args) } } // namespace osrm +} + #endif /* CONTAINER_HPP */ diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index 7faabdbc6..96548481b 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -1,11 +1,16 @@ #ifndef COORDINATE_CALCULATION #define COORDINATE_CALCULATION -struct FixedPointCoordinate; - #include #include +namespace osrm +{ +namespace util +{ + +struct FixedPointCoordinate; + namespace coordinate_calculation { double haversineDistance(const int lat1, const int lon1, const int lat2, const int lon2); @@ -49,4 +54,7 @@ double bearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); } +} +} + #endif // COORDINATE_CALCULATION diff --git a/include/util/datastore_options.hpp b/include/util/datastore_options.hpp index 8426fa13b..b467bb836 100644 --- a/include/util/datastore_options.hpp +++ b/include/util/datastore_options.hpp @@ -13,6 +13,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // generate boost::program_options object for the routing part bool GenerateDataStoreOptions(const int argc, const char *argv[], @@ -199,59 +204,62 @@ bool GenerateDataStoreOptions(const int argc, if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .hsgr file must be specified"); + throw exception("valid .hsgr file must be specified"); } path_iterator = paths.find("nodesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .nodes file must be specified"); + throw exception("valid .nodes file must be specified"); } path_iterator = paths.find("edgesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .edges file must be specified"); + throw exception("valid .edges file must be specified"); } path_iterator = paths.find("geometry"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .geometry file must be specified"); + throw exception("valid .geometry file must be specified"); } path_iterator = paths.find("ramindex"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .ramindex file must be specified"); + throw exception("valid .ramindex file must be specified"); } path_iterator = paths.find("fileindex"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .fileindex file must be specified"); + throw exception("valid .fileindex file must be specified"); } path_iterator = paths.find("namesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .names file must be specified"); + throw exception("valid .names file must be specified"); } path_iterator = paths.find("timestamp"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception("valid .timestamp file must be specified"); + throw exception("valid .timestamp file must be specified"); } return true; } +} +} + #endif /* DATASTORE_OPTIONS_HPP */ diff --git a/include/util/deallocating_vector.hpp b/include/util/deallocating_vector.hpp index a486db371..aa9ec3ea2 100644 --- a/include/util/deallocating_vector.hpp +++ b/include/util/deallocating_vector.hpp @@ -9,6 +9,11 @@ #include #include +namespace osrm +{ +namespace util +{ + template struct ConstDeallocatingVectorIteratorState { ConstDeallocatingVectorIteratorState() @@ -302,7 +307,7 @@ class DeallocatingVector { // down-size const std::size_t number_of_necessary_buckets = 1 + (new_size / ELEMENTS_PER_BLOCK); for (const auto bucket_index : - osrm::irange(number_of_necessary_buckets, bucket_list.size())) + irange(number_of_necessary_buckets, bucket_list.size())) { if (nullptr != bucket_list[bucket_index]) { @@ -374,4 +379,7 @@ void swap(DeallocatingVector &lhs, DeallocatingVector &rhs) lhs.swap(rhs); } +} +} + #endif /* DEALLOCATING_VECTOR_HPP */ diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index d4cd06871..b06ed3dc6 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -6,7 +6,12 @@ #ifndef DEBUG_GEOMETRY -inline void DEBUG_GEOMETRY_START(ContractorConfig & /* config */) {} +namespace osrm +{ +namespace util +{ + +inline void DEBUG_GEOMETRY_START(const contractor::ContractorConfig & /* config */) {} inline void DEBUG_GEOMETRY_EDGE(int /* new_segment_weight */, double /* segment_length */, OSMNodeID /* previous_osm_node_id */, @@ -17,25 +22,28 @@ inline void DEBUG_GEOMETRY_STOP() {} inline void DEBUG_TURNS_START(const std::string & /* debug_turns_filename */) {} inline void DEBUG_TURN(const NodeID /* node */, - const std::vector & /* m_node_info_list */, + const std::vector & /* m_node_info_list */, const FixedPointCoordinate & /* first_coordinate */, const int /* turn_angle */, const int /* turn_penalty */) { } inline void DEBUG_UTURN(const NodeID /* node */, - const std::vector & /* m_node_info_list */, + const std::vector & /* m_node_info_list */, const int /* uturn_penalty */) { } inline void DEBUG_SIGNAL(const NodeID /* node */, - const std::vector & /* m_node_info_list */, + const std::vector & /* m_node_info_list */, const int /* signal_penalty */) { } inline void DEBUG_TURNS_STOP() {} +} +} + #else // DEBUG_GEOMETRY #include @@ -47,6 +55,12 @@ inline void DEBUG_TURNS_STOP() {} #include "util/coordinate.hpp" #include "util/coordinate_calculation.hpp" +namespace osrm +{ +namespace util +{ + + boost::filesystem::ofstream debug_geometry_file; bool dg_output_debug_geometry = false; bool dg_first_debug_geometry = true; @@ -56,7 +70,7 @@ boost::filesystem::ofstream dg_debug_turns_file; bool dg_output_turn_debug = false; bool dg_first_turn_debug = true; -inline void DEBUG_GEOMETRY_START(const ContractorConfig &config) +inline void DEBUG_GEOMETRY_START(const contractor::ContractorConfig &config) { time_t raw_time; struct tm *timeinfo; @@ -118,12 +132,12 @@ inline void DEBUG_TURNS_START(const std::string &debug_turns_path) } inline void DEBUG_SIGNAL(const NodeID node, - const std::vector &m_node_info_list, + const std::vector &m_node_info_list, const int traffic_signal_penalty) { if (dg_output_turn_debug) { - const QueryNode &nodeinfo = m_node_info_list[node]; + const extractor::QueryNode &nodeinfo = m_node_info_list[node]; if (!dg_first_turn_debug) dg_debug_turns_file << "," << std::endl; dg_debug_turns_file @@ -137,12 +151,12 @@ inline void DEBUG_SIGNAL(const NodeID node, } inline void DEBUG_UTURN(const NodeID node, - const std::vector &m_node_info_list, + const std::vector &m_node_info_list, const int traffic_signal_penalty) { if (dg_output_turn_debug) { - const QueryNode &nodeinfo = m_node_info_list[node]; + const extractor::QueryNode &nodeinfo = m_node_info_list[node]; if (!dg_first_turn_debug) dg_debug_turns_file << "," << std::endl; dg_debug_turns_file @@ -156,14 +170,14 @@ inline void DEBUG_UTURN(const NodeID node, } inline void DEBUG_TURN(const NodeID node, - const std::vector &m_node_info_list, + const std::vector &m_node_info_list, const FixedPointCoordinate &first_coordinate, const int turn_angle, const int turn_penalty) { if (turn_penalty > 0 && dg_output_turn_debug) { - const QueryNode &v = m_node_info_list[node]; + const extractor::QueryNode &v = m_node_info_list[node]; const float bearing_uv = coordinate_calculation::bearing(first_coordinate, v); float uvw_normal = bearing_uv + turn_angle / 2; @@ -194,6 +208,9 @@ inline void DEBUG_TURNS_STOP() } } +} +} + #endif // DEBUG_GEOMETRY #endif // DEBUG_GEOMETRY_H diff --git a/include/util/dist_table_wrapper.hpp b/include/util/dist_table_wrapper.hpp index 516131393..3e23ce2ac 100644 --- a/include/util/dist_table_wrapper.hpp +++ b/include/util/dist_table_wrapper.hpp @@ -6,6 +6,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // This Wrapper provides an easier access to a distance table that is given as an linear vector template class DistTableWrapper @@ -58,4 +63,7 @@ template class DistTableWrapper const std::size_t number_of_nodes_; }; +} +} + #endif // DIST_TABLE_WRAPPER_H diff --git a/include/util/dynamic_graph.hpp b/include/util/dynamic_graph.hpp index 4dd2f0022..c4219cf28 100644 --- a/include/util/dynamic_graph.hpp +++ b/include/util/dynamic_graph.hpp @@ -15,13 +15,18 @@ #include #include +namespace osrm +{ +namespace util +{ + template class DynamicGraph { public: using EdgeData = EdgeDataT; using NodeIterator = unsigned; using EdgeIterator = unsigned; - using EdgeRange = osrm::range; + using EdgeRange = range; class InputEdge { @@ -72,7 +77,7 @@ template class DynamicGraph node_array.resize(number_of_nodes + 1); EdgeIterator edge = 0; EdgeIterator position = 0; - for (const auto node : osrm::irange(0u, number_of_nodes)) + for (const auto node : irange(0u, number_of_nodes)) { EdgeIterator last_edge = edge; while (edge < number_of_edges && graph[edge].source == node) @@ -87,9 +92,9 @@ template class DynamicGraph edge_list.reserve(static_cast(edge_list.size() * 1.1)); edge_list.resize(position); edge = 0; - for (const auto node : osrm::irange(0u, number_of_nodes)) + for (const auto node : irange(0u, number_of_nodes)) { - for (const auto i : osrm::irange(node_array[node].first_edge, + for (const auto i : irange(node_array[node].first_edge, node_array[node].first_edge + node_array[node].edges)) { edge_list[i].target = graph[edge].target; @@ -111,7 +116,7 @@ template class DynamicGraph unsigned GetDirectedOutDegree(const NodeIterator n) const { unsigned degree = 0; - for (const auto edge : osrm::irange(BeginEdges(n), EndEdges(n))) + for (const auto edge : irange(BeginEdges(n), EndEdges(n))) { if (!GetEdgeData(edge).reversed) { @@ -141,7 +146,7 @@ template class DynamicGraph EdgeRange GetAdjacentEdgeRange(const NodeIterator node) const { - return osrm::irange(BeginEdges(node), EndEdges(node)); + return irange(BeginEdges(node), EndEdges(node)); } NodeIterator InsertNode() @@ -175,12 +180,12 @@ template class DynamicGraph edge_list.reserve(requiredCapacity * 1.1); } edge_list.resize(edge_list.size() + newSize); - for (const auto i : osrm::irange(0u, node.edges)) + for (const auto i : irange(0u, node.edges)) { edge_list[newFirstEdge + i] = edge_list[node.first_edge + i]; makeDummy(node.first_edge + i); } - for (const auto i : osrm::irange(node.edges + 1, newSize)) + for (const auto i : irange(node.edges + 1, newSize)) { makeDummy(newFirstEdge + i); } @@ -235,7 +240,7 @@ template class DynamicGraph // searches for a specific edge EdgeIterator FindEdge(const NodeIterator from, const NodeIterator to) const { - for (const auto i : osrm::irange(BeginEdges(from), EndEdges(from))) + for (const auto i : irange(BeginEdges(from), EndEdges(from))) { if (to == edge_list[i].target) { @@ -316,4 +321,7 @@ template class DynamicGraph DeallocatingVector edge_list; }; +} +} + #endif // DYNAMICGRAPH_HPP diff --git a/include/util/fingerprint.hpp b/include/util/fingerprint.hpp index bb58fe697..14b869871 100644 --- a/include/util/fingerprint.hpp +++ b/include/util/fingerprint.hpp @@ -4,6 +4,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // implements a singleton, i.e. there is one and only one conviguration object class FingerPrint { @@ -29,4 +34,7 @@ class FingerPrint static_assert(std::is_trivial::value, "FingerPrint needs to be trivial."); +} +} + #endif /* FingerPrint_H */ diff --git a/include/util/fingerprint_impl.hpp.in b/include/util/fingerprint_impl.hpp.in index 85fcebdb0..f391e4ca2 100644 --- a/include/util/fingerprint_impl.hpp.in +++ b/include/util/fingerprint_impl.hpp.in @@ -13,6 +13,11 @@ #cmakedefine MD5GRAPH "${MD5GRAPH}" #cmakedefine MD5OBJECTS "${MD5OBJECTS}" +namespace osrm +{ +namespace util +{ + FingerPrint FingerPrint::GetValid() { FingerPrint fingerprint; @@ -52,7 +57,7 @@ bool FingerPrint::TestGraphUtil(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { - throw osrm::exception("hsgr input file misses magic number. Check or reprocess the file"); + throw exception("hsgr input file misses magic number. Check or reprocess the file"); } return std::equal(md5_graph, md5_graph + 32, other.md5_graph); } @@ -61,7 +66,7 @@ bool FingerPrint::TestPrepare(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { - throw osrm::exception("osrm input file misses magic number. Check or reprocess the file"); + throw exception("osrm input file misses magic number. Check or reprocess the file"); } return std::equal(md5_prepare, md5_prepare + 32, other.md5_prepare); } @@ -70,7 +75,7 @@ bool FingerPrint::TestRTree(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { - throw osrm::exception("r-tree input file misses magic number. Check or reprocess the file"); + throw exception("r-tree input file misses magic number. Check or reprocess the file"); } return std::equal(md5_tree, md5_tree + 32, other.md5_tree); } @@ -79,7 +84,10 @@ bool FingerPrint::TestQueryObjects(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { - throw osrm::exception("missing magic number. Check or reprocess the file"); + throw exception("missing magic number. Check or reprocess the file"); } return std::equal(md5_objects, md5_objects + 32, other.md5_objects); } + +} +} diff --git a/include/util/fixed_point_number.hpp b/include/util/fixed_point_number.hpp index 0ff409fc8..ba4b111db 100644 --- a/include/util/fixed_point_number.hpp +++ b/include/util/fixed_point_number.hpp @@ -11,6 +11,8 @@ namespace osrm { +namespace util +{ // implements an binary based fixed point number type template ), "FP19 has wrong size != 4"); + } +} + #endif // FIXED_POINT_NUMBER_HPP diff --git a/include/util/floating_point.hpp b/include/util/floating_point.hpp index 79ec495bd..e7963e630 100644 --- a/include/util/floating_point.hpp +++ b/include/util/floating_point.hpp @@ -8,11 +8,16 @@ namespace osrm { +namespace util +{ + template bool epsilon_compare(const FloatT number1, const FloatT number2) { static_assert(std::is_floating_point::value, "type must be floating point"); return (std::abs(number1 - number2) < std::numeric_limits::epsilon()); } + +} } #endif // FLOATING_POINT_HPP diff --git a/include/util/graph_loader.hpp b/include/util/graph_loader.hpp index c64048ede..6ff030b5a 100644 --- a/include/util/graph_loader.hpp +++ b/include/util/graph_loader.hpp @@ -22,13 +22,18 @@ #include #include +namespace osrm +{ +namespace util +{ + /** * Reads the .restrictions file and loads it to a vector. * The since the restrictions reference nodes using their external node id, * we need to renumber it to the new internal id. */ unsigned loadRestrictionsFromFile(std::istream &input_stream, - std::vector &restriction_list) + std::vector &restriction_list) { const FingerPrint fingerprint_valid = FingerPrint::GetValid(); FingerPrint fingerprint_loaded; @@ -45,7 +50,7 @@ unsigned loadRestrictionsFromFile(std::istream &input_stream, if (number_of_usable_restrictions > 0) { input_stream.read((char *)restriction_list.data(), - number_of_usable_restrictions * sizeof(TurnRestriction)); + number_of_usable_restrictions * sizeof(extractor::TurnRestriction)); } return number_of_usable_restrictions; @@ -60,7 +65,7 @@ unsigned loadRestrictionsFromFile(std::istream &input_stream, NodeID loadNodesFromFile(std::istream &input_stream, std::vector &barrier_node_list, std::vector &traffic_light_node_list, - std::vector &node_array) + std::vector &node_array) { const FingerPrint fingerprint_valid = FingerPrint::GetValid(); FingerPrint fingerprint_loaded; @@ -76,10 +81,10 @@ NodeID loadNodesFromFile(std::istream &input_stream, input_stream.read(reinterpret_cast(&n), sizeof(NodeID)); SimpleLogger().Write() << "Importing n = " << n << " nodes "; - ExternalMemoryNode current_node; + extractor::ExternalMemoryNode current_node; for (NodeID i = 0; i < n; ++i) { - input_stream.read(reinterpret_cast(¤t_node), sizeof(ExternalMemoryNode)); + input_stream.read(reinterpret_cast(¤t_node), sizeof(extractor::ExternalMemoryNode)); node_array.emplace_back(current_node.lat, current_node.lon, current_node.node_id); if (current_node.barrier) { @@ -101,21 +106,21 @@ NodeID loadNodesFromFile(std::istream &input_stream, /** * Reads a .osrm file and produces the edges. */ -NodeID loadEdgesFromFile(std::istream &input_stream, std::vector &edge_list) +NodeID loadEdgesFromFile(std::istream &input_stream, std::vector &edge_list) { EdgeID m; input_stream.read(reinterpret_cast(&m), sizeof(unsigned)); edge_list.resize(m); SimpleLogger().Write() << " and " << m << " edges "; - input_stream.read((char *)edge_list.data(), m * sizeof(NodeBasedEdge)); + input_stream.read((char *)edge_list.data(), m * sizeof(extractor::NodeBasedEdge)); BOOST_ASSERT(edge_list.size() > 0); #ifndef NDEBUG SimpleLogger().Write() << "Validating loaded edges..."; tbb::parallel_sort(edge_list.begin(), edge_list.end(), - [](const NodeBasedEdge &lhs, const NodeBasedEdge &rhs) + [](const extractor::NodeBasedEdge &lhs, const extractor::NodeBasedEdge &rhs) { return (lhs.source < rhs.source) || (lhs.source == rhs.source && lhs.target < rhs.target); @@ -148,11 +153,11 @@ unsigned readHSGRFromStream(const boost::filesystem::path &hsgr_file, { if (!boost::filesystem::exists(hsgr_file)) { - throw osrm::exception("hsgr file does not exist"); + throw exception("hsgr file does not exist"); } if (0 == boost::filesystem::file_size(hsgr_file)) { - throw osrm::exception("hsgr file is empty"); + throw exception("hsgr file is empty"); } boost::filesystem::ifstream hsgr_input_stream(hsgr_file, std::ios::binary); @@ -192,4 +197,7 @@ unsigned readHSGRFromStream(const boost::filesystem::path &hsgr_file, return number_of_nodes; } +} +} + #endif // GRAPH_LOADER_HPP diff --git a/include/util/graph_utils.hpp b/include/util/graph_utils.hpp index 7c907ff22..c2165c5b6 100644 --- a/include/util/graph_utils.hpp +++ b/include/util/graph_utils.hpp @@ -6,6 +6,11 @@ #include #include +namespace osrm +{ +namespace util +{ + /// This function checks if the graph (consisting of directed edges) is undirected template bool isUndirectedGraph(const GraphT &graph) { @@ -91,4 +96,7 @@ std::vector directedEdgesFromCompressed(const std::vector +namespace osrm +{ +namespace util +{ + // computes a 64 bit value that corresponds to the hilbert space filling curve struct FixedPointCoordinate; @@ -19,4 +24,7 @@ class HilbertCode inline void TransposeCoordinate(uint32_t *X) const; }; +} +} + #endif /* HILBERT_VALUE_HPP */ diff --git a/include/util/ini_file.hpp b/include/util/ini_file.hpp index a99962f52..1ccc302e8 100644 --- a/include/util/ini_file.hpp +++ b/include/util/ini_file.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace { @@ -21,4 +26,7 @@ std::string read_file_lower_content(const boost::filesystem::path &path) return ini_file_content; } } +} +} + #endif // INI_FILE_HPP diff --git a/include/util/integer_range.hpp b/include/util/integer_range.hpp index 6c27b55dc..cba88ad92 100644 --- a/include/util/integer_range.hpp +++ b/include/util/integer_range.hpp @@ -9,6 +9,8 @@ namespace osrm { +namespace util +{ template class range { @@ -45,6 +47,8 @@ irange(const Integer first, { return range(first, last); } + +} } #endif // INTEGER_RANGE_HPP diff --git a/include/util/iso_8601_duration_parser.hpp b/include/util/iso_8601_duration_parser.hpp index aded519f9..493149c01 100644 --- a/include/util/iso_8601_duration_parser.hpp +++ b/include/util/iso_8601_duration_parser.hpp @@ -5,6 +5,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace qi = boost::spirit::qi; template struct iso_8601_grammar : qi::grammar @@ -72,4 +77,7 @@ template struct iso_8601_grammar : qi::grammar } }; +} +} + #endif // ISO_8601_DURATION_PARSER_HPP diff --git a/include/util/json_logger.hpp b/include/util/json_logger.hpp index cb3333f70..6b81cc6fc 100644 --- a/include/util/json_logger.hpp +++ b/include/util/json_logger.hpp @@ -10,6 +10,8 @@ namespace osrm { +namespace util +{ namespace json { @@ -17,7 +19,7 @@ namespace json // thread safe manner. class Logger { - using MapT = std::unordered_map; + using MapT = std::unordered_map; public: static Logger *get() @@ -53,6 +55,8 @@ class Logger boost::thread_specific_ptr map; }; + +} } } diff --git a/include/util/json_renderer.hpp b/include/util/json_renderer.hpp index b0e7de640..9f6656053 100644 --- a/include/util/json_renderer.hpp +++ b/include/util/json_renderer.hpp @@ -11,6 +11,8 @@ namespace osrm { +namespace util +{ namespace json { @@ -156,5 +158,7 @@ inline void render(std::vector &out, const Object &object) } } // namespace json +} // namespace util } // namespace osrm + #endif // JSON_RENDERER_HPP diff --git a/include/util/json_util.hpp b/include/util/json_util.hpp index d1eb7ae3f..2cf012eb2 100644 --- a/include/util/json_util.hpp +++ b/include/util/json_util.hpp @@ -8,6 +8,8 @@ namespace osrm { +namespace util +{ namespace json { @@ -26,16 +28,16 @@ template T clamp_float(T d) return d; } -template osrm::json::Array make_array(Args... args) +template Array make_array(Args... args) { - osrm::json::Array a; + Array a; append_to_container(a.values, args...); return a; } -template osrm::json::Array make_array(const std::vector &vector) +template Array make_array(const std::vector &vector) { - osrm::json::Array a; + Array a; for (const auto &v : vector) { a.values.emplace_back(v); @@ -44,9 +46,9 @@ template osrm::json::Array make_array(const std::vector &vector) } // template specialization needed as clang does not play nice -template <> osrm::json::Array make_array(const std::vector &vector) +template <> Array make_array(const std::vector &vector) { - osrm::json::Array a; + Array a; for (const bool v : vector) { a.values.emplace_back(v); @@ -55,22 +57,24 @@ template <> osrm::json::Array make_array(const std::vector &vector) } // Easy acces to object hierachies -osrm::json::Value &get(osrm::json::Value &value) { return value; } +Value &get(Value &value) { return value; } template -osrm::json::Value &get(osrm::json::Value &value, const char *key, Keys... keys) +Value &get(Value &value, const char *key, Keys... keys) { - using recursive_object_t = mapbox::util::recursive_wrapper; + using recursive_object_t = mapbox::util::recursive_wrapper; return get(value.get().get().values[key], keys...); } template -osrm::json::Value &get(osrm::json::Value &value, unsigned key, Keys... keys) +Value &get(Value &value, unsigned key, Keys... keys) { - using recursive_array_t = mapbox::util::recursive_wrapper; + using recursive_array_t = mapbox::util::recursive_wrapper; return get(value.get().get().values[key], keys...); } } // namespace json +} // namespace util } // namespace osrm + #endif // JSON_UTIL_HPP diff --git a/include/util/lua_util.hpp b/include/util/lua_util.hpp index f45dbffa1..47339fdd8 100644 --- a/include/util/lua_util.hpp +++ b/include/util/lua_util.hpp @@ -13,6 +13,11 @@ extern "C" { #include #include +namespace osrm +{ +namespace util +{ + template void LUA_print(T output) { std::cout << "[LUA] " << output << std::endl; } // Check if the lua function is defined @@ -35,4 +40,7 @@ inline void luaAddScriptFolderToLoadPath(lua_State *lua_state, const char *file_ luaL_dostring(lua_state, lua_code.c_str()); } +} +} + #endif // LUA_UTIL_HPP diff --git a/include/util/make_unique.hpp b/include/util/make_unique.hpp index 9c42ac520..09a1dd924 100644 --- a/include/util/make_unique.hpp +++ b/include/util/make_unique.hpp @@ -7,6 +7,9 @@ namespace osrm { +namespace util +{ + // Implement make_unique according to N3656. Taken from libcxx's implementation /// \brief Constructs a `new T()` with the given args and returns a @@ -42,5 +45,8 @@ make_unique(size_t n) /// This function isn't used and is only here to provide better compile errors. template typename std::enable_if::value != 0>::type make_unique(Args &&...) = delete; + } +} + #endif // MAKE_UNIQUE_H_ diff --git a/include/util/matching_debug_info.hpp b/include/util/matching_debug_info.hpp index 37f99403d..dc8e561d7 100644 --- a/include/util/matching_debug_info.hpp +++ b/include/util/matching_debug_info.hpp @@ -7,10 +7,15 @@ #include "osrm/coordinate.hpp" +namespace osrm +{ +namespace util +{ + // Provides the debug interface for introspection tools struct MatchingDebugInfo { - MatchingDebugInfo(const osrm::json::Logger *logger) : logger(logger) + MatchingDebugInfo(const json::Logger *logger) : logger(logger) { if (logger) { @@ -26,25 +31,25 @@ struct MatchingDebugInfo return; } - osrm::json::Array states; + json::Array states; for (auto &elem : candidates_list) { - osrm::json::Array timestamps; + json::Array timestamps; for (auto &elem_s : elem) { - osrm::json::Object state; - state.values["transitions"] = osrm::json::Array(); + json::Object state; + state.values["transitions"] = json::Array(); state.values["coordinate"] = - osrm::json::make_array(elem_s.phantom_node.location.lat / COORDINATE_PRECISION, + json::make_array(elem_s.phantom_node.location.lat / COORDINATE_PRECISION, elem_s.phantom_node.location.lon / COORDINATE_PRECISION); state.values["viterbi"] = - osrm::json::clamp_float(osrm::matching::IMPOSSIBLE_LOG_PROB); + json::clamp_float(engine::map_matching::IMPOSSIBLE_LOG_PROB); state.values["pruned"] = 0u; timestamps.values.push_back(state); } states.values.push_back(timestamps); } - osrm::json::get(*object, "states") = states; + json::get(*object, "states") = states; } void add_transition_info(const unsigned prev_t, @@ -63,14 +68,14 @@ struct MatchingDebugInfo return; } - osrm::json::Object transistion; - transistion.values["to"] = osrm::json::make_array(current_t, current_state); - transistion.values["properties"] = osrm::json::make_array( - osrm::json::clamp_float(prev_viterbi), osrm::json::clamp_float(emission_pr), - osrm::json::clamp_float(transition_pr), network_distance, haversine_distance); + json::Object transistion; + transistion.values["to"] = json::make_array(current_t, current_state); + transistion.values["properties"] = json::make_array( + json::clamp_float(prev_viterbi), json::clamp_float(emission_pr), + json::clamp_float(transition_pr), network_distance, haversine_distance); - osrm::json::get(*object, "states", prev_t, prev_state, "transitions") - .get>() + json::get(*object, "states", prev_t, prev_state, "transitions") + .get>() .get() .values.push_back(transistion); } @@ -89,11 +94,11 @@ struct MatchingDebugInfo { for (auto s_prime = 0u; s_prime < viterbi[t].size(); ++s_prime) { - osrm::json::get(*object, "states", t, s_prime, "viterbi") = - osrm::json::clamp_float(viterbi[t][s_prime]); - osrm::json::get(*object, "states", t, s_prime, "pruned") = + json::get(*object, "states", t, s_prime, "viterbi") = + json::clamp_float(viterbi[t][s_prime]); + json::get(*object, "states", t, s_prime, "pruned") = static_cast(pruned[t][s_prime]); - osrm::json::get(*object, "states", t, s_prime, "suspicious") = + json::get(*object, "states", t, s_prime, "suspicious") = static_cast(suspicious[t][s_prime]); } } @@ -107,7 +112,7 @@ struct MatchingDebugInfo return; } - osrm::json::get(*object, "states", t, s, "chosen") = true; + json::get(*object, "states", t, s, "chosen") = true; } void add_breakage(const std::vector &breakage) @@ -118,11 +123,14 @@ struct MatchingDebugInfo return; } - osrm::json::get(*object, "breakage") = osrm::json::make_array(breakage); + json::get(*object, "breakage") = json::make_array(breakage); } - const osrm::json::Logger *logger; - osrm::json::Value *object; + const json::Logger *logger; + json::Value *object; }; +} +} + #endif // MATCHING_DEBUG_INFO_HPP diff --git a/include/util/matrix_graph_wrapper.hpp b/include/util/matrix_graph_wrapper.hpp index b6aada34b..11b1f2586 100644 --- a/include/util/matrix_graph_wrapper.hpp +++ b/include/util/matrix_graph_wrapper.hpp @@ -7,7 +7,12 @@ #include "util/typedefs.hpp" -// This Wrapper provides all methods that are needed for TarjanSCC, when the graph is given in a +namespace osrm +{ +namespace util +{ + +// This Wrapper provides all methods that are needed for extractor::TarjanSCC, when the graph is given in a // matrix representation (e.g. as output from a distance table call) template class MatrixGraphWrapper @@ -40,4 +45,7 @@ template class MatrixGraphWrapper const std::size_t number_of_nodes_; }; +} +} + #endif // MATRIX_GRAPH_WRAPPER_H diff --git a/include/util/mercator.hpp b/include/util/mercator.hpp index e338d9b1b..230c1ad23 100644 --- a/include/util/mercator.hpp +++ b/include/util/mercator.hpp @@ -1,6 +1,11 @@ #ifndef MERCATOR_HPP #define MERCATOR_HPP +namespace osrm +{ +namespace util +{ + struct mercator { static double y2lat(const double value) noexcept; @@ -8,4 +13,7 @@ struct mercator static double lat2y(const double latitude) noexcept; }; +} +} + #endif // MERCATOR_HPP diff --git a/include/util/node_based_graph.hpp b/include/util/node_based_graph.hpp index 51842ebbe..09b082496 100644 --- a/include/util/node_based_graph.hpp +++ b/include/util/node_based_graph.hpp @@ -9,6 +9,11 @@ #include +namespace osrm +{ +namespace util +{ + struct NodeBasedEdgeData { NodeBasedEdgeData() @@ -25,7 +30,7 @@ struct NodeBasedEdgeData bool reversed, bool roundabout, bool startpoint, - TravelMode travel_mode) + extractor::TravelMode travel_mode) : distance(distance), edge_id(edge_id), name_id(name_id), access_restricted(access_restricted), reversed(reversed), roundabout(roundabout), startpoint(startpoint), travel_mode(travel_mode) @@ -39,7 +44,7 @@ struct NodeBasedEdgeData bool reversed : 1; bool roundabout : 1; bool startpoint : 1; - TravelMode travel_mode : 4; + extractor::TravelMode travel_mode : 4; bool IsCompatibleTo(const NodeBasedEdgeData &other) const { @@ -55,11 +60,11 @@ using NodeBasedDynamicGraph = DynamicGraph; /// two edges for undirected edges. inline std::shared_ptr NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, - const std::vector &input_edge_list) + const std::vector &input_edge_list) { auto edges_list = directedEdgesFromCompressed( input_edge_list, - [](NodeBasedDynamicGraph::InputEdge &output_edge, const NodeBasedEdge &input_edge) + [](NodeBasedDynamicGraph::InputEdge &output_edge, const extractor::NodeBasedEdge &input_edge) { output_edge.data.distance = static_cast(input_edge.weight); BOOST_ASSERT(output_edge.data.distance > 0); @@ -79,4 +84,7 @@ NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, return graph; } +} +} + #endif // NODE_BASED_GRAPH_HPP diff --git a/include/util/osrm_exception.hpp b/include/util/osrm_exception.hpp index a776f84fd..fc84cb981 100644 --- a/include/util/osrm_exception.hpp +++ b/include/util/osrm_exception.hpp @@ -7,6 +7,9 @@ namespace osrm { +namespace util +{ + class exception final : public std::exception { public: @@ -21,5 +24,8 @@ class exception final : public std::exception const char *what() const noexcept override { return message.c_str(); } const std::string message; }; + } +} + #endif /* OSRM_EXCEPTION_HPP */ diff --git a/include/util/percent.hpp b/include/util/percent.hpp index bcca00e3c..4f0d0e72c 100644 --- a/include/util/percent.hpp +++ b/include/util/percent.hpp @@ -4,6 +4,11 @@ #include #include +namespace osrm +{ +namespace util +{ + class Percent { public: @@ -71,4 +76,7 @@ class Percent } }; +} +} + #endif // PERCENT_HPP diff --git a/include/util/range_algorithms.hpp b/include/util/range_algorithms.hpp index f821bf8ef..47393b523 100644 --- a/include/util/range_algorithms.hpp +++ b/include/util/range_algorithms.hpp @@ -5,6 +5,8 @@ namespace osrm { +namespace util +{ template auto max_element(const Container &c) -> decltype(std::max_element(c.begin(), c.end())) @@ -17,6 +19,8 @@ auto max_element(const Container &c) -> decltype(std::max_element(c.cbegin(), c. { return std::max_element(c.cbegin(), c.cend()); } + +} } #endif // RANGE_ALGORITHMS_HPP diff --git a/include/util/range_table.hpp b/include/util/range_table.hpp index 9e40f6b4c..97cbc3abe 100644 --- a/include/util/range_table.hpp +++ b/include/util/range_table.hpp @@ -7,6 +7,11 @@ #include #include + +namespace osrm +{ +namespace util +{ /* * These pre-declarations are needed because parsing C++ is hard * and otherwise the compiler gets confused. @@ -35,7 +40,7 @@ template class RangeTable using BlockT = std::array; using BlockContainerT = typename ShM::vector; using OffsetContainerT = typename ShM::vector; - using RangeT = osrm::range; + using RangeT = range; friend std::ostream &operator<<<>(std::ostream &out, const RangeTable &table); friend std::istream &operator>><>(std::istream &in, RangeTable &table); @@ -166,7 +171,7 @@ template class RangeTable BOOST_ASSERT(begin_idx < sum_lengths && end_idx <= sum_lengths); BOOST_ASSERT(begin_idx <= end_idx); - return osrm::irange(begin_idx, end_idx); + return irange(begin_idx, end_idx); } private: @@ -229,4 +234,7 @@ std::istream &operator>>(std::istream &in, RangeTable #include +namespace osrm +{ +namespace util +{ + // TODO: Make template type, add tests struct RectangleInt2D { @@ -173,4 +178,7 @@ struct RectangleInt2D } }; +} +} + #endif diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index 8085c3aa5..f1a55c8fb 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -12,6 +12,11 @@ #include #include #include + +namespace osrm +{ +namespace util +{ const static unsigned INIT_OK_START_ENGINE = 0; const static unsigned INIT_OK_DO_NOT_START_ENGINE = 1; const static unsigned INIT_FAILED = -1; @@ -53,49 +58,49 @@ populate_base_path(std::unordered_map &ser if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".hsgr not found"); + throw exception(".hsgr not found"); } path_iterator = server_paths.find("nodesdata"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".nodes not found"); + throw exception(".nodes not found"); } path_iterator = server_paths.find("edgesdata"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".edges not found"); + throw exception(".edges not found"); } path_iterator = server_paths.find("geometries"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".geometry not found"); + throw exception(".geometry not found"); } path_iterator = server_paths.find("ramindex"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".ramIndex not found"); + throw exception(".ramIndex not found"); } path_iterator = server_paths.find("fileindex"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".fileIndex not found"); + throw exception(".fileIndex not found"); } path_iterator = server_paths.find("namesdata"); if (path_iterator == server_paths.end() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw osrm::exception(".namesIndex not found"); + throw exception(".namesIndex not found"); } SimpleLogger().Write() << "HSGR file:\t" << server_paths["hsgrdata"]; @@ -226,15 +231,15 @@ GenerateServerProgramOptions(const int argc, if (1 > requested_num_threads) { - throw osrm::exception("Number of threads must be a positive number"); + throw exception("Number of threads must be a positive number"); } if (2 > max_locations_distance_table) { - throw osrm::exception("Max location for distance table must be at least two"); + throw exception("Max location for distance table must be at least two"); } if (2 > max_locations_map_matching) { - throw osrm::exception("Max location for map matching must be at least two"); + throw exception("Max location for map matching must be at least two"); } if (!use_shared_memory && option_variables.count("base")) @@ -254,4 +259,7 @@ GenerateServerProgramOptions(const int argc, return INIT_OK_DO_NOT_START_ENGINE; } +} +} + #endif // ROUTED_OPTIONS_HPP diff --git a/include/util/shared_memory_vector_wrapper.hpp b/include/util/shared_memory_vector_wrapper.hpp index fef9c78e7..ab651745d 100644 --- a/include/util/shared_memory_vector_wrapper.hpp +++ b/include/util/shared_memory_vector_wrapper.hpp @@ -8,6 +8,11 @@ #include #include +namespace osrm +{ +namespace util +{ + template class ShMemIterator : public std::iterator { DataT *p; @@ -124,4 +129,7 @@ template struct ShM std::vector>::type; }; +} +} + #endif // SHARED_MEMORY_VECTOR_WRAPPER_HPP diff --git a/include/util/simple_logger.hpp b/include/util/simple_logger.hpp index 041225abe..0b33f51fa 100644 --- a/include/util/simple_logger.hpp +++ b/include/util/simple_logger.hpp @@ -12,6 +12,11 @@ enum LogLevel logDEBUG }; +namespace osrm +{ +namespace util +{ + class LogPolicy { public: @@ -44,4 +49,7 @@ class SimpleLogger LogLevel level; }; +} +} + #endif /* SIMPLE_LOGGER_HPP */ diff --git a/include/util/static_graph.hpp b/include/util/static_graph.hpp index e8270409f..744dabb8b 100644 --- a/include/util/static_graph.hpp +++ b/include/util/static_graph.hpp @@ -13,13 +13,18 @@ #include #include +namespace osrm +{ +namespace util +{ + template class StaticGraph { public: using NodeIterator = NodeID; using EdgeIterator = NodeID; using EdgeData = EdgeDataT; - using EdgeRange = osrm::range; + using EdgeRange = range; class InputEdge { @@ -57,7 +62,7 @@ template class StaticGraph EdgeRange GetAdjacentEdgeRange(const NodeID node) const { - return osrm::irange(BeginEdges(node), EndEdges(node)); + return irange(BeginEdges(node), EndEdges(node)); } template StaticGraph(const int nodes, const ContainerT &graph) @@ -70,7 +75,7 @@ template class StaticGraph node_array.resize(number_of_nodes + 1); EdgeIterator edge = 0; EdgeIterator position = 0; - for (const auto node : osrm::irange(0u, number_of_nodes + 1)) + for (const auto node : irange(0u, number_of_nodes + 1)) { EdgeIterator last_edge = edge; while (edge < number_of_edges && graph[edge].source == node) @@ -82,10 +87,10 @@ template class StaticGraph } edge_array.resize(position); //(edge) edge = 0; - for (const auto node : osrm::irange(0u, number_of_nodes)) + for (const auto node : irange(0u, number_of_nodes)) { EdgeIterator e = node_array[node + 1].first_edge; - for (const auto i : osrm::irange(node_array[node].first_edge, e)) + for (const auto i : irange(node_array[node].first_edge, e)) { edge_array[i].target = graph[edge].target; edge_array[i].data = graph[edge].data; @@ -132,7 +137,7 @@ template class StaticGraph // searches for a specific edge EdgeIterator FindEdge(const NodeIterator from, const NodeIterator to) const { - for (const auto i : osrm::irange(BeginEdges(from), EndEdges(from))) + for (const auto i : irange(BeginEdges(from), EndEdges(from))) { if (to == edge_array[i].target) { @@ -189,4 +194,7 @@ template class StaticGraph typename ShM::vector edge_array; }; +} +} + #endif // STATIC_GRAPH_HPP diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index ef8f9e839..0b244f167 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -32,6 +32,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // Static RTree for serving nearest neighbour queries template , @@ -265,11 +270,11 @@ class StaticRTree if (!boost::filesystem::exists(node_file)) { - throw osrm::exception("ram index file does not exist"); + throw exception("ram index file does not exist"); } if (0 == boost::filesystem::file_size(node_file)) { - throw osrm::exception("ram index file is empty"); + throw exception("ram index file is empty"); } boost::filesystem::ifstream tree_node_file(node_file, std::ios::binary); @@ -285,11 +290,11 @@ class StaticRTree // open leaf node file and store thread specific pointer if (!boost::filesystem::exists(leaf_file)) { - throw osrm::exception("mem index file does not exist"); + throw exception("mem index file does not exist"); } if (0 == boost::filesystem::file_size(leaf_file)) { - throw osrm::exception("mem index file is empty"); + throw exception("mem index file is empty"); } leaves_stream.open(leaf_file, std::ios::binary); @@ -306,11 +311,11 @@ class StaticRTree // open leaf node file and store thread specific pointer if (!boost::filesystem::exists(leaf_file)) { - throw osrm::exception("mem index file does not exist"); + throw exception("mem index file does not exist"); } if (0 == boost::filesystem::file_size(leaf_file)) { - throw osrm::exception("mem index file is empty"); + throw exception("mem index file is empty"); } leaves_stream.open(leaf_file, std::ios::binary); @@ -411,7 +416,7 @@ class StaticRTree LoadLeafFromDisk(leaf_id, current_leaf_node); // current object represents a block on disk - for (const auto i : osrm::irange(0u, current_leaf_node.object_count)) + for (const auto i : irange(0u, current_leaf_node.object_count)) { auto ¤t_edge = current_leaf_node.objects[i]; const float current_perpendicular_distance = @@ -449,7 +454,7 @@ class StaticRTree } if (!leaves_stream.good()) { - throw osrm::exception("Could not read from leaf file."); + throw exception("Could not read from leaf file."); } const uint64_t seek_pos = sizeof(uint64_t) + leaf_id * sizeof(LeafNode); leaves_stream.seekg(seek_pos); @@ -491,4 +496,7 @@ class StaticRTree //[2] "Nearest Neighbor Queries", N. Roussopulos et al; 1995; DOI: 10.1145/223784.223794 //[3] "Distance Browsing in Spatial Databases"; G. Hjaltason, H. Samet; 1999; ACM Trans. DB Sys // Vol.24 No.2, pp.265-318 +} +} + #endif // STATIC_RTREE_HPP diff --git a/include/util/string_util.hpp b/include/util/string_util.hpp index 78ccfb34a..6a3c772bd 100644 --- a/include/util/string_util.hpp +++ b/include/util/string_util.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace util +{ + // precision: position after decimal point // length: maximum number of digits including comma and decimals // work with negative values to prevent overflowing when taking -value @@ -122,4 +127,7 @@ inline std::size_t URIDecode(const std::string &input, std::string &output) inline std::size_t URIDecodeInPlace(std::string &URI) { return URIDecode(URI, URI); } +} +} + #endif // STRING_UTIL_HPP diff --git a/include/util/timing_util.hpp b/include/util/timing_util.hpp index dc6435634..44af92b89 100644 --- a/include/util/timing_util.hpp +++ b/include/util/timing_util.hpp @@ -7,6 +7,11 @@ #include #include +namespace osrm +{ +namespace util +{ + struct GlobalTimer { GlobalTimer() : time(0) {} @@ -60,4 +65,7 @@ class GlobalTimerFactory #define TIMER_MIN(_X) \ std::chrono::duration_cast(_X##_stop - _X##_start).count() +} +} + #endif // TIMING_UTIL_HPP diff --git a/include/util/tribool.hpp b/include/util/tribool.hpp index ff9637273..ec7ca76a7 100644 --- a/include/util/tribool.hpp +++ b/include/util/tribool.hpp @@ -3,11 +3,16 @@ namespace osrm { +namespace util +{ + enum class tribool : char { yes, no, indeterminate }; + +} } #endif // TRIBOOL_HPP diff --git a/include/util/trigonometry_table.hpp b/include/util/trigonometry_table.hpp index c02b5b78a..5c92829c0 100644 --- a/include/util/trigonometry_table.hpp +++ b/include/util/trigonometry_table.hpp @@ -6,6 +6,11 @@ #include +namespace osrm +{ +namespace util +{ + constexpr unsigned short atan_table[4096] = { 0x0000, 0x0014, 0x0028, 0x003d, 0x0051, 0x0065, 0x007a, 0x008e, 0x00a3, 0x00b7, 0x00cb, 0x00e0, 0x00f4, 0x0108, 0x011d, 0x0131, 0x0146, 0x015a, 0x016e, 0x0183, 0x0197, 0x01ab, 0x01c0, 0x01d4, @@ -418,4 +423,7 @@ inline double atan2_lookup(double y, double x) return angle; } +} +} + #endif // TRIGONOMETRY_TABLE_HPP diff --git a/include/util/typedefs.hpp b/include/util/typedefs.hpp index 0060a7381..243f04ed6 100644 --- a/include/util/typedefs.hpp +++ b/include/util/typedefs.hpp @@ -1,8 +1,9 @@ #ifndef TYPEDEFS_H #define TYPEDEFS_H -#include #include "osrm/strong_typedef.hpp" + +#include #include // Necessary workaround for Windows as VS doesn't implement C99 diff --git a/include/util/xml_renderer.hpp b/include/util/xml_renderer.hpp index b9de27c4f..b8fa82a58 100644 --- a/include/util/xml_renderer.hpp +++ b/include/util/xml_renderer.hpp @@ -7,6 +7,8 @@ namespace osrm { +namespace util +{ namespace json { @@ -105,6 +107,9 @@ template inline void gpx_render(std::vector &out, const const std::string footer{""}; out.insert(out.end(), footer.begin(), footer.end()); } + } // namespace json +} // namespace util } // namespace osrm + #endif // XML_RENDERER_HPP diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 9e911c1f5..247c76ba6 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -4,6 +4,11 @@ #include #include +namespace osrm +{ +namespace util +{ + /* This is an implementation of Tabulation hashing, which has suprising properties like universality. @@ -85,4 +90,7 @@ class XORMiniHash } }; +} +} + #endif // XOR_FAST_HASH_HPP diff --git a/include/util/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp index 2754b4545..046580dc9 100644 --- a/include/util/xor_fast_hash_storage.hpp +++ b/include/util/xor_fast_hash_storage.hpp @@ -6,6 +6,11 @@ #include #include +namespace osrm +{ +namespace util +{ + template class XORFastHashStorage { public: @@ -71,4 +76,7 @@ template class XORFastHashStorage unsigned current_timestamp; }; +} +} + #endif // XOR_FAST_HASH_STORAGE_HPP diff --git a/src/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp index db43bf20e..ab6b019a7 100644 --- a/src/benchmarks/static_rtree.cpp +++ b/src/benchmarks/static_rtree.cpp @@ -9,6 +9,11 @@ #include #include +namespace osrm +{ +namespace benchmarks +{ + // Choosen by a fair W20 dice roll (this value is completely arbitrary) constexpr unsigned RANDOM_SEED = 13; constexpr int32_t WORLD_MIN_LAT = -90 * COORDINATE_PRECISION; @@ -16,22 +21,22 @@ constexpr int32_t WORLD_MAX_LAT = 90 * COORDINATE_PRECISION; constexpr int32_t WORLD_MIN_LON = -180 * COORDINATE_PRECISION; constexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION; -using RTreeLeaf = EdgeBasedNode; -using FixedPointCoordinateListPtr = std::shared_ptr>; -using BenchStaticRTree = StaticRTree::vector, false>; -using BenchQuery = GeospatialQuery; +using RTreeLeaf = extractor::EdgeBasedNode; +using FixedPointCoordinateListPtr = std::shared_ptr>; +using BenchStaticRTree = util::StaticRTree::vector, false>; +using BenchQuery = engine::GeospatialQuery; FixedPointCoordinateListPtr loadCoordinates(const boost::filesystem::path &nodes_file) { boost::filesystem::ifstream nodes_input_stream(nodes_file, std::ios::binary); - QueryNode current_node; + extractor::QueryNode current_node; unsigned coordinate_count = 0; nodes_input_stream.read((char *)&coordinate_count, sizeof(unsigned)); auto coords = std::make_shared>(coordinate_count); for (unsigned i = 0; i < coordinate_count; ++i) { - nodes_input_stream.read((char *)¤t_node, sizeof(QueryNode)); + nodes_input_stream.read((char *)¤t_node, sizeof(extractor::QueryNode)); coords->at(i) = FixedPointCoordinate(current_node.lat, current_node.lon); BOOST_ASSERT((std::abs(coords->at(i).lat) >> 30) == 0); BOOST_ASSERT((std::abs(coords->at(i).lon) >> 30) == 0); @@ -51,6 +56,7 @@ void benchmarkQuery(const std::vector &queries, for (const auto &q : queries) { auto result = query(q); + (void) result; } TIMER_STOP(query); @@ -102,6 +108,8 @@ void benchmark(BenchStaticRTree &rtree, BenchQuery &geo_query, unsigned num_quer return geo_query.NearestPhantomNodes(q, 10); }); } +} +} int main(int argc, char **argv) { @@ -116,12 +124,12 @@ int main(int argc, char **argv) const char *file_path = argv[2]; const char *nodes_path = argv[3]; - auto coords = loadCoordinates(nodes_path); + auto coords = osrm::benchmarks::loadCoordinates(nodes_path); - BenchStaticRTree rtree(ram_path, file_path, coords); - BenchQuery query(rtree, coords); + osrm::benchmarks::BenchStaticRTree rtree(ram_path, file_path, coords); + osrm::benchmarks::BenchQuery query(rtree, coords); - benchmark(rtree, query, 10000); + osrm::benchmarks::benchmark(rtree, query, 10000); return 0; } diff --git a/src/contractor/contractor_options.cpp b/src/contractor/contractor_options.cpp index d25bb71fd..51b8228b7 100644 --- a/src/contractor/contractor_options.cpp +++ b/src/contractor/contractor_options.cpp @@ -8,6 +8,11 @@ #include +namespace osrm +{ +namespace contractor +{ + return_code ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &contractor_config) { @@ -87,13 +92,13 @@ ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &cont if (option_variables.count("version")) { - SimpleLogger().Write() << OSRM_VERSION; + util::SimpleLogger().Write() << OSRM_VERSION; return return_code::exit; } if (option_variables.count("help")) { - SimpleLogger().Write() << "\n" << visible_options; + util::SimpleLogger().Write() << "\n" << visible_options; return return_code::exit; } @@ -101,7 +106,7 @@ ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &cont if (!option_variables.count("input")) { - SimpleLogger().Write() << "\n" << visible_options; + util::SimpleLogger().Write() << "\n" << visible_options; return return_code::fail; } @@ -119,3 +124,5 @@ void ContractorOptions::GenerateOutputFilesNames(ContractorConfig &contractor_co contractor_config.edge_penalty_path = contractor_config.osrm_input_path.string() + ".edge_penalties"; } +} +} diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index 7e814ded7..b108522fa 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -30,6 +30,24 @@ #include "util/debug_geometry.hpp" +namespace std +{ + +template <> struct hash> +{ + std::size_t operator()(const std::pair &k) const + { + return OSMNodeID_to_uint64_t(k.first) ^ (OSMNodeID_to_uint64_t(k.second) << 12); + } +}; +} + + +namespace osrm +{ +namespace contractor +{ + Prepare::~Prepare() {} int Prepare::Run() @@ -37,24 +55,24 @@ int Prepare::Run() #ifdef WIN32 #pragma message("Memory consumption on Windows can be higher due to different bit packing") #else - static_assert(sizeof(NodeBasedEdge) == 20, - "changing NodeBasedEdge type has influence on memory consumption!"); - static_assert(sizeof(EdgeBasedEdge) == 16, + static_assert(sizeof(extractor::NodeBasedEdge) == 20, + "changing extractor::NodeBasedEdge type has influence on memory consumption!"); + static_assert(sizeof(extractor::EdgeBasedEdge) == 16, "changing EdgeBasedEdge type has influence on memory consumption!"); #endif if (config.core_factor > 1.0 || config.core_factor < 0) { - throw osrm::exception("Core factor must be between 0.0 to 1.0 (inclusive)"); + throw util::exception("Core factor must be between 0.0 to 1.0 (inclusive)"); } TIMER_START(preparing); // Create a new lua state - SimpleLogger().Write() << "Loading edge-expanded graph representation"; + util::SimpleLogger().Write() << "Loading edge-expanded graph representation"; - DeallocatingVector edge_based_edge_list; + util::DeallocatingVector edge_based_edge_list; size_t max_edge_id = LoadEdgeExpandedGraph( config.edge_based_graph_path, edge_based_edge_list, config.edge_segment_lookup_path, @@ -69,12 +87,12 @@ int Prepare::Run() { ReadNodeLevels(node_levels); } - DeallocatingVector contracted_edge_list; + util::DeallocatingVector contracted_edge_list; ContractGraph(max_edge_id, edge_based_edge_list, contracted_edge_list, is_core_node, node_levels); TIMER_STOP(contraction); - SimpleLogger().Write() << "Contraction took " << TIMER_SEC(contraction) << " sec"; + util::SimpleLogger().Write() << "Contraction took " << TIMER_SEC(contraction) << " sec"; std::size_t number_of_used_edges = WriteContractedGraph(max_edge_id, contracted_edge_list); WriteCoreNodeMarker(std::move(is_core_node)); @@ -85,35 +103,23 @@ int Prepare::Run() TIMER_STOP(preparing); - SimpleLogger().Write() << "Preprocessing : " << TIMER_SEC(preparing) << " seconds"; - SimpleLogger().Write() << "Contraction: " << ((max_edge_id + 1) / TIMER_SEC(contraction)) + util::SimpleLogger().Write() << "Preprocessing : " << TIMER_SEC(preparing) << " seconds"; + util::SimpleLogger().Write() << "Contraction: " << ((max_edge_id + 1) / TIMER_SEC(contraction)) << " nodes/sec and " << number_of_used_edges / TIMER_SEC(contraction) << " edges/sec"; - SimpleLogger().Write() << "finished preprocessing"; + util::SimpleLogger().Write() << "finished preprocessing"; return 0; } -namespace std -{ - -template <> struct hash> -{ - std::size_t operator()(const std::pair &k) const - { - return OSMNodeID_to_uint64_t(k.first) ^ (OSMNodeID_to_uint64_t(k.second) << 12); - } -}; -} - std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_filename, - DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &edge_based_edge_list, const std::string &edge_segment_lookup_filename, const std::string &edge_penalty_filename, const std::string &segment_speed_filename) { - SimpleLogger().Write() << "Opening " << edge_based_graph_filename; + util::SimpleLogger().Write() << "Opening " << edge_based_graph_filename; boost::filesystem::ifstream input_stream(edge_based_graph_filename, std::ios::binary); const bool update_edge_weights = segment_speed_filename != ""; @@ -127,14 +133,14 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f edge_fixed_penalties_input_stream.open(edge_penalty_filename, std::ios::binary); if (!edge_segment_input_stream || !edge_fixed_penalties_input_stream) { - throw osrm::exception("Could not load .edge_segment_lookup or .edge_penalties, did you " + throw util::exception("Could not load .edge_segment_lookup or .edge_penalties, did you " "run osrm-extract with '--generate-edge-lookup'?"); } } - const FingerPrint fingerprint_valid = FingerPrint::GetValid(); - FingerPrint fingerprint_loaded; - input_stream.read((char *)&fingerprint_loaded, sizeof(FingerPrint)); + const util::FingerPrint fingerprint_valid = util::FingerPrint::GetValid(); + util::FingerPrint fingerprint_loaded; + input_stream.read((char *)&fingerprint_loaded, sizeof(util::FingerPrint)); fingerprint_loaded.TestPrepare(fingerprint_valid); size_t number_of_edges = 0; @@ -143,13 +149,13 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f input_stream.read((char *)&max_edge_id, sizeof(size_t)); edge_based_edge_list.resize(number_of_edges); - SimpleLogger().Write() << "Reading " << number_of_edges << " edges from the edge based graph"; + util::SimpleLogger().Write() << "Reading " << number_of_edges << " edges from the edge based graph"; std::unordered_map, unsigned> segment_speed_lookup; if (update_edge_weights) { - SimpleLogger().Write() << "Segment speed data supplied, will update edge weights from " + util::SimpleLogger().Write() << "Segment speed data supplied, will update edge weights from " << segment_speed_filename; io::CSVReader<3> csv_in(segment_speed_filename); csv_in.set_header("from_node", "to_node", "speed"); @@ -163,14 +169,14 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f } } - DEBUG_GEOMETRY_START(config); + util::DEBUG_GEOMETRY_START(config); - // TODO: can we read this in bulk? DeallocatingVector isn't necessarily + // TODO: can we read this in bulk? util::DeallocatingVector isn't necessarily // all stored contiguously for (; number_of_edges > 0; --number_of_edges) { - EdgeBasedEdge inbuffer; - input_stream.read((char *)&inbuffer, sizeof(EdgeBasedEdge)); + extractor::EdgeBasedEdge inbuffer; + input_stream.read((char *)&inbuffer, sizeof(extractor::EdgeBasedEdge)); if (update_edge_weights) { @@ -212,7 +218,7 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f (segment_length * 10.) / (speed_iter->second / 3.6) + .5))); new_weight += new_segment_weight; - DEBUG_GEOMETRY_EDGE(new_segment_weight, segment_length, previous_osm_node_id, + util::DEBUG_GEOMETRY_EDGE(new_segment_weight, segment_length, previous_osm_node_id, this_osm_node_id); } else @@ -220,7 +226,7 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f // If no lookup found, use the original weight value for this segment new_weight += segment_weight; - DEBUG_GEOMETRY_EDGE(segment_weight, segment_length, previous_osm_node_id, + util::DEBUG_GEOMETRY_EDGE(segment_weight, segment_length, previous_osm_node_id, this_osm_node_id); } @@ -233,8 +239,8 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f edge_based_edge_list.emplace_back(std::move(inbuffer)); } - DEBUG_GEOMETRY_STOP(); - SimpleLogger().Write() << "Done reading edges"; + util::DEBUG_GEOMETRY_STOP(); + util::SimpleLogger().Write() << "Done reading edges"; return max_edge_id; } @@ -277,17 +283,17 @@ void Prepare::WriteCoreNodeMarker(std::vector &&in_is_core_node) const } std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, - const DeallocatingVector &contracted_edge_list) + const util::DeallocatingVector &contracted_edge_list) { // Sorting contracted edges in a way that the static query graph can read some in in-place. tbb::parallel_sort(contracted_edge_list.begin(), contracted_edge_list.end()); const unsigned contracted_edge_count = contracted_edge_list.size(); - SimpleLogger().Write() << "Serializing compacted graph of " << contracted_edge_count + util::SimpleLogger().Write() << "Serializing compacted graph of " << contracted_edge_count << " edges"; - const FingerPrint fingerprint = FingerPrint::GetValid(); + const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); boost::filesystem::ofstream hsgr_output_stream(config.graph_output_path, std::ios::binary); - hsgr_output_stream.write((char *)&fingerprint, sizeof(FingerPrint)); + hsgr_output_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); const unsigned max_used_node_id = [&contracted_edge_list] { unsigned tmp_max = 0; @@ -301,20 +307,20 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, return tmp_max; }(); - SimpleLogger().Write(logDEBUG) << "input graph has " << (max_node_id + 1) << " nodes"; - SimpleLogger().Write(logDEBUG) << "contracted graph has " << (max_used_node_id + 1) << " nodes"; + util::SimpleLogger().Write(logDEBUG) << "input graph has " << (max_node_id + 1) << " nodes"; + util::SimpleLogger().Write(logDEBUG) << "contracted graph has " << (max_used_node_id + 1) << " nodes"; - std::vector::NodeArrayEntry> node_array; + std::vector::NodeArrayEntry> node_array; // make sure we have at least one sentinel node_array.resize(max_node_id + 2); - SimpleLogger().Write() << "Building node array"; - StaticGraph::EdgeIterator edge = 0; - StaticGraph::EdgeIterator position = 0; - StaticGraph::EdgeIterator last_edge; + util::SimpleLogger().Write() << "Building node array"; + util::StaticGraph::EdgeIterator edge = 0; + util::StaticGraph::EdgeIterator position = 0; + util::StaticGraph::EdgeIterator last_edge; // initializing 'first_edge'-field of nodes: - for (const auto node : osrm::irange(0u, max_used_node_id + 1)) + for (const auto node : util::irange(0u, max_used_node_id + 1)) { last_edge = edge; while ((edge < contracted_edge_count) && (contracted_edge_list[edge].source == node)) @@ -326,17 +332,17 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, } for (const auto sentinel_counter : - osrm::irange(max_used_node_id + 1, node_array.size())) + util::irange(max_used_node_id + 1, node_array.size())) { // sentinel element, guarded against underflow node_array[sentinel_counter].first_edge = contracted_edge_count; } - SimpleLogger().Write() << "Serializing node array"; + util::SimpleLogger().Write() << "Serializing node array"; RangebasedCRC32 crc32_calculator; const unsigned edges_crc32 = crc32_calculator(contracted_edge_list); - SimpleLogger().Write() << "Writing CRC32: " << edges_crc32; + util::SimpleLogger().Write() << "Writing CRC32: " << edges_crc32; const unsigned node_array_size = node_array.size(); // serialize crc32, aka checksum @@ -349,15 +355,15 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, if (node_array_size > 0) { hsgr_output_stream.write((char *)&node_array[0], - sizeof(StaticGraph::NodeArrayEntry) * node_array_size); + sizeof(util::StaticGraph::NodeArrayEntry) * node_array_size); } // serialize all edges - SimpleLogger().Write() << "Building edge array"; + util::SimpleLogger().Write() << "Building edge array"; int number_of_used_edges = 0; - StaticGraph::EdgeArrayEntry current_edge; - for (const auto edge : osrm::irange(0, contracted_edge_list.size())) + util::StaticGraph::EdgeArrayEntry current_edge; + for (const auto edge : util::irange(0, contracted_edge_list.size())) { // no eigen loops BOOST_ASSERT(contracted_edge_list[edge].source != contracted_edge_list[edge].target); @@ -369,19 +375,19 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, #ifndef NDEBUG if (current_edge.data.distance <= 0) { - SimpleLogger().Write(logWARNING) << "Edge: " << edge + util::SimpleLogger().Write(logWARNING) << "Edge: " << edge << ",source: " << contracted_edge_list[edge].source << ", target: " << contracted_edge_list[edge].target << ", dist: " << current_edge.data.distance; - SimpleLogger().Write(logWARNING) << "Failed at adjacency list of node " + util::SimpleLogger().Write(logWARNING) << "Failed at adjacency list of node " << contracted_edge_list[edge].source << "/" << node_array.size() - 1; return 1; } #endif hsgr_output_stream.write((char *)¤t_edge, - sizeof(StaticGraph::EdgeArrayEntry)); + sizeof(util::StaticGraph::EdgeArrayEntry)); ++number_of_used_edges; } @@ -393,8 +399,8 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, \brief Build contracted graph. */ void Prepare::ContractGraph(const unsigned max_edge_id, - DeallocatingVector &edge_based_edge_list, - DeallocatingVector &contracted_edge_list, + util::DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &contracted_edge_list, std::vector &is_core_node, std::vector &inout_node_levels) const { @@ -407,3 +413,5 @@ void Prepare::ContractGraph(const unsigned max_edge_id, contractor.GetCoreMarker(is_core_node); contractor.GetNodeLevels(inout_node_levels); } +} +} diff --git a/src/engine/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp index 2be347fd8..cced730b2 100644 --- a/src/engine/douglas_peucker.cpp +++ b/src/engine/douglas_peucker.cpp @@ -9,13 +9,18 @@ #include #include +namespace osrm +{ +namespace engine +{ + namespace { struct CoordinatePairCalculator { CoordinatePairCalculator() = delete; - CoordinatePairCalculator(const FixedPointCoordinate &coordinate_a, - const FixedPointCoordinate &coordinate_b) + CoordinatePairCalculator(const util::FixedPointCoordinate &coordinate_a, + const util::FixedPointCoordinate &coordinate_b) { // initialize distance calculator with two fixed coordinates a, b const float RAD = 0.017453292519943295769236907684886f; @@ -25,7 +30,7 @@ struct CoordinatePairCalculator second_lon = (coordinate_b.lon / COORDINATE_PRECISION) * RAD; } - int operator()(FixedPointCoordinate &other) const + int operator()(util::FixedPointCoordinate &other) const { // set third coordinate c const float RAD = 0.017453292519943295769236907684886f; @@ -135,3 +140,5 @@ void DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigne } } } +} +} diff --git a/src/engine/osrm_impl.cpp b/src/engine/osrm_impl.cpp index 0be92a777..200eb2741 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/osrm_impl.cpp @@ -28,43 +28,51 @@ #include #include +namespace osrm +{ +namespace engine +{ + OSRM::OSRM_impl::OSRM_impl(LibOSRMConfig &lib_config) { if (lib_config.use_shared_memory) { - barrier = osrm::make_unique(); - query_data_facade = new SharedDataFacade(); + barrier = util::make_unique(); + query_data_facade = new datafacade::SharedDataFacade(); } else { // populate base path - populate_base_path(lib_config.server_paths); - query_data_facade = new InternalDataFacade(lib_config.server_paths); + util::populate_base_path(lib_config.server_paths); + query_data_facade = new datafacade::InternalDataFacade( + lib_config.server_paths); } + using DataFacade = datafacade::BaseDataFacade; + // The following plugins handle all requests. - RegisterPlugin(new DistanceTablePlugin>( + RegisterPlugin(new plugins::DistanceTablePlugin( query_data_facade, lib_config.max_locations_distance_table)); - RegisterPlugin(new HelloWorldPlugin()); - RegisterPlugin(new NearestPlugin>(query_data_facade)); - RegisterPlugin(new MapMatchingPlugin>( + RegisterPlugin(new plugins::HelloWorldPlugin()); + RegisterPlugin(new plugins::NearestPlugin(query_data_facade)); + RegisterPlugin(new plugins::MapMatchingPlugin( query_data_facade, lib_config.max_locations_map_matching)); - RegisterPlugin(new TimestampPlugin>(query_data_facade)); - RegisterPlugin(new ViaRoutePlugin>( - query_data_facade, lib_config.max_locations_viaroute)); - RegisterPlugin(new RoundTripPlugin>( - query_data_facade, lib_config.max_locations_trip)); + RegisterPlugin(new plugins::TimestampPlugin(query_data_facade)); + RegisterPlugin(new plugins::ViaRoutePlugin(query_data_facade, + lib_config.max_locations_viaroute)); + RegisterPlugin( + new plugins::RoundTripPlugin(query_data_facade, lib_config.max_locations_trip)); } -void OSRM::OSRM_impl::RegisterPlugin(BasePlugin *raw_plugin_ptr) +void OSRM::OSRM_impl::RegisterPlugin(plugins::BasePlugin *raw_plugin_ptr) { - std::unique_ptr plugin_ptr(raw_plugin_ptr); - SimpleLogger().Write() << "loaded plugin: " << plugin_ptr->GetDescriptor(); + std::unique_ptr plugin_ptr(raw_plugin_ptr); + util::SimpleLogger().Write() << "loaded plugin: " << plugin_ptr->GetDescriptor(); plugin_map[plugin_ptr->GetDescriptor()] = std::move(plugin_ptr); } int OSRM::OSRM_impl::RunQuery(const RouteParameters &route_parameters, - osrm::json::Object &json_result) + util::json::Object &json_result) { const auto &plugin_iterator = plugin_map.find(route_parameters.service); @@ -124,17 +132,20 @@ void OSRM::OSRM_impl::increase_concurrent_query_count() // increment query count ++(barrier->number_of_queries); - (static_cast *>(query_data_facade)) + (static_cast *>( + query_data_facade)) ->CheckAndReloadFacade(); } // proxy code for compilation firewall -OSRM::OSRM(LibOSRMConfig &lib_config) : OSRM_pimpl_(osrm::make_unique(lib_config)) {} +OSRM::OSRM(LibOSRMConfig &lib_config) : OSRM_pimpl_(util::make_unique(lib_config)) {} // needed because unique_ptr needs the size of OSRM_impl for delete OSRM::~OSRM() {} -int OSRM::RunQuery(const RouteParameters &route_parameters, osrm::json::Object &json_result) +int OSRM::RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result) { return OSRM_pimpl_->RunQuery(route_parameters, json_result); } +} +} diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp index 670ffe706..e5b5873df 100644 --- a/src/engine/phantom_node.cpp +++ b/src/engine/phantom_node.cpp @@ -5,6 +5,11 @@ #include +namespace osrm +{ +namespace engine +{ + PhantomNode::PhantomNode(NodeID forward_node_id, NodeID reverse_node_id, unsigned name_id, @@ -15,10 +20,10 @@ PhantomNode::PhantomNode(NodeID forward_node_id, unsigned packed_geometry_id, bool is_tiny_component, unsigned component_id, - FixedPointCoordinate &location, + util::FixedPointCoordinate &location, unsigned short fwd_segment_position, - TravelMode forward_travel_mode, - TravelMode backward_travel_mode) + extractor::TravelMode forward_travel_mode, + extractor::TravelMode backward_travel_mode) : forward_node_id(forward_node_id), reverse_node_id(reverse_node_id), name_id(name_id), forward_weight(forward_weight), reverse_weight(reverse_weight), forward_offset(forward_offset), reverse_offset(reverse_offset), @@ -74,3 +79,5 @@ bool PhantomNode::is_valid(const unsigned number_of_nodes) const bool PhantomNode::IsValid() const { return location.IsValid() && (name_id != INVALID_NAMEID); } bool PhantomNode::operator==(const PhantomNode &other) const { return location == other.location; } +} +} diff --git a/src/engine/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp index 2cb7935f7..042653084 100644 --- a/src/engine/polyline_compressor.cpp +++ b/src/engine/polyline_compressor.cpp @@ -3,6 +3,11 @@ #include "osrm/coordinate.hpp" +namespace osrm +{ +namespace engine +{ + std::string PolylineCompressor::encode_vector(std::vector &numbers) const { std::string output; @@ -47,7 +52,7 @@ PolylineCompressor::get_encoded_string(const std::vector &po std::vector delta_numbers; delta_numbers.reserve((polyline.size() - 1) * 2); - FixedPointCoordinate previous_coordinate = {0, 0}; + util::FixedPointCoordinate previous_coordinate = {0, 0}; for (const auto &segment : polyline) { if (segment.necessary) @@ -62,10 +67,10 @@ PolylineCompressor::get_encoded_string(const std::vector &po return encode_vector(delta_numbers); } -std::vector +std::vector PolylineCompressor::decode_string(const std::string &geometry_string) const { - std::vector new_coordinates; + std::vector new_coordinates; int index = 0, len = geometry_string.size(); int lat = 0, lng = 0; @@ -92,7 +97,7 @@ PolylineCompressor::decode_string(const std::string &geometry_string) const int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; - FixedPointCoordinate p; + util::FixedPointCoordinate p; p.lat = COORDINATE_PRECISION * (((double)lat / 1E6)); p.lon = COORDINATE_PRECISION * (((double)lng / 1E6)); new_coordinates.push_back(p); @@ -100,3 +105,5 @@ PolylineCompressor::decode_string(const std::string &geometry_string) const return new_coordinates; } +} +} diff --git a/src/engine/polyline_formatter.cpp b/src/engine/polyline_formatter.cpp index 52fa4935d..0b22ddb24 100644 --- a/src/engine/polyline_formatter.cpp +++ b/src/engine/polyline_formatter.cpp @@ -5,21 +5,26 @@ #include "osrm/coordinate.hpp" -osrm::json::String +namespace osrm +{ +namespace engine +{ + +util::json::String PolylineFormatter::printEncodedString(const std::vector &polyline) const { - return osrm::json::String(PolylineCompressor().get_encoded_string(polyline)); + return util::json::String(PolylineCompressor().get_encoded_string(polyline)); } -osrm::json::Array +util::json::Array PolylineFormatter::printUnencodedString(const std::vector &polyline) const { - osrm::json::Array json_geometry_array; + util::json::Array json_geometry_array; for (const auto &segment : polyline) { if (segment.necessary) { - osrm::json::Array json_coordinate; + util::json::Array json_coordinate; json_coordinate.values.push_back(segment.location.lat / COORDINATE_PRECISION); json_coordinate.values.push_back(segment.location.lon / COORDINATE_PRECISION); json_geometry_array.values.push_back(json_coordinate); @@ -27,3 +32,5 @@ PolylineFormatter::printUnencodedString(const std::vector &p } return json_geometry_array; } +} +} diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index c0c1290fb..6565896f3 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -7,6 +7,11 @@ #include "engine/polyline_compressor.hpp" +namespace osrm +{ +namespace engine +{ + RouteParameters::RouteParameters() : zoom_level(18), print_instructions(false), alternate_route(true), geometry(true), compression(true), deprecatedAPI(false), uturn_default(false), classify(false), @@ -151,3 +156,5 @@ void RouteParameters::SetCoordinatesFromGeometry(const std::string &geometry_str PolylineCompressor pc; coordinates = pc.decode_string(geometry_string); } +} +} diff --git a/src/engine/search_engine_data.cpp b/src/engine/search_engine_data.cpp index d96fd22da..9aeb87d39 100644 --- a/src/engine/search_engine_data.cpp +++ b/src/engine/search_engine_data.cpp @@ -2,6 +2,11 @@ #include "util/binary_heap.hpp" +namespace osrm +{ +namespace engine +{ + void SearchEngineData::InitializeOrClearFirstThreadLocalStorage(const unsigned number_of_nodes) { if (forward_heap_1.get()) @@ -64,3 +69,5 @@ void SearchEngineData::InitializeOrClearThirdThreadLocalStorage(const unsigned n reverse_heap_3.reset(new QueryHeap(number_of_nodes)); } } +} +} diff --git a/src/extractor/compressed_edge_container.cpp b/src/extractor/compressed_edge_container.cpp index 2b9c5146f..9f20ac1ea 100644 --- a/src/extractor/compressed_edge_container.cpp +++ b/src/extractor/compressed_edge_container.cpp @@ -10,6 +10,11 @@ #include +namespace osrm +{ +namespace extractor +{ + CompressedEdgeContainer::CompressedEdgeContainer() { m_free_list.reserve(100); @@ -181,7 +186,7 @@ void CompressedEdgeContainer::PrintStatistics() const longest_chain_length = std::max(longest_chain_length, (uint64_t)current_vector.size()); } - SimpleLogger().Write() << "Geometry successfully removed:" + util::SimpleLogger().Write() << "Geometry successfully removed:" "\n compressed edges: " << compressed_edges << "\n compressed geometries: " << compressed_geometries @@ -212,3 +217,5 @@ NodeID CompressedEdgeContainer::GetLastEdgeSourceID(const EdgeID edge_id) const BOOST_ASSERT(bucket.size() >= 2); return bucket[bucket.size() - 2].first; } +} +} diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 896f84e7f..8bae91dc1 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -16,8 +16,13 @@ #include #include +namespace osrm +{ +namespace extractor +{ + EdgeBasedGraphFactory::EdgeBasedGraphFactory( - std::shared_ptr node_based_graph, + std::shared_ptr node_based_graph, const CompressedEdgeContainer &compressed_edge_container, const std::unordered_set &barrier_nodes, const std::unordered_set &traffic_lights, @@ -32,7 +37,7 @@ EdgeBasedGraphFactory::EdgeBasedGraphFactory( { } -void EdgeBasedGraphFactory::GetEdgeBasedEdges(DeallocatingVector &output_edge_list) +void EdgeBasedGraphFactory::GetEdgeBasedEdges(util::DeallocatingVector &output_edge_list) { BOOST_ASSERT_MSG(0 == output_edge_list.size(), "Vector is not empty"); using std::swap; // Koenig swap @@ -108,7 +113,7 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeI // TODO: move to lambda function with C++11 int temp_sum = 0; - for (const auto i : osrm::irange(0u, geometry_size)) + for (const auto i : util::irange(0u, geometry_size)) { forward_dist_prefix_sum[i] = temp_sum; temp_sum += forward_geometry[i].second; @@ -117,7 +122,7 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeI } temp_sum = 0; - for (const auto i : osrm::irange(0u, geometry_size)) + for (const auto i : util::irange(0u, geometry_size)) { temp_sum += reverse_geometry[reverse_geometry.size() - 1 - i].second; reverse_dist_prefix_sum[i] = reverse_data.distance - temp_sum; @@ -127,7 +132,7 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeI NodeID current_edge_source_coordinate_id = node_u; // traverse arrays from start and end respectively - for (const auto i : osrm::irange(0u, geometry_size)) + for (const auto i : util::irange(0u, geometry_size)) { BOOST_ASSERT(current_edge_source_coordinate_id == reverse_geometry[geometry_size - 1 - i].first); @@ -238,10 +243,10 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename, TIMER_STOP(generate_edges); - SimpleLogger().Write() << "Timing statistics for edge-expanded graph:"; - SimpleLogger().Write() << "Renumbering edges: " << TIMER_SEC(renumber) << "s"; - SimpleLogger().Write() << "Generating nodes: " << TIMER_SEC(generate_nodes) << "s"; - SimpleLogger().Write() << "Generating edges: " << TIMER_SEC(generate_edges) << "s"; + util::SimpleLogger().Write() << "Timing statistics for edge-expanded graph:"; + util::SimpleLogger().Write() << "Renumbering edges: " << TIMER_SEC(renumber) << "s"; + util::SimpleLogger().Write() << "Generating nodes: " << TIMER_SEC(generate_nodes) << "s"; + util::SimpleLogger().Write() << "Generating edges: " << TIMER_SEC(generate_edges) << "s"; } /// Renumbers all _forward_ edges and sets the edge_id. @@ -251,7 +256,7 @@ unsigned EdgeBasedGraphFactory::RenumberEdges() { // renumber edge based node of outgoing edges unsigned numbered_edges_count = 0; - for (const auto current_node : osrm::irange(0u, m_node_based_graph->GetNumberOfNodes())) + for (const auto current_node : util::irange(0u, m_node_based_graph->GetNumberOfNodes())) { for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(current_node)) { @@ -277,10 +282,10 @@ unsigned EdgeBasedGraphFactory::RenumberEdges() /// Creates the nodes in the edge expanded graph from edges in the node-based graph. void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() { - Percent progress(m_node_based_graph->GetNumberOfNodes()); + util::Percent progress(m_node_based_graph->GetNumberOfNodes()); // loop over all edges and generate new set of nodes - for (const auto node_u : osrm::irange(0u, m_node_based_graph->GetNumberOfNodes())) + for (const auto node_u : util::irange(0u, m_node_based_graph->GetNumberOfNodes())) { BOOST_ASSERT(node_u != SPECIAL_NODEID); BOOST_ASSERT(node_u < m_node_based_graph->GetNumberOfNodes()); @@ -315,7 +320,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() BOOST_ASSERT(m_edge_based_node_list.size() == m_edge_based_node_is_startpoint.size()); - SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() + util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " nodes in edge-expanded graph"; } @@ -337,7 +342,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( const bool generate_edge_lookup) #endif { - SimpleLogger().Write() << "generating edge-expanded edges"; + util::SimpleLogger().Write() << "generating edge-expanded edges"; unsigned node_based_edge_counter = 0; unsigned original_edges_counter = 0; @@ -366,13 +371,13 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( unsigned skipped_barrier_turns_counter = 0; unsigned compressed = 0; - Percent progress(m_node_based_graph->GetNumberOfNodes()); + util::Percent progress(m_node_based_graph->GetNumberOfNodes()); #ifdef DEBUG_GEOMETRY - DEBUG_TURNS_START(debug_turns_path); + util::DEBUG_TURNS_START(debug_turns_path); #endif - for (const auto node_u : osrm::irange(0u, m_node_based_graph->GetNumberOfNodes())) + for (const auto node_u : util::irange(0u, m_node_based_graph->GetNumberOfNodes())) { // progress.printStatus(node_u); for (const EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(node_u)) @@ -446,7 +451,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( { distance += speed_profile.traffic_signal_penalty; - DEBUG_SIGNAL(node_v, m_node_info_list, speed_profile.traffic_signal_penalty); + util::DEBUG_SIGNAL(node_v, m_node_info_list, speed_profile.traffic_signal_penalty); } // unpack last node of first segment if packed @@ -461,7 +466,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( ? m_compressed_edge_container.GetFirstEdgeTargetID(e2) : node_w)]; - const double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates( + const double turn_angle = util::ComputeAngle::OfThreeFixedPointCoordinates( first_coordinate, m_node_info_list[node_v], third_coordinate); const int turn_penalty = GetTurnPenalty(turn_angle, lua_state); @@ -470,10 +475,10 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( { distance += speed_profile.u_turn_penalty; - DEBUG_UTURN(node_v, m_node_info_list, speed_profile.u_turn_penalty); + util::DEBUG_UTURN(node_v, m_node_info_list, speed_profile.u_turn_penalty); } - DEBUG_TURN(node_v, m_node_info_list, first_coordinate, turn_angle, turn_penalty); + util::DEBUG_TURN(node_v, m_node_info_list, first_coordinate, turn_angle, turn_penalty); distance += turn_penalty; @@ -541,7 +546,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( const QueryNode &from = m_node_info_list[previous]; const QueryNode &to = m_node_info_list[target_node.first]; const double segment_length = - coordinate_calculation::greatCircleDistance(from.lat, from.lon, + util::coordinate_calculation::greatCircleDistance(from.lat, from.lon, to.lat, to.lon); edge_segment_file.write(reinterpret_cast(&to.node_id), @@ -559,7 +564,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( static const unsigned node_count = 2; const QueryNode from = m_node_info_list[node_u]; const QueryNode to = m_node_info_list[node_v]; - const double segment_length = coordinate_calculation::greatCircleDistance( + const double segment_length = util::coordinate_calculation::greatCircleDistance( from.lat, from.lon, to.lat, to.lon); edge_segment_file.write(reinterpret_cast(&node_count), sizeof(node_count)); @@ -578,7 +583,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( } } - DEBUG_TURNS_STOP(); + util::DEBUG_TURNS_STOP(); FlushVectorToStream(edge_data_file, original_edge_data_vector); @@ -586,15 +591,15 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( edge_data_file.write((char *)&original_edges_counter, sizeof(unsigned)); edge_data_file.close(); - SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " edge based nodes"; - SimpleLogger().Write() << "Node-based graph contains " << node_based_edge_counter << " edges"; - SimpleLogger().Write() << "Edge-expanded graph ..."; - SimpleLogger().Write() << " contains " << m_edge_based_edge_list.size() << " edges"; - SimpleLogger().Write() << " skips " << restricted_turns_counter << " turns, " + util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " edge based nodes"; + util::SimpleLogger().Write() << "Node-based graph contains " << node_based_edge_counter << " edges"; + util::SimpleLogger().Write() << "Edge-expanded graph ..."; + util::SimpleLogger().Write() << " contains " << m_edge_based_edge_list.size() << " edges"; + util::SimpleLogger().Write() << " skips " << restricted_turns_counter << " turns, " "defined by " << m_restriction_map->size() << " restrictions"; - SimpleLogger().Write() << " skips " << skipped_uturns_counter << " U turns"; - SimpleLogger().Write() << " skips " << skipped_barrier_turns_counter << " turns over barriers"; + util::SimpleLogger().Write() << " skips " << skipped_uturns_counter << " U turns"; + util::SimpleLogger().Write() << " skips " << skipped_barrier_turns_counter << " turns over barriers"; } int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) const @@ -611,7 +616,7 @@ int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) co } catch (const luabind::error &er) { - SimpleLogger().Write(logWARNING) << er.what(); + util::SimpleLogger().Write(logWARNING) << er.what(); } } return 0; @@ -673,3 +678,5 @@ TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID node_u, return TurnInstructionsClass::GetTurnDirectionOfInstruction(angle); } +} +} diff --git a/src/extractor/external_memory_node.cpp b/src/extractor/external_memory_node.cpp index 35dc18af1..249c25606 100644 --- a/src/extractor/external_memory_node.cpp +++ b/src/extractor/external_memory_node.cpp @@ -3,6 +3,11 @@ #include +namespace osrm +{ +namespace extractor +{ + ExternalMemoryNode::ExternalMemoryNode( int lat, int lon, OSMNodeID node_id, bool barrier, bool traffic_lights) : QueryNode(lat, lon, node_id), barrier(barrier), traffic_lights(traffic_lights) @@ -37,3 +42,5 @@ ExternalMemoryNodeSTXXLCompare::value_type ExternalMemoryNodeSTXXLCompare::min_v { return ExternalMemoryNode::min_value(); } +} +} diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 80fe2ac5f..72333644a 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -24,6 +24,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + static const int WRITE_BLOCK_BUFFER_SIZE = 8000; ExtractionContainers::ExtractionContainers() @@ -65,8 +70,8 @@ void ExtractionContainers::PrepareData(const std::string &output_file_name, { std::ofstream file_out_stream; file_out_stream.open(output_file_name.c_str(), std::ios::binary); - const FingerPrint fingerprint = FingerPrint::GetValid(); - file_out_stream.write((char *)&fingerprint, sizeof(FingerPrint)); + const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); + file_out_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); PrepareNodes(); WriteNodes(file_out_stream); @@ -100,7 +105,7 @@ void ExtractionContainers::WriteNames(const std::string &names_file_name) const } // builds and writes the index - RangeTable<> name_index_range(name_lengths); + util::RangeTable<> name_index_range(name_lengths); name_file_stream << name_index_range; name_file_stream.write((char *)&total_length, sizeof(unsigned)); @@ -182,7 +187,7 @@ void ExtractionContainers::PrepareNodes() } if (internal_id > std::numeric_limits::max()) { - throw osrm::exception("There are too many nodes remaining after filtering, OSRM only " + throw util::exception("There are too many nodes remaining after filtering, OSRM only " "supports 2^32 unique nodes"); } max_internal_node_id = boost::numeric_cast(internal_id); @@ -212,7 +217,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) { if (edge_iterator->result.osm_source_id < node_iterator->node_id) { - SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " + util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << edge_iterator->result.source; edge_iterator->result.source = SPECIAL_NODEID; ++edge_iterator; @@ -249,7 +254,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) // them. This happens when using osmosis with bbox or polygon to extract smaller areas. auto markSourcesInvalid = [](InternalExtractorEdge &edge) { - SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " + util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << edge.result.source; edge.result.source = SPECIAL_NODEID; edge.result.osm_source_id = SPECIAL_OSM_NODEID; @@ -284,7 +289,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) if (edge_iterator->result.osm_target_id < node_iterator->node_id) { - SimpleLogger().Write(LogLevel::logWARNING) + util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << OSMNodeID_to_uint64_t(edge_iterator->result.osm_target_id); edge_iterator->result.target = SPECIAL_NODEID; @@ -302,11 +307,11 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) BOOST_ASSERT(edge_iterator->source_coordinate.lat != std::numeric_limits::min()); BOOST_ASSERT(edge_iterator->source_coordinate.lon != std::numeric_limits::min()); - const double distance = coordinate_calculation::greatCircleDistance( + const double distance = util::coordinate_calculation::greatCircleDistance( edge_iterator->source_coordinate.lat, edge_iterator->source_coordinate.lon, node_iterator->lat, node_iterator->lon); - if (lua_function_exists(segment_state, "segment_function")) + if (util::lua_function_exists(segment_state, "segment_function")) { luabind::call_function( segment_state, "segment_function", boost::cref(edge_iterator->source_coordinate), @@ -325,7 +330,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) return (distance * 10.) / (data.speed / 3.6); break; case InternalExtractorEdge::WeightType::INVALID: - osrm::exception("invalid weight type"); + util::exception("invalid weight type"); } return -1.0; }(edge_iterator->weight_data); @@ -356,7 +361,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) // them. This happens when using osmosis with bbox or polygon to extract smaller areas. auto markTargetsInvalid = [](InternalExtractorEdge &edge) { - SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " + util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " << edge.result.target; edge.result.target = SPECIAL_NODEID; }; @@ -488,7 +493,7 @@ void ExtractionContainers::WriteEdges(std::ofstream &file_out_stream) const if (used_edges_counter > std::numeric_limits::max()) { - throw osrm::exception("There are too many edges, OSRM only supports 2^32"); + throw util::exception("There are too many edges, OSRM only supports 2^32"); } TIMER_STOP(write_edges); std::cout << "ok, after " << TIMER_SEC(write_edges) << "s" << std::endl; @@ -501,7 +506,7 @@ void ExtractionContainers::WriteEdges(std::ofstream &file_out_stream) const file_out_stream.write((char *)&used_edges_counter_buffer, sizeof(unsigned)); std::cout << "ok" << std::endl; - SimpleLogger().Write() << "Processed " << used_edges_counter << " edges"; + util::SimpleLogger().Write() << "Processed " << used_edges_counter << " edges"; } void ExtractionContainers::WriteNodes(std::ofstream &file_out_stream) const @@ -541,7 +546,7 @@ void ExtractionContainers::WriteNodes(std::ofstream &file_out_stream) const TIMER_STOP(write_nodes); std::cout << "ok, after " << TIMER_SEC(write_nodes) << "s" << std::endl; - SimpleLogger().Write() << "Processed " << max_internal_node_id << " nodes"; + util::SimpleLogger().Write() << "Processed " << max_internal_node_id << " nodes"; } void ExtractionContainers::WriteRestrictions(const std::string &path) const @@ -550,8 +555,8 @@ void ExtractionContainers::WriteRestrictions(const std::string &path) const std::ofstream restrictions_out_stream; unsigned written_restriction_count = 0; restrictions_out_stream.open(path.c_str(), std::ios::binary); - const FingerPrint fingerprint = FingerPrint::GetValid(); - restrictions_out_stream.write((char *)&fingerprint, sizeof(FingerPrint)); + const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); + restrictions_out_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); const auto count_position = restrictions_out_stream.tellp(); restrictions_out_stream.write((char *)&written_restriction_count, sizeof(unsigned)); @@ -569,7 +574,7 @@ void ExtractionContainers::WriteRestrictions(const std::string &path) const restrictions_out_stream.seekp(count_position); restrictions_out_stream.write((char *)&written_restriction_count, sizeof(unsigned)); restrictions_out_stream.close(); - SimpleLogger().Write() << "usable restrictions: " << written_restriction_count; + util::SimpleLogger().Write() << "usable restrictions: " << written_restriction_count; } void ExtractionContainers::PrepareRestrictions() @@ -609,7 +614,7 @@ void ExtractionContainers::PrepareRestrictions() if (way_start_and_end_iterator->way_id > OSMWayID(restrictions_iterator->restriction.from.way)) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " + util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " << restrictions_iterator->restriction.from.way; restrictions_iterator->restriction.from.node = SPECIAL_NODEID; ++restrictions_iterator; @@ -625,7 +630,7 @@ void ExtractionContainers::PrepareRestrictions() auto via_id_iter = external_to_internal_node_id_map.find(via_node_id); if (via_id_iter == external_to_internal_node_id_map.end()) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid node: " + util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid node: " << restrictions_iterator->restriction.via.node; restrictions_iterator->restriction.via.node = SPECIAL_NODEID; ++restrictions_iterator; @@ -686,7 +691,7 @@ void ExtractionContainers::PrepareRestrictions() if (way_start_and_end_iterator->way_id > OSMWayID(restrictions_iterator->restriction.to.way)) { - SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " + util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " << restrictions_iterator->restriction.to.way; restrictions_iterator->restriction.to.way = SPECIAL_NODEID; ++restrictions_iterator; @@ -720,3 +725,5 @@ void ExtractionContainers::PrepareRestrictions() TIMER_STOP(fix_restriction_ends); std::cout << "ok, after " << TIMER_SEC(fix_restriction_ends) << "s" << std::endl; } +} +} diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 4038b3ec9..053e5bd1c 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -46,6 +46,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + /** * TODO: Refactor this function into smaller functions for better readability. * @@ -69,7 +74,7 @@ int extractor::run() { try { - LogPolicy::GetInstance().Unmute(); + util::LogPolicy::GetInstance().Unmute(); TIMER_START(extracting); const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads(); @@ -77,15 +82,15 @@ int extractor::run() std::min(recommended_num_threads, config.requested_num_threads); tbb::task_scheduler_init init(number_of_threads); - SimpleLogger().Write() << "Input file: " << config.input_path.filename().string(); - SimpleLogger().Write() << "Profile: " << config.profile_path.filename().string(); - SimpleLogger().Write() << "Threads: " << number_of_threads; + util::SimpleLogger().Write() << "Input file: " << config.input_path.filename().string(); + util::SimpleLogger().Write() << "Profile: " << config.profile_path.filename().string(); + util::SimpleLogger().Write() << "Threads: " << number_of_threads; // setup scripting environment ScriptingEnvironment scripting_environment(config.profile_path.string().c_str()); ExtractionContainers extraction_containers; - auto extractor_callbacks = osrm::make_unique(extraction_containers); + auto extractor_callbacks = util::make_unique(extraction_containers); const osmium::io::File input_file(config.input_path.string()); osmium::io::Reader reader(input_file); @@ -96,12 +101,12 @@ int extractor::run() std::atomic number_of_relations{0}; std::atomic number_of_others{0}; - SimpleLogger().Write() << "Parsing in progress.."; + util::SimpleLogger().Write() << "Parsing in progress.."; TIMER_START(parsing); lua_State *segment_state = scripting_environment.GetLuaState(); - if (lua_function_exists(segment_state, "source_function")) + if (util::lua_function_exists(segment_state, "source_function")) { // bind a single instance of SourceContainer class to relevant lua state SourceContainer sources; @@ -115,7 +120,7 @@ int extractor::run() { generator = "unknown tool"; } - SimpleLogger().Write() << "input file generated by " << generator; + util::SimpleLogger().Write() << "input file generated by " << generator; // write .timestamp data file std::string timestamp = header.get("osmosis_replication_timestamp"); @@ -123,7 +128,7 @@ int extractor::run() { timestamp = "n/a"; } - SimpleLogger().Write() << "timestamp: " << timestamp; + util::SimpleLogger().Write() << "timestamp: " << timestamp; boost::filesystem::ofstream timestamp_out(config.timestamp_file_name); timestamp_out.write(timestamp.c_str(), timestamp.length()); @@ -214,9 +219,9 @@ int extractor::run() } } TIMER_STOP(parsing); - SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds"; + util::SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds"; - SimpleLogger().Write() << "Raw input contains " << number_of_nodes.load() << " nodes, " + util::SimpleLogger().Write() << "Raw input contains " << number_of_nodes.load() << " nodes, " << number_of_ways.load() << " ways, and " << number_of_relations.load() << " relations, and " << number_of_others.load() << " unknown entities"; @@ -225,7 +230,7 @@ int extractor::run() if (extraction_containers.all_edges_list.empty()) { - SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; + util::SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; return 1; } @@ -233,11 +238,11 @@ int extractor::run() config.names_file_name, segment_state); TIMER_STOP(extracting); - SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s"; + util::SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s"; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << e.what(); + util::SimpleLogger().Write(logWARNING) << e.what(); return 1; } @@ -250,12 +255,12 @@ int extractor::run() // // // Create a new lua state - SimpleLogger().Write() << "Generating edge-expanded graph representation"; + util::SimpleLogger().Write() << "Generating edge-expanded graph representation"; TIMER_START(expansion); std::vector node_based_edge_list; - DeallocatingVector edge_based_edge_list; + util::DeallocatingVector edge_based_edge_list; std::vector node_is_startpoint; std::vector internal_to_external_node_map; auto graph_size = @@ -267,7 +272,7 @@ int extractor::run() TIMER_STOP(expansion); - SimpleLogger().Write() << "building r-tree ..."; + util::SimpleLogger().Write() << "building r-tree ..."; TIMER_START(rtree); FindComponents(max_edge_id, edge_based_edge_list, node_based_edge_list); @@ -277,21 +282,21 @@ int extractor::run() TIMER_STOP(rtree); - SimpleLogger().Write() << "writing node map ..."; + util::SimpleLogger().Write() << "writing node map ..."; WriteNodeMapping(internal_to_external_node_map); WriteEdgeBasedGraph(config.edge_graph_output_path, max_edge_id, edge_based_edge_list); - SimpleLogger().Write() << "Expansion : " + util::SimpleLogger().Write() << "Expansion : " << (number_of_node_based_nodes / TIMER_SEC(expansion)) << " nodes/sec and " << ((max_edge_id + 1) / TIMER_SEC(expansion)) << " edges/sec"; - SimpleLogger().Write() << "To prepare the data for routing, run: " + util::SimpleLogger().Write() << "To prepare the data for routing, run: " << "./osrm-prepare " << config.output_file_name << std::endl; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << e.what(); + util::SimpleLogger().Write(logWARNING) << e.what(); return 1; } @@ -309,39 +314,39 @@ void extractor::SetupScriptingEnvironment(lua_State *lua_state, luaL_openlibs(lua_state); // adjust lua load path - luaAddScriptFolderToLoadPath(lua_state, config.profile_path.string().c_str()); + util::luaAddScriptFolderToLoadPath(lua_state, config.profile_path.string().c_str()); // Now call our function in a lua script if (0 != luaL_dofile(lua_state, config.profile_path.string().c_str())) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; - throw osrm::exception(msg.str()); + throw util::exception(msg.str()); } if (0 != luaL_dostring(lua_state, "return traffic_signal_penalty\n")) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; - throw osrm::exception(msg.str()); + throw util::exception(msg.str()); } speed_profile.traffic_signal_penalty = 10 * lua_tointeger(lua_state, -1); - SimpleLogger().Write(logDEBUG) << "traffic_signal_penalty: " + util::SimpleLogger().Write(logDEBUG) << "traffic_signal_penalty: " << speed_profile.traffic_signal_penalty; if (0 != luaL_dostring(lua_state, "return u_turn_penalty\n")) { std::stringstream msg; msg << lua_tostring(lua_state, -1) << " occurred in scripting block"; - throw osrm::exception(msg.str()); + throw util::exception(msg.str()); } speed_profile.u_turn_penalty = 10 * lua_tointeger(lua_state, -1); - speed_profile.has_turn_penalty_function = lua_function_exists(lua_state, "turn_function"); + speed_profile.has_turn_penalty_function = util::lua_function_exists(lua_state, "turn_function"); } void extractor::FindComponents(unsigned max_edge_id, - const DeallocatingVector &input_edge_list, + const util::DeallocatingVector &input_edge_list, std::vector &input_nodes) const { struct UncontractedEdgeData @@ -363,7 +368,7 @@ void extractor::FindComponents(unsigned max_edge_id, return source == rhs.source && target == rhs.target; } }; - using UncontractedGraph = StaticGraph; + using UncontractedGraph = util::StaticGraph; std::vector edges; edges.reserve(input_edge_list.size() * 2); @@ -424,9 +429,9 @@ std::shared_ptr extractor::LoadRestrictionMap() std::ios::in | std::ios::binary); std::vector restriction_list; - loadRestrictionsFromFile(input_stream, restriction_list); + util::loadRestrictionsFromFile(input_stream, restriction_list); - SimpleLogger().Write() << " - " << restriction_list.size() << " restrictions."; + util::SimpleLogger().Write() << " - " << restriction_list.size() << " restrictions."; return std::make_shared(restriction_list); } @@ -434,7 +439,7 @@ std::shared_ptr extractor::LoadRestrictionMap() /** \brief Load node based graph from .osrm file */ -std::shared_ptr +std::shared_ptr extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, std::unordered_set &traffic_lights, std::vector &internal_to_external_node_map) @@ -446,10 +451,10 @@ extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, std::vector barrier_list; std::vector traffic_light_list; - NodeID number_of_node_based_nodes = loadNodesFromFile( + NodeID number_of_node_based_nodes = util::loadNodesFromFile( input_stream, barrier_list, traffic_light_list, internal_to_external_node_map); - SimpleLogger().Write() << " - " << barrier_list.size() << " bollard nodes, " + util::SimpleLogger().Write() << " - " << barrier_list.size() << " bollard nodes, " << traffic_light_list.size() << " traffic lights"; // insert into unordered sets for fast lookup @@ -461,15 +466,15 @@ extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, traffic_light_list.clear(); traffic_light_list.shrink_to_fit(); - loadEdgesFromFile(input_stream, edge_list); + util::loadEdgesFromFile(input_stream, edge_list); if (edge_list.empty()) { - SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; - return std::shared_ptr(); + util::SimpleLogger().Write(logWARNING) << "The input data is empty, exiting."; + return std::shared_ptr(); } - return NodeBasedDynamicGraphFromEdges(number_of_node_based_nodes, edge_list); + return util::NodeBasedDynamicGraphFromEdges(number_of_node_based_nodes, edge_list); } /** @@ -479,7 +484,7 @@ std::pair extractor::BuildEdgeExpandedGraph(std::vector &internal_to_external_node_map, std::vector &node_based_edge_list, std::vector &node_is_startpoint, - DeallocatingVector &edge_based_edge_list) + util::DeallocatingVector &edge_based_edge_list) { lua_State *lua_state = luaL_newstate(); luabind::open(lua_state); @@ -550,7 +555,7 @@ void extractor::BuildRTree(std::vector node_based_edge_list, std::vector node_is_startpoint, const std::vector &internal_to_external_node_map) { - SimpleLogger().Write() << "constructing r-tree of " << node_based_edge_list.size() + util::SimpleLogger().Write() << "constructing r-tree of " << node_based_edge_list.size() << " edge elements build on-top of " << internal_to_external_node_map.size() << " coordinates"; @@ -559,7 +564,7 @@ void extractor::BuildRTree(std::vector node_based_edge_list, // Filter node based edges based on startpoint auto out_iter = node_based_edge_list.begin(); auto in_iter = node_based_edge_list.begin(); - for (auto index : osrm::irange(0, node_is_startpoint.size())) + for (auto index : util::irange(0, node_is_startpoint.size())) { BOOST_ASSERT(in_iter != node_based_edge_list.end()); if (node_is_startpoint[index]) @@ -573,23 +578,23 @@ void extractor::BuildRTree(std::vector node_based_edge_list, node_based_edge_list.resize(new_size); TIMER_START(construction); - StaticRTree rtree(node_based_edge_list, config.rtree_nodes_output_path, + util::StaticRTree rtree(node_based_edge_list, config.rtree_nodes_output_path, config.rtree_leafs_output_path, internal_to_external_node_map); TIMER_STOP(construction); - SimpleLogger().Write() << "finished r-tree construction in " << TIMER_SEC(construction) + util::SimpleLogger().Write() << "finished r-tree construction in " << TIMER_SEC(construction) << " seconds"; } void extractor::WriteEdgeBasedGraph(std::string const &output_file_filename, size_t const max_edge_id, - DeallocatingVector const &edge_based_edge_list) + util::DeallocatingVector const &edge_based_edge_list) { std::ofstream file_out_stream; file_out_stream.open(output_file_filename.c_str(), std::ios::binary); - const FingerPrint fingerprint = FingerPrint::GetValid(); - file_out_stream.write((char *)&fingerprint, sizeof(FingerPrint)); + const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); + file_out_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); std::cout << "[extractor] Writing edge-based-graph egdes ... " << std::flush; TIMER_START(write_edges); @@ -606,6 +611,8 @@ void extractor::WriteEdgeBasedGraph(std::string const &output_file_filename, TIMER_STOP(write_edges); std::cout << "ok, after " << TIMER_SEC(write_edges) << "s" << std::endl; - SimpleLogger().Write() << "Processed " << number_of_used_edges << " edges"; + util::SimpleLogger().Write() << "Processed " << number_of_used_edges << " edges"; file_out_stream.close(); } +} +} diff --git a/src/extractor/extractor_callbacks.cpp b/src/extractor/extractor_callbacks.cpp index 9b740c6dd..03f60134f 100644 --- a/src/extractor/extractor_callbacks.cpp +++ b/src/extractor/extractor_callbacks.cpp @@ -18,6 +18,11 @@ #include #include +namespace osrm +{ +namespace extractor +{ + ExtractorCallbacks::ExtractorCallbacks(ExtractionContainers &extraction_containers) : external_memory(extraction_containers) { @@ -45,7 +50,7 @@ void ExtractorCallbacks::ProcessRestriction( if (restriction) { external_memory.restrictions_list.push_back(restriction.get()); - // SimpleLogger().Write() << "from: " << restriction.get().restriction.from.node << + // util::SimpleLogger().Write() << "from: " << restriction.get().restriction.from.node << // ",via: " << restriction.get().restriction.via.node << // ", to: " << restriction.get().restriction.to.node << // ", only: " << (restriction.get().restriction.flags.is_only ? @@ -79,7 +84,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (std::numeric_limits::max() == input_way.id()) { - SimpleLogger().Write(logDEBUG) << "found bogus way with id: " << input_way.id() + util::SimpleLogger().Write(logDEBUG) << "found bogus way with id: " << input_way.id() << " of size " << input_way.nodes().size(); return; } @@ -118,7 +123,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (forward_weight_data.type == InternalExtractorEdge::WeightType::INVALID && backward_weight_data.type == InternalExtractorEdge::WeightType::INVALID) { - SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << input_way.id(); + util::SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << input_way.id(); return; } @@ -159,7 +164,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti { BOOST_ASSERT(split_edge == false); BOOST_ASSERT(parsed_way.backward_travel_mode != TRAVEL_MODE_INACCESSIBLE); - osrm::for_each_pair(input_way.nodes().crbegin(), input_way.nodes().crend(), + util::for_each_pair(input_way.nodes().crbegin(), input_way.nodes().crend(), [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { external_memory.all_edges_list.push_back(InternalExtractorEdge( @@ -179,7 +184,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti { const bool forward_only = split_edge || TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode; - osrm::for_each_pair(input_way.nodes().cbegin(), input_way.nodes().cend(), + util::for_each_pair(input_way.nodes().cbegin(), input_way.nodes().cend(), [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { external_memory.all_edges_list.push_back(InternalExtractorEdge( @@ -192,7 +197,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (split_edge) { BOOST_ASSERT(parsed_way.backward_travel_mode != TRAVEL_MODE_INACCESSIBLE); - osrm::for_each_pair( + util::for_each_pair( input_way.nodes().cbegin(), input_way.nodes().cend(), [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) { @@ -210,3 +215,5 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti OSMNodeID(input_way.nodes()[1].ref()), OSMNodeID(input_way.nodes()[0].ref())}); } } +} +} diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp index 16bc3de53..90d9ee8e3 100644 --- a/src/extractor/extractor_options.cpp +++ b/src/extractor/extractor_options.cpp @@ -9,6 +9,11 @@ #include +namespace osrm +{ +namespace extractor +{ + return_code ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extractor_config) { @@ -87,13 +92,13 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac option_variables); if (option_variables.count("version")) { - SimpleLogger().Write() << OSRM_VERSION; + util::SimpleLogger().Write() << OSRM_VERSION; return return_code::exit; } if (option_variables.count("help")) { - SimpleLogger().Write() << visible_options; + util::SimpleLogger().Write() << visible_options; return return_code::exit; } @@ -102,10 +107,10 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac // parse config file if (boost::filesystem::is_regular_file(extractor_config.config_file_path)) { - SimpleLogger().Write() << "Reading options from: " + util::SimpleLogger().Write() << "Reading options from: " << extractor_config.config_file_path.string(); std::string ini_file_contents = - read_file_lower_content(extractor_config.config_file_path); + util::read_file_lower_content(extractor_config.config_file_path); std::stringstream config_stream(ini_file_contents); boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables); @@ -114,13 +119,13 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac if (!option_variables.count("input")) { - SimpleLogger().Write() << visible_options; + util::SimpleLogger().Write() << visible_options; return return_code::exit; } } catch (std::exception &e) { - SimpleLogger().Write(logWARNING) << e.what(); + util::SimpleLogger().Write(logWARNING) << e.what(); return return_code::fail; } @@ -205,3 +210,5 @@ void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_confi extractor_config.edge_penalty_path.replace(pos, 8, ".osrm.edge_penalties"); } } +} +} diff --git a/src/extractor/graph_compressor.cpp b/src/extractor/graph_compressor.cpp index 751c10eb0..ec02fdc57 100644 --- a/src/extractor/graph_compressor.cpp +++ b/src/extractor/graph_compressor.cpp @@ -8,6 +8,11 @@ #include "util/simple_logger.hpp" +namespace osrm +{ +namespace extractor +{ + GraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile) : speed_profile(std::move(speed_profile)) { @@ -16,15 +21,15 @@ GraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile) void GraphCompressor::Compress(const std::unordered_set &barrier_nodes, const std::unordered_set &traffic_lights, RestrictionMap &restriction_map, - NodeBasedDynamicGraph &graph, + util::NodeBasedDynamicGraph &graph, CompressedEdgeContainer &geometry_compressor) { const unsigned original_number_of_nodes = graph.GetNumberOfNodes(); const unsigned original_number_of_edges = graph.GetNumberOfEdges(); - Percent progress(original_number_of_nodes); + util::Percent progress(original_number_of_nodes); - for (const NodeID node_v : osrm::irange(0u, original_number_of_nodes)) + for (const NodeID node_v : util::irange(0u, original_number_of_nodes)) { progress.printStatus(node_v); @@ -163,13 +168,13 @@ void GraphCompressor::Compress(const std::unordered_set &barrier_nodes, void GraphCompressor::PrintStatistics(unsigned original_number_of_nodes, unsigned original_number_of_edges, - const NodeBasedDynamicGraph &graph) const + const util::NodeBasedDynamicGraph &graph) const { unsigned new_node_count = 0; unsigned new_edge_count = 0; - for (const auto i : osrm::irange(0u, graph.GetNumberOfNodes())) + for (const auto i : util::irange(0u, graph.GetNumberOfNodes())) { if (graph.GetOutDegree(i) > 0) { @@ -177,8 +182,10 @@ void GraphCompressor::PrintStatistics(unsigned original_number_of_nodes, new_edge_count += (graph.EndEdges(i) - graph.BeginEdges(i)); } } - SimpleLogger().Write() << "Node compression ratio: " + util::SimpleLogger().Write() << "Node compression ratio: " << new_node_count / (double)original_number_of_nodes; - SimpleLogger().Write() << "Edge compression ratio: " + util::SimpleLogger().Write() << "Edge compression ratio: " << new_edge_count / (double)original_number_of_edges; } +} +} diff --git a/src/extractor/import_edge.cpp b/src/extractor/import_edge.cpp index 999559219..b3b6b612d 100644 --- a/src/extractor/import_edge.cpp +++ b/src/extractor/import_edge.cpp @@ -3,6 +3,11 @@ #include "extractor/travel_mode.hpp" #include "util/typedefs.hpp" +namespace osrm +{ +namespace extractor +{ + bool NodeBasedEdge::operator<(const NodeBasedEdge &other) const { if (source == other.source) @@ -84,3 +89,5 @@ EdgeBasedEdge::EdgeBasedEdge(const NodeID source, backward(backward) { } +} +} diff --git a/src/extractor/raster_source.cpp b/src/extractor/raster_source.cpp index 3c9abb16f..840e79449 100644 --- a/src/extractor/raster_source.cpp +++ b/src/extractor/raster_source.cpp @@ -7,6 +7,11 @@ #include +namespace osrm +{ +namespace extractor +{ + RasterSource::RasterSource(RasterGrid _raster_data, std::size_t _width, std::size_t _height, @@ -87,20 +92,20 @@ int SourceContainer::loadRasterSource(const std::string &path_string, const auto itr = LoadedSourcePaths.find(path_string); if (itr != LoadedSourcePaths.end()) { - SimpleLogger().Write() << "[source loader] Already loaded source '" << path_string + util::SimpleLogger().Write() << "[source loader] Already loaded source '" << path_string << "' at source_id " << itr->second; return itr->second; } int source_id = static_cast(LoadedSources.size()); - SimpleLogger().Write() << "[source loader] Loading from " << path_string << " ... "; + util::SimpleLogger().Write() << "[source loader] Loading from " << path_string << " ... "; TIMER_START(loading_source); boost::filesystem::path filepath(path_string); if (!boost::filesystem::exists(filepath)) { - throw osrm::exception("error reading: no such path"); + throw util::exception("error reading: no such path"); } RasterGrid rasterData{filepath, ncols, nrows}; @@ -110,7 +115,7 @@ int SourceContainer::loadRasterSource(const std::string &path_string, LoadedSourcePaths.emplace(path_string, source_id); LoadedSources.push_back(std::move(source)); - SimpleLogger().Write() << "[source loader] ok, after " << TIMER_SEC(loading_source) << "s"; + util::SimpleLogger().Write() << "[source loader] ok, after " << TIMER_SEC(loading_source) << "s"; return source_id; } @@ -120,7 +125,7 @@ RasterDatum SourceContainer::getRasterDataFromSource(unsigned int source_id, int { if (LoadedSources.size() < source_id + 1) { - throw osrm::exception("error reading: no such loaded source"); + throw util::exception("error reading: no such loaded source"); } BOOST_ASSERT(lat < (90 * COORDINATE_PRECISION)); @@ -138,7 +143,7 @@ SourceContainer::getRasterInterpolateFromSource(unsigned int source_id, int lon, { if (LoadedSources.size() < source_id + 1) { - throw osrm::exception("error reading: no such loaded source"); + throw util::exception("error reading: no such loaded source"); } BOOST_ASSERT(lat < (90 * COORDINATE_PRECISION)); @@ -149,3 +154,5 @@ SourceContainer::getRasterInterpolateFromSource(unsigned int source_id, int lon, const auto &found = LoadedSources[source_id]; return found.getRasterInterpolate(lon, lat); } +} +} diff --git a/src/extractor/restriction_map.cpp b/src/extractor/restriction_map.cpp index f5f84446e..d41b1c497 100644 --- a/src/extractor/restriction_map.cpp +++ b/src/extractor/restriction_map.cpp @@ -1,5 +1,10 @@ #include "extractor/restriction_map.hpp" +namespace osrm +{ +namespace extractor +{ + RestrictionMap::RestrictionMap(const std::vector &restriction_list) : m_count(0) { // decompose restriction consisting of a start, via and end node into a @@ -152,3 +157,5 @@ bool RestrictionMap::IsSourceNode(const NodeID node) const { return m_restriction_start_nodes.find(node) != m_restriction_start_nodes.end(); } +} +} diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index bb631894c..2c3641a4c 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -19,11 +19,16 @@ #include #include +namespace osrm +{ +namespace extractor +{ + namespace { int luaErrorCallback(lua_State *lua_state) { std::string error_msg = lua_tostring(lua_state, -1); - throw osrm::exception("ERROR occurred in profile script:\n" + error_msg); + throw util::exception("ERROR occurred in profile script:\n" + error_msg); } } @@ -47,33 +52,33 @@ void RestrictionParser::ReadUseRestrictionsSetting(lua_State *lua_state) if (use_turn_restrictions) { - SimpleLogger().Write() << "Using turn restrictions"; + util::SimpleLogger().Write() << "Using turn restrictions"; } else { - SimpleLogger().Write() << "Ignoring turn restrictions"; + util::SimpleLogger().Write() << "Ignoring turn restrictions"; } } void RestrictionParser::ReadRestrictionExceptions(lua_State *lua_state) { - if (lua_function_exists(lua_state, "get_exceptions")) + if (util::lua_function_exists(lua_state, "get_exceptions")) { luabind::set_pcall_callback(&luaErrorCallback); // get list of turn restriction exceptions luabind::call_function(lua_state, "get_exceptions", boost::ref(restriction_exceptions)); const unsigned exception_count = restriction_exceptions.size(); - SimpleLogger().Write() << "Found " << exception_count + util::SimpleLogger().Write() << "Found " << exception_count << " exceptions to turn restrictions:"; for (const std::string &str : restriction_exceptions) { - SimpleLogger().Write() << " " << str; + util::SimpleLogger().Write() << " " << str; } } else { - SimpleLogger().Write() << "Found no exceptions to turn restrictions"; + util::SimpleLogger().Write() << "Found no exceptions to turn restrictions"; } } @@ -222,3 +227,5 @@ bool RestrictionParser::ShouldIgnoreRestriction(const std::string &except_tag_st std::end(restriction_exceptions), current_string); }); } +} +} diff --git a/src/extractor/scripting_environment.cpp b/src/extractor/scripting_environment.cpp index f4fae0da3..247291f74 100644 --- a/src/extractor/scripting_environment.cpp +++ b/src/extractor/scripting_environment.cpp @@ -17,6 +17,11 @@ #include #include + +namespace osrm +{ +namespace extractor +{ namespace { // wrapper method as luabind doesn't automatically overload funcs w/ default parameters @@ -32,13 +37,13 @@ int luaErrorCallback(lua_State *state) std::string error_msg = lua_tostring(state, -1); std::ostringstream error_stream; error_stream << error_msg; - throw osrm::exception("ERROR occurred in profile script:\n" + error_stream.str()); + throw util::exception("ERROR occurred in profile script:\n" + error_stream.str()); } } ScriptingEnvironment::ScriptingEnvironment(const std::string &file_name) : file_name(file_name) { - SimpleLogger().Write() << "Using script " << file_name; + util::SimpleLogger().Write() << "Using script " << file_name; } void ScriptingEnvironment::InitLuaState(lua_State *lua_state) @@ -49,11 +54,11 @@ void ScriptingEnvironment::InitLuaState(lua_State *lua_state) // open utility libraries string library; luaL_openlibs(lua_state); - luaAddScriptFolderToLoadPath(lua_state, file_name.c_str()); + util::luaAddScriptFolderToLoadPath(lua_state, file_name.c_str()); // Add our function to the state's global scope luabind::module(lua_state) - [luabind::def("print", LUA_print), + [luabind::def("print", util::LUA_print), luabind::def("durationIsValid", durationIsValid), luabind::def("parseDuration", parseDuration), luabind::class_("sources") @@ -110,9 +115,9 @@ void ScriptingEnvironment::InitLuaState(lua_State *lua_state) luabind::class_("EdgeTarget") .property("lat", &ExternalMemoryNode::lat) .property("lon", &ExternalMemoryNode::lon), - luabind::class_("Coordinate") - .property("lat", &FixedPointCoordinate::lat) - .property("lon", &FixedPointCoordinate::lon), + luabind::class_("Coordinate") + .property("lat", &util::FixedPointCoordinate::lat) + .property("lon", &util::FixedPointCoordinate::lon), luabind::class_("RasterDatum") .property("datum", &RasterDatum::datum) .def("invalid_data", &RasterDatum::get_invalid)]; @@ -122,7 +127,7 @@ void ScriptingEnvironment::InitLuaState(lua_State *lua_state) luabind::object error_msg(luabind::from_stack(lua_state, -1)); std::ostringstream error_stream; error_stream << error_msg; - throw osrm::exception("ERROR occurred in profile script:\n" + error_stream.str()); + throw util::exception("ERROR occurred in profile script:\n" + error_stream.str()); } } @@ -141,3 +146,5 @@ lua_State *ScriptingEnvironment::GetLuaState() return ref.get(); } +} +} diff --git a/src/server/connection.cpp b/src/server/connection.cpp index 0a93e18af..58718a050 100644 --- a/src/server/connection.cpp +++ b/src/server/connection.cpp @@ -10,7 +10,9 @@ #include #include -namespace http +namespace osrm +{ +namespace server { Connection::Connection(boost::asio::io_service &io_service, RequestHandler &handler) @@ -38,14 +40,14 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t } // no error detected, let's parse the request - compression_type compression_type(no_compression); - osrm::tribool result; + http::compression_type compression_type(http::no_compression); + util::tribool result; std::tie(result, compression_type) = request_parser.parse(current_request, incoming_data_buffer.data(), incoming_data_buffer.data() + bytes_transferred); // the request has been parsed - if (result == osrm::tribool::yes) + if (result == util::tribool::yes) { current_request.endpoint = TCP_socket.remote_endpoint().address(); request_handler.handle_request(current_request, current_reply); @@ -56,7 +58,7 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t // compress the result w/ gzip/deflate if requested switch (compression_type) { - case deflate_rfc1951: + case http::deflate_rfc1951: // use deflate for compression current_reply.headers.insert(current_reply.headers.begin(), {"Content-Encoding", "deflate"}); @@ -65,7 +67,7 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t output_buffer = current_reply.headers_to_buffers(); output_buffer.push_back(boost::asio::buffer(compressed_output)); break; - case gzip_rfc1952: + case http::gzip_rfc1952: // use gzip for compression current_reply.headers.insert(current_reply.headers.begin(), {"Content-Encoding", "gzip"}); @@ -74,7 +76,7 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t output_buffer = current_reply.headers_to_buffers(); output_buffer.push_back(boost::asio::buffer(compressed_output)); break; - case no_compression: + case http::no_compression: // don't use any compression current_reply.set_uncompressed_size(); output_buffer = current_reply.to_buffers(); @@ -86,9 +88,9 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t strand.wrap(boost::bind(&Connection::handle_write, this->shared_from_this(), boost::asio::placeholders::error))); } - else if (result == osrm::tribool::no) + else if (result == util::tribool::no) { // request is not parseable - current_reply = reply::stock_reply(reply::bad_request); + current_reply = http::reply::stock_reply(http::reply::bad_request); boost::asio::async_write( TCP_socket, current_reply.to_buffers(), @@ -118,14 +120,14 @@ void Connection::handle_write(const boost::system::error_code &error) } std::vector Connection::compress_buffers(const std::vector &uncompressed_data, - const compression_type compression_type) + const http::compression_type compression_type) { boost::iostreams::gzip_params compression_parameters; // there's a trade-off between speed and size. speed wins compression_parameters.level = boost::iostreams::zlib::best_speed; // check which compression flavor is used - if (deflate_rfc1951 == compression_type) + if (http::deflate_rfc1951 == compression_type) { compression_parameters.noheader = true; } @@ -141,3 +143,4 @@ std::vector Connection::compress_buffers(const std::vector &uncompre return compressed_data; } } +} diff --git a/src/server/http/reply.cpp b/src/server/http/reply.cpp index be6e3bfbc..87faa1ba1 100644 --- a/src/server/http/reply.cpp +++ b/src/server/http/reply.cpp @@ -2,6 +2,10 @@ #include +namespace osrm +{ +namespace server +{ namespace http { @@ -101,3 +105,5 @@ boost::asio::const_buffer reply::status_to_buffer(const reply::status_type statu reply::reply() : status(ok) {} } +} +} diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index 00d1d8f23..a579a039d 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -20,22 +20,27 @@ #include #include +namespace osrm +{ +namespace server +{ + RequestHandler::RequestHandler() : routing_machine(nullptr) {} void RequestHandler::handle_request(const http::request ¤t_request, http::reply ¤t_reply) { - osrm::json::Object json_result; + util::json::Object json_result; // parse command try { std::string request_string; - URIDecode(current_request.uri, request_string); + util::URIDecode(current_request.uri, request_string); // deactivated as GCC apparently does not implement that, not even in 4.9 // std::time_t t = std::time(nullptr); - // SimpleLogger().Write() << std::put_time(std::localtime(&t), "%m-%d-%Y %H:%M:%S") << + // util::SimpleLogger().Write() << std::put_time(std::localtime(&t), "%m-%d-%Y %H:%M:%S") << // " " << current_request.endpoint.to_string() << " " << // current_request.referrer << ( 0 == current_request.referrer.length() ? "- " :" ") << // current_request.agent << ( 0 == current_request.agent.length() ? "- " :" ") << @@ -48,7 +53,7 @@ void RequestHandler::handle_request(const http::request ¤t_request, time_stamp = localtime(<ime); // log timestamp - SimpleLogger().Write() << (time_stamp->tm_mday < 10 ? "0" : "") << time_stamp->tm_mday + util::SimpleLogger().Write() << (time_stamp->tm_mday < 10 ? "0" : "") << time_stamp->tm_mday << "-" << (time_stamp->tm_mon + 1 < 10 ? "0" : "") << (time_stamp->tm_mon + 1) << "-" << 1900 + time_stamp->tm_year << " " << (time_stamp->tm_hour < 10 ? "0" : "") @@ -61,7 +66,7 @@ void RequestHandler::handle_request(const http::request ¤t_request, << (0 == current_request.agent.length() ? "- " : " ") << request_string; - RouteParameters route_parameters; + engine::RouteParameters route_parameters; APIGrammarParser api_parser(&route_parameters); auto api_iterator = request_string.begin(); @@ -116,7 +121,7 @@ void RequestHandler::handle_request(const http::request ¤t_request, std::to_string(current_reply.content.size())); if ("gpx" == route_parameters.output_format) { // gpx file - osrm::json::gpx_render(current_reply.content, json_result.values["route"]); + util::json::gpx_render(current_reply.content, json_result.values["route"]); current_reply.headers.emplace_back("Content-Type", "application/gpx+xml; charset=UTF-8"); current_reply.headers.emplace_back("Content-Disposition", @@ -124,14 +129,14 @@ void RequestHandler::handle_request(const http::request ¤t_request, } else if (route_parameters.jsonp_parameter.empty()) { // json file - osrm::json::render(current_reply.content, json_result); + util::json::render(current_reply.content, json_result); current_reply.headers.emplace_back("Content-Type", "application/json; charset=UTF-8"); current_reply.headers.emplace_back("Content-Disposition", "inline; filename=\"response.json\""); } else { // jsonp - osrm::json::render(current_reply.content, json_result); + util::json::render(current_reply.content, json_result); current_reply.headers.emplace_back("Content-Type", "text/javascript; charset=UTF-8"); current_reply.headers.emplace_back("Content-Disposition", "inline; filename=\"response.js\""); @@ -145,9 +150,11 @@ void RequestHandler::handle_request(const http::request ¤t_request, { current_reply = http::reply::stock_reply(http::reply::internal_server_error); ; - SimpleLogger().Write(logWARNING) << "[server error] code: " << e.what() + util::SimpleLogger().Write(logWARNING) << "[server error] code: " << e.what() << ", uri: " << current_request.uri; } } void RequestHandler::RegisterRoutingMachine(OSRM *osrm) { routing_machine = osrm; } +} +} diff --git a/src/server/request_parser.cpp b/src/server/request_parser.cpp index 818ed44b3..3d6149d06 100644 --- a/src/server/request_parser.cpp +++ b/src/server/request_parser.cpp @@ -10,197 +10,199 @@ #include -namespace http +namespace osrm +{ +namespace server { RequestParser::RequestParser() : state(internal_state::method_start), current_header({"", ""}), - selected_compression(no_compression), is_post_header(false), content_length(0) + selected_compression(http::no_compression), is_post_header(false), content_length(0) { } -std::tuple -RequestParser::parse(request ¤t_request, char *begin, char *end) +std::tuple +RequestParser::parse(http::request ¤t_request, char *begin, char *end) { while (begin != end) { - osrm::tribool result = consume(current_request, *begin++); - if (result != osrm::tribool::indeterminate) + util::tribool result = consume(current_request, *begin++); + if (result != util::tribool::indeterminate) { return std::make_tuple(result, selected_compression); } } - osrm::tribool result = osrm::tribool::indeterminate; + util::tribool result = util::tribool::indeterminate; if (state == internal_state::post_request && content_length <= 0) { - result = osrm::tribool::yes; + result = util::tribool::yes; } return std::make_tuple(result, selected_compression); } -osrm::tribool RequestParser::consume(request ¤t_request, const char input) +util::tribool RequestParser::consume(http::request ¤t_request, const char input) { switch (state) { case internal_state::method_start: if (!is_char(input) || is_CTL(input) || is_special(input)) { - return osrm::tribool::no; + return util::tribool::no; } if (input == 'P') { state = internal_state::post_O; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } state = internal_state::method; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::post_O: if (input == 'O') { state = internal_state::post_S; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::post_S: if (input == 'S') { state = internal_state::post_T; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::post_T: if (input == 'T') { is_post_header = true; state = internal_state::method; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::post_request: current_request.uri.push_back(input); --content_length; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::method: if (input == ' ') { state = internal_state::uri; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return osrm::tribool::no; + return util::tribool::no; } - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::uri_start: if (is_CTL(input)) { - return osrm::tribool::no; + return util::tribool::no; } state = internal_state::uri; current_request.uri.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::uri: if (input == ' ') { state = internal_state::http_version_h; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_CTL(input)) { - return osrm::tribool::no; + return util::tribool::no; } current_request.uri.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::http_version_h: if (input == 'H') { state = internal_state::http_version_t_1; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_t_1: if (input == 'T') { state = internal_state::http_version_t_2; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_t_2: if (input == 'T') { state = internal_state::http_version_p; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_p: if (input == 'P') { state = internal_state::http_version_slash; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_slash: if (input == '/') { state = internal_state::http_version_major_start; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_major_start: if (is_digit(input)) { state = internal_state::http_version_major; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_major: if (input == '.') { state = internal_state::http_version_minor_start; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_digit(input)) { - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_minor_start: if (is_digit(input)) { state = internal_state::http_version_minor; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::http_version_minor: if (input == '\r') { state = internal_state::expecting_newline_1; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_digit(input)) { - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::expecting_newline_1: if (input == '\n') { state = internal_state::header_line_start; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::header_line_start: if (boost::iequals(current_header.name, "Accept-Encoding")) { /* giving gzip precedence over deflate */ if (boost::icontains(current_header.value, "deflate")) { - selected_compression = deflate_rfc1951; + selected_compression = http::deflate_rfc1951; } if (boost::icontains(current_header.value, "gzip")) { - selected_compression = gzip_rfc1952; + selected_compression = http::gzip_rfc1952; } } @@ -228,77 +230,77 @@ osrm::tribool RequestParser::consume(request ¤t_request, const char input) { if (!boost::icontains(current_header.value, "application/x-www-form-urlencoded")) { - return osrm::tribool::no; + return util::tribool::no; } } if (input == '\r') { state = internal_state::expecting_newline_3; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return osrm::tribool::no; + return util::tribool::no; } state = internal_state::header_name; current_header.clear(); current_header.name.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::header_lws: if (input == '\r') { state = internal_state::expecting_newline_2; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (input == ' ' || input == '\t') { - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_CTL(input)) { - return osrm::tribool::no; + return util::tribool::no; } state = internal_state::header_value; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::header_name: if (input == ':') { state = internal_state::space_before_header_value; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return osrm::tribool::no; + return util::tribool::no; } current_header.name.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::space_before_header_value: if (input == ' ') { state = internal_state::header_value; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::header_value: if (input == '\r') { state = internal_state::expecting_newline_2; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } if (is_CTL(input)) { - return osrm::tribool::no; + return util::tribool::no; } current_header.value.push_back(input); - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; case internal_state::expecting_newline_2: if (input == '\n') { state = internal_state::header_line_start; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::no; + return util::tribool::no; case internal_state::expecting_newline_3: if (input == '\n') { @@ -309,13 +311,13 @@ osrm::tribool RequestParser::consume(request ¤t_request, const char input) current_request.uri.push_back('?'); } state = internal_state::post_request; - return osrm::tribool::indeterminate; + return util::tribool::indeterminate; } - return osrm::tribool::yes; + return util::tribool::yes; } - return osrm::tribool::no; + return util::tribool::no; default: // should never be reached - return input == '\n' ? osrm::tribool::yes : osrm::tribool::no; + return input == '\n' ? util::tribool::yes : util::tribool::no; } } @@ -363,3 +365,4 @@ bool RequestParser::is_digit(const int character) const return character >= '0' && character <= '9'; } } +} diff --git a/src/tools/check-hsgr.cpp b/src/tools/check-hsgr.cpp index 068e4b392..4c6b3deb1 100644 --- a/src/tools/check-hsgr.cpp +++ b/src/tools/check-hsgr.cpp @@ -12,45 +12,53 @@ #include #include -using EdgeData = QueryEdge::EdgeData; -using QueryGraph = StaticGraph; +namespace osrm +{ +namespace tools +{ + +using EdgeData = contractor::QueryEdge::EdgeData; +using QueryGraph = util::StaticGraph; + +} +} int main(int argc, char *argv[]) { - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { if (argc != 2) { - SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " "; + osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " "; return 1; } boost::filesystem::path hsgr_path(argv[1]); - std::vector node_list; - std::vector edge_list; - SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); + std::vector node_list; + std::vector edge_list; + osrm::util::SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); unsigned m_check_sum = 0; unsigned m_number_of_nodes = readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); - SimpleLogger().Write() << "expecting " << m_number_of_nodes + osrm::util::SimpleLogger().Write() << "expecting " << m_number_of_nodes << " nodes, checksum: " << m_check_sum; BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); - SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() + osrm::util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() << " edges"; - auto m_query_graph = std::make_shared(node_list, edge_list); + auto m_query_graph = std::make_shared(node_list, edge_list); BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); BOOST_ASSERT_MSG(0 == edge_list.size(), "edge list not flushed"); - Percent progress(m_query_graph->GetNumberOfNodes()); - for (const auto node_u : osrm::irange(0u, m_query_graph->GetNumberOfNodes())) + osrm::util::Percent progress(m_query_graph->GetNumberOfNodes()); + for (const auto node_u : osrm::util::irange(0u, m_query_graph->GetNumberOfNodes())) { for (const auto eid : m_query_graph->GetAdjacentEdgeRange(node_u)) { - const EdgeData &data = m_query_graph->GetEdgeData(eid); + const osrm::tools::EdgeData &data = m_query_graph->GetEdgeData(eid); if (!data.shortcut) { continue; @@ -59,7 +67,7 @@ int main(int argc, char *argv[]) const EdgeID edge_id_1 = m_query_graph->FindEdgeInEitherDirection(node_u, data.id); if (SPECIAL_EDGEID == edge_id_1) { - throw osrm::exception("cannot find first segment of edge (" + + throw osrm::util::exception("cannot find first segment of edge (" + std::to_string(node_u) + "," + std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + std::to_string(eid)); @@ -67,7 +75,7 @@ int main(int argc, char *argv[]) const EdgeID edge_id_2 = m_query_graph->FindEdgeInEitherDirection(data.id, node_v); if (SPECIAL_EDGEID == edge_id_2) { - throw osrm::exception("cannot find second segment of edge (" + + throw osrm::util::exception("cannot find second segment of edge (" + std::to_string(node_u) + "," + std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + std::to_string(eid)); @@ -76,11 +84,11 @@ int main(int argc, char *argv[]) progress.printStatus(node_u); } m_query_graph.reset(); - SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK"; + osrm::util::SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK"; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); } return 0; } diff --git a/src/tools/components.cpp b/src/tools/components.cpp index 411fca66d..ffefa984f 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -26,7 +26,9 @@ #include #include -namespace +namespace osrm +{ +namespace tools { struct TarjanEdgeData @@ -37,7 +39,7 @@ struct TarjanEdgeData unsigned name_id; }; -using TarjanGraph = StaticGraph; +using TarjanGraph = util::StaticGraph; using TarjanEdge = TarjanGraph::InputEdge; void deleteFileIfExists(const std::string &file_name) @@ -47,27 +49,26 @@ void deleteFileIfExists(const std::string &file_name) boost::filesystem::remove(file_name); } } -} std::size_t loadGraph(const char *path, - std::vector &coordinate_list, + std::vector &coordinate_list, std::vector &graph_edge_list) { std::ifstream input_stream(path, std::ifstream::in | std::ifstream::binary); if (!input_stream.is_open()) { - throw osrm::exception("Cannot open osrm file"); + throw util::exception("Cannot open osrm file"); } // load graph data - std::vector edge_list; + std::vector edge_list; std::vector traffic_light_node_list; std::vector barrier_node_list; - auto number_of_nodes = loadNodesFromFile(input_stream, barrier_node_list, + auto number_of_nodes = util::loadNodesFromFile(input_stream, barrier_node_list, traffic_light_node_list, coordinate_list); - loadEdgesFromFile(input_stream, edge_list); + util::loadEdgesFromFile(input_stream, edge_list); traffic_light_node_list.clear(); traffic_light_node_list.shrink_to_fit(); @@ -94,46 +95,48 @@ std::size_t loadGraph(const char *path, return number_of_nodes; } +} +} int main(int argc, char *argv[]) { - std::vector coordinate_list; + std::vector coordinate_list; - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { // enable logging if (argc < 2) { - SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " "; + osrm::util::SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " "; return -1; } - std::vector graph_edge_list; - auto number_of_nodes = loadGraph(argv[1], coordinate_list, graph_edge_list); + std::vector graph_edge_list; + auto number_of_nodes = osrm::tools::loadGraph(argv[1], coordinate_list, graph_edge_list); tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); - const auto graph = std::make_shared(number_of_nodes, graph_edge_list); + const auto graph = std::make_shared(number_of_nodes, graph_edge_list); graph_edge_list.clear(); graph_edge_list.shrink_to_fit(); - SimpleLogger().Write() << "Starting SCC graph traversal"; + osrm::util::SimpleLogger().Write() << "Starting SCC graph traversal"; - auto tarjan = osrm::make_unique>(graph); + auto tarjan = osrm::util::make_unique>(graph); tarjan->run(); - SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() + osrm::util::SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() << " many components"; - SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs"; + osrm::util::SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs"; // output TIMER_START(SCC_RUN_SETUP); // remove files from previous run if exist - deleteFileIfExists("component.dbf"); - deleteFileIfExists("component.shx"); - deleteFileIfExists("component.shp"); + osrm::tools::deleteFileIfExists("component.dbf"); + osrm::tools::deleteFileIfExists("component.shx"); + osrm::tools::deleteFileIfExists("component.shp"); - Percent percentage(graph->GetNumberOfNodes()); + osrm::util::Percent percentage(graph->GetNumberOfNodes()); OGRRegisterAll(); @@ -142,13 +145,13 @@ int main(int argc, char *argv[]) OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(psz_driver_name); if (nullptr == po_driver) { - throw osrm::exception("ESRI Shapefile driver not available"); + throw osrm::util::exception("ESRI Shapefile driver not available"); } auto *po_datasource = po_driver->CreateDataSource("component.shp", nullptr); if (nullptr == po_datasource) { - throw osrm::exception("Creation of output file failed"); + throw osrm::util::exception("Creation of output file failed"); } auto *po_srs = new OGRSpatialReference(); @@ -158,26 +161,26 @@ int main(int argc, char *argv[]) if (nullptr == po_layer) { - throw osrm::exception("Layer creation failed."); + throw osrm::util::exception("Layer creation failed."); } TIMER_STOP(SCC_RUN_SETUP); - SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000. + osrm::util::SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000. << "s"; uint64_t total_network_length = 0; percentage.reinit(graph->GetNumberOfNodes()); TIMER_START(SCC_OUTPUT); - for (const NodeID source : osrm::irange(0u, graph->GetNumberOfNodes())) + for (const NodeID source : osrm::util::irange(0u, graph->GetNumberOfNodes())) { percentage.printIncrement(); for (const auto current_edge : graph->GetAdjacentEdgeRange(source)) { - const TarjanGraph::NodeIterator target = graph->GetTarget(current_edge); + const auto target = graph->GetTarget(current_edge); if (source < target || SPECIAL_EDGEID == graph->FindEdge(target, source)) { total_network_length += - 100 * coordinate_calculation::greatCircleDistance( + 100 * osrm::util::coordinate_calculation::greatCircleDistance( coordinate_list[source].lat, coordinate_list[source].lon, coordinate_list[target].lat, coordinate_list[target].lon); @@ -193,17 +196,17 @@ int main(int argc, char *argv[]) if (size_of_containing_component < 1000) { OGRLineString line_string; - line_string.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION, - coordinate_list[source].lat / COORDINATE_PRECISION); - line_string.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION, - coordinate_list[target].lat / COORDINATE_PRECISION); + line_string.addPoint(coordinate_list[source].lon / osrm::COORDINATE_PRECISION, + coordinate_list[source].lat / osrm::COORDINATE_PRECISION); + line_string.addPoint(coordinate_list[target].lon / osrm::COORDINATE_PRECISION, + coordinate_list[target].lat / osrm::COORDINATE_PRECISION); OGRFeature *po_feature = OGRFeature::CreateFeature(po_layer->GetLayerDefn()); po_feature->SetGeometry(&line_string); if (OGRERR_NONE != po_layer->CreateFeature(po_feature)) { - throw osrm::exception("Failed to create feature in shapefile."); + throw osrm::util::exception("Failed to create feature in shapefile."); } OGRFeature::DestroyFeature(po_feature); } @@ -213,18 +216,18 @@ int main(int argc, char *argv[]) OGRSpatialReference::DestroySpatialReference(po_srs); OGRDataSource::DestroyDataSource(po_datasource); TIMER_STOP(SCC_OUTPUT); - SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. + osrm::util::SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. << "s"; - SimpleLogger().Write() << "total network distance: " + osrm::util::SimpleLogger().Write() << "total network distance: " << static_cast(total_network_length / 100 / 1000.) << " km"; - SimpleLogger().Write() << "finished component analysis"; + osrm::util::SimpleLogger().Write() << "finished component analysis"; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); } return 0; } diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index f5f994bcb..151965281 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -11,28 +11,30 @@ #include #include +using namespace osrm; + int main(int argc, char *argv[]) try { - LogPolicy::GetInstance().Unmute(); - ContractorConfig contractor_config; + util::LogPolicy::GetInstance().Unmute(); + contractor::ContractorConfig contractor_config; - const return_code result = ContractorOptions::ParseArguments(argc, argv, contractor_config); + const contractor::return_code result = contractor::ContractorOptions::ParseArguments(argc, argv, contractor_config); - if (return_code::fail == result) + if (contractor::return_code::fail == result) { return EXIT_FAILURE; } - if (return_code::exit == result) + if (contractor::return_code::exit == result) { return EXIT_SUCCESS; } - ContractorOptions::GenerateOutputFilesNames(contractor_config); + contractor::ContractorOptions::GenerateOutputFilesNames(contractor_config); if (1 > contractor_config.requested_num_threads) { - SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; + util::SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; return EXIT_FAILURE; } @@ -40,43 +42,43 @@ int main(int argc, char *argv[]) try if (recommended_num_threads != contractor_config.requested_num_threads) { - SimpleLogger().Write(logWARNING) << "The recommended number of threads is " + util::SimpleLogger().Write(logWARNING) << "The recommended number of threads is " << recommended_num_threads << "! This setting may have performance side-effects."; } if (!boost::filesystem::is_regular_file(contractor_config.osrm_input_path)) { - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "Input file " << contractor_config.osrm_input_path.string() << " not found!"; return EXIT_FAILURE; } if (!boost::filesystem::is_regular_file(contractor_config.profile_path)) { - SimpleLogger().Write(logWARNING) << "Profile " << contractor_config.profile_path.string() + util::SimpleLogger().Write(logWARNING) << "Profile " << contractor_config.profile_path.string() << " not found!"; return EXIT_FAILURE; } - SimpleLogger().Write() << "Input file: " + util::SimpleLogger().Write() << "Input file: " << contractor_config.osrm_input_path.filename().string(); - SimpleLogger().Write() << "Profile: " << contractor_config.profile_path.filename().string(); - SimpleLogger().Write() << "Threads: " << contractor_config.requested_num_threads; + util::SimpleLogger().Write() << "Profile: " << contractor_config.profile_path.filename().string(); + util::SimpleLogger().Write() << "Threads: " << contractor_config.requested_num_threads; tbb::task_scheduler_init init(contractor_config.requested_num_threads); - return Prepare(contractor_config).Run(); + return contractor::Prepare(contractor_config).Run(); } catch (const std::bad_alloc &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "Please provide more memory or consider using a larger swapfile"; return EXIT_FAILURE; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); return EXIT_FAILURE; } diff --git a/src/tools/datastore.cpp b/src/tools/datastore.cpp index 899fba4c7..b459465f2 100644 --- a/src/tools/datastore.cpp +++ b/src/tools/datastore.cpp @@ -19,10 +19,6 @@ #include "osrm/coordinate.hpp" -using RTreeLeaf = BaseDataFacade::RTreeLeaf; -using RTreeNode = StaticRTree::vector, true>::TreeNode; -using QueryGraph = StaticGraph; - #ifdef __linux__ #include #endif @@ -36,6 +32,20 @@ using QueryGraph = StaticGraph; #include #include +// FIXME remove after move to datastore +using namespace osrm::engine::datafacade; +using namespace osrm::datastore; +using namespace osrm; + +using RTreeLeaf = typename engine::datafacade::BaseDataFacade::RTreeLeaf; +using RTreeNode = util::StaticRTree::vector, true>::TreeNode; +using QueryGraph = util::StaticGraph; + +namespace osrm +{ +namespace tools +{ + // delete a shared memory region. report warning if it could not be deleted void deleteRegion(const SharedDataType region) { @@ -62,13 +72,16 @@ void deleteRegion(const SharedDataType region) } }(); - SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; + util::SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; } } +} +} + int main(const int argc, const char *argv[]) try { - LogPolicy::GetInstance().Unmute(); + util::LogPolicy::GetInstance().Unmute(); SharedBarriers barrier; #ifdef __linux__ @@ -76,7 +89,7 @@ int main(const int argc, const char *argv[]) try const bool lock_flags = MCL_CURRENT | MCL_FUTURE; if (-1 == mlockall(lock_flags)) { - SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not request RAM lock"; + util::SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not request RAM lock"; } #endif @@ -91,45 +104,45 @@ int main(const int argc, const char *argv[]) try barrier.pending_update_mutex.unlock(); } - SimpleLogger().Write(logDEBUG) << "Checking input parameters"; + util::SimpleLogger().Write(logDEBUG) << "Checking input parameters"; std::unordered_map server_paths; - if (!GenerateDataStoreOptions(argc, argv, server_paths)) + if (!util::GenerateDataStoreOptions(argc, argv, server_paths)) { return EXIT_SUCCESS; } if (server_paths.find("hsgrdata") == server_paths.end()) { - throw osrm::exception("no hsgr file found"); + throw util::exception("no hsgr file found"); } if (server_paths.find("ramindex") == server_paths.end()) { - throw osrm::exception("no ram index file found"); + throw util::exception("no ram index file found"); } if (server_paths.find("fileindex") == server_paths.end()) { - throw osrm::exception("no leaf index file found"); + throw util::exception("no leaf index file found"); } if (server_paths.find("nodesdata") == server_paths.end()) { - throw osrm::exception("no nodes file found"); + throw util::exception("no nodes file found"); } if (server_paths.find("edgesdata") == server_paths.end()) { - throw osrm::exception("no edges file found"); + throw util::exception("no edges file found"); } if (server_paths.find("namesdata") == server_paths.end()) { - throw osrm::exception("no names file found"); + throw util::exception("no names file found"); } if (server_paths.find("geometry") == server_paths.end()) { - throw osrm::exception("no geometry file found"); + throw util::exception("no geometry file found"); } if (server_paths.find("core") == server_paths.end()) { - throw osrm::exception("no core file found"); + throw util::exception("no core file found"); } auto paths_iterator = server_paths.find("hsgrdata"); @@ -173,19 +186,19 @@ int main(const int argc, const char *argv[]) try // determine segment to use bool segment2_in_use = SharedMemory::RegionExists(LAYOUT_2); - const SharedDataType layout_region = [&] + const engine::datafacade::SharedDataType layout_region = [&] { return segment2_in_use ? LAYOUT_1 : LAYOUT_2; }(); - const SharedDataType data_region = [&] + const engine::datafacade::SharedDataType data_region = [&] { return segment2_in_use ? DATA_1 : DATA_2; }(); - const SharedDataType previous_layout_region = [&] + const engine::datafacade::SharedDataType previous_layout_region = [&] { return segment2_in_use ? LAYOUT_2 : LAYOUT_1; }(); - const SharedDataType previous_data_region = [&] + const engine::datafacade::SharedDataType previous_data_region = [&] { return segment2_in_use ? DATA_2 : DATA_1; }(); @@ -198,15 +211,15 @@ int main(const int argc, const char *argv[]) try file_index_path.length() + 1); // collect number of elements to store in shared memory object - SimpleLogger().Write() << "load names from: " << names_data_path; + util::SimpleLogger().Write() << "load names from: " << names_data_path; // number of entries in name index boost::filesystem::ifstream name_stream(names_data_path, std::ios::binary); unsigned name_blocks = 0; name_stream.read((char *)&name_blocks, sizeof(unsigned)); shared_layout_ptr->SetBlockSize(SharedDataLayout::NAME_OFFSETS, name_blocks); - shared_layout_ptr->SetBlockSize::BlockT>( + shared_layout_ptr->SetBlockSize::BlockT>( SharedDataLayout::NAME_BLOCKS, name_blocks); - SimpleLogger().Write() << "name offsets size: " << name_blocks; + util::SimpleLogger().Write() << "name offsets size: " << name_blocks; BOOST_ASSERT_MSG(0 != name_blocks, "name file broken"); unsigned number_of_chars = 0; @@ -223,9 +236,9 @@ int main(const int argc, const char *argv[]) try number_of_original_edges); shared_layout_ptr->SetBlockSize(SharedDataLayout::NAME_ID_LIST, number_of_original_edges); - shared_layout_ptr->SetBlockSize(SharedDataLayout::TRAVEL_MODE, + shared_layout_ptr->SetBlockSize(SharedDataLayout::TRAVEL_MODE, number_of_original_edges); - shared_layout_ptr->SetBlockSize(SharedDataLayout::TURN_INSTRUCTION, + shared_layout_ptr->SetBlockSize(SharedDataLayout::TURN_INSTRUCTION, number_of_original_edges); // note: there are 32 geometry indicators in one unsigned block shared_layout_ptr->SetBlockSize(SharedDataLayout::GEOMETRIES_INDICATORS, @@ -233,16 +246,16 @@ int main(const int argc, const char *argv[]) try boost::filesystem::ifstream hsgr_input_stream(hsgr_path, std::ios::binary); - FingerPrint fingerprint_valid = FingerPrint::GetValid(); - FingerPrint fingerprint_loaded; - hsgr_input_stream.read((char *)&fingerprint_loaded, sizeof(FingerPrint)); + util::FingerPrint fingerprint_valid = util::FingerPrint::GetValid(); + util::FingerPrint fingerprint_loaded; + hsgr_input_stream.read((char *)&fingerprint_loaded, sizeof(util::FingerPrint)); if (fingerprint_loaded.TestGraphUtil(fingerprint_valid)) { - SimpleLogger().Write(logDEBUG) << "Fingerprint checked out ok"; + util::SimpleLogger().Write(logDEBUG) << "Fingerprint checked out ok"; } else { - SimpleLogger().Write(logWARNING) << ".hsgr was prepared with different build. " + util::SimpleLogger().Write(logWARNING) << ".hsgr was prepared with different build. " "Reprocess to get rid of this warning."; } @@ -279,7 +292,7 @@ int main(const int argc, const char *argv[]) try boost::filesystem::ifstream timestamp_stream(timestamp_path); if (!timestamp_stream) { - SimpleLogger().Write(logWARNING) << timestamp_path << " not found. setting to default"; + util::SimpleLogger().Write(logWARNING) << timestamp_path << " not found. setting to default"; } else { @@ -309,7 +322,7 @@ int main(const int argc, const char *argv[]) try boost::filesystem::ifstream nodes_input_stream(nodes_data_path, std::ios::binary); unsigned coordinate_list_size = 0; nodes_input_stream.read((char *)&coordinate_list_size, sizeof(unsigned)); - shared_layout_ptr->SetBlockSize(SharedDataLayout::COORDINATE_LIST, + shared_layout_ptr->SetBlockSize(SharedDataLayout::COORDINATE_LIST, coordinate_list_size); // load geometries sizes @@ -326,7 +339,7 @@ int main(const int argc, const char *argv[]) try shared_layout_ptr->SetBlockSize(SharedDataLayout::GEOMETRIES_LIST, number_of_compressed_geometries); // allocate shared memory block - SimpleLogger().Write() << "allocating shared memory of " << shared_layout_ptr->GetSizeOfLayout() + util::SimpleLogger().Write() << "allocating shared memory of " << shared_layout_ptr->GetSizeOfLayout() << " bytes"; SharedMemory *shared_memory = SharedMemoryFactory::Get(data_region, shared_layout_ptr->GetSizeOfLayout()); @@ -390,19 +403,19 @@ int main(const int argc, const char *argv[]) try unsigned *name_id_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::NAME_ID_LIST); - TravelMode *travel_mode_ptr = shared_layout_ptr->GetBlockPtr( + extractor::TravelMode *travel_mode_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::TRAVEL_MODE); - TurnInstruction *turn_instructions_ptr = shared_layout_ptr->GetBlockPtr( + extractor::TurnInstruction *turn_instructions_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::TURN_INSTRUCTION); unsigned *geometries_indicator_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::GEOMETRIES_INDICATORS); - OriginalEdgeData current_edge_data; + extractor::OriginalEdgeData current_edge_data; for (unsigned i = 0; i < number_of_original_edges; ++i) { - edges_input_stream.read((char *)&(current_edge_data), sizeof(OriginalEdgeData)); + edges_input_stream.read((char *)&(current_edge_data), sizeof(extractor::OriginalEdgeData)); via_node_ptr[i] = current_edge_data.via_node; name_id_ptr[i] = current_edge_data.name_id; travel_mode_ptr[i] = current_edge_data.travel_mode; @@ -456,15 +469,15 @@ int main(const int argc, const char *argv[]) try } // Loading list of coordinates - FixedPointCoordinate *coordinates_ptr = - shared_layout_ptr->GetBlockPtr( + util::FixedPointCoordinate *coordinates_ptr = + shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::COORDINATE_LIST); - QueryNode current_node; + extractor::QueryNode current_node; for (unsigned i = 0; i < coordinate_list_size; ++i) { - nodes_input_stream.read((char *)¤t_node, sizeof(QueryNode)); - coordinates_ptr[i] = FixedPointCoordinate(current_node.lat, current_node.lon); + nodes_input_stream.read((char *)¤t_node, sizeof(extractor::QueryNode)); + coordinates_ptr[i] = util::FixedPointCoordinate(current_node.lat, current_node.lon); } nodes_input_stream.close(); @@ -552,20 +565,21 @@ int main(const int argc, const char *argv[]) try data_timestamp_ptr->layout = layout_region; data_timestamp_ptr->data = data_region; data_timestamp_ptr->timestamp += 1; - deleteRegion(previous_data_region); - deleteRegion(previous_layout_region); - SimpleLogger().Write() << "all data loaded"; + tools::deleteRegion(previous_data_region); + tools::deleteRegion(previous_layout_region); + util::SimpleLogger().Write() << "all data loaded"; shared_layout_ptr->PrintInformation(); + return EXIT_SUCCESS; } catch (const std::bad_alloc &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - SimpleLogger().Write(logWARNING) << "Please provide more memory or disable locking the virtual " + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "Please provide more memory or disable locking the virtual " "address space (note: this makes OSRM swap, i.e. slow)"; return EXIT_FAILURE; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); + util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); } diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index 1d34a084f..7f317cb8d 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -8,55 +8,57 @@ #include #include +using namespace osrm; + int main(int argc, char *argv[]) try { - LogPolicy::GetInstance().Unmute(); - ExtractorConfig extractor_config; + util::LogPolicy::GetInstance().Unmute(); + extractor::ExtractorConfig extractor_config; - const return_code result = ExtractorOptions::ParseArguments(argc, argv, extractor_config); + const extractor::return_code result = extractor::ExtractorOptions::ParseArguments(argc, argv, extractor_config); - if (return_code::fail == result) + if (extractor::return_code::fail == result) { return EXIT_FAILURE; } - if (return_code::exit == result) + if (extractor::return_code::exit == result) { return EXIT_SUCCESS; } - ExtractorOptions::GenerateOutputFilesNames(extractor_config); + extractor::ExtractorOptions::GenerateOutputFilesNames(extractor_config); if (1 > extractor_config.requested_num_threads) { - SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; + util::SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger"; return EXIT_FAILURE; } if (!boost::filesystem::is_regular_file(extractor_config.input_path)) { - SimpleLogger().Write(logWARNING) << "Input file " << extractor_config.input_path.string() + util::SimpleLogger().Write(logWARNING) << "Input file " << extractor_config.input_path.string() << " not found!"; return EXIT_FAILURE; } if (!boost::filesystem::is_regular_file(extractor_config.profile_path)) { - SimpleLogger().Write(logWARNING) << "Profile " << extractor_config.profile_path.string() + util::SimpleLogger().Write(logWARNING) << "Profile " << extractor_config.profile_path.string() << " not found!"; return EXIT_FAILURE; } - return extractor(extractor_config).run(); + return extractor::extractor(extractor_config).run(); } catch (const std::bad_alloc &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "Please provide more memory or consider using a larger swapfile"; return EXIT_FAILURE; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); return EXIT_FAILURE; } diff --git a/src/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp index b29e78e85..dda28000e 100644 --- a/src/tools/io-benchmark.cpp +++ b/src/tools/io-benchmark.cpp @@ -1,4 +1,3 @@ -#include "util/version.hpp" #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" @@ -20,7 +19,12 @@ #include #include -const unsigned number_of_elements = 268435456; +namespace osrm +{ +namespace tools +{ + +const unsigned NUMBER_OF_ELEMENTS = 268435456; struct Statistics { @@ -41,33 +45,34 @@ void runStatistics(std::vector &timings_vector, Statistics &stats) stats.dev = std::sqrt(primary_sq_sum / timings_vector.size() - (stats.mean * stats.mean)); } +} +} + int main(int argc, char *argv[]) { #ifdef __FreeBSD__ - SimpleLogger().Write() << "Not supported on FreeBSD"; + osrm::util::SimpleLogger().Write() << "Not supported on FreeBSD"; return 0; #endif #ifdef _WIN32 - SimpleLogger().Write() << "Not supported on Windows"; + osrm::util::SimpleLogger().Write() << "Not supported on Windows"; return 0; #else - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); boost::filesystem::path test_path; try { - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; - if (1 == argc) { - SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device"; + osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device"; return -1; } test_path = boost::filesystem::path(argv[1]); test_path /= "osrm.tst"; - SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string(); + osrm::util::SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string(); // create files for testing if (2 == argc) @@ -75,17 +80,17 @@ int main(int argc, char *argv[]) // create file to test if (boost::filesystem::exists(test_path)) { - throw osrm::exception("Data file already exists"); + throw osrm::util::exception("Data file already exists"); } - int *random_array = new int[number_of_elements]; - std::generate(random_array, random_array + number_of_elements, std::rand); + int *random_array = new int[osrm::tools::NUMBER_OF_ELEMENTS]; + std::generate(random_array, random_array + osrm::tools::NUMBER_OF_ELEMENTS, std::rand); #ifdef __APPLE__ FILE *fd = fopen(test_path.string().c_str(), "w"); fcntl(fileno(fd), F_NOCACHE, 1); fcntl(fileno(fd), F_RDAHEAD, 0); TIMER_START(write_1gb); - write(fileno(fd), (char *)random_array, number_of_elements * sizeof(unsigned)); + write(fileno(fd), (char *)random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); TIMER_STOP(write_1gb); fclose(fd); #endif @@ -94,24 +99,24 @@ int main(int argc, char *argv[]) open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU); if (-1 == file_desc) { - throw osrm::exception("Could not open random data file"); + throw osrm::util::exception("Could not open random data file"); } TIMER_START(write_1gb); - int ret = write(file_desc, random_array, number_of_elements * sizeof(unsigned)); + int ret = write(file_desc, random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); if (0 > ret) { - throw osrm::exception("could not write random data file"); + throw osrm::util::exception("could not write random data file"); } TIMER_STOP(write_1gb); close(file_desc); #endif delete[] random_array; - SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb) + osrm::util::SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb) << "s"; - SimpleLogger().Write() << "raw write performance: " << std::setprecision(5) + osrm::util::SimpleLogger().Write() << "raw write performance: " << std::setprecision(5) << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) << "MB/sec"; - SimpleLogger().Write(logDEBUG) + osrm::util::SimpleLogger().Write(logDEBUG) << "finished creation of random data. Flush disk cache now!"; } else @@ -119,15 +124,15 @@ int main(int argc, char *argv[]) // Run Non-Cached I/O benchmarks if (!boost::filesystem::exists(test_path)) { - throw osrm::exception("data file does not exist"); + throw osrm::util::exception("data file does not exist"); } // volatiles do not get optimized - Statistics stats; + osrm::tools::Statistics stats; #ifdef __APPLE__ volatile unsigned single_block[1024]; - char *raw_array = new char[number_of_elements * sizeof(unsigned)]; + char *raw_array = new char[osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)]; FILE *fd = fopen(test_path.string().c_str(), "r"); fcntl(fileno(fd), F_NOCACHE, 1); fcntl(fileno(fd), F_RDAHEAD, 0); @@ -138,33 +143,33 @@ int main(int argc, char *argv[]) int file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); if (-1 == file_desc) { - SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); + osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); return -1; } - char *raw_array = (char *)memalign(512, number_of_elements * sizeof(unsigned)); + char *raw_array = (char *)memalign(512, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); #endif TIMER_START(read_1gb); #ifdef __APPLE__ - read(fileno(fd), raw_array, number_of_elements * sizeof(unsigned)); + read(fileno(fd), raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); close(fileno(fd)); fd = fopen(test_path.string().c_str(), "r"); #endif #ifdef __linux__ - int ret = read(file_desc, raw_array, number_of_elements * sizeof(unsigned)); - SimpleLogger().Write(logDEBUG) << "read " << ret + int ret = read(file_desc, raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + osrm::util::SimpleLogger().Write(logDEBUG) << "read " << ret << " bytes, error: " << strerror(errno); close(file_desc); file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); - SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); + osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); #endif TIMER_STOP(read_1gb); - SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb) << "s"; - SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed + osrm::util::SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb) << "s"; + osrm::util::SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed << 1024 * 1024 / TIMER_SEC(read_1gb) << "MB/sec"; std::vector timing_results_raw_random; - SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB"; + osrm::util::SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB"; #ifdef __APPLE__ fseek(fd, 0, SEEK_SET); @@ -173,7 +178,7 @@ int main(int argc, char *argv[]) lseek(file_desc, 0, SEEK_SET); #endif // make 1000 random access, time each I/O seperately - unsigned number_of_blocks = (number_of_elements * sizeof(unsigned) - 1) / 4096; + unsigned number_of_blocks = (osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned) - 1) / 4096; std::random_device rd; std::default_random_engine e1(rd()); std::uniform_int_distribution uniform_dist(0, number_of_blocks - 1); @@ -199,30 +204,30 @@ int main(int argc, char *argv[]) TIMER_STOP(random_access); if (((off_t)-1) == ret1) { - SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); - throw osrm::exception("seek error"); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); + throw osrm::util::exception("seek error"); } if (-1 == ret2) { - SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); - throw osrm::exception("read error"); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); + throw osrm::util::exception("read error"); } timing_results_raw_random.push_back(TIMER_SEC(random_access)); } // Do statistics - SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics"; + osrm::util::SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics"; std::ofstream random_csv("random.csv", std::ios::trunc); for (unsigned i = 0; i < timing_results_raw_random.size(); ++i) { random_csv << i << ", " << timing_results_raw_random[i] << std::endl; } random_csv.close(); - runStatistics(timing_results_raw_random, stats); + osrm::tools::runStatistics(timing_results_raw_random, stats); - SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed + osrm::util::SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed << "min: " << stats.min << "ms, " << "mean: " << stats.mean << "ms, " << "med: " << stats.med << "ms, " @@ -260,15 +265,15 @@ int main(int argc, char *argv[]) TIMER_STOP(read_every_100); if (((off_t)-1) == ret1) { - SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); - throw osrm::exception("seek error"); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); + throw osrm::util::exception("seek error"); } if (-1 == ret2) { - SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); - throw osrm::exception("read error"); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); + throw osrm::util::exception("read error"); } timing_results_raw_seq.push_back(TIMER_SEC(read_every_100)); } @@ -282,7 +287,7 @@ int main(int argc, char *argv[]) close(file_desc); #endif // Do statistics - SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics"; + osrm::util::SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics"; // print simple statistics: min, max, median, variance std::ofstream seq_csv("sequential.csv", std::ios::trunc); for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i) @@ -290,8 +295,8 @@ int main(int argc, char *argv[]) seq_csv << i << ", " << timing_results_raw_seq[i] << std::endl; } seq_csv.close(); - runStatistics(timing_results_raw_seq, stats); - SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed + osrm::tools::runStatistics(timing_results_raw_seq, stats); + osrm::util::SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed << "min: " << stats.min << "ms, " << "mean: " << stats.mean << "ms, " << "med: " << stats.med << "ms, " @@ -301,18 +306,18 @@ int main(int argc, char *argv[]) if (boost::filesystem::exists(test_path)) { boost::filesystem::remove(test_path); - SimpleLogger().Write(logDEBUG) << "removing temporary files"; + osrm::util::SimpleLogger().Write(logDEBUG) << "removing temporary files"; } } } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); - SimpleLogger().Write(logWARNING) << "cleaning up, and exiting"; + osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "cleaning up, and exiting"; if (boost::filesystem::exists(test_path)) { boost::filesystem::remove(test_path); - SimpleLogger().Write(logWARNING) << "removing temporary files"; + osrm::util::SimpleLogger().Write(logWARNING) << "removing temporary files"; } return -1; } diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index 4890fa694..ee00fa38b 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -39,25 +39,27 @@ BOOL WINAPI console_ctrl_handler(DWORD ctrl_type) } #endif +using namespace osrm; + int main(int argc, const char *argv[]) try { - LogPolicy::GetInstance().Unmute(); + util::LogPolicy::GetInstance().Unmute(); bool trial_run = false; std::string ip_address; int ip_port, requested_thread_num; LibOSRMConfig lib_config; - const unsigned init_result = GenerateServerProgramOptions( + const unsigned init_result = util::GenerateServerProgramOptions( argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, lib_config.use_shared_memory, trial_run, lib_config.max_locations_trip, lib_config.max_locations_viaroute, lib_config.max_locations_distance_table, lib_config.max_locations_map_matching); - if (init_result == INIT_OK_DO_NOT_START_ENGINE) + if (init_result == util::INIT_OK_DO_NOT_START_ENGINE) { return EXIT_SUCCESS; } - if (init_result == INIT_FAILED) + if (init_result == util::INIT_FAILED) { return EXIT_FAILURE; } @@ -70,7 +72,7 @@ int main(int argc, const char *argv[]) try if (should_lock && -1 == mlockall(MCL_CURRENT | MCL_FUTURE)) { could_lock = false; - SimpleLogger().Write(logWARNING) << "memory could not be locked to RAM"; + util::SimpleLogger().Write(logWARNING) << "memory could not be locked to RAM"; } } ~MemoryLocker() @@ -81,16 +83,16 @@ int main(int argc, const char *argv[]) try bool should_lock = false, could_lock = true; } memory_locker(lib_config.use_shared_memory); #endif - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; + util::SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; if (lib_config.use_shared_memory) { - SimpleLogger().Write(logDEBUG) << "Loading from shared memory"; + util::SimpleLogger().Write(logDEBUG) << "Loading from shared memory"; } - SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num; - SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address; - SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port; + util::SimpleLogger().Write(logDEBUG) << "Threads:\t" << requested_thread_num; + util::SimpleLogger().Write(logDEBUG) << "IP address:\t" << ip_address; + util::SimpleLogger().Write(logDEBUG) << "IP port:\t" << ip_port; #ifndef _WIN32 int sig = 0; @@ -101,13 +103,13 @@ int main(int argc, const char *argv[]) try #endif OSRM osrm_lib(lib_config); - auto routing_server = Server::CreateServer(ip_address, ip_port, requested_thread_num); + auto routing_server = server::Server::CreateServer(ip_address, ip_port, requested_thread_num); routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib); if (trial_run) { - SimpleLogger().Write() << "trial run, quitting after successful initialization"; + util::SimpleLogger().Write() << "trial run, quitting after successful initialization"; } else { @@ -127,18 +129,18 @@ int main(int argc, const char *argv[]) try sigaddset(&wait_mask, SIGQUIT); sigaddset(&wait_mask, SIGTERM); pthread_sigmask(SIG_BLOCK, &wait_mask, nullptr); - SimpleLogger().Write() << "running and waiting for requests"; + util::SimpleLogger().Write() << "running and waiting for requests"; sigwait(&wait_mask, &sig); #else // Set console control handler to allow server to be stopped. - console_ctrl_function = std::bind(&Server::Stop, routing_server); + console_ctrl_function = std::bind(&server::Server::Stop, routing_server); SetConsoleCtrlHandler(console_ctrl_handler, TRUE); - SimpleLogger().Write() << "running and waiting for requests"; + util::SimpleLogger().Write() << "running and waiting for requests"; routing_server->Run(); #endif - SimpleLogger().Write() << "initiating shutdown"; + util::SimpleLogger().Write() << "initiating shutdown"; routing_server->Stop(); - SimpleLogger().Write() << "stopping threads"; + util::SimpleLogger().Write() << "stopping threads"; auto status = future.wait_for(std::chrono::seconds(2)); @@ -148,24 +150,24 @@ int main(int argc, const char *argv[]) try } else { - SimpleLogger().Write(logWARNING) << "Didn't exit within 2 seconds. Hard abort!"; + util::SimpleLogger().Write(logWARNING) << "Didn't exit within 2 seconds. Hard abort!"; server_task.reset(); // just kill it } } - SimpleLogger().Write() << "freeing objects"; + util::SimpleLogger().Write() << "freeing objects"; routing_server.reset(); - SimpleLogger().Write() << "shutdown completed"; + util::SimpleLogger().Write() << "shutdown completed"; } catch (const std::bad_alloc &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - SimpleLogger().Write(logWARNING) + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "Please provide more memory or consider using a larger swapfile"; return EXIT_FAILURE; } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); return EXIT_FAILURE; } diff --git a/src/tools/simpleclient.cpp b/src/tools/simpleclient.cpp index 0e5460a9e..65198ee05 100644 --- a/src/tools/simpleclient.cpp +++ b/src/tools/simpleclient.cpp @@ -1,4 +1,3 @@ -#include "util/version.hpp" #include "util/json_renderer.hpp" #include "util/routed_options.hpp" #include "util/simple_logger.hpp" @@ -12,32 +11,31 @@ int main(int argc, const char *argv[]) { - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { std::string ip_address; int ip_port, requested_thread_num; bool trial_run = false; - LibOSRMConfig lib_config; - const unsigned init_result = GenerateServerProgramOptions( + osrm::LibOSRMConfig lib_config; + const unsigned init_result = osrm::util::GenerateServerProgramOptions( argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, lib_config.use_shared_memory, trial_run, lib_config.max_locations_trip, lib_config.max_locations_viaroute, lib_config.max_locations_distance_table, lib_config.max_locations_map_matching); - if (init_result == INIT_OK_DO_NOT_START_ENGINE) + if (init_result == osrm::util::INIT_OK_DO_NOT_START_ENGINE) { return 0; } - if (init_result == INIT_FAILED) + if (init_result == osrm::util::INIT_FAILED) { return 1; } - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; - OSRM routing_machine(lib_config); + osrm::OSRM routing_machine(lib_config); - RouteParameters route_parameters; + osrm::RouteParameters route_parameters; route_parameters.zoom_level = 18; // no generalization route_parameters.print_instructions = true; // turn by turn instructions route_parameters.alternate_route = true; // get an alternate route, too @@ -51,19 +49,19 @@ int main(int argc, const char *argv[]) // route_parameters.hints.push_back(); // see wiki, saves I/O if done properly // start_coordinate - route_parameters.coordinates.emplace_back(52.519930 * COORDINATE_PRECISION, - 13.438640 * COORDINATE_PRECISION); + route_parameters.coordinates.emplace_back(52.519930 * osrm::COORDINATE_PRECISION, + 13.438640 * osrm::COORDINATE_PRECISION); // target_coordinate - route_parameters.coordinates.emplace_back(52.513191 * COORDINATE_PRECISION, - 13.415852 * COORDINATE_PRECISION); + route_parameters.coordinates.emplace_back(52.513191 * osrm::COORDINATE_PRECISION, + 13.415852 * osrm::COORDINATE_PRECISION); osrm::json::Object json_result; const int result_code = routing_machine.RunQuery(route_parameters, json_result); - SimpleLogger().Write() << "http code: " << result_code; - osrm::json::render(SimpleLogger().Write(), json_result); + osrm::util::SimpleLogger().Write() << "http code: " << result_code; + osrm::json::render(osrm::util::SimpleLogger().Write(), json_result); } catch (std::exception ¤t_exception) { - SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what(); return -1; } return 0; diff --git a/src/tools/springclean.cpp b/src/tools/springclean.cpp index 2535478a5..f242e5ed2 100644 --- a/src/tools/springclean.cpp +++ b/src/tools/springclean.cpp @@ -2,9 +2,17 @@ #include "datastore/shared_memory_factory.hpp" #include "engine/datafacade/shared_datatype.hpp" -#include "util/version.hpp" #include "util/simple_logger.hpp" +namespace osrm +{ +namespace tools +{ + +// FIXME remove after folding back into datastore +using namespace datastore; +using namespace engine::datafacade; + void deleteRegion(const SharedDataType region) { if (SharedMemory::RegionExists(region) && !SharedMemory::Remove(region)) @@ -30,46 +38,47 @@ void deleteRegion(const SharedDataType region) } }(); - SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; + util::SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; } } // find all existing shmem regions and remove them. void springclean() { - SimpleLogger().Write() << "spring-cleaning all shared memory regions"; + util::SimpleLogger().Write() << "spring-cleaning all shared memory regions"; deleteRegion(DATA_1); deleteRegion(LAYOUT_1); deleteRegion(DATA_2); deleteRegion(LAYOUT_2); deleteRegion(CURRENT_REGIONS); } +} +} int main() { - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION << "\n\n"; - SimpleLogger().Write() << "Releasing all locks"; - SimpleLogger().Write() << "ATTENTION! BE CAREFUL!"; - SimpleLogger().Write() << "----------------------"; - SimpleLogger().Write() << "This tool may put osrm-routed into an undefined state!"; - SimpleLogger().Write() << "Type 'Y' to acknowledge that you know what your are doing."; - SimpleLogger().Write() << "\n\nDo you want to purge all shared memory allocated " + osrm::util::SimpleLogger().Write() << "Releasing all locks"; + osrm::util::SimpleLogger().Write() << "ATTENTION! BE CAREFUL!"; + osrm::util::SimpleLogger().Write() << "----------------------"; + osrm::util::SimpleLogger().Write() << "This tool may put osrm-routed into an undefined state!"; + osrm::util::SimpleLogger().Write() << "Type 'Y' to acknowledge that you know what your are doing."; + osrm::util::SimpleLogger().Write() << "\n\nDo you want to purge all shared memory allocated " << "by osrm-datastore? [type 'Y' to confirm]"; const auto letter = getchar(); if (letter != 'Y') { - SimpleLogger().Write() << "aborted."; + osrm::util::SimpleLogger().Write() << "aborted."; return 0; } - springclean(); + osrm::tools::springclean(); } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); } return 0; } diff --git a/src/tools/unlock_all_mutexes.cpp b/src/tools/unlock_all_mutexes.cpp index f4c248c48..f59bf7721 100644 --- a/src/tools/unlock_all_mutexes.cpp +++ b/src/tools/unlock_all_mutexes.cpp @@ -1,4 +1,3 @@ -#include "util/version.hpp" #include "util/simple_logger.hpp" #include "engine/datafacade/shared_barriers.hpp" @@ -6,19 +5,18 @@ int main() { - LogPolicy::GetInstance().Unmute(); + osrm::util::LogPolicy::GetInstance().Unmute(); try { - SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; - SimpleLogger().Write() << "Releasing all locks"; - SharedBarriers barrier; + osrm::util::SimpleLogger().Write() << "Releasing all locks"; + osrm::engine::datafacade::SharedBarriers barrier; barrier.pending_update_mutex.unlock(); barrier.query_mutex.unlock(); barrier.update_mutex.unlock(); } catch (const std::exception &e) { - SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); } return 0; } diff --git a/src/util/compute_angle.cpp b/src/util/compute_angle.cpp index 885cb8221..ebc2f0f2e 100644 --- a/src/util/compute_angle.cpp +++ b/src/util/compute_angle.cpp @@ -7,6 +7,11 @@ #include +namespace osrm +{ +namespace util +{ + double ComputeAngle::OfThreeFixedPointCoordinates(const FixedPointCoordinate &first, const FixedPointCoordinate &second, const FixedPointCoordinate &third) noexcept @@ -25,3 +30,5 @@ double ComputeAngle::OfThreeFixedPointCoordinates(const FixedPointCoordinate &fi } return angle; } +} +} diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index 0092b01cf..4a35c7ed4 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -11,6 +11,11 @@ #include #include +namespace osrm +{ +namespace util +{ + FixedPointCoordinate::FixedPointCoordinate() : lat(std::numeric_limits::min()), lon(std::numeric_limits::min()) { @@ -50,3 +55,5 @@ std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordina out << "(" << static_cast(coordinate.lat / COORDINATE_PRECISION) << "," << static_cast(coordinate.lon / COORDINATE_PRECISION) << ")"; return out; } +} +} diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index 2e6a3137e..05190123f 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -11,6 +11,11 @@ #include +namespace osrm +{ +namespace util +{ + namespace { constexpr static const double RAD = 0.017453292519943295769236907684886; @@ -223,3 +228,5 @@ double bearing(const FixedPointCoordinate &first_coordinate, return result; } } +} +} diff --git a/src/util/hilbert_value.cpp b/src/util/hilbert_value.cpp index 96e39773b..5ddfce0b4 100644 --- a/src/util/hilbert_value.cpp +++ b/src/util/hilbert_value.cpp @@ -2,6 +2,11 @@ #include "osrm/coordinate.hpp" +namespace osrm +{ +namespace util +{ + uint64_t HilbertCode::operator()(const FixedPointCoordinate ¤t_coordinate) const { unsigned location[2]; @@ -71,3 +76,5 @@ void HilbertCode::TransposeCoordinate(uint32_t *X) const X[i] ^= t; } } +} +} diff --git a/src/util/mercator.cpp b/src/util/mercator.cpp index 36c1a9b84..ab9637172 100644 --- a/src/util/mercator.cpp +++ b/src/util/mercator.cpp @@ -2,6 +2,11 @@ #include +namespace osrm +{ +namespace util +{ + double mercator::y2lat(const double value) noexcept { return 180. * M_1_PI * (2. * std::atan(std::exp(value * M_PI / 180.)) - M_PI_2); @@ -11,3 +16,5 @@ double mercator::lat2y(const double latitude) noexcept { return 180. * M_1_PI * std::log(std::tan(M_PI_4 + latitude * (M_PI / 180.) / 2.)); } +} +} diff --git a/src/util/osrm_exception.cpp b/src/util/osrm_exception.cpp index 475e75194..a987bc75d 100644 --- a/src/util/osrm_exception.cpp +++ b/src/util/osrm_exception.cpp @@ -1,7 +1,5 @@ #include "util/osrm_exception.hpp" -namespace osrm -{ // This function exists to 'anchor' the class, and stop the compiler from // copying vtable and RTTI info into every object file that includes // this header. (Caught by -Wweak-vtables under Clang.) @@ -12,5 +10,13 @@ namespace osrm // always have at least one out-of-line virtual method in the class. Without // this, the compiler will copy the vtable and RTTI into every .o file that // #includes the header, bloating .o file sizes and increasing link times. + +namespace osrm +{ +namespace util +{ + void exception::anchor() const {} + +} } diff --git a/src/util/simple_logger.cpp b/src/util/simple_logger.cpp index de3d68190..13ee10391 100644 --- a/src/util/simple_logger.cpp +++ b/src/util/simple_logger.cpp @@ -11,6 +11,11 @@ #include #include +namespace osrm +{ +namespace util +{ + namespace { static const char COL_RESET[]{"\x1b[0m"}; @@ -92,3 +97,5 @@ SimpleLogger::~SimpleLogger() } } } +} +} diff --git a/unit_tests/engine/douglas_peucker.cpp b/unit_tests/engine/douglas_peucker.cpp index 827ce5016..0a5bc0a87 100644 --- a/unit_tests/engine/douglas_peucker.cpp +++ b/unit_tests/engine/douglas_peucker.cpp @@ -10,9 +10,12 @@ BOOST_AUTO_TEST_SUITE(douglas_peucker) +using namespace osrm; +using namespace osrm::engine; + SegmentInformation getTestInfo(int lat, int lon, bool necessary) { - return SegmentInformation(FixedPointCoordinate(lat, lon), 0, 0, 0, TurnInstruction::HeadOn, + return SegmentInformation(util::FixedPointCoordinate(lat, lon), 0, 0, 0, extractor::TurnInstruction::HeadOn, necessary, false, 0); } diff --git a/unit_tests/engine/geometry_string.cpp b/unit_tests/engine/geometry_string.cpp index 7e5e07c2c..182cabda8 100644 --- a/unit_tests/engine/geometry_string.cpp +++ b/unit_tests/engine/geometry_string.cpp @@ -9,23 +9,28 @@ #include #include -BOOST_AUTO_TEST_CASE(geometry_string) +BOOST_AUTO_TEST_SUITE(polyline) + +using namespace osrm; +using namespace osrm::engine; + +BOOST_AUTO_TEST_CASE(decode) { // Polyline string for the 5 coordinates const std::string polyline = "_gjaR_gjaR_pR_ibE_pR_ibE_pR_ibE_pR_ibE"; PolylineCompressor pc; - std::vector coords = pc.decode_string(polyline); + std::vector coords = pc.decode_string(polyline); // Test coordinates; these would be the coordinates we give the loc parameter, // e.g. loc=10.00,10.0&loc=10.01,10.1... - FixedPointCoordinate coord1(10.00 * COORDINATE_PRECISION, 10.0 * COORDINATE_PRECISION); - FixedPointCoordinate coord2(10.01 * COORDINATE_PRECISION, 10.1 * COORDINATE_PRECISION); - FixedPointCoordinate coord3(10.02 * COORDINATE_PRECISION, 10.2 * COORDINATE_PRECISION); - FixedPointCoordinate coord4(10.03 * COORDINATE_PRECISION, 10.3 * COORDINATE_PRECISION); - FixedPointCoordinate coord5(10.04 * COORDINATE_PRECISION, 10.4 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord1(10.00 * COORDINATE_PRECISION, 10.0 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord2(10.01 * COORDINATE_PRECISION, 10.1 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord3(10.02 * COORDINATE_PRECISION, 10.2 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord4(10.03 * COORDINATE_PRECISION, 10.3 * COORDINATE_PRECISION); + util::FixedPointCoordinate coord5(10.04 * COORDINATE_PRECISION, 10.4 * COORDINATE_PRECISION); // Put the test coordinates into the vector for comparison - std::vector cmp_coords; + std::vector cmp_coords; cmp_coords.emplace_back(coord1); cmp_coords.emplace_back(coord2); cmp_coords.emplace_back(coord3); @@ -45,3 +50,5 @@ BOOST_AUTO_TEST_CASE(geometry_string) BOOST_CHECK_CLOSE(cmp1_lon, cmp2_lon, 0.0001); } } + +BOOST_AUTO_TEST_SUITE_END() diff --git a/unit_tests/extractor/compressed_edge_container.cpp b/unit_tests/extractor/compressed_edge_container.cpp index 4a83f0402..593ec597c 100644 --- a/unit_tests/extractor/compressed_edge_container.cpp +++ b/unit_tests/extractor/compressed_edge_container.cpp @@ -6,6 +6,9 @@ BOOST_AUTO_TEST_SUITE(compressed_edge_container) +using namespace osrm; +using namespace osrm::extractor; + BOOST_AUTO_TEST_CASE(long_road_test) { // 0 1 2 3 diff --git a/unit_tests/extractor/graph_compressor.cpp b/unit_tests/extractor/graph_compressor.cpp index e4cd1ddbb..83751bf6a 100644 --- a/unit_tests/extractor/graph_compressor.cpp +++ b/unit_tests/extractor/graph_compressor.cpp @@ -12,6 +12,11 @@ BOOST_AUTO_TEST_SUITE(graph_compressor) +using namespace osrm; +using namespace osrm::extractor; +using InputEdge = util::NodeBasedDynamicGraph::InputEdge; +using Graph = util::NodeBasedDynamicGraph; + BOOST_AUTO_TEST_CASE(long_road_test) { // @@ -25,7 +30,6 @@ BOOST_AUTO_TEST_CASE(long_road_test) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, // travel_mode @@ -42,7 +46,7 @@ BOOST_AUTO_TEST_CASE(long_road_test) BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[4].data)); BOOST_ASSERT(edges[4].data.IsCompatibleTo(edges[6].data)); - NodeBasedDynamicGraph graph(5, edges); + Graph graph(5, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK_EQUAL(graph.FindEdge(0, 1), SPECIAL_EDGEID); @@ -67,7 +71,6 @@ BOOST_AUTO_TEST_CASE(loop_test) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, forward, backward, // roundabout, travel_mode @@ -98,7 +101,7 @@ BOOST_AUTO_TEST_CASE(loop_test) BOOST_ASSERT(edges[9].data.IsCompatibleTo(edges[10].data)); BOOST_ASSERT(edges[10].data.IsCompatibleTo(edges[11].data)); - NodeBasedDynamicGraph graph(6, edges); + Graph graph(6, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK_EQUAL(graph.FindEdge(5, 0), SPECIAL_EDGEID); @@ -125,7 +128,6 @@ BOOST_AUTO_TEST_CASE(t_intersection) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, // travel_mode @@ -143,7 +145,7 @@ BOOST_AUTO_TEST_CASE(t_intersection) BOOST_ASSERT(edges[3].data.IsCompatibleTo(edges[4].data)); BOOST_ASSERT(edges[4].data.IsCompatibleTo(edges[5].data)); - NodeBasedDynamicGraph graph(4, edges); + Graph graph(4, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID); @@ -164,7 +166,6 @@ BOOST_AUTO_TEST_CASE(street_name_changes) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, forward, backward, // roundabout, travel_mode @@ -177,7 +178,7 @@ BOOST_AUTO_TEST_CASE(street_name_changes) BOOST_ASSERT(edges[0].data.IsCompatibleTo(edges[1].data)); BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[3].data)); - NodeBasedDynamicGraph graph(5, edges); + Graph graph(5, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID); @@ -197,7 +198,6 @@ BOOST_AUTO_TEST_CASE(direction_changes) RestrictionMap map; CompressedEdgeContainer container; - using InputEdge = NodeBasedDynamicGraph::InputEdge; std::vector edges = { // source, target, distance, edge_id, name_id, access_restricted, reverse, roundabout, // travel_mode @@ -207,7 +207,7 @@ BOOST_AUTO_TEST_CASE(direction_changes) {2, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}, }; - NodeBasedDynamicGraph graph(5, edges); + Graph graph(5, edges); compressor.Compress(barrier_nodes, traffic_lights, map, graph, container); BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID); diff --git a/unit_tests/extractor/raster_source.cpp b/unit_tests/extractor/raster_source.cpp index 3f43d2f40..2160372f1 100644 --- a/unit_tests/extractor/raster_source.cpp +++ b/unit_tests/extractor/raster_source.cpp @@ -9,6 +9,9 @@ BOOST_AUTO_TEST_SUITE(raster_source) +using namespace osrm; +using namespace osrm::extractor; + int normalize(double coord) { return static_cast(coord * COORDINATE_PRECISION); } #define CHECK_QUERY(source_id, lon, lat, expected) \ @@ -73,11 +76,11 @@ BOOST_AUTO_TEST_CASE(raster_test) BOOST_CHECK_EQUAL(source_already_loaded_id, 0); BOOST_CHECK_THROW(sources.getRasterDataFromSource(1, normalize(0.02), normalize(0.02)), - osrm::exception); + util::exception); BOOST_CHECK_THROW( sources.loadRasterSource("../unit_tests/fixtures/nonexistent.asc", 0, 0.1, 0, 0.1, 7, 7), - osrm::exception); + util::exception); } BOOST_AUTO_TEST_SUITE_END() diff --git a/unit_tests/util/bearing.cpp b/unit_tests/util/bearing.cpp index 90664b27d..77e2ede66 100644 --- a/unit_tests/util/bearing.cpp +++ b/unit_tests/util/bearing.cpp @@ -5,7 +5,10 @@ #include #include -BOOST_AUTO_TEST_SUITE(bearing) +BOOST_AUTO_TEST_SUITE(bearing_test) + +using namespace osrm; +using namespace osrm::util; // Verify that the bearing-bounds checking function behaves as expected BOOST_AUTO_TEST_CASE(bearing_range_test) diff --git a/unit_tests/util/binary_heap.cpp b/unit_tests/util/binary_heap.cpp index 4f270f168..44aef1342 100644 --- a/unit_tests/util/binary_heap.cpp +++ b/unit_tests/util/binary_heap.cpp @@ -12,6 +12,9 @@ BOOST_AUTO_TEST_SUITE(binary_heap) +using namespace osrm; +using namespace osrm::util; + struct TestData { unsigned value; diff --git a/unit_tests/util/coordinate.cpp b/unit_tests/util/coordinate.cpp index e636d2f8f..8c32f080c 100644 --- a/unit_tests/util/coordinate.cpp +++ b/unit_tests/util/coordinate.cpp @@ -6,6 +6,9 @@ #include +using namespace osrm; +using namespace osrm::util; + // Regression test for bug captured in #1347 BOOST_AUTO_TEST_CASE(regression_test_1347) { diff --git a/unit_tests/util/duration_parsing.cpp b/unit_tests/util/duration_parsing.cpp index b92916ad7..72a5b6306 100644 --- a/unit_tests/util/duration_parsing.cpp +++ b/unit_tests/util/duration_parsing.cpp @@ -5,33 +5,36 @@ BOOST_AUTO_TEST_SUITE(durations_are_valid) +using namespace osrm; +using namespace osrm::util; + BOOST_AUTO_TEST_CASE(all_necessary_test) { - BOOST_CHECK_EQUAL(durationIsValid("00:01"), true); - BOOST_CHECK_EQUAL(durationIsValid("00:01:01"), true); - BOOST_CHECK_EQUAL(durationIsValid("PT15M"), true); + BOOST_CHECK_EQUAL(extractor::durationIsValid("00:01"), true); + BOOST_CHECK_EQUAL(extractor::durationIsValid("00:01:01"), true); + BOOST_CHECK_EQUAL(extractor::durationIsValid("PT15M"), true); } BOOST_AUTO_TEST_CASE(common_durations_get_translated) { - BOOST_CHECK_EQUAL(parseDuration("00:01"), 60); - BOOST_CHECK_EQUAL(parseDuration("00:01:01"), 61); - BOOST_CHECK_EQUAL(parseDuration("01:01"), 3660); + BOOST_CHECK_EQUAL(extractor::parseDuration("00:01"), 60); + BOOST_CHECK_EQUAL(extractor::parseDuration("00:01:01"), 61); + BOOST_CHECK_EQUAL(extractor::parseDuration("01:01"), 3660); // check all combinations of iso duration tokens - BOOST_CHECK_EQUAL(parseDuration("PT1M1S"), 61); - BOOST_CHECK_EQUAL(parseDuration("PT1H1S"), 3601); - BOOST_CHECK_EQUAL(parseDuration("PT15M"), 900); - BOOST_CHECK_EQUAL(parseDuration("PT15S"), 15); - BOOST_CHECK_EQUAL(parseDuration("PT15H"), 54000); - BOOST_CHECK_EQUAL(parseDuration("PT1H15M"), 4500); - BOOST_CHECK_EQUAL(parseDuration("PT1H15M1S"), 4501); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1M1S"), 61); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1H1S"), 3601); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT15M"), 900); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT15S"), 15); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT15H"), 54000); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1H15M"), 4500); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1H15M1S"), 4501); } BOOST_AUTO_TEST_CASE(iso_8601_durations_case_insensitive) { - BOOST_CHECK_EQUAL(parseDuration("PT15m"), 900); - BOOST_CHECK_EQUAL(parseDuration("PT1h15m"), 4500); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT15m"), 900); + BOOST_CHECK_EQUAL(extractor::parseDuration("PT1h15m"), 4500); } BOOST_AUTO_TEST_SUITE_END() diff --git a/unit_tests/util/dynamic_graph.cpp b/unit_tests/util/dynamic_graph.cpp index 44f69eb76..263b60c7a 100644 --- a/unit_tests/util/dynamic_graph.cpp +++ b/unit_tests/util/dynamic_graph.cpp @@ -8,6 +8,9 @@ BOOST_AUTO_TEST_SUITE(dynamic_graph) +using namespace osrm; +using namespace osrm::util; + struct TestData { EdgeID id; diff --git a/unit_tests/util/range_table.cpp b/unit_tests/util/range_table.cpp index 01fe9448f..a5db4c597 100644 --- a/unit_tests/util/range_table.cpp +++ b/unit_tests/util/range_table.cpp @@ -7,11 +7,14 @@ #include #include +BOOST_AUTO_TEST_SUITE(range_table) + +using namespace osrm; +using namespace osrm::util; + constexpr unsigned BLOCK_SIZE = 16; typedef RangeTable TestRangeTable; -BOOST_AUTO_TEST_SUITE(range_table) - void ConstructionTest(stxxl::vector lengths, std::vector offsets) { BOOST_ASSERT(lengths.size() == offsets.size() - 1); diff --git a/unit_tests/util/static_graph.cpp b/unit_tests/util/static_graph.cpp index f9b69f629..7f6c6ab4c 100644 --- a/unit_tests/util/static_graph.cpp +++ b/unit_tests/util/static_graph.cpp @@ -10,6 +10,9 @@ BOOST_AUTO_TEST_SUITE(static_graph) +using namespace osrm; +using namespace osrm::util; + struct TestData { EdgeID id; diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index 9e0cc9520..fd3a19b69 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -25,10 +25,13 @@ BOOST_AUTO_TEST_SUITE(static_rtree) +using namespace osrm; +using namespace osrm::util; + constexpr uint32_t TEST_BRANCHING_FACTOR = 8; constexpr uint32_t TEST_LEAF_NODE_SIZE = 64; -typedef EdgeBasedNode TestData; +using TestData = extractor::EdgeBasedNode; using TestStaticRTree = StaticRTree, false, @@ -108,7 +111,7 @@ template struct RandomGraphFixture { int lat = lat_udist(g); int lon = lon_udist(g); - nodes.emplace_back(QueryNode(lat, lon, OSMNodeID(i))); + nodes.emplace_back(extractor::QueryNode(lat, lon, OSMNodeID(i))); coords->emplace_back(FixedPointCoordinate(lat, lon)); } @@ -131,7 +134,7 @@ template struct RandomGraphFixture } } - std::vector nodes; + std::vector nodes; std::shared_ptr> coords; std::vector edges; }; @@ -148,7 +151,7 @@ struct GraphFixture FixedPointCoordinate c(input_coords[i].first * COORDINATE_PRECISION, input_coords[i].second * COORDINATE_PRECISION); coords->emplace_back(c); - nodes.emplace_back(QueryNode(c.lat, c.lon, OSMNodeID(i))); + nodes.emplace_back(extractor::QueryNode(c.lat, c.lon, OSMNodeID(i))); } for (const auto &pair : input_edges) @@ -166,7 +169,7 @@ struct GraphFixture } } - std::vector nodes; + std::vector nodes; std::shared_ptr> coords; std::vector edges; }; @@ -252,7 +255,7 @@ void build_rtree(const std::string &prefix, boost::filesystem::ofstream node_stream(coords_path, std::ios::binary); const auto num_nodes = static_cast(fixture->nodes.size()); node_stream.write((char *)&num_nodes, sizeof(unsigned)); - node_stream.write((char *)&(fixture->nodes[0]), num_nodes * sizeof(QueryNode)); + node_stream.write((char *)&(fixture->nodes[0]), num_nodes * sizeof(extractor::QueryNode)); node_stream.close(); RTreeT r(fixture->edges, nodes_path, leaves_path, fixture->nodes); @@ -408,7 +411,7 @@ BOOST_AUTO_TEST_CASE(bearing_tests) std::string nodes_path; build_rtree("test_bearing", &fixture, leaves_path, nodes_path); MiniStaticRTree rtree(nodes_path, leaves_path, fixture.coords); - GeospatialQuery query(rtree, fixture.coords); + engine::GeospatialQuery query(rtree, fixture.coords); FixedPointCoordinate input(5.0 * COORDINATE_PRECISION, 5.1 * COORDINATE_PRECISION); diff --git a/unit_tests/util/string_util.cpp b/unit_tests/util/string_util.cpp index 1cee413b6..e3a7204cf 100644 --- a/unit_tests/util/string_util.cpp +++ b/unit_tests/util/string_util.cpp @@ -7,6 +7,9 @@ BOOST_AUTO_TEST_SUITE(string_util) +using namespace osrm; +using namespace osrm::util; + BOOST_AUTO_TEST_CASE(json_escaping) { std::string input{"\b\\"}; From 6991a38703e52b457893f779d51a1bab2f52d523 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Fri, 8 Jan 2016 01:31:57 +0100 Subject: [PATCH 047/701] Run clang-format --- include/contractor/contractor.hpp | 24 ++++--- include/contractor/contractor_options.hpp | 1 - include/contractor/crc32_processor.hpp | 1 - include/contractor/processing_chain.hpp | 17 ++--- include/contractor/query_edge.hpp | 1 - include/datastore/shared_memory_factory.hpp | 9 +-- include/engine/api_response_generator.hpp | 31 ++++---- include/engine/datafacade/datafacade_base.hpp | 9 ++- .../engine/datafacade/internal_datafacade.hpp | 22 +++--- include/engine/datafacade/shared_barriers.hpp | 1 - .../engine/datafacade/shared_datafacade.hpp | 28 ++++---- include/engine/datafacade/shared_datatype.hpp | 37 +++++----- include/engine/douglas_peucker.hpp | 1 - include/engine/geospatial_query.hpp | 24 +++---- .../engine/guidance/segment_compression.hpp | 2 +- include/engine/guidance/segment_list.hpp | 7 +- .../guidance/textual_route_annotation.hpp | 22 +++--- include/engine/internal_route_result.hpp | 4 +- .../engine/map_matching/bayes_classifier.hpp | 1 - .../map_matching/hidden_markov_model.hpp | 7 +- include/engine/object_encoder.hpp | 1 - include/engine/phantom_node.hpp | 4 +- include/engine/plugins/distance_table.hpp | 1 - include/engine/plugins/hello_world.hpp | 1 - include/engine/plugins/match.hpp | 12 ++-- include/engine/plugins/nearest.hpp | 4 +- include/engine/plugins/plugin_base.hpp | 1 - include/engine/plugins/timestamp.hpp | 1 - include/engine/plugins/trip.hpp | 12 ++-- include/engine/plugins/viaroute.hpp | 1 - include/engine/polyline_compressor.hpp | 1 - include/engine/polyline_formatter.hpp | 1 - include/engine/route_name_extraction.hpp | 3 +- .../routing_algorithms/alternative_path.hpp | 10 +-- .../direct_shortest_path.hpp | 1 - .../routing_algorithms/map_matching.hpp | 12 ++-- .../routing_algorithms/routing_base.hpp | 19 ++--- .../routing_algorithms/shortest_path.hpp | 1 - include/engine/search_engine.hpp | 1 - include/engine/search_engine_data.hpp | 4 +- include/engine/segment_information.hpp | 5 +- include/engine/trip/trip_brute_force.hpp | 1 - .../engine/trip/trip_farthest_insertion.hpp | 1 - .../engine/trip/trip_nearest_neighbour.hpp | 1 - include/engine/trip/trip_tabu_search.hpp | 1 - .../extractor/compressed_edge_container.hpp | 1 - .../extractor/edge_based_graph_factory.hpp | 1 - include/extractor/edge_based_node.hpp | 3 +- include/extractor/external_memory_node.hpp | 1 - include/extractor/extraction_containers.hpp | 1 - .../extractor/extraction_helper_functions.hpp | 1 - include/extractor/extraction_node.hpp | 1 - include/extractor/extraction_way.hpp | 1 - include/extractor/extractor_callbacks.hpp | 1 - include/extractor/extractor_options.hpp | 1 - .../first_and_last_segment_of_way.hpp | 1 - include/extractor/graph_compressor.hpp | 1 - include/extractor/import_edge.hpp | 1 - include/extractor/internal_extractor_edge.hpp | 1 - include/extractor/node_id.hpp | 1 - include/extractor/original_edge_data.hpp | 1 - include/extractor/query_node.hpp | 1 - include/extractor/raster_source.hpp | 1 - include/extractor/restriction.hpp | 1 - include/extractor/restriction_map.hpp | 2 - include/extractor/restriction_parser.hpp | 2 - include/extractor/scripting_environment.hpp | 1 - include/extractor/speed_profile.hpp | 1 - include/extractor/tarjan_scc.hpp | 3 +- include/extractor/travel_mode.hpp | 4 +- include/extractor/turn_instructions.hpp | 1 - include/osrm/coordinate.hpp | 1 - include/osrm/json_container.hpp | 5 +- include/osrm/libosrm_config.hpp | 1 - include/osrm/osrm.hpp | 4 +- include/osrm/route_parameters.hpp | 2 - include/osrm/strong_typedef.hpp | 1 - include/server/api_grammar.hpp | 1 - include/server/connection.hpp | 1 - include/server/http/compression_type.hpp | 1 - include/server/http/header.hpp | 1 - include/server/http/reply.hpp | 1 - include/server/http/request.hpp | 1 - include/server/request_handler.hpp | 1 - include/server/request_parser.hpp | 2 - include/server/server.hpp | 4 +- include/util/bearing.hpp | 1 - include/util/binary_heap.hpp | 1 - include/util/cast.hpp | 1 - include/util/compute_angle.hpp | 1 - include/util/coordinate_calculation.hpp | 1 - include/util/datastore_options.hpp | 1 - include/util/deallocating_vector.hpp | 4 +- include/util/debug_geometry.hpp | 3 - include/util/dist_table_wrapper.hpp | 1 - include/util/dynamic_graph.hpp | 3 +- include/util/fingerprint.hpp | 1 - include/util/fixed_point_number.hpp | 1 - include/util/floating_point.hpp | 1 - include/util/graph_loader.hpp | 7 +- include/util/hilbert_value.hpp | 1 - include/util/integer_range.hpp | 1 - include/util/iso_8601_duration_parser.hpp | 1 - include/util/json_logger.hpp | 1 - include/util/json_util.hpp | 6 +- include/util/lua_util.hpp | 1 - include/util/make_unique.hpp | 1 - include/util/matching_debug_info.hpp | 3 +- include/util/matrix_graph_wrapper.hpp | 4 +- include/util/mercator.hpp | 1 - include/util/node_based_graph.hpp | 5 +- include/util/osrm_exception.hpp | 1 - include/util/percent.hpp | 1 - include/util/range_algorithms.hpp | 1 - include/util/range_table.hpp | 1 - include/util/rectangle.hpp | 17 +++-- include/util/routed_options.hpp | 1 - include/util/shared_memory_vector_wrapper.hpp | 1 - include/util/simple_logger.hpp | 1 - include/util/static_graph.hpp | 1 - include/util/string_util.hpp | 1 - include/util/timing_util.hpp | 1 - include/util/tribool.hpp | 1 - include/util/trigonometry_table.hpp | 1 - include/util/xor_fast_hash.hpp | 1 - include/util/xor_fast_hash_storage.hpp | 1 - src/benchmarks/static_rtree.cpp | 5 +- src/contractor/processing_chain.cpp | 66 +++++++++-------- src/extractor/compressed_edge_container.cpp | 18 +++-- src/extractor/edge_based_graph_factory.cpp | 33 +++++---- src/extractor/extraction_containers.cpp | 21 +++--- src/extractor/extractor.cpp | 43 +++++------ src/extractor/extractor_callbacks.cpp | 5 +- src/extractor/extractor_options.cpp | 2 +- src/extractor/graph_compressor.cpp | 4 +- src/extractor/raster_source.cpp | 5 +- src/extractor/restriction_parser.cpp | 5 +- src/server/request_handler.cpp | 24 +++---- src/tools/check-hsgr.cpp | 23 +++--- src/tools/components.cpp | 43 ++++++----- src/tools/contract.cpp | 18 ++--- src/tools/datastore.cpp | 41 ++++++----- src/tools/extract.cpp | 11 +-- src/tools/io-benchmark.cpp | 72 +++++++++++-------- src/tools/simpleclient.cpp | 3 +- src/tools/springclean.cpp | 11 +-- src/util/coordinate.cpp | 3 +- src/util/osrm_exception.cpp | 1 - unit_tests/engine/douglas_peucker.cpp | 4 +- 149 files changed, 457 insertions(+), 498 deletions(-) diff --git a/include/contractor/contractor.hpp b/include/contractor/contractor.hpp index 29f0f22dd..633a67d41 100644 --- a/include/contractor/contractor.hpp +++ b/include/contractor/contractor.hpp @@ -74,8 +74,11 @@ class Contractor // using ContractorHeap = util::BinaryHeap // >; - using ContractorHeap = - util::BinaryHeap>; + using ContractorHeap = util::BinaryHeap>; using ContractorEdge = ContractorGraph::InputEdge; struct ContractorThreadData @@ -258,7 +261,8 @@ class Contractor // } // } // - // util::SimpleLogger().Write() << "edges at node with id " << highestNode << " has degree + // util::SimpleLogger().Write() << "edges at node with id " << highestNode << " has + // degree // " << maxdegree; // for(unsigned i = contractor_graph->BeginEdges(highestNode); i < // contractor_graph->EndEdges(highestNode); ++i) { @@ -345,9 +349,10 @@ class Contractor if (!flushed_contractor && (number_of_contracted_nodes > static_cast(number_of_nodes * 0.65 * core_factor))) { - util::DeallocatingVector new_edge_set; // this one is not explicitely - // cleared since it goes out of - // scope anywa + util::DeallocatingVector + new_edge_set; // this one is not explicitely + // cleared since it goes out of + // scope anywa std::cout << " [flush " << number_of_contracted_nodes << " nodes] " << std::flush; // Delete old heap data to free memory that we need for the coming operations @@ -595,7 +600,8 @@ class Contractor // avgdegree /= std::max((unsigned)1,(unsigned)remaining_nodes.size() ); // quaddegree /= std::max((unsigned)1,(unsigned)remaining_nodes.size() ); // - // util::SimpleLogger().Write() << "rest: " << remaining_nodes.size() << ", max: " + // util::SimpleLogger().Write() << "rest: " << remaining_nodes.size() << ", + // max: " // << maxdegree << ", min: " << mindegree << ", avg: " << avgdegree << ", // quad: " << quaddegree; @@ -639,7 +645,8 @@ class Contractor } util::SimpleLogger().Write() << "[core] " << remaining_nodes.size() << " nodes " - << contractor_graph->GetNumberOfEdges() << " edges." << std::endl; + << contractor_graph->GetNumberOfEdges() << " edges." + << std::endl; thread_data_list.data.clear(); } @@ -1067,7 +1074,6 @@ class Contractor std::vector is_core_node; util::XORFastHash fast_hash; }; - } } diff --git a/include/contractor/contractor_options.hpp b/include/contractor/contractor_options.hpp index cb29d82f3..589f6bc13 100644 --- a/include/contractor/contractor_options.hpp +++ b/include/contractor/contractor_options.hpp @@ -55,7 +55,6 @@ struct ContractorOptions static void GenerateOutputFilesNames(ContractorConfig &extractor_config); }; - } } diff --git a/include/contractor/crc32_processor.hpp b/include/contractor/crc32_processor.hpp index 827cdda0a..eaef76c8e 100644 --- a/include/contractor/crc32_processor.hpp +++ b/include/contractor/crc32_processor.hpp @@ -119,7 +119,6 @@ struct RangebasedCRC32 private: IteratorbasedCRC32 crc32; }; - } } diff --git a/include/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp index d1bc08e24..08247cf44 100644 --- a/include/contractor/processing_chain.hpp +++ b/include/contractor/processing_chain.hpp @@ -47,21 +47,22 @@ class Prepare void WriteCoreNodeMarker(std::vector &&is_core_node) const; void WriteNodeLevels(std::vector &&node_levels) const; void ReadNodeLevels(std::vector &contraction_order) const; - std::size_t WriteContractedGraph(unsigned number_of_edge_based_nodes, - const util::DeallocatingVector &contracted_edge_list); + std::size_t + WriteContractedGraph(unsigned number_of_edge_based_nodes, + const util::DeallocatingVector &contracted_edge_list); void FindComponents(unsigned max_edge_id, const util::DeallocatingVector &edges, std::vector &nodes) const; private: ContractorConfig config; - std::size_t LoadEdgeExpandedGraph(const std::string &edge_based_graph_path, - util::DeallocatingVector &edge_based_edge_list, - const std::string &edge_segment_lookup_path, - const std::string &edge_penalty_path, - const std::string &segment_speed_path); + std::size_t + LoadEdgeExpandedGraph(const std::string &edge_based_graph_path, + util::DeallocatingVector &edge_based_edge_list, + const std::string &edge_segment_lookup_path, + const std::string &edge_penalty_path, + const std::string &segment_speed_path); }; - } } diff --git a/include/contractor/query_edge.hpp b/include/contractor/query_edge.hpp index 75949c4dd..a3265b882 100644 --- a/include/contractor/query_edge.hpp +++ b/include/contractor/query_edge.hpp @@ -53,7 +53,6 @@ struct QueryEdge data.id == right.data.id); } }; - } } diff --git a/include/datastore/shared_memory_factory.hpp b/include/datastore/shared_memory_factory.hpp index 37ae802c4..4c4cb2aa6 100644 --- a/include/datastore/shared_memory_factory.hpp +++ b/include/datastore/shared_memory_factory.hpp @@ -115,7 +115,8 @@ class SharedMemory region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write); remover.SetID(shm.get_shmid()); - util::SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; + util::SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size + << " bytes"; } } @@ -247,7 +248,8 @@ class SharedMemory region = boost::interprocess::mapped_region(shm, boost::interprocess::read_write); remover.SetID(key); - util::SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size << " bytes"; + util::SimpleLogger().Write(logDEBUG) << "writeable memory allocated " << size + << " bytes"; } } @@ -346,7 +348,7 @@ template class SharedMemoryFactory_tmpl catch (const boost::interprocess::interprocess_exception &e) { util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " - << e.get_error_code(); + << e.get_error_code(); throw util::exception(e.what()); } } @@ -356,7 +358,6 @@ template class SharedMemoryFactory_tmpl }; using SharedMemoryFactory = SharedMemoryFactory_tmpl<>; - } } diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index 02dbf70f0..d8c16ba33 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -96,14 +96,15 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con const InternalRouteResult &raw_route, util::json::Object &json_result) { - if( not raw_route.is_valid() ){ - return; + if (not raw_route.is_valid()) + { + return; } const constexpr bool ALLOW_SIMPLIFICATION = true; const constexpr bool EXTRACT_ROUTE = false; const constexpr bool EXTRACT_ALTERNATIVE = true; Segments segment_list(raw_route, EXTRACT_ROUTE, config.zoom_level, ALLOW_SIMPLIFICATION, - facade); + facade); json_result.values["route_summary"] = SummarizeRoute(raw_route, segment_list); json_result.values["via_points"] = ListViaPoints(raw_route); json_result.values["via_indices"] = ListViaIndices(segment_list); @@ -125,7 +126,7 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con if (raw_route.has_alternative()) { Segments alternate_segment_list(raw_route, EXTRACT_ALTERNATIVE, config.zoom_level, - ALLOW_SIMPLIFICATION, facade); + ALLOW_SIMPLIFICATION, facade); // Alternative Route Summaries are stored in an array to (down the line) allow multiple // alternatives @@ -140,7 +141,8 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con auto alternate_geometry_string = GetGeometry(config.compression, alternate_segment_list); util::json::Array json_alternate_geometries_array; - json_alternate_geometries_array.values.emplace_back(std::move(alternate_geometry_string)); + json_alternate_geometries_array.values.emplace_back( + std::move(alternate_geometry_string)); json_result.values["alternative_geometries"] = json_alternate_geometries_array; } @@ -192,7 +194,8 @@ ApiResponseGenerator::SummarizeRoute(const InternalRouteResult &raw { const auto start_name_id = raw_route.segment_end_coordinates.front().source_phantom.name_id; json_route_summary.values["start_point"] = facade->get_name_for_id(start_name_id); - const auto destination_name_id = raw_route.segment_end_coordinates.back().target_phantom.name_id; + const auto destination_name_id = + raw_route.segment_end_coordinates.back().target_phantom.name_id; json_route_summary.values["end_point"] = facade->get_name_for_id(destination_name_id); } json_route_summary.values["total_time"] = segment_list.GetDuration(); @@ -217,8 +220,10 @@ ApiResponseGenerator::ListViaPoints(const InternalRouteResult &raw_ { std::string tmp; util::json::Array json_coordinate; - json_coordinate.values.emplace_back(nodes.target_phantom.location.lat / COORDINATE_PRECISION); - json_coordinate.values.emplace_back(nodes.target_phantom.location.lon / COORDINATE_PRECISION); + json_coordinate.values.emplace_back(nodes.target_phantom.location.lat / + COORDINATE_PRECISION); + json_coordinate.values.emplace_back(nodes.target_phantom.location.lon / + COORDINATE_PRECISION); json_via_points_array.values.emplace_back(std::move(json_coordinate)); } return json_via_points_array; @@ -235,7 +240,8 @@ ApiResponseGenerator::ListViaIndices(const Segments &segment_list) } template -util::json::Value ApiResponseGenerator::GetGeometry(const bool return_encoded, const Segments &segments) const +util::json::Value ApiResponseGenerator::GetGeometry(const bool return_encoded, + const Segments &segments) const { if (return_encoded) return PolylineFormatter().printEncodedString(segments.Get()); @@ -284,11 +290,12 @@ ApiResponseGenerator::BuildHintData(const InternalRouteResult &raw_ } template -ApiResponseGenerator MakeApiResponseGenerator(DataFacadeT *facade){ - return ApiResponseGenerator(facade); +ApiResponseGenerator MakeApiResponseGenerator(DataFacadeT *facade) +{ + return ApiResponseGenerator(facade); } } // namespace engine } // namespace osrm -#endif //ENGINE_GUIDANCE_API_RESPONSE_GENERATOR_HPP_ +#endif // ENGINE_GUIDANCE_API_RESPONSE_GENERATOR_HPP_ diff --git a/include/engine/datafacade/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp index ab419bf19..c4c4c87f4 100644 --- a/include/engine/datafacade/datafacade_base.hpp +++ b/include/engine/datafacade/datafacade_base.hpp @@ -85,10 +85,10 @@ template class BaseDataFacade const int bearing = 0, const int bearing_range = 180) = 0; - virtual std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, - const int bearing = 0, - const int bearing_range = 180) = 0; + virtual std::pair NearestPhantomNodeWithAlternativeFromBigComponent( + const util::FixedPointCoordinate &input_coordinate, + const int bearing = 0, + const int bearing_range = 180) = 0; virtual unsigned GetCheckSum() const = 0; @@ -102,7 +102,6 @@ template class BaseDataFacade virtual std::string GetTimestamp() const = 0; }; - } } } diff --git a/include/engine/datafacade/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp index ba43513da..bbe18249a 100644 --- a/include/engine/datafacade/internal_datafacade.hpp +++ b/include/engine/datafacade/internal_datafacade.hpp @@ -37,7 +37,8 @@ template class InternalDataFacade final : public BaseDataFacad using QueryGraph = util::StaticGraph; using InputEdge = typename QueryGraph::InputEdge; using RTreeLeaf = typename super::RTreeLeaf; - using InternalRTree = util::StaticRTree::vector, false>; + using InternalRTree = + util::StaticRTree::vector, false>; using InternalGeospatialQuery = GeospatialQuery; InternalDataFacade() {} @@ -98,8 +99,8 @@ template class InternalDataFacade final : public BaseDataFacad BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); // BOOST_ASSERT_MSG(0 != edge_list.size(), "edge list empty"); - util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() - << " edges"; + util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " + << edge_list.size() << " edges"; m_query_graph = std::unique_ptr(new QueryGraph(node_list, edge_list)); BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); @@ -120,7 +121,8 @@ template class InternalDataFacade final : public BaseDataFacad for (unsigned i = 0; i < number_of_coordinates; ++i) { nodes_input_stream.read((char *)¤t_node, sizeof(extractor::QueryNode)); - m_coordinate_list->at(i) = util::FixedPointCoordinate(current_node.lat, current_node.lon); + m_coordinate_list->at(i) = + util::FixedPointCoordinate(current_node.lat, current_node.lon); BOOST_ASSERT((std::abs(m_coordinate_list->at(i).lat) >> 30) == 0); BOOST_ASSERT((std::abs(m_coordinate_list->at(i).lon) >> 30) == 0); } @@ -140,7 +142,8 @@ template class InternalDataFacade final : public BaseDataFacad extractor::OriginalEdgeData current_edge_data; for (unsigned i = 0; i < number_of_edges; ++i) { - edges_input_stream.read((char *)&(current_edge_data), sizeof(extractor::OriginalEdgeData)); + edges_input_stream.read((char *)&(current_edge_data), + sizeof(extractor::OriginalEdgeData)); m_via_node_list[i] = current_edge_data.via_node; m_name_ID_list[i] = current_edge_data.name_id; m_turn_instruction_list[i] = current_edge_data.turn_instruction; @@ -371,10 +374,10 @@ template class InternalDataFacade final : public BaseDataFacad bearing_range); } - std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, - const int bearing = 0, - const int bearing_range = 180) override final + std::pair NearestPhantomNodeWithAlternativeFromBigComponent( + const util::FixedPointCoordinate &input_coordinate, + const int bearing = 0, + const int bearing_range = 180) override final { if (!m_static_rtree.get()) { @@ -444,7 +447,6 @@ template class InternalDataFacade final : public BaseDataFacad std::string GetTimestamp() const override final { return m_timestamp; } }; - } } } diff --git a/include/engine/datafacade/shared_barriers.hpp b/include/engine/datafacade/shared_barriers.hpp index 4eb7d5371..e22e27ea4 100644 --- a/include/engine/datafacade/shared_barriers.hpp +++ b/include/engine/datafacade/shared_barriers.hpp @@ -36,7 +36,6 @@ struct SharedBarriers // Is there any query? int number_of_queries; }; - } } } diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 536cc230e..62fb08363 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -38,7 +38,8 @@ template class SharedDataFacade final : public BaseDataFacade< using NameIndexBlock = typename util::RangeTable<16, true>::BlockT; using InputEdge = typename QueryGraph::InputEdge; using RTreeLeaf = typename super::RTreeLeaf; - using SharedRTree = util::StaticRTree::vector, true>; + using SharedRTree = + util::StaticRTree::vector, true>; using SharedGeospatialQuery = GeospatialQuery; using TimeStampedRTreePair = std::pair>; using RTreeNode = typename SharedRTree::TreeNode; @@ -125,19 +126,22 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadNodeAndEdgeInformation() { - util::FixedPointCoordinate *coordinate_list_ptr = data_layout->GetBlockPtr( - shared_memory, SharedDataLayout::COORDINATE_LIST); + util::FixedPointCoordinate *coordinate_list_ptr = + data_layout->GetBlockPtr(shared_memory, + SharedDataLayout::COORDINATE_LIST); m_coordinate_list = util::make_unique::vector>( coordinate_list_ptr, data_layout->num_entries[SharedDataLayout::COORDINATE_LIST]); extractor::TravelMode *travel_mode_list_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::TRAVEL_MODE); + data_layout->GetBlockPtr(shared_memory, + SharedDataLayout::TRAVEL_MODE); typename util::ShM::vector travel_mode_list( travel_mode_list_ptr, data_layout->num_entries[SharedDataLayout::TRAVEL_MODE]); m_travel_mode_list.swap(travel_mode_list); - extractor::TurnInstruction *turn_instruction_list_ptr = data_layout->GetBlockPtr( - shared_memory, SharedDataLayout::TURN_INSTRUCTION); + extractor::TurnInstruction *turn_instruction_list_ptr = + data_layout->GetBlockPtr( + shared_memory, SharedDataLayout::TURN_INSTRUCTION); typename util::ShM::vector turn_instruction_list( turn_instruction_list_ptr, data_layout->num_entries[SharedDataLayout::TURN_INSTRUCTION]); @@ -258,7 +262,8 @@ template class SharedDataFacade final : public BaseDataFacade< file_index_path = boost::filesystem::path(file_index_ptr); if (!boost::filesystem::exists(file_index_path)) { - util::SimpleLogger().Write(logDEBUG) << "Leaf file name " << file_index_path.string(); + util::SimpleLogger().Write(logDEBUG) << "Leaf file name " + << file_index_path.string(); throw util::exception("Could not load leaf index file. " "Is any data loaded into shared memory?"); } @@ -397,10 +402,10 @@ template class SharedDataFacade final : public BaseDataFacade< bearing_range); } - std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, - const int bearing = 0, - const int bearing_range = 180) override final + std::pair NearestPhantomNodeWithAlternativeFromBigComponent( + const util::FixedPointCoordinate &input_coordinate, + const int bearing = 0, + const int bearing_range = 180) override final { if (!m_static_rtree.get() || CURRENT_TIMESTAMP != m_static_rtree->first) { @@ -452,7 +457,6 @@ template class SharedDataFacade final : public BaseDataFacade< std::string GetTimestamp() const override final { return m_timestamp; } }; - } } } diff --git a/include/engine/datafacade/shared_datatype.hpp b/include/engine/datafacade/shared_datatype.hpp index b576008cc..84a9d266b 100644 --- a/include/engine/datafacade/shared_datatype.hpp +++ b/include/engine/datafacade/shared_datatype.hpp @@ -54,41 +54,41 @@ struct SharedDataLayout void PrintInformation() const { util::SimpleLogger().Write(logDEBUG) << "NAME_OFFSETS " - << ": " << GetBlockSize(NAME_OFFSETS); + << ": " << GetBlockSize(NAME_OFFSETS); util::SimpleLogger().Write(logDEBUG) << "NAME_BLOCKS " - << ": " << GetBlockSize(NAME_BLOCKS); + << ": " << GetBlockSize(NAME_BLOCKS); util::SimpleLogger().Write(logDEBUG) << "NAME_CHAR_LIST " - << ": " << GetBlockSize(NAME_CHAR_LIST); + << ": " << GetBlockSize(NAME_CHAR_LIST); util::SimpleLogger().Write(logDEBUG) << "NAME_ID_LIST " - << ": " << GetBlockSize(NAME_ID_LIST); + << ": " << GetBlockSize(NAME_ID_LIST); util::SimpleLogger().Write(logDEBUG) << "VIA_NODE_LIST " - << ": " << GetBlockSize(VIA_NODE_LIST); + << ": " << GetBlockSize(VIA_NODE_LIST); util::SimpleLogger().Write(logDEBUG) << "GRAPH_NODE_LIST " - << ": " << GetBlockSize(GRAPH_NODE_LIST); + << ": " << GetBlockSize(GRAPH_NODE_LIST); util::SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST " - << ": " << GetBlockSize(GRAPH_EDGE_LIST); + << ": " << GetBlockSize(GRAPH_EDGE_LIST); util::SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST " - << ": " << GetBlockSize(COORDINATE_LIST); + << ": " << GetBlockSize(COORDINATE_LIST); util::SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION " - << ": " << GetBlockSize(TURN_INSTRUCTION); + << ": " << GetBlockSize(TURN_INSTRUCTION); util::SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE " - << ": " << GetBlockSize(TRAVEL_MODE); + << ": " << GetBlockSize(TRAVEL_MODE); util::SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE " - << ": " << GetBlockSize(R_SEARCH_TREE); + << ": " << GetBlockSize(R_SEARCH_TREE); util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX " - << ": " << GetBlockSize(GEOMETRIES_INDEX); + << ": " << GetBlockSize(GEOMETRIES_INDEX); util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST " - << ": " << GetBlockSize(GEOMETRIES_LIST); + << ": " << GetBlockSize(GEOMETRIES_LIST); util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDICATORS" - << ": " << GetBlockSize(GEOMETRIES_INDICATORS); + << ": " << GetBlockSize(GEOMETRIES_INDICATORS); util::SimpleLogger().Write(logDEBUG) << "HSGR_CHECKSUM " - << ": " << GetBlockSize(HSGR_CHECKSUM); + << ": " << GetBlockSize(HSGR_CHECKSUM); util::SimpleLogger().Write(logDEBUG) << "TIMESTAMP " - << ": " << GetBlockSize(TIMESTAMP); + << ": " << GetBlockSize(TIMESTAMP); util::SimpleLogger().Write(logDEBUG) << "FILE_INDEX_PATH " - << ": " << GetBlockSize(FILE_INDEX_PATH); + << ": " << GetBlockSize(FILE_INDEX_PATH); util::SimpleLogger().Write(logDEBUG) << "CORE_MARKER " - << ": " << GetBlockSize(CORE_MARKER); + << ": " << GetBlockSize(CORE_MARKER); } template inline void SetBlockSize(BlockID bid, uint64_t entries) @@ -171,7 +171,6 @@ struct SharedDataTimestamp SharedDataType data; unsigned timestamp; }; - } } } diff --git a/include/engine/douglas_peucker.hpp b/include/engine/douglas_peucker.hpp index c7e8dd0b2..df4fe921d 100644 --- a/include/engine/douglas_peucker.hpp +++ b/include/engine/douglas_peucker.hpp @@ -55,7 +55,6 @@ class DouglasPeucker void Run(RandomAccessIt begin, RandomAccessIt end, const unsigned zoom_level); void Run(std::vector &input_geometry, const unsigned zoom_level); }; - } } diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index efd8c2603..41307043a 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -77,10 +77,10 @@ template class GeospatialQuery // Returns the nearest phantom node. If this phantom node is not from a big component // a second phantom node is return that is the nearest coordinate in a big component. - std::pair - NearestPhantomNodeWithAlternativeFromBigComponent(const util::FixedPointCoordinate &input_coordinate, - const int bearing = 0, - const int bearing_range = 180) + std::pair NearestPhantomNodeWithAlternativeFromBigComponent( + const util::FixedPointCoordinate &input_coordinate, + const int bearing = 0, + const int bearing_range = 180) { bool has_small_component = false; bool has_big_component = false; @@ -139,9 +139,10 @@ template class GeospatialQuery { util::FixedPointCoordinate point_on_segment; double ratio; - const auto current_perpendicular_distance = util::coordinate_calculation::perpendicularDistance( - coordinates->at(data.u), coordinates->at(data.v), input_coordinate, point_on_segment, - ratio); + const auto current_perpendicular_distance = + util::coordinate_calculation::perpendicularDistance( + coordinates->at(data.u), coordinates->at(data.v), input_coordinate, + point_on_segment, ratio); auto transformed = PhantomNodeWithDistance{PhantomNode{data, point_on_segment}, current_perpendicular_distance}; @@ -163,8 +164,8 @@ template class GeospatialQuery const int filter_bearing, const int filter_bearing_range) { - const double forward_edge_bearing = - util::coordinate_calculation::bearing(coordinates->at(segment.u), coordinates->at(segment.v)); + const double forward_edge_bearing = util::coordinate_calculation::bearing( + coordinates->at(segment.u), coordinates->at(segment.v)); const double backward_edge_bearing = (forward_edge_bearing + 180) > 360 ? (forward_edge_bearing - 180) @@ -172,11 +173,11 @@ template class GeospatialQuery const bool forward_bearing_valid = util::bearing::CheckInBounds(std::round(forward_edge_bearing), filter_bearing, - filter_bearing_range) && + filter_bearing_range) && segment.forward_edge_based_node_id != SPECIAL_NODEID; const bool backward_bearing_valid = util::bearing::CheckInBounds(std::round(backward_edge_bearing), filter_bearing, - filter_bearing_range) && + filter_bearing_range) && segment.reverse_edge_based_node_id != SPECIAL_NODEID; return std::make_pair(forward_bearing_valid, backward_bearing_valid); } @@ -184,7 +185,6 @@ template class GeospatialQuery RTreeT &rtree; const std::shared_ptr coordinates; }; - } } diff --git a/include/engine/guidance/segment_compression.hpp b/include/engine/guidance/segment_compression.hpp index 7981dbcaa..b9eea766d 100644 --- a/include/engine/guidance/segment_compression.hpp +++ b/include/engine/guidance/segment_compression.hpp @@ -63,4 +63,4 @@ inline void CombineSimilarSegments(std::vector &segments) } // namespace engine } // namespace osrm -#endif //ENGINE_GUIDANCE_PROCESSING_SEGMENT_COMPRESSION_HPP_ +#endif // ENGINE_GUIDANCE_PROCESSING_SEGMENT_COMPRESSION_HPP_ diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index ff42b77e6..8ae9b6884 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -146,7 +146,8 @@ void SegmentList::AddLeg(const std::vector &leg_data, const extractor::TravelMode travel_mode = (traversed_in_reverse ? target_node.backward_travel_mode : target_node.forward_travel_mode); segments.emplace_back(target_node.location, target_node.name_id, segment_duration, 0.f, - is_via_leg ? extractor::TurnInstruction::ReachViaLocation : extractor::TurnInstruction::NoTurn, + is_via_leg ? extractor::TurnInstruction::ReachViaLocation + : extractor::TurnInstruction::NoTurn, true, true, travel_mode); } @@ -220,8 +221,8 @@ void SegmentList::Finalize(const bool extract_alternative, { // move down names by one, q&d hack segments[i - 1].name_id = segments[i].name_id; - segments[i].length = util::coordinate_calculation::greatCircleDistance(segments[i - 1].location, - segments[i].location); + segments[i].length = util::coordinate_calculation::greatCircleDistance( + segments[i - 1].location, segments[i].location); } float segment_length = 0.; diff --git a/include/engine/guidance/textual_route_annotation.hpp b/include/engine/guidance/textual_route_annotation.hpp index 5a13428ba..da9a9d8bc 100644 --- a/include/engine/guidance/textual_route_annotation.hpp +++ b/include/engine/guidance/textual_route_annotation.hpp @@ -21,13 +21,13 @@ namespace engine { namespace guidance { -template< typename DataFacadeT > -inline util::json::Array -AnnotateRoute(const std::vector &route_segments, DataFacadeT* facade) +template +inline util::json::Array AnnotateRoute(const std::vector &route_segments, + DataFacadeT *facade) { util::json::Array json_instruction_array; - if( route_segments.empty() ) - return json_instruction_array; + if (route_segments.empty()) + return json_instruction_array; // Segment information has following format: //["instruction id","streetname",length,position,time,"length","earth_direction",azimuth] std::int32_t necessary_segments_running_index = 0; @@ -42,7 +42,7 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT round_about = {std::numeric_limits::max(), 0, 0}; std::string temp_dist, temp_length, temp_duration, temp_bearing, temp_instruction; - //Generate annotations for every segment + // Generate annotations for every segment for (const SegmentInformation &segment : route_segments) { util::json::Array json_instruction_row; @@ -59,8 +59,8 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT std::string current_turn_instruction; if (extractor::TurnInstruction::LeaveRoundAbout == current_instruction) { - temp_instruction = - std::to_string(util::cast::enum_to_underlying(extractor::TurnInstruction::EnterRoundAbout)); + temp_instruction = std::to_string(util::cast::enum_to_underlying( + extractor::TurnInstruction::EnterRoundAbout)); current_turn_instruction += temp_instruction; current_turn_instruction += "-"; temp_instruction = std::to_string(round_about.leave_at_exit + 1); @@ -110,9 +110,9 @@ AnnotateRoute(const std::vector &route_segments, DataFacadeT } util::json::Array json_last_instruction_row; - temp_instruction = - std::to_string(util::cast::enum_to_underlying(extractor::TurnInstruction::ReachedYourDestination)); - json_last_instruction_row.values.emplace_back( std::move(temp_instruction)); + temp_instruction = std::to_string( + util::cast::enum_to_underlying(extractor::TurnInstruction::ReachedYourDestination)); + json_last_instruction_row.values.emplace_back(std::move(temp_instruction)); json_last_instruction_row.values.push_back(""); json_last_instruction_row.values.push_back(0); json_last_instruction_row.values.push_back(necessary_segments_running_index - 1); diff --git a/include/engine/internal_route_result.hpp b/include/engine/internal_route_result.hpp index d4536b405..25a1c9605 100644 --- a/include/engine/internal_route_result.hpp +++ b/include/engine/internal_route_result.hpp @@ -19,7 +19,8 @@ struct PathData { PathData() : node(SPECIAL_NODEID), name_id(INVALID_EDGE_WEIGHT), segment_duration(INVALID_EDGE_WEIGHT), - turn_instruction(extractor::TurnInstruction::NoTurn), travel_mode(TRAVEL_MODE_INACCESSIBLE) + turn_instruction(extractor::TurnInstruction::NoTurn), + travel_mode(TRAVEL_MODE_INACCESSIBLE) { } @@ -65,7 +66,6 @@ struct InternalRouteResult { } }; - } } diff --git a/include/engine/map_matching/bayes_classifier.hpp b/include/engine/map_matching/bayes_classifier.hpp index af2c60b29..f3c2e8eee 100644 --- a/include/engine/map_matching/bayes_classifier.hpp +++ b/include/engine/map_matching/bayes_classifier.hpp @@ -94,7 +94,6 @@ class BayesClassifier double positive_apriori_probability; double negative_apriori_probability; }; - } } } diff --git a/include/engine/map_matching/hidden_markov_model.hpp b/include/engine/map_matching/hidden_markov_model.hpp index f7528d61a..c387c1faf 100644 --- a/include/engine/map_matching/hidden_markov_model.hpp +++ b/include/engine/map_matching/hidden_markov_model.hpp @@ -34,8 +34,7 @@ struct EmissionLogProbability double operator()(const double distance) const { - return -0.5 * (log_2_pi + (distance / sigma_z) * (distance / sigma_z)) - - log_sigma_z; + return -0.5 * (log_2_pi + (distance / sigma_z) * (distance / sigma_z)) - log_sigma_z; } }; @@ -116,8 +115,7 @@ template struct HiddenMarkovModel viterbi[initial_timestamp][s] = emission_log_probability(candidates_list[initial_timestamp][s].distance); parents[initial_timestamp][s] = std::make_pair(initial_timestamp, s); - pruned[initial_timestamp][s] = - viterbi[initial_timestamp][s] < MINIMAL_LOG_PROB; + pruned[initial_timestamp][s] = viterbi[initial_timestamp][s] < MINIMAL_LOG_PROB; suspicious[initial_timestamp][s] = false; breakage[initial_timestamp] = @@ -140,7 +138,6 @@ template struct HiddenMarkovModel return initial_timestamp; } }; - } } } diff --git a/include/engine/object_encoder.hpp b/include/engine/object_encoder.hpp index b97dbc509..c9fe21b04 100644 --- a/include/engine/object_encoder.hpp +++ b/include/engine/object_encoder.hpp @@ -63,7 +63,6 @@ struct ObjectEncoder } } }; - } } diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index 585d2edcd..1c258b8ef 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -34,7 +34,8 @@ struct PhantomNode PhantomNode(); - template PhantomNode(const OtherT &other, const util::FixedPointCoordinate &foot_point) + template + PhantomNode(const OtherT &other, const util::FixedPointCoordinate &foot_point) { forward_node_id = other.forward_edge_based_node_id; reverse_node_id = other.reverse_edge_based_node_id; @@ -137,7 +138,6 @@ inline std::ostream &operator<<(std::ostream &out, const PhantomNode &pn) << "loc: " << pn.location; return out; } - } } diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index d72253909..1a37cfd06 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -219,7 +219,6 @@ template class DistanceTablePlugin final : public BasePlugin std::string descriptor_string; DataFacadeT *facade; }; - } } } diff --git a/include/engine/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp index 38a62b37c..1b79ca3e2 100644 --- a/include/engine/plugins/hello_world.hpp +++ b/include/engine/plugins/hello_world.hpp @@ -80,7 +80,6 @@ class HelloWorldPlugin final : public BasePlugin private: std::string descriptor_string; }; - } } } diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 9df0aa2af..3dded7b99 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -37,7 +37,9 @@ template class MapMatchingPlugin : public BasePlugin using SubMatching = routing_algorithms::SubMatching; using SubMatchingList = routing_algorithms::SubMatchingList; using CandidateLists = routing_algorithms::CandidateLists; - using ClassifierT = map_matching::BayesClassifier; + using ClassifierT = map_matching::BayesClassifier; using TraceClassification = ClassifierT::ClassificationT; public: @@ -203,13 +205,13 @@ template class MapMatchingPlugin : public BasePlugin if (route_parameters.geometry || route_parameters.print_instructions) { using SegmentList = guidance::SegmentList; - //Passing false to extract_alternative extracts the route. + // Passing false to extract_alternative extracts the route. const constexpr bool EXTRACT_ROUTE = false; // by passing false to segment_list, we skip the douglas peucker simplification // and mark all segments as necessary within the generation process const constexpr bool NO_ROUTE_SIMPLIFICATION = false; SegmentList segment_list(raw_route, EXTRACT_ROUTE, route_parameters.zoom_level, - NO_ROUTE_SIMPLIFICATION, facade); + NO_ROUTE_SIMPLIFICATION, facade); if (route_parameters.geometry) { @@ -220,8 +222,7 @@ template class MapMatchingPlugin : public BasePlugin if (route_parameters.print_instructions) { subtrace.values["instructions"] = - guidance::AnnotateRoute( - segment_list.Get(), facade); + guidance::AnnotateRoute(segment_list.Get(), facade); } util::json::Object json_route_summary; @@ -379,7 +380,6 @@ template class MapMatchingPlugin : public BasePlugin int max_locations_map_matching; ClassifierT classifier; }; - } } } diff --git a/include/engine/plugins/nearest.hpp b/include/engine/plugins/nearest.hpp index 03604b1dc..0a41fa409 100644 --- a/include/engine/plugins/nearest.hpp +++ b/include/engine/plugins/nearest.hpp @@ -30,8 +30,7 @@ template class NearestPlugin final : public BasePlugin util::json::Object &json_result) override final { // check number of parameters - if (route_parameters.coordinates.empty() || - !route_parameters.coordinates.front().IsValid()) + if (route_parameters.coordinates.empty() || !route_parameters.coordinates.front().IsValid()) { return Status::Error; } @@ -101,7 +100,6 @@ template class NearestPlugin final : public BasePlugin DataFacadeT *facade; std::string descriptor_string; }; - } } } diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index a2c7eba8c..3f3e62719 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -112,7 +112,6 @@ class BasePlugin return snapped_phantoms; } }; - } } } diff --git a/include/engine/plugins/timestamp.hpp b/include/engine/plugins/timestamp.hpp index 1ec3d0a62..2bf4bdd50 100644 --- a/include/engine/plugins/timestamp.hpp +++ b/include/engine/plugins/timestamp.hpp @@ -36,7 +36,6 @@ template class TimestampPlugin final : public BasePlugin const DataFacadeT *facade; std::string descriptor_string; }; - } } } diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index 54632fdcd..e2705f9bc 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -149,8 +149,8 @@ template class RoundTripPlugin final : public BasePlugin } // Run TarjanSCC - auto wrapper = std::make_shared>(result_table.GetTable(), - number_of_locations); + auto wrapper = std::make_shared>( + result_table.GetTable(), number_of_locations); auto scc = extractor::TarjanSCC>(wrapper); scc.run(); @@ -301,13 +301,12 @@ template class RoundTripPlugin final : public BasePlugin if (component_size < BF_MAX_FEASABLE) { - scc_route = - trip::BruteForceTrip(start, end, number_of_locations, result_table); + scc_route = trip::BruteForceTrip(start, end, number_of_locations, result_table); } else { - scc_route = trip::FarthestInsertionTrip(start, end, number_of_locations, - result_table); + scc_route = + trip::FarthestInsertionTrip(start, end, number_of_locations, result_table); } // use this output if debugging of route is needed: @@ -366,7 +365,6 @@ template class RoundTripPlugin final : public BasePlugin return Status::Ok; } }; - } } } diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index 8e58c00f9..b2790a6c3 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -166,7 +166,6 @@ template class ViaRoutePlugin final : public BasePlugin return Status::Ok; } }; - } } } diff --git a/include/engine/polyline_compressor.hpp b/include/engine/polyline_compressor.hpp index 5d26a14fa..9a7ba4d02 100644 --- a/include/engine/polyline_compressor.hpp +++ b/include/engine/polyline_compressor.hpp @@ -25,7 +25,6 @@ class PolylineCompressor std::vector decode_string(const std::string &geometry_string) const; }; - } } diff --git a/include/engine/polyline_formatter.hpp b/include/engine/polyline_formatter.hpp index 861fec01f..b2c5afe24 100644 --- a/include/engine/polyline_formatter.hpp +++ b/include/engine/polyline_formatter.hpp @@ -19,7 +19,6 @@ struct PolylineFormatter util::json::Array printUnencodedString(const std::vector &polyline) const; }; - } } diff --git a/include/engine/route_name_extraction.hpp b/include/engine/route_name_extraction.hpp index df6a8ac89..dd28f97c1 100644 --- a/include/engine/route_name_extraction.hpp +++ b/include/engine/route_name_extraction.hpp @@ -28,7 +28,7 @@ template struct ExtractRouteNames const unsigned blocked_name_id) const { SegmentT result_segment; - result_segment.name_id = blocked_name_id; //make sure we get a valid name + result_segment.name_id = blocked_name_id; // make sure we get a valid name result_segment.length = 0; for (const SegmentT &segment : segment_list) @@ -139,7 +139,6 @@ template struct ExtractRouteNames return route_names; } }; - } } diff --git a/include/engine/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp index ec82818f8..91634813f 100644 --- a/include/engine/routing_algorithms/alternative_path.hpp +++ b/include/engine/routing_algorithms/alternative_path.hpp @@ -564,7 +564,8 @@ class AlternativeRouting final const NodeID node = forward_heap.DeleteMin(); const int distance = forward_heap.GetKey(node); // const NodeID parentnode = forward_heap.GetData(node).parent; - // util::SimpleLogger().Write() << (is_forward_directed ? "[fwd] " : "[rev] ") << "settled edge (" + // util::SimpleLogger().Write() << (is_forward_directed ? "[fwd] " : "[rev] ") << "settled + // edge (" // << parentnode << "," << node << "), dist: " << distance; const int scaled_distance = @@ -588,10 +589,12 @@ class AlternativeRouting final { *middle_node = node; *upper_bound_to_shortest_path_distance = new_distance; - // util::SimpleLogger().Write() << "accepted middle_node " << *middle_node << " at + // util::SimpleLogger().Write() << "accepted middle_node " << *middle_node + // << " at // distance " << new_distance; // } else { - // util::SimpleLogger().Write() << "discarded middle_node " << *middle_node << " + // util::SimpleLogger().Write() << "discarded middle_node " << *middle_node + // << " // at distance " << new_distance; } } @@ -846,7 +849,6 @@ class AlternativeRouting final return (upper_bound <= t_test_path_length); } }; - } } } diff --git a/include/engine/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp index 7c935928c..437d88d27 100644 --- a/include/engine/routing_algorithms/direct_shortest_path.hpp +++ b/include/engine/routing_algorithms/direct_shortest_path.hpp @@ -131,7 +131,6 @@ class DirectShortestPathRouting final raw_route_data.unpacked_path_segments.front()); } }; - } } } diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 23edcedb5..f3422dd6d 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -147,8 +147,8 @@ class MapMatching final : public BasicRoutingInterface - MAX_BROKEN_STATES); + trace_split = + trace_split || (t - prev_unbroken_timestamps.back() > MAX_BROKEN_STATES); } if (trace_split) @@ -194,8 +194,8 @@ class MapMatching final : public BasicRoutingInterface(0u, prev_viterbi.size())) @@ -246,8 +246,7 @@ class MapMatching final : public BasicRoutingInterface SUSPICIOUS_DISTANCE_DELTA; + current_suspicious[s_prime] = d_t > SUSPICIOUS_DISTANCE_DELTA; model.breakage[t] = false; } } @@ -355,7 +354,6 @@ class MapMatching final : public BasicRoutingInterface class BasicRoutingInterface { private: @@ -231,7 +230,8 @@ template class BasicRoutingInterface { BOOST_ASSERT_MSG(!ed.shortcut, "original edge flagged as shortcut"); unsigned name_index = facade->GetNameIndexFromEdgeID(ed.id); - const extractor::TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id); + const extractor::TurnInstruction turn_instruction = + facade->GetTurnInstructionForEdgeID(ed.id); const extractor::TravelMode travel_mode = facade->GetTravelModeForEdgeID(ed.id); if (!facade->EdgeIsCompressed(ed.id)) @@ -260,7 +260,8 @@ template class BasicRoutingInterface for (std::size_t i = start_index; i < end_index; ++i) { unpacked_path.emplace_back(id_vector[i], name_index, - extractor::TurnInstruction::NoTurn, 0, travel_mode); + extractor::TurnInstruction::NoTurn, 0, + travel_mode); } unpacked_path.back().turn_instruction = turn_instruction; unpacked_path.back().segment_duration = ed.distance; @@ -304,9 +305,10 @@ template class BasicRoutingInterface { BOOST_ASSERT(i < id_vector.size()); BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode > 0); - unpacked_path.emplace_back(PathData{ - id_vector[i], phantom_node_pair.target_phantom.name_id, extractor::TurnInstruction::NoTurn, - 0, phantom_node_pair.target_phantom.forward_travel_mode}); + unpacked_path.emplace_back( + PathData{id_vector[i], phantom_node_pair.target_phantom.name_id, + extractor::TurnInstruction::NoTurn, 0, + phantom_node_pair.target_phantom.forward_travel_mode}); } } @@ -658,16 +660,15 @@ template class BasicRoutingInterface { current_coordinate = facade->GetCoordinateOfNode(p.node); distance += util::coordinate_calculation::haversineDistance(previous_coordinate, - current_coordinate); + current_coordinate); previous_coordinate = current_coordinate; } distance += util::coordinate_calculation::haversineDistance(previous_coordinate, - target_phantom.location); + target_phantom.location); } return distance; } }; - } } } diff --git a/include/engine/routing_algorithms/shortest_path.hpp b/include/engine/routing_algorithms/shortest_path.hpp index 8a057d42d..2613c3227 100644 --- a/include/engine/routing_algorithms/shortest_path.hpp +++ b/include/engine/routing_algorithms/shortest_path.hpp @@ -521,7 +521,6 @@ class ShortestPathRouting final } } }; - } } } diff --git a/include/engine/search_engine.hpp b/include/engine/search_engine.hpp index fefc90368..c15b8535f 100644 --- a/include/engine/search_engine.hpp +++ b/include/engine/search_engine.hpp @@ -41,7 +41,6 @@ template class SearchEngine ~SearchEngine() {} }; - } } diff --git a/include/engine/search_engine_data.hpp b/include/engine/search_engine_data.hpp index 2e5b59da5..3112a780c 100644 --- a/include/engine/search_engine_data.hpp +++ b/include/engine/search_engine_data.hpp @@ -19,7 +19,8 @@ struct HeapData struct SearchEngineData { - using QueryHeap = util::BinaryHeap>; + using QueryHeap = + util::BinaryHeap>; using SearchEngineHeapPtr = boost::thread_specific_ptr; static SearchEngineHeapPtr forward_heap_1; @@ -35,7 +36,6 @@ struct SearchEngineData void InitializeOrClearThirdThreadLocalStorage(const unsigned number_of_nodes); }; - } } diff --git a/include/engine/segment_information.hpp b/include/engine/segment_information.hpp index 527726f92..842f5a3e3 100644 --- a/include/engine/segment_information.hpp +++ b/include/engine/segment_information.hpp @@ -49,12 +49,11 @@ struct SegmentInformation const extractor::TravelMode travel_mode) : location(std::move(location)), name_id(name_id), duration(duration), length(length), pre_turn_bearing(0), post_turn_bearing(0), turn_instruction(turn_instruction), - travel_mode(travel_mode), necessary(turn_instruction != extractor::TurnInstruction::NoTurn), - is_via_location(false) + travel_mode(travel_mode), + necessary(turn_instruction != extractor::TurnInstruction::NoTurn), is_via_location(false) { } }; - } } diff --git a/include/engine/trip/trip_brute_force.hpp b/include/engine/trip/trip_brute_force.hpp index 5cecabcac..351295cf8 100644 --- a/include/engine/trip/trip_brute_force.hpp +++ b/include/engine/trip/trip_brute_force.hpp @@ -77,7 +77,6 @@ std::vector BruteForceTrip(const NodeIDIterator start, return route; } - } } } diff --git a/include/engine/trip/trip_farthest_insertion.hpp b/include/engine/trip/trip_farthest_insertion.hpp index 2e3b401a4..35a0c7fd4 100644 --- a/include/engine/trip/trip_farthest_insertion.hpp +++ b/include/engine/trip/trip_farthest_insertion.hpp @@ -190,7 +190,6 @@ std::vector FarthestInsertionTrip(const NodeIDIterator &start, BOOST_ASSERT_MSG(static_cast(max_to) < number_of_locations, "start node"); return FindRoute(number_of_locations, component_size, start, end, dist_table, max_from, max_to); } - } } } diff --git a/include/engine/trip/trip_nearest_neighbour.hpp b/include/engine/trip/trip_nearest_neighbour.hpp index a7a5baeb3..7f2921765 100644 --- a/include/engine/trip/trip_nearest_neighbour.hpp +++ b/include/engine/trip/trip_nearest_neighbour.hpp @@ -92,7 +92,6 @@ std::vector NearestNeighbourTrip(const NodeIDIterator &start, } return route; } - } } } diff --git a/include/engine/trip/trip_tabu_search.hpp b/include/engine/trip/trip_tabu_search.hpp index d92763616..24ff7455d 100644 --- a/include/engine/trip/trip_tabu_search.hpp +++ b/include/engine/trip/trip_tabu_search.hpp @@ -34,7 +34,6 @@ void TabuSearchTrip(const PhantomNodeArray &phantom_node_vector, std::vector &min_loc_permutation) { } - } } } diff --git a/include/extractor/compressed_edge_container.hpp b/include/extractor/compressed_edge_container.hpp index 47146162c..ed9122dd2 100644 --- a/include/extractor/compressed_edge_container.hpp +++ b/include/extractor/compressed_edge_container.hpp @@ -43,7 +43,6 @@ class CompressedEdgeContainer std::vector m_free_list; std::unordered_map m_edge_id_to_list_index_map; }; - } } diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 47aeecdcb..19a3d1ba8 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -117,7 +117,6 @@ class EdgeBasedGraphFactory void FlushVectorToStream(std::ofstream &edge_data_file, std::vector &original_edge_data_vector) const; }; - } } diff --git a/include/extractor/edge_based_node.hpp b/include/extractor/edge_based_node.hpp index aee2d6a34..c41c3b8e3 100644 --- a/include/extractor/edge_based_node.hpp +++ b/include/extractor/edge_based_node.hpp @@ -59,7 +59,7 @@ struct EdgeBasedNode } static inline util::FixedPointCoordinate Centroid(const util::FixedPointCoordinate &a, - const util::FixedPointCoordinate &b) + const util::FixedPointCoordinate &b) { util::FixedPointCoordinate centroid; // The coordinates of the midpoint are given by: @@ -89,7 +89,6 @@ struct EdgeBasedNode TravelMode forward_travel_mode : 4; TravelMode backward_travel_mode : 4; }; - } } diff --git a/include/extractor/external_memory_node.hpp b/include/extractor/external_memory_node.hpp index 544e59fdc..a4f9ca941 100644 --- a/include/extractor/external_memory_node.hpp +++ b/include/extractor/external_memory_node.hpp @@ -31,7 +31,6 @@ struct ExternalMemoryNodeSTXXLCompare value_type max_value(); value_type min_value(); }; - } } diff --git a/include/extractor/extraction_containers.hpp b/include/extractor/extraction_containers.hpp index 53177e0d6..848e4576e 100644 --- a/include/extractor/extraction_containers.hpp +++ b/include/extractor/extraction_containers.hpp @@ -65,7 +65,6 @@ class ExtractionContainers const std::string &names_file_name, lua_State *segment_state); }; - } } diff --git a/include/extractor/extraction_helper_functions.hpp b/include/extractor/extraction_helper_functions.hpp index 82a493b77..b7df3ca9b 100644 --- a/include/extractor/extraction_helper_functions.hpp +++ b/include/extractor/extraction_helper_functions.hpp @@ -94,7 +94,6 @@ unsigned parseDuration(const std::string &s) return std::numeric_limits::max(); } - } } diff --git a/include/extractor/extraction_node.hpp b/include/extractor/extraction_node.hpp index 82826e717..e82f298ba 100644 --- a/include/extractor/extraction_node.hpp +++ b/include/extractor/extraction_node.hpp @@ -13,7 +13,6 @@ struct ExtractionNode bool traffic_lights; bool barrier; }; - } } diff --git a/include/extractor/extraction_way.hpp b/include/extractor/extraction_way.hpp index f54b5fe77..ef88feaff 100644 --- a/include/extractor/extraction_way.hpp +++ b/include/extractor/extraction_way.hpp @@ -103,7 +103,6 @@ struct ExtractionWay TravelMode forward_travel_mode : 4; TravelMode backward_travel_mode : 4; }; - } } diff --git a/include/extractor/extractor_callbacks.hpp b/include/extractor/extractor_callbacks.hpp index a862f936c..673c2f601 100644 --- a/include/extractor/extractor_callbacks.hpp +++ b/include/extractor/extractor_callbacks.hpp @@ -51,7 +51,6 @@ class ExtractorCallbacks // warning: caller needs to take care of synchronization! void ProcessWay(const osmium::Way ¤t_way, const ExtractionWay &result_way); }; - } } diff --git a/include/extractor/extractor_options.hpp b/include/extractor/extractor_options.hpp index 05949f52f..2fbe3c894 100644 --- a/include/extractor/extractor_options.hpp +++ b/include/extractor/extractor_options.hpp @@ -52,7 +52,6 @@ struct ExtractorOptions static void GenerateOutputFilesNames(ExtractorConfig &extractor_config); }; - } } diff --git a/include/extractor/first_and_last_segment_of_way.hpp b/include/extractor/first_and_last_segment_of_way.hpp index d4ea8e457..df2ca92cc 100644 --- a/include/extractor/first_and_last_segment_of_way.hpp +++ b/include/extractor/first_and_last_segment_of_way.hpp @@ -53,7 +53,6 @@ struct FirstAndLastSegmentOfWayStxxlCompare value_type max_value() { return FirstAndLastSegmentOfWay::max_value(); } value_type min_value() { return FirstAndLastSegmentOfWay::min_value(); } }; - } } diff --git a/include/extractor/graph_compressor.hpp b/include/extractor/graph_compressor.hpp index 56496aefd..69d738e68 100644 --- a/include/extractor/graph_compressor.hpp +++ b/include/extractor/graph_compressor.hpp @@ -37,7 +37,6 @@ class GraphCompressor SpeedProfileProperties speed_profile; }; - } } diff --git a/include/extractor/import_edge.hpp b/include/extractor/import_edge.hpp index 095c9f95a..fc43e2a23 100644 --- a/include/extractor/import_edge.hpp +++ b/include/extractor/import_edge.hpp @@ -94,7 +94,6 @@ struct EdgeBasedEdge bool forward : 1; bool backward : 1; }; - } } diff --git a/include/extractor/internal_extractor_edge.hpp b/include/extractor/internal_extractor_edge.hpp index 2d3447fda..8e4a133bc 100644 --- a/include/extractor/internal_extractor_edge.hpp +++ b/include/extractor/internal_extractor_edge.hpp @@ -152,7 +152,6 @@ struct CmpEdgeByOSMTargetID value_type max_value() { return InternalExtractorEdge::max_osm_value(); } value_type min_value() { return InternalExtractorEdge::min_osm_value(); } }; - } } diff --git a/include/extractor/node_id.hpp b/include/extractor/node_id.hpp index f27fd656c..faaefb2ef 100644 --- a/include/extractor/node_id.hpp +++ b/include/extractor/node_id.hpp @@ -15,7 +15,6 @@ struct Cmp value_type max_value() { return MAX_OSM_NODEID; } value_type min_value() { return MIN_OSM_NODEID; } }; - } } diff --git a/include/extractor/original_edge_data.hpp b/include/extractor/original_edge_data.hpp index dd9273bb9..3e5c0016d 100644 --- a/include/extractor/original_edge_data.hpp +++ b/include/extractor/original_edge_data.hpp @@ -37,7 +37,6 @@ struct OriginalEdgeData bool compressed_geometry; TravelMode travel_mode; }; - } } diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index 512aeaca3..abd5d5d0d 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -59,7 +59,6 @@ struct QueryNode return std::numeric_limits::lowest(); } }; - } } diff --git a/include/extractor/raster_source.hpp b/include/extractor/raster_source.hpp index a4707253c..104462619 100644 --- a/include/extractor/raster_source.hpp +++ b/include/extractor/raster_source.hpp @@ -149,7 +149,6 @@ class SourceContainer std::vector LoadedSources; std::unordered_map LoadedSourcePaths; }; - } } diff --git a/include/extractor/restriction.hpp b/include/extractor/restriction.hpp index 690d92b2b..5916c85ea 100644 --- a/include/extractor/restriction.hpp +++ b/include/extractor/restriction.hpp @@ -108,7 +108,6 @@ struct CmpRestrictionContainerByTo value_type max_value() const { return InputRestrictionContainer::max_value(); } value_type min_value() const { return InputRestrictionContainer::min_value(); } }; - } } diff --git a/include/extractor/restriction_map.hpp b/include/extractor/restriction_map.hpp index e5a6a12ba..5b9a35fb4 100644 --- a/include/extractor/restriction_map.hpp +++ b/include/extractor/restriction_map.hpp @@ -64,7 +64,6 @@ template <> struct hash }; } - namespace osrm { namespace extractor @@ -157,7 +156,6 @@ class RestrictionMap std::unordered_set m_restriction_start_nodes; std::unordered_set m_no_turn_via_node_set; }; - } } diff --git a/include/extractor/restriction_parser.hpp b/include/extractor/restriction_parser.hpp index 2bbad8268..075964ba0 100644 --- a/include/extractor/restriction_parser.hpp +++ b/include/extractor/restriction_parser.hpp @@ -14,7 +14,6 @@ namespace osmium class Relation; } - namespace osrm { namespace extractor @@ -52,7 +51,6 @@ class RestrictionParser std::vector restriction_exceptions; bool use_turn_restrictions; }; - } } diff --git a/include/extractor/scripting_environment.hpp b/include/extractor/scripting_environment.hpp index 0f1342b62..d02c7cb26 100644 --- a/include/extractor/scripting_environment.hpp +++ b/include/extractor/scripting_environment.hpp @@ -34,7 +34,6 @@ class ScriptingEnvironment std::string file_name; tbb::enumerable_thread_specific> script_contexts; }; - } } diff --git a/include/extractor/speed_profile.hpp b/include/extractor/speed_profile.hpp index 65c4141b5..82aa34bd1 100644 --- a/include/extractor/speed_profile.hpp +++ b/include/extractor/speed_profile.hpp @@ -17,7 +17,6 @@ struct SpeedProfileProperties int u_turn_penalty; bool has_turn_penalty_function; }; - } } diff --git a/include/extractor/tarjan_scc.hpp b/include/extractor/tarjan_scc.hpp index a8b8eb6ba..c49f00fb7 100644 --- a/include/extractor/tarjan_scc.hpp +++ b/include/extractor/tarjan_scc.hpp @@ -147,7 +147,7 @@ template class TarjanSCC if (size_of_current_component > 1000) { util::SimpleLogger().Write() << "large component [" << component_index - << "]=" << size_of_current_component; + << "]=" << size_of_current_component; } ++component_index; @@ -178,7 +178,6 @@ template class TarjanSCC unsigned get_component_id(const NodeID node) const { return components_index[node]; } }; - } } diff --git a/include/extractor/travel_mode.hpp b/include/extractor/travel_mode.hpp index 62fc03b92..f5d5c23f9 100644 --- a/include/extractor/travel_mode.hpp +++ b/include/extractor/travel_mode.hpp @@ -7,11 +7,11 @@ namespace extractor { using TravelMode = unsigned char; - } } -namespace { +namespace +{ static const osrm::extractor::TravelMode TRAVEL_MODE_INACCESSIBLE = 0; static const osrm::extractor::TravelMode TRAVEL_MODE_DEFAULT = 1; } diff --git a/include/extractor/turn_instructions.hpp b/include/extractor/turn_instructions.hpp index ca3623504..f5f164f18 100644 --- a/include/extractor/turn_instructions.hpp +++ b/include/extractor/turn_instructions.hpp @@ -79,7 +79,6 @@ struct TurnInstructionsClass return true; } }; - } } diff --git a/include/osrm/coordinate.hpp b/include/osrm/coordinate.hpp index b36d57ca6..e1c7fef7d 100644 --- a/include/osrm/coordinate.hpp +++ b/include/osrm/coordinate.hpp @@ -67,7 +67,6 @@ std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordina } using util::FixedPointCoordinate; - } #endif /* COORDINATE_HPP_ */ diff --git a/include/osrm/json_container.hpp b/include/osrm/json_container.hpp index 7c8377d32..7ab25d544 100644 --- a/include/osrm/json_container.hpp +++ b/include/osrm/json_container.hpp @@ -98,8 +98,9 @@ struct Array } // namespace JSON } // namespace util -namespace json { - using namespace osrm::util::json; +namespace json +{ +using namespace osrm::util::json; } } // namespace osrm diff --git a/include/osrm/libosrm_config.hpp b/include/osrm/libosrm_config.hpp index 4606e6003..743c68225 100644 --- a/include/osrm/libosrm_config.hpp +++ b/include/osrm/libosrm_config.hpp @@ -45,7 +45,6 @@ struct LibOSRMConfig int max_locations_map_matching = -1; bool use_shared_memory = true; }; - } #endif // SERVER_CONFIG_HPP diff --git a/include/osrm/osrm.hpp b/include/osrm/osrm.hpp index 695403d73..3f3e55333 100644 --- a/include/osrm/osrm.hpp +++ b/include/osrm/osrm.hpp @@ -43,7 +43,8 @@ struct Object; } } -namespace engine { +namespace engine +{ struct RouteParameters; class OSRM { @@ -59,7 +60,6 @@ class OSRM } using engine::OSRM; - } #endif // OSRM_HPP diff --git a/include/osrm/route_parameters.hpp b/include/osrm/route_parameters.hpp index f7bc2a261..53c8629e7 100644 --- a/include/osrm/route_parameters.hpp +++ b/include/osrm/route_parameters.hpp @@ -119,11 +119,9 @@ struct RouteParameters std::vector is_destination; std::vector is_source; }; - } using engine::RouteParameters; - } #endif // ROUTE_PARAMETERS_HPP diff --git a/include/osrm/strong_typedef.hpp b/include/osrm/strong_typedef.hpp index f4c80865e..f33932a38 100644 --- a/include/osrm/strong_typedef.hpp +++ b/include/osrm/strong_typedef.hpp @@ -68,7 +68,6 @@ namespace osrm } \ }; \ } - } #endif // OSRM_STRONG_TYPEDEF_HPP diff --git a/include/server/api_grammar.hpp b/include/server/api_grammar.hpp index 7a04d884b..afa577e1c 100644 --- a/include/server/api_grammar.hpp +++ b/include/server/api_grammar.hpp @@ -102,7 +102,6 @@ template struct APIGrammar : qi::grammar http::reply current_reply; std::vector compressed_output; }; - } } diff --git a/include/server/http/compression_type.hpp b/include/server/http/compression_type.hpp index 2a71cfa54..7ff929c0e 100644 --- a/include/server/http/compression_type.hpp +++ b/include/server/http/compression_type.hpp @@ -14,7 +14,6 @@ enum compression_type gzip_rfc1952, deflate_rfc1951 }; - } } } diff --git a/include/server/http/header.hpp b/include/server/http/header.hpp index da43412bb..33cc4bb2f 100644 --- a/include/server/http/header.hpp +++ b/include/server/http/header.hpp @@ -27,7 +27,6 @@ struct header std::string name; std::string value; }; - } } } diff --git a/include/server/http/reply.hpp b/include/server/http/reply.hpp index 15ca91a13..8474a5c2d 100644 --- a/include/server/http/reply.hpp +++ b/include/server/http/reply.hpp @@ -38,7 +38,6 @@ class reply std::string status_to_string(reply::status_type status); boost::asio::const_buffer status_to_buffer(reply::status_type status); }; - } } } diff --git a/include/server/http/request.hpp b/include/server/http/request.hpp index 0e6fb7d59..1b86253f7 100644 --- a/include/server/http/request.hpp +++ b/include/server/http/request.hpp @@ -19,7 +19,6 @@ struct request std::string agent; boost::asio::ip::address endpoint; }; - } } } diff --git a/include/server/request_handler.hpp b/include/server/request_handler.hpp index 66d2cd2b1..900370a8a 100644 --- a/include/server/request_handler.hpp +++ b/include/server/request_handler.hpp @@ -35,7 +35,6 @@ class RequestHandler private: engine::OSRM *routing_machine; }; - } } diff --git a/include/server/request_parser.hpp b/include/server/request_parser.hpp index b4df13162..0b44849ae 100644 --- a/include/server/request_parser.hpp +++ b/include/server/request_parser.hpp @@ -17,7 +17,6 @@ namespace http struct request; } - class RequestParser { public: @@ -71,7 +70,6 @@ class RequestParser bool is_post_header; int content_length; }; - } } diff --git a/include/server/server.hpp b/include/server/server.hpp index 2d40a45b8..4e6758206 100644 --- a/include/server/server.hpp +++ b/include/server/server.hpp @@ -30,7 +30,8 @@ class Server static std::shared_ptr CreateServer(std::string &ip_address, int ip_port, unsigned requested_num_threads) { - util::SimpleLogger().Write() << "http 1.1 compression handled by zlib version " << zlibVersion(); + util::SimpleLogger().Write() << "http 1.1 compression handled by zlib version " + << zlibVersion(); const unsigned hardware_threads = std::max(1u, std::thread::hardware_concurrency()); const unsigned real_num_threads = std::min(hardware_threads, requested_num_threads); return std::make_shared(ip_address, ip_port, real_num_threads); @@ -93,7 +94,6 @@ class Server std::shared_ptr new_connection; RequestHandler request_handler; }; - } } diff --git a/include/util/bearing.hpp b/include/util/bearing.hpp index 190e97a08..f1ba6244f 100644 --- a/include/util/bearing.hpp +++ b/include/util/bearing.hpp @@ -90,7 +90,6 @@ inline bool CheckInBounds(const int A, const int B, const int range) } } } - } } diff --git a/include/util/binary_heap.hpp b/include/util/binary_heap.hpp index c7d57505f..f3c01f6b6 100644 --- a/include/util/binary_heap.hpp +++ b/include/util/binary_heap.hpp @@ -290,7 +290,6 @@ class BinaryHeap #endif } }; - } } diff --git a/include/util/cast.hpp b/include/util/cast.hpp index 479eaa2a4..e78f630b6 100644 --- a/include/util/cast.hpp +++ b/include/util/cast.hpp @@ -43,7 +43,6 @@ template inline std::string to_string_with_preci return rv; } } - } } diff --git a/include/util/compute_angle.hpp b/include/util/compute_angle.hpp index 40f820d9e..2662ed99e 100644 --- a/include/util/compute_angle.hpp +++ b/include/util/compute_angle.hpp @@ -16,7 +16,6 @@ struct ComputeAngle const FixedPointCoordinate &second, const FixedPointCoordinate &third) noexcept; }; - } } diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index 96548481b..1507d14f0 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -53,7 +53,6 @@ double radToDeg(const double radian); double bearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); } - } } diff --git a/include/util/datastore_options.hpp b/include/util/datastore_options.hpp index b467bb836..bd0902506 100644 --- a/include/util/datastore_options.hpp +++ b/include/util/datastore_options.hpp @@ -258,7 +258,6 @@ bool GenerateDataStoreOptions(const int argc, return true; } - } } diff --git a/include/util/deallocating_vector.hpp b/include/util/deallocating_vector.hpp index aa9ec3ea2..c8883b2c6 100644 --- a/include/util/deallocating_vector.hpp +++ b/include/util/deallocating_vector.hpp @@ -306,8 +306,7 @@ class DeallocatingVector else { // down-size const std::size_t number_of_necessary_buckets = 1 + (new_size / ELEMENTS_PER_BLOCK); - for (const auto bucket_index : - irange(number_of_necessary_buckets, bucket_list.size())) + for (const auto bucket_index : irange(number_of_necessary_buckets, bucket_list.size())) { if (nullptr != bucket_list[bucket_index]) { @@ -378,7 +377,6 @@ void swap(DeallocatingVector &lhs, DeallocatingVector &rhs) { lhs.swap(rhs); } - } } diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index b06ed3dc6..41a3ebc8d 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -40,7 +40,6 @@ inline void DEBUG_SIGNAL(const NodeID /* node */, } inline void DEBUG_TURNS_STOP() {} - } } @@ -60,7 +59,6 @@ namespace osrm namespace util { - boost::filesystem::ofstream debug_geometry_file; bool dg_output_debug_geometry = false; bool dg_first_debug_geometry = true; @@ -207,7 +205,6 @@ inline void DEBUG_TURNS_STOP() dg_debug_turns_file.close(); } } - } } diff --git a/include/util/dist_table_wrapper.hpp b/include/util/dist_table_wrapper.hpp index 3e23ce2ac..28a693938 100644 --- a/include/util/dist_table_wrapper.hpp +++ b/include/util/dist_table_wrapper.hpp @@ -62,7 +62,6 @@ template class DistTableWrapper std::vector table_; const std::size_t number_of_nodes_; }; - } } diff --git a/include/util/dynamic_graph.hpp b/include/util/dynamic_graph.hpp index c4219cf28..7df32a9fc 100644 --- a/include/util/dynamic_graph.hpp +++ b/include/util/dynamic_graph.hpp @@ -95,7 +95,7 @@ template class DynamicGraph for (const auto node : irange(0u, number_of_nodes)) { for (const auto i : irange(node_array[node].first_edge, - node_array[node].first_edge + node_array[node].edges)) + node_array[node].first_edge + node_array[node].edges)) { edge_list[i].target = graph[edge].target; BOOST_ASSERT(edge_list[i].target < number_of_nodes); @@ -320,7 +320,6 @@ template class DynamicGraph std::vector node_array; DeallocatingVector edge_list; }; - } } diff --git a/include/util/fingerprint.hpp b/include/util/fingerprint.hpp index 14b869871..df656cde1 100644 --- a/include/util/fingerprint.hpp +++ b/include/util/fingerprint.hpp @@ -33,7 +33,6 @@ class FingerPrint }; static_assert(std::is_trivial::value, "FingerPrint needs to be trivial."); - } } diff --git a/include/util/fixed_point_number.hpp b/include/util/fixed_point_number.hpp index ba4b111db..8216b4caf 100644 --- a/include/util/fixed_point_number.hpp +++ b/include/util/fixed_point_number.hpp @@ -187,7 +187,6 @@ class FixedPointNumber }; static_assert(4 == sizeof(FixedPointNumber<1>), "FP19 has wrong size != 4"); - } } diff --git a/include/util/floating_point.hpp b/include/util/floating_point.hpp index e7963e630..779f095db 100644 --- a/include/util/floating_point.hpp +++ b/include/util/floating_point.hpp @@ -16,7 +16,6 @@ template bool epsilon_compare(const FloatT number1, const Floa static_assert(std::is_floating_point::value, "type must be floating point"); return (std::abs(number1 - number2) < std::numeric_limits::epsilon()); } - } } diff --git a/include/util/graph_loader.hpp b/include/util/graph_loader.hpp index 6ff030b5a..b4d3f4f5e 100644 --- a/include/util/graph_loader.hpp +++ b/include/util/graph_loader.hpp @@ -84,7 +84,8 @@ NodeID loadNodesFromFile(std::istream &input_stream, extractor::ExternalMemoryNode current_node; for (NodeID i = 0; i < n; ++i) { - input_stream.read(reinterpret_cast(¤t_node), sizeof(extractor::ExternalMemoryNode)); + input_stream.read(reinterpret_cast(¤t_node), + sizeof(extractor::ExternalMemoryNode)); node_array.emplace_back(current_node.lat, current_node.lon, current_node.node_id); if (current_node.barrier) { @@ -106,7 +107,8 @@ NodeID loadNodesFromFile(std::istream &input_stream, /** * Reads a .osrm file and produces the edges. */ -NodeID loadEdgesFromFile(std::istream &input_stream, std::vector &edge_list) +NodeID loadEdgesFromFile(std::istream &input_stream, + std::vector &edge_list) { EdgeID m; input_stream.read(reinterpret_cast(&m), sizeof(unsigned)); @@ -196,7 +198,6 @@ unsigned readHSGRFromStream(const boost::filesystem::path &hsgr_file, return number_of_nodes; } - } } diff --git a/include/util/hilbert_value.hpp b/include/util/hilbert_value.hpp index 6c8af4f19..641782e85 100644 --- a/include/util/hilbert_value.hpp +++ b/include/util/hilbert_value.hpp @@ -23,7 +23,6 @@ class HilbertCode inline uint64_t BitInterleaving(const uint32_t a, const uint32_t b) const; inline void TransposeCoordinate(uint32_t *X) const; }; - } } diff --git a/include/util/integer_range.hpp b/include/util/integer_range.hpp index cba88ad92..ee706bd8b 100644 --- a/include/util/integer_range.hpp +++ b/include/util/integer_range.hpp @@ -47,7 +47,6 @@ irange(const Integer first, { return range(first, last); } - } } diff --git a/include/util/iso_8601_duration_parser.hpp b/include/util/iso_8601_duration_parser.hpp index 493149c01..91f9d2dc4 100644 --- a/include/util/iso_8601_duration_parser.hpp +++ b/include/util/iso_8601_duration_parser.hpp @@ -76,7 +76,6 @@ template struct iso_8601_grammar : qi::grammar return temp; } }; - } } diff --git a/include/util/json_logger.hpp b/include/util/json_logger.hpp index 6b81cc6fc..aa72b54cf 100644 --- a/include/util/json_logger.hpp +++ b/include/util/json_logger.hpp @@ -55,7 +55,6 @@ class Logger boost::thread_specific_ptr map; }; - } } } diff --git a/include/util/json_util.hpp b/include/util/json_util.hpp index 2cf012eb2..d858f6b20 100644 --- a/include/util/json_util.hpp +++ b/include/util/json_util.hpp @@ -59,15 +59,13 @@ template <> Array make_array(const std::vector &vector) // Easy acces to object hierachies Value &get(Value &value) { return value; } -template -Value &get(Value &value, const char *key, Keys... keys) +template Value &get(Value &value, const char *key, Keys... keys) { using recursive_object_t = mapbox::util::recursive_wrapper; return get(value.get().get().values[key], keys...); } -template -Value &get(Value &value, unsigned key, Keys... keys) +template Value &get(Value &value, unsigned key, Keys... keys) { using recursive_array_t = mapbox::util::recursive_wrapper; return get(value.get().get().values[key], keys...); diff --git a/include/util/lua_util.hpp b/include/util/lua_util.hpp index 47339fdd8..4eb799e04 100644 --- a/include/util/lua_util.hpp +++ b/include/util/lua_util.hpp @@ -39,7 +39,6 @@ inline void luaAddScriptFolderToLoadPath(lua_State *lua_state, const char *file_ const std::string lua_code = "package.path = \"" + folder + "/?.lua;\" .. package.path"; luaL_dostring(lua_state, lua_code.c_str()); } - } } diff --git a/include/util/make_unique.hpp b/include/util/make_unique.hpp index 09a1dd924..74d4e3d0e 100644 --- a/include/util/make_unique.hpp +++ b/include/util/make_unique.hpp @@ -45,7 +45,6 @@ make_unique(size_t n) /// This function isn't used and is only here to provide better compile errors. template typename std::enable_if::value != 0>::type make_unique(Args &&...) = delete; - } } diff --git a/include/util/matching_debug_info.hpp b/include/util/matching_debug_info.hpp index dc8e561d7..e90053378 100644 --- a/include/util/matching_debug_info.hpp +++ b/include/util/matching_debug_info.hpp @@ -41,7 +41,7 @@ struct MatchingDebugInfo state.values["transitions"] = json::Array(); state.values["coordinate"] = json::make_array(elem_s.phantom_node.location.lat / COORDINATE_PRECISION, - elem_s.phantom_node.location.lon / COORDINATE_PRECISION); + elem_s.phantom_node.location.lon / COORDINATE_PRECISION); state.values["viterbi"] = json::clamp_float(engine::map_matching::IMPOSSIBLE_LOG_PROB); state.values["pruned"] = 0u; @@ -129,7 +129,6 @@ struct MatchingDebugInfo const json::Logger *logger; json::Value *object; }; - } } diff --git a/include/util/matrix_graph_wrapper.hpp b/include/util/matrix_graph_wrapper.hpp index 11b1f2586..52f7fd390 100644 --- a/include/util/matrix_graph_wrapper.hpp +++ b/include/util/matrix_graph_wrapper.hpp @@ -12,7 +12,8 @@ namespace osrm namespace util { -// This Wrapper provides all methods that are needed for extractor::TarjanSCC, when the graph is given in a +// This Wrapper provides all methods that are needed for extractor::TarjanSCC, when the graph is +// given in a // matrix representation (e.g. as output from a distance table call) template class MatrixGraphWrapper @@ -44,7 +45,6 @@ template class MatrixGraphWrapper const std::vector table_; const std::size_t number_of_nodes_; }; - } } diff --git a/include/util/mercator.hpp b/include/util/mercator.hpp index 230c1ad23..eda28a96c 100644 --- a/include/util/mercator.hpp +++ b/include/util/mercator.hpp @@ -12,7 +12,6 @@ struct mercator static double lat2y(const double latitude) noexcept; }; - } } diff --git a/include/util/node_based_graph.hpp b/include/util/node_based_graph.hpp index 09b082496..c1aa0323d 100644 --- a/include/util/node_based_graph.hpp +++ b/include/util/node_based_graph.hpp @@ -63,8 +63,8 @@ NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, const std::vector &input_edge_list) { auto edges_list = directedEdgesFromCompressed( - input_edge_list, - [](NodeBasedDynamicGraph::InputEdge &output_edge, const extractor::NodeBasedEdge &input_edge) + input_edge_list, [](NodeBasedDynamicGraph::InputEdge &output_edge, + const extractor::NodeBasedEdge &input_edge) { output_edge.data.distance = static_cast(input_edge.weight); BOOST_ASSERT(output_edge.data.distance > 0); @@ -83,7 +83,6 @@ NodeBasedDynamicGraphFromEdges(std::size_t number_of_nodes, return graph; } - } } diff --git a/include/util/osrm_exception.hpp b/include/util/osrm_exception.hpp index fc84cb981..6c7c5e2f6 100644 --- a/include/util/osrm_exception.hpp +++ b/include/util/osrm_exception.hpp @@ -24,7 +24,6 @@ class exception final : public std::exception const char *what() const noexcept override { return message.c_str(); } const std::string message; }; - } } diff --git a/include/util/percent.hpp b/include/util/percent.hpp index 4f0d0e72c..d34a77d07 100644 --- a/include/util/percent.hpp +++ b/include/util/percent.hpp @@ -75,7 +75,6 @@ class Percent } } }; - } } diff --git a/include/util/range_algorithms.hpp b/include/util/range_algorithms.hpp index 47393b523..964595634 100644 --- a/include/util/range_algorithms.hpp +++ b/include/util/range_algorithms.hpp @@ -19,7 +19,6 @@ auto max_element(const Container &c) -> decltype(std::max_element(c.cbegin(), c. { return std::max_element(c.cbegin(), c.cend()); } - } } diff --git a/include/util/range_table.hpp b/include/util/range_table.hpp index 97cbc3abe..f06df1def 100644 --- a/include/util/range_table.hpp +++ b/include/util/range_table.hpp @@ -233,7 +233,6 @@ std::istream &operator>>(std::istream &in, RangeTable struct ShM SharedMemoryWrapper, std::vector>::type; }; - } } diff --git a/include/util/simple_logger.hpp b/include/util/simple_logger.hpp index 0b33f51fa..29301b9d5 100644 --- a/include/util/simple_logger.hpp +++ b/include/util/simple_logger.hpp @@ -48,7 +48,6 @@ class SimpleLogger std::ostringstream os; LogLevel level; }; - } } diff --git a/include/util/static_graph.hpp b/include/util/static_graph.hpp index 744dabb8b..c37b09e40 100644 --- a/include/util/static_graph.hpp +++ b/include/util/static_graph.hpp @@ -193,7 +193,6 @@ template class StaticGraph typename ShM::vector node_array; typename ShM::vector edge_array; }; - } } diff --git a/include/util/string_util.hpp b/include/util/string_util.hpp index 6a3c772bd..1a54c9475 100644 --- a/include/util/string_util.hpp +++ b/include/util/string_util.hpp @@ -126,7 +126,6 @@ inline std::size_t URIDecode(const std::string &input, std::string &output) } inline std::size_t URIDecodeInPlace(std::string &URI) { return URIDecode(URI, URI); } - } } diff --git a/include/util/timing_util.hpp b/include/util/timing_util.hpp index 44af92b89..537f0dc5e 100644 --- a/include/util/timing_util.hpp +++ b/include/util/timing_util.hpp @@ -64,7 +64,6 @@ class GlobalTimerFactory std::chrono::duration_cast(_X##_stop - _X##_start).count()) #define TIMER_MIN(_X) \ std::chrono::duration_cast(_X##_stop - _X##_start).count() - } } diff --git a/include/util/tribool.hpp b/include/util/tribool.hpp index ec7ca76a7..85282de88 100644 --- a/include/util/tribool.hpp +++ b/include/util/tribool.hpp @@ -12,7 +12,6 @@ enum class tribool : char no, indeterminate }; - } } #endif // TRIBOOL_HPP diff --git a/include/util/trigonometry_table.hpp b/include/util/trigonometry_table.hpp index 5c92829c0..69e0bb459 100644 --- a/include/util/trigonometry_table.hpp +++ b/include/util/trigonometry_table.hpp @@ -422,7 +422,6 @@ inline double atan2_lookup(double y, double x) } return angle; } - } } diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 247c76ba6..5b7a103bb 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -89,7 +89,6 @@ class XORMiniHash return table1[byte1] ^ table2[byte2] ^ table3[byte3] ^ table4[byte4]; } }; - } } diff --git a/include/util/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp index 046580dc9..7fad54027 100644 --- a/include/util/xor_fast_hash_storage.hpp +++ b/include/util/xor_fast_hash_storage.hpp @@ -75,7 +75,6 @@ template class XORFastHashStorage XORFastHash fast_hasher; unsigned current_timestamp; }; - } } diff --git a/src/benchmarks/static_rtree.cpp b/src/benchmarks/static_rtree.cpp index ab6b019a7..54126c805 100644 --- a/src/benchmarks/static_rtree.cpp +++ b/src/benchmarks/static_rtree.cpp @@ -23,7 +23,8 @@ constexpr int32_t WORLD_MAX_LON = 180 * COORDINATE_PRECISION; using RTreeLeaf = extractor::EdgeBasedNode; using FixedPointCoordinateListPtr = std::shared_ptr>; -using BenchStaticRTree = util::StaticRTree::vector, false>; +using BenchStaticRTree = + util::StaticRTree::vector, false>; using BenchQuery = engine::GeospatialQuery; FixedPointCoordinateListPtr loadCoordinates(const boost::filesystem::path &nodes_file) @@ -56,7 +57,7 @@ void benchmarkQuery(const std::vector &queries, for (const auto &q : queries) { auto result = query(q); - (void) result; + (void)result; } TIMER_STOP(query); diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index b108522fa..f563de45b 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -42,7 +42,6 @@ template <> struct hash> }; } - namespace osrm { namespace contractor @@ -105,19 +104,20 @@ int Prepare::Run() util::SimpleLogger().Write() << "Preprocessing : " << TIMER_SEC(preparing) << " seconds"; util::SimpleLogger().Write() << "Contraction: " << ((max_edge_id + 1) / TIMER_SEC(contraction)) - << " nodes/sec and " << number_of_used_edges / TIMER_SEC(contraction) - << " edges/sec"; + << " nodes/sec and " + << number_of_used_edges / TIMER_SEC(contraction) << " edges/sec"; util::SimpleLogger().Write() << "finished preprocessing"; return 0; } -std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_filename, - util::DeallocatingVector &edge_based_edge_list, - const std::string &edge_segment_lookup_filename, - const std::string &edge_penalty_filename, - const std::string &segment_speed_filename) +std::size_t Prepare::LoadEdgeExpandedGraph( + std::string const &edge_based_graph_filename, + util::DeallocatingVector &edge_based_edge_list, + const std::string &edge_segment_lookup_filename, + const std::string &edge_penalty_filename, + const std::string &segment_speed_filename) { util::SimpleLogger().Write() << "Opening " << edge_based_graph_filename; boost::filesystem::ifstream input_stream(edge_based_graph_filename, std::ios::binary); @@ -149,14 +149,16 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f input_stream.read((char *)&max_edge_id, sizeof(size_t)); edge_based_edge_list.resize(number_of_edges); - util::SimpleLogger().Write() << "Reading " << number_of_edges << " edges from the edge based graph"; + util::SimpleLogger().Write() << "Reading " << number_of_edges + << " edges from the edge based graph"; std::unordered_map, unsigned> segment_speed_lookup; if (update_edge_weights) { - util::SimpleLogger().Write() << "Segment speed data supplied, will update edge weights from " - << segment_speed_filename; + util::SimpleLogger().Write() + << "Segment speed data supplied, will update edge weights from " + << segment_speed_filename; io::CSVReader<3> csv_in(segment_speed_filename); csv_in.set_header("from_node", "to_node", "speed"); uint64_t from_node_id{}; @@ -218,8 +220,8 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f (segment_length * 10.) / (speed_iter->second / 3.6) + .5))); new_weight += new_segment_weight; - util::DEBUG_GEOMETRY_EDGE(new_segment_weight, segment_length, previous_osm_node_id, - this_osm_node_id); + util::DEBUG_GEOMETRY_EDGE(new_segment_weight, segment_length, + previous_osm_node_id, this_osm_node_id); } else { @@ -227,7 +229,7 @@ std::size_t Prepare::LoadEdgeExpandedGraph(std::string const &edge_based_graph_f new_weight += segment_weight; util::DEBUG_GEOMETRY_EDGE(segment_weight, segment_length, previous_osm_node_id, - this_osm_node_id); + this_osm_node_id); } previous_osm_node_id = this_osm_node_id; @@ -282,14 +284,15 @@ void Prepare::WriteCoreNodeMarker(std::vector &&in_is_core_node) const sizeof(char) * unpacked_bool_flags.size()); } -std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, - const util::DeallocatingVector &contracted_edge_list) +std::size_t +Prepare::WriteContractedGraph(unsigned max_node_id, + const util::DeallocatingVector &contracted_edge_list) { // Sorting contracted edges in a way that the static query graph can read some in in-place. tbb::parallel_sort(contracted_edge_list.begin(), contracted_edge_list.end()); const unsigned contracted_edge_count = contracted_edge_list.size(); util::SimpleLogger().Write() << "Serializing compacted graph of " << contracted_edge_count - << " edges"; + << " edges"; const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); boost::filesystem::ofstream hsgr_output_stream(config.graph_output_path, std::ios::binary); @@ -308,7 +311,8 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, }(); util::SimpleLogger().Write(logDEBUG) << "input graph has " << (max_node_id + 1) << " nodes"; - util::SimpleLogger().Write(logDEBUG) << "contracted graph has " << (max_used_node_id + 1) << " nodes"; + util::SimpleLogger().Write(logDEBUG) << "contracted graph has " << (max_used_node_id + 1) + << " nodes"; std::vector::NodeArrayEntry> node_array; // make sure we have at least one sentinel @@ -355,7 +359,8 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, if (node_array_size > 0) { hsgr_output_stream.write((char *)&node_array[0], - sizeof(util::StaticGraph::NodeArrayEntry) * node_array_size); + sizeof(util::StaticGraph::NodeArrayEntry) * + node_array_size); } // serialize all edges @@ -375,14 +380,14 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, #ifndef NDEBUG if (current_edge.data.distance <= 0) { - util::SimpleLogger().Write(logWARNING) << "Edge: " << edge - << ",source: " << contracted_edge_list[edge].source - << ", target: " << contracted_edge_list[edge].target - << ", dist: " << current_edge.data.distance; + util::SimpleLogger().Write(logWARNING) + << "Edge: " << edge << ",source: " << contracted_edge_list[edge].source + << ", target: " << contracted_edge_list[edge].target + << ", dist: " << current_edge.data.distance; util::SimpleLogger().Write(logWARNING) << "Failed at adjacency list of node " - << contracted_edge_list[edge].source << "/" - << node_array.size() - 1; + << contracted_edge_list[edge].source << "/" + << node_array.size() - 1; return 1; } #endif @@ -398,11 +403,12 @@ std::size_t Prepare::WriteContractedGraph(unsigned max_node_id, /** \brief Build contracted graph. */ -void Prepare::ContractGraph(const unsigned max_edge_id, - util::DeallocatingVector &edge_based_edge_list, - util::DeallocatingVector &contracted_edge_list, - std::vector &is_core_node, - std::vector &inout_node_levels) const +void Prepare::ContractGraph( + const unsigned max_edge_id, + util::DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &contracted_edge_list, + std::vector &is_core_node, + std::vector &inout_node_levels) const { std::vector node_levels; node_levels.swap(inout_node_levels); diff --git a/src/extractor/compressed_edge_container.cpp b/src/extractor/compressed_edge_container.cpp index 9f20ac1ea..e34bb424e 100644 --- a/src/extractor/compressed_edge_container.cpp +++ b/src/extractor/compressed_edge_container.cpp @@ -186,16 +186,14 @@ void CompressedEdgeContainer::PrintStatistics() const longest_chain_length = std::max(longest_chain_length, (uint64_t)current_vector.size()); } - util::SimpleLogger().Write() << "Geometry successfully removed:" - "\n compressed edges: " - << compressed_edges - << "\n compressed geometries: " << compressed_geometries - << "\n longest chain length: " << longest_chain_length - << "\n cmpr ratio: " << ((float)compressed_edges / - std::max(compressed_geometries, (uint64_t)1)) - << "\n avg chain length: " - << (float)compressed_geometries / - std::max((uint64_t)1, compressed_edges); + util::SimpleLogger().Write() + << "Geometry successfully removed:" + "\n compressed edges: " + << compressed_edges << "\n compressed geometries: " << compressed_geometries + << "\n longest chain length: " << longest_chain_length << "\n cmpr ratio: " + << ((float)compressed_edges / std::max(compressed_geometries, (uint64_t)1)) + << "\n avg chain length: " + << (float)compressed_geometries / std::max((uint64_t)1, compressed_edges); } const CompressedEdgeContainer::EdgeBucket & diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 8bae91dc1..6c2bedcc1 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -37,7 +37,8 @@ EdgeBasedGraphFactory::EdgeBasedGraphFactory( { } -void EdgeBasedGraphFactory::GetEdgeBasedEdges(util::DeallocatingVector &output_edge_list) +void EdgeBasedGraphFactory::GetEdgeBasedEdges( + util::DeallocatingVector &output_edge_list) { BOOST_ASSERT_MSG(0 == output_edge_list.size(), "Vector is not empty"); using std::swap; // Koenig swap @@ -321,7 +322,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() BOOST_ASSERT(m_edge_based_node_list.size() == m_edge_based_node_is_startpoint.size()); util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() - << " nodes in edge-expanded graph"; + << " nodes in edge-expanded graph"; } /// Actually it also generates OriginalEdgeData and serializes them... @@ -451,7 +452,8 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( { distance += speed_profile.traffic_signal_penalty; - util::DEBUG_SIGNAL(node_v, m_node_info_list, speed_profile.traffic_signal_penalty); + util::DEBUG_SIGNAL(node_v, m_node_info_list, + speed_profile.traffic_signal_penalty); } // unpack last node of first segment if packed @@ -478,7 +480,8 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( util::DEBUG_UTURN(node_v, m_node_info_list, speed_profile.u_turn_penalty); } - util::DEBUG_TURN(node_v, m_node_info_list, first_coordinate, turn_angle, turn_penalty); + util::DEBUG_TURN(node_v, m_node_info_list, first_coordinate, turn_angle, + turn_penalty); distance += turn_penalty; @@ -546,8 +549,8 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( const QueryNode &from = m_node_info_list[previous]; const QueryNode &to = m_node_info_list[target_node.first]; const double segment_length = - util::coordinate_calculation::greatCircleDistance(from.lat, from.lon, - to.lat, to.lon); + util::coordinate_calculation::greatCircleDistance( + from.lat, from.lon, to.lat, to.lon); edge_segment_file.write(reinterpret_cast(&to.node_id), sizeof(to.node_id)); @@ -564,8 +567,9 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( static const unsigned node_count = 2; const QueryNode from = m_node_info_list[node_u]; const QueryNode to = m_node_info_list[node_v]; - const double segment_length = util::coordinate_calculation::greatCircleDistance( - from.lat, from.lon, to.lat, to.lon); + const double segment_length = + util::coordinate_calculation::greatCircleDistance(from.lat, from.lon, + to.lat, to.lon); edge_segment_file.write(reinterpret_cast(&node_count), sizeof(node_count)); edge_segment_file.write(reinterpret_cast(&from.node_id), @@ -591,15 +595,18 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( edge_data_file.write((char *)&original_edges_counter, sizeof(unsigned)); edge_data_file.close(); - util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " edge based nodes"; - util::SimpleLogger().Write() << "Node-based graph contains " << node_based_edge_counter << " edges"; + util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() + << " edge based nodes"; + util::SimpleLogger().Write() << "Node-based graph contains " << node_based_edge_counter + << " edges"; util::SimpleLogger().Write() << "Edge-expanded graph ..."; util::SimpleLogger().Write() << " contains " << m_edge_based_edge_list.size() << " edges"; util::SimpleLogger().Write() << " skips " << restricted_turns_counter << " turns, " - "defined by " - << m_restriction_map->size() << " restrictions"; + "defined by " + << m_restriction_map->size() << " restrictions"; util::SimpleLogger().Write() << " skips " << skipped_uturns_counter << " U turns"; - util::SimpleLogger().Write() << " skips " << skipped_barrier_turns_counter << " turns over barriers"; + util::SimpleLogger().Write() << " skips " << skipped_barrier_turns_counter + << " turns over barriers"; } int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) const diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 72333644a..299d35f24 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -218,7 +218,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) if (edge_iterator->result.osm_source_id < node_iterator->node_id) { util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " - << edge_iterator->result.source; + << edge_iterator->result.source; edge_iterator->result.source = SPECIAL_NODEID; ++edge_iterator; continue; @@ -255,7 +255,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) auto markSourcesInvalid = [](InternalExtractorEdge &edge) { util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " - << edge.result.source; + << edge.result.source; edge.result.source = SPECIAL_NODEID; edge.result.osm_source_id = SPECIAL_OSM_NODEID; }; @@ -362,7 +362,7 @@ void ExtractionContainers::PrepareEdges(lua_State *segment_state) auto markTargetsInvalid = [](InternalExtractorEdge &edge) { util::SimpleLogger().Write(LogLevel::logWARNING) << "Found invalid node reference " - << edge.result.target; + << edge.result.target; edge.result.target = SPECIAL_NODEID; }; std::for_each(edge_iterator, all_edges_list_end_, markTargetsInvalid); @@ -614,8 +614,9 @@ void ExtractionContainers::PrepareRestrictions() if (way_start_and_end_iterator->way_id > OSMWayID(restrictions_iterator->restriction.from.way)) { - util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " - << restrictions_iterator->restriction.from.way; + util::SimpleLogger().Write(LogLevel::logDEBUG) + << "Restriction references invalid way: " + << restrictions_iterator->restriction.from.way; restrictions_iterator->restriction.from.node = SPECIAL_NODEID; ++restrictions_iterator; continue; @@ -630,8 +631,9 @@ void ExtractionContainers::PrepareRestrictions() auto via_id_iter = external_to_internal_node_id_map.find(via_node_id); if (via_id_iter == external_to_internal_node_id_map.end()) { - util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid node: " - << restrictions_iterator->restriction.via.node; + util::SimpleLogger().Write(LogLevel::logDEBUG) + << "Restriction references invalid node: " + << restrictions_iterator->restriction.via.node; restrictions_iterator->restriction.via.node = SPECIAL_NODEID; ++restrictions_iterator; continue; @@ -691,8 +693,9 @@ void ExtractionContainers::PrepareRestrictions() if (way_start_and_end_iterator->way_id > OSMWayID(restrictions_iterator->restriction.to.way)) { - util::SimpleLogger().Write(LogLevel::logDEBUG) << "Restriction references invalid way: " - << restrictions_iterator->restriction.to.way; + util::SimpleLogger().Write(LogLevel::logDEBUG) + << "Restriction references invalid way: " + << restrictions_iterator->restriction.to.way; restrictions_iterator->restriction.to.way = SPECIAL_NODEID; ++restrictions_iterator; continue; diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 053e5bd1c..693576877 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -219,12 +219,13 @@ int extractor::run() } } TIMER_STOP(parsing); - util::SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds"; + util::SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) + << " seconds"; - util::SimpleLogger().Write() << "Raw input contains " << number_of_nodes.load() << " nodes, " - << number_of_ways.load() << " ways, and " - << number_of_relations.load() << " relations, and " - << number_of_others.load() << " unknown entities"; + util::SimpleLogger().Write() << "Raw input contains " << number_of_nodes.load() + << " nodes, " << number_of_ways.load() << " ways, and " + << number_of_relations.load() << " relations, and " + << number_of_others.load() << " unknown entities"; extractor_callbacks.reset(); @@ -238,7 +239,8 @@ int extractor::run() config.names_file_name, segment_state); TIMER_STOP(extracting); - util::SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s"; + util::SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) + << "s"; } catch (const std::exception &e) { @@ -287,12 +289,11 @@ int extractor::run() WriteEdgeBasedGraph(config.edge_graph_output_path, max_edge_id, edge_based_edge_list); - util::SimpleLogger().Write() << "Expansion : " - << (number_of_node_based_nodes / TIMER_SEC(expansion)) - << " nodes/sec and " << ((max_edge_id + 1) / TIMER_SEC(expansion)) - << " edges/sec"; + util::SimpleLogger().Write() + << "Expansion : " << (number_of_node_based_nodes / TIMER_SEC(expansion)) + << " nodes/sec and " << ((max_edge_id + 1) / TIMER_SEC(expansion)) << " edges/sec"; util::SimpleLogger().Write() << "To prepare the data for routing, run: " - << "./osrm-prepare " << config.output_file_name << std::endl; + << "./osrm-prepare " << config.output_file_name << std::endl; } catch (const std::exception &e) { @@ -332,7 +333,7 @@ void extractor::SetupScriptingEnvironment(lua_State *lua_state, } speed_profile.traffic_signal_penalty = 10 * lua_tointeger(lua_state, -1); util::SimpleLogger().Write(logDEBUG) << "traffic_signal_penalty: " - << speed_profile.traffic_signal_penalty; + << speed_profile.traffic_signal_penalty; if (0 != luaL_dostring(lua_state, "return u_turn_penalty\n")) { @@ -455,7 +456,7 @@ extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, input_stream, barrier_list, traffic_light_list, internal_to_external_node_map); util::SimpleLogger().Write() << " - " << barrier_list.size() << " bollard nodes, " - << traffic_light_list.size() << " traffic lights"; + << traffic_light_list.size() << " traffic lights"; // insert into unordered sets for fast lookup barrier_nodes.insert(barrier_list.begin(), barrier_list.end()); @@ -556,8 +557,8 @@ void extractor::BuildRTree(std::vector node_based_edge_list, const std::vector &internal_to_external_node_map) { util::SimpleLogger().Write() << "constructing r-tree of " << node_based_edge_list.size() - << " edge elements build on-top of " - << internal_to_external_node_map.size() << " coordinates"; + << " edge elements build on-top of " + << internal_to_external_node_map.size() << " coordinates"; BOOST_ASSERT(node_is_startpoint.size() == node_based_edge_list.size()); @@ -579,16 +580,18 @@ void extractor::BuildRTree(std::vector node_based_edge_list, TIMER_START(construction); util::StaticRTree rtree(node_based_edge_list, config.rtree_nodes_output_path, - config.rtree_leafs_output_path, internal_to_external_node_map); + config.rtree_leafs_output_path, + internal_to_external_node_map); TIMER_STOP(construction); util::SimpleLogger().Write() << "finished r-tree construction in " << TIMER_SEC(construction) - << " seconds"; + << " seconds"; } -void extractor::WriteEdgeBasedGraph(std::string const &output_file_filename, - size_t const max_edge_id, - util::DeallocatingVector const &edge_based_edge_list) +void extractor::WriteEdgeBasedGraph( + std::string const &output_file_filename, + size_t const max_edge_id, + util::DeallocatingVector const &edge_based_edge_list) { std::ofstream file_out_stream; diff --git a/src/extractor/extractor_callbacks.cpp b/src/extractor/extractor_callbacks.cpp index 03f60134f..25cc24ead 100644 --- a/src/extractor/extractor_callbacks.cpp +++ b/src/extractor/extractor_callbacks.cpp @@ -85,7 +85,7 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (std::numeric_limits::max() == input_way.id()) { util::SimpleLogger().Write(logDEBUG) << "found bogus way with id: " << input_way.id() - << " of size " << input_way.nodes().size(); + << " of size " << input_way.nodes().size(); return; } @@ -123,7 +123,8 @@ void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const Extracti if (forward_weight_data.type == InternalExtractorEdge::WeightType::INVALID && backward_weight_data.type == InternalExtractorEdge::WeightType::INVALID) { - util::SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << input_way.id(); + util::SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " + << input_way.id(); return; } diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp index 90d9ee8e3..12081266c 100644 --- a/src/extractor/extractor_options.cpp +++ b/src/extractor/extractor_options.cpp @@ -108,7 +108,7 @@ ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extrac if (boost::filesystem::is_regular_file(extractor_config.config_file_path)) { util::SimpleLogger().Write() << "Reading options from: " - << extractor_config.config_file_path.string(); + << extractor_config.config_file_path.string(); std::string ini_file_contents = util::read_file_lower_content(extractor_config.config_file_path); std::stringstream config_stream(ini_file_contents); diff --git a/src/extractor/graph_compressor.cpp b/src/extractor/graph_compressor.cpp index ec02fdc57..c288bf54b 100644 --- a/src/extractor/graph_compressor.cpp +++ b/src/extractor/graph_compressor.cpp @@ -183,9 +183,9 @@ void GraphCompressor::PrintStatistics(unsigned original_number_of_nodes, } } util::SimpleLogger().Write() << "Node compression ratio: " - << new_node_count / (double)original_number_of_nodes; + << new_node_count / (double)original_number_of_nodes; util::SimpleLogger().Write() << "Edge compression ratio: " - << new_edge_count / (double)original_number_of_edges; + << new_edge_count / (double)original_number_of_edges; } } } diff --git a/src/extractor/raster_source.cpp b/src/extractor/raster_source.cpp index 840e79449..2d369cb44 100644 --- a/src/extractor/raster_source.cpp +++ b/src/extractor/raster_source.cpp @@ -93,7 +93,7 @@ int SourceContainer::loadRasterSource(const std::string &path_string, if (itr != LoadedSourcePaths.end()) { util::SimpleLogger().Write() << "[source loader] Already loaded source '" << path_string - << "' at source_id " << itr->second; + << "' at source_id " << itr->second; return itr->second; } @@ -115,7 +115,8 @@ int SourceContainer::loadRasterSource(const std::string &path_string, LoadedSourcePaths.emplace(path_string, source_id); LoadedSources.push_back(std::move(source)); - util::SimpleLogger().Write() << "[source loader] ok, after " << TIMER_SEC(loading_source) << "s"; + util::SimpleLogger().Write() << "[source loader] ok, after " << TIMER_SEC(loading_source) + << "s"; return source_id; } diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index 2c3641a4c..3df9e0754 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -24,7 +24,8 @@ namespace osrm namespace extractor { -namespace { +namespace +{ int luaErrorCallback(lua_State *lua_state) { std::string error_msg = lua_tostring(lua_state, -1); @@ -70,7 +71,7 @@ void RestrictionParser::ReadRestrictionExceptions(lua_State *lua_state) boost::ref(restriction_exceptions)); const unsigned exception_count = restriction_exceptions.size(); util::SimpleLogger().Write() << "Found " << exception_count - << " exceptions to turn restrictions:"; + << " exceptions to turn restrictions:"; for (const std::string &str : restriction_exceptions) { util::SimpleLogger().Write() << " " << str; diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index a579a039d..4b83c83ee 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -53,18 +53,16 @@ void RequestHandler::handle_request(const http::request ¤t_request, time_stamp = localtime(<ime); // log timestamp - util::SimpleLogger().Write() << (time_stamp->tm_mday < 10 ? "0" : "") << time_stamp->tm_mday - << "-" << (time_stamp->tm_mon + 1 < 10 ? "0" : "") - << (time_stamp->tm_mon + 1) << "-" << 1900 + time_stamp->tm_year - << " " << (time_stamp->tm_hour < 10 ? "0" : "") - << time_stamp->tm_hour << ":" << (time_stamp->tm_min < 10 ? "0" : "") - << time_stamp->tm_min << ":" << (time_stamp->tm_sec < 10 ? "0" : "") - << time_stamp->tm_sec << " " << current_request.endpoint.to_string() - << " " << current_request.referrer - << (0 == current_request.referrer.length() ? "- " : " ") - << current_request.agent - << (0 == current_request.agent.length() ? "- " : " ") - << request_string; + util::SimpleLogger().Write() + << (time_stamp->tm_mday < 10 ? "0" : "") << time_stamp->tm_mday << "-" + << (time_stamp->tm_mon + 1 < 10 ? "0" : "") << (time_stamp->tm_mon + 1) << "-" + << 1900 + time_stamp->tm_year << " " << (time_stamp->tm_hour < 10 ? "0" : "") + << time_stamp->tm_hour << ":" << (time_stamp->tm_min < 10 ? "0" : "") + << time_stamp->tm_min << ":" << (time_stamp->tm_sec < 10 ? "0" : "") + << time_stamp->tm_sec << " " << current_request.endpoint.to_string() << " " + << current_request.referrer << (0 == current_request.referrer.length() ? "- " : " ") + << current_request.agent << (0 == current_request.agent.length() ? "- " : " ") + << request_string; engine::RouteParameters route_parameters; APIGrammarParser api_parser(&route_parameters); @@ -151,7 +149,7 @@ void RequestHandler::handle_request(const http::request ¤t_request, current_reply = http::reply::stock_reply(http::reply::internal_server_error); ; util::SimpleLogger().Write(logWARNING) << "[server error] code: " << e.what() - << ", uri: " << current_request.uri; + << ", uri: " << current_request.uri; } } diff --git a/src/tools/check-hsgr.cpp b/src/tools/check-hsgr.cpp index 4c6b3deb1..6f97d32ec 100644 --- a/src/tools/check-hsgr.cpp +++ b/src/tools/check-hsgr.cpp @@ -19,7 +19,6 @@ namespace tools using EdgeData = contractor::QueryEdge::EdgeData; using QueryGraph = util::StaticGraph; - } } @@ -44,10 +43,10 @@ int main(int argc, char *argv[]) unsigned m_number_of_nodes = readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); osrm::util::SimpleLogger().Write() << "expecting " << m_number_of_nodes - << " nodes, checksum: " << m_check_sum; + << " nodes, checksum: " << m_check_sum; BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); - osrm::util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " << edge_list.size() - << " edges"; + osrm::util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " + << edge_list.size() << " edges"; auto m_query_graph = std::make_shared(node_list, edge_list); BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); @@ -67,18 +66,18 @@ int main(int argc, char *argv[]) const EdgeID edge_id_1 = m_query_graph->FindEdgeInEitherDirection(node_u, data.id); if (SPECIAL_EDGEID == edge_id_1) { - throw osrm::util::exception("cannot find first segment of edge (" + - std::to_string(node_u) + "," + std::to_string(data.id) + - "," + std::to_string(node_v) + "), eid: " + - std::to_string(eid)); + throw osrm::util::exception( + "cannot find first segment of edge (" + std::to_string(node_u) + "," + + std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + + std::to_string(eid)); } const EdgeID edge_id_2 = m_query_graph->FindEdgeInEitherDirection(data.id, node_v); if (SPECIAL_EDGEID == edge_id_2) { - throw osrm::util::exception("cannot find second segment of edge (" + - std::to_string(node_u) + "," + std::to_string(data.id) + - "," + std::to_string(node_v) + "), eid: " + - std::to_string(eid)); + throw osrm::util::exception( + "cannot find second segment of edge (" + std::to_string(node_u) + "," + + std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + + std::to_string(eid)); } } progress.printStatus(node_u); diff --git a/src/tools/components.cpp b/src/tools/components.cpp index ffefa984f..ae6da2126 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -66,7 +66,7 @@ std::size_t loadGraph(const char *path, std::vector barrier_node_list; auto number_of_nodes = util::loadNodesFromFile(input_stream, barrier_node_list, - traffic_light_node_list, coordinate_list); + traffic_light_node_list, coordinate_list); util::loadEdgesFromFile(input_stream, edge_list); @@ -116,17 +116,20 @@ int main(int argc, char *argv[]) auto number_of_nodes = osrm::tools::loadGraph(argv[1], coordinate_list, graph_edge_list); tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); - const auto graph = std::make_shared(number_of_nodes, graph_edge_list); + const auto graph = + std::make_shared(number_of_nodes, graph_edge_list); graph_edge_list.clear(); graph_edge_list.shrink_to_fit(); osrm::util::SimpleLogger().Write() << "Starting SCC graph traversal"; - auto tarjan = osrm::util::make_unique>(graph); + auto tarjan = + osrm::util::make_unique>(graph); tarjan->run(); osrm::util::SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() - << " many components"; - osrm::util::SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " size 1 SCCs"; + << " many components"; + osrm::util::SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() + << " size 1 SCCs"; // output TIMER_START(SCC_RUN_SETUP); @@ -141,8 +144,7 @@ int main(int argc, char *argv[]) OGRRegisterAll(); const char *psz_driver_name = "ESRI Shapefile"; - auto *po_driver = - OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(psz_driver_name); + auto *po_driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(psz_driver_name); if (nullptr == po_driver) { throw osrm::util::exception("ESRI Shapefile driver not available"); @@ -164,8 +166,8 @@ int main(int argc, char *argv[]) throw osrm::util::exception("Layer creation failed."); } TIMER_STOP(SCC_RUN_SETUP); - osrm::util::SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP) / 1000. - << "s"; + osrm::util::SimpleLogger().Write() << "shapefile setup took " + << TIMER_MSEC(SCC_RUN_SETUP) / 1000. << "s"; uint64_t total_network_length = 0; percentage.reinit(graph->GetNumberOfNodes()); @@ -196,12 +198,15 @@ int main(int argc, char *argv[]) if (size_of_containing_component < 1000) { OGRLineString line_string; - line_string.addPoint(coordinate_list[source].lon / osrm::COORDINATE_PRECISION, - coordinate_list[source].lat / osrm::COORDINATE_PRECISION); - line_string.addPoint(coordinate_list[target].lon / osrm::COORDINATE_PRECISION, - coordinate_list[target].lat / osrm::COORDINATE_PRECISION); + line_string.addPoint( + coordinate_list[source].lon / osrm::COORDINATE_PRECISION, + coordinate_list[source].lat / osrm::COORDINATE_PRECISION); + line_string.addPoint( + coordinate_list[target].lon / osrm::COORDINATE_PRECISION, + coordinate_list[target].lat / osrm::COORDINATE_PRECISION); - OGRFeature *po_feature = OGRFeature::CreateFeature(po_layer->GetLayerDefn()); + OGRFeature *po_feature = + OGRFeature::CreateFeature(po_layer->GetLayerDefn()); po_feature->SetGeometry(&line_string); if (OGRERR_NONE != po_layer->CreateFeature(po_feature)) @@ -216,12 +221,12 @@ int main(int argc, char *argv[]) OGRSpatialReference::DestroySpatialReference(po_srs); OGRDataSource::DestroyDataSource(po_datasource); TIMER_STOP(SCC_OUTPUT); - osrm::util::SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. - << "s"; + osrm::util::SimpleLogger().Write() + << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. << "s"; - osrm::util::SimpleLogger().Write() << "total network distance: " - << static_cast(total_network_length / 100 / 1000.) - << " km"; + osrm::util::SimpleLogger().Write() + << "total network distance: " + << static_cast(total_network_length / 100 / 1000.) << " km"; osrm::util::SimpleLogger().Write() << "finished component analysis"; } diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index 151965281..508f77bf8 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -18,7 +18,8 @@ int main(int argc, char *argv[]) try util::LogPolicy::GetInstance().Unmute(); contractor::ContractorConfig contractor_config; - const contractor::return_code result = contractor::ContractorOptions::ParseArguments(argc, argv, contractor_config); + const contractor::return_code result = + contractor::ContractorOptions::ParseArguments(argc, argv, contractor_config); if (contractor::return_code::fail == result) { @@ -42,9 +43,9 @@ int main(int argc, char *argv[]) try if (recommended_num_threads != contractor_config.requested_num_threads) { - util::SimpleLogger().Write(logWARNING) << "The recommended number of threads is " - << recommended_num_threads - << "! This setting may have performance side-effects."; + util::SimpleLogger().Write(logWARNING) + << "The recommended number of threads is " << recommended_num_threads + << "! This setting may have performance side-effects."; } if (!boost::filesystem::is_regular_file(contractor_config.osrm_input_path)) @@ -56,14 +57,15 @@ int main(int argc, char *argv[]) try if (!boost::filesystem::is_regular_file(contractor_config.profile_path)) { - util::SimpleLogger().Write(logWARNING) << "Profile " << contractor_config.profile_path.string() - << " not found!"; + util::SimpleLogger().Write(logWARNING) + << "Profile " << contractor_config.profile_path.string() << " not found!"; return EXIT_FAILURE; } util::SimpleLogger().Write() << "Input file: " - << contractor_config.osrm_input_path.filename().string(); - util::SimpleLogger().Write() << "Profile: " << contractor_config.profile_path.filename().string(); + << contractor_config.osrm_input_path.filename().string(); + util::SimpleLogger().Write() << "Profile: " + << contractor_config.profile_path.filename().string(); util::SimpleLogger().Write() << "Threads: " << contractor_config.requested_num_threads; tbb::task_scheduler_init init(contractor_config.requested_num_threads); diff --git a/src/tools/datastore.cpp b/src/tools/datastore.cpp index b459465f2..41e11dcfe 100644 --- a/src/tools/datastore.cpp +++ b/src/tools/datastore.cpp @@ -37,8 +37,11 @@ using namespace osrm::engine::datafacade; using namespace osrm::datastore; using namespace osrm; -using RTreeLeaf = typename engine::datafacade::BaseDataFacade::RTreeLeaf; -using RTreeNode = util::StaticRTree::vector, true>::TreeNode; +using RTreeLeaf = + typename engine::datafacade::BaseDataFacade::RTreeLeaf; +using RTreeNode = util::StaticRTree::vector, + true>::TreeNode; using QueryGraph = util::StaticGraph; namespace osrm @@ -75,7 +78,6 @@ void deleteRegion(const SharedDataType region) util::SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; } } - } } @@ -89,7 +91,8 @@ int main(const int argc, const char *argv[]) try const bool lock_flags = MCL_CURRENT | MCL_FUTURE; if (-1 == mlockall(lock_flags)) { - util::SimpleLogger().Write(logWARNING) << "Process " << argv[0] << " could not request RAM lock"; + util::SimpleLogger().Write(logWARNING) << "Process " << argv[0] + << " could not request RAM lock"; } #endif @@ -237,9 +240,9 @@ int main(const int argc, const char *argv[]) try shared_layout_ptr->SetBlockSize(SharedDataLayout::NAME_ID_LIST, number_of_original_edges); shared_layout_ptr->SetBlockSize(SharedDataLayout::TRAVEL_MODE, - number_of_original_edges); + number_of_original_edges); shared_layout_ptr->SetBlockSize(SharedDataLayout::TURN_INSTRUCTION, - number_of_original_edges); + number_of_original_edges); // note: there are 32 geometry indicators in one unsigned block shared_layout_ptr->SetBlockSize(SharedDataLayout::GEOMETRIES_INDICATORS, number_of_original_edges); @@ -256,7 +259,7 @@ int main(const int argc, const char *argv[]) try else { util::SimpleLogger().Write(logWARNING) << ".hsgr was prepared with different build. " - "Reprocess to get rid of this warning."; + "Reprocess to get rid of this warning."; } // load checksum @@ -292,7 +295,8 @@ int main(const int argc, const char *argv[]) try boost::filesystem::ifstream timestamp_stream(timestamp_path); if (!timestamp_stream) { - util::SimpleLogger().Write(logWARNING) << timestamp_path << " not found. setting to default"; + util::SimpleLogger().Write(logWARNING) << timestamp_path + << " not found. setting to default"; } else { @@ -323,7 +327,7 @@ int main(const int argc, const char *argv[]) try unsigned coordinate_list_size = 0; nodes_input_stream.read((char *)&coordinate_list_size, sizeof(unsigned)); shared_layout_ptr->SetBlockSize(SharedDataLayout::COORDINATE_LIST, - coordinate_list_size); + coordinate_list_size); // load geometries sizes std::ifstream geometry_input_stream(geometries_data_path.string().c_str(), std::ios::binary); @@ -339,8 +343,8 @@ int main(const int argc, const char *argv[]) try shared_layout_ptr->SetBlockSize(SharedDataLayout::GEOMETRIES_LIST, number_of_compressed_geometries); // allocate shared memory block - util::SimpleLogger().Write() << "allocating shared memory of " << shared_layout_ptr->GetSizeOfLayout() - << " bytes"; + util::SimpleLogger().Write() << "allocating shared memory of " + << shared_layout_ptr->GetSizeOfLayout() << " bytes"; SharedMemory *shared_memory = SharedMemoryFactory::Get(data_region, shared_layout_ptr->GetSizeOfLayout()); char *shared_memory_ptr = static_cast(shared_memory->Ptr()); @@ -403,11 +407,13 @@ int main(const int argc, const char *argv[]) try unsigned *name_id_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::NAME_ID_LIST); - extractor::TravelMode *travel_mode_ptr = shared_layout_ptr->GetBlockPtr( - shared_memory_ptr, SharedDataLayout::TRAVEL_MODE); + extractor::TravelMode *travel_mode_ptr = + shared_layout_ptr->GetBlockPtr(shared_memory_ptr, + SharedDataLayout::TRAVEL_MODE); - extractor::TurnInstruction *turn_instructions_ptr = shared_layout_ptr->GetBlockPtr( - shared_memory_ptr, SharedDataLayout::TURN_INSTRUCTION); + extractor::TurnInstruction *turn_instructions_ptr = + shared_layout_ptr->GetBlockPtr( + shared_memory_ptr, SharedDataLayout::TURN_INSTRUCTION); unsigned *geometries_indicator_ptr = shared_layout_ptr->GetBlockPtr( shared_memory_ptr, SharedDataLayout::GEOMETRIES_INDICATORS); @@ -575,8 +581,9 @@ int main(const int argc, const char *argv[]) try catch (const std::bad_alloc &e) { util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - util::SimpleLogger().Write(logWARNING) << "Please provide more memory or disable locking the virtual " - "address space (note: this makes OSRM swap, i.e. slow)"; + util::SimpleLogger().Write(logWARNING) + << "Please provide more memory or disable locking the virtual " + "address space (note: this makes OSRM swap, i.e. slow)"; return EXIT_FAILURE; } catch (const std::exception &e) diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index 7f317cb8d..a4edf8ba0 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -15,7 +15,8 @@ int main(int argc, char *argv[]) try util::LogPolicy::GetInstance().Unmute(); extractor::ExtractorConfig extractor_config; - const extractor::return_code result = extractor::ExtractorOptions::ParseArguments(argc, argv, extractor_config); + const extractor::return_code result = + extractor::ExtractorOptions::ParseArguments(argc, argv, extractor_config); if (extractor::return_code::fail == result) { @@ -37,15 +38,15 @@ int main(int argc, char *argv[]) try if (!boost::filesystem::is_regular_file(extractor_config.input_path)) { - util::SimpleLogger().Write(logWARNING) << "Input file " << extractor_config.input_path.string() - << " not found!"; + util::SimpleLogger().Write(logWARNING) + << "Input file " << extractor_config.input_path.string() << " not found!"; return EXIT_FAILURE; } if (!boost::filesystem::is_regular_file(extractor_config.profile_path)) { - util::SimpleLogger().Write(logWARNING) << "Profile " << extractor_config.profile_path.string() - << " not found!"; + util::SimpleLogger().Write(logWARNING) + << "Profile " << extractor_config.profile_path.string() << " not found!"; return EXIT_FAILURE; } return extractor::extractor(extractor_config).run(); diff --git a/src/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp index dda28000e..edd128d1b 100644 --- a/src/tools/io-benchmark.cpp +++ b/src/tools/io-benchmark.cpp @@ -44,7 +44,6 @@ void runStatistics(std::vector &timings_vector, Statistics &stats) timings_vector.begin(), 0.0); stats.dev = std::sqrt(primary_sq_sum / timings_vector.size() - (stats.mean * stats.mean)); } - } } @@ -66,7 +65,8 @@ int main(int argc, char *argv[]) { if (1 == argc) { - osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device"; + osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] + << " /path/on/device"; return -1; } @@ -90,7 +90,8 @@ int main(int argc, char *argv[]) fcntl(fileno(fd), F_NOCACHE, 1); fcntl(fileno(fd), F_RDAHEAD, 0); TIMER_START(write_1gb); - write(fileno(fd), (char *)random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + write(fileno(fd), (char *)random_array, + osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); TIMER_STOP(write_1gb); fclose(fd); #endif @@ -102,7 +103,8 @@ int main(int argc, char *argv[]) throw osrm::util::exception("Could not open random data file"); } TIMER_START(write_1gb); - int ret = write(file_desc, random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + int ret = + write(file_desc, random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); if (0 > ret) { throw osrm::util::exception("could not write random data file"); @@ -111,10 +113,11 @@ int main(int argc, char *argv[]) close(file_desc); #endif delete[] random_array; - osrm::util::SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb) - << "s"; + osrm::util::SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " + << TIMER_SEC(write_1gb) << "s"; osrm::util::SimpleLogger().Write() << "raw write performance: " << std::setprecision(5) - << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) << "MB/sec"; + << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) + << "MB/sec"; osrm::util::SimpleLogger().Write(logDEBUG) << "finished creation of random data. Flush disk cache now!"; @@ -146,7 +149,8 @@ int main(int argc, char *argv[]) osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); return -1; } - char *raw_array = (char *)memalign(512, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + char *raw_array = + (char *)memalign(512, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); #endif TIMER_START(read_1gb); #ifdef __APPLE__ @@ -155,18 +159,21 @@ int main(int argc, char *argv[]) fd = fopen(test_path.string().c_str(), "r"); #endif #ifdef __linux__ - int ret = read(file_desc, raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + int ret = + read(file_desc, raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); osrm::util::SimpleLogger().Write(logDEBUG) << "read " << ret - << " bytes, error: " << strerror(errno); + << " bytes, error: " << strerror(errno); close(file_desc); file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); #endif TIMER_STOP(read_1gb); - osrm::util::SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb) << "s"; - osrm::util::SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed - << 1024 * 1024 / TIMER_SEC(read_1gb) << "MB/sec"; + osrm::util::SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " + << TIMER_SEC(read_1gb) << "s"; + osrm::util::SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) + << std::fixed << 1024 * 1024 / TIMER_SEC(read_1gb) + << "MB/sec"; std::vector timing_results_raw_random; osrm::util::SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB"; @@ -178,7 +185,8 @@ int main(int argc, char *argv[]) lseek(file_desc, 0, SEEK_SET); #endif // make 1000 random access, time each I/O seperately - unsigned number_of_blocks = (osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned) - 1) / 4096; + unsigned number_of_blocks = + (osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned) - 1) / 4096; std::random_device rd; std::default_random_engine e1(rd()); std::uniform_int_distribution uniform_dist(0, number_of_blocks - 1); @@ -205,13 +213,15 @@ int main(int argc, char *argv[]) if (((off_t)-1) == ret1) { osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - osrm::util::SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); + osrm::util::SimpleLogger().Write(logWARNING) << "seek error " + << strerror(errno); throw osrm::util::exception("seek error"); } if (-1 == ret2) { osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - osrm::util::SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); + osrm::util::SimpleLogger().Write(logWARNING) << "read error " + << strerror(errno); throw osrm::util::exception("read error"); } timing_results_raw_random.push_back(TIMER_SEC(random_access)); @@ -227,12 +237,12 @@ int main(int argc, char *argv[]) random_csv.close(); osrm::tools::runStatistics(timing_results_raw_random, stats); - osrm::util::SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed - << "min: " << stats.min << "ms, " - << "mean: " << stats.mean << "ms, " - << "med: " << stats.med << "ms, " - << "max: " << stats.max << "ms, " - << "dev: " << stats.dev << "ms"; + osrm::util::SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) + << std::fixed << "min: " << stats.min << "ms, " + << "mean: " << stats.mean << "ms, " + << "med: " << stats.med << "ms, " + << "max: " << stats.max << "ms, " + << "dev: " << stats.dev << "ms"; std::vector timing_results_raw_seq; #ifdef __APPLE__ @@ -266,13 +276,15 @@ int main(int argc, char *argv[]) if (((off_t)-1) == ret1) { osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - osrm::util::SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno); + osrm::util::SimpleLogger().Write(logWARNING) << "seek error " + << strerror(errno); throw osrm::util::exception("seek error"); } if (-1 == ret2) { osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - osrm::util::SimpleLogger().Write(logWARNING) << "read error " << strerror(errno); + osrm::util::SimpleLogger().Write(logWARNING) << "read error " + << strerror(errno); throw osrm::util::exception("read error"); } timing_results_raw_seq.push_back(TIMER_SEC(read_every_100)); @@ -296,12 +308,12 @@ int main(int argc, char *argv[]) } seq_csv.close(); osrm::tools::runStatistics(timing_results_raw_seq, stats); - osrm::util::SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed - << "min: " << stats.min << "ms, " - << "mean: " << stats.mean << "ms, " - << "med: " << stats.med << "ms, " - << "max: " << stats.max << "ms, " - << "dev: " << stats.dev << "ms"; + osrm::util::SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) + << std::fixed << "min: " << stats.min << "ms, " + << "mean: " << stats.mean << "ms, " + << "med: " << stats.med << "ms, " + << "max: " << stats.max << "ms, " + << "dev: " << stats.dev << "ms"; if (boost::filesystem::exists(test_path)) { diff --git a/src/tools/simpleclient.cpp b/src/tools/simpleclient.cpp index 65198ee05..f00b302d6 100644 --- a/src/tools/simpleclient.cpp +++ b/src/tools/simpleclient.cpp @@ -61,7 +61,8 @@ int main(int argc, const char *argv[]) } catch (std::exception ¤t_exception) { - osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " << current_exception.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " + << current_exception.what(); return -1; } return 0; diff --git a/src/tools/springclean.cpp b/src/tools/springclean.cpp index f242e5ed2..7408e7d2c 100644 --- a/src/tools/springclean.cpp +++ b/src/tools/springclean.cpp @@ -63,10 +63,13 @@ int main() osrm::util::SimpleLogger().Write() << "Releasing all locks"; osrm::util::SimpleLogger().Write() << "ATTENTION! BE CAREFUL!"; osrm::util::SimpleLogger().Write() << "----------------------"; - osrm::util::SimpleLogger().Write() << "This tool may put osrm-routed into an undefined state!"; - osrm::util::SimpleLogger().Write() << "Type 'Y' to acknowledge that you know what your are doing."; - osrm::util::SimpleLogger().Write() << "\n\nDo you want to purge all shared memory allocated " - << "by osrm-datastore? [type 'Y' to confirm]"; + osrm::util::SimpleLogger().Write() + << "This tool may put osrm-routed into an undefined state!"; + osrm::util::SimpleLogger().Write() + << "Type 'Y' to acknowledge that you know what your are doing."; + osrm::util::SimpleLogger().Write() + << "\n\nDo you want to purge all shared memory allocated " + << "by osrm-datastore? [type 'Y' to confirm]"; const auto letter = getchar(); if (letter != 'Y') diff --git a/src/util/coordinate.cpp b/src/util/coordinate.cpp index 4a35c7ed4..da1f9db9e 100644 --- a/src/util/coordinate.cpp +++ b/src/util/coordinate.cpp @@ -52,7 +52,8 @@ bool FixedPointCoordinate::operator==(const FixedPointCoordinate &other) const std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate) { - out << "(" << static_cast(coordinate.lat / COORDINATE_PRECISION) << "," << static_cast(coordinate.lon / COORDINATE_PRECISION) << ")"; + out << "(" << static_cast(coordinate.lat / COORDINATE_PRECISION) << "," + << static_cast(coordinate.lon / COORDINATE_PRECISION) << ")"; return out; } } diff --git a/src/util/osrm_exception.cpp b/src/util/osrm_exception.cpp index a987bc75d..91ca7c4f5 100644 --- a/src/util/osrm_exception.cpp +++ b/src/util/osrm_exception.cpp @@ -17,6 +17,5 @@ namespace util { void exception::anchor() const {} - } } diff --git a/unit_tests/engine/douglas_peucker.cpp b/unit_tests/engine/douglas_peucker.cpp index 0a5bc0a87..4c165c1a6 100644 --- a/unit_tests/engine/douglas_peucker.cpp +++ b/unit_tests/engine/douglas_peucker.cpp @@ -15,8 +15,8 @@ using namespace osrm::engine; SegmentInformation getTestInfo(int lat, int lon, bool necessary) { - return SegmentInformation(util::FixedPointCoordinate(lat, lon), 0, 0, 0, extractor::TurnInstruction::HeadOn, - necessary, false, 0); + return SegmentInformation(util::FixedPointCoordinate(lat, lon), 0, 0, 0, + extractor::TurnInstruction::HeadOn, necessary, false, 0); } BOOST_AUTO_TEST_CASE(all_necessary_test) From 21804aecdbba25d2322d1ab8e44f130766fb062f Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 8 Jan 2016 23:33:31 +0100 Subject: [PATCH 048/701] Prefer `inline` over `static inline` for free standing functions When you mark free standing functions as `static inline` instead of just `inline` they can not get merged across TUs and therefore produce code bloat which is bad for the binaries size, the CPUs instruction cache, and so on. Please also see the discussion at: - https://groups.google.com/forum/#!topic/mozilla.dev.platform/Ulw9HoZbSyQ - http://stackoverflow.com/a/12836392 Note that non-fully specialized templates (i.e. with a kind of at least `Template :: * -> *`) are `inline` by default. --- include/util/string_util.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/util/string_util.hpp b/include/util/string_util.hpp index 1a54c9475..41c5f091f 100644 --- a/include/util/string_util.hpp +++ b/include/util/string_util.hpp @@ -15,7 +15,7 @@ namespace util // precision: position after decimal point // length: maximum number of digits including comma and decimals // work with negative values to prevent overflowing when taking -value -template static inline char *printInt(char *buffer, int value) +template char *printInt(char *buffer, int value) { static_assert(length > 0, "length must be positive"); static_assert(precision > 0, "precision must be positive"); From a2555983e66f96be5bc026ed7f0164623fdde3a5 Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Fri, 8 Jan 2016 12:43:33 +0100 Subject: [PATCH 049/701] replaces and/not with &&/! for windows --- include/engine/api_response_generator.hpp | 2 +- include/engine/guidance/segment_list.hpp | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index d8c16ba33..9b056ed61 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -257,7 +257,7 @@ ApiResponseGenerator::BuildRouteSegments(const Segments &segment_li for (const auto &segment : segment_list.Get()) { const auto current_turn = segment.turn_instruction; - if (extractor::TurnInstructionsClass::TurnIsNecessary(current_turn) and + if (extractor::TurnInstructionsClass::TurnIsNecessary(current_turn) && (extractor::TurnInstruction::EnterRoundAbout != current_turn)) { diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index 8ae9b6884..51a1695bd 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -77,7 +77,7 @@ SegmentList::SegmentList(const InternalRouteResult &raw_route, const DataFacade *facade) : total_distance(0), total_duration(0) { - if (not raw_route.is_valid()) + if (!raw_route.is_valid()) { return; } @@ -105,7 +105,7 @@ SegmentList::SegmentList(const InternalRouteResult &raw_route, } } - if (not allow_simplification) + if (!allow_simplification) { // to prevent any simplifications, we mark all segments as necessary for (auto &segment : segments) @@ -178,7 +178,7 @@ void SegmentList::AppendSegment(const FixedPointCoordinate &coordin { // if the start location is on top of a node, the first movement might be zero-length, // in which case we dont' add a new description, but instead update the existing one - if ((1 == segments.size()) and (segments.front().location == coordinate)) + if ((1 == segments.size()) && (segments.front().location == coordinate)) { if (path_point.segment_duration > 0) { @@ -191,8 +191,8 @@ void SegmentList::AppendSegment(const FixedPointCoordinate &coordin // make sure mode changes are announced, even when there otherwise is no turn const auto getTurn = [](const PathData &path_point, const extractor::TravelMode previous_mode) { - if (extractor::TurnInstruction::NoTurn == path_point.turn_instruction and - previous_mode != path_point.travel_mode and path_point.segment_duration > 0) + if (extractor::TurnInstruction::NoTurn == path_point.turn_instruction && + previous_mode != path_point.travel_mode && path_point.segment_duration > 0) { return extractor::TurnInstruction::GoStraight; } From 8638cbf8b2c0bf81dff00ac72207a706445e9b6d Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Fri, 8 Jan 2016 13:31:16 +0100 Subject: [PATCH 050/701] missed a not --- include/engine/api_response_generator.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index 9b056ed61..7f4d66cf9 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -96,7 +96,7 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con const InternalRouteResult &raw_route, util::json::Object &json_result) { - if (not raw_route.is_valid()) + if (!raw_route.is_valid()) { return; } From 4dc6ff9fb8931bd4fa90a61c0feea5e5904723cf Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Fri, 8 Jan 2016 14:29:09 +0100 Subject: [PATCH 051/701] and another missed not --- include/engine/route_name_extraction.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/engine/route_name_extraction.hpp b/include/engine/route_name_extraction.hpp index dd28f97c1..e9070b486 100644 --- a/include/engine/route_name_extraction.hpp +++ b/include/engine/route_name_extraction.hpp @@ -129,7 +129,7 @@ template struct ExtractRouteNames route_names.shortest_path_name_1 = facade->get_name_for_id(shortest_segment_1.name_id); route_names.shortest_path_name_2 = facade->get_name_for_id(shortest_segment_2.name_id); - if (not alternative_path_segments.empty()) + if (!alternative_path_segments.empty()) { route_names.alternative_path_name_1 = facade->get_name_for_id(alternative_segment_1.name_id); From 23cd4d5ed223755ad8068a6d3c9fe5c3cffacd91 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sat, 9 Jan 2016 17:32:40 +0100 Subject: [PATCH 052/701] not -> ! --- include/engine/api_response_generator.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index 7f4d66cf9..77a220d7e 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -190,7 +190,7 @@ ApiResponseGenerator::SummarizeRoute(const InternalRouteResult &raw const Segments &segment_list) const { util::json::Object json_route_summary; - if (not raw_route.segment_end_coordinates.empty()) + if (!raw_route.segment_end_coordinates.empty()) { const auto start_name_id = raw_route.segment_end_coordinates.front().source_phantom.name_id; json_route_summary.values["start_point"] = facade->get_name_for_id(start_name_id); From c590596dbe6fbf0f6a343e4cde463c32726fb03a Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 8 Jan 2016 12:55:37 +0100 Subject: [PATCH 053/701] Make DouglasPeucker a free standing function --- include/engine/api_response_generator.hpp | 4 +- include/engine/douglas_peucker.hpp | 52 +++++++++++------------ include/engine/guidance/segment_list.hpp | 7 ++- src/engine/douglas_peucker.cpp | 28 ++++++------ unit_tests/engine/douglas_peucker.cpp | 52 ++++++++++++----------- 5 files changed, 73 insertions(+), 70 deletions(-) diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index 77a220d7e..747a3639b 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -4,7 +4,6 @@ #include "guidance/segment_list.hpp" #include "guidance/textual_route_annotation.hpp" -#include "engine/douglas_peucker.hpp" #include "engine/internal_route_result.hpp" #include "engine/object_encoder.hpp" #include "engine/phantom_node.hpp" @@ -261,7 +260,8 @@ ApiResponseGenerator::BuildRouteSegments(const Segments &segment_li (extractor::TurnInstruction::EnterRoundAbout != current_turn)) { - detail::Segment seg = {segment.name_id, static_cast(segment.length), + detail::Segment seg = {segment.name_id, + static_cast(segment.length), static_cast(result.size())}; result.emplace_back(std::move(seg)); } diff --git a/include/engine/douglas_peucker.hpp b/include/engine/douglas_peucker.hpp index df4fe921d..a100f0f04 100644 --- a/include/engine/douglas_peucker.hpp +++ b/include/engine/douglas_peucker.hpp @@ -3,24 +3,16 @@ #include "engine/segment_information.hpp" -#include -#include -#include #include +#include namespace osrm { namespace engine { - -/* This class object computes the bitvector of indicating generalized input - * points according to the (Ramer-)Douglas-Peucker algorithm. - * - * Input is vector of pairs. Each pair consists of the point information and a - * bit indicating if the points is present in the generalization. - * Note: points may also be pre-selected*/ - -static const std::array DOUGLAS_PEUCKER_THRESHOLDS{{ +namespace detail +{ +const constexpr int DOUGLAS_PEUCKER_THRESHOLDS[19] = { 512440, // z0 256720, // z1 122560, // z2 @@ -39,22 +31,28 @@ static const std::array DOUGLAS_PEUCKER_THRESHOLDS{{ 20, // z15 8, // z16 6, // z17 - 4 // z18 -}}; - -class DouglasPeucker -{ - public: - using RandomAccessIt = std::vector::iterator; - - using GeometryRange = std::pair; - // Stack to simulate the recursion - std::stack recursion_stack; - - public: - void Run(RandomAccessIt begin, RandomAccessIt end, const unsigned zoom_level); - void Run(std::vector &input_geometry, const unsigned zoom_level); + 4, // z18 }; + +const constexpr auto DOUGLAS_PEUCKER_THRESHOLDS_SIZE = + sizeof(DOUGLAS_PEUCKER_THRESHOLDS) / sizeof(*DOUGLAS_PEUCKER_THRESHOLDS); +} // ns detail + +// These functions compute the bitvector of indicating generalized input +// points according to the (Ramer-)Douglas-Peucker algorithm. +// +// Input is vector of pairs. Each pair consists of the point information and a +// bit indicating if the points is present in the generalization. +// Note: points may also be pre-selected*/ +void douglasPeucker(std::vector::iterator begin, + std::vector::iterator end, + const unsigned zoom_level); + +// Convenience range-based function +inline void douglasPeucker(std::vector &geometry, const unsigned zoom_level) +{ + douglasPeucker(begin(geometry), end(geometry), zoom_level); +} } } diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index 51a1695bd..e75ab41a0 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -272,14 +272,13 @@ void SegmentList::Finalize(const bool extract_alternative, if (allow_simplification) { - DouglasPeucker polyline_generalizer; - polyline_generalizer.Run(segments.begin(), segments.end(), zoom_level); + douglasPeucker(segments, zoom_level); } std::uint32_t necessary_segments = 0; // a running index that counts the necessary pieces via_indices.push_back(0); - const auto markNecessarySegments = [this, &necessary_segments](SegmentInformation &first, - const SegmentInformation &second) + const auto markNecessarySegments = + [this, &necessary_segments](SegmentInformation &first, const SegmentInformation &second) { if (!first.necessary) return; diff --git a/src/engine/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp index cced730b2..f9635d0ea 100644 --- a/src/engine/douglas_peucker.cpp +++ b/src/engine/douglas_peucker.cpp @@ -1,13 +1,13 @@ #include "engine/douglas_peucker.hpp" -#include "engine/segment_information.hpp" - #include #include "osrm/coordinate.hpp" #include #include #include +#include +#include namespace osrm { @@ -59,13 +59,15 @@ struct CoordinatePairCalculator }; } -void DouglasPeucker::Run(std::vector &input_geometry, const unsigned zoom_level) +void douglasPeucker(std::vector::iterator begin, + std::vector::iterator end, + const unsigned zoom_level) { - Run(std::begin(input_geometry), std::end(input_geometry), zoom_level); -} + using Iter = decltype(begin); + using GeometryRange = std::pair; + + std::stack recursion_stack; -void DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigned zoom_level) -{ const auto size = std::distance(begin, end); if (size < 2) { @@ -76,7 +78,8 @@ void DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigne std::prev(end)->necessary = true; { - BOOST_ASSERT_MSG(zoom_level < DOUGLAS_PEUCKER_THRESHOLDS.size(), "unsupported zoom level"); + BOOST_ASSERT_MSG(zoom_level < detail::DOUGLAS_PEUCKER_THRESHOLDS_SIZE, + "unsupported zoom level"); auto left_border = begin; auto right_border = std::next(begin); // Sweep over array and identify those ranges that need to be checked @@ -117,7 +120,8 @@ void DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigne { const int distance = dist_calc(it->location); // found new feasible maximum? - if (distance > max_int_distance && distance > DOUGLAS_PEUCKER_THRESHOLDS[zoom_level]) + if (distance > max_int_distance && + distance > detail::DOUGLAS_PEUCKER_THRESHOLDS[zoom_level]) { farthest_entry_it = it; max_int_distance = distance; @@ -125,7 +129,7 @@ void DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigne } // check if maximum violates a zoom level dependent threshold - if (max_int_distance > DOUGLAS_PEUCKER_THRESHOLDS[zoom_level]) + if (max_int_distance > detail::DOUGLAS_PEUCKER_THRESHOLDS[zoom_level]) { // mark idx as necessary farthest_entry_it->necessary = true; @@ -140,5 +144,5 @@ void DouglasPeucker::Run(RandomAccessIt begin, RandomAccessIt end, const unsigne } } } -} -} +} // ns engine +} // ns osrm diff --git a/unit_tests/engine/douglas_peucker.cpp b/unit_tests/engine/douglas_peucker.cpp index 4c165c1a6..ec25a88c6 100644 --- a/unit_tests/engine/douglas_peucker.cpp +++ b/unit_tests/engine/douglas_peucker.cpp @@ -8,7 +8,7 @@ #include -BOOST_AUTO_TEST_SUITE(douglas_peucker) +BOOST_AUTO_TEST_SUITE(douglas_peucker_simplification) using namespace osrm; using namespace osrm::engine; @@ -22,18 +22,20 @@ SegmentInformation getTestInfo(int lat, int lon, bool necessary) BOOST_AUTO_TEST_CASE(all_necessary_test) { /* - * x - * / \ - * x \ - * / \ - * x x - */ - std::vector info = {getTestInfo(5, 5, true), getTestInfo(6, 6, true), - getTestInfo(10, 10, true), getTestInfo(5, 15, true)}; - DouglasPeucker dp; - for (unsigned z = 0; z < DOUGLAS_PEUCKER_THRESHOLDS.size(); z++) + x + / \ + x \ + / \ + x x + / + */ + std::vector info = {getTestInfo(5, 5, true), + getTestInfo(6, 6, true), + getTestInfo(10, 10, true), + getTestInfo(5, 15, true)}; + for (unsigned z = 0; z < detail::DOUGLAS_PEUCKER_THRESHOLDS_SIZE; z++) { - dp.Run(info, z); + douglasPeucker(info, z); for (const auto &i : info) { BOOST_CHECK_EQUAL(i.necessary, true); @@ -43,29 +45,29 @@ BOOST_AUTO_TEST_CASE(all_necessary_test) BOOST_AUTO_TEST_CASE(remove_second_node_test) { - DouglasPeucker dp; - for (unsigned z = 0; z < DOUGLAS_PEUCKER_THRESHOLDS.size(); z++) + for (unsigned z = 0; z < detail::DOUGLAS_PEUCKER_THRESHOLDS_SIZE; z++) { /* - * x--x - * | \ - * x-x x - * | - * x - */ + x--x + | \ + x-x x + | + x + */ std::vector info = { getTestInfo(5 * COORDINATE_PRECISION, 5 * COORDINATE_PRECISION, true), getTestInfo(5 * COORDINATE_PRECISION, - 5 * COORDINATE_PRECISION + DOUGLAS_PEUCKER_THRESHOLDS[z], false), + 5 * COORDINATE_PRECISION + detail::DOUGLAS_PEUCKER_THRESHOLDS[z], false), getTestInfo(10 * COORDINATE_PRECISION, 10 * COORDINATE_PRECISION, false), getTestInfo(10 * COORDINATE_PRECISION, - 10 + COORDINATE_PRECISION + DOUGLAS_PEUCKER_THRESHOLDS[z] * 2, false), + 10 + COORDINATE_PRECISION + detail::DOUGLAS_PEUCKER_THRESHOLDS[z] * 2, + false), getTestInfo(5 * COORDINATE_PRECISION, 15 * COORDINATE_PRECISION, false), - getTestInfo(5 * COORDINATE_PRECISION + DOUGLAS_PEUCKER_THRESHOLDS[z], + getTestInfo(5 * COORDINATE_PRECISION + detail::DOUGLAS_PEUCKER_THRESHOLDS[z], 15 * COORDINATE_PRECISION, true), }; - BOOST_TEST_MESSAGE("Threshold (" << z << "): " << DOUGLAS_PEUCKER_THRESHOLDS[z]); - dp.Run(info, z); + BOOST_TEST_MESSAGE("Threshold (" << z << "): " << detail::DOUGLAS_PEUCKER_THRESHOLDS[z]); + douglasPeucker(info, z); BOOST_CHECK_EQUAL(info[0].necessary, true); BOOST_CHECK_EQUAL(info[1].necessary, false); BOOST_CHECK_EQUAL(info[2].necessary, true); From c65dd16460fe71626626f1b3afc2541f58544ff3 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 8 Jan 2016 13:00:24 +0100 Subject: [PATCH 054/701] Make PolylineCompresser's encode and decode free standing functions --- include/engine/polyline_compressor.hpp | 21 ++++------- src/engine/polyline_compressor.cpp | 52 +++++++++++++------------- src/engine/polyline_formatter.cpp | 4 +- src/engine/route_parameters.cpp | 6 ++- unit_tests/engine/geometry_string.cpp | 3 +- 5 files changed, 41 insertions(+), 45 deletions(-) diff --git a/include/engine/polyline_compressor.hpp b/include/engine/polyline_compressor.hpp index 9a7ba4d02..8f7b695bf 100644 --- a/include/engine/polyline_compressor.hpp +++ b/include/engine/polyline_compressor.hpp @@ -2,6 +2,7 @@ #define POLYLINECOMPRESSOR_H_ #include "osrm/coordinate.hpp" +#include "engine/segment_information.hpp" #include #include @@ -10,21 +11,13 @@ namespace osrm { namespace engine { +// Encodes geometry into polyline format. +// See: https://developers.google.com/maps/documentation/utilities/polylinealgorithm +std::string polylineEncode(const std::vector &geometry); -struct SegmentInformation; - -class PolylineCompressor -{ - private: - std::string encode_vector(std::vector &numbers) const; - - std::string encode_number(const int number_to_encode) const; - - public: - std::string get_encoded_string(const std::vector &polyline) const; - - std::vector decode_string(const std::string &geometry_string) const; -}; +// Decodes geometry from polyline format +// See: https://developers.google.com/maps/documentation/utilities/polylinealgorithm +std::vector polylineDecode(const std::string &polyline); } } diff --git a/src/engine/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp index 042653084..2af6735a3 100644 --- a/src/engine/polyline_compressor.cpp +++ b/src/engine/polyline_compressor.cpp @@ -1,33 +1,15 @@ #include "engine/polyline_compressor.hpp" -#include "engine/segment_information.hpp" -#include "osrm/coordinate.hpp" +#include namespace osrm { namespace engine { - -std::string PolylineCompressor::encode_vector(std::vector &numbers) const +namespace /*detail*/ // anonymous to keep TU local { - std::string output; - const auto end = numbers.size(); - for (std::size_t i = 0; i < end; ++i) - { - numbers[i] <<= 1; - if (numbers[i] < 0) - { - numbers[i] = ~(numbers[i]); - } - } - for (const int number : numbers) - { - output += encode_number(number); - } - return output; -} -std::string PolylineCompressor::encode_number(int number_to_encode) const +std::string encode(int number_to_encode) { std::string output; while (number_to_encode >= 0x20) @@ -42,8 +24,27 @@ std::string PolylineCompressor::encode_number(int number_to_encode) const return output; } -std::string -PolylineCompressor::get_encoded_string(const std::vector &polyline) const +std::string encode(std::vector &numbers) +{ + std::string output; + const auto end = numbers.size(); + for (std::size_t i = 0; i < end; ++i) + { + numbers[i] <<= 1; + if (numbers[i] < 0) + { + numbers[i] = ~(numbers[i]); + } + } + for (const int number : numbers) + { + output += encode(number); + } + return output; +} +} // anonymous ns + +std::string polylineEncode(const std::vector &polyline) { if (polyline.empty()) { @@ -64,11 +65,10 @@ PolylineCompressor::get_encoded_string(const std::vector &po previous_coordinate = segment.location; } } - return encode_vector(delta_numbers); + return encode(delta_numbers); } -std::vector -PolylineCompressor::decode_string(const std::string &geometry_string) const +std::vector polylineDecode(const std::string &geometry_string) { std::vector new_coordinates; int index = 0, len = geometry_string.size(); diff --git a/src/engine/polyline_formatter.cpp b/src/engine/polyline_formatter.cpp index 0b22ddb24..617ef7977 100644 --- a/src/engine/polyline_formatter.cpp +++ b/src/engine/polyline_formatter.cpp @@ -5,6 +5,8 @@ #include "osrm/coordinate.hpp" +#include + namespace osrm { namespace engine @@ -13,7 +15,7 @@ namespace engine util::json::String PolylineFormatter::printEncodedString(const std::vector &polyline) const { - return util::json::String(PolylineCompressor().get_encoded_string(polyline)); + return util::json::String(polylineEncode(polyline)); } util::json::Array diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index 6565896f3..bbcf40def 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -7,6 +7,9 @@ #include "engine/polyline_compressor.hpp" +#include +#include + namespace osrm { namespace engine @@ -153,8 +156,7 @@ void RouteParameters::AddSource(const boost::fusion::vector &rec void RouteParameters::SetCoordinatesFromGeometry(const std::string &geometry_string) { - PolylineCompressor pc; - coordinates = pc.decode_string(geometry_string); + coordinates = polylineDecode(geometry_string); } } } diff --git a/unit_tests/engine/geometry_string.cpp b/unit_tests/engine/geometry_string.cpp index 182cabda8..235df9b6b 100644 --- a/unit_tests/engine/geometry_string.cpp +++ b/unit_tests/engine/geometry_string.cpp @@ -18,8 +18,7 @@ BOOST_AUTO_TEST_CASE(decode) { // Polyline string for the 5 coordinates const std::string polyline = "_gjaR_gjaR_pR_ibE_pR_ibE_pR_ibE_pR_ibE"; - PolylineCompressor pc; - std::vector coords = pc.decode_string(polyline); + const auto coords = polylineDecode(polyline); // Test coordinates; these would be the coordinates we give the loc parameter, // e.g. loc=10.00,10.0&loc=10.01,10.1... From 0627c3443d553e420357357656215a59ff710ec5 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 8 Jan 2016 13:15:09 +0100 Subject: [PATCH 055/701] Make PolylineFormatter's encodedAsJSON and unencodedAsJSON free standing functions --- include/engine/api_response_generator.hpp | 4 ++-- include/engine/polyline_formatter.hpp | 13 ++++++------- src/engine/polyline_formatter.cpp | 11 ++--------- 3 files changed, 10 insertions(+), 18 deletions(-) diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index 747a3639b..5cde1f30c 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -243,9 +243,9 @@ util::json::Value ApiResponseGenerator::GetGeometry(const bool retu const Segments &segments) const { if (return_encoded) - return PolylineFormatter().printEncodedString(segments.Get()); + return polylineEncodeAsJSON(segments.Get()); else - return PolylineFormatter().printUnencodedString(segments.Get()); + return polylineUnencodedAsJSON(segments.Get()); } template diff --git a/include/engine/polyline_formatter.hpp b/include/engine/polyline_formatter.hpp index b2c5afe24..434d792fe 100644 --- a/include/engine/polyline_formatter.hpp +++ b/include/engine/polyline_formatter.hpp @@ -1,6 +1,7 @@ #ifndef POLYLINE_FORMATTER_HPP #define POLYLINE_FORMATTER_HPP +#include "engine/segment_information.hpp" #include "osrm/json_container.hpp" #include @@ -11,14 +12,12 @@ namespace osrm namespace engine { -struct SegmentInformation; +// Encodes geometry into polyline format, returning an encoded JSON object +// See: https://developers.google.com/maps/documentation/utilities/polylinealgorithm +util::json::String polylineEncodeAsJSON(const std::vector &geometry); -struct PolylineFormatter -{ - util::json::String printEncodedString(const std::vector &polyline) const; - - util::json::Array printUnencodedString(const std::vector &polyline) const; -}; +// Does not encode the geometry in polyline format, instead returning an unencoded JSON object +util::json::Array polylineUnencodedAsJSON(const std::vector &geometry); } } diff --git a/src/engine/polyline_formatter.cpp b/src/engine/polyline_formatter.cpp index 617ef7977..5039e2375 100644 --- a/src/engine/polyline_formatter.cpp +++ b/src/engine/polyline_formatter.cpp @@ -1,25 +1,18 @@ #include "engine/polyline_formatter.hpp" - #include "engine/polyline_compressor.hpp" -#include "engine/segment_information.hpp" - #include "osrm/coordinate.hpp" -#include - namespace osrm { namespace engine { -util::json::String -PolylineFormatter::printEncodedString(const std::vector &polyline) const +util::json::String polylineEncodeAsJSON(const std::vector &polyline) { return util::json::String(polylineEncode(polyline)); } -util::json::Array -PolylineFormatter::printUnencodedString(const std::vector &polyline) const +util::json::Array polylineUnencodedAsJSON(const std::vector &polyline) { util::json::Array json_geometry_array; for (const auto &segment : polyline) From 03f64a6c2057ceab5d0ed70ce19db7bb652b4f8b Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 8 Jan 2016 15:35:17 +0100 Subject: [PATCH 056/701] Make RouteNameExtraction a free standing function --- include/engine/api_response_generator.hpp | 6 +- include/engine/route_name_extraction.hpp | 224 +++++++++++----------- 2 files changed, 116 insertions(+), 114 deletions(-) diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index 5cde1f30c..3b8945b8e 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -48,7 +48,6 @@ template class ApiResponseGenerator using DataFacade = DataFacadeT; using Segments = guidance::SegmentList; using Segment = detail::Segment; - using RouteNameExtractor = ExtractRouteNames; ApiResponseGenerator(DataFacade *facade); @@ -120,7 +119,6 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con } RouteNames route_names; - RouteNameExtractor generate_route_names; if (raw_route.has_alternative()) { @@ -156,7 +154,7 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con // generate names for both the main path and the alternative route auto path_segments = BuildRouteSegments(segment_list); auto alternate_segments = BuildRouteSegments(alternate_segment_list); - route_names = generate_route_names(path_segments, alternate_segments, facade); + route_names = extractRouteNames(path_segments, alternate_segments, facade); util::json::Array json_alternate_names_array; util::json::Array json_alternate_names; @@ -172,7 +170,7 @@ void ApiResponseGenerator::DescribeRoute(const RouteParameters &con // generate names for the main route on its own auto path_segments = BuildRouteSegments(segment_list); std::vector alternate_segments; - route_names = generate_route_names(path_segments, alternate_segments, facade); + route_names = extractRouteNames(path_segments, alternate_segments, facade); } util::json::Array json_route_names; diff --git a/include/engine/route_name_extraction.hpp b/include/engine/route_name_extraction.hpp index e9070b486..7fd598ca8 100644 --- a/include/engine/route_name_extraction.hpp +++ b/include/engine/route_name_extraction.hpp @@ -5,6 +5,7 @@ #include #include +#include #include namespace osrm @@ -20,125 +21,128 @@ struct RouteNames std::string alternative_path_name_2; }; -// construct routes names -template struct ExtractRouteNames +namespace detail { - private: - SegmentT PickNextLongestSegment(const std::vector &segment_list, - const unsigned blocked_name_id) const - { - SegmentT result_segment; - result_segment.name_id = blocked_name_id; // make sure we get a valid name - result_segment.length = 0; - for (const SegmentT &segment : segment_list) +template +SegmentT pickNextLongestSegment(const std::vector &segment_list, + const unsigned blocked_name_id) +{ + SegmentT result_segment; + result_segment.name_id = blocked_name_id; // make sure we get a valid name + result_segment.length = 0; + + for (const SegmentT &segment : segment_list) + { + if (segment.name_id != blocked_name_id && segment.length > result_segment.length && + segment.name_id != 0) { - if (segment.name_id != blocked_name_id && segment.length > result_segment.length && - segment.name_id != 0) - { - result_segment = segment; - } + result_segment = segment; } - return result_segment; } + return result_segment; +} - public: - RouteNames operator()(std::vector &shortest_path_segments, - std::vector &alternative_path_segments, - const DataFacadeT *facade) const +} // ns detail + +template +RouteNames extractRouteNames(std::vector &shortest_path_segments, + std::vector &alternative_path_segments, + const DataFacadeT *facade) +{ + RouteNames route_names; + + if (shortest_path_segments.empty()) { - RouteNames route_names; - - SegmentT shortest_segment_1, shortest_segment_2; - SegmentT alternative_segment_1, alternative_segment_2; - - auto length_comperator = [](const SegmentT &a, const SegmentT &b) - { - return a.length > b.length; - }; - auto name_id_comperator = [](const SegmentT &a, const SegmentT &b) - { - return a.name_id < b.name_id; - }; - - if (shortest_path_segments.empty()) - { - return route_names; - } - - // pick the longest segment for the shortest path. - std::sort(shortest_path_segments.begin(), shortest_path_segments.end(), length_comperator); - shortest_segment_1 = shortest_path_segments[0]; - if (!alternative_path_segments.empty()) - { - std::sort(alternative_path_segments.begin(), alternative_path_segments.end(), - length_comperator); - - // also pick the longest segment for the alternative path - alternative_segment_1 = alternative_path_segments[0]; - } - - // compute the set difference (for shortest path) depending on names between shortest and - // alternative - std::vector shortest_path_set_difference(shortest_path_segments.size()); - std::sort(shortest_path_segments.begin(), shortest_path_segments.end(), name_id_comperator); - std::sort(alternative_path_segments.begin(), alternative_path_segments.end(), - name_id_comperator); - std::set_difference(shortest_path_segments.begin(), shortest_path_segments.end(), - alternative_path_segments.begin(), alternative_path_segments.end(), - shortest_path_set_difference.begin(), name_id_comperator); - - std::sort(shortest_path_set_difference.begin(), shortest_path_set_difference.end(), - length_comperator); - shortest_segment_2 = - PickNextLongestSegment(shortest_path_set_difference, shortest_segment_1.name_id); - - // compute the set difference (for alternative path) depending on names between shortest and - // alternative - // vectors are still sorted, no need to do again - BOOST_ASSERT(std::is_sorted(shortest_path_segments.begin(), shortest_path_segments.end(), - name_id_comperator)); - BOOST_ASSERT(std::is_sorted(alternative_path_segments.begin(), - alternative_path_segments.end(), name_id_comperator)); - - std::vector alternative_path_set_difference(alternative_path_segments.size()); - std::set_difference(alternative_path_segments.begin(), alternative_path_segments.end(), - shortest_path_segments.begin(), shortest_path_segments.end(), - alternative_path_set_difference.begin(), name_id_comperator); - - std::sort(alternative_path_set_difference.begin(), alternative_path_set_difference.end(), - length_comperator); - - if (!alternative_path_segments.empty()) - { - alternative_segment_2 = PickNextLongestSegment(alternative_path_set_difference, - alternative_segment_1.name_id); - } - - // move the segments into the order in which they occur. - if (shortest_segment_1.position > shortest_segment_2.position) - { - std::swap(shortest_segment_1, shortest_segment_2); - } - if (alternative_segment_1.position > alternative_segment_2.position) - { - std::swap(alternative_segment_1, alternative_segment_2); - } - - // fetching names for the selected segments - route_names.shortest_path_name_1 = facade->get_name_for_id(shortest_segment_1.name_id); - route_names.shortest_path_name_2 = facade->get_name_for_id(shortest_segment_2.name_id); - - if (!alternative_path_segments.empty()) - { - route_names.alternative_path_name_1 = - facade->get_name_for_id(alternative_segment_1.name_id); - route_names.alternative_path_name_2 = - facade->get_name_for_id(alternative_segment_2.name_id); - } return route_names; } -}; + + SegmentT shortest_segment_1, shortest_segment_2; + SegmentT alternative_segment_1, alternative_segment_2; + + const auto length_comperator = [](const SegmentT &a, const SegmentT &b) + { + return a.length > b.length; + }; + const auto name_id_comperator = [](const SegmentT &a, const SegmentT &b) + { + return a.name_id < b.name_id; + }; + + // pick the longest segment for the shortest path. + std::sort(shortest_path_segments.begin(), shortest_path_segments.end(), length_comperator); + shortest_segment_1 = shortest_path_segments[0]; + + if (!alternative_path_segments.empty()) + { + std::sort(alternative_path_segments.begin(), alternative_path_segments.end(), + length_comperator); + + // also pick the longest segment for the alternative path + alternative_segment_1 = alternative_path_segments[0]; + } + + // compute the set difference (for shortest path) depending on names between shortest and + // alternative + std::vector shortest_path_set_difference(shortest_path_segments.size()); + std::sort(shortest_path_segments.begin(), shortest_path_segments.end(), name_id_comperator); + std::sort(alternative_path_segments.begin(), alternative_path_segments.end(), + name_id_comperator); + std::set_difference(shortest_path_segments.begin(), shortest_path_segments.end(), + alternative_path_segments.begin(), alternative_path_segments.end(), + shortest_path_set_difference.begin(), name_id_comperator); + + std::sort(shortest_path_set_difference.begin(), shortest_path_set_difference.end(), + length_comperator); + shortest_segment_2 = + pickNextLongestSegment(shortest_path_set_difference, shortest_segment_1.name_id); + + // compute the set difference (for alternative path) depending on names between shortest and + // alternative + // vectors are still sorted, no need to do again + BOOST_ASSERT(std::is_sorted(shortest_path_segments.begin(), shortest_path_segments.end(), + name_id_comperator)); + BOOST_ASSERT(std::is_sorted(alternative_path_segments.begin(), alternative_path_segments.end(), + name_id_comperator)); + + std::vector alternative_path_set_difference(alternative_path_segments.size()); + std::set_difference(alternative_path_segments.begin(), alternative_path_segments.end(), + shortest_path_segments.begin(), shortest_path_segments.end(), + alternative_path_set_difference.begin(), name_id_comperator); + + std::sort(alternative_path_set_difference.begin(), alternative_path_set_difference.end(), + length_comperator); + + if (!alternative_path_segments.empty()) + { + alternative_segment_2 = + pickNextLongestSegment(alternative_path_set_difference, alternative_segment_1.name_id); + } + + // move the segments into the order in which they occur. + if (shortest_segment_1.position > shortest_segment_2.position) + { + std::swap(shortest_segment_1, shortest_segment_2); + } + if (alternative_segment_1.position > alternative_segment_2.position) + { + std::swap(alternative_segment_1, alternative_segment_2); + } + + // fetching names for the selected segments + route_names.shortest_path_name_1 = facade->get_name_for_id(shortest_segment_1.name_id); + route_names.shortest_path_name_2 = facade->get_name_for_id(shortest_segment_2.name_id); + + if (!alternative_path_segments.empty()) + { + route_names.alternative_path_name_1 = + facade->get_name_for_id(alternative_segment_1.name_id); + route_names.alternative_path_name_2 = + facade->get_name_for_id(alternative_segment_2.name_id); + } + + return route_names; +} } } From f65dd632107b0abc5500e88818d320379bfe3095 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 8 Jan 2016 22:37:25 +0100 Subject: [PATCH 057/701] Make TurnInstructionsClass functions free standing functions --- include/engine/api_response_generator.hpp | 2 +- .../guidance/textual_route_annotation.hpp | 2 +- include/extractor/turn_instructions.hpp | 82 +++++++++---------- src/extractor/edge_based_graph_factory.cpp | 2 +- 4 files changed, 42 insertions(+), 46 deletions(-) diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index 3b8945b8e..cfdc5bdc1 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -254,7 +254,7 @@ ApiResponseGenerator::BuildRouteSegments(const Segments &segment_li for (const auto &segment : segment_list.Get()) { const auto current_turn = segment.turn_instruction; - if (extractor::TurnInstructionsClass::TurnIsNecessary(current_turn) && + if (extractor::isTurnNecessary(current_turn) && (extractor::TurnInstruction::EnterRoundAbout != current_turn)) { diff --git a/include/engine/guidance/textual_route_annotation.hpp b/include/engine/guidance/textual_route_annotation.hpp index da9a9d8bc..a66786724 100644 --- a/include/engine/guidance/textual_route_annotation.hpp +++ b/include/engine/guidance/textual_route_annotation.hpp @@ -47,7 +47,7 @@ inline util::json::Array AnnotateRoute(const std::vector &ro { util::json::Array json_instruction_row; extractor::TurnInstruction current_instruction = segment.turn_instruction; - if (extractor::TurnInstructionsClass::TurnIsNecessary(current_instruction)) + if (extractor::isTurnNecessary(current_instruction)) { if (extractor::TurnInstruction::EnterRoundAbout == current_instruction) { diff --git a/include/extractor/turn_instructions.hpp b/include/extractor/turn_instructions.hpp index f5f164f18..9a08c97da 100644 --- a/include/extractor/turn_instructions.hpp +++ b/include/extractor/turn_instructions.hpp @@ -31,54 +31,50 @@ enum class TurnInstruction : unsigned char AccessRestrictionPenalty = 129 }; -struct TurnInstructionsClass +// Translates between angles and their human-friendly directional representation +inline TurnInstruction getTurnDirection(const double angle) { - TurnInstructionsClass() = delete; - TurnInstructionsClass(const TurnInstructionsClass &) = delete; - - static inline TurnInstruction GetTurnDirectionOfInstruction(const double angle) + if (angle >= 23 && angle < 67) { - if (angle >= 23 && angle < 67) - { - return TurnInstruction::TurnSharpRight; - } - if (angle >= 67 && angle < 113) - { - return TurnInstruction::TurnRight; - } - if (angle >= 113 && angle < 158) - { - return TurnInstruction::TurnSlightRight; - } - if (angle >= 158 && angle < 202) - { - return TurnInstruction::GoStraight; - } - if (angle >= 202 && angle < 248) - { - return TurnInstruction::TurnSlightLeft; - } - if (angle >= 248 && angle < 292) - { - return TurnInstruction::TurnLeft; - } - if (angle >= 292 && angle < 336) - { - return TurnInstruction::TurnSharpLeft; - } - return TurnInstruction::UTurn; + return TurnInstruction::TurnSharpRight; } - - static inline bool TurnIsNecessary(const TurnInstruction turn_instruction) + if (angle >= 67 && angle < 113) { - if (TurnInstruction::NoTurn == turn_instruction || - TurnInstruction::StayOnRoundAbout == turn_instruction) - { - return false; - } - return true; + return TurnInstruction::TurnRight; } -}; + if (angle >= 113 && angle < 158) + { + return TurnInstruction::TurnSlightRight; + } + if (angle >= 158 && angle < 202) + { + return TurnInstruction::GoStraight; + } + if (angle >= 202 && angle < 248) + { + return TurnInstruction::TurnSlightLeft; + } + if (angle >= 248 && angle < 292) + { + return TurnInstruction::TurnLeft; + } + if (angle >= 292 && angle < 336) + { + return TurnInstruction::TurnSharpLeft; + } + return TurnInstruction::UTurn; +} + +// Decides if a turn is needed to be done for the current instruction +inline bool isTurnNecessary(const TurnInstruction turn_instruction) +{ + if (TurnInstruction::NoTurn == turn_instruction || + TurnInstruction::StayOnRoundAbout == turn_instruction) + { + return false; + } + return true; +} } } diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 6c2bedcc1..b26f34fc8 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -683,7 +683,7 @@ TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID node_u, } } - return TurnInstructionsClass::GetTurnDirectionOfInstruction(angle); + return getTurnDirection(angle); } } } From f68247673aaf075c7570e1ecff53390ac960cb4b Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 8 Jan 2016 23:08:32 +0100 Subject: [PATCH 058/701] Make ComputeAngle a free standing function --- include/engine/plugins/match.hpp | 6 ++-- include/util/compute_angle.hpp | 33 +++++++++++++++------ src/extractor/edge_based_graph_factory.cpp | 2 +- src/util/compute_angle.cpp | 34 ---------------------- 4 files changed, 28 insertions(+), 47 deletions(-) delete mode 100644 src/util/compute_angle.cpp diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 3dded7b99..bc831cbc3 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -107,9 +107,9 @@ template class MapMatchingPlugin : public BasePlugin if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate) { - double turn_angle = util::ComputeAngle::OfThreeFixedPointCoordinates( - input_coords[current_coordinate - 1], input_coords[current_coordinate], - input_coords[current_coordinate + 1]); + double turn_angle = util::ComputeAngle(input_coords[current_coordinate - 1], + input_coords[current_coordinate], + input_coords[current_coordinate + 1]); // sharp turns indicate a possible uturn if (turn_angle <= 90.0 || turn_angle >= 270.0) diff --git a/include/util/compute_angle.hpp b/include/util/compute_angle.hpp index 2662ed99e..02313e912 100644 --- a/include/util/compute_angle.hpp +++ b/include/util/compute_angle.hpp @@ -1,21 +1,36 @@ #ifndef COMPUTE_ANGLE_HPP #define COMPUTE_ANGLE_HPP +#include "osrm/coordinate.hpp" +#include "util/trigonometry_table.hpp" +#include "util/mercator.hpp" + namespace osrm { namespace util { -struct FixedPointCoordinate; - -struct ComputeAngle +// Get angle of line segment (A,C)->(C,B) +inline double ComputeAngle(const FixedPointCoordinate first, + const FixedPointCoordinate second, + const FixedPointCoordinate third) noexcept { - // Get angle of line segment (A,C)->(C,B) - // atan2 magic, formerly cosine theorem - static double OfThreeFixedPointCoordinates(const FixedPointCoordinate &first, - const FixedPointCoordinate &second, - const FixedPointCoordinate &third) noexcept; -}; + const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION; + const double v1y = mercator::lat2y(first.lat / COORDINATE_PRECISION) - + mercator::lat2y(second.lat / COORDINATE_PRECISION); + const double v2x = (third.lon - second.lon) / COORDINATE_PRECISION; + const double v2y = mercator::lat2y(third.lat / COORDINATE_PRECISION) - + mercator::lat2y(second.lat / COORDINATE_PRECISION); + + double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / M_PI; + + while (angle < 0.) + { + angle += 360.; + } + + return angle; +} } } diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index b26f34fc8..38fc76990 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -468,7 +468,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( ? m_compressed_edge_container.GetFirstEdgeTargetID(e2) : node_w)]; - const double turn_angle = util::ComputeAngle::OfThreeFixedPointCoordinates( + const double turn_angle = util::ComputeAngle( first_coordinate, m_node_info_list[node_v], third_coordinate); const int turn_penalty = GetTurnPenalty(turn_angle, lua_state); diff --git a/src/util/compute_angle.cpp b/src/util/compute_angle.cpp deleted file mode 100644 index ebc2f0f2e..000000000 --- a/src/util/compute_angle.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "util/compute_angle.hpp" - -#include "util/trigonometry_table.hpp" -#include "util/mercator.hpp" - -#include "osrm/coordinate.hpp" - -#include - -namespace osrm -{ -namespace util -{ - -double ComputeAngle::OfThreeFixedPointCoordinates(const FixedPointCoordinate &first, - const FixedPointCoordinate &second, - const FixedPointCoordinate &third) noexcept -{ - const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION; - const double v1y = mercator::lat2y(first.lat / COORDINATE_PRECISION) - - mercator::lat2y(second.lat / COORDINATE_PRECISION); - const double v2x = (third.lon - second.lon) / COORDINATE_PRECISION; - const double v2y = mercator::lat2y(third.lat / COORDINATE_PRECISION) - - mercator::lat2y(second.lat / COORDINATE_PRECISION); - - double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / M_PI; - while (angle < 0.) - { - angle += 360.; - } - return angle; -} -} -} From 05658aeb3b12490aabfffab40ed12ade54441a79 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 11 Jan 2016 20:05:34 +0100 Subject: [PATCH 059/701] Ignore .swp file --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 21608e35b..c94aeb428 100644 --- a/.gitignore +++ b/.gitignore @@ -78,3 +78,5 @@ stxxl.errlog # Deprecated config file # ########################## /server.ini + +*.swp From f875e26fbf1c19222f5bfc84259d168bb1b3cd14 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 11 Jan 2016 14:06:49 +0100 Subject: [PATCH 060/701] Inline mercator transformations; no need for separate translation unit --- include/util/compute_angle.hpp | 8 ++++---- include/util/mercator.hpp | 18 +++++++++++++----- include/util/static_rtree.hpp | 4 ++-- src/util/coordinate_calculation.cpp | 8 ++++---- src/util/mercator.cpp | 10 ---------- 5 files changed, 23 insertions(+), 25 deletions(-) diff --git a/include/util/compute_angle.hpp b/include/util/compute_angle.hpp index 02313e912..b34f7bed9 100644 --- a/include/util/compute_angle.hpp +++ b/include/util/compute_angle.hpp @@ -16,11 +16,11 @@ inline double ComputeAngle(const FixedPointCoordinate first, const FixedPointCoordinate third) noexcept { const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION; - const double v1y = mercator::lat2y(first.lat / COORDINATE_PRECISION) - - mercator::lat2y(second.lat / COORDINATE_PRECISION); + const double v1y = mercator::latToY(first.lat / COORDINATE_PRECISION) - + mercator::latToY(second.lat / COORDINATE_PRECISION); const double v2x = (third.lon - second.lon) / COORDINATE_PRECISION; - const double v2y = mercator::lat2y(third.lat / COORDINATE_PRECISION) - - mercator::lat2y(second.lat / COORDINATE_PRECISION); + const double v2y = mercator::latToY(third.lat / COORDINATE_PRECISION) - + mercator::latToY(second.lat / COORDINATE_PRECISION); double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / M_PI; diff --git a/include/util/mercator.hpp b/include/util/mercator.hpp index eda28a96c..fa22c9db0 100644 --- a/include/util/mercator.hpp +++ b/include/util/mercator.hpp @@ -1,17 +1,25 @@ #ifndef MERCATOR_HPP #define MERCATOR_HPP +#include + namespace osrm { namespace util { - -struct mercator +namespace mercator { - static double y2lat(const double value) noexcept; - static double lat2y(const double latitude) noexcept; -}; +inline double yToLat(const double value) noexcept +{ + return 180. * M_1_PI * (2. * std::atan(std::exp(value * M_PI / 180.)) - M_PI_2); +} + +inline double latToY(const double latitude) noexcept +{ + return 180. * M_1_PI * std::log(std::tan(M_PI_4 + latitude * (M_PI / 180.) / 2.)); +} +} } } diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 0b244f167..3a415e3b6 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -144,7 +144,7 @@ class StaticRTree coordinate_list.at(current_element.v).lon)); current_centroid.lat = COORDINATE_PRECISION * - mercator::lat2y(current_centroid.lat / COORDINATE_PRECISION); + mercator::latToY(current_centroid.lat / COORDINATE_PRECISION); current_wrapper.m_hilbert_value = get_hilbert_number(current_centroid); } @@ -345,7 +345,7 @@ class StaticRTree { std::vector results; std::pair projected_coordinate = { - mercator::lat2y(input_coordinate.lat / COORDINATE_PRECISION), + mercator::latToY(input_coordinate.lat / COORDINATE_PRECISION), input_coordinate.lon / COORDINATE_PRECISION}; // initialize queue with root element diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index 05190123f..1fcc9cf87 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -102,7 +102,7 @@ double perpendicularDistance(const FixedPointCoordinate &segment_source, { return perpendicularDistanceFromProjectedCoordinate( segment_source, segment_target, query_location, - {mercator::lat2y(query_location.lat / COORDINATE_PRECISION), + {mercator::latToY(query_location.lat / COORDINATE_PRECISION), query_location.lon / COORDINATE_PRECISION}, nearest_location, ratio); } @@ -134,9 +134,9 @@ perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment // initialize values const double x = projected_coordinate.first; const double y = projected_coordinate.second; - const double a = mercator::lat2y(segment_source.lat / COORDINATE_PRECISION); + const double a = mercator::latToY(segment_source.lat / COORDINATE_PRECISION); const double b = segment_source.lon / COORDINATE_PRECISION; - const double c = mercator::lat2y(segment_target.lat / COORDINATE_PRECISION); + const double c = mercator::latToY(segment_target.lat / COORDINATE_PRECISION); const double d = segment_target.lon / COORDINATE_PRECISION; double p, q /*,mX*/, new_y; if (std::abs(a - c) > std::numeric_limits::epsilon()) @@ -190,7 +190,7 @@ perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment else { // point lies in between - nearest_location.lat = static_cast(mercator::y2lat(p) * COORDINATE_PRECISION); + nearest_location.lat = static_cast(mercator::yToLat(p) * COORDINATE_PRECISION); nearest_location.lon = static_cast(q * COORDINATE_PRECISION); } BOOST_ASSERT(nearest_location.IsValid()); diff --git a/src/util/mercator.cpp b/src/util/mercator.cpp index ab9637172..19c5e1d42 100644 --- a/src/util/mercator.cpp +++ b/src/util/mercator.cpp @@ -6,15 +6,5 @@ namespace osrm { namespace util { - -double mercator::y2lat(const double value) noexcept -{ - return 180. * M_1_PI * (2. * std::atan(std::exp(value * M_PI / 180.)) - M_PI_2); -} - -double mercator::lat2y(const double latitude) noexcept -{ - return 180. * M_1_PI * std::log(std::tan(M_PI_4 + latitude * (M_PI / 180.) / 2.)); -} } } From fc292cc2d804f2a64386268e425ee525a697848c Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 11 Jan 2016 16:29:20 +0100 Subject: [PATCH 061/701] No need for extra translation units (for edge data structures) --- CMakeLists.txt | 2 +- include/extractor/import_edge.hpp | 96 ++++++++++++++++++++++++------- src/extractor/import_edge.cpp | 93 ------------------------------ 3 files changed, 75 insertions(+), 116 deletions(-) delete mode 100644 src/extractor/import_edge.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5ea4fa687..6a1cf4e87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -67,7 +67,7 @@ add_library(EXTRACTOR OBJECT ${ExtractorGlob}) add_library(CONTRACTOR OBJECT ${ContractorGlob}) add_library(ENGINE OBJECT ${EngineGlob}) add_library(SERVER OBJECT ${ServerGlob}) -add_library(GRAPH OBJECT src/extractor/external_memory_node.cpp src/extractor/import_edge.cpp) +add_library(GRAPH OBJECT src/extractor/external_memory_node.cpp) add_library(PHANTOM OBJECT src/engine/phantom_node.cpp) add_dependencies(UTIL FingerPrintConfigure) diff --git a/include/extractor/import_edge.hpp b/include/extractor/import_edge.hpp index fc43e2a23..48729a375 100644 --- a/include/extractor/import_edge.hpp +++ b/include/extractor/import_edge.hpp @@ -11,20 +11,46 @@ namespace extractor struct NodeBasedEdge { - bool operator<(const NodeBasedEdge &e) const; + bool operator<(const NodeBasedEdge &other) const + { + if (source == other.source) + { + if (target == other.target) + { + if (weight == other.weight) + { + return forward && backward && ((!other.forward) || (!other.backward)); + } + return weight < other.weight; + } + return target < other.target; + } + return source < other.source; + } - NodeBasedEdge(); - explicit NodeBasedEdge(NodeID source, - NodeID target, - NodeID name_id, - EdgeWeight weight, - bool forward, - bool backward, - bool roundabout, - bool access_restricted, - bool startpoint, - TravelMode travel_mode, - bool is_split); + NodeBasedEdge() + : source(SPECIAL_NODEID), target(SPECIAL_NODEID), name_id(0), weight(0), forward(false), + backward(false), roundabout(false), access_restricted(false), startpoint(true), + is_split(false), travel_mode(false) + { + } + + NodeBasedEdge(NodeID source, + NodeID target, + NodeID name_id, + EdgeWeight weight, + bool forward, + bool backward, + bool roundabout, + bool access_restricted, + bool startpoint, + TravelMode travel_mode, + bool is_split) + : source(source), target(target), name_id(name_id), weight(weight), forward(forward), + backward(backward), roundabout(roundabout), access_restricted(access_restricted), + startpoint(startpoint), is_split(is_split), travel_mode(travel_mode) + { + } NodeID source; NodeID target; @@ -75,18 +101,44 @@ struct EdgeBasedEdge { public: - bool operator<(const EdgeBasedEdge &e) const; + bool operator<(const EdgeBasedEdge &other) const + { + if (source == other.source) + { + if (target == other.target) + { + if (weight == other.weight) + { + return forward && backward && ((!other.forward) || (!other.backward)); + } + return weight < other.weight; + } + return target < other.target; + } + return source < other.source; + } + template + explicit EdgeBasedEdge(const EdgeT &other) + : source(other.source), target(other.target), edge_id(other.data.via), + weight(other.data.distance), forward(other.data.forward), backward(other.data.backward) + { + } - template explicit EdgeBasedEdge(const EdgeT &myEdge); + EdgeBasedEdge() : source(0), target(0), edge_id(0), weight(0), forward(false), backward(false) + { + } - EdgeBasedEdge(); + EdgeBasedEdge(const NodeID source, + const NodeID target, + const NodeID edge_id, + const EdgeWeight weight, + const bool forward, + const bool backward) + : source(source), target(target), edge_id(edge_id), weight(weight), forward(forward), + backward(backward) + { + } - explicit EdgeBasedEdge(const NodeID source, - const NodeID target, - const NodeID edge_id, - const EdgeWeight weight, - const bool forward, - const bool backward); NodeID source; NodeID target; NodeID edge_id; diff --git a/src/extractor/import_edge.cpp b/src/extractor/import_edge.cpp deleted file mode 100644 index b3b6b612d..000000000 --- a/src/extractor/import_edge.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include "extractor/import_edge.hpp" - -#include "extractor/travel_mode.hpp" -#include "util/typedefs.hpp" - -namespace osrm -{ -namespace extractor -{ - -bool NodeBasedEdge::operator<(const NodeBasedEdge &other) const -{ - if (source == other.source) - { - if (target == other.target) - { - if (weight == other.weight) - { - return forward && backward && ((!other.forward) || (!other.backward)); - } - return weight < other.weight; - } - return target < other.target; - } - return source < other.source; -} - -NodeBasedEdge::NodeBasedEdge() - : source(SPECIAL_NODEID), target(SPECIAL_NODEID), name_id(0), weight(0), forward(false), - backward(false), roundabout(false), access_restricted(false), startpoint(true), - is_split(false), travel_mode(false) -{ -} - -NodeBasedEdge::NodeBasedEdge(NodeID source, - NodeID target, - NodeID name_id, - EdgeWeight weight, - bool forward, - bool backward, - bool roundabout, - bool access_restricted, - bool startpoint, - TravelMode travel_mode, - bool is_split) - : source(source), target(target), name_id(name_id), weight(weight), forward(forward), - backward(backward), roundabout(roundabout), access_restricted(access_restricted), - startpoint(startpoint), is_split(is_split), travel_mode(travel_mode) -{ -} - -bool EdgeBasedEdge::operator<(const EdgeBasedEdge &other) const -{ - if (source == other.source) - { - if (target == other.target) - { - if (weight == other.weight) - { - return forward && backward && ((!other.forward) || (!other.backward)); - } - return weight < other.weight; - } - return target < other.target; - } - return source < other.source; -} - -template -EdgeBasedEdge::EdgeBasedEdge(const EdgeT &other) - : source(other.source), target(other.target), edge_id(other.data.via), - weight(other.data.distance), forward(other.data.forward), backward(other.data.backward) -{ -} - -/** Default constructor. target and weight are set to 0.*/ -EdgeBasedEdge::EdgeBasedEdge() - : source(0), target(0), edge_id(0), weight(0), forward(false), backward(false) -{ -} - -EdgeBasedEdge::EdgeBasedEdge(const NodeID source, - const NodeID target, - const NodeID edge_id, - const EdgeWeight weight, - const bool forward, - const bool backward) - : source(source), target(target), edge_id(edge_id), weight(weight), forward(forward), - backward(backward) -{ -} -} -} From 4813488f84169f6a00cd4aee89e49de8d3e2fb6c Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 11 Jan 2016 16:55:22 +0100 Subject: [PATCH 062/701] Split import_edge.hpp: node_based_edge.hpp, edge_based_edge.hpp closes #1604 --- include/contractor/processing_chain.hpp | 1 + include/extractor/edge_based_edge.hpp | 80 +++++++++ .../extractor/edge_based_graph_factory.hpp | 1 + include/extractor/extractor.hpp | 1 + include/extractor/import_edge.hpp | 152 ------------------ include/extractor/internal_extractor_edge.hpp | 2 +- include/extractor/node_based_edge.hpp | 133 +++++++++++++++ include/extractor/restriction_map.hpp | 1 + include/extractor/tarjan_scc.hpp | 2 +- include/util/graph_loader.hpp | 2 +- include/util/node_based_graph.hpp | 2 +- src/contractor/processing_chain.cpp | 2 +- src/extractor/edge_based_graph_factory.cpp | 1 + src/extractor/extractor.cpp | 1 + 14 files changed, 224 insertions(+), 157 deletions(-) create mode 100644 include/extractor/edge_based_edge.hpp delete mode 100644 include/extractor/import_edge.hpp create mode 100644 include/extractor/node_based_edge.hpp diff --git a/include/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp index 08247cf44..42034eb57 100644 --- a/include/contractor/processing_chain.hpp +++ b/include/contractor/processing_chain.hpp @@ -4,6 +4,7 @@ #include "contractor/contractor.hpp" #include "contractor/contractor_options.hpp" #include "contractor/query_edge.hpp" +#include "extractor/edge_based_edge.hpp" #include "util/static_graph.hpp" #include "util/deallocating_vector.hpp" #include "util/node_based_graph.hpp" diff --git a/include/extractor/edge_based_edge.hpp b/include/extractor/edge_based_edge.hpp new file mode 100644 index 000000000..e4e5ef3f3 --- /dev/null +++ b/include/extractor/edge_based_edge.hpp @@ -0,0 +1,80 @@ +#ifndef EDGE_BASED_EDGE_HPP +#define EDGE_BASED_EDGE_HPP + +#include "extractor/travel_mode.hpp" +#include "util/typedefs.hpp" + +namespace osrm +{ +namespace extractor +{ + +struct EdgeBasedEdge +{ + public: + EdgeBasedEdge(); + + template explicit EdgeBasedEdge(const EdgeT &other); + + EdgeBasedEdge(const NodeID source, + const NodeID target, + const NodeID edge_id, + const EdgeWeight weight, + const bool forward, + const bool backward); + + bool operator<(const EdgeBasedEdge &other) const; + + NodeID source; + NodeID target; + NodeID edge_id; + EdgeWeight weight : 30; + bool forward : 1; + bool backward : 1; +}; + +// Impl. + +inline EdgeBasedEdge::EdgeBasedEdge() + : source(0), target(0), edge_id(0), weight(0), forward(false), backward(false) +{ +} + +template +inline EdgeBasedEdge::EdgeBasedEdge(const EdgeT &other) + : source(other.source), target(other.target), edge_id(other.data.via), + weight(other.data.distance), forward(other.data.forward), backward(other.data.backward) +{ +} + +inline EdgeBasedEdge::EdgeBasedEdge(const NodeID source, + const NodeID target, + const NodeID edge_id, + const EdgeWeight weight, + const bool forward, + const bool backward) + : source(source), target(target), edge_id(edge_id), weight(weight), forward(forward), + backward(backward) +{ +} + +inline bool EdgeBasedEdge::operator<(const EdgeBasedEdge &other) const +{ + if (source == other.source) + { + if (target == other.target) + { + if (weight == other.weight) + { + return forward && backward && ((!other.forward) || (!other.backward)); + } + return weight < other.weight; + } + return target < other.target; + } + return source < other.source; +} +} // ns extractor +} // ns osrm + +#endif /* EDGE_BASED_EDGE_HPP */ diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 19a3d1ba8..94772a3dd 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -3,6 +3,7 @@ #ifndef EDGE_BASED_GRAPH_FACTORY_HPP_ #define EDGE_BASED_GRAPH_FACTORY_HPP_ +#include "extractor/edge_based_edge.hpp" #include "extractor/speed_profile.hpp" #include "util/typedefs.hpp" #include "extractor/compressed_edge_container.hpp" diff --git a/include/extractor/extractor.hpp b/include/extractor/extractor.hpp index c9faca9d5..68feaf624 100644 --- a/include/extractor/extractor.hpp +++ b/include/extractor/extractor.hpp @@ -1,6 +1,7 @@ #ifndef EXTRACTOR_HPP #define EXTRACTOR_HPP +#include "extractor/edge_based_edge.hpp" #include "extractor/extractor_options.hpp" #include "extractor/edge_based_graph_factory.hpp" #include "extractor/graph_compressor.hpp" diff --git a/include/extractor/import_edge.hpp b/include/extractor/import_edge.hpp deleted file mode 100644 index 48729a375..000000000 --- a/include/extractor/import_edge.hpp +++ /dev/null @@ -1,152 +0,0 @@ -#ifndef IMPORT_EDGE_HPP -#define IMPORT_EDGE_HPP - -#include "extractor/travel_mode.hpp" -#include "util/typedefs.hpp" - -namespace osrm -{ -namespace extractor -{ - -struct NodeBasedEdge -{ - bool operator<(const NodeBasedEdge &other) const - { - if (source == other.source) - { - if (target == other.target) - { - if (weight == other.weight) - { - return forward && backward && ((!other.forward) || (!other.backward)); - } - return weight < other.weight; - } - return target < other.target; - } - return source < other.source; - } - - NodeBasedEdge() - : source(SPECIAL_NODEID), target(SPECIAL_NODEID), name_id(0), weight(0), forward(false), - backward(false), roundabout(false), access_restricted(false), startpoint(true), - is_split(false), travel_mode(false) - { - } - - NodeBasedEdge(NodeID source, - NodeID target, - NodeID name_id, - EdgeWeight weight, - bool forward, - bool backward, - bool roundabout, - bool access_restricted, - bool startpoint, - TravelMode travel_mode, - bool is_split) - : source(source), target(target), name_id(name_id), weight(weight), forward(forward), - backward(backward), roundabout(roundabout), access_restricted(access_restricted), - startpoint(startpoint), is_split(is_split), travel_mode(travel_mode) - { - } - - NodeID source; - NodeID target; - NodeID name_id; - EdgeWeight weight; - bool forward : 1; - bool backward : 1; - bool roundabout : 1; - bool access_restricted : 1; - bool startpoint : 1; - bool is_split : 1; - TravelMode travel_mode : 4; -}; - -struct NodeBasedEdgeWithOSM : NodeBasedEdge -{ - explicit NodeBasedEdgeWithOSM(OSMNodeID source, - OSMNodeID target, - NodeID name_id, - EdgeWeight weight, - bool forward, - bool backward, - bool roundabout, - bool access_restricted, - bool startpoint, - TravelMode travel_mode, - bool is_split) - : NodeBasedEdge(SPECIAL_NODEID, - SPECIAL_NODEID, - name_id, - weight, - forward, - backward, - roundabout, - access_restricted, - startpoint, - travel_mode, - is_split), - osm_source_id(source), osm_target_id(target) - { - } - - OSMNodeID osm_source_id; - OSMNodeID osm_target_id; -}; - -struct EdgeBasedEdge -{ - - public: - bool operator<(const EdgeBasedEdge &other) const - { - if (source == other.source) - { - if (target == other.target) - { - if (weight == other.weight) - { - return forward && backward && ((!other.forward) || (!other.backward)); - } - return weight < other.weight; - } - return target < other.target; - } - return source < other.source; - } - template - explicit EdgeBasedEdge(const EdgeT &other) - : source(other.source), target(other.target), edge_id(other.data.via), - weight(other.data.distance), forward(other.data.forward), backward(other.data.backward) - { - } - - EdgeBasedEdge() : source(0), target(0), edge_id(0), weight(0), forward(false), backward(false) - { - } - - EdgeBasedEdge(const NodeID source, - const NodeID target, - const NodeID edge_id, - const EdgeWeight weight, - const bool forward, - const bool backward) - : source(source), target(target), edge_id(edge_id), weight(weight), forward(forward), - backward(backward) - { - } - - NodeID source; - NodeID target; - NodeID edge_id; - EdgeWeight weight : 30; - bool forward : 1; - bool backward : 1; -}; -} -} - -#endif /* IMPORT_EDGE_HPP */ diff --git a/include/extractor/internal_extractor_edge.hpp b/include/extractor/internal_extractor_edge.hpp index 8e4a133bc..a85a95d99 100644 --- a/include/extractor/internal_extractor_edge.hpp +++ b/include/extractor/internal_extractor_edge.hpp @@ -3,7 +3,7 @@ #include "util/typedefs.hpp" #include "extractor/travel_mode.hpp" -#include "extractor/import_edge.hpp" +#include "extractor/node_based_edge.hpp" #include diff --git a/include/extractor/node_based_edge.hpp b/include/extractor/node_based_edge.hpp new file mode 100644 index 000000000..434af6c1e --- /dev/null +++ b/include/extractor/node_based_edge.hpp @@ -0,0 +1,133 @@ +#ifndef NODE_BASED_EDGE_HPP +#define NODE_BASED_EDGE_HPP + +#include "extractor/travel_mode.hpp" +#include "util/typedefs.hpp" + +namespace osrm +{ +namespace extractor +{ + +struct NodeBasedEdge +{ + NodeBasedEdge(); + + NodeBasedEdge(NodeID source, + NodeID target, + NodeID name_id, + EdgeWeight weight, + bool forward, + bool backward, + bool roundabout, + bool access_restricted, + bool startpoint, + TravelMode travel_mode, + bool is_split); + + bool operator<(const NodeBasedEdge &other) const; + + NodeID source; + NodeID target; + NodeID name_id; + EdgeWeight weight; + bool forward : 1; + bool backward : 1; + bool roundabout : 1; + bool access_restricted : 1; + bool startpoint : 1; + bool is_split : 1; + TravelMode travel_mode : 4; +}; + +struct NodeBasedEdgeWithOSM : NodeBasedEdge +{ + NodeBasedEdgeWithOSM(OSMNodeID source, + OSMNodeID target, + NodeID name_id, + EdgeWeight weight, + bool forward, + bool backward, + bool roundabout, + bool access_restricted, + bool startpoint, + TravelMode travel_mode, + bool is_split); + + OSMNodeID osm_source_id; + OSMNodeID osm_target_id; +}; + +// Impl. + +inline NodeBasedEdge::NodeBasedEdge() + : source(SPECIAL_NODEID), target(SPECIAL_NODEID), name_id(0), weight(0), forward(false), + backward(false), roundabout(false), access_restricted(false), startpoint(true), + is_split(false), travel_mode(false) +{ +} + +inline NodeBasedEdge::NodeBasedEdge(NodeID source, + NodeID target, + NodeID name_id, + EdgeWeight weight, + bool forward, + bool backward, + bool roundabout, + bool access_restricted, + bool startpoint, + TravelMode travel_mode, + bool is_split) + : source(source), target(target), name_id(name_id), weight(weight), forward(forward), + backward(backward), roundabout(roundabout), access_restricted(access_restricted), + startpoint(startpoint), is_split(is_split), travel_mode(travel_mode) +{ +} + +inline bool NodeBasedEdge::operator<(const NodeBasedEdge &other) const +{ + if (source == other.source) + { + if (target == other.target) + { + if (weight == other.weight) + { + return forward && backward && ((!other.forward) || (!other.backward)); + } + return weight < other.weight; + } + return target < other.target; + } + return source < other.source; +} + +inline NodeBasedEdgeWithOSM::NodeBasedEdgeWithOSM(OSMNodeID source, + OSMNodeID target, + NodeID name_id, + EdgeWeight weight, + bool forward, + bool backward, + bool roundabout, + bool access_restricted, + bool startpoint, + TravelMode travel_mode, + bool is_split) + : NodeBasedEdge(SPECIAL_NODEID, + SPECIAL_NODEID, + name_id, + weight, + forward, + backward, + roundabout, + access_restricted, + startpoint, + travel_mode, + is_split), + osm_source_id(source), osm_target_id(target) +{ +} + +} // ns extractor +} // ns osrm + +#endif /* NODE_BASED_EDGE_HPP */ diff --git a/include/extractor/restriction_map.hpp b/include/extractor/restriction_map.hpp index 5b9a35fb4..23b3ac886 100644 --- a/include/extractor/restriction_map.hpp +++ b/include/extractor/restriction_map.hpp @@ -1,6 +1,7 @@ #ifndef RESTRICTION_MAP_HPP #define RESTRICTION_MAP_HPP +#include "extractor/edge_based_edge.hpp" #include "extractor/restriction.hpp" #include "util/std_hash.hpp" #include "util/typedefs.hpp" diff --git a/include/extractor/tarjan_scc.hpp b/include/extractor/tarjan_scc.hpp index c49f00fb7..874d3f677 100644 --- a/include/extractor/tarjan_scc.hpp +++ b/include/extractor/tarjan_scc.hpp @@ -3,7 +3,7 @@ #include "util/typedefs.hpp" #include "util/deallocating_vector.hpp" -#include "extractor/import_edge.hpp" +#include "extractor/node_based_edge.hpp" #include "extractor/query_node.hpp" #include "util/percent.hpp" diff --git a/include/util/graph_loader.hpp b/include/util/graph_loader.hpp index b4d3f4f5e..91a7f7e77 100644 --- a/include/util/graph_loader.hpp +++ b/include/util/graph_loader.hpp @@ -5,7 +5,7 @@ #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" #include "extractor/external_memory_node.hpp" -#include "extractor/import_edge.hpp" +#include "extractor/node_based_edge.hpp" #include "extractor/query_node.hpp" #include "extractor/restriction.hpp" #include "util/typedefs.hpp" diff --git a/include/util/node_based_graph.hpp b/include/util/node_based_graph.hpp index c1aa0323d..fcfad9e4d 100644 --- a/include/util/node_based_graph.hpp +++ b/include/util/node_based_graph.hpp @@ -2,7 +2,7 @@ #define NODE_BASED_GRAPH_HPP #include "util/dynamic_graph.hpp" -#include "extractor/import_edge.hpp" +#include "extractor/node_based_edge.hpp" #include "util/graph_utils.hpp" #include diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index f563de45b..30402bfa2 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -1,7 +1,7 @@ #include "contractor/processing_chain.hpp" #include "contractor/contractor.hpp" -#include "contractor/contractor.hpp" +#include "extractor/edge_based_edge.hpp" #include "util/deallocating_vector.hpp" diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 38fc76990..6b60a193e 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -1,3 +1,4 @@ +#include "extractor/edge_based_edge.hpp" #include "extractor/edge_based_graph_factory.hpp" #include "util/coordinate_calculation.hpp" #include "util/percent.hpp" diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 693576877..ddf787c35 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -1,5 +1,6 @@ #include "extractor/extractor.hpp" +#include "extractor/edge_based_edge.hpp" #include "extractor/extraction_containers.hpp" #include "extractor/extraction_node.hpp" #include "extractor/extraction_way.hpp" From c93ca02fb81c4dc0888dfee39f921236a6369c9b Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 11 Jan 2016 18:05:24 +0100 Subject: [PATCH 063/701] Rips out dead code from the container.hpp and creates for_each_pai.hpp I added two TODOs that I would like to address in the future. --- include/contractor/contractor_options.hpp | 2 +- include/engine/guidance/segment_list.hpp | 2 +- include/engine/plugins/viaroute.hpp | 1 + .../routing_algorithms/alternative_path.hpp | 15 ++-- include/extractor/extractor_options.hpp | 2 +- include/util/container.hpp | 73 +------------------ include/util/for_each_pair.hpp | 45 ++++++++++++ include/util/json_util.hpp | 2 + src/extractor/extractor_callbacks.cpp | 2 +- 9 files changed, 63 insertions(+), 81 deletions(-) create mode 100644 include/util/for_each_pair.hpp diff --git a/include/contractor/contractor_options.hpp b/include/contractor/contractor_options.hpp index 589f6bc13..04316e925 100644 --- a/include/contractor/contractor_options.hpp +++ b/include/contractor/contractor_options.hpp @@ -19,7 +19,7 @@ enum class return_code : unsigned struct ContractorConfig { - ContractorConfig() noexcept : requested_num_threads(0) {} + ContractorConfig() : requested_num_threads(0) {} boost::filesystem::path config_file_path; boost::filesystem::path osrm_input_path; diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index e75ab41a0..488f15812 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -9,7 +9,7 @@ #include "engine/segment_information.hpp" #include "util/integer_range.hpp" #include "util/coordinate_calculation.hpp" -#include "util/container.hpp" +#include "util/for_each_pair.hpp" #include "extractor/turn_instructions.hpp" #include diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index b2790a6c3..fd18a72e9 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -6,6 +6,7 @@ #include "engine/api_response_generator.hpp" #include "engine/object_encoder.hpp" #include "engine/search_engine.hpp" +#include "util/for_each_pair.hpp" #include "util/integer_range.hpp" #include "util/json_renderer.hpp" #include "util/make_unique.hpp" diff --git a/include/engine/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp index 91634813f..70d08b870 100644 --- a/include/engine/routing_algorithms/alternative_path.hpp +++ b/include/engine/routing_algorithms/alternative_path.hpp @@ -4,10 +4,11 @@ #include "engine/routing_algorithms/routing_base.hpp" #include "engine/search_engine_data.hpp" #include "util/integer_range.hpp" -#include "util/container.hpp" #include +#include +#include #include #include @@ -148,7 +149,9 @@ class AlternativeRouting final return; } - util::sort_unique_resize(via_node_candidate_list); + std::sort(begin(via_node_candidate_list), end(via_node_candidate_list)); + auto unique_end = std::unique(begin(via_node_candidate_list), end(via_node_candidate_list)); + via_node_candidate_list.resize(unique_end - begin(via_node_candidate_list)); std::vector packed_forward_path; std::vector packed_reverse_path; @@ -439,10 +442,10 @@ class AlternativeRouting final partially_unpacked_shortest_path.size())) - 1; for (int64_t current_node = 0; (current_node < packed_path_length) && - (partially_unpacked_via_path[current_node] == - partially_unpacked_shortest_path[current_node] && - partially_unpacked_via_path[current_node + 1] == - partially_unpacked_shortest_path[current_node + 1]); + (partially_unpacked_via_path[current_node] == + partially_unpacked_shortest_path[current_node] && + partially_unpacked_via_path[current_node + 1] == + partially_unpacked_shortest_path[current_node + 1]); ++current_node) { EdgeID selected_edge = diff --git a/include/extractor/extractor_options.hpp b/include/extractor/extractor_options.hpp index 2fbe3c894..287d62f06 100644 --- a/include/extractor/extractor_options.hpp +++ b/include/extractor/extractor_options.hpp @@ -19,7 +19,7 @@ enum class return_code : unsigned struct ExtractorConfig { - ExtractorConfig() noexcept : requested_num_threads(0) {} + ExtractorConfig() : requested_num_threads(0) {} boost::filesystem::path config_file_path; boost::filesystem::path input_path; boost::filesystem::path profile_path; diff --git a/include/util/container.hpp b/include/util/container.hpp index e901af90d..bd85e9c9c 100644 --- a/include/util/container.hpp +++ b/include/util/container.hpp @@ -1,79 +1,11 @@ #ifndef CONTAINER_HPP #define CONTAINER_HPP -#include -#include -#include - namespace osrm { namespace util { -namespace detail -{ -// Culled by SFINAE if reserve does not exist or is not accessible -template -constexpr auto has_resize_method(T &t) noexcept -> decltype(t.resize(0), bool()) -{ - return true; -} - -// Used as fallback when SFINAE culls the template method -constexpr bool has_resize_method(...) noexcept { return false; } -} - -template void sort_unique_resize(Container &vector) noexcept -{ - std::sort(std::begin(vector), std::end(vector)); - const auto number_of_unique_elements = - std::unique(std::begin(vector), std::end(vector)) - std::begin(vector); - if (detail::has_resize_method(vector)) - { - vector.resize(number_of_unique_elements); - } -} - -// template inline void sort_unique_resize_shrink_vector(std::vector &vector) -// { -// sort_unique_resize(vector); -// vector.shrink_to_fit(); -// } - -// template inline void remove_consecutive_duplicates_from_vector(std::vector -// &vector) -// { -// const auto number_of_unique_elements = std::unique(vector.begin(), vector.end()) - -// vector.begin(); -// vector.resize(number_of_unique_elements); -// } - -template -Function for_each_pair(ForwardIterator begin, ForwardIterator end, Function function) -{ - if (begin == end) - { - return function; - } - - auto next = begin; - next = std::next(next); - - while (next != end) - { - function(*begin, *next); - begin = std::next(begin); - next = std::next(next); - } - return function; -} - -template -Function for_each_pair(ContainerT &container, Function function) -{ - return for_each_pair(std::begin(container), std::end(container), function); -} - template void append_to_container(Container &&) {} template @@ -82,8 +14,7 @@ void append_to_container(Container &&container, T value, Args &&... args) container.emplace_back(value); append_to_container(std::forward(container), std::forward(args)...); } - -} // namespace osrm +} } -#endif /* CONTAINER_HPP */ +#endif diff --git a/include/util/for_each_pair.hpp b/include/util/for_each_pair.hpp new file mode 100644 index 000000000..86fc75e28 --- /dev/null +++ b/include/util/for_each_pair.hpp @@ -0,0 +1,45 @@ +#ifndef FOR_EACH_PAIR_HPP +#define FOR_EACH_PAIR_HPP + +#include +#include + +namespace osrm +{ +namespace util +{ + +// TODO: check why this is not an option here: +// std::adjacent_find(begin, end, [=](const auto& l, const auto& r){ return function(), false; }); +template +Function for_each_pair(ForwardIterator begin, ForwardIterator end, Function function) +{ + if (begin == end) + { + return function; + } + + auto next = begin; + next = std::next(next); + + while (next != end) + { + function(*begin, *next); + begin = std::next(begin); + next = std::next(next); + } + return function; +} + +template +Function for_each_pair(ContainerT &container, Function function) +{ + using std::begin; + using std::end; + return for_each_pair(begin(container), end(container), function); +} + +} // namespace util +} // namespace osrm + +#endif /* FOR_EACH_PAIR_HPP */ diff --git a/include/util/json_util.hpp b/include/util/json_util.hpp index d858f6b20..1d10471dd 100644 --- a/include/util/json_util.hpp +++ b/include/util/json_util.hpp @@ -2,6 +2,7 @@ #define JSON_UTIL_HPP #include "osrm/json_container.hpp" +#include "util/container.hpp" #include #include @@ -31,6 +32,7 @@ template T clamp_float(T d) template Array make_array(Args... args) { Array a; + // TODO: check why a.values.emplace_back(args...); is not an option here append_to_container(a.values, args...); return a; } diff --git a/src/extractor/extractor_callbacks.cpp b/src/extractor/extractor_callbacks.cpp index 25cc24ead..9fd4b73dc 100644 --- a/src/extractor/extractor_callbacks.cpp +++ b/src/extractor/extractor_callbacks.cpp @@ -5,8 +5,8 @@ #include "extractor/external_memory_node.hpp" #include "extractor/restriction.hpp" -#include "util/container.hpp" #include "util/simple_logger.hpp" +#include "util/for_each_pair.hpp" #include From f46706843b87bd67328f575933ac0fc926bb9a76 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 12 Jan 2016 13:40:36 +0100 Subject: [PATCH 064/701] STXXL's debug build creates stxxl_debug.{a,so}, adapts FindSTXXL References: - https://github.com/Project-OSRM/osrm-backend/issues/1885 --- cmake/FindSTXXL.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/FindSTXXL.cmake b/cmake/FindSTXXL.cmake index 76a2722b0..473fb6a29 100644 --- a/cmake/FindSTXXL.cmake +++ b/cmake/FindSTXXL.cmake @@ -24,7 +24,7 @@ FIND_PATH(STXXL_INCLUDE_DIR stxxl.h ) FIND_LIBRARY(STXXL_LIBRARY - NAMES stxxl + NAMES stxxl stxxl_debug HINTS $ENV{STXXL_DIR} PATH_SUFFIXES lib64 lib From 466251287f4bd5d9c8b24d7e6e838a829f4a0d27 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 12 Jan 2016 15:41:30 +0100 Subject: [PATCH 065/701] Define compile-time constants for coordinate calculation only once Closes #1327. --- include/util/coordinate_calculation.hpp | 5 +++++ src/engine/douglas_peucker.cpp | 20 +++++++++----------- src/util/coordinate_calculation.cpp | 13 ++----------- 3 files changed, 16 insertions(+), 22 deletions(-) diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index 1507d14f0..7e15b8ba0 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -9,6 +9,11 @@ namespace osrm namespace util { +const constexpr long double RAD = 0.017453292519943295769236907684886; +// earth radius varies between 6,356.750-6,378.135 km (3,949.901-3,963.189mi) +// The IUGG value for the equatorial radius is 6378.137 km (3963.19 miles) +const constexpr long double EARTH_RADIUS = 6372797.560856; + struct FixedPointCoordinate; namespace coordinate_calculation diff --git a/src/engine/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp index f9635d0ea..67760bc1c 100644 --- a/src/engine/douglas_peucker.cpp +++ b/src/engine/douglas_peucker.cpp @@ -1,4 +1,5 @@ #include "engine/douglas_peucker.hpp" +#include "util/coordinate_calculation.hpp" #include #include "osrm/coordinate.hpp" @@ -23,30 +24,27 @@ struct CoordinatePairCalculator const util::FixedPointCoordinate &coordinate_b) { // initialize distance calculator with two fixed coordinates a, b - const float RAD = 0.017453292519943295769236907684886f; - first_lat = (coordinate_a.lat / COORDINATE_PRECISION) * RAD; - first_lon = (coordinate_a.lon / COORDINATE_PRECISION) * RAD; - second_lat = (coordinate_b.lat / COORDINATE_PRECISION) * RAD; - second_lon = (coordinate_b.lon / COORDINATE_PRECISION) * RAD; + first_lat = (coordinate_a.lat / COORDINATE_PRECISION) * util::RAD; + first_lon = (coordinate_a.lon / COORDINATE_PRECISION) * util::RAD; + second_lat = (coordinate_b.lat / COORDINATE_PRECISION) * util::RAD; + second_lon = (coordinate_b.lon / COORDINATE_PRECISION) * util::RAD; } int operator()(util::FixedPointCoordinate &other) const { // set third coordinate c - const float RAD = 0.017453292519943295769236907684886f; - const float earth_radius = 6372797.560856f; - const float float_lat1 = (other.lat / COORDINATE_PRECISION) * RAD; - const float float_lon1 = (other.lon / COORDINATE_PRECISION) * RAD; + const float float_lat1 = (other.lat / COORDINATE_PRECISION) * util::RAD; + const float float_lon1 = (other.lon / COORDINATE_PRECISION) * util::RAD; // compute distance (a,c) const float x_value_1 = (first_lon - float_lon1) * cos((float_lat1 + first_lat) / 2.f); const float y_value_1 = first_lat - float_lat1; - const float dist1 = std::hypot(x_value_1, y_value_1) * earth_radius; + const float dist1 = std::hypot(x_value_1, y_value_1) * util::EARTH_RADIUS; // compute distance (b,c) const float x_value_2 = (second_lon - float_lon1) * cos((float_lat1 + second_lat) / 2.f); const float y_value_2 = second_lat - float_lat1; - const float dist2 = std::hypot(x_value_2, y_value_2) * earth_radius; + const float dist2 = std::hypot(x_value_2, y_value_2) * util::EARTH_RADIUS; // return the minimum return static_cast(std::min(dist1, dist2)); diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index 1fcc9cf87..4f1386310 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -15,15 +15,6 @@ namespace osrm { namespace util { - -namespace -{ -constexpr static const double RAD = 0.017453292519943295769236907684886; -// earth radius varies between 6,356.750-6,378.135 km (3,949.901-3,963.189mi) -// The IUGG value for the equatorial radius is 6378.137 km (3963.19 miles) -constexpr static const double earth_radius = 6372797.560856; -} - namespace coordinate_calculation { @@ -49,7 +40,7 @@ double haversineDistance(const int lat1, const int lon1, const int lat2, const i const double aharv = std::pow(std::sin(dlat / 2.0), 2.0) + std::cos(dlat1) * std::cos(dlat2) * std::pow(std::sin(dlong / 2.), 2); const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv)); - return earth_radius * charv; + return EARTH_RADIUS * charv; } double haversineDistance(const FixedPointCoordinate &coordinate_1, @@ -80,7 +71,7 @@ double greatCircleDistance(const int lat1, const int lon1, const int lat2, const const double x_value = (float_lon2 - float_lon1) * std::cos((float_lat1 + float_lat2) / 2.0); const double y_value = float_lat2 - float_lat1; - return std::hypot(x_value, y_value) * earth_radius; + return std::hypot(x_value, y_value) * EARTH_RADIUS; } double perpendicularDistance(const FixedPointCoordinate &source_coordinate, From 37276371453f208369067bc1f4bb9e4045bc3bbe Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 11 Jan 2016 12:03:01 +0100 Subject: [PATCH 066/701] Build osmium_convert in order to be able to eventually replace osmosis This provides a script to build the libosmium examples such as osmium_convert (to convert from xml to pbf). I initially tried a CMake ExternalProject setup, but this was more complicated than I initially thought; this is the more elegant solution. The goal is to eventually rip out osmosis, so that we no longer depend on java for the cucumber tests. References: - https://github.com/Project-OSRM/osrm-backend/issues/1788 --- .gitignore | 1 + scripts/build_osmium_tools.sh | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100755 scripts/build_osmium_tools.sh diff --git a/.gitignore b/.gitignore index c94aeb428..e6a125f9e 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ Thumbs.db ####################### /build/ /cmake/postinst +/third_party/libosmium/tmp/ # Eclipse related files # ######################### diff --git a/scripts/build_osmium_tools.sh b/scripts/build_osmium_tools.sh new file mode 100755 index 000000000..81777ec39 --- /dev/null +++ b/scripts/build_osmium_tools.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +# Builds command line tools shipped with libosmium for example osmium_convert +# CMake build directory is build/osmium; binaries are located under build/osmium/examples + + +# e: exit on first error, x: print commands +set -ex + +BUILD_DIR=build/osmium + +cmake -E remove_directory $BUILD_DIR +cmake -E make_directory $BUILD_DIR +cmake -E chdir $BUILD_DIR cmake ../../third_party/libosmium -DCMAKE_BUILD_TYPE=Release -DBUILD_EXAMPLES=1 -DBUILD_TESTING=0 +cmake -E chdir $BUILD_DIR cmake --build . From 43dcdb21ec191b4c60795daec1101e94ec9ca1d2 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 13 Jan 2016 14:34:36 +0100 Subject: [PATCH 067/701] Revert "Build osmium_convert in order to be able to eventually replace osmosis" This reverts commit 344588114dd5076385b35e0fbaef966de681f95f. --- .gitignore | 1 - scripts/build_osmium_tools.sh | 15 --------------- 2 files changed, 16 deletions(-) delete mode 100755 scripts/build_osmium_tools.sh diff --git a/.gitignore b/.gitignore index e6a125f9e..c94aeb428 100644 --- a/.gitignore +++ b/.gitignore @@ -41,7 +41,6 @@ Thumbs.db ####################### /build/ /cmake/postinst -/third_party/libosmium/tmp/ # Eclipse related files # ######################### diff --git a/scripts/build_osmium_tools.sh b/scripts/build_osmium_tools.sh deleted file mode 100755 index 81777ec39..000000000 --- a/scripts/build_osmium_tools.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash - -# Builds command line tools shipped with libosmium for example osmium_convert -# CMake build directory is build/osmium; binaries are located under build/osmium/examples - - -# e: exit on first error, x: print commands -set -ex - -BUILD_DIR=build/osmium - -cmake -E remove_directory $BUILD_DIR -cmake -E make_directory $BUILD_DIR -cmake -E chdir $BUILD_DIR cmake ../../third_party/libosmium -DCMAKE_BUILD_TYPE=Release -DBUILD_EXAMPLES=1 -DBUILD_TESTING=0 -cmake -E chdir $BUILD_DIR cmake --build . From 9959fd26bb6e7c4ef05ffcc308c897c8ad4b8682 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 13 Jan 2016 14:41:55 +0100 Subject: [PATCH 068/701] Do not convert osm xml files to pbf for the cucumber tests --- features/support/data.rb | 18 +----------------- features/support/exceptions.rb | 6 ------ 2 files changed, 1 insertion(+), 23 deletions(-) diff --git a/features/support/data.rb b/features/support/data.rb index 62ed7d370..eabd934bd 100644 --- a/features/support/data.rb +++ b/features/support/data.rb @@ -229,17 +229,6 @@ def write_osm end end -def convert_osm_to_pbf - unless File.exist?("#{osm_file}.osm.pbf") - log_preprocess_info - log "== Converting #{osm_file}.osm to protobuffer format...", :preprocess - unless system "osmosis --read-xml #{osm_file}.osm --write-pbf #{osm_file}.osm.pbf omitmetadata=true >>#{PREPROCESS_LOG_FILE} 2>&1" - raise OsmosisError.new $?, "osmosis exited with code #{$?.exitstatus}" - end - log '', :preprocess - end -end - def extracted? Dir.chdir TEST_FOLDER do File.exist?("#{extracted_file}.osrm") && @@ -258,15 +247,10 @@ def write_timestamp File.open( "#{prepared_file}.osrm.timestamp", 'w') {|f| f.write(OSM_TIMESTAMP) } end -def pbf? - input_format=='pbf' -end - def write_input_data Dir.chdir TEST_FOLDER do write_osm write_timestamp - convert_osm_to_pbf if pbf? end end @@ -274,7 +258,7 @@ def extract_data Dir.chdir TEST_FOLDER do log_preprocess_info log "== Extracting #{osm_file}.osm...", :preprocess - unless system "#{BIN_PATH}/osrm-extract #{osm_file}.osm#{'.pbf' if pbf?} #{@extract_args} --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" + unless system "#{BIN_PATH}/osrm-extract #{osm_file}.osm #{@extract_args} --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" log "*** Exited with code #{$?.exitstatus}.", :preprocess raise ExtractError.new $?.exitstatus, "osrm-extract exited with code #{$?.exitstatus}." end diff --git a/features/support/exceptions.rb b/features/support/exceptions.rb index 02f59d388..d04dc385c 100644 --- a/features/support/exceptions.rb +++ b/features/support/exceptions.rb @@ -37,12 +37,6 @@ class FileError < OSRMError end end -class OsmosisError < OSRMError - def initialize code, msg - super 'osmosis', code, msg, PREPROCESS_LOG_FILE, 40 - end -end - class ExtractError < OSRMError def initialize code, msg super 'osrm-extract', code, msg, PREPROCESS_LOG_FILE, 3 From 03faf2665bcedc5514422f587041965d9a9cca2d Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 13 Jan 2016 14:43:14 +0100 Subject: [PATCH 069/701] No longer install osmosis on travis --- .travis.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 5d8e5fa8a..d5a186008 100644 --- a/.travis.yml +++ b/.travis.yml @@ -117,12 +117,8 @@ install: mkdir cmake && travis_retry wget --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake export PATH=${DEPS_DIR}/cmake/bin:${PATH} - OSMOSIS_URL="http://bretth.dev.openstreetmap.org/osmosis-build/osmosis-latest.tgz" - mkdir osmosis && travis_retry wget --quiet -O - ${OSMOSIS_URL} | tar -xz -C osmosis - export PATH=${DEPS_DIR}/osmosis/bin:${PATH} - elif [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then - brew install cmake boost libzip libstxxl libxml2 lua51 luabind tbb GDAL osmosis + brew install cmake boost libzip libstxxl libxml2 lua51 luabind tbb GDAL fi before_script: From 7c8626d1448ef28bdd62568304a33a202e1c7eae Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 13 Jan 2016 14:44:29 +0100 Subject: [PATCH 070/701] No longer install osmosis in docker env --- docker/Dockerfile | 2 -- 1 file changed, 2 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index 4535949a1..aa37682f5 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -12,8 +12,6 @@ RUN pip install awscli # luabind RUN curl https://gist.githubusercontent.com/DennisOSRM/f2eb7b948e6fe1ae319e/raw/install-luabind.sh | sudo bash -# osmosis -RUN curl -s https://gist.githubusercontent.com/DennisOSRM/803a64a9178ec375069f/raw/ | sudo bash RUN useradd -ms /bin/bash mapbox USER mapbox From 1157cb9b9514f1cba47ccf974df8a5ab4051b669 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Wed, 13 Jan 2016 17:57:03 +0100 Subject: [PATCH 071/701] Remove obsolete protobuf test --- features/testbot/protobuffer.feature | 156 --------------------------- 1 file changed, 156 deletions(-) delete mode 100644 features/testbot/protobuffer.feature diff --git a/features/testbot/protobuffer.feature b/features/testbot/protobuffer.feature deleted file mode 100644 index e32de26c2..000000000 --- a/features/testbot/protobuffer.feature +++ /dev/null @@ -1,156 +0,0 @@ -@routing @pbf @testbot -Feature: Importing protobuffer (.pbf) format -# Test normally read .osm, which is faster than .pbf files, -# since we don't need to use osmosis to first convert to .pbf -# The scenarios in this file test the ability to import .pbf files, -# including nodes, way, restictions, and a various special situations. - - Background: - Given the profile "testbot" - And the import format "pbf" - - Scenario: Testbot - Protobuffer import, nodes and ways - Given the node map - | | | | d | - | a | b | c | | - | | | | e | - - And the ways - | nodes | highway | oneway | - | abc | primary | | - | cd | primary | yes | - | ce | river | | - | de | primary | | - - When I route I should get - | from | to | route | - | d | c | de,ce | - | e | d | de | - - - Scenario: Testbot - Protobuffer import, turn restiction relations - Given the node map - | | n | | - | w | j | e | - | | s | | - - And the ways - | nodes | oneway | - | sj | yes | - | nj | -1 | - | wj | -1 | - | ej | -1 | - - And the relations - | type | way:from | way:to | node:via | restriction | - | restriction | sj | wj | j | no_left_turn | - - When I route I should get - | from | to | route | - | s | w | | - | s | n | sj,nj | - | s | e | sj,ej | - - - Scenario: Testbot - Protobuffer import, distances at longitude 45 - Given the node locations - | node | lat | lon | - | a | 80 | 45 | - | b | 0 | 45 | - - And the ways - | nodes | - | ab | - - When I route I should get - | from | to | route | distance | - | a | b | ab | 8905559m ~0.1% | - - Scenario: Testbot - Protobuffer import, distances at longitude 80 - Given the node locations - | node | lat | lon | - | a | 80 | 80 | - | b | 0 | 80 | - - And the ways - | nodes | - | ab | - - When I route I should get - | from | to | route | distance | - | a | b | ab | 8905559m ~0.1% | - - Scenario: Testbot - Protobuffer import, empty dataset - Given the node map - | | - - Given the ways - | nodes | - - When the data has been prepared - Then "osrm-extract" should return code 1 - - - Scenario: Testbot - Protobuffer import, streetnames with UTF characters - Given the node map - | a | b | c | d | - - And the ways - | nodes | name | - | ab | Scandinavian København | - | bc | Japanese 東京 | - | cd | Cyrillic Москва | - - When I route I should get - | from | to | route | - | a | b | Scandinavian København | - | b | c | Japanese 東京 | - | c | d | Cyrillic Москва | - - Scenario: Testbot - Protobuffer import, bearing af 45 degree intervals - Given the node map - | b | a | h | - | c | x | g | - | d | e | f | - - And the ways - | nodes | - | xa | - | xb | - | xc | - | xd | - | xe | - | xf | - | xg | - | xh | - - When I route I should get - | from | to | route | compass | bearing | - | x | a | xa | N | 0 | - | x | b | xb | NW | 315 | - | x | c | xc | W | 270 | - | x | d | xd | SW | 225 | - | x | e | xe | S | 180 | - | x | f | xf | SE | 135 | - | x | g | xg | E | 90 | - | x | h | xh | NE | 45 | - - - Scenario: Testbot - Protobuffer import, rraffic signals should incur a delay - Given the node map - | a | b | c | - | d | e | f | - - And the nodes - | node | highway | - | e | traffic_signals | - - And the ways - | nodes | - | abc | - | def | - - When I route I should get - | from | to | route | time | distance | - | a | c | abc | 20s +-1 | 200m +-1 | - | d | f | def | 27s +-1 | 200m +-1 | From 328faf37445b43b868ae42356c98bb7acf15ea35 Mon Sep 17 00:00:00 2001 From: Mathias Gug Date: Wed, 13 Jan 2016 11:53:59 -0800 Subject: [PATCH 072/701] Fix debian package upgrades. The postinst script fails on package upgrade given that the symlink already exists. Note that symlinks should *not* be handled in a postinst scripts. Instead dh_links should be used so that symlinks are compliant with the Debian policy. --- cmake/CPackDebianConfig.cmake | 3 +-- cmake/postinst.in | 2 -- 2 files changed, 1 insertion(+), 4 deletions(-) delete mode 100644 cmake/postinst.in diff --git a/cmake/CPackDebianConfig.cmake b/cmake/CPackDebianConfig.cmake index 84b80a6bc..13216dd2f 100644 --- a/cmake/CPackDebianConfig.cmake +++ b/cmake/CPackDebianConfig.cmake @@ -36,7 +36,6 @@ SET(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6-dev, libbz2-1.0, libstxxl1, libxml2, file(GLOB_RECURSE ProfileGlob ${CMAKE_SOURCE_DIR}/profiles/*) install(FILES ${ProfileGlob} DESTINATION "share/doc/${LOWER_PROJECT_NAME}/profiles") -CONFIGURE_FILE (${CMAKE_SOURCE_DIR}/cmake/postinst.in postinst) -set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_CURRENT_BINARY_DIR}/postinst;${CMAKE_CURRENT_BINARY_DIR}/copyright;") +set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_CURRENT_BINARY_DIR}/copyright;") MESSAGE(STATUS "Debian Package: ${CPACK_DEBIAN_PACKAGE_NAME} (${CPACK_DEBIAN_PACKAGE_VERSION}) [${CPACK_PACKAGE_FILE_NAME}.deb]") diff --git a/cmake/postinst.in b/cmake/postinst.in deleted file mode 100644 index 92f2fde4f..000000000 --- a/cmake/postinst.in +++ /dev/null @@ -1,2 +0,0 @@ -#/usr/bin/env bash -ln -s /usr/share/doc/@CMAKE_PROJECT_NAME@/profiles/car.lua @CMAKE_INSTALL_PREFIX@/profile.lua From e7d9e42a16ec25154adcb4e64a6428d2e764659a Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 13 Jan 2016 18:36:11 +0100 Subject: [PATCH 073/701] Fix race condition in osrm-routed HTTP server We had a similar issue a few month ago. Stumbled upon this by accident. It goes like this: - `output_buffer` is function-local - we pass it to async_write and leave the scope - `output_buffers` goes out of scope - bad things happen, sometimes The fix is to, again, put it inside the connection that handles itself via the enable_shared_from_this idiom. References: - http://www.boost.org/doc/libs/1_59_0/doc/html/boost_asio/reference/async_write/overload1.html - https://github.com/Project-OSRM/osrm-backend/pull/1690 --- include/server/connection.hpp | 2 ++ src/server/connection.cpp | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/include/server/connection.hpp b/include/server/connection.hpp index 8421c03c2..ace005392 100644 --- a/include/server/connection.hpp +++ b/include/server/connection.hpp @@ -63,6 +63,8 @@ class Connection : public std::enable_shared_from_this http::request current_request; http::reply current_reply; std::vector compressed_output; + // Header compression_header; + std::vector output_buffer; }; } } diff --git a/src/server/connection.cpp b/src/server/connection.cpp index 58718a050..0f4b59750 100644 --- a/src/server/connection.cpp +++ b/src/server/connection.cpp @@ -52,9 +52,6 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t current_request.endpoint = TCP_socket.remote_endpoint().address(); request_handler.handle_request(current_request, current_reply); - // Header compression_header; - std::vector output_buffer; - // compress the result w/ gzip/deflate if requested switch (compression_type) { From 6b15f29d7cb242f81da9238bff2ccafa4d7d0170 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 14 Jan 2016 18:27:36 +0100 Subject: [PATCH 074/701] Fix handling unexpected errors. --- include/engine/plugins/viaroute.hpp | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index fd18a72e9..49768df10 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -137,14 +137,15 @@ template class ViaRoutePlugin final : public BasePlugin route_parameters.uturns, raw_route); } - bool no_route = INVALID_EDGE_WEIGHT == raw_route.shortest_path_length; - - auto generator = MakeApiResponseGenerator(facade); - generator.DescribeRoute(route_parameters, raw_route, json_result); - // we can only know this after the fact, different SCC ids still // allow for connection in one direction. - if (no_route) + if (raw_route.is_valid()) + { + auto generator = MakeApiResponseGenerator(facade); + generator.DescribeRoute(route_parameters, raw_route, json_result); + json_result.values["status_message"] = "Found route between points"; + } + else { auto first_component_id = snapped_phantoms.front().component.id; auto not_in_same_component = @@ -153,15 +154,17 @@ template class ViaRoutePlugin final : public BasePlugin { return node.component.id != first_component_id; }); + if (not_in_same_component) { json_result.values["status_message"] = "Impossible route between points"; return Status::EmptyResult; } - } - else - { - json_result.values["status_message"] = "Found route between points"; + else + { + json_result.values["status_message"] = "No route found between points"; + return Status::Error; + } } return Status::Ok; From 490e838c608b9543f093bd0753d066f2d3e63a90 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Fri, 15 Jan 2016 00:39:49 +0100 Subject: [PATCH 075/701] Add regression test for Disney Land bug --- features/testbot/via.feature | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/features/testbot/via.feature b/features/testbot/via.feature index 4a7c96328..5c7e03837 100644 --- a/features/testbot/via.feature +++ b/features/testbot/via.feature @@ -117,3 +117,22 @@ Feature: Via points | 1,2,3 | ab,ab | 200m +-1 | head,via,destination | | 1,3,2 | ab,ab,bc,cd,da,ab | 1100m +-1 | head,via,right,right,right,right,destination | | 3,2,1 | ab,bc,cd,da,ab,ab,bc,cd,da,ab | 1800m | head,right,right,right,right,via,right,right,right,right,destination | + + + # See issue #1896 + Scenario: Via point at a dead end with oneway + Given the node map + | a | b | c | + | | d | | + | | e | | + + And the ways + | nodes | oneway | + | abc | no | + | bd | no | + | de | yes | + + When I route I should get + | waypoints | route | + | a,d,c | abc,bd,bd,bd,abc | + | c,d,a | abc,bd,bd,bd,abc | From cc4713d87886a1c78fba518143b6f1f2cb4d4fed Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Fri, 15 Jan 2016 00:56:31 +0100 Subject: [PATCH 076/701] Add regression test for uturn before barrier --- features/testbot/via.feature | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/features/testbot/via.feature b/features/testbot/via.feature index 5c7e03837..2168c741f 100644 --- a/features/testbot/via.feature +++ b/features/testbot/via.feature @@ -136,3 +136,29 @@ Feature: Via points | waypoints | route | | a,d,c | abc,bd,bd,bd,abc | | c,d,a | abc,bd,bd,bd,abc | + + # See issue #1896 + Scenario: Via point at a dead end with barrier + Given the profile "car" + Given the node map + | a | b | c | + | | 1 | | + | | d | | + | | | | + | | | | + | f | e | | + + And the nodes + | node | barrier | + | d | bollard | + + And the ways + | nodes | + | abc | + | bd | + | afed | + + When I route I should get + | waypoints | route | + | a,1,c | abc,bd,bd,bd,abc | + | c,1,a | abc,bd,bd,bd,abc | From 22e83013e3cff3fd724bd462dc1a126065398d59 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Fri, 15 Jan 2016 16:10:20 +0100 Subject: [PATCH 077/701] Fix uturns at dead-end streets --- src/extractor/edge_based_graph_factory.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 6b60a193e..f71544b17 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -421,10 +421,23 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( } else { - if ((node_u == node_w) && (m_node_based_graph->GetOutDegree(node_v) > 1)) + if (node_u == node_w && m_node_based_graph->GetOutDegree(node_v) > 1) { - ++skipped_uturns_counter; - continue; + auto number_of_emmiting_bidirectional_edges = 0; + for (auto edge : m_node_based_graph->GetAdjacentEdgeRange(node_v)) + { + auto target = m_node_based_graph->GetTarget(edge); + auto reverse_edge = m_node_based_graph->FindEdge(target, node_v); + if (!m_node_based_graph->GetEdgeData(reverse_edge).reversed) + { + ++number_of_emmiting_bidirectional_edges; + } + } + if (number_of_emmiting_bidirectional_edges > 1) + { + ++skipped_uturns_counter; + continue; + } } } From b8e29f5ae3de5049a427d9240a67b4a8e725ecbd Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Fri, 15 Jan 2016 15:18:51 +0100 Subject: [PATCH 078/701] Add a u-turn instruciton when performing a u-turn at a via-node --- include/engine/guidance/segment_list.hpp | 25 +++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index 488f15812..07c932de1 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -102,6 +102,23 @@ SegmentList::SegmentList(const InternalRouteResult &raw_route, raw_route.segment_end_coordinates[raw_index].target_phantom, raw_route.target_traversed_in_reverse[raw_index], raw_route.is_via_leg(raw_index), facade); + if (raw_route.is_via_leg(raw_index)) + { + const auto &source_phantom = + raw_route.segment_end_coordinates[raw_index].target_phantom; + if (raw_route.target_traversed_in_reverse[raw_index] != raw_route.source_traversed_in_reverse[raw_index+1]) + { + bool traversed_in_reverse = raw_route.target_traversed_in_reverse[raw_index]; + const extractor::TravelMode travel_mode = + (traversed_in_reverse ? source_phantom.backward_travel_mode + : source_phantom.forward_travel_mode); + const bool constexpr IS_NECESSARY = true; + const bool constexpr IS_VIA_LOCATION = true; + segments.emplace_back(source_phantom.location, source_phantom.name_id, 0, 0.f, + extractor::TurnInstruction::UTurn, IS_NECESSARY, + IS_VIA_LOCATION, travel_mode); + } + } } } @@ -145,10 +162,12 @@ void SegmentList::AddLeg(const std::vector &leg_data, (traversed_in_reverse ? target_node.reverse_weight : target_node.forward_weight); const extractor::TravelMode travel_mode = (traversed_in_reverse ? target_node.backward_travel_mode : target_node.forward_travel_mode); + const bool constexpr IS_NECESSARY = true; + const bool constexpr IS_VIA_LOCATION = true; segments.emplace_back(target_node.location, target_node.name_id, segment_duration, 0.f, is_via_leg ? extractor::TurnInstruction::ReachViaLocation : extractor::TurnInstruction::NoTurn, - true, true, travel_mode); + IS_NECESSARY, IS_VIA_LOCATION, travel_mode); } template std::uint32_t SegmentList::GetDistance() const @@ -277,8 +296,8 @@ void SegmentList::Finalize(const bool extract_alternative, std::uint32_t necessary_segments = 0; // a running index that counts the necessary pieces via_indices.push_back(0); - const auto markNecessarySegments = - [this, &necessary_segments](SegmentInformation &first, const SegmentInformation &second) + const auto markNecessarySegments = [this, &necessary_segments](SegmentInformation &first, + const SegmentInformation &second) { if (!first.necessary) return; From 8a745ecdfd18db6aeb24295564b31748cf7fa59b Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Fri, 15 Jan 2016 15:27:45 +0100 Subject: [PATCH 079/701] fixed u-turn testcase to actually emit u-turn instruction --- features/testbot/uturn.feature | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/testbot/uturn.feature b/features/testbot/uturn.feature index 26c681897..032bec685 100644 --- a/features/testbot/uturn.feature +++ b/features/testbot/uturn.feature @@ -43,7 +43,7 @@ Feature: U-turns at via points When I route I should get | waypoints | route | - | a,e,c | ab,be,be,bc | + | a,e,c | ab,be,be,be,bc | @todo Scenario: Instructions at via points at u-turns @@ -89,5 +89,5 @@ Feature: U-turns at via points When I route I should get | waypoints | route | - | 1,2,3,4,5 | ab,be,be,bc,bc,cd,dg,dg,cd | + | 1,2,3,4,5 | ab,be,be,be,bc,bc,cd,dg,dg,dg,cd | From 491b1d9c967c9eed4d74dd35734f6447b341b79c Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 11 Jan 2016 15:13:44 +0100 Subject: [PATCH 080/701] Remove headers with no reverse dependencies Found with ``` daniel@x1c /t/o/i/util> for header in *.hpp echo -n $header: ag -iQ $header ../../ --noheading | wc -l end ... fixed_point_number.hpp:0 range_algorithms.hpp:0 ... ``` Only two. Surprises me to be honest. But we're cleaning up for quite a bit now. --- include/util/fixed_point_number.hpp | 193 ---------------------------- include/util/range_algorithms.hpp | 25 ---- 2 files changed, 218 deletions(-) delete mode 100644 include/util/fixed_point_number.hpp delete mode 100644 include/util/range_algorithms.hpp diff --git a/include/util/fixed_point_number.hpp b/include/util/fixed_point_number.hpp deleted file mode 100644 index 8216b4caf..000000000 --- a/include/util/fixed_point_number.hpp +++ /dev/null @@ -1,193 +0,0 @@ -#ifndef FIXED_POINT_NUMBER_HPP -#define FIXED_POINT_NUMBER_HPP - -#include -#include - -#include -#include -#include -#include - -namespace osrm -{ -namespace util -{ - -// implements an binary based fixed point number type -template -class FixedPointNumber -{ - static_assert(FractionalBitSize > 0, "FractionalBitSize must be greater than 0"); - static_assert(FractionalBitSize <= 32, "FractionalBitSize must at most 32"); - - typename std::conditional::type m_fixed_point_state; - constexpr static const decltype(m_fixed_point_state) PRECISION = 1 << FractionalBitSize; - - // state signage encapsulates whether the state should either represent a - // signed or an unsigned floating point number - using state_signage = - typename std::conditional::type, - decltype(m_fixed_point_state)>::type; - - public: - FixedPointNumber() : m_fixed_point_state(0) {} - - // the type is either initialized with a floating point value or an - // integral state. Anything else will throw at compile-time. - template - constexpr FixedPointNumber(const T &&input) noexcept - : m_fixed_point_state(static_cast( - std::round(std::forward(input) * PRECISION))) - { - static_assert( - std::is_floating_point::value || std::is_integral::value, - "FixedPointNumber needs to be initialized with floating point or integral value"); - } - - // get max value - template ::value>::type * = nullptr> - constexpr static auto max() noexcept -> T - { - return static_cast(std::numeric_limits::max()) / PRECISION; - } - - // get min value - template ::value>::type * = nullptr> - constexpr static auto min() noexcept -> T - { - return static_cast(1) / PRECISION; - } - - // get lowest value - template ::value>::type * = nullptr> - constexpr static auto lowest() noexcept -> T - { - return static_cast(std::numeric_limits::min()) / PRECISION; - } - - // cast to floating point type T, return value - template ::value>::type * = nullptr> - explicit operator const T() const noexcept - { - // casts to external type (signed or unsigned) and then to float - return static_cast(static_cast(m_fixed_point_state)) / PRECISION; - } - - // warn about cast to integral type T, its disabled for good reason - template ::value>::type * = nullptr> - explicit operator T() const - { - static_assert(std::is_integral::value, - "casts to integral types have been disabled on purpose"); - } - - // compare, ie. sort fixed-point numbers - bool operator<(const FixedPointNumber &other) const noexcept - { - return m_fixed_point_state < other.m_fixed_point_state; - } - - // equality, ie. sort fixed-point numbers - bool operator==(const FixedPointNumber &other) const noexcept - { - return m_fixed_point_state == other.m_fixed_point_state; - } - - bool operator!=(const FixedPointNumber &other) const { return !(*this == other); } - bool operator>(const FixedPointNumber &other) const { return other < *this; } - bool operator<=(const FixedPointNumber &other) const { return !(other < *this); } - bool operator>=(const FixedPointNumber &other) const { return !(*this < other); } - - // arithmetic operators - FixedPointNumber operator+(const FixedPointNumber &other) const noexcept - { - FixedPointNumber tmp = *this; - tmp.m_fixed_point_state += other.m_fixed_point_state; - return tmp; - } - - FixedPointNumber &operator+=(const FixedPointNumber &other) noexcept - { - this->m_fixed_point_state += other.m_fixed_point_state; - return *this; - } - - FixedPointNumber operator-(const FixedPointNumber &other) const noexcept - { - FixedPointNumber tmp = *this; - tmp.m_fixed_point_state -= other.m_fixed_point_state; - return tmp; - } - - FixedPointNumber &operator-=(const FixedPointNumber &other) noexcept - { - this->m_fixed_point_state -= other.m_fixed_point_state; - return *this; - } - - FixedPointNumber operator*(const FixedPointNumber &other) const noexcept - { - int64_t temp = this->m_fixed_point_state; - temp *= other.m_fixed_point_state; - - // rounding! - if (!truncate_results) - { - temp = temp + ((temp & 1 << (FractionalBitSize - 1)) << 1); - } - temp >>= FractionalBitSize; - FixedPointNumber tmp; - tmp.m_fixed_point_state = static_cast(temp); - return tmp; - } - - FixedPointNumber &operator*=(const FixedPointNumber &other) noexcept - { - int64_t temp = this->m_fixed_point_state; - temp *= other.m_fixed_point_state; - - // rounding! - if (!truncate_results) - { - temp = temp + ((temp & 1 << (FractionalBitSize - 1)) << 1); - } - temp >>= FractionalBitSize; - this->m_fixed_point_state = static_cast(temp); - return *this; - } - - FixedPointNumber operator/(const FixedPointNumber &other) const noexcept - { - int64_t temp = this->m_fixed_point_state; - temp <<= FractionalBitSize; - temp /= static_cast(other.m_fixed_point_state); - FixedPointNumber tmp; - tmp.m_fixed_point_state = static_cast(temp); - return tmp; - } - - FixedPointNumber &operator/=(const FixedPointNumber &other) noexcept - { - int64_t temp = this->m_fixed_point_state; - temp <<= FractionalBitSize; - temp /= static_cast(other.m_fixed_point_state); - FixedPointNumber tmp; - this->m_fixed_point_state = static_cast(temp); - return *this; - } -}; - -static_assert(4 == sizeof(FixedPointNumber<1>), "FP19 has wrong size != 4"); -} -} - -#endif // FIXED_POINT_NUMBER_HPP diff --git a/include/util/range_algorithms.hpp b/include/util/range_algorithms.hpp deleted file mode 100644 index 964595634..000000000 --- a/include/util/range_algorithms.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef RANGE_ALGORITHMS_HPP -#define RANGE_ALGORITHMS_HPP - -#include - -namespace osrm -{ -namespace util -{ - -template -auto max_element(const Container &c) -> decltype(std::max_element(c.begin(), c.end())) -{ - return std::max_element(c.begin(), c.end()); -} - -template -auto max_element(const Container &c) -> decltype(std::max_element(c.cbegin(), c.cend())) -{ - return std::max_element(c.cbegin(), c.cend()); -} -} -} - -#endif // RANGE_ALGORITHMS_HPP From a877f8abf01b60ff42039e116ea07ac62e88d8e6 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 18 Jan 2016 16:54:13 +0100 Subject: [PATCH 081/701] Switch to explicit find in modernize script --- scripts/modernize.sh | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/scripts/modernize.sh b/scripts/modernize.sh index ee0f2ed46..48d90ba36 100755 --- a/scripts/modernize.sh +++ b/scripts/modernize.sh @@ -3,4 +3,17 @@ # Runs the Clang Modernizer in parallel on the code base. # Requires a compilation database in the build directory. -git ls-files '*.cpp' | xargs -I{} -P $(nproc) clang-modernize -p build -final-syntax-check -format -style=file -summary -for-compilers=clang-3.4,gcc-4.8 -include . -exclude third_party {} +find src include unit_tests -type f -name '*.hpp' -o -name '*.cpp' \ + | xargs \ + -I{} \ + -P $(nproc) \ + clang-modernize \ + -p build \ + -final-syntax-check \ + -format \ + -style=file \ + -summary \ + -for-compilers=clang-3.4,gcc-4.8 \ + -include . \ + -exclude third_party \ + {} From 4b0e1a4b19759d4999f47c13376bd545f1aa884c Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 18 Jan 2016 16:54:30 +0100 Subject: [PATCH 082/701] Run modernizer --- include/engine/geospatial_query.hpp | 2 +- include/extractor/first_and_last_segment_of_way.hpp | 5 +++-- include/extractor/node_based_edge.hpp | 2 +- include/extractor/query_node.hpp | 3 ++- src/tools/datastore.cpp | 2 +- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index 41307043a..11b0db648 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -28,7 +28,7 @@ template class GeospatialQuery public: GeospatialQuery(RTreeT &rtree_, std::shared_ptr coordinates_) - : rtree(rtree_), coordinates(coordinates_) + : rtree(rtree_), coordinates(std::move(coordinates_)) { } diff --git a/include/extractor/first_and_last_segment_of_way.hpp b/include/extractor/first_and_last_segment_of_way.hpp index df2ca92cc..37d0e40c8 100644 --- a/include/extractor/first_and_last_segment_of_way.hpp +++ b/include/extractor/first_and_last_segment_of_way.hpp @@ -28,8 +28,9 @@ struct FirstAndLastSegmentOfWay } FirstAndLastSegmentOfWay(OSMWayID w, OSMNodeID fs, OSMNodeID ft, OSMNodeID ls, OSMNodeID lt) - : way_id(w), first_segment_source_id(fs), first_segment_target_id(ft), - last_segment_source_id(ls), last_segment_target_id(lt) + : way_id(std::move(w)), first_segment_source_id(std::move(fs)), + first_segment_target_id(std::move(ft)), last_segment_source_id(std::move(ls)), + last_segment_target_id(std::move(lt)) { } diff --git a/include/extractor/node_based_edge.hpp b/include/extractor/node_based_edge.hpp index 434af6c1e..9af6ee9c4 100644 --- a/include/extractor/node_based_edge.hpp +++ b/include/extractor/node_based_edge.hpp @@ -123,7 +123,7 @@ inline NodeBasedEdgeWithOSM::NodeBasedEdgeWithOSM(OSMNodeID source, startpoint, travel_mode, is_split), - osm_source_id(source), osm_target_id(target) + osm_source_id(std::move(source)), osm_target_id(std::move(target)) { } diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index abd5d5d0d..98d03210d 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -19,7 +19,8 @@ struct QueryNode using key_type = OSMNodeID; // type of NodeID using value_type = int; // type of lat,lons - explicit QueryNode(int lat, int lon, OSMNodeID node_id) : lat(lat), lon(lon), node_id(node_id) + explicit QueryNode(int lat, int lon, OSMNodeID node_id) + : lat(lat), lon(lon), node_id(std::move(node_id)) { } QueryNode() diff --git a/src/tools/datastore.cpp b/src/tools/datastore.cpp index 41e11dcfe..c00a9cc63 100644 --- a/src/tools/datastore.cpp +++ b/src/tools/datastore.cpp @@ -208,7 +208,7 @@ int main(const int argc, const char *argv[]) try // Allocate a memory layout in shared memory, deallocate previous auto *layout_memory = SharedMemoryFactory::Get(layout_region, sizeof(SharedDataLayout)); - auto *shared_layout_ptr = new (layout_memory->Ptr()) SharedDataLayout(); + auto shared_layout_ptr = new (layout_memory->Ptr()) SharedDataLayout(); shared_layout_ptr->SetBlockSize(SharedDataLayout::FILE_INDEX_PATH, file_index_path.length() + 1); From 790520e335b840b4cba1d6c9cc5a718f2655320c Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 18 Jan 2016 21:23:13 +0100 Subject: [PATCH 083/701] Enable AppVeyor only for master/develop and PRs --- appveyor.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/appveyor.yml b/appveyor.yml index b8fb9799f..f1c98286a 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -25,6 +25,11 @@ artifacts: # - path: osrm_Debug.zip # name: osrm_Debug.zip +branches: + only: + - master + - develop + deploy: provider: FTP server: From 9d12de9bce8469f9aa177049ebf43533e6d699fe Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Wed, 13 Jan 2016 23:17:32 +0100 Subject: [PATCH 084/701] Fix wrong assertion and emplace_back bug in trip plugin --- include/engine/plugins/trip.hpp | 38 ++++++++++++++++----------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index e2705f9bc..45a436dbf 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -102,26 +102,18 @@ template class RoundTripPlugin final : public BasePlugin // NodeID 3, 6, 7, 8 are in component 1 // => in_component = [0, 1, 2, 4, 5, 3, 6, 7, 8] // => in_range = [0, 5] - SCC_Component(std::vector in_component, std::vector in_range) - : component(std::move(in_component)), range(std::move(in_range)) + SCC_Component(std::vector in_component_nodes, std::vector in_range) + : component(std::move(in_component_nodes)), range(std::move(in_range)) { - range.push_back(component.size()); - - BOOST_ASSERT_MSG(component.size() >= range.size(), - "scc component and its ranges do not match"); BOOST_ASSERT_MSG(component.size() > 0, "there's no scc component"); - BOOST_ASSERT_MSG(*std::max_element(range.begin(), range.end()) <= component.size(), + BOOST_ASSERT_MSG(*std::max_element(range.begin(), range.end()) == component.size(), "scc component ranges are out of bound"); - BOOST_ASSERT_MSG(*std::min_element(range.begin(), range.end()) >= 0, + BOOST_ASSERT_MSG(*std::min_element(range.begin(), range.end()) == 0, "invalid scc component range"); BOOST_ASSERT_MSG(std::is_sorted(std::begin(range), std::end(range)), "invalid component ranges"); }; - // constructor to use when whole graph is one single scc - SCC_Component(std::vector in_component) - : component(std::move(in_component)), range({0, component.size()}){}; - std::size_t GetNumberOfComponents() const { BOOST_ASSERT_MSG(range.size() > 0, "there's no range"); @@ -145,7 +137,8 @@ template class RoundTripPlugin final : public BasePlugin // whole graph is one scc std::vector location_ids(number_of_locations); std::iota(std::begin(location_ids), std::end(location_ids), 0); - return SCC_Component(std::move(location_ids)); + std::vector range = {0, location_ids.size()}; + return SCC_Component(std::move(location_ids), std::move(range)); } // Run TarjanSCC @@ -170,6 +163,8 @@ template class RoundTripPlugin final : public BasePlugin range.push_back(prefix); prefix += scc.get_component_size(j); } + // senitel + range.push_back(components.size()); for (std::size_t i = 0; i < number_of_locations; ++i) { @@ -211,11 +206,13 @@ template class RoundTripPlugin final : public BasePlugin BOOST_ASSERT(min_route.segment_end_coordinates.size() == trip.size()); std::vector uturns(trip.size() + 1); + BOOST_ASSERT(route_parameters.uturns.size() > 0); std::transform(trip.begin(), trip.end(), uturns.begin(), [&route_parameters](const NodeID idx) { return route_parameters.uturns[idx]; }); + BOOST_ASSERT(uturns.size() > 0); uturns.back() = route_parameters.uturns[trip.front()]; search_engine_ptr->shortest_path(min_route.segment_end_coordinates, uturns, min_route); @@ -291,13 +288,14 @@ template class RoundTripPlugin final : public BasePlugin { const auto component_size = scc.range[k + 1] - scc.range[k]; - BOOST_ASSERT_MSG(component_size >= 0, "invalid component size"); + BOOST_ASSERT_MSG(component_size > 0, "invalid component size"); + + std::vector scc_route; + NodeIDIterator start = std::begin(scc.component) + scc.range[k]; + NodeIDIterator end = std::begin(scc.component) + scc.range[k + 1]; if (component_size > 1) { - std::vector scc_route; - NodeIDIterator start = std::begin(scc.component) + scc.range[k]; - NodeIDIterator end = std::begin(scc.component) + scc.range[k + 1]; if (component_size < BF_MAX_FEASABLE) { @@ -320,13 +318,13 @@ template class RoundTripPlugin final : public BasePlugin // return s; // }(); - route_result.push_back(std::move(scc_route)); } else { - // if component only consists of one node, add it to the result routes - route_result.emplace_back(scc.component[scc.range[k]]); + scc_route = std::vector(start, end); } + + route_result.push_back(std::move(scc_route)); } // compute all round trip routes From 42942bb1e0f17279494c5b27c17c7731cf2e509a Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Fri, 15 Jan 2016 17:57:01 +0100 Subject: [PATCH 085/701] Add regression test --- features/testbot/trip.feature | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/features/testbot/trip.feature b/features/testbot/trip.feature index c9f944b26..5f3376369 100644 --- a/features/testbot/trip.feature +++ b/features/testbot/trip.feature @@ -82,5 +82,20 @@ Feature: Basic trip planning | waypoints | trips | | a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p | cbalkjihgfedc,ponm | + # Test single node in each component #1850 + Scenario: Testbot - Trip planning with less than 10 nodes + Given the node map + | a | 1 | b | + | | | | + | c | 2 | d | + + And the ways + | nodes | + | ab | + | cd | + + When I plan a trip I should get + | waypoints | trips | + | 1,2 | | From 5d743bb0a3f2c19cdf8dfaeb0608a892a3c4bf29 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 19 Jan 2016 14:28:09 +0100 Subject: [PATCH 086/701] Switch to explicit find in tidy script --- scripts/tidy.sh | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/scripts/tidy.sh b/scripts/tidy.sh index 7ecabfa45..7f4ba1486 100755 --- a/scripts/tidy.sh +++ b/scripts/tidy.sh @@ -3,4 +3,12 @@ # Runs the Clang Tidy Tool in parallel on the code base. # Requires a compilation database in the build directory. -git ls-files '*.cpp' | grep -v third_party | xargs -I{} -P $(nproc) clang-tidy -p build -header-filter='.*' {} + +find src include unit_tests -type f -name '*.hpp' -o -name '*.cpp' \ + | xargs \ + -I{} \ + -P $(nproc) \ + clang-tidy \ + -p build \ + -header-filter='.*' \ + {} From 6e717bfd30dafc164676ce9f1679f357e811da5b Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 19 Jan 2016 14:38:32 +0100 Subject: [PATCH 087/701] Switch to const constexpr for header constants (3.5/3 internal linkage) --- include/engine/datafacade/shared_datatype.hpp | 5 +---- include/extractor/travel_mode.hpp | 7 ++----- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/include/engine/datafacade/shared_datatype.hpp b/include/engine/datafacade/shared_datatype.hpp index 84a9d266b..ab3004df6 100644 --- a/include/engine/datafacade/shared_datatype.hpp +++ b/include/engine/datafacade/shared_datatype.hpp @@ -15,11 +15,8 @@ namespace engine namespace datafacade { -namespace -{ // Added at the start and end of each block as sanity check -static const char CANARY[] = "OSRM"; -} +const constexpr char CANARY[] = "OSRM"; struct SharedDataLayout { diff --git a/include/extractor/travel_mode.hpp b/include/extractor/travel_mode.hpp index f5d5c23f9..1de8c2266 100644 --- a/include/extractor/travel_mode.hpp +++ b/include/extractor/travel_mode.hpp @@ -10,9 +10,6 @@ using TravelMode = unsigned char; } } -namespace -{ -static const osrm::extractor::TravelMode TRAVEL_MODE_INACCESSIBLE = 0; -static const osrm::extractor::TravelMode TRAVEL_MODE_DEFAULT = 1; -} +const constexpr osrm::extractor::TravelMode TRAVEL_MODE_INACCESSIBLE = 0; +const constexpr osrm::extractor::TravelMode TRAVEL_MODE_DEFAULT = 1; #endif /* TRAVEL_MODE_HPP */ From e20f92bbbb1a93492aff3cd90c1231fbd1e6ea7d Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 19 Jan 2016 16:03:45 +0100 Subject: [PATCH 088/701] Anonymous namespaces in header files are bad They duplicate the code across translation units. --- include/util/ini_file.hpp | 6 +----- include/util/std_hash.hpp | 4 ---- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/include/util/ini_file.hpp b/include/util/ini_file.hpp index 1ccc302e8..64c793277 100644 --- a/include/util/ini_file.hpp +++ b/include/util/ini_file.hpp @@ -12,11 +12,8 @@ namespace osrm namespace util { -namespace -{ - // support old capitalized option names by down-casing them with a regex replace -std::string read_file_lower_content(const boost::filesystem::path &path) +inline std::string read_file_lower_content(const boost::filesystem::path &path) { boost::filesystem::fstream config_stream(path); std::string ini_file_content((std::istreambuf_iterator(config_stream)), @@ -27,6 +24,5 @@ std::string read_file_lower_content(const boost::filesystem::path &path) } } } -} #endif // INI_FILE_HPP diff --git a/include/util/std_hash.hpp b/include/util/std_hash.hpp index ff5ac187b..b456ab1ca 100644 --- a/include/util/std_hash.hpp +++ b/include/util/std_hash.hpp @@ -6,9 +6,6 @@ // this is largely inspired by boost's hash combine as can be found in // "The C++ Standard Library" 2nd Edition. Nicolai M. Josuttis. 2012. -namespace -{ - template void hash_combine(std::size_t &seed, const T &val) { seed ^= std::hash()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2); @@ -29,7 +26,6 @@ template std::size_t hash_val(const Types &... args) hash_val(seed, args...); return seed; } -} namespace std { From 1ed7bcfb2ccdf65211822af1c1f115273e1f2001 Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Wed, 13 Jan 2016 17:42:50 -0800 Subject: [PATCH 089/701] DataFacade should only remove shared segments if they're actually different from the last time they were checked. --- include/engine/datafacade/shared_datafacade.hpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 62fb08363..faefbe1ed 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -225,6 +225,10 @@ template class SharedDataFacade final : public BaseDataFacade< SharedDataFacade() { + if (!datastore::SharedMemory::RegionExists(CURRENT_REGIONS)) + { + throw util::exception("No shared memory blocks found, have you forgotten to run osrm-datastore?"); + } data_timestamp_ptr = (SharedDataTimestamp *)datastore::SharedMemoryFactory::Get( CURRENT_REGIONS, sizeof(SharedDataTimestamp), false, false) ->Ptr(); @@ -239,8 +243,7 @@ template class SharedDataFacade final : public BaseDataFacade< void CheckAndReloadFacade() { if (CURRENT_LAYOUT != data_timestamp_ptr->layout || - CURRENT_DATA != data_timestamp_ptr->data || - CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) + CURRENT_DATA != data_timestamp_ptr->data) { // release the previous shared memory segments datastore::SharedMemory::Remove(CURRENT_LAYOUT); @@ -248,8 +251,12 @@ template class SharedDataFacade final : public BaseDataFacade< CURRENT_LAYOUT = data_timestamp_ptr->layout; CURRENT_DATA = data_timestamp_ptr->data; - CURRENT_TIMESTAMP = data_timestamp_ptr->timestamp; + CURRENT_TIMESTAMP = 0; // Force trigger a reload + } + if (CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) + { + CURRENT_TIMESTAMP = data_timestamp_ptr->timestamp; m_layout_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_LAYOUT)); data_layout = (SharedDataLayout *)(m_layout_memory->Ptr()); From 80b897d8cfa9f47e148b2ed36b0f106a9cbeb7e8 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 13 Jan 2016 10:57:05 +0100 Subject: [PATCH 090/701] Fix shared memory non-copyable properties --- include/datastore/shared_memory_factory.hpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/include/datastore/shared_memory_factory.hpp b/include/datastore/shared_memory_factory.hpp index 4c4cb2aa6..ae8e11ee5 100644 --- a/include/datastore/shared_memory_factory.hpp +++ b/include/datastore/shared_memory_factory.hpp @@ -77,6 +77,7 @@ class SharedMemory SharedMemory() = delete; SharedMemory(const SharedMemory &) = delete; + SharedMemory &operator=(const SharedMemory &) = delete; template SharedMemory(const boost::filesystem::path &lock_file, @@ -187,11 +188,13 @@ class SharedMemory class SharedMemory { SharedMemory(const SharedMemory &) = delete; + SharedMemory &operator=(const SharedMemory &) = delete; // Remove shared memory on destruction class shm_remove { private: shm_remove(const shm_remove &) = delete; + shm_remove &operator=(const shm_remove &) = delete; char *m_shmid; bool m_initialized; @@ -355,6 +358,7 @@ template class SharedMemoryFactory_tmpl SharedMemoryFactory_tmpl() = delete; SharedMemoryFactory_tmpl(const SharedMemoryFactory_tmpl &) = delete; + SharedMemoryFactory_tmpl &operator=(const SharedMemoryFactory_tmpl &) = delete; }; using SharedMemoryFactory = SharedMemoryFactory_tmpl<>; From e21eaa4b9eaa6c3885b618ec1d0d9c11b7492ea2 Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Fri, 15 Jan 2016 00:57:36 -0800 Subject: [PATCH 091/701] Adds a shared/exclusive lock around queries and CheckAndReloadFacade. Without this, it's possible for CheckAndReloadFacade to start working while a query is still in progress, leading to undefined behaviour. --- .../engine/datafacade/shared_datafacade.hpp | 103 +++++++++++------- src/engine/osrm_impl.cpp | 12 +- 2 files changed, 73 insertions(+), 42 deletions(-) diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index faefbe1ed..359584682 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -223,6 +223,8 @@ template class SharedDataFacade final : public BaseDataFacade< public: virtual ~SharedDataFacade() {} + boost::shared_mutex data_mutex; + SharedDataFacade() { if (!datastore::SharedMemory::RegionExists(CURRENT_REGIONS)) @@ -243,57 +245,76 @@ template class SharedDataFacade final : public BaseDataFacade< void CheckAndReloadFacade() { if (CURRENT_LAYOUT != data_timestamp_ptr->layout || - CURRENT_DATA != data_timestamp_ptr->data) + CURRENT_DATA != data_timestamp_ptr->data || + CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) { - // release the previous shared memory segments - datastore::SharedMemory::Remove(CURRENT_LAYOUT); - datastore::SharedMemory::Remove(CURRENT_DATA); - CURRENT_LAYOUT = data_timestamp_ptr->layout; - CURRENT_DATA = data_timestamp_ptr->data; - CURRENT_TIMESTAMP = 0; // Force trigger a reload - } + // Get exclusive lock + util::SimpleLogger().Write(logDEBUG) << "Updates available, getting exclusive lock"; + boost::unique_lock lock(data_mutex); - if (CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) - { - CURRENT_TIMESTAMP = data_timestamp_ptr->timestamp; - m_layout_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_LAYOUT)); - - data_layout = (SharedDataLayout *)(m_layout_memory->Ptr()); - - m_large_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_DATA)); - shared_memory = (char *)(m_large_memory->Ptr()); - - const char *file_index_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::FILE_INDEX_PATH); - file_index_path = boost::filesystem::path(file_index_ptr); - if (!boost::filesystem::exists(file_index_path)) + if (CURRENT_LAYOUT != data_timestamp_ptr->layout || + CURRENT_DATA != data_timestamp_ptr->data) { - util::SimpleLogger().Write(logDEBUG) << "Leaf file name " - << file_index_path.string(); - throw util::exception("Could not load leaf index file. " - "Is any data loaded into shared memory?"); + // release the previous shared memory segments + datastore::SharedMemory::Remove(CURRENT_LAYOUT); + datastore::SharedMemory::Remove(CURRENT_DATA); + + CURRENT_LAYOUT = data_timestamp_ptr->layout; + CURRENT_DATA = data_timestamp_ptr->data; + CURRENT_TIMESTAMP = 0; // Force trigger a reload + + util::SimpleLogger().Write(logDEBUG) << "Current layout was different to new layout, swapping"; + } + else + { + util::SimpleLogger().Write(logDEBUG) << "Current layout was same to new layout, not swapping"; + } - LoadGraph(); - LoadChecksum(); - LoadNodeAndEdgeInformation(); - LoadGeometries(); - LoadTimestamp(); - LoadViaNodeList(); - LoadNames(); - LoadCoreInformation(); - - data_layout->PrintInformation(); - - util::SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); - for (unsigned i = 0; i < m_coordinate_list->size(); ++i) + if (CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) { - if (!GetCoordinateOfNode(i).IsValid()) + CURRENT_TIMESTAMP = data_timestamp_ptr->timestamp; + + util::SimpleLogger().Write(logDEBUG) << "Performing data reload"; + m_layout_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_LAYOUT)); + + data_layout = (SharedDataLayout *) (m_layout_memory->Ptr()); + + m_large_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_DATA)); + shared_memory = (char *) (m_large_memory->Ptr()); + + const char *file_index_ptr = + data_layout->GetBlockPtr(shared_memory, SharedDataLayout::FILE_INDEX_PATH); + file_index_path = boost::filesystem::path(file_index_ptr); + if (!boost::filesystem::exists(file_index_path)) { + util::SimpleLogger().Write(logDEBUG) << "Leaf file name " + << file_index_path.string(); + throw util::exception("Could not load leaf index file. " + "Is any data loaded into shared memory?"); + } + + LoadGraph(); + LoadChecksum(); + LoadNodeAndEdgeInformation(); + LoadGeometries(); + LoadTimestamp(); + LoadViaNodeList(); + LoadNames(); + LoadCoreInformation(); + + data_layout->PrintInformation(); + + util::SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); + for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { - util::SimpleLogger().Write() << "coordinate " << i << " not valid"; + if (!GetCoordinateOfNode(i).IsValid()) + { + util::SimpleLogger().Write() << "coordinate " << i << " not valid"; + } } } + util::SimpleLogger().Write(logDEBUG) << "Releasing exclusive lock"; } } diff --git a/src/engine/osrm_impl.cpp b/src/engine/osrm_impl.cpp index 200eb2741..c059698b4 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/osrm_impl.cpp @@ -82,8 +82,18 @@ int OSRM::OSRM_impl::RunQuery(const RouteParameters &route_parameters, return 400; } + osrm::engine::plugins::BasePlugin::Status return_code; increase_concurrent_query_count(); - auto return_code = plugin_iterator->second->HandleRequest(route_parameters, json_result); + if (barrier) { + // Get a shared data lock so that other threads won't update + // things while the query is running + boost::shared_lock data_lock{ + (static_cast *>( + query_data_facade))->data_mutex}; + return_code = plugin_iterator->second->HandleRequest(route_parameters, json_result); + } else { + return_code = plugin_iterator->second->HandleRequest(route_parameters, json_result); + } decrease_concurrent_query_count(); return static_cast(return_code); } From 238e77d9592ffca568b00d9828bfda1e9ab49810 Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Tue, 19 Jan 2016 10:42:58 -0800 Subject: [PATCH 092/701] Include the travel mode in the last instruction by copying it from the previous instruction. --- include/engine/guidance/textual_route_annotation.hpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/include/engine/guidance/textual_route_annotation.hpp b/include/engine/guidance/textual_route_annotation.hpp index a66786724..085f952a9 100644 --- a/include/engine/guidance/textual_route_annotation.hpp +++ b/include/engine/guidance/textual_route_annotation.hpp @@ -41,6 +41,7 @@ inline util::json::Array AnnotateRoute(const std::vector &ro round_about = {std::numeric_limits::max(), 0, 0}; std::string temp_dist, temp_length, temp_duration, temp_bearing, temp_instruction; + extractor::TravelMode last_travel_mode = TRAVEL_MODE_DEFAULT; // Generate annotations for every segment for (const SegmentInformation &segment : route_segments) @@ -89,6 +90,7 @@ inline util::json::Array AnnotateRoute(const std::vector &ro static_cast(std::round(post_turn_bearing_value))); json_instruction_row.values.push_back(segment.travel_mode); + last_travel_mode = segment.travel_mode; // pre turn bearing const double pre_turn_bearing_value = (segment.pre_turn_bearing / 10.); @@ -120,6 +122,7 @@ inline util::json::Array AnnotateRoute(const std::vector &ro json_last_instruction_row.values.push_back("0m"); json_last_instruction_row.values.push_back(util::bearing::get(0.0)); json_last_instruction_row.values.push_back(0.); + json_last_instruction_row.values.push_back(last_travel_mode); json_last_instruction_row.values.push_back(util::bearing::get(0.0)); json_last_instruction_row.values.push_back(0.); json_instruction_array.values.emplace_back(std::move(json_last_instruction_row)); From 1c1bfd75411cf7ffb95f6f19fcf4bef9d2ae1ae7 Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Thu, 7 Jan 2016 10:33:47 +0100 Subject: [PATCH 093/701] Fix routing when start and target are on the same segment Fixes issue #1864. Given the simple set-up: a --> b --> c ^-----------| This would translate into an edge based graph (ab) -> (bc), (bc) -> (ca), (ca) -> (ab). Starting at the end of the one-way street (ab) and going to the beginning, the query has to find a self-loop within the graph (ab) -> (bc) -> (ca) -> (ab), as both nodes map to the same segment (ab). --- CMakeLists.txt | 5 +- features/support/data.rb | 2 +- features/testbot/distance_matrix.feature | 28 ++- features/testbot/via.feature | 45 +++- include/contractor/contractor.hpp | 188 +++++++++++----- include/contractor/processing_chain.hpp | 3 + .../routing_algorithms/alternative_path.hpp | 61 ++++- .../direct_shortest_path.hpp | 8 +- .../routing_algorithms/many_to_many.hpp | 17 +- .../routing_algorithms/routing_base.hpp | 208 ++++++++++++++---- .../routing_algorithms/shortest_path.hpp | 158 +++---------- .../extractor/edge_based_graph_factory.hpp | 8 +- include/extractor/extractor.hpp | 12 +- include/extractor/extractor_options.hpp | 5 + include/util/io.hpp | 127 +++++++++++ src/contractor/processing_chain.cpp | 42 +++- src/extractor/edge_based_graph_factory.cpp | 16 ++ src/extractor/extractor.cpp | 42 ++-- src/extractor/extractor_options.cpp | 4 + src/tools/extract.cpp | 2 +- unit_tests/io/io.cpp | 43 ++++ unit_tests/io_tests.cpp | 7 + 22 files changed, 744 insertions(+), 287 deletions(-) create mode 100644 include/util/io.hpp create mode 100644 unit_tests/io/io.cpp create mode 100644 unit_tests/io_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a1cf4e87..763842cf8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,7 +44,7 @@ add_custom_target(FingerPrintConfigure ALL ${CMAKE_COMMAND} COMMENT "Configuring revision fingerprint" VERBATIM) -add_custom_target(tests DEPENDS engine-tests extractor-tests util-tests) +add_custom_target(tests DEPENDS engine-tests extractor-tests util-tests io-tests) add_custom_target(benchmarks DEPENDS rtree-bench) set(BOOST_COMPONENTS date_time filesystem iostreams program_options regex system thread unit_test_framework) @@ -61,6 +61,7 @@ file(GLOB EngineGlob src/engine/*.cpp src/engine/**/*.cpp) file(GLOB ExtractorTestsGlob unit_tests/extractor/*.cpp) file(GLOB EngineTestsGlob unit_tests/engine/*.cpp) file(GLOB UtilTestsGlob unit_tests/util/*.cpp) +file(GLOB IOTestsGlob unit_tests/io/*.cpp) add_library(UTIL OBJECT ${UtilGlob}) add_library(EXTRACTOR OBJECT ${ExtractorGlob}) @@ -85,6 +86,7 @@ target_link_libraries(osrm-routed OSRM) add_executable(engine-tests EXCLUDE_FROM_ALL unit_tests/engine_tests.cpp ${EngineTestsGlob} $ $ $) add_executable(extractor-tests EXCLUDE_FROM_ALL unit_tests/extractor_tests.cpp ${ExtractorTestsGlob} $ $) add_executable(util-tests EXCLUDE_FROM_ALL unit_tests/util_tests.cpp ${UtilTestsGlob} $ $) +add_executable(io-tests EXCLUDE_FROM_ALL unit_tests/io_tests.cpp ${IOTestsGlob} $) # Benchmarks add_executable(rtree-bench EXCLUDE_FROM_ALL src/benchmarks/static_rtree.cpp $ $) @@ -248,6 +250,7 @@ target_link_libraries(engine-tests ${Boost_LIBRARIES}) target_link_libraries(extractor-tests ${Boost_LIBRARIES}) target_link_libraries(util-tests ${Boost_LIBRARIES}) target_link_libraries(rtree-bench ${Boost_LIBRARIES}) +target_link_libraries(io-tests ${Boost_LIBRARIES}) find_package(Threads REQUIRED) target_link_libraries(osrm-extract ${CMAKE_THREAD_LIBS_INIT}) diff --git a/features/support/data.rb b/features/support/data.rb index eabd934bd..adc3d118c 100644 --- a/features/support/data.rb +++ b/features/support/data.rb @@ -263,7 +263,7 @@ def extract_data raise ExtractError.new $?.exitstatus, "osrm-extract exited with code #{$?.exitstatus}." end begin - ["osrm","osrm.names","osrm.restrictions","osrm.ebg","osrm.edges","osrm.fileIndex","osrm.geometry","osrm.nodes","osrm.ramIndex"].each do |file| + ["osrm","osrm.names","osrm.restrictions","osrm.ebg","osrm.enw","osrm.edges","osrm.fileIndex","osrm.geometry","osrm.nodes","osrm.ramIndex"].each do |file| log "Renaming #{osm_file}.#{file} to #{extracted_file}.#{file}", :preprocess File.rename "#{osm_file}.#{file}", "#{extracted_file}.#{file}" end diff --git a/features/testbot/distance_matrix.feature b/features/testbot/distance_matrix.feature index 491012623..d02136ef8 100644 --- a/features/testbot/distance_matrix.feature +++ b/features/testbot/distance_matrix.feature @@ -29,7 +29,7 @@ Feature: Basic Distance Matrix | ab | primary | | bc | secondary | | cd | tertiary | - + When I request a travel time matrix I should get | | a | b | c | d | | a | 0 | 100 | 300 | 600 | @@ -49,7 +49,7 @@ Feature: Basic Distance Matrix | | a | b | | a | 0 | 95 +- 10 | | b | 95 ~10% | 0 | - + Scenario: Testbot - Travel time matrix of small grid Given the node map | a | b | c | @@ -82,7 +82,7 @@ Feature: Basic Distance Matrix | | a | b | | a | 0 | 100 | | b | | 0 | - + Scenario: Testbot - Travel time matrix of network with oneways Given the node map | x | a | b | y | @@ -136,7 +136,7 @@ Feature: Basic Distance Matrix | a | 100 | 200 | 300 | | b | 0 | 100 | 200 | - Scenario: Testbog - All coordinates are from same small component + Scenario: Testbot - All coordinates are from same small component Given a grid size of 300 meters Given the extract extra arguments "--small-component-size 4" Given the node map @@ -156,7 +156,7 @@ Feature: Basic Distance Matrix | f | 0 | 300 | | g | 300 | 0 | - Scenario: Testbog - Coordinates are from different small component and snap to big CC + Scenario: Testbot - Coordinates are from different small component and snap to big CC Given a grid size of 300 meters Given the extract extra arguments "--small-component-size 4" Given the node map @@ -179,3 +179,21 @@ Feature: Basic Distance Matrix | h | 0 | 300 | 0 | 300 | | i | 300 | 0 | 300 | 0 | + Scenario: Testbot - Travel time matrix with loops + Given the node map + | a | 1 | 2 | b | + | d | 4 | 3 | c | + + And the ways + | nodes | oneway | + | ab | yes | + | bc | yes | + | cd | yes | + | da | yes | + + When I request a travel time matrix I should get + | | 1 | 2 | 3 | 4 | + | 1 | 0 | 100 +-1 | 400 +-1 | 500 +-1 | + | 2 | 700 +-1 | 0 | 300 +-1 | 400 +-1 | + | 3 | 400 +-1 | 500 +-1 | 0 | 100 +-1 | + | 4 | 300 +-1 | 400 +-1 | 700 +-1 | 0 | diff --git a/features/testbot/via.feature b/features/testbot/via.feature index 2168c741f..3af38a9d6 100644 --- a/features/testbot/via.feature +++ b/features/testbot/via.feature @@ -93,8 +93,6 @@ Feature: Via points | 1,3,2 | ab,bc,cd,cd,de,ef,fa,ab,bc | 1600m +-1 | head,straight,straight,via,right,right,right,right,straight,destination | | 3,2,1 | cd,de,ef,fa,ab,bc,bc,cd,de,ef,fa,ab | 2400m +-1 | head,right,right,right,right,straight,via,straight,right,right,right,right,destination | - # TODO: Remove this ignore when https://github.com/Project-OSRM/osrm-backend/issues/1863 gets fixed - @ignore-platform-mac Scenario: Via points on ring on the same oneway # xa it to avoid only having a single ring, which cna trigger edge cases Given the node map @@ -118,7 +116,6 @@ Feature: Via points | 1,3,2 | ab,ab,bc,cd,da,ab | 1100m +-1 | head,via,right,right,right,right,destination | | 3,2,1 | ab,bc,cd,da,ab,ab,bc,cd,da,ab | 1800m | head,right,right,right,right,via,right,right,right,right,destination | - # See issue #1896 Scenario: Via point at a dead end with oneway Given the node map @@ -162,3 +159,45 @@ Feature: Via points | waypoints | route | | a,1,c | abc,bd,bd,bd,abc | | c,1,a | abc,bd,bd,bd,abc | + + Scenario: Via points on ring on the same oneway, forces one of the vertices to be top node + Given the node map + | a | 1 | 2 | b | + | 8 | | | 3 | + | 7 | | | 4 | + | d | 6 | 5 | c | + + And the ways + | nodes | oneway | + | ab | yes | + | bc | yes | + | cd | yes | + | da | yes | + + When I route I should get + | waypoints | route | distance | turns | + | 2,1 | ab,bc,cd,da,ab | 1100m +-1 | head,right,right,right,right,destination | + | 4,3 | bc,cd,da,ab,bc | 1100m +-1 | head,right,right,right,right,destination | + | 6,5 | cd,da,ab,bc,cd | 1100m +-1 | head,right,right,right,right,destination | + | 8,7 | da,ab,bc,cd,da | 1100m +-1 | head,right,right,right,right,destination | + + Scenario: Multiple Via points on ring on the same oneway, forces one of the vertices to be top node + Given the node map + | a | 1 | 2 | 3 | b | + | | | | | 4 | + | | | | | 5 | + | | | | | 6 | + | d | 9 | 8 | 7 | c | + + And the ways + | nodes | oneway | + | ab | yes | + | bc | yes | + | cd | yes | + | da | yes | + + When I route I should get + | waypoints | route | distance | turns | + | 3,2,1 | ab,bc,cd,da,ab,ab,bc,cd,da,ab | 3000m +-1 | head,right,right,right,right,via,right,right,right,right,destination | + | 6,5,4 | bc,cd,da,ab,bc,bc,cd,da,ab,bc | 3000m +-1 | head,right,right,right,right,via,right,right,right,right,destination | + | 9,8,7 | cd,da,ab,bc,cd,cd,da,ab,bc,cd | 3000m +-1 | head,right,right,right,right,via,right,right,right,right,destination | diff --git a/include/contractor/contractor.hpp b/include/contractor/contractor.hpp index 633a67d41..6e4f8688b 100644 --- a/include/contractor/contractor.hpp +++ b/include/contractor/contractor.hpp @@ -145,8 +145,11 @@ class Contractor } template - Contractor(int nodes, ContainerT &input_edge_list, std::vector &&node_levels_) - : node_levels(std::move(node_levels_)) + Contractor(int nodes, + ContainerT &input_edge_list, + std::vector &&node_levels_, + std::vector &&node_weights_) + : node_levels(std::move(node_levels_)), node_weights(std::move(node_weights_)) { std::vector edges; edges.reserve(input_edge_list.size() * 2); @@ -203,8 +206,7 @@ class Contractor forward_edge.data.shortcut = reverse_edge.data.shortcut = false; forward_edge.data.id = reverse_edge.data.id = id; forward_edge.data.originalEdges = reverse_edge.data.originalEdges = 1; - forward_edge.data.distance = reverse_edge.data.distance = - std::numeric_limits::max(); + forward_edge.data.distance = reverse_edge.data.distance = INVALID_EDGE_WEIGHT; // remove parallel edges while (i < edges.size() && edges[i].source == source && edges[i].target == target) { @@ -223,7 +225,7 @@ class Contractor // merge edges (s,t) and (t,s) into bidirectional edge if (forward_edge.data.distance == reverse_edge.data.distance) { - if ((int)forward_edge.data.distance != std::numeric_limits::max()) + if ((int)forward_edge.data.distance != INVALID_EDGE_WEIGHT) { forward_edge.data.backward = true; edges[edge++] = forward_edge; @@ -231,11 +233,11 @@ class Contractor } else { // insert seperate edges - if (((int)forward_edge.data.distance) != std::numeric_limits::max()) + if (((int)forward_edge.data.distance) != INVALID_EDGE_WEIGHT) { edges[edge++] = forward_edge; } - if ((int)reverse_edge.data.distance != std::numeric_limits::max()) + if ((int)reverse_edge.data.distance != INVALID_EDGE_WEIGHT) { edges[edge++] = reverse_edge; } @@ -360,18 +362,21 @@ class Contractor // Create new priority array std::vector new_node_priority(remaining_nodes.size()); + std::vector new_node_weights(remaining_nodes.size()); // this map gives the old IDs from the new ones, necessary to get a consistent graph // at the end of contraction orig_node_id_from_new_node_id_map.resize(remaining_nodes.size()); // this map gives the new IDs from the old ones, necessary to remap targets from the // remaining graph - std::vector new_node_id_from_orig_id_map(number_of_nodes, UINT_MAX); + std::vector new_node_id_from_orig_id_map(number_of_nodes, SPECIAL_NODEID); for (const auto new_node_id : util::irange(0, remaining_nodes.size())) { auto &node = remaining_nodes[new_node_id]; BOOST_ASSERT(node_priorities.size() > node.id); new_node_priority[new_node_id] = node_priorities[node.id]; + BOOST_ASSERT(node_weights.size() > node.id); + new_node_weights[new_node_id] = node_weights[node.id]; } // build forward and backward renumbering map and remap ids in remaining_nodes @@ -404,9 +409,9 @@ class Contractor new_node_id_from_orig_id_map[target], data}; new_edge.data.is_original_via_node_ID = true; - BOOST_ASSERT_MSG(UINT_MAX != new_node_id_from_orig_id_map[source], + BOOST_ASSERT_MSG(SPECIAL_NODEID != new_node_id_from_orig_id_map[source], "new source id not resolveable"); - BOOST_ASSERT_MSG(UINT_MAX != new_node_id_from_orig_id_map[target], + BOOST_ASSERT_MSG(SPECIAL_NODEID != new_node_id_from_orig_id_map[target], "new target id not resolveable"); new_edge_set.push_back(new_edge); } @@ -420,8 +425,12 @@ class Contractor // Replace old priorities array by new one node_priorities.swap(new_node_priority); // Delete old node_priorities vector + // Due to the scope, these should get cleared automatically? @daniel-j-h do you + // agree? new_node_priority.clear(); new_node_priority.shrink_to_fit(); + + node_weights.swap(new_node_weights); // old Graph is removed contractor_graph.reset(); @@ -581,7 +590,7 @@ class Contractor remaining_nodes.resize(begin_independent_nodes_idx); // unsigned maxdegree = 0; // unsigned avgdegree = 0; - // unsigned mindegree = UINT_MAX; + // unsigned mindegree = SPECIAL_NODEID; // unsigned quaddegree = 0; // // for(unsigned i = 0; i < remaining_nodes.size(); ++i) { @@ -686,8 +695,8 @@ class Contractor new_edge.source = node; new_edge.target = target; } - BOOST_ASSERT_MSG(UINT_MAX != new_edge.source, "Source id invalid"); - BOOST_ASSERT_MSG(UINT_MAX != new_edge.target, "Target id invalid"); + BOOST_ASSERT_MSG(SPECIAL_NODEID != new_edge.source, "Source id invalid"); + BOOST_ASSERT_MSG(SPECIAL_NODEID != new_edge.target, "Target id invalid"); new_edge.data.distance = data.distance; new_edge.data.shortcut = data.shortcut; if (!data.is_original_via_node_ID && !orig_node_id_from_new_node_id_map.empty()) @@ -718,23 +727,55 @@ class Contractor } private: + inline void RelaxNode(const NodeID node, + const NodeID forbidden_node, + const int distance, + ContractorHeap &heap) + { + const short current_hop = heap.GetData(node).hop + 1; + for (auto edge : contractor_graph->GetAdjacentEdgeRange(node)) + { + const ContractorEdgeData &data = contractor_graph->GetEdgeData(edge); + if (!data.forward) + { + continue; + } + const NodeID to = contractor_graph->GetTarget(edge); + if (forbidden_node == to) + { + continue; + } + const int to_distance = distance + data.distance; + + // New Node discovered -> Add to Heap + Node Info Storage + if (!heap.WasInserted(to)) + { + heap.Insert(to, to_distance, ContractorHeapData(current_hop, false)); + } + // Found a shorter Path -> Update distance + else if (to_distance < heap.GetKey(to)) + { + heap.DecreaseKey(to, to_distance); + heap.GetData(to).hop = current_hop; + } + } + } + inline void Dijkstra(const int max_distance, const unsigned number_of_targets, const int maxNodes, - ContractorThreadData *const data, + ContractorThreadData &data, const NodeID middleNode) { - ContractorHeap &heap = data->heap; + ContractorHeap &heap = data.heap; int nodes = 0; unsigned number_of_targets_found = 0; while (!heap.Empty()) { const NodeID node = heap.DeleteMin(); - const int distance = heap.GetKey(node); - const short current_hop = heap.GetData(node).hop + 1; - + const auto distance = heap.GetKey(node); if (++nodes > maxNodes) { return; @@ -754,33 +795,7 @@ class Contractor } } - // iterate over all edges of node - for (auto edge : contractor_graph->GetAdjacentEdgeRange(node)) - { - const ContractorEdgeData &data = contractor_graph->GetEdgeData(edge); - if (!data.forward) - { - continue; - } - const NodeID to = contractor_graph->GetTarget(edge); - if (middleNode == to) - { - continue; - } - const int to_distance = distance + data.distance; - - // New Node discovered -> Add to Heap + Node Info Storage - if (!heap.WasInserted(to)) - { - heap.Insert(to, to_distance, ContractorHeapData(current_hop, false)); - } - // Found a shorter Path -> Update distance - else if (to_distance < heap.GetKey(to)) - { - heap.DecreaseKey(to, to_distance); - heap.GetData(to).hop = current_hop; - } - } + RelaxNode(node, middleNode, distance, heap); } } @@ -815,13 +830,21 @@ class Contractor ContractNode(ContractorThreadData *data, const NodeID node, ContractionStats *stats = nullptr) { ContractorHeap &heap = data->heap; - int inserted_edges_size = data->inserted_edges.size(); + std::size_t inserted_edges_size = data->inserted_edges.size(); std::vector &inserted_edges = data->inserted_edges; + const constexpr bool SHORTCUT_ARC = true; + const constexpr bool FORWARD_DIRECTION_ENABLED = true; + const constexpr bool FORWARD_DIRECTION_DISABLED = false; + const constexpr bool REVERSE_DIRECTION_ENABLED = true; + const constexpr bool REVERSE_DIRECTION_DISABLED = false; for (auto in_edge : contractor_graph->GetAdjacentEdgeRange(node)) { const ContractorEdgeData &in_data = contractor_graph->GetEdgeData(in_edge); const NodeID source = contractor_graph->GetTarget(in_edge); + if (source == node) + continue; + if (RUNSIMULATION) { BOOST_ASSERT(stats != nullptr); @@ -846,22 +869,64 @@ class Contractor continue; } const NodeID target = contractor_graph->GetTarget(out_edge); - const int path_distance = in_data.distance + out_data.distance; + if (node == target) + continue; + + const EdgeWeight path_distance = in_data.distance + out_data.distance; + if (target == source) + { + if (path_distance < node_weights[node]) + { + if (RUNSIMULATION) + { + // make sure to prune better, but keep inserting this loop if it should + // still be the best + // CAREFUL: This only works due to the independent node-setting. This + // guarantees that source is not connected to another node that is + // contracted + node_weights[source] = path_distance + 1; + BOOST_ASSERT(stats != nullptr); + stats->edges_added_count += 2; + stats->original_edges_added_count += + 2 * (out_data.originalEdges + in_data.originalEdges); + } + else + { + // CAREFUL: This only works due to the independent node-setting. This + // guarantees that source is not connected to another node that is + // contracted + node_weights[source] = path_distance; // make sure to prune better + inserted_edges.emplace_back( + source, target, path_distance, + out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, + FORWARD_DIRECTION_ENABLED, REVERSE_DIRECTION_DISABLED); + + inserted_edges.emplace_back( + target, source, path_distance, + out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, + FORWARD_DIRECTION_DISABLED, REVERSE_DIRECTION_ENABLED); + } + } + continue; + } max_distance = std::max(max_distance, path_distance); if (!heap.WasInserted(target)) { - heap.Insert(target, INT_MAX, ContractorHeapData(0, true)); + heap.Insert(target, INVALID_EDGE_WEIGHT, ContractorHeapData(0, true)); ++number_of_targets; } } if (RUNSIMULATION) { - Dijkstra(max_distance, number_of_targets, 1000, data, node); + const int constexpr SIMULATION_SEARCH_SPACE_SIZE = 1000; + Dijkstra(max_distance, number_of_targets, SIMULATION_SEARCH_SPACE_SIZE, *data, + node); } else { - Dijkstra(max_distance, number_of_targets, 2000, data, node); + const int constexpr FULL_SEARCH_SPACE_SIZE = 2000; + Dijkstra(max_distance, number_of_targets, FULL_SEARCH_SPACE_SIZE, *data, node); } for (auto out_edge : contractor_graph->GetAdjacentEdgeRange(node)) { @@ -871,6 +936,8 @@ class Contractor continue; } const NodeID target = contractor_graph->GetTarget(out_edge); + if (target == node) + continue; const int path_distance = in_data.distance + out_data.distance; const int distance = heap.GetKey(target); if (path_distance < distance) @@ -886,22 +953,26 @@ class Contractor { inserted_edges.emplace_back(source, target, path_distance, out_data.originalEdges + in_data.originalEdges, - node, true, true, false); + node, SHORTCUT_ARC, FORWARD_DIRECTION_ENABLED, + REVERSE_DIRECTION_DISABLED); inserted_edges.emplace_back(target, source, path_distance, out_data.originalEdges + in_data.originalEdges, - node, true, false, true); + node, SHORTCUT_ARC, FORWARD_DIRECTION_DISABLED, + REVERSE_DIRECTION_ENABLED); } } } } + // Check For One-Way Streets to decide on the creation of self-loops + if (!RUNSIMULATION) { - int iend = inserted_edges.size(); - for (int i = inserted_edges_size; i < iend; ++i) + std::size_t iend = inserted_edges.size(); + for (std::size_t i = inserted_edges_size; i < iend; ++i) { bool found = false; - for (int other = i + 1; other < iend; ++other) + for (std::size_t other = i + 1; other < iend; ++other) { if (inserted_edges[other].source != inserted_edges[i].source) { @@ -1071,6 +1142,13 @@ class Contractor stxxl::vector external_edge_list; std::vector orig_node_id_from_new_node_id_map; std::vector node_levels; + + // A list of weights for every node in the graph. + // The weight represents the cost for a u-turn on the segment in the base-graph in addition to + // its traversal. + // During contraction, self-loops are checked against this node weight to ensure that necessary + // self-loops are added. + std::vector node_weights; std::vector is_core_node; util::XORFastHash fast_hash; }; diff --git a/include/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp index 42034eb57..e75af29e0 100644 --- a/include/contractor/processing_chain.hpp +++ b/include/contractor/processing_chain.hpp @@ -11,6 +11,8 @@ #include +#include + #include struct lua_State; @@ -43,6 +45,7 @@ class Prepare void ContractGraph(const unsigned max_edge_id, util::DeallocatingVector &edge_based_edge_list, util::DeallocatingVector &contracted_edge_list, + std::vector &&node_weights, std::vector &is_core_node, std::vector &node_levels) const; void WriteCoreNodeMarker(std::vector &&is_core_node) const; diff --git a/include/engine/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp index 70d08b870..7d7f64832 100644 --- a/include/engine/routing_algorithms/alternative_path.hpp +++ b/include/engine/routing_algorithms/alternative_path.hpp @@ -156,8 +156,23 @@ class AlternativeRouting final std::vector packed_forward_path; std::vector packed_reverse_path; - super::RetrievePackedPathFromSingleHeap(forward_heap1, middle_node, packed_forward_path); - super::RetrievePackedPathFromSingleHeap(reverse_heap1, middle_node, packed_reverse_path); + if (upper_bound_to_shortest_path_distance != + forward_heap1.GetKey(middle_node) + reverse_heap1.GetKey(middle_node)) + { + // Self Loop + BOOST_ASSERT(forward_heap1.GetData(middle_node).parent == middle_node && + reverse_heap1.GetData(middle_node).parent == middle_node); + packed_forward_path.push_back(middle_node); + packed_forward_path.push_back(middle_node); + } + else + { + + super::RetrievePackedPathFromSingleHeap(forward_heap1, middle_node, + packed_forward_path); + super::RetrievePackedPathFromSingleHeap(reverse_heap1, middle_node, + packed_reverse_path); + } // this set is is used as an indicator if a node is on the shortest path std::unordered_set nodes_in_path(packed_forward_path.size() + @@ -382,10 +397,13 @@ class AlternativeRouting final int upper_bound_s_v_path_length = INVALID_EDGE_WEIGHT; new_reverse_heap.Insert(via_node, 0, via_node); // compute path by reusing forward search from s + const bool constexpr STALLING_ENABLED = true; + const bool constexpr DO_NOT_FORCE_LOOPS = false; while (!new_reverse_heap.Empty()) { super::RoutingStep(new_reverse_heap, existing_forward_heap, s_v_middle, - upper_bound_s_v_path_length, min_edge_offset, false); + upper_bound_s_v_path_length, min_edge_offset, false, + STALLING_ENABLED, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS); } // compute path by reusing backward search from node t NodeID v_t_middle = SPECIAL_NODEID; @@ -394,7 +412,8 @@ class AlternativeRouting final while (!new_forward_heap.Empty()) { super::RoutingStep(new_forward_heap, existing_reverse_heap, v_t_middle, - upper_bound_of_v_t_path_length, min_edge_offset, true); + upper_bound_of_v_t_path_length, min_edge_offset, true, + STALLING_ENABLED, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS); } *real_length_of_via_path = upper_bound_s_v_path_length + upper_bound_of_v_t_path_length; @@ -442,10 +461,10 @@ class AlternativeRouting final partially_unpacked_shortest_path.size())) - 1; for (int64_t current_node = 0; (current_node < packed_path_length) && - (partially_unpacked_via_path[current_node] == - partially_unpacked_shortest_path[current_node] && - partially_unpacked_via_path[current_node + 1] == - partially_unpacked_shortest_path[current_node + 1]); + (partially_unpacked_via_path[current_node] == + partially_unpacked_shortest_path[current_node] && + partially_unpacked_via_path[current_node + 1] == + partially_unpacked_shortest_path[current_node + 1]); ++current_node) { EdgeID selected_edge = @@ -600,6 +619,18 @@ class AlternativeRouting final // << " // at distance " << new_distance; } + else + { + // check whether there is a loop present at the node + const auto loop_distance = super::GetLoopWeight(node); + const int new_distance_with_loop = new_distance + loop_distance; + if (loop_distance != INVALID_EDGE_WEIGHT && + new_distance_with_loop <= *upper_bound_to_shortest_path_distance) + { + *middle_node = node; + *upper_bound_to_shortest_path_distance = loop_distance; + } + } } } @@ -655,10 +686,13 @@ class AlternativeRouting final int upper_bound_s_v_path_length = INVALID_EDGE_WEIGHT; // compute path by reusing forward search from s new_reverse_heap.Insert(candidate.node, 0, candidate.node); + const bool constexpr STALLING_ENABLED = true; + const bool constexpr DO_NOT_FORCE_LOOPS = false; while (new_reverse_heap.Size() > 0) { super::RoutingStep(new_reverse_heap, existing_forward_heap, *s_v_middle, - upper_bound_s_v_path_length, min_edge_offset, false); + upper_bound_s_v_path_length, min_edge_offset, false, + STALLING_ENABLED, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS); } if (INVALID_EDGE_WEIGHT == upper_bound_s_v_path_length) @@ -673,7 +707,8 @@ class AlternativeRouting final while (new_forward_heap.Size() > 0) { super::RoutingStep(new_forward_heap, existing_reverse_heap, *v_t_middle, - upper_bound_of_v_t_path_length, min_edge_offset, true); + upper_bound_of_v_t_path_length, min_edge_offset, true, + STALLING_ENABLED, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS); } if (INVALID_EDGE_WEIGHT == upper_bound_of_v_t_path_length) @@ -841,12 +876,14 @@ class AlternativeRouting final if (!forward_heap3.Empty()) { super::RoutingStep(forward_heap3, reverse_heap3, middle, upper_bound, - min_edge_offset, true); + min_edge_offset, true, STALLING_ENABLED, DO_NOT_FORCE_LOOPS, + DO_NOT_FORCE_LOOPS); } if (!reverse_heap3.Empty()) { super::RoutingStep(reverse_heap3, forward_heap3, middle, upper_bound, - min_edge_offset, false); + min_edge_offset, false, STALLING_ENABLED, DO_NOT_FORCE_LOOPS, + DO_NOT_FORCE_LOOPS); } } return (upper_bound <= t_test_path_length); diff --git a/include/engine/routing_algorithms/direct_shortest_path.hpp b/include/engine/routing_algorithms/direct_shortest_path.hpp index 437d88d27..931b6a5da 100644 --- a/include/engine/routing_algorithms/direct_shortest_path.hpp +++ b/include/engine/routing_algorithms/direct_shortest_path.hpp @@ -93,6 +93,9 @@ class DirectShortestPathRouting final int distance = INVALID_EDGE_WEIGHT; std::vector packed_leg; + const bool constexpr DO_NOT_FORCE_LOOPS = + false; // prevents forcing of loops, since offsets are set correctly + if (super::facade->GetCoreSize() > 0) { engine_working_data.InitializeOrClearSecondThreadLocalStorage( @@ -103,11 +106,12 @@ class DirectShortestPathRouting final reverse_core_heap.Clear(); super::SearchWithCore(forward_heap, reverse_heap, forward_core_heap, reverse_core_heap, - distance, packed_leg); + distance, packed_leg, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS); } else { - super::Search(forward_heap, reverse_heap, distance, packed_leg); + super::Search(forward_heap, reverse_heap, distance, packed_leg, DO_NOT_FORCE_LOOPS, + DO_NOT_FORCE_LOOPS); } // No path found for both target nodes? diff --git a/include/engine/routing_algorithms/many_to_many.hpp b/include/engine/routing_algorithms/many_to_many.hpp index c8311783f..016b5e94b 100644 --- a/include/engine/routing_algorithms/many_to_many.hpp +++ b/include/engine/routing_algorithms/many_to_many.hpp @@ -139,14 +139,21 @@ class ManyToManyRouting final // get target id from bucket entry const unsigned target_id = current_bucket.target_id; const int target_distance = current_bucket.distance; - const EdgeWeight current_distance = - (*result_table)[source_id * number_of_targets + target_id]; + auto ¤t_distance = (*result_table)[source_id * number_of_targets + target_id]; // check if new distance is better const EdgeWeight new_distance = source_distance + target_distance; - if (new_distance >= 0 && new_distance < current_distance) + if (new_distance < 0) { - (*result_table)[source_id * number_of_targets + target_id] = - (source_distance + target_distance); + const EdgeWeight loop_weight = super::GetLoopWeight(node); + const int new_distance_with_loop = new_distance + loop_weight; + if (loop_weight != INVALID_EDGE_WEIGHT && new_distance_with_loop >= 0) + { + current_distance = std::min(current_distance, new_distance_with_loop); + } + } + else if (new_distance < current_distance) + { + (*result_table)[source_id * number_of_targets + target_id] = new_distance; } } } diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index 19865b494..6f9315d1e 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -5,9 +5,17 @@ #include "engine/internal_route_result.hpp" #include "engine/search_engine_data.hpp" #include "extractor/turn_instructions.hpp" +#include "util/typedefs.hpp" #include +#include +#include + +#include +#include +#include +#include #include namespace osrm @@ -71,24 +79,54 @@ template class BasicRoutingInterface void RoutingStep(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, NodeID &middle_node_id, - int &upper_bound, - int min_edge_offset, + std::int32_t &upper_bound, + std::int32_t min_edge_offset, const bool forward_direction, - const bool stalling = true) const + const bool stalling, + const bool force_loop_forward, + const bool force_loop_reverse) const { const NodeID node = forward_heap.DeleteMin(); - const int distance = forward_heap.GetKey(node); + const std::int32_t distance = forward_heap.GetKey(node); if (reverse_heap.WasInserted(node)) { - const int new_distance = reverse_heap.GetKey(node) + distance; + const std::int32_t new_distance = reverse_heap.GetKey(node) + distance; if (new_distance < upper_bound) { - if (new_distance >= 0) + if (new_distance >= 0 && + (!force_loop_forward || + forward_heap.GetData(node).parent != + node) // if loops are forced, they are so at the source + && (!force_loop_reverse || reverse_heap.GetData(node).parent != node)) { middle_node_id = node; upper_bound = new_distance; } + else + { + // check whether there is a loop present at the node + for (const auto edge : facade->GetAdjacentEdgeRange(node)) + { + const EdgeData &data = facade->GetEdgeData(edge); + bool forward_directionFlag = + (forward_direction ? data.forward : data.backward); + if (forward_directionFlag) + { + const NodeID to = facade->GetTarget(edge); + if (to == node) + { + const EdgeWeight edge_weight = data.distance; + const std::int32_t loop_distance = new_distance + edge_weight; + if (loop_distance >= 0 && loop_distance < upper_bound) + { + middle_node_id = node; + upper_bound = loop_distance; + } + } + } + } + } } } @@ -111,7 +149,7 @@ template class BasicRoutingInterface if (reverse_flag) { const NodeID to = facade->GetTarget(edge); - const int edge_weight = data.distance; + const EdgeWeight edge_weight = data.distance; BOOST_ASSERT_MSG(edge_weight > 0, "edge_weight invalid"); @@ -134,7 +172,7 @@ template class BasicRoutingInterface { const NodeID to = facade->GetTarget(edge); - const int edge_weight = data.distance; + const EdgeWeight edge_weight = data.distance; BOOST_ASSERT_MSG(edge_weight > 0, "edge_weight invalid"); const int to_distance = distance + edge_weight; @@ -155,6 +193,24 @@ template class BasicRoutingInterface } } + inline EdgeWeight GetLoopWeight(NodeID node) const + { + EdgeWeight loop_weight = INVALID_EDGE_WEIGHT; + for (auto edge : facade->GetAdjacentEdgeRange(node)) + { + const auto &data = facade->GetEdgeData(edge); + if (data.forward) + { + const NodeID to = facade->GetTarget(edge); + if (to == node) + { + loop_weight = std::min(loop_weight, data.distance); + } + } + } + return loop_weight; + } + template void UnpackPath(RandomIter packed_path_begin, RandomIter packed_path_end, @@ -188,10 +244,10 @@ template class BasicRoutingInterface // facade->FindEdge does not suffice here in case of shortcuts. // The above explanation unclear? Think! EdgeID smaller_edge_id = SPECIAL_EDGEID; - int edge_weight = std::numeric_limits::max(); + EdgeWeight edge_weight = std::numeric_limits::max(); for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first)) { - const int weight = facade->GetEdgeData(edge_id).distance; + const EdgeWeight weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) && facade->GetEdgeData(edge_id).forward) { @@ -207,7 +263,7 @@ template class BasicRoutingInterface { for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second)) { - const int weight = facade->GetEdgeData(edge_id).distance; + const EdgeWeight weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) && facade->GetEdgeData(edge_id).backward) { @@ -345,10 +401,10 @@ template class BasicRoutingInterface recursion_stack.pop(); EdgeID smaller_edge_id = SPECIAL_EDGEID; - int edge_weight = std::numeric_limits::max(); + EdgeWeight edge_weight = std::numeric_limits::max(); for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.first)) { - const int weight = facade->GetEdgeData(edge_id).distance; + const EdgeWeight weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.second) && (weight < edge_weight) && facade->GetEdgeData(edge_id).forward) { @@ -361,7 +417,7 @@ template class BasicRoutingInterface { for (const auto edge_id : facade->GetAdjacentEdgeRange(edge.second)) { - const int weight = facade->GetEdgeData(edge_id).distance; + const EdgeWeight weight = facade->GetEdgeData(edge_id).distance; if ((facade->GetTarget(edge_id) == edge.first) && (weight < edge_weight) && facade->GetEdgeData(edge_id).backward) { @@ -414,10 +470,23 @@ template class BasicRoutingInterface } // assumes that heaps are already setup correctly. + // ATTENTION: This only works if no additional offset is supplied next to the Phantom Node + // Offsets. + // In case additional offsets are supplied, you might have to force a loop first. + // A forced loop might be necessary, if source and target are on the same segment. + // If this is the case and the offsets of the respective direction are larger for the source + // than the target + // then a force loop is required (e.g. source_phantom.forward_node_id == + // target_phantom.forward_node_id + // && source_phantom.GetForwardWeightPlusOffset() > target_phantom.GetForwardWeightPlusOffset()) + // requires + // a force loop, if the heaps have been initialized with positive offsets. void Search(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, - int &distance, - std::vector &packed_leg) const + std::int32_t &distance, + std::vector &packed_leg, + const bool force_loop_forward, + const bool force_loop_reverse) const { NodeID middle = SPECIAL_NODEID; @@ -428,15 +497,18 @@ template class BasicRoutingInterface BOOST_ASSERT(reverse_heap.MinKey() >= 0); // run two-Target Dijkstra routing step. + const constexpr bool STALLING_ENABLED = true; while (0 < (forward_heap.Size() + reverse_heap.Size())) { if (!forward_heap.Empty()) { - RoutingStep(forward_heap, reverse_heap, middle, distance, min_edge_offset, true); + RoutingStep(forward_heap, reverse_heap, middle, distance, min_edge_offset, true, + STALLING_ENABLED, force_loop_forward, force_loop_reverse); } if (!reverse_heap.Empty()) { - RoutingStep(reverse_heap, forward_heap, middle, distance, min_edge_offset, false); + RoutingStep(reverse_heap, forward_heap, middle, distance, min_edge_offset, false, + STALLING_ENABLED, force_loop_reverse, force_loop_forward); } } @@ -450,16 +522,38 @@ template class BasicRoutingInterface BOOST_ASSERT_MSG((SPECIAL_NODEID != middle && INVALID_EDGE_WEIGHT != distance), "no path found"); - RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle, packed_leg); + // make sure to correctly unpack loops + if (distance != forward_heap.GetKey(middle) + reverse_heap.GetKey(middle)) + { + // self loop + BOOST_ASSERT(forward_heap.GetData(middle).parent == middle && + reverse_heap.GetData(middle).parent == middle); + packed_leg.push_back(middle); + packed_leg.push_back(middle); + } + else + { + RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle, packed_leg); + } } // assumes that heaps are already setup correctly. + // A forced loop might be necessary, if source and target are on the same segment. + // If this is the case and the offsets of the respective direction are larger for the source + // than the target + // then a force loop is required (e.g. source_phantom.forward_node_id == + // target_phantom.forward_node_id + // && source_phantom.GetForwardWeightPlusOffset() > target_phantom.GetForwardWeightPlusOffset()) + // requires + // a force loop, if the heaps have been initialized with positive offsets. void SearchWithCore(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, SearchEngineData::QueryHeap &forward_core_heap, SearchEngineData::QueryHeap &reverse_core_heap, int &distance, - std::vector &packed_leg) const + std::vector &packed_leg, + const bool force_loop_forward, + const bool force_loop_reverse) const { NodeID middle = SPECIAL_NODEID; @@ -471,6 +565,7 @@ template class BasicRoutingInterface // we only every insert negative offsets for nodes in the forward heap BOOST_ASSERT(reverse_heap.MinKey() >= 0); + const constexpr bool STALLING_ENABLED = true; // run two-Target Dijkstra routing step. while (0 < (forward_heap.Size() + reverse_heap.Size())) { @@ -484,8 +579,8 @@ template class BasicRoutingInterface } else { - RoutingStep(forward_heap, reverse_heap, middle, distance, min_edge_offset, - true); + RoutingStep(forward_heap, reverse_heap, middle, distance, min_edge_offset, true, + STALLING_ENABLED, force_loop_forward, force_loop_reverse); } } if (!reverse_heap.Empty()) @@ -499,7 +594,7 @@ template class BasicRoutingInterface else { RoutingStep(reverse_heap, forward_heap, middle, distance, min_edge_offset, - false); + false, STALLING_ENABLED, force_loop_reverse, force_loop_forward); } } } @@ -548,18 +643,21 @@ template class BasicRoutingInterface BOOST_ASSERT(min_core_edge_offset <= 0); // run two-target Dijkstra routing step on core with termination criterion + const constexpr bool STALLING_DISABLED = false; while (0 < (forward_core_heap.Size() + reverse_core_heap.Size()) && distance > (forward_core_heap.MinKey() + reverse_core_heap.MinKey())) { if (!forward_core_heap.Empty()) { RoutingStep(forward_core_heap, reverse_core_heap, middle, distance, - min_core_edge_offset, true, false); + min_core_edge_offset, true, STALLING_DISABLED, force_loop_forward, + force_loop_reverse); } if (!reverse_core_heap.Empty()) { RoutingStep(reverse_core_heap, forward_core_heap, middle, distance, - min_core_edge_offset, false, false); + min_core_edge_offset, false, STALLING_DISABLED, force_loop_reverse, + force_loop_forward); } } @@ -573,29 +671,45 @@ template class BasicRoutingInterface BOOST_ASSERT_MSG((SPECIAL_NODEID != middle && INVALID_EDGE_WEIGHT != distance), "no path found"); - // we need to unpack sub path from core heaps - if (facade->IsCoreNode(middle)) + if (distance != forward_heap.GetKey(middle) + reverse_heap.GetKey(middle)) { - std::vector packed_core_leg; - RetrievePackedPathFromHeap(forward_core_heap, reverse_core_heap, middle, - packed_core_leg); - BOOST_ASSERT(packed_core_leg.size() > 0); - RetrievePackedPathFromSingleHeap(forward_heap, packed_core_leg.front(), packed_leg); - std::reverse(packed_leg.begin(), packed_leg.end()); - packed_leg.insert(packed_leg.end(), packed_core_leg.begin(), packed_core_leg.end()); - RetrievePackedPathFromSingleHeap(reverse_heap, packed_core_leg.back(), packed_leg); + // self loop + BOOST_ASSERT(forward_heap.GetData(middle).parent == middle && + reverse_heap.GetData(middle).parent == middle); + packed_leg.push_back(middle); + packed_leg.push_back(middle); } else { - RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle, packed_leg); + // we need to unpack sub path from core heaps + if (facade->IsCoreNode(middle)) + { + std::vector packed_core_leg; + RetrievePackedPathFromHeap(forward_core_heap, reverse_core_heap, middle, + packed_core_leg); + BOOST_ASSERT(packed_core_leg.size() > 0); + RetrievePackedPathFromSingleHeap(forward_heap, packed_core_leg.front(), packed_leg); + std::reverse(packed_leg.begin(), packed_leg.end()); + packed_leg.insert(packed_leg.end(), packed_core_leg.begin(), packed_core_leg.end()); + RetrievePackedPathFromSingleHeap(reverse_heap, packed_core_leg.back(), packed_leg); + } + else + { + RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle, packed_leg); + } } } + // Requires the heaps for be empty + // If heaps should be adjusted to be initialized outside of this function, + // the addition of force_loop parameters might be required double get_network_distance(SearchEngineData::QueryHeap &forward_heap, SearchEngineData::QueryHeap &reverse_heap, const PhantomNode &source_phantom, const PhantomNode &target_phantom) const { + BOOST_ASSERT(forward_heap.Empty()); + BOOST_ASSERT(reverse_heap.Empty()); EdgeWeight upper_bound = INVALID_EDGE_WEIGHT; NodeID middle_node = SPECIAL_NODEID; EdgeWeight edge_offset = std::min(0, -source_phantom.GetForwardWeightPlusOffset()); @@ -628,17 +742,19 @@ template class BasicRoutingInterface } // search from s and t till new_min/(1+epsilon) > length_of_shortest_path + const constexpr bool STALLING_ENABLED = true; + const constexpr bool DO_NOT_FORCE_LOOPS = false; while (0 < (forward_heap.Size() + reverse_heap.Size())) { if (0 < forward_heap.Size()) { - RoutingStep(forward_heap, reverse_heap, middle_node, upper_bound, edge_offset, - true); + RoutingStep(forward_heap, reverse_heap, middle_node, upper_bound, edge_offset, true, + STALLING_ENABLED, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS); } if (0 < reverse_heap.Size()) { RoutingStep(reverse_heap, forward_heap, middle_node, upper_bound, edge_offset, - false); + false, STALLING_ENABLED, DO_NOT_FORCE_LOOPS, DO_NOT_FORCE_LOOPS); } } @@ -646,7 +762,19 @@ template class BasicRoutingInterface if (upper_bound != INVALID_EDGE_WEIGHT) { std::vector packed_leg; - RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle_node, packed_leg); + if (upper_bound != forward_heap.GetKey(middle_node) + reverse_heap.GetKey(middle_node)) + { + // self loop + BOOST_ASSERT(forward_heap.GetData(middle_node).parent == middle_node && + reverse_heap.GetData(middle_node).parent == middle_node); + packed_leg.push_back(middle_node); + packed_leg.push_back(middle_node); + } + else + { + RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle_node, packed_leg); + } + std::vector unpacked_path; PhantomNodes nodes; nodes.source_phantom = source_phantom; diff --git a/include/engine/routing_algorithms/shortest_path.hpp b/include/engine/routing_algorithms/shortest_path.hpp index 2613c3227..d03780fbb 100644 --- a/include/engine/routing_algorithms/shortest_path.hpp +++ b/include/engine/routing_algorithms/shortest_path.hpp @@ -24,6 +24,9 @@ class ShortestPathRouting final using super = BasicRoutingInterface>; using QueryHeap = SearchEngineData::QueryHeap; SearchEngineData &engine_working_data; + const static constexpr bool FORWARD_DIRECTION = true; + const static constexpr bool REVERSE_DIRECTION = false; + const static constexpr bool DO_NOT_FORCE_LOOP = false; public: ShortestPathRouting(DataFacadeT *facade, SearchEngineData &engine_working_data) @@ -33,6 +36,19 @@ class ShortestPathRouting final ~ShortestPathRouting() {} + inline bool + forceLoop(bool forward, const PhantomNode &source_phantom, const PhantomNode &target_phantom) const + { + if (forward) + return source_phantom.forward_node_id == target_phantom.forward_node_id && + source_phantom.GetForwardWeightPlusOffset() > + target_phantom.GetForwardWeightPlusOffset(); + else + return source_phantom.reverse_node_id == target_phantom.reverse_node_id && + source_phantom.GetReverseWeightPlusOffset() > + target_phantom.GetReverseWeightPlusOffset(); + }; + // allows a uturn at the target_phantom // searches source forward/reverse -> target forward/reverse void SearchWithUTurn(QueryHeap &forward_heap, @@ -76,113 +92,12 @@ class ShortestPathRouting final target_phantom.GetReverseWeightPlusOffset(), target_phantom.reverse_node_id); } + BOOST_ASSERT(forward_heap.Size() > 0); BOOST_ASSERT(reverse_heap.Size() > 0); - super::Search(forward_heap, reverse_heap, new_total_distance, leg_packed_path); - } - - // If source and target are reverse on a oneway we need to find a path - // that connects the two. This is _not_ the shortest path in our model, - // as source and target are on the same edge based node. - // We force a detour by inserting "virtaul vias", which means we search a path - // from all nodes that are connected by outgoing edges to all nodes that are connected by - // incoming edges. - // ------^ - // | ^source - // | ^ - // | ^target - // ------^ - void SearchLoop(QueryHeap &forward_heap, - QueryHeap &reverse_heap, - const bool search_forward_node, - const bool search_reverse_node, - const PhantomNode &source_phantom, - const PhantomNode &target_phantom, - const int total_distance_to_forward, - const int total_distance_to_reverse, - int &new_total_distance_to_forward, - int &new_total_distance_to_reverse, - std::vector &leg_packed_path_forward, - std::vector &leg_packed_path_reverse) const - { - BOOST_ASSERT(source_phantom.forward_node_id == target_phantom.forward_node_id); - BOOST_ASSERT(source_phantom.reverse_node_id == target_phantom.reverse_node_id); - - if (search_forward_node) - { - forward_heap.Clear(); - reverse_heap.Clear(); - - auto node_id = source_phantom.forward_node_id; - - for (const auto edge : super::facade->GetAdjacentEdgeRange(node_id)) - { - const auto &data = super::facade->GetEdgeData(edge); - if (data.forward) - { - auto target = super::facade->GetTarget(edge); - auto offset = total_distance_to_forward + data.distance - - source_phantom.GetForwardWeightPlusOffset(); - forward_heap.Insert(target, offset, target); - } - - if (data.backward) - { - auto target = super::facade->GetTarget(edge); - auto offset = data.distance + target_phantom.GetForwardWeightPlusOffset(); - reverse_heap.Insert(target, offset, target); - } - } - - BOOST_ASSERT(forward_heap.Size() > 0); - BOOST_ASSERT(reverse_heap.Size() > 0); - super::Search(forward_heap, reverse_heap, new_total_distance_to_forward, - leg_packed_path_forward); - - // insert node to both endpoints to close the leg - leg_packed_path_forward.push_back(node_id); - std::reverse(leg_packed_path_forward.begin(), leg_packed_path_forward.end()); - leg_packed_path_forward.push_back(node_id); - std::reverse(leg_packed_path_forward.begin(), leg_packed_path_forward.end()); - } - - if (search_reverse_node) - { - forward_heap.Clear(); - reverse_heap.Clear(); - - auto node_id = source_phantom.reverse_node_id; - - for (const auto edge : super::facade->GetAdjacentEdgeRange(node_id)) - { - const auto &data = super::facade->GetEdgeData(edge); - if (data.forward) - { - auto target = super::facade->GetTarget(edge); - auto offset = total_distance_to_reverse + data.distance - - source_phantom.GetReverseWeightPlusOffset(); - forward_heap.Insert(target, offset, target); - } - - if (data.backward) - { - auto target = super::facade->GetTarget(edge); - auto offset = data.distance + target_phantom.GetReverseWeightPlusOffset(); - reverse_heap.Insert(target, offset, target); - } - } - - BOOST_ASSERT(forward_heap.Size() > 0); - BOOST_ASSERT(reverse_heap.Size() > 0); - super::Search(forward_heap, reverse_heap, new_total_distance_to_reverse, - leg_packed_path_reverse); - - // insert node to both endpoints to close the leg - leg_packed_path_reverse.push_back(node_id); - std::reverse(leg_packed_path_reverse.begin(), leg_packed_path_reverse.end()); - leg_packed_path_reverse.push_back(node_id); - std::reverse(leg_packed_path_reverse.begin(), leg_packed_path_reverse.end()); - } + super::Search(forward_heap, reverse_heap, new_total_distance, leg_packed_path, + forceLoop(FORWARD_DIRECTION, source_phantom, target_phantom), + forceLoop(REVERSE_DIRECTION, source_phantom, target_phantom)); } // searches shortest path between: @@ -227,8 +142,9 @@ class ShortestPathRouting final } BOOST_ASSERT(forward_heap.Size() > 0); BOOST_ASSERT(reverse_heap.Size() > 0); - super::Search(forward_heap, reverse_heap, new_total_distance_to_forward, - leg_packed_path_forward); + super::Search( + forward_heap, reverse_heap, new_total_distance_to_forward, leg_packed_path_forward, + forceLoop(FORWARD_DIRECTION, source_phantom, target_phantom), DO_NOT_FORCE_LOOP); } if (search_to_reverse_node) @@ -255,7 +171,8 @@ class ShortestPathRouting final BOOST_ASSERT(forward_heap.Size() > 0); BOOST_ASSERT(reverse_heap.Size() > 0); super::Search(forward_heap, reverse_heap, new_total_distance_to_reverse, - leg_packed_path_reverse); + leg_packed_path_reverse, DO_NOT_FORCE_LOOP, + forceLoop(REVERSE_DIRECTION, source_phantom, target_phantom)); } } @@ -336,19 +253,6 @@ class ShortestPathRouting final BOOST_ASSERT(!search_from_reverse_node || source_phantom.reverse_node_id != SPECIAL_NODEID); - if (source_phantom.forward_node_id == target_phantom.forward_node_id && - source_phantom.GetForwardWeightPlusOffset() > - target_phantom.GetForwardWeightPlusOffset()) - { - search_to_forward_node = search_from_reverse_node; - } - if (source_phantom.reverse_node_id == target_phantom.reverse_node_id && - source_phantom.GetReverseWeightPlusOffset() > - target_phantom.GetReverseWeightPlusOffset()) - { - search_to_reverse_node = search_from_forward_node; - } - BOOST_ASSERT(search_from_forward_node || search_from_reverse_node); if (search_to_reverse_node || search_to_forward_node) @@ -385,18 +289,6 @@ class ShortestPathRouting final packed_leg_to_reverse); } } - else - { - search_to_forward_node = target_phantom.forward_node_id != SPECIAL_NODEID; - search_to_reverse_node = target_phantom.reverse_node_id != SPECIAL_NODEID; - BOOST_ASSERT(search_from_reverse_node == search_to_reverse_node); - BOOST_ASSERT(search_from_forward_node == search_to_forward_node); - SearchLoop(forward_heap, reverse_heap, search_from_forward_node, - search_from_reverse_node, source_phantom, target_phantom, - total_distance_to_forward, total_distance_to_reverse, - new_total_distance_to_forward, new_total_distance_to_reverse, - packed_leg_to_forward, packed_leg_to_reverse); - } // No path found for both target nodes? if ((INVALID_EDGE_WEIGHT == new_total_distance_to_forward) && diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 94772a3dd..ef9bacf99 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -62,10 +62,11 @@ class EdgeBasedGraphFactory const bool generate_edge_lookup); #endif + //The following get access functions destroy the content in the factory void GetEdgeBasedEdges(util::DeallocatingVector &edges); - void GetEdgeBasedNodes(std::vector &nodes); void GetStartPointMarkers(std::vector &node_is_startpoint); + void GetEdgeBasedNodeWeights(std::vector &output_node_weights); unsigned GetHighestEdgeID(); @@ -80,6 +81,11 @@ class EdgeBasedGraphFactory //! maps index from m_edge_based_node_list to ture/false if the node is an entry point to the //! graph std::vector m_edge_based_node_is_startpoint; + + //! node weights that indicate the length of the segment (node based) represented by the + //! edge-based node + std::vector m_edge_based_node_weights; + //! list of edge based nodes (compressed segments) std::vector m_edge_based_node_list; util::DeallocatingVector m_edge_based_edge_list; diff --git a/include/extractor/extractor.hpp b/include/extractor/extractor.hpp index 68feaf624..72e5be8b7 100644 --- a/include/extractor/extractor.hpp +++ b/include/extractor/extractor.hpp @@ -6,24 +6,28 @@ #include "extractor/edge_based_graph_factory.hpp" #include "extractor/graph_compressor.hpp" +#include "util/typedefs.hpp" + namespace osrm { namespace extractor { -class extractor +class Extractor { public: - extractor(ExtractorConfig extractor_config) : config(std::move(extractor_config)) {} + Extractor(ExtractorConfig extractor_config) : config(std::move(extractor_config)) {} int run(); private: ExtractorConfig config; + void SetupScriptingEnvironment(lua_State *myLuaState, SpeedProfileProperties &speed_profile); std::pair BuildEdgeExpandedGraph(std::vector &internal_to_external_node_map, std::vector &node_based_edge_list, std::vector &node_is_startpoint, + std::vector &edge_based_node_weights, util::DeallocatingVector &edge_based_edge_list); void WriteNodeMapping(const std::vector &internal_to_external_node_map); void FindComponents(unsigned max_edge_id, @@ -38,8 +42,8 @@ class extractor std::unordered_set &traffic_lights, std::vector &internal_to_external_node_map); - void WriteEdgeBasedGraph(std::string const &output_file_filename, - size_t const max_edge_id, + void WriteEdgeBasedGraph(const std::string &output_file_filename, + const size_t max_edge_id, util::DeallocatingVector const &edge_based_edge_list); }; } diff --git a/include/extractor/extractor_options.hpp b/include/extractor/extractor_options.hpp index 287d62f06..57f79c1ec 100644 --- a/include/extractor/extractor_options.hpp +++ b/include/extractor/extractor_options.hpp @@ -35,6 +35,11 @@ struct ExtractorConfig std::string rtree_nodes_output_path; std::string rtree_leafs_output_path; + // every edge based node represents a segment in the original graph. During contraciton we need + // to know about this segment length, as we might have to add self-loops in cases of shorter + // parts than the segment represents itself + std::string edge_based_node_weights_output_path; + unsigned requested_num_threads; unsigned small_component_size; diff --git a/include/util/io.hpp b/include/util/io.hpp new file mode 100644 index 000000000..b7951032c --- /dev/null +++ b/include/util/io.hpp @@ -0,0 +1,127 @@ +#ifndef OSRM_INCLUDE_UTIL_IO_HPP_ +#define OSRM_INCLUDE_UTIL_IO_HPP_ + +#include "util/simple_logger.hpp" + +#include + +#include +#include + +#include +#include +#include + +#include "util/fingerprint.hpp" + +namespace osrm +{ +namespace util +{ + +inline bool writeFingerprint(std::ostream &stream) +{ + const auto fingerprint = FingerPrint::GetValid(); + stream.write(reinterpret_cast(&fingerprint), sizeof(fingerprint)); + return static_cast(stream); +} + +inline bool readAndCheckFingerprint(std::istream &stream) +{ + FingerPrint fingerprint; + const auto valid = FingerPrint::GetValid(); + stream.read(reinterpret_cast(&fingerprint), sizeof(fingerprint)); + // compare the compilation state stored in the fingerprint + return static_cast(stream) && valid.IsMagicNumberOK(fingerprint) && + valid.TestPrepare(fingerprint) && valid.TestGraphUtil(fingerprint) && + valid.TestRTree(fingerprint) && valid.TestQueryObjects(fingerprint); +} + +template +bool serializeVector(const std::string &filename, const std::vector &data) +{ + std::ofstream stream(filename, std::ios::binary); + + writeFingerprint(stream); + + std::uint64_t count = data.size(); + stream.write(reinterpret_cast(&count), sizeof(count)); + if (!data.empty()) + stream.write(reinterpret_cast(&data[0]), sizeof(simple_type) * count); + return static_cast(stream); +} + +template +bool deserializeVector(const std::string &filename, std::vector &data) +{ + std::ifstream stream(filename, std::ios::binary); + + if (!readAndCheckFingerprint(stream)) + return false; + + std::uint64_t count = 0; + stream.read(reinterpret_cast(&count), sizeof(count)); + data.resize(count); + if (count) + stream.read(reinterpret_cast(&data[0]), sizeof(simple_type) * count); + return static_cast(stream); +} + +inline bool serializeFlags(const boost::filesystem::path &path, const std::vector &flags) +{ + // TODO this should be replaced with a FILE-based write using error checking + std::ofstream flag_stream(path.string(), std::ios::binary); + + writeFingerprint(flag_stream); + + std::uint32_t number_of_bits = flags.size(); + flag_stream.write(reinterpret_cast(&number_of_bits), sizeof(number_of_bits)); + // putting bits in ints + std::uint32_t chunk = 0; + std::size_t chunk_count = 0; + for (std::size_t bit_nr = 0; bit_nr < number_of_bits;) + { + std::bitset<32> chunk_bitset; + for (std::size_t chunk_bit = 0; chunk_bit < 32 && bit_nr < number_of_bits; + ++chunk_bit, ++bit_nr) + chunk_bitset[chunk_bit] = flags[bit_nr]; + + chunk = chunk_bitset.to_ulong(); + ++chunk_count; + flag_stream.write(reinterpret_cast(&chunk), sizeof(chunk)); + } + SimpleLogger().Write() << "Wrote " << number_of_bits << " bits in " << chunk_count + << " chunks (Flags)."; + return static_cast(flag_stream); +} + +inline bool deserializeFlags(const boost::filesystem::path &path, std::vector &flags) +{ + SimpleLogger().Write() << "Reading flags from " << path; + std::ifstream flag_stream(path.string(), std::ios::binary); + + if (!readAndCheckFingerprint(flag_stream)) + return false; + + std::uint32_t number_of_bits; + flag_stream.read(reinterpret_cast(&number_of_bits), sizeof(number_of_bits)); + flags.resize(number_of_bits); + // putting bits in ints + std::uint32_t chunks = (number_of_bits + 31) / 32; + std::size_t bit_position = 0; + std::uint32_t chunk; + for (std::size_t chunk_id = 0; chunk_id < chunks; ++chunk_id) + { + flag_stream.read(reinterpret_cast(&chunk), sizeof(chunk)); + std::bitset<32> chunk_bits(chunk); + for (std::size_t bit = 0; bit < 32 && bit_position < number_of_bits; ++bit, ++bit_position) + flags[bit_position] = chunk_bits[bit]; + } + SimpleLogger().Write() << "Read " << number_of_bits << " bits in " << chunks + << " Chunks from disk."; + return static_cast(flag_stream); +} +} // namespace util +} // namespace osrm + +#endif // OSRM_INCLUDE_UTIL_IO_HPP_ diff --git a/src/contractor/processing_chain.cpp b/src/contractor/processing_chain.cpp index 30402bfa2..a28f347a1 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/processing_chain.cpp @@ -7,6 +7,7 @@ #include "contractor/crc32_processor.hpp" #include "util/graph_loader.hpp" +#include "util/io.hpp" #include "util/integer_range.hpp" #include "util/lua_util.hpp" #include "util/osrm_exception.hpp" @@ -22,6 +23,9 @@ #include +#include +#include +#include #include #include #include @@ -73,7 +77,7 @@ int Prepare::Run() util::DeallocatingVector edge_based_edge_list; - size_t max_edge_id = LoadEdgeExpandedGraph( + std::size_t max_edge_id = LoadEdgeExpandedGraph( config.edge_based_graph_path, edge_based_edge_list, config.edge_segment_lookup_path, config.edge_penalty_path, config.segment_speed_lookup_path); @@ -86,9 +90,18 @@ int Prepare::Run() { ReadNodeLevels(node_levels); } + + util::SimpleLogger().Write() << "Reading node weights."; + std::vector node_weights; + std::string node_file_name = config.osrm_input_path.string() + ".enw"; + if (util::deserializeVector(node_file_name, node_weights)) + util::SimpleLogger().Write() << "Done reading node weights."; + else + util::SimpleLogger().Write() << "Failed reading node weights."; + util::DeallocatingVector contracted_edge_list; - ContractGraph(max_edge_id, edge_based_edge_list, contracted_edge_list, is_core_node, - node_levels); + ContractGraph(max_edge_id, edge_based_edge_list, contracted_edge_list, std::move(node_weights), + is_core_node, node_levels); TIMER_STOP(contraction); util::SimpleLogger().Write() << "Contraction took " << TIMER_SEC(contraction) << " sec"; @@ -143,10 +156,12 @@ std::size_t Prepare::LoadEdgeExpandedGraph( input_stream.read((char *)&fingerprint_loaded, sizeof(util::FingerPrint)); fingerprint_loaded.TestPrepare(fingerprint_valid); - size_t number_of_edges = 0; - size_t max_edge_id = SPECIAL_EDGEID; - input_stream.read((char *)&number_of_edges, sizeof(size_t)); - input_stream.read((char *)&max_edge_id, sizeof(size_t)); + // TODO std::size_t can vary on systems. Our files are not transferable, but we might want to + // consider using a fixed size type for I/O + std::size_t number_of_edges = 0; + std::size_t max_edge_id = SPECIAL_EDGEID; + input_stream.read((char *)&number_of_edges, sizeof(std::size_t)); + input_stream.read((char *)&max_edge_id, sizeof(std::size_t)); edge_based_edge_list.resize(number_of_edges); util::SimpleLogger().Write() << "Reading " << number_of_edges @@ -179,7 +194,6 @@ std::size_t Prepare::LoadEdgeExpandedGraph( { extractor::EdgeBasedEdge inbuffer; input_stream.read((char *)&inbuffer, sizeof(extractor::EdgeBasedEdge)); - if (update_edge_weights) { // Processing-time edge updates @@ -370,8 +384,11 @@ Prepare::WriteContractedGraph(unsigned max_node_id, util::StaticGraph::EdgeArrayEntry current_edge; for (const auto edge : util::irange(0, contracted_edge_list.size())) { + // some self-loops are required for oneway handling. Need to assertthat we only keep these + // (TODO) // no eigen loops - BOOST_ASSERT(contracted_edge_list[edge].source != contracted_edge_list[edge].target); + // BOOST_ASSERT(contracted_edge_list[edge].source != contracted_edge_list[edge].target || + // node_represents_oneway[contracted_edge_list[edge].source]); current_edge.target = contracted_edge_list[edge].target; current_edge.data = contracted_edge_list[edge].data; @@ -407,17 +424,22 @@ void Prepare::ContractGraph( const unsigned max_edge_id, util::DeallocatingVector &edge_based_edge_list, util::DeallocatingVector &contracted_edge_list, + std::vector &&node_weights, std::vector &is_core_node, std::vector &inout_node_levels) const { std::vector node_levels; node_levels.swap(inout_node_levels); - Contractor contractor(max_edge_id + 1, edge_based_edge_list, std::move(node_levels)); + Contractor contractor(max_edge_id + 1, edge_based_edge_list, std::move(node_levels), + std::move(node_weights)); contractor.Run(config.core_factor); contractor.GetEdges(contracted_edge_list); contractor.GetCoreMarker(is_core_node); contractor.GetNodeLevels(inout_node_levels); + + std::cout << "Levels: " << inout_node_levels.size() << " Core: " << is_core_node.size() + << " MEID: " << max_edge_id << std::endl; } } } diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index f71544b17..a6585b0f9 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -67,6 +67,12 @@ void EdgeBasedGraphFactory::GetStartPointMarkers(std::vector &node_is_star swap(m_edge_based_node_is_startpoint, node_is_startpoint); } +void EdgeBasedGraphFactory::GetEdgeBasedNodeWeights(std::vector &output_node_weights) +{ + using std::swap; // Koenig swap + swap(m_edge_based_node_weights, output_node_weights); +} + unsigned EdgeBasedGraphFactory::GetHighestEdgeID() { return m_max_edge_id; } void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeID node_v) @@ -92,6 +98,9 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeI return; } + if (forward_data.edge_id != SPECIAL_NODEID && reverse_data.edge_id == SPECIAL_NODEID) + m_edge_based_node_weights[forward_data.edge_id] = INVALID_EDGE_WEIGHT; + BOOST_ASSERT(m_compressed_edge_container.HasEntryForID(edge_id_1) == m_compressed_edge_container.HasEntryForID(edge_id_2)); if (m_compressed_edge_container.HasEntryForID(edge_id_1)) @@ -231,6 +240,7 @@ void EdgeBasedGraphFactory::Run(const std::string &original_edge_data_filename, TIMER_STOP(renumber); TIMER_START(generate_nodes); + m_edge_based_node_weights.reserve(m_max_edge_id + 1); GenerateEdgeExpandedNodes(); TIMER_STOP(generate_nodes); @@ -270,6 +280,11 @@ unsigned EdgeBasedGraphFactory::RenumberEdges() continue; } + // oneway streets always require this self-loop. Other streets only if a u-turn plus + // traversal + // of the street takes longer than the loop + m_edge_based_node_weights.push_back(edge_data.distance + speed_profile.u_turn_penalty); + BOOST_ASSERT(numbered_edges_count < m_node_based_graph->GetNumberOfEdges()); edge_data.edge_id = numbered_edges_count; ++numbered_edges_count; @@ -321,6 +336,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() } BOOST_ASSERT(m_edge_based_node_list.size() == m_edge_based_node_is_startpoint.size()); + BOOST_ASSERT(m_max_edge_id+1 == m_edge_based_node_weights.size()); util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " nodes in edge-expanded graph"; diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index ddf787c35..cdd7ced41 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -9,6 +9,7 @@ #include "extractor/scripting_environment.hpp" #include "extractor/raster_source.hpp" +#include "util/io.hpp" #include "util/make_unique.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" @@ -46,6 +47,7 @@ #include #include #include +#include namespace osrm { @@ -71,7 +73,7 @@ namespace extractor * graph * */ -int extractor::run() +int Extractor::run() { try { @@ -265,16 +267,25 @@ int extractor::run() std::vector node_based_edge_list; util::DeallocatingVector edge_based_edge_list; std::vector node_is_startpoint; + std::vector edge_based_node_weights; std::vector internal_to_external_node_map; - auto graph_size = - BuildEdgeExpandedGraph(internal_to_external_node_map, node_based_edge_list, - node_is_startpoint, edge_based_edge_list); + auto graph_size = BuildEdgeExpandedGraph(internal_to_external_node_map, + node_based_edge_list, node_is_startpoint, + edge_based_node_weights, edge_based_edge_list); auto number_of_node_based_nodes = graph_size.first; auto max_edge_id = graph_size.second; TIMER_STOP(expansion); + util::SimpleLogger().Write() << "Saving edge-based node weights to file."; + TIMER_START(timer_write_node_weights); + util::serializeVector(config.edge_based_node_weights_output_path, + edge_based_node_weights); + TIMER_STOP(timer_write_node_weights); + util::SimpleLogger().Write() << "Done writing. (" << TIMER_SEC(timer_write_node_weights) + << ")"; + util::SimpleLogger().Write() << "building r-tree ..."; TIMER_START(rtree); @@ -309,7 +320,7 @@ int extractor::run() \brief Setups scripting environment (lua-scripting) Also initializes speed profile. */ -void extractor::SetupScriptingEnvironment(lua_State *lua_state, +void Extractor::SetupScriptingEnvironment(lua_State *lua_state, SpeedProfileProperties &speed_profile) { // open utility libraries string library; @@ -347,7 +358,7 @@ void extractor::SetupScriptingEnvironment(lua_State *lua_state, speed_profile.has_turn_penalty_function = util::lua_function_exists(lua_state, "turn_function"); } -void extractor::FindComponents(unsigned max_edge_id, +void Extractor::FindComponents(unsigned max_edge_id, const util::DeallocatingVector &input_edge_list, std::vector &input_nodes) const { @@ -425,7 +436,7 @@ void extractor::FindComponents(unsigned max_edge_id, /** \brief Build load restrictions from .restriction file */ -std::shared_ptr extractor::LoadRestrictionMap() +std::shared_ptr Extractor::LoadRestrictionMap() { boost::filesystem::ifstream input_stream(config.restriction_file_name, std::ios::in | std::ios::binary); @@ -442,7 +453,7 @@ std::shared_ptr extractor::LoadRestrictionMap() \brief Load node based graph from .osrm file */ std::shared_ptr -extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, +Extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, std::unordered_set &traffic_lights, std::vector &internal_to_external_node_map) { @@ -483,9 +494,10 @@ extractor::LoadNodeBasedGraph(std::unordered_set &barrier_nodes, \brief Building an edge-expanded graph from node-based input and turn restrictions */ std::pair -extractor::BuildEdgeExpandedGraph(std::vector &internal_to_external_node_map, +Extractor::BuildEdgeExpandedGraph(std::vector &internal_to_external_node_map, std::vector &node_based_edge_list, std::vector &node_is_startpoint, + std::vector &edge_based_node_weights, util::DeallocatingVector &edge_based_edge_list) { lua_State *lua_state = luaL_newstate(); @@ -526,6 +538,7 @@ extractor::BuildEdgeExpandedGraph(std::vector &internal_to_external_n edge_based_graph_factory.GetEdgeBasedEdges(edge_based_edge_list); edge_based_graph_factory.GetEdgeBasedNodes(node_based_edge_list); edge_based_graph_factory.GetStartPointMarkers(node_is_startpoint); + edge_based_graph_factory.GetEdgeBasedNodeWeights(edge_based_node_weights); auto max_edge_id = edge_based_graph_factory.GetHighestEdgeID(); const std::size_t number_of_node_based_nodes = node_based_graph->GetNumberOfNodes(); @@ -535,7 +548,7 @@ extractor::BuildEdgeExpandedGraph(std::vector &internal_to_external_n /** \brief Writing info on original (node-based) nodes */ -void extractor::WriteNodeMapping(const std::vector &internal_to_external_node_map) +void Extractor::WriteNodeMapping(const std::vector &internal_to_external_node_map) { boost::filesystem::ofstream node_stream(config.node_output_path, std::ios::binary); const unsigned size_of_mapping = internal_to_external_node_map.size(); @@ -553,7 +566,7 @@ void extractor::WriteNodeMapping(const std::vector &internal_to_exter Saves tree into '.ramIndex' and leaves into '.fileIndex'. */ -void extractor::BuildRTree(std::vector node_based_edge_list, +void Extractor::BuildRTree(std::vector node_based_edge_list, std::vector node_is_startpoint, const std::vector &internal_to_external_node_map) { @@ -589,7 +602,7 @@ void extractor::BuildRTree(std::vector node_based_edge_list, << " seconds"; } -void extractor::WriteEdgeBasedGraph( +void Extractor::WriteEdgeBasedGraph( std::string const &output_file_filename, size_t const max_edge_id, util::DeallocatingVector const &edge_based_edge_list) @@ -600,7 +613,8 @@ void extractor::WriteEdgeBasedGraph( const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); file_out_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); - std::cout << "[extractor] Writing edge-based-graph egdes ... " << std::flush; + util::SimpleLogger().Write() << "[extractor] Writing edge-based-graph egdes ... " + << std::flush; TIMER_START(write_edges); size_t number_of_used_edges = edge_based_edge_list.size(); @@ -613,7 +627,7 @@ void extractor::WriteEdgeBasedGraph( } TIMER_STOP(write_edges); - std::cout << "ok, after " << TIMER_SEC(write_edges) << "s" << std::endl; + util::SimpleLogger().Write() << "ok, after " << TIMER_SEC(write_edges) << "s" << std::endl; util::SimpleLogger().Write() << "Processed " << number_of_used_edges << " edges"; file_out_stream.close(); diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp index 12081266c..7c985714f 100644 --- a/src/extractor/extractor_options.cpp +++ b/src/extractor/extractor_options.cpp @@ -142,6 +142,7 @@ void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_confi extractor_config.geometry_output_path = input_path.string(); extractor_config.edge_output_path = input_path.string(); extractor_config.edge_graph_output_path = input_path.string(); + extractor_config.edge_based_node_weights_output_path = input_path.string(); extractor_config.node_output_path = input_path.string(); extractor_config.rtree_nodes_output_path = input_path.string(); extractor_config.rtree_leafs_output_path = input_path.string(); @@ -173,6 +174,7 @@ void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_confi extractor_config.node_output_path.append(".osrm.nodes"); extractor_config.edge_output_path.append(".osrm.edges"); extractor_config.edge_graph_output_path.append(".osrm.ebg"); + extractor_config.edge_based_node_weights_output_path.append(".osrm.enw"); extractor_config.rtree_nodes_output_path.append(".osrm.ramIndex"); extractor_config.rtree_leafs_output_path.append(".osrm.fileIndex"); extractor_config.edge_segment_lookup_path.append(".osrm.edge_segment_lookup"); @@ -188,6 +190,7 @@ void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_confi extractor_config.node_output_path.replace(pos, 5, ".osrm.nodes"); extractor_config.edge_output_path.replace(pos, 5, ".osrm.edges"); extractor_config.edge_graph_output_path.replace(pos, 5, ".osrm.ebg"); + extractor_config.edge_based_node_weights_output_path.replace(pos, 5, ".osrm.enw"); extractor_config.rtree_nodes_output_path.replace(pos, 5, ".osrm.ramIndex"); extractor_config.rtree_leafs_output_path.replace(pos, 5, ".osrm.fileIndex"); extractor_config.edge_segment_lookup_path.replace(pos, 5, ".osrm.edge_segment_lookup"); @@ -204,6 +207,7 @@ void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_confi extractor_config.node_output_path.replace(pos, 8, ".osrm.nodes"); extractor_config.edge_output_path.replace(pos, 8, ".osrm.edges"); extractor_config.edge_graph_output_path.replace(pos, 8, ".osrm.ebg"); + extractor_config.edge_based_node_weights_output_path.replace(pos, 8, ".osrm.enw"); extractor_config.rtree_nodes_output_path.replace(pos, 8, ".osrm.ramIndex"); extractor_config.rtree_leafs_output_path.replace(pos, 8, ".osrm.fileIndex"); extractor_config.edge_segment_lookup_path.replace(pos, 8, ".osrm.edge_segment_lookup"); diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index a4edf8ba0..7f27fbc8d 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -49,7 +49,7 @@ int main(int argc, char *argv[]) try << "Profile " << extractor_config.profile_path.string() << " not found!"; return EXIT_FAILURE; } - return extractor::extractor(extractor_config).run(); + return extractor::Extractor(extractor_config).run(); } catch (const std::bad_alloc &e) { diff --git a/unit_tests/io/io.cpp b/unit_tests/io/io.cpp new file mode 100644 index 000000000..75aed5bc1 --- /dev/null +++ b/unit_tests/io/io.cpp @@ -0,0 +1,43 @@ +#include "util/io.hpp" +#include "util/typedefs.hpp" + +#include +#include + +#include + +const static std::string IO_TMP_FILE = "test_io.tmp"; + +BOOST_AUTO_TEST_SUITE(osrm_io) + +BOOST_AUTO_TEST_CASE(io_flags) +{ + std::vector flags_in, flags_out; + flags_in.resize(53); + for (std::size_t i = 0; i < flags_in.size(); ++i) + flags_in[i] = ((i % 2) == 1); + + osrm::util::serializeFlags(IO_TMP_FILE, flags_in); + osrm::util::deserializeFlags(IO_TMP_FILE, flags_out); + + BOOST_REQUIRE_EQUAL(flags_in.size(), flags_out.size()); + BOOST_CHECK_EQUAL_COLLECTIONS(flags_out.begin(), flags_out.end(), flags_in.begin(), + flags_in.end()); +} + +BOOST_AUTO_TEST_CASE(io_data) +{ + std::vector data_in, data_out; + data_in.resize(53); + for (std::size_t i = 0; i < data_in.size(); ++i) + data_in[i] = i; + + osrm::util::serializeVector(IO_TMP_FILE, data_in); + osrm::util::deserializeVector(IO_TMP_FILE, data_out); + + BOOST_REQUIRE_EQUAL(data_in.size(), data_out.size()); + BOOST_CHECK_EQUAL_COLLECTIONS(data_out.begin(), data_out.end(), data_in.begin(), + data_in.end()); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/unit_tests/io_tests.cpp b/unit_tests/io_tests.cpp new file mode 100644 index 000000000..4b0d83b56 --- /dev/null +++ b/unit_tests/io_tests.cpp @@ -0,0 +1,7 @@ +#define BOOST_TEST_MODULE io tests + +#include + +/* + * This file will contain an automatically generated main function. + */ From b36145e3c423a579800ca14da2a3c3ef9f7195ef Mon Sep 17 00:00:00 2001 From: karenzshea Date: Tue, 19 Jan 2016 16:43:33 -0500 Subject: [PATCH 094/701] add target test --- unit_tests/util/static_graph.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/unit_tests/util/static_graph.cpp b/unit_tests/util/static_graph.cpp index 7f6c6ab4c..1e6721489 100644 --- a/unit_tests/util/static_graph.cpp +++ b/unit_tests/util/static_graph.cpp @@ -94,6 +94,16 @@ BOOST_FIXTURE_TEST_CASE(array_test, TestRandomArrayEntryFixture) } } +BOOST_AUTO_TEST_CASE(target_test) +{ + std::vector input_edges = { + TestInputEdge{0, 1, TestData{1}}, TestInputEdge{3, 0, TestData{2}}}; + TestStaticGraph simple_graph = TestStaticGraph(4, input_edges); + + auto target = simple_graph.GetTarget(simple_graph.FindEdge(3, 0)); + BOOST_CHECK_EQUAL(target, 0); +} + BOOST_AUTO_TEST_CASE(find_test) { /* From 439eb9da3df2066c5e2f86eabb926234be2b83a9 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 7 Jan 2016 19:19:55 +0100 Subject: [PATCH 095/701] Create public facing libraries for extractor, contractor and datastore New libraries libosrm_extract, libosrm_contract, libosrm_store --- .travis.yml | 12 +- CMakeLists.txt | 197 ++- cmake/pkgconfig.in | 4 +- example/CMakeLists.txt | 33 + example/cmake/FindLibOSRM.cmake | 65 + example/cmake/FindTBB.cmake | 283 ++++ example/example.cpp | 63 + include/contractor/contractor.hpp | 1184 +---------------- ...ctor_options.hpp => contractor_config.hpp} | 25 +- include/contractor/graph_contractor.hpp | 1104 +++++++++++++++ include/contractor/processing_chain.hpp | 73 - .../engine/datafacade/shared_datafacade.hpp | 113 +- include/engine/{osrm_impl.hpp => engine.hpp} | 21 +- .../engine_config.hpp} | 11 +- include/engine/phantom_node.hpp | 72 +- include/engine/plugins/distance_table.hpp | 6 +- include/engine/plugins/trip.hpp | 4 +- include/engine/plugins/viaroute.hpp | 8 +- include/engine/route_parameters.hpp | 125 ++ include/extractor/external_memory_node.hpp | 27 +- include/extractor/extractor.hpp | 2 +- include/extractor/extractor_config.hpp | 78 ++ include/extractor/extractor_options.hpp | 63 - include/osrm/coordinate.hpp | 71 +- include/osrm/engine_config.hpp | 12 + include/osrm/json_container.hpp | 110 +- include/osrm/osrm.hpp | 17 +- include/osrm/route_parameters.hpp | 126 +- include/server/request_handler.hpp | 6 +- .../shared_barriers.hpp | 6 +- .../shared_datatype.hpp | 45 +- .../shared_memory.hpp} | 70 +- include/storage/storage.hpp | 25 + include/util/coordinate.hpp | 71 + include/util/debug_geometry.hpp | 2 +- include/util/fingerprint.hpp | 2 +- include/util/fingerprint_impl.hpp.in | 2 +- include/util/graph_loader.hpp | 4 +- include/util/io.hpp | 2 +- include/util/json_container.hpp | 102 ++ include/util/range_table.hpp | 1 - include/util/static_rtree.hpp | 1 - include/{osrm => util}/strong_typedef.hpp | 31 +- include/util/typedefs.hpp | 2 +- .../{processing_chain.cpp => contractor.cpp} | 33 +- src/contractor/contractor_options.cpp | 128 -- src/engine/{osrm_impl.cpp => engine.cpp} | 48 +- src/engine/phantom_node.cpp | 83 -- src/engine/route_parameters.cpp | 3 +- src/extractor/external_memory_node.cpp | 46 - src/extractor/extractor_options.cpp | 218 --- src/osrm/osrm.cpp | 22 + src/server/request_handler.cpp | 4 +- .../datastore.cpp => storage/storage.cpp} | 120 +- src/tools/check-hsgr.cpp | 120 +- src/tools/components.cpp | 238 ++-- src/tools/contract.cpp | 125 +- src/tools/extract.cpp | 142 +- src/tools/io-benchmark.cpp | 468 ++++--- src/tools/routed.cpp | 18 +- src/tools/simpleclient.cpp | 69 - src/tools/springclean.cpp | 53 +- .../tools/store.cpp | 88 +- src/tools/unlock_all_mutexes.cpp | 26 +- test/data/Makefile | 29 + test/data/data.md5sum | 1 + unit_tests/io_tests.cpp | 7 - unit_tests/{io => util}/io.cpp | 0 68 files changed, 3266 insertions(+), 3104 deletions(-) create mode 100644 example/CMakeLists.txt create mode 100644 example/cmake/FindLibOSRM.cmake create mode 100644 example/cmake/FindTBB.cmake create mode 100644 example/example.cpp rename include/contractor/{contractor_options.hpp => contractor_config.hpp} (68%) create mode 100644 include/contractor/graph_contractor.hpp delete mode 100644 include/contractor/processing_chain.hpp rename include/engine/{osrm_impl.hpp => engine.hpp} (81%) rename include/{osrm/libosrm_config.hpp => engine/engine_config.hpp} (94%) create mode 100644 include/engine/route_parameters.hpp create mode 100644 include/extractor/extractor_config.hpp delete mode 100644 include/extractor/extractor_options.hpp create mode 100644 include/osrm/engine_config.hpp rename include/{engine/datafacade => storage}/shared_barriers.hpp (96%) rename include/{engine/datafacade => storage}/shared_datatype.hpp (53%) rename include/{datastore/shared_memory_factory.hpp => storage/shared_memory.hpp} (85%) create mode 100644 include/storage/storage.hpp create mode 100644 include/util/coordinate.hpp create mode 100644 include/util/json_container.hpp rename include/{osrm => util}/strong_typedef.hpp (69%) rename src/contractor/{processing_chain.cpp => contractor.cpp} (94%) delete mode 100644 src/contractor/contractor_options.cpp rename src/engine/{osrm_impl.cpp => engine.cpp} (75%) delete mode 100644 src/engine/phantom_node.cpp delete mode 100644 src/extractor/external_memory_node.cpp delete mode 100644 src/extractor/extractor_options.cpp create mode 100644 src/osrm/osrm.cpp rename src/{tools/datastore.cpp => storage/storage.cpp} (86%) delete mode 100644 src/tools/simpleclient.cpp rename include/util/datastore_options.hpp => src/tools/store.cpp (80%) create mode 100755 test/data/Makefile create mode 100644 test/data/data.md5sum delete mode 100644 unit_tests/io_tests.cpp rename unit_tests/{io => util}/io.cpp (100%) diff --git a/.travis.yml b/.travis.yml index d5a186008..da116e2ac 100644 --- a/.travis.yml +++ b/.travis.yml @@ -118,7 +118,7 @@ install: export PATH=${DEPS_DIR}/cmake/bin:${PATH} elif [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then - brew install cmake boost libzip libstxxl libxml2 lua51 luabind tbb GDAL + brew install cmake boost libzip libstxxl libxml2 lua51 luabind tbb GDAL md5sha1sum fi before_script: @@ -135,8 +135,18 @@ script: - make --jobs=2 - make tests --jobs=2 - make benchmarks + - sudo make install + - | + if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then + sudo ldconfig + fi - ./extractor-tests - ./engine-tests - ./util-tests - cd .. - cucumber -p verify + - make -C test/data + - mkdir example/build && cd example/build + - cmake .. + - make + - ./osrm-example ../../test/data/berlin-latest.osrm diff --git a/CMakeLists.txt b/CMakeLists.txt index 763842cf8..b07b94b53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,7 +44,7 @@ add_custom_target(FingerPrintConfigure ALL ${CMAKE_COMMAND} COMMENT "Configuring revision fingerprint" VERBATIM) -add_custom_target(tests DEPENDS engine-tests extractor-tests util-tests io-tests) +add_custom_target(tests DEPENDS engine-tests extractor-tests util-tests) add_custom_target(benchmarks DEPENDS rtree-bench) set(BOOST_COMPONENTS date_time filesystem iostreams program_options regex system thread unit_test_framework) @@ -56,6 +56,7 @@ configure_file( file(GLOB UtilGlob src/util/*.cpp) file(GLOB ExtractorGlob src/extractor/*.cpp) file(GLOB ContractorGlob src/contractor/*.cpp) +file(GLOB StorageGlob src/storage/*.cpp) file(GLOB ServerGlob src/server/*.cpp src/server/**/*.cpp) file(GLOB EngineGlob src/engine/*.cpp src/engine/**/*.cpp) file(GLOB ExtractorTestsGlob unit_tests/extractor/*.cpp) @@ -66,30 +67,29 @@ file(GLOB IOTestsGlob unit_tests/io/*.cpp) add_library(UTIL OBJECT ${UtilGlob}) add_library(EXTRACTOR OBJECT ${ExtractorGlob}) add_library(CONTRACTOR OBJECT ${ContractorGlob}) +add_library(STORAGE OBJECT ${StorageGlob}) add_library(ENGINE OBJECT ${EngineGlob}) add_library(SERVER OBJECT ${ServerGlob}) -add_library(GRAPH OBJECT src/extractor/external_memory_node.cpp) -add_library(PHANTOM OBJECT src/engine/phantom_node.cpp) add_dependencies(UTIL FingerPrintConfigure) set_target_properties(UTIL PROPERTIES LINKER_LANGUAGE CXX) -add_executable(osrm-extract src/tools/extract.cpp $ $) -add_executable(osrm-prepare src/tools/contract.cpp $ $ $) -add_executable(osrm-routed src/tools/routed.cpp $ $ $) -add_executable(osrm-datastore src/tools/datastore.cpp $ $) -add_library(OSRM $ $ $) - -target_link_libraries(osrm-routed OSRM) +add_executable(osrm-extract src/tools/extract.cpp) +add_executable(osrm-prepare src/tools/contract.cpp) +add_executable(osrm-routed src/tools/routed.cpp $ $) +add_executable(osrm-datastore src/tools/store.cpp $) +add_library(osrm src/osrm/osrm.cpp $ $) +add_library(osrm_extract $ $) +add_library(osrm_contract $ $) +add_library(osrm_store $ $) # Unit tests -add_executable(engine-tests EXCLUDE_FROM_ALL unit_tests/engine_tests.cpp ${EngineTestsGlob} $ $ $) +add_executable(engine-tests EXCLUDE_FROM_ALL unit_tests/engine_tests.cpp ${EngineTestsGlob} $ $) add_executable(extractor-tests EXCLUDE_FROM_ALL unit_tests/extractor_tests.cpp ${ExtractorTestsGlob} $ $) -add_executable(util-tests EXCLUDE_FROM_ALL unit_tests/util_tests.cpp ${UtilTestsGlob} $ $) -add_executable(io-tests EXCLUDE_FROM_ALL unit_tests/io_tests.cpp ${IOTestsGlob} $) +add_executable(util-tests EXCLUDE_FROM_ALL unit_tests/util_tests.cpp ${UtilTestsGlob} $) # Benchmarks -add_executable(rtree-bench EXCLUDE_FROM_ALL src/benchmarks/static_rtree.cpp $ $) +add_executable(rtree-bench EXCLUDE_FROM_ALL src/benchmarks/static_rtree.cpp $) # Check the release mode if(NOT CMAKE_BUILD_TYPE MATCHES Debug) @@ -221,10 +221,7 @@ if(APPLE) endif() if(UNIX AND NOT APPLE) - target_link_libraries(osrm-prepare rt) - target_link_libraries(osrm-datastore rt) - target_link_libraries(OSRM rt) - target_link_libraries(engine-tests rt) + set(MAYBE_RT_LIBRARY rt) endif() list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/third_party/libosmium/cmake") @@ -232,8 +229,6 @@ set(OSMIUM_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/third_party/libosmium/includ find_package(Osmium REQUIRED COMPONENTS io) include_directories(SYSTEM ${OSMIUM_INCLUDE_DIRS}) -target_link_libraries(osrm-extract ${OSMIUM_LIBRARIES}) -target_link_libraries(extractor-tests ${OSMIUM_LIBRARIES}) find_package(Boost 1.49.0 COMPONENTS ${BOOST_COMPONENTS} REQUIRED) if(NOT Boost_FOUND) @@ -241,72 +236,29 @@ if(NOT Boost_FOUND) endif() include_directories(SYSTEM ${Boost_INCLUDE_DIRS}) -target_link_libraries(OSRM ${Boost_LIBRARIES}) -target_link_libraries(osrm-extract ${Boost_LIBRARIES}) -target_link_libraries(osrm-prepare ${Boost_LIBRARIES}) -target_link_libraries(osrm-routed ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM) -target_link_libraries(osrm-datastore ${Boost_LIBRARIES}) -target_link_libraries(engine-tests ${Boost_LIBRARIES}) -target_link_libraries(extractor-tests ${Boost_LIBRARIES}) -target_link_libraries(util-tests ${Boost_LIBRARIES}) -target_link_libraries(rtree-bench ${Boost_LIBRARIES}) -target_link_libraries(io-tests ${Boost_LIBRARIES}) - find_package(Threads REQUIRED) -target_link_libraries(osrm-extract ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(osrm-datastore ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(osrm-prepare ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(OSRM ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(engine-tests ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(extractor-tests ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(util-tests ${CMAKE_THREAD_LIBS_INIT}) -target_link_libraries(rtree-bench ${CMAKE_THREAD_LIBS_INIT}) find_package(TBB REQUIRED) +include_directories(SYSTEM ${TBB_INCLUDE_DIR}) if(WIN32 AND CMAKE_BUILD_TYPE MATCHES Debug) set(TBB_LIBRARIES ${TBB_DEBUG_LIBRARIES}) endif() -target_link_libraries(osrm-datastore ${TBB_LIBRARIES}) -target_link_libraries(osrm-extract ${TBB_LIBRARIES}) -target_link_libraries(osrm-prepare ${TBB_LIBRARIES}) -target_link_libraries(osrm-routed ${TBB_LIBRARIES}) -target_link_libraries(engine-tests ${TBB_LIBRARIES}) -target_link_libraries(extractor-tests ${TBB_LIBRARIES}) -target_link_libraries(util-tests ${TBB_LIBRARIES}) -target_link_libraries(rtree-bench ${TBB_LIBRARIES}) -include_directories(SYSTEM ${TBB_INCLUDE_DIR}) find_package( Luabind REQUIRED ) include(check_luabind) - include_directories(SYSTEM ${LUABIND_INCLUDE_DIR}) -target_link_libraries(osrm-extract ${LUABIND_LIBRARY}) -target_link_libraries(osrm-prepare ${LUABIND_LIBRARY}) -target_link_libraries(extractor-tests ${LUABIND_LIBRARY}) +set(USED_LUA_LIBRARIES ${LUA_LIBRARY}) if(LUAJIT_FOUND) - target_link_libraries(osrm-extract ${LUAJIT_LIBRARIES}) - target_link_libraries(osrm-prepare ${LUAJIT_LIBRARIES}) - target_link_libraries(extractor-tests ${LUAJIT_LIBRARY}) -else() - target_link_libraries(osrm-extract ${LUA_LIBRARY}) - target_link_libraries(osrm-prepare ${LUA_LIBRARY}) - target_link_libraries(extractor-tests ${LUA_LIBRARY}) + set(USED_LUA_LIBRARIES, LUAJIT_LIBRARIES) endif() include_directories(SYSTEM ${LUA_INCLUDE_DIR}) find_package(EXPAT REQUIRED) include_directories(SYSTEM ${EXPAT_INCLUDE_DIRS}) -target_link_libraries(osrm-extract ${EXPAT_LIBRARIES}) -target_link_libraries(extractor-tests ${EXPAT_LIBRARY}) find_package(STXXL REQUIRED) include_directories(SYSTEM ${STXXL_INCLUDE_DIR}) -target_link_libraries(OSRM ${STXXL_LIBRARY}) -target_link_libraries(osrm-extract ${STXXL_LIBRARY}) -target_link_libraries(osrm-prepare ${STXXL_LIBRARY}) -target_link_libraries(extractor-tests ${STXXL_LIBRARY}) -target_link_libraries(util-tests ${STXXL_LIBRARY}) set(OpenMP_FIND_QUIETLY ON) find_package(OpenMP) @@ -317,14 +269,9 @@ endif() find_package(BZip2 REQUIRED) include_directories(SYSTEM ${BZIP_INCLUDE_DIRS}) -target_link_libraries(osrm-extract ${BZIP2_LIBRARIES}) -target_link_libraries(extractor-tests ${BZIP2_LIBRARIES}) find_package(ZLIB REQUIRED) include_directories(SYSTEM ${ZLIB_INCLUDE_DIRS}) -target_link_libraries(osrm-extract ${ZLIB_LIBRARY}) -target_link_libraries(osrm-routed ${ZLIB_LIBRARY}) -target_link_libraries(extractor-tests ${ZLIB_LIBRARY}) if (ENABLE_JSON_LOGGING) message(STATUS "Enabling json logging") @@ -336,21 +283,71 @@ if (DEBUG_GEOMETRY) add_definitions(-DDEBUG_GEOMETRY) endif() + +# Binaries +target_link_libraries(osrm-datastore osrm_store ${Boost_LIBRARIES}) +target_link_libraries(osrm-extract osrm_extract ${Boost_LIBRARIES}) +target_link_libraries(osrm-prepare osrm_contract ${Boost_LIBRARIES}) +target_link_libraries(osrm-routed osrm ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} ${ZLIB_LIBRARY}) + +set(EXTRACTOR_LIBRARIES + ${BZIP2_LIBRARIES} + ${Boost_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + ${EXPAT_LIBRARIES} + ${LUABIND_LIBRARY} + ${USED_LUA_LIBRARIES} + ${OSMIUM_LIBRARIES} + ${STXXL_LIBRARY} + ${TBB_LIBRARIES} + ${ZLIB_LIBRARY}) +set(CONTRACTOR_LIBRARIES + ${Boost_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + ${LUABIND_LIBRARY} + ${USED_LUA_LIBRARIES} + ${STXXL_LIBRARY} + ${TBB_LIBRARIES} + ${MAYBE_RT_LIBRARY}) +set(ENGINE_LIBRARIES + ${Boost_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + ${STXXL_LIBRARY} + ${TBB_LIBRARIES} + ${MAYBE_RT_LIBRARY}) +set(STORAGE_LIBRARIES + ${Boost_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + ${TBB_LIBRARIES} + ${MAYBE_RT_LIBRARY}) +set(UTIL_LIBRARIES + ${Boost_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + ${STXXL_LIBRARY} + ${TBB_LIBRARIES}) +# Libraries +target_link_libraries(osrm ${ENGINE_LIBRARIES}) +target_link_libraries(osrm_contract ${CONTRACTOR_LIBRARIES}) +target_link_libraries(osrm_extract ${EXTRACTOR_LIBRARIES}) +target_link_libraries(osrm_store ${STORAGE_LIBRARIES}) +# Tests +target_link_libraries(engine-tests ${ENGINE_LIBRARIES}) +target_link_libraries(extractor-tests ${EXTRACTOR_LIBRARIES}) +target_link_libraries(rtree-bench ${Boost_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} ${TBB_LIBRARIES}) +target_link_libraries(util-tests ${UTIL_LIBRARIES}) + if(BUILD_TOOLS) message(STATUS "Activating OSRM internal tools") find_package(GDAL) if(GDAL_FOUND) - add_executable(osrm-components src/tools/components.cpp $ $) + add_executable(osrm-components src/tools/components.cpp $) target_link_libraries(osrm-components ${TBB_LIBRARIES}) include_directories(SYSTEM ${GDAL_INCLUDE_DIR}) target_link_libraries(osrm-components ${GDAL_LIBRARIES} ${Boost_LIBRARIES}) install(TARGETS osrm-components DESTINATION bin) else() - message(FATAL_ERROR "libgdal and/or development headers not found") + message(WARNING "libgdal and/or development headers not found") endif() - add_executable(osrm-cli src/tools/simpleclient.cpp) - target_link_libraries(osrm-cli ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} OSRM) - target_link_libraries(osrm-cli ${TBB_LIBRARIES}) add_executable(osrm-io-benchmark src/tools/io-benchmark.cpp $) target_link_libraries(osrm-io-benchmark ${Boost_LIBRARIES}) add_executable(osrm-unlock-all src/tools/unlock_all_mutexes.cpp $) @@ -358,21 +355,17 @@ if(BUILD_TOOLS) if(UNIX AND NOT APPLE) target_link_libraries(osrm-unlock-all rt) endif() - add_executable(osrm-check-hsgr src/tools/check-hsgr.cpp $ $) + add_executable(osrm-check-hsgr src/tools/check-hsgr.cpp $) target_link_libraries(osrm-check-hsgr ${Boost_LIBRARIES} ${TBB_LIBRARIES}) - add_executable(osrm-springclean src/tools/springclean.cpp $ $) + add_executable(osrm-springclean src/tools/springclean.cpp $) target_link_libraries(osrm-springclean ${Boost_LIBRARIES}) - install(TARGETS osrm-cli DESTINATION bin) install(TARGETS osrm-io-benchmark DESTINATION bin) install(TARGETS osrm-unlock-all DESTINATION bin) install(TARGETS osrm-check-hsgr DESTINATION bin) install(TARGETS osrm-springclean DESTINATION bin) endif() -file(GLOB InstallGlob include/osrm/*.hpp) -file(GLOB VariantGlob third_party/variant/*.hpp) - # Add RPATH info to executables so that when they are run after being installed # (i.e., from /usr/local/bin/) the linker can find library dependencies. For # more info see http://www.cmake.org/Wiki/CMake_RPATH_handling @@ -381,29 +374,35 @@ set_property(TARGET osrm-prepare PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) set_property(TARGET osrm-datastore PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) set_property(TARGET osrm-routed PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) -install(FILES ${InstallGlob} DESTINATION include/osrm) +file(GLOB VariantGlob third_party/variant/*.hpp) +file(GLOB LibraryGlob include/osrm/*.hpp) +set(EngineHeader include/engine/engine.hpp include/engine/engine_config.hpp include/engine/route_parameters.hpp) +set(UtilHeader include/util/coordinate.hpp include/util/json_container.hpp) +set(ExtractorHeader include/extractor/extractor.hpp include/extractor/extractor_config.hpp) +set(ContractorHeader include/contractor/contractor.hpp include/contractor/contractor_config.hpp) +#set(StorageHeader include/storage/storage.hpp include/storage/storage_config.hpp) +install(FILES ${EngineHeader} DESTINATION include/osrm/engine) +install(FILES ${UtilHeader} DESTINATION include/osrm/util) +install(FILES ${ExtractorHeader} DESTINATION include/osrm/extractor) +install(FILES ${ContractorHeader} DESTINATION include/osrm/contractor) +install(FILES ${LibraryGlob} DESTINATION include/osrm) install(FILES ${VariantGlob} DESTINATION include/variant) install(TARGETS osrm-extract DESTINATION bin) install(TARGETS osrm-prepare DESTINATION bin) install(TARGETS osrm-datastore DESTINATION bin) install(TARGETS osrm-routed DESTINATION bin) -install(TARGETS OSRM DESTINATION lib) +install(TARGETS osrm DESTINATION lib) +install(TARGETS osrm_extract DESTINATION lib) +install(TARGETS osrm_contract DESTINATION lib) +install(TARGETS osrm_store DESTINATION lib) -list(GET Boost_LIBRARIES 1 BOOST_LIBRARY_FIRST) -get_filename_component(BOOST_LIBRARY_LISTING "${BOOST_LIBRARY_FIRST}" PATH) -set(BOOST_LIBRARY_LISTING "-L${BOOST_LIBRARY_LISTING}") -foreach(lib ${Boost_LIBRARIES}) - get_filename_component(BOOST_LIBRARY_NAME "${lib}" NAME_WE) - string(REPLACE "lib" "" BOOST_LIBRARY_NAME ${BOOST_LIBRARY_NAME}) - set(BOOST_LIBRARY_LISTING "${BOOST_LIBRARY_LISTING} -l${BOOST_LIBRARY_NAME}") -endforeach() -list(GET TBB_LIBRARIES 1 TBB_LIBRARY_FIRST) -get_filename_component(TBB_LIBRARY_LISTING "${TBB_LIBRARY_FIRST}" PATH) -set(TBB_LIBRARY_LISTING "-L${TBB_LIBRARY_LISTING}") -foreach(lib ${TBB_LIBRARIES}) - get_filename_component(TBB_LIBRARY_NAME "${lib}" NAME_WE) - string(REPLACE "lib" "" TBB_LIBRARY_NAME ${TBB_LIBRARY_NAME}) - set(TBB_LIBRARY_LISTING "${TBB_LIBRARY_LISTING} -l${TBB_LIBRARY_NAME}") +list(GET ENGINE_LIBRARIES 1 ENGINE_LIBRARY_FIRST) +foreach(lib ${ENGINE_LIBRARIES}) + get_filename_component(ENGINE_LIBRARY_PATH "${ENGINE_LIBRARY_FIRST}" PATH) + get_filename_component(ENGINE_LIBRARY_NAME "${lib}" NAME_WE) + string(REPLACE "lib" "" ENGINE_LIBRARY_NAME ${ENGINE_LIBRARY_NAME}) + string(REPLACE "-l" "" ENGINE_LIBRARY_NAME ${ENGINE_LIBRARY_NAME}) + set(ENGINE_LIBRARY_LISTING "${ENGINE_LIBRARY_LISTING} -L${ENGINE_LIBRARY_PATH} -l${ENGINE_LIBRARY_NAME}") endforeach() configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/pkgconfig.in libosrm.pc @ONLY) diff --git a/cmake/pkgconfig.in b/cmake/pkgconfig.in index 16263bfe0..34876c7a5 100644 --- a/cmake/pkgconfig.in +++ b/cmake/pkgconfig.in @@ -6,6 +6,6 @@ Name: libOSRM Description: Project OSRM library Version: v@OSRM_VERSION_MAJOR@.@OSRM_VERSION_MINOR@.@OSRM_VERSION_PATCH@ Requires: -Libs: -L${libdir} -lOSRM -Libs.private: @BOOST_LIBRARY_LISTING@ @TBB_LIBRARY_LISTING@ +Libs: -L${libdir} -losrm +Libs.private: @ENGINE_LIBRARY_LISTING@ Cflags: -I${includedir} diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt new file mode 100644 index 000000000..86a8a7f10 --- /dev/null +++ b/example/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 2.8.8) + +if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR AND NOT MSVC_IDE) + message(FATAL_ERROR "In-source builds are not allowed. +Please create a directory and run cmake from there, passing the path to this source directory as the last argument. +This process created the file `CMakeCache.txt' and the directory `CMakeFiles'. Please delete them.") +endif() + +project(osrm-example C CXX) + +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 ") + +set(bitness 32) +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(bitness 64) + message(STATUS "Building on a 64 bit system") +else() + message(WARNING "Building on a 32 bit system is unsupported") +endif() + +if(WIN32 AND MSVC_VERSION LESS 1800) + message(FATAL_ERROR "Building with Microsoft compiler needs Visual Studio 2013 or later (Express version works too)") +endif() + +add_executable(osrm-example example.cpp) + +find_package(LibOSRM REQUIRED) +find_package(Boost 1.49.0 COMPONENTS filesystem system thread REQUIRED) + +target_link_libraries(osrm-example ${LibOSRM_LIBRARIES} ${Boost_LIBRARIES}) +include_directories(SYSTEM ${LibOSRM_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) + diff --git a/example/cmake/FindLibOSRM.cmake b/example/cmake/FindLibOSRM.cmake new file mode 100644 index 000000000..35085b460 --- /dev/null +++ b/example/cmake/FindLibOSRM.cmake @@ -0,0 +1,65 @@ +# - Try to find LibOSRM +# Once done this will define +# LibOSRM_FOUND - System has LibOSRM +# LibOSRM_INCLUDE_DIRS - The LibOSRM include directories +# LibOSRM_LIBRARIES - The libraries needed to use LibOSRM +# LibOSRM_DEFINITIONS - Compiler switches required for using LibOSRM + +find_package(PkgConfig) +pkg_check_modules(PC_LibOSRM QUIET libosrm) +set(LibOSRM_DEFINITIONS ${PC_LibOSRM_CFLAGS_OTHER}) + +find_path(LibOSRM_INCLUDE_DIR osrm/osrm.hpp + PATH_SUFFIXES osrm include/osrm include + HINTS ${PC_LibOSRM_INCLUDEDIR} ${PC_LibOSRM_INCLUDE_DIRS} + ~/Library/Frameworks + /Library/Frameworks + /usr/local + /usr + /opt/local + /opt) + +set(LibOSRM_INCLUDE_DIRS ${LibOSRM_INCLUDE_DIR}) + +find_library(TEST_LibOSRM_STATIC_LIBRARY Names osrm.lib libosrm.a + PATH_SUFFIXES osrm lib/osrm lib + HINTS ${PC_LibOSRM_LIBDIR} ${PC_LibOSRM_LIBRARY_DIRS} + ~/Library/Frameworks + /Library/Frameworks + /usr/local + /usr + /opt/local + /opt) +find_library(TEST_LibOSRM_DYNAMIC_LIBRARY Names osrm.dynlib libosrm.so + PATH_SUFFIXES osrm lib/osrm lib + HINTS ${PC_LibOSRM_LIBDIR} ${PC_LibOSRM_LIBRARY_DIRS} + ~/Library/Frameworks + /Library/Frameworks + /usr/local + /usr + /opt/local + /opt) + +if (NOT ("${TEST_LibOSRM_STATIC_LIBRARY}" STREQUAL "TEST_LibOSRM_STATIC_LIBRARY-NOTFOUND")) + if ("${PC_LibOSRM_STATIC_LIBRARIES}" STREQUAL "") + set(LibOSRM_STATIC_LIBRARIES ${TEST_LibOSRM_STATIC_LIBRARY}) + else() + set(LibOSRM_STATIC_LIBRARIES ${PC_LibOSRM_STATIC_LIBRARIES}) + endif() + set(LibOSRM_LIBRARIES ${LibOSRM_STATIC_LIBRARIES}) +endif() + +if (NOT ("${TEST_LibOSRM_DYNAMIC_LIBRARY}" STREQUAL "TEST_LibOSRM_DYNAMIC_LIBRARY-NOTFOUND")) + if ("${PC_LibOSRM_LIBRARIES}" STREQUAL "") + set(LibOSRM_DYNAMIC_LIBRARIES ${TEST_LibOSRM_DYNAMIC_LIBRARY}) + else() + set(LibOSRM_DYNAMIC_LIBRARIES ${PC_LibOSRM_LIBRARIES}) + endif() + set(LibOSRM_LIBRARIES ${LibOSRM_DYNAMIC_LIBRARIES}) +endif() + +include(FindPackageHandleStandardArgs) +# handle the QUIETLY and REQUIRED arguments and set LIBOSRM_FOUND to TRUE +# if all listed variables are TRUE +find_package_handle_standard_args(LibOSRM DEFAULT_MSG + LibOSRM_LIBRARIES LibOSRM_INCLUDE_DIR) diff --git a/example/cmake/FindTBB.cmake b/example/cmake/FindTBB.cmake new file mode 100644 index 000000000..f9e3e0f57 --- /dev/null +++ b/example/cmake/FindTBB.cmake @@ -0,0 +1,283 @@ +# Locate Intel Threading Building Blocks include paths and libraries +# FindTBB.cmake can be found at https://code.google.com/p/findtbb/ +# Written by Hannes Hofmann +# Improvements by Gino van den Bergen , +# Florian Uhlig , +# Jiri Marsik + +# The MIT License +# +# Copyright (c) 2011 Hannes Hofmann +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# 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 AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +# GvdB: This module uses the environment variable TBB_ARCH_PLATFORM which defines architecture and compiler. +# e.g. "ia32/vc8" or "em64t/cc4.1.0_libc2.4_kernel2.6.16.21" +# TBB_ARCH_PLATFORM is set by the build script tbbvars[.bat|.sh|.csh], which can be found +# in the TBB installation directory (TBB_INSTALL_DIR). +# +# GvdB: Mac OS X distribution places libraries directly in lib directory. +# +# For backwards compatibility, you may explicitely set the CMake variables TBB_ARCHITECTURE and TBB_COMPILER. +# TBB_ARCHITECTURE [ ia32 | em64t | itanium ] +# which architecture to use +# TBB_COMPILER e.g. vc9 or cc3.2.3_libc2.3.2_kernel2.4.21 or cc4.0.1_os10.4.9 +# which compiler to use (detected automatically on Windows) + +# This module respects +# TBB_INSTALL_DIR or $ENV{TBB21_INSTALL_DIR} or $ENV{TBB_INSTALL_DIR} + +# This module defines +# TBB_INCLUDE_DIRS, where to find task_scheduler_init.h, etc. +# TBB_LIBRARY_DIRS, where to find libtbb, libtbbmalloc +# TBB_DEBUG_LIBRARY_DIRS, where to find libtbb_debug, libtbbmalloc_debug +# TBB_INSTALL_DIR, the base TBB install directory +# TBB_LIBRARIES, the libraries to link against to use TBB. +# TBB_DEBUG_LIBRARIES, the libraries to link against to use TBB with debug symbols. +# TBB_FOUND, If false, don't try to use TBB. +# TBB_INTERFACE_VERSION, as defined in tbb/tbb_stddef.h + + +if (WIN32) + # has em64t/vc8 em64t/vc9 + # has ia32/vc7.1 ia32/vc8 ia32/vc9 + set(_TBB_DEFAULT_INSTALL_DIR "C:/Program Files/Intel/TBB" "C:/Program Files (x86)/Intel/TBB") + set(_TBB_LIB_NAME "tbb") + set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") + set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") + set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") + if (MSVC71) + set (_TBB_COMPILER "vc7.1") + endif(MSVC71) + if (MSVC80) + set(_TBB_COMPILER "vc8") + endif(MSVC80) + if (MSVC90) + set(_TBB_COMPILER "vc9") + endif(MSVC90) + if(MSVC10) + set(_TBB_COMPILER "vc10") + endif(MSVC10) + # Todo: add other Windows compilers such as ICL. + set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) +endif (WIN32) + +if (UNIX) + if (APPLE) + # MAC + set(_TBB_DEFAULT_INSTALL_DIR "/Library/Frameworks/Intel_TBB.framework/Versions") + # libs: libtbb.dylib, libtbbmalloc.dylib, *_debug + set(_TBB_LIB_NAME "tbb") + set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") + set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") + set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") + # default flavor on apple: ia32/cc4.0.1_os10.4.9 + # Jiri: There is no reason to presume there is only one flavor and + # that user's setting of variables should be ignored. + if(NOT TBB_COMPILER) + set(_TBB_COMPILER "cc4.0.1_os10.4.9") + elseif (NOT TBB_COMPILER) + set(_TBB_COMPILER ${TBB_COMPILER}) + endif(NOT TBB_COMPILER) + if(NOT TBB_ARCHITECTURE) + set(_TBB_ARCHITECTURE "ia32") + elseif(NOT TBB_ARCHITECTURE) + set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) + endif(NOT TBB_ARCHITECTURE) + else (APPLE) + # LINUX + set(_TBB_DEFAULT_INSTALL_DIR "/opt/intel/tbb" "/usr/local/include" "/usr/include") + set(_TBB_LIB_NAME "tbb") + set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") + set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") + set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") + # has em64t/cc3.2.3_libc2.3.2_kernel2.4.21 em64t/cc3.3.3_libc2.3.3_kernel2.6.5 em64t/cc3.4.3_libc2.3.4_kernel2.6.9 em64t/cc4.1.0_libc2.4_kernel2.6.16.21 + # has ia32/* + # has itanium/* + set(_TBB_COMPILER ${TBB_COMPILER}) + set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) + endif (APPLE) +endif (UNIX) + +if (CMAKE_SYSTEM MATCHES "SunOS.*") +# SUN +# not yet supported +# has em64t/cc3.4.3_kernel5.10 +# has ia32/* +endif (CMAKE_SYSTEM MATCHES "SunOS.*") + + +#-- Clear the public variables +set (TBB_FOUND "NO") + + +#-- Find TBB install dir and set ${_TBB_INSTALL_DIR} and cached ${TBB_INSTALL_DIR} +# first: use CMake variable TBB_INSTALL_DIR +if (TBB_INSTALL_DIR) + set (_TBB_INSTALL_DIR ${TBB_INSTALL_DIR}) +endif (TBB_INSTALL_DIR) +# second: use environment variable +if (NOT _TBB_INSTALL_DIR) + if (NOT "$ENV{TBB_INSTALL_DIR}" STREQUAL "") + set (_TBB_INSTALL_DIR $ENV{TBB_INSTALL_DIR}) + endif (NOT "$ENV{TBB_INSTALL_DIR}" STREQUAL "") + # Intel recommends setting TBB21_INSTALL_DIR + if (NOT "$ENV{TBB21_INSTALL_DIR}" STREQUAL "") + set (_TBB_INSTALL_DIR $ENV{TBB21_INSTALL_DIR}) + endif (NOT "$ENV{TBB21_INSTALL_DIR}" STREQUAL "") + if (NOT "$ENV{TBB22_INSTALL_DIR}" STREQUAL "") + set (_TBB_INSTALL_DIR $ENV{TBB22_INSTALL_DIR}) + endif (NOT "$ENV{TBB22_INSTALL_DIR}" STREQUAL "") + if (NOT "$ENV{TBB30_INSTALL_DIR}" STREQUAL "") + set (_TBB_INSTALL_DIR $ENV{TBB30_INSTALL_DIR}) + endif (NOT "$ENV{TBB30_INSTALL_DIR}" STREQUAL "") +endif (NOT _TBB_INSTALL_DIR) +# third: try to find path automatically +if (NOT _TBB_INSTALL_DIR) + if (_TBB_DEFAULT_INSTALL_DIR) + set (_TBB_INSTALL_DIR ${_TBB_DEFAULT_INSTALL_DIR}) + endif (_TBB_DEFAULT_INSTALL_DIR) +endif (NOT _TBB_INSTALL_DIR) +# sanity check +if (NOT _TBB_INSTALL_DIR) + message ("ERROR: Unable to find Intel TBB install directory. ${_TBB_INSTALL_DIR}") +else (NOT _TBB_INSTALL_DIR) +# finally: set the cached CMake variable TBB_INSTALL_DIR +if (NOT TBB_INSTALL_DIR) + set (TBB_INSTALL_DIR ${_TBB_INSTALL_DIR} CACHE PATH "Intel TBB install directory") + mark_as_advanced(TBB_INSTALL_DIR) +endif (NOT TBB_INSTALL_DIR) + + +#-- A macro to rewrite the paths of the library. This is necessary, because +# find_library() always found the em64t/vc9 version of the TBB libs +macro(TBB_CORRECT_LIB_DIR var_name) +# if (NOT "${_TBB_ARCHITECTURE}" STREQUAL "em64t") + string(REPLACE em64t "${_TBB_ARCHITECTURE}" ${var_name} ${${var_name}}) +# endif (NOT "${_TBB_ARCHITECTURE}" STREQUAL "em64t") + string(REPLACE ia32 "${_TBB_ARCHITECTURE}" ${var_name} ${${var_name}}) + string(REPLACE vc7.1 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) + string(REPLACE vc8 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) + string(REPLACE vc9 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) + string(REPLACE vc10 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) +endmacro(TBB_CORRECT_LIB_DIR var_content) + + +#-- Look for include directory and set ${TBB_INCLUDE_DIR} +set (TBB_INC_SEARCH_DIR ${_TBB_INSTALL_DIR}/include) +# Jiri: tbbvars now sets the CPATH environment variable to the directory +# containing the headers. +find_path(TBB_INCLUDE_DIR + tbb/task_scheduler_init.h + PATHS ${TBB_INC_SEARCH_DIR} ENV CPATH +) +mark_as_advanced(TBB_INCLUDE_DIR) + + +#-- Look for libraries +# GvdB: $ENV{TBB_ARCH_PLATFORM} is set by the build script tbbvars[.bat|.sh|.csh] +if (NOT $ENV{TBB_ARCH_PLATFORM} STREQUAL "") + set (_TBB_LIBRARY_DIR + ${_TBB_INSTALL_DIR}/lib/$ENV{TBB_ARCH_PLATFORM} + ${_TBB_INSTALL_DIR}/$ENV{TBB_ARCH_PLATFORM}/lib + ) +endif (NOT $ENV{TBB_ARCH_PLATFORM} STREQUAL "") +# Jiri: This block isn't mutually exclusive with the previous one +# (hence no else), instead I test if the user really specified +# the variables in question. +if ((NOT ${TBB_ARCHITECTURE} STREQUAL "") AND (NOT ${TBB_COMPILER} STREQUAL "")) + # HH: deprecated + message(STATUS "[Warning] FindTBB.cmake: The use of TBB_ARCHITECTURE and TBB_COMPILER is deprecated and may not be supported in future versions. Please set \$ENV{TBB_ARCH_PLATFORM} (using tbbvars.[bat|csh|sh]).") + # Jiri: It doesn't hurt to look in more places, so I store the hints from + # ENV{TBB_ARCH_PLATFORM} and the TBB_ARCHITECTURE and TBB_COMPILER + # variables and search them both. + set (_TBB_LIBRARY_DIR "${_TBB_INSTALL_DIR}/${_TBB_ARCHITECTURE}/${_TBB_COMPILER}/lib" ${_TBB_LIBRARY_DIR}) +endif ((NOT ${TBB_ARCHITECTURE} STREQUAL "") AND (NOT ${TBB_COMPILER} STREQUAL "")) + +# GvdB: Mac OS X distribution places libraries directly in lib directory. +list(APPEND _TBB_LIBRARY_DIR ${_TBB_INSTALL_DIR}/lib) + +# Jiri: No reason not to check the default paths. From recent versions, +# tbbvars has started exporting the LIBRARY_PATH and LD_LIBRARY_PATH +# variables, which now point to the directories of the lib files. +# It all makes more sense to use the ${_TBB_LIBRARY_DIR} as a HINTS +# argument instead of the implicit PATHS as it isn't hard-coded +# but computed by system introspection. Searching the LIBRARY_PATH +# and LD_LIBRARY_PATH environment variables is now even more important +# that tbbvars doesn't export TBB_ARCH_PLATFORM and it facilitates +# the use of TBB built from sources. +find_library(TBB_LIBRARY ${_TBB_LIB_NAME} HINTS ${_TBB_LIBRARY_DIR} + PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) +find_library(TBB_MALLOC_LIBRARY ${_TBB_LIB_MALLOC_NAME} HINTS ${_TBB_LIBRARY_DIR} + PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) + +#Extract path from TBB_LIBRARY name +get_filename_component(TBB_LIBRARY_DIR ${TBB_LIBRARY} PATH) + +#TBB_CORRECT_LIB_DIR(TBB_LIBRARY) +#TBB_CORRECT_LIB_DIR(TBB_MALLOC_LIBRARY) +mark_as_advanced(TBB_LIBRARY TBB_MALLOC_LIBRARY) + +#-- Look for debug libraries +# Jiri: Changed the same way as for the release libraries. +find_library(TBB_LIBRARY_DEBUG ${_TBB_LIB_DEBUG_NAME} HINTS ${_TBB_LIBRARY_DIR} + PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) +find_library(TBB_MALLOC_LIBRARY_DEBUG ${_TBB_LIB_MALLOC_DEBUG_NAME} HINTS ${_TBB_LIBRARY_DIR} + PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) + +# Jiri: Self-built TBB stores the debug libraries in a separate directory. +# Extract path from TBB_LIBRARY_DEBUG name +get_filename_component(TBB_LIBRARY_DEBUG_DIR ${TBB_LIBRARY_DEBUG} PATH) + +#TBB_CORRECT_LIB_DIR(TBB_LIBRARY_DEBUG) +#TBB_CORRECT_LIB_DIR(TBB_MALLOC_LIBRARY_DEBUG) +mark_as_advanced(TBB_LIBRARY_DEBUG TBB_MALLOC_LIBRARY_DEBUG) + + +if (TBB_INCLUDE_DIR) + if (TBB_LIBRARY) + set (TBB_FOUND "YES") + set (TBB_LIBRARIES ${TBB_LIBRARY} ${TBB_MALLOC_LIBRARY} ${TBB_LIBRARIES}) + set (TBB_DEBUG_LIBRARIES ${TBB_LIBRARY_DEBUG} ${TBB_MALLOC_LIBRARY_DEBUG} ${TBB_DEBUG_LIBRARIES}) + set (TBB_INCLUDE_DIRS ${TBB_INCLUDE_DIR} CACHE PATH "TBB include directory" FORCE) + set (TBB_LIBRARY_DIRS ${TBB_LIBRARY_DIR} CACHE PATH "TBB library directory" FORCE) + # Jiri: Self-built TBB stores the debug libraries in a separate directory. + set (TBB_DEBUG_LIBRARY_DIRS ${TBB_LIBRARY_DEBUG_DIR} CACHE PATH "TBB debug library directory" FORCE) + mark_as_advanced(TBB_INCLUDE_DIRS TBB_LIBRARY_DIRS TBB_DEBUG_LIBRARY_DIRS TBB_LIBRARIES TBB_DEBUG_LIBRARIES) + message(STATUS "Found Intel TBB") + endif (TBB_LIBRARY) +endif (TBB_INCLUDE_DIR) + +if (NOT TBB_FOUND) + message("ERROR: Intel TBB NOT found!") + message(STATUS "Looked for Threading Building Blocks in ${_TBB_INSTALL_DIR}") + # do only throw fatal, if this pkg is REQUIRED + if (TBB_FIND_REQUIRED) + message(FATAL_ERROR "Could NOT find TBB library.") + endif (TBB_FIND_REQUIRED) +endif (NOT TBB_FOUND) + +endif (NOT _TBB_INSTALL_DIR) + +if (TBB_FOUND) + set(TBB_INTERFACE_VERSION 0) + FILE(READ "${TBB_INCLUDE_DIRS}/tbb/tbb_stddef.h" _TBB_VERSION_CONTENTS) + STRING(REGEX REPLACE ".*#define TBB_INTERFACE_VERSION ([0-9]+).*" "\\1" TBB_INTERFACE_VERSION "${_TBB_VERSION_CONTENTS}") + set(TBB_INTERFACE_VERSION "${TBB_INTERFACE_VERSION}") +endif (TBB_FOUND) diff --git a/example/example.cpp b/example/example.cpp new file mode 100644 index 000000000..0442ca698 --- /dev/null +++ b/example/example.cpp @@ -0,0 +1,63 @@ +#include "osrm/json_container.hpp" +#include "osrm/engine_config.hpp" +#include "osrm/route_parameters.hpp" +#include "osrm/osrm.hpp" + +#include +#include +#include +#include +#include + +int main(int argc, const char *argv[]) try +{ + if (argc < 2) + { + std::cerr << "Error: Not enough arguments." << std::endl + << "Run " << argv[0] << " data.osrm" << std::endl; + return EXIT_FAILURE; + } + + osrm::EngineConfig engine_config; + std::string base_path(argv[1]); + engine_config.server_paths["ramindex"] = base_path + ".ramIndex"; + engine_config.server_paths["fileindex"] = base_path + ".fileIndex"; + engine_config.server_paths["hsgrdata"] = base_path + ".hsgr"; + engine_config.server_paths["nodesdata"] = base_path + ".nodes"; + engine_config.server_paths["edgesdata"] = base_path + ".edges"; + engine_config.server_paths["coredata"] = base_path + ".core"; + engine_config.server_paths["geometries"] = base_path + ".geometry"; + engine_config.server_paths["timestamp"] = base_path + ".timestamp"; + engine_config.server_paths["namesdata"] = base_path + ".names"; + engine_config.use_shared_memory = false; + + osrm::OSRM routing_machine(engine_config); + + osrm::RouteParameters route_parameters; + // route is in Berlin + auto start = std::make_pair(52.519930, 13.438640); + auto target = std::make_pair(52.513191, 13.415852); + route_parameters.service = "viaroute"; + route_parameters.AddCoordinate({start.first, start.second}); + route_parameters.AddCoordinate({target.first, target.second}); + + osrm::json::Object json_result; + const int result_code = routing_machine.RunQuery(route_parameters, json_result); + std::cout << "result code: " << result_code << std::endl; + // 2xx code + if (result_code / 100 == 2) + { + // Extract data out of JSON structure + auto& summary = json_result.values["route_summary"].get(); + auto duration = summary.values["total_time"].get().value; + auto distance = summary.values["total_distance"].get().value; + std::cout << "duration: " << duration << std::endl; + std::cout << "distance: " << distance << std::endl; + } + return EXIT_SUCCESS; +} +catch (const std::exception ¤t_exception) +{ + std::cout << "exception: " << current_exception.what(); + return EXIT_FAILURE; +} diff --git a/include/contractor/contractor.hpp b/include/contractor/contractor.hpp index 6e4f8688b..64d3c0491 100644 --- a/include/contractor/contractor.hpp +++ b/include/contractor/contractor.hpp @@ -1,1158 +1,74 @@ -#ifndef CONTRACTOR_HPP -#define CONTRACTOR_HPP +#ifndef CONTRACTOR_CONTRACTOR_HPP +#define CONTRACTOR_CONTRACTOR_HPP -#include "util/binary_heap.hpp" -#include "util/deallocating_vector.hpp" -#include "util/dynamic_graph.hpp" -#include "util/percent.hpp" +#include "extractor/edge_based_edge.hpp" +#include "extractor/node_based_edge.hpp" +#include "contractor/contractor.hpp" +#include "contractor/contractor_config.hpp" #include "contractor/query_edge.hpp" -#include "util/xor_fast_hash.hpp" -#include "util/xor_fast_hash_storage.hpp" -#include "util/integer_range.hpp" -#include "util/simple_logger.hpp" -#include "util/timing_util.hpp" -#include "util/typedefs.hpp" +#include "extractor/edge_based_edge.hpp" +#include "util/static_graph.hpp" +#include "util/deallocating_vector.hpp" +#include "util/node_based_graph.hpp" -#include +#include -#include - -#include -#include -#include - -#include -#include -#include #include +struct lua_State; + namespace osrm { +namespace extractor +{ +struct SpeedProfileProperties; +struct EdgeBasedNode; +struct EdgeBasedEdge; +} namespace contractor { +/// Base class of osrm-contract class Contractor { - - private: - struct ContractorEdgeData - { - ContractorEdgeData() - : distance(0), id(0), originalEdges(0), shortcut(0), forward(0), backward(0), - is_original_via_node_ID(false) - { - } - ContractorEdgeData(unsigned distance, - unsigned original_edges, - unsigned id, - bool shortcut, - bool forward, - bool backward) - : distance(distance), id(id), - originalEdges(std::min((unsigned)1 << 28, original_edges)), shortcut(shortcut), - forward(forward), backward(backward), is_original_via_node_ID(false) - { - } - unsigned distance; - unsigned id; - unsigned originalEdges : 28; - bool shortcut : 1; - bool forward : 1; - bool backward : 1; - bool is_original_via_node_ID : 1; - } data; - - struct ContractorHeapData - { - short hop; - bool target; - ContractorHeapData() : hop(0), target(false) {} - ContractorHeapData(short h, bool t) : hop(h), target(t) {} - }; - - using ContractorGraph = util::DynamicGraph; - // using ContractorHeap = util::BinaryHeap - // >; - using ContractorHeap = util::BinaryHeap>; - using ContractorEdge = ContractorGraph::InputEdge; - - struct ContractorThreadData - { - ContractorHeap heap; - std::vector inserted_edges; - std::vector neighbours; - explicit ContractorThreadData(NodeID nodes) : heap(nodes) {} - }; - - struct NodePriorityData - { - int depth; - NodePriorityData() : depth(0) {} - }; - - struct ContractionStats - { - int edges_deleted_count; - int edges_added_count; - int original_edges_deleted_count; - int original_edges_added_count; - ContractionStats() - : edges_deleted_count(0), edges_added_count(0), original_edges_deleted_count(0), - original_edges_added_count(0) - { - } - }; - - struct RemainingNodeData - { - RemainingNodeData() : id(0), is_independent(false) {} - NodeID id : 31; - bool is_independent : 1; - }; - - struct ThreadDataContainer - { - explicit ThreadDataContainer(int number_of_nodes) : number_of_nodes(number_of_nodes) {} - - inline ContractorThreadData *getThreadData() - { - bool exists = false; - auto &ref = data.local(exists); - if (!exists) - { - ref = std::make_shared(number_of_nodes); - } - - return ref.get(); - } - - int number_of_nodes; - using EnumerableThreadData = - tbb::enumerable_thread_specific>; - EnumerableThreadData data; - }; - public: - template - Contractor(int nodes, ContainerT &input_edge_list) - : Contractor(nodes, input_edge_list, {}, {}) + using EdgeData = QueryEdge::EdgeData; + + explicit Contractor(ContractorConfig contractor_config) : config(std::move(contractor_config)) { } + Contractor(const Contractor &) = delete; + Contractor& operator=(const Contractor &) = delete; - template - Contractor(int nodes, - ContainerT &input_edge_list, - std::vector &&node_levels_, - std::vector &&node_weights_) - : node_levels(std::move(node_levels_)), node_weights(std::move(node_weights_)) - { - std::vector edges; - edges.reserve(input_edge_list.size() * 2); + int Run(); - const auto dend = input_edge_list.dend(); - for (auto diter = input_edge_list.dbegin(); diter != dend; ++diter) - { - BOOST_ASSERT_MSG(static_cast(std::max(diter->weight, 1)) > 0, - "edge distance < 1"); -#ifndef NDEBUG - if (static_cast(std::max(diter->weight, 1)) > 24 * 60 * 60 * 10) - { - util::SimpleLogger().Write(logWARNING) - << "Edge weight large -> " - << static_cast(std::max(diter->weight, 1)) << " : " - << static_cast(diter->source) << " -> " - << static_cast(diter->target); - } -#endif - edges.emplace_back(diter->source, diter->target, - static_cast(std::max(diter->weight, 1)), 1, - diter->edge_id, false, diter->forward ? true : false, - diter->backward ? true : false); - - edges.emplace_back(diter->target, diter->source, - static_cast(std::max(diter->weight, 1)), 1, - diter->edge_id, false, diter->backward ? true : false, - diter->forward ? true : false); - } - // clear input vector - input_edge_list.clear(); - // FIXME not sure if we need this - edges.shrink_to_fit(); - - tbb::parallel_sort(edges.begin(), edges.end()); - NodeID edge = 0; - for (NodeID i = 0; i < edges.size();) - { - const NodeID source = edges[i].source; - const NodeID target = edges[i].target; - const NodeID id = edges[i].data.id; - // remove eigenloops - if (source == target) - { - ++i; - continue; - } - ContractorEdge forward_edge; - ContractorEdge reverse_edge; - forward_edge.source = reverse_edge.source = source; - forward_edge.target = reverse_edge.target = target; - forward_edge.data.forward = reverse_edge.data.backward = true; - forward_edge.data.backward = reverse_edge.data.forward = false; - forward_edge.data.shortcut = reverse_edge.data.shortcut = false; - forward_edge.data.id = reverse_edge.data.id = id; - forward_edge.data.originalEdges = reverse_edge.data.originalEdges = 1; - forward_edge.data.distance = reverse_edge.data.distance = INVALID_EDGE_WEIGHT; - // remove parallel edges - while (i < edges.size() && edges[i].source == source && edges[i].target == target) - { - if (edges[i].data.forward) - { - forward_edge.data.distance = - std::min(edges[i].data.distance, forward_edge.data.distance); - } - if (edges[i].data.backward) - { - reverse_edge.data.distance = - std::min(edges[i].data.distance, reverse_edge.data.distance); - } - ++i; - } - // merge edges (s,t) and (t,s) into bidirectional edge - if (forward_edge.data.distance == reverse_edge.data.distance) - { - if ((int)forward_edge.data.distance != INVALID_EDGE_WEIGHT) - { - forward_edge.data.backward = true; - edges[edge++] = forward_edge; - } - } - else - { // insert seperate edges - if (((int)forward_edge.data.distance) != INVALID_EDGE_WEIGHT) - { - edges[edge++] = forward_edge; - } - if ((int)reverse_edge.data.distance != INVALID_EDGE_WEIGHT) - { - edges[edge++] = reverse_edge; - } - } - } - std::cout << "merged " << edges.size() - edge << " edges out of " << edges.size() - << std::endl; - edges.resize(edge); - contractor_graph = std::make_shared(nodes, edges); - edges.clear(); - edges.shrink_to_fit(); - - BOOST_ASSERT(0 == edges.capacity()); - // unsigned maxdegree = 0; - // NodeID highestNode = 0; - // - // for(unsigned i = 0; i < contractor_graph->GetNumberOfNodes(); ++i) { - // unsigned degree = contractor_graph->EndEdges(i) - - // contractor_graph->BeginEdges(i); - // if(degree > maxdegree) { - // maxdegree = degree; - // highestNode = i; - // } - // } - // - // util::SimpleLogger().Write() << "edges at node with id " << highestNode << " has - // degree - // " << maxdegree; - // for(unsigned i = contractor_graph->BeginEdges(highestNode); i < - // contractor_graph->EndEdges(highestNode); ++i) { - // util::SimpleLogger().Write() << " ->(" << highestNode << "," << - // contractor_graph->GetTarget(i) - // << "); via: " << contractor_graph->GetEdgeData(i).via; - // } - - std::cout << "contractor finished initalization" << std::endl; - } - - ~Contractor() {} - - void Run(double core_factor = 1.0) - { - // for the preperation we can use a big grain size, which is much faster (probably cache) - constexpr size_t InitGrainSize = 100000; - constexpr size_t PQGrainSize = 100000; - // auto_partitioner will automatically increase the blocksize if we have - // a lot of data. It is *important* for the last loop iterations - // (which have a very small dataset) that it is devisible. - constexpr size_t IndependentGrainSize = 1; - constexpr size_t ContractGrainSize = 1; - constexpr size_t NeighboursGrainSize = 1; - constexpr size_t DeleteGrainSize = 1; - - const NodeID number_of_nodes = contractor_graph->GetNumberOfNodes(); - util::Percent p(number_of_nodes); - - ThreadDataContainer thread_data_list(number_of_nodes); - - NodeID number_of_contracted_nodes = 0; - std::vector node_data; - std::vector node_priorities; - is_core_node.resize(number_of_nodes, false); - - std::vector remaining_nodes(number_of_nodes); - // initialize priorities in parallel - tbb::parallel_for(tbb::blocked_range(0, number_of_nodes, InitGrainSize), - [this, &remaining_nodes](const tbb::blocked_range &range) - { - for (int x = range.begin(), end = range.end(); x != end; ++x) - { - remaining_nodes[x].id = x; - } - }); - - bool use_cached_node_priorities = !node_levels.empty(); - if (use_cached_node_priorities) - { - std::cout << "using cached node priorities ..." << std::flush; - node_priorities.swap(node_levels); - std::cout << "ok" << std::endl; - } - else - { - node_data.resize(number_of_nodes); - node_priorities.resize(number_of_nodes); - node_levels.resize(number_of_nodes); - - std::cout << "initializing elimination PQ ..." << std::flush; - tbb::parallel_for(tbb::blocked_range(0, number_of_nodes, PQGrainSize), - [this, &node_priorities, &node_data, - &thread_data_list](const tbb::blocked_range &range) - { - ContractorThreadData *data = thread_data_list.getThreadData(); - for (int x = range.begin(), end = range.end(); x != end; ++x) - { - node_priorities[x] = - this->EvaluateNodePriority(data, &node_data[x], x); - } - }); - std::cout << "ok" << std::endl; - } - BOOST_ASSERT(node_priorities.size() == number_of_nodes); - - std::cout << "preprocessing " << number_of_nodes << " nodes ..." << std::flush; - - unsigned current_level = 0; - bool flushed_contractor = false; - while (number_of_nodes > 2 && - number_of_contracted_nodes < static_cast(number_of_nodes * core_factor)) - { - if (!flushed_contractor && (number_of_contracted_nodes > - static_cast(number_of_nodes * 0.65 * core_factor))) - { - util::DeallocatingVector - new_edge_set; // this one is not explicitely - // cleared since it goes out of - // scope anywa - std::cout << " [flush " << number_of_contracted_nodes << " nodes] " << std::flush; - - // Delete old heap data to free memory that we need for the coming operations - thread_data_list.data.clear(); - - // Create new priority array - std::vector new_node_priority(remaining_nodes.size()); - std::vector new_node_weights(remaining_nodes.size()); - // this map gives the old IDs from the new ones, necessary to get a consistent graph - // at the end of contraction - orig_node_id_from_new_node_id_map.resize(remaining_nodes.size()); - // this map gives the new IDs from the old ones, necessary to remap targets from the - // remaining graph - std::vector new_node_id_from_orig_id_map(number_of_nodes, SPECIAL_NODEID); - - for (const auto new_node_id : util::irange(0, remaining_nodes.size())) - { - auto &node = remaining_nodes[new_node_id]; - BOOST_ASSERT(node_priorities.size() > node.id); - new_node_priority[new_node_id] = node_priorities[node.id]; - BOOST_ASSERT(node_weights.size() > node.id); - new_node_weights[new_node_id] = node_weights[node.id]; - } - - // build forward and backward renumbering map and remap ids in remaining_nodes - for (const auto new_node_id : util::irange(0, remaining_nodes.size())) - { - auto &node = remaining_nodes[new_node_id]; - // create renumbering maps in both directions - orig_node_id_from_new_node_id_map[new_node_id] = node.id; - new_node_id_from_orig_id_map[node.id] = new_node_id; - node.id = new_node_id; - } - // walk over all nodes - for (const auto source : - util::irange(0, contractor_graph->GetNumberOfNodes())) - { - for (auto current_edge : contractor_graph->GetAdjacentEdgeRange(source)) - { - ContractorGraph::EdgeData &data = - contractor_graph->GetEdgeData(current_edge); - const NodeID target = contractor_graph->GetTarget(current_edge); - if (SPECIAL_NODEID == new_node_id_from_orig_id_map[source]) - { - external_edge_list.push_back({source, target, data}); - } - else - { - // node is not yet contracted. - // add (renumbered) outgoing edges to new util::DynamicGraph. - ContractorEdge new_edge = {new_node_id_from_orig_id_map[source], - new_node_id_from_orig_id_map[target], data}; - - new_edge.data.is_original_via_node_ID = true; - BOOST_ASSERT_MSG(SPECIAL_NODEID != new_node_id_from_orig_id_map[source], - "new source id not resolveable"); - BOOST_ASSERT_MSG(SPECIAL_NODEID != new_node_id_from_orig_id_map[target], - "new target id not resolveable"); - new_edge_set.push_back(new_edge); - } - } - } - - // Delete map from old NodeIDs to new ones. - new_node_id_from_orig_id_map.clear(); - new_node_id_from_orig_id_map.shrink_to_fit(); - - // Replace old priorities array by new one - node_priorities.swap(new_node_priority); - // Delete old node_priorities vector - // Due to the scope, these should get cleared automatically? @daniel-j-h do you - // agree? - new_node_priority.clear(); - new_node_priority.shrink_to_fit(); - - node_weights.swap(new_node_weights); - // old Graph is removed - contractor_graph.reset(); - - // create new graph - tbb::parallel_sort(new_edge_set.begin(), new_edge_set.end()); - contractor_graph = - std::make_shared(remaining_nodes.size(), new_edge_set); - - new_edge_set.clear(); - flushed_contractor = true; - - // INFO: MAKE SURE THIS IS THE LAST OPERATION OF THE FLUSH! - // reinitialize heaps and ThreadData objects with appropriate size - thread_data_list.number_of_nodes = contractor_graph->GetNumberOfNodes(); - } - - tbb::parallel_for( - tbb::blocked_range(0, remaining_nodes.size(), IndependentGrainSize), - [this, &node_priorities, &remaining_nodes, - &thread_data_list](const tbb::blocked_range &range) - { - ContractorThreadData *data = thread_data_list.getThreadData(); - // determine independent node set - for (auto i = range.begin(), end = range.end(); i != end; ++i) - { - const NodeID node = remaining_nodes[i].id; - remaining_nodes[i].is_independent = - this->IsNodeIndependent(node_priorities, data, node); - } - }); - - // sort all remaining nodes to the beginning of the sequence - const auto begin_independent_nodes = stable_partition( - remaining_nodes.begin(), remaining_nodes.end(), [](RemainingNodeData node_data) - { - return !node_data.is_independent; - }); - auto begin_independent_nodes_idx = - std::distance(remaining_nodes.begin(), begin_independent_nodes); - auto end_independent_nodes_idx = remaining_nodes.size(); - - if (!use_cached_node_priorities) - { - // write out contraction level - tbb::parallel_for( - tbb::blocked_range(begin_independent_nodes_idx, - end_independent_nodes_idx, ContractGrainSize), - [this, remaining_nodes, flushed_contractor, - current_level](const tbb::blocked_range &range) - { - if (flushed_contractor) - { - for (int position = range.begin(), end = range.end(); position != end; - ++position) - { - const NodeID x = remaining_nodes[position].id; - node_levels[orig_node_id_from_new_node_id_map[x]] = current_level; - } - } - else - { - for (int position = range.begin(), end = range.end(); position != end; - ++position) - { - const NodeID x = remaining_nodes[position].id; - node_levels[x] = current_level; - } - } - }); - } - - // contract independent nodes - tbb::parallel_for(tbb::blocked_range(begin_independent_nodes_idx, - end_independent_nodes_idx, - ContractGrainSize), - [this, &remaining_nodes, - &thread_data_list](const tbb::blocked_range &range) - { - ContractorThreadData *data = thread_data_list.getThreadData(); - for (int position = range.begin(), end = range.end(); - position != end; ++position) - { - const NodeID x = remaining_nodes[position].id; - this->ContractNode(data, x); - } - }); - - tbb::parallel_for( - tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, - DeleteGrainSize), - [this, &remaining_nodes, &thread_data_list](const tbb::blocked_range &range) - { - ContractorThreadData *data = thread_data_list.getThreadData(); - for (int position = range.begin(), end = range.end(); position != end; - ++position) - { - const NodeID x = remaining_nodes[position].id; - this->DeleteIncomingEdges(data, x); - } - }); - - // make sure we really sort each block - tbb::parallel_for( - thread_data_list.data.range(), - [&](const ThreadDataContainer::EnumerableThreadData::range_type &range) - { - for (auto &data : range) - tbb::parallel_sort(data->inserted_edges.begin(), - data->inserted_edges.end()); - }); - - // insert new edges - for (auto &data : thread_data_list.data) - { - for (const ContractorEdge &edge : data->inserted_edges) - { - const EdgeID current_edge_ID = - contractor_graph->FindEdge(edge.source, edge.target); - if (current_edge_ID < contractor_graph->EndEdges(edge.source)) - { - ContractorGraph::EdgeData ¤t_data = - contractor_graph->GetEdgeData(current_edge_ID); - if (current_data.shortcut && edge.data.forward == current_data.forward && - edge.data.backward == current_data.backward && - edge.data.distance < current_data.distance) - { - // found a duplicate edge with smaller weight, update it. - current_data = edge.data; - continue; - } - } - contractor_graph->InsertEdge(edge.source, edge.target, edge.data); - } - data->inserted_edges.clear(); - } - - if (!use_cached_node_priorities) - { - tbb::parallel_for( - tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, - NeighboursGrainSize), - [this, &node_priorities, &remaining_nodes, &node_data, - &thread_data_list](const tbb::blocked_range &range) - { - ContractorThreadData *data = thread_data_list.getThreadData(); - for (int position = range.begin(), end = range.end(); position != end; - ++position) - { - NodeID x = remaining_nodes[position].id; - this->UpdateNodeNeighbours(node_priorities, node_data, data, x); - } - }); - } - - // remove contracted nodes from the pool - number_of_contracted_nodes += end_independent_nodes_idx - begin_independent_nodes_idx; - remaining_nodes.resize(begin_independent_nodes_idx); - // unsigned maxdegree = 0; - // unsigned avgdegree = 0; - // unsigned mindegree = SPECIAL_NODEID; - // unsigned quaddegree = 0; - // - // for(unsigned i = 0; i < remaining_nodes.size(); ++i) { - // unsigned degree = contractor_graph->EndEdges(remaining_nodes[i].id) - // - - // contractor_graph->BeginEdges(remaining_nodes[i].first); - // if(degree > maxdegree) - // maxdegree = degree; - // if(degree < mindegree) - // mindegree = degree; - // - // avgdegree += degree; - // quaddegree += (degree*degree); - // } - // - // avgdegree /= std::max((unsigned)1,(unsigned)remaining_nodes.size() ); - // quaddegree /= std::max((unsigned)1,(unsigned)remaining_nodes.size() ); - // - // util::SimpleLogger().Write() << "rest: " << remaining_nodes.size() << ", - // max: " - // << maxdegree << ", min: " << mindegree << ", avg: " << avgdegree << ", - // quad: " << quaddegree; - - p.printStatus(number_of_contracted_nodes); - ++current_level; - } - - if (remaining_nodes.size() > 2) - { - if (orig_node_id_from_new_node_id_map.size() > 0) - { - tbb::parallel_for(tbb::blocked_range(0, remaining_nodes.size(), InitGrainSize), - [this, &remaining_nodes](const tbb::blocked_range &range) - { - for (int x = range.begin(), end = range.end(); x != end; ++x) - { - const auto orig_id = remaining_nodes[x].id; - is_core_node[orig_node_id_from_new_node_id_map[orig_id]] = - true; - } - }); - } - else - { - tbb::parallel_for(tbb::blocked_range(0, remaining_nodes.size(), InitGrainSize), - [this, &remaining_nodes](const tbb::blocked_range &range) - { - for (int x = range.begin(), end = range.end(); x != end; ++x) - { - const auto orig_id = remaining_nodes[x].id; - is_core_node[orig_id] = true; - } - }); - } - } - else - { - // in this case we don't need core markers since we fully contracted - // the graph - is_core_node.clear(); - } - - util::SimpleLogger().Write() << "[core] " << remaining_nodes.size() << " nodes " - << contractor_graph->GetNumberOfEdges() << " edges." - << std::endl; - - thread_data_list.data.clear(); - } - - inline void GetCoreMarker(std::vector &out_is_core_node) - { - out_is_core_node.swap(is_core_node); - } - - inline void GetNodeLevels(std::vector &out_node_levels) - { - out_node_levels.swap(node_levels); - } - - template inline void GetEdges(util::DeallocatingVector &edges) - { - util::Percent p(contractor_graph->GetNumberOfNodes()); - util::SimpleLogger().Write() << "Getting edges of minimized graph"; - const NodeID number_of_nodes = contractor_graph->GetNumberOfNodes(); - if (contractor_graph->GetNumberOfNodes()) - { - Edge new_edge; - for (const auto node : util::irange(0u, number_of_nodes)) - { - p.printStatus(node); - for (auto edge : contractor_graph->GetAdjacentEdgeRange(node)) - { - const NodeID target = contractor_graph->GetTarget(edge); - const ContractorGraph::EdgeData &data = contractor_graph->GetEdgeData(edge); - if (!orig_node_id_from_new_node_id_map.empty()) - { - new_edge.source = orig_node_id_from_new_node_id_map[node]; - new_edge.target = orig_node_id_from_new_node_id_map[target]; - } - else - { - new_edge.source = node; - new_edge.target = target; - } - BOOST_ASSERT_MSG(SPECIAL_NODEID != new_edge.source, "Source id invalid"); - BOOST_ASSERT_MSG(SPECIAL_NODEID != new_edge.target, "Target id invalid"); - new_edge.data.distance = data.distance; - new_edge.data.shortcut = data.shortcut; - if (!data.is_original_via_node_ID && !orig_node_id_from_new_node_id_map.empty()) - { - // tranlate the _node id_ of the shortcutted node - new_edge.data.id = orig_node_id_from_new_node_id_map[data.id]; - } - else - { - new_edge.data.id = data.id; - } - BOOST_ASSERT_MSG(new_edge.data.id != INT_MAX, // 2^31 - "edge id invalid"); - new_edge.data.forward = data.forward; - new_edge.data.backward = data.backward; - edges.push_back(new_edge); - } - } - } - contractor_graph.reset(); - orig_node_id_from_new_node_id_map.clear(); - orig_node_id_from_new_node_id_map.shrink_to_fit(); - - BOOST_ASSERT(0 == orig_node_id_from_new_node_id_map.capacity()); - - edges.append(external_edge_list.begin(), external_edge_list.end()); - external_edge_list.clear(); - } + protected: + void ContractGraph(const unsigned max_edge_id, + util::DeallocatingVector &edge_based_edge_list, + util::DeallocatingVector &contracted_edge_list, + std::vector &&node_weights, + std::vector &is_core_node, + std::vector &inout_node_levels) const; + void WriteCoreNodeMarker(std::vector &&is_core_node) const; + void WriteNodeLevels(std::vector &&node_levels) const; + void ReadNodeLevels(std::vector &contraction_order) const; + std::size_t + WriteContractedGraph(unsigned number_of_edge_based_nodes, + const util::DeallocatingVector &contracted_edge_list); + void FindComponents(unsigned max_edge_id, + const util::DeallocatingVector &edges, + std::vector &nodes) const; private: - inline void RelaxNode(const NodeID node, - const NodeID forbidden_node, - const int distance, - ContractorHeap &heap) - { - const short current_hop = heap.GetData(node).hop + 1; - for (auto edge : contractor_graph->GetAdjacentEdgeRange(node)) - { - const ContractorEdgeData &data = contractor_graph->GetEdgeData(edge); - if (!data.forward) - { - continue; - } - const NodeID to = contractor_graph->GetTarget(edge); - if (forbidden_node == to) - { - continue; - } - const int to_distance = distance + data.distance; - - // New Node discovered -> Add to Heap + Node Info Storage - if (!heap.WasInserted(to)) - { - heap.Insert(to, to_distance, ContractorHeapData(current_hop, false)); - } - // Found a shorter Path -> Update distance - else if (to_distance < heap.GetKey(to)) - { - heap.DecreaseKey(to, to_distance); - heap.GetData(to).hop = current_hop; - } - } - } - - inline void Dijkstra(const int max_distance, - const unsigned number_of_targets, - const int maxNodes, - ContractorThreadData &data, - const NodeID middleNode) - { - - ContractorHeap &heap = data.heap; - - int nodes = 0; - unsigned number_of_targets_found = 0; - while (!heap.Empty()) - { - const NodeID node = heap.DeleteMin(); - const auto distance = heap.GetKey(node); - if (++nodes > maxNodes) - { - return; - } - if (distance > max_distance) - { - return; - } - - // Destination settled? - if (heap.GetData(node).target) - { - ++number_of_targets_found; - if (number_of_targets_found >= number_of_targets) - { - return; - } - } - - RelaxNode(node, middleNode, distance, heap); - } - } - - inline float EvaluateNodePriority(ContractorThreadData *const data, - NodePriorityData *const node_data, - const NodeID node) - { - ContractionStats stats; - - // perform simulated contraction - ContractNode(data, node, &stats); - - // Result will contain the priority - float result; - if (0 == (stats.edges_deleted_count * stats.original_edges_deleted_count)) - { - result = 1.f * node_data->depth; - } - else - { - result = 2.f * (((float)stats.edges_added_count) / stats.edges_deleted_count) + - 4.f * (((float)stats.original_edges_added_count) / - stats.original_edges_deleted_count) + - 1.f * node_data->depth; - } - BOOST_ASSERT(result >= 0); - return result; - } - - template - inline bool - ContractNode(ContractorThreadData *data, const NodeID node, ContractionStats *stats = nullptr) - { - ContractorHeap &heap = data->heap; - std::size_t inserted_edges_size = data->inserted_edges.size(); - std::vector &inserted_edges = data->inserted_edges; - const constexpr bool SHORTCUT_ARC = true; - const constexpr bool FORWARD_DIRECTION_ENABLED = true; - const constexpr bool FORWARD_DIRECTION_DISABLED = false; - const constexpr bool REVERSE_DIRECTION_ENABLED = true; - const constexpr bool REVERSE_DIRECTION_DISABLED = false; - - for (auto in_edge : contractor_graph->GetAdjacentEdgeRange(node)) - { - const ContractorEdgeData &in_data = contractor_graph->GetEdgeData(in_edge); - const NodeID source = contractor_graph->GetTarget(in_edge); - if (source == node) - continue; - - if (RUNSIMULATION) - { - BOOST_ASSERT(stats != nullptr); - ++stats->edges_deleted_count; - stats->original_edges_deleted_count += in_data.originalEdges; - } - if (!in_data.backward) - { - continue; - } - - heap.Clear(); - heap.Insert(source, 0, ContractorHeapData()); - int max_distance = 0; - unsigned number_of_targets = 0; - - for (auto out_edge : contractor_graph->GetAdjacentEdgeRange(node)) - { - const ContractorEdgeData &out_data = contractor_graph->GetEdgeData(out_edge); - if (!out_data.forward) - { - continue; - } - const NodeID target = contractor_graph->GetTarget(out_edge); - if (node == target) - continue; - - const EdgeWeight path_distance = in_data.distance + out_data.distance; - if (target == source) - { - if (path_distance < node_weights[node]) - { - if (RUNSIMULATION) - { - // make sure to prune better, but keep inserting this loop if it should - // still be the best - // CAREFUL: This only works due to the independent node-setting. This - // guarantees that source is not connected to another node that is - // contracted - node_weights[source] = path_distance + 1; - BOOST_ASSERT(stats != nullptr); - stats->edges_added_count += 2; - stats->original_edges_added_count += - 2 * (out_data.originalEdges + in_data.originalEdges); - } - else - { - // CAREFUL: This only works due to the independent node-setting. This - // guarantees that source is not connected to another node that is - // contracted - node_weights[source] = path_distance; // make sure to prune better - inserted_edges.emplace_back( - source, target, path_distance, - out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, - FORWARD_DIRECTION_ENABLED, REVERSE_DIRECTION_DISABLED); - - inserted_edges.emplace_back( - target, source, path_distance, - out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, - FORWARD_DIRECTION_DISABLED, REVERSE_DIRECTION_ENABLED); - } - } - continue; - } - max_distance = std::max(max_distance, path_distance); - if (!heap.WasInserted(target)) - { - heap.Insert(target, INVALID_EDGE_WEIGHT, ContractorHeapData(0, true)); - ++number_of_targets; - } - } - - if (RUNSIMULATION) - { - const int constexpr SIMULATION_SEARCH_SPACE_SIZE = 1000; - Dijkstra(max_distance, number_of_targets, SIMULATION_SEARCH_SPACE_SIZE, *data, - node); - } - else - { - const int constexpr FULL_SEARCH_SPACE_SIZE = 2000; - Dijkstra(max_distance, number_of_targets, FULL_SEARCH_SPACE_SIZE, *data, node); - } - for (auto out_edge : contractor_graph->GetAdjacentEdgeRange(node)) - { - const ContractorEdgeData &out_data = contractor_graph->GetEdgeData(out_edge); - if (!out_data.forward) - { - continue; - } - const NodeID target = contractor_graph->GetTarget(out_edge); - if (target == node) - continue; - const int path_distance = in_data.distance + out_data.distance; - const int distance = heap.GetKey(target); - if (path_distance < distance) - { - if (RUNSIMULATION) - { - BOOST_ASSERT(stats != nullptr); - stats->edges_added_count += 2; - stats->original_edges_added_count += - 2 * (out_data.originalEdges + in_data.originalEdges); - } - else - { - inserted_edges.emplace_back(source, target, path_distance, - out_data.originalEdges + in_data.originalEdges, - node, SHORTCUT_ARC, FORWARD_DIRECTION_ENABLED, - REVERSE_DIRECTION_DISABLED); - - inserted_edges.emplace_back(target, source, path_distance, - out_data.originalEdges + in_data.originalEdges, - node, SHORTCUT_ARC, FORWARD_DIRECTION_DISABLED, - REVERSE_DIRECTION_ENABLED); - } - } - } - } - // Check For One-Way Streets to decide on the creation of self-loops - - if (!RUNSIMULATION) - { - std::size_t iend = inserted_edges.size(); - for (std::size_t i = inserted_edges_size; i < iend; ++i) - { - bool found = false; - for (std::size_t other = i + 1; other < iend; ++other) - { - if (inserted_edges[other].source != inserted_edges[i].source) - { - continue; - } - if (inserted_edges[other].target != inserted_edges[i].target) - { - continue; - } - if (inserted_edges[other].data.distance != inserted_edges[i].data.distance) - { - continue; - } - if (inserted_edges[other].data.shortcut != inserted_edges[i].data.shortcut) - { - continue; - } - inserted_edges[other].data.forward |= inserted_edges[i].data.forward; - inserted_edges[other].data.backward |= inserted_edges[i].data.backward; - found = true; - break; - } - if (!found) - { - inserted_edges[inserted_edges_size++] = inserted_edges[i]; - } - } - inserted_edges.resize(inserted_edges_size); - } - return true; - } - - inline void DeleteIncomingEdges(ContractorThreadData *data, const NodeID node) - { - std::vector &neighbours = data->neighbours; - neighbours.clear(); - - // find all neighbours - for (auto e : contractor_graph->GetAdjacentEdgeRange(node)) - { - const NodeID u = contractor_graph->GetTarget(e); - if (u != node) - { - neighbours.push_back(u); - } - } - // eliminate duplicate entries ( forward + backward edges ) - std::sort(neighbours.begin(), neighbours.end()); - neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); - - for (const auto i : util::irange(0, neighbours.size())) - { - contractor_graph->DeleteEdgesTo(neighbours[i], node); - } - } - - inline bool UpdateNodeNeighbours(std::vector &priorities, - std::vector &node_data, - ContractorThreadData *const data, - const NodeID node) - { - std::vector &neighbours = data->neighbours; - neighbours.clear(); - - // find all neighbours - for (auto e : contractor_graph->GetAdjacentEdgeRange(node)) - { - const NodeID u = contractor_graph->GetTarget(e); - if (u == node) - { - continue; - } - neighbours.push_back(u); - node_data[u].depth = (std::max)(node_data[node].depth + 1, node_data[u].depth); - } - // eliminate duplicate entries ( forward + backward edges ) - std::sort(neighbours.begin(), neighbours.end()); - neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); - - // re-evaluate priorities of neighboring nodes - for (const NodeID u : neighbours) - { - priorities[u] = EvaluateNodePriority(data, &(node_data)[u], u); - } - return true; - } - - inline bool IsNodeIndependent(const std::vector &priorities, - ContractorThreadData *const data, - NodeID node) const - { - const float priority = priorities[node]; - - std::vector &neighbours = data->neighbours; - neighbours.clear(); - - for (auto e : contractor_graph->GetAdjacentEdgeRange(node)) - { - const NodeID target = contractor_graph->GetTarget(e); - if (node == target) - { - continue; - } - const float target_priority = priorities[target]; - BOOST_ASSERT(target_priority >= 0); - // found a neighbour with lower priority? - if (priority > target_priority) - { - return false; - } - // tie breaking - if (std::abs(priority - target_priority) < std::numeric_limits::epsilon() && - bias(node, target)) - { - return false; - } - neighbours.push_back(target); - } - - std::sort(neighbours.begin(), neighbours.end()); - neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); - - // examine all neighbours that are at most 2 hops away - for (const NodeID u : neighbours) - { - for (auto e : contractor_graph->GetAdjacentEdgeRange(u)) - { - const NodeID target = contractor_graph->GetTarget(e); - if (node == target) - { - continue; - } - const float target_priority = priorities[target]; - BOOST_ASSERT(target_priority >= 0); - // found a neighbour with lower priority? - if (priority > target_priority) - { - return false; - } - // tie breaking - if (std::abs(priority - target_priority) < std::numeric_limits::epsilon() && - bias(node, target)) - { - return false; - } - } - } - return true; - } - - // This bias function takes up 22 assembly instructions in total on X86 - inline bool bias(const NodeID a, const NodeID b) const - { - const unsigned short hasha = fast_hash(a); - const unsigned short hashb = fast_hash(b); - - // The compiler optimizes that to conditional register flags but without branching - // statements! - if (hasha != hashb) - { - return hasha < hashb; - } - return a < b; - } - - std::shared_ptr contractor_graph; - stxxl::vector external_edge_list; - std::vector orig_node_id_from_new_node_id_map; - std::vector node_levels; - - // A list of weights for every node in the graph. - // The weight represents the cost for a u-turn on the segment in the base-graph in addition to - // its traversal. - // During contraction, self-loops are checked against this node weight to ensure that necessary - // self-loops are added. - std::vector node_weights; - std::vector is_core_node; - util::XORFastHash fast_hash; + ContractorConfig config; + std::size_t + LoadEdgeExpandedGraph(const std::string &edge_based_graph_path, + util::DeallocatingVector &edge_based_edge_list, + const std::string &edge_segment_lookup_path, + const std::string &edge_penalty_path, + const std::string &segment_speed_path); }; } } -#endif // CONTRACTOR_HPP +#endif // PROCESSING_CHAIN_HPP diff --git a/include/contractor/contractor_options.hpp b/include/contractor/contractor_config.hpp similarity index 68% rename from include/contractor/contractor_options.hpp rename to include/contractor/contractor_config.hpp index 04316e925..61c88b0a3 100644 --- a/include/contractor/contractor_options.hpp +++ b/include/contractor/contractor_config.hpp @@ -10,17 +10,21 @@ namespace osrm namespace contractor { -enum class return_code : unsigned -{ - ok, - fail, - exit -}; - struct ContractorConfig { ContractorConfig() : requested_num_threads(0) {} + // Infer the output names from the path of the .osrm file + void UseDefaultOutputNames() + { + level_output_path = osrm_input_path.string() + ".level"; + core_output_path = osrm_input_path.string() + ".core"; + graph_output_path = osrm_input_path.string() + ".hsgr"; + edge_based_graph_path = osrm_input_path.string() + ".ebg"; + edge_segment_lookup_path = osrm_input_path.string() + ".edge_segment_lookup"; + edge_penalty_path = osrm_input_path.string() + ".edge_penalties"; + } + boost::filesystem::path config_file_path; boost::filesystem::path osrm_input_path; boost::filesystem::path profile_path; @@ -48,13 +52,6 @@ struct ContractorConfig std::string debug_geometry_path; #endif }; - -struct ContractorOptions -{ - static return_code ParseArguments(int argc, char *argv[], ContractorConfig &extractor_config); - - static void GenerateOutputFilesNames(ContractorConfig &extractor_config); -}; } } diff --git a/include/contractor/graph_contractor.hpp b/include/contractor/graph_contractor.hpp new file mode 100644 index 000000000..65b31039f --- /dev/null +++ b/include/contractor/graph_contractor.hpp @@ -0,0 +1,1104 @@ +#ifndef GRAPH_CONTRACTOR_HPP +#define GRAPH_CONTRACTOR_HPP + +#include "util/binary_heap.hpp" +#include "util/deallocating_vector.hpp" +#include "util/dynamic_graph.hpp" +#include "util/percent.hpp" +#include "contractor/query_edge.hpp" +#include "util/xor_fast_hash.hpp" +#include "util/xor_fast_hash_storage.hpp" +#include "util/integer_range.hpp" +#include "util/simple_logger.hpp" +#include "util/timing_util.hpp" +#include "util/typedefs.hpp" + +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace osrm +{ +namespace contractor +{ + +class GraphContractor +{ + private: + struct ContractorEdgeData + { + ContractorEdgeData() + : distance(0), id(0), originalEdges(0), shortcut(0), forward(0), backward(0), + is_original_via_node_ID(false) + { + } + ContractorEdgeData(unsigned distance, + unsigned original_edges, + unsigned id, + bool shortcut, + bool forward, + bool backward) + : distance(distance), id(id), + originalEdges(std::min((unsigned)1 << 28, original_edges)), shortcut(shortcut), + forward(forward), backward(backward), is_original_via_node_ID(false) + { + } + unsigned distance; + unsigned id; + unsigned originalEdges : 28; + bool shortcut : 1; + bool forward : 1; + bool backward : 1; + bool is_original_via_node_ID : 1; + } data; + + struct ContractorHeapData + { + ContractorHeapData() {} + ContractorHeapData(short hop_, bool target_) : hop(hop_), target(target_) {} + + short hop = 0; + bool target = false; + }; + + using ContractorGraph = util::DynamicGraph; + // using ContractorHeap = util::BinaryHeap + // >; + using ContractorHeap = util::BinaryHeap>; + using ContractorEdge = ContractorGraph::InputEdge; + + struct ContractorThreadData + { + ContractorHeap heap; + std::vector inserted_edges; + std::vector neighbours; + explicit ContractorThreadData(NodeID nodes) : heap(nodes) {} + }; + + using NodeDepth = int; + + struct ContractionStats + { + int edges_deleted_count; + int edges_added_count; + int original_edges_deleted_count; + int original_edges_added_count; + ContractionStats() + : edges_deleted_count(0), edges_added_count(0), original_edges_deleted_count(0), + original_edges_added_count(0) + { + } + }; + + struct RemainingNodeData + { + RemainingNodeData() : id(0), is_independent(false) {} + NodeID id : 31; + bool is_independent : 1; + }; + + struct ThreadDataContainer + { + explicit ThreadDataContainer(int number_of_nodes) : number_of_nodes(number_of_nodes) {} + + inline ContractorThreadData *getThreadData() + { + bool exists = false; + auto &ref = data.local(exists); + if (!exists) + { + ref = std::make_shared(number_of_nodes); + } + + return ref.get(); + } + + int number_of_nodes; + using EnumerableThreadData = + tbb::enumerable_thread_specific>; + EnumerableThreadData data; + }; + + public: + template + GraphContractor(int nodes, ContainerT &input_edge_list) + : GraphContractor(nodes, input_edge_list, {}, {}) + { + } + + template + GraphContractor(int nodes, + ContainerT &input_edge_list, + std::vector &&node_levels_, + std::vector &&node_weights_) + : node_levels(std::move(node_levels_)), node_weights(std::move(node_weights_)) + { + std::vector edges; + edges.reserve(input_edge_list.size() * 2); + + const auto dend = input_edge_list.dend(); + for (auto diter = input_edge_list.dbegin(); diter != dend; ++diter) + { + BOOST_ASSERT_MSG(static_cast(std::max(diter->weight, 1)) > 0, + "edge distance < 1"); +#ifndef NDEBUG + if (static_cast(std::max(diter->weight, 1)) > 24 * 60 * 60 * 10) + { + util::SimpleLogger().Write(logWARNING) + << "Edge weight large -> " + << static_cast(std::max(diter->weight, 1)) << " : " + << static_cast(diter->source) << " -> " + << static_cast(diter->target); + } +#endif + edges.emplace_back(diter->source, diter->target, + static_cast(std::max(diter->weight, 1)), 1, + diter->edge_id, false, diter->forward ? true : false, + diter->backward ? true : false); + + edges.emplace_back(diter->target, diter->source, + static_cast(std::max(diter->weight, 1)), 1, + diter->edge_id, false, diter->backward ? true : false, + diter->forward ? true : false); + } + // clear input vector + input_edge_list.clear(); + // FIXME not sure if we need this + edges.shrink_to_fit(); + + tbb::parallel_sort(edges.begin(), edges.end()); + NodeID edge = 0; + for (NodeID i = 0; i < edges.size();) + { + const NodeID source = edges[i].source; + const NodeID target = edges[i].target; + const NodeID id = edges[i].data.id; + // remove eigenloops + if (source == target) + { + ++i; + continue; + } + ContractorEdge forward_edge; + ContractorEdge reverse_edge; + forward_edge.source = reverse_edge.source = source; + forward_edge.target = reverse_edge.target = target; + forward_edge.data.forward = reverse_edge.data.backward = true; + forward_edge.data.backward = reverse_edge.data.forward = false; + forward_edge.data.shortcut = reverse_edge.data.shortcut = false; + forward_edge.data.id = reverse_edge.data.id = id; + forward_edge.data.originalEdges = reverse_edge.data.originalEdges = 1; + forward_edge.data.distance = reverse_edge.data.distance = INVALID_EDGE_WEIGHT; + // remove parallel edges + while (i < edges.size() && edges[i].source == source && edges[i].target == target) + { + if (edges[i].data.forward) + { + forward_edge.data.distance = + std::min(edges[i].data.distance, forward_edge.data.distance); + } + if (edges[i].data.backward) + { + reverse_edge.data.distance = + std::min(edges[i].data.distance, reverse_edge.data.distance); + } + ++i; + } + // merge edges (s,t) and (t,s) into bidirectional edge + if (forward_edge.data.distance == reverse_edge.data.distance) + { + if ((int)forward_edge.data.distance != INVALID_EDGE_WEIGHT) + { + forward_edge.data.backward = true; + edges[edge++] = forward_edge; + } + } + else + { // insert seperate edges + if (((int)forward_edge.data.distance) != INVALID_EDGE_WEIGHT) + { + edges[edge++] = forward_edge; + } + if ((int)reverse_edge.data.distance != INVALID_EDGE_WEIGHT) + { + edges[edge++] = reverse_edge; + } + } + } + util::SimpleLogger().Write() << "merged " << edges.size() - edge << " edges out of " << edges.size(); + edges.resize(edge); + contractor_graph = std::make_shared(nodes, edges); + edges.clear(); + edges.shrink_to_fit(); + + BOOST_ASSERT(0 == edges.capacity()); + util::SimpleLogger().Write() << "contractor finished initalization"; + } + + void Run(double core_factor = 1.0) + { + // for the preperation we can use a big grain size, which is much faster (probably cache) + const constexpr size_t InitGrainSize = 100000; + const constexpr size_t PQGrainSize = 100000; + // auto_partitioner will automatically increase the blocksize if we have + // a lot of data. It is *important* for the last loop iterations + // (which have a very small dataset) that it is devisible. + const constexpr size_t IndependentGrainSize = 1; + const constexpr size_t ContractGrainSize = 1; + const constexpr size_t NeighboursGrainSize = 1; + const constexpr size_t DeleteGrainSize = 1; + + const NodeID number_of_nodes = contractor_graph->GetNumberOfNodes(); + util::Percent p(number_of_nodes); + + ThreadDataContainer thread_data_list(number_of_nodes); + + NodeID number_of_contracted_nodes = 0; + std::vector node_depth; + std::vector node_priorities; + is_core_node.resize(number_of_nodes, false); + + std::vector remaining_nodes(number_of_nodes); + // initialize priorities in parallel + tbb::parallel_for(tbb::blocked_range(0, number_of_nodes, InitGrainSize), + [this, &remaining_nodes](const tbb::blocked_range &range) + { + for (int x = range.begin(), end = range.end(); x != end; ++x) + { + remaining_nodes[x].id = x; + } + }); + + bool use_cached_node_priorities = !node_levels.empty(); + if (use_cached_node_priorities) + { + std::cout << "using cached node priorities ..." << std::flush; + node_priorities.swap(node_levels); + std::cout << "ok" << std::endl; + } + else + { + node_depth.resize(number_of_nodes, 0); + node_priorities.resize(number_of_nodes); + node_levels.resize(number_of_nodes); + + std::cout << "initializing elimination PQ ..." << std::flush; + tbb::parallel_for(tbb::blocked_range(0, number_of_nodes, PQGrainSize), + [this, &node_priorities, &node_depth, + &thread_data_list](const tbb::blocked_range &range) + { + ContractorThreadData *data = thread_data_list.getThreadData(); + for (int x = range.begin(), end = range.end(); x != end; ++x) + { + node_priorities[x] = + this->EvaluateNodePriority(data, node_depth[x], x); + } + }); + std::cout << "ok" << std::endl; + } + BOOST_ASSERT(node_priorities.size() == number_of_nodes); + + std::cout << "preprocessing " << number_of_nodes << " nodes ..." << std::flush; + + unsigned current_level = 0; + bool flushed_contractor = false; + while (number_of_nodes > 2 && + number_of_contracted_nodes < static_cast(number_of_nodes * core_factor)) + { + if (!flushed_contractor && (number_of_contracted_nodes > + static_cast(number_of_nodes * 0.65 * core_factor))) + { + util::DeallocatingVector + new_edge_set; // this one is not explicitely + // cleared since it goes out of + // scope anywa + std::cout << " [flush " << number_of_contracted_nodes << " nodes] " << std::flush; + + // Delete old heap data to free memory that we need for the coming operations + thread_data_list.data.clear(); + + // Create new priority array + std::vector new_node_priority(remaining_nodes.size()); + std::vector new_node_weights(remaining_nodes.size()); + // this map gives the old IDs from the new ones, necessary to get a consistent graph + // at the end of contraction + orig_node_id_from_new_node_id_map.resize(remaining_nodes.size()); + // this map gives the new IDs from the old ones, necessary to remap targets from the + // remaining graph + std::vector new_node_id_from_orig_id_map(number_of_nodes, SPECIAL_NODEID); + + for (const auto new_node_id : util::irange(0, remaining_nodes.size())) + { + auto &node = remaining_nodes[new_node_id]; + BOOST_ASSERT(node_priorities.size() > node.id); + new_node_priority[new_node_id] = node_priorities[node.id]; + BOOST_ASSERT(node_weights.size() > node.id); + new_node_weights[new_node_id] = node_weights[node.id]; + } + + // build forward and backward renumbering map and remap ids in remaining_nodes + for (const auto new_node_id : util::irange(0, remaining_nodes.size())) + { + auto &node = remaining_nodes[new_node_id]; + // create renumbering maps in both directions + orig_node_id_from_new_node_id_map[new_node_id] = node.id; + new_node_id_from_orig_id_map[node.id] = new_node_id; + node.id = new_node_id; + } + // walk over all nodes + for (const auto source : + util::irange(0, contractor_graph->GetNumberOfNodes())) + { + for (auto current_edge : contractor_graph->GetAdjacentEdgeRange(source)) + { + ContractorGraph::EdgeData &data = + contractor_graph->GetEdgeData(current_edge); + const NodeID target = contractor_graph->GetTarget(current_edge); + if (SPECIAL_NODEID == new_node_id_from_orig_id_map[source]) + { + external_edge_list.push_back({source, target, data}); + } + else + { + // node is not yet contracted. + // add (renumbered) outgoing edges to new util::DynamicGraph. + ContractorEdge new_edge = {new_node_id_from_orig_id_map[source], + new_node_id_from_orig_id_map[target], data}; + + new_edge.data.is_original_via_node_ID = true; + BOOST_ASSERT_MSG(SPECIAL_NODEID != new_node_id_from_orig_id_map[source], + "new source id not resolveable"); + BOOST_ASSERT_MSG(SPECIAL_NODEID != new_node_id_from_orig_id_map[target], + "new target id not resolveable"); + new_edge_set.push_back(new_edge); + } + } + } + + // Delete map from old NodeIDs to new ones. + new_node_id_from_orig_id_map.clear(); + new_node_id_from_orig_id_map.shrink_to_fit(); + + // Replace old priorities array by new one + node_priorities.swap(new_node_priority); + // Delete old node_priorities vector + // Due to the scope, these should get cleared automatically? @daniel-j-h do you + // agree? + new_node_priority.clear(); + new_node_priority.shrink_to_fit(); + + node_weights.swap(new_node_weights); + // old Graph is removed + contractor_graph.reset(); + + // create new graph + tbb::parallel_sort(new_edge_set.begin(), new_edge_set.end()); + contractor_graph = + std::make_shared(remaining_nodes.size(), new_edge_set); + + new_edge_set.clear(); + flushed_contractor = true; + + // INFO: MAKE SURE THIS IS THE LAST OPERATION OF THE FLUSH! + // reinitialize heaps and ThreadData objects with appropriate size + thread_data_list.number_of_nodes = contractor_graph->GetNumberOfNodes(); + } + + tbb::parallel_for( + tbb::blocked_range(0, remaining_nodes.size(), IndependentGrainSize), + [this, &node_priorities, &remaining_nodes, + &thread_data_list](const tbb::blocked_range &range) + { + ContractorThreadData *data = thread_data_list.getThreadData(); + // determine independent node set + for (auto i = range.begin(), end = range.end(); i != end; ++i) + { + const NodeID node = remaining_nodes[i].id; + remaining_nodes[i].is_independent = + this->IsNodeIndependent(node_priorities, data, node); + } + }); + + // sort all remaining nodes to the beginning of the sequence + const auto begin_independent_nodes = stable_partition( + remaining_nodes.begin(), remaining_nodes.end(), [](RemainingNodeData node_data) + { + return !node_data.is_independent; + }); + auto begin_independent_nodes_idx = + std::distance(remaining_nodes.begin(), begin_independent_nodes); + auto end_independent_nodes_idx = remaining_nodes.size(); + + if (!use_cached_node_priorities) + { + // write out contraction level + tbb::parallel_for( + tbb::blocked_range(begin_independent_nodes_idx, + end_independent_nodes_idx, ContractGrainSize), + [this, remaining_nodes, flushed_contractor, + current_level](const tbb::blocked_range &range) + { + if (flushed_contractor) + { + for (int position = range.begin(), end = range.end(); position != end; + ++position) + { + const NodeID x = remaining_nodes[position].id; + node_levels[orig_node_id_from_new_node_id_map[x]] = current_level; + } + } + else + { + for (int position = range.begin(), end = range.end(); position != end; + ++position) + { + const NodeID x = remaining_nodes[position].id; + node_levels[x] = current_level; + } + } + }); + } + + // contract independent nodes + tbb::parallel_for(tbb::blocked_range(begin_independent_nodes_idx, + end_independent_nodes_idx, + ContractGrainSize), + [this, &remaining_nodes, + &thread_data_list](const tbb::blocked_range &range) + { + ContractorThreadData *data = thread_data_list.getThreadData(); + for (int position = range.begin(), end = range.end(); + position != end; ++position) + { + const NodeID x = remaining_nodes[position].id; + this->ContractNode(data, x); + } + }); + + tbb::parallel_for( + tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, + DeleteGrainSize), + [this, &remaining_nodes, &thread_data_list](const tbb::blocked_range &range) + { + ContractorThreadData *data = thread_data_list.getThreadData(); + for (int position = range.begin(), end = range.end(); position != end; + ++position) + { + const NodeID x = remaining_nodes[position].id; + this->DeleteIncomingEdges(data, x); + } + }); + + // make sure we really sort each block + tbb::parallel_for( + thread_data_list.data.range(), + [&](const ThreadDataContainer::EnumerableThreadData::range_type &range) + { + for (auto &data : range) + tbb::parallel_sort(data->inserted_edges.begin(), + data->inserted_edges.end()); + }); + + // insert new edges + for (auto &data : thread_data_list.data) + { + for (const ContractorEdge &edge : data->inserted_edges) + { + const EdgeID current_edge_ID = + contractor_graph->FindEdge(edge.source, edge.target); + if (current_edge_ID < contractor_graph->EndEdges(edge.source)) + { + ContractorGraph::EdgeData ¤t_data = + contractor_graph->GetEdgeData(current_edge_ID); + if (current_data.shortcut && edge.data.forward == current_data.forward && + edge.data.backward == current_data.backward && + edge.data.distance < current_data.distance) + { + // found a duplicate edge with smaller weight, update it. + current_data = edge.data; + continue; + } + } + contractor_graph->InsertEdge(edge.source, edge.target, edge.data); + } + data->inserted_edges.clear(); + } + + if (!use_cached_node_priorities) + { + tbb::parallel_for( + tbb::blocked_range(begin_independent_nodes_idx, end_independent_nodes_idx, + NeighboursGrainSize), + [this, &node_priorities, &remaining_nodes, &node_depth, + &thread_data_list](const tbb::blocked_range &range) + { + ContractorThreadData *data = thread_data_list.getThreadData(); + for (int position = range.begin(), end = range.end(); position != end; + ++position) + { + NodeID x = remaining_nodes[position].id; + this->UpdateNodeNeighbours(node_priorities, node_depth, data, x); + } + }); + } + + // remove contracted nodes from the pool + number_of_contracted_nodes += end_independent_nodes_idx - begin_independent_nodes_idx; + remaining_nodes.resize(begin_independent_nodes_idx); + + p.printStatus(number_of_contracted_nodes); + ++current_level; + } + + if (remaining_nodes.size() > 2) + { + if (orig_node_id_from_new_node_id_map.size() > 0) + { + tbb::parallel_for(tbb::blocked_range(0, remaining_nodes.size(), InitGrainSize), + [this, &remaining_nodes](const tbb::blocked_range &range) + { + for (int x = range.begin(), end = range.end(); x != end; ++x) + { + const auto orig_id = remaining_nodes[x].id; + is_core_node[orig_node_id_from_new_node_id_map[orig_id]] = + true; + } + }); + } + else + { + tbb::parallel_for(tbb::blocked_range(0, remaining_nodes.size(), InitGrainSize), + [this, &remaining_nodes](const tbb::blocked_range &range) + { + for (int x = range.begin(), end = range.end(); x != end; ++x) + { + const auto orig_id = remaining_nodes[x].id; + is_core_node[orig_id] = true; + } + }); + } + } + else + { + // in this case we don't need core markers since we fully contracted + // the graph + is_core_node.clear(); + } + + util::SimpleLogger().Write() << "[core] " << remaining_nodes.size() << " nodes " + << contractor_graph->GetNumberOfEdges() << " edges." + << std::endl; + + thread_data_list.data.clear(); + } + + inline void GetCoreMarker(std::vector &out_is_core_node) + { + out_is_core_node.swap(is_core_node); + } + + inline void GetNodeLevels(std::vector &out_node_levels) + { + out_node_levels.swap(node_levels); + } + + template inline void GetEdges(util::DeallocatingVector &edges) + { + util::Percent p(contractor_graph->GetNumberOfNodes()); + util::SimpleLogger().Write() << "Getting edges of minimized graph"; + const NodeID number_of_nodes = contractor_graph->GetNumberOfNodes(); + if (contractor_graph->GetNumberOfNodes()) + { + Edge new_edge; + for (const auto node : util::irange(0u, number_of_nodes)) + { + p.printStatus(node); + for (auto edge : contractor_graph->GetAdjacentEdgeRange(node)) + { + const NodeID target = contractor_graph->GetTarget(edge); + const ContractorGraph::EdgeData &data = contractor_graph->GetEdgeData(edge); + if (!orig_node_id_from_new_node_id_map.empty()) + { + new_edge.source = orig_node_id_from_new_node_id_map[node]; + new_edge.target = orig_node_id_from_new_node_id_map[target]; + } + else + { + new_edge.source = node; + new_edge.target = target; + } + BOOST_ASSERT_MSG(SPECIAL_NODEID != new_edge.source, "Source id invalid"); + BOOST_ASSERT_MSG(SPECIAL_NODEID != new_edge.target, "Target id invalid"); + new_edge.data.distance = data.distance; + new_edge.data.shortcut = data.shortcut; + if (!data.is_original_via_node_ID && !orig_node_id_from_new_node_id_map.empty()) + { + // tranlate the _node id_ of the shortcutted node + new_edge.data.id = orig_node_id_from_new_node_id_map[data.id]; + } + else + { + new_edge.data.id = data.id; + } + BOOST_ASSERT_MSG(new_edge.data.id != INT_MAX, // 2^31 + "edge id invalid"); + new_edge.data.forward = data.forward; + new_edge.data.backward = data.backward; + edges.push_back(new_edge); + } + } + } + contractor_graph.reset(); + orig_node_id_from_new_node_id_map.clear(); + orig_node_id_from_new_node_id_map.shrink_to_fit(); + + BOOST_ASSERT(0 == orig_node_id_from_new_node_id_map.capacity()); + + edges.append(external_edge_list.begin(), external_edge_list.end()); + external_edge_list.clear(); + } + + private: + inline void RelaxNode(const NodeID node, + const NodeID forbidden_node, + const int distance, + ContractorHeap &heap) + { + const short current_hop = heap.GetData(node).hop + 1; + for (auto edge : contractor_graph->GetAdjacentEdgeRange(node)) + { + const ContractorEdgeData &data = contractor_graph->GetEdgeData(edge); + if (!data.forward) + { + continue; + } + const NodeID to = contractor_graph->GetTarget(edge); + if (forbidden_node == to) + { + continue; + } + const int to_distance = distance + data.distance; + + // New Node discovered -> Add to Heap + Node Info Storage + if (!heap.WasInserted(to)) + { + heap.Insert(to, to_distance, ContractorHeapData {current_hop, false}); + } + // Found a shorter Path -> Update distance + else if (to_distance < heap.GetKey(to)) + { + heap.DecreaseKey(to, to_distance); + heap.GetData(to).hop = current_hop; + } + } + } + + inline void Dijkstra(const int max_distance, + const unsigned number_of_targets, + const int maxNodes, + ContractorThreadData &data, + const NodeID middleNode) + { + + ContractorHeap &heap = data.heap; + + int nodes = 0; + unsigned number_of_targets_found = 0; + while (!heap.Empty()) + { + const NodeID node = heap.DeleteMin(); + const auto distance = heap.GetKey(node); + if (++nodes > maxNodes) + { + return; + } + if (distance > max_distance) + { + return; + } + + // Destination settled? + if (heap.GetData(node).target) + { + ++number_of_targets_found; + if (number_of_targets_found >= number_of_targets) + { + return; + } + } + + RelaxNode(node, middleNode, distance, heap); + } + } + + inline float EvaluateNodePriority(ContractorThreadData *const data, + const NodeDepth node_depth, + const NodeID node) + { + ContractionStats stats; + + // perform simulated contraction + ContractNode(data, node, &stats); + + // Result will contain the priority + float result; + if (0 == (stats.edges_deleted_count * stats.original_edges_deleted_count)) + { + result = 1.f * node_depth; + } + else + { + result = 2.f * (((float)stats.edges_added_count) / stats.edges_deleted_count) + + 4.f * (((float)stats.original_edges_added_count) / + stats.original_edges_deleted_count) + + 1.f * node_depth; + } + BOOST_ASSERT(result >= 0); + return result; + } + + template + inline bool + ContractNode(ContractorThreadData *data, const NodeID node, ContractionStats *stats = nullptr) + { + ContractorHeap &heap = data->heap; + std::size_t inserted_edges_size = data->inserted_edges.size(); + std::vector &inserted_edges = data->inserted_edges; + const constexpr bool SHORTCUT_ARC = true; + const constexpr bool FORWARD_DIRECTION_ENABLED = true; + const constexpr bool FORWARD_DIRECTION_DISABLED = false; + const constexpr bool REVERSE_DIRECTION_ENABLED = true; + const constexpr bool REVERSE_DIRECTION_DISABLED = false; + + for (auto in_edge : contractor_graph->GetAdjacentEdgeRange(node)) + { + const ContractorEdgeData &in_data = contractor_graph->GetEdgeData(in_edge); + const NodeID source = contractor_graph->GetTarget(in_edge); + if (source == node) + continue; + + if (RUNSIMULATION) + { + BOOST_ASSERT(stats != nullptr); + ++stats->edges_deleted_count; + stats->original_edges_deleted_count += in_data.originalEdges; + } + if (!in_data.backward) + { + continue; + } + + heap.Clear(); + heap.Insert(source, 0, ContractorHeapData {}); + int max_distance = 0; + unsigned number_of_targets = 0; + + for (auto out_edge : contractor_graph->GetAdjacentEdgeRange(node)) + { + const ContractorEdgeData &out_data = contractor_graph->GetEdgeData(out_edge); + if (!out_data.forward) + { + continue; + } + const NodeID target = contractor_graph->GetTarget(out_edge); + if (node == target) + continue; + + const EdgeWeight path_distance = in_data.distance + out_data.distance; + if (target == source) + { + if (path_distance < node_weights[node]) + { + if (RUNSIMULATION) + { + // make sure to prune better, but keep inserting this loop if it should + // still be the best + // CAREFUL: This only works due to the independent node-setting. This + // guarantees that source is not connected to another node that is + // contracted + node_weights[source] = path_distance + 1; + BOOST_ASSERT(stats != nullptr); + stats->edges_added_count += 2; + stats->original_edges_added_count += + 2 * (out_data.originalEdges + in_data.originalEdges); + } + else + { + // CAREFUL: This only works due to the independent node-setting. This + // guarantees that source is not connected to another node that is + // contracted + node_weights[source] = path_distance; // make sure to prune better + inserted_edges.emplace_back( + source, target, path_distance, + out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, + FORWARD_DIRECTION_ENABLED, REVERSE_DIRECTION_DISABLED); + + inserted_edges.emplace_back( + target, source, path_distance, + out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, + FORWARD_DIRECTION_DISABLED, REVERSE_DIRECTION_ENABLED); + } + } + continue; + } + max_distance = std::max(max_distance, path_distance); + if (!heap.WasInserted(target)) + { + heap.Insert(target, INVALID_EDGE_WEIGHT, ContractorHeapData {0, true}); + ++number_of_targets; + } + } + + if (RUNSIMULATION) + { + const int constexpr SIMULATION_SEARCH_SPACE_SIZE = 1000; + Dijkstra(max_distance, number_of_targets, SIMULATION_SEARCH_SPACE_SIZE, *data, + node); + } + else + { + const int constexpr FULL_SEARCH_SPACE_SIZE = 2000; + Dijkstra(max_distance, number_of_targets, FULL_SEARCH_SPACE_SIZE, *data, node); + } + for (auto out_edge : contractor_graph->GetAdjacentEdgeRange(node)) + { + const ContractorEdgeData &out_data = contractor_graph->GetEdgeData(out_edge); + if (!out_data.forward) + { + continue; + } + const NodeID target = contractor_graph->GetTarget(out_edge); + if (target == node) + continue; + const int path_distance = in_data.distance + out_data.distance; + const int distance = heap.GetKey(target); + if (path_distance < distance) + { + if (RUNSIMULATION) + { + BOOST_ASSERT(stats != nullptr); + stats->edges_added_count += 2; + stats->original_edges_added_count += + 2 * (out_data.originalEdges + in_data.originalEdges); + } + else + { + inserted_edges.emplace_back(source, target, path_distance, + out_data.originalEdges + in_data.originalEdges, + node, SHORTCUT_ARC, FORWARD_DIRECTION_ENABLED, + REVERSE_DIRECTION_DISABLED); + + inserted_edges.emplace_back(target, source, path_distance, + out_data.originalEdges + in_data.originalEdges, + node, SHORTCUT_ARC, FORWARD_DIRECTION_DISABLED, + REVERSE_DIRECTION_ENABLED); + } + } + } + } + // Check For One-Way Streets to decide on the creation of self-loops + + if (!RUNSIMULATION) + { + std::size_t iend = inserted_edges.size(); + for (std::size_t i = inserted_edges_size; i < iend; ++i) + { + bool found = false; + for (std::size_t other = i + 1; other < iend; ++other) + { + if (inserted_edges[other].source != inserted_edges[i].source) + { + continue; + } + if (inserted_edges[other].target != inserted_edges[i].target) + { + continue; + } + if (inserted_edges[other].data.distance != inserted_edges[i].data.distance) + { + continue; + } + if (inserted_edges[other].data.shortcut != inserted_edges[i].data.shortcut) + { + continue; + } + inserted_edges[other].data.forward |= inserted_edges[i].data.forward; + inserted_edges[other].data.backward |= inserted_edges[i].data.backward; + found = true; + break; + } + if (!found) + { + inserted_edges[inserted_edges_size++] = inserted_edges[i]; + } + } + inserted_edges.resize(inserted_edges_size); + } + return true; + } + + inline void DeleteIncomingEdges(ContractorThreadData *data, const NodeID node) + { + std::vector &neighbours = data->neighbours; + neighbours.clear(); + + // find all neighbours + for (auto e : contractor_graph->GetAdjacentEdgeRange(node)) + { + const NodeID u = contractor_graph->GetTarget(e); + if (u != node) + { + neighbours.push_back(u); + } + } + // eliminate duplicate entries ( forward + backward edges ) + std::sort(neighbours.begin(), neighbours.end()); + neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); + + for (const auto i : util::irange(0, neighbours.size())) + { + contractor_graph->DeleteEdgesTo(neighbours[i], node); + } + } + + inline bool UpdateNodeNeighbours(std::vector &priorities, + std::vector &node_depth, + ContractorThreadData *const data, + const NodeID node) + { + std::vector &neighbours = data->neighbours; + neighbours.clear(); + + // find all neighbours + for (auto e : contractor_graph->GetAdjacentEdgeRange(node)) + { + const NodeID u = contractor_graph->GetTarget(e); + if (u == node) + { + continue; + } + neighbours.push_back(u); + node_depth[u] = std::max(node_depth[node] + 1, node_depth[u]); + } + // eliminate duplicate entries ( forward + backward edges ) + std::sort(neighbours.begin(), neighbours.end()); + neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); + + // re-evaluate priorities of neighboring nodes + for (const NodeID u : neighbours) + { + priorities[u] = EvaluateNodePriority(data, node_depth[u], u); + } + return true; + } + + inline bool IsNodeIndependent(const std::vector &priorities, + ContractorThreadData *const data, + NodeID node) const + { + const float priority = priorities[node]; + + std::vector &neighbours = data->neighbours; + neighbours.clear(); + + for (auto e : contractor_graph->GetAdjacentEdgeRange(node)) + { + const NodeID target = contractor_graph->GetTarget(e); + if (node == target) + { + continue; + } + const float target_priority = priorities[target]; + BOOST_ASSERT(target_priority >= 0); + // found a neighbour with lower priority? + if (priority > target_priority) + { + return false; + } + // tie breaking + if (std::abs(priority - target_priority) < std::numeric_limits::epsilon() && + bias(node, target)) + { + return false; + } + neighbours.push_back(target); + } + + std::sort(neighbours.begin(), neighbours.end()); + neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); + + // examine all neighbours that are at most 2 hops away + for (const NodeID u : neighbours) + { + for (auto e : contractor_graph->GetAdjacentEdgeRange(u)) + { + const NodeID target = contractor_graph->GetTarget(e); + if (node == target) + { + continue; + } + const float target_priority = priorities[target]; + BOOST_ASSERT(target_priority >= 0); + // found a neighbour with lower priority? + if (priority > target_priority) + { + return false; + } + // tie breaking + if (std::abs(priority - target_priority) < std::numeric_limits::epsilon() && + bias(node, target)) + { + return false; + } + } + } + return true; + } + + // This bias function takes up 22 assembly instructions in total on X86 + inline bool bias(const NodeID a, const NodeID b) const + { + const unsigned short hasha = fast_hash(a); + const unsigned short hashb = fast_hash(b); + + // The compiler optimizes that to conditional register flags but without branching + // statements! + if (hasha != hashb) + { + return hasha < hashb; + } + return a < b; + } + + std::shared_ptr contractor_graph; + stxxl::vector external_edge_list; + std::vector orig_node_id_from_new_node_id_map; + std::vector node_levels; + + // A list of weights for every node in the graph. + // The weight represents the cost for a u-turn on the segment in the base-graph in addition to + // its traversal. + // During contraction, self-loops are checked against this node weight to ensure that necessary + // self-loops are added. + std::vector node_weights; + std::vector is_core_node; + util::XORFastHash fast_hash; +}; +} +} + +#endif // CONTRACTOR_HPP diff --git a/include/contractor/processing_chain.hpp b/include/contractor/processing_chain.hpp deleted file mode 100644 index e75af29e0..000000000 --- a/include/contractor/processing_chain.hpp +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef PROCESSING_CHAIN_HPP -#define PROCESSING_CHAIN_HPP - -#include "contractor/contractor.hpp" -#include "contractor/contractor_options.hpp" -#include "contractor/query_edge.hpp" -#include "extractor/edge_based_edge.hpp" -#include "util/static_graph.hpp" -#include "util/deallocating_vector.hpp" -#include "util/node_based_graph.hpp" - -#include - -#include - -#include - -struct lua_State; - -namespace osrm -{ -namespace extractor -{ -struct SpeedProfileProperties; -struct EdgeBasedNode; -} -namespace contractor -{ - -/** - \brief class of 'prepare' utility. - */ -class Prepare -{ - public: - using EdgeData = QueryEdge::EdgeData; - - explicit Prepare(ContractorConfig contractor_config) : config(std::move(contractor_config)) {} - Prepare(const Prepare &) = delete; - ~Prepare(); - - int Run(); - - protected: - void ContractGraph(const unsigned max_edge_id, - util::DeallocatingVector &edge_based_edge_list, - util::DeallocatingVector &contracted_edge_list, - std::vector &&node_weights, - std::vector &is_core_node, - std::vector &node_levels) const; - void WriteCoreNodeMarker(std::vector &&is_core_node) const; - void WriteNodeLevels(std::vector &&node_levels) const; - void ReadNodeLevels(std::vector &contraction_order) const; - std::size_t - WriteContractedGraph(unsigned number_of_edge_based_nodes, - const util::DeallocatingVector &contracted_edge_list); - void FindComponents(unsigned max_edge_id, - const util::DeallocatingVector &edges, - std::vector &nodes) const; - - private: - ContractorConfig config; - std::size_t - LoadEdgeExpandedGraph(const std::string &edge_based_graph_path, - util::DeallocatingVector &edge_based_edge_list, - const std::string &edge_segment_lookup_path, - const std::string &edge_penalty_path, - const std::string &segment_speed_path); -}; -} -} - -#endif // PROCESSING_CHAIN_HPP diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 359584682..7238bec6c 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -4,7 +4,8 @@ // implements all data storage when shared memory _IS_ used #include "engine/datafacade/datafacade_base.hpp" -#include "engine/datafacade/shared_datatype.hpp" +#include "storage/shared_datatype.hpp" +#include "storage/shared_memory.hpp" #include "engine/geospatial_query.hpp" #include "util/range_table.hpp" @@ -44,18 +45,18 @@ template class SharedDataFacade final : public BaseDataFacade< using TimeStampedRTreePair = std::pair>; using RTreeNode = typename SharedRTree::TreeNode; - SharedDataLayout *data_layout; + storage::SharedDataLayout *data_layout; char *shared_memory; - SharedDataTimestamp *data_timestamp_ptr; + storage::SharedDataTimestamp *data_timestamp_ptr; - SharedDataType CURRENT_LAYOUT; - SharedDataType CURRENT_DATA; + storage::SharedDataType CURRENT_LAYOUT; + storage::SharedDataType CURRENT_DATA; unsigned CURRENT_TIMESTAMP; unsigned m_check_sum; std::unique_ptr m_query_graph; - std::unique_ptr m_layout_memory; - std::unique_ptr m_large_memory; + std::unique_ptr m_layout_memory; + std::unique_ptr m_large_memory; std::string m_timestamp; std::shared_ptr::vector> m_coordinate_list; @@ -79,17 +80,17 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadChecksum() { m_check_sum = - *data_layout->GetBlockPtr(shared_memory, SharedDataLayout::HSGR_CHECKSUM); + *data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::HSGR_CHECKSUM); util::SimpleLogger().Write() << "set checksum: " << m_check_sum; } void LoadTimestamp() { char *timestamp_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::TIMESTAMP); - m_timestamp.resize(data_layout->GetBlockSize(SharedDataLayout::TIMESTAMP)); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::TIMESTAMP); + m_timestamp.resize(data_layout->GetBlockSize(storage::SharedDataLayout::TIMESTAMP)); std::copy(timestamp_ptr, - timestamp_ptr + data_layout->GetBlockSize(SharedDataLayout::TIMESTAMP), + timestamp_ptr + data_layout->GetBlockSize(storage::SharedDataLayout::TIMESTAMP), m_timestamp.begin()); } @@ -98,11 +99,11 @@ template class SharedDataFacade final : public BaseDataFacade< BOOST_ASSERT_MSG(!m_coordinate_list->empty(), "coordinates must be loaded before r-tree"); RTreeNode *tree_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::R_SEARCH_TREE); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::R_SEARCH_TREE); m_static_rtree.reset(new TimeStampedRTreePair( CURRENT_TIMESTAMP, util::make_unique( - tree_ptr, data_layout->num_entries[SharedDataLayout::R_SEARCH_TREE], + tree_ptr, data_layout->num_entries[storage::SharedDataLayout::R_SEARCH_TREE], file_index_path, m_coordinate_list))); m_geospatial_query.reset( new SharedGeospatialQuery(*m_static_rtree->second, m_coordinate_list)); @@ -111,15 +112,15 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadGraph() { GraphNode *graph_nodes_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GRAPH_NODE_LIST); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::GRAPH_NODE_LIST); GraphEdge *graph_edges_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GRAPH_EDGE_LIST); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::GRAPH_EDGE_LIST); typename util::ShM::vector node_list( - graph_nodes_ptr, data_layout->num_entries[SharedDataLayout::GRAPH_NODE_LIST]); + graph_nodes_ptr, data_layout->num_entries[storage::SharedDataLayout::GRAPH_NODE_LIST]); typename util::ShM::vector edge_list( - graph_edges_ptr, data_layout->num_entries[SharedDataLayout::GRAPH_EDGE_LIST]); + graph_edges_ptr, data_layout->num_entries[storage::SharedDataLayout::GRAPH_EDGE_LIST]); m_query_graph.reset(new QueryGraph(node_list, edge_list)); } @@ -128,56 +129,56 @@ template class SharedDataFacade final : public BaseDataFacade< util::FixedPointCoordinate *coordinate_list_ptr = data_layout->GetBlockPtr(shared_memory, - SharedDataLayout::COORDINATE_LIST); + storage::SharedDataLayout::COORDINATE_LIST); m_coordinate_list = util::make_unique::vector>( - coordinate_list_ptr, data_layout->num_entries[SharedDataLayout::COORDINATE_LIST]); + coordinate_list_ptr, data_layout->num_entries[storage::SharedDataLayout::COORDINATE_LIST]); extractor::TravelMode *travel_mode_list_ptr = data_layout->GetBlockPtr(shared_memory, - SharedDataLayout::TRAVEL_MODE); + storage::SharedDataLayout::TRAVEL_MODE); typename util::ShM::vector travel_mode_list( - travel_mode_list_ptr, data_layout->num_entries[SharedDataLayout::TRAVEL_MODE]); + travel_mode_list_ptr, data_layout->num_entries[storage::SharedDataLayout::TRAVEL_MODE]); m_travel_mode_list.swap(travel_mode_list); extractor::TurnInstruction *turn_instruction_list_ptr = data_layout->GetBlockPtr( - shared_memory, SharedDataLayout::TURN_INSTRUCTION); + shared_memory, storage::SharedDataLayout::TURN_INSTRUCTION); typename util::ShM::vector turn_instruction_list( turn_instruction_list_ptr, - data_layout->num_entries[SharedDataLayout::TURN_INSTRUCTION]); + data_layout->num_entries[storage::SharedDataLayout::TURN_INSTRUCTION]); m_turn_instruction_list.swap(turn_instruction_list); unsigned *name_id_list_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_ID_LIST); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::NAME_ID_LIST); typename util::ShM::vector name_id_list( - name_id_list_ptr, data_layout->num_entries[SharedDataLayout::NAME_ID_LIST]); + name_id_list_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_ID_LIST]); m_name_ID_list.swap(name_id_list); } void LoadViaNodeList() { NodeID *via_node_list_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::VIA_NODE_LIST); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::VIA_NODE_LIST); typename util::ShM::vector via_node_list( - via_node_list_ptr, data_layout->num_entries[SharedDataLayout::VIA_NODE_LIST]); + via_node_list_ptr, data_layout->num_entries[storage::SharedDataLayout::VIA_NODE_LIST]); m_via_node_list.swap(via_node_list); } void LoadNames() { unsigned *offsets_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_OFFSETS); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::NAME_OFFSETS); NameIndexBlock *blocks_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_BLOCKS); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::NAME_BLOCKS); typename util::ShM::vector name_offsets( - offsets_ptr, data_layout->num_entries[SharedDataLayout::NAME_OFFSETS]); + offsets_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_OFFSETS]); typename util::ShM::vector name_blocks( - blocks_ptr, data_layout->num_entries[SharedDataLayout::NAME_BLOCKS]); + blocks_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_BLOCKS]); char *names_list_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::NAME_CHAR_LIST); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::NAME_CHAR_LIST); typename util::ShM::vector names_char_list( - names_list_ptr, data_layout->num_entries[SharedDataLayout::NAME_CHAR_LIST]); + names_list_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_CHAR_LIST]); m_name_table = util::make_unique>( name_offsets, name_blocks, static_cast(names_char_list.size())); @@ -186,37 +187,37 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadCoreInformation() { - if (data_layout->num_entries[SharedDataLayout::CORE_MARKER] <= 0) + if (data_layout->num_entries[storage::SharedDataLayout::CORE_MARKER] <= 0) { return; } unsigned *core_marker_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::CORE_MARKER); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::CORE_MARKER); typename util::ShM::vector is_core_node( - core_marker_ptr, data_layout->num_entries[SharedDataLayout::CORE_MARKER]); + core_marker_ptr, data_layout->num_entries[storage::SharedDataLayout::CORE_MARKER]); m_is_core_node.swap(is_core_node); } void LoadGeometries() { unsigned *geometries_compressed_ptr = data_layout->GetBlockPtr( - shared_memory, SharedDataLayout::GEOMETRIES_INDICATORS); + shared_memory, storage::SharedDataLayout::GEOMETRIES_INDICATORS); typename util::ShM::vector edge_is_compressed( geometries_compressed_ptr, - data_layout->num_entries[SharedDataLayout::GEOMETRIES_INDICATORS]); + data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDICATORS]); m_edge_is_compressed.swap(edge_is_compressed); unsigned *geometries_index_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GEOMETRIES_INDEX); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::GEOMETRIES_INDEX); typename util::ShM::vector geometry_begin_indices( - geometries_index_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_INDEX]); + geometries_index_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDEX]); m_geometry_indices.swap(geometry_begin_indices); unsigned *geometries_list_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::GEOMETRIES_LIST); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::GEOMETRIES_LIST); typename util::ShM::vector geometry_list( - geometries_list_ptr, data_layout->num_entries[SharedDataLayout::GEOMETRIES_LIST]); + geometries_list_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_LIST]); m_geometry_list.swap(geometry_list); } @@ -227,15 +228,16 @@ template class SharedDataFacade final : public BaseDataFacade< SharedDataFacade() { - if (!datastore::SharedMemory::RegionExists(CURRENT_REGIONS)) + if (!storage::SharedMemory::RegionExists(storage::CURRENT_REGIONS)) { throw util::exception("No shared memory blocks found, have you forgotten to run osrm-datastore?"); } - data_timestamp_ptr = (SharedDataTimestamp *)datastore::SharedMemoryFactory::Get( - CURRENT_REGIONS, sizeof(SharedDataTimestamp), false, false) - ->Ptr(); - CURRENT_LAYOUT = LAYOUT_NONE; - CURRENT_DATA = DATA_NONE; + data_timestamp_ptr = static_cast( + storage::makeSharedMemory(storage::CURRENT_REGIONS, + sizeof(storage::SharedDataTimestamp), false, false) + ->Ptr()); + CURRENT_LAYOUT = storage::LAYOUT_NONE; + CURRENT_DATA = storage::DATA_NONE; CURRENT_TIMESTAMP = 0; // load data @@ -248,7 +250,6 @@ template class SharedDataFacade final : public BaseDataFacade< CURRENT_DATA != data_timestamp_ptr->data || CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) { - // Get exclusive lock util::SimpleLogger().Write(logDEBUG) << "Updates available, getting exclusive lock"; boost::unique_lock lock(data_mutex); @@ -257,8 +258,8 @@ template class SharedDataFacade final : public BaseDataFacade< CURRENT_DATA != data_timestamp_ptr->data) { // release the previous shared memory segments - datastore::SharedMemory::Remove(CURRENT_LAYOUT); - datastore::SharedMemory::Remove(CURRENT_DATA); + storage::SharedMemory::Remove(CURRENT_LAYOUT); + storage::SharedMemory::Remove(CURRENT_DATA); CURRENT_LAYOUT = data_timestamp_ptr->layout; CURRENT_DATA = data_timestamp_ptr->data; @@ -277,15 +278,15 @@ template class SharedDataFacade final : public BaseDataFacade< CURRENT_TIMESTAMP = data_timestamp_ptr->timestamp; util::SimpleLogger().Write(logDEBUG) << "Performing data reload"; - m_layout_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_LAYOUT)); + m_layout_memory.reset(storage::makeSharedMemory(CURRENT_LAYOUT)); - data_layout = (SharedDataLayout *) (m_layout_memory->Ptr()); + data_layout = (storage::SharedDataLayout *) (m_layout_memory->Ptr()); - m_large_memory.reset(datastore::SharedMemoryFactory::Get(CURRENT_DATA)); + m_large_memory.reset(storage::makeSharedMemory(CURRENT_DATA)); shared_memory = (char *) (m_large_memory->Ptr()); const char *file_index_ptr = - data_layout->GetBlockPtr(shared_memory, SharedDataLayout::FILE_INDEX_PATH); + data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::FILE_INDEX_PATH); file_index_path = boost::filesystem::path(file_index_ptr); if (!boost::filesystem::exists(file_index_path)) { util::SimpleLogger().Write(logDEBUG) << "Leaf file name " @@ -303,8 +304,6 @@ template class SharedDataFacade final : public BaseDataFacade< LoadNames(); LoadCoreInformation(); - data_layout->PrintInformation(); - util::SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { diff --git a/include/engine/osrm_impl.hpp b/include/engine/engine.hpp similarity index 81% rename from include/engine/osrm_impl.hpp rename to include/engine/engine.hpp index c37135102..3b23445ba 100644 --- a/include/engine/osrm_impl.hpp +++ b/include/engine/engine.hpp @@ -1,10 +1,9 @@ -#ifndef OSRM_IMPL_HPP -#define OSRM_IMPL_HPP +#ifndef ENGINE_HPP +#define ENGINE_HPP #include "contractor/query_edge.hpp" #include "osrm/json_container.hpp" -#include "osrm/libosrm_config.hpp" #include "osrm/osrm.hpp" #include @@ -14,6 +13,11 @@ namespace osrm { +namespace storage +{ +struct SharedBarriers; +} + namespace util { namespace json @@ -24,33 +28,32 @@ struct Object; namespace engine { +struct EngineConfig; struct RouteParameters; namespace plugins { class BasePlugin; } - namespace datafacade { -struct SharedBarriers; template class BaseDataFacade; } -class OSRM::OSRM_impl final +class Engine final { private: using PluginMap = std::unordered_map>; public: - OSRM_impl(LibOSRMConfig &lib_config); - OSRM_impl(const OSRM_impl &) = delete; + Engine(EngineConfig &config_); + Engine(const Engine &) = delete; int RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result); private: void RegisterPlugin(plugins::BasePlugin *plugin); PluginMap plugin_map; // will only be initialized if shared memory is used - std::unique_ptr barrier; + std::unique_ptr barrier; // base class pointer to the objects datafacade::BaseDataFacade *query_data_facade; diff --git a/include/osrm/libosrm_config.hpp b/include/engine/engine_config.hpp similarity index 94% rename from include/osrm/libosrm_config.hpp rename to include/engine/engine_config.hpp index 743c68225..d16f3f4ce 100644 --- a/include/osrm/libosrm_config.hpp +++ b/include/engine/engine_config.hpp @@ -25,8 +25,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef LIBOSRM_CONFIG_HPP -#define LIBOSRM_CONFIG_HPP +#ifndef ENGINE_CONFIG_HPP +#define ENGINE_CONFIG_HPP #include @@ -36,7 +36,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace osrm { -struct LibOSRMConfig +namespace engine +{ + +struct EngineConfig { std::unordered_map server_paths; int max_locations_trip = -1; @@ -45,6 +48,8 @@ struct LibOSRMConfig int max_locations_map_matching = -1; bool use_shared_memory = true; }; + +} } #endif // SERVER_CONFIG_HPP diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index 1c258b8ef..ca9b685c2 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -30,9 +30,63 @@ struct PhantomNode util::FixedPointCoordinate &location, unsigned short fwd_segment_position, extractor::TravelMode forward_travel_mode, - extractor::TravelMode backward_travel_mode); + extractor::TravelMode backward_travel_mode) + : forward_node_id(forward_node_id), reverse_node_id(reverse_node_id), name_id(name_id), + forward_weight(forward_weight), reverse_weight(reverse_weight), + forward_offset(forward_offset), reverse_offset(reverse_offset), + packed_geometry_id(packed_geometry_id), component{component_id, is_tiny_component}, + location(location), fwd_segment_position(fwd_segment_position), + forward_travel_mode(forward_travel_mode), backward_travel_mode(backward_travel_mode) + { + } - PhantomNode(); + PhantomNode() + : forward_node_id(SPECIAL_NODEID), reverse_node_id(SPECIAL_NODEID), + name_id(std::numeric_limits::max()), forward_weight(INVALID_EDGE_WEIGHT), + reverse_weight(INVALID_EDGE_WEIGHT), forward_offset(0), reverse_offset(0), + packed_geometry_id(SPECIAL_EDGEID), component{INVALID_COMPONENTID, false}, + fwd_segment_position(0), forward_travel_mode(TRAVEL_MODE_INACCESSIBLE), + backward_travel_mode(TRAVEL_MODE_INACCESSIBLE) + { + } + + int GetForwardWeightPlusOffset() const + { + if (SPECIAL_NODEID == forward_node_id) + { + return 0; + } + return forward_offset + forward_weight; + } + + int GetReverseWeightPlusOffset() const + { + if (SPECIAL_NODEID == reverse_node_id) + { + return 0; + } + return reverse_offset + reverse_weight; + } + + bool IsBidirected() const + { + return (forward_node_id != SPECIAL_NODEID) && (reverse_node_id != SPECIAL_NODEID); + } + + bool IsCompressed() const { return (forward_offset != 0) || (reverse_offset != 0); } + + bool IsValid(const unsigned number_of_nodes) const + { + return location.IsValid() && + ((forward_node_id < number_of_nodes) || (reverse_node_id < number_of_nodes)) && + ((forward_weight != INVALID_EDGE_WEIGHT) || + (reverse_weight != INVALID_EDGE_WEIGHT)) && + (component.id != INVALID_COMPONENTID) && (name_id != INVALID_NAMEID); + } + + bool IsValid() const { return location.IsValid() && (name_id != INVALID_NAMEID); } + + bool operator==(const PhantomNode &other) const { return location == other.location; } template PhantomNode(const OtherT &other, const util::FixedPointCoordinate &foot_point) @@ -82,20 +136,6 @@ struct PhantomNode // but the saved byte would be padding anyway extractor::TravelMode forward_travel_mode; extractor::TravelMode backward_travel_mode; - - int GetForwardWeightPlusOffset() const; - - int GetReverseWeightPlusOffset() const; - - bool IsBidirected() const; - - bool IsCompressed() const; - - bool is_valid(const unsigned numberOfNodes) const; - - bool IsValid() const; - - bool operator==(const PhantomNode &other) const; }; #ifndef _MSC_VER diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index 1a37cfd06..0f607ba57 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -96,7 +96,7 @@ template class DistanceTablePlugin final : public BasePlugin { PhantomNode current_phantom_node; ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node); - if (current_phantom_node.is_valid(facade->GetNumberOfNodes())) + if (current_phantom_node.IsValid(facade->GetNumberOfNodes())) { if (route_parameters.is_source[i]) { @@ -130,7 +130,7 @@ template class DistanceTablePlugin final : public BasePlugin facade->NearestPhantomNodeWithAlternativeFromBigComponent( route_parameters.coordinates[i], bearing, range); // we didn't found a fitting node, return error - if (!phantom_node_source_out_iter->first.is_valid(facade->GetNumberOfNodes())) + if (!phantom_node_source_out_iter->first.IsValid(facade->GetNumberOfNodes())) { json_result.values["status_message"] = std::string("Could not find a matching segment for coordinate ") + @@ -153,7 +153,7 @@ template class DistanceTablePlugin final : public BasePlugin facade->NearestPhantomNodeWithAlternativeFromBigComponent( route_parameters.coordinates[i], bearing, range); // we didn't found a fitting node, return error - if (!phantom_node_target_out_iter->first.is_valid(facade->GetNumberOfNodes())) + if (!phantom_node_target_out_iter->first.IsValid(facade->GetNumberOfNodes())) { json_result.values["status_message"] = std::string("Could not find a matching segment for coordinate ") + diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index 45a436dbf..db8440547 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -66,7 +66,7 @@ template class RoundTripPlugin final : public BasePlugin { PhantomNode current_phantom_node; ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node); - if (current_phantom_node.is_valid(facade->GetNumberOfNodes())) + if (current_phantom_node.IsValid(facade->GetNumberOfNodes())) { phantom_node_list.push_back(std::move(current_phantom_node)); continue; @@ -83,7 +83,7 @@ template class RoundTripPlugin final : public BasePlugin break; } phantom_node_list.push_back(std::move(results.front().phantom_node)); - BOOST_ASSERT(phantom_node_list.back().is_valid(facade->GetNumberOfNodes())); + BOOST_ASSERT(phantom_node_list.back().IsValid(facade->GetNumberOfNodes())); } return phantom_node_list; diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index 49768df10..b3d8bb00f 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -85,7 +85,7 @@ template class ViaRoutePlugin final : public BasePlugin { ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], phantom_node_pair_list[i].first); - if (phantom_node_pair_list[i].first.is_valid(facade->GetNumberOfNodes())) + if (phantom_node_pair_list[i].first.IsValid(facade->GetNumberOfNodes())) { continue; } @@ -97,15 +97,15 @@ template class ViaRoutePlugin final : public BasePlugin phantom_node_pair_list[i] = facade->NearestPhantomNodeWithAlternativeFromBigComponent( route_parameters.coordinates[i], bearing, range); // we didn't found a fitting node, return error - if (!phantom_node_pair_list[i].first.is_valid(facade->GetNumberOfNodes())) + if (!phantom_node_pair_list[i].first.IsValid(facade->GetNumberOfNodes())) { json_result.values["status_message"] = std::string("Could not find a matching segment for coordinate ") + std::to_string(i); return Status::NoSegment; } - BOOST_ASSERT(phantom_node_pair_list[i].first.is_valid(facade->GetNumberOfNodes())); - BOOST_ASSERT(phantom_node_pair_list[i].second.is_valid(facade->GetNumberOfNodes())); + BOOST_ASSERT(phantom_node_pair_list[i].first.IsValid(facade->GetNumberOfNodes())); + BOOST_ASSERT(phantom_node_pair_list[i].second.IsValid(facade->GetNumberOfNodes())); } auto snapped_phantoms = snapPhantomNodes(phantom_node_pair_list); diff --git a/include/engine/route_parameters.hpp b/include/engine/route_parameters.hpp new file mode 100644 index 000000000..e808880ec --- /dev/null +++ b/include/engine/route_parameters.hpp @@ -0,0 +1,125 @@ +/* + +Copyright (c) 2016, Project OSRM contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef ROUTE_PARAMETERS_HPP +#define ROUTE_PARAMETERS_HPP + +#include "osrm/coordinate.hpp" + +#include +#include + +#include +#include + +namespace osrm +{ +namespace engine +{ + +struct RouteParameters +{ + RouteParameters(); + + void SetZoomLevel(const short level); + + void SetNumberOfResults(const short number); + + void SetAlternateRouteFlag(const bool flag); + + void SetUTurn(const bool flag); + + void SetAllUTurns(const bool flag); + + void SetClassify(const bool classify); + + void SetMatchingBeta(const double beta); + + void SetGPSPrecision(const double precision); + + void SetDeprecatedAPIFlag(const std::string &); + + void SetChecksum(const unsigned check_sum); + + void SetInstructionFlag(const bool flag); + + void SetService(const std::string &service); + + void SetOutputFormat(const std::string &format); + + void SetJSONpParameter(const std::string ¶meter); + + void AddHint(const std::string &hint); + + void AddTimestamp(const unsigned timestamp); + + void AddBearing(const boost::fusion::vector> &received_bearing, + boost::spirit::qi::unused_type unused, + bool &pass); + + void SetLanguage(const std::string &language); + + void SetGeometryFlag(const bool flag); + + void SetCompressionFlag(const bool flag); + + void AddCoordinate(const boost::fusion::vector &received_coordinates); + + void AddDestination(const boost::fusion::vector &received_coordinates); + + void AddSource(const boost::fusion::vector &received_coordinates); + + void SetCoordinatesFromGeometry(const std::string &geometry_string); + + short zoom_level; + bool print_instructions; + bool alternate_route; + bool geometry; + bool compression; + bool deprecatedAPI; + bool uturn_default; + bool classify; + double matching_beta; + double gps_precision; + unsigned check_sum; + short num_results; + std::string service; + std::string output_format; + std::string jsonp_parameter; + std::string language; + std::vector hints; + std::vector timestamps; + std::vector>> bearings; + std::vector uturns; + std::vector coordinates; + std::vector is_destination; + std::vector is_source; +}; +} +} + +#endif // ROUTE_PARAMETERS_HPP diff --git a/include/extractor/external_memory_node.hpp b/include/extractor/external_memory_node.hpp index a4f9ca941..6658a7e6e 100644 --- a/include/extractor/external_memory_node.hpp +++ b/include/extractor/external_memory_node.hpp @@ -12,13 +12,23 @@ namespace extractor struct ExternalMemoryNode : QueryNode { - ExternalMemoryNode(int lat, int lon, OSMNodeID id, bool barrier, bool traffic_light); + ExternalMemoryNode(int lat, int lon, OSMNodeID node_id, bool barrier, bool traffic_lights) + : QueryNode(lat, lon, node_id), barrier(barrier), traffic_lights(traffic_lights) + { + } - ExternalMemoryNode(); + ExternalMemoryNode() : barrier(false), traffic_lights(false) {} - static ExternalMemoryNode min_value(); + static ExternalMemoryNode min_value() + { + return ExternalMemoryNode(0, 0, MIN_OSM_NODEID, false, false); + } - static ExternalMemoryNode max_value(); + static ExternalMemoryNode max_value() + { + return ExternalMemoryNode(std::numeric_limits::max(), std::numeric_limits::max(), + MAX_OSM_NODEID, false, false); + } bool barrier; bool traffic_lights; @@ -27,9 +37,12 @@ struct ExternalMemoryNode : QueryNode struct ExternalMemoryNodeSTXXLCompare { using value_type = ExternalMemoryNode; - bool operator()(const ExternalMemoryNode &left, const ExternalMemoryNode &right) const; - value_type max_value(); - value_type min_value(); + value_type max_value() { return value_type::max_value(); } + value_type min_value() { return value_type::min_value(); } + bool operator()(const value_type &left, const value_type &right) const + { + return left.node_id < right.node_id; + } }; } } diff --git a/include/extractor/extractor.hpp b/include/extractor/extractor.hpp index 72e5be8b7..2255d2b62 100644 --- a/include/extractor/extractor.hpp +++ b/include/extractor/extractor.hpp @@ -2,7 +2,7 @@ #define EXTRACTOR_HPP #include "extractor/edge_based_edge.hpp" -#include "extractor/extractor_options.hpp" +#include "extractor/extractor_config.hpp" #include "extractor/edge_based_graph_factory.hpp" #include "extractor/graph_compressor.hpp" diff --git a/include/extractor/extractor_config.hpp b/include/extractor/extractor_config.hpp new file mode 100644 index 000000000..8e44f5e2e --- /dev/null +++ b/include/extractor/extractor_config.hpp @@ -0,0 +1,78 @@ +#ifndef EXTRACTOR_CONFIG_HPP +#define EXTRACTOR_CONFIG_HPP + +#include + +#include +#include + +namespace osrm +{ +namespace extractor +{ + +struct ExtractorConfig +{ + ExtractorConfig() noexcept : requested_num_threads(0) {} + void UseDefaultOutputNames() + { + std::string basepath = input_path.string(); + + auto pos = std::string::npos; + std::array known_extensions{ + {".osm.bz2", ".osm.pbf", ".osm.xml", ".pbf", ".osm"}}; + for (auto ext : known_extensions) + { + pos = basepath.find(ext); + if (pos != std::string::npos) + { + basepath.replace(pos, ext.size(), ""); + break; + } + } + + output_file_name = basepath + ".osrm"; + restriction_file_name = basepath + ".osrm.restrictions"; + names_file_name = basepath + ".osrm.names"; + timestamp_file_name = basepath + ".osrm.timestamp"; + geometry_output_path = basepath + ".osrm.geometry"; + node_output_path = basepath + ".osrm.nodes"; + edge_output_path = basepath + ".osrm.edges"; + edge_graph_output_path = basepath + ".osrm.ebg"; + rtree_nodes_output_path = basepath + ".osrm.ramIndex"; + rtree_leafs_output_path = basepath + ".osrm.fileIndex"; + edge_segment_lookup_path = basepath + ".osrm.edge_segment_lookup"; + edge_penalty_path = basepath + ".osrm.edge_penalties"; + edge_based_node_weights_output_path = basepath + ".osrm.enw"; + } + + boost::filesystem::path config_file_path; + boost::filesystem::path input_path; + boost::filesystem::path profile_path; + + std::string output_file_name; + std::string restriction_file_name; + std::string names_file_name; + std::string timestamp_file_name; + std::string geometry_output_path; + std::string edge_output_path; + std::string edge_graph_output_path; + std::string edge_based_node_weights_output_path; + std::string node_output_path; + std::string rtree_nodes_output_path; + std::string rtree_leafs_output_path; + + unsigned requested_num_threads; + unsigned small_component_size; + + bool generate_edge_lookup; + std::string edge_penalty_path; + std::string edge_segment_lookup_path; +#ifdef DEBUG_GEOMETRY + std::string debug_turns_path; +#endif +}; +} +} + +#endif // EXTRACTOR_CONFIG_HPP diff --git a/include/extractor/extractor_options.hpp b/include/extractor/extractor_options.hpp deleted file mode 100644 index 57f79c1ec..000000000 --- a/include/extractor/extractor_options.hpp +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef EXTRACTOR_OPTIONS_HPP -#define EXTRACTOR_OPTIONS_HPP - -#include - -#include - -namespace osrm -{ -namespace extractor -{ - -enum class return_code : unsigned -{ - ok, - fail, - exit -}; - -struct ExtractorConfig -{ - ExtractorConfig() : requested_num_threads(0) {} - boost::filesystem::path config_file_path; - boost::filesystem::path input_path; - boost::filesystem::path profile_path; - - std::string output_file_name; - std::string restriction_file_name; - std::string names_file_name; - std::string timestamp_file_name; - std::string geometry_output_path; - std::string edge_output_path; - std::string edge_graph_output_path; - std::string node_output_path; - std::string rtree_nodes_output_path; - std::string rtree_leafs_output_path; - - // every edge based node represents a segment in the original graph. During contraciton we need - // to know about this segment length, as we might have to add self-loops in cases of shorter - // parts than the segment represents itself - std::string edge_based_node_weights_output_path; - - unsigned requested_num_threads; - unsigned small_component_size; - - bool generate_edge_lookup; - std::string edge_penalty_path; - std::string edge_segment_lookup_path; -#ifdef DEBUG_GEOMETRY - std::string debug_turns_path; -#endif -}; - -struct ExtractorOptions -{ - static return_code ParseArguments(int argc, char *argv[], ExtractorConfig &extractor_config); - - static void GenerateOutputFilesNames(ExtractorConfig &extractor_config); -}; -} -} - -#endif // EXTRACTOR_OPTIONS_HPP diff --git a/include/osrm/coordinate.hpp b/include/osrm/coordinate.hpp index e1c7fef7d..34fbb5e26 100644 --- a/include/osrm/coordinate.hpp +++ b/include/osrm/coordinate.hpp @@ -1,72 +1,11 @@ -/* +#ifndef GLOBAL_COORDINATE_HPP +#define GLOBAL_COORDINATE_HPP -Copyright (c) 2016, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#ifndef COORDINATE_HPP_ -#define COORDINATE_HPP_ - -#include //for std::ostream -#include -#include +#include "util/coordinate.hpp" namespace osrm { - -constexpr static const double COORDINATE_PRECISION = 1000000.0; - -namespace util -{ - -struct FixedPointCoordinate -{ - int lat; - int lon; - - FixedPointCoordinate(); - FixedPointCoordinate(int lat, int lon); - - template - FixedPointCoordinate(const T &coordinate) - : lat(coordinate.lat), lon(coordinate.lon) - { - static_assert(std::is_same::value, - "coordinate types incompatible"); - static_assert(std::is_same::value, - "coordinate types incompatible"); - } - - bool IsValid() const; - bool operator==(const FixedPointCoordinate &other) const; - friend std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate); -}; - -std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate); + using util::FixedPointCoordinate; } -using util::FixedPointCoordinate; -} - -#endif /* COORDINATE_HPP_ */ +#endif diff --git a/include/osrm/engine_config.hpp b/include/osrm/engine_config.hpp new file mode 100644 index 000000000..6c10e9441 --- /dev/null +++ b/include/osrm/engine_config.hpp @@ -0,0 +1,12 @@ +#ifndef GLOBAL_ENGINE_CONFIG_HPP +#define GLOBAL_ENGINE_CONFIG_HPP + +#include "engine/engine_config.hpp" + +namespace osrm +{ + using engine::EngineConfig; +} + +#endif + diff --git a/include/osrm/json_container.hpp b/include/osrm/json_container.hpp index 7ab25d544..1b0787713 100644 --- a/include/osrm/json_container.hpp +++ b/include/osrm/json_container.hpp @@ -1,108 +1,8 @@ -/* - -Copyright (c) 2016, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -// based on -// https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp - -#ifndef JSON_CONTAINER_HPP -#define JSON_CONTAINER_HPP - -#include - -#include -#include -#include -#include - +#ifndef GLOBAL_JSON_CONTAINER_HPP +#define GLOBAL_JSON_CONTAINER_HPP +#include "util/json_container.hpp" namespace osrm { - -namespace util -{ - -namespace json -{ - -struct Object; -struct Array; - -struct String -{ - String() {} - String(const char *value) : value(value) {} - String(std::string value) : value(std::move(value)) {} - std::string value; -}; - -struct Number -{ - Number() {} - Number(double value) : value(static_cast(value)) {} - double value; -}; - -struct True -{ -}; - -struct False -{ -}; - -struct Null -{ -}; - -using Value = mapbox::util::variant, - mapbox::util::recursive_wrapper, - True, - False, - Null>; - -struct Object -{ - std::unordered_map values; -}; - -struct Array -{ - std::vector values; -}; - -} // namespace JSON -} // namespace util - -namespace json -{ -using namespace osrm::util::json; + namespace json = osrm::util::json; } - -} // namespace osrm - -#endif // JSON_CONTAINER_HPP +#endif diff --git a/include/osrm/osrm.hpp b/include/osrm/osrm.hpp index 3f3e55333..a1594b902 100644 --- a/include/osrm/osrm.hpp +++ b/include/osrm/osrm.hpp @@ -45,21 +45,26 @@ struct Object; namespace engine { +class Engine; +struct EngineConfig; struct RouteParameters; +} + +using engine::EngineConfig; +using engine::RouteParameters; +namespace json = util::json; + class OSRM { private: - class OSRM_impl; - std::unique_ptr OSRM_pimpl_; + std::unique_ptr engine_; public: - OSRM(LibOSRMConfig &lib_config); + OSRM(EngineConfig &lib_config); ~OSRM(); // needed because we need to define it with the implementation of OSRM_impl - int RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result); + int RunQuery(const RouteParameters &route_parameters, json::Object &json_result); }; -} -using engine::OSRM; } #endif // OSRM_HPP diff --git a/include/osrm/route_parameters.hpp b/include/osrm/route_parameters.hpp index 53c8629e7..57c884d5f 100644 --- a/include/osrm/route_parameters.hpp +++ b/include/osrm/route_parameters.hpp @@ -1,127 +1,11 @@ -/* +#ifndef GLOBAL_ROUTE_PARAMETERS_HPP +#define GLOBAL_ROUTE_PARAMETERS_HPP -Copyright (c) 2016, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ - -#ifndef ROUTE_PARAMETERS_HPP -#define ROUTE_PARAMETERS_HPP - -#include "coordinate.hpp" - -#include -#include - -#include -#include +#include "engine/route_parameters.hpp" namespace osrm { -namespace engine -{ - -struct RouteParameters -{ - RouteParameters(); - - void SetZoomLevel(const short level); - - void SetNumberOfResults(const short number); - - void SetAlternateRouteFlag(const bool flag); - - void SetUTurn(const bool flag); - - void SetAllUTurns(const bool flag); - - void SetClassify(const bool classify); - - void SetMatchingBeta(const double beta); - - void SetGPSPrecision(const double precision); - - void SetDeprecatedAPIFlag(const std::string &); - - void SetChecksum(const unsigned check_sum); - - void SetInstructionFlag(const bool flag); - - void SetService(const std::string &service); - - void SetOutputFormat(const std::string &format); - - void SetJSONpParameter(const std::string ¶meter); - - void AddHint(const std::string &hint); - - void AddTimestamp(const unsigned timestamp); - - void AddBearing(const boost::fusion::vector> &received_bearing, - boost::spirit::qi::unused_type unused, - bool &pass); - - void SetLanguage(const std::string &language); - - void SetGeometryFlag(const bool flag); - - void SetCompressionFlag(const bool flag); - - void AddCoordinate(const boost::fusion::vector &received_coordinates); - - void AddDestination(const boost::fusion::vector &received_coordinates); - - void AddSource(const boost::fusion::vector &received_coordinates); - - void SetCoordinatesFromGeometry(const std::string &geometry_string); - - short zoom_level; - bool print_instructions; - bool alternate_route; - bool geometry; - bool compression; - bool deprecatedAPI; - bool uturn_default; - bool classify; - double matching_beta; - double gps_precision; - unsigned check_sum; - short num_results; - std::string service; - std::string output_format; - std::string jsonp_parameter; - std::string language; - std::vector hints; - std::vector timestamps; - std::vector>> bearings; - std::vector uturns; - std::vector coordinates; - std::vector is_destination; - std::vector is_source; -}; + using engine::RouteParameters; } -using engine::RouteParameters; -} - -#endif // ROUTE_PARAMETERS_HPP +#endif diff --git a/include/server/request_handler.hpp b/include/server/request_handler.hpp index 900370a8a..eba77eac7 100644 --- a/include/server/request_handler.hpp +++ b/include/server/request_handler.hpp @@ -5,9 +5,9 @@ namespace osrm { +class OSRM; namespace engine { -class OSRM; struct RouteParameters; } namespace server @@ -30,10 +30,10 @@ class RequestHandler RequestHandler(const RequestHandler &) = delete; void handle_request(const http::request ¤t_request, http::reply ¤t_reply); - void RegisterRoutingMachine(engine::OSRM *osrm); + void RegisterRoutingMachine(OSRM *osrm); private: - engine::OSRM *routing_machine; + OSRM *routing_machine; }; } } diff --git a/include/engine/datafacade/shared_barriers.hpp b/include/storage/shared_barriers.hpp similarity index 96% rename from include/engine/datafacade/shared_barriers.hpp rename to include/storage/shared_barriers.hpp index e22e27ea4..48d305c79 100644 --- a/include/engine/datafacade/shared_barriers.hpp +++ b/include/storage/shared_barriers.hpp @@ -6,11 +6,8 @@ namespace osrm { -namespace engine +namespace storage { -namespace datafacade -{ - struct SharedBarriers { @@ -38,6 +35,5 @@ struct SharedBarriers }; } } -} #endif // SHARED_BARRIERS_HPP diff --git a/include/engine/datafacade/shared_datatype.hpp b/include/storage/shared_datatype.hpp similarity index 53% rename from include/engine/datafacade/shared_datatype.hpp rename to include/storage/shared_datatype.hpp index ab3004df6..69e409e42 100644 --- a/include/engine/datafacade/shared_datatype.hpp +++ b/include/storage/shared_datatype.hpp @@ -10,9 +10,7 @@ namespace osrm { -namespace engine -{ -namespace datafacade +namespace storage { // Added at the start and end of each block as sanity check @@ -48,46 +46,6 @@ struct SharedDataLayout SharedDataLayout() : num_entries(), entry_size() {} - void PrintInformation() const - { - util::SimpleLogger().Write(logDEBUG) << "NAME_OFFSETS " - << ": " << GetBlockSize(NAME_OFFSETS); - util::SimpleLogger().Write(logDEBUG) << "NAME_BLOCKS " - << ": " << GetBlockSize(NAME_BLOCKS); - util::SimpleLogger().Write(logDEBUG) << "NAME_CHAR_LIST " - << ": " << GetBlockSize(NAME_CHAR_LIST); - util::SimpleLogger().Write(logDEBUG) << "NAME_ID_LIST " - << ": " << GetBlockSize(NAME_ID_LIST); - util::SimpleLogger().Write(logDEBUG) << "VIA_NODE_LIST " - << ": " << GetBlockSize(VIA_NODE_LIST); - util::SimpleLogger().Write(logDEBUG) << "GRAPH_NODE_LIST " - << ": " << GetBlockSize(GRAPH_NODE_LIST); - util::SimpleLogger().Write(logDEBUG) << "GRAPH_EDGE_LIST " - << ": " << GetBlockSize(GRAPH_EDGE_LIST); - util::SimpleLogger().Write(logDEBUG) << "COORDINATE_LIST " - << ": " << GetBlockSize(COORDINATE_LIST); - util::SimpleLogger().Write(logDEBUG) << "TURN_INSTRUCTION " - << ": " << GetBlockSize(TURN_INSTRUCTION); - util::SimpleLogger().Write(logDEBUG) << "TRAVEL_MODE " - << ": " << GetBlockSize(TRAVEL_MODE); - util::SimpleLogger().Write(logDEBUG) << "R_SEARCH_TREE " - << ": " << GetBlockSize(R_SEARCH_TREE); - util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDEX " - << ": " << GetBlockSize(GEOMETRIES_INDEX); - util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_LIST " - << ": " << GetBlockSize(GEOMETRIES_LIST); - util::SimpleLogger().Write(logDEBUG) << "GEOMETRIES_INDICATORS" - << ": " << GetBlockSize(GEOMETRIES_INDICATORS); - util::SimpleLogger().Write(logDEBUG) << "HSGR_CHECKSUM " - << ": " << GetBlockSize(HSGR_CHECKSUM); - util::SimpleLogger().Write(logDEBUG) << "TIMESTAMP " - << ": " << GetBlockSize(TIMESTAMP); - util::SimpleLogger().Write(logDEBUG) << "FILE_INDEX_PATH " - << ": " << GetBlockSize(FILE_INDEX_PATH); - util::SimpleLogger().Write(logDEBUG) << "CORE_MARKER " - << ": " << GetBlockSize(CORE_MARKER); - } - template inline void SetBlockSize(BlockID bid, uint64_t entries) { num_entries[bid] = entries; @@ -170,6 +128,5 @@ struct SharedDataTimestamp }; } } -} #endif /* SHARED_DATA_TYPE_HPP */ diff --git a/include/datastore/shared_memory_factory.hpp b/include/storage/shared_memory.hpp similarity index 85% rename from include/datastore/shared_memory_factory.hpp rename to include/storage/shared_memory.hpp index ae8e11ee5..3b04d2e32 100644 --- a/include/datastore/shared_memory_factory.hpp +++ b/include/storage/shared_memory.hpp @@ -1,5 +1,5 @@ -#ifndef SHARED_MEMORY_FACTORY_HPP -#define SHARED_MEMORY_FACTORY_HPP +#ifndef SHARED_MEMORY_HPP +#define SHARED_MEMORY_HPP #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" @@ -26,7 +26,7 @@ namespace osrm { -namespace datastore +namespace storage { struct OSRMLockFile @@ -322,47 +322,37 @@ class SharedMemory }; #endif -template class SharedMemoryFactory_tmpl +template +SharedMemory *makeSharedMemory(const IdentifierT &id, + const uint64_t size = 0, + bool read_write = false, + bool remove_prev = true) { - public: - template - static SharedMemory *Get(const IdentifierT &id, - const uint64_t size = 0, - bool read_write = false, - bool remove_prev = true) + try + { + LockFileT lock_file; + if (!boost::filesystem::exists(lock_file())) { - try - { - LockFileT lock_file; - if (!boost::filesystem::exists(lock_file())) - { - if (0 == size) - { - throw util::exception("lock file does not exist, exiting"); - } - else - { - boost::filesystem::ofstream ofs(lock_file()); - ofs.close(); - } - } - return new SharedMemory(lock_file(), id, size, read_write, remove_prev); - } - catch (const boost::interprocess::interprocess_exception &e) - { - util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " - << e.get_error_code(); - throw util::exception(e.what()); - } + if (0 == size) + { + throw util::exception("lock file does not exist, exiting"); + } + else + { + boost::filesystem::ofstream ofs(lock_file()); + } } + return new SharedMemory(lock_file(), id, size, read_write, remove_prev); + } + catch (const boost::interprocess::interprocess_exception &e) + { + util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " + << e.get_error_code(); + throw util::exception(e.what()); + } +} - SharedMemoryFactory_tmpl() = delete; - SharedMemoryFactory_tmpl(const SharedMemoryFactory_tmpl &) = delete; - SharedMemoryFactory_tmpl &operator=(const SharedMemoryFactory_tmpl &) = delete; -}; - -using SharedMemoryFactory = SharedMemoryFactory_tmpl<>; } } -#endif // SHARED_MEMORY_FACTORY_HPP +#endif // SHARED_MEMORY_HPP diff --git a/include/storage/storage.hpp b/include/storage/storage.hpp new file mode 100644 index 000000000..0b63b32d1 --- /dev/null +++ b/include/storage/storage.hpp @@ -0,0 +1,25 @@ +#ifndef STORAGE_HPP +#define STORAGE_HPP + +#include + +#include +#include + +namespace osrm +{ +namespace storage +{ +using DataPaths = std::unordered_map; +class Storage +{ +public: + Storage(const DataPaths& data_paths); + int Run(); +private: + DataPaths paths; +}; +} +} + +#endif diff --git a/include/util/coordinate.hpp b/include/util/coordinate.hpp new file mode 100644 index 000000000..ca6b26e71 --- /dev/null +++ b/include/util/coordinate.hpp @@ -0,0 +1,71 @@ +/* + +Copyright (c) 2016, Project OSRM contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#ifndef COORDINATE_HPP_ +#define COORDINATE_HPP_ + +#include //for std::ostream +#include +#include + +namespace osrm +{ + +constexpr const double COORDINATE_PRECISION = 1000000.0; + +namespace util +{ + +struct FixedPointCoordinate +{ + int lat; + int lon; + + FixedPointCoordinate(); + FixedPointCoordinate(int lat, int lon); + + template + FixedPointCoordinate(const T &coordinate) + : lat(coordinate.lat), lon(coordinate.lon) + { + static_assert(std::is_same::value, + "coordinate types incompatible"); + static_assert(std::is_same::value, + "coordinate types incompatible"); + } + + bool IsValid() const; + bool operator==(const FixedPointCoordinate &other) const; + friend std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate); +}; + +std::ostream &operator<<(std::ostream &out, const FixedPointCoordinate &coordinate); +} + +} + +#endif /* COORDINATE_HPP_ */ diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index 41a3ebc8d..73e829175 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -1,7 +1,7 @@ #ifndef DEBUG_GEOMETRY_H #define DEBUG_GEOMETRY_H -#include "contractor/contractor_options.hpp" +#include "contractor/contractor_config.hpp" #include "extractor/query_node.hpp" #ifndef DEBUG_GEOMETRY diff --git a/include/util/fingerprint.hpp b/include/util/fingerprint.hpp index df656cde1..e8238c0ac 100644 --- a/include/util/fingerprint.hpp +++ b/include/util/fingerprint.hpp @@ -17,7 +17,7 @@ class FingerPrint const boost::uuids::uuid &GetFingerPrint() const; bool IsMagicNumberOK(const FingerPrint &other) const; bool TestGraphUtil(const FingerPrint &other) const; - bool TestPrepare(const FingerPrint &other) const; + bool TestContractor(const FingerPrint &other) const; bool TestRTree(const FingerPrint &other) const; bool TestQueryObjects(const FingerPrint &other) const; diff --git a/include/util/fingerprint_impl.hpp.in b/include/util/fingerprint_impl.hpp.in index f391e4ca2..1a52269d1 100644 --- a/include/util/fingerprint_impl.hpp.in +++ b/include/util/fingerprint_impl.hpp.in @@ -62,7 +62,7 @@ bool FingerPrint::TestGraphUtil(const FingerPrint &other) const return std::equal(md5_graph, md5_graph + 32, other.md5_graph); } -bool FingerPrint::TestPrepare(const FingerPrint &other) const +bool FingerPrint::TestContractor(const FingerPrint &other) const { if (!IsMagicNumberOK(other)) { diff --git a/include/util/graph_loader.hpp b/include/util/graph_loader.hpp index 91a7f7e77..224fb375b 100644 --- a/include/util/graph_loader.hpp +++ b/include/util/graph_loader.hpp @@ -39,7 +39,7 @@ unsigned loadRestrictionsFromFile(std::istream &input_stream, FingerPrint fingerprint_loaded; unsigned number_of_usable_restrictions = 0; input_stream.read((char *)&fingerprint_loaded, sizeof(FingerPrint)); - if (!fingerprint_loaded.TestPrepare(fingerprint_valid)) + if (!fingerprint_loaded.TestContractor(fingerprint_valid)) { SimpleLogger().Write(logWARNING) << ".restrictions was prepared with different build.\n" "Reprocess to get rid of this warning."; @@ -71,7 +71,7 @@ NodeID loadNodesFromFile(std::istream &input_stream, FingerPrint fingerprint_loaded; input_stream.read(reinterpret_cast(&fingerprint_loaded), sizeof(FingerPrint)); - if (!fingerprint_loaded.TestPrepare(fingerprint_valid)) + if (!fingerprint_loaded.TestContractor(fingerprint_valid)) { SimpleLogger().Write(logWARNING) << ".osrm was prepared with different build.\n" "Reprocess to get rid of this warning."; diff --git a/include/util/io.hpp b/include/util/io.hpp index b7951032c..70ab64a1b 100644 --- a/include/util/io.hpp +++ b/include/util/io.hpp @@ -33,7 +33,7 @@ inline bool readAndCheckFingerprint(std::istream &stream) stream.read(reinterpret_cast(&fingerprint), sizeof(fingerprint)); // compare the compilation state stored in the fingerprint return static_cast(stream) && valid.IsMagicNumberOK(fingerprint) && - valid.TestPrepare(fingerprint) && valid.TestGraphUtil(fingerprint) && + valid.TestContractor(fingerprint) && valid.TestGraphUtil(fingerprint) && valid.TestRTree(fingerprint) && valid.TestQueryObjects(fingerprint); } diff --git a/include/util/json_container.hpp b/include/util/json_container.hpp new file mode 100644 index 000000000..d3a9ca4a8 --- /dev/null +++ b/include/util/json_container.hpp @@ -0,0 +1,102 @@ +/* + +Copyright (c) 2016, Project OSRM contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, this +list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +// based on +// https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp + +#ifndef JSON_CONTAINER_HPP +#define JSON_CONTAINER_HPP + +#include + +#include +#include +#include +#include + +namespace osrm +{ + +namespace util +{ + +namespace json +{ + +struct Object; +struct Array; + +struct String +{ + String() {} + String(const char *value) : value(value) {} + String(std::string value) : value(std::move(value)) {} + std::string value; +}; + +struct Number +{ + Number() {} + Number(double value) : value(static_cast(value)) {} + double value; +}; + +struct True +{ +}; + +struct False +{ +}; + +struct Null +{ +}; + +using Value = mapbox::util::variant, + mapbox::util::recursive_wrapper, + True, + False, + Null>; + +struct Object +{ + std::unordered_map values; +}; + +struct Array +{ + std::vector values; +}; + +} // namespace JSON +} // namespace util +} // namespace osrm + +#endif // JSON_CONTAINER_HPP diff --git a/include/util/range_table.hpp b/include/util/range_table.hpp index f06df1def..e31697b9d 100644 --- a/include/util/range_table.hpp +++ b/include/util/range_table.hpp @@ -2,7 +2,6 @@ #define RANGE_TABLE_HPP #include "util/integer_range.hpp" -#include "datastore/shared_memory_factory.hpp" #include "util/shared_memory_vector_wrapper.hpp" #include diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 3a415e3b6..3aea17943 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -4,7 +4,6 @@ #include "util/deallocating_vector.hpp" #include "util/hilbert_value.hpp" #include "util/rectangle.hpp" -#include "datastore/shared_memory_factory.hpp" #include "util/shared_memory_vector_wrapper.hpp" #include "util/bearing.hpp" diff --git a/include/osrm/strong_typedef.hpp b/include/util/strong_typedef.hpp similarity index 69% rename from include/osrm/strong_typedef.hpp rename to include/util/strong_typedef.hpp index f33932a38..58e70602f 100644 --- a/include/osrm/strong_typedef.hpp +++ b/include/util/strong_typedef.hpp @@ -1,32 +1,5 @@ -#ifndef OSRM_STRONG_TYPEDEF_HPP -#define OSRM_STRONG_TYPEDEF_HPP - -/* - -Copyright (c) 2016, Project OSRM contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. -Redistributions in binary form must reproduce the above copyright notice, this -list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -*/ +#ifndef STRONG_TYPEDEF_HPP +#define STRONG_TYPEDEF_HPP #include #include diff --git a/include/util/typedefs.hpp b/include/util/typedefs.hpp index 243f04ed6..614e7ebd6 100644 --- a/include/util/typedefs.hpp +++ b/include/util/typedefs.hpp @@ -1,7 +1,7 @@ #ifndef TYPEDEFS_H #define TYPEDEFS_H -#include "osrm/strong_typedef.hpp" +#include "util/strong_typedef.hpp" #include #include diff --git a/src/contractor/processing_chain.cpp b/src/contractor/contractor.cpp similarity index 94% rename from src/contractor/processing_chain.cpp rename to src/contractor/contractor.cpp index a28f347a1..70352a45b 100644 --- a/src/contractor/processing_chain.cpp +++ b/src/contractor/contractor.cpp @@ -1,5 +1,5 @@ -#include "contractor/processing_chain.hpp" #include "contractor/contractor.hpp" +#include "contractor/graph_contractor.hpp" #include "extractor/edge_based_edge.hpp" @@ -51,9 +51,7 @@ namespace osrm namespace contractor { -Prepare::~Prepare() {} - -int Prepare::Run() +int Contractor::Run() { #ifdef WIN32 #pragma message("Memory consumption on Windows can be higher due to different bit packing") @@ -125,7 +123,7 @@ int Prepare::Run() return 0; } -std::size_t Prepare::LoadEdgeExpandedGraph( +std::size_t Contractor::LoadEdgeExpandedGraph( std::string const &edge_based_graph_filename, util::DeallocatingVector &edge_based_edge_list, const std::string &edge_segment_lookup_filename, @@ -154,7 +152,7 @@ std::size_t Prepare::LoadEdgeExpandedGraph( const util::FingerPrint fingerprint_valid = util::FingerPrint::GetValid(); util::FingerPrint fingerprint_loaded; input_stream.read((char *)&fingerprint_loaded, sizeof(util::FingerPrint)); - fingerprint_loaded.TestPrepare(fingerprint_valid); + fingerprint_loaded.TestContractor(fingerprint_valid); // TODO std::size_t can vary on systems. Our files are not transferable, but we might want to // consider using a fixed size type for I/O @@ -260,7 +258,7 @@ std::size_t Prepare::LoadEdgeExpandedGraph( return max_edge_id; } -void Prepare::ReadNodeLevels(std::vector &node_levels) const +void Contractor::ReadNodeLevels(std::vector &node_levels) const { boost::filesystem::ifstream order_input_stream(config.level_output_path, std::ios::binary); @@ -270,7 +268,7 @@ void Prepare::ReadNodeLevels(std::vector &node_levels) const order_input_stream.read((char *)node_levels.data(), sizeof(float) * node_levels.size()); } -void Prepare::WriteNodeLevels(std::vector &&in_node_levels) const +void Contractor::WriteNodeLevels(std::vector &&in_node_levels) const { std::vector node_levels(std::move(in_node_levels)); @@ -281,7 +279,7 @@ void Prepare::WriteNodeLevels(std::vector &&in_node_levels) const order_output_stream.write((char *)node_levels.data(), sizeof(float) * node_levels.size()); } -void Prepare::WriteCoreNodeMarker(std::vector &&in_is_core_node) const +void Contractor::WriteCoreNodeMarker(std::vector &&in_is_core_node) const { std::vector is_core_node(std::move(in_is_core_node)); std::vector unpacked_bool_flags(std::move(is_core_node.size())); @@ -299,7 +297,7 @@ void Prepare::WriteCoreNodeMarker(std::vector &&in_is_core_node) const } std::size_t -Prepare::WriteContractedGraph(unsigned max_node_id, +Contractor::WriteContractedGraph(unsigned max_node_id, const util::DeallocatingVector &contracted_edge_list) { // Sorting contracted edges in a way that the static query graph can read some in in-place. @@ -420,7 +418,7 @@ Prepare::WriteContractedGraph(unsigned max_node_id, /** \brief Build contracted graph. */ -void Prepare::ContractGraph( +void Contractor::ContractGraph( const unsigned max_edge_id, util::DeallocatingVector &edge_based_edge_list, util::DeallocatingVector &contracted_edge_list, @@ -431,15 +429,12 @@ void Prepare::ContractGraph( std::vector node_levels; node_levels.swap(inout_node_levels); - Contractor contractor(max_edge_id + 1, edge_based_edge_list, std::move(node_levels), + GraphContractor graph_contractor(max_edge_id + 1, edge_based_edge_list, std::move(node_levels), std::move(node_weights)); - contractor.Run(config.core_factor); - contractor.GetEdges(contracted_edge_list); - contractor.GetCoreMarker(is_core_node); - contractor.GetNodeLevels(inout_node_levels); - - std::cout << "Levels: " << inout_node_levels.size() << " Core: " << is_core_node.size() - << " MEID: " << max_edge_id << std::endl; + graph_contractor.Run(config.core_factor); + graph_contractor.GetEdges(contracted_edge_list); + graph_contractor.GetCoreMarker(is_core_node); + graph_contractor.GetNodeLevels(inout_node_levels); } } } diff --git a/src/contractor/contractor_options.cpp b/src/contractor/contractor_options.cpp deleted file mode 100644 index 51b8228b7..000000000 --- a/src/contractor/contractor_options.cpp +++ /dev/null @@ -1,128 +0,0 @@ -#include "contractor/contractor_options.hpp" - -#include "util/simple_logger.hpp" -#include "util/version.hpp" - -#include -#include - -#include - -namespace osrm -{ -namespace contractor -{ - -return_code -ContractorOptions::ParseArguments(int argc, char *argv[], ContractorConfig &contractor_config) -{ - // declare a group of options that will be allowed only on command line - boost::program_options::options_description generic_options("Options"); - generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( - "config,c", - boost::program_options::value(&contractor_config.config_file_path) - ->default_value("contractor.ini"), - "Path to a configuration file."); - - // declare a group of options that will be allowed both on command line and in config file - boost::program_options::options_description config_options("Configuration"); - config_options.add_options()( - "profile,p", - boost::program_options::value(&contractor_config.profile_path) - ->default_value("profile.lua"), - "Path to LUA routing profile")( - "threads,t", - boost::program_options::value(&contractor_config.requested_num_threads) - ->default_value(tbb::task_scheduler_init::default_num_threads()), - "Number of threads to use")( - "core,k", - boost::program_options::value(&contractor_config.core_factor)->default_value(1.0), - "Percentage of the graph (in vertices) to contract [0..1]")( - "segment-speed-file", - boost::program_options::value(&contractor_config.segment_speed_lookup_path), - "Lookup file containing nodeA,nodeB,speed data to adjust edge weights")( - "level-cache,o", boost::program_options::value(&contractor_config.use_cached_priority) - ->default_value(false), - "Use .level file to retain the contaction level for each node from the last run."); - -#ifdef DEBUG_GEOMETRY - config_options.add_options()( - "debug-geometry", - boost::program_options::value(&contractor_config.debug_geometry_path), - "Write out edge-weight debugging geometry data in GeoJSON format to this file"); -#endif - - // hidden options, will be allowed both on command line and in config file, but will not be - // shown to the user - boost::program_options::options_description hidden_options("Hidden options"); - hidden_options.add_options()("input,i", boost::program_options::value( - &contractor_config.osrm_input_path), - "Input file in .osm, .osm.bz2 or .osm.pbf format"); - - // positional option - boost::program_options::positional_options_description positional_options; - positional_options.add("input", 1); - - // combine above options for parsing - boost::program_options::options_description cmdline_options; - cmdline_options.add(generic_options).add(config_options).add(hidden_options); - - boost::program_options::options_description config_file_options; - config_file_options.add(config_options).add(hidden_options); - - boost::program_options::options_description visible_options( - "Usage: " + boost::filesystem::basename(argv[0]) + " [options]"); - visible_options.add(generic_options).add(config_options); - - // parse command line options - boost::program_options::variables_map option_variables; - boost::program_options::store(boost::program_options::command_line_parser(argc, argv) - .options(cmdline_options) - .positional(positional_options) - .run(), - option_variables); - - const auto &temp_config_path = option_variables["config"].as(); - if (boost::filesystem::is_regular_file(temp_config_path)) - { - boost::program_options::store(boost::program_options::parse_config_file( - temp_config_path.string().c_str(), cmdline_options, true), - option_variables); - } - - if (option_variables.count("version")) - { - util::SimpleLogger().Write() << OSRM_VERSION; - return return_code::exit; - } - - if (option_variables.count("help")) - { - util::SimpleLogger().Write() << "\n" << visible_options; - return return_code::exit; - } - - boost::program_options::notify(option_variables); - - if (!option_variables.count("input")) - { - util::SimpleLogger().Write() << "\n" << visible_options; - return return_code::fail; - } - - return return_code::ok; -} - -void ContractorOptions::GenerateOutputFilesNames(ContractorConfig &contractor_config) -{ - contractor_config.level_output_path = contractor_config.osrm_input_path.string() + ".level"; - contractor_config.core_output_path = contractor_config.osrm_input_path.string() + ".core"; - contractor_config.graph_output_path = contractor_config.osrm_input_path.string() + ".hsgr"; - contractor_config.edge_based_graph_path = contractor_config.osrm_input_path.string() + ".ebg"; - contractor_config.edge_segment_lookup_path = - contractor_config.osrm_input_path.string() + ".edge_segment_lookup"; - contractor_config.edge_penalty_path = - contractor_config.osrm_input_path.string() + ".edge_penalties"; -} -} -} diff --git a/src/engine/osrm_impl.cpp b/src/engine/engine.cpp similarity index 75% rename from src/engine/osrm_impl.cpp rename to src/engine/engine.cpp index c059698b4..c9fe44ed1 100644 --- a/src/engine/osrm_impl.cpp +++ b/src/engine/engine.cpp @@ -1,4 +1,6 @@ -#include "engine/osrm_impl.hpp" +#include "engine/engine.hpp" +#include "engine/engine_config.hpp" +#include "engine/route_parameters.hpp" #include "engine/plugins/distance_table.hpp" #include "engine/plugins/hello_world.hpp" @@ -7,10 +9,12 @@ #include "engine/plugins/trip.hpp" #include "engine/plugins/viaroute.hpp" #include "engine/plugins/match.hpp" + #include "engine/datafacade/datafacade_base.hpp" #include "engine/datafacade/internal_datafacade.hpp" -#include "engine/datafacade/shared_barriers.hpp" #include "engine/datafacade/shared_datafacade.hpp" + +#include "storage/shared_barriers.hpp" #include "util/make_unique.hpp" #include "util/routed_options.hpp" #include "util/simple_logger.hpp" @@ -19,10 +23,6 @@ #include #include -#include "osrm/libosrm_config.hpp" -#include "osrm/osrm.hpp" -#include "osrm/route_parameters.hpp" - #include #include #include @@ -33,45 +33,45 @@ namespace osrm namespace engine { -OSRM::OSRM_impl::OSRM_impl(LibOSRMConfig &lib_config) +Engine::Engine(EngineConfig &config) { - if (lib_config.use_shared_memory) + if (config.use_shared_memory) { - barrier = util::make_unique(); + barrier = util::make_unique(); query_data_facade = new datafacade::SharedDataFacade(); } else { // populate base path - util::populate_base_path(lib_config.server_paths); + util::populate_base_path(config.server_paths); query_data_facade = new datafacade::InternalDataFacade( - lib_config.server_paths); + config.server_paths); } using DataFacade = datafacade::BaseDataFacade; // The following plugins handle all requests. RegisterPlugin(new plugins::DistanceTablePlugin( - query_data_facade, lib_config.max_locations_distance_table)); + query_data_facade, config.max_locations_distance_table)); RegisterPlugin(new plugins::HelloWorldPlugin()); RegisterPlugin(new plugins::NearestPlugin(query_data_facade)); RegisterPlugin(new plugins::MapMatchingPlugin( - query_data_facade, lib_config.max_locations_map_matching)); + query_data_facade, config.max_locations_map_matching)); RegisterPlugin(new plugins::TimestampPlugin(query_data_facade)); RegisterPlugin(new plugins::ViaRoutePlugin(query_data_facade, - lib_config.max_locations_viaroute)); + config.max_locations_viaroute)); RegisterPlugin( - new plugins::RoundTripPlugin(query_data_facade, lib_config.max_locations_trip)); + new plugins::RoundTripPlugin(query_data_facade, config.max_locations_trip)); } -void OSRM::OSRM_impl::RegisterPlugin(plugins::BasePlugin *raw_plugin_ptr) +void Engine::RegisterPlugin(plugins::BasePlugin *raw_plugin_ptr) { std::unique_ptr plugin_ptr(raw_plugin_ptr); util::SimpleLogger().Write() << "loaded plugin: " << plugin_ptr->GetDescriptor(); plugin_map[plugin_ptr->GetDescriptor()] = std::move(plugin_ptr); } -int OSRM::OSRM_impl::RunQuery(const RouteParameters &route_parameters, +int Engine::RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result) { const auto &plugin_iterator = plugin_map.find(route_parameters.service); @@ -99,7 +99,7 @@ int OSRM::OSRM_impl::RunQuery(const RouteParameters &route_parameters, } // decrease number of concurrent queries -void OSRM::OSRM_impl::decrease_concurrent_query_count() +void Engine::decrease_concurrent_query_count() { if (!barrier) { @@ -121,7 +121,7 @@ void OSRM::OSRM_impl::decrease_concurrent_query_count() } // increase number of concurrent queries -void OSRM::OSRM_impl::increase_concurrent_query_count() +void Engine::increase_concurrent_query_count() { if (!barrier) { @@ -147,15 +147,5 @@ void OSRM::OSRM_impl::increase_concurrent_query_count() ->CheckAndReloadFacade(); } -// proxy code for compilation firewall -OSRM::OSRM(LibOSRMConfig &lib_config) : OSRM_pimpl_(util::make_unique(lib_config)) {} - -// needed because unique_ptr needs the size of OSRM_impl for delete -OSRM::~OSRM() {} - -int OSRM::RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result) -{ - return OSRM_pimpl_->RunQuery(route_parameters, json_result); -} } } diff --git a/src/engine/phantom_node.cpp b/src/engine/phantom_node.cpp deleted file mode 100644 index e5b5873df..000000000 --- a/src/engine/phantom_node.cpp +++ /dev/null @@ -1,83 +0,0 @@ -#include "engine/phantom_node.hpp" -#include "extractor/travel_mode.hpp" -#include "util/typedefs.hpp" -#include "osrm/coordinate.hpp" - -#include - -namespace osrm -{ -namespace engine -{ - -PhantomNode::PhantomNode(NodeID forward_node_id, - NodeID reverse_node_id, - unsigned name_id, - int forward_weight, - int reverse_weight, - int forward_offset, - int reverse_offset, - unsigned packed_geometry_id, - bool is_tiny_component, - unsigned component_id, - util::FixedPointCoordinate &location, - unsigned short fwd_segment_position, - extractor::TravelMode forward_travel_mode, - extractor::TravelMode backward_travel_mode) - : forward_node_id(forward_node_id), reverse_node_id(reverse_node_id), name_id(name_id), - forward_weight(forward_weight), reverse_weight(reverse_weight), - forward_offset(forward_offset), reverse_offset(reverse_offset), - packed_geometry_id(packed_geometry_id), component{component_id, is_tiny_component}, - location(location), fwd_segment_position(fwd_segment_position), - forward_travel_mode(forward_travel_mode), backward_travel_mode(backward_travel_mode) -{ -} - -PhantomNode::PhantomNode() - : forward_node_id(SPECIAL_NODEID), reverse_node_id(SPECIAL_NODEID), - name_id(std::numeric_limits::max()), forward_weight(INVALID_EDGE_WEIGHT), - reverse_weight(INVALID_EDGE_WEIGHT), forward_offset(0), reverse_offset(0), - packed_geometry_id(SPECIAL_EDGEID), component{INVALID_COMPONENTID, false}, - fwd_segment_position(0), forward_travel_mode(TRAVEL_MODE_INACCESSIBLE), - backward_travel_mode(TRAVEL_MODE_INACCESSIBLE) -{ -} - -int PhantomNode::GetForwardWeightPlusOffset() const -{ - if (SPECIAL_NODEID == forward_node_id) - { - return 0; - } - return forward_offset + forward_weight; -} - -int PhantomNode::GetReverseWeightPlusOffset() const -{ - if (SPECIAL_NODEID == reverse_node_id) - { - return 0; - } - return reverse_offset + reverse_weight; -} - -bool PhantomNode::IsBidirected() const -{ - return (forward_node_id != SPECIAL_NODEID) && (reverse_node_id != SPECIAL_NODEID); -} - -bool PhantomNode::IsCompressed() const { return (forward_offset != 0) || (reverse_offset != 0); } - -bool PhantomNode::is_valid(const unsigned number_of_nodes) const -{ - return location.IsValid() && - ((forward_node_id < number_of_nodes) || (reverse_node_id < number_of_nodes)) && - ((forward_weight != INVALID_EDGE_WEIGHT) || (reverse_weight != INVALID_EDGE_WEIGHT)) && - (component.id != INVALID_COMPONENTID) && (name_id != INVALID_NAMEID); -} - -bool PhantomNode::IsValid() const { return location.IsValid() && (name_id != INVALID_NAMEID); } - -bool PhantomNode::operator==(const PhantomNode &other) const { return location == other.location; } -} -} diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index bbcf40def..01df5783d 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -3,7 +3,8 @@ #include #include -#include "osrm/route_parameters.hpp" +#include "engine/route_parameters.hpp" +#include "util/coordinate.hpp" #include "engine/polyline_compressor.hpp" diff --git a/src/extractor/external_memory_node.cpp b/src/extractor/external_memory_node.cpp deleted file mode 100644 index 249c25606..000000000 --- a/src/extractor/external_memory_node.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "extractor/external_memory_node.hpp" -#include "extractor/query_node.hpp" - -#include - -namespace osrm -{ -namespace extractor -{ - -ExternalMemoryNode::ExternalMemoryNode( - int lat, int lon, OSMNodeID node_id, bool barrier, bool traffic_lights) - : QueryNode(lat, lon, node_id), barrier(barrier), traffic_lights(traffic_lights) -{ -} - -ExternalMemoryNode::ExternalMemoryNode() : barrier(false), traffic_lights(false) {} - -ExternalMemoryNode ExternalMemoryNode::min_value() -{ - return ExternalMemoryNode(0, 0, MIN_OSM_NODEID, false, false); -} - -ExternalMemoryNode ExternalMemoryNode::max_value() -{ - return ExternalMemoryNode(std::numeric_limits::max(), std::numeric_limits::max(), - MAX_OSM_NODEID, false, false); -} - -bool ExternalMemoryNodeSTXXLCompare::operator()(const ExternalMemoryNode &left, - const ExternalMemoryNode &right) const -{ - return left.node_id < right.node_id; -} - -ExternalMemoryNodeSTXXLCompare::value_type ExternalMemoryNodeSTXXLCompare::max_value() -{ - return ExternalMemoryNode::max_value(); -} - -ExternalMemoryNodeSTXXLCompare::value_type ExternalMemoryNodeSTXXLCompare::min_value() -{ - return ExternalMemoryNode::min_value(); -} -} -} diff --git a/src/extractor/extractor_options.cpp b/src/extractor/extractor_options.cpp deleted file mode 100644 index 7c985714f..000000000 --- a/src/extractor/extractor_options.cpp +++ /dev/null @@ -1,218 +0,0 @@ -#include "extractor/extractor_options.hpp" - -#include "util/ini_file.hpp" -#include "util/version.hpp" -#include "util/simple_logger.hpp" - -#include -#include - -#include - -namespace osrm -{ -namespace extractor -{ - -return_code -ExtractorOptions::ParseArguments(int argc, char *argv[], ExtractorConfig &extractor_config) -{ - // declare a group of options that will be allowed only on command line - boost::program_options::options_description generic_options("Options"); - generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( - /* - * TODO: re-enable this - "restrictions,r", - boost::program_options::value(&extractor_config.restrictions_path), - "Restrictions file in .osrm.restrictions format")( - */ - "config,c", - boost::program_options::value(&extractor_config.config_file_path) - ->default_value("extractor.ini"), - "Path to a configuration file."); - - // declare a group of options that will be allowed both on command line and in config file - boost::program_options::options_description config_options("Configuration"); - config_options.add_options()( - "profile,p", - boost::program_options::value(&extractor_config.profile_path) - ->default_value("profile.lua"), - "Path to LUA routing profile")( - "threads,t", - boost::program_options::value(&extractor_config.requested_num_threads) - ->default_value(tbb::task_scheduler_init::default_num_threads()), - "Number of threads to use")( - "generate-edge-lookup", - boost::program_options::value(&extractor_config.generate_edge_lookup) - ->implicit_value(true) - ->default_value(false), - "Generate a lookup table for internal edge-expanded-edge IDs to OSM node pairs")( - "small-component-size", - boost::program_options::value(&extractor_config.small_component_size) - ->default_value(1000), - "Number of nodes required before a strongly-connected-componennt is considered big " - "(affects nearest neighbor snapping)"); - -#ifdef DEBUG_GEOMETRY - config_options.add_options()("debug-turns", boost::program_options::value( - &extractor_config.debug_turns_path), - "Write out GeoJSON with turn penalty data"); -#endif // DEBUG_GEOMETRY - - // hidden options, will be allowed both on command line and in config file, but will not be - // shown to the user - boost::program_options::options_description hidden_options("Hidden options"); - hidden_options.add_options()("input,i", boost::program_options::value( - &extractor_config.input_path), - "Input file in .osm, .osm.bz2 or .osm.pbf format"); - - // positional option - boost::program_options::positional_options_description positional_options; - positional_options.add("input", 1); - - // combine above options for parsing - boost::program_options::options_description cmdline_options; - cmdline_options.add(generic_options).add(config_options).add(hidden_options); - - boost::program_options::options_description config_file_options; - config_file_options.add(config_options).add(hidden_options); - - boost::program_options::options_description visible_options( - boost::filesystem::basename(argv[0]) + " [options]"); - visible_options.add(generic_options).add(config_options); - - // parse command line options - try - { - boost::program_options::variables_map option_variables; - boost::program_options::store(boost::program_options::command_line_parser(argc, argv) - .options(cmdline_options) - .positional(positional_options) - .run(), - option_variables); - if (option_variables.count("version")) - { - util::SimpleLogger().Write() << OSRM_VERSION; - return return_code::exit; - } - - if (option_variables.count("help")) - { - util::SimpleLogger().Write() << visible_options; - return return_code::exit; - } - - boost::program_options::notify(option_variables); - - // parse config file - if (boost::filesystem::is_regular_file(extractor_config.config_file_path)) - { - util::SimpleLogger().Write() << "Reading options from: " - << extractor_config.config_file_path.string(); - std::string ini_file_contents = - util::read_file_lower_content(extractor_config.config_file_path); - std::stringstream config_stream(ini_file_contents); - boost::program_options::store(parse_config_file(config_stream, config_file_options), - option_variables); - boost::program_options::notify(option_variables); - } - - if (!option_variables.count("input")) - { - util::SimpleLogger().Write() << visible_options; - return return_code::exit; - } - } - catch (std::exception &e) - { - util::SimpleLogger().Write(logWARNING) << e.what(); - return return_code::fail; - } - - return return_code::ok; -} - -void ExtractorOptions::GenerateOutputFilesNames(ExtractorConfig &extractor_config) -{ - boost::filesystem::path &input_path = extractor_config.input_path; - extractor_config.output_file_name = input_path.string(); - extractor_config.restriction_file_name = input_path.string(); - extractor_config.names_file_name = input_path.string(); - extractor_config.timestamp_file_name = input_path.string(); - extractor_config.geometry_output_path = input_path.string(); - extractor_config.edge_output_path = input_path.string(); - extractor_config.edge_graph_output_path = input_path.string(); - extractor_config.edge_based_node_weights_output_path = input_path.string(); - extractor_config.node_output_path = input_path.string(); - extractor_config.rtree_nodes_output_path = input_path.string(); - extractor_config.rtree_leafs_output_path = input_path.string(); - extractor_config.edge_segment_lookup_path = input_path.string(); - extractor_config.edge_penalty_path = input_path.string(); - std::string::size_type pos = extractor_config.output_file_name.find(".osm.bz2"); - if (pos == std::string::npos) - { - pos = extractor_config.output_file_name.find(".osm.pbf"); - if (pos == std::string::npos) - { - pos = extractor_config.output_file_name.find(".osm.xml"); - } - } - if (pos == std::string::npos) - { - pos = extractor_config.output_file_name.find(".pbf"); - } - if (pos == std::string::npos) - { - pos = extractor_config.output_file_name.find(".osm"); - if (pos == std::string::npos) - { - extractor_config.output_file_name.append(".osrm"); - extractor_config.restriction_file_name.append(".osrm.restrictions"); - extractor_config.names_file_name.append(".osrm.names"); - extractor_config.timestamp_file_name.append(".osrm.timestamp"); - extractor_config.geometry_output_path.append(".osrm.geometry"); - extractor_config.node_output_path.append(".osrm.nodes"); - extractor_config.edge_output_path.append(".osrm.edges"); - extractor_config.edge_graph_output_path.append(".osrm.ebg"); - extractor_config.edge_based_node_weights_output_path.append(".osrm.enw"); - extractor_config.rtree_nodes_output_path.append(".osrm.ramIndex"); - extractor_config.rtree_leafs_output_path.append(".osrm.fileIndex"); - extractor_config.edge_segment_lookup_path.append(".osrm.edge_segment_lookup"); - extractor_config.edge_penalty_path.append(".osrm.edge_penalties"); - } - else - { - extractor_config.output_file_name.replace(pos, 5, ".osrm"); - extractor_config.restriction_file_name.replace(pos, 5, ".osrm.restrictions"); - extractor_config.names_file_name.replace(pos, 5, ".osrm.names"); - extractor_config.timestamp_file_name.replace(pos, 5, ".osrm.timestamp"); - extractor_config.geometry_output_path.replace(pos, 5, ".osrm.geometry"); - extractor_config.node_output_path.replace(pos, 5, ".osrm.nodes"); - extractor_config.edge_output_path.replace(pos, 5, ".osrm.edges"); - extractor_config.edge_graph_output_path.replace(pos, 5, ".osrm.ebg"); - extractor_config.edge_based_node_weights_output_path.replace(pos, 5, ".osrm.enw"); - extractor_config.rtree_nodes_output_path.replace(pos, 5, ".osrm.ramIndex"); - extractor_config.rtree_leafs_output_path.replace(pos, 5, ".osrm.fileIndex"); - extractor_config.edge_segment_lookup_path.replace(pos, 5, ".osrm.edge_segment_lookup"); - extractor_config.edge_penalty_path.replace(pos, 5, ".osrm.edge_penalties"); - } - } - else - { - extractor_config.output_file_name.replace(pos, 8, ".osrm"); - extractor_config.restriction_file_name.replace(pos, 8, ".osrm.restrictions"); - extractor_config.names_file_name.replace(pos, 8, ".osrm.names"); - extractor_config.timestamp_file_name.replace(pos, 8, ".osrm.timestamp"); - extractor_config.geometry_output_path.replace(pos, 8, ".osrm.geometry"); - extractor_config.node_output_path.replace(pos, 8, ".osrm.nodes"); - extractor_config.edge_output_path.replace(pos, 8, ".osrm.edges"); - extractor_config.edge_graph_output_path.replace(pos, 8, ".osrm.ebg"); - extractor_config.edge_based_node_weights_output_path.replace(pos, 8, ".osrm.enw"); - extractor_config.rtree_nodes_output_path.replace(pos, 8, ".osrm.ramIndex"); - extractor_config.rtree_leafs_output_path.replace(pos, 8, ".osrm.fileIndex"); - extractor_config.edge_segment_lookup_path.replace(pos, 8, ".osrm.edge_segment_lookup"); - extractor_config.edge_penalty_path.replace(pos, 8, ".osrm.edge_penalties"); - } -} -} -} diff --git a/src/osrm/osrm.cpp b/src/osrm/osrm.cpp new file mode 100644 index 000000000..1100b1df9 --- /dev/null +++ b/src/osrm/osrm.cpp @@ -0,0 +1,22 @@ +#include "osrm/osrm.hpp" +#include "engine/engine.hpp" +#include "engine/engine_config.hpp" +#include "engine/plugins/plugin_base.hpp" +#include "storage/shared_barriers.hpp" +#include "util/make_unique.hpp" + +namespace osrm +{ + +// proxy code for compilation firewall +OSRM::OSRM(engine::EngineConfig &config_) : engine_(util::make_unique(config_)) {} + +// needed because unique_ptr needs the size of OSRM_impl for delete +OSRM::~OSRM() {} + +int OSRM::RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result) +{ + return engine_->RunQuery(route_parameters, json_result); +} + +} diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index 4b83c83ee..96b94671d 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -10,8 +10,8 @@ #include "util/xml_renderer.hpp" #include "util/typedefs.hpp" -#include "osrm/route_parameters.hpp" -#include "osrm/json_container.hpp" +#include "engine/route_parameters.hpp" +#include "util/json_container.hpp" #include "osrm/osrm.hpp" #include diff --git a/src/tools/datastore.cpp b/src/storage/storage.cpp similarity index 86% rename from src/tools/datastore.cpp rename to src/storage/storage.cpp index c00a9cc63..833061344 100644 --- a/src/tools/datastore.cpp +++ b/src/storage/storage.cpp @@ -2,16 +2,16 @@ #include "util/range_table.hpp" #include "contractor/query_edge.hpp" #include "extractor/query_node.hpp" -#include "datastore/shared_memory_factory.hpp" #include "util/shared_memory_vector_wrapper.hpp" #include "util/static_graph.hpp" #include "util/static_rtree.hpp" #include "engine/datafacade/datafacade_base.hpp" #include "extractor/travel_mode.hpp" #include "extractor/turn_instructions.hpp" -#include "engine/datafacade/shared_datatype.hpp" -#include "engine/datafacade/shared_barriers.hpp" -#include "util/datastore_options.hpp" +#include "storage/storage.hpp" +#include "storage/shared_datatype.hpp" +#include "storage/shared_barriers.hpp" +#include "storage/shared_memory.hpp" #include "util/fingerprint.hpp" #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" @@ -32,10 +32,10 @@ #include #include -// FIXME remove after move to datastore -using namespace osrm::engine::datafacade; -using namespace osrm::datastore; -using namespace osrm; +namespace osrm +{ +namespace storage +{ using RTreeLeaf = typename engine::datafacade::BaseDataFacade::RTreeLeaf; @@ -44,11 +44,6 @@ using RTreeNode = util::StaticRTree::TreeNode; using QueryGraph = util::StaticGraph; -namespace osrm -{ -namespace tools -{ - // delete a shared memory region. report warning if it could not be deleted void deleteRegion(const SharedDataType region) { @@ -78,10 +73,10 @@ void deleteRegion(const SharedDataType region) util::SimpleLogger().Write(logWARNING) << "could not delete shared memory region " << name; } } -} -} -int main(const int argc, const char *argv[]) try +Storage::Storage(const DataPaths &paths_) : paths(paths_) {} + +int Storage::Run() { util::LogPolicy::GetInstance().Unmute(); SharedBarriers barrier; @@ -91,8 +86,7 @@ int main(const int argc, const char *argv[]) try const bool lock_flags = MCL_CURRENT | MCL_FUTURE; if (-1 == mlockall(lock_flags)) { - util::SimpleLogger().Write(logWARNING) << "Process " << argv[0] - << " could not request RAM lock"; + util::SimpleLogger().Write(logWARNING) << "Could not request RAM lock"; } #endif @@ -107,107 +101,99 @@ int main(const int argc, const char *argv[]) try barrier.pending_update_mutex.unlock(); } - util::SimpleLogger().Write(logDEBUG) << "Checking input parameters"; - - std::unordered_map server_paths; - if (!util::GenerateDataStoreOptions(argc, argv, server_paths)) - { - return EXIT_SUCCESS; - } - - if (server_paths.find("hsgrdata") == server_paths.end()) + if (paths.find("hsgrdata") == paths.end()) { throw util::exception("no hsgr file found"); } - if (server_paths.find("ramindex") == server_paths.end()) + if (paths.find("ramindex") == paths.end()) { throw util::exception("no ram index file found"); } - if (server_paths.find("fileindex") == server_paths.end()) + if (paths.find("fileindex") == paths.end()) { throw util::exception("no leaf index file found"); } - if (server_paths.find("nodesdata") == server_paths.end()) + if (paths.find("nodesdata") == paths.end()) { throw util::exception("no nodes file found"); } - if (server_paths.find("edgesdata") == server_paths.end()) + if (paths.find("edgesdata") == paths.end()) { throw util::exception("no edges file found"); } - if (server_paths.find("namesdata") == server_paths.end()) + if (paths.find("namesdata") == paths.end()) { throw util::exception("no names file found"); } - if (server_paths.find("geometry") == server_paths.end()) + if (paths.find("geometry") == paths.end()) { throw util::exception("no geometry file found"); } - if (server_paths.find("core") == server_paths.end()) + if (paths.find("core") == paths.end()) { throw util::exception("no core file found"); } - auto paths_iterator = server_paths.find("hsgrdata"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + auto paths_iterator = paths.find("hsgrdata"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path &hsgr_path = paths_iterator->second; - paths_iterator = server_paths.find("timestamp"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + paths_iterator = paths.find("timestamp"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path ×tamp_path = paths_iterator->second; - paths_iterator = server_paths.find("ramindex"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + paths_iterator = paths.find("ramindex"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path &ram_index_path = paths_iterator->second; - paths_iterator = server_paths.find("fileindex"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + paths_iterator = paths.find("fileindex"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path index_file_path_absolute = boost::filesystem::canonical(paths_iterator->second); const std::string &file_index_path = index_file_path_absolute.string(); - paths_iterator = server_paths.find("nodesdata"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + paths_iterator = paths.find("nodesdata"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path &nodes_data_path = paths_iterator->second; - paths_iterator = server_paths.find("edgesdata"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + paths_iterator = paths.find("edgesdata"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path &edges_data_path = paths_iterator->second; - paths_iterator = server_paths.find("namesdata"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + paths_iterator = paths.find("namesdata"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path &names_data_path = paths_iterator->second; - paths_iterator = server_paths.find("geometry"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + paths_iterator = paths.find("geometry"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path &geometries_data_path = paths_iterator->second; - paths_iterator = server_paths.find("core"); - BOOST_ASSERT(server_paths.end() != paths_iterator); + paths_iterator = paths.find("core"); + BOOST_ASSERT(paths.end() != paths_iterator); BOOST_ASSERT(!paths_iterator->second.empty()); const boost::filesystem::path &core_marker_path = paths_iterator->second; // determine segment to use bool segment2_in_use = SharedMemory::RegionExists(LAYOUT_2); - const engine::datafacade::SharedDataType layout_region = [&] + const storage::SharedDataType layout_region = [&] { return segment2_in_use ? LAYOUT_1 : LAYOUT_2; }(); - const engine::datafacade::SharedDataType data_region = [&] + const storage::SharedDataType data_region = [&] { return segment2_in_use ? DATA_1 : DATA_2; }(); - const engine::datafacade::SharedDataType previous_layout_region = [&] + const storage::SharedDataType previous_layout_region = [&] { return segment2_in_use ? LAYOUT_2 : LAYOUT_1; }(); - const engine::datafacade::SharedDataType previous_data_region = [&] + const storage::SharedDataType previous_data_region = [&] { return segment2_in_use ? DATA_2 : DATA_1; }(); // Allocate a memory layout in shared memory, deallocate previous - auto *layout_memory = SharedMemoryFactory::Get(layout_region, sizeof(SharedDataLayout)); + auto *layout_memory = makeSharedMemory(layout_region, sizeof(SharedDataLayout)); auto shared_layout_ptr = new (layout_memory->Ptr()) SharedDataLayout(); shared_layout_ptr->SetBlockSize(SharedDataLayout::FILE_INDEX_PATH, @@ -345,8 +331,7 @@ int main(const int argc, const char *argv[]) try // allocate shared memory block util::SimpleLogger().Write() << "allocating shared memory of " << shared_layout_ptr->GetSizeOfLayout() << " bytes"; - SharedMemory *shared_memory = - SharedMemoryFactory::Get(data_region, shared_layout_ptr->GetSizeOfLayout()); + auto *shared_memory = makeSharedMemory(data_region, shared_layout_ptr->GetSizeOfLayout()); char *shared_memory_ptr = static_cast(shared_memory->Ptr()); // read actual data into shared memory object // @@ -555,7 +540,7 @@ int main(const int argc, const char *argv[]) try // acquire lock SharedMemory *data_type_memory = - SharedMemoryFactory::Get(CURRENT_REGIONS, sizeof(SharedDataTimestamp), true, false); + makeSharedMemory(CURRENT_REGIONS, sizeof(SharedDataTimestamp), true, false); SharedDataTimestamp *data_timestamp_ptr = static_cast(data_type_memory->Ptr()); @@ -571,22 +556,11 @@ int main(const int argc, const char *argv[]) try data_timestamp_ptr->layout = layout_region; data_timestamp_ptr->data = data_region; data_timestamp_ptr->timestamp += 1; - tools::deleteRegion(previous_data_region); - tools::deleteRegion(previous_layout_region); + deleteRegion(previous_data_region); + deleteRegion(previous_layout_region); util::SimpleLogger().Write() << "all data loaded"; - shared_layout_ptr->PrintInformation(); return EXIT_SUCCESS; } -catch (const std::bad_alloc &e) -{ - util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - util::SimpleLogger().Write(logWARNING) - << "Please provide more memory or disable locking the virtual " - "address space (note: this makes OSRM swap, i.e. slow)"; - return EXIT_FAILURE; } -catch (const std::exception &e) -{ - util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); } diff --git a/src/tools/check-hsgr.cpp b/src/tools/check-hsgr.cpp index 6f97d32ec..54822b1df 100644 --- a/src/tools/check-hsgr.cpp +++ b/src/tools/check-hsgr.cpp @@ -11,6 +11,7 @@ #include #include +#include namespace osrm { @@ -22,72 +23,71 @@ using QueryGraph = util::StaticGraph; } } -int main(int argc, char *argv[]) +int main(int argc, char *argv[]) try { osrm::util::LogPolicy::GetInstance().Unmute(); - try + if (argc != 2) { - if (argc != 2) + osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " "; + return EXIT_FAILURE; + } + + boost::filesystem::path hsgr_path(argv[1]); + + std::vector node_list; + std::vector edge_list; + osrm::util::SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); + + unsigned m_check_sum = 0; + unsigned m_number_of_nodes = + readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); + osrm::util::SimpleLogger().Write() << "expecting " << m_number_of_nodes + << " nodes, checksum: " << m_check_sum; + BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); + osrm::util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " + << edge_list.size() << " edges"; + auto m_query_graph = std::make_shared(node_list, edge_list); + + BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); + BOOST_ASSERT_MSG(0 == edge_list.size(), "edge list not flushed"); + + osrm::util::Percent progress(m_query_graph->GetNumberOfNodes()); + for (const auto node_u : osrm::util::irange(0u, m_query_graph->GetNumberOfNodes())) + { + for (const auto eid : m_query_graph->GetAdjacentEdgeRange(node_u)) { - osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " "; - return 1; - } - - boost::filesystem::path hsgr_path(argv[1]); - - std::vector node_list; - std::vector edge_list; - osrm::util::SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); - - unsigned m_check_sum = 0; - unsigned m_number_of_nodes = - readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); - osrm::util::SimpleLogger().Write() << "expecting " << m_number_of_nodes - << " nodes, checksum: " << m_check_sum; - BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); - osrm::util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " - << edge_list.size() << " edges"; - auto m_query_graph = std::make_shared(node_list, edge_list); - - BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); - BOOST_ASSERT_MSG(0 == edge_list.size(), "edge list not flushed"); - - osrm::util::Percent progress(m_query_graph->GetNumberOfNodes()); - for (const auto node_u : osrm::util::irange(0u, m_query_graph->GetNumberOfNodes())) - { - for (const auto eid : m_query_graph->GetAdjacentEdgeRange(node_u)) + const osrm::tools::EdgeData &data = m_query_graph->GetEdgeData(eid); + if (!data.shortcut) { - const osrm::tools::EdgeData &data = m_query_graph->GetEdgeData(eid); - if (!data.shortcut) - { - continue; - } - const unsigned node_v = m_query_graph->GetTarget(eid); - const EdgeID edge_id_1 = m_query_graph->FindEdgeInEitherDirection(node_u, data.id); - if (SPECIAL_EDGEID == edge_id_1) - { - throw osrm::util::exception( - "cannot find first segment of edge (" + std::to_string(node_u) + "," + - std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + - std::to_string(eid)); - } - const EdgeID edge_id_2 = m_query_graph->FindEdgeInEitherDirection(data.id, node_v); - if (SPECIAL_EDGEID == edge_id_2) - { - throw osrm::util::exception( - "cannot find second segment of edge (" + std::to_string(node_u) + "," + - std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + - std::to_string(eid)); - } + continue; + } + const unsigned node_v = m_query_graph->GetTarget(eid); + const EdgeID edge_id_1 = m_query_graph->FindEdgeInEitherDirection(node_u, data.id); + if (SPECIAL_EDGEID == edge_id_1) + { + throw osrm::util::exception( + "cannot find first segment of edge (" + std::to_string(node_u) + "," + + std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + + std::to_string(eid)); + } + const EdgeID edge_id_2 = m_query_graph->FindEdgeInEitherDirection(data.id, node_v); + if (SPECIAL_EDGEID == edge_id_2) + { + throw osrm::util::exception( + "cannot find second segment of edge (" + std::to_string(node_u) + "," + + std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + + std::to_string(eid)); } - progress.printStatus(node_u); } - m_query_graph.reset(); - osrm::util::SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK"; + progress.printStatus(node_u); } - catch (const std::exception &e) - { - osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - } - return 0; + m_query_graph.reset(); + osrm::util::SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK"; + + return EXIT_SUCCESS; +} +catch (const std::exception &e) +{ + osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + return EXIT_FAILURE; } diff --git a/src/tools/components.cpp b/src/tools/components.cpp index ae6da2126..69e92cb3c 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -98,141 +98,139 @@ std::size_t loadGraph(const char *path, } } -int main(int argc, char *argv[]) +int main(int argc, char *argv[]) try { std::vector coordinate_list; - osrm::util::LogPolicy::GetInstance().Unmute(); - try + + // enable logging + if (argc < 2) { - // enable logging - if (argc < 2) + osrm::util::SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " "; + return EXIT_FAILURE; + } + + std::vector graph_edge_list; + auto number_of_nodes = osrm::tools::loadGraph(argv[1], coordinate_list, graph_edge_list); + + tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); + const auto graph = + std::make_shared(number_of_nodes, graph_edge_list); + graph_edge_list.clear(); + graph_edge_list.shrink_to_fit(); + + osrm::util::SimpleLogger().Write() << "Starting SCC graph traversal"; + + auto tarjan = + osrm::util::make_unique>(graph); + tarjan->run(); + osrm::util::SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() + << " many components"; + osrm::util::SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() + << " size 1 SCCs"; + + // output + TIMER_START(SCC_RUN_SETUP); + + // remove files from previous run if exist + osrm::tools::deleteFileIfExists("component.dbf"); + osrm::tools::deleteFileIfExists("component.shx"); + osrm::tools::deleteFileIfExists("component.shp"); + + osrm::util::Percent percentage(graph->GetNumberOfNodes()); + + OGRRegisterAll(); + + const char *psz_driver_name = "ESRI Shapefile"; + auto *po_driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(psz_driver_name); + if (nullptr == po_driver) + { + throw osrm::util::exception("ESRI Shapefile driver not available"); + } + auto *po_datasource = po_driver->CreateDataSource("component.shp", nullptr); + + if (nullptr == po_datasource) + { + throw osrm::util::exception("Creation of output file failed"); + } + + auto *po_srs = new OGRSpatialReference(); + po_srs->importFromEPSG(4326); + + auto *po_layer = po_datasource->CreateLayer("component", po_srs, wkbLineString, nullptr); + + if (nullptr == po_layer) + { + throw osrm::util::exception("Layer creation failed."); + } + TIMER_STOP(SCC_RUN_SETUP); + osrm::util::SimpleLogger().Write() << "shapefile setup took " + << TIMER_MSEC(SCC_RUN_SETUP) / 1000. << "s"; + + uint64_t total_network_length = 0; + percentage.reinit(graph->GetNumberOfNodes()); + TIMER_START(SCC_OUTPUT); + for (const NodeID source : osrm::util::irange(0u, graph->GetNumberOfNodes())) + { + percentage.printIncrement(); + for (const auto current_edge : graph->GetAdjacentEdgeRange(source)) { - osrm::util::SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0] << " "; - return -1; - } + const auto target = graph->GetTarget(current_edge); - std::vector graph_edge_list; - auto number_of_nodes = osrm::tools::loadGraph(argv[1], coordinate_list, graph_edge_list); - - tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end()); - const auto graph = - std::make_shared(number_of_nodes, graph_edge_list); - graph_edge_list.clear(); - graph_edge_list.shrink_to_fit(); - - osrm::util::SimpleLogger().Write() << "Starting SCC graph traversal"; - - auto tarjan = - osrm::util::make_unique>(graph); - tarjan->run(); - osrm::util::SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components() - << " many components"; - osrm::util::SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() - << " size 1 SCCs"; - - // output - TIMER_START(SCC_RUN_SETUP); - - // remove files from previous run if exist - osrm::tools::deleteFileIfExists("component.dbf"); - osrm::tools::deleteFileIfExists("component.shx"); - osrm::tools::deleteFileIfExists("component.shp"); - - osrm::util::Percent percentage(graph->GetNumberOfNodes()); - - OGRRegisterAll(); - - const char *psz_driver_name = "ESRI Shapefile"; - auto *po_driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(psz_driver_name); - if (nullptr == po_driver) - { - throw osrm::util::exception("ESRI Shapefile driver not available"); - } - auto *po_datasource = po_driver->CreateDataSource("component.shp", nullptr); - - if (nullptr == po_datasource) - { - throw osrm::util::exception("Creation of output file failed"); - } - - auto *po_srs = new OGRSpatialReference(); - po_srs->importFromEPSG(4326); - - auto *po_layer = po_datasource->CreateLayer("component", po_srs, wkbLineString, nullptr); - - if (nullptr == po_layer) - { - throw osrm::util::exception("Layer creation failed."); - } - TIMER_STOP(SCC_RUN_SETUP); - osrm::util::SimpleLogger().Write() << "shapefile setup took " - << TIMER_MSEC(SCC_RUN_SETUP) / 1000. << "s"; - - uint64_t total_network_length = 0; - percentage.reinit(graph->GetNumberOfNodes()); - TIMER_START(SCC_OUTPUT); - for (const NodeID source : osrm::util::irange(0u, graph->GetNumberOfNodes())) - { - percentage.printIncrement(); - for (const auto current_edge : graph->GetAdjacentEdgeRange(source)) + if (source < target || SPECIAL_EDGEID == graph->FindEdge(target, source)) { - const auto target = graph->GetTarget(current_edge); + total_network_length += + 100 * osrm::util::coordinate_calculation::greatCircleDistance( + coordinate_list[source].lat, coordinate_list[source].lon, + coordinate_list[target].lat, coordinate_list[target].lon); - if (source < target || SPECIAL_EDGEID == graph->FindEdge(target, source)) + BOOST_ASSERT(current_edge != SPECIAL_EDGEID); + BOOST_ASSERT(source != SPECIAL_NODEID); + BOOST_ASSERT(target != SPECIAL_NODEID); + + const unsigned size_of_containing_component = + std::min(tarjan->get_component_size(tarjan->get_component_id(source)), + tarjan->get_component_size(tarjan->get_component_id(target))); + + // edges that end on bollard nodes may actually be in two distinct components + if (size_of_containing_component < 1000) { - total_network_length += - 100 * osrm::util::coordinate_calculation::greatCircleDistance( - coordinate_list[source].lat, coordinate_list[source].lon, - coordinate_list[target].lat, coordinate_list[target].lon); + OGRLineString line_string; + line_string.addPoint( + coordinate_list[source].lon / osrm::COORDINATE_PRECISION, + coordinate_list[source].lat / osrm::COORDINATE_PRECISION); + line_string.addPoint( + coordinate_list[target].lon / osrm::COORDINATE_PRECISION, + coordinate_list[target].lat / osrm::COORDINATE_PRECISION); - BOOST_ASSERT(current_edge != SPECIAL_EDGEID); - BOOST_ASSERT(source != SPECIAL_NODEID); - BOOST_ASSERT(target != SPECIAL_NODEID); + OGRFeature *po_feature = + OGRFeature::CreateFeature(po_layer->GetLayerDefn()); - const unsigned size_of_containing_component = - std::min(tarjan->get_component_size(tarjan->get_component_id(source)), - tarjan->get_component_size(tarjan->get_component_id(target))); - - // edges that end on bollard nodes may actually be in two distinct components - if (size_of_containing_component < 1000) + po_feature->SetGeometry(&line_string); + if (OGRERR_NONE != po_layer->CreateFeature(po_feature)) { - OGRLineString line_string; - line_string.addPoint( - coordinate_list[source].lon / osrm::COORDINATE_PRECISION, - coordinate_list[source].lat / osrm::COORDINATE_PRECISION); - line_string.addPoint( - coordinate_list[target].lon / osrm::COORDINATE_PRECISION, - coordinate_list[target].lat / osrm::COORDINATE_PRECISION); - - OGRFeature *po_feature = - OGRFeature::CreateFeature(po_layer->GetLayerDefn()); - - po_feature->SetGeometry(&line_string); - if (OGRERR_NONE != po_layer->CreateFeature(po_feature)) - { - throw osrm::util::exception("Failed to create feature in shapefile."); - } - OGRFeature::DestroyFeature(po_feature); + throw osrm::util::exception("Failed to create feature in shapefile."); } + OGRFeature::DestroyFeature(po_feature); } } } - OGRSpatialReference::DestroySpatialReference(po_srs); - OGRDataSource::DestroyDataSource(po_datasource); - TIMER_STOP(SCC_OUTPUT); - osrm::util::SimpleLogger().Write() - << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. << "s"; - - osrm::util::SimpleLogger().Write() - << "total network distance: " - << static_cast(total_network_length / 100 / 1000.) << " km"; - - osrm::util::SimpleLogger().Write() << "finished component analysis"; } - catch (const std::exception &e) - { - osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - } - return 0; + OGRSpatialReference::DestroySpatialReference(po_srs); + OGRDataSource::DestroyDataSource(po_datasource); + TIMER_STOP(SCC_OUTPUT); + osrm::util::SimpleLogger().Write() + << "generating output took: " << TIMER_MSEC(SCC_OUTPUT) / 1000. << "s"; + + osrm::util::SimpleLogger().Write() + << "total network distance: " + << static_cast(total_network_length / 100 / 1000.) << " km"; + + osrm::util::SimpleLogger().Write() << "finished component analysis"; + return EXIT_SUCCESS; +} +catch (const std::exception &e) +{ + osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + return EXIT_FAILURE; } diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index 508f77bf8..a5253decf 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -1,7 +1,10 @@ -#include "contractor/processing_chain.hpp" -#include "contractor/contractor_options.hpp" +#include "contractor/contractor.hpp" +#include "contractor/contractor_config.hpp" #include "util/simple_logger.hpp" +#include "util/version.hpp" +#include +#include #include #include @@ -13,25 +16,131 @@ using namespace osrm; +enum class return_code : unsigned +{ + ok, + fail, + exit +}; + +return_code +parseArguments(int argc, char *argv[], contractor::ContractorConfig &contractor_config) +{ + // declare a group of options that will be allowed only on command line + boost::program_options::options_description generic_options("Options"); + generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( + "config,c", + boost::program_options::value(&contractor_config.config_file_path) + ->default_value("contractor.ini"), + "Path to a configuration file."); + + // declare a group of options that will be allowed both on command line and in config file + boost::program_options::options_description config_options("Configuration"); + config_options.add_options()( + "profile,p", + boost::program_options::value(&contractor_config.profile_path) + ->default_value("profile.lua"), + "Path to LUA routing profile")( + "threads,t", + boost::program_options::value(&contractor_config.requested_num_threads) + ->default_value(tbb::task_scheduler_init::default_num_threads()), + "Number of threads to use")( + "core,k", + boost::program_options::value(&contractor_config.core_factor)->default_value(1.0), + "Percentage of the graph (in vertices) to contract [0..1]")( + "segment-speed-file", + boost::program_options::value(&contractor_config.segment_speed_lookup_path), + "Lookup file containing nodeA,nodeB,speed data to adjust edge weights")( + "level-cache,o", boost::program_options::value(&contractor_config.use_cached_priority) + ->default_value(false), + "Use .level file to retain the contaction level for each node from the last run."); + +#ifdef DEBUG_GEOMETRY + config_options.add_options()( + "debug-geometry", + boost::program_options::value(&contractor_config.debug_geometry_path), + "Write out edge-weight debugging geometry data in GeoJSON format to this file"); +#endif + + // hidden options, will be allowed both on command line and in config file, but will not be + // shown to the user + boost::program_options::options_description hidden_options("Hidden options"); + hidden_options.add_options()("input,i", boost::program_options::value( + &contractor_config.osrm_input_path), + "Input file in .osm, .osm.bz2 or .osm.pbf format"); + + // positional option + boost::program_options::positional_options_description positional_options; + positional_options.add("input", 1); + + // combine above options for parsing + boost::program_options::options_description cmdline_options; + cmdline_options.add(generic_options).add(config_options).add(hidden_options); + + boost::program_options::options_description config_file_options; + config_file_options.add(config_options).add(hidden_options); + + boost::program_options::options_description visible_options( + "Usage: " + boost::filesystem::basename(argv[0]) + " [options]"); + visible_options.add(generic_options).add(config_options); + + // parse command line options + boost::program_options::variables_map option_variables; + boost::program_options::store(boost::program_options::command_line_parser(argc, argv) + .options(cmdline_options) + .positional(positional_options) + .run(), + option_variables); + + const auto &temp_config_path = option_variables["config"].as(); + if (boost::filesystem::is_regular_file(temp_config_path)) + { + boost::program_options::store(boost::program_options::parse_config_file( + temp_config_path.string().c_str(), cmdline_options, true), + option_variables); + } + + if (option_variables.count("version")) + { + util::SimpleLogger().Write() << OSRM_VERSION; + return return_code::exit; + } + + if (option_variables.count("help")) + { + util::SimpleLogger().Write() << "\n" << visible_options; + return return_code::exit; + } + + boost::program_options::notify(option_variables); + + if (!option_variables.count("input")) + { + util::SimpleLogger().Write() << "\n" << visible_options; + return return_code::fail; + } + + return return_code::ok; +} + int main(int argc, char *argv[]) try { util::LogPolicy::GetInstance().Unmute(); contractor::ContractorConfig contractor_config; - const contractor::return_code result = - contractor::ContractorOptions::ParseArguments(argc, argv, contractor_config); + const return_code result = parseArguments(argc, argv, contractor_config); - if (contractor::return_code::fail == result) + if (return_code::fail == result) { return EXIT_FAILURE; } - if (contractor::return_code::exit == result) + if (return_code::exit == result) { return EXIT_SUCCESS; } - contractor::ContractorOptions::GenerateOutputFilesNames(contractor_config); + contractor_config.UseDefaultOutputNames(); if (1 > contractor_config.requested_num_threads) { @@ -70,7 +179,7 @@ int main(int argc, char *argv[]) try tbb::task_scheduler_init init(contractor_config.requested_num_threads); - return contractor::Prepare(contractor_config).Run(); + return contractor::Contractor(contractor_config).Run(); } catch (const std::bad_alloc &e) { diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index 7f27fbc8d..9c63bfb4b 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -1,8 +1,13 @@ #include "extractor/extractor.hpp" -#include "extractor/extractor_options.hpp" +#include "extractor/extractor_config.hpp" #include "util/simple_logger.hpp" +#include "util/ini_file.hpp" +#include "util/version.hpp" + +#include #include +#include #include #include @@ -10,25 +15,150 @@ using namespace osrm; +enum class return_code : unsigned +{ + ok, + fail, + exit +}; + +return_code +parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_config) +{ + // declare a group of options that will be allowed only on command line + boost::program_options::options_description generic_options("Options"); + generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( + /* + * TODO: re-enable this + "restrictions,r", + boost::program_options::value(&extractor_config.restrictions_path), + "Restrictions file in .osrm.restrictions format")( + */ + "config,c", + boost::program_options::value(&extractor_config.config_file_path) + ->default_value("extractor.ini"), + "Path to a configuration file."); + + // declare a group of options that will be allowed both on command line and in config file + boost::program_options::options_description config_options("Configuration"); + config_options.add_options()( + "profile,p", + boost::program_options::value(&extractor_config.profile_path) + ->default_value("profile.lua"), + "Path to LUA routing profile")( + "threads,t", + boost::program_options::value(&extractor_config.requested_num_threads) + ->default_value(tbb::task_scheduler_init::default_num_threads()), + "Number of threads to use")( + "generate-edge-lookup", + boost::program_options::value(&extractor_config.generate_edge_lookup) + ->implicit_value(true) + ->default_value(false), + "Generate a lookup table for internal edge-expanded-edge IDs to OSM node pairs")( + "small-component-size", + boost::program_options::value(&extractor_config.small_component_size) + ->default_value(1000), + "Number of nodes required before a strongly-connected-componennt is considered big " + "(affects nearest neighbor snapping)"); + +#ifdef DEBUG_GEOMETRY + config_options.add_options()("debug-turns", boost::program_options::value( + &extractor_config.debug_turns_path), + "Write out GeoJSON with turn penalty data"); +#endif // DEBUG_GEOMETRY + + // hidden options, will be allowed both on command line and in config file, but will not be + // shown to the user + boost::program_options::options_description hidden_options("Hidden options"); + hidden_options.add_options()("input,i", boost::program_options::value( + &extractor_config.input_path), + "Input file in .osm, .osm.bz2 or .osm.pbf format"); + + // positional option + boost::program_options::positional_options_description positional_options; + positional_options.add("input", 1); + + // combine above options for parsing + boost::program_options::options_description cmdline_options; + cmdline_options.add(generic_options).add(config_options).add(hidden_options); + + boost::program_options::options_description config_file_options; + config_file_options.add(config_options).add(hidden_options); + + boost::program_options::options_description visible_options( + boost::filesystem::basename(argv[0]) + " [options]"); + visible_options.add(generic_options).add(config_options); + + // parse command line options + try + { + boost::program_options::variables_map option_variables; + boost::program_options::store(boost::program_options::command_line_parser(argc, argv) + .options(cmdline_options) + .positional(positional_options) + .run(), + option_variables); + if (option_variables.count("version")) + { + util::SimpleLogger().Write() << OSRM_VERSION; + return return_code::exit; + } + + if (option_variables.count("help")) + { + util::SimpleLogger().Write() << visible_options; + return return_code::exit; + } + + boost::program_options::notify(option_variables); + + // parse config file + if (boost::filesystem::is_regular_file(extractor_config.config_file_path)) + { + util::SimpleLogger().Write() << "Reading options from: " + << extractor_config.config_file_path.string(); + std::string ini_file_contents = + util::read_file_lower_content(extractor_config.config_file_path); + std::stringstream config_stream(ini_file_contents); + boost::program_options::store(parse_config_file(config_stream, config_file_options), + option_variables); + boost::program_options::notify(option_variables); + } + + if (!option_variables.count("input")) + { + util::SimpleLogger().Write() << visible_options; + return return_code::exit; + } + } + catch (std::exception &e) + { + util::SimpleLogger().Write(logWARNING) << e.what(); + return return_code::fail; + } + + return return_code::ok; +} + + int main(int argc, char *argv[]) try { util::LogPolicy::GetInstance().Unmute(); extractor::ExtractorConfig extractor_config; - const extractor::return_code result = - extractor::ExtractorOptions::ParseArguments(argc, argv, extractor_config); + const auto result = parseArguments(argc, argv, extractor_config); - if (extractor::return_code::fail == result) + if (return_code::fail == result) { return EXIT_FAILURE; } - if (extractor::return_code::exit == result) + if (return_code::exit == result) { return EXIT_SUCCESS; } - extractor::ExtractorOptions::GenerateOutputFilesNames(extractor_config); + extractor_config.UseDefaultOutputNames(); if (1 > extractor_config.requested_num_threads) { diff --git a/src/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp index edd128d1b..8c08288a5 100644 --- a/src/tools/io-benchmark.cpp +++ b/src/tools/io-benchmark.cpp @@ -47,7 +47,9 @@ void runStatistics(std::vector &timings_vector, Statistics &stats) } } -int main(int argc, char *argv[]) +boost::filesystem::path test_path; + +int main(int argc, char *argv[]) try { #ifdef __FreeBSD__ @@ -60,279 +62,275 @@ int main(int argc, char *argv[]) #else osrm::util::LogPolicy::GetInstance().Unmute(); - boost::filesystem::path test_path; - try + if (1 == argc) { - if (1 == argc) + osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] + << " /path/on/device"; + return -1; + } + + test_path = boost::filesystem::path(argv[1]); + test_path /= "osrm.tst"; + osrm::util::SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string(); + + // create files for testing + if (2 == argc) + { + // create file to test + if (boost::filesystem::exists(test_path)) { - osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] - << " /path/on/device"; + throw osrm::util::exception("Data file already exists"); + } + + int *random_array = new int[osrm::tools::NUMBER_OF_ELEMENTS]; + std::generate(random_array, random_array + osrm::tools::NUMBER_OF_ELEMENTS, std::rand); +#ifdef __APPLE__ + FILE *fd = fopen(test_path.string().c_str(), "w"); + fcntl(fileno(fd), F_NOCACHE, 1); + fcntl(fileno(fd), F_RDAHEAD, 0); + TIMER_START(write_1gb); + write(fileno(fd), (char *)random_array, + osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + TIMER_STOP(write_1gb); + fclose(fd); +#endif +#ifdef __linux__ + int file_desc = + open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU); + if (-1 == file_desc) + { + throw osrm::util::exception("Could not open random data file"); + } + TIMER_START(write_1gb); + int ret = + write(file_desc, random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + if (0 > ret) + { + throw osrm::util::exception("could not write random data file"); + } + TIMER_STOP(write_1gb); + close(file_desc); +#endif + delete[] random_array; + osrm::util::SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " + << TIMER_SEC(write_1gb) << "s"; + osrm::util::SimpleLogger().Write() << "raw write performance: " << std::setprecision(5) + << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) + << "MB/sec"; + + osrm::util::SimpleLogger().Write(logDEBUG) + << "finished creation of random data. Flush disk cache now!"; + } + else + { + // Run Non-Cached I/O benchmarks + if (!boost::filesystem::exists(test_path)) + { + throw osrm::util::exception("data file does not exist"); + } + + // volatiles do not get optimized + osrm::tools::Statistics stats; + +#ifdef __APPLE__ + volatile unsigned single_block[1024]; + char *raw_array = new char[osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)]; + FILE *fd = fopen(test_path.string().c_str(), "r"); + fcntl(fileno(fd), F_NOCACHE, 1); + fcntl(fileno(fd), F_RDAHEAD, 0); +#endif +#ifdef __linux__ + char *single_block = (char *)memalign(512, 1024 * sizeof(unsigned)); + + int file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); + if (-1 == file_desc) + { + osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); return -1; } - - test_path = boost::filesystem::path(argv[1]); - test_path /= "osrm.tst"; - osrm::util::SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string(); - - // create files for testing - if (2 == argc) - { - // create file to test - if (boost::filesystem::exists(test_path)) - { - throw osrm::util::exception("Data file already exists"); - } - - int *random_array = new int[osrm::tools::NUMBER_OF_ELEMENTS]; - std::generate(random_array, random_array + osrm::tools::NUMBER_OF_ELEMENTS, std::rand); + char *raw_array = + (char *)memalign(512, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); +#endif + TIMER_START(read_1gb); #ifdef __APPLE__ - FILE *fd = fopen(test_path.string().c_str(), "w"); - fcntl(fileno(fd), F_NOCACHE, 1); - fcntl(fileno(fd), F_RDAHEAD, 0); - TIMER_START(write_1gb); - write(fileno(fd), (char *)random_array, - osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); - TIMER_STOP(write_1gb); - fclose(fd); + read(fileno(fd), raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + close(fileno(fd)); + fd = fopen(test_path.string().c_str(), "r"); #endif #ifdef __linux__ - int file_desc = - open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU); - if (-1 == file_desc) - { - throw osrm::util::exception("Could not open random data file"); - } - TIMER_START(write_1gb); - int ret = - write(file_desc, random_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); - if (0 > ret) - { - throw osrm::util::exception("could not write random data file"); - } - TIMER_STOP(write_1gb); - close(file_desc); + int ret = + read(file_desc, raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + osrm::util::SimpleLogger().Write(logDEBUG) << "read " << ret + << " bytes, error: " << strerror(errno); + close(file_desc); + file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); + osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); #endif - delete[] random_array; - osrm::util::SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " - << TIMER_SEC(write_1gb) << "s"; - osrm::util::SimpleLogger().Write() << "raw write performance: " << std::setprecision(5) - << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) - << "MB/sec"; + TIMER_STOP(read_1gb); - osrm::util::SimpleLogger().Write(logDEBUG) - << "finished creation of random data. Flush disk cache now!"; + osrm::util::SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " + << TIMER_SEC(read_1gb) << "s"; + osrm::util::SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) + << std::fixed << 1024 * 1024 / TIMER_SEC(read_1gb) + << "MB/sec"; + + std::vector timing_results_raw_random; + osrm::util::SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB"; + +#ifdef __APPLE__ + fseek(fd, 0, SEEK_SET); +#endif +#ifdef __linux__ + lseek(file_desc, 0, SEEK_SET); +#endif + // make 1000 random access, time each I/O seperately + unsigned number_of_blocks = + (osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned) - 1) / 4096; + std::random_device rd; + std::default_random_engine e1(rd()); + std::uniform_int_distribution uniform_dist(0, number_of_blocks - 1); + for (unsigned i = 0; i < 1000; ++i) + { + unsigned block_to_read = uniform_dist(e1); + off_t current_offset = block_to_read * 4096; + TIMER_START(random_access); +#ifdef __APPLE__ + int ret1 = fseek(fd, current_offset, SEEK_SET); + int ret2 = read(fileno(fd), (char *)&single_block[0], 4096); +#endif + +#ifdef __FreeBSD__ + int ret1 = 0; + int ret2 = 0; +#endif + +#ifdef __linux__ + int ret1 = lseek(file_desc, current_offset, SEEK_SET); + int ret2 = read(file_desc, (char *)single_block, 4096); +#endif + TIMER_STOP(random_access); + if (((off_t)-1) == ret1) + { + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "seek error " + << strerror(errno); + throw osrm::util::exception("seek error"); + } + if (-1 == ret2) + { + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "read error " + << strerror(errno); + throw osrm::util::exception("read error"); + } + timing_results_raw_random.push_back(TIMER_SEC(random_access)); } - else + + // Do statistics + osrm::util::SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics"; + std::ofstream random_csv("random.csv", std::ios::trunc); + for (unsigned i = 0; i < timing_results_raw_random.size(); ++i) { - // Run Non-Cached I/O benchmarks - if (!boost::filesystem::exists(test_path)) - { - throw osrm::util::exception("data file does not exist"); - } + random_csv << i << ", " << timing_results_raw_random[i] << std::endl; + } + random_csv.close(); + osrm::tools::runStatistics(timing_results_raw_random, stats); - // volatiles do not get optimized - osrm::tools::Statistics stats; + osrm::util::SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) + << std::fixed << "min: " << stats.min << "ms, " + << "mean: " << stats.mean << "ms, " + << "med: " << stats.med << "ms, " + << "max: " << stats.max << "ms, " + << "dev: " << stats.dev << "ms"; + std::vector timing_results_raw_seq; #ifdef __APPLE__ - volatile unsigned single_block[1024]; - char *raw_array = new char[osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)]; - FILE *fd = fopen(test_path.string().c_str(), "r"); - fcntl(fileno(fd), F_NOCACHE, 1); - fcntl(fileno(fd), F_RDAHEAD, 0); + fseek(fd, 0, SEEK_SET); #endif #ifdef __linux__ - char *single_block = (char *)memalign(512, 1024 * sizeof(unsigned)); - - int file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); - if (-1 == file_desc) - { - osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); - return -1; - } - char *raw_array = - (char *)memalign(512, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); + lseek(file_desc, 0, SEEK_SET); #endif - TIMER_START(read_1gb); + + // read every 100th block + for (unsigned i = 0; i < 1000; ++i) + { + off_t current_offset = i * 4096; + TIMER_START(read_every_100); #ifdef __APPLE__ - read(fileno(fd), raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); - close(fileno(fd)); - fd = fopen(test_path.string().c_str(), "r"); -#endif -#ifdef __linux__ - int ret = - read(file_desc, raw_array, osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned)); - osrm::util::SimpleLogger().Write(logDEBUG) << "read " << ret - << " bytes, error: " << strerror(errno); - close(file_desc); - file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC); - osrm::util::SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno); -#endif - TIMER_STOP(read_1gb); - - osrm::util::SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " - << TIMER_SEC(read_1gb) << "s"; - osrm::util::SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) - << std::fixed << 1024 * 1024 / TIMER_SEC(read_1gb) - << "MB/sec"; - - std::vector timing_results_raw_random; - osrm::util::SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB"; - -#ifdef __APPLE__ - fseek(fd, 0, SEEK_SET); -#endif -#ifdef __linux__ - lseek(file_desc, 0, SEEK_SET); -#endif - // make 1000 random access, time each I/O seperately - unsigned number_of_blocks = - (osrm::tools::NUMBER_OF_ELEMENTS * sizeof(unsigned) - 1) / 4096; - std::random_device rd; - std::default_random_engine e1(rd()); - std::uniform_int_distribution uniform_dist(0, number_of_blocks - 1); - for (unsigned i = 0; i < 1000; ++i) - { - unsigned block_to_read = uniform_dist(e1); - off_t current_offset = block_to_read * 4096; - TIMER_START(random_access); -#ifdef __APPLE__ - int ret1 = fseek(fd, current_offset, SEEK_SET); - int ret2 = read(fileno(fd), (char *)&single_block[0], 4096); + int ret1 = fseek(fd, current_offset, SEEK_SET); + int ret2 = read(fileno(fd), (char *)&single_block, 4096); #endif #ifdef __FreeBSD__ - int ret1 = 0; - int ret2 = 0; + int ret1 = 0; + int ret2 = 0; #endif #ifdef __linux__ - int ret1 = lseek(file_desc, current_offset, SEEK_SET); - int ret2 = read(file_desc, (char *)single_block, 4096); -#endif - TIMER_STOP(random_access); - if (((off_t)-1) == ret1) - { - osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - osrm::util::SimpleLogger().Write(logWARNING) << "seek error " - << strerror(errno); - throw osrm::util::exception("seek error"); - } - if (-1 == ret2) - { - osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - osrm::util::SimpleLogger().Write(logWARNING) << "read error " - << strerror(errno); - throw osrm::util::exception("read error"); - } - timing_results_raw_random.push_back(TIMER_SEC(random_access)); - } + int ret1 = lseek(file_desc, current_offset, SEEK_SET); - // Do statistics - osrm::util::SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics"; - std::ofstream random_csv("random.csv", std::ios::trunc); - for (unsigned i = 0; i < timing_results_raw_random.size(); ++i) + int ret2 = read(file_desc, (char *)single_block, 4096); +#endif + TIMER_STOP(read_every_100); + if (((off_t)-1) == ret1) { - random_csv << i << ", " << timing_results_raw_random[i] << std::endl; + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "seek error " + << strerror(errno); + throw osrm::util::exception("seek error"); } - random_csv.close(); - osrm::tools::runStatistics(timing_results_raw_random, stats); - - osrm::util::SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) - << std::fixed << "min: " << stats.min << "ms, " - << "mean: " << stats.mean << "ms, " - << "med: " << stats.med << "ms, " - << "max: " << stats.max << "ms, " - << "dev: " << stats.dev << "ms"; - - std::vector timing_results_raw_seq; -#ifdef __APPLE__ - fseek(fd, 0, SEEK_SET); -#endif -#ifdef __linux__ - lseek(file_desc, 0, SEEK_SET); -#endif - - // read every 100th block - for (unsigned i = 0; i < 1000; ++i) + if (-1 == ret2) { - off_t current_offset = i * 4096; - TIMER_START(read_every_100); -#ifdef __APPLE__ - int ret1 = fseek(fd, current_offset, SEEK_SET); - int ret2 = read(fileno(fd), (char *)&single_block, 4096); -#endif - -#ifdef __FreeBSD__ - int ret1 = 0; - int ret2 = 0; -#endif - -#ifdef __linux__ - int ret1 = lseek(file_desc, current_offset, SEEK_SET); - - int ret2 = read(file_desc, (char *)single_block, 4096); -#endif - TIMER_STOP(read_every_100); - if (((off_t)-1) == ret1) - { - osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - osrm::util::SimpleLogger().Write(logWARNING) << "seek error " - << strerror(errno); - throw osrm::util::exception("seek error"); - } - if (-1 == ret2) - { - osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; - osrm::util::SimpleLogger().Write(logWARNING) << "read error " - << strerror(errno); - throw osrm::util::exception("read error"); - } - timing_results_raw_seq.push_back(TIMER_SEC(read_every_100)); + osrm::util::SimpleLogger().Write(logWARNING) << "offset: " << current_offset; + osrm::util::SimpleLogger().Write(logWARNING) << "read error " + << strerror(errno); + throw osrm::util::exception("read error"); } + timing_results_raw_seq.push_back(TIMER_SEC(read_every_100)); + } #ifdef __APPLE__ - fclose(fd); - // free(single_element); - free(raw_array); + fclose(fd); + // free(single_element); + free(raw_array); // free(single_block); #endif #ifdef __linux__ - close(file_desc); + close(file_desc); #endif - // Do statistics - osrm::util::SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics"; - // print simple statistics: min, max, median, variance - std::ofstream seq_csv("sequential.csv", std::ios::trunc); - for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i) - { - seq_csv << i << ", " << timing_results_raw_seq[i] << std::endl; - } - seq_csv.close(); - osrm::tools::runStatistics(timing_results_raw_seq, stats); - osrm::util::SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) - << std::fixed << "min: " << stats.min << "ms, " - << "mean: " << stats.mean << "ms, " - << "med: " << stats.med << "ms, " - << "max: " << stats.max << "ms, " - << "dev: " << stats.dev << "ms"; - - if (boost::filesystem::exists(test_path)) - { - boost::filesystem::remove(test_path); - osrm::util::SimpleLogger().Write(logDEBUG) << "removing temporary files"; - } + // Do statistics + osrm::util::SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics"; + // print simple statistics: min, max, median, variance + std::ofstream seq_csv("sequential.csv", std::ios::trunc); + for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i) + { + seq_csv << i << ", " << timing_results_raw_seq[i] << std::endl; } - } - catch (const std::exception &e) - { - osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); - osrm::util::SimpleLogger().Write(logWARNING) << "cleaning up, and exiting"; + seq_csv.close(); + osrm::tools::runStatistics(timing_results_raw_seq, stats); + osrm::util::SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) + << std::fixed << "min: " << stats.min << "ms, " + << "mean: " << stats.mean << "ms, " + << "med: " << stats.med << "ms, " + << "max: " << stats.max << "ms, " + << "dev: " << stats.dev << "ms"; + if (boost::filesystem::exists(test_path)) { boost::filesystem::remove(test_path); - osrm::util::SimpleLogger().Write(logWARNING) << "removing temporary files"; + osrm::util::SimpleLogger().Write(logDEBUG) << "removing temporary files"; } - return -1; } - return 0; + return EXIT_SUCCESS; #endif } +catch (const std::exception &e) +{ + osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); + osrm::util::SimpleLogger().Write(logWARNING) << "cleaning up, and exiting"; + if (boost::filesystem::exists(test_path)) + { + boost::filesystem::remove(test_path); + osrm::util::SimpleLogger().Write(logWARNING) << "removing temporary files"; + } + return EXIT_FAILURE; +} diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index ee00fa38b..81f8eb6aa 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -4,7 +4,7 @@ #include "util/simple_logger.hpp" #include "osrm/osrm.hpp" -#include "osrm/libosrm_config.hpp" +#include "osrm/engine_config.hpp" #ifdef __linux__ #include @@ -49,12 +49,12 @@ int main(int argc, const char *argv[]) try std::string ip_address; int ip_port, requested_thread_num; - LibOSRMConfig lib_config; + EngineConfig config; const unsigned init_result = util::GenerateServerProgramOptions( - argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, - lib_config.use_shared_memory, trial_run, lib_config.max_locations_trip, - lib_config.max_locations_viaroute, lib_config.max_locations_distance_table, - lib_config.max_locations_map_matching); + argc, argv, config.server_paths, ip_address, ip_port, requested_thread_num, + config.use_shared_memory, trial_run, config.max_locations_trip, + config.max_locations_viaroute, config.max_locations_distance_table, + config.max_locations_map_matching); if (init_result == util::INIT_OK_DO_NOT_START_ENGINE) { return EXIT_SUCCESS; @@ -81,11 +81,11 @@ int main(int argc, const char *argv[]) try (void)munlockall(); } bool should_lock = false, could_lock = true; - } memory_locker(lib_config.use_shared_memory); + } memory_locker(config.use_shared_memory); #endif util::SimpleLogger().Write() << "starting up engines, " << OSRM_VERSION; - if (lib_config.use_shared_memory) + if (config.use_shared_memory) { util::SimpleLogger().Write(logDEBUG) << "Loading from shared memory"; } @@ -102,7 +102,7 @@ int main(int argc, const char *argv[]) try pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask); #endif - OSRM osrm_lib(lib_config); + OSRM osrm_lib(config); auto routing_server = server::Server::CreateServer(ip_address, ip_port, requested_thread_num); routing_server->GetRequestHandlerPtr().RegisterRoutingMachine(&osrm_lib); diff --git a/src/tools/simpleclient.cpp b/src/tools/simpleclient.cpp deleted file mode 100644 index f00b302d6..000000000 --- a/src/tools/simpleclient.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include "util/json_renderer.hpp" -#include "util/routed_options.hpp" -#include "util/simple_logger.hpp" - -#include "osrm/json_container.hpp" -#include "osrm/libosrm_config.hpp" -#include "osrm/route_parameters.hpp" -#include "osrm/osrm.hpp" - -#include - -int main(int argc, const char *argv[]) -{ - osrm::util::LogPolicy::GetInstance().Unmute(); - try - { - std::string ip_address; - int ip_port, requested_thread_num; - bool trial_run = false; - osrm::LibOSRMConfig lib_config; - const unsigned init_result = osrm::util::GenerateServerProgramOptions( - argc, argv, lib_config.server_paths, ip_address, ip_port, requested_thread_num, - lib_config.use_shared_memory, trial_run, lib_config.max_locations_trip, - lib_config.max_locations_viaroute, lib_config.max_locations_distance_table, - lib_config.max_locations_map_matching); - - if (init_result == osrm::util::INIT_OK_DO_NOT_START_ENGINE) - { - return 0; - } - if (init_result == osrm::util::INIT_FAILED) - { - return 1; - } - - osrm::OSRM routing_machine(lib_config); - - osrm::RouteParameters route_parameters; - route_parameters.zoom_level = 18; // no generalization - route_parameters.print_instructions = true; // turn by turn instructions - route_parameters.alternate_route = true; // get an alternate route, too - route_parameters.geometry = true; // retrieve geometry of route - route_parameters.compression = true; // polyline encoding - route_parameters.check_sum = -1; // see wiki - route_parameters.service = "viaroute"; // that's routing - route_parameters.output_format = "json"; - route_parameters.jsonp_parameter = ""; // set for jsonp wrapping - route_parameters.language = ""; // unused atm - // route_parameters.hints.push_back(); // see wiki, saves I/O if done properly - - // start_coordinate - route_parameters.coordinates.emplace_back(52.519930 * osrm::COORDINATE_PRECISION, - 13.438640 * osrm::COORDINATE_PRECISION); - // target_coordinate - route_parameters.coordinates.emplace_back(52.513191 * osrm::COORDINATE_PRECISION, - 13.415852 * osrm::COORDINATE_PRECISION); - osrm::json::Object json_result; - const int result_code = routing_machine.RunQuery(route_parameters, json_result); - osrm::util::SimpleLogger().Write() << "http code: " << result_code; - osrm::json::render(osrm::util::SimpleLogger().Write(), json_result); - } - catch (std::exception ¤t_exception) - { - osrm::util::SimpleLogger().Write(logWARNING) << "caught exception: " - << current_exception.what(); - return -1; - } - return 0; -} diff --git a/src/tools/springclean.cpp b/src/tools/springclean.cpp index 7408e7d2c..440dda2f7 100644 --- a/src/tools/springclean.cpp +++ b/src/tools/springclean.cpp @@ -1,7 +1,7 @@ #include -#include "datastore/shared_memory_factory.hpp" -#include "engine/datafacade/shared_datatype.hpp" +#include "storage/shared_memory.hpp" +#include "storage/shared_datatype.hpp" #include "util/simple_logger.hpp" namespace osrm @@ -10,8 +10,7 @@ namespace tools { // FIXME remove after folding back into datastore -using namespace datastore; -using namespace engine::datafacade; +using namespace storage; void deleteRegion(const SharedDataType region) { @@ -55,33 +54,31 @@ void springclean() } } -int main() +int main() try { osrm::util::LogPolicy::GetInstance().Unmute(); - try - { - osrm::util::SimpleLogger().Write() << "Releasing all locks"; - osrm::util::SimpleLogger().Write() << "ATTENTION! BE CAREFUL!"; - osrm::util::SimpleLogger().Write() << "----------------------"; - osrm::util::SimpleLogger().Write() - << "This tool may put osrm-routed into an undefined state!"; - osrm::util::SimpleLogger().Write() - << "Type 'Y' to acknowledge that you know what your are doing."; - osrm::util::SimpleLogger().Write() - << "\n\nDo you want to purge all shared memory allocated " - << "by osrm-datastore? [type 'Y' to confirm]"; + osrm::util::SimpleLogger().Write() << "Releasing all locks"; + osrm::util::SimpleLogger().Write() << "ATTENTION! BE CAREFUL!"; + osrm::util::SimpleLogger().Write() << "----------------------"; + osrm::util::SimpleLogger().Write() + << "This tool may put osrm-routed into an undefined state!"; + osrm::util::SimpleLogger().Write() + << "Type 'Y' to acknowledge that you know what your are doing."; + osrm::util::SimpleLogger().Write() + << "\n\nDo you want to purge all shared memory allocated " + << "by osrm-datastore? [type 'Y' to confirm]"; - const auto letter = getchar(); - if (letter != 'Y') - { - osrm::util::SimpleLogger().Write() << "aborted."; - return 0; - } - osrm::tools::springclean(); - } - catch (const std::exception &e) + const auto letter = getchar(); + if (letter != 'Y') { - osrm::util::SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); + osrm::util::SimpleLogger().Write() << "aborted."; + return EXIT_SUCCESS; } - return 0; + osrm::tools::springclean(); + return EXIT_SUCCESS; +} +catch (const std::exception &e) +{ + osrm::util::SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); + return EXIT_FAILURE; } diff --git a/include/util/datastore_options.hpp b/src/tools/store.cpp similarity index 80% rename from include/util/datastore_options.hpp rename to src/tools/store.cpp index bd0902506..7065cbb10 100644 --- a/include/util/datastore_options.hpp +++ b/src/tools/store.cpp @@ -1,27 +1,19 @@ -#ifndef DATASTORE_OPTIONS_HPP -#define DATASTORE_OPTIONS_HPP - -#include "util/version.hpp" -#include "util/ini_file.hpp" +#include "storage/storage.hpp" #include "util/osrm_exception.hpp" #include "util/simple_logger.hpp" +#include "util/typedefs.hpp" +#include "util/ini_file.hpp" +#include "util/version.hpp" -#include -#include +#include #include -#include -#include - -namespace osrm -{ -namespace util -{ +using namespace osrm; // generate boost::program_options object for the routing part -bool GenerateDataStoreOptions(const int argc, +bool generateDataStoreOptions(const int argc, const char *argv[], - std::unordered_map &paths) + storage::DataPaths &paths) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); @@ -76,6 +68,13 @@ bool GenerateDataStoreOptions(const int argc, boost::filesystem::basename(argv[0]) + " [] "); visible_options.add(generic_options).add(config_options); + // print help options if no infile is specified + if (argc < 2) + { + util::SimpleLogger().Write() << visible_options; + return false; + } + // parse command line options boost::program_options::variables_map option_variables; boost::program_options::store(boost::program_options::command_line_parser(argc, argv) @@ -86,13 +85,13 @@ bool GenerateDataStoreOptions(const int argc, if (option_variables.count("version")) { - SimpleLogger().Write() << OSRM_VERSION; + util::SimpleLogger().Write() << OSRM_VERSION; return false; } if (option_variables.count("help")) { - SimpleLogger().Write() << visible_options; + util::SimpleLogger().Write() << visible_options; return false; } @@ -121,8 +120,8 @@ bool GenerateDataStoreOptions(const int argc, boost::filesystem::is_regular_file(paths.find("config")->second)) || option_variables.count("base")) { - SimpleLogger().Write(logWARNING) << "conflicting parameters"; - SimpleLogger().Write() << visible_options; + util::SimpleLogger().Write(logWARNING) << "conflicting parameters"; + util::SimpleLogger().Write() << visible_options; return false; } } @@ -132,8 +131,8 @@ bool GenerateDataStoreOptions(const int argc, if (path_iterator != paths.end() && boost::filesystem::is_regular_file(path_iterator->second) && !option_variables.count("base")) { - SimpleLogger().Write() << "Reading options from: " << path_iterator->second.string(); - std::string ini_file_contents = read_file_lower_content(path_iterator->second); + util::SimpleLogger().Write() << "Reading options from: " << path_iterator->second.string(); + std::string ini_file_contents = util::read_file_lower_content(path_iterator->second); std::stringstream config_stream(ini_file_contents); boost::program_options::store(parse_config_file(config_stream, config_file_options), option_variables); @@ -204,61 +203,84 @@ bool GenerateDataStoreOptions(const int argc, if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw exception("valid .hsgr file must be specified"); + throw util::exception("valid .hsgr file must be specified"); } path_iterator = paths.find("nodesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw exception("valid .nodes file must be specified"); + throw util::exception("valid .nodes file must be specified"); } path_iterator = paths.find("edgesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw exception("valid .edges file must be specified"); + throw util::exception("valid .edges file must be specified"); } path_iterator = paths.find("geometry"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw exception("valid .geometry file must be specified"); + throw util::exception("valid .geometry file must be specified"); } path_iterator = paths.find("ramindex"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw exception("valid .ramindex file must be specified"); + throw util::exception("valid .ramindex file must be specified"); } path_iterator = paths.find("fileindex"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw exception("valid .fileindex file must be specified"); + throw util::exception("valid .fileindex file must be specified"); } path_iterator = paths.find("namesdata"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw exception("valid .names file must be specified"); + throw util::exception("valid .names file must be specified"); } path_iterator = paths.find("timestamp"); if (path_iterator == paths.end() || path_iterator->second.string().empty() || !boost::filesystem::is_regular_file(path_iterator->second)) { - throw exception("valid .timestamp file must be specified"); + throw util::exception("valid .timestamp file must be specified"); } return true; } -} -} -#endif /* DATASTORE_OPTIONS_HPP */ +int main(const int argc, const char *argv[]) try +{ + util::LogPolicy::GetInstance().Unmute(); + + storage::DataPaths paths; + if (!generateDataStoreOptions(argc, argv, paths)) + { + return EXIT_SUCCESS; + } + + storage::Storage storage(paths); + return storage.Run(); +} +catch (const std::bad_alloc &e) +{ + util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); + util::SimpleLogger().Write(logWARNING) + << "Please provide more memory or disable locking the virtual " + "address space (note: this makes OSRM swap, i.e. slow)"; + return EXIT_FAILURE; +} +catch (const std::exception &e) +{ + util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what(); + return EXIT_FAILURE; +} diff --git a/src/tools/unlock_all_mutexes.cpp b/src/tools/unlock_all_mutexes.cpp index f59bf7721..2af8477ab 100644 --- a/src/tools/unlock_all_mutexes.cpp +++ b/src/tools/unlock_all_mutexes.cpp @@ -1,22 +1,20 @@ #include "util/simple_logger.hpp" -#include "engine/datafacade/shared_barriers.hpp" +#include "storage/shared_barriers.hpp" #include -int main() +int main() try { osrm::util::LogPolicy::GetInstance().Unmute(); - try - { - osrm::util::SimpleLogger().Write() << "Releasing all locks"; - osrm::engine::datafacade::SharedBarriers barrier; - barrier.pending_update_mutex.unlock(); - barrier.query_mutex.unlock(); - barrier.update_mutex.unlock(); - } - catch (const std::exception &e) - { - osrm::util::SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); - } + osrm::util::SimpleLogger().Write() << "Releasing all locks"; + osrm::storage::SharedBarriers barrier; + barrier.pending_update_mutex.unlock(); + barrier.query_mutex.unlock(); + barrier.update_mutex.unlock(); return 0; } +catch (const std::exception &e) +{ + osrm::util::SimpleLogger().Write(logWARNING) << "[excpetion] " << e.what(); + return EXIT_FAILURE; +} diff --git a/test/data/Makefile b/test/data/Makefile new file mode 100755 index 000000000..a21afa7f5 --- /dev/null +++ b/test/data/Makefile @@ -0,0 +1,29 @@ +BERLIN_URL:=https://s3.amazonaws.com/mapbox/node-osrm/testing/berlin-latest.osm.pbf +TOOL_ROOT:=../../build +PROFILE_ROOT:=../../profiles +OSRM_EXTRACT:=$(TOOL_ROOT)/osrm-extract +OSRM_PREPARE:=$(TOOL_ROOT)/osrm-prepare +PROFILE:=$(PROFILE_ROOT)/car.lua + +all: berlin-latest.osrm.hsgr + +clean: + rm berlin-latest.* + +berlin-latest.osm.pbf: + wget $(BERLIN_URL) -O berlin-latest.osm.pbf + +berlin-latest.osrm: berlin-latest.osm.pbf $(PROFILE) $(OSRM_EXTRACT) + @echo "Verifiyng data file integrity..." + md5sum -c data.md5sum + @echo "Running osrm-extract..." + $(OSRM_EXTRACT) berlin-latest.osm.pbf -p $(PROFILE) + +berlin-latest.osrm.hsgr: berlin-latest.osrm $(PROFILE) $(OSRM_PREPARE) + @echo "Running osrm-prepare..." + $(OSRM_PREPARE) berlin-latest.osrm -p $(PROFILE) + +checksum: + md5sum berlin-latest.osm.pbf > data.md5sum + +.PHONY: clean checksum diff --git a/test/data/data.md5sum b/test/data/data.md5sum new file mode 100644 index 000000000..008701a46 --- /dev/null +++ b/test/data/data.md5sum @@ -0,0 +1 @@ +045af81d07eb9f22e5718db13cf337e4 berlin-latest.osm.pbf diff --git a/unit_tests/io_tests.cpp b/unit_tests/io_tests.cpp deleted file mode 100644 index 4b0d83b56..000000000 --- a/unit_tests/io_tests.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#define BOOST_TEST_MODULE io tests - -#include - -/* - * This file will contain an automatically generated main function. - */ diff --git a/unit_tests/io/io.cpp b/unit_tests/util/io.cpp similarity index 100% rename from unit_tests/io/io.cpp rename to unit_tests/util/io.cpp From 17f8e65808a4f1c56ebe12a6f3e88f20d5275b9d Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 21 Jan 2016 04:00:12 +0100 Subject: [PATCH 096/701] Fail hard if node weights are not there --- src/contractor/contractor.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/contractor/contractor.cpp b/src/contractor/contractor.cpp index 70352a45b..6b01c564a 100644 --- a/src/contractor/contractor.cpp +++ b/src/contractor/contractor.cpp @@ -93,9 +93,13 @@ int Contractor::Run() std::vector node_weights; std::string node_file_name = config.osrm_input_path.string() + ".enw"; if (util::deserializeVector(node_file_name, node_weights)) + { util::SimpleLogger().Write() << "Done reading node weights."; + } else - util::SimpleLogger().Write() << "Failed reading node weights."; + { + throw util::exception("Failed reading node weights."); + } util::DeallocatingVector contracted_edge_list; ContractGraph(max_edge_id, edge_based_edge_list, contracted_edge_list, std::move(node_weights), From 502aedb33e904a9c854d641d0d85b50ef571357a Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 20 Jan 2016 12:41:33 +0100 Subject: [PATCH 097/701] Provide a way to selectively enable assertions in release mode - Throwing an assertion exception for proper stack unwinding, making sure destructors are called - On in Debug mode, in Release, enable via: cmake -DCMAKE_BUILD_TYPE=Release -DENABLE_ASSERTIONS=ON Current problem that I'm seeing is that some code is not catching exceptions or worse silently swallowing them. Would like to check the whole pipeline before merging this in. --- CMakeLists.txt | 7 +++++++ include/util/assert.hpp | 20 ++++++++++++++++++++ src/util/assert.cpp | 29 +++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 include/util/assert.hpp create mode 100644 src/util/assert.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b07b94b53..6a2fca602 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,6 +32,7 @@ endif() option(ENABLE_JSON_LOGGING "Adds additional JSON debug logging to the response" OFF) option(DEBUG_GEOMETRY "Enables an option to dump GeoJSON of the final routing graph" OFF) option(BUILD_TOOLS "Build OSRM tools" OFF) +option(ENABLE_ASSERTIONS OFF) include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}/include/) include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/) @@ -97,6 +98,7 @@ if(NOT CMAKE_BUILD_TYPE MATCHES Debug) endif() if(CMAKE_BUILD_TYPE MATCHES Debug) message(STATUS "Configuring OSRM in debug mode") + set(ENABLE_ASSERTIONS ON) if(NOT ${CMAKE_CXX_COMPILER_ID} STREQUAL "MSVC") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-inline -fno-omit-frame-pointer") @@ -366,6 +368,11 @@ if(BUILD_TOOLS) install(TARGETS osrm-springclean DESTINATION bin) endif() +if (ENABLE_ASSERTIONS) + message(STATUS "Enabling assertions") + add_definitions(-DBOOST_ENABLE_ASSERT_HANDLER) +endif() + # Add RPATH info to executables so that when they are run after being installed # (i.e., from /usr/local/bin/) the linker can find library dependencies. For # more info see http://www.cmake.org/Wiki/CMake_RPATH_handling diff --git a/include/util/assert.hpp b/include/util/assert.hpp new file mode 100644 index 000000000..d9bfb9542 --- /dev/null +++ b/include/util/assert.hpp @@ -0,0 +1,20 @@ +#ifndef OSRM_ASSERT_HPP +#define OSRM_ASSERT_HPP + +#include + +#include + +namespace osrm +{ +namespace util +{ +// Assertion type to be thrown for stack unwinding +struct assertionError final : std::logic_error +{ + assertionError(const char *msg) : std::logic_error{msg} {} +}; +} +} + +#endif diff --git a/src/util/assert.cpp b/src/util/assert.cpp new file mode 100644 index 000000000..70517840a --- /dev/null +++ b/src/util/assert.cpp @@ -0,0 +1,29 @@ +#include "util/assert.hpp" + +#include + +namespace +{ +// We throw to guarantee for stack-unwinding and therefore our destructors being called. +void assertion_failed_msg_helper( + char const *expr, char const *msg, char const *function, char const *file, long line) +{ + std::ostringstream fmt; + fmt << file << ":" << line << "\nin: " << function << ": " << expr << "\n" << msg; + throw osrm::util::assertionError{fmt.str().c_str()}; +} +} + +// Boost.Assert only declares the following two functions and let's us define them here. +namespace boost +{ +void assertion_failed(char const *expr, char const *function, char const *file, long line) +{ + ::assertion_failed_msg_helper(expr, "", function, file, line); +} +void assertion_failed_msg( + char const *expr, char const *msg, char const *function, char const *file, long line) +{ + ::assertion_failed_msg_helper(expr, msg, function, file, line); +} +} From b48022be227bc478377fc1f9f454d94c8b970c04 Mon Sep 17 00:00:00 2001 From: Mortada Mehyar Date: Mon, 25 Jan 2016 14:53:44 -0800 Subject: [PATCH 098/701] make it possible to disable max_locations in map_matching --- include/util/routed_options.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index 7cb69af3e..070b0d694 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -237,7 +237,7 @@ GenerateServerProgramOptions(const int argc, { throw exception("Max location for distance table must be at least two"); } - if (2 > max_locations_map_matching) + if (max_locations_map_matching > 0 && 2 > max_locations_map_matching) { throw exception("Max location for map matching must be at least two"); } From 40a3008318a72464daf57b5eccee0b0b00fb7952 Mon Sep 17 00:00:00 2001 From: Mathias Gug Date: Mon, 25 Jan 2016 15:03:37 -0800 Subject: [PATCH 099/701] Send the Connection: close response header so that proxy server don't try to reuse the connection. Given that osrm-routed does *not* support keepalive the Connection: close response header should be set. --- src/server/http/reply.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/server/http/reply.cpp b/src/server/http/reply.cpp index 87faa1ba1..efea8f628 100644 --- a/src/server/http/reply.cpp +++ b/src/server/http/reply.cpp @@ -103,7 +103,11 @@ boost::asio::const_buffer reply::status_to_buffer(const reply::status_type statu return boost::asio::buffer(http_bad_request_string); } -reply::reply() : status(ok) {} +reply::reply() : status(ok) +{ + // We do not currently support keep alive. Always set 'Connection: close'. + headers.emplace_back("Connection", "close"); +} } } } From 17c3c1d66ab14caa9507404265de7a8bcf4032cb Mon Sep 17 00:00:00 2001 From: Mortada Mehyar Date: Mon, 25 Jan 2016 15:17:44 -0800 Subject: [PATCH 100/701] improve comments for gps_precision --- include/engine/plugins/match.hpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index bc831cbc3..713245376 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -85,8 +85,9 @@ template class MapMatchingPlugin : public BasePlugin { CandidateLists candidates_lists; - // assuming the gps_precision is the standart-diviation of normal distribution that models - // GPS noise (in this model) this should give us the correct candidate with >0.95 + // assuming gps_precision is the standard deviation of a normal distribution that + // models GPS noise (in this model), this should give us the correct search radius + // with > 99% confidence double query_radius = 3 * gps_precision; double last_distance = util::coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]); From 752c15c230cd2839b402f69a422fd52d91330440 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 21 Jan 2016 17:50:27 +0100 Subject: [PATCH 101/701] Add taginfo checker script and update taginfo --- .travis.yml | 1 + scripts/check_taginfo.py | 51 ++++++++++++++ taginfo.json | 147 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 192 insertions(+), 7 deletions(-) create mode 100755 scripts/check_taginfo.py diff --git a/.travis.yml b/.travis.yml index da116e2ac..45029745c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -132,6 +132,7 @@ before_script: - cmake .. -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS:-OFF} -DBUILD_TOOLS=1 script: + - ./scripts/check_taginfo.py taginfo.json profiles/car.lua - make --jobs=2 - make tests --jobs=2 - make benchmarks diff --git a/scripts/check_taginfo.py b/scripts/check_taginfo.py new file mode 100755 index 000000000..04c2b1932 --- /dev/null +++ b/scripts/check_taginfo.py @@ -0,0 +1,51 @@ +#!/usr/bin/python2 + +import json +import sys +import re + +WHITELIST = set(["mph"]) + +if len(sys.argv) < 3: + print "Not enough arguments.\nUsage: " + sys.argv[0] + " taginfo.json profile.lua" + sys.exit(1) + +taginfo_path = sys.argv[1] +profile_path = sys.argv[2] + +taginfo = None +with open(taginfo_path) as f: + taginfo = json.load(f) + +valid_strings = [t["key"] for t in taginfo["tags"]] +valid_strings += [t["value"] for t in taginfo["tags"] if "value" in t] + +string_regxp = re.compile("\"([\d\w\_:]+)\"") + +profile = None +with open(profile_path) as f: + profile = f.readlines() + +n_errors = 0 +for n, line in enumerate(profile): + # ignore comments + if line.strip().startswith("--"): + continue + tokens = set(string_regxp.findall(line)) + errors = [] + for token in tokens: + if token not in WHITELIST and token not in valid_strings: + idx = line.find("\""+token+"\"") + errors.append((idx, token)) + errors = sorted(errors) + n_errors += len(errors) + if len(errors) > 0: + prefix = "%i: " % n + offset = len(prefix) + for idx, token in errors: + sys.stdout.write(prefix + line) + marker = " "*(idx+offset) + "~"*(len(token)+2) + print(marker) + +if n_errors > 0: + sys.exit(1) diff --git a/taginfo.json b/taginfo.json index 17a4f8f24..4ef48de28 100644 --- a/taginfo.json +++ b/taginfo.json @@ -6,13 +6,12 @@ "description": "High-performance routing engine for shortest paths in road networks.", "project_url": "http://project-osrm.org", "icon_url": "http://project-osrm.org/images/osrm_icon.png", - "contact_name": "Dennis Luxen", - "contact_email": "info@project-osrm.org" + "contact_name": "Patrick Niklaus", + "contact_email": "patrick@mapbox.com" }, "tags": [ { "key": "highway", - "description": "Type of road.", "object_types": [ "way" ] }, { @@ -22,6 +21,23 @@ }, { "key": "oneway", + "value": "true", + "object_types": [ "way" ] + }, + { + "key": "oneway", + "value": "1", + "object_types": [ "way" ] + }, + { + "key": "oneway", + "value": "-1", + "object_types": [ "way" ] + }, + { + "key": "oneway", + "value": "reversible", + "description": "is marked as non-routable because of time-dependence", "object_types": [ "way" ] }, { @@ -38,10 +54,127 @@ "key": "status", "description": "This is used by HOT." }, - { - "key": "access", - "object_types": [ "way" ] - }, + {"key": "maxspeed:advisory"}, + {"key": "maxspeed:advisory:forward"}, + {"key": "maxspeed:advisory:backward"}, + {"key": "bridge", "value": "movable", "description": "uses capacity and duration"}, + {"key": "capacity:car", "description": "used for movable bridges"}, + {"key": "side_road", "value": "yes", "description": "gets speed penalty"}, + {"key": "side_road", "value": "rotary", "description": "gets speed penalty"}, + {"key": "route", "object_types": ["way"]}, + {"key": "highway", "value": "traffic_signals", "object_types": ["node"]}, + {"key": "access", "value": "yes"}, + {"key": "access", "value": "motorcar"}, + {"key": "access", "value": "motor_vehicle"}, + {"key": "access", "value": "vehicle"}, + {"key": "access", "value": "permissive"}, + {"key": "access", "value": "designated"}, + {"key": "access", "value": "destination"}, + {"key": "access", "value": "no"}, + {"key": "access", "value": "private"}, + {"key": "access", "value": "agricultural"}, + {"key": "access", "value": "forestry"}, + {"key": "access", "value": "emergency"}, + {"key": "access", "value": "psv"}, + {"key": "access", "value": "delivery"}, + {"key": "maxspeed", "value": "urban"}, + {"key": "maxspeed", "value": "rural"}, + {"key": "maxspeed", "value": "trunk"}, + {"key": "maxspeed", "value": "motorway"}, + {"key": "maxspeed", "value": "ch:rural"}, + {"key": "maxspeed", "value": "ch:trunk"}, + {"key": "maxspeed", "value": "ch:motorway"}, + {"key": "maxspeed", "value": "de:living_street"}, + {"key": "maxspeed", "value": "ru:living_street"}, + {"key": "maxspeed", "value": "ru:urban"}, + {"key": "maxspeed", "value": "ua:urban"}, + {"key": "maxspeed", "value": "at:rural"}, + {"key": "maxspeed", "value": "de:rural"}, + {"key": "maxspeed", "value": "at:trunk"}, + {"key": "maxspeed", "value": "cz:trunk"}, + {"key": "maxspeed", "value": "ro:trunk"}, + {"key": "maxspeed", "value": "cz:motorway"}, + {"key": "maxspeed", "value": "de:motorway"}, + {"key": "maxspeed", "value": "ru:motorway"}, + {"key": "maxspeed", "value": "gb:nsl_single"}, + {"key": "maxspeed", "value": "gb:nsl_dual"}, + {"key": "maxspeed", "value": "gb:motorway"}, + {"key": "maxspeed", "value": "uk:nsl_single"}, + {"key": "maxspeed", "value": "uk:nsl_dual"}, + {"key": "maxspeed", "value": "uk:motorway"}, + {"key": "smoothness", "value": "intermediate"}, + {"key": "smoothness", "value": "bad"}, + {"key": "smoothness", "value": "very_bad"}, + {"key": "smoothness", "value": "horrible"}, + {"key": "smoothness", "value": "very_horrible"}, + {"key": "smoothness", "value": "impassable"}, + {"key": "tracktype", "value": "grade1"}, + {"key": "tracktype", "value": "grade2"}, + {"key": "tracktype", "value": "grade3"}, + {"key": "tracktype", "value": "grade4"}, + {"key": "tracktype", "value": "grade5"}, + {"key": "bollard", "value": "rising"}, + {"key": "bollard", "description": "Non-rising bollards are barriers"}, + {"key": "barrier", "value": "cattle_grid"}, + {"key": "barrier", "value": "border_control"}, + {"key": "barrier", "value": "checkpoint"}, + {"key": "barrier", "value": "toll_booth"}, + {"key": "barrier", "value": "sally_port"}, + {"key": "barrier", "value": "gate"}, + {"key": "barrier", "value": "lift_gate"}, + {"key": "barrier", "value": "no"}, + {"key": "barrier", "value": "entrance"}, + {"key": "highway", "value": "motorway"}, + {"key": "highway", "value": "motorway_link"}, + {"key": "highway", "value": "trunk"}, + {"key": "highway", "value": "trunk_link"}, + {"key": "highway", "value": "primary"}, + {"key": "highway", "value": "primary_link"}, + {"key": "highway", "value": "secondary"}, + {"key": "highway", "value": "secondary_link"}, + {"key": "highway", "value": "tertiary"}, + {"key": "highway", "value": "tertiary_link"}, + {"key": "highway", "value": "unclassified"}, + {"key": "highway", "value": "residential"}, + {"key": "highway", "value": "living_street"}, + {"key": "highway", "value": "service"}, + {"key": "highway", "value": "ferry"}, + {"key": "highway", "value": "movable"}, + {"key": "highway", "value": "shuttle_train"}, + {"key": "highway", "value": "default"}, + {"key": "width", "description": "Penalties for narrow streets"}, + {"key": "lanes", "description": "Penalties for shared single lane streets"}, + {"key": "surface", "value": "asphalt"}, + {"key": "surface", "value": "concrete"}, + {"key": "surface", "value": "concrete:plates"}, + {"key": "surface", "value": "concrete:lanes"}, + {"key": "surface", "value": "paved"}, + {"key": "surface", "value": "cement"}, + {"key": "surface", "value": "compacted"}, + {"key": "surface", "value": "fine_gravel"}, + {"key": "surface", "value": "paving_stones"}, + {"key": "surface", "value": "metal"}, + {"key": "surface", "value": "bricks"}, + {"key": "surface", "value": "grass"}, + {"key": "surface", "value": "wood"}, + {"key": "surface", "value": "sett"}, + {"key": "surface", "value": "grass_paver"}, + {"key": "surface", "value": "gravel"}, + {"key": "surface", "value": "unpaved"}, + {"key": "surface", "value": "ground"}, + {"key": "surface", "value": "dirt"}, + {"key": "surface", "value": "pebblestone"}, + {"key": "surface", "value": "tartan"}, + {"key": "surface", "value": "cobblestone"}, + {"key": "surface", "value": "clay"}, + {"key": "surface", "value": "earth"}, + {"key": "surface", "value": "stone"}, + {"key": "surface", "value": "rocky"}, + {"key": "surface", "value": "sand"}, + {"key": "surface", "value": "mud"}, + {"key": "motorcar"}, + {"key": "motor_vehicle"}, + {"key": "vehicle"}, { "key": "barrier" }, From 9304ad125c3d1a8c90dff090fa2bc8a7d865fd23 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 21 Jan 2016 20:18:18 +0100 Subject: [PATCH 102/701] Fix python2 --- scripts/check_taginfo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/check_taginfo.py b/scripts/check_taginfo.py index 04c2b1932..c2c4c7276 100755 --- a/scripts/check_taginfo.py +++ b/scripts/check_taginfo.py @@ -1,4 +1,4 @@ -#!/usr/bin/python2 +#!/usr/bin/env python2 import json import sys From 234cf2d84706f3a4898eaeff5c5af7fba38bf040 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 21 Jan 2016 20:20:33 +0100 Subject: [PATCH 103/701] Move taginfo check --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 45029745c..e0e75c74f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -123,6 +123,7 @@ install: before_script: - cd ${TRAVIS_BUILD_DIR} + - ./scripts/check_taginfo.py taginfo.json profiles/car.lua - rvm use 1.9.3 - gem install bundler - bundle install @@ -132,7 +133,6 @@ before_script: - cmake .. -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS:-OFF} -DBUILD_TOOLS=1 script: - - ./scripts/check_taginfo.py taginfo.json profiles/car.lua - make --jobs=2 - make tests --jobs=2 - make benchmarks From 0f9eec887f8b3d247df8da0a43b7c6c6c78563ee Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 26 Jan 2016 04:42:12 +0100 Subject: [PATCH 104/701] Only run script on linux --- .travis.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index e0e75c74f..e907dde5f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -123,7 +123,10 @@ install: before_script: - cd ${TRAVIS_BUILD_DIR} - - ./scripts/check_taginfo.py taginfo.json profiles/car.lua + - | + if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then + ./scripts/check_taginfo.py taginfo.json profiles/car.lua + fi - rvm use 1.9.3 - gem install bundler - bundle install From 2c0547bb0e6b99b792d72bf41fd647bf130e6059 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 15:56:08 +0100 Subject: [PATCH 105/701] Make XORFastHash great again --- include/util/xor_fast_hash.hpp | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 5b7a103bb..54f9d67d9 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -1,7 +1,13 @@ #ifndef XOR_FAST_HASH_HPP #define XOR_FAST_HASH_HPP +#include + +#include #include +#include +#include +#include #include namespace osrm @@ -29,27 +35,29 @@ namespace util */ class XORFastHash { // 65k entries - std::vector table1; - std::vector table2; + std::array table1; + std::array table2; public: XORFastHash() { - table1.resize(2 << 16); - table2.resize(2 << 16); - for (unsigned i = 0; i < (2 << 16); ++i) - { - table1[i] = static_cast(i); - table2[i] = static_cast(i); - } - std::random_shuffle(table1.begin(), table1.end()); - std::random_shuffle(table2.begin(), table2.end()); + std::mt19937 generator; // impl. defined but deterministic default seed + + std::iota(begin(table1), end(table1), 0u); + std::shuffle(begin(table1), end(table1), generator); + + std::iota(begin(table2), end(table2), 0u); + std::shuffle(begin(table2), end(table2), generator); } inline unsigned short operator()(const unsigned originalValue) const { unsigned short lsb = ((originalValue)&0xffff); unsigned short msb = (((originalValue) >> 16) & 0xffff); + + BOOST_ASSERT(lsb < table1.size()); + BOOST_ASSERT(msb < table2.size()); + return table1[lsb] ^ table2[msb]; } }; From f8b5e7e2c9d726c77842a3aea460dcfc7bc903fe Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 15:58:14 +0100 Subject: [PATCH 106/701] Removes XORMiniHash, unused --- include/util/xor_fast_hash.hpp | 36 ---------------------------------- 1 file changed, 36 deletions(-) diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 54f9d67d9..49a59f756 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -61,42 +61,6 @@ class XORFastHash return table1[lsb] ^ table2[msb]; } }; - -class XORMiniHash -{ // 256 entries - std::vector table1; - std::vector table2; - std::vector table3; - std::vector table4; - - public: - XORMiniHash() - { - table1.resize(1 << 8); - table2.resize(1 << 8); - table3.resize(1 << 8); - table4.resize(1 << 8); - for (unsigned i = 0; i < (1 << 8); ++i) - { - table1[i] = static_cast(i); - table2[i] = static_cast(i); - table3[i] = static_cast(i); - table4[i] = static_cast(i); - } - std::random_shuffle(table1.begin(), table1.end()); - std::random_shuffle(table2.begin(), table2.end()); - std::random_shuffle(table3.begin(), table3.end()); - std::random_shuffle(table4.begin(), table4.end()); - } - unsigned char operator()(const unsigned originalValue) const - { - unsigned char byte1 = ((originalValue)&0xff); - unsigned char byte2 = ((originalValue >> 8) & 0xff); - unsigned char byte3 = ((originalValue >> 16) & 0xff); - unsigned char byte4 = ((originalValue >> 24) & 0xff); - return table1[byte1] ^ table2[byte2] ^ table3[byte3] ^ table4[byte4]; - } -}; } } From 2f42196fcaeea644725451b959801d2245123026 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 16:11:33 +0100 Subject: [PATCH 107/701] Explicitely type XORFastHash --- include/util/xor_fast_hash.hpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 49a59f756..4c1b864c0 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -10,6 +10,8 @@ #include #include +#include + namespace osrm { namespace util @@ -35,8 +37,8 @@ namespace util */ class XORFastHash { // 65k entries - std::array table1; - std::array table2; + std::array table1; + std::array table2; public: XORFastHash() @@ -50,10 +52,10 @@ class XORFastHash std::shuffle(begin(table2), end(table2), generator); } - inline unsigned short operator()(const unsigned originalValue) const + inline std::uint16_t operator()(const std::uint32_t originalValue) const { - unsigned short lsb = ((originalValue)&0xffff); - unsigned short msb = (((originalValue) >> 16) & 0xffff); + std::uint16_t lsb = ((originalValue)&0xffff); + std::uint16_t msb = (((originalValue) >> 16) & 0xffff); BOOST_ASSERT(lsb < table1.size()); BOOST_ASSERT(msb < table2.size()); From 60ef6070b012b3a0b0df34926dd11b39a2a911d3 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 16:19:51 +0100 Subject: [PATCH 108/701] Simplify uint32_t splitting in XORFastHash --- include/util/xor_fast_hash.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 4c1b864c0..0cfed223f 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -37,8 +37,8 @@ namespace util */ class XORFastHash { // 65k entries - std::array table1; - std::array table2; + std::array table1; + std::array table2; public: XORFastHash() @@ -54,8 +54,8 @@ class XORFastHash inline std::uint16_t operator()(const std::uint32_t originalValue) const { - std::uint16_t lsb = ((originalValue)&0xffff); - std::uint16_t msb = (((originalValue) >> 16) & 0xffff); + std::uint16_t lsb = originalValue & 0xffffu; + std::uint16_t msb = originalValue >> 16u; BOOST_ASSERT(lsb < table1.size()); BOOST_ASSERT(msb < table2.size()); From 1417d43430e220a6aee358390496a8c6d5febbbf Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 16:30:46 +0100 Subject: [PATCH 109/701] Cut down memory usage for tables in XORFastHash by factor of four `pow(2, 16)` is not `2 << 16` but rather `1 << 16`. With this change we cut memory usage in half for the XORFastHash's two tables. Adapts XORFastHashStorage, memory usage reduction by factor two. --- include/util/xor_fast_hash.hpp | 4 ++-- include/util/xor_fast_hash_storage.hpp | 18 ++++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index 0cfed223f..b9ed0520e 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -37,8 +37,8 @@ namespace util */ class XORFastHash { // 65k entries - std::array table1; - std::array table2; + std::array table1; + std::array table2; public: XORFastHash() diff --git a/include/util/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp index 7fad54027..6872da900 100644 --- a/include/util/xor_fast_hash_storage.hpp +++ b/include/util/xor_fast_hash_storage.hpp @@ -34,29 +34,35 @@ template class XORFastHashStorage XORFastHashStorage() = delete; - explicit XORFastHashStorage(size_t) : positions(2 << 16), current_timestamp(0) {} + explicit XORFastHashStorage(size_t) : positions(1u << 16u), current_timestamp(0) {} HashCell &operator[](const NodeID node) { - unsigned short position = fast_hasher(node); + std::uint16_t position = fast_hasher(node); while ((positions[position].time == current_timestamp) && (positions[position].id != node)) { - ++position %= (2 << 16); + ++position %= (1u << 16u); } positions[position].time = current_timestamp; positions[position].id = node; + + BOOST_ASSERT(position < positions.size()); + return positions[position]; } // peek into table, get key for node, think of it as a read-only operator[] Key peek_index(const NodeID node) const { - unsigned short position = fast_hasher(node); + std::uint16_t position = fast_hasher(node); while ((positions[position].time == current_timestamp) && (positions[position].id != node)) { - ++position %= (2 << 16); + ++position %= (1u << 16u); } + + BOOST_ASSERT(position < positions.size()); + return positions[position].key; } @@ -66,7 +72,7 @@ template class XORFastHashStorage if (std::numeric_limits::max() == current_timestamp) { positions.clear(); - positions.resize(2 << 16); + positions.resize(1u << 16u); } } From a6e7954128b6e9c1d23ecdd7f75890b677fcdd94 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 19:17:02 +0100 Subject: [PATCH 110/701] Make XORFastHash's number of hashable elements compile time constant Still constraint by the usage of uint32_t and subsequent splitting into two uint16_t we use for indexing into the tables. --- include/contractor/graph_contractor.hpp | 2 +- include/util/xor_fast_hash.hpp | 10 ++++++---- include/util/xor_fast_hash_storage.hpp | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/include/contractor/graph_contractor.hpp b/include/contractor/graph_contractor.hpp index 65b31039f..541d9e74b 100644 --- a/include/contractor/graph_contractor.hpp +++ b/include/contractor/graph_contractor.hpp @@ -1096,7 +1096,7 @@ class GraphContractor // self-loops are added. std::vector node_weights; std::vector is_core_node; - util::XORFastHash fast_hash; + util::XORFastHash<> fast_hash; }; } } diff --git a/include/util/xor_fast_hash.hpp b/include/util/xor_fast_hash.hpp index b9ed0520e..6ad79d66a 100644 --- a/include/util/xor_fast_hash.hpp +++ b/include/util/xor_fast_hash.hpp @@ -35,10 +35,12 @@ namespace util 10: ret */ -class XORFastHash -{ // 65k entries - std::array table1; - std::array table2; +template class XORFastHash +{ + static_assert(MaxNumElements <= (1u << 16u), "only 65536 elements indexable with uint16_t"); + + std::array table1; + std::array table2; public: XORFastHash() diff --git a/include/util/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp index 6872da900..297aabb2f 100644 --- a/include/util/xor_fast_hash_storage.hpp +++ b/include/util/xor_fast_hash_storage.hpp @@ -78,7 +78,7 @@ template class XORFastHashStorage private: std::vector positions; - XORFastHash fast_hasher; + XORFastHash<> fast_hasher; unsigned current_timestamp; }; } From 312b414d8f2d82d3a8e360fc5419b36700121f8b Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 22 Jan 2016 10:48:14 +0100 Subject: [PATCH 111/701] Adapts XORFastHashStorage to XORFastHash compile time limits --- include/util/xor_fast_hash_storage.hpp | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/include/util/xor_fast_hash_storage.hpp b/include/util/xor_fast_hash_storage.hpp index 297aabb2f..6d2d76baa 100644 --- a/include/util/xor_fast_hash_storage.hpp +++ b/include/util/xor_fast_hash_storage.hpp @@ -11,7 +11,8 @@ namespace osrm namespace util { -template class XORFastHashStorage +template +class XORFastHashStorage { public: struct HashCell @@ -26,22 +27,18 @@ template class XORFastHashStorage } HashCell(const HashCell &other) : time(other.key), id(other.id), key(other.time) {} - operator Key() const { return key; } - void operator=(const Key key_to_insert) { key = key_to_insert; } }; - XORFastHashStorage() = delete; - - explicit XORFastHashStorage(size_t) : positions(1u << 16u), current_timestamp(0) {} + explicit XORFastHashStorage(size_t) : positions(MaxNumElements), current_timestamp{0u} {} HashCell &operator[](const NodeID node) { std::uint16_t position = fast_hasher(node); while ((positions[position].time == current_timestamp) && (positions[position].id != node)) { - ++position %= (1u << 16u); + ++position %= MaxNumElements; } positions[position].time = current_timestamp; @@ -58,7 +55,7 @@ template class XORFastHashStorage std::uint16_t position = fast_hasher(node); while ((positions[position].time == current_timestamp) && (positions[position].id != node)) { - ++position %= (1u << 16u); + ++position %= MaxNumElements; } BOOST_ASSERT(position < positions.size()); @@ -72,13 +69,13 @@ template class XORFastHashStorage if (std::numeric_limits::max() == current_timestamp) { positions.clear(); - positions.resize(1u << 16u); + positions.resize(MaxNumElements); } } private: std::vector positions; - XORFastHash<> fast_hasher; + XORFastHash fast_hasher; unsigned current_timestamp; }; } From 0fbdd57835c121bfcd67330db1ae82c982ccd644 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 22 Jan 2016 19:36:10 +0100 Subject: [PATCH 112/701] Quickfixes polyline encoder's undefined behavior via left-shifting negative numbers --- src/engine/polyline_compressor.cpp | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/engine/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp index 2af6735a3..61e4f2c8b 100644 --- a/src/engine/polyline_compressor.cpp +++ b/src/engine/polyline_compressor.cpp @@ -1,6 +1,7 @@ #include "engine/polyline_compressor.hpp" #include +#include namespace osrm { @@ -27,13 +28,22 @@ std::string encode(int number_to_encode) std::string encode(std::vector &numbers) { std::string output; - const auto end = numbers.size(); - for (std::size_t i = 0; i < end; ++i) + for (auto &number : numbers) { - numbers[i] <<= 1; - if (numbers[i] < 0) + bool isNegative = number < 0; + + if (isNegative) { - numbers[i] = ~(numbers[i]); + const unsigned binary = std::llabs(number); + const unsigned twos = (~binary) + 1u; + number = twos; + } + + number <<= 1u; + + if (isNegative) + { + number = ~number; } } for (const int number : numbers) From 2211731c80023e436b9d2cf65dafbeaa105716c5 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 26 Jan 2016 10:30:48 +0100 Subject: [PATCH 113/701] Alternative test depends on random order, make less random-ish --- features/testbot/alternative.feature | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/features/testbot/alternative.feature b/features/testbot/alternative.feature index d6ca030c6..cb99b4377 100644 --- a/features/testbot/alternative.feature +++ b/features/testbot/alternative.feature @@ -6,7 +6,7 @@ Feature: Alternative route And the node map | | b | c | d | | | - | a | | | | | z | + | a | | k | | | z | | | g | h | i | j | | And the ways @@ -20,6 +20,8 @@ Feature: Alternative route | hi | | ij | | jz | + | ck | + | kh | Scenario: Enabled alternative Given the query options From 04e26ba6b8789ad16967249f62a18746706d0cb8 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 26 Jan 2016 11:10:40 +0100 Subject: [PATCH 114/701] Adds missing cstdlib header for std::llabs --- src/engine/polyline_compressor.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/engine/polyline_compressor.cpp b/src/engine/polyline_compressor.cpp index 61e4f2c8b..f057c0522 100644 --- a/src/engine/polyline_compressor.cpp +++ b/src/engine/polyline_compressor.cpp @@ -1,6 +1,7 @@ #include "engine/polyline_compressor.hpp" #include +#include #include namespace osrm From 2a882aa58d7c98aba6eff58efba1e15a7ce081ab Mon Sep 17 00:00:00 2001 From: Freenerd Date: Wed, 23 Dec 2015 18:46:03 +0100 Subject: [PATCH 115/701] Tests: Preserve param order on POST --- features/support/http.rb | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/features/support/http.rb b/features/support/http.rb index 0b9fb9af7..1c9538eef 100644 --- a/features/support/http.rb +++ b/features/support/http.rb @@ -1,31 +1,22 @@ require 'net/http' # Converts an array [["param","val1"], ["param","val2"]] into ?param=val1¶m=val2 -def params_to_url params +def params_to_string params kv_pairs = params.map { |kv| kv[0].to_s + "=" + kv[1].to_s } - url = kv_pairs.size > 0 ? ("?" + kv_pairs.join("&")) : "" + url = kv_pairs.size > 0 ? kv_pairs.join("&") : "" return url end -# Converts an array [["param","val1"], ["param","val2"]] into ["param"=>["val1", "val2"]] -def params_to_map params - result = {} - params.each do |pair| - if not result.has_key? pair[0] - result[pair[0]] = [] - end - result[pair[0]] << [pair[1]] - end -end - def send_request base_uri, parameters Timeout.timeout(OSRM_TIMEOUT) do if @http_method.eql? "POST" uri = URI.parse base_uri @query = uri.to_s - response = Net::HTTP.post_form uri, (params_to_map parameters) + req = Net::HTTP::Post.new('localhost:8000') + req.body = params_to_string parameters + response = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end else - uri = URI.parse base_uri+(params_to_url parameters) + uri = URI.parse(base_uri + "?" + params_to_string(parameters)) @query = uri.to_s response = Net::HTTP.get_response uri end From c05d23a586e20707e89159523efee5ba7593fe8a Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 21 Jan 2016 19:57:07 +0100 Subject: [PATCH 116/701] Fix POST request --- features/support/http.rb | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/features/support/http.rb b/features/support/http.rb index 1c9538eef..d2dbf31e1 100644 --- a/features/support/http.rb +++ b/features/support/http.rb @@ -1,6 +1,6 @@ require 'net/http' -# Converts an array [["param","val1"], ["param","val2"]] into ?param=val1¶m=val2 +# Converts an array [["param","val1"], ["param","val2"]] into param=val1¶m=val2 def params_to_string params kv_pairs = params.map { |kv| kv[0].to_s + "=" + kv[1].to_s } url = kv_pairs.size > 0 ? kv_pairs.join("&") : "" @@ -9,15 +9,16 @@ end def send_request base_uri, parameters Timeout.timeout(OSRM_TIMEOUT) do + uri_string = base_uri + "?" + params_to_string(parameters) + uri = URI.parse(uri_string) + @query = uri.to_s if @http_method.eql? "POST" - uri = URI.parse base_uri - @query = uri.to_s - req = Net::HTTP::Post.new('localhost:8000') - req.body = params_to_string parameters - response = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end + Net::HTTP.start(uri.hostname, uri.port) do |http| + req = Net::HTTP::Post.new(uri.path) + req.body = params_to_string parameters + response = http.request(req) + end else - uri = URI.parse(base_uri + "?" + params_to_string(parameters)) - @query = uri.to_s response = Net::HTTP.get_response uri end end From bf455c8d20902b29e0126df62fc126a97ff64c5a Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 26 Jan 2016 17:09:02 +0100 Subject: [PATCH 117/701] Fix empty parameter list --- features/support/http.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/features/support/http.rb b/features/support/http.rb index d2dbf31e1..2f066e689 100644 --- a/features/support/http.rb +++ b/features/support/http.rb @@ -9,7 +9,11 @@ end def send_request base_uri, parameters Timeout.timeout(OSRM_TIMEOUT) do - uri_string = base_uri + "?" + params_to_string(parameters) + uri_string = base_uri + params = params_to_string(parameters) + if not params.eql? "" + uri_string = uri_string + "?" + params + end uri = URI.parse(uri_string) @query = uri.to_s if @http_method.eql? "POST" From 54a917310796adc6e91c5872fe064c5ce03ecfa7 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 12:03:33 +0100 Subject: [PATCH 118/701] Make public RouteParameters header no longer depend on Spirit And includes the optional header that was transitively included by the spirit header before. Hopefully this will speed up compile times, as the RouteParameters header is used in a lot of translation units. --- include/engine/route_parameters.hpp | 3 +-- include/server/api_grammar.hpp | 2 +- src/engine/route_parameters.cpp | 1 - 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/include/engine/route_parameters.hpp b/include/engine/route_parameters.hpp index e808880ec..b77207e32 100644 --- a/include/engine/route_parameters.hpp +++ b/include/engine/route_parameters.hpp @@ -31,7 +31,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "osrm/coordinate.hpp" #include -#include +#include #include #include @@ -78,7 +78,6 @@ struct RouteParameters void AddTimestamp(const unsigned timestamp); void AddBearing(const boost::fusion::vector> &received_bearing, - boost::spirit::qi::unused_type unused, bool &pass); void SetLanguage(const std::string &language); diff --git a/include/server/api_grammar.hpp b/include/server/api_grammar.hpp index afa577e1c..a0bfce60d 100644 --- a/include/server/api_grammar.hpp +++ b/include/server/api_grammar.hpp @@ -64,7 +64,7 @@ template struct APIGrammar : qi::grammar> qi::lit("b") >> '=' >> (qi::int_ >> -(qi::lit(',') >> qi::int_ | - qi::attr(10)))[boost::bind(&HandlerT::AddBearing, handler, ::_1, ::_2, ::_3)]; + qi::attr(10)))[boost::bind(&HandlerT::AddBearing, handler, ::_1, ::_3)]; u = (-qi::lit('&')) >> qi::lit("u") >> '=' >> qi::bool_[boost::bind(&HandlerT::SetUTurn, handler, ::_1)]; uturns = (-qi::lit('&')) >> qi::lit("uturns") >> '=' >> diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index 01df5783d..bc77c17ae 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -100,7 +100,6 @@ void RouteParameters::AddTimestamp(const unsigned timestamp) void RouteParameters::AddBearing( const boost::fusion::vector> &received_bearing, - boost::spirit::qi::unused_type /* unused */, bool &pass) { pass = false; From 0fcca0415092aef85083f431736dbc4ab72f91ca Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 12:52:35 +0100 Subject: [PATCH 119/701] TU-local STXXL comparator for OSMNodeIDs, needs {min,max}_value Can not use std::less<>{} because of this. --- include/extractor/node_id.hpp | 21 --------------------- src/extractor/extraction_containers.cpp | 17 +++++++++++++++-- 2 files changed, 15 insertions(+), 23 deletions(-) delete mode 100644 include/extractor/node_id.hpp diff --git a/include/extractor/node_id.hpp b/include/extractor/node_id.hpp deleted file mode 100644 index faaefb2ef..000000000 --- a/include/extractor/node_id.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef NODE_ID_HPP -#define NODE_ID_HPP - -#include "util/typedefs.hpp" - -namespace osrm -{ -namespace extractor -{ - -struct Cmp -{ - using value_type = OSMNodeID; - bool operator()(const value_type left, const value_type right) const { return left < right; } - value_type max_value() { return MAX_OSM_NODEID; } - value_type min_value() { return MIN_OSM_NODEID; } -}; -} -} - -#endif // NODE_ID_HPP diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 299d35f24..26f8d7eb8 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -2,7 +2,6 @@ #include "extractor/extraction_way.hpp" #include "util/coordinate_calculation.hpp" -#include "extractor/node_id.hpp" #include "util/range_table.hpp" #include "util/osrm_exception.hpp" @@ -24,6 +23,19 @@ #include #include +namespace +{ +// Needed for STXXL comparison - STXXL requires max_value(), min_value(), so we can not use +// std::less{}. Anonymous namespace to keep translation unit local. +struct OSMNodeIDSTXXLLess +{ + using value_type = OSMNodeID; + bool operator()(const value_type left, const value_type right) const { return left < right; } + value_type max_value() { return MAX_OSM_NODEID; } + value_type min_value() { return MIN_OSM_NODEID; } +}; +} + namespace osrm { namespace extractor @@ -136,7 +148,8 @@ void ExtractionContainers::PrepareNodes() { std::cout << "[extractor] Sorting used nodes ... " << std::flush; TIMER_START(sorting_used_nodes); - stxxl::sort(used_node_id_list.begin(), used_node_id_list.end(), Cmp(), stxxl_memory); + stxxl::sort(used_node_id_list.begin(), used_node_id_list.end(), OSMNodeIDSTXXLLess(), + stxxl_memory); TIMER_STOP(sorting_used_nodes); std::cout << "ok, after " << TIMER_SEC(sorting_used_nodes) << "s" << std::endl; From 46fc6f8da49ff25401e750acf5809cc940ca9c94 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 12:58:24 +0100 Subject: [PATCH 120/701] Collapse computeAngle into coordinate calculation --- include/engine/plugins/match.hpp | 8 ++--- include/util/compute_angle.hpp | 37 ---------------------- include/util/coordinate_calculation.hpp | 5 +++ src/extractor/edge_based_graph_factory.cpp | 5 ++- src/util/coordinate_calculation.cpp | 22 +++++++++++++ 5 files changed, 33 insertions(+), 44 deletions(-) delete mode 100644 include/util/compute_angle.hpp diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 713245376..0de44148a 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -10,7 +10,7 @@ #include "engine/guidance/segment_list.hpp" #include "engine/api_response_generator.hpp" #include "engine/routing_algorithms/map_matching.hpp" -#include "util/compute_angle.hpp" +#include "util/coordinate_calculation.hpp" #include "util/integer_range.hpp" #include "util/json_logger.hpp" #include "util/json_util.hpp" @@ -108,9 +108,9 @@ template class MapMatchingPlugin : public BasePlugin if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate) { - double turn_angle = util::ComputeAngle(input_coords[current_coordinate - 1], - input_coords[current_coordinate], - input_coords[current_coordinate + 1]); + double turn_angle = util::coordinate_calculation::computeAngle( + input_coords[current_coordinate - 1], input_coords[current_coordinate], + input_coords[current_coordinate + 1]); // sharp turns indicate a possible uturn if (turn_angle <= 90.0 || turn_angle >= 270.0) diff --git a/include/util/compute_angle.hpp b/include/util/compute_angle.hpp deleted file mode 100644 index b34f7bed9..000000000 --- a/include/util/compute_angle.hpp +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef COMPUTE_ANGLE_HPP -#define COMPUTE_ANGLE_HPP - -#include "osrm/coordinate.hpp" -#include "util/trigonometry_table.hpp" -#include "util/mercator.hpp" - -namespace osrm -{ -namespace util -{ - -// Get angle of line segment (A,C)->(C,B) -inline double ComputeAngle(const FixedPointCoordinate first, - const FixedPointCoordinate second, - const FixedPointCoordinate third) noexcept -{ - const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION; - const double v1y = mercator::latToY(first.lat / COORDINATE_PRECISION) - - mercator::latToY(second.lat / COORDINATE_PRECISION); - const double v2x = (third.lon - second.lon) / COORDINATE_PRECISION; - const double v2y = mercator::latToY(third.lat / COORDINATE_PRECISION) - - mercator::latToY(second.lat / COORDINATE_PRECISION); - - double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / M_PI; - - while (angle < 0.) - { - angle += 360.; - } - - return angle; -} -} -} - -#endif // COMPUTE_ANGLE_HPP diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index 7e15b8ba0..decef8d64 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -57,6 +57,11 @@ double radToDeg(const double radian); double bearing(const FixedPointCoordinate &first_coordinate, const FixedPointCoordinate &second_coordinate); + +// Get angle of line segment (A,C)->(C,B) +double computeAngle(const FixedPointCoordinate &first, + const FixedPointCoordinate &second, + const FixedPointCoordinate &third); } } } diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index a6585b0f9..cc615c905 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -2,7 +2,6 @@ #include "extractor/edge_based_graph_factory.hpp" #include "util/coordinate_calculation.hpp" #include "util/percent.hpp" -#include "util/compute_angle.hpp" #include "util/integer_range.hpp" #include "util/lua_util.hpp" #include "util/simple_logger.hpp" @@ -336,7 +335,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedNodes() } BOOST_ASSERT(m_edge_based_node_list.size() == m_edge_based_node_is_startpoint.size()); - BOOST_ASSERT(m_max_edge_id+1 == m_edge_based_node_weights.size()); + BOOST_ASSERT(m_max_edge_id + 1 == m_edge_based_node_weights.size()); util::SimpleLogger().Write() << "Generated " << m_edge_based_node_list.size() << " nodes in edge-expanded graph"; @@ -498,7 +497,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( ? m_compressed_edge_container.GetFirstEdgeTargetID(e2) : node_w)]; - const double turn_angle = util::ComputeAngle( + const double turn_angle = util::coordinate_calculation::computeAngle( first_coordinate, m_node_info_list[node_v], third_coordinate); const int turn_penalty = GetTurnPenalty(turn_angle, lua_state); diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index 4f1386310..f2d99ed4f 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -2,6 +2,7 @@ #include "util/mercator.hpp" #include "util/string_util.hpp" +#include "util/trigonometry_table.hpp" #include @@ -218,6 +219,27 @@ double bearing(const FixedPointCoordinate &first_coordinate, } return result; } + +double computeAngle(const FixedPointCoordinate &first, + const FixedPointCoordinate &second, + const FixedPointCoordinate &third) +{ + const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION; + const double v1y = mercator::latToY(first.lat / COORDINATE_PRECISION) - + mercator::latToY(second.lat / COORDINATE_PRECISION); + const double v2x = (third.lon - second.lon) / COORDINATE_PRECISION; + const double v2y = mercator::latToY(third.lat / COORDINATE_PRECISION) - + mercator::latToY(second.lat / COORDINATE_PRECISION); + + double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / M_PI; + + while (angle < 0.) + { + angle += 360.; + } + + return angle; +} } } } From d391df52ba6b66f1a03e6005417dc53a8f537b3a Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 13:07:24 +0100 Subject: [PATCH 121/701] Be kind to the optimizer, pass coordinates by value (just two ints) --- include/engine/datafacade/datafacade_base.hpp | 6 +- .../engine/datafacade/internal_datafacade.hpp | 6 +- .../engine/datafacade/shared_datafacade.hpp | 100 ++++++++++-------- include/engine/geospatial_query.hpp | 14 +-- include/engine/guidance/segment_list.hpp | 4 +- include/engine/phantom_node.hpp | 6 +- include/engine/plugins/hello_world.hpp | 2 +- include/engine/plugins/plugin_base.hpp | 2 +- include/extractor/edge_based_node.hpp | 4 +- include/util/coordinate_calculation.hpp | 50 ++++----- include/util/debug_geometry.hpp | 19 ++-- include/util/hilbert_value.hpp | 11 +- include/util/rectangle.hpp | 6 +- include/util/static_rtree.hpp | 12 +-- src/engine/douglas_peucker.cpp | 6 +- src/util/coordinate_calculation.cpp | 48 ++++----- src/util/hilbert_value.cpp | 31 +++--- 17 files changed, 165 insertions(+), 162 deletions(-) diff --git a/include/engine/datafacade/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp index c4c4c87f4..c7006e4d3 100644 --- a/include/engine/datafacade/datafacade_base.hpp +++ b/include/engine/datafacade/datafacade_base.hpp @@ -74,19 +74,19 @@ template class BaseDataFacade virtual extractor::TravelMode GetTravelModeForEdgeID(const unsigned id) const = 0; virtual std::vector - NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) = 0; virtual std::vector - NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) = 0; virtual std::pair NearestPhantomNodeWithAlternativeFromBigComponent( - const util::FixedPointCoordinate &input_coordinate, + const util::FixedPointCoordinate input_coordinate, const int bearing = 0, const int bearing_range = 180) = 0; diff --git a/include/engine/datafacade/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp index bbe18249a..b78e5c040 100644 --- a/include/engine/datafacade/internal_datafacade.hpp +++ b/include/engine/datafacade/internal_datafacade.hpp @@ -343,7 +343,7 @@ template class InternalDataFacade final : public BaseDataFacad } std::vector - NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) override final @@ -359,7 +359,7 @@ template class InternalDataFacade final : public BaseDataFacad } std::vector - NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) override final @@ -375,7 +375,7 @@ template class InternalDataFacade final : public BaseDataFacad } std::pair NearestPhantomNodeWithAlternativeFromBigComponent( - const util::FixedPointCoordinate &input_coordinate, + const util::FixedPointCoordinate input_coordinate, const int bearing = 0, const int bearing_range = 180) override final { diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 7238bec6c..bbb2accb0 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -79,8 +79,8 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadChecksum() { - m_check_sum = - *data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::HSGR_CHECKSUM); + m_check_sum = *data_layout->GetBlockPtr(shared_memory, + storage::SharedDataLayout::HSGR_CHECKSUM); util::SimpleLogger().Write() << "set checksum: " << m_check_sum; } @@ -98,8 +98,8 @@ template class SharedDataFacade final : public BaseDataFacade< { BOOST_ASSERT_MSG(!m_coordinate_list->empty(), "coordinates must be loaded before r-tree"); - RTreeNode *tree_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::R_SEARCH_TREE); + RTreeNode *tree_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::R_SEARCH_TREE); m_static_rtree.reset(new TimeStampedRTreePair( CURRENT_TIMESTAMP, util::make_unique( @@ -111,11 +111,11 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadGraph() { - GraphNode *graph_nodes_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::GRAPH_NODE_LIST); + GraphNode *graph_nodes_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::GRAPH_NODE_LIST); - GraphEdge *graph_edges_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::GRAPH_EDGE_LIST); + GraphEdge *graph_edges_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::GRAPH_EDGE_LIST); typename util::ShM::vector node_list( graph_nodes_ptr, data_layout->num_entries[storage::SharedDataLayout::GRAPH_NODE_LIST]); @@ -128,10 +128,11 @@ template class SharedDataFacade final : public BaseDataFacade< { util::FixedPointCoordinate *coordinate_list_ptr = - data_layout->GetBlockPtr(shared_memory, - storage::SharedDataLayout::COORDINATE_LIST); + data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::COORDINATE_LIST); m_coordinate_list = util::make_unique::vector>( - coordinate_list_ptr, data_layout->num_entries[storage::SharedDataLayout::COORDINATE_LIST]); + coordinate_list_ptr, + data_layout->num_entries[storage::SharedDataLayout::COORDINATE_LIST]); extractor::TravelMode *travel_mode_list_ptr = data_layout->GetBlockPtr(shared_memory, @@ -148,8 +149,8 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->num_entries[storage::SharedDataLayout::TURN_INSTRUCTION]); m_turn_instruction_list.swap(turn_instruction_list); - unsigned *name_id_list_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::NAME_ID_LIST); + unsigned *name_id_list_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::NAME_ID_LIST); typename util::ShM::vector name_id_list( name_id_list_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_ID_LIST]); m_name_ID_list.swap(name_id_list); @@ -157,8 +158,8 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadViaNodeList() { - NodeID *via_node_list_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::VIA_NODE_LIST); + NodeID *via_node_list_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::VIA_NODE_LIST); typename util::ShM::vector via_node_list( via_node_list_ptr, data_layout->num_entries[storage::SharedDataLayout::VIA_NODE_LIST]); m_via_node_list.swap(via_node_list); @@ -166,17 +167,17 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadNames() { - unsigned *offsets_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::NAME_OFFSETS); - NameIndexBlock *blocks_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::NAME_BLOCKS); + unsigned *offsets_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::NAME_OFFSETS); + NameIndexBlock *blocks_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::NAME_BLOCKS); typename util::ShM::vector name_offsets( offsets_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_OFFSETS]); typename util::ShM::vector name_blocks( blocks_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_BLOCKS]); - char *names_list_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::NAME_CHAR_LIST); + char *names_list_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::NAME_CHAR_LIST); typename util::ShM::vector names_char_list( names_list_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_CHAR_LIST]); m_name_table = util::make_unique>( @@ -192,8 +193,8 @@ template class SharedDataFacade final : public BaseDataFacade< return; } - unsigned *core_marker_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::CORE_MARKER); + unsigned *core_marker_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::CORE_MARKER); typename util::ShM::vector is_core_node( core_marker_ptr, data_layout->num_entries[storage::SharedDataLayout::CORE_MARKER]); m_is_core_node.swap(is_core_node); @@ -208,16 +209,18 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDICATORS]); m_edge_is_compressed.swap(edge_is_compressed); - unsigned *geometries_index_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::GEOMETRIES_INDEX); + unsigned *geometries_index_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::GEOMETRIES_INDEX); typename util::ShM::vector geometry_begin_indices( - geometries_index_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDEX]); + geometries_index_ptr, + data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDEX]); m_geometry_indices.swap(geometry_begin_indices); - unsigned *geometries_list_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::GEOMETRIES_LIST); + unsigned *geometries_list_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::GEOMETRIES_LIST); typename util::ShM::vector geometry_list( - geometries_list_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_LIST]); + geometries_list_ptr, + data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_LIST]); m_geometry_list.swap(geometry_list); } @@ -230,12 +233,12 @@ template class SharedDataFacade final : public BaseDataFacade< { if (!storage::SharedMemory::RegionExists(storage::CURRENT_REGIONS)) { - throw util::exception("No shared memory blocks found, have you forgotten to run osrm-datastore?"); + throw util::exception( + "No shared memory blocks found, have you forgotten to run osrm-datastore?"); } data_timestamp_ptr = static_cast( storage::makeSharedMemory(storage::CURRENT_REGIONS, - sizeof(storage::SharedDataTimestamp), false, false) - ->Ptr()); + sizeof(storage::SharedDataTimestamp), false, false)->Ptr()); CURRENT_LAYOUT = storage::LAYOUT_NONE; CURRENT_DATA = storage::DATA_NONE; CURRENT_TIMESTAMP = 0; @@ -263,14 +266,15 @@ template class SharedDataFacade final : public BaseDataFacade< CURRENT_LAYOUT = data_timestamp_ptr->layout; CURRENT_DATA = data_timestamp_ptr->data; - CURRENT_TIMESTAMP = 0; // Force trigger a reload + CURRENT_TIMESTAMP = 0; // Force trigger a reload - util::SimpleLogger().Write(logDEBUG) << "Current layout was different to new layout, swapping"; + util::SimpleLogger().Write(logDEBUG) + << "Current layout was different to new layout, swapping"; } else { - util::SimpleLogger().Write(logDEBUG) << "Current layout was same to new layout, not swapping"; - + util::SimpleLogger().Write(logDEBUG) + << "Current layout was same to new layout, not swapping"; } if (CURRENT_TIMESTAMP != data_timestamp_ptr->timestamp) @@ -280,19 +284,20 @@ template class SharedDataFacade final : public BaseDataFacade< util::SimpleLogger().Write(logDEBUG) << "Performing data reload"; m_layout_memory.reset(storage::makeSharedMemory(CURRENT_LAYOUT)); - data_layout = (storage::SharedDataLayout *) (m_layout_memory->Ptr()); + data_layout = (storage::SharedDataLayout *)(m_layout_memory->Ptr()); m_large_memory.reset(storage::makeSharedMemory(CURRENT_DATA)); - shared_memory = (char *) (m_large_memory->Ptr()); + shared_memory = (char *)(m_large_memory->Ptr()); - const char *file_index_ptr = - data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::FILE_INDEX_PATH); + const char *file_index_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::FILE_INDEX_PATH); file_index_path = boost::filesystem::path(file_index_ptr); - if (!boost::filesystem::exists(file_index_path)) { + if (!boost::filesystem::exists(file_index_path)) + { util::SimpleLogger().Write(logDEBUG) << "Leaf file name " - << file_index_path.string(); + << file_index_path.string(); throw util::exception("Could not load leaf index file. " - "Is any data loaded into shared memory?"); + "Is any data loaded into shared memory?"); } LoadGraph(); @@ -304,7 +309,8 @@ template class SharedDataFacade final : public BaseDataFacade< LoadNames(); LoadCoreInformation(); - util::SimpleLogger().Write() << "number of geometries: " << m_coordinate_list->size(); + util::SimpleLogger().Write() + << "number of geometries: " << m_coordinate_list->size(); for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { if (!GetCoordinateOfNode(i).IsValid()) @@ -398,7 +404,7 @@ template class SharedDataFacade final : public BaseDataFacade< } std::vector - NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate input_coordinate, const float max_distance, const int bearing = 0, const int bearing_range = 180) override final @@ -414,7 +420,7 @@ template class SharedDataFacade final : public BaseDataFacade< } std::vector - NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) override final @@ -430,7 +436,7 @@ template class SharedDataFacade final : public BaseDataFacade< } std::pair NearestPhantomNodeWithAlternativeFromBigComponent( - const util::FixedPointCoordinate &input_coordinate, + const util::FixedPointCoordinate input_coordinate, const int bearing = 0, const int bearing_range = 180) override final { diff --git a/include/engine/geospatial_query.hpp b/include/engine/geospatial_query.hpp index 11b0db648..1aad5388b 100644 --- a/include/engine/geospatial_query.hpp +++ b/include/engine/geospatial_query.hpp @@ -35,7 +35,7 @@ template class GeospatialQuery // Returns nearest PhantomNodes in the given bearing range within max_distance. // Does not filter by small/big component! std::vector - NearestPhantomNodesInRange(const util::FixedPointCoordinate &input_coordinate, + NearestPhantomNodesInRange(const util::FixedPointCoordinate input_coordinate, const double max_distance, const int bearing = 0, const int bearing_range = 180) @@ -57,7 +57,7 @@ template class GeospatialQuery // Returns max_results nearest PhantomNodes in the given bearing range. // Does not filter by small/big component! std::vector - NearestPhantomNodes(const util::FixedPointCoordinate &input_coordinate, + NearestPhantomNodes(const util::FixedPointCoordinate input_coordinate, const unsigned max_results, const int bearing = 0, const int bearing_range = 180) @@ -78,7 +78,7 @@ template class GeospatialQuery // Returns the nearest phantom node. If this phantom node is not from a big component // a second phantom node is return that is the nearest coordinate in a big component. std::pair NearestPhantomNodeWithAlternativeFromBigComponent( - const util::FixedPointCoordinate &input_coordinate, + const util::FixedPointCoordinate input_coordinate, const int bearing = 0, const int bearing_range = 180) { @@ -86,8 +86,8 @@ template class GeospatialQuery bool has_big_component = false; auto results = rtree.Nearest( input_coordinate, - [this, bearing, bearing_range, &has_big_component, - &has_small_component](const EdgeData &data) + [this, bearing, bearing_range, &has_big_component, &has_small_component]( + const EdgeData &data) { auto use_segment = (!has_small_component || (!has_big_component && !data.component.is_tiny)); @@ -122,7 +122,7 @@ template class GeospatialQuery private: std::vector - MakePhantomNodes(const util::FixedPointCoordinate &input_coordinate, + MakePhantomNodes(const util::FixedPointCoordinate input_coordinate, const std::vector &results) const { std::vector distance_and_phantoms(results.size()); @@ -134,7 +134,7 @@ template class GeospatialQuery return distance_and_phantoms; } - PhantomNodeWithDistance MakePhantomNode(const util::FixedPointCoordinate &input_coordinate, + PhantomNodeWithDistance MakePhantomNode(const util::FixedPointCoordinate input_coordinate, const EdgeData &data) const { util::FixedPointCoordinate point_on_segment; diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index 07c932de1..011b31d8a 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -51,7 +51,7 @@ template class SegmentList const bool is_via_leg, const DataFacade *facade); - void AppendSegment(const FixedPointCoordinate &coordinate, const PathData &path_point); + void AppendSegment(const FixedPointCoordinate coordinate, const PathData &path_point); void Finalize(const bool extract_alternative, const InternalRouteResult &raw_route, const unsigned zoom_level, @@ -192,7 +192,7 @@ std::vector const &SegmentList::Get() const } template -void SegmentList::AppendSegment(const FixedPointCoordinate &coordinate, +void SegmentList::AppendSegment(const FixedPointCoordinate coordinate, const PathData &path_point) { // if the start location is on top of a node, the first movement might be zero-length, diff --git a/include/engine/phantom_node.hpp b/include/engine/phantom_node.hpp index ca9b685c2..3cb43c019 100644 --- a/include/engine/phantom_node.hpp +++ b/include/engine/phantom_node.hpp @@ -27,7 +27,7 @@ struct PhantomNode unsigned packed_geometry_id, bool is_tiny_component, unsigned component_id, - util::FixedPointCoordinate &location, + util::FixedPointCoordinate location, unsigned short fwd_segment_position, extractor::TravelMode forward_travel_mode, extractor::TravelMode backward_travel_mode) @@ -35,7 +35,7 @@ struct PhantomNode forward_weight(forward_weight), reverse_weight(reverse_weight), forward_offset(forward_offset), reverse_offset(reverse_offset), packed_geometry_id(packed_geometry_id), component{component_id, is_tiny_component}, - location(location), fwd_segment_position(fwd_segment_position), + location(std::move(location)), fwd_segment_position(fwd_segment_position), forward_travel_mode(forward_travel_mode), backward_travel_mode(backward_travel_mode) { } @@ -89,7 +89,7 @@ struct PhantomNode bool operator==(const PhantomNode &other) const { return location == other.location; } template - PhantomNode(const OtherT &other, const util::FixedPointCoordinate &foot_point) + PhantomNode(const OtherT &other, const util::FixedPointCoordinate foot_point) { forward_node_id = other.forward_edge_based_node_id; reverse_node_id = other.reverse_edge_based_node_id; diff --git a/include/engine/plugins/hello_world.hpp b/include/engine/plugins/hello_world.hpp index 1b79ca3e2..312b6e5d6 100644 --- a/include/engine/plugins/hello_world.hpp +++ b/include/engine/plugins/hello_world.hpp @@ -50,7 +50,7 @@ class HelloWorldPlugin final : public BasePlugin util::json::Array json_locations; unsigned counter = 0; - for (const util::FixedPointCoordinate &coordinate : routeParameters.coordinates) + for (const auto coordinate : routeParameters.coordinates) { util::json::Object json_location; util::json::Array json_coordinates; diff --git a/include/engine/plugins/plugin_base.hpp b/include/engine/plugins/plugin_base.hpp index 3f3e62719..0eb36e948 100644 --- a/include/engine/plugins/plugin_base.hpp +++ b/include/engine/plugins/plugin_base.hpp @@ -38,7 +38,7 @@ class BasePlugin const unsigned min = 2) const final { if (min > coordinates.size() || std::any_of(std::begin(coordinates), std::end(coordinates), - [](const util::FixedPointCoordinate &coordinate) + [](const util::FixedPointCoordinate coordinate) { return !coordinate.IsValid(); })) diff --git a/include/extractor/edge_based_node.hpp b/include/extractor/edge_based_node.hpp index c41c3b8e3..4c821d275 100644 --- a/include/extractor/edge_based_node.hpp +++ b/include/extractor/edge_based_node.hpp @@ -58,8 +58,8 @@ struct EdgeBasedNode (reverse_edge_based_node_id != SPECIAL_NODEID)); } - static inline util::FixedPointCoordinate Centroid(const util::FixedPointCoordinate &a, - const util::FixedPointCoordinate &b) + static inline util::FixedPointCoordinate Centroid(const util::FixedPointCoordinate a, + const util::FixedPointCoordinate b) { util::FixedPointCoordinate centroid; // The coordinates of the midpoint are given by: diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index decef8d64..ea80f8d6b 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -1,6 +1,8 @@ #ifndef COORDINATE_CALCULATION #define COORDINATE_CALCULATION +#include "osrm/coordinate.hpp" + #include #include @@ -14,54 +16,52 @@ const constexpr long double RAD = 0.017453292519943295769236907684886; // The IUGG value for the equatorial radius is 6378.137 km (3963.19 miles) const constexpr long double EARTH_RADIUS = 6372797.560856; -struct FixedPointCoordinate; - namespace coordinate_calculation { double haversineDistance(const int lat1, const int lon1, const int lat2, const int lon2); -double haversineDistance(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate); +double haversineDistance(const FixedPointCoordinate first_coordinate, + const FixedPointCoordinate second_coordinate); -double greatCircleDistance(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate); +double greatCircleDistance(const FixedPointCoordinate first_coordinate, + const FixedPointCoordinate second_coordinate); double greatCircleDistance(const int lat1, const int lon1, const int lat2, const int lon2); -double perpendicularDistance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location); +double perpendicularDistance(const FixedPointCoordinate segment_source, + const FixedPointCoordinate segment_target, + const FixedPointCoordinate query_location); -double perpendicularDistance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, +double perpendicularDistance(const FixedPointCoordinate segment_source, + const FixedPointCoordinate segment_target, + const FixedPointCoordinate query_location, FixedPointCoordinate &nearest_location, double &ratio); double -perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate); +perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate segment_source, + const FixedPointCoordinate segment_target, + const FixedPointCoordinate query_location, + const std::pair projected_coordinate); double -perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate, +perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate segment_source, + const FixedPointCoordinate segment_target, + const FixedPointCoordinate query_location, + const std::pair projected_coordinate, FixedPointCoordinate &nearest_location, double &ratio); double degToRad(const double degree); double radToDeg(const double radian); -double bearing(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate); +double bearing(const FixedPointCoordinate first_coordinate, + const FixedPointCoordinate second_coordinate); // Get angle of line segment (A,C)->(C,B) -double computeAngle(const FixedPointCoordinate &first, - const FixedPointCoordinate &second, - const FixedPointCoordinate &third); +double computeAngle(const FixedPointCoordinate first, + const FixedPointCoordinate second, + const FixedPointCoordinate third); } } } diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index 73e829175..be9da638d 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -3,6 +3,7 @@ #include "contractor/contractor_config.hpp" #include "extractor/query_node.hpp" +#include "osrm/coordinate.hpp" #ifndef DEBUG_GEOMETRY @@ -23,7 +24,7 @@ inline void DEBUG_GEOMETRY_STOP() {} inline void DEBUG_TURNS_START(const std::string & /* debug_turns_filename */) {} inline void DEBUG_TURN(const NodeID /* node */, const std::vector & /* m_node_info_list */, - const FixedPointCoordinate & /* first_coordinate */, + const FixedPointCoordinate /* first_coordinate */, const int /* turn_angle */, const int /* turn_penalty */) { @@ -95,11 +96,9 @@ inline void DEBUG_GEOMETRY_EDGE(int new_segment_weight, if (!dg_first_debug_geometry) debug_geometry_file << "," << std::endl; debug_geometry_file << "{ \"type\":\"Feature\",\"properties\":{\"original\":false, " - "\"weight\":" - << new_segment_weight / 10.0 << ",\"speed\":" - << static_cast( - std::floor((segment_length / new_segment_weight) * 10. * 3.6)) - << ","; + "\"weight\":" << new_segment_weight / 10.0 << ",\"speed\":" + << static_cast(std::floor((segment_length / new_segment_weight) * + 10. * 3.6)) << ","; debug_geometry_file << "\"from_node\": " << previous_osm_node_id << ", \"to_node\": " << this_osm_node_id << ","; debug_geometry_file << "\"timestamp\": \"" << dg_time_buffer << "\"},"; @@ -114,7 +113,8 @@ inline void DEBUG_GEOMETRY_STOP() { if (dg_output_debug_geometry) { - debug_geometry_file << std::endl << "]}" << std::endl; + debug_geometry_file << std::endl + << "]}" << std::endl; debug_geometry_file.close(); } } @@ -169,7 +169,7 @@ inline void DEBUG_UTURN(const NodeID node, inline void DEBUG_TURN(const NodeID node, const std::vector &m_node_info_list, - const FixedPointCoordinate &first_coordinate, + const FixedPointCoordinate first_coordinate, const int turn_angle, const int turn_penalty) { @@ -201,7 +201,8 @@ inline void DEBUG_TURNS_STOP() { if (dg_output_turn_debug) { - dg_debug_turns_file << std::endl << "]}" << std::endl; + dg_debug_turns_file << std::endl + << "]}" << std::endl; dg_debug_turns_file.close(); } } diff --git a/include/util/hilbert_value.hpp b/include/util/hilbert_value.hpp index 641782e85..858260278 100644 --- a/include/util/hilbert_value.hpp +++ b/include/util/hilbert_value.hpp @@ -1,6 +1,8 @@ #ifndef HILBERT_VALUE_HPP #define HILBERT_VALUE_HPP +#include "osrm/coordinate.hpp" + #include namespace osrm @@ -9,19 +11,16 @@ namespace util { // computes a 64 bit value that corresponds to the hilbert space filling curve - -struct FixedPointCoordinate; - class HilbertCode { public: - uint64_t operator()(const FixedPointCoordinate ¤t_coordinate) const; + std::uint64_t operator()(const FixedPointCoordinate current_coordinate) const; HilbertCode() {} HilbertCode(const HilbertCode &) = delete; private: - inline uint64_t BitInterleaving(const uint32_t a, const uint32_t b) const; - inline void TransposeCoordinate(uint32_t *X) const; + inline std::uint64_t BitInterleaving(const std::uint32_t a, const std::uint32_t b) const; + inline void TransposeCoordinate(std::uint32_t *x) const; }; } } diff --git a/include/util/rectangle.hpp b/include/util/rectangle.hpp index 947f438f0..80aa98cfd 100644 --- a/include/util/rectangle.hpp +++ b/include/util/rectangle.hpp @@ -62,7 +62,7 @@ struct RectangleInt2D Contains(lower_left)); } - double GetMinDist(const FixedPointCoordinate &location) const + double GetMinDist(const FixedPointCoordinate location) const { const bool is_contained = Contains(location); if (is_contained) @@ -139,7 +139,7 @@ struct RectangleInt2D return min_dist; } - double GetMinMaxDist(const FixedPointCoordinate &location) const + double GetMinMaxDist(const FixedPointCoordinate location) const { double min_max_dist = std::numeric_limits::max(); // Get minmax distance to each of the four sides @@ -170,7 +170,7 @@ struct RectangleInt2D return min_max_dist; } - bool Contains(const FixedPointCoordinate &location) const + bool Contains(const FixedPointCoordinate location) const { const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat); const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon); diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 3aea17943..616300c12 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -124,8 +124,8 @@ class StaticRTree // generate auxiliary vector of hilbert-values tbb::parallel_for( tbb::blocked_range(0, m_element_count), - [&input_data_vector, &input_wrapper_vector, &get_hilbert_number, - &coordinate_list](const tbb::blocked_range &range) + [&input_data_vector, &input_wrapper_vector, &get_hilbert_number, &coordinate_list]( + const tbb::blocked_range &range) { for (uint64_t element_counter = range.begin(), end = range.end(); element_counter != end; ++element_counter) @@ -322,7 +322,7 @@ class StaticRTree } // Override filter and terminator for the desired behaviour. - std::vector Nearest(const FixedPointCoordinate &input_coordinate, + std::vector Nearest(const FixedPointCoordinate input_coordinate, const std::size_t max_results) { return Nearest(input_coordinate, @@ -338,7 +338,7 @@ class StaticRTree // Override filter and terminator for the desired behaviour. template - std::vector Nearest(const FixedPointCoordinate &input_coordinate, + std::vector Nearest(const FixedPointCoordinate input_coordinate, const FilterT filter, const TerminationT terminate) { @@ -407,7 +407,7 @@ class StaticRTree private: template void ExploreLeafNode(const std::uint32_t leaf_id, - const FixedPointCoordinate &input_coordinate, + const FixedPointCoordinate input_coordinate, const std::pair &projected_coordinate, QueueT &traversal_queue) { @@ -432,7 +432,7 @@ class StaticRTree template void ExploreTreeNode(const TreeNode &parent, - const FixedPointCoordinate &input_coordinate, + const FixedPointCoordinate input_coordinate, QueueT &traversal_queue) { for (uint32_t i = 0; i < parent.child_count; ++i) diff --git a/src/engine/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp index 67760bc1c..be3572306 100644 --- a/src/engine/douglas_peucker.cpp +++ b/src/engine/douglas_peucker.cpp @@ -20,8 +20,8 @@ namespace struct CoordinatePairCalculator { CoordinatePairCalculator() = delete; - CoordinatePairCalculator(const util::FixedPointCoordinate &coordinate_a, - const util::FixedPointCoordinate &coordinate_b) + CoordinatePairCalculator(const util::FixedPointCoordinate coordinate_a, + const util::FixedPointCoordinate coordinate_b) { // initialize distance calculator with two fixed coordinates a, b first_lat = (coordinate_a.lat / COORDINATE_PRECISION) * util::RAD; @@ -30,7 +30,7 @@ struct CoordinatePairCalculator second_lon = (coordinate_b.lon / COORDINATE_PRECISION) * util::RAD; } - int operator()(util::FixedPointCoordinate &other) const + int operator()(const util::FixedPointCoordinate other) const { // set third coordinate c const float float_lat1 = (other.lat / COORDINATE_PRECISION) * util::RAD; diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index f2d99ed4f..e0dfe006a 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -6,8 +6,6 @@ #include -#include "osrm/coordinate.hpp" - #include #include @@ -44,15 +42,15 @@ double haversineDistance(const int lat1, const int lon1, const int lat2, const i return EARTH_RADIUS * charv; } -double haversineDistance(const FixedPointCoordinate &coordinate_1, - const FixedPointCoordinate &coordinate_2) +double haversineDistance(const FixedPointCoordinate coordinate_1, + const FixedPointCoordinate coordinate_2) { return haversineDistance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, coordinate_2.lon); } -double greatCircleDistance(const FixedPointCoordinate &coordinate_1, - const FixedPointCoordinate &coordinate_2) +double greatCircleDistance(const FixedPointCoordinate coordinate_1, + const FixedPointCoordinate coordinate_2) { return greatCircleDistance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, coordinate_2.lon); @@ -75,9 +73,9 @@ double greatCircleDistance(const int lat1, const int lon1, const int lat2, const return std::hypot(x_value, y_value) * EARTH_RADIUS; } -double perpendicularDistance(const FixedPointCoordinate &source_coordinate, - const FixedPointCoordinate &target_coordinate, - const FixedPointCoordinate &query_location) +double perpendicularDistance(const FixedPointCoordinate source_coordinate, + const FixedPointCoordinate target_coordinate, + const FixedPointCoordinate query_location) { double ratio; FixedPointCoordinate nearest_location; @@ -86,9 +84,9 @@ double perpendicularDistance(const FixedPointCoordinate &source_coordinate, nearest_location, ratio); } -double perpendicularDistance(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, +double perpendicularDistance(const FixedPointCoordinate segment_source, + const FixedPointCoordinate segment_target, + const FixedPointCoordinate query_location, FixedPointCoordinate &nearest_location, double &ratio) { @@ -100,10 +98,10 @@ double perpendicularDistance(const FixedPointCoordinate &segment_source, } double -perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &source_coordinate, - const FixedPointCoordinate &target_coordinate, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate) +perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate source_coordinate, + const FixedPointCoordinate target_coordinate, + const FixedPointCoordinate query_location, + const std::pair projected_coordinate) { double ratio; FixedPointCoordinate nearest_location; @@ -114,10 +112,10 @@ perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &source_ } double -perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate &segment_source, - const FixedPointCoordinate &segment_target, - const FixedPointCoordinate &query_location, - const std::pair &projected_coordinate, +perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate segment_source, + const FixedPointCoordinate segment_target, + const FixedPointCoordinate query_location, + const std::pair projected_coordinate, FixedPointCoordinate &nearest_location, double &ratio) { @@ -196,8 +194,8 @@ double degToRad(const double degree) { return degree * (static_cast(M_PI double radToDeg(const double radian) { return radian * (180.0 * static_cast(M_1_PI)); } -double bearing(const FixedPointCoordinate &first_coordinate, - const FixedPointCoordinate &second_coordinate) +double bearing(const FixedPointCoordinate first_coordinate, + const FixedPointCoordinate second_coordinate) { const double lon_diff = second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION; @@ -220,9 +218,9 @@ double bearing(const FixedPointCoordinate &first_coordinate, return result; } -double computeAngle(const FixedPointCoordinate &first, - const FixedPointCoordinate &second, - const FixedPointCoordinate &third) +double computeAngle(const FixedPointCoordinate first, + const FixedPointCoordinate second, + const FixedPointCoordinate third) { const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION; const double v1y = mercator::latToY(first.lat / COORDINATE_PRECISION) - diff --git a/src/util/hilbert_value.cpp b/src/util/hilbert_value.cpp index 5ddfce0b4..a7d23eef0 100644 --- a/src/util/hilbert_value.cpp +++ b/src/util/hilbert_value.cpp @@ -1,13 +1,11 @@ #include "util/hilbert_value.hpp" -#include "osrm/coordinate.hpp" - namespace osrm { namespace util { -uint64_t HilbertCode::operator()(const FixedPointCoordinate ¤t_coordinate) const +std::uint64_t HilbertCode::operator()(const FixedPointCoordinate current_coordinate) const { unsigned location[2]; location[0] = current_coordinate.lat + static_cast(90 * COORDINATE_PRECISION); @@ -17,10 +15,11 @@ uint64_t HilbertCode::operator()(const FixedPointCoordinate ¤t_coordinate) return BitInterleaving(location[0], location[1]); } -uint64_t HilbertCode::BitInterleaving(const uint32_t latitude, const uint32_t longitude) const +std::uint64_t HilbertCode::BitInterleaving(const std::uint32_t latitude, + const std::uint32_t longitude) const { - uint64_t result = 0; - for (int8_t index = 31; index >= 0; --index) + std::uint64_t result = 0; + for (std::int8_t index = 31; index >= 0; --index) { result |= (latitude >> index) & 1; result <<= 1; @@ -33,9 +32,9 @@ uint64_t HilbertCode::BitInterleaving(const uint32_t latitude, const uint32_t lo return result; } -void HilbertCode::TransposeCoordinate(uint32_t *X) const +void HilbertCode::TransposeCoordinate(std::uint32_t *x) const { - uint32_t M = 1u << (32 - 1), P, Q, t; + std::uint32_t M = 1u << (32 - 1), P, Q, t; int i; // Inverse undo for (Q = M; Q > 1; Q >>= 1) @@ -44,28 +43,28 @@ void HilbertCode::TransposeCoordinate(uint32_t *X) const for (i = 0; i < 2; ++i) { - const bool condition = (X[i] & Q); + const bool condition = (x[i] & Q); if (condition) { - X[0] ^= P; // invert + x[0] ^= P; // invert } else { - t = (X[0] ^ X[i]) & P; - X[0] ^= t; - X[i] ^= t; + t = (x[0] ^ x[i]) & P; + x[0] ^= t; + x[i] ^= t; } } // exchange } // Gray encode for (i = 1; i < 2; ++i) { - X[i] ^= X[i - 1]; + x[i] ^= x[i - 1]; } t = 0; for (Q = M; Q > 1; Q >>= 1) { - const bool condition = (X[2 - 1] & Q); + const bool condition = (x[2 - 1] & Q); if (condition) { t ^= Q - 1; @@ -73,7 +72,7 @@ void HilbertCode::TransposeCoordinate(uint32_t *X) const } // check if this for loop is wrong for (i = 0; i < 2; ++i) { - X[i] ^= t; + x[i] ^= t; } } } From 7a115e93c013f18370e53bff8349a66df8845720 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 21 Jan 2016 14:36:23 +0100 Subject: [PATCH 122/701] Removes check-hsgr --- CMakeLists.txt | 3 -- src/tools/check-hsgr.cpp | 93 ---------------------------------------- 2 files changed, 96 deletions(-) delete mode 100644 src/tools/check-hsgr.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a2fca602..7f238c834 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -357,14 +357,11 @@ if(BUILD_TOOLS) if(UNIX AND NOT APPLE) target_link_libraries(osrm-unlock-all rt) endif() - add_executable(osrm-check-hsgr src/tools/check-hsgr.cpp $) - target_link_libraries(osrm-check-hsgr ${Boost_LIBRARIES} ${TBB_LIBRARIES}) add_executable(osrm-springclean src/tools/springclean.cpp $) target_link_libraries(osrm-springclean ${Boost_LIBRARIES}) install(TARGETS osrm-io-benchmark DESTINATION bin) install(TARGETS osrm-unlock-all DESTINATION bin) - install(TARGETS osrm-check-hsgr DESTINATION bin) install(TARGETS osrm-springclean DESTINATION bin) endif() diff --git a/src/tools/check-hsgr.cpp b/src/tools/check-hsgr.cpp deleted file mode 100644 index 54822b1df..000000000 --- a/src/tools/check-hsgr.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include "util/percent.hpp" -#include "contractor/query_edge.hpp" -#include "util/static_graph.hpp" -#include "util/integer_range.hpp" -#include "util/graph_loader.hpp" -#include "util/simple_logger.hpp" -#include "util/osrm_exception.hpp" - -#include -#include - -#include -#include -#include - -namespace osrm -{ -namespace tools -{ - -using EdgeData = contractor::QueryEdge::EdgeData; -using QueryGraph = util::StaticGraph; -} -} - -int main(int argc, char *argv[]) try -{ - osrm::util::LogPolicy::GetInstance().Unmute(); - if (argc != 2) - { - osrm::util::SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " "; - return EXIT_FAILURE; - } - - boost::filesystem::path hsgr_path(argv[1]); - - std::vector node_list; - std::vector edge_list; - osrm::util::SimpleLogger().Write() << "loading graph from " << hsgr_path.string(); - - unsigned m_check_sum = 0; - unsigned m_number_of_nodes = - readHSGRFromStream(hsgr_path, node_list, edge_list, &m_check_sum); - osrm::util::SimpleLogger().Write() << "expecting " << m_number_of_nodes - << " nodes, checksum: " << m_check_sum; - BOOST_ASSERT_MSG(0 != node_list.size(), "node list empty"); - osrm::util::SimpleLogger().Write() << "loaded " << node_list.size() << " nodes and " - << edge_list.size() << " edges"; - auto m_query_graph = std::make_shared(node_list, edge_list); - - BOOST_ASSERT_MSG(0 == node_list.size(), "node list not flushed"); - BOOST_ASSERT_MSG(0 == edge_list.size(), "edge list not flushed"); - - osrm::util::Percent progress(m_query_graph->GetNumberOfNodes()); - for (const auto node_u : osrm::util::irange(0u, m_query_graph->GetNumberOfNodes())) - { - for (const auto eid : m_query_graph->GetAdjacentEdgeRange(node_u)) - { - const osrm::tools::EdgeData &data = m_query_graph->GetEdgeData(eid); - if (!data.shortcut) - { - continue; - } - const unsigned node_v = m_query_graph->GetTarget(eid); - const EdgeID edge_id_1 = m_query_graph->FindEdgeInEitherDirection(node_u, data.id); - if (SPECIAL_EDGEID == edge_id_1) - { - throw osrm::util::exception( - "cannot find first segment of edge (" + std::to_string(node_u) + "," + - std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + - std::to_string(eid)); - } - const EdgeID edge_id_2 = m_query_graph->FindEdgeInEitherDirection(data.id, node_v); - if (SPECIAL_EDGEID == edge_id_2) - { - throw osrm::util::exception( - "cannot find second segment of edge (" + std::to_string(node_u) + "," + - std::to_string(data.id) + "," + std::to_string(node_v) + "), eid: " + - std::to_string(eid)); - } - } - progress.printStatus(node_u); - } - m_query_graph.reset(); - osrm::util::SimpleLogger().Write() << "Data file " << argv[0] << " appears to be OK"; - - return EXIT_SUCCESS; -} -catch (const std::exception &e) -{ - osrm::util::SimpleLogger().Write(logWARNING) << "[exception] " << e.what(); - return EXIT_FAILURE; -} From 38e8a90f4e38532a23b4ced5da568460844af083 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 25 Jan 2016 15:32:41 +0100 Subject: [PATCH 123/701] Make HilbertCode a free standing function --- include/util/hilbert_value.hpp | 14 ++------------ include/util/static_rtree.hpp | 6 ++---- src/util/hilbert_value.cpp | 25 ++++++++++++++----------- 3 files changed, 18 insertions(+), 27 deletions(-) diff --git a/include/util/hilbert_value.hpp b/include/util/hilbert_value.hpp index 858260278..fb9274458 100644 --- a/include/util/hilbert_value.hpp +++ b/include/util/hilbert_value.hpp @@ -10,18 +10,8 @@ namespace osrm namespace util { -// computes a 64 bit value that corresponds to the hilbert space filling curve -class HilbertCode -{ - public: - std::uint64_t operator()(const FixedPointCoordinate current_coordinate) const; - HilbertCode() {} - HilbertCode(const HilbertCode &) = delete; - - private: - inline std::uint64_t BitInterleaving(const std::uint32_t a, const std::uint32_t b) const; - inline void TransposeCoordinate(std::uint32_t *x) const; -}; +// Computes a 64 bit value that corresponds to the hilbert space filling curve +std::uint64_t hilbertCode(const FixedPointCoordinate coordinate); } } diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 616300c12..32bc71eee 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -119,12 +119,10 @@ class StaticRTree { std::vector input_wrapper_vector(m_element_count); - HilbertCode get_hilbert_number; - // generate auxiliary vector of hilbert-values tbb::parallel_for( tbb::blocked_range(0, m_element_count), - [&input_data_vector, &input_wrapper_vector, &get_hilbert_number, &coordinate_list]( + [&input_data_vector, &input_wrapper_vector, &coordinate_list]( const tbb::blocked_range &range) { for (uint64_t element_counter = range.begin(), end = range.end(); @@ -145,7 +143,7 @@ class StaticRTree COORDINATE_PRECISION * mercator::latToY(current_centroid.lat / COORDINATE_PRECISION); - current_wrapper.m_hilbert_value = get_hilbert_number(current_centroid); + current_wrapper.m_hilbert_value = hilbertCode(current_centroid); } }); diff --git a/src/util/hilbert_value.cpp b/src/util/hilbert_value.cpp index a7d23eef0..15f0c08c0 100644 --- a/src/util/hilbert_value.cpp +++ b/src/util/hilbert_value.cpp @@ -5,18 +5,10 @@ namespace osrm namespace util { -std::uint64_t HilbertCode::operator()(const FixedPointCoordinate current_coordinate) const +namespace { - unsigned location[2]; - location[0] = current_coordinate.lat + static_cast(90 * COORDINATE_PRECISION); - location[1] = current_coordinate.lon + static_cast(180 * COORDINATE_PRECISION); - TransposeCoordinate(location); - return BitInterleaving(location[0], location[1]); -} - -std::uint64_t HilbertCode::BitInterleaving(const std::uint32_t latitude, - const std::uint32_t longitude) const +std::uint64_t bitInterleaving(const std::uint32_t latitude, const std::uint32_t longitude) { std::uint64_t result = 0; for (std::int8_t index = 31; index >= 0; --index) @@ -32,7 +24,7 @@ std::uint64_t HilbertCode::BitInterleaving(const std::uint32_t latitude, return result; } -void HilbertCode::TransposeCoordinate(std::uint32_t *x) const +void transposeCoordinate(std::uint32_t *x) { std::uint32_t M = 1u << (32 - 1), P, Q, t; int i; @@ -75,5 +67,16 @@ void HilbertCode::TransposeCoordinate(std::uint32_t *x) const x[i] ^= t; } } +} // anonymous ns + +std::uint64_t hilbertCode(const FixedPointCoordinate coordinate) +{ + unsigned location[2]; + location[0] = coordinate.lat + static_cast(90 * COORDINATE_PRECISION); + location[1] = coordinate.lon + static_cast(180 * COORDINATE_PRECISION); + + transposeCoordinate(location); + return bitInterleaving(location[0], location[1]); +} } } From 46185fe9e8538caef5e9e2938cac55bf686c091d Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 26 Jan 2016 05:10:50 +0100 Subject: [PATCH 124/701] Ptr -> auto --- .../engine/datafacade/shared_datafacade.hpp | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index bbb2accb0..64ee0ae21 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -86,7 +86,7 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadTimestamp() { - char *timestamp_ptr = + auto timestamp_ptr = data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::TIMESTAMP); m_timestamp.resize(data_layout->GetBlockSize(storage::SharedDataLayout::TIMESTAMP)); std::copy(timestamp_ptr, @@ -98,7 +98,7 @@ template class SharedDataFacade final : public BaseDataFacade< { BOOST_ASSERT_MSG(!m_coordinate_list->empty(), "coordinates must be loaded before r-tree"); - RTreeNode *tree_ptr = data_layout->GetBlockPtr( + auto tree_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::R_SEARCH_TREE); m_static_rtree.reset(new TimeStampedRTreePair( CURRENT_TIMESTAMP, @@ -111,10 +111,10 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadGraph() { - GraphNode *graph_nodes_ptr = data_layout->GetBlockPtr( + auto graph_nodes_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::GRAPH_NODE_LIST); - GraphEdge *graph_edges_ptr = data_layout->GetBlockPtr( + auto graph_edges_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::GRAPH_EDGE_LIST); typename util::ShM::vector node_list( @@ -127,21 +127,21 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadNodeAndEdgeInformation() { - util::FixedPointCoordinate *coordinate_list_ptr = + auto coordinate_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::COORDINATE_LIST); m_coordinate_list = util::make_unique::vector>( coordinate_list_ptr, data_layout->num_entries[storage::SharedDataLayout::COORDINATE_LIST]); - extractor::TravelMode *travel_mode_list_ptr = + auto travel_mode_list_ptr = data_layout->GetBlockPtr(shared_memory, storage::SharedDataLayout::TRAVEL_MODE); typename util::ShM::vector travel_mode_list( travel_mode_list_ptr, data_layout->num_entries[storage::SharedDataLayout::TRAVEL_MODE]); m_travel_mode_list.swap(travel_mode_list); - extractor::TurnInstruction *turn_instruction_list_ptr = + auto turn_instruction_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::TURN_INSTRUCTION); typename util::ShM::vector turn_instruction_list( @@ -149,7 +149,7 @@ template class SharedDataFacade final : public BaseDataFacade< data_layout->num_entries[storage::SharedDataLayout::TURN_INSTRUCTION]); m_turn_instruction_list.swap(turn_instruction_list); - unsigned *name_id_list_ptr = data_layout->GetBlockPtr( + auto name_id_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::NAME_ID_LIST); typename util::ShM::vector name_id_list( name_id_list_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_ID_LIST]); @@ -158,7 +158,7 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadViaNodeList() { - NodeID *via_node_list_ptr = data_layout->GetBlockPtr( + auto via_node_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::VIA_NODE_LIST); typename util::ShM::vector via_node_list( via_node_list_ptr, data_layout->num_entries[storage::SharedDataLayout::VIA_NODE_LIST]); @@ -167,16 +167,16 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadNames() { - unsigned *offsets_ptr = data_layout->GetBlockPtr( + auto offsets_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::NAME_OFFSETS); - NameIndexBlock *blocks_ptr = data_layout->GetBlockPtr( + auto blocks_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::NAME_BLOCKS); typename util::ShM::vector name_offsets( offsets_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_OFFSETS]); typename util::ShM::vector name_blocks( blocks_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_BLOCKS]); - char *names_list_ptr = data_layout->GetBlockPtr( + auto names_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::NAME_CHAR_LIST); typename util::ShM::vector names_char_list( names_list_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_CHAR_LIST]); @@ -193,7 +193,7 @@ template class SharedDataFacade final : public BaseDataFacade< return; } - unsigned *core_marker_ptr = data_layout->GetBlockPtr( + auto core_marker_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::CORE_MARKER); typename util::ShM::vector is_core_node( core_marker_ptr, data_layout->num_entries[storage::SharedDataLayout::CORE_MARKER]); @@ -202,21 +202,21 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadGeometries() { - unsigned *geometries_compressed_ptr = data_layout->GetBlockPtr( + auto geometries_compressed_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::GEOMETRIES_INDICATORS); typename util::ShM::vector edge_is_compressed( geometries_compressed_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDICATORS]); m_edge_is_compressed.swap(edge_is_compressed); - unsigned *geometries_index_ptr = data_layout->GetBlockPtr( + auto geometries_index_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::GEOMETRIES_INDEX); typename util::ShM::vector geometry_begin_indices( geometries_index_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDEX]); m_geometry_indices.swap(geometry_begin_indices); - unsigned *geometries_list_ptr = data_layout->GetBlockPtr( + auto geometries_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::GEOMETRIES_LIST); typename util::ShM::vector geometry_list( geometries_list_ptr, @@ -238,7 +238,8 @@ template class SharedDataFacade final : public BaseDataFacade< } data_timestamp_ptr = static_cast( storage::makeSharedMemory(storage::CURRENT_REGIONS, - sizeof(storage::SharedDataTimestamp), false, false)->Ptr()); + sizeof(storage::SharedDataTimestamp), false, false) + ->Ptr()); CURRENT_LAYOUT = storage::LAYOUT_NONE; CURRENT_DATA = storage::DATA_NONE; CURRENT_TIMESTAMP = 0; @@ -289,7 +290,7 @@ template class SharedDataFacade final : public BaseDataFacade< m_large_memory.reset(storage::makeSharedMemory(CURRENT_DATA)); shared_memory = (char *)(m_large_memory->Ptr()); - const char *file_index_ptr = data_layout->GetBlockPtr( + const auto file_index_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::FILE_INDEX_PATH); file_index_path = boost::filesystem::path(file_index_ptr); if (!boost::filesystem::exists(file_index_path)) @@ -309,8 +310,8 @@ template class SharedDataFacade final : public BaseDataFacade< LoadNames(); LoadCoreInformation(); - util::SimpleLogger().Write() - << "number of geometries: " << m_coordinate_list->size(); + util::SimpleLogger().Write() << "number of geometries: " + << m_coordinate_list->size(); for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { if (!GetCoordinateOfNode(i).IsValid()) From d9c281cd7c88443a96b6c73e3077f761dec7c50b Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 26 Jan 2016 06:59:20 +0100 Subject: [PATCH 125/701] Remove boost fusion dependency in RouteParameters --- example/example.cpp | 6 ++--- include/engine/route_parameters.hpp | 10 +++----- include/server/api_grammar.hpp | 37 +++++++++++++++++++++++----- src/engine/route_parameters.cpp | 38 ++++++++++------------------- 4 files changed, 50 insertions(+), 41 deletions(-) diff --git a/example/example.cpp b/example/example.cpp index 0442ca698..1a59b34a0 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -35,11 +35,9 @@ int main(int argc, const char *argv[]) try osrm::RouteParameters route_parameters; // route is in Berlin - auto start = std::make_pair(52.519930, 13.438640); - auto target = std::make_pair(52.513191, 13.415852); route_parameters.service = "viaroute"; - route_parameters.AddCoordinate({start.first, start.second}); - route_parameters.AddCoordinate({target.first, target.second}); + route_parameters.AddCoordinate(52.519930, 13.438640); + route_parameters.AddCoordinate(52.513191, 13.415852); osrm::json::Object json_result; const int result_code = routing_machine.RunQuery(route_parameters, json_result); diff --git a/include/engine/route_parameters.hpp b/include/engine/route_parameters.hpp index b77207e32..172ce18c4 100644 --- a/include/engine/route_parameters.hpp +++ b/include/engine/route_parameters.hpp @@ -30,7 +30,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "osrm/coordinate.hpp" -#include #include #include @@ -77,8 +76,7 @@ struct RouteParameters void AddTimestamp(const unsigned timestamp); - void AddBearing(const boost::fusion::vector> &received_bearing, - bool &pass); + bool AddBearing(int bearing, boost::optional range); void SetLanguage(const std::string &language); @@ -86,11 +84,11 @@ struct RouteParameters void SetCompressionFlag(const bool flag); - void AddCoordinate(const boost::fusion::vector &received_coordinates); + void AddCoordinate(const double latitude, const double longitude); - void AddDestination(const boost::fusion::vector &received_coordinates); + void AddDestination(const double latitude, const double longitude); - void AddSource(const boost::fusion::vector &received_coordinates); + void AddSource(const double latitude, const double longitude); void SetCoordinatesFromGeometry(const std::string &geometry_string); diff --git a/include/server/api_grammar.hpp b/include/server/api_grammar.hpp index a0bfce60d..35673d94c 100644 --- a/include/server/api_grammar.hpp +++ b/include/server/api_grammar.hpp @@ -16,6 +16,32 @@ template struct APIGrammar : qi::grammar> &received_bearing, bool &pass) + { + const int bearing = boost::fusion::at_c<0>(received_bearing); + const boost::optional range = boost::fusion::at_c<1>(received_bearing); + pass = handler->AddBearing(bearing, range); + }; + const auto add_coordinate_wrapper = + [this](const boost::fusion::vector &received_coordinate) + { + handler->AddCoordinate(boost::fusion::at_c<0>(received_coordinate), + boost::fusion::at_c<1>(received_coordinate)); + }; + const auto add_source_wrapper = + [this](const boost::fusion::vector &received_coordinate) + { + handler->AddSource(boost::fusion::at_c<0>(received_coordinate), + boost::fusion::at_c<1>(received_coordinate)); + }; + const auto add_destination_wrapper = + [this](const boost::fusion::vector &received_coordinate) + { + handler->AddDestination(boost::fusion::at_c<0>(received_coordinate), + boost::fusion::at_c<1>(received_coordinate)); + }; + api_call = qi::lit('/') >> string[boost::bind(&HandlerT::SetService, handler, ::_1)] >> -query; query = ('?') >> +(zoom | output | jsonp | checksum | uturns | location_with_options | @@ -50,21 +76,20 @@ template struct APIGrammar : qi::grammar> qi::lit("loc") >> '=' >> (qi::double_ >> qi::lit(',') >> - qi::double_)[boost::bind(&HandlerT::AddCoordinate, handler, ::_1)]; + qi::double_)[boost::bind(add_coordinate_wrapper, ::_1)]; destination = (-qi::lit('&')) >> qi::lit("dst") >> '=' >> (qi::double_ >> qi::lit(',') >> - qi::double_)[boost::bind(&HandlerT::AddDestination, handler, ::_1)]; + qi::double_)[boost::bind(add_destination_wrapper, ::_1)]; source = (-qi::lit('&')) >> qi::lit("src") >> '=' >> (qi::double_ >> qi::lit(',') >> - qi::double_)[boost::bind(&HandlerT::AddSource, handler, ::_1)]; + qi::double_)[boost::bind(add_source_wrapper, ::_1)]; hint = (-qi::lit('&')) >> qi::lit("hint") >> '=' >> stringwithDot[boost::bind(&HandlerT::AddHint, handler, ::_1)]; timestamp = (-qi::lit('&')) >> qi::lit("t") >> '=' >> qi::uint_[boost::bind(&HandlerT::AddTimestamp, handler, ::_1)]; bearing = (-qi::lit('&')) >> qi::lit("b") >> '=' >> - (qi::int_ >> - -(qi::lit(',') >> qi::int_ | - qi::attr(10)))[boost::bind(&HandlerT::AddBearing, handler, ::_1, ::_3)]; + (qi::int_ >> -(qi::lit(',') >> qi::int_ | + qi::attr(10)))[boost::bind(add_bearing_wrapper, ::_1, ::_3)]; u = (-qi::lit('&')) >> qi::lit("u") >> '=' >> qi::bool_[boost::bind(&HandlerT::SetUTurn, handler, ::_1)]; uturns = (-qi::lit('&')) >> qi::lit("uturns") >> '=' >> diff --git a/src/engine/route_parameters.cpp b/src/engine/route_parameters.cpp index bc77c17ae..9e05e5e31 100644 --- a/src/engine/route_parameters.cpp +++ b/src/engine/route_parameters.cpp @@ -1,8 +1,3 @@ -#include -#include -#include -#include - #include "engine/route_parameters.hpp" #include "util/coordinate.hpp" @@ -98,19 +93,14 @@ void RouteParameters::AddTimestamp(const unsigned timestamp) } } -void RouteParameters::AddBearing( - const boost::fusion::vector> &received_bearing, - bool &pass) +bool RouteParameters::AddBearing(int bearing, boost::optional range) { - pass = false; - const int bearing = boost::fusion::at_c<0>(received_bearing); - const boost::optional range = boost::fusion::at_c<1>(received_bearing); if (bearing < 0 || bearing > 359) - return; + return false; if (range && (*range < 0 || *range > 180)) - return; + return false; bearings.emplace_back(std::make_pair(bearing, range)); - pass = true; + return true; } void RouteParameters::SetLanguage(const std::string &language_string) @@ -122,33 +112,31 @@ void RouteParameters::SetGeometryFlag(const bool flag) { geometry = flag; } void RouteParameters::SetCompressionFlag(const bool flag) { compression = flag; } -void RouteParameters::AddCoordinate( - const boost::fusion::vector &received_coordinates) +void RouteParameters::AddCoordinate(const double latitude, const double longitude) { coordinates.emplace_back( - static_cast(COORDINATE_PRECISION * boost::fusion::at_c<0>(received_coordinates)), - static_cast(COORDINATE_PRECISION * boost::fusion::at_c<1>(received_coordinates))); + static_cast(COORDINATE_PRECISION * latitude), + static_cast(COORDINATE_PRECISION * longitude)); is_source.push_back(true); is_destination.push_back(true); uturns.push_back(uturn_default); } -void RouteParameters::AddDestination( - const boost::fusion::vector &received_coordinates) +void RouteParameters::AddDestination(const double latitude, const double longitude) { coordinates.emplace_back( - static_cast(COORDINATE_PRECISION * boost::fusion::at_c<0>(received_coordinates)), - static_cast(COORDINATE_PRECISION * boost::fusion::at_c<1>(received_coordinates))); + static_cast(COORDINATE_PRECISION * latitude), + static_cast(COORDINATE_PRECISION * longitude)); is_source.push_back(false); is_destination.push_back(true); uturns.push_back(uturn_default); } -void RouteParameters::AddSource(const boost::fusion::vector &received_coordinates) +void RouteParameters::AddSource(const double latitude, const double longitude) { coordinates.emplace_back( - static_cast(COORDINATE_PRECISION * boost::fusion::at_c<0>(received_coordinates)), - static_cast(COORDINATE_PRECISION * boost::fusion::at_c<1>(received_coordinates))); + static_cast(COORDINATE_PRECISION * latitude), + static_cast(COORDINATE_PRECISION * longitude)); is_source.push_back(true); is_destination.push_back(false); uturns.push_back(uturn_default); From 08028046773460f274da166ff4b5f85521819109 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 26 Jan 2016 16:53:48 +0100 Subject: [PATCH 126/701] Fix PR comments --- include/engine/datafacade/shared_datafacade.hpp | 2 +- include/util/debug_geometry.hpp | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 64ee0ae21..25b39b783 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -285,7 +285,7 @@ template class SharedDataFacade final : public BaseDataFacade< util::SimpleLogger().Write(logDEBUG) << "Performing data reload"; m_layout_memory.reset(storage::makeSharedMemory(CURRENT_LAYOUT)); - data_layout = (storage::SharedDataLayout *)(m_layout_memory->Ptr()); + data_layout = static_cast(m_layout_memory->Ptr()); m_large_memory.reset(storage::makeSharedMemory(CURRENT_DATA)); shared_memory = (char *)(m_large_memory->Ptr()); diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index be9da638d..f76e0cd4f 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -113,8 +113,7 @@ inline void DEBUG_GEOMETRY_STOP() { if (dg_output_debug_geometry) { - debug_geometry_file << std::endl - << "]}" << std::endl; + debug_geometry_file << "\n]}" << std::endl; debug_geometry_file.close(); } } @@ -201,8 +200,7 @@ inline void DEBUG_TURNS_STOP() { if (dg_output_turn_debug) { - dg_debug_turns_file << std::endl - << "]}" << std::endl; + dg_debug_turns_file << "\n]}" << std::endl; dg_debug_turns_file.close(); } } From d189339495e223a6ceea21a73bb7e434775172fa Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 27 Jan 2016 17:18:04 +0100 Subject: [PATCH 127/701] Makes the extractor no longer depend on the crc32 computation --- src/extractor/extractor.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index cdd7ced41..6d6dd78f7 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -24,7 +24,6 @@ #include "extractor/restriction_map.hpp" #include "extractor/tarjan_scc.hpp" -#include "contractor/crc32_processor.hpp" #include #include From a48f02e0da2c0ec8fe208ebe2bacc2880bb5ec5f Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 27 Jan 2016 11:20:55 +0100 Subject: [PATCH 128/701] Takes care of proper special member generation globally, fixes #1689 Phew, a lot of classes were affected by this. The rationale for the changes are as follows: - When a type X declares any constructor, the default constructor is not declared, so there is no need for X() = delete there. In fact, there is brutal difference between those two: deleted members participate in overload resolution, but not-declared members do not! - When a type X wants to be non-copyable (e.g. to be only movable, like threads, unique_ptrs, and so on), you can either do it by inheriting from boost::noncopyable (the old way), or better declare both (!) the copy constructor _and_ the copy assignment operator as deleted: X(X const&) = delete; X& operator=(X const&) = delete; We had tons of types with deleted copy constructors that were lacking a corresponding deleted copy assignment operator, making them still copyable and you wouldn't even notice (read: scary)! References: - http://accu.org/content/conf2014/Howard_Hinnant_Accu_2014.pdf - http://www.boost.org/doc/libs/master/libs/core/doc/html/core/noncopyable.html Note: I know, I'm quoting Hinnant's extraordinary slides a lot, but getting the sematic right here is so incredibly important. --- include/engine/engine.hpp | 3 + .../routing_algorithms/routing_base.hpp | 18 +++--- .../extractor/edge_based_graph_factory.hpp | 4 +- include/extractor/extractor_callbacks.hpp | 5 +- include/extractor/scripting_environment.hpp | 4 +- include/server/connection.hpp | 2 +- include/server/request_handler.hpp | 1 + include/storage/shared_memory.hpp | 56 ++++++++++--------- include/util/simple_logger.hpp | 1 + include/util/static_rtree.hpp | 2 +- src/engine/douglas_peucker.cpp | 1 - src/server/request_handler.cpp | 1 - 12 files changed, 55 insertions(+), 43 deletions(-) diff --git a/include/engine/engine.hpp b/include/engine/engine.hpp index 3b23445ba..1ca8ad609 100644 --- a/include/engine/engine.hpp +++ b/include/engine/engine.hpp @@ -46,7 +46,10 @@ class Engine final public: Engine(EngineConfig &config_); + Engine(const Engine &) = delete; + Engine &operator=(const Engine &) = delete; + int RunQuery(const RouteParameters &route_parameters, util::json::Object &json_result); private: diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index 6f9315d1e..156ebba9e 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -42,11 +42,12 @@ template class BasicRoutingInterface DataFacadeT *facade; public: - BasicRoutingInterface() = delete; - BasicRoutingInterface(const BasicRoutingInterface &) = delete; explicit BasicRoutingInterface(DataFacadeT *facade) : facade(facade) {} ~BasicRoutingInterface() {} + BasicRoutingInterface(const BasicRoutingInterface &) = delete; + BasicRoutingInterface &operator=(const BasicRoutingInterface &) = delete; + /* min_edge_offset is needed in case we use multiple nodes as start/target nodes with different (even negative) offsets. @@ -98,7 +99,8 @@ template class BasicRoutingInterface (!force_loop_forward || forward_heap.GetData(node).parent != node) // if loops are forced, they are so at the source - && (!force_loop_reverse || reverse_heap.GetData(node).parent != node)) + && + (!force_loop_reverse || reverse_heap.GetData(node).parent != node)) { middle_node_id = node; upper_bound = new_distance; @@ -362,8 +364,10 @@ template class BasicRoutingInterface BOOST_ASSERT(i < id_vector.size()); BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode > 0); unpacked_path.emplace_back( - PathData{id_vector[i], phantom_node_pair.target_phantom.name_id, - extractor::TurnInstruction::NoTurn, 0, + PathData{id_vector[i], + phantom_node_pair.target_phantom.name_id, + extractor::TurnInstruction::NoTurn, + 0, phantom_node_pair.target_phantom.forward_travel_mode}); } } @@ -601,8 +605,8 @@ template class BasicRoutingInterface // TODO check if unordered_set might be faster // sort by id and increasing by distance - auto entry_point_comparator = [](const std::pair &lhs, - const std::pair &rhs) + auto entry_point_comparator = + [](const std::pair &lhs, const std::pair &rhs) { return lhs.first < rhs.first || (lhs.first == rhs.first && lhs.second < rhs.second); }; diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index ef9bacf99..7957cb60b 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -36,8 +36,8 @@ namespace extractor class EdgeBasedGraphFactory { public: - EdgeBasedGraphFactory() = delete; EdgeBasedGraphFactory(const EdgeBasedGraphFactory &) = delete; + EdgeBasedGraphFactory &operator=(const EdgeBasedGraphFactory &) = delete; explicit EdgeBasedGraphFactory(std::shared_ptr node_based_graph, const CompressedEdgeContainer &compressed_edge_container, @@ -62,7 +62,7 @@ class EdgeBasedGraphFactory const bool generate_edge_lookup); #endif - //The following get access functions destroy the content in the factory + // The following get access functions destroy the content in the factory void GetEdgeBasedEdges(util::DeallocatingVector &edges); void GetEdgeBasedNodes(std::vector &nodes); void GetStartPointMarkers(std::vector &node_is_startpoint); diff --git a/include/extractor/extractor_callbacks.hpp b/include/extractor/extractor_callbacks.hpp index 673c2f601..db4e870f3 100644 --- a/include/extractor/extractor_callbacks.hpp +++ b/include/extractor/extractor_callbacks.hpp @@ -38,10 +38,11 @@ class ExtractorCallbacks ExtractionContainers &external_memory; public: - ExtractorCallbacks() = delete; - ExtractorCallbacks(const ExtractorCallbacks &) = delete; explicit ExtractorCallbacks(ExtractionContainers &extraction_containers); + ExtractorCallbacks(const ExtractorCallbacks &) = delete; + ExtractorCallbacks &operator=(const ExtractorCallbacks &) = delete; + // warning: caller needs to take care of synchronization! void ProcessNode(const osmium::Node ¤t_node, const ExtractionNode &result_node); diff --git a/include/extractor/scripting_environment.hpp b/include/extractor/scripting_environment.hpp index d02c7cb26..cd9de04cc 100644 --- a/include/extractor/scripting_environment.hpp +++ b/include/extractor/scripting_environment.hpp @@ -23,9 +23,11 @@ namespace extractor class ScriptingEnvironment { public: - ScriptingEnvironment() = delete; explicit ScriptingEnvironment(const std::string &file_name); + ScriptingEnvironment(const ScriptingEnvironment &) = delete; + ScriptingEnvironment &operator=(const ScriptingEnvironment &) = delete; + lua_State *GetLuaState(); private: diff --git a/include/server/connection.hpp b/include/server/connection.hpp index ace005392..08821597e 100644 --- a/include/server/connection.hpp +++ b/include/server/connection.hpp @@ -39,7 +39,7 @@ class Connection : public std::enable_shared_from_this public: explicit Connection(boost::asio::io_service &io_service, RequestHandler &handler); Connection(const Connection &) = delete; - Connection() = delete; + Connection &operator=(const Connection &) = delete; boost::asio::ip::tcp::socket &socket(); diff --git a/include/server/request_handler.hpp b/include/server/request_handler.hpp index eba77eac7..16b3886a6 100644 --- a/include/server/request_handler.hpp +++ b/include/server/request_handler.hpp @@ -28,6 +28,7 @@ class RequestHandler RequestHandler(); RequestHandler(const RequestHandler &) = delete; + RequestHandler &operator=(const RequestHandler &) = delete; void handle_request(const http::request ¤t_request, http::reply ¤t_reply); void RegisterRoutingMachine(OSRM *osrm); diff --git a/include/storage/shared_memory.hpp b/include/storage/shared_memory.hpp index 3b04d2e32..7f14482e3 100644 --- a/include/storage/shared_memory.hpp +++ b/include/storage/shared_memory.hpp @@ -58,7 +58,10 @@ class SharedMemory } shm_remove() : m_shmid(INT_MIN), m_initialized(false) {} + shm_remove(const shm_remove &) = delete; + shm_remove &operator=(const shm_remove &) = delete; + ~shm_remove() { if (m_initialized) @@ -75,7 +78,6 @@ class SharedMemory public: void *Ptr() const { return region.get_address(); } - SharedMemory() = delete; SharedMemory(const SharedMemory &) = delete; SharedMemory &operator=(const SharedMemory &) = delete; @@ -193,8 +195,6 @@ class SharedMemory class shm_remove { private: - shm_remove(const shm_remove &) = delete; - shm_remove &operator=(const shm_remove &) = delete; char *m_shmid; bool m_initialized; @@ -207,6 +207,9 @@ class SharedMemory shm_remove() : m_shmid("undefined"), m_initialized(false) {} + shm_remove(const shm_remove &) = delete; + shm_remove &operator=(const shm_remove &) = delete; + ~shm_remove() { if (m_initialized) @@ -324,34 +327,33 @@ class SharedMemory template SharedMemory *makeSharedMemory(const IdentifierT &id, - const uint64_t size = 0, - bool read_write = false, - bool remove_prev = true) + const uint64_t size = 0, + bool read_write = false, + bool remove_prev = true) { - try - { - LockFileT lock_file; - if (!boost::filesystem::exists(lock_file())) + try { - if (0 == size) - { - throw util::exception("lock file does not exist, exiting"); - } - else - { - boost::filesystem::ofstream ofs(lock_file()); - } + LockFileT lock_file; + if (!boost::filesystem::exists(lock_file())) + { + if (0 == size) + { + throw util::exception("lock file does not exist, exiting"); + } + else + { + boost::filesystem::ofstream ofs(lock_file()); + } + } + return new SharedMemory(lock_file(), id, size, read_write, remove_prev); + } + catch (const boost::interprocess::interprocess_exception &e) + { + util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " + << e.get_error_code(); + throw util::exception(e.what()); } - return new SharedMemory(lock_file(), id, size, read_write, remove_prev); - } - catch (const boost::interprocess::interprocess_exception &e) - { - util::SimpleLogger().Write(logWARNING) << "caught exception: " << e.what() << ", code " - << e.get_error_code(); - throw util::exception(e.what()); - } } - } } diff --git a/include/util/simple_logger.hpp b/include/util/simple_logger.hpp index 29301b9d5..f71f0ff7d 100644 --- a/include/util/simple_logger.hpp +++ b/include/util/simple_logger.hpp @@ -29,6 +29,7 @@ class LogPolicy static LogPolicy &GetInstance(); LogPolicy(const LogPolicy &) = delete; + LogPolicy &operator=(const LogPolicy &) = delete; private: LogPolicy() : m_is_mute(true) {} diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index 32bc71eee..c6f34f71d 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -106,8 +106,8 @@ class StaticRTree boost::filesystem::ifstream leaves_stream; public: - StaticRTree() = delete; StaticRTree(const StaticRTree &) = delete; + StaticRTree &operator=(const StaticRTree &) = delete; template // Construct a packed Hilbert-R-Tree with Kamel-Faloutsos algorithm [1] diff --git a/src/engine/douglas_peucker.cpp b/src/engine/douglas_peucker.cpp index be3572306..2685b4a2a 100644 --- a/src/engine/douglas_peucker.cpp +++ b/src/engine/douglas_peucker.cpp @@ -19,7 +19,6 @@ namespace { struct CoordinatePairCalculator { - CoordinatePairCalculator() = delete; CoordinatePairCalculator(const util::FixedPointCoordinate coordinate_a, const util::FixedPointCoordinate coordinate_b) { diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index 96b94671d..6df6c1e99 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -147,7 +147,6 @@ void RequestHandler::handle_request(const http::request ¤t_request, catch (const std::exception &e) { current_reply = http::reply::stock_reply(http::reply::internal_server_error); - ; util::SimpleLogger().Write(logWARNING) << "[server error] code: " << e.what() << ", uri: " << current_request.uri; } From 603b83e1c3fdf55e31721c092f49f9745cf49b76 Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Thu, 28 Jan 2016 15:26:56 +0100 Subject: [PATCH 129/701] Fixes Alternative Routing when including loops --- features/testbot/alternative_loop.feature | 29 +++++++++++++++++++ .../routing_algorithms/alternative_path.hpp | 19 ++++++++---- 2 files changed, 42 insertions(+), 6 deletions(-) create mode 100644 features/testbot/alternative_loop.feature diff --git a/features/testbot/alternative_loop.feature b/features/testbot/alternative_loop.feature new file mode 100644 index 000000000..6af2bfe0e --- /dev/null +++ b/features/testbot/alternative_loop.feature @@ -0,0 +1,29 @@ +@routing @testbot @alternative +Feature: Alternative route + + Background: + Given the profile "testbot" + + Scenario: Alternative Loop Paths + Given the node map + | a | 2 | 1 | b | + | 7 | | | 4 | + | 8 | | | 3 | + | c | 5 | 6 | d | + + And the ways + | nodes | oneway | + | ab | yes | + | bd | yes | + | dc | yes | + | ca | yes | + + And the query options + | alt | true | + + When I route I should get + | from | to | route | alternative | + | 1 | 2 | ab,bd,dc,ca,ab | | + | 3 | 4 | bd,dc,ca,ab,bd | | + | 5 | 6 | dc,ca,ab,bd,dc | | + | 7 | 8 | ca,ab,bd,dc,ca | | diff --git a/include/engine/routing_algorithms/alternative_path.hpp b/include/engine/routing_algorithms/alternative_path.hpp index 7d7f64832..024b03611 100644 --- a/include/engine/routing_algorithms/alternative_path.hpp +++ b/include/engine/routing_algorithms/alternative_path.hpp @@ -156,8 +156,10 @@ class AlternativeRouting final std::vector packed_forward_path; std::vector packed_reverse_path; - if (upper_bound_to_shortest_path_distance != - forward_heap1.GetKey(middle_node) + reverse_heap1.GetKey(middle_node)) + const bool path_is_a_loop = + upper_bound_to_shortest_path_distance != + forward_heap1.GetKey(middle_node) + reverse_heap1.GetKey(middle_node); + if (path_is_a_loop) { // Self Loop BOOST_ASSERT(forward_heap1.GetData(middle_node).parent == middle_node && @@ -239,6 +241,8 @@ class AlternativeRouting final std::vector preselected_node_list; for (const NodeID node : via_node_candidate_list) { + if (node == middle_node) + continue; const auto fwd_iterator = approximated_forward_sharing.find(node); const int fwd_sharing = (fwd_iterator != approximated_forward_sharing.end()) ? fwd_iterator->second : 0; @@ -265,10 +269,13 @@ class AlternativeRouting final } std::vector &packed_shortest_path = packed_forward_path; - std::reverse(packed_shortest_path.begin(), packed_shortest_path.end()); - packed_shortest_path.emplace_back(middle_node); - packed_shortest_path.insert(packed_shortest_path.end(), packed_reverse_path.begin(), - packed_reverse_path.end()); + if (!path_is_a_loop) + { + std::reverse(packed_shortest_path.begin(), packed_shortest_path.end()); + packed_shortest_path.emplace_back(middle_node); + packed_shortest_path.insert(packed_shortest_path.end(), packed_reverse_path.begin(), + packed_reverse_path.end()); + } std::vector ranked_candidates_list; // prioritizing via nodes for deep inspection From efee07e20b32aba15a7ffb6da3105858c60ab501 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Fri, 29 Jan 2016 15:58:48 +0100 Subject: [PATCH 130/701] Move arrays don't copy --- include/engine/plugins/distance_table.hpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index 0f607ba57..b1625ed93 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -192,7 +192,7 @@ template class DistanceTablePlugin final : public BasePlugin json_row.values.insert(json_row.values.end(), row_begin_iterator, row_end_iterator); matrix_json_array.values.push_back(json_row); } - json_result.values["distance_table"] = matrix_json_array; + json_result.values["distance_table"] = std::move(matrix_json_array); util::json::Array target_coord_json_array; for (const auto &phantom : snapped_target_phantoms) @@ -202,7 +202,7 @@ template class DistanceTablePlugin final : public BasePlugin json_coord.values.push_back(phantom.location.lon / COORDINATE_PRECISION); target_coord_json_array.values.push_back(json_coord); } - json_result.values["destination_coordinates"] = target_coord_json_array; + json_result.values["destination_coordinates"] = std::move(target_coord_json_array); util::json::Array source_coord_json_array; for (const auto &phantom : snapped_source_phantoms) { @@ -211,7 +211,7 @@ template class DistanceTablePlugin final : public BasePlugin json_coord.values.push_back(phantom.location.lon / COORDINATE_PRECISION); source_coord_json_array.values.push_back(json_coord); } - json_result.values["source_coordinates"] = source_coord_json_array; + json_result.values["source_coordinates"] = std::move(source_coord_json_array); return Status::Ok; } From 262cdd7bc0d7909631b03138b2343a8a9a00fc3f Mon Sep 17 00:00:00 2001 From: karenzshea Date: Thu, 28 Jan 2016 18:43:19 -0500 Subject: [PATCH 131/701] move tribool obj into request_parser --- include/server/request_parser.hpp | 12 ++- include/util/tribool.hpp | 17 ---- src/server/connection.cpp | 6 +- src/server/request_parser.cpp | 138 +++++++++++++++--------------- 4 files changed, 80 insertions(+), 93 deletions(-) delete mode 100644 include/util/tribool.hpp diff --git a/include/server/request_parser.hpp b/include/server/request_parser.hpp index 0b44849ae..cbf91e0a3 100644 --- a/include/server/request_parser.hpp +++ b/include/server/request_parser.hpp @@ -3,7 +3,6 @@ #include "server/http/compression_type.hpp" #include "server/http/header.hpp" -#include "util/tribool.hpp" #include @@ -22,11 +21,18 @@ class RequestParser public: RequestParser(); - std::tuple + std::tuple parse(http::request ¤t_request, char *begin, char *end); + enum class RequestStatus : char + { + valid, + invalid, + indeterminate + }; + private: - util::tribool consume(http::request ¤t_request, const char input); + RequestStatus consume(http::request ¤t_request, const char input); bool is_char(const int character) const; diff --git a/include/util/tribool.hpp b/include/util/tribool.hpp deleted file mode 100644 index 85282de88..000000000 --- a/include/util/tribool.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef TRIBOOL_HPP -#define TRIBOOL_HPP - -namespace osrm -{ -namespace util -{ - -enum class tribool : char -{ - yes, - no, - indeterminate -}; -} -} -#endif // TRIBOOL_HPP diff --git a/src/server/connection.cpp b/src/server/connection.cpp index 0f4b59750..067360840 100644 --- a/src/server/connection.cpp +++ b/src/server/connection.cpp @@ -41,13 +41,13 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t // no error detected, let's parse the request http::compression_type compression_type(http::no_compression); - util::tribool result; + RequestStatus result; std::tie(result, compression_type) = request_parser.parse(current_request, incoming_data_buffer.data(), incoming_data_buffer.data() + bytes_transferred); // the request has been parsed - if (result == util::tribool::yes) + if (result == RequestStatus::yes) { current_request.endpoint = TCP_socket.remote_endpoint().address(); request_handler.handle_request(current_request, current_reply); @@ -85,7 +85,7 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t strand.wrap(boost::bind(&Connection::handle_write, this->shared_from_this(), boost::asio::placeholders::error))); } - else if (result == util::tribool::no) + else if (result == RequestStatus::no) { // request is not parseable current_reply = http::reply::stock_reply(http::reply::bad_request); diff --git a/src/server/request_parser.cpp b/src/server/request_parser.cpp index 3d6149d06..6b997f624 100644 --- a/src/server/request_parser.cpp +++ b/src/server/request_parser.cpp @@ -4,8 +4,6 @@ #include "server/http/header.hpp" #include "server/http/request.hpp" -#include "util/tribool.hpp" - #include #include @@ -21,177 +19,177 @@ RequestParser::RequestParser() { } -std::tuple +std::tuple RequestParser::parse(http::request ¤t_request, char *begin, char *end) { while (begin != end) { - util::tribool result = consume(current_request, *begin++); - if (result != util::tribool::indeterminate) + RequestStatus result = consume(current_request, *begin++); + if (result != RequestStatus::indeterminate) { return std::make_tuple(result, selected_compression); } } - util::tribool result = util::tribool::indeterminate; + RequestStatus result = RequestStatus::indeterminate; if (state == internal_state::post_request && content_length <= 0) { - result = util::tribool::yes; + result = RequestStatus::valid; } return std::make_tuple(result, selected_compression); } -util::tribool RequestParser::consume(http::request ¤t_request, const char input) +RequestStatus RequestParser::consume(http::request ¤t_request, const char input) { switch (state) { case internal_state::method_start: if (!is_char(input) || is_CTL(input) || is_special(input)) { - return util::tribool::no; + return RequestStatus::invalid; } if (input == 'P') { state = internal_state::post_O; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } state = internal_state::method; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::post_O: if (input == 'O') { state = internal_state::post_S; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::post_S: if (input == 'S') { state = internal_state::post_T; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::post_T: if (input == 'T') { is_post_header = true; state = internal_state::method; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::post_request: current_request.uri.push_back(input); --content_length; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::method: if (input == ' ') { state = internal_state::uri; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return util::tribool::no; + return RequestStatus::invalid; } - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::uri_start: if (is_CTL(input)) { - return util::tribool::no; + return RequestStatus::invalid; } state = internal_state::uri; current_request.uri.push_back(input); - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::uri: if (input == ' ') { state = internal_state::http_version_h; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (is_CTL(input)) { - return util::tribool::no; + return RequestStatus::invalid; } current_request.uri.push_back(input); - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::http_version_h: if (input == 'H') { state = internal_state::http_version_t_1; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::http_version_t_1: if (input == 'T') { state = internal_state::http_version_t_2; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::http_version_t_2: if (input == 'T') { state = internal_state::http_version_p; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::http_version_p: if (input == 'P') { state = internal_state::http_version_slash; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::http_version_slash: if (input == '/') { state = internal_state::http_version_major_start; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::http_version_major_start: if (is_digit(input)) { state = internal_state::http_version_major; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::http_version_major: if (input == '.') { state = internal_state::http_version_minor_start; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (is_digit(input)) { - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::http_version_minor_start: if (is_digit(input)) { state = internal_state::http_version_minor; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::http_version_minor: if (input == '\r') { state = internal_state::expecting_newline_1; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (is_digit(input)) { - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::expecting_newline_1: if (input == '\n') { state = internal_state::header_line_start; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::header_line_start: if (boost::iequals(current_header.name, "Accept-Encoding")) { @@ -230,77 +228,77 @@ util::tribool RequestParser::consume(http::request ¤t_request, const char { if (!boost::icontains(current_header.value, "application/x-www-form-urlencoded")) { - return util::tribool::no; + return RequestStatus::invalid; } } if (input == '\r') { state = internal_state::expecting_newline_3; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return util::tribool::no; + return RequestStatus::invalid; } state = internal_state::header_name; current_header.clear(); current_header.name.push_back(input); - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::header_lws: if (input == '\r') { state = internal_state::expecting_newline_2; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (input == ' ' || input == '\t') { - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (is_CTL(input)) { - return util::tribool::no; + return RequestStatus::invalid; } state = internal_state::header_value; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::header_name: if (input == ':') { state = internal_state::space_before_header_value; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (!is_char(input) || is_CTL(input) || is_special(input)) { - return util::tribool::no; + return RequestStatus::invalid; } current_header.name.push_back(input); - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::space_before_header_value: if (input == ' ') { state = internal_state::header_value; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::header_value: if (input == '\r') { state = internal_state::expecting_newline_2; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } if (is_CTL(input)) { - return util::tribool::no; + return RequestStatus::invalid; } current_header.value.push_back(input); - return util::tribool::indeterminate; + return RequestStatus::indeterminate; case internal_state::expecting_newline_2: if (input == '\n') { state = internal_state::header_line_start; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::no; + return RequestStatus::invalid; case internal_state::expecting_newline_3: if (input == '\n') { @@ -311,13 +309,13 @@ util::tribool RequestParser::consume(http::request ¤t_request, const char current_request.uri.push_back('?'); } state = internal_state::post_request; - return util::tribool::indeterminate; + return RequestStatus::indeterminate; } - return util::tribool::yes; + return RequestStatus::valid; } - return util::tribool::no; + return RequestStatus::invalid; default: // should never be reached - return input == '\n' ? util::tribool::yes : util::tribool::no; + return input == '\n' ? RequestStatus::valid : RequestStatus::invalid; } } From f5c12ec4330c0c835fc09dc349878e4fc670b861 Mon Sep 17 00:00:00 2001 From: karenzshea Date: Fri, 29 Jan 2016 17:02:18 -0500 Subject: [PATCH 132/701] comments --- include/server/request_parser.hpp | 6 +++--- src/server/connection.cpp | 6 +++--- src/server/request_parser.cpp | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/include/server/request_parser.hpp b/include/server/request_parser.hpp index cbf91e0a3..46f4b66b5 100644 --- a/include/server/request_parser.hpp +++ b/include/server/request_parser.hpp @@ -21,9 +21,6 @@ class RequestParser public: RequestParser(); - std::tuple - parse(http::request ¤t_request, char *begin, char *end); - enum class RequestStatus : char { valid, @@ -31,6 +28,9 @@ class RequestParser indeterminate }; + std::tuple + parse(http::request ¤t_request, char *begin, char *end); + private: RequestStatus consume(http::request ¤t_request, const char input); diff --git a/src/server/connection.cpp b/src/server/connection.cpp index 067360840..9115ea4c4 100644 --- a/src/server/connection.cpp +++ b/src/server/connection.cpp @@ -41,13 +41,13 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t // no error detected, let's parse the request http::compression_type compression_type(http::no_compression); - RequestStatus result; + RequestParser::RequestStatus result; std::tie(result, compression_type) = request_parser.parse(current_request, incoming_data_buffer.data(), incoming_data_buffer.data() + bytes_transferred); // the request has been parsed - if (result == RequestStatus::yes) + if (result == RequestParser::RequestStatus::valid) { current_request.endpoint = TCP_socket.remote_endpoint().address(); request_handler.handle_request(current_request, current_reply); @@ -85,7 +85,7 @@ void Connection::handle_read(const boost::system::error_code &error, std::size_t strand.wrap(boost::bind(&Connection::handle_write, this->shared_from_this(), boost::asio::placeholders::error))); } - else if (result == RequestStatus::no) + else if (result == RequestParser::RequestStatus::invalid) { // request is not parseable current_reply = http::reply::stock_reply(http::reply::bad_request); diff --git a/src/server/request_parser.cpp b/src/server/request_parser.cpp index 6b997f624..f11b89836 100644 --- a/src/server/request_parser.cpp +++ b/src/server/request_parser.cpp @@ -19,7 +19,7 @@ RequestParser::RequestParser() { } -std::tuple +std::tuple RequestParser::parse(http::request ¤t_request, char *begin, char *end) { while (begin != end) @@ -39,7 +39,7 @@ RequestParser::parse(http::request ¤t_request, char *begin, char *end) return std::make_tuple(result, selected_compression); } -RequestStatus RequestParser::consume(http::request ¤t_request, const char input) +RequestParser::RequestStatus RequestParser::consume(http::request ¤t_request, const char input) { switch (state) { From 8804330d8345d701997845432eb5b32f33c296f9 Mon Sep 17 00:00:00 2001 From: Kerrick Staley Date: Mon, 1 Feb 2016 12:32:28 -0800 Subject: [PATCH 133/701] Add operator<< to OSRM_STRONG_TYPEDEF Useful for debugging. --- include/util/strong_typedef.hpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/include/util/strong_typedef.hpp b/include/util/strong_typedef.hpp index 58e70602f..8aa49b515 100644 --- a/include/util/strong_typedef.hpp +++ b/include/util/strong_typedef.hpp @@ -1,6 +1,7 @@ #ifndef STRONG_TYPEDEF_HPP #define STRONG_TYPEDEF_HPP +#include #include #include @@ -17,6 +18,7 @@ namespace osrm { \ static_assert(std::is_arithmetic(), ""); \ From x; \ + friend std::ostream& operator<<(std::ostream& stream, const To& inst); \ \ public: \ To() = default; \ @@ -40,6 +42,9 @@ namespace osrm return std::hash()(static_cast(k)); \ } \ }; \ + } \ + inline std::ostream& operator<<(std::ostream& stream, const To& inst) { \ + return stream << #To << '(' << inst.x << ')'; \ } } From 5e15bceaae0095f64a843a0b064b75704a94fd6d Mon Sep 17 00:00:00 2001 From: Bas Couwenberg Date: Sun, 7 Feb 2016 02:59:44 +0100 Subject: [PATCH 134/701] Fix 'egdes' typo, replace with 'edges'. --- src/extractor/extractor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 6d6dd78f7..3d239893c 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -612,7 +612,7 @@ void Extractor::WriteEdgeBasedGraph( const util::FingerPrint fingerprint = util::FingerPrint::GetValid(); file_out_stream.write((char *)&fingerprint, sizeof(util::FingerPrint)); - util::SimpleLogger().Write() << "[extractor] Writing edge-based-graph egdes ... " + util::SimpleLogger().Write() << "[extractor] Writing edge-based-graph edges ... " << std::flush; TIMER_START(write_edges); From ff966490bbdad4bb9510a3ffa8d84f54cbe10440 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 5 Feb 2016 14:58:06 +0100 Subject: [PATCH 135/701] Fixes datafacade includes --- include/engine/datafacade/datafacade_base.hpp | 5 ++- .../engine/datafacade/internal_datafacade.hpp | 17 ++++++++- .../engine/datafacade/shared_datafacade.hpp | 36 ++++++++++--------- 3 files changed, 40 insertions(+), 18 deletions(-) diff --git a/include/engine/datafacade/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp index c7006e4d3..e737f2def 100644 --- a/include/engine/datafacade/datafacade_base.hpp +++ b/include/engine/datafacade/datafacade_base.hpp @@ -14,8 +14,11 @@ #include "osrm/coordinate.hpp" +#include + +#include +#include #include -#include namespace osrm { diff --git a/include/engine/datafacade/internal_datafacade.hpp b/include/engine/datafacade/internal_datafacade.hpp index b78e5c040..11f65e3e4 100644 --- a/include/engine/datafacade/internal_datafacade.hpp +++ b/include/engine/datafacade/internal_datafacade.hpp @@ -18,9 +18,24 @@ #include "osrm/coordinate.hpp" -#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include namespace osrm { diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 25b39b783..c35391300 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -14,11 +14,19 @@ #include "util/make_unique.hpp" #include "util/simple_logger.hpp" -#include +#include #include #include #include +#include +#include +#include + +#include +#include +#include +#include namespace osrm { @@ -111,7 +119,7 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadGraph() { - auto graph_nodes_ptr = data_layout->GetBlockPtr( + auto graph_nodes_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::GRAPH_NODE_LIST); auto graph_edges_ptr = data_layout->GetBlockPtr( @@ -127,23 +135,20 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadNodeAndEdgeInformation() { - auto coordinate_list_ptr = - data_layout->GetBlockPtr( - shared_memory, storage::SharedDataLayout::COORDINATE_LIST); + auto coordinate_list_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::COORDINATE_LIST); m_coordinate_list = util::make_unique::vector>( coordinate_list_ptr, data_layout->num_entries[storage::SharedDataLayout::COORDINATE_LIST]); - auto travel_mode_list_ptr = - data_layout->GetBlockPtr(shared_memory, - storage::SharedDataLayout::TRAVEL_MODE); + auto travel_mode_list_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::TRAVEL_MODE); typename util::ShM::vector travel_mode_list( travel_mode_list_ptr, data_layout->num_entries[storage::SharedDataLayout::TRAVEL_MODE]); m_travel_mode_list.swap(travel_mode_list); - auto turn_instruction_list_ptr = - data_layout->GetBlockPtr( - shared_memory, storage::SharedDataLayout::TURN_INSTRUCTION); + auto turn_instruction_list_ptr = data_layout->GetBlockPtr( + shared_memory, storage::SharedDataLayout::TURN_INSTRUCTION); typename util::ShM::vector turn_instruction_list( turn_instruction_list_ptr, data_layout->num_entries[storage::SharedDataLayout::TURN_INSTRUCTION]); @@ -238,8 +243,7 @@ template class SharedDataFacade final : public BaseDataFacade< } data_timestamp_ptr = static_cast( storage::makeSharedMemory(storage::CURRENT_REGIONS, - sizeof(storage::SharedDataTimestamp), false, false) - ->Ptr()); + sizeof(storage::SharedDataTimestamp), false, false)->Ptr()); CURRENT_LAYOUT = storage::LAYOUT_NONE; CURRENT_DATA = storage::DATA_NONE; CURRENT_TIMESTAMP = 0; @@ -285,7 +289,7 @@ template class SharedDataFacade final : public BaseDataFacade< util::SimpleLogger().Write(logDEBUG) << "Performing data reload"; m_layout_memory.reset(storage::makeSharedMemory(CURRENT_LAYOUT)); - data_layout = static_cast(m_layout_memory->Ptr()); + data_layout = static_cast(m_layout_memory->Ptr()); m_large_memory.reset(storage::makeSharedMemory(CURRENT_DATA)); shared_memory = (char *)(m_large_memory->Ptr()); @@ -310,8 +314,8 @@ template class SharedDataFacade final : public BaseDataFacade< LoadNames(); LoadCoreInformation(); - util::SimpleLogger().Write() << "number of geometries: " - << m_coordinate_list->size(); + util::SimpleLogger().Write() + << "number of geometries: " << m_coordinate_list->size(); for (unsigned i = 0; i < m_coordinate_list->size(); ++i) { if (!GetCoordinateOfNode(i).IsValid()) From 3075f6cea71c18de93d34f8c4d8f943abdf2b7ce Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 5 Feb 2016 15:06:28 +0100 Subject: [PATCH 136/701] No need for deferred, non-blocking or timeout acquisition --- include/engine/datafacade/shared_datafacade.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index c35391300..3fff40cee 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -26,7 +26,7 @@ #include #include #include -#include +#include namespace osrm { @@ -260,7 +260,7 @@ template class SharedDataFacade final : public BaseDataFacade< { // Get exclusive lock util::SimpleLogger().Write(logDEBUG) << "Updates available, getting exclusive lock"; - boost::unique_lock lock(data_mutex); + const boost::lock_guard lock(data_mutex); if (CURRENT_LAYOUT != data_timestamp_ptr->layout || CURRENT_DATA != data_timestamp_ptr->data) From 7b37c847bdb1f1b211eac9aaff229c26b10e1a7c Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 5 Feb 2016 16:45:36 +0100 Subject: [PATCH 137/701] Fixes shared memory wrapper includes --- include/util/shared_memory_vector_wrapper.hpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/include/util/shared_memory_vector_wrapper.hpp b/include/util/shared_memory_vector_wrapper.hpp index c6756f5f5..6812fffb8 100644 --- a/include/util/shared_memory_vector_wrapper.hpp +++ b/include/util/shared_memory_vector_wrapper.hpp @@ -3,10 +3,13 @@ #include +#include + #include #include #include #include +#include namespace osrm { From fa8529949b3b9de86b80dd7f6e5e2e0e7f6e853c Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 5 Feb 2016 17:53:17 +0100 Subject: [PATCH 138/701] Make swap noexcept (as it has to be!) and fix swap misuses --- .../engine/datafacade/shared_datafacade.hpp | 19 ++++++------- include/util/range_table.hpp | 6 ++-- include/util/shared_memory_vector_wrapper.hpp | 28 +++++++++---------- include/util/static_graph.hpp | 5 ++-- 4 files changed, 30 insertions(+), 28 deletions(-) diff --git a/include/engine/datafacade/shared_datafacade.hpp b/include/engine/datafacade/shared_datafacade.hpp index 3fff40cee..5b6728b20 100644 --- a/include/engine/datafacade/shared_datafacade.hpp +++ b/include/engine/datafacade/shared_datafacade.hpp @@ -134,7 +134,6 @@ template class SharedDataFacade final : public BaseDataFacade< void LoadNodeAndEdgeInformation() { - auto coordinate_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::COORDINATE_LIST); m_coordinate_list = util::make_unique::vector>( @@ -145,20 +144,20 @@ template class SharedDataFacade final : public BaseDataFacade< shared_memory, storage::SharedDataLayout::TRAVEL_MODE); typename util::ShM::vector travel_mode_list( travel_mode_list_ptr, data_layout->num_entries[storage::SharedDataLayout::TRAVEL_MODE]); - m_travel_mode_list.swap(travel_mode_list); + m_travel_mode_list = std::move(travel_mode_list); auto turn_instruction_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::TURN_INSTRUCTION); typename util::ShM::vector turn_instruction_list( turn_instruction_list_ptr, data_layout->num_entries[storage::SharedDataLayout::TURN_INSTRUCTION]); - m_turn_instruction_list.swap(turn_instruction_list); + m_turn_instruction_list = std::move(turn_instruction_list); auto name_id_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::NAME_ID_LIST); typename util::ShM::vector name_id_list( name_id_list_ptr, data_layout->num_entries[storage::SharedDataLayout::NAME_ID_LIST]); - m_name_ID_list.swap(name_id_list); + m_name_ID_list = std::move(name_id_list); } void LoadViaNodeList() @@ -167,7 +166,7 @@ template class SharedDataFacade final : public BaseDataFacade< shared_memory, storage::SharedDataLayout::VIA_NODE_LIST); typename util::ShM::vector via_node_list( via_node_list_ptr, data_layout->num_entries[storage::SharedDataLayout::VIA_NODE_LIST]); - m_via_node_list.swap(via_node_list); + m_via_node_list = std::move(via_node_list); } void LoadNames() @@ -188,7 +187,7 @@ template class SharedDataFacade final : public BaseDataFacade< m_name_table = util::make_unique>( name_offsets, name_blocks, static_cast(names_char_list.size())); - m_names_char_list.swap(names_char_list); + m_names_char_list = std::move(names_char_list); } void LoadCoreInformation() @@ -202,7 +201,7 @@ template class SharedDataFacade final : public BaseDataFacade< shared_memory, storage::SharedDataLayout::CORE_MARKER); typename util::ShM::vector is_core_node( core_marker_ptr, data_layout->num_entries[storage::SharedDataLayout::CORE_MARKER]); - m_is_core_node.swap(is_core_node); + m_is_core_node = std::move(is_core_node); } void LoadGeometries() @@ -212,21 +211,21 @@ template class SharedDataFacade final : public BaseDataFacade< typename util::ShM::vector edge_is_compressed( geometries_compressed_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDICATORS]); - m_edge_is_compressed.swap(edge_is_compressed); + m_edge_is_compressed = std::move(edge_is_compressed); auto geometries_index_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::GEOMETRIES_INDEX); typename util::ShM::vector geometry_begin_indices( geometries_index_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_INDEX]); - m_geometry_indices.swap(geometry_begin_indices); + m_geometry_indices = std::move(geometry_begin_indices); auto geometries_list_ptr = data_layout->GetBlockPtr( shared_memory, storage::SharedDataLayout::GEOMETRIES_LIST); typename util::ShM::vector geometry_list( geometries_list_ptr, data_layout->num_entries[storage::SharedDataLayout::GEOMETRIES_LIST]); - m_geometry_list.swap(geometry_list); + m_geometry_list = std::move(geometry_list); } public: diff --git a/include/util/range_table.hpp b/include/util/range_table.hpp index e31697b9d..f01234958 100644 --- a/include/util/range_table.hpp +++ b/include/util/range_table.hpp @@ -6,6 +6,7 @@ #include #include +#include namespace osrm { @@ -52,8 +53,9 @@ template class RangeTable const unsigned sum_lengths) : sum_lengths(sum_lengths) { - block_offsets.swap(external_offsets); - diff_blocks.swap(external_blocks); + using std::swap; + swap(block_offsets, external_offsets); + swap(diff_blocks, external_blocks); } // construct table from length vector diff --git a/include/util/shared_memory_vector_wrapper.hpp b/include/util/shared_memory_vector_wrapper.hpp index 6812fffb8..757469029 100644 --- a/include/util/shared_memory_vector_wrapper.hpp +++ b/include/util/shared_memory_vector_wrapper.hpp @@ -55,13 +55,6 @@ template class SharedMemoryWrapper SharedMemoryWrapper(DataT *ptr, std::size_t size) : m_ptr(ptr), m_size(size) {} - void swap(SharedMemoryWrapper &other) - { - // BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid"); - std::swap(m_size, other.m_size); - std::swap(m_ptr, other.m_ptr); - } - DataT &at(const std::size_t index) { return m_ptr[index]; } const DataT &at(const std::size_t index) const { return m_ptr[index]; } @@ -85,6 +78,9 @@ template class SharedMemoryWrapper BOOST_ASSERT_MSG(index < m_size, "invalid size"); return m_ptr[index]; } + + template + friend void swap(SharedMemoryWrapper &, SharedMemoryWrapper &) noexcept; }; template <> class SharedMemoryWrapper @@ -98,13 +94,6 @@ template <> class SharedMemoryWrapper SharedMemoryWrapper(unsigned *ptr, std::size_t size) : m_ptr(ptr), m_size(size) {} - void swap(SharedMemoryWrapper &other) - { - // BOOST_ASSERT_MSG(m_size != 0 || other.size() != 0, "size invalid"); - std::swap(m_size, other.m_size); - std::swap(m_ptr, other.m_ptr); - } - bool at(const std::size_t index) const { const std::size_t bucket = index / 32; @@ -123,8 +112,19 @@ template <> class SharedMemoryWrapper const unsigned offset = index % 32; return m_ptr[bucket] & (1 << offset); } + + template + friend void swap(SharedMemoryWrapper &, SharedMemoryWrapper &) noexcept; }; +// Both SharedMemoryWrapper and the SharedMemoryWrapper specializations share this impl. +template +void swap(SharedMemoryWrapper &lhs, SharedMemoryWrapper &rhs) noexcept +{ + std::swap(lhs.m_ptr, rhs.m_ptr); + std::swap(lhs.m_size, rhs.m_size); +} + template struct ShM { using vector = typename std::conditional class StaticGraph number_of_nodes = static_cast(nodes.size() - 1); number_of_edges = static_cast(edges.size()); - node_array.swap(nodes); - edge_array.swap(edges); + using std::swap; + swap(node_array, nodes); + swap(edge_array, edges); } unsigned GetNumberOfNodes() const { return number_of_nodes; } From b8d20dfe995d7a2697bdc332ea9e35f17e18e835 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 5 Feb 2016 17:54:59 +0100 Subject: [PATCH 139/701] Prevent undefined behavior from left shifting into sign bit when offset is 31 --- include/util/shared_memory_vector_wrapper.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/util/shared_memory_vector_wrapper.hpp b/include/util/shared_memory_vector_wrapper.hpp index 757469029..74f4a8e81 100644 --- a/include/util/shared_memory_vector_wrapper.hpp +++ b/include/util/shared_memory_vector_wrapper.hpp @@ -98,7 +98,7 @@ template <> class SharedMemoryWrapper { const std::size_t bucket = index / 32; const unsigned offset = static_cast(index % 32); - return m_ptr[bucket] & (1 << offset); + return m_ptr[bucket] & (1u << offset); } std::size_t size() const { return m_size; } @@ -110,7 +110,7 @@ template <> class SharedMemoryWrapper BOOST_ASSERT_MSG(index < m_size, "invalid size"); const unsigned bucket = index / 32; const unsigned offset = index % 32; - return m_ptr[bucket] & (1 << offset); + return m_ptr[bucket] & (1u << offset); } template From bb06bfbbd71a45e8e29b542ca5afa328370958b5 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 5 Feb 2016 18:07:51 +0100 Subject: [PATCH 140/701] Same undefined behavior from shifting into the sign bit in Storage --- src/storage/storage.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/storage/storage.cpp b/src/storage/storage.cpp index 833061344..d5439c8c5 100644 --- a/src/storage/storage.cpp +++ b/src/storage/storage.cpp @@ -425,7 +425,7 @@ int Storage::Run() }(); if (current_edge_data.compressed_geometry) { - geometries_indicator_ptr[bucket] = (value | (1 << offset)); + geometries_indicator_ptr[bucket] = (value | (1u << offset)); } } edges_input_stream.close(); @@ -513,7 +513,7 @@ int Storage::Run() return return_value; }(); - core_marker_ptr[bucket] = (value | (1 << offset)); + core_marker_ptr[bucket] = (value | (1u << offset)); } } From 2e762d05f9e8a112df9c578c6ec32fc32d582f95 Mon Sep 17 00:00:00 2001 From: Dane Springmeyer Date: Tue, 9 Feb 2016 17:49:47 -0800 Subject: [PATCH 141/701] Ensure key command line programs can be run before running cucumber tests - Otherwise, currently, if osrm-extract crashes at startup then the tests continue on and will crash many many times. - This also tests that --help returns an exit code of zero and will catch if this behavior ever changes or is inconsistent between the command line programs --- features/support/env.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/features/support/env.rb b/features/support/env.rb index cb707f9e1..94d7d3625 100644 --- a/features/support/env.rb +++ b/features/support/env.rb @@ -76,6 +76,10 @@ def verify_existance_of_binaries unless File.exists? "#{BIN_PATH}/#{bin}#{EXE}" raise "*** #{BIN_PATH}/#{bin}#{EXE} is missing. Build failed?" end + unless system "#{BIN_PATH}/#{bin}#{EXE} --help" + log "*** Exited with code #{$?.exitstatus}.", :preprocess + raise "*** #{BIN_PATH}/#{bin}#{EXE} --help exited with code #{$?.exitstatus}." + end end end From 2949a52a111726d8d5b0f34a3b0355180fed26b5 Mon Sep 17 00:00:00 2001 From: Dane Springmeyer Date: Wed, 10 Feb 2016 12:58:36 -0800 Subject: [PATCH 142/701] remove uneeded and deprecated usage of mapbox::util::static_visitor --- include/util/json_renderer.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/util/json_renderer.hpp b/include/util/json_renderer.hpp index 9f6656053..9569829f0 100644 --- a/include/util/json_renderer.hpp +++ b/include/util/json_renderer.hpp @@ -16,7 +16,7 @@ namespace util namespace json { -struct Renderer : mapbox::util::static_visitor<> +struct Renderer { explicit Renderer(std::ostream &_out) : out(_out) {} @@ -72,7 +72,7 @@ struct Renderer : mapbox::util::static_visitor<> std::ostream &out; }; -struct ArrayRenderer : mapbox::util::static_visitor<> +struct ArrayRenderer { explicit ArrayRenderer(std::vector &_out) : out(_out) {} From c40375a4244970c4e3bef7beae12848e779e2c9e Mon Sep 17 00:00:00 2001 From: Dane Springmeyer Date: Wed, 10 Feb 2016 13:41:22 -0800 Subject: [PATCH 143/701] update libosmium to v2.6.0 --- third_party/libosmium/CHANGELOG.md | 29 +- third_party/libosmium/CMakeLists.txt | 8 +- .../include/osmium/area/assembler.hpp | 4 +- .../osmium/area/detail/node_ref_segment.hpp | 2 +- .../include/osmium/area/detail/proto_ring.hpp | 2 +- .../osmium/area/detail/segment_list.hpp | 2 +- .../osmium/area/multipolygon_collector.hpp | 2 +- .../include/osmium/area/problem_reporter.hpp | 2 +- .../area/problem_reporter_exception.hpp | 2 +- .../osmium/area/problem_reporter_ogr.hpp | 2 +- .../osmium/area/problem_reporter_stream.hpp | 2 +- .../libosmium/include/osmium/builder/attr.hpp | 877 ++ .../include/osmium/builder/builder.hpp | 2 +- .../include/osmium/builder/builder_helper.hpp | 21 +- .../osmium/builder/osm_object_builder.hpp | 14 +- .../libosmium/include/osmium/diff_handler.hpp | 2 +- .../include/osmium/diff_iterator.hpp | 2 +- .../libosmium/include/osmium/diff_visitor.hpp | 2 +- .../include/osmium/dynamic_handler.hpp | 2 +- .../osmium/experimental/flex_reader.hpp | 2 +- third_party/libosmium/include/osmium/fwd.hpp | 2 +- .../include/osmium/geom/coordinates.hpp | 2 +- .../libosmium/include/osmium/geom/factory.hpp | 2 +- .../libosmium/include/osmium/geom/geojson.hpp | 2 +- .../libosmium/include/osmium/geom/geos.hpp | 2 +- .../include/osmium/geom/haversine.hpp | 2 +- .../osmium/geom/mercator_projection.hpp | 2 +- .../libosmium/include/osmium/geom/ogr.hpp | 2 +- .../include/osmium/geom/projection.hpp | 45 +- .../include/osmium/geom/rapid_geojson.hpp | 2 +- .../include/osmium/geom/relations.hpp | 2 +- .../libosmium/include/osmium/geom/tile.hpp | 2 +- .../libosmium/include/osmium/geom/util.hpp | 2 +- .../libosmium/include/osmium/geom/wkb.hpp | 2 +- .../libosmium/include/osmium/geom/wkt.hpp | 2 +- .../libosmium/include/osmium/handler.hpp | 2 +- .../include/osmium/handler/chain.hpp | 2 +- .../include/osmium/handler/check_order.hpp | 136 + .../include/osmium/handler/disk_store.hpp | 2 +- .../libosmium/include/osmium/handler/dump.hpp | 2 +- .../handler/node_locations_for_ways.hpp | 2 +- .../osmium/handler/object_relations.hpp | 2 +- .../include/osmium/index/bool_vector.hpp | 2 +- .../index/detail/create_map_with_fd.hpp | 2 +- .../osmium/index/detail/mmap_vector_anon.hpp | 2 +- .../osmium/index/detail/mmap_vector_base.hpp | 2 +- .../osmium/index/detail/mmap_vector_file.hpp | 2 +- .../include/osmium/index/detail/tmpfile.hpp | 2 +- .../osmium/index/detail/vector_map.hpp | 2 +- .../osmium/index/detail/vector_multimap.hpp | 2 +- .../libosmium/include/osmium/index/index.hpp | 2 +- .../libosmium/include/osmium/index/map.hpp | 2 +- .../include/osmium/index/map/all.hpp | 2 +- .../osmium/index/map/dense_file_array.hpp | 2 +- .../osmium/index/map/dense_mem_array.hpp | 2 +- .../osmium/index/map/dense_mmap_array.hpp | 2 +- .../include/osmium/index/map/dummy.hpp | 2 +- .../osmium/index/map/sparse_file_array.hpp | 2 +- .../osmium/index/map/sparse_mem_array.hpp | 2 +- .../osmium/index/map/sparse_mem_map.hpp | 2 +- .../osmium/index/map/sparse_mem_table.hpp | 2 +- .../osmium/index/map/sparse_mmap_array.hpp | 2 +- .../include/osmium/index/multimap.hpp | 2 +- .../include/osmium/index/multimap/all.hpp | 2 +- .../include/osmium/index/multimap/hybrid.hpp | 2 +- .../index/multimap/sparse_file_array.hpp | 2 +- .../index/multimap/sparse_mem_array.hpp | 2 +- .../index/multimap/sparse_mem_multimap.hpp | 2 +- .../index/multimap/sparse_mmap_array.hpp | 2 +- .../osmium/index/node_locations_map.hpp | 2 +- .../include/osmium/io/any_compression.hpp | 2 +- .../libosmium/include/osmium/io/any_input.hpp | 2 +- .../include/osmium/io/any_output.hpp | 2 +- .../include/osmium/io/bzip2_compression.hpp | 2 +- .../include/osmium/io/compression.hpp | 2 +- .../include/osmium/io/debug_output.hpp | 2 +- .../osmium/io/detail/debug_output_format.hpp | 2 +- .../include/osmium/io/detail/input_format.hpp | 2 +- .../osmium/io/detail/o5m_input_format.hpp | 2 +- .../osmium/io/detail/opl_output_format.hpp | 2 +- .../osmium/io/detail/output_format.hpp | 2 +- .../include/osmium/io/detail/pbf.hpp | 2 +- .../include/osmium/io/detail/pbf_decoder.hpp | 2 +- .../osmium/io/detail/pbf_input_format.hpp | 2 +- .../osmium/io/detail/pbf_output_format.hpp | 2 +- .../osmium/io/detail/protobuf_tags.hpp | 2 +- .../include/osmium/io/detail/queue_util.hpp | 2 +- .../include/osmium/io/detail/read_thread.hpp | 2 +- .../include/osmium/io/detail/read_write.hpp | 2 +- .../include/osmium/io/detail/string_table.hpp | 2 +- .../include/osmium/io/detail/string_util.hpp | 7 +- .../include/osmium/io/detail/write_thread.hpp | 2 +- .../osmium/io/detail/xml_input_format.hpp | 2 +- .../osmium/io/detail/xml_output_format.hpp | 2 +- .../include/osmium/io/detail/zlib.hpp | 2 +- .../libosmium/include/osmium/io/error.hpp | 2 +- .../libosmium/include/osmium/io/file.hpp | 2 +- .../include/osmium/io/file_compression.hpp | 2 +- .../include/osmium/io/file_format.hpp | 2 +- .../include/osmium/io/gzip_compression.hpp | 2 +- .../libosmium/include/osmium/io/header.hpp | 2 +- .../include/osmium/io/input_iterator.hpp | 2 +- .../libosmium/include/osmium/io/o5m_input.hpp | 2 +- .../include/osmium/io/opl_output.hpp | 2 +- .../include/osmium/io/output_iterator.hpp | 2 +- .../libosmium/include/osmium/io/overwrite.hpp | 2 +- .../libosmium/include/osmium/io/pbf_input.hpp | 2 +- .../include/osmium/io/pbf_output.hpp | 2 +- .../libosmium/include/osmium/io/reader.hpp | 2 +- .../include/osmium/io/reader_iterator.hpp | 2 +- .../libosmium/include/osmium/io/writer.hpp | 2 +- .../include/osmium/io/writer_options.hpp | 2 +- .../libosmium/include/osmium/io/xml_input.hpp | 2 +- .../include/osmium/io/xml_output.hpp | 2 +- .../include/osmium/memory/buffer.hpp | 42 +- .../include/osmium/memory/collection.hpp | 12 +- .../libosmium/include/osmium/memory/item.hpp | 2 +- .../include/osmium/memory/item_iterator.hpp | 12 +- .../osmium/object_pointer_collection.hpp | 2 +- third_party/libosmium/include/osmium/osm.hpp | 2 +- .../libosmium/include/osmium/osm/area.hpp | 2 +- .../libosmium/include/osmium/osm/box.hpp | 13 +- .../include/osmium/osm/changeset.hpp | 2 +- .../libosmium/include/osmium/osm/crc.hpp | 2 +- .../include/osmium/osm/diff_object.hpp | 2 +- .../libosmium/include/osmium/osm/entity.hpp | 2 +- .../include/osmium/osm/entity_bits.hpp | 2 +- .../include/osmium/osm/item_type.hpp | 2 +- .../libosmium/include/osmium/osm/location.hpp | 2 +- .../libosmium/include/osmium/osm/node.hpp | 2 +- .../libosmium/include/osmium/osm/node_ref.hpp | 2 +- .../include/osmium/osm/node_ref_list.hpp | 2 +- .../libosmium/include/osmium/osm/object.hpp | 2 +- .../include/osmium/osm/object_comparisons.hpp | 2 +- .../libosmium/include/osmium/osm/relation.hpp | 2 +- .../libosmium/include/osmium/osm/segment.hpp | 2 +- .../libosmium/include/osmium/osm/tag.hpp | 2 +- .../include/osmium/osm/timestamp.hpp | 17 +- .../libosmium/include/osmium/osm/types.hpp | 2 +- .../include/osmium/osm/types_from_string.hpp | 2 +- .../include/osmium/osm/undirected_segment.hpp | 2 +- .../libosmium/include/osmium/osm/way.hpp | 2 +- .../include/osmium/relations/collector.hpp | 2 +- .../osmium/relations/detail/member_meta.hpp | 2 +- .../osmium/relations/detail/relation_meta.hpp | 2 +- .../libosmium/include/osmium/tags/filter.hpp | 2 +- .../include/osmium/tags/regex_filter.hpp | 2 +- .../libosmium/include/osmium/tags/taglist.hpp | 2 +- .../osmium/thread/function_wrapper.hpp | 2 +- .../libosmium/include/osmium/thread/pool.hpp | 2 +- .../libosmium/include/osmium/thread/queue.hpp | 2 +- .../include/osmium/thread/sorted_queue.hpp | 2 +- .../libosmium/include/osmium/thread/util.hpp | 2 +- .../libosmium/include/osmium/util/cast.hpp | 2 +- .../include/osmium/util/compatibility.hpp | 2 +- .../libosmium/include/osmium/util/config.hpp | 2 +- .../libosmium/include/osmium/util/delta.hpp | 2 +- .../libosmium/include/osmium/util/double.hpp | 2 +- .../libosmium/include/osmium/util/endian.hpp | 2 +- .../libosmium/include/osmium/util/file.hpp | 2 +- .../libosmium/include/osmium/util/memory.hpp | 99 + .../include/osmium/util/memory_mapping.hpp | 2 +- .../libosmium/include/osmium/util/minmax.hpp | 2 +- .../libosmium/include/osmium/util/options.hpp | 2 +- .../libosmium/include/osmium/util/string.hpp | 2 +- .../include/osmium/util/verbose_output.hpp | 17 +- .../libosmium/include/osmium/visitor.hpp | 2 +- third_party/libosmium/test/CMakeLists.txt | 184 - third_party/libosmium/test/README | 13 - .../libosmium/test/data-tests/.gitignore | 1 - .../libosmium/test/data-tests/CMakeLists.txt | 118 - .../libosmium/test/data-tests/README.md | 10 - .../include/check_basics_handler.hpp | 92 - .../data-tests/include/check_wkt_handler.hpp | 86 - .../test/data-tests/include/common.hpp | 22 - .../data-tests/include/testdata-testcases.hpp | 10 - .../test/data-tests/multipolygon.qgs | 880 -- .../run-testdata-multipolygon.cmake | 46 - .../test/data-tests/testcases/test-100.cpp | 41 - .../test/data-tests/testcases/test-101.cpp | 43 - .../test/data-tests/testcases/test-110.cpp | 58 - .../test/data-tests/testdata-multipolygon.cpp | 182 - .../test/data-tests/testdata-overview.cpp | 101 - .../test/data-tests/testdata-testcases.cpp | 25 - .../test/data-tests/testdata-xml.cpp | 561 - third_party/libosmium/test/include/catch.hpp | 9416 ----------------- .../libosmium/test/include/catch_orig.hpp | 9416 ----------------- third_party/libosmium/test/include/utils.hpp | 18 - .../libosmium/test/include/win_mkstemp.hpp | 42 - .../libosmium/test/t/area/test_area_id.cpp | 25 - .../test/t/area/test_node_ref_segment.cpp | 129 - third_party/libosmium/test/t/basic/helper.hpp | 103 - .../libosmium/test/t/basic/test_box.cpp | 98 - .../libosmium/test/t/basic/test_changeset.cpp | 123 - .../libosmium/test/t/basic/test_crc.cpp | 70 - .../test/t/basic/test_entity_bits.cpp | 31 - .../libosmium/test/t/basic/test_location.cpp | 154 - .../libosmium/test/t/basic/test_node.cpp | 125 - .../libosmium/test/t/basic/test_node_ref.cpp | 57 - .../test/t/basic/test_object_comparisons.cpp | 147 - .../libosmium/test/t/basic/test_relation.cpp | 76 - .../libosmium/test/t/basic/test_timestamp.cpp | 77 - .../test/t/basic/test_types_from_string.cpp | 90 - .../libosmium/test/t/basic/test_way.cpp | 90 - .../test/t/buffer/test_buffer_basics.cpp | 34 - .../test/t/buffer/test_buffer_node.cpp | 199 - .../test/t/buffer/test_buffer_purge.cpp | 186 - third_party/libosmium/test/t/geom/helper.hpp | 15 - .../libosmium/test/t/geom/test_exception.cpp | 16 - .../t/geom/test_factory_with_projection.cpp | 41 - .../libosmium/test/t/geom/test_geojson.cpp | 236 - .../libosmium/test/t/geom/test_geos.cpp | 205 - .../libosmium/test/t/geom/test_geos_wkb.cpp | 156 - .../libosmium/test/t/geom/test_mercator.cpp | 37 - .../libosmium/test/t/geom/test_ogr.cpp | 185 - .../libosmium/test/t/geom/test_projection.cpp | 149 - .../libosmium/test/t/geom/test_tile.cpp | 93 - .../libosmium/test/t/geom/test_tile_data.hpp | 477 - .../libosmium/test/t/geom/test_wkb.cpp | 133 - .../libosmium/test/t/geom/test_wkt.cpp | 206 - .../test/t/index/test_id_to_location.cpp | 170 - third_party/libosmium/test/t/io/data.osm | 4 - third_party/libosmium/test/t/io/data.osm.bz2 | Bin 200 -> 0 bytes third_party/libosmium/test/t/io/data.osm.gz | Bin 187 -> 0 bytes .../libosmium/test/t/io/data_bzip2.txt | 1 - .../libosmium/test/t/io/data_bzip2.txt.bz2 | Bin 45 -> 0 bytes .../libosmium/test/t/io/deleted_nodes.osh | 5 - .../libosmium/test/t/io/deleted_nodes.osh.pbf | Bin 189 -> 0 bytes .../libosmium/test/t/io/test_bzip2.cpp | 33 - .../libosmium/test/t/io/test_file_formats.cpp | 275 - .../test/t/io/test_output_iterator.cpp | 37 - .../libosmium/test/t/io/test_output_utils.cpp | 153 - .../libosmium/test/t/io/test_reader.cpp | 212 - .../test_reader_with_mock_decompression.cpp | 145 - .../t/io/test_reader_with_mock_parser.cpp | 123 - .../libosmium/test/t/io/test_string_table.cpp | 94 - .../libosmium/test/t/io/test_writer.cpp | 117 - .../io/test_writer_with_mock_compression.cpp | 99 - .../t/io/test_writer_with_mock_encoder.cpp | 105 - .../libosmium/test/t/tags/test_filter.cpp | 216 - .../libosmium/test/t/tags/test_operators.cpp | 61 - .../libosmium/test/t/tags/test_tag_list.cpp | 113 - .../libosmium/test/t/thread/test_pool.cpp | 72 - .../test/t/util/test_cast_with_assert.cpp | 89 - .../libosmium/test/t/util/test_delta.cpp | 94 - .../libosmium/test/t/util/test_double.cpp | 33 - .../libosmium/test/t/util/test_file.cpp | 71 - .../test/t/util/test_memory_mapping.cpp | 419 - .../libosmium/test/t/util/test_minmax.cpp | 68 - .../libosmium/test/t/util/test_options.cpp | 81 - .../libosmium/test/t/util/test_string.cpp | 68 - third_party/libosmium/test/test_main.cpp | 2 - third_party/libosmium/test/valgrind.supp | 47 - 253 files changed, 1431 insertions(+), 28359 deletions(-) create mode 100644 third_party/libosmium/include/osmium/builder/attr.hpp create mode 100644 third_party/libosmium/include/osmium/handler/check_order.hpp create mode 100644 third_party/libosmium/include/osmium/util/memory.hpp delete mode 100644 third_party/libosmium/test/CMakeLists.txt delete mode 100644 third_party/libosmium/test/README delete mode 100644 third_party/libosmium/test/data-tests/.gitignore delete mode 100644 third_party/libosmium/test/data-tests/CMakeLists.txt delete mode 100644 third_party/libosmium/test/data-tests/README.md delete mode 100644 third_party/libosmium/test/data-tests/include/check_basics_handler.hpp delete mode 100644 third_party/libosmium/test/data-tests/include/check_wkt_handler.hpp delete mode 100644 third_party/libosmium/test/data-tests/include/common.hpp delete mode 100644 third_party/libosmium/test/data-tests/include/testdata-testcases.hpp delete mode 100644 third_party/libosmium/test/data-tests/multipolygon.qgs delete mode 100644 third_party/libosmium/test/data-tests/run-testdata-multipolygon.cmake delete mode 100644 third_party/libosmium/test/data-tests/testcases/test-100.cpp delete mode 100644 third_party/libosmium/test/data-tests/testcases/test-101.cpp delete mode 100644 third_party/libosmium/test/data-tests/testcases/test-110.cpp delete mode 100644 third_party/libosmium/test/data-tests/testdata-multipolygon.cpp delete mode 100644 third_party/libosmium/test/data-tests/testdata-overview.cpp delete mode 100644 third_party/libosmium/test/data-tests/testdata-testcases.cpp delete mode 100644 third_party/libosmium/test/data-tests/testdata-xml.cpp delete mode 100644 third_party/libosmium/test/include/catch.hpp delete mode 100644 third_party/libosmium/test/include/catch_orig.hpp delete mode 100644 third_party/libosmium/test/include/utils.hpp delete mode 100644 third_party/libosmium/test/include/win_mkstemp.hpp delete mode 100644 third_party/libosmium/test/t/area/test_area_id.cpp delete mode 100644 third_party/libosmium/test/t/area/test_node_ref_segment.cpp delete mode 100644 third_party/libosmium/test/t/basic/helper.hpp delete mode 100644 third_party/libosmium/test/t/basic/test_box.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_changeset.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_crc.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_entity_bits.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_location.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_node.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_node_ref.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_object_comparisons.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_relation.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_timestamp.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_types_from_string.cpp delete mode 100644 third_party/libosmium/test/t/basic/test_way.cpp delete mode 100644 third_party/libosmium/test/t/buffer/test_buffer_basics.cpp delete mode 100644 third_party/libosmium/test/t/buffer/test_buffer_node.cpp delete mode 100644 third_party/libosmium/test/t/buffer/test_buffer_purge.cpp delete mode 100644 third_party/libosmium/test/t/geom/helper.hpp delete mode 100644 third_party/libosmium/test/t/geom/test_exception.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_factory_with_projection.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_geojson.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_geos.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_geos_wkb.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_mercator.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_ogr.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_projection.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_tile.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_tile_data.hpp delete mode 100644 third_party/libosmium/test/t/geom/test_wkb.cpp delete mode 100644 third_party/libosmium/test/t/geom/test_wkt.cpp delete mode 100644 third_party/libosmium/test/t/index/test_id_to_location.cpp delete mode 100644 third_party/libosmium/test/t/io/data.osm delete mode 100644 third_party/libosmium/test/t/io/data.osm.bz2 delete mode 100644 third_party/libosmium/test/t/io/data.osm.gz delete mode 100644 third_party/libosmium/test/t/io/data_bzip2.txt delete mode 100644 third_party/libosmium/test/t/io/data_bzip2.txt.bz2 delete mode 100644 third_party/libosmium/test/t/io/deleted_nodes.osh delete mode 100644 third_party/libosmium/test/t/io/deleted_nodes.osh.pbf delete mode 100644 third_party/libosmium/test/t/io/test_bzip2.cpp delete mode 100644 third_party/libosmium/test/t/io/test_file_formats.cpp delete mode 100644 third_party/libosmium/test/t/io/test_output_iterator.cpp delete mode 100644 third_party/libosmium/test/t/io/test_output_utils.cpp delete mode 100644 third_party/libosmium/test/t/io/test_reader.cpp delete mode 100644 third_party/libosmium/test/t/io/test_reader_with_mock_decompression.cpp delete mode 100644 third_party/libosmium/test/t/io/test_reader_with_mock_parser.cpp delete mode 100644 third_party/libosmium/test/t/io/test_string_table.cpp delete mode 100644 third_party/libosmium/test/t/io/test_writer.cpp delete mode 100644 third_party/libosmium/test/t/io/test_writer_with_mock_compression.cpp delete mode 100644 third_party/libosmium/test/t/io/test_writer_with_mock_encoder.cpp delete mode 100644 third_party/libosmium/test/t/tags/test_filter.cpp delete mode 100644 third_party/libosmium/test/t/tags/test_operators.cpp delete mode 100644 third_party/libosmium/test/t/tags/test_tag_list.cpp delete mode 100644 third_party/libosmium/test/t/thread/test_pool.cpp delete mode 100644 third_party/libosmium/test/t/util/test_cast_with_assert.cpp delete mode 100644 third_party/libosmium/test/t/util/test_delta.cpp delete mode 100644 third_party/libosmium/test/t/util/test_double.cpp delete mode 100644 third_party/libosmium/test/t/util/test_file.cpp delete mode 100644 third_party/libosmium/test/t/util/test_memory_mapping.cpp delete mode 100644 third_party/libosmium/test/t/util/test_minmax.cpp delete mode 100644 third_party/libosmium/test/t/util/test_options.cpp delete mode 100644 third_party/libosmium/test/t/util/test_string.cpp delete mode 100644 third_party/libosmium/test/test_main.cpp delete mode 100644 third_party/libosmium/test/valgrind.supp diff --git a/third_party/libosmium/CHANGELOG.md b/third_party/libosmium/CHANGELOG.md index e9377b656..2ca6518c8 100644 --- a/third_party/libosmium/CHANGELOG.md +++ b/third_party/libosmium/CHANGELOG.md @@ -13,6 +13,32 @@ This project adheres to [Semantic Versioning](http://semver.org/). ### Fixed +## [2.6.0] - 2016-02-04 + +### Added + +- The new handler osmium::handler::CheckOrder can be used to check that a + file is properly ordered. +- Add new method to build OSM nodes, ways, relations, changesets, and areas + in buffers that wraps the older Builder classes. The new code is much easier + to use and very flexible. There is no documentation yet, but the tests in + `test/t/builder/test_attr.cpp` can give you an idea how it works. +- Add util class to get memory usage of current process on Linux. + +### Changed + +- New Buffer memory management speeds up Buffer use, because it doesn't clear + the memory unnecessarily. + +### Fixed + +- osmium::Box::extend() function now ignores invalid locations. +- Install of external library headers. +- Check way has at least one node before calling `is_closed()` in area + assembler. +- Declaration/definition of some friend functions was in the wrong namespace. + + ## [2.5.4] - 2015-12-03 ### Changed @@ -234,7 +260,8 @@ This project adheres to [Semantic Versioning](http://semver.org/). Doxygen (up to version 1.8.8). This version contains a workaround to fix this. -[unreleased]: https://github.com/osmcode/libosmium/compare/v2.5.4...HEAD +[unreleased]: https://github.com/osmcode/libosmium/compare/v2.6.0...HEAD +[2.6.0]: https://github.com/osmcode/libosmium/compare/v2.5.4...v2.6.0 [2.5.4]: https://github.com/osmcode/libosmium/compare/v2.5.3...v2.5.4 [2.5.3]: https://github.com/osmcode/libosmium/compare/v2.5.2...v2.5.3 [2.5.2]: https://github.com/osmcode/libosmium/compare/v2.5.1...v2.5.2 diff --git a/third_party/libosmium/CMakeLists.txt b/third_party/libosmium/CMakeLists.txt index 0764915ea..73394674e 100644 --- a/third_party/libosmium/CMakeLists.txt +++ b/third_party/libosmium/CMakeLists.txt @@ -24,8 +24,8 @@ set(CMAKE_CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo;MinSizeRel;Dev;Cover project(libosmium) set(LIBOSMIUM_VERSION_MAJOR 2) -set(LIBOSMIUM_VERSION_MINOR 5) -set(LIBOSMIUM_VERSION_PATCH 4) +set(LIBOSMIUM_VERSION_MINOR 6) +set(LIBOSMIUM_VERSION_PATCH 0) set(LIBOSMIUM_VERSION "${LIBOSMIUM_VERSION_MAJOR}.${LIBOSMIUM_VERSION_MINOR}.${LIBOSMIUM_VERSION_PATCH}") @@ -459,7 +459,7 @@ endif() install(DIRECTORY include/osmium DESTINATION include) if(INSTALL_GDALCPP) - install(include/gdalcpp.hpp DESTINATION include) + install(FILES include/gdalcpp.hpp DESTINATION include) endif() if(INSTALL_PROTOZERO) @@ -467,7 +467,7 @@ if(INSTALL_PROTOZERO) endif() if(INSTALL_UTFCPP) - install(include/utf8.hpp DESTINATION include) + install(FILES include/utf8.h DESTINATION include) install(DIRECTORY include/utf8 DESTINATION include) endif() diff --git a/third_party/libosmium/include/osmium/area/assembler.hpp b/third_party/libosmium/include/osmium/area/assembler.hpp index 87feea29e..1d9b0df6b 100644 --- a/third_party/libosmium/include/osmium/area/assembler.hpp +++ b/third_party/libosmium/include/osmium/area/assembler.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -753,7 +753,7 @@ namespace osmium { for (size_t offset : members) { if (!std::strcmp(memit->role(), "inner")) { const osmium::Way& way = in_buffer.get(offset); - if (way.is_closed() && way.tags().size() > 0) { + if (!way.nodes().empty() && way.is_closed() && way.tags().size() > 0) { auto d = std::count_if(way.tags().begin(), way.tags().end(), filter()); if (d > 0) { osmium::tags::KeyFilter::iterator way_fi_begin(filter(), way.tags().begin(), way.tags().end()); diff --git a/third_party/libosmium/include/osmium/area/detail/node_ref_segment.hpp b/third_party/libosmium/include/osmium/area/detail/node_ref_segment.hpp index aab5b8fa3..7c1555a33 100644 --- a/third_party/libosmium/include/osmium/area/detail/node_ref_segment.hpp +++ b/third_party/libosmium/include/osmium/area/detail/node_ref_segment.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/area/detail/proto_ring.hpp b/third_party/libosmium/include/osmium/area/detail/proto_ring.hpp index 162e2896d..59478dc63 100644 --- a/third_party/libosmium/include/osmium/area/detail/proto_ring.hpp +++ b/third_party/libosmium/include/osmium/area/detail/proto_ring.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/area/detail/segment_list.hpp b/third_party/libosmium/include/osmium/area/detail/segment_list.hpp index 289ecf0c9..29eec589c 100644 --- a/third_party/libosmium/include/osmium/area/detail/segment_list.hpp +++ b/third_party/libosmium/include/osmium/area/detail/segment_list.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/area/multipolygon_collector.hpp b/third_party/libosmium/include/osmium/area/multipolygon_collector.hpp index 2881597b0..81a28b24b 100644 --- a/third_party/libosmium/include/osmium/area/multipolygon_collector.hpp +++ b/third_party/libosmium/include/osmium/area/multipolygon_collector.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/area/problem_reporter.hpp b/third_party/libosmium/include/osmium/area/problem_reporter.hpp index 4ae4bb23d..1dde85ba9 100644 --- a/third_party/libosmium/include/osmium/area/problem_reporter.hpp +++ b/third_party/libosmium/include/osmium/area/problem_reporter.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/area/problem_reporter_exception.hpp b/third_party/libosmium/include/osmium/area/problem_reporter_exception.hpp index 7c9a5e393..abadd9653 100644 --- a/third_party/libosmium/include/osmium/area/problem_reporter_exception.hpp +++ b/third_party/libosmium/include/osmium/area/problem_reporter_exception.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/area/problem_reporter_ogr.hpp b/third_party/libosmium/include/osmium/area/problem_reporter_ogr.hpp index 68fae3bb8..d58fe559c 100644 --- a/third_party/libosmium/include/osmium/area/problem_reporter_ogr.hpp +++ b/third_party/libosmium/include/osmium/area/problem_reporter_ogr.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/area/problem_reporter_stream.hpp b/third_party/libosmium/include/osmium/area/problem_reporter_stream.hpp index b6a004cdf..ffd94a605 100644 --- a/third_party/libosmium/include/osmium/area/problem_reporter_stream.hpp +++ b/third_party/libosmium/include/osmium/area/problem_reporter_stream.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/builder/attr.hpp b/third_party/libosmium/include/osmium/builder/attr.hpp new file mode 100644 index 000000000..d9831c28f --- /dev/null +++ b/third_party/libosmium/include/osmium/builder/attr.hpp @@ -0,0 +1,877 @@ +#ifndef OSMIUM_BUILDER_ATTR_HPP +#define OSMIUM_BUILDER_ATTR_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2016 Jochen Topf 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace osmium { + + namespace builder { + + namespace detail { + +#ifdef _MSC_VER + // workaround for bug in MSVC + + template + struct is_handled_by; + + template + struct is_handled_by { + static constexpr bool value = false; + }; + + template + struct is_handled_by { + static constexpr bool value = std::is_base_of::value || + is_handled_by::value; + }; + + template + struct are_all_handled_by; + + template + struct are_all_handled_by { + static constexpr bool value = std::is_base_of::value; + }; + + template + struct are_all_handled_by { + static constexpr bool value = std::is_base_of::value && + are_all_handled_by::value; + }; +#else + // True if Predicate matches for none of the types Ts + template class Predicate, typename... Ts> + struct static_none_of : std::is_same::type...>, + std::tuple::type..., std::false_type>> + {}; + + // True if Predicate matches for all of the types Ts + template class Predicate, typename... Ts> + struct static_all_of : std::is_same::type...>, + std::tuple::type..., std::true_type>> + {}; + + // True if THandler is derived from the handler for at least one of the types in TTypes + template + struct is_handled_by { + template + using HasHandler = std::is_base_of; + + static constexpr bool value = !static_none_of::value; + }; + + // True if THandler is derived from the handlers of all the types in TTypes + template + struct are_all_handled_by { + template + using HasHandler = std::is_base_of; + + static constexpr bool value = static_all_of::value; + }; +#endif + + + // Wraps any type, so that we can derive from it + template + struct type_wrapper { + + using type = TType; + + TType value; + + constexpr explicit type_wrapper(const TType& v) : + value(v) { + } + + }; // struct type_wrapper + + // Small wrapper for begin/end iterator + template + struct iterator_wrapper { + + using type = TType; + + TType first; + TType last; + + constexpr iterator_wrapper(TType begin, TType end) : + first(begin), + last(end) {} + + constexpr TType begin() const { + return first; + } + + constexpr TType end() const { + return last; + } + + }; // struct iterator_wrapper + + + struct entity_handler {}; + struct object_handler; + struct node_handler; + struct tags_handler; + struct nodes_handler; + struct members_handler; + struct changeset_handler; + struct discussion_handler; + struct ring_handler; + + } // namespace detail + +#define OSMIUM_ATTRIBUTE(_handler, _name, _type) \ + struct _name : public osmium::builder::detail::type_wrapper<_type> { \ + using handler = osmium::builder::detail::_handler; + +#define OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(_handler, _name, _type) \ + OSMIUM_ATTRIBUTE(_handler, _name, _type) \ + constexpr explicit _name(std::add_const<_type>::type& value) : \ + type_wrapper(value) {} \ + } + +#define OSMIUM_ATTRIBUTE_ITER(_handler, _name) \ + template \ + struct _name : public osmium::builder::detail::iterator_wrapper { \ + using handler = osmium::builder::detail::_handler; \ + constexpr _name(TIterator first, TIterator last) : \ + osmium::builder::detail::iterator_wrapper(first, last) {} \ + } + + namespace attr { + + OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(object_handler, _id, osmium::object_id_type); + OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(object_handler, _version, osmium::object_version_type); + OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(entity_handler, _uid, osmium::user_id_type); + OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(entity_handler, _cid, osmium::changeset_id_type); + + OSMIUM_ATTRIBUTE(object_handler, _deleted, bool) + constexpr explicit _deleted(bool value = true) noexcept : + type_wrapper(value) {} + }; + + OSMIUM_ATTRIBUTE(object_handler, _visible, bool) + constexpr explicit _visible(bool value = true) noexcept : + type_wrapper(value) {} + }; + + OSMIUM_ATTRIBUTE(object_handler, _timestamp, osmium::Timestamp) + constexpr explicit _timestamp(const osmium::Timestamp& value) noexcept : + type_wrapper(value) {} + constexpr explicit _timestamp(time_t value) noexcept : + type_wrapper(osmium::Timestamp{value}) {} + constexpr explicit _timestamp(uint32_t value) noexcept : + type_wrapper(osmium::Timestamp{value}) {} + explicit _timestamp(const char* value) : + type_wrapper(osmium::Timestamp{value}) {} + explicit _timestamp(const std::string& value) : + type_wrapper(osmium::Timestamp{value}) {} + }; + + OSMIUM_ATTRIBUTE(node_handler, _location, osmium::Location) + constexpr explicit _location(const osmium::Location& value) noexcept : + type_wrapper(value) {} + explicit _location(double lat, double lon) : + type_wrapper(osmium::Location{lat, lon}) {} + }; + + OSMIUM_ATTRIBUTE(entity_handler, _user, const char*) + constexpr explicit _user(const char* val) noexcept : + type_wrapper(val) {} + explicit _user(const std::string& val) noexcept : + type_wrapper(val.c_str()) {} + }; + + using pair_of_cstrings = std::pair; + using pair_of_strings = std::pair; + + class member_type { + + osmium::item_type m_type; + osmium::object_id_type m_ref; + const char* m_role; + + public: + + constexpr member_type(osmium::item_type type, osmium::object_id_type ref, const char* role = "") noexcept : + m_type(type), + m_ref(ref), + m_role(role) { + } + + constexpr osmium::item_type type() const noexcept { + return m_type; + } + + constexpr osmium::object_id_type ref() const noexcept { + return m_ref; + } + + constexpr const char* role() const noexcept { + return m_role; + } + + }; // class member_type + + class comment_type { + + osmium::Timestamp m_date; + osmium::user_id_type m_uid; + const char* m_user; + const char* m_text; + + public: + + constexpr comment_type(osmium::Timestamp date, osmium::user_id_type uid, const char* user, const char* text) noexcept : + m_date(date), + m_uid(uid), + m_user(user), + m_text(text) { + } + + constexpr osmium::Timestamp date() const noexcept { + return m_date; + } + + constexpr osmium::user_id_type uid() const noexcept { + return m_uid; + } + + constexpr const char* user() const noexcept { + return m_user; + } + + constexpr const char* text() const noexcept { + return m_text; + } + + }; // class comment_type + + namespace detail { + + OSMIUM_ATTRIBUTE_ITER(tags_handler, tags_from_iterator_pair); + + OSMIUM_ATTRIBUTE_ITER(nodes_handler, nodes_from_iterator_pair); + + OSMIUM_ATTRIBUTE_ITER(members_handler, members_from_iterator_pair); + + OSMIUM_ATTRIBUTE_ITER(discussion_handler, comments_from_iterator_pair); + + OSMIUM_ATTRIBUTE_ITER(ring_handler, outer_ring_from_iterator_pair); + OSMIUM_ATTRIBUTE_ITER(ring_handler, inner_ring_from_iterator_pair); + + } // namespace detail + + OSMIUM_ATTRIBUTE(tags_handler, _tag, pair_of_cstrings) + explicit _tag(const pair_of_cstrings& value) noexcept : + type_wrapper(value) {} + explicit _tag(const std::pair& value) : + type_wrapper(pair_of_cstrings{value.first, value.second}) {} + explicit _tag(const std::pair& value) : + type_wrapper(pair_of_cstrings{value.first, value.second}) {} + explicit _tag(const std::pair& value) : + type_wrapper(pair_of_cstrings{value.first, value.second}) {} + explicit _tag(const pair_of_strings& value) : + type_wrapper(std::make_pair(value.first.c_str(), value.second.c_str())) {} + explicit _tag(const char* key, const char* val) : + type_wrapper(std::make_pair(key, val)) {} + explicit _tag(const std::string& key, const std::string& val) : + type_wrapper(std::make_pair(key.c_str(), val.c_str())) {} + }; + + template + inline constexpr detail::tags_from_iterator_pair _tags(TTagIterator first, TTagIterator last) { + return detail::tags_from_iterator_pair(first, last); + } + + template + inline detail::tags_from_iterator_pair _tags(const TContainer& container) { + return detail::tags_from_iterator_pair(std::begin(container), std::end(container)); + } + + using tag_ilist = std::initializer_list>; + inline detail::tags_from_iterator_pair _tags(const tag_ilist& container) { + return detail::tags_from_iterator_pair(std::begin(container), std::end(container)); + } + + + + OSMIUM_ATTRIBUTE(nodes_handler, _node, osmium::NodeRef) + constexpr explicit _node(osmium::object_id_type value) noexcept : + type_wrapper(NodeRef{value}) {} + constexpr explicit _node(const NodeRef& value) noexcept : + type_wrapper(value) {} + }; + + template + inline constexpr detail::nodes_from_iterator_pair _nodes(TIdIterator first, TIdIterator last) { + return detail::nodes_from_iterator_pair(first, last); + } + + template + inline detail::nodes_from_iterator_pair _nodes(const TContainer& container) { + return detail::nodes_from_iterator_pair(std::begin(container), std::end(container)); + } + + using object_id_ilist = std::initializer_list; + inline detail::nodes_from_iterator_pair _nodes(const object_id_ilist& container) { + return detail::nodes_from_iterator_pair(std::begin(container), std::end(container)); + } + + using node_ref_ilist = std::initializer_list; + inline detail::nodes_from_iterator_pair _nodes(const node_ref_ilist& container) { + return detail::nodes_from_iterator_pair(std::begin(container), std::end(container)); + } + + + OSMIUM_ATTRIBUTE(members_handler, _member, member_type) + constexpr explicit _member(const member_type& value) noexcept : + type_wrapper(value) {} + constexpr explicit _member(osmium::item_type type, osmium::object_id_type id) noexcept : + type_wrapper({type, id}) {} + constexpr explicit _member(osmium::item_type type, osmium::object_id_type id, const char* role) noexcept : + type_wrapper({type, id, role}) {} + explicit _member(osmium::item_type type, osmium::object_id_type id, const std::string& role) noexcept : + type_wrapper({type, id, role.c_str()}) {} + explicit _member(const osmium::RelationMember& member) noexcept : + type_wrapper({member.type(), member.ref(), member.role()}) {} + }; + + template + inline constexpr detail::members_from_iterator_pair _members(TMemberIterator first, TMemberIterator last) { + return detail::members_from_iterator_pair(first, last); + } + + template + inline detail::members_from_iterator_pair _members(const TContainer& container) { + return detail::members_from_iterator_pair(std::begin(container), std::end(container)); + } + + using member_ilist = std::initializer_list; + inline detail::members_from_iterator_pair _members(const member_ilist& container) { + return detail::members_from_iterator_pair(std::begin(container), std::end(container)); + } + + + OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(changeset_handler, _num_changes, osmium::num_changes_type); + OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(changeset_handler, _num_comments, osmium::num_comments_type); + OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(changeset_handler, _created_at, osmium::Timestamp); + OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR(changeset_handler, _closed_at, osmium::Timestamp); + + OSMIUM_ATTRIBUTE(discussion_handler, _comment, comment_type) + constexpr explicit _comment(const comment_type& value) noexcept : + type_wrapper(value) {} + explicit _comment(const osmium::ChangesetComment& comment) noexcept : + type_wrapper({comment.date(), comment.uid(), comment.user(), comment.text()}) {} + }; + + template + inline constexpr detail::comments_from_iterator_pair _comments(TCommentIterator first, TCommentIterator last) { + return detail::comments_from_iterator_pair(first, last); + } + + template + inline detail::comments_from_iterator_pair _comments(const TContainer& container) { + return detail::comments_from_iterator_pair(std::begin(container), std::end(container)); + } + + using comment_ilist = std::initializer_list; + inline detail::comments_from_iterator_pair _comments(const comment_ilist& container) { + return detail::comments_from_iterator_pair(std::begin(container), std::end(container)); + } + + + template + inline constexpr detail::outer_ring_from_iterator_pair _outer_ring(TIdIterator first, TIdIterator last) { + return detail::outer_ring_from_iterator_pair(first, last); + } + + template + inline detail::outer_ring_from_iterator_pair _outer_ring(const TContainer& container) { + return detail::outer_ring_from_iterator_pair(std::begin(container), std::end(container)); + } + + using object_id_ilist = std::initializer_list; + inline detail::outer_ring_from_iterator_pair _outer_ring(const object_id_ilist& container) { + return detail::outer_ring_from_iterator_pair(std::begin(container), std::end(container)); + } + + using node_ref_ilist = std::initializer_list; + inline detail::outer_ring_from_iterator_pair _outer_ring(const node_ref_ilist& container) { + return detail::outer_ring_from_iterator_pair(std::begin(container), std::end(container)); + } + + template + inline constexpr detail::inner_ring_from_iterator_pair _inner_ring(TIdIterator first, TIdIterator last) { + return detail::inner_ring_from_iterator_pair(first, last); + } + + template + inline detail::inner_ring_from_iterator_pair _inner_ring(const TContainer& container) { + return detail::inner_ring_from_iterator_pair(std::begin(container), std::end(container)); + } + + using object_id_ilist = std::initializer_list; + inline detail::inner_ring_from_iterator_pair _inner_ring(const object_id_ilist& container) { + return detail::inner_ring_from_iterator_pair(std::begin(container), std::end(container)); + } + + using node_ref_ilist = std::initializer_list; + inline detail::inner_ring_from_iterator_pair _inner_ring(const node_ref_ilist& container) { + return detail::inner_ring_from_iterator_pair(std::begin(container), std::end(container)); + } + + + } // namespace attr + +#undef OSMIUM_ATTRIBUTE_ITER +#undef OSMIUM_ATTRIBUTE_WITH_CONSTRUCTOR +#undef OSMIUM_ATTRIBUTE + + namespace detail { + + struct changeset_handler : public entity_handler { + + template + static void set_value(osmium::Changeset&, const TDummy&) noexcept { + } + + static void set_value(osmium::Changeset& changeset, attr::_cid id) noexcept { + changeset.set_id(id.value); + } + + static void set_value(osmium::Changeset& changeset, attr::_num_changes num_changes) noexcept { + changeset.set_num_changes(num_changes.value); + } + + static void set_value(osmium::Changeset& changeset, attr::_num_comments num_comments) noexcept { + changeset.set_num_comments(num_comments.value); + } + + static void set_value(osmium::Changeset& changeset, attr::_created_at created_at) noexcept { + changeset.set_created_at(created_at.value); + } + + static void set_value(osmium::Changeset& changeset, attr::_closed_at closed_at) noexcept { + changeset.set_closed_at(closed_at.value); + } + + static void set_value(osmium::Changeset& changeset, attr::_uid uid) noexcept { + changeset.set_uid(uid.value); + } + + }; + + struct object_handler : public entity_handler { + + template + static void set_value(osmium::OSMObject&, const TDummy&) noexcept { + } + + static void set_value(osmium::OSMObject& object, attr::_id id) noexcept { + object.set_id(id.value); + } + + static void set_value(osmium::OSMObject& object, attr::_version version) noexcept { + object.set_version(version.value); + } + + static void set_value(osmium::OSMObject& object, attr::_visible visible) noexcept { + object.set_visible(visible.value); + } + + static void set_value(osmium::OSMObject& object, attr::_deleted deleted) noexcept { + object.set_deleted(deleted.value); + } + + static void set_value(osmium::OSMObject& object, attr::_timestamp timestamp) noexcept { + object.set_timestamp(timestamp.value); + } + + static void set_value(osmium::OSMObject& object, attr::_cid changeset) noexcept { + object.set_changeset(changeset.value); + } + + static void set_value(osmium::OSMObject& object, attr::_uid uid) noexcept { + object.set_uid(uid.value); + } + + }; // object_handler + + struct node_handler : public object_handler { + + using object_handler::set_value; + + static void set_value(osmium::Node& node, attr::_location location) noexcept { + node.set_location(location.value); + } + + }; // node_handler + + template + inline void add_basic(TBuilder& builder, const TArgs&... args) noexcept { + (void)std::initializer_list{ + (THandler::set_value(builder.object(), args), 0)... + }; + } + + // ============================================================== + + template + inline constexpr const char* get_user(const attr::_user& user, const TArgs&...) noexcept { + return user.value; + } + + inline constexpr const char* get_user() noexcept { + return ""; + } + + template + inline constexpr typename std::enable_if::value, const char*>::type + get_user(const TFirst&, const TRest&... args) noexcept { + return get_user(args...); + } + + template + inline void add_user(TBuilder& builder, const TArgs&... args) { + builder.add_user(get_user(args...)); + } + + // ============================================================== + + struct tags_handler { + + template + static void set_value(TagListBuilder&, const TDummy&) noexcept { + } + + static void set_value(TagListBuilder& builder, const attr::_tag& tag) { + builder.add_tag(tag.value); + } + + template + static void set_value(TagListBuilder& builder, const attr::detail::tags_from_iterator_pair& tags) { + for (const auto& tag : tags) { + builder.add_tag(tag); + } + } + + }; // struct tags_handler + + struct nodes_handler { + + template + static void set_value(WayNodeListBuilder&, const TDummy&) noexcept { + } + + static void set_value(WayNodeListBuilder& builder, const attr::_node& node_ref) { + builder.add_node_ref(node_ref.value); + } + + template + static void set_value(WayNodeListBuilder& builder, const attr::detail::nodes_from_iterator_pair& nodes) { + for (const auto& ref : nodes) { + builder.add_node_ref(ref); + } + } + + }; // struct nodes_handler + + struct members_handler { + + template + static void set_value(RelationMemberListBuilder&, const TDummy&) noexcept { + } + + static void set_value(RelationMemberListBuilder& builder, const attr::_member& member) { + builder.add_member(member.value.type(), member.value.ref(), member.value.role()); + } + + template + static void set_value(RelationMemberListBuilder& builder, const attr::detail::members_from_iterator_pair& members) { + for (const auto& member : members) { + builder.add_member(member.type(), member.ref(), member.role()); + } + } + + }; // struct members_handler + + struct discussion_handler { + + template + static void set_value(ChangesetDiscussionBuilder&, const TDummy&) noexcept { + } + + static void set_value(ChangesetDiscussionBuilder& builder, const attr::_comment& comment) { + builder.add_comment(comment.value.date(), comment.value.uid(), comment.value.user()); + builder.add_comment_text(comment.value.text()); + } + + template + static void set_value(ChangesetDiscussionBuilder& builder, const attr::detail::comments_from_iterator_pair& comments) { + for (const auto& comment : comments) { + builder.add_comment(comment.date(), comment.uid(), comment.user()); + builder.add_comment_text(comment.text()); + } + } + + }; // struct discussion_handler + + struct ring_handler { + + template + static void set_value(AreaBuilder&, const TDummy&) noexcept { + } + + template + static void set_value(AreaBuilder& parent, const attr::detail::outer_ring_from_iterator_pair& nodes) { + OuterRingBuilder builder(parent.buffer(), &parent); + for (const auto& ref : nodes) { + builder.add_node_ref(ref); + } + } + + template + static void set_value(AreaBuilder& parent, const attr::detail::inner_ring_from_iterator_pair& nodes) { + InnerRingBuilder builder(parent.buffer(), &parent); + for (const auto& ref : nodes) { + builder.add_node_ref(ref); + } + } + + }; // struct ring_handler + + // ============================================================== + + template + inline typename std::enable_if::value>::type + add_list(osmium::builder::Builder&, const TArgs&...) noexcept { + } + + template + inline typename std::enable_if::value>::type + add_list(osmium::builder::Builder& parent, const TArgs&... args) { + TBuilder builder(parent.buffer(), &parent); + (void)std::initializer_list{ + (THandler::set_value(builder, args), 0)... + }; + } + + struct any_node_handlers : public node_handler, public tags_handler {}; + struct any_way_handlers : public object_handler, public tags_handler, public nodes_handler {}; + struct any_relation_handlers : public object_handler, public tags_handler, public members_handler {}; + struct any_area_handlers : public object_handler, public tags_handler, public ring_handler {}; + struct any_changeset_handlers : public changeset_handler, public tags_handler, public discussion_handler {}; + + } // namespace detail + + + /** + * Create a node using the given arguments and add it to the given buffer. + * + * @param buffer The buffer to which the node will be added. + * @param args The attributes of the node. + * @returns The position in the buffer where this node was added. + */ + template + inline size_t add_node(osmium::memory::Buffer& buffer, const TArgs&... args) { + static_assert(sizeof...(args) > 0, "add_node() must have buffer and at least one additional argument"); + static_assert(detail::are_all_handled_by::value, "Attribute not allowed in add_node()"); + + NodeBuilder builder(buffer); + + detail::add_basic(builder, args...); + detail::add_user(builder, args...); + detail::add_list(builder, args...); + + return buffer.commit(); + } + + /** + * Create a way using the given arguments and add it to the given buffer. + * + * @param buffer The buffer to which the way will be added. + * @param args The attributes of the way. + * @returns The position in the buffer where this way was added. + */ + template + inline size_t add_way(osmium::memory::Buffer& buffer, const TArgs&... args) { + static_assert(sizeof...(args) > 0, "add_way() must have buffer and at least one additional argument"); + static_assert(detail::are_all_handled_by::value, "Attribute not allowed in add_way()"); + + WayBuilder builder(buffer); + + detail::add_basic(builder, args...); + detail::add_user(builder, args...); + detail::add_list(builder, args...); + detail::add_list(builder, args...); + + return buffer.commit(); + } + + /** + * Create a relation using the given arguments and add it to the given buffer. + * + * @param buffer The buffer to which the relation will be added. + * @param args The attributes of the relation. + * @returns The position in the buffer where this relation was added. + */ + template + inline size_t add_relation(osmium::memory::Buffer& buffer, const TArgs&... args) { + static_assert(sizeof...(args) > 0, "add_relation() must have buffer and at least one additional argument"); + static_assert(detail::are_all_handled_by::value, "Attribute not allowed in add_relation()"); + + RelationBuilder builder(buffer); + + detail::add_basic(builder, args...); + detail::add_user(builder, args...); + detail::add_list(builder, args...); + detail::add_list(builder, args...); + + return buffer.commit(); + } + + /** + * Create a changeset using the given arguments and add it to the given buffer. + * + * @param buffer The buffer to which the changeset will be added. + * @param args The attributes of the changeset. + * @returns The position in the buffer where this changeset was added. + */ + template + inline size_t add_changeset(osmium::memory::Buffer& buffer, const TArgs&... args) { + static_assert(sizeof...(args) > 0, "add_changeset() must have buffer and at least one additional argument"); + static_assert(detail::are_all_handled_by::value, "Attribute not allowed in add_changeset()"); + + ChangesetBuilder builder(buffer); + + detail::add_basic(builder, args...); + detail::add_user(builder, args...); + detail::add_list(builder, args...); + detail::add_list(builder, args...); + + return buffer.commit(); + } + + /** + * Create a area using the given arguments and add it to the given buffer. + * + * @param buffer The buffer to which the area will be added. + * @param args The attributes of the area. + * @returns The position in the buffer where this area was added. + */ + template + inline size_t add_area(osmium::memory::Buffer& buffer, const TArgs&... args) { + static_assert(sizeof...(args) > 0, "add_area() must have buffer and at least one additional argument"); + static_assert(detail::are_all_handled_by::value, "Attribute not allowed in add_area()"); + + AreaBuilder builder(buffer); + + detail::add_basic(builder, args...); + detail::add_user(builder, args...); + detail::add_list(builder, args...); + + (void)std::initializer_list{ + (detail::ring_handler::set_value(builder, args), 0)... + }; + + return buffer.commit(); + } + + /** + * Create a WayNodeList using the given arguments and add it to the given buffer. + * + * @param buffer The buffer to which the list will be added. + * @param args The contents of the list. + * @returns The position in the buffer where this list was added. + */ + template + inline size_t add_way_node_list(osmium::memory::Buffer& buffer, const TArgs&... args) { + static_assert(sizeof...(args) > 0, "add_way_node_list() must have buffer and at least one additional argument"); + static_assert(detail::are_all_handled_by::value, "Attribute not allowed in add_way_node_list()"); + + { + WayNodeListBuilder builder(buffer); + (void)std::initializer_list{ + (detail::nodes_handler::set_value(builder, args), 0)... + }; + } + + return buffer.commit(); + } + + /** + * Create a TagList using the given arguments and add it to the given buffer. + * + * @param buffer The buffer to which the list will be added. + * @param args The contents of the list. + * @returns The position in the buffer where this list was added. + */ + template + inline size_t add_tag_list(osmium::memory::Buffer& buffer, const TArgs&... args) { + static_assert(sizeof...(args) > 0, "add_tag_list() must have buffer and at least one additional argument"); + static_assert(detail::are_all_handled_by::value, "Attribute not allowed in add_tag_list()"); + + { + TagListBuilder builder(buffer); + (void)std::initializer_list{ + (detail::tags_handler::set_value(builder, args), 0)... + }; + } + + return buffer.commit(); + } + + } // namespace builder + +} // namespace osmium + +#endif // OSMIUM_BUILDER_ATTR_HPP diff --git a/third_party/libosmium/include/osmium/builder/builder.hpp b/third_party/libosmium/include/osmium/builder/builder.hpp index 63eb4bb2d..869fe44e5 100644 --- a/third_party/libosmium/include/osmium/builder/builder.hpp +++ b/third_party/libosmium/include/osmium/builder/builder.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/builder/builder_helper.hpp b/third_party/libosmium/include/osmium/builder/builder_helper.hpp index eebdf338c..e1b7c52ff 100644 --- a/third_party/libosmium/include/osmium/builder/builder_helper.hpp +++ b/third_party/libosmium/include/osmium/builder/builder_helper.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -41,6 +41,7 @@ DEALINGS IN THE SOFTWARE. #include #include +#include namespace osmium { @@ -50,7 +51,11 @@ namespace osmium { namespace builder { - inline const osmium::WayNodeList& build_way_node_list(osmium::memory::Buffer& buffer, const std::initializer_list& nodes) { + /** + * @deprecated + * Use osmium::builder::add_way_node_list() instead. + */ + OSMIUM_DEPRECATED inline const osmium::WayNodeList& build_way_node_list(osmium::memory::Buffer& buffer, const std::initializer_list& nodes) { size_t pos = buffer.committed(); { osmium::builder::WayNodeListBuilder wnl_builder(buffer); @@ -62,6 +67,10 @@ namespace osmium { return buffer.get(pos); } + /** + * @deprecated + * Use osmium::builder::add_tag_list() instead. + */ inline const osmium::TagList& build_tag_list(osmium::memory::Buffer& buffer, const std::initializer_list>& tags) { size_t pos = buffer.committed(); { @@ -74,6 +83,10 @@ namespace osmium { return buffer.get(pos); } + /** + * @deprecated + * Use osmium::builder::add_tag_list() instead. + */ inline const osmium::TagList& build_tag_list_from_map(osmium::memory::Buffer& buffer, const std::map& tags) { size_t pos = buffer.committed(); { @@ -86,6 +99,10 @@ namespace osmium { return buffer.get(pos); } + /** + * @deprecated + * Use osmium::builder::add_tag_list() instead. + */ inline const osmium::TagList& build_tag_list_from_func(osmium::memory::Buffer& buffer, std::function func) { size_t pos = buffer.committed(); { diff --git a/third_party/libosmium/include/osmium/builder/osm_object_builder.hpp b/third_party/libosmium/include/osmium/builder/osm_object_builder.hpp index 82b4b23ce..d4b54f8fc 100644 --- a/third_party/libosmium/include/osmium/builder/osm_object_builder.hpp +++ b/third_party/libosmium/include/osmium/builder/osm_object_builder.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -34,8 +34,10 @@ DEALINGS IN THE SOFTWARE. */ #include +#include #include #include +#include #include #include #include @@ -49,7 +51,6 @@ DEALINGS IN THE SOFTWARE. #include #include #include -#include namespace osmium { @@ -137,6 +138,15 @@ namespace osmium { * * @param tag Pair of key/value 0-terminated strings. */ + void add_tag(const std::pair& tag) { + add_tag(tag.first, tag.second); + } + void add_tag(const std::pair& tag) { + add_tag(tag.first, tag.second); + } + void add_tag(const std::pair& tag) { + add_tag(tag.first, tag.second); + } void add_tag(const std::pair& tag) { add_tag(tag.first, tag.second); } diff --git a/third_party/libosmium/include/osmium/diff_handler.hpp b/third_party/libosmium/include/osmium/diff_handler.hpp index 06d8a93ed..a5fc34fba 100644 --- a/third_party/libosmium/include/osmium/diff_handler.hpp +++ b/third_party/libosmium/include/osmium/diff_handler.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/diff_iterator.hpp b/third_party/libosmium/include/osmium/diff_iterator.hpp index 6725fecc8..6e0ba4bbf 100644 --- a/third_party/libosmium/include/osmium/diff_iterator.hpp +++ b/third_party/libosmium/include/osmium/diff_iterator.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/diff_visitor.hpp b/third_party/libosmium/include/osmium/diff_visitor.hpp index ac16a8ed4..95660de6b 100644 --- a/third_party/libosmium/include/osmium/diff_visitor.hpp +++ b/third_party/libosmium/include/osmium/diff_visitor.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/dynamic_handler.hpp b/third_party/libosmium/include/osmium/dynamic_handler.hpp index 7077554ff..e7c9900fa 100644 --- a/third_party/libosmium/include/osmium/dynamic_handler.hpp +++ b/third_party/libosmium/include/osmium/dynamic_handler.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/experimental/flex_reader.hpp b/third_party/libosmium/include/osmium/experimental/flex_reader.hpp index c1d235746..8059ea32a 100644 --- a/third_party/libosmium/include/osmium/experimental/flex_reader.hpp +++ b/third_party/libosmium/include/osmium/experimental/flex_reader.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/fwd.hpp b/third_party/libosmium/include/osmium/fwd.hpp index bfcb5f57f..84def8ef1 100644 --- a/third_party/libosmium/include/osmium/fwd.hpp +++ b/third_party/libosmium/include/osmium/fwd.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/coordinates.hpp b/third_party/libosmium/include/osmium/geom/coordinates.hpp index 6544e68aa..0f1387622 100644 --- a/third_party/libosmium/include/osmium/geom/coordinates.hpp +++ b/third_party/libosmium/include/osmium/geom/coordinates.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/factory.hpp b/third_party/libosmium/include/osmium/geom/factory.hpp index 19375806b..394228eb9 100644 --- a/third_party/libosmium/include/osmium/geom/factory.hpp +++ b/third_party/libosmium/include/osmium/geom/factory.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/geojson.hpp b/third_party/libosmium/include/osmium/geom/geojson.hpp index e5b5a9cfc..044a89f86 100644 --- a/third_party/libosmium/include/osmium/geom/geojson.hpp +++ b/third_party/libosmium/include/osmium/geom/geojson.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/geos.hpp b/third_party/libosmium/include/osmium/geom/geos.hpp index 49b1fd7c0..f9026e5a9 100644 --- a/third_party/libosmium/include/osmium/geom/geos.hpp +++ b/third_party/libosmium/include/osmium/geom/geos.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/haversine.hpp b/third_party/libosmium/include/osmium/geom/haversine.hpp index e62a31b03..632bc1612 100644 --- a/third_party/libosmium/include/osmium/geom/haversine.hpp +++ b/third_party/libosmium/include/osmium/geom/haversine.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/mercator_projection.hpp b/third_party/libosmium/include/osmium/geom/mercator_projection.hpp index 22a0d646b..a0c38088a 100644 --- a/third_party/libosmium/include/osmium/geom/mercator_projection.hpp +++ b/third_party/libosmium/include/osmium/geom/mercator_projection.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/ogr.hpp b/third_party/libosmium/include/osmium/geom/ogr.hpp index 4d5995cf7..b8e9ef3ab 100644 --- a/third_party/libosmium/include/osmium/geom/ogr.hpp +++ b/third_party/libosmium/include/osmium/geom/ogr.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/projection.hpp b/third_party/libosmium/include/osmium/geom/projection.hpp index 6419101f8..42d95b27e 100644 --- a/third_party/libosmium/include/osmium/geom/projection.hpp +++ b/third_party/libosmium/include/osmium/geom/projection.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -68,10 +68,6 @@ namespace osmium { std::unique_ptr m_crs; - projPJ get() const { - return m_crs.get(); - } - public: CRS(const std::string& crs) : @@ -85,6 +81,13 @@ namespace osmium { CRS(std::string("+init=epsg:") + std::to_string(epsg)) { } + /** + * Get underlying projPJ handle from proj library. + */ + projPJ get() const { + return m_crs.get(); + } + bool is_latlong() const { return pj_is_latlong(m_crs.get()) != 0; } @@ -93,24 +96,24 @@ namespace osmium { return pj_is_geocent(m_crs.get()) != 0; } - /** - * Transform coordinates from one CRS into another. Wraps the same function - * of the proj library. - * - * Coordinates have to be in radians and are produced in radians. - * - * @throws osmmium::projection_error if the projection fails - */ - friend Coordinates transform(const CRS& src, const CRS& dest, Coordinates c) { - int result = pj_transform(src.get(), dest.get(), 1, 1, &c.x, &c.y, nullptr); - if (result != 0) { - throw osmium::projection_error(std::string("projection failed: ") + pj_strerrno(result)); - } - return c; - } - }; // class CRS + /** + * Transform coordinates from one CRS into another. Wraps the same + * function of the proj library. + * + * Coordinates have to be in radians and are produced in radians. + * + * @throws osmmium::projection_error if the projection fails + */ + inline Coordinates transform(const CRS& src, const CRS& dest, Coordinates c) { + int result = pj_transform(src.get(), dest.get(), 1, 1, &c.x, &c.y, nullptr); + if (result != 0) { + throw osmium::projection_error(std::string("projection failed: ") + pj_strerrno(result)); + } + return c; + } + /** * Functor that does projection from WGS84 (EPSG:4326) to the given * CRS. diff --git a/third_party/libosmium/include/osmium/geom/rapid_geojson.hpp b/third_party/libosmium/include/osmium/geom/rapid_geojson.hpp index 87e479bf1..87e13110f 100644 --- a/third_party/libosmium/include/osmium/geom/rapid_geojson.hpp +++ b/third_party/libosmium/include/osmium/geom/rapid_geojson.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/relations.hpp b/third_party/libosmium/include/osmium/geom/relations.hpp index e9e2aa420..76d452e4e 100644 --- a/third_party/libosmium/include/osmium/geom/relations.hpp +++ b/third_party/libosmium/include/osmium/geom/relations.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/tile.hpp b/third_party/libosmium/include/osmium/geom/tile.hpp index 6ca068262..e35c2ee59 100644 --- a/third_party/libosmium/include/osmium/geom/tile.hpp +++ b/third_party/libosmium/include/osmium/geom/tile.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/util.hpp b/third_party/libosmium/include/osmium/geom/util.hpp index 5e9f8228c..fa9c8bc36 100644 --- a/third_party/libosmium/include/osmium/geom/util.hpp +++ b/third_party/libosmium/include/osmium/geom/util.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/wkb.hpp b/third_party/libosmium/include/osmium/geom/wkb.hpp index 49833e66b..19c12165e 100644 --- a/third_party/libosmium/include/osmium/geom/wkb.hpp +++ b/third_party/libosmium/include/osmium/geom/wkb.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/geom/wkt.hpp b/third_party/libosmium/include/osmium/geom/wkt.hpp index 9cf5371a9..ae73b9604 100644 --- a/third_party/libosmium/include/osmium/geom/wkt.hpp +++ b/third_party/libosmium/include/osmium/geom/wkt.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/handler.hpp b/third_party/libosmium/include/osmium/handler.hpp index 47e997efc..3620d6546 100644 --- a/third_party/libosmium/include/osmium/handler.hpp +++ b/third_party/libosmium/include/osmium/handler.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/handler/chain.hpp b/third_party/libosmium/include/osmium/handler/chain.hpp index 4f3291ca6..e59eb05b9 100644 --- a/third_party/libosmium/include/osmium/handler/chain.hpp +++ b/third_party/libosmium/include/osmium/handler/chain.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/handler/check_order.hpp b/third_party/libosmium/include/osmium/handler/check_order.hpp new file mode 100644 index 000000000..143794bd5 --- /dev/null +++ b/third_party/libosmium/include/osmium/handler/check_order.hpp @@ -0,0 +1,136 @@ +#ifndef OSMIUM_HANDLER_CHECK_ORDER_HPP +#define OSMIUM_HANDLER_CHECK_ORDER_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2016 Jochen Topf 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 +#include +#include + +#include +#include +#include +#include +#include + +namespace osmium { + + /** + * Exception thrown when a method in the CheckOrder class detects + * that the input is out of order. + */ + struct out_of_order_error : public std::runtime_error { + + out_of_order_error(const std::string& what) : + std::runtime_error(what) { + } + + out_of_order_error(const char* what) : + std::runtime_error(what) { + } + + }; // struct out_of_order_error + + namespace handler { + + /** + * Handler that can be used to check that an OSM file is ordered + * correctly. Ordered in this case refers to the usual order in OSM + * files: First nodes in the order of their IDs, then ways in the order + * of their IDs, then relations in the order or their IDs. IDs have to + * be unique for each type. + * + * To use this add a CheckOrder member variable to your handler and + * call the node(), way(), and relation() methods from your node(), + * way(), and relations() handlers, respectively. An out_of_order_error + * exception will be thrown when the input is not in order. + */ + class CheckOrder : public osmium::handler::Handler { + + osmium::object_id_type m_max_node_id = std::numeric_limits::min(); + osmium::object_id_type m_max_way_id = std::numeric_limits::min(); + osmium::object_id_type m_max_relation_id = std::numeric_limits::min(); + + public: + + void node(const osmium::Node& node) { + if (m_max_way_id > 0) { + throw out_of_order_error("Found a node after a way."); + } + if (m_max_relation_id > 0) { + throw out_of_order_error("Found a node after a relation."); + } + + if (m_max_node_id >= node.id()) { + throw out_of_order_error("Node IDs out of order."); + } + m_max_node_id = node.id(); + } + + void way(const osmium::Way& way) { + if (m_max_relation_id > 0) { + throw out_of_order_error("Found a way after a relation."); + } + + if (m_max_way_id >= way.id()) { + throw out_of_order_error("Way IDs out of order."); + } + m_max_way_id = way.id(); + } + + void relation(const osmium::Relation& relation) { + if (m_max_relation_id >= relation.id()) { + throw out_of_order_error("Relation IDs out of order."); + } + m_max_relation_id = relation.id(); + } + + osmium::object_id_type max_node_id() const noexcept { + return m_max_node_id; + } + + osmium::object_id_type max_way_id() const noexcept { + return m_max_way_id; + } + + osmium::object_id_type max_relation_id() const noexcept { + return m_max_relation_id; + } + + }; // class CheckOrder + + } // namespace handler + +} // namespace osmium + +#endif // OSMIUM_HANDLER_CHECK_ORDER_HPP diff --git a/third_party/libosmium/include/osmium/handler/disk_store.hpp b/third_party/libosmium/include/osmium/handler/disk_store.hpp index ccae5962a..b8ab229a3 100644 --- a/third_party/libosmium/include/osmium/handler/disk_store.hpp +++ b/third_party/libosmium/include/osmium/handler/disk_store.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/handler/dump.hpp b/third_party/libosmium/include/osmium/handler/dump.hpp index a23236e10..3863b77ec 100644 --- a/third_party/libosmium/include/osmium/handler/dump.hpp +++ b/third_party/libosmium/include/osmium/handler/dump.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/handler/node_locations_for_ways.hpp b/third_party/libosmium/include/osmium/handler/node_locations_for_ways.hpp index 8d31310c3..f62a4db7c 100644 --- a/third_party/libosmium/include/osmium/handler/node_locations_for_ways.hpp +++ b/third_party/libosmium/include/osmium/handler/node_locations_for_ways.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/handler/object_relations.hpp b/third_party/libosmium/include/osmium/handler/object_relations.hpp index dc4aa45d8..4afcf6a6d 100644 --- a/third_party/libosmium/include/osmium/handler/object_relations.hpp +++ b/third_party/libosmium/include/osmium/handler/object_relations.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/bool_vector.hpp b/third_party/libosmium/include/osmium/index/bool_vector.hpp index 04850a5fc..e6e190e27 100644 --- a/third_party/libosmium/include/osmium/index/bool_vector.hpp +++ b/third_party/libosmium/include/osmium/index/bool_vector.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/detail/create_map_with_fd.hpp b/third_party/libosmium/include/osmium/index/detail/create_map_with_fd.hpp index a2e6b768a..640b3c693 100644 --- a/third_party/libosmium/include/osmium/index/detail/create_map_with_fd.hpp +++ b/third_party/libosmium/include/osmium/index/detail/create_map_with_fd.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/detail/mmap_vector_anon.hpp b/third_party/libosmium/include/osmium/index/detail/mmap_vector_anon.hpp index 12a18036b..cd6942fbf 100644 --- a/third_party/libosmium/include/osmium/index/detail/mmap_vector_anon.hpp +++ b/third_party/libosmium/include/osmium/index/detail/mmap_vector_anon.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/detail/mmap_vector_base.hpp b/third_party/libosmium/include/osmium/index/detail/mmap_vector_base.hpp index e5f28e9b9..aadeef0b5 100644 --- a/third_party/libosmium/include/osmium/index/detail/mmap_vector_base.hpp +++ b/third_party/libosmium/include/osmium/index/detail/mmap_vector_base.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/detail/mmap_vector_file.hpp b/third_party/libosmium/include/osmium/index/detail/mmap_vector_file.hpp index 54ef5137e..666a409d4 100644 --- a/third_party/libosmium/include/osmium/index/detail/mmap_vector_file.hpp +++ b/third_party/libosmium/include/osmium/index/detail/mmap_vector_file.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/detail/tmpfile.hpp b/third_party/libosmium/include/osmium/index/detail/tmpfile.hpp index 06cab6544..0f3d1205b 100644 --- a/third_party/libosmium/include/osmium/index/detail/tmpfile.hpp +++ b/third_party/libosmium/include/osmium/index/detail/tmpfile.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/detail/vector_map.hpp b/third_party/libosmium/include/osmium/index/detail/vector_map.hpp index 2a13061e2..0fa59dd48 100644 --- a/third_party/libosmium/include/osmium/index/detail/vector_map.hpp +++ b/third_party/libosmium/include/osmium/index/detail/vector_map.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/detail/vector_multimap.hpp b/third_party/libosmium/include/osmium/index/detail/vector_multimap.hpp index 789fc9499..35a4cc182 100644 --- a/third_party/libosmium/include/osmium/index/detail/vector_multimap.hpp +++ b/third_party/libosmium/include/osmium/index/detail/vector_multimap.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/index.hpp b/third_party/libosmium/include/osmium/index/index.hpp index 78c142d82..37d022d1b 100644 --- a/third_party/libosmium/include/osmium/index/index.hpp +++ b/third_party/libosmium/include/osmium/index/index.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map.hpp b/third_party/libosmium/include/osmium/index/map.hpp index 68a9c201c..f90a895d1 100644 --- a/third_party/libosmium/include/osmium/index/map.hpp +++ b/third_party/libosmium/include/osmium/index/map.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/all.hpp b/third_party/libosmium/include/osmium/index/map/all.hpp index 9ffadc0de..348d77135 100644 --- a/third_party/libosmium/include/osmium/index/map/all.hpp +++ b/third_party/libosmium/include/osmium/index/map/all.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/dense_file_array.hpp b/third_party/libosmium/include/osmium/index/map/dense_file_array.hpp index d209a875c..6694d11f3 100644 --- a/third_party/libosmium/include/osmium/index/map/dense_file_array.hpp +++ b/third_party/libosmium/include/osmium/index/map/dense_file_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/dense_mem_array.hpp b/third_party/libosmium/include/osmium/index/map/dense_mem_array.hpp index b45eec458..6c33f7dda 100644 --- a/third_party/libosmium/include/osmium/index/map/dense_mem_array.hpp +++ b/third_party/libosmium/include/osmium/index/map/dense_mem_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/dense_mmap_array.hpp b/third_party/libosmium/include/osmium/index/map/dense_mmap_array.hpp index a912aebd1..e63170a77 100644 --- a/third_party/libosmium/include/osmium/index/map/dense_mmap_array.hpp +++ b/third_party/libosmium/include/osmium/index/map/dense_mmap_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/dummy.hpp b/third_party/libosmium/include/osmium/index/map/dummy.hpp index d6a360e56..98d082b82 100644 --- a/third_party/libosmium/include/osmium/index/map/dummy.hpp +++ b/third_party/libosmium/include/osmium/index/map/dummy.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/sparse_file_array.hpp b/third_party/libosmium/include/osmium/index/map/sparse_file_array.hpp index 2ba9315dd..495833c72 100644 --- a/third_party/libosmium/include/osmium/index/map/sparse_file_array.hpp +++ b/third_party/libosmium/include/osmium/index/map/sparse_file_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/sparse_mem_array.hpp b/third_party/libosmium/include/osmium/index/map/sparse_mem_array.hpp index 9adf41f0a..29fadf653 100644 --- a/third_party/libosmium/include/osmium/index/map/sparse_mem_array.hpp +++ b/third_party/libosmium/include/osmium/index/map/sparse_mem_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/sparse_mem_map.hpp b/third_party/libosmium/include/osmium/index/map/sparse_mem_map.hpp index d001b6791..41351c865 100644 --- a/third_party/libosmium/include/osmium/index/map/sparse_mem_map.hpp +++ b/third_party/libosmium/include/osmium/index/map/sparse_mem_map.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/sparse_mem_table.hpp b/third_party/libosmium/include/osmium/index/map/sparse_mem_table.hpp index 797a9265e..241a64f97 100644 --- a/third_party/libosmium/include/osmium/index/map/sparse_mem_table.hpp +++ b/third_party/libosmium/include/osmium/index/map/sparse_mem_table.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/map/sparse_mmap_array.hpp b/third_party/libosmium/include/osmium/index/map/sparse_mmap_array.hpp index c85e2c938..939c389e1 100644 --- a/third_party/libosmium/include/osmium/index/map/sparse_mmap_array.hpp +++ b/third_party/libosmium/include/osmium/index/map/sparse_mmap_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/multimap.hpp b/third_party/libosmium/include/osmium/index/multimap.hpp index a7e1aadb3..de6aa1eb4 100644 --- a/third_party/libosmium/include/osmium/index/multimap.hpp +++ b/third_party/libosmium/include/osmium/index/multimap.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/multimap/all.hpp b/third_party/libosmium/include/osmium/index/multimap/all.hpp index 8b0ae99f9..3fc99d4c9 100644 --- a/third_party/libosmium/include/osmium/index/multimap/all.hpp +++ b/third_party/libosmium/include/osmium/index/multimap/all.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/multimap/hybrid.hpp b/third_party/libosmium/include/osmium/index/multimap/hybrid.hpp index e13ee680f..ba9430232 100644 --- a/third_party/libosmium/include/osmium/index/multimap/hybrid.hpp +++ b/third_party/libosmium/include/osmium/index/multimap/hybrid.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/multimap/sparse_file_array.hpp b/third_party/libosmium/include/osmium/index/multimap/sparse_file_array.hpp index 0b9ae92c5..c36200162 100644 --- a/third_party/libosmium/include/osmium/index/multimap/sparse_file_array.hpp +++ b/third_party/libosmium/include/osmium/index/multimap/sparse_file_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/multimap/sparse_mem_array.hpp b/third_party/libosmium/include/osmium/index/multimap/sparse_mem_array.hpp index c4140cba0..f718edd91 100644 --- a/third_party/libosmium/include/osmium/index/multimap/sparse_mem_array.hpp +++ b/third_party/libosmium/include/osmium/index/multimap/sparse_mem_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/multimap/sparse_mem_multimap.hpp b/third_party/libosmium/include/osmium/index/multimap/sparse_mem_multimap.hpp index 84cb640d9..0859fca21 100644 --- a/third_party/libosmium/include/osmium/index/multimap/sparse_mem_multimap.hpp +++ b/third_party/libosmium/include/osmium/index/multimap/sparse_mem_multimap.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/multimap/sparse_mmap_array.hpp b/third_party/libosmium/include/osmium/index/multimap/sparse_mmap_array.hpp index 9f92555f6..6319c1754 100644 --- a/third_party/libosmium/include/osmium/index/multimap/sparse_mmap_array.hpp +++ b/third_party/libosmium/include/osmium/index/multimap/sparse_mmap_array.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/index/node_locations_map.hpp b/third_party/libosmium/include/osmium/index/node_locations_map.hpp index ca4b1361e..c6ce37dbb 100644 --- a/third_party/libosmium/include/osmium/index/node_locations_map.hpp +++ b/third_party/libosmium/include/osmium/index/node_locations_map.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/any_compression.hpp b/third_party/libosmium/include/osmium/io/any_compression.hpp index 00e8ee2be..7f9f3d562 100644 --- a/third_party/libosmium/include/osmium/io/any_compression.hpp +++ b/third_party/libosmium/include/osmium/io/any_compression.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/any_input.hpp b/third_party/libosmium/include/osmium/io/any_input.hpp index 36f43b785..dd8445132 100644 --- a/third_party/libosmium/include/osmium/io/any_input.hpp +++ b/third_party/libosmium/include/osmium/io/any_input.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/any_output.hpp b/third_party/libosmium/include/osmium/io/any_output.hpp index 990a27bac..53cc5bbd2 100644 --- a/third_party/libosmium/include/osmium/io/any_output.hpp +++ b/third_party/libosmium/include/osmium/io/any_output.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/bzip2_compression.hpp b/third_party/libosmium/include/osmium/io/bzip2_compression.hpp index fc0e33c53..e5cad0be3 100644 --- a/third_party/libosmium/include/osmium/io/bzip2_compression.hpp +++ b/third_party/libosmium/include/osmium/io/bzip2_compression.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/compression.hpp b/third_party/libosmium/include/osmium/io/compression.hpp index b337503ca..7d95661bd 100644 --- a/third_party/libosmium/include/osmium/io/compression.hpp +++ b/third_party/libosmium/include/osmium/io/compression.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/debug_output.hpp b/third_party/libosmium/include/osmium/io/debug_output.hpp index 2836f7987..84db9cdb8 100644 --- a/third_party/libosmium/include/osmium/io/debug_output.hpp +++ b/third_party/libosmium/include/osmium/io/debug_output.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/debug_output_format.hpp b/third_party/libosmium/include/osmium/io/detail/debug_output_format.hpp index f1766dea6..3f7537ea6 100644 --- a/third_party/libosmium/include/osmium/io/detail/debug_output_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/debug_output_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/input_format.hpp b/third_party/libosmium/include/osmium/io/detail/input_format.hpp index d26b1ee92..0d7885131 100644 --- a/third_party/libosmium/include/osmium/io/detail/input_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/input_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/o5m_input_format.hpp b/third_party/libosmium/include/osmium/io/detail/o5m_input_format.hpp index 0318432e8..7293cfa73 100644 --- a/third_party/libosmium/include/osmium/io/detail/o5m_input_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/o5m_input_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/opl_output_format.hpp b/third_party/libosmium/include/osmium/io/detail/opl_output_format.hpp index 2d863ea82..3fedf7e9c 100644 --- a/third_party/libosmium/include/osmium/io/detail/opl_output_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/opl_output_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/output_format.hpp b/third_party/libosmium/include/osmium/io/detail/output_format.hpp index 4c38c4d1e..34ca82f24 100644 --- a/third_party/libosmium/include/osmium/io/detail/output_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/output_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/pbf.hpp b/third_party/libosmium/include/osmium/io/detail/pbf.hpp index 13d552910..88c499326 100644 --- a/third_party/libosmium/include/osmium/io/detail/pbf.hpp +++ b/third_party/libosmium/include/osmium/io/detail/pbf.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/pbf_decoder.hpp b/third_party/libosmium/include/osmium/io/detail/pbf_decoder.hpp index 09e09bf02..43de1c18e 100644 --- a/third_party/libosmium/include/osmium/io/detail/pbf_decoder.hpp +++ b/third_party/libosmium/include/osmium/io/detail/pbf_decoder.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/pbf_input_format.hpp b/third_party/libosmium/include/osmium/io/detail/pbf_input_format.hpp index e9d0e71d1..0c6a9ef54 100644 --- a/third_party/libosmium/include/osmium/io/detail/pbf_input_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/pbf_input_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/pbf_output_format.hpp b/third_party/libosmium/include/osmium/io/detail/pbf_output_format.hpp index 88c1cf489..02b543f69 100644 --- a/third_party/libosmium/include/osmium/io/detail/pbf_output_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/pbf_output_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/protobuf_tags.hpp b/third_party/libosmium/include/osmium/io/detail/protobuf_tags.hpp index 3f2308766..1106f0318 100644 --- a/third_party/libosmium/include/osmium/io/detail/protobuf_tags.hpp +++ b/third_party/libosmium/include/osmium/io/detail/protobuf_tags.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/queue_util.hpp b/third_party/libosmium/include/osmium/io/detail/queue_util.hpp index 6c9f071bc..af8454411 100644 --- a/third_party/libosmium/include/osmium/io/detail/queue_util.hpp +++ b/third_party/libosmium/include/osmium/io/detail/queue_util.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/read_thread.hpp b/third_party/libosmium/include/osmium/io/detail/read_thread.hpp index 6f96c0b65..a933787e3 100644 --- a/third_party/libosmium/include/osmium/io/detail/read_thread.hpp +++ b/third_party/libosmium/include/osmium/io/detail/read_thread.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/read_write.hpp b/third_party/libosmium/include/osmium/io/detail/read_write.hpp index 6db6d8aa8..769e2b39a 100644 --- a/third_party/libosmium/include/osmium/io/detail/read_write.hpp +++ b/third_party/libosmium/include/osmium/io/detail/read_write.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/string_table.hpp b/third_party/libosmium/include/osmium/io/detail/string_table.hpp index 1cb142d00..55c622681 100644 --- a/third_party/libosmium/include/osmium/io/detail/string_table.hpp +++ b/third_party/libosmium/include/osmium/io/detail/string_table.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/string_util.hpp b/third_party/libosmium/include/osmium/io/detail/string_util.hpp index 672266a92..f80088e63 100644 --- a/third_party/libosmium/include/osmium/io/detail/string_util.hpp +++ b/third_party/libosmium/include/osmium/io/detail/string_util.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -110,7 +110,10 @@ namespace osmium { assert(len > 0); if (size_t(len) >= max_size) { - int len2 = string_snprintf(out, +#ifndef NDEBUG + int len2 = +#endif + string_snprintf(out, old_size, size_t(len) + 1, format, diff --git a/third_party/libosmium/include/osmium/io/detail/write_thread.hpp b/third_party/libosmium/include/osmium/io/detail/write_thread.hpp index 81ab1947f..796048638 100644 --- a/third_party/libosmium/include/osmium/io/detail/write_thread.hpp +++ b/third_party/libosmium/include/osmium/io/detail/write_thread.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/xml_input_format.hpp b/third_party/libosmium/include/osmium/io/detail/xml_input_format.hpp index 11d3cba08..8cb5efe8a 100644 --- a/third_party/libosmium/include/osmium/io/detail/xml_input_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/xml_input_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/xml_output_format.hpp b/third_party/libosmium/include/osmium/io/detail/xml_output_format.hpp index 3d7878c8e..09bd6b3ce 100644 --- a/third_party/libosmium/include/osmium/io/detail/xml_output_format.hpp +++ b/third_party/libosmium/include/osmium/io/detail/xml_output_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/detail/zlib.hpp b/third_party/libosmium/include/osmium/io/detail/zlib.hpp index 4d86168d2..2b6dddb94 100644 --- a/third_party/libosmium/include/osmium/io/detail/zlib.hpp +++ b/third_party/libosmium/include/osmium/io/detail/zlib.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/error.hpp b/third_party/libosmium/include/osmium/io/error.hpp index 6b5c677c0..fb6ccf738 100644 --- a/third_party/libosmium/include/osmium/io/error.hpp +++ b/third_party/libosmium/include/osmium/io/error.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/file.hpp b/third_party/libosmium/include/osmium/io/file.hpp index 87fcc3707..56fc8d513 100644 --- a/third_party/libosmium/include/osmium/io/file.hpp +++ b/third_party/libosmium/include/osmium/io/file.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/file_compression.hpp b/third_party/libosmium/include/osmium/io/file_compression.hpp index 292ddcfca..1cfb0f0c2 100644 --- a/third_party/libosmium/include/osmium/io/file_compression.hpp +++ b/third_party/libosmium/include/osmium/io/file_compression.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/file_format.hpp b/third_party/libosmium/include/osmium/io/file_format.hpp index edfb1ff9f..c447cb478 100644 --- a/third_party/libosmium/include/osmium/io/file_format.hpp +++ b/third_party/libosmium/include/osmium/io/file_format.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/gzip_compression.hpp b/third_party/libosmium/include/osmium/io/gzip_compression.hpp index 184787539..e6ca010de 100644 --- a/third_party/libosmium/include/osmium/io/gzip_compression.hpp +++ b/third_party/libosmium/include/osmium/io/gzip_compression.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/header.hpp b/third_party/libosmium/include/osmium/io/header.hpp index 4b0830a62..55ff5c6de 100644 --- a/third_party/libosmium/include/osmium/io/header.hpp +++ b/third_party/libosmium/include/osmium/io/header.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/input_iterator.hpp b/third_party/libosmium/include/osmium/io/input_iterator.hpp index 864776303..8be975930 100644 --- a/third_party/libosmium/include/osmium/io/input_iterator.hpp +++ b/third_party/libosmium/include/osmium/io/input_iterator.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/o5m_input.hpp b/third_party/libosmium/include/osmium/io/o5m_input.hpp index b63f72853..c59e3a6b6 100644 --- a/third_party/libosmium/include/osmium/io/o5m_input.hpp +++ b/third_party/libosmium/include/osmium/io/o5m_input.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/opl_output.hpp b/third_party/libosmium/include/osmium/io/opl_output.hpp index 04385d968..c79e260b6 100644 --- a/third_party/libosmium/include/osmium/io/opl_output.hpp +++ b/third_party/libosmium/include/osmium/io/opl_output.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/output_iterator.hpp b/third_party/libosmium/include/osmium/io/output_iterator.hpp index 1cf1d1dcb..ce050ebab 100644 --- a/third_party/libosmium/include/osmium/io/output_iterator.hpp +++ b/third_party/libosmium/include/osmium/io/output_iterator.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/overwrite.hpp b/third_party/libosmium/include/osmium/io/overwrite.hpp index f9fbc71af..5361698a5 100644 --- a/third_party/libosmium/include/osmium/io/overwrite.hpp +++ b/third_party/libosmium/include/osmium/io/overwrite.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/pbf_input.hpp b/third_party/libosmium/include/osmium/io/pbf_input.hpp index d7f3787ae..ab1f324d7 100644 --- a/third_party/libosmium/include/osmium/io/pbf_input.hpp +++ b/third_party/libosmium/include/osmium/io/pbf_input.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/pbf_output.hpp b/third_party/libosmium/include/osmium/io/pbf_output.hpp index dad1013d7..0a50f2cc9 100644 --- a/third_party/libosmium/include/osmium/io/pbf_output.hpp +++ b/third_party/libosmium/include/osmium/io/pbf_output.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/reader.hpp b/third_party/libosmium/include/osmium/io/reader.hpp index fd2a6d240..7c60511af 100644 --- a/third_party/libosmium/include/osmium/io/reader.hpp +++ b/third_party/libosmium/include/osmium/io/reader.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/reader_iterator.hpp b/third_party/libosmium/include/osmium/io/reader_iterator.hpp index 862078935..116442fd1 100644 --- a/third_party/libosmium/include/osmium/io/reader_iterator.hpp +++ b/third_party/libosmium/include/osmium/io/reader_iterator.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/writer.hpp b/third_party/libosmium/include/osmium/io/writer.hpp index 7cd133d0e..b389698fc 100644 --- a/third_party/libosmium/include/osmium/io/writer.hpp +++ b/third_party/libosmium/include/osmium/io/writer.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/writer_options.hpp b/third_party/libosmium/include/osmium/io/writer_options.hpp index ef1955312..9f6416424 100644 --- a/third_party/libosmium/include/osmium/io/writer_options.hpp +++ b/third_party/libosmium/include/osmium/io/writer_options.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/xml_input.hpp b/third_party/libosmium/include/osmium/io/xml_input.hpp index dfcd0a9fc..87f4ecc81 100644 --- a/third_party/libosmium/include/osmium/io/xml_input.hpp +++ b/third_party/libosmium/include/osmium/io/xml_input.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/io/xml_output.hpp b/third_party/libosmium/include/osmium/io/xml_output.hpp index 18a13869d..344487d5d 100644 --- a/third_party/libosmium/include/osmium/io/xml_output.hpp +++ b/third_party/libosmium/include/osmium/io/xml_output.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/memory/buffer.hpp b/third_party/libosmium/include/osmium/memory/buffer.hpp index bc6e9f8b9..07a31fed9 100644 --- a/third_party/libosmium/include/osmium/memory/buffer.hpp +++ b/third_party/libosmium/include/osmium/memory/buffer.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -39,9 +39,9 @@ DEALINGS IN THE SOFTWARE. #include #include #include +#include #include #include -#include #include #include @@ -108,7 +108,7 @@ namespace osmium { private: - std::vector m_memory; + std::unique_ptr m_memory; unsigned char* m_data; size_t m_capacity; size_t m_written; @@ -195,8 +195,8 @@ namespace osmium { * of the alignment. */ explicit Buffer(size_t capacity, auto_grow auto_grow = auto_grow::yes) : - m_memory(capacity), - m_data(m_memory.data()), + m_memory(new unsigned char[capacity]), + m_data(m_memory.get()), m_capacity(capacity), m_written(0), m_committed(0), @@ -302,18 +302,22 @@ namespace osmium { * memory management. * @throws std::invalid_argument if the size isn't a multiple * of the alignment. + * @throws std::bad_alloc if there isn't enough memory available. */ void grow(size_t size) { assert(m_data); - if (m_memory.empty()) { + if (!m_memory) { throw std::logic_error("Can't grow Buffer if it doesn't use internal memory management."); } if (m_capacity < size) { if (size % align_bytes != 0) { throw std::invalid_argument("buffer capacity needs to be multiple of alignment"); } - m_memory.resize(size); - m_data = m_memory.data(); + std::unique_ptr memory(new unsigned char[size]); + std::copy_n(m_memory.get(), m_capacity, memory.get()); + using std::swap; + swap(m_memory, memory); + m_data = m_memory.get(); m_capacity = size; } } @@ -418,7 +422,7 @@ namespace osmium { } // if there's still not enough space, then try growing the buffer. if (m_written + size > m_capacity) { - if (!m_memory.empty() && (m_auto_grow == auto_grow::yes)) { + if (m_memory && (m_auto_grow == auto_grow::yes)) { // double buffer size until there is enough space size_t new_capacity = m_capacity * 2; while (m_written + size > new_capacity) { @@ -654,16 +658,16 @@ namespace osmium { return m_data != nullptr; } - friend void swap(Buffer& lhs, Buffer& rhs) { + void swap(Buffer& other) { using std::swap; - swap(lhs.m_memory, rhs.m_memory); - swap(lhs.m_data, rhs.m_data); - swap(lhs.m_capacity, rhs.m_capacity); - swap(lhs.m_written, rhs.m_written); - swap(lhs.m_committed, rhs.m_committed); - swap(lhs.m_auto_grow, rhs.m_auto_grow); - swap(lhs.m_full, rhs.m_full); + swap(m_memory, other.m_memory); + swap(m_data, other.m_data); + swap(m_capacity, other.m_capacity); + swap(m_written, other.m_written); + swap(m_committed, other.m_committed); + swap(m_auto_grow, other.m_auto_grow); + swap(m_full, other.m_full); } /** @@ -714,6 +718,10 @@ namespace osmium { }; // class Buffer + inline void swap(Buffer& lhs, Buffer& rhs) { + lhs.swap(rhs); + } + /** * Compare two buffers for equality. * diff --git a/third_party/libosmium/include/osmium/memory/collection.hpp b/third_party/libosmium/include/osmium/memory/collection.hpp index 3878b9a3a..17ace7025 100644 --- a/third_party/libosmium/include/osmium/memory/collection.hpp +++ b/third_party/libosmium/include/osmium/memory/collection.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -95,12 +95,18 @@ namespace osmium { } template - friend std::basic_ostream& operator<<(std::basic_ostream& out, const CollectionIterator& iter) { - return out << static_cast(iter.m_data); + void print(std::basic_ostream& out) const { + out << static_cast(m_data); } }; // class CollectionIterator + template + inline std::basic_ostream& operator<<(std::basic_ostream& out, const CollectionIterator& iter) { + iter.print(out); + return out; + } + template class Collection : public Item { diff --git a/third_party/libosmium/include/osmium/memory/item.hpp b/third_party/libosmium/include/osmium/memory/item.hpp index f95ce8807..fd404ce93 100644 --- a/third_party/libosmium/include/osmium/memory/item.hpp +++ b/third_party/libosmium/include/osmium/memory/item.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/memory/item_iterator.hpp b/third_party/libosmium/include/osmium/memory/item_iterator.hpp index 87af56830..3886c9870 100644 --- a/third_party/libosmium/include/osmium/memory/item_iterator.hpp +++ b/third_party/libosmium/include/osmium/memory/item_iterator.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -209,12 +209,18 @@ namespace osmium { } template - friend std::basic_ostream& operator<<(std::basic_ostream& out, const ItemIterator& iter) { - return out << static_cast(iter.m_data); + void print(std::basic_ostream& out) const { + out << static_cast(m_data); } }; // class ItemIterator + template + inline std::basic_ostream& operator<<(std::basic_ostream& out, const ItemIterator& iter) { + iter.print(out); + return out; + } + } // namespace memory } // namespace osmium diff --git a/third_party/libosmium/include/osmium/object_pointer_collection.hpp b/third_party/libosmium/include/osmium/object_pointer_collection.hpp index 85566b6a4..09a52934e 100644 --- a/third_party/libosmium/include/osmium/object_pointer_collection.hpp +++ b/third_party/libosmium/include/osmium/object_pointer_collection.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm.hpp b/third_party/libosmium/include/osmium/osm.hpp index e92d9b8ef..594db7572 100644 --- a/third_party/libosmium/include/osmium/osm.hpp +++ b/third_party/libosmium/include/osmium/osm.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/area.hpp b/third_party/libosmium/include/osmium/osm/area.hpp index 7fb2a798b..ee232f0bd 100644 --- a/third_party/libosmium/include/osmium/osm/area.hpp +++ b/third_party/libosmium/include/osmium/osm/area.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/box.hpp b/third_party/libosmium/include/osmium/osm/box.hpp index 155f5e902..6fcf48d6c 100644 --- a/third_party/libosmium/include/osmium/osm/box.hpp +++ b/third_party/libosmium/include/osmium/osm/box.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -100,15 +100,15 @@ namespace osmium { /** * Extend this bounding box by the specified location. If the - * location is undefined, the bounding box is unchanged. If - * the box is undefined it will only contain the location after + * location is invalid, the bounding box is unchanged. If the + * box is undefined it will only contain the new location after * this call. * * @param location The location we want to extend the box by. * @returns A reference to this box. */ Box& extend(const Location& location) noexcept { - if (location) { + if (location.valid()) { if (m_bottom_left) { if (location.x() < m_bottom_left.x()) { m_bottom_left.set_x(location.x()); @@ -147,7 +147,7 @@ namespace osmium { * Box is defined, ie. contains defined locations. */ explicit constexpr operator bool() const noexcept { - return static_cast(m_bottom_left); + return bool(m_bottom_left) && bool(m_top_right); } /** @@ -203,6 +203,9 @@ namespace osmium { /** * Calculate size of the box in square degrees. * + * Note that this measure isn't very useful if you want to know the + * real-world size of the bounding box! + * * @throws osmium::invalid_location unless all coordinates are valid. */ double size() const { diff --git a/third_party/libosmium/include/osmium/osm/changeset.hpp b/third_party/libosmium/include/osmium/osm/changeset.hpp index db3f717da..f59db4808 100644 --- a/third_party/libosmium/include/osmium/osm/changeset.hpp +++ b/third_party/libosmium/include/osmium/osm/changeset.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/crc.hpp b/third_party/libosmium/include/osmium/osm/crc.hpp index f5e01e47b..ff39996f5 100644 --- a/third_party/libosmium/include/osmium/osm/crc.hpp +++ b/third_party/libosmium/include/osmium/osm/crc.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/diff_object.hpp b/third_party/libosmium/include/osmium/osm/diff_object.hpp index d9872eaea..609ab7453 100644 --- a/third_party/libosmium/include/osmium/osm/diff_object.hpp +++ b/third_party/libosmium/include/osmium/osm/diff_object.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/entity.hpp b/third_party/libosmium/include/osmium/osm/entity.hpp index c7f70553c..140a559bc 100644 --- a/third_party/libosmium/include/osmium/osm/entity.hpp +++ b/third_party/libosmium/include/osmium/osm/entity.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/entity_bits.hpp b/third_party/libosmium/include/osmium/osm/entity_bits.hpp index 1c1cb8027..50b3e4cb0 100644 --- a/third_party/libosmium/include/osmium/osm/entity_bits.hpp +++ b/third_party/libosmium/include/osmium/osm/entity_bits.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/item_type.hpp b/third_party/libosmium/include/osmium/osm/item_type.hpp index 95826bc98..272b2dd4d 100644 --- a/third_party/libosmium/include/osmium/osm/item_type.hpp +++ b/third_party/libosmium/include/osmium/osm/item_type.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/location.hpp b/third_party/libosmium/include/osmium/osm/location.hpp index f79117e0a..85f4b162a 100644 --- a/third_party/libosmium/include/osmium/osm/location.hpp +++ b/third_party/libosmium/include/osmium/osm/location.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/node.hpp b/third_party/libosmium/include/osmium/osm/node.hpp index 1ff7d1c28..677ffc784 100644 --- a/third_party/libosmium/include/osmium/osm/node.hpp +++ b/third_party/libosmium/include/osmium/osm/node.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/node_ref.hpp b/third_party/libosmium/include/osmium/osm/node_ref.hpp index e1c9c12e1..05b9ca711 100644 --- a/third_party/libosmium/include/osmium/osm/node_ref.hpp +++ b/third_party/libosmium/include/osmium/osm/node_ref.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/node_ref_list.hpp b/third_party/libosmium/include/osmium/osm/node_ref_list.hpp index f990b88c0..84edc0760 100644 --- a/third_party/libosmium/include/osmium/osm/node_ref_list.hpp +++ b/third_party/libosmium/include/osmium/osm/node_ref_list.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/object.hpp b/third_party/libosmium/include/osmium/osm/object.hpp index c0f46adbd..6d1de6f67 100644 --- a/third_party/libosmium/include/osmium/osm/object.hpp +++ b/third_party/libosmium/include/osmium/osm/object.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/object_comparisons.hpp b/third_party/libosmium/include/osmium/osm/object_comparisons.hpp index bdf99e11c..fe3529b4a 100644 --- a/third_party/libosmium/include/osmium/osm/object_comparisons.hpp +++ b/third_party/libosmium/include/osmium/osm/object_comparisons.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/relation.hpp b/third_party/libosmium/include/osmium/osm/relation.hpp index eec51193d..9c4e69cc7 100644 --- a/third_party/libosmium/include/osmium/osm/relation.hpp +++ b/third_party/libosmium/include/osmium/osm/relation.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/segment.hpp b/third_party/libosmium/include/osmium/osm/segment.hpp index fe43102fc..d35f97066 100644 --- a/third_party/libosmium/include/osmium/osm/segment.hpp +++ b/third_party/libosmium/include/osmium/osm/segment.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/tag.hpp b/third_party/libosmium/include/osmium/osm/tag.hpp index 4eba2210e..3f1a29826 100644 --- a/third_party/libosmium/include/osmium/osm/tag.hpp +++ b/third_party/libosmium/include/osmium/osm/tag.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/timestamp.hpp b/third_party/libosmium/include/osmium/osm/timestamp.hpp index 651b43f68..613752e68 100644 --- a/third_party/libosmium/include/osmium/osm/timestamp.hpp +++ b/third_party/libosmium/include/osmium/osm/timestamp.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -33,6 +33,7 @@ DEALINGS IN THE SOFTWARE. */ +#include #include #include #include @@ -177,8 +178,9 @@ namespace osmium { } /** - * Return UTC Unix time as string in ISO date/time - * ("yyyy-mm-ddThh:mm:ssZ") format. + * Return the timestamp as string in ISO date/time + * ("yyyy-mm-ddThh:mm:ssZ") format. If the timestamp is invalid, an + * empty string will be returned. */ std::string to_iso() const { std::string s; @@ -186,10 +188,15 @@ namespace osmium { if (m_timestamp != 0) { struct tm tm; time_t sse = seconds_since_epoch(); +#ifndef NDEBUG + auto result = +#endif #ifndef _MSC_VER - gmtime_r(&sse, &tm); + gmtime_r(&sse, &tm); + assert(result != nullptr); #else - gmtime_s(&tm, &sse); + gmtime_s(&tm, &sse); + assert(result == 0); #endif s.resize(timestamp_length); diff --git a/third_party/libosmium/include/osmium/osm/types.hpp b/third_party/libosmium/include/osmium/osm/types.hpp index e4250d966..984dd135c 100644 --- a/third_party/libosmium/include/osmium/osm/types.hpp +++ b/third_party/libosmium/include/osmium/osm/types.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/types_from_string.hpp b/third_party/libosmium/include/osmium/osm/types_from_string.hpp index 67ab2c157..aed064898 100644 --- a/third_party/libosmium/include/osmium/osm/types_from_string.hpp +++ b/third_party/libosmium/include/osmium/osm/types_from_string.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/undirected_segment.hpp b/third_party/libosmium/include/osmium/osm/undirected_segment.hpp index 654ef7d9a..c2442ae3c 100644 --- a/third_party/libosmium/include/osmium/osm/undirected_segment.hpp +++ b/third_party/libosmium/include/osmium/osm/undirected_segment.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/osm/way.hpp b/third_party/libosmium/include/osmium/osm/way.hpp index 90cde8c3c..3bc30b0c6 100644 --- a/third_party/libosmium/include/osmium/osm/way.hpp +++ b/third_party/libosmium/include/osmium/osm/way.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/relations/collector.hpp b/third_party/libosmium/include/osmium/relations/collector.hpp index 7d27b3398..af9d63c1a 100644 --- a/third_party/libosmium/include/osmium/relations/collector.hpp +++ b/third_party/libosmium/include/osmium/relations/collector.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/relations/detail/member_meta.hpp b/third_party/libosmium/include/osmium/relations/detail/member_meta.hpp index ea86734ea..a540f4378 100644 --- a/third_party/libosmium/include/osmium/relations/detail/member_meta.hpp +++ b/third_party/libosmium/include/osmium/relations/detail/member_meta.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/relations/detail/relation_meta.hpp b/third_party/libosmium/include/osmium/relations/detail/relation_meta.hpp index a48c50acc..93aa41cf2 100644 --- a/third_party/libosmium/include/osmium/relations/detail/relation_meta.hpp +++ b/third_party/libosmium/include/osmium/relations/detail/relation_meta.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/tags/filter.hpp b/third_party/libosmium/include/osmium/tags/filter.hpp index 0d3fc4ee2..407992e6d 100644 --- a/third_party/libosmium/include/osmium/tags/filter.hpp +++ b/third_party/libosmium/include/osmium/tags/filter.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/tags/regex_filter.hpp b/third_party/libosmium/include/osmium/tags/regex_filter.hpp index 725c42376..8ea6d60c3 100644 --- a/third_party/libosmium/include/osmium/tags/regex_filter.hpp +++ b/third_party/libosmium/include/osmium/tags/regex_filter.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/tags/taglist.hpp b/third_party/libosmium/include/osmium/tags/taglist.hpp index 8fc9c68cd..b1f346fe1 100644 --- a/third_party/libosmium/include/osmium/tags/taglist.hpp +++ b/third_party/libosmium/include/osmium/tags/taglist.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/thread/function_wrapper.hpp b/third_party/libosmium/include/osmium/thread/function_wrapper.hpp index 2fc0b7e22..4366c0a7c 100644 --- a/third_party/libosmium/include/osmium/thread/function_wrapper.hpp +++ b/third_party/libosmium/include/osmium/thread/function_wrapper.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/thread/pool.hpp b/third_party/libosmium/include/osmium/thread/pool.hpp index f7b4f4038..207f55514 100644 --- a/third_party/libosmium/include/osmium/thread/pool.hpp +++ b/third_party/libosmium/include/osmium/thread/pool.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/thread/queue.hpp b/third_party/libosmium/include/osmium/thread/queue.hpp index 65b18475c..771735883 100644 --- a/third_party/libosmium/include/osmium/thread/queue.hpp +++ b/third_party/libosmium/include/osmium/thread/queue.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/thread/sorted_queue.hpp b/third_party/libosmium/include/osmium/thread/sorted_queue.hpp index e76ade101..5478643c9 100644 --- a/third_party/libosmium/include/osmium/thread/sorted_queue.hpp +++ b/third_party/libosmium/include/osmium/thread/sorted_queue.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/thread/util.hpp b/third_party/libosmium/include/osmium/thread/util.hpp index a20e618a0..2ef331a2c 100644 --- a/third_party/libosmium/include/osmium/thread/util.hpp +++ b/third_party/libosmium/include/osmium/thread/util.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/cast.hpp b/third_party/libosmium/include/osmium/util/cast.hpp index 4866fdec4..c31ffce79 100644 --- a/third_party/libosmium/include/osmium/util/cast.hpp +++ b/third_party/libosmium/include/osmium/util/cast.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/compatibility.hpp b/third_party/libosmium/include/osmium/util/compatibility.hpp index 27adca7b7..b83cc1558 100644 --- a/third_party/libosmium/include/osmium/util/compatibility.hpp +++ b/third_party/libosmium/include/osmium/util/compatibility.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/config.hpp b/third_party/libosmium/include/osmium/util/config.hpp index e31cd6a9b..c40512322 100644 --- a/third_party/libosmium/include/osmium/util/config.hpp +++ b/third_party/libosmium/include/osmium/util/config.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/delta.hpp b/third_party/libosmium/include/osmium/util/delta.hpp index 558a1d4f9..34c4eb228 100644 --- a/third_party/libosmium/include/osmium/util/delta.hpp +++ b/third_party/libosmium/include/osmium/util/delta.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/double.hpp b/third_party/libosmium/include/osmium/util/double.hpp index e0701394c..1352c5fb1 100644 --- a/third_party/libosmium/include/osmium/util/double.hpp +++ b/third_party/libosmium/include/osmium/util/double.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/endian.hpp b/third_party/libosmium/include/osmium/util/endian.hpp index a5d91543e..fe23a5517 100644 --- a/third_party/libosmium/include/osmium/util/endian.hpp +++ b/third_party/libosmium/include/osmium/util/endian.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/file.hpp b/third_party/libosmium/include/osmium/util/file.hpp index 39e01af83..86b93ff72 100644 --- a/third_party/libosmium/include/osmium/util/file.hpp +++ b/third_party/libosmium/include/osmium/util/file.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/memory.hpp b/third_party/libosmium/include/osmium/util/memory.hpp new file mode 100644 index 000000000..7ef445b1d --- /dev/null +++ b/third_party/libosmium/include/osmium/util/memory.hpp @@ -0,0 +1,99 @@ +#ifndef OSMIUM_UTIL_MEMORY_HPP +#define OSMIUM_UTIL_MEMORY_HPP + +/* + +This file is part of Osmium (http://osmcode.org/libosmium). + +Copyright 2013-2016 Jochen Topf 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 +#include +#include + +namespace osmium { + + class MemoryUsage { + + int m_current = 0; + int m_peak = 0; + +#ifdef __linux__ + int parse_number(const std::string& line) { + int f = line.find_first_of("0123456789"); + int l = line.find_last_of("0123456789"); + return std::atoi(line.substr(f, l-f+1).c_str()); + } +#endif + + public: + + /** + * Get the memory usage for the current process. The constructor will + * get the memory usage. Use the current() and peak() calls to access + * the result. + * + * This will only work on Linux, on other architectures this will + * always return 0. + */ + MemoryUsage() { +#ifdef __linux__ + static const char* filename = "/proc/self/status"; + std::ifstream status_file(filename); + + if (status_file.is_open()) { + std::string line; + while (! status_file.eof() ) { + std::getline(status_file, line); + if (line.substr(0, 6) == "VmPeak") { + m_peak = parse_number(line); + } + if (line.substr(0, 6) == "VmSize") { + m_current = parse_number(line); + } + } + } +#endif + } + + /// Return current memory usage in MBytes + int current() const { + return m_current / 1024; + } + + /// Return peak memory usage in MBytes + int peak() const { + return m_peak / 1024; + } + + }; // class MemoryUsage + +} // namespace osmium + +#endif // OSMIUM_UTIL_MEMORY_HPP diff --git a/third_party/libosmium/include/osmium/util/memory_mapping.hpp b/third_party/libosmium/include/osmium/util/memory_mapping.hpp index b187c3c80..67e944e70 100644 --- a/third_party/libosmium/include/osmium/util/memory_mapping.hpp +++ b/third_party/libosmium/include/osmium/util/memory_mapping.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/minmax.hpp b/third_party/libosmium/include/osmium/util/minmax.hpp index 2eb601a24..b4ff4ea90 100644 --- a/third_party/libosmium/include/osmium/util/minmax.hpp +++ b/third_party/libosmium/include/osmium/util/minmax.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/options.hpp b/third_party/libosmium/include/osmium/util/options.hpp index 1019c8bbf..9b00b4811 100644 --- a/third_party/libosmium/include/osmium/util/options.hpp +++ b/third_party/libosmium/include/osmium/util/options.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/string.hpp b/third_party/libosmium/include/osmium/util/string.hpp index 55bfc6cd5..1198288c0 100644 --- a/third_party/libosmium/include/osmium/util/string.hpp +++ b/third_party/libosmium/include/osmium/util/string.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/include/osmium/util/verbose_output.hpp b/third_party/libosmium/include/osmium/util/verbose_output.hpp index 249d67fbf..c7677a436 100644 --- a/third_party/libosmium/include/osmium/util/verbose_output.hpp +++ b/third_party/libosmium/include/osmium/util/verbose_output.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 @@ -115,23 +115,28 @@ namespace osmium { } template - friend VerboseOutput& operator<<(VerboseOutput& verbose_output, const T& value) { - if (verbose_output.m_verbose) { - verbose_output.start_line(); + void print(const T& value) { + if (m_verbose) { + start_line(); std::cerr << value; // check if there was a newline a the end and remember that std::ostringstream output_buffer; output_buffer << value; if (!output_buffer.str().empty() && output_buffer.str().back() == '\n') { - verbose_output.m_newline = true; + m_newline = true; } } - return verbose_output; } }; // class VerboseOutput + template + inline VerboseOutput& operator<<(VerboseOutput& verbose_output, const T& value) { + verbose_output.print(value); + return verbose_output; + } + } // namespace util } // namespace osmium diff --git a/third_party/libosmium/include/osmium/visitor.hpp b/third_party/libosmium/include/osmium/visitor.hpp index c76eb17df..427096864 100644 --- a/third_party/libosmium/include/osmium/visitor.hpp +++ b/third_party/libosmium/include/osmium/visitor.hpp @@ -5,7 +5,7 @@ This file is part of Osmium (http://osmcode.org/libosmium). -Copyright 2013-2015 Jochen Topf and others (see README). +Copyright 2013-2016 Jochen Topf and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 diff --git a/third_party/libosmium/test/CMakeLists.txt b/third_party/libosmium/test/CMakeLists.txt deleted file mode 100644 index f57416120..000000000 --- a/third_party/libosmium/test/CMakeLists.txt +++ /dev/null @@ -1,184 +0,0 @@ -#----------------------------------------------------------------------------- -# -# CMake Config -# -# Libosmium unit tests -# -#----------------------------------------------------------------------------- - -message(STATUS "Configuring unit tests") - -include(CMakeParseArguments) -include_directories(include) - -add_library(testlib STATIC test_main.cpp) - -set(ALL_TESTS "") - -# Otherwise GCC throws a lot of warnings for REQUIRE(...) from Catch v.1.2.1 -if(CMAKE_COMPILER_IS_GNUCXX) - add_definitions(-Wno-parentheses) -endif() - - -#----------------------------------------------------------------------------- -# -# Define function for adding tests -# -# add_unit_tests(group name [ENABLE_IF bool] [LIBS libs] [LABELS labels]) -# -# group - test group (directory) -# name - name of test -# bool - boolean variable telling whether the test should be run (optional) -# libs - lib or libs that should be used when compiling test (optional) -# labels - additional labels this test should get (optional) -# -#----------------------------------------------------------------------------- -function(add_unit_test _tgroup _tname) - set(_testid "${_tgroup}_${_tname}") - set(_tpath "${_tgroup}/${_tname}") - - set(ALL_TESTS "${ALL_TESTS};${_tpath}" PARENT_SCOPE) - - cmake_parse_arguments(_param "" "ENABLE_IF" "LIBS;LABELS" ${ARGN}) - - if(Osmium_DEBUG) - message("${_testid} ENABLE_IF=[${_param_ENABLE_IF}] LIBS=[${_param_LIBS}] LABELS=[${_param_LABELS}]") - endif() - - if((NOT(DEFINED _param_ENABLE_IF)) OR (_param_ENABLE_IF)) - if(Osmium_DEBUG) - message("Adding test: ${_tpath}") - endif() - add_executable(${_testid} t/${_tpath}.cpp) - target_link_libraries(${_testid} testlib) - - if(DEFINED _param_LIBS) - if(Osmium_DEBUG) - message(" Adding libs: ${_param_LIBS}") - endif() - target_link_libraries(${_testid} ${_param_LIBS}) - endif() - - add_test(NAME ${_testid} - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} - COMMAND ${_testid} - ) - - set(_labels "unit;fast;${_tgroup}") - if(DEFINED _param_LABELS) - if(Osmium_DEBUG) - message(" Adding labels: ${_param_LABELS}") - endif() - set(_labels "${_labels};${_param_LABELS}") - endif() - - set_tests_properties(${_testid} PROPERTIES - LABELS "${_labels}" - ENVIRONMENT "OSMIUM_TEST_DATA_DIR=${CMAKE_CURRENT_SOURCE_DIR}" - ) - else() - message("Skipped test ${_tpath} because a dependency was not found") - set(OSMIUM_SKIPPED_TESTS - "${OSMIUM_SKIPPED_TESTS} ${_tpath}" - CACHE STRING "Tests that were skipped because of missing dependecies") - endif() -endfunction() - -#----------------------------------------------------------------------------- -# -# Add all tests. -# -#----------------------------------------------------------------------------- -add_unit_test(area test_area_id) -add_unit_test(area test_node_ref_segment) - -add_unit_test(basic test_box) -add_unit_test(basic test_changeset) -add_unit_test(basic test_crc) -add_unit_test(basic test_entity_bits) -add_unit_test(basic test_location) -add_unit_test(basic test_node) -add_unit_test(basic test_node_ref) -add_unit_test(basic test_object_comparisons) -add_unit_test(basic test_relation) -add_unit_test(basic test_timestamp) -add_unit_test(basic test_types_from_string) -add_unit_test(basic test_way) - -add_unit_test(buffer test_buffer_basics) -add_unit_test(buffer test_buffer_node) -add_unit_test(buffer test_buffer_purge) - -if(GEOS_FOUND AND PROJ_FOUND) - set(GEOS_AND_PROJ_FOUND TRUE) -else() - set(GEOS_AND_PROJ_FOUND FALSE) -endif() -add_unit_test(geom test_factory_with_projection - ENABLE_IF ${GEOS_AND_PROJ_FOUND} - LIBS ${GEOS_LIBRARY} ${PROJ_LIBRARY}) - -add_unit_test(geom test_exception) -add_unit_test(geom test_geojson) -add_unit_test(geom test_geos ENABLE_IF ${GEOS_FOUND} LIBS ${GEOS_LIBRARY}) -add_unit_test(geom test_geos_wkb ENABLE_IF ${GEOS_FOUND} LIBS ${GEOS_LIBRARY}) -add_unit_test(geom test_mercator) -add_unit_test(geom test_ogr ENABLE_IF ${GDAL_FOUND} LIBS ${GDAL_LIBRARY}) -add_unit_test(geom test_projection ENABLE_IF ${PROJ_FOUND} LIBS ${PROJ_LIBRARY}) -add_unit_test(geom test_tile) -add_unit_test(geom test_wkb) -add_unit_test(geom test_wkt) - -add_unit_test(index test_id_to_location ENABLE_IF ${SPARSEHASH_FOUND}) - -add_unit_test(io test_bzip2 ENABLE_IF ${BZIP2_FOUND} LIBS ${BZIP2_LIBRARIES}) -add_unit_test(io test_file_formats) -add_unit_test(io test_reader LIBS "${OSMIUM_XML_LIBRARIES};${OSMIUM_PBF_LIBRARIES}") -add_unit_test(io test_reader_with_mock_decompression ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES}) -add_unit_test(io test_reader_with_mock_parser ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT}) -add_unit_test(io test_output_utils) -add_unit_test(io test_output_iterator ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT}) -add_unit_test(io test_string_table) -add_unit_test(io test_writer ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES}) -add_unit_test(io test_writer_with_mock_compression ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES}) -add_unit_test(io test_writer_with_mock_encoder ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES}) - -add_unit_test(tags test_filter) -add_unit_test(tags test_operators) -add_unit_test(tags test_tag_list) - -add_unit_test(thread test_pool ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT}) - -add_unit_test(util test_cast_with_assert) -add_unit_test(util test_delta) -add_unit_test(util test_double) -add_unit_test(util test_file) -add_unit_test(util test_memory_mapping) -add_unit_test(util test_minmax) -add_unit_test(util test_options) -add_unit_test(util test_string) - - -#----------------------------------------------------------------------------- -# -# Check that all tests available in test/t/*/test_*.cpp are run. -# -#----------------------------------------------------------------------------- -file(GLOB TESTS_IN_DIR RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/t" t/*/test_*.cpp) - -foreach(file ${TESTS_IN_DIR}) - string(REPLACE ".cpp" "" out1 ${file}) - string(REPLACE "//" "/" tname ${out1}) - list(FIND ALL_TESTS ${tname} found) - if(${found} EQUAL -1) - message(WARNING "Test '${tname}' not found in cmake config. It will not be run!") - endif() -endforeach() - - -#----------------------------------------------------------------------------- -message(STATUS "Configuring unit tests - done") - - -#----------------------------------------------------------------------------- diff --git a/third_party/libosmium/test/README b/third_party/libosmium/test/README deleted file mode 100644 index 8195824b4..000000000 --- a/third_party/libosmium/test/README +++ /dev/null @@ -1,13 +0,0 @@ -Osmium uses Catch (https://github.com/philsquared/Catch/) for its unit tests. - -Only one header file is needed (catch.hpp) which can be downloaded from -http://builds.catch-lib.net/ and put into the include directory. - -Osmium needs a few changes to catch.hpp, they were patched in. To be able to -compare with the original version, it is stored in include/catch_orig.hpp. - -Changes are: -* Disable more warnings in GCC -* CATCH_CONFIG_CPP11_NULLPTR must be set for MSVC -* Problem with test running in loop: https://github.com/philsquared/Catch/issues/271 - diff --git a/third_party/libosmium/test/data-tests/.gitignore b/third_party/libosmium/test/data-tests/.gitignore deleted file mode 100644 index 98df22eda..000000000 --- a/third_party/libosmium/test/data-tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -multipolygon.qgs~ diff --git a/third_party/libosmium/test/data-tests/CMakeLists.txt b/third_party/libosmium/test/data-tests/CMakeLists.txt deleted file mode 100644 index a36c31cfd..000000000 --- a/third_party/libosmium/test/data-tests/CMakeLists.txt +++ /dev/null @@ -1,118 +0,0 @@ -#----------------------------------------------------------------------------- -# -# CMake Config -# -# Libosmium data tests -# -#----------------------------------------------------------------------------- - -message(STATUS "Configuring data tests") - -if(NOT GDAL_FOUND OR NOT EXPAT_FOUND) - message(STATUS "Sorry, building data tests needs GDAL and Expat") - message(STATUS "Configuring data tests - failed") - return() -endif() - -message(STATUS "Looking for osm-testdata") -find_path(OSM_TESTDATA grid/data/all.osm HINT ../../../osm-testdata) -if(OSM_TESTDATA STREQUAL "OSM_TESTDATA-NOTFOUND") - message(STATUS "Looking for osm-testdata - not found (data tests disabled)") - message(STATUS "Configuring data tests - failed") - return() -endif() -message(STATUS "Looking for osm-testdata - found") - - -#----------------------------------------------------------------------------- - -include_directories("include") -include_directories("../include") - - -#----------------------------------------------------------------------------- -# -# testcases -# -#----------------------------------------------------------------------------- -file(GLOB TESTCASE_CPPS testcases/*.cpp) -add_executable(testdata-testcases testdata-testcases.cpp ${TESTCASE_CPPS}) -target_link_libraries(testdata-testcases - ${OSMIUM_XML_LIBRARIES} -) -add_test(NAME testdata-testcases - COMMAND testdata-testcases -) -set_tests_properties(testdata-testcases PROPERTIES - ENVIRONMENT "TESTCASES_DIR=${OSM_TESTDATA}/grid/data" - LABELS "data;fast") - - -#----------------------------------------------------------------------------- -# -# xml -# -#----------------------------------------------------------------------------- -add_executable(testdata-xml testdata-xml.cpp) -target_link_libraries(testdata-xml - ${OSMIUM_XML_LIBRARIES} -) -add_test(NAME testdata-xml - COMMAND testdata-xml -) -set_tests_properties(testdata-xml PROPERTIES - ENVIRONMENT "TESTDIR=${OSM_TESTDATA}/xml/data" - LABELS "data;fast") - - -#----------------------------------------------------------------------------- -# -# overview -# -#----------------------------------------------------------------------------- -add_executable(testdata-overview testdata-overview.cpp) -target_link_libraries(testdata-overview - ${OSMIUM_XML_LIBRARIES} - ${GDAL_LIBRARIES} -) -add_test(NAME testdata-overview - COMMAND testdata-overview ${OSM_TESTDATA}/grid/data/all.osm -) -set_tests_properties(testdata-overview PROPERTIES - LABELS "data;slow") - - -#----------------------------------------------------------------------------- -# -# multipolygon -# -#----------------------------------------------------------------------------- - -find_program(RUBY ruby) -find_package(Gem COMPONENTS json) -find_program(SPATIALITE spatialite) - -if(RUBY AND GEM_json_FOUND AND SPATIALITE) - add_executable(testdata-multipolygon testdata-multipolygon.cpp) - target_link_libraries(testdata-multipolygon - ${OSMIUM_XML_LIBRARIES} - ${GDAL_LIBRARIES} - ) - - add_test(NAME testdata-multipolygon - COMMAND ${CMAKE_COMMAND} - -D OSM_TESTDATA=${OSM_TESTDATA} - -D RUBY=${RUBY} - -P ${CMAKE_CURRENT_SOURCE_DIR}/run-testdata-multipolygon.cmake) - - set_tests_properties(testdata-multipolygon PROPERTIES LABELS "data;slow") -else() - message(WARNING "Disabled testdata-multipolygon test because 'ruby' and/or 'json' ruby gem and/or 'spatialite' was not found") -endif() - - -#----------------------------------------------------------------------------- -message(STATUS "Configuring data tests - done") - - -#----------------------------------------------------------------------------- diff --git a/third_party/libosmium/test/data-tests/README.md b/third_party/libosmium/test/data-tests/README.md deleted file mode 100644 index 5138bf856..000000000 --- a/third_party/libosmium/test/data-tests/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# OSM Testdata - -This directory contains software that can be used with the osm-testdata -repository at https://github.com/osmcode/osm-testdata . To use it, clone -the `osm-testdata` repository in the same directory where you cloned the -`libosmium` repository. - -Tests will be built if the CMake option `BUILD_DATA_TESTS` is set and run as -part of the `ctest` run. - diff --git a/third_party/libosmium/test/data-tests/include/check_basics_handler.hpp b/third_party/libosmium/test/data-tests/include/check_basics_handler.hpp deleted file mode 100644 index 757ab4d3f..000000000 --- a/third_party/libosmium/test/data-tests/include/check_basics_handler.hpp +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef CHECK_BASICS_HANDLER_HPP -#define CHECK_BASICS_HANDLER_HPP - -#include -#include - -#include -#include - -/** - * Check some basics of the input data: - * - * 1. Correct number of nodes, ways, and relations - * 2. Correct ID space used by nodes, ways, and relations - * 3. No ID used more than once - */ -class CheckBasicsHandler : public osmium::handler::Handler { - - // Lower bound for the id range allowed in this test. - int m_id_range; - - // In the beginning these contains the number of nodes, ways, and relations - // supposedly in the data.osm file. They will be decremented on each object - // and have to be 0 at the end. - int m_num_nodes; - int m_num_ways; - int m_num_relations; - - // All IDs encountered in the data.osm file will be stored in this set and - // checked for duplicates. - std::unordered_set m_ids; - - // Check id is in range [min, max] and that it isn't more than once in input. - void id_check(osmium::object_id_type id, osmium::object_id_type min, osmium::object_id_type max) { - if (id < m_id_range + min || id > m_id_range + max) { - std::cerr << " id " << id << " out of range for this test case\n"; - exit(1); - } - - auto r = m_ids.insert(id); - if (!r.second) { - std::cerr << " id " << id << " contained twice in data.osm\n"; - exit(1); - } - } - -public: - - static const int ids_per_testcase = 1000; - - CheckBasicsHandler(int testcase, int nodes, int ways, int relations) : - osmium::handler::Handler(), - m_id_range(testcase * ids_per_testcase), - m_num_nodes(nodes), - m_num_ways(ways), - m_num_relations(relations) { - } - - ~CheckBasicsHandler() { - if (m_num_nodes != 0) { - std::cerr << " wrong number of nodes in data.osm\n"; - exit(1); - } - if (m_num_ways != 0) { - std::cerr << " wrong number of ways in data.osm\n"; - exit(1); - } - if (m_num_relations != 0) { - std::cerr << " wrong number of relations in data.osm\n"; - exit(1); - } - } - - void node(const osmium::Node& node) { - id_check(node.id(), 0, 799); - --m_num_nodes; - } - - void way(const osmium::Way& way) { - id_check(way.id(), 800, 899); - --m_num_ways; - } - - void relations(const osmium::Relation& relation) { - id_check(relation.id(), 900, 999); - --m_num_relations; - } - -}; // CheckBasicsHandler - - -#endif // CHECK_BASICS_HANDLER_HPP diff --git a/third_party/libosmium/test/data-tests/include/check_wkt_handler.hpp b/third_party/libosmium/test/data-tests/include/check_wkt_handler.hpp deleted file mode 100644 index fe0199e0a..000000000 --- a/third_party/libosmium/test/data-tests/include/check_wkt_handler.hpp +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef CHECK_WKT_HANDLER_HPP -#define CHECK_WKT_HANDLER_HPP - -#include -#include -#include -#include -#include - -#include -#include -#include - -class CheckWKTHandler : public osmium::handler::Handler { - - std::map m_geometries; - osmium::geom::WKTFactory<> m_factory; - - void read_wkt_file(const std::string& filename) { - std::ifstream in(filename, std::ifstream::in); - if (in) { - osmium::object_id_type id; - std::string line; - while (std::getline(in, line)) { - size_t pos = line.find_first_of(' '); - - if (pos == std::string::npos) { - std::cerr << filename << " not formatted correctly\n"; - exit(1); - } - - std::string id_str = line.substr(0, pos); - std::istringstream iss(id_str); - iss >> id; - - if (m_geometries.find(id) != m_geometries.end()) { - std::cerr << filename + " contains id " << id << "twice\n"; - exit(1); - } - - m_geometries[id] = line.substr(pos+1); - } - } - } - -public: - - CheckWKTHandler(const std::string& dirname, int test_id) : - osmium::handler::Handler() { - - std::string filename = dirname + "/" + std::to_string(test_id / 100) + "/" + std::to_string(test_id) + "/"; - read_wkt_file(filename + "nodes.wkt"); - read_wkt_file(filename + "ways.wkt"); - } - - ~CheckWKTHandler() { - if (!m_geometries.empty()) { - for (const auto& geom : m_geometries) { - std::cerr << "geometry id " << geom.first << " not in data.osm.\n"; - } - exit(1); - } - } - - void node(const osmium::Node& node) { - const std::string wkt = m_geometries[node.id()]; - assert(wkt != "" && "Missing geometry for node in nodes.wkt"); - - std::string this_wkt = m_factory.create_point(node.location()); - assert(wkt == this_wkt && "wkt geometries don't match"); - m_geometries.erase(node.id()); - } - - void way(const osmium::Way& way) { - const std::string wkt = m_geometries[way.id()]; - assert(wkt != "" && "Missing geometry for way in ways.wkt"); - - std::string this_wkt = m_factory.create_linestring(way); - assert(wkt == this_wkt && "wkt geometries don't match"); - m_geometries.erase(way.id()); - } - -}; // CheckWKTHandler - - -#endif // CHECK_WKT_HANDLER_HPP diff --git a/third_party/libosmium/test/data-tests/include/common.hpp b/third_party/libosmium/test/data-tests/include/common.hpp deleted file mode 100644 index a6fd3df61..000000000 --- a/third_party/libosmium/test/data-tests/include/common.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef COMMON_HPP -#define COMMON_HPP - -#include -#include - -#include -#include -#include -#include -#include - -typedef osmium::index::map::Dummy index_neg_type; -typedef osmium::index::map::SparseMemArray index_pos_type; -typedef osmium::handler::NodeLocationsForWays location_handler_type; - -#include "check_basics_handler.hpp" -#include "check_wkt_handler.hpp" - -#include "testdata-testcases.hpp" - -#endif // COMMON_HPP diff --git a/third_party/libosmium/test/data-tests/include/testdata-testcases.hpp b/third_party/libosmium/test/data-tests/include/testdata-testcases.hpp deleted file mode 100644 index d7d0c01d7..000000000 --- a/third_party/libosmium/test/data-tests/include/testdata-testcases.hpp +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef TESTDATA_TESTCASES_HPP -#define TESTDATA_TESTCASES_HPP - -#include - -#include - -extern std::string dirname; - -#endif // TESTDATA_TESTCASES_HPP diff --git a/third_party/libosmium/test/data-tests/multipolygon.qgs b/third_party/libosmium/test/data-tests/multipolygon.qgs deleted file mode 100644 index 5553670bb..000000000 --- a/third_party/libosmium/test/data-tests/multipolygon.qgs +++ /dev/null @@ -1,880 +0,0 @@ - - - - - - degrees - - 0.77500024999999972 - -0.84791712574962541 - 10.22498975000000065 - 3.94791712574962572 - - 0 - - - +proj=longlat +datum=WGS84 +no_defs - 3452 - 4326 - EPSG:4326 - WGS 84 - longlat - WGS84 - true - - - - - - - - - - - - - - - - - - - - lerrors20140228172357933 - dbname='./multipolygon.db' table="lerrors" (GEOMETRY) sql= - - - - - - Error Lines - - - +proj=longlat +datum=WGS84 +no_defs - 3452 - 4326 - EPSG:4326 - WGS 84 - longlat - WGS84 - true - - - spatialite - COALESCE( "OGC_FID", '<NULL>' ) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - 0 - 0 - OGC_FID - - - - - - - - - - - - . - - 0 - . - generatedlayout - - - - - - multipolygons20140221151811742 - dbname='./multipolygon.db' table="multipolygons" (GEOMETRY) sql= - - - - - - multipolygons - - - +proj=longlat +datum=WGS84 +no_defs - 3452 - 4326 - EPSG:4326 - WGS 84 - longlat - WGS84 - true - - - spatialite - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - 0 - 0 - OGC_FID - - - - - - - - - . - - 0 - . - generatedlayout - - - - - - perrors20140228163658956 - dbname='./multipolygon.db' table="perrors" (GEOMETRY) sql= - - - - - - Error Points - - - +proj=longlat +datum=WGS84 +no_defs - 3452 - 4326 - EPSG:4326 - WGS 84 - longlat - WGS84 - true - - - spatialite - COALESCE( "OGC_FID", '<NULL>' ) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 0 - 0 - 0 - OGC_FID - - - - - - - - - - - - . - - 0 - . - generatedlayout - - - - - - - - - - - 0.82500024999999999 - -0.35415386986094277 - 8.17498974999999994 - 3.45415386986094308 - - - - - - - false - - mp test - - - - 2 - true - D - - - - true - - false - - NONE - - - - - - - - 0 - 255 - 255 - 255 - 255 - 255 - 255 - - - - - - - - - - - EPSG:4326 - - - - - - true - 255 - - - - - - diff --git a/third_party/libosmium/test/data-tests/run-testdata-multipolygon.cmake b/third_party/libosmium/test/data-tests/run-testdata-multipolygon.cmake deleted file mode 100644 index 0d08f5a52..000000000 --- a/third_party/libosmium/test/data-tests/run-testdata-multipolygon.cmake +++ /dev/null @@ -1,46 +0,0 @@ -#----------------------------------------------------------------------------- -# -# Helper script that runs the 'multipolygon' test. -# -#----------------------------------------------------------------------------- - -# Remove files that might be left over from previous run -file(REMOVE multipolygon.db multipolygon-tests.json) - - -#----------------------------------------------------------------------------- -# -# Create multipolygons from test data. -# -#----------------------------------------------------------------------------- -execute_process( - COMMAND ${CMAKE_CURRENT_BINARY_DIR}/testdata-multipolygon - ${OSM_TESTDATA}/grid/data/all.osm - RESULT_VARIABLE _result - OUTPUT_FILE multipolygon.log - ERROR_FILE multipolygon.log -) - -if(_result) - message(FATAL_ERROR "Error running testdata-multipolygon command") -endif() - - -#----------------------------------------------------------------------------- -# -# Compare created multipolygons with reference data. -# -#----------------------------------------------------------------------------- -execute_process( - COMMAND ${RUBY} ${OSM_TESTDATA}/bin/compare-areas.rb - ${OSM_TESTDATA}/grid/data/tests.json - multipolygon-tests.json - RESULT_VARIABLE _result -) - -if(_result) - message(FATAL_ERROR "Error running compare-areas command") -endif() - - -#----------------------------------------------------------------------------- diff --git a/third_party/libosmium/test/data-tests/testcases/test-100.cpp b/third_party/libosmium/test/data-tests/testcases/test-100.cpp deleted file mode 100644 index feafe771a..000000000 --- a/third_party/libosmium/test/data-tests/testcases/test-100.cpp +++ /dev/null @@ -1,41 +0,0 @@ - -#include "common.hpp" - -class TestHandler100 : public osmium::handler::Handler { - -public: - - TestHandler100() : - osmium::handler::Handler() { - } - - void node(osmium::Node& node) { - if (node.id() == 100000) { - REQUIRE(node.version() == 1); - REQUIRE(node.timestamp() == osmium::Timestamp("2014-01-01T00:00:00Z")); - REQUIRE(node.uid() == 1); - REQUIRE(!strcmp(node.user(), "test")); - REQUIRE(node.changeset() == 1); - REQUIRE(node.location().lon() == 1.02); - REQUIRE(node.location().lat() == 1.02); - } else { - throw std::runtime_error("Unknown ID"); - } - } - -}; // class TestHandler100 - -TEST_CASE("100") { - - SECTION("test 100") { - osmium::io::Reader reader(dirname + "/1/100/data.osm"); - - CheckBasicsHandler check_basics_handler(100, 1, 0, 0); - CheckWKTHandler check_wkt_handler(dirname, 100); - TestHandler100 test_handler; - - osmium::apply(reader, check_basics_handler, check_wkt_handler, test_handler); - } - -} - diff --git a/third_party/libosmium/test/data-tests/testcases/test-101.cpp b/third_party/libosmium/test/data-tests/testcases/test-101.cpp deleted file mode 100644 index de2a5fdb7..000000000 --- a/third_party/libosmium/test/data-tests/testcases/test-101.cpp +++ /dev/null @@ -1,43 +0,0 @@ - -#include "common.hpp" - -class TestHandler101 : public osmium::handler::Handler { - -public: - - TestHandler101() : - osmium::handler::Handler() { - } - - void node(osmium::Node& node) { - if (node.id() == 101000) { - REQUIRE(node.version() == 1); - REQUIRE(node.location().lon() == 1.12); - REQUIRE(node.location().lat() == 1.02); - } else if (node.id() == 101001) { - REQUIRE(node.version() == 1); - REQUIRE(node.location().lon() == 1.12); - REQUIRE(node.location().lat() == 1.03); - } else if (node.id() == 101002) { - } else if (node.id() == 101003) { - } else { - throw std::runtime_error("Unknown ID"); - } - } - -}; // class TestHandler101 - -TEST_CASE("101") { - - SECTION("test 101") { - osmium::io::Reader reader(dirname + "/1/101/data.osm"); - - CheckBasicsHandler check_basics_handler(101, 4, 0, 0); - CheckWKTHandler check_wkt_handler(dirname, 101); - TestHandler101 test_handler; - - osmium::apply(reader, check_basics_handler, check_wkt_handler, test_handler); - } - -} - diff --git a/third_party/libosmium/test/data-tests/testcases/test-110.cpp b/third_party/libosmium/test/data-tests/testcases/test-110.cpp deleted file mode 100644 index 16b039b1b..000000000 --- a/third_party/libosmium/test/data-tests/testcases/test-110.cpp +++ /dev/null @@ -1,58 +0,0 @@ - -#include "common.hpp" - -class TestHandler110 : public osmium::handler::Handler { - -public: - - TestHandler110() : - osmium::handler::Handler() { - } - - void node(const osmium::Node& node) { - if (node.id() == 110000) { - REQUIRE(node.location().lon() == 1.02); - REQUIRE(node.location().lat() == 1.12); - } else if (node.id() == 110001) { - REQUIRE(node.location().lon() == 1.07); - REQUIRE(node.location().lat() == 1.13); - } else { - throw std::runtime_error("Unknown ID"); - } - } - - void way(const osmium::Way& way) { - if (way.id() == 110800) { - REQUIRE(way.version() == 1); - REQUIRE(way.nodes().size() == 2); - REQUIRE(!way.is_closed()); - - const char *test_id = way.tags().get_value_by_key("test:id"); - REQUIRE(test_id); - REQUIRE(!strcmp(test_id, "110")); - } else { - throw std::runtime_error("Unknown ID"); - } - } - -}; // class TestHandler110 - -TEST_CASE("110") { - - SECTION("test 110") { - osmium::io::Reader reader(dirname + "/1/110/data.osm"); - - index_pos_type index_pos; - index_neg_type index_neg; - location_handler_type location_handler(index_pos, index_neg); - location_handler.ignore_errors(); - - CheckBasicsHandler check_basics_handler(110, 2, 1, 0); - CheckWKTHandler check_wkt_handler(dirname, 110); - TestHandler110 test_handler; - - osmium::apply(reader, location_handler, check_basics_handler, check_wkt_handler, test_handler); - } - -} - diff --git a/third_party/libosmium/test/data-tests/testdata-multipolygon.cpp b/third_party/libosmium/test/data-tests/testdata-multipolygon.cpp deleted file mode 100644 index cf4fc521a..000000000 --- a/third_party/libosmium/test/data-tests/testdata-multipolygon.cpp +++ /dev/null @@ -1,182 +0,0 @@ - -#include -#include -#include - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -typedef osmium::index::map::SparseMemArray index_type; - -typedef osmium::handler::NodeLocationsForWays location_handler_type; - -struct less_charptr { - - bool operator()(const char* a, const char* b) const { - return std::strcmp(a, b) < 0; - } - -}; // less_charptr - -typedef std::map tagmap_type; - -inline tagmap_type create_map(const osmium::TagList& taglist) { - tagmap_type map; - - for (auto& tag : taglist) { - map[tag.key()] = tag.value(); - } - - return map; -} - -class TestHandler : public osmium::handler::Handler { - - gdalcpp::Layer m_layer_point; - gdalcpp::Layer m_layer_lines; - gdalcpp::Layer m_layer_mpoly; - - osmium::geom::OGRFactory<> m_ogr_factory; - osmium::geom::WKTFactory<> m_wkt_factory; - - std::ofstream m_out; - - bool m_first_out {true}; - -public: - - explicit TestHandler(gdalcpp::Dataset& dataset) : - m_layer_point(dataset, "points", wkbPoint), - m_layer_lines(dataset, "lines", wkbLineString), - m_layer_mpoly(dataset, "multipolygons", wkbMultiPolygon), - m_out("multipolygon-tests.json") { - - m_layer_point.add_field("id", OFTReal, 10); - m_layer_point.add_field("type", OFTString, 30); - - m_layer_lines.add_field("id", OFTReal, 10); - m_layer_lines.add_field("type", OFTString, 30); - - m_layer_mpoly.add_field("id", OFTReal, 10); - m_layer_mpoly.add_field("from_type", OFTString, 1); - } - - ~TestHandler() { - m_out << "\n]\n"; - } - - void node(const osmium::Node& node) { - gdalcpp::Feature feature(m_layer_point, m_ogr_factory.create_point(node)); - feature.set_field("id", static_cast(node.id())); - feature.set_field("type", node.tags().get_value_by_key("type")); - feature.add_to_layer(); - } - - void way(const osmium::Way& way) { - try { - gdalcpp::Feature feature(m_layer_lines, m_ogr_factory.create_linestring(way)); - feature.set_field("id", static_cast(way.id())); - feature.set_field("type", way.tags().get_value_by_key("type")); - feature.add_to_layer(); - } catch (osmium::geometry_error&) { - std::cerr << "Ignoring illegal geometry for way " << way.id() << ".\n"; - } - } - - void area(const osmium::Area& area) { - if (m_first_out) { - m_out << "[\n"; - m_first_out = false; - } else { - m_out << ",\n"; - } - m_out << "{\n \"test_id\": " << (area.orig_id() / 1000) << ",\n \"area_id\": " << area.id() << ",\n \"from_id\": " << area.orig_id() << ",\n \"from_type\": \"" << (area.from_way() ? "way" : "relation") << "\",\n \"wkt\": \""; - try { - std::string wkt = m_wkt_factory.create_multipolygon(area); - m_out << wkt << "\",\n \"tags\": {"; - - auto tagmap = create_map(area.tags()); - bool first = true; - for (auto& tag : tagmap) { - if (first) { - first = false; - } else { - m_out << ", "; - } - m_out << '"' << tag.first << "\": \"" << tag.second << '"'; - } - m_out << "}\n}"; - } catch (osmium::geometry_error&) { - m_out << "INVALID\"\n}"; - } - try { - gdalcpp::Feature feature(m_layer_mpoly, m_ogr_factory.create_multipolygon(area)); - feature.set_field("id", static_cast(area.orig_id())); - - std::string from_type; - if (area.from_way()) { - from_type = "w"; - } else { - from_type = "r"; - } - feature.set_field("from_type", from_type.c_str()); - feature.add_to_layer(); - } catch (osmium::geometry_error&) { - std::cerr << "Ignoring illegal geometry for area " << area.id() << " created from " << (area.from_way() ? "way" : "relation") << " with id=" << area.orig_id() << ".\n"; - } - } - -}; // class TestHandler - -/* ================================================== */ - -int main(int argc, char* argv[]) { - if (argc != 2) { - std::cerr << "Usage: " << argv[0] << " INFILE\n"; - exit(1); - } - - std::string output_format("SQLite"); - std::string input_filename(argv[1]); - std::string output_filename("multipolygon.db"); - - CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); - gdalcpp::Dataset dataset{output_format, output_filename, gdalcpp::SRS{}, { "SPATIALITE=TRUE" }}; - - osmium::area::ProblemReporterOGR problem_reporter(dataset); - osmium::area::Assembler::config_type assembler_config(&problem_reporter); - assembler_config.enable_debug_output(); - osmium::area::MultipolygonCollector collector(assembler_config); - - std::cerr << "Pass 1...\n"; - osmium::io::Reader reader1(input_filename); - collector.read_relations(reader1); - reader1.close(); - std::cerr << "Pass 1 done\n"; - - index_type index; - location_handler_type location_handler(index); - location_handler.ignore_errors(); - - TestHandler test_handler(dataset); - - std::cerr << "Pass 2...\n"; - osmium::io::Reader reader2(input_filename); - osmium::apply(reader2, location_handler, test_handler, collector.handler([&test_handler](const osmium::memory::Buffer& area_buffer) { - osmium::apply(area_buffer, test_handler); - })); - reader2.close(); - std::cerr << "Pass 2 done\n"; -} - diff --git a/third_party/libosmium/test/data-tests/testdata-overview.cpp b/third_party/libosmium/test/data-tests/testdata-overview.cpp deleted file mode 100644 index 43d672dd1..000000000 --- a/third_party/libosmium/test/data-tests/testdata-overview.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* The code in this file is released into the Public Domain. */ - -#include - -#include - -#include - -#include -#include -#include -#include -#include - -typedef osmium::index::map::SparseMemArray index_type; -typedef osmium::handler::NodeLocationsForWays location_handler_type; - -class TestOverviewHandler : public osmium::handler::Handler { - - gdalcpp::Layer m_layer_nodes; - gdalcpp::Layer m_layer_labels; - gdalcpp::Layer m_layer_ways; - - osmium::geom::OGRFactory<> m_factory; - -public: - - explicit TestOverviewHandler(gdalcpp::Dataset& dataset) : - m_layer_nodes(dataset, "nodes", wkbPoint), - m_layer_labels(dataset, "labels", wkbPoint), - m_layer_ways(dataset, "ways", wkbLineString) { - - m_layer_nodes.add_field("id", OFTReal, 10); - - m_layer_labels.add_field("id", OFTReal, 10); - m_layer_labels.add_field("label", OFTString, 30); - - m_layer_ways.add_field("id", OFTReal, 10); - m_layer_ways.add_field("test", OFTInteger, 3); - } - - void node(const osmium::Node& node) { - const char* label = node.tags().get_value_by_key("label"); - if (label) { - gdalcpp::Feature feature(m_layer_labels, m_factory.create_point(node)); - feature.set_field("id", static_cast(node.id())); - feature.set_field("label", label); - feature.add_to_layer(); - } else { - gdalcpp::Feature feature(m_layer_nodes, m_factory.create_point(node)); - feature.set_field("id", static_cast(node.id())); - feature.add_to_layer(); - } - } - - void way(const osmium::Way& way) { - try { - gdalcpp::Feature feature(m_layer_ways, m_factory.create_linestring(way)); - feature.set_field("id", static_cast(way.id())); - - const char* test = way.tags().get_value_by_key("test"); - if (test) { - feature.set_field("test", test); - } - - feature.add_to_layer(); - } catch (osmium::geometry_error&) { - std::cerr << "Ignoring illegal geometry for way " << way.id() << ".\n"; - } - } - -}; - -/* ================================================== */ - -int main(int argc, char* argv[]) { - if (argc != 2) { - std::cerr << "Usage: " << argv[0] << " INFILE\n"; - exit(1); - } - - std::string output_format("SQLite"); - std::string input_filename(argv[1]); - std::string output_filename("testdata-overview.db"); - ::unlink(output_filename.c_str()); - - CPLSetConfigOption("OGR_SQLITE_SYNCHRONOUS", "FALSE"); - gdalcpp::Dataset dataset(output_format, output_filename, gdalcpp::SRS{}, { "SPATIALITE=TRUE" }); - - osmium::io::Reader reader(input_filename); - - index_type index; - location_handler_type location_handler(index); - location_handler.ignore_errors(); - - TestOverviewHandler handler(dataset); - - osmium::apply(reader, location_handler, handler); - reader.close(); -} - diff --git a/third_party/libosmium/test/data-tests/testdata-testcases.cpp b/third_party/libosmium/test/data-tests/testdata-testcases.cpp deleted file mode 100644 index 0ea7fc859..000000000 --- a/third_party/libosmium/test/data-tests/testdata-testcases.cpp +++ /dev/null @@ -1,25 +0,0 @@ - -#include -#include - -#define CATCH_CONFIG_RUNNER - -#include "testdata-testcases.hpp" - -std::string dirname; - -int main(int argc, char* argv[]) { - const char* testcases_dir = getenv("TESTCASES_DIR"); - if (testcases_dir) { - dirname = testcases_dir; - std::cerr << "Running tests from '" << dirname << "' (from TESTCASES_DIR environment variable)\n"; - } else { - std::cerr << "Please set TESTCASES_DIR environment variable.\n"; - exit(1); - } - - int result = Catch::Session().run(argc, argv); - - return result; -} - diff --git a/third_party/libosmium/test/data-tests/testdata-xml.cpp b/third_party/libosmium/test/data-tests/testdata-xml.cpp deleted file mode 100644 index b5a0e9028..000000000 --- a/third_party/libosmium/test/data-tests/testdata-xml.cpp +++ /dev/null @@ -1,561 +0,0 @@ -/* The code in this file is released into the Public Domain. */ - -#define CATCH_CONFIG_MAIN -#include "catch.hpp" - -#include -#include -#include -#include - -#include -#include -#include -#include - -std::string S_(const char* s) { - return std::string(s); -} - -std::string filename(const char* test_id, const char* suffix = "osm") { - const char* testdir = getenv("TESTDIR"); - if (!testdir) { - std::cerr << "You have to set TESTDIR environment variable before running testdata-xml\n"; - exit(2); - } - - std::string f; - f += testdir; - f += "/"; - f += test_id; - f += "/data."; - f += suffix; - return f; -} - -struct header_buffer_type { - osmium::io::Header header; - osmium::memory::Buffer buffer; -}; - -// ============================================= - -// The following helper functions are used to call different parts of the -// Osmium internals used to read and parse XML files. This way those parts -// can be tested individually. These function can not be used in normal -// operations, because they make certain assumptions, for instance that -// file contents fit into small buffers. - -std::string read_file(const char* test_id) { - int fd = osmium::io::detail::open_for_reading(filename(test_id)); - assert(fd >= 0); - - std::string input(10000, '\0'); - auto n = ::read(fd, reinterpret_cast(const_cast(input.data())), 10000); - assert(n >= 0); - input.resize(static_cast(n)); - - close(fd); - - return input; -} - -std::string read_gz_file(const char* test_id, const char* suffix) { - int fd = osmium::io::detail::open_for_reading(filename(test_id, suffix)); - assert(fd >= 0); - - osmium::io::GzipDecompressor gzip_decompressor(fd); - std::string input = gzip_decompressor.read(); - gzip_decompressor.close(); - - return input; -} - - -header_buffer_type parse_xml(std::string input) { - osmium::io::detail::future_string_queue_type input_queue; - osmium::io::detail::future_buffer_queue_type output_queue; - std::promise header_promise; - std::future header_future = header_promise.get_future(); - - osmium::io::detail::add_to_queue(input_queue, std::move(input)); - osmium::io::detail::add_to_queue(input_queue, std::string{}); - - osmium::io::detail::XMLParser parser(input_queue, output_queue, header_promise, osmium::osm_entity_bits::all); - parser.parse(); - - header_buffer_type result; - result.header = header_future.get(); - std::future future_buffer; - output_queue.wait_and_pop(future_buffer); - result.buffer = future_buffer.get(); - - if (result.buffer) { - std::future future_buffer2; - output_queue.wait_and_pop(future_buffer2); - assert(!future_buffer2.get()); - } - - return result; -} - -header_buffer_type read_xml(const char* test_id) { - std::string input = read_file(test_id); - return parse_xml(input); -} - -// ============================================= - -TEST_CASE("Reading OSM XML 100") { - - SECTION("Direct") { - header_buffer_type r = read_xml("100-correct_but_no_data"); - - REQUIRE(r.header.get("generator") == "testdata"); - REQUIRE(0 == r.buffer.committed()); - REQUIRE(! r.buffer); - } - - SECTION("Using Reader") { - osmium::io::Reader reader(filename("100-correct_but_no_data")); - - osmium::io::Header header = reader.header(); - REQUIRE(header.get("generator") == "testdata"); - - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(0 == buffer.committed()); - REQUIRE(! buffer); - reader.close(); - } - - SECTION("Using Reader asking for header only") { - osmium::io::Reader reader(filename("100-correct_but_no_data"), osmium::osm_entity_bits::nothing); - - osmium::io::Header header = reader.header(); - REQUIRE(header.get("generator") == "testdata"); - reader.close(); - } - -} - -// ============================================= - -TEST_CASE("Reading OSM XML 101") { - - SECTION("Direct") { - REQUIRE_THROWS_AS(read_xml("101-missing_version"), osmium::format_version_error); - try { - read_xml("101-missing_version"); - } catch (osmium::format_version_error& e) { - REQUIRE(e.version.empty()); - } - } - - SECTION("Using Reader") { - REQUIRE_THROWS_AS({ - osmium::io::Reader reader(filename("101-missing_version")); - osmium::io::Header header = reader.header(); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - }, osmium::format_version_error); - } - -} - -// ============================================= - -TEST_CASE("Reading OSM XML 102") { - - SECTION("Direct") { - REQUIRE_THROWS_AS(read_xml("102-wrong_version"), osmium::format_version_error); - try { - read_xml("102-wrong_version"); - } catch (osmium::format_version_error& e) { - REQUIRE(e.version == "0.1"); - } - } - - SECTION("Using Reader") { - REQUIRE_THROWS_AS({ - osmium::io::Reader reader(filename("102-wrong_version")); - - osmium::io::Header header = reader.header(); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - }, osmium::format_version_error); - } - -} - -// ============================================= - -TEST_CASE("Reading OSM XML 103") { - - SECTION("Direct") { - REQUIRE_THROWS_AS(read_xml("103-old_version"), osmium::format_version_error); - try { - read_xml("103-old_version"); - } catch (osmium::format_version_error& e) { - REQUIRE(e.version == "0.5"); - } - } - - SECTION("Using Reader") { - REQUIRE_THROWS_AS({ - osmium::io::Reader reader(filename("103-old_version")); - osmium::io::Header header = reader.header(); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - }, osmium::format_version_error); - } - -} - -// ============================================= - -TEST_CASE("Reading OSM XML 104") { - - SECTION("Direct") { - REQUIRE_THROWS_AS(read_xml("104-empty_file"), osmium::xml_error); - try { - read_xml("104-empty_file"); - } catch (osmium::xml_error& e) { - REQUIRE(e.line == 1); - REQUIRE(e.column == 0); - } - } - - SECTION("Using Reader") { - REQUIRE_THROWS_AS({ - osmium::io::Reader reader(filename("104-empty_file")); - osmium::io::Header header = reader.header(); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - }, osmium::xml_error); - } -} - -// ============================================= - -TEST_CASE("Reading OSM XML 105") { - - SECTION("Direct") { - REQUIRE_THROWS_AS(read_xml("105-incomplete_xml_file"), osmium::xml_error); - } - - SECTION("Using Reader") { - REQUIRE_THROWS_AS({ - osmium::io::Reader reader(filename("105-incomplete_xml_file")); - osmium::io::Header header = reader.header(); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - }, osmium::xml_error); - } - -} - -// ============================================= - -TEST_CASE("Reading OSM XML 120") { - - SECTION("Direct") { - std::string data = read_gz_file("120-correct_gzip_file_without_data", "osm.gz"); - - REQUIRE(data.size() == 102); - - header_buffer_type r = parse_xml(data); - REQUIRE(r.header.get("generator") == "testdata"); - REQUIRE(0 == r.buffer.committed()); - REQUIRE(! r.buffer); - } - - SECTION("Using Reader") { - osmium::io::Reader reader(filename("120-correct_gzip_file_without_data", "osm.gz")); - - osmium::io::Header header = reader.header(); - REQUIRE(header.get("generator") == "testdata"); - - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(0 == buffer.committed()); - REQUIRE(! buffer); - reader.close(); - } - -} - -// ============================================= - -TEST_CASE("Reading OSM XML 121") { - - SECTION("Direct") { - REQUIRE_THROWS_AS( { - read_gz_file("121-truncated_gzip_file", "osm.gz"); - }, osmium::gzip_error); - } - - SECTION("Using Reader") { - // can throw osmium::gzip_error or osmium::xml_error - REQUIRE_THROWS({ - osmium::io::Reader reader(filename("121-truncated_gzip_file", "osm.gz")); - osmium::io::Header header = reader.header(); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - }); - } - -} - -// ============================================= - -TEST_CASE("Reading OSM XML 122") { - - SECTION("Direct") { - REQUIRE_THROWS_AS( { - read_xml("122-no_osm_element"); - }, osmium::xml_error); - } - - SECTION("Using Reader") { - REQUIRE_THROWS_AS({ - osmium::io::Reader reader(filename("122-no_osm_element")); - osmium::io::Header header = reader.header(); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - }, osmium::xml_error); - } - -} - -// ============================================= - -TEST_CASE("Reading OSM XML 140") { - - SECTION("Using Reader") { - osmium::io::Reader reader(filename("140-unicode")); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - - int count = 0; - for (auto it = buffer.begin(); it != buffer.end(); ++it) { - ++count; - REQUIRE(it->id() == count); - const osmium::TagList& t = it->tags(); - - const char* uc = t["unicode_char"]; - - auto len = atoi(t["unicode_utf8_length"]); - REQUIRE(len == strlen(uc)); - - REQUIRE(S_(uc) == t["unicode_xml"]); - -// workaround for missing support for u8 string literals on Windows -#if !defined(_MSC_VER) - switch (count) { - case 1: - REQUIRE(S_(uc) == u8"a"); - break; - case 2: - REQUIRE(S_(uc) == u8"\u00e4"); - break; - case 3: - REQUIRE(S_(uc) == u8"\u30dc"); - break; - case 4: - REQUIRE(S_(uc) == u8"\U0001d11e"); - break; - case 5: - REQUIRE(S_(uc) == u8"\U0001f6eb"); - break; - default: - REQUIRE(false); // should not be here - } -#endif - } - REQUIRE(count == 5); - } - -} - - -// ============================================= - -TEST_CASE("Reading OSM XML 141") { - - SECTION("Using Reader") { - osmium::io::Reader reader(filename("141-entities")); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - REQUIRE(buffer.committed() > 0); - REQUIRE(buffer.get(0).type() == osmium::item_type::node); - - const osmium::Node& node = buffer.get(0); - const osmium::TagList& tags = node.tags(); - - REQUIRE(S_(tags["less-than"]) == "<"); - REQUIRE(S_(tags["greater-than"]) == ">"); - REQUIRE(S_(tags["apostrophe"]) == "'"); - REQUIRE(S_(tags["ampersand"]) == "&"); - REQUIRE(S_(tags["quote"]) == "\""); - } - -} - - -// ============================================= - -TEST_CASE("Reading OSM XML 142") { - - SECTION("Using Reader to read nodes") { - osmium::io::Reader reader(filename("142-whitespace")); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - - int count = 0; - for (auto it = buffer.begin(); it != buffer.end(); ++it) { - ++count; - REQUIRE(it->id() == count); - REQUIRE(it->tags().size() == 1); - const osmium::Tag& tag = *(it->tags().begin()); - - switch (count) { - case 1: - REQUIRE(S_(it->user()) == "user name"); - REQUIRE(S_(tag.key()) == "key with space"); - REQUIRE(S_(tag.value()) == "value with space"); - break; - case 2: - REQUIRE(S_(it->user()) == "line\nfeed"); - REQUIRE(S_(tag.key()) == "key with\nlinefeed"); - REQUIRE(S_(tag.value()) == "value with\nlinefeed"); - break; - case 3: - REQUIRE(S_(it->user()) == "carriage\rreturn"); - REQUIRE(S_(tag.key()) == "key with\rcarriage\rreturn"); - REQUIRE(S_(tag.value()) == "value with\rcarriage\rreturn"); - break; - case 4: - REQUIRE(S_(it->user()) == "tab\tulator"); - REQUIRE(S_(tag.key()) == "key with\ttab"); - REQUIRE(S_(tag.value()) == "value with\ttab"); - break; - case 5: - REQUIRE(S_(it->user()) == "unencoded linefeed"); - REQUIRE(S_(tag.key()) == "key with unencoded linefeed"); - REQUIRE(S_(tag.value()) == "value with unencoded linefeed"); - break; - default: - REQUIRE(false); // should not be here - } - } - REQUIRE(count == 5); - } - - SECTION("Using Reader to read relation") { - osmium::io::Reader reader(filename("142-whitespace")); - osmium::memory::Buffer buffer = reader.read(); - reader.close(); - - auto it = buffer.begin(); - REQUIRE(it != buffer.end()); - REQUIRE(it->id() == 21); - const auto& members = it->members(); - REQUIRE(members.size() == 5); - - int count = 0; - for (const auto& member : members) { - ++count; - switch (count) { - case 1: - REQUIRE(S_(member.role()) == "role with whitespace"); - break; - case 2: - REQUIRE(S_(member.role()) == "role with\nlinefeed"); - break; - case 3: - REQUIRE(S_(member.role()) == "role with\rcarriage\rreturn"); - break; - case 4: - REQUIRE(S_(member.role()) == "role with\ttab"); - break; - case 5: - REQUIRE(S_(member.role()) == "role with unencoded linefeed"); - break; - default: - REQUIRE(false); // should not be here - } - } - REQUIRE(count == 5); - } - -} - - -// ============================================= - -TEST_CASE("Reading OSM XML 200") { - - SECTION("Direct") { - header_buffer_type r = read_xml("200-nodes"); - - REQUIRE(r.header.get("generator") == "testdata"); - REQUIRE(r.buffer.committed() > 0); - REQUIRE(r.buffer.get(0).type() == osmium::item_type::node); - REQUIRE(r.buffer.get(0).id() == 36966060); - REQUIRE(std::distance(r.buffer.begin(), r.buffer.end()) == 3); - } - - SECTION("Using Reader") { - osmium::io::Reader reader(filename("200-nodes")); - - osmium::io::Header header = reader.header(); - REQUIRE(header.get("generator") == "testdata"); - - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(buffer.committed() > 0); - REQUIRE(buffer.get(0).type() == osmium::item_type::node); - REQUIRE(buffer.get(0).id() == 36966060); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 3); - reader.close(); - } - - SECTION("Using Reader asking for nodes") { - osmium::io::Reader reader(filename("200-nodes"), osmium::osm_entity_bits::node); - - osmium::io::Header header = reader.header(); - REQUIRE(header.get("generator") == "testdata"); - - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(buffer.committed() > 0); - REQUIRE(buffer.get(0).type() == osmium::item_type::node); - REQUIRE(buffer.get(0).id() == 36966060); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 3); - reader.close(); - } - - SECTION("Using Reader asking for header only") { - osmium::io::Reader reader(filename("200-nodes"), osmium::osm_entity_bits::nothing); - - osmium::io::Header header = reader.header(); - REQUIRE(header.get("generator") == "testdata"); - - REQUIRE_THROWS({ - reader.read(); - }); - - reader.close(); - } - - SECTION("Using Reader asking for ways") { - osmium::io::Reader reader(filename("200-nodes"), osmium::osm_entity_bits::way); - - osmium::io::Header header = reader.header(); - REQUIRE(header.get("generator") == "testdata"); - - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(0 == buffer.committed()); - REQUIRE(! buffer); - reader.close(); - } - -} - diff --git a/third_party/libosmium/test/include/catch.hpp b/third_party/libosmium/test/include/catch.hpp deleted file mode 100644 index 73abfe8c6..000000000 --- a/third_party/libosmium/test/include/catch.hpp +++ /dev/null @@ -1,9416 +0,0 @@ -/* - * Catch v1.2.1 - * Generated: 2015-06-30 18:23:27.961086 - * ---------------------------------------------------------- - * This file has been merged from multiple headers. Please don't edit it directly - * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED -#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED - -#define TWOBLUECUBES_CATCH_HPP_INCLUDED - -#ifdef __clang__ -# pragma clang system_header -#elif defined __GNUC__ -# pragma GCC system_header -#endif - -// #included from: internal/catch_suppress_warnings.h - -#define TWOBLUECUBES_CATCH_SUPPRESS_WARNINGS_H_INCLUDED - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(push) -# pragma warning(disable: 161 1682) -# else // __ICC -# pragma clang diagnostic ignored "-Wglobal-constructors" -# pragma clang diagnostic ignored "-Wvariadic-macros" -# pragma clang diagnostic ignored "-Wc99-extensions" -# pragma clang diagnostic ignored "-Wunused-variable" -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -# pragma clang diagnostic ignored "-Wc++98-compat" -# pragma clang diagnostic ignored "-Wc++98-compat-pedantic" -# pragma clang diagnostic ignored "-Wswitch-enum" -# endif -#elif defined __GNUC__ -# pragma GCC diagnostic ignored "-Wvariadic-macros" -# pragma GCC diagnostic ignored "-Wunused-variable" -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wpadded" -#endif - -#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) -# define CATCH_IMPL -#endif - -#ifdef CATCH_IMPL -# ifndef CLARA_CONFIG_MAIN -# define CLARA_CONFIG_MAIN_NOT_DEFINED -# define CLARA_CONFIG_MAIN -# endif -#endif - -// #included from: internal/catch_notimplemented_exception.h -#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED - -// #included from: catch_common.h -#define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED - -#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line -#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) -#define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) - -#define INTERNAL_CATCH_STRINGIFY2( expr ) #expr -#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr ) - -#include -#include -#include - -// #included from: catch_compiler_capabilities.h -#define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED - -// Detect a number of compiler features - mostly C++11/14 conformance - by compiler -// The following features are defined: -// -// CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported? -// CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported? -// CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods -// CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported? -// CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported - -// CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? - -// CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? - -// In general each macro has a _NO_ form -// (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature. -// Many features, at point of detection, define an _INTERNAL_ macro, so they -// can be combined, en-mass, with the _NO_ forms later. - -// All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11 - -#ifdef __clang__ - -# if __has_feature(cxx_nullptr) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -# endif - -# if __has_feature(cxx_noexcept) -# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# endif - -#endif // __clang__ - -//////////////////////////////////////////////////////////////////////////////// -// Borland -#ifdef __BORLANDC__ - -#endif // __BORLANDC__ - -//////////////////////////////////////////////////////////////////////////////// -// EDG -#ifdef __EDG_VERSION__ - -#endif // __EDG_VERSION__ - -//////////////////////////////////////////////////////////////////////////////// -// Digital Mars -#ifdef __DMC__ - -#endif // __DMC__ - -//////////////////////////////////////////////////////////////////////////////// -// GCC -#ifdef __GNUC__ - -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) ) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -#endif - -#endif // __GNUC__ - -//////////////////////////////////////////////////////////////////////////////// -// Visual C++ -#ifdef _MSC_VER - -#if (_MSC_VER >= 1600) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -#endif - -#if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) -#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -#endif - -#endif // _MSC_VER - -// Use variadic macros if the compiler supports them -#if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \ - ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \ - ( defined __GNUC__ && __GNUC__ >= 3 ) || \ - ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L ) - -#define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS - -#endif - -//////////////////////////////////////////////////////////////////////////////// -// C++ language feature support - -// catch all support for C++11 -#if (__cplusplus >= 201103L) - -# define CATCH_CPP11_OR_GREATER - -# if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -# define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM -# define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE -# define CATCH_INTERNAL_CONFIG_CPP11_TUPLE -# endif - -# ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS -# define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS -# endif - -#endif // __cplusplus >= 201103L - -// Now set the actual defines based on the above + anything the user has configured -#if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_NULLPTR -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_NOEXCEPT -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_GENERATED_METHODS -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_IS_ENUM -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_TUPLE -#endif -#if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS) -#define CATCH_CONFIG_VARIADIC_MACROS -#endif - -// noexcept support: -#if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT) -# define CATCH_NOEXCEPT noexcept -# define CATCH_NOEXCEPT_IS(x) noexcept(x) -#else -# define CATCH_NOEXCEPT throw() -# define CATCH_NOEXCEPT_IS(x) -#endif - -namespace Catch { - - class NonCopyable { -#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - NonCopyable( NonCopyable const& ) = delete; - NonCopyable( NonCopyable && ) = delete; - NonCopyable& operator = ( NonCopyable const& ) = delete; - NonCopyable& operator = ( NonCopyable && ) = delete; -#else - NonCopyable( NonCopyable const& info ); - NonCopyable& operator = ( NonCopyable const& ); -#endif - - protected: - NonCopyable() {} - virtual ~NonCopyable(); - }; - - class SafeBool { - public: - typedef void (SafeBool::*type)() const; - - static type makeSafe( bool value ) { - return value ? &SafeBool::trueValue : 0; - } - private: - void trueValue() const {} - }; - - template - inline void deleteAll( ContainerT& container ) { - typename ContainerT::const_iterator it = container.begin(); - typename ContainerT::const_iterator itEnd = container.end(); - for(; it != itEnd; ++it ) - delete *it; - } - template - inline void deleteAllValues( AssociativeContainerT& container ) { - typename AssociativeContainerT::const_iterator it = container.begin(); - typename AssociativeContainerT::const_iterator itEnd = container.end(); - for(; it != itEnd; ++it ) - delete it->second; - } - - bool startsWith( std::string const& s, std::string const& prefix ); - bool endsWith( std::string const& s, std::string const& suffix ); - bool contains( std::string const& s, std::string const& infix ); - void toLowerInPlace( std::string& s ); - std::string toLower( std::string const& s ); - std::string trim( std::string const& str ); - bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); - - struct pluralise { - pluralise( std::size_t count, std::string const& label ); - - friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); - - std::size_t m_count; - std::string m_label; - }; - - struct SourceLineInfo { - - SourceLineInfo(); - SourceLineInfo( char const* _file, std::size_t _line ); - SourceLineInfo( SourceLineInfo const& other ); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - SourceLineInfo( SourceLineInfo && ) = default; - SourceLineInfo& operator = ( SourceLineInfo const& ) = default; - SourceLineInfo& operator = ( SourceLineInfo && ) = default; -# endif - bool empty() const; - bool operator == ( SourceLineInfo const& other ) const; - bool operator < ( SourceLineInfo const& other ) const; - - std::string file; - std::size_t line; - }; - - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); - - // This is just here to avoid compiler warnings with macro constants and boolean literals - inline bool isTrue( bool value ){ return value; } - inline bool alwaysTrue() { return true; } - inline bool alwaysFalse() { return false; } - - void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ); - - // Use this in variadic streaming macros to allow - // >> +StreamEndStop - // as well as - // >> stuff +StreamEndStop - struct StreamEndStop { - std::string operator+() { - return std::string(); - } - }; - template - T const& operator + ( T const& value, StreamEndStop ) { - return value; - } -} - -#define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) -#define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO ); - -#include - -namespace Catch { - - class NotImplementedException : public std::exception - { - public: - NotImplementedException( SourceLineInfo const& lineInfo ); - NotImplementedException( NotImplementedException const& ) {} - - virtual ~NotImplementedException() CATCH_NOEXCEPT {} - - virtual const char* what() const CATCH_NOEXCEPT; - - private: - std::string m_what; - SourceLineInfo m_lineInfo; - }; - -} // end namespace Catch - -/////////////////////////////////////////////////////////////////////////////// -#define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO ) - -// #included from: internal/catch_context.h -#define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED - -// #included from: catch_interfaces_generators.h -#define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED - -#include - -namespace Catch { - - struct IGeneratorInfo { - virtual ~IGeneratorInfo(); - virtual bool moveNext() = 0; - virtual std::size_t getCurrentIndex() const = 0; - }; - - struct IGeneratorsForTest { - virtual ~IGeneratorsForTest(); - - virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0; - virtual bool moveNext() = 0; - }; - - IGeneratorsForTest* createGeneratorsForTest(); - -} // end namespace Catch - -// #included from: catch_ptr.hpp -#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - // An intrusive reference counting smart pointer. - // T must implement addRef() and release() methods - // typically implementing the IShared interface - template - class Ptr { - public: - Ptr() : m_p( NULL ){} - Ptr( T* p ) : m_p( p ){ - if( m_p ) - m_p->addRef(); - } - Ptr( Ptr const& other ) : m_p( other.m_p ){ - if( m_p ) - m_p->addRef(); - } - ~Ptr(){ - if( m_p ) - m_p->release(); - } - void reset() { - if( m_p ) - m_p->release(); - m_p = NULL; - } - Ptr& operator = ( T* p ){ - Ptr temp( p ); - swap( temp ); - return *this; - } - Ptr& operator = ( Ptr const& other ){ - Ptr temp( other ); - swap( temp ); - return *this; - } - void swap( Ptr& other ) { std::swap( m_p, other.m_p ); } - T* get() { return m_p; } - const T* get() const{ return m_p; } - T& operator*() const { return *m_p; } - T* operator->() const { return m_p; } - bool operator !() const { return m_p == NULL; } - operator SafeBool::type() const { return SafeBool::makeSafe( m_p != NULL ); } - - private: - T* m_p; - }; - - struct IShared : NonCopyable { - virtual ~IShared(); - virtual void addRef() const = 0; - virtual void release() const = 0; - }; - - template - struct SharedImpl : T { - - SharedImpl() : m_rc( 0 ){} - - virtual void addRef() const { - ++m_rc; - } - virtual void release() const { - if( --m_rc == 0 ) - delete this; - } - - mutable unsigned int m_rc; - }; - -} // end namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#include -#include -#include - -namespace Catch { - - class TestCase; - class Stream; - struct IResultCapture; - struct IRunner; - struct IGeneratorsForTest; - struct IConfig; - - struct IContext - { - virtual ~IContext(); - - virtual IResultCapture* getResultCapture() = 0; - virtual IRunner* getRunner() = 0; - virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0; - virtual bool advanceGeneratorsForCurrentTest() = 0; - virtual Ptr getConfig() const = 0; - }; - - struct IMutableContext : IContext - { - virtual ~IMutableContext(); - virtual void setResultCapture( IResultCapture* resultCapture ) = 0; - virtual void setRunner( IRunner* runner ) = 0; - virtual void setConfig( Ptr const& config ) = 0; - }; - - IContext& getCurrentContext(); - IMutableContext& getCurrentMutableContext(); - void cleanUpContext(); - Stream createStream( std::string const& streamName ); - -} - -// #included from: internal/catch_test_registry.hpp -#define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED - -// #included from: catch_interfaces_testcase.h -#define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED - -#include - -namespace Catch { - - class TestSpec; - - struct ITestCase : IShared { - virtual void invoke () const = 0; - protected: - virtual ~ITestCase(); - }; - - class TestCase; - struct IConfig; - - struct ITestCaseRegistry { - virtual ~ITestCaseRegistry(); - virtual std::vector const& getAllTests() const = 0; - virtual void getFilteredTests( TestSpec const& testSpec, IConfig const& config, std::vector& matchingTestCases, bool negated = false ) const = 0; - - }; -} - -namespace Catch { - -template -class MethodTestCase : public SharedImpl { - -public: - MethodTestCase( void (C::*method)() ) : m_method( method ) {} - - virtual void invoke() const { - C obj; - (obj.*m_method)(); - } - -private: - virtual ~MethodTestCase() {} - - void (C::*m_method)(); -}; - -typedef void(*TestFunction)(); - -struct NameAndDesc { - NameAndDesc( const char* _name = "", const char* _description= "" ) - : name( _name ), description( _description ) - {} - - const char* name; - const char* description; -}; - -struct AutoReg { - - AutoReg( TestFunction function, - SourceLineInfo const& lineInfo, - NameAndDesc const& nameAndDesc ); - - template - AutoReg( void (C::*method)(), - char const* className, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ) { - registerTestCase( new MethodTestCase( method ), - className, - nameAndDesc, - lineInfo ); - } - - void registerTestCase( ITestCase* testCase, - char const* className, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ); - - ~AutoReg(); - -private: - AutoReg( AutoReg const& ); - void operator= ( AutoReg const& ); -}; - -} // end namespace Catch - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TESTCASE( ... ) \ - static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); }\ - static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )() - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... )\ - namespace{ \ - struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \ - void test(); \ - }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \ - } \ - void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test() - -#else - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \ - static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\ - static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )() - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\ - namespace{ \ - struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \ - void test(); \ - }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \ - } \ - void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test() - -#endif - -// #included from: internal/catch_capture.hpp -#define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED - -// #included from: catch_result_builder.h -#define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED - -// #included from: catch_result_type.h -#define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED - -namespace Catch { - - // ResultWas::OfType enum - struct ResultWas { enum OfType { - Unknown = -1, - Ok = 0, - Info = 1, - Warning = 2, - - FailureBit = 0x10, - - ExpressionFailed = FailureBit | 1, - ExplicitFailure = FailureBit | 2, - - Exception = 0x100 | FailureBit, - - ThrewException = Exception | 1, - DidntThrowException = Exception | 2, - - FatalErrorCondition = 0x200 | FailureBit - - }; }; - - inline bool isOk( ResultWas::OfType resultType ) { - return ( resultType & ResultWas::FailureBit ) == 0; - } - inline bool isJustInfo( int flags ) { - return flags == ResultWas::Info; - } - - // ResultDisposition::Flags enum - struct ResultDisposition { enum Flags { - Normal = 0x01, - - ContinueOnFailure = 0x02, // Failures fail test, but execution continues - FalseTest = 0x04, // Prefix expression with ! - SuppressFail = 0x08 // Failures are reported but do not fail the test - }; }; - - inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { - return static_cast( static_cast( lhs ) | static_cast( rhs ) ); - } - - inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } - inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } - inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } - -} // end namespace Catch - -// #included from: catch_assertionresult.h -#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED - -#include - -namespace Catch { - - struct AssertionInfo - { - AssertionInfo() {} - AssertionInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - std::string const& _capturedExpression, - ResultDisposition::Flags _resultDisposition ); - - std::string macroName; - SourceLineInfo lineInfo; - std::string capturedExpression; - ResultDisposition::Flags resultDisposition; - }; - - struct AssertionResultData - { - AssertionResultData() : resultType( ResultWas::Unknown ) {} - - std::string reconstructedExpression; - std::string message; - ResultWas::OfType resultType; - }; - - class AssertionResult { - public: - AssertionResult(); - AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); - ~AssertionResult(); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - AssertionResult( AssertionResult const& ) = default; - AssertionResult( AssertionResult && ) = default; - AssertionResult& operator = ( AssertionResult const& ) = default; - AssertionResult& operator = ( AssertionResult && ) = default; -# endif - - bool isOk() const; - bool succeeded() const; - ResultWas::OfType getResultType() const; - bool hasExpression() const; - bool hasMessage() const; - std::string getExpression() const; - std::string getExpressionInMacro() const; - bool hasExpandedExpression() const; - std::string getExpandedExpression() const; - std::string getMessage() const; - SourceLineInfo getSourceInfo() const; - std::string getTestMacroName() const; - - protected: - AssertionInfo m_info; - AssertionResultData m_resultData; - }; - -} // end namespace Catch - -namespace Catch { - - struct TestFailureException{}; - - template class ExpressionLhs; - - struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison; - - struct CopyableStream { - CopyableStream() {} - CopyableStream( CopyableStream const& other ) { - oss << other.oss.str(); - } - CopyableStream& operator=( CopyableStream const& other ) { - oss.str(""); - oss << other.oss.str(); - return *this; - } - std::ostringstream oss; - }; - - class ResultBuilder { - public: - ResultBuilder( char const* macroName, - SourceLineInfo const& lineInfo, - char const* capturedExpression, - ResultDisposition::Flags resultDisposition ); - - template - ExpressionLhs operator <= ( T const& operand ); - ExpressionLhs operator <= ( bool value ); - - template - ResultBuilder& operator << ( T const& value ) { - m_stream.oss << value; - return *this; - } - - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); - - ResultBuilder& setResultType( ResultWas::OfType result ); - ResultBuilder& setResultType( bool result ); - ResultBuilder& setLhs( std::string const& lhs ); - ResultBuilder& setRhs( std::string const& rhs ); - ResultBuilder& setOp( std::string const& op ); - - void endExpression(); - - std::string reconstructExpression() const; - AssertionResult build() const; - - void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal ); - void captureResult( ResultWas::OfType resultType ); - void captureExpression(); - void react(); - bool shouldDebugBreak() const; - bool allowThrows() const; - - private: - AssertionInfo m_assertionInfo; - AssertionResultData m_data; - struct ExprComponents { - ExprComponents() : testFalse( false ) {} - bool testFalse; - std::string lhs, rhs, op; - } m_exprComponents; - CopyableStream m_stream; - - bool m_shouldDebugBreak; - bool m_shouldThrow; - }; - -} // namespace Catch - -// Include after due to circular dependency: -// #included from: catch_expression_lhs.hpp -#define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED - -// #included from: catch_evaluate.hpp -#define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4389) // '==' : signed/unsigned mismatch -#endif - -#include - -namespace Catch { -namespace Internal { - - enum Operator { - IsEqualTo, - IsNotEqualTo, - IsLessThan, - IsGreaterThan, - IsLessThanOrEqualTo, - IsGreaterThanOrEqualTo - }; - - template struct OperatorTraits { static const char* getName(){ return "*error*"; } }; - template<> struct OperatorTraits { static const char* getName(){ return "=="; } }; - template<> struct OperatorTraits { static const char* getName(){ return "!="; } }; - template<> struct OperatorTraits { static const char* getName(){ return "<"; } }; - template<> struct OperatorTraits { static const char* getName(){ return ">"; } }; - template<> struct OperatorTraits { static const char* getName(){ return "<="; } }; - template<> struct OperatorTraits{ static const char* getName(){ return ">="; } }; - - template - inline T& opCast(T const& t) { return const_cast(t); } - -// nullptr_t support based on pull request #154 from Konstantin Baumann -#ifdef CATCH_CONFIG_CPP11_NULLPTR - inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } -#endif // CATCH_CONFIG_CPP11_NULLPTR - - // So the compare overloads can be operator agnostic we convey the operator as a template - // enum, which is used to specialise an Evaluator for doing the comparison. - template - class Evaluator{}; - - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs) { - return opCast( lhs ) == opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) != opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) < opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) > opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) >= opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) <= opCast( rhs ); - } - }; - - template - bool applyEvaluator( T1 const& lhs, T2 const& rhs ) { - return Evaluator::evaluate( lhs, rhs ); - } - - // This level of indirection allows us to specialise for integer types - // to avoid signed/ unsigned warnings - - // "base" overload - template - bool compare( T1 const& lhs, T2 const& rhs ) { - return Evaluator::evaluate( lhs, rhs ); - } - - // unsigned X to int - template bool compare( unsigned int lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned long lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned char lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - - // unsigned X to long - template bool compare( unsigned int lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned long lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned char lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - - // int to unsigned X - template bool compare( int lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( int lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( int lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // long to unsigned X - template bool compare( long lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // pointer to long (when comparing against NULL) - template bool compare( long lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, long rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } - - // pointer to int (when comparing against NULL) - template bool compare( int lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, int rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } - -#ifdef CATCH_CONFIG_CPP11_NULLPTR - // pointer to nullptr_t (when comparing against nullptr) - template bool compare( std::nullptr_t, T* rhs ) { - return Evaluator::evaluate( NULL, rhs ); - } - template bool compare( T* lhs, std::nullptr_t ) { - return Evaluator::evaluate( lhs, NULL ); - } -#endif // CATCH_CONFIG_CPP11_NULLPTR - -} // end of namespace Internal -} // end of namespace Catch - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -// #included from: catch_tostring.h -#define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED - -#include -#include -#include -#include -#include - -#ifdef __OBJC__ -// #included from: catch_objc_arc.hpp -#define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED - -#import - -#ifdef __has_feature -#define CATCH_ARC_ENABLED __has_feature(objc_arc) -#else -#define CATCH_ARC_ENABLED 0 -#endif - -void arcSafeRelease( NSObject* obj ); -id performOptionalSelector( id obj, SEL sel ); - -#if !CATCH_ARC_ENABLED -inline void arcSafeRelease( NSObject* obj ) { - [obj release]; -} -inline id performOptionalSelector( id obj, SEL sel ) { - if( [obj respondsToSelector: sel] ) - return [obj performSelector: sel]; - return nil; -} -#define CATCH_UNSAFE_UNRETAINED -#define CATCH_ARC_STRONG -#else -inline void arcSafeRelease( NSObject* ){} -inline id performOptionalSelector( id obj, SEL sel ) { -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-performSelector-leaks" -#endif - if( [obj respondsToSelector: sel] ) - return [obj performSelector: sel]; -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - return nil; -} -#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained -#define CATCH_ARC_STRONG __strong -#endif - -#endif - -#ifdef CATCH_CONFIG_CPP11_TUPLE -#include -#endif - -#ifdef CATCH_CONFIG_CPP11_IS_ENUM -#include -#endif - -namespace Catch { - -// Why we're here. -template -std::string toString( T const& value ); - -// Built in overloads - -std::string toString( std::string const& value ); -std::string toString( std::wstring const& value ); -std::string toString( const char* const value ); -std::string toString( char* const value ); -std::string toString( const wchar_t* const value ); -std::string toString( wchar_t* const value ); -std::string toString( int value ); -std::string toString( unsigned long value ); -std::string toString( unsigned int value ); -std::string toString( const double value ); -std::string toString( const float value ); -std::string toString( bool value ); -std::string toString( char value ); -std::string toString( signed char value ); -std::string toString( unsigned char value ); - -#ifdef CATCH_CONFIG_CPP11_NULLPTR -std::string toString( std::nullptr_t ); -#endif - -#ifdef __OBJC__ - std::string toString( NSString const * const& nsstring ); - std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ); - std::string toString( NSObject* const& nsObject ); -#endif - -namespace Detail { - - extern std::string unprintableString; - - struct BorgType { - template BorgType( T const& ); - }; - - struct TrueType { char sizer[1]; }; - struct FalseType { char sizer[2]; }; - - TrueType& testStreamable( std::ostream& ); - FalseType testStreamable( FalseType ); - - FalseType operator<<( std::ostream const&, BorgType const& ); - - template - struct IsStreamInsertable { - static std::ostream &s; - static T const&t; - enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) }; - }; - -#if defined(CATCH_CONFIG_CPP11_IS_ENUM) - template::value - > - struct EnumStringMaker - { - static std::string convert( T const& ) { return unprintableString; } - }; - - template - struct EnumStringMaker - { - static std::string convert( T const& v ) - { - return ::Catch::toString( - static_cast::type>(v) - ); - } - }; -#endif - template - struct StringMakerBase { -#if defined(CATCH_CONFIG_CPP11_IS_ENUM) - template - static std::string convert( T const& v ) - { - return EnumStringMaker::convert( v ); - } -#else - template - static std::string convert( T const& ) { return unprintableString; } -#endif - }; - - template<> - struct StringMakerBase { - template - static std::string convert( T const& _value ) { - std::ostringstream oss; - oss << _value; - return oss.str(); - } - }; - - std::string rawMemoryToString( const void *object, std::size_t size ); - - template - inline std::string rawMemoryToString( const T& object ) { - return rawMemoryToString( &object, sizeof(object) ); - } - -} // end namespace Detail - -template -struct StringMaker : - Detail::StringMakerBase::value> {}; - -template -struct StringMaker { - template - static std::string convert( U* p ) { - if( !p ) - return INTERNAL_CATCH_STRINGIFY( NULL ); - else - return Detail::rawMemoryToString( p ); - } -}; - -template -struct StringMaker { - static std::string convert( R C::* p ) { - if( !p ) - return INTERNAL_CATCH_STRINGIFY( NULL ); - else - return Detail::rawMemoryToString( p ); - } -}; - -namespace Detail { - template - std::string rangeToString( InputIterator first, InputIterator last ); -} - -//template -//struct StringMaker > { -// static std::string convert( std::vector const& v ) { -// return Detail::rangeToString( v.begin(), v.end() ); -// } -//}; - -template -std::string toString( std::vector const& v ) { - return Detail::rangeToString( v.begin(), v.end() ); -} - -#ifdef CATCH_CONFIG_CPP11_TUPLE - -// toString for tuples -namespace TupleDetail { - template< - typename Tuple, - std::size_t N = 0, - bool = (N < std::tuple_size::value) - > - struct ElementPrinter { - static void print( const Tuple& tuple, std::ostream& os ) - { - os << ( N ? ", " : " " ) - << Catch::toString(std::get(tuple)); - ElementPrinter::print(tuple,os); - } - }; - - template< - typename Tuple, - std::size_t N - > - struct ElementPrinter { - static void print( const Tuple&, std::ostream& ) {} - }; - -} - -template -struct StringMaker> { - - static std::string convert( const std::tuple& tuple ) - { - std::ostringstream os; - os << '{'; - TupleDetail::ElementPrinter>::print( tuple, os ); - os << " }"; - return os.str(); - } -}; -#endif // CATCH_CONFIG_CPP11_TUPLE - -namespace Detail { - template - std::string makeString( T const& value ) { - return StringMaker::convert( value ); - } -} // end namespace Detail - -/// \brief converts any type to a string -/// -/// The default template forwards on to ostringstream - except when an -/// ostringstream overload does not exist - in which case it attempts to detect -/// that and writes {?}. -/// Overload (not specialise) this template for custom typs that you don't want -/// to provide an ostream overload for. -template -std::string toString( T const& value ) { - return StringMaker::convert( value ); -} - - namespace Detail { - template - std::string rangeToString( InputIterator first, InputIterator last ) { - std::ostringstream oss; - oss << "{ "; - if( first != last ) { - oss << Catch::toString( *first ); - for( ++first ; first != last ; ++first ) - oss << ", " << Catch::toString( *first ); - } - oss << " }"; - return oss.str(); - } -} - -} // end namespace Catch - -namespace Catch { - -// Wraps the LHS of an expression and captures the operator and RHS (if any) - -// wrapping them all in a ResultBuilder object -template -class ExpressionLhs { - ExpressionLhs& operator = ( ExpressionLhs const& ); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - ExpressionLhs& operator = ( ExpressionLhs && ) = delete; -# endif - -public: - ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ) {} -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - ExpressionLhs( ExpressionLhs const& ) = default; - ExpressionLhs( ExpressionLhs && ) = default; -# endif - - template - ResultBuilder& operator == ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator != ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator < ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator > ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator <= ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator >= ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - ResultBuilder& operator == ( bool rhs ) { - return captureExpression( rhs ); - } - - ResultBuilder& operator != ( bool rhs ) { - return captureExpression( rhs ); - } - - void endExpression() { - bool value = m_lhs ? true : false; - m_rb - .setLhs( Catch::toString( value ) ) - .setResultType( value ) - .endExpression(); - } - - // Only simple binary expressions are allowed on the LHS. - // If more complex compositions are required then place the sub expression in parentheses - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); - -private: - template - ResultBuilder& captureExpression( RhsT const& rhs ) { - return m_rb - .setResultType( Internal::compare( m_lhs, rhs ) ) - .setLhs( Catch::toString( m_lhs ) ) - .setRhs( Catch::toString( rhs ) ) - .setOp( Internal::OperatorTraits::getName() ); - } - -private: - ResultBuilder& m_rb; - T m_lhs; -}; - -} // end namespace Catch - - -namespace Catch { - - template - inline ExpressionLhs ResultBuilder::operator <= ( T const& operand ) { - return ExpressionLhs( *this, operand ); - } - - inline ExpressionLhs ResultBuilder::operator <= ( bool value ) { - return ExpressionLhs( *this, value ); - } - -} // namespace Catch - -// #included from: catch_message.h -#define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED - -#include - -namespace Catch { - - struct MessageInfo { - MessageInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - ResultWas::OfType _type ); - - std::string macroName; - SourceLineInfo lineInfo; - ResultWas::OfType type; - std::string message; - unsigned int sequence; - - bool operator == ( MessageInfo const& other ) const { - return sequence == other.sequence; - } - bool operator < ( MessageInfo const& other ) const { - return sequence < other.sequence; - } - private: - static unsigned int globalCount; - }; - - struct MessageBuilder { - MessageBuilder( std::string const& macroName, - SourceLineInfo const& lineInfo, - ResultWas::OfType type ) - : m_info( macroName, lineInfo, type ) - {} - - template - MessageBuilder& operator << ( T const& value ) { - m_stream << value; - return *this; - } - - MessageInfo m_info; - std::ostringstream m_stream; - }; - - class ScopedMessage { - public: - ScopedMessage( MessageBuilder const& builder ); - ScopedMessage( ScopedMessage const& other ); - ~ScopedMessage(); - - MessageInfo m_info; - }; - -} // end namespace Catch - -// #included from: catch_interfaces_capture.h -#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED - -#include - -namespace Catch { - - class TestCase; - class AssertionResult; - struct AssertionInfo; - struct SectionInfo; - struct MessageInfo; - class ScopedMessageBuilder; - struct Counts; - - struct IResultCapture { - - virtual ~IResultCapture(); - - virtual void assertionEnded( AssertionResult const& result ) = 0; - virtual bool sectionStarted( SectionInfo const& sectionInfo, - Counts& assertions ) = 0; - virtual void sectionEnded( SectionInfo const& name, Counts const& assertions, double _durationInSeconds ) = 0; - virtual void pushScopedMessage( MessageInfo const& message ) = 0; - virtual void popScopedMessage( MessageInfo const& message ) = 0; - - virtual std::string getCurrentTestName() const = 0; - virtual const AssertionResult* getLastResult() const = 0; - - virtual void handleFatalErrorCondition( std::string const& message ) = 0; - }; - - IResultCapture& getResultCapture(); -} - -// #included from: catch_debugger.h -#define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED - -// #included from: catch_platform.h -#define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED - -#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -#define CATCH_PLATFORM_MAC -#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#define CATCH_PLATFORM_IPHONE -#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) -#define CATCH_PLATFORM_WINDOWS -#endif - -#include - -namespace Catch{ - - bool isDebuggerActive(); - void writeToDebugConsole( std::string const& text ); -} - -#ifdef CATCH_PLATFORM_MAC - - // The following code snippet based on: - // http://cocoawithlove.com/2008/03/break-into-debugger.html - #ifdef DEBUG - #if defined(__ppc64__) || defined(__ppc__) - #define CATCH_BREAK_INTO_DEBUGGER() \ - if( Catch::isDebuggerActive() ) { \ - __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ - : : : "memory","r0","r3","r4" ); \ - } - #else - #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__("int $3\n" : : );} - #endif - #endif - -#elif defined(_MSC_VER) - #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); } -#elif defined(__MINGW32__) - extern "C" __declspec(dllimport) void __stdcall DebugBreak(); - #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); } -#endif - -#ifndef CATCH_BREAK_INTO_DEBUGGER -#define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); -#endif - -// #included from: catch_interfaces_runner.h -#define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED - -namespace Catch { - class TestCase; - - struct IRunner { - virtual ~IRunner(); - virtual bool aborting() const = 0; - }; -} - -/////////////////////////////////////////////////////////////////////////////// -// In the event of a failure works out if the debugger needs to be invoked -// and/or an exception thrown and takes appropriate action. -// This needs to be done as a macro so the debugger will stop in the user -// source code rather than in Catch library code -#define INTERNAL_CATCH_REACT( resultBuilder ) \ - if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \ - resultBuilder.react(); - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - try { \ - ( __catchResult <= expr ).endExpression(); \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( Catch::ResultDisposition::Normal ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::isTrue( false && (expr) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \ - INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ - if( Catch::getResultCapture().getLastResult()->succeeded() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_ELSE( expr, resultDisposition, macroName ) \ - INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ - if( !Catch::getResultCapture().getLastResult()->succeeded() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_NO_THROW( expr, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - try { \ - expr; \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( resultDisposition ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS( expr, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - if( __catchResult.allowThrows() ) \ - try { \ - expr; \ - __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ - } \ - catch( ... ) { \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - } \ - else \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - if( __catchResult.allowThrows() ) \ - try { \ - expr; \ - __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ - } \ - catch( exceptionType ) { \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( resultDisposition ); \ - } \ - else \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, ... ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ - __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ - __catchResult.captureResult( messageType ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) -#else - #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, log ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ - __catchResult << log + ::Catch::StreamEndStop(); \ - __catchResult.captureResult( messageType ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) -#endif - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_INFO( log, macroName ) \ - Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log; - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CHECK_THAT( arg, matcher, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg " " #matcher, resultDisposition ); \ - try { \ - std::string matcherAsString = ::Catch::Matchers::matcher.toString(); \ - __catchResult \ - .setLhs( Catch::toString( arg ) ) \ - .setRhs( matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString ) \ - .setOp( "matches" ) \ - .setResultType( ::Catch::Matchers::matcher.match( arg ) ); \ - __catchResult.captureExpression(); \ - } catch( ... ) { \ - __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -// #included from: internal/catch_section.h -#define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED - -// #included from: catch_section_info.h -#define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED - -namespace Catch { - - struct SectionInfo { - SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name, - std::string const& _description = std::string() ); - - std::string name; - std::string description; - SourceLineInfo lineInfo; - }; - -} // end namespace Catch - -// #included from: catch_totals.hpp -#define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED - -#include - -namespace Catch { - - struct Counts { - Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {} - - Counts operator - ( Counts const& other ) const { - Counts diff; - diff.passed = passed - other.passed; - diff.failed = failed - other.failed; - diff.failedButOk = failedButOk - other.failedButOk; - return diff; - } - Counts& operator += ( Counts const& other ) { - passed += other.passed; - failed += other.failed; - failedButOk += other.failedButOk; - return *this; - } - - std::size_t total() const { - return passed + failed + failedButOk; - } - bool allPassed() const { - return failed == 0 && failedButOk == 0; - } - bool allOk() const { - return failed == 0; - } - - std::size_t passed; - std::size_t failed; - std::size_t failedButOk; - }; - - struct Totals { - - Totals operator - ( Totals const& other ) const { - Totals diff; - diff.assertions = assertions - other.assertions; - diff.testCases = testCases - other.testCases; - return diff; - } - - Totals delta( Totals const& prevTotals ) const { - Totals diff = *this - prevTotals; - if( diff.assertions.failed > 0 ) - ++diff.testCases.failed; - else if( diff.assertions.failedButOk > 0 ) - ++diff.testCases.failedButOk; - else - ++diff.testCases.passed; - return diff; - } - - Totals& operator += ( Totals const& other ) { - assertions += other.assertions; - testCases += other.testCases; - return *this; - } - - Counts assertions; - Counts testCases; - }; -} - -// #included from: catch_timer.h -#define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED - -#ifdef CATCH_PLATFORM_WINDOWS -typedef unsigned long long uint64_t; -#else -#include -#endif - -namespace Catch { - - class Timer { - public: - Timer() : m_ticks( 0 ) {} - void start(); - unsigned int getElapsedMicroseconds() const; - unsigned int getElapsedMilliseconds() const; - double getElapsedSeconds() const; - - private: - uint64_t m_ticks; - }; - -} // namespace Catch - -#include - -namespace Catch { - - class Section : NonCopyable { - public: - Section( SectionInfo const& info ); - ~Section(); - - // This indicates whether the section should be executed or not - operator bool() const; - - private: - SectionInfo m_info; - - std::string m_name; - Counts m_assertions; - bool m_sectionIncluded; - Timer m_timer; - }; - -} // end namespace Catch - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define INTERNAL_CATCH_SECTION( ... ) \ - if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) -#else - #define INTERNAL_CATCH_SECTION( name, desc ) \ - if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) ) -#endif - -// #included from: internal/catch_generators.hpp -#define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED - -#include -#include -#include -#include - -namespace Catch { - -template -struct IGenerator { - virtual ~IGenerator() {} - virtual T getValue( std::size_t index ) const = 0; - virtual std::size_t size () const = 0; -}; - -template -class BetweenGenerator : public IGenerator { -public: - BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){} - - virtual T getValue( std::size_t index ) const { - return m_from+static_cast( index ); - } - - virtual std::size_t size() const { - return static_cast( 1+m_to-m_from ); - } - -private: - - T m_from; - T m_to; -}; - -template -class ValuesGenerator : public IGenerator { -public: - ValuesGenerator(){} - - void add( T value ) { - m_values.push_back( value ); - } - - virtual T getValue( std::size_t index ) const { - return m_values[index]; - } - - virtual std::size_t size() const { - return m_values.size(); - } - -private: - std::vector m_values; -}; - -template -class CompositeGenerator { -public: - CompositeGenerator() : m_totalSize( 0 ) {} - - // *** Move semantics, similar to auto_ptr *** - CompositeGenerator( CompositeGenerator& other ) - : m_fileInfo( other.m_fileInfo ), - m_totalSize( 0 ) - { - move( other ); - } - - CompositeGenerator& setFileInfo( const char* fileInfo ) { - m_fileInfo = fileInfo; - return *this; - } - - ~CompositeGenerator() { - deleteAll( m_composed ); - } - - operator T () const { - size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize ); - - typename std::vector*>::const_iterator it = m_composed.begin(); - typename std::vector*>::const_iterator itEnd = m_composed.end(); - for( size_t index = 0; it != itEnd; ++it ) - { - const IGenerator* generator = *it; - if( overallIndex >= index && overallIndex < index + generator->size() ) - { - return generator->getValue( overallIndex-index ); - } - index += generator->size(); - } - CATCH_INTERNAL_ERROR( "Indexed past end of generated range" ); - return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so - } - - void add( const IGenerator* generator ) { - m_totalSize += generator->size(); - m_composed.push_back( generator ); - } - - CompositeGenerator& then( CompositeGenerator& other ) { - move( other ); - return *this; - } - - CompositeGenerator& then( T value ) { - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( value ); - add( valuesGen ); - return *this; - } - -private: - - void move( CompositeGenerator& other ) { - std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) ); - m_totalSize += other.m_totalSize; - other.m_composed.clear(); - } - - std::vector*> m_composed; - std::string m_fileInfo; - size_t m_totalSize; -}; - -namespace Generators -{ - template - CompositeGenerator between( T from, T to ) { - CompositeGenerator generators; - generators.add( new BetweenGenerator( from, to ) ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2 ) { - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - generators.add( valuesGen ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2, T val3 ){ - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - valuesGen->add( val3 ); - generators.add( valuesGen ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2, T val3, T val4 ) { - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - valuesGen->add( val3 ); - valuesGen->add( val4 ); - generators.add( valuesGen ); - return generators; - } - -} // end namespace Generators - -using namespace Generators; - -} // end namespace Catch - -#define INTERNAL_CATCH_LINESTR2( line ) #line -#define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line ) - -#define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" ) - -// #included from: internal/catch_interfaces_exception.h -#define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED - -#include -// #included from: catch_interfaces_registry_hub.h -#define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED - -#include - -namespace Catch { - - class TestCase; - struct ITestCaseRegistry; - struct IExceptionTranslatorRegistry; - struct IExceptionTranslator; - struct IReporterRegistry; - struct IReporterFactory; - - struct IRegistryHub { - virtual ~IRegistryHub(); - - virtual IReporterRegistry const& getReporterRegistry() const = 0; - virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; - virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; - }; - - struct IMutableRegistryHub { - virtual ~IMutableRegistryHub(); - virtual void registerReporter( std::string const& name, IReporterFactory* factory ) = 0; - virtual void registerTest( TestCase const& testInfo ) = 0; - virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; - }; - - IRegistryHub& getRegistryHub(); - IMutableRegistryHub& getMutableRegistryHub(); - void cleanUp(); - std::string translateActiveException(); - -} - - -namespace Catch { - - typedef std::string(*exceptionTranslateFunction)(); - - struct IExceptionTranslator { - virtual ~IExceptionTranslator(); - virtual std::string translate() const = 0; - }; - - struct IExceptionTranslatorRegistry { - virtual ~IExceptionTranslatorRegistry(); - - virtual std::string translateActiveException() const = 0; - }; - - class ExceptionTranslatorRegistrar { - template - class ExceptionTranslator : public IExceptionTranslator { - public: - - ExceptionTranslator( std::string(*translateFunction)( T& ) ) - : m_translateFunction( translateFunction ) - {} - - virtual std::string translate() const { - try { - throw; - } - catch( T& ex ) { - return m_translateFunction( ex ); - } - } - - protected: - std::string(*m_translateFunction)( T& ); - }; - - public: - template - ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { - getMutableRegistryHub().registerTranslator - ( new ExceptionTranslator( translateFunction ) ); - } - }; -} - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) \ - static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature ); \ - namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ) ); }\ - static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature ) - -// #included from: internal/catch_approx.hpp -#define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED - -#include -#include - -namespace Catch { -namespace Detail { - - class Approx { - public: - explicit Approx ( double value ) - : m_epsilon( std::numeric_limits::epsilon()*100 ), - m_scale( 1.0 ), - m_value( value ) - {} - - Approx( Approx const& other ) - : m_epsilon( other.m_epsilon ), - m_scale( other.m_scale ), - m_value( other.m_value ) - {} - - static Approx custom() { - return Approx( 0 ); - } - - Approx operator()( double value ) { - Approx approx( value ); - approx.epsilon( m_epsilon ); - approx.scale( m_scale ); - return approx; - } - - friend bool operator == ( double lhs, Approx const& rhs ) { - // Thanks to Richard Harris for his help refining this formula - return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) ); - } - - friend bool operator == ( Approx const& lhs, double rhs ) { - return operator==( rhs, lhs ); - } - - friend bool operator != ( double lhs, Approx const& rhs ) { - return !operator==( lhs, rhs ); - } - - friend bool operator != ( Approx const& lhs, double rhs ) { - return !operator==( rhs, lhs ); - } - - Approx& epsilon( double newEpsilon ) { - m_epsilon = newEpsilon; - return *this; - } - - Approx& scale( double newScale ) { - m_scale = newScale; - return *this; - } - - std::string toString() const { - std::ostringstream oss; - oss << "Approx( " << Catch::toString( m_value ) << " )"; - return oss.str(); - } - - private: - double m_epsilon; - double m_scale; - double m_value; - }; -} - -template<> -inline std::string toString( Detail::Approx const& value ) { - return value.toString(); -} - -} // end namespace Catch - -// #included from: internal/catch_matchers.hpp -#define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED - -namespace Catch { -namespace Matchers { - namespace Impl { - - template - struct Matcher : SharedImpl - { - typedef ExpressionT ExpressionType; - - virtual ~Matcher() {} - virtual Ptr clone() const = 0; - virtual bool match( ExpressionT const& expr ) const = 0; - virtual std::string toString() const = 0; - }; - - template - struct MatcherImpl : Matcher { - - virtual Ptr > clone() const { - return Ptr >( new DerivedT( static_cast( *this ) ) ); - } - }; - - namespace Generic { - - template - class AllOf : public MatcherImpl, ExpressionT> { - public: - - AllOf() {} - AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {} - - AllOf& add( Matcher const& matcher ) { - m_matchers.push_back( matcher.clone() ); - return *this; - } - virtual bool match( ExpressionT const& expr ) const - { - for( std::size_t i = 0; i < m_matchers.size(); ++i ) - if( !m_matchers[i]->match( expr ) ) - return false; - return true; - } - virtual std::string toString() const { - std::ostringstream oss; - oss << "( "; - for( std::size_t i = 0; i < m_matchers.size(); ++i ) { - if( i != 0 ) - oss << " and "; - oss << m_matchers[i]->toString(); - } - oss << " )"; - return oss.str(); - } - - private: - std::vector > > m_matchers; - }; - - template - class AnyOf : public MatcherImpl, ExpressionT> { - public: - - AnyOf() {} - AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {} - - AnyOf& add( Matcher const& matcher ) { - m_matchers.push_back( matcher.clone() ); - return *this; - } - virtual bool match( ExpressionT const& expr ) const - { - for( std::size_t i = 0; i < m_matchers.size(); ++i ) - if( m_matchers[i]->match( expr ) ) - return true; - return false; - } - virtual std::string toString() const { - std::ostringstream oss; - oss << "( "; - for( std::size_t i = 0; i < m_matchers.size(); ++i ) { - if( i != 0 ) - oss << " or "; - oss << m_matchers[i]->toString(); - } - oss << " )"; - return oss.str(); - } - - private: - std::vector > > m_matchers; - }; - - } - - namespace StdString { - - inline std::string makeString( std::string const& str ) { return str; } - inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); } - - struct Equals : MatcherImpl { - Equals( std::string const& str ) : m_str( str ){} - Equals( Equals const& other ) : m_str( other.m_str ){} - - virtual ~Equals(); - - virtual bool match( std::string const& expr ) const { - return m_str == expr; - } - virtual std::string toString() const { - return "equals: \"" + m_str + "\""; - } - - std::string m_str; - }; - - struct Contains : MatcherImpl { - Contains( std::string const& substr ) : m_substr( substr ){} - Contains( Contains const& other ) : m_substr( other.m_substr ){} - - virtual ~Contains(); - - virtual bool match( std::string const& expr ) const { - return expr.find( m_substr ) != std::string::npos; - } - virtual std::string toString() const { - return "contains: \"" + m_substr + "\""; - } - - std::string m_substr; - }; - - struct StartsWith : MatcherImpl { - StartsWith( std::string const& substr ) : m_substr( substr ){} - StartsWith( StartsWith const& other ) : m_substr( other.m_substr ){} - - virtual ~StartsWith(); - - virtual bool match( std::string const& expr ) const { - return expr.find( m_substr ) == 0; - } - virtual std::string toString() const { - return "starts with: \"" + m_substr + "\""; - } - - std::string m_substr; - }; - - struct EndsWith : MatcherImpl { - EndsWith( std::string const& substr ) : m_substr( substr ){} - EndsWith( EndsWith const& other ) : m_substr( other.m_substr ){} - - virtual ~EndsWith(); - - virtual bool match( std::string const& expr ) const { - return expr.find( m_substr ) == expr.size() - m_substr.size(); - } - virtual std::string toString() const { - return "ends with: \"" + m_substr + "\""; - } - - std::string m_substr; - }; - } // namespace StdString - } // namespace Impl - - // The following functions create the actual matcher objects. - // This allows the types to be inferred - template - inline Impl::Generic::AllOf AllOf( Impl::Matcher const& m1, - Impl::Matcher const& m2 ) { - return Impl::Generic::AllOf().add( m1 ).add( m2 ); - } - template - inline Impl::Generic::AllOf AllOf( Impl::Matcher const& m1, - Impl::Matcher const& m2, - Impl::Matcher const& m3 ) { - return Impl::Generic::AllOf().add( m1 ).add( m2 ).add( m3 ); - } - template - inline Impl::Generic::AnyOf AnyOf( Impl::Matcher const& m1, - Impl::Matcher const& m2 ) { - return Impl::Generic::AnyOf().add( m1 ).add( m2 ); - } - template - inline Impl::Generic::AnyOf AnyOf( Impl::Matcher const& m1, - Impl::Matcher const& m2, - Impl::Matcher const& m3 ) { - return Impl::Generic::AnyOf().add( m1 ).add( m2 ).add( m3 ); - } - - inline Impl::StdString::Equals Equals( std::string const& str ) { - return Impl::StdString::Equals( str ); - } - inline Impl::StdString::Equals Equals( const char* str ) { - return Impl::StdString::Equals( Impl::StdString::makeString( str ) ); - } - inline Impl::StdString::Contains Contains( std::string const& substr ) { - return Impl::StdString::Contains( substr ); - } - inline Impl::StdString::Contains Contains( const char* substr ) { - return Impl::StdString::Contains( Impl::StdString::makeString( substr ) ); - } - inline Impl::StdString::StartsWith StartsWith( std::string const& substr ) { - return Impl::StdString::StartsWith( substr ); - } - inline Impl::StdString::StartsWith StartsWith( const char* substr ) { - return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) ); - } - inline Impl::StdString::EndsWith EndsWith( std::string const& substr ) { - return Impl::StdString::EndsWith( substr ); - } - inline Impl::StdString::EndsWith EndsWith( const char* substr ) { - return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) ); - } - -} // namespace Matchers - -using namespace Matchers; - -} // namespace Catch - -// #included from: internal/catch_interfaces_tag_alias_registry.h -#define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED - -// #included from: catch_tag_alias.h -#define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED - -#include - -namespace Catch { - - struct TagAlias { - TagAlias( std::string _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} - - std::string tag; - SourceLineInfo lineInfo; - }; - - struct RegistrarForTagAliases { - RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); - }; - -} // end namespace Catch - -#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } -// #included from: catch_option.hpp -#define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED - -namespace Catch { - - // An optional type - template - class Option { - public: - Option() : nullableValue( NULL ) {} - Option( T const& _value ) - : nullableValue( new( storage ) T( _value ) ) - {} - Option( Option const& _other ) - : nullableValue( _other ? new( storage ) T( *_other ) : NULL ) - {} - - ~Option() { - reset(); - } - - Option& operator= ( Option const& _other ) { - if( &_other != this ) { - reset(); - if( _other ) - nullableValue = new( storage ) T( *_other ); - } - return *this; - } - Option& operator = ( T const& _value ) { - reset(); - nullableValue = new( storage ) T( _value ); - return *this; - } - - void reset() { - if( nullableValue ) - nullableValue->~T(); - nullableValue = NULL; - } - - T& operator*() { return *nullableValue; } - T const& operator*() const { return *nullableValue; } - T* operator->() { return nullableValue; } - const T* operator->() const { return nullableValue; } - - T valueOr( T const& defaultValue ) const { - return nullableValue ? *nullableValue : defaultValue; - } - - bool some() const { return nullableValue != NULL; } - bool none() const { return nullableValue == NULL; } - - bool operator !() const { return nullableValue == NULL; } - operator SafeBool::type() const { - return SafeBool::makeSafe( some() ); - } - - private: - T* nullableValue; - char storage[sizeof(T)]; - }; - -} // end namespace Catch - -namespace Catch { - - struct ITagAliasRegistry { - virtual ~ITagAliasRegistry(); - virtual Option find( std::string const& alias ) const = 0; - virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; - - static ITagAliasRegistry const& get(); - }; - -} // end namespace Catch - -// These files are included here so the single_include script doesn't put them -// in the conditionally compiled sections -// #included from: internal/catch_test_case_info.h -#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED - -#include -#include - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - struct ITestCase; - - struct TestCaseInfo { - enum SpecialProperties{ - None = 0, - IsHidden = 1 << 1, - ShouldFail = 1 << 2, - MayFail = 1 << 3, - Throws = 1 << 4 - }; - - TestCaseInfo( std::string const& _name, - std::string const& _className, - std::string const& _description, - std::set const& _tags, - SourceLineInfo const& _lineInfo ); - - TestCaseInfo( TestCaseInfo const& other ); - - bool isHidden() const; - bool throws() const; - bool okToFail() const; - bool expectedToFail() const; - - std::string name; - std::string className; - std::string description; - std::set tags; - std::set lcaseTags; - std::string tagsAsString; - SourceLineInfo lineInfo; - SpecialProperties properties; - }; - - class TestCase : public TestCaseInfo { - public: - - TestCase( ITestCase* testCase, TestCaseInfo const& info ); - TestCase( TestCase const& other ); - - TestCase withName( std::string const& _newName ) const; - - void invoke() const; - - TestCaseInfo const& getTestCaseInfo() const; - - void swap( TestCase& other ); - bool operator == ( TestCase const& other ) const; - bool operator < ( TestCase const& other ) const; - TestCase& operator = ( TestCase const& other ); - - private: - Ptr test; - }; - - TestCase makeTestCase( ITestCase* testCase, - std::string const& className, - std::string const& name, - std::string const& description, - SourceLineInfo const& lineInfo ); -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - - -#ifdef __OBJC__ -// #included from: internal/catch_objc.hpp -#define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED - -#import - -#include - -// NB. Any general catch headers included here must be included -// in catch.hpp first to make sure they are included by the single -// header for non obj-usage - -/////////////////////////////////////////////////////////////////////////////// -// This protocol is really only here for (self) documenting purposes, since -// all its methods are optional. -@protocol OcFixture - -@optional - --(void) setUp; --(void) tearDown; - -@end - -namespace Catch { - - class OcMethod : public SharedImpl { - - public: - OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} - - virtual void invoke() const { - id obj = [[m_cls alloc] init]; - - performOptionalSelector( obj, @selector(setUp) ); - performOptionalSelector( obj, m_sel ); - performOptionalSelector( obj, @selector(tearDown) ); - - arcSafeRelease( obj ); - } - private: - virtual ~OcMethod() {} - - Class m_cls; - SEL m_sel; - }; - - namespace Detail{ - - inline std::string getAnnotation( Class cls, - std::string const& annotationName, - std::string const& testCaseName ) { - NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; - SEL sel = NSSelectorFromString( selStr ); - arcSafeRelease( selStr ); - id value = performOptionalSelector( cls, sel ); - if( value ) - return [(NSString*)value UTF8String]; - return ""; - } - } - - inline size_t registerTestMethods() { - size_t noTestMethods = 0; - int noClasses = objc_getClassList( NULL, 0 ); - - Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); - objc_getClassList( classes, noClasses ); - - for( int c = 0; c < noClasses; c++ ) { - Class cls = classes[c]; - { - u_int count; - Method* methods = class_copyMethodList( cls, &count ); - for( u_int m = 0; m < count ; m++ ) { - SEL selector = method_getName(methods[m]); - std::string methodName = sel_getName(selector); - if( startsWith( methodName, "Catch_TestCase_" ) ) { - std::string testCaseName = methodName.substr( 15 ); - std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); - std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); - const char* className = class_getName( cls ); - - getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) ); - noTestMethods++; - } - } - free(methods); - } - } - return noTestMethods; - } - - namespace Matchers { - namespace Impl { - namespace NSStringMatchers { - - template - struct StringHolder : MatcherImpl{ - StringHolder( NSString* substr ) : m_substr( [substr copy] ){} - StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} - StringHolder() { - arcSafeRelease( m_substr ); - } - - NSString* m_substr; - }; - - struct Equals : StringHolder { - Equals( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( ExpressionType const& str ) const { - return (str != nil || m_substr == nil ) && - [str isEqualToString:m_substr]; - } - - virtual std::string toString() const { - return "equals string: " + Catch::toString( m_substr ); - } - }; - - struct Contains : StringHolder { - Contains( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( ExpressionType const& str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location != NSNotFound; - } - - virtual std::string toString() const { - return "contains string: " + Catch::toString( m_substr ); - } - }; - - struct StartsWith : StringHolder { - StartsWith( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( ExpressionType const& str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location == 0; - } - - virtual std::string toString() const { - return "starts with: " + Catch::toString( m_substr ); - } - }; - struct EndsWith : StringHolder { - EndsWith( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( ExpressionType const& str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location == [str length] - [m_substr length]; - } - - virtual std::string toString() const { - return "ends with: " + Catch::toString( m_substr ); - } - }; - - } // namespace NSStringMatchers - } // namespace Impl - - inline Impl::NSStringMatchers::Equals - Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } - - inline Impl::NSStringMatchers::Contains - Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } - - inline Impl::NSStringMatchers::StartsWith - StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } - - inline Impl::NSStringMatchers::EndsWith - EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } - - } // namespace Matchers - - using namespace Matchers; - -} // namespace Catch - -/////////////////////////////////////////////////////////////////////////////// -#define OC_TEST_CASE( name, desc )\ -+(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \ -{\ -return @ name; \ -}\ -+(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \ -{ \ -return @ desc; \ -} \ --(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test ) - -#endif - -#ifdef CATCH_IMPL -// #included from: internal/catch_impl.hpp -#define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED - -// Collect all the implementation files together here -// These are the equivalent of what would usually be cpp files - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wweak-vtables" -#endif - -// #included from: ../catch_runner.hpp -#define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED - -// #included from: internal/catch_commandline.hpp -#define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED - -// #included from: catch_config.hpp -#define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED - -// #included from: catch_test_spec_parser.hpp -#define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -// #included from: catch_test_spec.hpp -#define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -#include -#include - -namespace Catch { - - class TestSpec { - struct Pattern : SharedImpl<> { - virtual ~Pattern(); - virtual bool matches( TestCaseInfo const& testCase ) const = 0; - }; - class NamePattern : public Pattern { - enum WildcardPosition { - NoWildcard = 0, - WildcardAtStart = 1, - WildcardAtEnd = 2, - WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd - }; - - public: - NamePattern( std::string const& name ) : m_name( toLower( name ) ), m_wildcard( NoWildcard ) { - if( startsWith( m_name, "*" ) ) { - m_name = m_name.substr( 1 ); - m_wildcard = WildcardAtStart; - } - if( endsWith( m_name, "*" ) ) { - m_name = m_name.substr( 0, m_name.size()-1 ); - m_wildcard = static_cast( m_wildcard | WildcardAtEnd ); - } - } - virtual ~NamePattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { - switch( m_wildcard ) { - case NoWildcard: - return m_name == toLower( testCase.name ); - case WildcardAtStart: - return endsWith( toLower( testCase.name ), m_name ); - case WildcardAtEnd: - return startsWith( toLower( testCase.name ), m_name ); - case WildcardAtBothEnds: - return contains( toLower( testCase.name ), m_name ); - } - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" -#endif - throw std::logic_error( "Unknown enum" ); -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - } - private: - std::string m_name; - WildcardPosition m_wildcard; - }; - class TagPattern : public Pattern { - public: - TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} - virtual ~TagPattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { - return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end(); - } - private: - std::string m_tag; - }; - class ExcludedPattern : public Pattern { - public: - ExcludedPattern( Ptr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} - virtual ~ExcludedPattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } - private: - Ptr m_underlyingPattern; - }; - - struct Filter { - std::vector > m_patterns; - - bool matches( TestCaseInfo const& testCase ) const { - // All patterns in a filter must match for the filter to be a match - for( std::vector >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) - if( !(*it)->matches( testCase ) ) - return false; - return true; - } - }; - - public: - bool hasFilters() const { - return !m_filters.empty(); - } - bool matches( TestCaseInfo const& testCase ) const { - // A TestSpec matches if any filter matches - for( std::vector::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it ) - if( it->matches( testCase ) ) - return true; - return false; - } - - private: - std::vector m_filters; - - friend class TestSpecParser; - }; -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -namespace Catch { - - class TestSpecParser { - enum Mode{ None, Name, QuotedName, Tag }; - Mode m_mode; - bool m_exclusion; - std::size_t m_start, m_pos; - std::string m_arg; - TestSpec::Filter m_currentFilter; - TestSpec m_testSpec; - ITagAliasRegistry const* m_tagAliases; - - public: - TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} - - TestSpecParser& parse( std::string const& arg ) { - m_mode = None; - m_exclusion = false; - m_start = std::string::npos; - m_arg = m_tagAliases->expandAliases( arg ); - for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) - visitChar( m_arg[m_pos] ); - if( m_mode == Name ) - addPattern(); - return *this; - } - TestSpec testSpec() { - addFilter(); - return m_testSpec; - } - private: - void visitChar( char c ) { - if( m_mode == None ) { - switch( c ) { - case ' ': return; - case '~': m_exclusion = true; return; - case '[': return startNewMode( Tag, ++m_pos ); - case '"': return startNewMode( QuotedName, ++m_pos ); - default: startNewMode( Name, m_pos ); break; - } - } - if( m_mode == Name ) { - if( c == ',' ) { - addPattern(); - addFilter(); - } - else if( c == '[' ) { - if( subString() == "exclude:" ) - m_exclusion = true; - else - addPattern(); - startNewMode( Tag, ++m_pos ); - } - } - else if( m_mode == QuotedName && c == '"' ) - addPattern(); - else if( m_mode == Tag && c == ']' ) - addPattern(); - } - void startNewMode( Mode mode, std::size_t start ) { - m_mode = mode; - m_start = start; - } - std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); } - template - void addPattern() { - std::string token = subString(); - if( startsWith( token, "exclude:" ) ) { - m_exclusion = true; - token = token.substr( 8 ); - } - if( !token.empty() ) { - Ptr pattern = new T( token ); - if( m_exclusion ) - pattern = new TestSpec::ExcludedPattern( pattern ); - m_currentFilter.m_patterns.push_back( pattern ); - } - m_exclusion = false; - m_mode = None; - } - void addFilter() { - if( !m_currentFilter.m_patterns.empty() ) { - m_testSpec.m_filters.push_back( m_currentFilter ); - m_currentFilter = TestSpec::Filter(); - } - } - }; - inline TestSpec parseTestSpec( std::string const& arg ) { - return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); - } - -} // namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -// #included from: catch_interfaces_config.h -#define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED - -#include -#include -#include - -namespace Catch { - - struct Verbosity { enum Level { - NoOutput = 0, - Quiet, - Normal - }; }; - - struct WarnAbout { enum What { - Nothing = 0x00, - NoAssertions = 0x01 - }; }; - - struct ShowDurations { enum OrNot { - DefaultForReporter, - Always, - Never - }; }; - struct RunTests { enum InWhatOrder { - InDeclarationOrder, - InLexicographicalOrder, - InRandomOrder - }; }; - - class TestSpec; - - struct IConfig : IShared { - - virtual ~IConfig(); - - virtual bool allowThrows() const = 0; - virtual std::ostream& stream() const = 0; - virtual std::string name() const = 0; - virtual bool includeSuccessfulResults() const = 0; - virtual bool shouldDebugBreak() const = 0; - virtual bool warnAboutMissingAssertions() const = 0; - virtual int abortAfter() const = 0; - virtual bool showInvisibles() const = 0; - virtual ShowDurations::OrNot showDurations() const = 0; - virtual TestSpec const& testSpec() const = 0; - virtual RunTests::InWhatOrder runOrder() const = 0; - virtual unsigned int rngSeed() const = 0; - virtual bool forceColour() const = 0; - }; -} - -// #included from: catch_stream.h -#define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED - -#include - -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - class Stream { - public: - Stream(); - Stream( std::streambuf* _streamBuf, bool _isOwned ); - void release(); - - std::streambuf* streamBuf; - - private: - bool isOwned; - }; - - std::ostream& cout(); - std::ostream& cerr(); -} - -#include -#include -#include -#include -#include - -#ifndef CATCH_CONFIG_CONSOLE_WIDTH -#define CATCH_CONFIG_CONSOLE_WIDTH 80 -#endif - -namespace Catch { - - struct ConfigData { - - ConfigData() - : listTests( false ), - listTags( false ), - listReporters( false ), - listTestNamesOnly( false ), - showSuccessfulTests( false ), - shouldDebugBreak( false ), - noThrow( false ), - showHelp( false ), - showInvisibles( false ), - forceColour( false ), - abortAfter( -1 ), - rngSeed( 0 ), - verbosity( Verbosity::Normal ), - warnings( WarnAbout::Nothing ), - showDurations( ShowDurations::DefaultForReporter ), - runOrder( RunTests::InDeclarationOrder ) - {} - - bool listTests; - bool listTags; - bool listReporters; - bool listTestNamesOnly; - - bool showSuccessfulTests; - bool shouldDebugBreak; - bool noThrow; - bool showHelp; - bool showInvisibles; - bool forceColour; - - int abortAfter; - unsigned int rngSeed; - - Verbosity::Level verbosity; - WarnAbout::What warnings; - ShowDurations::OrNot showDurations; - RunTests::InWhatOrder runOrder; - - std::string reporterName; - std::string outputFilename; - std::string name; - std::string processName; - - std::vector testsOrTags; - }; - - class Config : public SharedImpl { - private: - Config( Config const& other ); - Config& operator = ( Config const& other ); - virtual void dummy(); - public: - - Config() - : m_os( Catch::cout().rdbuf() ) - {} - - Config( ConfigData const& data ) - : m_data( data ), - m_os( Catch::cout().rdbuf() ) - { - if( !data.testsOrTags.empty() ) { - TestSpecParser parser( ITagAliasRegistry::get() ); - for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) - parser.parse( data.testsOrTags[i] ); - m_testSpec = parser.testSpec(); - } - } - - virtual ~Config() { - m_os.rdbuf( Catch::cout().rdbuf() ); - m_stream.release(); - } - - void setFilename( std::string const& filename ) { - m_data.outputFilename = filename; - } - - std::string const& getFilename() const { - return m_data.outputFilename ; - } - - bool listTests() const { return m_data.listTests; } - bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } - bool listTags() const { return m_data.listTags; } - bool listReporters() const { return m_data.listReporters; } - - std::string getProcessName() const { return m_data.processName; } - - bool shouldDebugBreak() const { return m_data.shouldDebugBreak; } - - void setStreamBuf( std::streambuf* buf ) { - m_os.rdbuf( buf ? buf : Catch::cout().rdbuf() ); - } - - void useStream( std::string const& streamName ) { - Stream stream = createStream( streamName ); - setStreamBuf( stream.streamBuf ); - m_stream.release(); - m_stream = stream; - } - - std::string getReporterName() const { return m_data.reporterName; } - - int abortAfter() const { return m_data.abortAfter; } - - TestSpec const& testSpec() const { return m_testSpec; } - - bool showHelp() const { return m_data.showHelp; } - bool showInvisibles() const { return m_data.showInvisibles; } - - // IConfig interface - virtual bool allowThrows() const { return !m_data.noThrow; } - virtual std::ostream& stream() const { return m_os; } - virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } - virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; } - virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; } - virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; } - virtual RunTests::InWhatOrder runOrder() const { return m_data.runOrder; } - virtual unsigned int rngSeed() const { return m_data.rngSeed; } - virtual bool forceColour() const { return m_data.forceColour; } - - private: - ConfigData m_data; - - Stream m_stream; - mutable std::ostream m_os; - TestSpec m_testSpec; - }; - -} // end namespace Catch - -// #included from: catch_clara.h -#define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED - -// Use Catch's value for console width (store Clara's off to the side, if present) -#ifdef CLARA_CONFIG_CONSOLE_WIDTH -#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH -#undef CLARA_CONFIG_CONSOLE_WIDTH -#endif -#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - -// Declare Clara inside the Catch namespace -#define STITCH_CLARA_OPEN_NAMESPACE namespace Catch { -// #included from: ../external/clara.h - -// Only use header guard if we are not using an outer namespace -#if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE) - -#ifndef STITCH_CLARA_OPEN_NAMESPACE -#define TWOBLUECUBES_CLARA_H_INCLUDED -#define STITCH_CLARA_OPEN_NAMESPACE -#define STITCH_CLARA_CLOSE_NAMESPACE -#else -#define STITCH_CLARA_CLOSE_NAMESPACE } -#endif - -#define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE - -// ----------- #included from tbc_text_format.h ----------- - -// Only use header guard if we are not using an outer namespace -#if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE) -#ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -#define TBC_TEXT_FORMAT_H_INCLUDED -#endif - -#include -#include -#include - -// Use optional outer namespace -#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE { -#endif - -namespace Tbc { - -#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH - const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - struct TextAttributes { - TextAttributes() - : initialIndent( std::string::npos ), - indent( 0 ), - width( consoleWidth-1 ), - tabChar( '\t' ) - {} - - TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } - TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } - TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } - TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } - - std::size_t initialIndent; // indent of first line, or npos - std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos - std::size_t width; // maximum width of text, including indent. Longer text will wrap - char tabChar; // If this char is seen the indent is changed to current pos - }; - - class Text { - public: - Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) - : attr( _attr ) - { - std::string wrappableChars = " [({.,/|\\-"; - std::size_t indent = _attr.initialIndent != std::string::npos - ? _attr.initialIndent - : _attr.indent; - std::string remainder = _str; - - while( !remainder.empty() ) { - if( lines.size() >= 1000 ) { - lines.push_back( "... message truncated due to excessive size" ); - return; - } - std::size_t tabPos = std::string::npos; - std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); - std::size_t pos = remainder.find_first_of( '\n' ); - if( pos <= width ) { - width = pos; - } - pos = remainder.find_last_of( _attr.tabChar, width ); - if( pos != std::string::npos ) { - tabPos = pos; - if( remainder[width] == '\n' ) - width--; - remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); - } - - if( width == remainder.size() ) { - spliceLine( indent, remainder, width ); - } - else if( remainder[width] == '\n' ) { - spliceLine( indent, remainder, width ); - if( width <= 1 || remainder.size() != 1 ) - remainder = remainder.substr( 1 ); - indent = _attr.indent; - } - else { - pos = remainder.find_last_of( wrappableChars, width ); - if( pos != std::string::npos && pos > 0 ) { - spliceLine( indent, remainder, pos ); - if( remainder[0] == ' ' ) - remainder = remainder.substr( 1 ); - } - else { - spliceLine( indent, remainder, width-1 ); - lines.back() += "-"; - } - if( lines.size() == 1 ) - indent = _attr.indent; - if( tabPos != std::string::npos ) - indent += tabPos; - } - } - } - - void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { - lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); - _remainder = _remainder.substr( _pos ); - } - - typedef std::vector::const_iterator const_iterator; - - const_iterator begin() const { return lines.begin(); } - const_iterator end() const { return lines.end(); } - std::string const& last() const { return lines.back(); } - std::size_t size() const { return lines.size(); } - std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } - std::string toString() const { - std::ostringstream oss; - oss << *this; - return oss.str(); - } - - inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { - for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); - it != itEnd; ++it ) { - if( it != _text.begin() ) - _stream << "\n"; - _stream << *it; - } - return _stream; - } - - private: - std::string str; - TextAttributes attr; - std::vector lines; - }; - -} // end namespace Tbc - -#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -} // end outer namespace -#endif - -#endif // TBC_TEXT_FORMAT_H_INCLUDED - -// ----------- end of #include from tbc_text_format.h ----------- -// ........... back in /Users/philnash/Dev/OSS/Clara/srcs/clara.h - -#undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE - -#include -#include -#include -#include - -// Use optional outer namespace -#ifdef STITCH_CLARA_OPEN_NAMESPACE -STITCH_CLARA_OPEN_NAMESPACE -#endif - -namespace Clara { - - struct UnpositionalTag {}; - - extern UnpositionalTag _; - -#ifdef CLARA_CONFIG_MAIN - UnpositionalTag _; -#endif - - namespace Detail { - -#ifdef CLARA_CONSOLE_WIDTH - const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - using namespace Tbc; - - inline bool startsWith( std::string const& str, std::string const& prefix ) { - return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix; - } - - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - - template struct IsBool { static const bool value = false; }; - template<> struct IsBool { static const bool value = true; }; - - template - void convertInto( std::string const& _source, T& _dest ) { - std::stringstream ss; - ss << _source; - ss >> _dest; - if( ss.fail() ) - throw std::runtime_error( "Unable to convert " + _source + " to destination type" ); - } - inline void convertInto( std::string const& _source, std::string& _dest ) { - _dest = _source; - } - inline void convertInto( std::string const& _source, bool& _dest ) { - std::string sourceLC = _source; - std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower ); - if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" ) - _dest = true; - else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" ) - _dest = false; - else - throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" ); - } - inline void convertInto( bool _source, bool& _dest ) { - _dest = _source; - } - template - inline void convertInto( bool, T& ) { - throw std::runtime_error( "Invalid conversion" ); - } - - template - struct IArgFunction { - virtual ~IArgFunction() {} -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - IArgFunction() = default; - IArgFunction( IArgFunction const& ) = default; -# endif - virtual void set( ConfigT& config, std::string const& value ) const = 0; - virtual void setFlag( ConfigT& config ) const = 0; - virtual bool takesArg() const = 0; - virtual IArgFunction* clone() const = 0; - }; - - template - class BoundArgFunction { - public: - BoundArgFunction() : functionObj( NULL ) {} - BoundArgFunction( IArgFunction* _functionObj ) : functionObj( _functionObj ) {} - BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : NULL ) {} - BoundArgFunction& operator = ( BoundArgFunction const& other ) { - IArgFunction* newFunctionObj = other.functionObj ? other.functionObj->clone() : NULL; - delete functionObj; - functionObj = newFunctionObj; - return *this; - } - ~BoundArgFunction() { delete functionObj; } - - void set( ConfigT& config, std::string const& value ) const { - functionObj->set( config, value ); - } - void setFlag( ConfigT& config ) const { - functionObj->setFlag( config ); - } - bool takesArg() const { return functionObj->takesArg(); } - - bool isSet() const { - return functionObj != NULL; - } - private: - IArgFunction* functionObj; - }; - - template - struct NullBinder : IArgFunction{ - virtual void set( C&, std::string const& ) const {} - virtual void setFlag( C& ) const {} - virtual bool takesArg() const { return true; } - virtual IArgFunction* clone() const { return new NullBinder( *this ); } - }; - - template - struct BoundDataMember : IArgFunction{ - BoundDataMember( M C::* _member ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - convertInto( stringValue, p.*member ); - } - virtual void setFlag( C& p ) const { - convertInto( true, p.*member ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundDataMember( *this ); } - M C::* member; - }; - template - struct BoundUnaryMethod : IArgFunction{ - BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - typename RemoveConstRef::type value; - convertInto( stringValue, value ); - (p.*member)( value ); - } - virtual void setFlag( C& p ) const { - typename RemoveConstRef::type value; - convertInto( true, value ); - (p.*member)( value ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundUnaryMethod( *this ); } - void (C::*member)( M ); - }; - template - struct BoundNullaryMethod : IArgFunction{ - BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - bool value; - convertInto( stringValue, value ); - if( value ) - (p.*member)(); - } - virtual void setFlag( C& p ) const { - (p.*member)(); - } - virtual bool takesArg() const { return false; } - virtual IArgFunction* clone() const { return new BoundNullaryMethod( *this ); } - void (C::*member)(); - }; - - template - struct BoundUnaryFunction : IArgFunction{ - BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {} - virtual void set( C& obj, std::string const& stringValue ) const { - bool value; - convertInto( stringValue, value ); - if( value ) - function( obj ); - } - virtual void setFlag( C& p ) const { - function( p ); - } - virtual bool takesArg() const { return false; } - virtual IArgFunction* clone() const { return new BoundUnaryFunction( *this ); } - void (*function)( C& ); - }; - - template - struct BoundBinaryFunction : IArgFunction{ - BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {} - virtual void set( C& obj, std::string const& stringValue ) const { - typename RemoveConstRef::type value; - convertInto( stringValue, value ); - function( obj, value ); - } - virtual void setFlag( C& obj ) const { - typename RemoveConstRef::type value; - convertInto( true, value ); - function( obj, value ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundBinaryFunction( *this ); } - void (*function)( C&, T ); - }; - - } // namespace Detail - - struct Parser { - Parser() : separators( " \t=:" ) {} - - struct Token { - enum Type { Positional, ShortOpt, LongOpt }; - Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {} - Type type; - std::string data; - }; - - void parseIntoTokens( int argc, char const * const * argv, std::vector& tokens ) const { - const std::string doubleDash = "--"; - for( int i = 1; i < argc && argv[i] != doubleDash; ++i ) - parseIntoTokens( argv[i] , tokens); - } - void parseIntoTokens( std::string arg, std::vector& tokens ) const { - while( !arg.empty() ) { - Parser::Token token( Parser::Token::Positional, arg ); - arg = ""; - if( token.data[0] == '-' ) { - if( token.data.size() > 1 && token.data[1] == '-' ) { - token = Parser::Token( Parser::Token::LongOpt, token.data.substr( 2 ) ); - } - else { - token = Parser::Token( Parser::Token::ShortOpt, token.data.substr( 1 ) ); - if( token.data.size() > 1 && separators.find( token.data[1] ) == std::string::npos ) { - arg = "-" + token.data.substr( 1 ); - token.data = token.data.substr( 0, 1 ); - } - } - } - if( token.type != Parser::Token::Positional ) { - std::size_t pos = token.data.find_first_of( separators ); - if( pos != std::string::npos ) { - arg = token.data.substr( pos+1 ); - token.data = token.data.substr( 0, pos ); - } - } - tokens.push_back( token ); - } - } - std::string separators; - }; - - template - struct CommonArgProperties { - CommonArgProperties() {} - CommonArgProperties( Detail::BoundArgFunction const& _boundField ) : boundField( _boundField ) {} - - Detail::BoundArgFunction boundField; - std::string description; - std::string detail; - std::string placeholder; // Only value if boundField takes an arg - - bool takesArg() const { - return !placeholder.empty(); - } - void validate() const { - if( !boundField.isSet() ) - throw std::logic_error( "option not bound" ); - } - }; - struct OptionArgProperties { - std::vector shortNames; - std::string longName; - - bool hasShortName( std::string const& shortName ) const { - return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end(); - } - bool hasLongName( std::string const& _longName ) const { - return _longName == longName; - } - }; - struct PositionalArgProperties { - PositionalArgProperties() : position( -1 ) {} - int position; // -1 means non-positional (floating) - - bool isFixedPositional() const { - return position != -1; - } - }; - - template - class CommandLine { - - struct Arg : CommonArgProperties, OptionArgProperties, PositionalArgProperties { - Arg() {} - Arg( Detail::BoundArgFunction const& _boundField ) : CommonArgProperties( _boundField ) {} - - using CommonArgProperties::placeholder; // !TBD - - std::string dbgName() const { - if( !longName.empty() ) - return "--" + longName; - if( !shortNames.empty() ) - return "-" + shortNames[0]; - return "positional args"; - } - std::string commands() const { - std::ostringstream oss; - bool first = true; - std::vector::const_iterator it = shortNames.begin(), itEnd = shortNames.end(); - for(; it != itEnd; ++it ) { - if( first ) - first = false; - else - oss << ", "; - oss << "-" << *it; - } - if( !longName.empty() ) { - if( !first ) - oss << ", "; - oss << "--" << longName; - } - if( !placeholder.empty() ) - oss << " <" << placeholder << ">"; - return oss.str(); - } - }; - - // NOTE: std::auto_ptr is deprecated in c++11/c++0x -#if defined(__cplusplus) && __cplusplus > 199711L - typedef std::unique_ptr ArgAutoPtr; -#else - typedef std::auto_ptr ArgAutoPtr; -#endif - - friend void addOptName( Arg& arg, std::string const& optName ) - { - if( optName.empty() ) - return; - if( Detail::startsWith( optName, "--" ) ) { - if( !arg.longName.empty() ) - throw std::logic_error( "Only one long opt may be specified. '" - + arg.longName - + "' already specified, now attempting to add '" - + optName + "'" ); - arg.longName = optName.substr( 2 ); - } - else if( Detail::startsWith( optName, "-" ) ) - arg.shortNames.push_back( optName.substr( 1 ) ); - else - throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" ); - } - friend void setPositionalArg( Arg& arg, int position ) - { - arg.position = position; - } - - class ArgBuilder { - public: - ArgBuilder( Arg* arg ) : m_arg( arg ) {} - - // Bind a non-boolean data member (requires placeholder string) - template - void bind( M C::* field, std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundDataMember( field ); - m_arg->placeholder = placeholder; - } - // Bind a boolean data member (no placeholder required) - template - void bind( bool C::* field ) { - m_arg->boundField = new Detail::BoundDataMember( field ); - } - - // Bind a method taking a single, non-boolean argument (requires a placeholder string) - template - void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); - m_arg->placeholder = placeholder; - } - - // Bind a method taking a single, boolean argument (no placeholder string required) - template - void bind( void (C::* unaryMethod)( bool ) ) { - m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); - } - - // Bind a method that takes no arguments (will be called if opt is present) - template - void bind( void (C::* nullaryMethod)() ) { - m_arg->boundField = new Detail::BoundNullaryMethod( nullaryMethod ); - } - - // Bind a free function taking a single argument - the object to operate on (no placeholder string required) - template - void bind( void (* unaryFunction)( C& ) ) { - m_arg->boundField = new Detail::BoundUnaryFunction( unaryFunction ); - } - - // Bind a free function taking a single argument - the object to operate on (requires a placeholder string) - template - void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundBinaryFunction( binaryFunction ); - m_arg->placeholder = placeholder; - } - - ArgBuilder& describe( std::string const& description ) { - m_arg->description = description; - return *this; - } - ArgBuilder& detail( std::string const& detail ) { - m_arg->detail = detail; - return *this; - } - - protected: - Arg* m_arg; - }; - - class OptBuilder : public ArgBuilder { - public: - OptBuilder( Arg* arg ) : ArgBuilder( arg ) {} - OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {} - - OptBuilder& operator[]( std::string const& optName ) { - addOptName( *ArgBuilder::m_arg, optName ); - return *this; - } - }; - - public: - - CommandLine() - : m_boundProcessName( new Detail::NullBinder() ), - m_highestSpecifiedArgPosition( 0 ), - m_throwOnUnrecognisedTokens( false ) - {} - CommandLine( CommandLine const& other ) - : m_boundProcessName( other.m_boundProcessName ), - m_options ( other.m_options ), - m_positionalArgs( other.m_positionalArgs ), - m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ), - m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens ) - { - if( other.m_floatingArg.get() ) - m_floatingArg.reset( new Arg( *other.m_floatingArg ) ); - } - - CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) { - m_throwOnUnrecognisedTokens = shouldThrow; - return *this; - } - - OptBuilder operator[]( std::string const& optName ) { - m_options.push_back( Arg() ); - addOptName( m_options.back(), optName ); - OptBuilder builder( &m_options.back() ); - return builder; - } - - ArgBuilder operator[]( int position ) { - m_positionalArgs.insert( std::make_pair( position, Arg() ) ); - if( position > m_highestSpecifiedArgPosition ) - m_highestSpecifiedArgPosition = position; - setPositionalArg( m_positionalArgs[position], position ); - ArgBuilder builder( &m_positionalArgs[position] ); - return builder; - } - - // Invoke this with the _ instance - ArgBuilder operator[]( UnpositionalTag ) { - if( m_floatingArg.get() ) - throw std::logic_error( "Only one unpositional argument can be added" ); - m_floatingArg.reset( new Arg() ); - ArgBuilder builder( m_floatingArg.get() ); - return builder; - } - - template - void bindProcessName( M C::* field ) { - m_boundProcessName = new Detail::BoundDataMember( field ); - } - template - void bindProcessName( void (C::*_unaryMethod)( M ) ) { - m_boundProcessName = new Detail::BoundUnaryMethod( _unaryMethod ); - } - - void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const { - typename std::vector::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it; - std::size_t maxWidth = 0; - for( it = itBegin; it != itEnd; ++it ) - maxWidth = (std::max)( maxWidth, it->commands().size() ); - - for( it = itBegin; it != itEnd; ++it ) { - Detail::Text usage( it->commands(), Detail::TextAttributes() - .setWidth( maxWidth+indent ) - .setIndent( indent ) ); - Detail::Text desc( it->description, Detail::TextAttributes() - .setWidth( width - maxWidth - 3 ) ); - - for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) { - std::string usageCol = i < usage.size() ? usage[i] : ""; - os << usageCol; - - if( i < desc.size() && !desc[i].empty() ) - os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' ) - << desc[i]; - os << "\n"; - } - } - } - std::string optUsage() const { - std::ostringstream oss; - optUsage( oss ); - return oss.str(); - } - - void argSynopsis( std::ostream& os ) const { - for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) { - if( i > 1 ) - os << " "; - typename std::map::const_iterator it = m_positionalArgs.find( i ); - if( it != m_positionalArgs.end() ) - os << "<" << it->second.placeholder << ">"; - else if( m_floatingArg.get() ) - os << "<" << m_floatingArg->placeholder << ">"; - else - throw std::logic_error( "non consecutive positional arguments with no floating args" ); - } - // !TBD No indication of mandatory args - if( m_floatingArg.get() ) { - if( m_highestSpecifiedArgPosition > 1 ) - os << " "; - os << "[<" << m_floatingArg->placeholder << "> ...]"; - } - } - std::string argSynopsis() const { - std::ostringstream oss; - argSynopsis( oss ); - return oss.str(); - } - - void usage( std::ostream& os, std::string const& procName ) const { - validate(); - os << "usage:\n " << procName << " "; - argSynopsis( os ); - if( !m_options.empty() ) { - os << " [options]\n\nwhere options are: \n"; - optUsage( os, 2 ); - } - os << "\n"; - } - std::string usage( std::string const& procName ) const { - std::ostringstream oss; - usage( oss, procName ); - return oss.str(); - } - - ConfigT parse( int argc, char const * const * argv ) const { - ConfigT config; - parseInto( argc, argv, config ); - return config; - } - - std::vector parseInto( int argc, char const * const * argv, ConfigT& config ) const { - std::string processName = argv[0]; - std::size_t lastSlash = processName.find_last_of( "/\\" ); - if( lastSlash != std::string::npos ) - processName = processName.substr( lastSlash+1 ); - m_boundProcessName.set( config, processName ); - std::vector tokens; - Parser parser; - parser.parseIntoTokens( argc, argv, tokens ); - return populate( tokens, config ); - } - - std::vector populate( std::vector const& tokens, ConfigT& config ) const { - validate(); - std::vector unusedTokens = populateOptions( tokens, config ); - unusedTokens = populateFixedArgs( unusedTokens, config ); - unusedTokens = populateFloatingArgs( unusedTokens, config ); - return unusedTokens; - } - - std::vector populateOptions( std::vector const& tokens, ConfigT& config ) const { - std::vector unusedTokens; - std::vector errors; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - typename std::vector::const_iterator it = m_options.begin(), itEnd = m_options.end(); - for(; it != itEnd; ++it ) { - Arg const& arg = *it; - - try { - if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) || - ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) { - if( arg.takesArg() ) { - if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional ) - errors.push_back( "Expected argument to option: " + token.data ); - else - arg.boundField.set( config, tokens[++i].data ); - } - else { - arg.boundField.setFlag( config ); - } - break; - } - } - catch( std::exception& ex ) { - errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" ); - } - } - if( it == itEnd ) { - if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens ) - unusedTokens.push_back( token ); - else if( errors.empty() && m_throwOnUnrecognisedTokens ) - errors.push_back( "unrecognised option: " + token.data ); - } - } - if( !errors.empty() ) { - std::ostringstream oss; - for( std::vector::const_iterator it = errors.begin(), itEnd = errors.end(); - it != itEnd; - ++it ) { - if( it != errors.begin() ) - oss << "\n"; - oss << *it; - } - throw std::runtime_error( oss.str() ); - } - return unusedTokens; - } - std::vector populateFixedArgs( std::vector const& tokens, ConfigT& config ) const { - std::vector unusedTokens; - int position = 1; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - typename std::map::const_iterator it = m_positionalArgs.find( position ); - if( it != m_positionalArgs.end() ) - it->second.boundField.set( config, token.data ); - else - unusedTokens.push_back( token ); - if( token.type == Parser::Token::Positional ) - position++; - } - return unusedTokens; - } - std::vector populateFloatingArgs( std::vector const& tokens, ConfigT& config ) const { - if( !m_floatingArg.get() ) - return tokens; - std::vector unusedTokens; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - if( token.type == Parser::Token::Positional ) - m_floatingArg->boundField.set( config, token.data ); - else - unusedTokens.push_back( token ); - } - return unusedTokens; - } - - void validate() const - { - if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() ) - throw std::logic_error( "No options or arguments specified" ); - - for( typename std::vector::const_iterator it = m_options.begin(), - itEnd = m_options.end(); - it != itEnd; ++it ) - it->validate(); - } - - private: - Detail::BoundArgFunction m_boundProcessName; - std::vector m_options; - std::map m_positionalArgs; - ArgAutoPtr m_floatingArg; - int m_highestSpecifiedArgPosition; - bool m_throwOnUnrecognisedTokens; - }; - -} // end namespace Clara - -STITCH_CLARA_CLOSE_NAMESPACE -#undef STITCH_CLARA_OPEN_NAMESPACE -#undef STITCH_CLARA_CLOSE_NAMESPACE - -#endif // TWOBLUECUBES_CLARA_H_INCLUDED -#undef STITCH_CLARA_OPEN_NAMESPACE - -// Restore Clara's value for console width, if present -#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#endif - -#include - -namespace Catch { - - inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; } - inline void abortAfterX( ConfigData& config, int x ) { - if( x < 1 ) - throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" ); - config.abortAfter = x; - } - inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); } - - inline void addWarning( ConfigData& config, std::string const& _warning ) { - if( _warning == "NoAssertions" ) - config.warnings = static_cast( config.warnings | WarnAbout::NoAssertions ); - else - throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" ); - } - inline void setOrder( ConfigData& config, std::string const& order ) { - if( startsWith( "declared", order ) ) - config.runOrder = RunTests::InDeclarationOrder; - else if( startsWith( "lexical", order ) ) - config.runOrder = RunTests::InLexicographicalOrder; - else if( startsWith( "random", order ) ) - config.runOrder = RunTests::InRandomOrder; - else - throw std::runtime_error( "Unrecognised ordering: '" + order + "'" ); - } - inline void setRngSeed( ConfigData& config, std::string const& seed ) { - if( seed == "time" ) { - config.rngSeed = static_cast( std::time(0) ); - } - else { - std::stringstream ss; - ss << seed; - ss >> config.rngSeed; - if( ss.fail() ) - throw std::runtime_error( "Argment to --rng-seed should be the word 'time' or a number" ); - } - } - inline void setVerbosity( ConfigData& config, int level ) { - // !TBD: accept strings? - config.verbosity = static_cast( level ); - } - inline void setShowDurations( ConfigData& config, bool _showDurations ) { - config.showDurations = _showDurations - ? ShowDurations::Always - : ShowDurations::Never; - } - inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) { - std::ifstream f( _filename.c_str() ); - if( !f.is_open() ) - throw std::domain_error( "Unable to load input file: " + _filename ); - - std::string line; - while( std::getline( f, line ) ) { - line = trim(line); - if( !line.empty() && !startsWith( line, "#" ) ) - addTestOrTags( config, "\"" + line + "\"," ); - } - } - - inline Clara::CommandLine makeCommandLineParser() { - - using namespace Clara; - CommandLine cli; - - cli.bindProcessName( &ConfigData::processName ); - - cli["-?"]["-h"]["--help"] - .describe( "display usage information" ) - .bind( &ConfigData::showHelp ); - - cli["-l"]["--list-tests"] - .describe( "list all/matching test cases" ) - .bind( &ConfigData::listTests ); - - cli["-t"]["--list-tags"] - .describe( "list all/matching tags" ) - .bind( &ConfigData::listTags ); - - cli["-s"]["--success"] - .describe( "include successful tests in output" ) - .bind( &ConfigData::showSuccessfulTests ); - - cli["-b"]["--break"] - .describe( "break into debugger on failure" ) - .bind( &ConfigData::shouldDebugBreak ); - - cli["-e"]["--nothrow"] - .describe( "skip exception tests" ) - .bind( &ConfigData::noThrow ); - - cli["-i"]["--invisibles"] - .describe( "show invisibles (tabs, newlines)" ) - .bind( &ConfigData::showInvisibles ); - - cli["-o"]["--out"] - .describe( "output filename" ) - .bind( &ConfigData::outputFilename, "filename" ); - - cli["-r"]["--reporter"] -// .placeholder( "name[:filename]" ) - .describe( "reporter to use (defaults to console)" ) - .bind( &ConfigData::reporterName, "name" ); - - cli["-n"]["--name"] - .describe( "suite name" ) - .bind( &ConfigData::name, "name" ); - - cli["-a"]["--abort"] - .describe( "abort at first failure" ) - .bind( &abortAfterFirst ); - - cli["-x"]["--abortx"] - .describe( "abort after x failures" ) - .bind( &abortAfterX, "no. failures" ); - - cli["-w"]["--warn"] - .describe( "enable warnings" ) - .bind( &addWarning, "warning name" ); - -// - needs updating if reinstated -// cli.into( &setVerbosity ) -// .describe( "level of verbosity (0=no output)" ) -// .shortOpt( "v") -// .longOpt( "verbosity" ) -// .placeholder( "level" ); - - cli[_] - .describe( "which test or tests to use" ) - .bind( &addTestOrTags, "test name, pattern or tags" ); - - cli["-d"]["--durations"] - .describe( "show test durations" ) - .bind( &setShowDurations, "yes/no" ); - - cli["-f"]["--input-file"] - .describe( "load test names to run from a file" ) - .bind( &loadTestNamesFromFile, "filename" ); - - // Less common commands which don't have a short form - cli["--list-test-names-only"] - .describe( "list all/matching test cases names only" ) - .bind( &ConfigData::listTestNamesOnly ); - - cli["--list-reporters"] - .describe( "list all reporters" ) - .bind( &ConfigData::listReporters ); - - cli["--order"] - .describe( "test case order (defaults to decl)" ) - .bind( &setOrder, "decl|lex|rand" ); - - cli["--rng-seed"] - .describe( "set a specific seed for random numbers" ) - .bind( &setRngSeed, "'time'|number" ); - - cli["--force-colour"] - .describe( "force colourised output" ) - .bind( &ConfigData::forceColour ); - - return cli; - } - -} // end namespace Catch - -// #included from: internal/catch_list.hpp -#define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED - -// #included from: catch_text.h -#define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED - -#define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - -#define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch -// #included from: ../external/tbc_text_format.h -// Only use header guard if we are not using an outer namespace -#ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -# ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED -# ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -# define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -# endif -# else -# define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED -# endif -#endif -#ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -#include -#include -#include - -// Use optional outer namespace -#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE { -#endif - -namespace Tbc { - -#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH - const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - struct TextAttributes { - TextAttributes() - : initialIndent( std::string::npos ), - indent( 0 ), - width( consoleWidth-1 ), - tabChar( '\t' ) - {} - - TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } - TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } - TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } - TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } - - std::size_t initialIndent; // indent of first line, or npos - std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos - std::size_t width; // maximum width of text, including indent. Longer text will wrap - char tabChar; // If this char is seen the indent is changed to current pos - }; - - class Text { - public: - Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) - : attr( _attr ) - { - std::string wrappableChars = " [({.,/|\\-"; - std::size_t indent = _attr.initialIndent != std::string::npos - ? _attr.initialIndent - : _attr.indent; - std::string remainder = _str; - - while( !remainder.empty() ) { - if( lines.size() >= 1000 ) { - lines.push_back( "... message truncated due to excessive size" ); - return; - } - std::size_t tabPos = std::string::npos; - std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); - std::size_t pos = remainder.find_first_of( '\n' ); - if( pos <= width ) { - width = pos; - } - pos = remainder.find_last_of( _attr.tabChar, width ); - if( pos != std::string::npos ) { - tabPos = pos; - if( remainder[width] == '\n' ) - width--; - remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); - } - - if( width == remainder.size() ) { - spliceLine( indent, remainder, width ); - } - else if( remainder[width] == '\n' ) { - spliceLine( indent, remainder, width ); - if( width <= 1 || remainder.size() != 1 ) - remainder = remainder.substr( 1 ); - indent = _attr.indent; - } - else { - pos = remainder.find_last_of( wrappableChars, width ); - if( pos != std::string::npos && pos > 0 ) { - spliceLine( indent, remainder, pos ); - if( remainder[0] == ' ' ) - remainder = remainder.substr( 1 ); - } - else { - spliceLine( indent, remainder, width-1 ); - lines.back() += "-"; - } - if( lines.size() == 1 ) - indent = _attr.indent; - if( tabPos != std::string::npos ) - indent += tabPos; - } - } - } - - void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { - lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); - _remainder = _remainder.substr( _pos ); - } - - typedef std::vector::const_iterator const_iterator; - - const_iterator begin() const { return lines.begin(); } - const_iterator end() const { return lines.end(); } - std::string const& last() const { return lines.back(); } - std::size_t size() const { return lines.size(); } - std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } - std::string toString() const { - std::ostringstream oss; - oss << *this; - return oss.str(); - } - - inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { - for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); - it != itEnd; ++it ) { - if( it != _text.begin() ) - _stream << "\n"; - _stream << *it; - } - return _stream; - } - - private: - std::string str; - TextAttributes attr; - std::vector lines; - }; - -} // end namespace Tbc - -#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -} // end outer namespace -#endif - -#endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -#undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE - -namespace Catch { - using Tbc::Text; - using Tbc::TextAttributes; -} - -// #included from: catch_console_colour.hpp -#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED - -namespace Catch { - - struct Colour { - enum Code { - None = 0, - - White, - Red, - Green, - Blue, - Cyan, - Yellow, - Grey, - - Bright = 0x10, - - BrightRed = Bright | Red, - BrightGreen = Bright | Green, - LightGrey = Bright | Grey, - BrightWhite = Bright | White, - - // By intention - FileName = LightGrey, - Warning = Yellow, - ResultError = BrightRed, - ResultSuccess = BrightGreen, - ResultExpectedFailure = Warning, - - Error = BrightRed, - Success = Green, - - OriginalExpression = Cyan, - ReconstructedExpression = Yellow, - - SecondaryText = LightGrey, - Headers = White - }; - - // Use constructed object for RAII guard - Colour( Code _colourCode ); - Colour( Colour const& other ); - ~Colour(); - - // Use static method for one-shot changes - static void use( Code _colourCode ); - - private: - bool m_moved; - }; - - inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; } - -} // end namespace Catch - -// #included from: catch_interfaces_reporter.h -#define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED - -#include -#include -#include -#include - -namespace Catch -{ - struct ReporterConfig { - explicit ReporterConfig( Ptr const& _fullConfig ) - : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} - - ReporterConfig( Ptr const& _fullConfig, std::ostream& _stream ) - : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} - - std::ostream& stream() const { return *m_stream; } - Ptr fullConfig() const { return m_fullConfig; } - - private: - std::ostream* m_stream; - Ptr m_fullConfig; - }; - - struct ReporterPreferences { - ReporterPreferences() - : shouldRedirectStdOut( false ) - {} - - bool shouldRedirectStdOut; - }; - - template - struct LazyStat : Option { - LazyStat() : used( false ) {} - LazyStat& operator=( T const& _value ) { - Option::operator=( _value ); - used = false; - return *this; - } - void reset() { - Option::reset(); - used = false; - } - bool used; - }; - - struct TestRunInfo { - TestRunInfo( std::string const& _name ) : name( _name ) {} - std::string name; - }; - struct GroupInfo { - GroupInfo( std::string const& _name, - std::size_t _groupIndex, - std::size_t _groupsCount ) - : name( _name ), - groupIndex( _groupIndex ), - groupsCounts( _groupsCount ) - {} - - std::string name; - std::size_t groupIndex; - std::size_t groupsCounts; - }; - - struct AssertionStats { - AssertionStats( AssertionResult const& _assertionResult, - std::vector const& _infoMessages, - Totals const& _totals ) - : assertionResult( _assertionResult ), - infoMessages( _infoMessages ), - totals( _totals ) - { - if( assertionResult.hasMessage() ) { - // Copy message into messages list. - // !TBD This should have been done earlier, somewhere - MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); - builder << assertionResult.getMessage(); - builder.m_info.message = builder.m_stream.str(); - - infoMessages.push_back( builder.m_info ); - } - } - virtual ~AssertionStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - AssertionStats( AssertionStats const& ) = default; - AssertionStats( AssertionStats && ) = default; - AssertionStats& operator = ( AssertionStats const& ) = default; - AssertionStats& operator = ( AssertionStats && ) = default; -# endif - - AssertionResult assertionResult; - std::vector infoMessages; - Totals totals; - }; - - struct SectionStats { - SectionStats( SectionInfo const& _sectionInfo, - Counts const& _assertions, - double _durationInSeconds, - bool _missingAssertions ) - : sectionInfo( _sectionInfo ), - assertions( _assertions ), - durationInSeconds( _durationInSeconds ), - missingAssertions( _missingAssertions ) - {} - virtual ~SectionStats(); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - SectionStats( SectionStats const& ) = default; - SectionStats( SectionStats && ) = default; - SectionStats& operator = ( SectionStats const& ) = default; - SectionStats& operator = ( SectionStats && ) = default; -# endif - - SectionInfo sectionInfo; - Counts assertions; - double durationInSeconds; - bool missingAssertions; - }; - - struct TestCaseStats { - TestCaseStats( TestCaseInfo const& _testInfo, - Totals const& _totals, - std::string const& _stdOut, - std::string const& _stdErr, - bool _aborting ) - : testInfo( _testInfo ), - totals( _totals ), - stdOut( _stdOut ), - stdErr( _stdErr ), - aborting( _aborting ) - {} - virtual ~TestCaseStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestCaseStats( TestCaseStats const& ) = default; - TestCaseStats( TestCaseStats && ) = default; - TestCaseStats& operator = ( TestCaseStats const& ) = default; - TestCaseStats& operator = ( TestCaseStats && ) = default; -# endif - - TestCaseInfo testInfo; - Totals totals; - std::string stdOut; - std::string stdErr; - bool aborting; - }; - - struct TestGroupStats { - TestGroupStats( GroupInfo const& _groupInfo, - Totals const& _totals, - bool _aborting ) - : groupInfo( _groupInfo ), - totals( _totals ), - aborting( _aborting ) - {} - TestGroupStats( GroupInfo const& _groupInfo ) - : groupInfo( _groupInfo ), - aborting( false ) - {} - virtual ~TestGroupStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestGroupStats( TestGroupStats const& ) = default; - TestGroupStats( TestGroupStats && ) = default; - TestGroupStats& operator = ( TestGroupStats const& ) = default; - TestGroupStats& operator = ( TestGroupStats && ) = default; -# endif - - GroupInfo groupInfo; - Totals totals; - bool aborting; - }; - - struct TestRunStats { - TestRunStats( TestRunInfo const& _runInfo, - Totals const& _totals, - bool _aborting ) - : runInfo( _runInfo ), - totals( _totals ), - aborting( _aborting ) - {} - virtual ~TestRunStats(); - -# ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestRunStats( TestRunStats const& _other ) - : runInfo( _other.runInfo ), - totals( _other.totals ), - aborting( _other.aborting ) - {} -# else - TestRunStats( TestRunStats const& ) = default; - TestRunStats( TestRunStats && ) = default; - TestRunStats& operator = ( TestRunStats const& ) = default; - TestRunStats& operator = ( TestRunStats && ) = default; -# endif - - TestRunInfo runInfo; - Totals totals; - bool aborting; - }; - - struct IStreamingReporter : IShared { - virtual ~IStreamingReporter(); - - // Implementing class must also provide the following static method: - // static std::string getDescription(); - - virtual ReporterPreferences getPreferences() const = 0; - - virtual void noMatchingTestCases( std::string const& spec ) = 0; - - virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; - virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; - - virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; - virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; - - virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; - - // The return value indicates if the messages buffer should be cleared: - virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; - virtual void sectionEnded( SectionStats const& sectionStats ) = 0; - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; - virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; - - virtual void skipTest( TestCaseInfo const& testInfo ) = 0; - }; - - struct IReporterFactory { - virtual ~IReporterFactory(); - virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0; - virtual std::string getDescription() const = 0; - }; - - struct IReporterRegistry { - typedef std::map FactoryMap; - - virtual ~IReporterRegistry(); - virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const = 0; - virtual FactoryMap const& getFactories() const = 0; - }; - -} - -#include -#include - -namespace Catch { - - inline std::size_t listTests( Config const& config ) { - - TestSpec testSpec = config.testSpec(); - if( config.testSpec().hasFilters() ) - Catch::cout() << "Matching test cases:\n"; - else { - Catch::cout() << "All available test cases:\n"; - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - } - - std::size_t matchedTests = 0; - TextAttributes nameAttr, tagsAttr; - nameAttr.setInitialIndent( 2 ).setIndent( 4 ); - tagsAttr.setIndent( 6 ); - - std::vector matchedTestCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - matchedTests++; - TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); - Colour::Code colour = testCaseInfo.isHidden() - ? Colour::SecondaryText - : Colour::None; - Colour colourGuard( colour ); - - Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl; - if( !testCaseInfo.tags.empty() ) - Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl; - } - - if( !config.testSpec().hasFilters() ) - Catch::cout() << pluralise( matchedTests, "test case" ) << "\n" << std::endl; - else - Catch::cout() << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl; - return matchedTests; - } - - inline std::size_t listTestsNamesOnly( Config const& config ) { - TestSpec testSpec = config.testSpec(); - if( !config.testSpec().hasFilters() ) - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - std::size_t matchedTests = 0; - std::vector matchedTestCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - matchedTests++; - TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); - Catch::cout() << testCaseInfo.name << std::endl; - } - return matchedTests; - } - - struct TagInfo { - TagInfo() : count ( 0 ) {} - void add( std::string const& spelling ) { - ++count; - spellings.insert( spelling ); - } - std::string all() const { - std::string out; - for( std::set::const_iterator it = spellings.begin(), itEnd = spellings.end(); - it != itEnd; - ++it ) - out += "[" + *it + "]"; - return out; - } - std::set spellings; - std::size_t count; - }; - - inline std::size_t listTags( Config const& config ) { - TestSpec testSpec = config.testSpec(); - if( config.testSpec().hasFilters() ) - Catch::cout() << "Tags for matching test cases:\n"; - else { - Catch::cout() << "All available tags:\n"; - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - } - - std::map tagCounts; - - std::vector matchedTestCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - for( std::set::const_iterator tagIt = it->getTestCaseInfo().tags.begin(), - tagItEnd = it->getTestCaseInfo().tags.end(); - tagIt != tagItEnd; - ++tagIt ) { - std::string tagName = *tagIt; - std::string lcaseTagName = toLower( tagName ); - std::map::iterator countIt = tagCounts.find( lcaseTagName ); - if( countIt == tagCounts.end() ) - countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; - countIt->second.add( tagName ); - } - } - - for( std::map::const_iterator countIt = tagCounts.begin(), - countItEnd = tagCounts.end(); - countIt != countItEnd; - ++countIt ) { - std::ostringstream oss; - oss << " " << std::setw(2) << countIt->second.count << " "; - Text wrapper( countIt->second.all(), TextAttributes() - .setInitialIndent( 0 ) - .setIndent( oss.str().size() ) - .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) ); - Catch::cout() << oss.str() << wrapper << "\n"; - } - Catch::cout() << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl; - return tagCounts.size(); - } - - inline std::size_t listReporters( Config const& /*config*/ ) { - Catch::cout() << "Available reporters:\n"; - IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); - IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it; - std::size_t maxNameLen = 0; - for(it = itBegin; it != itEnd; ++it ) - maxNameLen = (std::max)( maxNameLen, it->first.size() ); - - for(it = itBegin; it != itEnd; ++it ) { - Text wrapper( it->second->getDescription(), TextAttributes() - .setInitialIndent( 0 ) - .setIndent( 7+maxNameLen ) - .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) ); - Catch::cout() << " " - << it->first - << ":" - << std::string( maxNameLen - it->first.size() + 2, ' ' ) - << wrapper << "\n"; - } - Catch::cout() << std::endl; - return factories.size(); - } - - inline Option list( Config const& config ) { - Option listedCount; - if( config.listTests() ) - listedCount = listedCount.valueOr(0) + listTests( config ); - if( config.listTestNamesOnly() ) - listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); - if( config.listTags() ) - listedCount = listedCount.valueOr(0) + listTags( config ); - if( config.listReporters() ) - listedCount = listedCount.valueOr(0) + listReporters( config ); - return listedCount; - } - -} // end namespace Catch - -// #included from: internal/catch_runner_impl.hpp -#define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED - -// #included from: catch_test_case_tracker.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { -namespace SectionTracking { - - class TrackedSection { - - typedef std::map TrackedSections; - - public: - enum RunState { - NotStarted, - Executing, - ExecutingChildren, - Completed - }; - - TrackedSection( std::string const& name, TrackedSection* parent ) - : m_name( name ), m_runState( NotStarted ), m_parent( parent ) - {} - - RunState runState() const { return m_runState; } - - TrackedSection* findChild( std::string const& childName ); - TrackedSection* acquireChild( std::string const& childName ); - - void enter() { - if( m_runState == NotStarted ) - m_runState = Executing; - } - void leave(); - - TrackedSection* getParent() { - return m_parent; - } - bool hasChildren() const { - return !m_children.empty(); - } - - private: - std::string m_name; - RunState m_runState; - TrackedSections m_children; - TrackedSection* m_parent; - }; - - inline TrackedSection* TrackedSection::findChild( std::string const& childName ) { - TrackedSections::iterator it = m_children.find( childName ); - return it != m_children.end() - ? &it->second - : NULL; - } - inline TrackedSection* TrackedSection::acquireChild( std::string const& childName ) { - if( TrackedSection* child = findChild( childName ) ) - return child; - m_children.insert( std::make_pair( childName, TrackedSection( childName, this ) ) ); - return findChild( childName ); - } - inline void TrackedSection::leave() { - for( TrackedSections::const_iterator it = m_children.begin(), itEnd = m_children.end(); - it != itEnd; - ++it ) - if( it->second.runState() != Completed ) { - m_runState = ExecutingChildren; - return; - } - m_runState = Completed; - } - - class TestCaseTracker { - public: - TestCaseTracker( std::string const& testCaseName ) - : m_testCase( testCaseName, NULL ), - m_currentSection( &m_testCase ), - m_completedASectionThisRun( false ) - {} - - bool enterSection( std::string const& name ) { - TrackedSection* child = m_currentSection->acquireChild( name ); - if( m_completedASectionThisRun || child->runState() == TrackedSection::Completed ) - return false; - - m_currentSection = child; - m_currentSection->enter(); - return true; - } - void leaveSection() { - m_currentSection->leave(); - m_currentSection = m_currentSection->getParent(); - assert( m_currentSection != NULL ); - m_completedASectionThisRun = true; - } - - bool currentSectionHasChildren() const { - return m_currentSection->hasChildren(); - } - bool isCompleted() const { - return m_testCase.runState() == TrackedSection::Completed; - } - - class Guard { - public: - Guard( TestCaseTracker& tracker ) : m_tracker( tracker ) { - m_tracker.enterTestCase(); - } - ~Guard() { - m_tracker.leaveTestCase(); - } - private: - Guard( Guard const& ); - void operator = ( Guard const& ); - TestCaseTracker& m_tracker; - }; - - private: - void enterTestCase() { - m_currentSection = &m_testCase; - m_completedASectionThisRun = false; - m_testCase.enter(); - } - void leaveTestCase() { - m_testCase.leave(); - } - - TrackedSection m_testCase; - TrackedSection* m_currentSection; - bool m_completedASectionThisRun; - }; - -} // namespace SectionTracking - -using SectionTracking::TestCaseTracker; - -} // namespace Catch - -// #included from: catch_fatal_condition.hpp -#define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED - -namespace Catch { - - // Report the error condition then exit the process - inline void fatal( std::string const& message, int exitCode ) { - IContext& context = Catch::getCurrentContext(); - IResultCapture* resultCapture = context.getResultCapture(); - resultCapture->handleFatalErrorCondition( message ); - - if( Catch::alwaysTrue() ) // avoids "no return" warnings - exit( exitCode ); - } - -} // namespace Catch - -#if defined ( CATCH_PLATFORM_WINDOWS ) ///////////////////////////////////////// - -namespace Catch { - - struct FatalConditionHandler { - void reset() {} - }; - -} // namespace Catch - -#else // Not Windows - assumed to be POSIX compatible ////////////////////////// - -#include - -namespace Catch { - - struct SignalDefs { int id; const char* name; }; - extern SignalDefs signalDefs[]; - SignalDefs signalDefs[] = { - { SIGINT, "SIGINT - Terminal interrupt signal" }, - { SIGILL, "SIGILL - Illegal instruction signal" }, - { SIGFPE, "SIGFPE - Floating point error signal" }, - { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, - { SIGTERM, "SIGTERM - Termination request signal" }, - { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } - }; - - struct FatalConditionHandler { - - static void handleSignal( int sig ) { - for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) - if( sig == signalDefs[i].id ) - fatal( signalDefs[i].name, -sig ); - fatal( "", -sig ); - } - - FatalConditionHandler() : m_isSet( true ) { - for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) - signal( signalDefs[i].id, handleSignal ); - } - ~FatalConditionHandler() { - reset(); - } - void reset() { - if( m_isSet ) { - for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) - signal( signalDefs[i].id, SIG_DFL ); - m_isSet = false; - } - } - - bool m_isSet; - }; - -} // namespace Catch - -#endif // not Windows - -#include -#include - -namespace Catch { - - class StreamRedirect { - - public: - StreamRedirect( std::ostream& stream, std::string& targetString ) - : m_stream( stream ), - m_prevBuf( stream.rdbuf() ), - m_targetString( targetString ) - { - stream.rdbuf( m_oss.rdbuf() ); - } - - ~StreamRedirect() { - m_targetString += m_oss.str(); - m_stream.rdbuf( m_prevBuf ); - } - - private: - std::ostream& m_stream; - std::streambuf* m_prevBuf; - std::ostringstream m_oss; - std::string& m_targetString; - }; - - /////////////////////////////////////////////////////////////////////////// - - class RunContext : public IResultCapture, public IRunner { - - RunContext( RunContext const& ); - void operator =( RunContext const& ); - - public: - - explicit RunContext( Ptr const& config, Ptr const& reporter ) - : m_runInfo( config->name() ), - m_context( getCurrentMutableContext() ), - m_activeTestCase( NULL ), - m_config( config ), - m_reporter( reporter ), - m_prevRunner( m_context.getRunner() ), - m_prevResultCapture( m_context.getResultCapture() ), - m_prevConfig( m_context.getConfig() ) - { - m_context.setRunner( this ); - m_context.setConfig( m_config ); - m_context.setResultCapture( this ); - m_reporter->testRunStarting( m_runInfo ); - } - - virtual ~RunContext() { - m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); - m_context.setRunner( m_prevRunner ); - m_context.setConfig( NULL ); - m_context.setResultCapture( m_prevResultCapture ); - m_context.setConfig( m_prevConfig ); - } - - void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { - m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); - } - void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { - m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); - } - - Totals runTest( TestCase const& testCase ) { - Totals prevTotals = m_totals; - - std::string redirectedCout; - std::string redirectedCerr; - - TestCaseInfo testInfo = testCase.getTestCaseInfo(); - - m_reporter->testCaseStarting( testInfo ); - - m_activeTestCase = &testCase; - m_testCaseTracker = TestCaseTracker( testInfo.name ); - - do { - do { - runCurrentTest( redirectedCout, redirectedCerr ); - } - while( !m_testCaseTracker->isCompleted() && !aborting() ); - } - while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() ); - - Totals deltaTotals = m_totals.delta( prevTotals ); - m_totals.testCases += deltaTotals.testCases; - m_reporter->testCaseEnded( TestCaseStats( testInfo, - deltaTotals, - redirectedCout, - redirectedCerr, - aborting() ) ); - - m_activeTestCase = NULL; - m_testCaseTracker.reset(); - - return deltaTotals; - } - - Ptr config() const { - return m_config; - } - - private: // IResultCapture - - virtual void assertionEnded( AssertionResult const& result ) { - if( result.getResultType() == ResultWas::Ok ) { - m_totals.assertions.passed++; - } - else if( !result.isOk() ) { - m_totals.assertions.failed++; - } - - if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) ) - m_messages.clear(); - - // Reset working state - m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); - m_lastResult = result; - } - - virtual bool sectionStarted ( - SectionInfo const& sectionInfo, - Counts& assertions - ) - { - std::ostringstream oss; - oss << sectionInfo.name << "@" << sectionInfo.lineInfo; - - if( !m_testCaseTracker->enterSection( oss.str() ) ) - return false; - - m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; - - m_reporter->sectionStarting( sectionInfo ); - - assertions = m_totals.assertions; - - return true; - } - bool testForMissingAssertions( Counts& assertions ) { - if( assertions.total() != 0 || - !m_config->warnAboutMissingAssertions() || - m_testCaseTracker->currentSectionHasChildren() ) - return false; - m_totals.assertions.failed++; - assertions.failed++; - return true; - } - - virtual void sectionEnded( SectionInfo const& info, Counts const& prevAssertions, double _durationInSeconds ) { - /* if( std::uncaught_exception() ) { // XXX Hack that makes Catch not run in loop in certain situations - m_unfinishedSections.push_back( UnfinishedSections( info, prevAssertions, _durationInSeconds ) ); - return; - }*/ - - Counts assertions = m_totals.assertions - prevAssertions; - bool missingAssertions = testForMissingAssertions( assertions ); - - m_testCaseTracker->leaveSection(); - - m_reporter->sectionEnded( SectionStats( info, assertions, _durationInSeconds, missingAssertions ) ); - m_messages.clear(); - } - - virtual void pushScopedMessage( MessageInfo const& message ) { - m_messages.push_back( message ); - } - - virtual void popScopedMessage( MessageInfo const& message ) { - m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); - } - - virtual std::string getCurrentTestName() const { - return m_activeTestCase - ? m_activeTestCase->getTestCaseInfo().name - : ""; - } - - virtual const AssertionResult* getLastResult() const { - return &m_lastResult; - } - - virtual void handleFatalErrorCondition( std::string const& message ) { - ResultBuilder resultBuilder = makeUnexpectedResultBuilder(); - resultBuilder.setResultType( ResultWas::FatalErrorCondition ); - resultBuilder << message; - resultBuilder.captureExpression(); - - handleUnfinishedSections(); - - // Recreate section for test case (as we will lose the one that was in scope) - TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); - SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); - - Counts assertions; - assertions.failed = 1; - SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); - m_reporter->sectionEnded( testCaseSectionStats ); - - TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); - - Totals deltaTotals; - deltaTotals.testCases.failed = 1; - m_reporter->testCaseEnded( TestCaseStats( testInfo, - deltaTotals, - "", - "", - false ) ); - m_totals.testCases.failed++; - testGroupEnded( "", m_totals, 1, 1 ); - m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); - } - - public: - // !TBD We need to do this another way! - bool aborting() const { - return m_totals.assertions.failed == static_cast( m_config->abortAfter() ); - } - - private: - - void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { - TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); - SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); - m_reporter->sectionStarting( testCaseSection ); - Counts prevAssertions = m_totals.assertions; - double duration = 0; - try { - m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal ); - TestCaseTracker::Guard guard( *m_testCaseTracker ); - - Timer timer; - timer.start(); - if( m_reporter->getPreferences().shouldRedirectStdOut ) { - StreamRedirect coutRedir( Catch::cout(), redirectedCout ); - StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); - invokeActiveTestCase(); - } - else { - invokeActiveTestCase(); - } - duration = timer.getElapsedSeconds(); - } - catch( TestFailureException& ) { - // This just means the test was aborted due to failure - } - catch(...) { - makeUnexpectedResultBuilder().useActiveException(); - } - handleUnfinishedSections(); - m_messages.clear(); - - Counts assertions = m_totals.assertions - prevAssertions; - bool missingAssertions = testForMissingAssertions( assertions ); - - if( testCaseInfo.okToFail() ) { - std::swap( assertions.failedButOk, assertions.failed ); - m_totals.assertions.failed -= assertions.failedButOk; - m_totals.assertions.failedButOk += assertions.failedButOk; - } - - SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); - m_reporter->sectionEnded( testCaseSectionStats ); - } - - void invokeActiveTestCase() { - FatalConditionHandler fatalConditionHandler; // Handle signals - m_activeTestCase->invoke(); - fatalConditionHandler.reset(); - } - - private: - - ResultBuilder makeUnexpectedResultBuilder() const { - return ResultBuilder( m_lastAssertionInfo.macroName.c_str(), - m_lastAssertionInfo.lineInfo, - m_lastAssertionInfo.capturedExpression.c_str(), - m_lastAssertionInfo.resultDisposition ); - } - - void handleUnfinishedSections() { - // If sections ended prematurely due to an exception we stored their - // infos here so we can tear them down outside the unwind process. - for( std::vector::const_reverse_iterator it = m_unfinishedSections.rbegin(), - itEnd = m_unfinishedSections.rend(); - it != itEnd; - ++it ) - sectionEnded( it->info, it->prevAssertions, it->durationInSeconds ); - m_unfinishedSections.clear(); - } - - struct UnfinishedSections { - UnfinishedSections( SectionInfo const& _info, Counts const& _prevAssertions, double _durationInSeconds ) - : info( _info ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds ) - {} - - SectionInfo info; - Counts prevAssertions; - double durationInSeconds; - }; - - TestRunInfo m_runInfo; - IMutableContext& m_context; - TestCase const* m_activeTestCase; - Option m_testCaseTracker; - AssertionResult m_lastResult; - - Ptr m_config; - Totals m_totals; - Ptr m_reporter; - std::vector m_messages; - IRunner* m_prevRunner; - IResultCapture* m_prevResultCapture; - Ptr m_prevConfig; - AssertionInfo m_lastAssertionInfo; - std::vector m_unfinishedSections; - }; - - IResultCapture& getResultCapture() { - if( IResultCapture* capture = getCurrentContext().getResultCapture() ) - return *capture; - else - throw std::logic_error( "No result capture instance" ); - } - -} // end namespace Catch - -// #included from: internal/catch_version.h -#define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED - -namespace Catch { - - // Versioning information - struct Version { - Version( unsigned int _majorVersion, - unsigned int _minorVersion, - unsigned int _patchNumber, - std::string const& _branchName, - unsigned int _buildNumber ); - - unsigned int const majorVersion; - unsigned int const minorVersion; - unsigned int const patchNumber; - - // buildNumber is only used if branchName is not null - std::string const branchName; - unsigned int const buildNumber; - - friend std::ostream& operator << ( std::ostream& os, Version const& version ); - - private: - void operator=( Version const& ); - }; - - extern Version libraryVersion; -} - -#include -#include -#include - -namespace Catch { - - class Runner { - - public: - Runner( Ptr const& config ) - : m_config( config ) - { - openStream(); - makeReporter(); - } - - Totals runTests() { - - RunContext context( m_config.get(), m_reporter ); - - Totals totals; - - context.testGroupStarting( "all tests", 1, 1 ); // deprecated? - - TestSpec testSpec = m_config->testSpec(); - if( !testSpec.hasFilters() ) - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests - - std::vector testCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, *m_config, testCases ); - - int testsRunForGroup = 0; - for( std::vector::const_iterator it = testCases.begin(), itEnd = testCases.end(); - it != itEnd; - ++it ) { - testsRunForGroup++; - if( m_testsAlreadyRun.find( *it ) == m_testsAlreadyRun.end() ) { - - if( context.aborting() ) - break; - - totals += context.runTest( *it ); - m_testsAlreadyRun.insert( *it ); - } - } - std::vector skippedTestCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, *m_config, skippedTestCases, true ); - - for( std::vector::const_iterator it = skippedTestCases.begin(), itEnd = skippedTestCases.end(); - it != itEnd; - ++it ) - m_reporter->skipTest( *it ); - - context.testGroupEnded( "all tests", totals, 1, 1 ); - return totals; - } - - private: - void openStream() { - // Open output file, if specified - if( !m_config->getFilename().empty() ) { - m_ofs.open( m_config->getFilename().c_str() ); - if( m_ofs.fail() ) { - std::ostringstream oss; - oss << "Unable to open file: '" << m_config->getFilename() << "'"; - throw std::domain_error( oss.str() ); - } - m_config->setStreamBuf( m_ofs.rdbuf() ); - } - } - void makeReporter() { - std::string reporterName = m_config->getReporterName().empty() - ? "console" - : m_config->getReporterName(); - - m_reporter = getRegistryHub().getReporterRegistry().create( reporterName, m_config.get() ); - if( !m_reporter ) { - std::ostringstream oss; - oss << "No reporter registered with name: '" << reporterName << "'"; - throw std::domain_error( oss.str() ); - } - } - - private: - Ptr m_config; - std::ofstream m_ofs; - Ptr m_reporter; - std::set m_testsAlreadyRun; - }; - - class Session : NonCopyable { - static bool alreadyInstantiated; - - public: - - struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; }; - - Session() - : m_cli( makeCommandLineParser() ) { - if( alreadyInstantiated ) { - std::string msg = "Only one instance of Catch::Session can ever be used"; - Catch::cerr() << msg << std::endl; - throw std::logic_error( msg ); - } - alreadyInstantiated = true; - } - ~Session() { - Catch::cleanUp(); - } - - void showHelp( std::string const& processName ) { - Catch::cout() << "\nCatch v" << libraryVersion << "\n"; - - m_cli.usage( Catch::cout(), processName ); - Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; - } - - int applyCommandLine( int argc, char* const argv[], OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) { - try { - m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail ); - m_unusedTokens = m_cli.parseInto( argc, argv, m_configData ); - if( m_configData.showHelp ) - showHelp( m_configData.processName ); - m_config.reset(); - } - catch( std::exception& ex ) { - { - Colour colourGuard( Colour::Red ); - Catch::cerr() - << "\nError(s) in input:\n" - << Text( ex.what(), TextAttributes().setIndent(2) ) - << "\n\n"; - } - m_cli.usage( Catch::cout(), m_configData.processName ); - return (std::numeric_limits::max)(); - } - return 0; - } - - void useConfigData( ConfigData const& _configData ) { - m_configData = _configData; - m_config.reset(); - } - - int run( int argc, char* const argv[] ) { - - int returnCode = applyCommandLine( argc, argv ); - if( returnCode == 0 ) - returnCode = run(); - return returnCode; - } - - int run() { - if( m_configData.showHelp ) - return 0; - - try - { - config(); // Force config to be constructed - - std::srand( m_configData.rngSeed ); - - Runner runner( m_config ); - - // Handle list request - if( Option listed = list( config() ) ) - return static_cast( *listed ); - - return static_cast( runner.runTests().assertions.failed ); - } - catch( std::exception& ex ) { - Catch::cerr() << ex.what() << std::endl; - return (std::numeric_limits::max)(); - } - } - - Clara::CommandLine const& cli() const { - return m_cli; - } - std::vector const& unusedTokens() const { - return m_unusedTokens; - } - ConfigData& configData() { - return m_configData; - } - Config& config() { - if( !m_config ) - m_config = new Config( m_configData ); - return *m_config; - } - - private: - Clara::CommandLine m_cli; - std::vector m_unusedTokens; - ConfigData m_configData; - Ptr m_config; - }; - - bool Session::alreadyInstantiated = false; - -} // end namespace Catch - -// #included from: catch_registry_hub.hpp -#define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED - -// #included from: catch_test_case_registry_impl.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED - -#include -#include -#include -#include -#include - -namespace Catch { - - class TestRegistry : public ITestCaseRegistry { - struct LexSort { - bool operator() (TestCase i,TestCase j) const { return (i const& getAllTests() const { - return m_functionsInOrder; - } - - virtual std::vector const& getAllNonHiddenTests() const { - return m_nonHiddenFunctions; - } - - virtual void getFilteredTests( TestSpec const& testSpec, IConfig const& config, std::vector& matchingTestCases, bool negated = false ) const { - - for( std::vector::const_iterator it = m_functionsInOrder.begin(), - itEnd = m_functionsInOrder.end(); - it != itEnd; - ++it ) { - bool includeTest = testSpec.matches( *it ) && ( config.allowThrows() || !it->throws() ); - if( includeTest != negated ) - matchingTestCases.push_back( *it ); - } - sortTests( config, matchingTestCases ); - } - - private: - - static void sortTests( IConfig const& config, std::vector& matchingTestCases ) { - - switch( config.runOrder() ) { - case RunTests::InLexicographicalOrder: - std::sort( matchingTestCases.begin(), matchingTestCases.end(), LexSort() ); - break; - case RunTests::InRandomOrder: - { - RandomNumberGenerator rng; - std::random_shuffle( matchingTestCases.begin(), matchingTestCases.end(), rng ); - } - break; - case RunTests::InDeclarationOrder: - // already in declaration order - break; - } - } - std::set m_functions; - std::vector m_functionsInOrder; - std::vector m_nonHiddenFunctions; - size_t m_unnamedCount; - }; - - /////////////////////////////////////////////////////////////////////////// - - class FreeFunctionTestCase : public SharedImpl { - public: - - FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {} - - virtual void invoke() const { - m_fun(); - } - - private: - virtual ~FreeFunctionTestCase(); - - TestFunction m_fun; - }; - - inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) { - std::string className = classOrQualifiedMethodName; - if( startsWith( className, "&" ) ) - { - std::size_t lastColons = className.rfind( "::" ); - std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); - if( penultimateColons == std::string::npos ) - penultimateColons = 1; - className = className.substr( penultimateColons, lastColons-penultimateColons ); - } - return className; - } - - /////////////////////////////////////////////////////////////////////////// - - AutoReg::AutoReg( TestFunction function, - SourceLineInfo const& lineInfo, - NameAndDesc const& nameAndDesc ) { - registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo ); - } - - AutoReg::~AutoReg() {} - - void AutoReg::registerTestCase( ITestCase* testCase, - char const* classOrQualifiedMethodName, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ) { - - getMutableRegistryHub().registerTest - ( makeTestCase( testCase, - extractClassName( classOrQualifiedMethodName ), - nameAndDesc.name, - nameAndDesc.description, - lineInfo ) ); - } - -} // end namespace Catch - -// #included from: catch_reporter_registry.hpp -#define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED - -#include - -namespace Catch { - - class ReporterRegistry : public IReporterRegistry { - - public: - - virtual ~ReporterRegistry() { - deleteAllValues( m_factories ); - } - - virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const { - FactoryMap::const_iterator it = m_factories.find( name ); - if( it == m_factories.end() ) - return NULL; - return it->second->create( ReporterConfig( config ) ); - } - - void registerReporter( std::string const& name, IReporterFactory* factory ) { - m_factories.insert( std::make_pair( name, factory ) ); - } - - FactoryMap const& getFactories() const { - return m_factories; - } - - private: - FactoryMap m_factories; - }; -} - -// #included from: catch_exception_translator_registry.hpp -#define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED - -#ifdef __OBJC__ -#import "Foundation/Foundation.h" -#endif - -namespace Catch { - - class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { - public: - ~ExceptionTranslatorRegistry() { - deleteAll( m_translators ); - } - - virtual void registerTranslator( const IExceptionTranslator* translator ) { - m_translators.push_back( translator ); - } - - virtual std::string translateActiveException() const { - try { -#ifdef __OBJC__ - // In Objective-C try objective-c exceptions first - @try { - throw; - } - @catch (NSException *exception) { - return Catch::toString( [exception description] ); - } -#else - throw; -#endif - } - catch( TestFailureException& ) { - throw; - } - catch( std::exception& ex ) { - return ex.what(); - } - catch( std::string& msg ) { - return msg; - } - catch( const char* msg ) { - return msg; - } - catch(...) { - return tryTranslators( m_translators.begin() ); - } - } - - std::string tryTranslators( std::vector::const_iterator it ) const { - if( it == m_translators.end() ) - return "Unknown exception"; - - try { - return (*it)->translate(); - } - catch(...) { - return tryTranslators( it+1 ); - } - } - - private: - std::vector m_translators; - }; -} - -namespace Catch { - - namespace { - - class RegistryHub : public IRegistryHub, public IMutableRegistryHub { - - RegistryHub( RegistryHub const& ); - void operator=( RegistryHub const& ); - - public: // IRegistryHub - RegistryHub() { - } - virtual IReporterRegistry const& getReporterRegistry() const { - return m_reporterRegistry; - } - virtual ITestCaseRegistry const& getTestCaseRegistry() const { - return m_testCaseRegistry; - } - virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() { - return m_exceptionTranslatorRegistry; - } - - public: // IMutableRegistryHub - virtual void registerReporter( std::string const& name, IReporterFactory* factory ) { - m_reporterRegistry.registerReporter( name, factory ); - } - virtual void registerTest( TestCase const& testInfo ) { - m_testCaseRegistry.registerTest( testInfo ); - } - virtual void registerTranslator( const IExceptionTranslator* translator ) { - m_exceptionTranslatorRegistry.registerTranslator( translator ); - } - - private: - TestRegistry m_testCaseRegistry; - ReporterRegistry m_reporterRegistry; - ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; - }; - - // Single, global, instance - inline RegistryHub*& getTheRegistryHub() { - static RegistryHub* theRegistryHub = NULL; - if( !theRegistryHub ) - theRegistryHub = new RegistryHub(); - return theRegistryHub; - } - } - - IRegistryHub& getRegistryHub() { - return *getTheRegistryHub(); - } - IMutableRegistryHub& getMutableRegistryHub() { - return *getTheRegistryHub(); - } - void cleanUp() { - delete getTheRegistryHub(); - getTheRegistryHub() = NULL; - cleanUpContext(); - } - std::string translateActiveException() { - return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); - } - -} // end namespace Catch - -// #included from: catch_notimplemented_exception.hpp -#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED - -#include - -namespace Catch { - - NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo ) - : m_lineInfo( lineInfo ) { - std::ostringstream oss; - oss << lineInfo << ": function "; - oss << "not implemented"; - m_what = oss.str(); - } - - const char* NotImplementedException::what() const CATCH_NOEXCEPT { - return m_what.c_str(); - } - -} // end namespace Catch - -// #included from: catch_context_impl.hpp -#define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED - -// #included from: catch_stream.hpp -#define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED - -// #included from: catch_streambuf.h -#define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED - -#include - -namespace Catch { - - class StreamBufBase : public std::streambuf { - public: - virtual ~StreamBufBase() CATCH_NOEXCEPT; - }; -} - -#include -#include -#include - -namespace Catch { - - template - class StreamBufImpl : public StreamBufBase { - char data[bufferSize]; - WriterF m_writer; - - public: - StreamBufImpl() { - setp( data, data + sizeof(data) ); - } - - ~StreamBufImpl() CATCH_NOEXCEPT { - sync(); - } - - private: - int overflow( int c ) { - sync(); - - if( c != EOF ) { - if( pbase() == epptr() ) - m_writer( std::string( 1, static_cast( c ) ) ); - else - sputc( static_cast( c ) ); - } - return 0; - } - - int sync() { - if( pbase() != pptr() ) { - m_writer( std::string( pbase(), static_cast( pptr() - pbase() ) ) ); - setp( pbase(), epptr() ); - } - return 0; - } - }; - - /////////////////////////////////////////////////////////////////////////// - - struct OutputDebugWriter { - - void operator()( std::string const&str ) { - writeToDebugConsole( str ); - } - }; - - Stream::Stream() - : streamBuf( NULL ), isOwned( false ) - {} - - Stream::Stream( std::streambuf* _streamBuf, bool _isOwned ) - : streamBuf( _streamBuf ), isOwned( _isOwned ) - {} - - void Stream::release() { - if( isOwned ) { - delete streamBuf; - streamBuf = NULL; - isOwned = false; - } - } - -#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement this functions - std::ostream& cout() { - return std::cout; - } - std::ostream& cerr() { - return std::cerr; - } -#endif -} - -namespace Catch { - - class Context : public IMutableContext { - - Context() : m_config( NULL ), m_runner( NULL ), m_resultCapture( NULL ) {} - Context( Context const& ); - void operator=( Context const& ); - - public: // IContext - virtual IResultCapture* getResultCapture() { - return m_resultCapture; - } - virtual IRunner* getRunner() { - return m_runner; - } - virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) { - return getGeneratorsForCurrentTest() - .getGeneratorInfo( fileInfo, totalSize ) - .getCurrentIndex(); - } - virtual bool advanceGeneratorsForCurrentTest() { - IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); - return generators && generators->moveNext(); - } - - virtual Ptr getConfig() const { - return m_config; - } - - public: // IMutableContext - virtual void setResultCapture( IResultCapture* resultCapture ) { - m_resultCapture = resultCapture; - } - virtual void setRunner( IRunner* runner ) { - m_runner = runner; - } - virtual void setConfig( Ptr const& config ) { - m_config = config; - } - - friend IMutableContext& getCurrentMutableContext(); - - private: - IGeneratorsForTest* findGeneratorsForCurrentTest() { - std::string testName = getResultCapture()->getCurrentTestName(); - - std::map::const_iterator it = - m_generatorsByTestName.find( testName ); - return it != m_generatorsByTestName.end() - ? it->second - : NULL; - } - - IGeneratorsForTest& getGeneratorsForCurrentTest() { - IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); - if( !generators ) { - std::string testName = getResultCapture()->getCurrentTestName(); - generators = createGeneratorsForTest(); - m_generatorsByTestName.insert( std::make_pair( testName, generators ) ); - } - return *generators; - } - - private: - Ptr m_config; - IRunner* m_runner; - IResultCapture* m_resultCapture; - std::map m_generatorsByTestName; - }; - - namespace { - Context* currentContext = NULL; - } - IMutableContext& getCurrentMutableContext() { - if( !currentContext ) - currentContext = new Context(); - return *currentContext; - } - IContext& getCurrentContext() { - return getCurrentMutableContext(); - } - - Stream createStream( std::string const& streamName ) { - if( streamName == "stdout" ) return Stream( Catch::cout().rdbuf(), false ); - if( streamName == "stderr" ) return Stream( Catch::cerr().rdbuf(), false ); - if( streamName == "debug" ) return Stream( new StreamBufImpl, true ); - - throw std::domain_error( "Unknown stream: " + streamName ); - } - - void cleanUpContext() { - delete currentContext; - currentContext = NULL; - } -} - -// #included from: catch_console_colour_impl.hpp -#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED - -namespace Catch { - namespace { - - struct IColourImpl { - virtual ~IColourImpl() {} - virtual void use( Colour::Code _colourCode ) = 0; - }; - - struct NoColourImpl : IColourImpl { - void use( Colour::Code ) {} - - static IColourImpl* instance() { - static NoColourImpl s_instance; - return &s_instance; - } - }; - - } // anon namespace -} // namespace Catch - -#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) -# ifdef CATCH_PLATFORM_WINDOWS -# define CATCH_CONFIG_COLOUR_WINDOWS -# else -# define CATCH_CONFIG_COLOUR_ANSI -# endif -#endif - -#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// - -#ifndef NOMINMAX -#define NOMINMAX -#endif - -#ifdef __AFXDLL -#include -#else -#include -#endif - -namespace Catch { -namespace { - - class Win32ColourImpl : public IColourImpl { - public: - Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) - { - CONSOLE_SCREEN_BUFFER_INFO csbiInfo; - GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); - originalAttributes = csbiInfo.wAttributes; - } - - virtual void use( Colour::Code _colourCode ) { - switch( _colourCode ) { - case Colour::None: return setTextAttribute( originalAttributes ); - case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); - case Colour::Red: return setTextAttribute( FOREGROUND_RED ); - case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); - case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); - case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); - case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); - case Colour::Grey: return setTextAttribute( 0 ); - - case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); - case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); - case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); - case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); - - case Colour::Bright: throw std::logic_error( "not a colour" ); - } - } - - private: - void setTextAttribute( WORD _textAttribute ) { - SetConsoleTextAttribute( stdoutHandle, _textAttribute ); - } - HANDLE stdoutHandle; - WORD originalAttributes; - }; - - IColourImpl* platformColourInstance() { - static Win32ColourImpl s_instance; - return &s_instance; - } - -} // end anon namespace -} // end namespace Catch - -#elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// - -#include - -namespace Catch { -namespace { - - // use POSIX/ ANSI console terminal codes - // Thanks to Adam Strzelecki for original contribution - // (http://github.com/nanoant) - // https://github.com/philsquared/Catch/pull/131 - class PosixColourImpl : public IColourImpl { - public: - virtual void use( Colour::Code _colourCode ) { - switch( _colourCode ) { - case Colour::None: - case Colour::White: return setColour( "[0m" ); - case Colour::Red: return setColour( "[0;31m" ); - case Colour::Green: return setColour( "[0;32m" ); - case Colour::Blue: return setColour( "[0:34m" ); - case Colour::Cyan: return setColour( "[0;36m" ); - case Colour::Yellow: return setColour( "[0;33m" ); - case Colour::Grey: return setColour( "[1;30m" ); - - case Colour::LightGrey: return setColour( "[0;37m" ); - case Colour::BrightRed: return setColour( "[1;31m" ); - case Colour::BrightGreen: return setColour( "[1;32m" ); - case Colour::BrightWhite: return setColour( "[1;37m" ); - - case Colour::Bright: throw std::logic_error( "not a colour" ); - } - } - static IColourImpl* instance() { - static PosixColourImpl s_instance; - return &s_instance; - } - - private: - void setColour( const char* _escapeCode ) { - Catch::cout() << '\033' << _escapeCode; - } - }; - - IColourImpl* platformColourInstance() { - Ptr config = getCurrentContext().getConfig(); - return (config && config->forceColour()) || isatty(STDOUT_FILENO) - ? PosixColourImpl::instance() - : NoColourImpl::instance(); - } - -} // end anon namespace -} // end namespace Catch - -#else // not Windows or ANSI /////////////////////////////////////////////// - -namespace Catch { - - static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } - -} // end namespace Catch - -#endif // Windows/ ANSI/ None - -namespace Catch { - - Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); } - Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast( _other ).m_moved = true; } - Colour::~Colour(){ if( !m_moved ) use( None ); } - - void Colour::use( Code _colourCode ) { - static IColourImpl* impl = isDebuggerActive() - ? NoColourImpl::instance() - : platformColourInstance(); - impl->use( _colourCode ); - } - -} // end namespace Catch - -// #included from: catch_generators_impl.hpp -#define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { - - struct GeneratorInfo : IGeneratorInfo { - - GeneratorInfo( std::size_t size ) - : m_size( size ), - m_currentIndex( 0 ) - {} - - bool moveNext() { - if( ++m_currentIndex == m_size ) { - m_currentIndex = 0; - return false; - } - return true; - } - - std::size_t getCurrentIndex() const { - return m_currentIndex; - } - - std::size_t m_size; - std::size_t m_currentIndex; - }; - - /////////////////////////////////////////////////////////////////////////// - - class GeneratorsForTest : public IGeneratorsForTest { - - public: - ~GeneratorsForTest() { - deleteAll( m_generatorsInOrder ); - } - - IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) { - std::map::const_iterator it = m_generatorsByName.find( fileInfo ); - if( it == m_generatorsByName.end() ) { - IGeneratorInfo* info = new GeneratorInfo( size ); - m_generatorsByName.insert( std::make_pair( fileInfo, info ) ); - m_generatorsInOrder.push_back( info ); - return *info; - } - return *it->second; - } - - bool moveNext() { - std::vector::const_iterator it = m_generatorsInOrder.begin(); - std::vector::const_iterator itEnd = m_generatorsInOrder.end(); - for(; it != itEnd; ++it ) { - if( (*it)->moveNext() ) - return true; - } - return false; - } - - private: - std::map m_generatorsByName; - std::vector m_generatorsInOrder; - }; - - IGeneratorsForTest* createGeneratorsForTest() - { - return new GeneratorsForTest(); - } - -} // end namespace Catch - -// #included from: catch_assertionresult.hpp -#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED - -namespace Catch { - - AssertionInfo::AssertionInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - std::string const& _capturedExpression, - ResultDisposition::Flags _resultDisposition ) - : macroName( _macroName ), - lineInfo( _lineInfo ), - capturedExpression( _capturedExpression ), - resultDisposition( _resultDisposition ) - {} - - AssertionResult::AssertionResult() {} - - AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) - : m_info( info ), - m_resultData( data ) - {} - - AssertionResult::~AssertionResult() {} - - // Result was a success - bool AssertionResult::succeeded() const { - return Catch::isOk( m_resultData.resultType ); - } - - // Result was a success, or failure is suppressed - bool AssertionResult::isOk() const { - return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); - } - - ResultWas::OfType AssertionResult::getResultType() const { - return m_resultData.resultType; - } - - bool AssertionResult::hasExpression() const { - return !m_info.capturedExpression.empty(); - } - - bool AssertionResult::hasMessage() const { - return !m_resultData.message.empty(); - } - - std::string AssertionResult::getExpression() const { - if( isFalseTest( m_info.resultDisposition ) ) - return "!" + m_info.capturedExpression; - else - return m_info.capturedExpression; - } - std::string AssertionResult::getExpressionInMacro() const { - if( m_info.macroName.empty() ) - return m_info.capturedExpression; - else - return m_info.macroName + "( " + m_info.capturedExpression + " )"; - } - - bool AssertionResult::hasExpandedExpression() const { - return hasExpression() && getExpandedExpression() != getExpression(); - } - - std::string AssertionResult::getExpandedExpression() const { - return m_resultData.reconstructedExpression; - } - - std::string AssertionResult::getMessage() const { - return m_resultData.message; - } - SourceLineInfo AssertionResult::getSourceInfo() const { - return m_info.lineInfo; - } - - std::string AssertionResult::getTestMacroName() const { - return m_info.macroName; - } - -} // end namespace Catch - -// #included from: catch_test_case_info.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED - -namespace Catch { - - inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { - if( startsWith( tag, "." ) || - tag == "hide" || - tag == "!hide" ) - return TestCaseInfo::IsHidden; - else if( tag == "!throws" ) - return TestCaseInfo::Throws; - else if( tag == "!shouldfail" ) - return TestCaseInfo::ShouldFail; - else if( tag == "!mayfail" ) - return TestCaseInfo::MayFail; - else - return TestCaseInfo::None; - } - inline bool isReservedTag( std::string const& tag ) { - return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] ); - } - inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { - if( isReservedTag( tag ) ) { - { - Colour colourGuard( Colour::Red ); - Catch::cerr() - << "Tag name [" << tag << "] not allowed.\n" - << "Tag names starting with non alpha-numeric characters are reserved\n"; - } - { - Colour colourGuard( Colour::FileName ); - Catch::cerr() << _lineInfo << std::endl; - } - exit(1); - } - } - - TestCase makeTestCase( ITestCase* _testCase, - std::string const& _className, - std::string const& _name, - std::string const& _descOrTags, - SourceLineInfo const& _lineInfo ) - { - bool isHidden( startsWith( _name, "./" ) ); // Legacy support - - // Parse out tags - std::set tags; - std::string desc, tag; - bool inTag = false; - for( std::size_t i = 0; i < _descOrTags.size(); ++i ) { - char c = _descOrTags[i]; - if( !inTag ) { - if( c == '[' ) - inTag = true; - else - desc += c; - } - else { - if( c == ']' ) { - TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); - if( prop == TestCaseInfo::IsHidden ) - isHidden = true; - else if( prop == TestCaseInfo::None ) - enforceNotReservedTag( tag, _lineInfo ); - - tags.insert( tag ); - tag.clear(); - inTag = false; - } - else - tag += c; - } - } - if( isHidden ) { - tags.insert( "hide" ); - tags.insert( "." ); - } - - TestCaseInfo info( _name, _className, desc, tags, _lineInfo ); - return TestCase( _testCase, info ); - } - - TestCaseInfo::TestCaseInfo( std::string const& _name, - std::string const& _className, - std::string const& _description, - std::set const& _tags, - SourceLineInfo const& _lineInfo ) - : name( _name ), - className( _className ), - description( _description ), - tags( _tags ), - lineInfo( _lineInfo ), - properties( None ) - { - std::ostringstream oss; - for( std::set::const_iterator it = _tags.begin(), itEnd = _tags.end(); it != itEnd; ++it ) { - oss << "[" << *it << "]"; - std::string lcaseTag = toLower( *it ); - properties = static_cast( properties | parseSpecialTag( lcaseTag ) ); - lcaseTags.insert( lcaseTag ); - } - tagsAsString = oss.str(); - } - - TestCaseInfo::TestCaseInfo( TestCaseInfo const& other ) - : name( other.name ), - className( other.className ), - description( other.description ), - tags( other.tags ), - lcaseTags( other.lcaseTags ), - tagsAsString( other.tagsAsString ), - lineInfo( other.lineInfo ), - properties( other.properties ) - {} - - bool TestCaseInfo::isHidden() const { - return ( properties & IsHidden ) != 0; - } - bool TestCaseInfo::throws() const { - return ( properties & Throws ) != 0; - } - bool TestCaseInfo::okToFail() const { - return ( properties & (ShouldFail | MayFail ) ) != 0; - } - bool TestCaseInfo::expectedToFail() const { - return ( properties & (ShouldFail ) ) != 0; - } - - TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {} - - TestCase::TestCase( TestCase const& other ) - : TestCaseInfo( other ), - test( other.test ) - {} - - TestCase TestCase::withName( std::string const& _newName ) const { - TestCase other( *this ); - other.name = _newName; - return other; - } - - void TestCase::swap( TestCase& other ) { - test.swap( other.test ); - name.swap( other.name ); - className.swap( other.className ); - description.swap( other.description ); - tags.swap( other.tags ); - lcaseTags.swap( other.lcaseTags ); - tagsAsString.swap( other.tagsAsString ); - std::swap( TestCaseInfo::properties, static_cast( other ).properties ); - std::swap( lineInfo, other.lineInfo ); - } - - void TestCase::invoke() const { - test->invoke(); - } - - bool TestCase::operator == ( TestCase const& other ) const { - return test.get() == other.test.get() && - name == other.name && - className == other.className; - } - - bool TestCase::operator < ( TestCase const& other ) const { - return name < other.name; - } - TestCase& TestCase::operator = ( TestCase const& other ) { - TestCase temp( other ); - swap( temp ); - return *this; - } - - TestCaseInfo const& TestCase::getTestCaseInfo() const - { - return *this; - } - -} // end namespace Catch - -// #included from: catch_version.hpp -#define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED - -namespace Catch { - - Version::Version - ( unsigned int _majorVersion, - unsigned int _minorVersion, - unsigned int _patchNumber, - std::string const& _branchName, - unsigned int _buildNumber ) - : majorVersion( _majorVersion ), - minorVersion( _minorVersion ), - patchNumber( _patchNumber ), - branchName( _branchName ), - buildNumber( _buildNumber ) - {} - - std::ostream& operator << ( std::ostream& os, Version const& version ) { - os << version.majorVersion << "." - << version.minorVersion << "." - << version.patchNumber; - - if( !version.branchName.empty() ) { - os << "-" << version.branchName - << "." << version.buildNumber; - } - return os; - } - - Version libraryVersion( 1, 2, 1, "", 0 ); - -} - -// #included from: catch_message.hpp -#define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED - -namespace Catch { - - MessageInfo::MessageInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - ResultWas::OfType _type ) - : macroName( _macroName ), - lineInfo( _lineInfo ), - type( _type ), - sequence( ++globalCount ) - {} - - // This may need protecting if threading support is added - unsigned int MessageInfo::globalCount = 0; - - //////////////////////////////////////////////////////////////////////////// - - ScopedMessage::ScopedMessage( MessageBuilder const& builder ) - : m_info( builder.m_info ) - { - m_info.message = builder.m_stream.str(); - getResultCapture().pushScopedMessage( m_info ); - } - ScopedMessage::ScopedMessage( ScopedMessage const& other ) - : m_info( other.m_info ) - {} - - ScopedMessage::~ScopedMessage() { - getResultCapture().popScopedMessage( m_info ); - } - -} // end namespace Catch - -// #included from: catch_legacy_reporter_adapter.hpp -#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED - -// #included from: catch_legacy_reporter_adapter.h -#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED - -namespace Catch -{ - // Deprecated - struct IReporter : IShared { - virtual ~IReporter(); - - virtual bool shouldRedirectStdout() const = 0; - - virtual void StartTesting() = 0; - virtual void EndTesting( Totals const& totals ) = 0; - virtual void StartGroup( std::string const& groupName ) = 0; - virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0; - virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0; - virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0; - virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0; - virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0; - virtual void NoAssertionsInSection( std::string const& sectionName ) = 0; - virtual void NoAssertionsInTestCase( std::string const& testName ) = 0; - virtual void Aborted() = 0; - virtual void Result( AssertionResult const& result ) = 0; - }; - - class LegacyReporterAdapter : public SharedImpl - { - public: - LegacyReporterAdapter( Ptr const& legacyReporter ); - virtual ~LegacyReporterAdapter(); - - virtual ReporterPreferences getPreferences() const; - virtual void noMatchingTestCases( std::string const& ); - virtual void testRunStarting( TestRunInfo const& ); - virtual void testGroupStarting( GroupInfo const& groupInfo ); - virtual void testCaseStarting( TestCaseInfo const& testInfo ); - virtual void sectionStarting( SectionInfo const& sectionInfo ); - virtual void assertionStarting( AssertionInfo const& ); - virtual bool assertionEnded( AssertionStats const& assertionStats ); - virtual void sectionEnded( SectionStats const& sectionStats ); - virtual void testCaseEnded( TestCaseStats const& testCaseStats ); - virtual void testGroupEnded( TestGroupStats const& testGroupStats ); - virtual void testRunEnded( TestRunStats const& testRunStats ); - virtual void skipTest( TestCaseInfo const& ); - - private: - Ptr m_legacyReporter; - }; -} - -namespace Catch -{ - LegacyReporterAdapter::LegacyReporterAdapter( Ptr const& legacyReporter ) - : m_legacyReporter( legacyReporter ) - {} - LegacyReporterAdapter::~LegacyReporterAdapter() {} - - ReporterPreferences LegacyReporterAdapter::getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout(); - return prefs; - } - - void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {} - void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) { - m_legacyReporter->StartTesting(); - } - void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) { - m_legacyReporter->StartGroup( groupInfo.name ); - } - void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) { - m_legacyReporter->StartTestCase( testInfo ); - } - void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) { - m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description ); - } - void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) { - // Not on legacy interface - } - - bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) { - if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { - for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); - it != itEnd; - ++it ) { - if( it->type == ResultWas::Info ) { - ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal ); - rb << it->message; - rb.setResultType( ResultWas::Info ); - AssertionResult result = rb.build(); - m_legacyReporter->Result( result ); - } - } - } - m_legacyReporter->Result( assertionStats.assertionResult ); - return true; - } - void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) { - if( sectionStats.missingAssertions ) - m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name ); - m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions ); - } - void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) { - m_legacyReporter->EndTestCase - ( testCaseStats.testInfo, - testCaseStats.totals, - testCaseStats.stdOut, - testCaseStats.stdErr ); - } - void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) { - if( testGroupStats.aborting ) - m_legacyReporter->Aborted(); - m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals ); - } - void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) { - m_legacyReporter->EndTesting( testRunStats.totals ); - } - void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) { - } -} - -// #included from: catch_timer.hpp - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wc++11-long-long" -#endif - -#ifdef CATCH_PLATFORM_WINDOWS -#include -#else -#include -#endif - -namespace Catch { - - namespace { -#ifdef CATCH_PLATFORM_WINDOWS - uint64_t getCurrentTicks() { - static uint64_t hz=0, hzo=0; - if (!hz) { - QueryPerformanceFrequency( reinterpret_cast( &hz ) ); - QueryPerformanceCounter( reinterpret_cast( &hzo ) ); - } - uint64_t t; - QueryPerformanceCounter( reinterpret_cast( &t ) ); - return ((t-hzo)*1000000)/hz; - } -#else - uint64_t getCurrentTicks() { - timeval t; - gettimeofday(&t,NULL); - return static_cast( t.tv_sec ) * 1000000ull + static_cast( t.tv_usec ); - } -#endif - } - - void Timer::start() { - m_ticks = getCurrentTicks(); - } - unsigned int Timer::getElapsedMicroseconds() const { - return static_cast(getCurrentTicks() - m_ticks); - } - unsigned int Timer::getElapsedMilliseconds() const { - return static_cast(getElapsedMicroseconds()/1000); - } - double Timer::getElapsedSeconds() const { - return getElapsedMicroseconds()/1000000.0; - } - -} // namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif -// #included from: catch_common.hpp -#define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED - -namespace Catch { - - bool startsWith( std::string const& s, std::string const& prefix ) { - return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix; - } - bool endsWith( std::string const& s, std::string const& suffix ) { - return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix; - } - bool contains( std::string const& s, std::string const& infix ) { - return s.find( infix ) != std::string::npos; - } - void toLowerInPlace( std::string& s ) { - std::transform( s.begin(), s.end(), s.begin(), ::tolower ); - } - std::string toLower( std::string const& s ) { - std::string lc = s; - toLowerInPlace( lc ); - return lc; - } - std::string trim( std::string const& str ) { - static char const* whitespaceChars = "\n\r\t "; - std::string::size_type start = str.find_first_not_of( whitespaceChars ); - std::string::size_type end = str.find_last_not_of( whitespaceChars ); - - return start != std::string::npos ? str.substr( start, 1+end-start ) : ""; - } - - bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { - bool replaced = false; - std::size_t i = str.find( replaceThis ); - while( i != std::string::npos ) { - replaced = true; - str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); - if( i < str.size()-withThis.size() ) - i = str.find( replaceThis, i+withThis.size() ); - else - i = std::string::npos; - } - return replaced; - } - - pluralise::pluralise( std::size_t count, std::string const& label ) - : m_count( count ), - m_label( label ) - {} - - std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { - os << pluraliser.m_count << " " << pluraliser.m_label; - if( pluraliser.m_count != 1 ) - os << "s"; - return os; - } - - SourceLineInfo::SourceLineInfo() : line( 0 ){} - SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) - : file( _file ), - line( _line ) - {} - SourceLineInfo::SourceLineInfo( SourceLineInfo const& other ) - : file( other.file ), - line( other.line ) - {} - bool SourceLineInfo::empty() const { - return file.empty(); - } - bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const { - return line == other.line && file == other.file; - } - bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const { - return line < other.line || ( line == other.line && file < other.file ); - } - - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { -#ifndef __GNUG__ - os << info.file << "(" << info.line << ")"; -#else - os << info.file << ":" << info.line; -#endif - return os; - } - - void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) { - std::ostringstream oss; - oss << locationInfo << ": Internal Catch error: '" << message << "'"; - if( alwaysTrue() ) - throw std::logic_error( oss.str() ); - } -} - -// #included from: catch_section.hpp -#define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED - -namespace Catch { - - SectionInfo::SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name, - std::string const& _description ) - : name( _name ), - description( _description ), - lineInfo( _lineInfo ) - {} - - Section::Section( SectionInfo const& info ) - : m_info( info ), - m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) - { - m_timer.start(); - } - - Section::~Section() { - if( m_sectionIncluded ) - getResultCapture().sectionEnded( m_info, m_assertions, m_timer.getElapsedSeconds() ); - } - - // This indicates whether the section should be executed or not - Section::operator bool() const { - return m_sectionIncluded; - } - -} // end namespace Catch - -// #included from: catch_debugger.hpp -#define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED - -#include - -#ifdef CATCH_PLATFORM_MAC - - #include - #include - #include - #include - #include - - namespace Catch{ - - // The following function is taken directly from the following technical note: - // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html - - // Returns true if the current process is being debugged (either - // running under the debugger or has a debugger attached post facto). - bool isDebuggerActive(){ - - int mib[4]; - struct kinfo_proc info; - size_t size; - - // Initialize the flags so that, if sysctl fails for some bizarre - // reason, we get a predictable result. - - info.kp_proc.p_flag = 0; - - // Initialize mib, which tells sysctl the info we want, in this case - // we're looking for information about a specific process ID. - - mib[0] = CTL_KERN; - mib[1] = KERN_PROC; - mib[2] = KERN_PROC_PID; - mib[3] = getpid(); - - // Call sysctl. - - size = sizeof(info); - if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0) != 0 ) { - Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; - return false; - } - - // We're being debugged if the P_TRACED flag is set. - - return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); - } - } // namespace Catch - -#elif defined(_MSC_VER) - extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); - namespace Catch { - bool isDebuggerActive() { - return IsDebuggerPresent() != 0; - } - } -#elif defined(__MINGW32__) - extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); - namespace Catch { - bool isDebuggerActive() { - return IsDebuggerPresent() != 0; - } - } -#else - namespace Catch { - inline bool isDebuggerActive() { return false; } - } -#endif // Platform - -#ifdef CATCH_PLATFORM_WINDOWS - extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* ); - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - ::OutputDebugStringA( text.c_str() ); - } - } -#else - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - // !TBD: Need a version for Mac/ XCode and other IDEs - Catch::cout() << text; - } - } -#endif // Platform - -// #included from: catch_tostring.hpp -#define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED - -namespace Catch { - -namespace Detail { - - std::string unprintableString = "{?}"; - - namespace { - struct Endianness { - enum Arch { Big, Little }; - - static Arch which() { - union _{ - int asInt; - char asChar[sizeof (int)]; - } u; - - u.asInt = 1; - return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; - } - }; - } - - std::string rawMemoryToString( const void *object, std::size_t size ) - { - // Reverse order for little endian architectures - int i = 0, end = static_cast( size ), inc = 1; - if( Endianness::which() == Endianness::Little ) { - i = end-1; - end = inc = -1; - } - - unsigned char const *bytes = static_cast(object); - std::ostringstream os; - os << "0x" << std::setfill('0') << std::hex; - for( ; i != end; i += inc ) - os << std::setw(2) << static_cast(bytes[i]); - return os.str(); - } -} - -std::string toString( std::string const& value ) { - std::string s = value; - if( getCurrentContext().getConfig()->showInvisibles() ) { - for(size_t i = 0; i < s.size(); ++i ) { - std::string subs; - switch( s[i] ) { - case '\n': subs = "\\n"; break; - case '\t': subs = "\\t"; break; - default: break; - } - if( !subs.empty() ) { - s = s.substr( 0, i ) + subs + s.substr( i+1 ); - ++i; - } - } - } - return "\"" + s + "\""; -} -std::string toString( std::wstring const& value ) { - - std::string s; - s.reserve( value.size() ); - for(size_t i = 0; i < value.size(); ++i ) - s += value[i] <= 0xff ? static_cast( value[i] ) : '?'; - return Catch::toString( s ); -} - -std::string toString( const char* const value ) { - return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" ); -} - -std::string toString( char* const value ) { - return Catch::toString( static_cast( value ) ); -} - -std::string toString( const wchar_t* const value ) -{ - return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" ); -} - -std::string toString( wchar_t* const value ) -{ - return Catch::toString( static_cast( value ) ); -} - -std::string toString( int value ) { - std::ostringstream oss; - oss << value; - if( value >= 255 ) - oss << " (0x" << std::hex << value << ")"; - return oss.str(); -} - -std::string toString( unsigned long value ) { - std::ostringstream oss; - oss << value; - if( value >= 255 ) - oss << " (0x" << std::hex << value << ")"; - return oss.str(); -} - -std::string toString( unsigned int value ) { - return Catch::toString( static_cast( value ) ); -} - -template -std::string fpToString( T value, int precision ) { - std::ostringstream oss; - oss << std::setprecision( precision ) - << std::fixed - << value; - std::string d = oss.str(); - std::size_t i = d.find_last_not_of( '0' ); - if( i != std::string::npos && i != d.size()-1 ) { - if( d[i] == '.' ) - i++; - d = d.substr( 0, i+1 ); - } - return d; -} - -std::string toString( const double value ) { - return fpToString( value, 10 ); -} -std::string toString( const float value ) { - return fpToString( value, 5 ) + "f"; -} - -std::string toString( bool value ) { - return value ? "true" : "false"; -} - -std::string toString( char value ) { - return value < ' ' - ? toString( static_cast( value ) ) - : Detail::makeString( value ); -} - -std::string toString( signed char value ) { - return toString( static_cast( value ) ); -} - -std::string toString( unsigned char value ) { - return toString( static_cast( value ) ); -} - -#ifdef CATCH_CONFIG_CPP11_NULLPTR -std::string toString( std::nullptr_t ) { - return "nullptr"; -} -#endif - -#ifdef __OBJC__ - std::string toString( NSString const * const& nsstring ) { - if( !nsstring ) - return "nil"; - return "@" + toString([nsstring UTF8String]); - } - std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) { - if( !nsstring ) - return "nil"; - return "@" + toString([nsstring UTF8String]); - } - std::string toString( NSObject* const& nsObject ) { - return toString( [nsObject description] ); - } -#endif - -} // end namespace Catch - -// #included from: catch_result_builder.hpp -#define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED - -namespace Catch { - - ResultBuilder::ResultBuilder( char const* macroName, - SourceLineInfo const& lineInfo, - char const* capturedExpression, - ResultDisposition::Flags resultDisposition ) - : m_assertionInfo( macroName, lineInfo, capturedExpression, resultDisposition ), - m_shouldDebugBreak( false ), - m_shouldThrow( false ) - {} - - ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) { - m_data.resultType = result; - return *this; - } - ResultBuilder& ResultBuilder::setResultType( bool result ) { - m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; - return *this; - } - ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) { - m_exprComponents.lhs = lhs; - return *this; - } - ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) { - m_exprComponents.rhs = rhs; - return *this; - } - ResultBuilder& ResultBuilder::setOp( std::string const& op ) { - m_exprComponents.op = op; - return *this; - } - - void ResultBuilder::endExpression() { - m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition ); - captureExpression(); - } - - void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { - m_assertionInfo.resultDisposition = resultDisposition; - m_stream.oss << Catch::translateActiveException(); - captureResult( ResultWas::ThrewException ); - } - - void ResultBuilder::captureResult( ResultWas::OfType resultType ) { - setResultType( resultType ); - captureExpression(); - } - - void ResultBuilder::captureExpression() { - AssertionResult result = build(); - getResultCapture().assertionEnded( result ); - - if( !result.isOk() ) { - if( getCurrentContext().getConfig()->shouldDebugBreak() ) - m_shouldDebugBreak = true; - if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) ) - m_shouldThrow = true; - } - } - void ResultBuilder::react() { - if( m_shouldThrow ) - throw Catch::TestFailureException(); - } - - bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; } - bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); } - - AssertionResult ResultBuilder::build() const - { - assert( m_data.resultType != ResultWas::Unknown ); - - AssertionResultData data = m_data; - - // Flip bool results if testFalse is set - if( m_exprComponents.testFalse ) { - if( data.resultType == ResultWas::Ok ) - data.resultType = ResultWas::ExpressionFailed; - else if( data.resultType == ResultWas::ExpressionFailed ) - data.resultType = ResultWas::Ok; - } - - data.message = m_stream.oss.str(); - data.reconstructedExpression = reconstructExpression(); - if( m_exprComponents.testFalse ) { - if( m_exprComponents.op == "" ) - data.reconstructedExpression = "!" + data.reconstructedExpression; - else - data.reconstructedExpression = "!(" + data.reconstructedExpression + ")"; - } - return AssertionResult( m_assertionInfo, data ); - } - std::string ResultBuilder::reconstructExpression() const { - if( m_exprComponents.op == "" ) - return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs; - else if( m_exprComponents.op == "matches" ) - return m_exprComponents.lhs + " " + m_exprComponents.rhs; - else if( m_exprComponents.op != "!" ) { - if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 && - m_exprComponents.lhs.find("\n") == std::string::npos && - m_exprComponents.rhs.find("\n") == std::string::npos ) - return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs; - else - return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs; - } - else - return "{can't expand - use " + m_assertionInfo.macroName + "_FALSE( " + m_assertionInfo.capturedExpression.substr(1) + " ) instead of " + m_assertionInfo.macroName + "( " + m_assertionInfo.capturedExpression + " ) for better diagnostics}"; - } - -} // end namespace Catch - -// #included from: catch_tag_alias_registry.hpp -#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED - -// #included from: catch_tag_alias_registry.h -#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED - -#include - -namespace Catch { - - class TagAliasRegistry : public ITagAliasRegistry { - public: - virtual ~TagAliasRegistry(); - virtual Option find( std::string const& alias ) const; - virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; - void add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); - static TagAliasRegistry& get(); - - private: - std::map m_registry; - }; - -} // end namespace Catch - -#include -#include - -namespace Catch { - - TagAliasRegistry::~TagAliasRegistry() {} - - Option TagAliasRegistry::find( std::string const& alias ) const { - std::map::const_iterator it = m_registry.find( alias ); - if( it != m_registry.end() ) - return it->second; - else - return Option(); - } - - std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { - std::string expandedTestSpec = unexpandedTestSpec; - for( std::map::const_iterator it = m_registry.begin(), itEnd = m_registry.end(); - it != itEnd; - ++it ) { - std::size_t pos = expandedTestSpec.find( it->first ); - if( pos != std::string::npos ) { - expandedTestSpec = expandedTestSpec.substr( 0, pos ) + - it->second.tag + - expandedTestSpec.substr( pos + it->first.size() ); - } - } - return expandedTestSpec; - } - - void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { - - if( !startsWith( alias, "[@" ) || !endsWith( alias, "]" ) ) { - std::ostringstream oss; - oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo; - throw std::domain_error( oss.str().c_str() ); - } - if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { - std::ostringstream oss; - oss << "error: tag alias, \"" << alias << "\" already registered.\n" - << "\tFirst seen at " << find(alias)->lineInfo << "\n" - << "\tRedefined at " << lineInfo; - throw std::domain_error( oss.str().c_str() ); - } - } - - TagAliasRegistry& TagAliasRegistry::get() { - static TagAliasRegistry instance; - return instance; - - } - - ITagAliasRegistry::~ITagAliasRegistry() {} - ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); } - - RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { - try { - TagAliasRegistry::get().add( alias, tag, lineInfo ); - } - catch( std::exception& ex ) { - Colour colourGuard( Colour::Red ); - Catch::cerr() << ex.what() << std::endl; - exit(1); - } - } - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_xml.hpp -#define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED - -// #included from: catch_reporter_bases.hpp -#define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED - -#include - -namespace Catch { - - struct StreamingReporterBase : SharedImpl { - - StreamingReporterBase( ReporterConfig const& _config ) - : m_config( _config.fullConfig() ), - stream( _config.stream() ) - {} - - virtual ~StreamingReporterBase(); - - virtual void noMatchingTestCases( std::string const& ) {} - - virtual void testRunStarting( TestRunInfo const& _testRunInfo ) { - currentTestRunInfo = _testRunInfo; - } - virtual void testGroupStarting( GroupInfo const& _groupInfo ) { - currentGroupInfo = _groupInfo; - } - - virtual void testCaseStarting( TestCaseInfo const& _testInfo ) { - currentTestCaseInfo = _testInfo; - } - virtual void sectionStarting( SectionInfo const& _sectionInfo ) { - m_sectionStack.push_back( _sectionInfo ); - } - - virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) { - m_sectionStack.pop_back(); - } - virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) { - currentTestCaseInfo.reset(); - } - virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) { - currentGroupInfo.reset(); - } - virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) { - currentTestCaseInfo.reset(); - currentGroupInfo.reset(); - currentTestRunInfo.reset(); - } - - virtual void skipTest( TestCaseInfo const& ) { - // Don't do anything with this by default. - // It can optionally be overridden in the derived class. - } - - Ptr m_config; - std::ostream& stream; - - LazyStat currentTestRunInfo; - LazyStat currentGroupInfo; - LazyStat currentTestCaseInfo; - - std::vector m_sectionStack; - }; - - struct CumulativeReporterBase : SharedImpl { - template - struct Node : SharedImpl<> { - explicit Node( T const& _value ) : value( _value ) {} - virtual ~Node() {} - - typedef std::vector > ChildNodes; - T value; - ChildNodes children; - }; - struct SectionNode : SharedImpl<> { - explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {} - virtual ~SectionNode(); - - bool operator == ( SectionNode const& other ) const { - return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; - } - bool operator == ( Ptr const& other ) const { - return operator==( *other ); - } - - SectionStats stats; - typedef std::vector > ChildSections; - typedef std::vector Assertions; - ChildSections childSections; - Assertions assertions; - std::string stdOut; - std::string stdErr; - }; - - struct BySectionInfo { - BySectionInfo( SectionInfo const& other ) : m_other( other ) {} - BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} - bool operator() ( Ptr const& node ) const { - return node->stats.sectionInfo.lineInfo == m_other.lineInfo; - } - private: - void operator=( BySectionInfo const& ); - SectionInfo const& m_other; - }; - - typedef Node TestCaseNode; - typedef Node TestGroupNode; - typedef Node TestRunNode; - - CumulativeReporterBase( ReporterConfig const& _config ) - : m_config( _config.fullConfig() ), - stream( _config.stream() ) - {} - ~CumulativeReporterBase(); - - virtual void testRunStarting( TestRunInfo const& ) {} - virtual void testGroupStarting( GroupInfo const& ) {} - - virtual void testCaseStarting( TestCaseInfo const& ) {} - - virtual void sectionStarting( SectionInfo const& sectionInfo ) { - SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); - Ptr node; - if( m_sectionStack.empty() ) { - if( !m_rootSection ) - m_rootSection = new SectionNode( incompleteStats ); - node = m_rootSection; - } - else { - SectionNode& parentNode = *m_sectionStack.back(); - SectionNode::ChildSections::const_iterator it = - std::find_if( parentNode.childSections.begin(), - parentNode.childSections.end(), - BySectionInfo( sectionInfo ) ); - if( it == parentNode.childSections.end() ) { - node = new SectionNode( incompleteStats ); - parentNode.childSections.push_back( node ); - } - else - node = *it; - } - m_sectionStack.push_back( node ); - m_deepestSection = node; - } - - virtual void assertionStarting( AssertionInfo const& ) {} - - virtual bool assertionEnded( AssertionStats const& assertionStats ) { - assert( !m_sectionStack.empty() ); - SectionNode& sectionNode = *m_sectionStack.back(); - sectionNode.assertions.push_back( assertionStats ); - return true; - } - virtual void sectionEnded( SectionStats const& sectionStats ) { - assert( !m_sectionStack.empty() ); - SectionNode& node = *m_sectionStack.back(); - node.stats = sectionStats; - m_sectionStack.pop_back(); - } - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) { - Ptr node = new TestCaseNode( testCaseStats ); - assert( m_sectionStack.size() == 0 ); - node->children.push_back( m_rootSection ); - m_testCases.push_back( node ); - m_rootSection.reset(); - - assert( m_deepestSection ); - m_deepestSection->stdOut = testCaseStats.stdOut; - m_deepestSection->stdErr = testCaseStats.stdErr; - } - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) { - Ptr node = new TestGroupNode( testGroupStats ); - node->children.swap( m_testCases ); - m_testGroups.push_back( node ); - } - virtual void testRunEnded( TestRunStats const& testRunStats ) { - Ptr node = new TestRunNode( testRunStats ); - node->children.swap( m_testGroups ); - m_testRuns.push_back( node ); - testRunEndedCumulative(); - } - virtual void testRunEndedCumulative() = 0; - - virtual void skipTest( TestCaseInfo const& ) {} - - Ptr m_config; - std::ostream& stream; - std::vector m_assertions; - std::vector > > m_sections; - std::vector > m_testCases; - std::vector > m_testGroups; - - std::vector > m_testRuns; - - Ptr m_rootSection; - Ptr m_deepestSection; - std::vector > m_sectionStack; - - }; - - template - char const* getLineOfChars() { - static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; - if( !*line ) { - memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); - line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; - } - return line; - } - -} // end namespace Catch - -// #included from: ../internal/catch_reporter_registrars.hpp -#define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED - -namespace Catch { - - template - class LegacyReporterRegistrar { - - class ReporterFactory : public IReporterFactory { - virtual IStreamingReporter* create( ReporterConfig const& config ) const { - return new LegacyReporterAdapter( new T( config ) ); - } - - virtual std::string getDescription() const { - return T::getDescription(); - } - }; - - public: - - LegacyReporterRegistrar( std::string const& name ) { - getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); - } - }; - - template - class ReporterRegistrar { - - class ReporterFactory : public IReporterFactory { - - // *** Please Note ***: - // - If you end up here looking at a compiler error because it's trying to register - // your custom reporter class be aware that the native reporter interface has changed - // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via - // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter. - // However please consider updating to the new interface as the old one is now - // deprecated and will probably be removed quite soon! - // Please contact me via github if you have any questions at all about this. - // In fact, ideally, please contact me anyway to let me know you've hit this - as I have - // no idea who is actually using custom reporters at all (possibly no-one!). - // The new interface is designed to minimise exposure to interface changes in the future. - virtual IStreamingReporter* create( ReporterConfig const& config ) const { - return new T( config ); - } - - virtual std::string getDescription() const { - return T::getDescription(); - } - }; - - public: - - ReporterRegistrar( std::string const& name ) { - getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); - } - }; -} - -#define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \ - namespace{ Catch::LegacyReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } -#define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \ - namespace{ Catch::ReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } - -// #included from: ../internal/catch_xmlwriter.hpp -#define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { - - class XmlWriter { - public: - - class ScopedElement { - public: - ScopedElement( XmlWriter* writer ) - : m_writer( writer ) - {} - - ScopedElement( ScopedElement const& other ) - : m_writer( other.m_writer ){ - other.m_writer = NULL; - } - - ~ScopedElement() { - if( m_writer ) - m_writer->endElement(); - } - - ScopedElement& writeText( std::string const& text, bool indent = true ) { - m_writer->writeText( text, indent ); - return *this; - } - - template - ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { - m_writer->writeAttribute( name, attribute ); - return *this; - } - - private: - mutable XmlWriter* m_writer; - }; - - XmlWriter() - : m_tagIsOpen( false ), - m_needsNewline( false ), - m_os( &Catch::cout() ) - {} - - XmlWriter( std::ostream& os ) - : m_tagIsOpen( false ), - m_needsNewline( false ), - m_os( &os ) - {} - - ~XmlWriter() { - while( !m_tags.empty() ) - endElement(); - } - - XmlWriter& startElement( std::string const& name ) { - ensureTagClosed(); - newlineIfNecessary(); - stream() << m_indent << "<" << name; - m_tags.push_back( name ); - m_indent += " "; - m_tagIsOpen = true; - return *this; - } - - ScopedElement scopedElement( std::string const& name ) { - ScopedElement scoped( this ); - startElement( name ); - return scoped; - } - - XmlWriter& endElement() { - newlineIfNecessary(); - m_indent = m_indent.substr( 0, m_indent.size()-2 ); - if( m_tagIsOpen ) { - stream() << "/>\n"; - m_tagIsOpen = false; - } - else { - stream() << m_indent << "\n"; - } - m_tags.pop_back(); - return *this; - } - - XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) { - if( !name.empty() && !attribute.empty() ) { - stream() << " " << name << "=\""; - writeEncodedText( attribute ); - stream() << "\""; - } - return *this; - } - - XmlWriter& writeAttribute( std::string const& name, bool attribute ) { - stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\""; - return *this; - } - - template - XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { - if( !name.empty() ) - stream() << " " << name << "=\"" << attribute << "\""; - return *this; - } - - XmlWriter& writeText( std::string const& text, bool indent = true ) { - if( !text.empty() ){ - bool tagWasOpen = m_tagIsOpen; - ensureTagClosed(); - if( tagWasOpen && indent ) - stream() << m_indent; - writeEncodedText( text ); - m_needsNewline = true; - } - return *this; - } - - XmlWriter& writeComment( std::string const& text ) { - ensureTagClosed(); - stream() << m_indent << ""; - m_needsNewline = true; - return *this; - } - - XmlWriter& writeBlankLine() { - ensureTagClosed(); - stream() << "\n"; - return *this; - } - - void setStream( std::ostream& os ) { - m_os = &os; - } - - private: - XmlWriter( XmlWriter const& ); - void operator=( XmlWriter const& ); - - std::ostream& stream() { - return *m_os; - } - - void ensureTagClosed() { - if( m_tagIsOpen ) { - stream() << ">\n"; - m_tagIsOpen = false; - } - } - - void newlineIfNecessary() { - if( m_needsNewline ) { - stream() << "\n"; - m_needsNewline = false; - } - } - - void writeEncodedText( std::string const& text ) { - static const char* charsToEncode = "<&\""; - std::string mtext = text; - std::string::size_type pos = mtext.find_first_of( charsToEncode ); - while( pos != std::string::npos ) { - stream() << mtext.substr( 0, pos ); - - switch( mtext[pos] ) { - case '<': - stream() << "<"; - break; - case '&': - stream() << "&"; - break; - case '\"': - stream() << """; - break; - } - mtext = mtext.substr( pos+1 ); - pos = mtext.find_first_of( charsToEncode ); - } - stream() << mtext; - } - - bool m_tagIsOpen; - bool m_needsNewline; - std::vector m_tags; - std::string m_indent; - std::ostream* m_os; - }; - -} -namespace Catch { - class XmlReporter : public StreamingReporterBase { - public: - XmlReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ), - m_sectionDepth( 0 ) - {} - - virtual ~XmlReporter(); - - static std::string getDescription() { - return "Reports test results as an XML document"; - } - - public: // StreamingReporterBase - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = true; - return prefs; - } - - virtual void noMatchingTestCases( std::string const& s ) { - StreamingReporterBase::noMatchingTestCases( s ); - } - - virtual void testRunStarting( TestRunInfo const& testInfo ) { - StreamingReporterBase::testRunStarting( testInfo ); - m_xml.setStream( stream ); - m_xml.startElement( "Catch" ); - if( !m_config->name().empty() ) - m_xml.writeAttribute( "name", m_config->name() ); - } - - virtual void testGroupStarting( GroupInfo const& groupInfo ) { - StreamingReporterBase::testGroupStarting( groupInfo ); - m_xml.startElement( "Group" ) - .writeAttribute( "name", groupInfo.name ); - } - - virtual void testCaseStarting( TestCaseInfo const& testInfo ) { - StreamingReporterBase::testCaseStarting(testInfo); - m_xml.startElement( "TestCase" ).writeAttribute( "name", trim( testInfo.name ) ); - - if ( m_config->showDurations() == ShowDurations::Always ) - m_testCaseTimer.start(); - } - - virtual void sectionStarting( SectionInfo const& sectionInfo ) { - StreamingReporterBase::sectionStarting( sectionInfo ); - if( m_sectionDepth++ > 0 ) { - m_xml.startElement( "Section" ) - .writeAttribute( "name", trim( sectionInfo.name ) ) - .writeAttribute( "description", sectionInfo.description ); - } - } - - virtual void assertionStarting( AssertionInfo const& ) { } - - virtual bool assertionEnded( AssertionStats const& assertionStats ) { - const AssertionResult& assertionResult = assertionStats.assertionResult; - - // Print any info messages in tags. - if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { - for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); - it != itEnd; - ++it ) { - if( it->type == ResultWas::Info ) { - m_xml.scopedElement( "Info" ) - .writeText( it->message ); - } else if ( it->type == ResultWas::Warning ) { - m_xml.scopedElement( "Warning" ) - .writeText( it->message ); - } - } - } - - // Drop out if result was successful but we're not printing them. - if( !m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType()) ) - return true; - - // Print the expression if there is one. - if( assertionResult.hasExpression() ) { - m_xml.startElement( "Expression" ) - .writeAttribute( "success", assertionResult.succeeded() ) - .writeAttribute( "type", assertionResult.getTestMacroName() ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ); - - m_xml.scopedElement( "Original" ) - .writeText( assertionResult.getExpression() ); - m_xml.scopedElement( "Expanded" ) - .writeText( assertionResult.getExpandedExpression() ); - } - - // And... Print a result applicable to each result type. - switch( assertionResult.getResultType() ) { - case ResultWas::ThrewException: - m_xml.scopedElement( "Exception" ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ) - .writeText( assertionResult.getMessage() ); - break; - case ResultWas::FatalErrorCondition: - m_xml.scopedElement( "Fatal Error Condition" ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ) - .writeText( assertionResult.getMessage() ); - break; - case ResultWas::Info: - m_xml.scopedElement( "Info" ) - .writeText( assertionResult.getMessage() ); - break; - case ResultWas::Warning: - // Warning will already have been written - break; - case ResultWas::ExplicitFailure: - m_xml.scopedElement( "Failure" ) - .writeText( assertionResult.getMessage() ); - break; - default: - break; - } - - if( assertionResult.hasExpression() ) - m_xml.endElement(); - - return true; - } - - virtual void sectionEnded( SectionStats const& sectionStats ) { - StreamingReporterBase::sectionEnded( sectionStats ); - if( --m_sectionDepth > 0 ) { - XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); - e.writeAttribute( "successes", sectionStats.assertions.passed ); - e.writeAttribute( "failures", sectionStats.assertions.failed ); - e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); - - if ( m_config->showDurations() == ShowDurations::Always ) - e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); - - m_xml.endElement(); - } - } - - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) { - StreamingReporterBase::testCaseEnded( testCaseStats ); - XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); - e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); - - if ( m_config->showDurations() == ShowDurations::Always ) - e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); - - m_xml.endElement(); - } - - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) { - StreamingReporterBase::testGroupEnded( testGroupStats ); - // TODO: Check testGroupStats.aborting and act accordingly. - m_xml.scopedElement( "OverallResults" ) - .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) - .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) - .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); - m_xml.endElement(); - } - - virtual void testRunEnded( TestRunStats const& testRunStats ) { - StreamingReporterBase::testRunEnded( testRunStats ); - m_xml.scopedElement( "OverallResults" ) - .writeAttribute( "successes", testRunStats.totals.assertions.passed ) - .writeAttribute( "failures", testRunStats.totals.assertions.failed ) - .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); - m_xml.endElement(); - } - - private: - Timer m_testCaseTimer; - XmlWriter m_xml; - int m_sectionDepth; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_junit.hpp -#define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED - -#include - -namespace Catch { - - class JunitReporter : public CumulativeReporterBase { - public: - JunitReporter( ReporterConfig const& _config ) - : CumulativeReporterBase( _config ), - xml( _config.stream() ) - {} - - ~JunitReporter(); - - static std::string getDescription() { - return "Reports test results in an XML format that looks like Ant's junitreport target"; - } - - virtual void noMatchingTestCases( std::string const& /*spec*/ ) {} - - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = true; - return prefs; - } - - virtual void testRunStarting( TestRunInfo const& runInfo ) { - CumulativeReporterBase::testRunStarting( runInfo ); - xml.startElement( "testsuites" ); - } - - virtual void testGroupStarting( GroupInfo const& groupInfo ) { - suiteTimer.start(); - stdOutForSuite.str(""); - stdErrForSuite.str(""); - unexpectedExceptions = 0; - CumulativeReporterBase::testGroupStarting( groupInfo ); - } - - virtual bool assertionEnded( AssertionStats const& assertionStats ) { - if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException ) - unexpectedExceptions++; - return CumulativeReporterBase::assertionEnded( assertionStats ); - } - - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) { - stdOutForSuite << testCaseStats.stdOut; - stdErrForSuite << testCaseStats.stdErr; - CumulativeReporterBase::testCaseEnded( testCaseStats ); - } - - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) { - double suiteTime = suiteTimer.getElapsedSeconds(); - CumulativeReporterBase::testGroupEnded( testGroupStats ); - writeGroup( *m_testGroups.back(), suiteTime ); - } - - virtual void testRunEndedCumulative() { - xml.endElement(); - } - - void writeGroup( TestGroupNode const& groupNode, double suiteTime ) { - XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); - TestGroupStats const& stats = groupNode.value; - xml.writeAttribute( "name", stats.groupInfo.name ); - xml.writeAttribute( "errors", unexpectedExceptions ); - xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); - xml.writeAttribute( "tests", stats.totals.assertions.total() ); - xml.writeAttribute( "hostname", "tbd" ); // !TBD - if( m_config->showDurations() == ShowDurations::Never ) - xml.writeAttribute( "time", "" ); - else - xml.writeAttribute( "time", suiteTime ); - xml.writeAttribute( "timestamp", "tbd" ); // !TBD - - // Write test cases - for( TestGroupNode::ChildNodes::const_iterator - it = groupNode.children.begin(), itEnd = groupNode.children.end(); - it != itEnd; - ++it ) - writeTestCase( **it ); - - xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false ); - xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false ); - } - - void writeTestCase( TestCaseNode const& testCaseNode ) { - TestCaseStats const& stats = testCaseNode.value; - - // All test cases have exactly one section - which represents the - // test case itself. That section may have 0-n nested sections - assert( testCaseNode.children.size() == 1 ); - SectionNode const& rootSection = *testCaseNode.children.front(); - - std::string className = stats.testInfo.className; - - if( className.empty() ) { - if( rootSection.childSections.empty() ) - className = "global"; - } - writeSection( className, "", rootSection ); - } - - void writeSection( std::string const& className, - std::string const& rootName, - SectionNode const& sectionNode ) { - std::string name = trim( sectionNode.stats.sectionInfo.name ); - if( !rootName.empty() ) - name = rootName + "/" + name; - - if( !sectionNode.assertions.empty() || - !sectionNode.stdOut.empty() || - !sectionNode.stdErr.empty() ) { - XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); - if( className.empty() ) { - xml.writeAttribute( "classname", name ); - xml.writeAttribute( "name", "root" ); - } - else { - xml.writeAttribute( "classname", className ); - xml.writeAttribute( "name", name ); - } - xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) ); - - writeAssertions( sectionNode ); - - if( !sectionNode.stdOut.empty() ) - xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false ); - if( !sectionNode.stdErr.empty() ) - xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false ); - } - for( SectionNode::ChildSections::const_iterator - it = sectionNode.childSections.begin(), - itEnd = sectionNode.childSections.end(); - it != itEnd; - ++it ) - if( className.empty() ) - writeSection( name, "", **it ); - else - writeSection( className, name, **it ); - } - - void writeAssertions( SectionNode const& sectionNode ) { - for( SectionNode::Assertions::const_iterator - it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end(); - it != itEnd; - ++it ) - writeAssertion( *it ); - } - void writeAssertion( AssertionStats const& stats ) { - AssertionResult const& result = stats.assertionResult; - if( !result.isOk() ) { - std::string elementName; - switch( result.getResultType() ) { - case ResultWas::ThrewException: - case ResultWas::FatalErrorCondition: - elementName = "error"; - break; - case ResultWas::ExplicitFailure: - elementName = "failure"; - break; - case ResultWas::ExpressionFailed: - elementName = "failure"; - break; - case ResultWas::DidntThrowException: - elementName = "failure"; - break; - - // We should never see these here: - case ResultWas::Info: - case ResultWas::Warning: - case ResultWas::Ok: - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - elementName = "internalError"; - break; - } - - XmlWriter::ScopedElement e = xml.scopedElement( elementName ); - - xml.writeAttribute( "message", result.getExpandedExpression() ); - xml.writeAttribute( "type", result.getTestMacroName() ); - - std::ostringstream oss; - if( !result.getMessage().empty() ) - oss << result.getMessage() << "\n"; - for( std::vector::const_iterator - it = stats.infoMessages.begin(), - itEnd = stats.infoMessages.end(); - it != itEnd; - ++it ) - if( it->type == ResultWas::Info ) - oss << it->message << "\n"; - - oss << "at " << result.getSourceInfo(); - xml.writeText( oss.str(), false ); - } - } - - XmlWriter xml; - Timer suiteTimer; - std::ostringstream stdOutForSuite; - std::ostringstream stdErrForSuite; - unsigned int unexpectedExceptions; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_console.hpp -#define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED - -namespace Catch { - - struct ConsoleReporter : StreamingReporterBase { - ConsoleReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ), - m_headerPrinted( false ) - {} - - virtual ~ConsoleReporter(); - static std::string getDescription() { - return "Reports test results as plain lines of text"; - } - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = false; - return prefs; - } - - virtual void noMatchingTestCases( std::string const& spec ) { - stream << "No test cases matched '" << spec << "'" << std::endl; - } - - virtual void assertionStarting( AssertionInfo const& ) { - } - - virtual bool assertionEnded( AssertionStats const& _assertionStats ) { - AssertionResult const& result = _assertionStats.assertionResult; - - bool printInfoMessages = true; - - // Drop out if result was successful and we're not printing those - if( !m_config->includeSuccessfulResults() && result.isOk() ) { - if( result.getResultType() != ResultWas::Warning ) - return false; - printInfoMessages = false; - } - - lazyPrint(); - - AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); - printer.print(); - stream << std::endl; - return true; - } - - virtual void sectionStarting( SectionInfo const& _sectionInfo ) { - m_headerPrinted = false; - StreamingReporterBase::sectionStarting( _sectionInfo ); - } - virtual void sectionEnded( SectionStats const& _sectionStats ) { - if( _sectionStats.missingAssertions ) { - lazyPrint(); - Colour colour( Colour::ResultError ); - if( m_sectionStack.size() > 1 ) - stream << "\nNo assertions in section"; - else - stream << "\nNo assertions in test case"; - stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; - } - if( m_headerPrinted ) { - if( m_config->showDurations() == ShowDurations::Always ) - stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl; - m_headerPrinted = false; - } - else { - if( m_config->showDurations() == ShowDurations::Always ) - stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl; - } - StreamingReporterBase::sectionEnded( _sectionStats ); - } - - virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) { - StreamingReporterBase::testCaseEnded( _testCaseStats ); - m_headerPrinted = false; - } - virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) { - if( currentGroupInfo.used ) { - printSummaryDivider(); - stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; - printTotals( _testGroupStats.totals ); - stream << "\n" << std::endl; - } - StreamingReporterBase::testGroupEnded( _testGroupStats ); - } - virtual void testRunEnded( TestRunStats const& _testRunStats ) { - printTotalsDivider( _testRunStats.totals ); - printTotals( _testRunStats.totals ); - stream << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - - class AssertionPrinter { - void operator= ( AssertionPrinter const& ); - public: - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) - : stream( _stream ), - stats( _stats ), - result( _stats.assertionResult ), - colour( Colour::None ), - message( result.getMessage() ), - messages( _stats.infoMessages ), - printInfoMessages( _printInfoMessages ) - { - switch( result.getResultType() ) { - case ResultWas::Ok: - colour = Colour::Success; - passOrFail = "PASSED"; - //if( result.hasMessage() ) - if( _stats.infoMessages.size() == 1 ) - messageLabel = "with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "with messages"; - break; - case ResultWas::ExpressionFailed: - if( result.isOk() ) { - colour = Colour::Success; - passOrFail = "FAILED - but was ok"; - } - else { - colour = Colour::Error; - passOrFail = "FAILED"; - } - if( _stats.infoMessages.size() == 1 ) - messageLabel = "with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "with messages"; - break; - case ResultWas::ThrewException: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "due to unexpected exception with message"; - break; - case ResultWas::FatalErrorCondition: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "due to a fatal error condition"; - break; - case ResultWas::DidntThrowException: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "because no exception was thrown where one was expected"; - break; - case ResultWas::Info: - messageLabel = "info"; - break; - case ResultWas::Warning: - messageLabel = "warning"; - break; - case ResultWas::ExplicitFailure: - passOrFail = "FAILED"; - colour = Colour::Error; - if( _stats.infoMessages.size() == 1 ) - messageLabel = "explicitly with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "explicitly with messages"; - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - passOrFail = "** internal error **"; - colour = Colour::Error; - break; - } - } - - void print() const { - printSourceInfo(); - if( stats.totals.assertions.total() > 0 ) { - if( result.isOk() ) - stream << "\n"; - printResultType(); - printOriginalExpression(); - printReconstructedExpression(); - } - else { - stream << "\n"; - } - printMessage(); - } - - private: - void printResultType() const { - if( !passOrFail.empty() ) { - Colour colourGuard( colour ); - stream << passOrFail << ":\n"; - } - } - void printOriginalExpression() const { - if( result.hasExpression() ) { - Colour colourGuard( Colour::OriginalExpression ); - stream << " "; - stream << result.getExpressionInMacro(); - stream << "\n"; - } - } - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - stream << "with expansion:\n"; - Colour colourGuard( Colour::ReconstructedExpression ); - stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n"; - } - } - void printMessage() const { - if( !messageLabel.empty() ) - stream << messageLabel << ":" << "\n"; - for( std::vector::const_iterator it = messages.begin(), itEnd = messages.end(); - it != itEnd; - ++it ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || it->type != ResultWas::Info ) - stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n"; - } - } - void printSourceInfo() const { - Colour colourGuard( Colour::FileName ); - stream << result.getSourceInfo() << ": "; - } - - std::ostream& stream; - AssertionStats const& stats; - AssertionResult const& result; - Colour::Code colour; - std::string passOrFail; - std::string messageLabel; - std::string message; - std::vector messages; - bool printInfoMessages; - }; - - void lazyPrint() { - - if( !currentTestRunInfo.used ) - lazyPrintRunInfo(); - if( !currentGroupInfo.used ) - lazyPrintGroupInfo(); - - if( !m_headerPrinted ) { - printTestCaseAndSectionHeader(); - m_headerPrinted = true; - } - } - void lazyPrintRunInfo() { - stream << "\n" << getLineOfChars<'~'>() << "\n"; - Colour colour( Colour::SecondaryText ); - stream << currentTestRunInfo->name - << " is a Catch v" << libraryVersion << " host application.\n" - << "Run with -? for options\n\n"; - - if( m_config->rngSeed() != 0 ) - stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; - - currentTestRunInfo.used = true; - } - void lazyPrintGroupInfo() { - if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) { - printClosedHeader( "Group: " + currentGroupInfo->name ); - currentGroupInfo.used = true; - } - } - void printTestCaseAndSectionHeader() { - assert( !m_sectionStack.empty() ); - printOpenHeader( currentTestCaseInfo->name ); - - if( m_sectionStack.size() > 1 ) { - Colour colourGuard( Colour::Headers ); - - std::vector::const_iterator - it = m_sectionStack.begin()+1, // Skip first section (test case) - itEnd = m_sectionStack.end(); - for( ; it != itEnd; ++it ) - printHeaderString( it->name, 2 ); - } - - SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; - - if( !lineInfo.empty() ){ - stream << getLineOfChars<'-'>() << "\n"; - Colour colourGuard( Colour::FileName ); - stream << lineInfo << "\n"; - } - stream << getLineOfChars<'.'>() << "\n" << std::endl; - } - - void printClosedHeader( std::string const& _name ) { - printOpenHeader( _name ); - stream << getLineOfChars<'.'>() << "\n"; - } - void printOpenHeader( std::string const& _name ) { - stream << getLineOfChars<'-'>() << "\n"; - { - Colour colourGuard( Colour::Headers ); - printHeaderString( _name ); - } - } - - // if string has a : in first line will set indent to follow it on - // subsequent lines - void printHeaderString( std::string const& _string, std::size_t indent = 0 ) { - std::size_t i = _string.find( ": " ); - if( i != std::string::npos ) - i+=2; - else - i = 0; - stream << Text( _string, TextAttributes() - .setIndent( indent+i) - .setInitialIndent( indent ) ) << "\n"; - } - - struct SummaryColumn { - - SummaryColumn( std::string const& _label, Colour::Code _colour ) - : label( _label ), - colour( _colour ) - {} - SummaryColumn addRow( std::size_t count ) { - std::ostringstream oss; - oss << count; - std::string row = oss.str(); - for( std::vector::iterator it = rows.begin(); it != rows.end(); ++it ) { - while( it->size() < row.size() ) - *it = " " + *it; - while( it->size() > row.size() ) - row = " " + row; - } - rows.push_back( row ); - return *this; - } - - std::string label; - Colour::Code colour; - std::vector rows; - - }; - - void printTotals( Totals const& totals ) { - if( totals.testCases.total() == 0 ) { - stream << Colour( Colour::Warning ) << "No tests ran\n"; - } - else if( totals.assertions.total() > 0 && totals.assertions.allPassed() ) { - stream << Colour( Colour::ResultSuccess ) << "All tests passed"; - stream << " (" - << pluralise( totals.assertions.passed, "assertion" ) << " in " - << pluralise( totals.testCases.passed, "test case" ) << ")" - << "\n"; - } - else { - - std::vector columns; - columns.push_back( SummaryColumn( "", Colour::None ) - .addRow( totals.testCases.total() ) - .addRow( totals.assertions.total() ) ); - columns.push_back( SummaryColumn( "passed", Colour::Success ) - .addRow( totals.testCases.passed ) - .addRow( totals.assertions.passed ) ); - columns.push_back( SummaryColumn( "failed", Colour::ResultError ) - .addRow( totals.testCases.failed ) - .addRow( totals.assertions.failed ) ); - columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) - .addRow( totals.testCases.failedButOk ) - .addRow( totals.assertions.failedButOk ) ); - - printSummaryRow( "test cases", columns, 0 ); - printSummaryRow( "assertions", columns, 1 ); - } - } - void printSummaryRow( std::string const& label, std::vector const& cols, std::size_t row ) { - for( std::vector::const_iterator it = cols.begin(); it != cols.end(); ++it ) { - std::string value = it->rows[row]; - if( it->label.empty() ) { - stream << label << ": "; - if( value != "0" ) - stream << value; - else - stream << Colour( Colour::Warning ) << "- none -"; - } - else if( value != "0" ) { - stream << Colour( Colour::LightGrey ) << " | "; - stream << Colour( it->colour ) - << value << " " << it->label; - } - } - stream << "\n"; - } - - static std::size_t makeRatio( std::size_t number, std::size_t total ) { - std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0; - return ( ratio == 0 && number > 0 ) ? 1 : ratio; - } - static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) { - if( i > j && i > k ) - return i; - else if( j > k ) - return j; - else - return k; - } - - void printTotalsDivider( Totals const& totals ) { - if( totals.testCases.total() > 0 ) { - std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() ); - std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() ); - std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() ); - while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 ) - findMax( failedRatio, failedButOkRatio, passedRatio )++; - while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 ) - findMax( failedRatio, failedButOkRatio, passedRatio )--; - - stream << Colour( Colour::Error ) << std::string( failedRatio, '=' ); - stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' ); - if( totals.testCases.allPassed() ) - stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' ); - else - stream << Colour( Colour::Success ) << std::string( passedRatio, '=' ); - } - else { - stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' ); - } - stream << "\n"; - } - void printSummaryDivider() { - stream << getLineOfChars<'-'>() << "\n"; - } - - private: - bool m_headerPrinted; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_compact.hpp -#define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED - -namespace Catch { - - struct CompactReporter : StreamingReporterBase { - - CompactReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - {} - - virtual ~CompactReporter(); - - static std::string getDescription() { - return "Reports test results on a single line, suitable for IDEs"; - } - - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = false; - return prefs; - } - - virtual void noMatchingTestCases( std::string const& spec ) { - stream << "No test cases matched '" << spec << "'" << std::endl; - } - - virtual void assertionStarting( AssertionInfo const& ) { - } - - virtual bool assertionEnded( AssertionStats const& _assertionStats ) { - AssertionResult const& result = _assertionStats.assertionResult; - - bool printInfoMessages = true; - - // Drop out if result was successful and we're not printing those - if( !m_config->includeSuccessfulResults() && result.isOk() ) { - if( result.getResultType() != ResultWas::Warning ) - return false; - printInfoMessages = false; - } - - AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); - printer.print(); - - stream << std::endl; - return true; - } - - virtual void testRunEnded( TestRunStats const& _testRunStats ) { - printTotals( _testRunStats.totals ); - stream << "\n" << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - class AssertionPrinter { - void operator= ( AssertionPrinter const& ); - public: - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) - : stream( _stream ) - , stats( _stats ) - , result( _stats.assertionResult ) - , messages( _stats.infoMessages ) - , itMessage( _stats.infoMessages.begin() ) - , printInfoMessages( _printInfoMessages ) - {} - - void print() { - printSourceInfo(); - - itMessage = messages.begin(); - - switch( result.getResultType() ) { - case ResultWas::Ok: - printResultType( Colour::ResultSuccess, passedString() ); - printOriginalExpression(); - printReconstructedExpression(); - if ( ! result.hasExpression() ) - printRemainingMessages( Colour::None ); - else - printRemainingMessages(); - break; - case ResultWas::ExpressionFailed: - if( result.isOk() ) - printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) ); - else - printResultType( Colour::Error, failedString() ); - printOriginalExpression(); - printReconstructedExpression(); - printRemainingMessages(); - break; - case ResultWas::ThrewException: - printResultType( Colour::Error, failedString() ); - printIssue( "unexpected exception with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::FatalErrorCondition: - printResultType( Colour::Error, failedString() ); - printIssue( "fatal error condition with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::DidntThrowException: - printResultType( Colour::Error, failedString() ); - printIssue( "expected exception, got none" ); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::Info: - printResultType( Colour::None, "info" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::Warning: - printResultType( Colour::None, "warning" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::ExplicitFailure: - printResultType( Colour::Error, failedString() ); - printIssue( "explicitly" ); - printRemainingMessages( Colour::None ); - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - printResultType( Colour::Error, "** internal error **" ); - break; - } - } - - private: - // Colour::LightGrey - - static Colour::Code dimColour() { return Colour::FileName; } - -#ifdef CATCH_PLATFORM_MAC - static const char* failedString() { return "FAILED"; } - static const char* passedString() { return "PASSED"; } -#else - static const char* failedString() { return "failed"; } - static const char* passedString() { return "passed"; } -#endif - - void printSourceInfo() const { - Colour colourGuard( Colour::FileName ); - stream << result.getSourceInfo() << ":"; - } - - void printResultType( Colour::Code colour, std::string passOrFail ) const { - if( !passOrFail.empty() ) { - { - Colour colourGuard( colour ); - stream << " " << passOrFail; - } - stream << ":"; - } - } - - void printIssue( std::string issue ) const { - stream << " " << issue; - } - - void printExpressionWas() { - if( result.hasExpression() ) { - stream << ";"; - { - Colour colour( dimColour() ); - stream << " expression was:"; - } - printOriginalExpression(); - } - } - - void printOriginalExpression() const { - if( result.hasExpression() ) { - stream << " " << result.getExpression(); - } - } - - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - { - Colour colour( dimColour() ); - stream << " for: "; - } - stream << result.getExpandedExpression(); - } - } - - void printMessage() { - if ( itMessage != messages.end() ) { - stream << " '" << itMessage->message << "'"; - ++itMessage; - } - } - - void printRemainingMessages( Colour::Code colour = dimColour() ) { - if ( itMessage == messages.end() ) - return; - - // using messages.end() directly yields compilation error: - std::vector::const_iterator itEnd = messages.end(); - const std::size_t N = static_cast( std::distance( itMessage, itEnd ) ); - - { - Colour colourGuard( colour ); - stream << " with " << pluralise( N, "message" ) << ":"; - } - - for(; itMessage != itEnd; ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || itMessage->type != ResultWas::Info ) { - stream << " '" << itMessage->message << "'"; - if ( ++itMessage != itEnd ) { - Colour colourGuard( dimColour() ); - stream << " and"; - } - } - } - } - - private: - std::ostream& stream; - AssertionStats const& stats; - AssertionResult const& result; - std::vector messages; - std::vector::const_iterator itMessage; - bool printInfoMessages; - }; - - // Colour, message variants: - // - white: No tests ran. - // - red: Failed [both/all] N test cases, failed [both/all] M assertions. - // - white: Passed [both/all] N test cases (no assertions). - // - red: Failed N tests cases, failed M assertions. - // - green: Passed [both/all] N tests cases with M assertions. - - std::string bothOrAll( std::size_t count ) const { - return count == 1 ? "" : count == 2 ? "both " : "all " ; - } - - void printTotals( const Totals& totals ) const { - if( totals.testCases.total() == 0 ) { - stream << "No tests ran."; - } - else if( totals.testCases.failed == totals.testCases.total() ) { - Colour colour( Colour::ResultError ); - const std::string qualify_assertions_failed = - totals.assertions.failed == totals.assertions.total() ? - bothOrAll( totals.assertions.failed ) : ""; - stream << - "Failed " << bothOrAll( totals.testCases.failed ) - << pluralise( totals.testCases.failed, "test case" ) << ", " - "failed " << qualify_assertions_failed << - pluralise( totals.assertions.failed, "assertion" ) << "."; - } - else if( totals.assertions.total() == 0 ) { - stream << - "Passed " << bothOrAll( totals.testCases.total() ) - << pluralise( totals.testCases.total(), "test case" ) - << " (no assertions)."; - } - else if( totals.assertions.failed ) { - Colour colour( Colour::ResultError ); - stream << - "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", " - "failed " << pluralise( totals.assertions.failed, "assertion" ) << "."; - } - else { - Colour colour( Colour::ResultSuccess ); - stream << - "Passed " << bothOrAll( totals.testCases.passed ) - << pluralise( totals.testCases.passed, "test case" ) << - " with " << pluralise( totals.assertions.passed, "assertion" ) << "."; - } - } - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter ) - -} // end namespace Catch - -namespace Catch { - NonCopyable::~NonCopyable() {} - IShared::~IShared() {} - StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {} - IContext::~IContext() {} - IResultCapture::~IResultCapture() {} - ITestCase::~ITestCase() {} - ITestCaseRegistry::~ITestCaseRegistry() {} - IRegistryHub::~IRegistryHub() {} - IMutableRegistryHub::~IMutableRegistryHub() {} - IExceptionTranslator::~IExceptionTranslator() {} - IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {} - IReporter::~IReporter() {} - IReporterFactory::~IReporterFactory() {} - IReporterRegistry::~IReporterRegistry() {} - IStreamingReporter::~IStreamingReporter() {} - AssertionStats::~AssertionStats() {} - SectionStats::~SectionStats() {} - TestCaseStats::~TestCaseStats() {} - TestGroupStats::~TestGroupStats() {} - TestRunStats::~TestRunStats() {} - CumulativeReporterBase::SectionNode::~SectionNode() {} - CumulativeReporterBase::~CumulativeReporterBase() {} - - StreamingReporterBase::~StreamingReporterBase() {} - ConsoleReporter::~ConsoleReporter() {} - CompactReporter::~CompactReporter() {} - IRunner::~IRunner() {} - IMutableContext::~IMutableContext() {} - IConfig::~IConfig() {} - XmlReporter::~XmlReporter() {} - JunitReporter::~JunitReporter() {} - TestRegistry::~TestRegistry() {} - FreeFunctionTestCase::~FreeFunctionTestCase() {} - IGeneratorInfo::~IGeneratorInfo() {} - IGeneratorsForTest::~IGeneratorsForTest() {} - TestSpec::Pattern::~Pattern() {} - TestSpec::NamePattern::~NamePattern() {} - TestSpec::TagPattern::~TagPattern() {} - TestSpec::ExcludedPattern::~ExcludedPattern() {} - - Matchers::Impl::StdString::Equals::~Equals() {} - Matchers::Impl::StdString::Contains::~Contains() {} - Matchers::Impl::StdString::StartsWith::~StartsWith() {} - Matchers::Impl::StdString::EndsWith::~EndsWith() {} - - void Config::dummy() {} -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#endif - -#ifdef CATCH_CONFIG_MAIN -// #included from: internal/catch_default_main.hpp -#define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED - -#ifndef __OBJC__ - -// Standard C/C++ main entry point -int main (int argc, char * const argv[]) { - return Catch::Session().run( argc, argv ); -} - -#else // __OBJC__ - -// Objective-C entry point -int main (int argc, char * const argv[]) { -#if !CATCH_ARC_ENABLED - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; -#endif - - Catch::registerTestMethods(); - int result = Catch::Session().run( argc, (char* const*)argv ); - -#if !CATCH_ARC_ENABLED - [pool drain]; -#endif - - return result; -} - -#endif // __OBJC__ - -#endif - -#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED -# undef CLARA_CONFIG_MAIN -#endif - -////// - -// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ -#ifdef CATCH_CONFIG_PREFIX_ALL - -#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" ) -#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE" ) - -#define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS" ) -#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" ) -#define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" ) - -#define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" ) -#define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE" ) -#define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" ) -#define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" ) -#define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" ) - -#define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" ) -#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" ) -#define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" ) - -#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" ) -#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" ) - -#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) -#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg ) -#define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) -#define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) -#define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) - #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) - #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) - #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) - #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ ) - #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ ) -#else - #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) - #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) - #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) - #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) - #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg ) - #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg ) -#endif -#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) - -#define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) -#define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) - -#define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) - -// "BDD-style" convenience wrappers -#ifdef CATCH_CONFIG_VARIADIC_MACROS -#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) -#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) -#else -#define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags ) -#define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) -#endif -#define CATCH_GIVEN( desc ) CATCH_SECTION( "Given: " desc, "" ) -#define CATCH_WHEN( desc ) CATCH_SECTION( " When: " desc, "" ) -#define CATCH_AND_WHEN( desc ) CATCH_SECTION( " And: " desc, "" ) -#define CATCH_THEN( desc ) CATCH_SECTION( " Then: " desc, "" ) -#define CATCH_AND_THEN( desc ) CATCH_SECTION( " And: " desc, "" ) - -// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required -#else - -#define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "REQUIRE" ) -#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE" ) - -#define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "REQUIRE_THROWS" ) -#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" ) -#define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" ) - -#define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" ) -#define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE" ) -#define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" ) -#define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" ) -#define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" ) - -#define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS" ) -#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" ) -#define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" ) - -#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" ) -#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" ) - -#define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) -#define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg ) -#define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) -#define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) -#define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) - #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) - #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) - #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) - #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ ) - #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ ) -#else - #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) - #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) - #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) - #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) - #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg ) - #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg ) -#endif -#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) - -#define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) -#define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) - -#define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) - -#endif - -#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) - -// "BDD-style" convenience wrappers -#ifdef CATCH_CONFIG_VARIADIC_MACROS -#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) -#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) -#else -#define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags ) -#define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) -#endif -#define GIVEN( desc ) SECTION( " Given: " desc, "" ) -#define WHEN( desc ) SECTION( " When: " desc, "" ) -#define AND_WHEN( desc ) SECTION( "And when: " desc, "" ) -#define THEN( desc ) SECTION( " Then: " desc, "" ) -#define AND_THEN( desc ) SECTION( " And: " desc, "" ) - -using Catch::Detail::Approx; - -// #included from: internal/catch_reenable_warnings.h - -#define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(pop) -# else -# pragma clang diagnostic pop -# endif -#elif defined __GNUC__ -# pragma GCC diagnostic pop -#endif - -#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED - diff --git a/third_party/libosmium/test/include/catch_orig.hpp b/third_party/libosmium/test/include/catch_orig.hpp deleted file mode 100644 index de61226cf..000000000 --- a/third_party/libosmium/test/include/catch_orig.hpp +++ /dev/null @@ -1,9416 +0,0 @@ -/* - * Catch v1.2.1 - * Generated: 2015-06-30 18:23:27.961086 - * ---------------------------------------------------------- - * This file has been merged from multiple headers. Please don't edit it directly - * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED -#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED - -#define TWOBLUECUBES_CATCH_HPP_INCLUDED - -#ifdef __clang__ -# pragma clang system_header -#elif defined __GNUC__ -# pragma GCC system_header -#endif - -// #included from: internal/catch_suppress_warnings.h - -#define TWOBLUECUBES_CATCH_SUPPRESS_WARNINGS_H_INCLUDED - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(push) -# pragma warning(disable: 161 1682) -# else // __ICC -# pragma clang diagnostic ignored "-Wglobal-constructors" -# pragma clang diagnostic ignored "-Wvariadic-macros" -# pragma clang diagnostic ignored "-Wc99-extensions" -# pragma clang diagnostic ignored "-Wunused-variable" -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -# pragma clang diagnostic ignored "-Wc++98-compat" -# pragma clang diagnostic ignored "-Wc++98-compat-pedantic" -# pragma clang diagnostic ignored "-Wswitch-enum" -# endif -#elif defined __GNUC__ -# pragma GCC diagnostic ignored "-Wvariadic-macros" -# pragma GCC diagnostic ignored "-Wunused-variable" -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wpadded" -#endif - -#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) -# define CATCH_IMPL -#endif - -#ifdef CATCH_IMPL -# ifndef CLARA_CONFIG_MAIN -# define CLARA_CONFIG_MAIN_NOT_DEFINED -# define CLARA_CONFIG_MAIN -# endif -#endif - -// #included from: internal/catch_notimplemented_exception.h -#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED - -// #included from: catch_common.h -#define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED - -#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line -#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) -#define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) - -#define INTERNAL_CATCH_STRINGIFY2( expr ) #expr -#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr ) - -#include -#include -#include - -// #included from: catch_compiler_capabilities.h -#define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED - -// Detect a number of compiler features - mostly C++11/14 conformance - by compiler -// The following features are defined: -// -// CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported? -// CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported? -// CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods -// CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported? -// CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported - -// CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? - -// CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? - -// In general each macro has a _NO_ form -// (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature. -// Many features, at point of detection, define an _INTERNAL_ macro, so they -// can be combined, en-mass, with the _NO_ forms later. - -// All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11 - -#ifdef __clang__ - -# if __has_feature(cxx_nullptr) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -# endif - -# if __has_feature(cxx_noexcept) -# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# endif - -#endif // __clang__ - -//////////////////////////////////////////////////////////////////////////////// -// Borland -#ifdef __BORLANDC__ - -#endif // __BORLANDC__ - -//////////////////////////////////////////////////////////////////////////////// -// EDG -#ifdef __EDG_VERSION__ - -#endif // __EDG_VERSION__ - -//////////////////////////////////////////////////////////////////////////////// -// Digital Mars -#ifdef __DMC__ - -#endif // __DMC__ - -//////////////////////////////////////////////////////////////////////////////// -// GCC -#ifdef __GNUC__ - -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) ) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -#endif - -#endif // __GNUC__ - -//////////////////////////////////////////////////////////////////////////////// -// Visual C++ -#ifdef _MSC_VER - -#if (_MSC_VER >= 1600) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -#endif - -#if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) -#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -#endif - -#endif // _MSC_VER - -// Use variadic macros if the compiler supports them -#if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \ - ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \ - ( defined __GNUC__ && __GNUC__ >= 3 ) || \ - ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L ) - -#define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS - -#endif - -//////////////////////////////////////////////////////////////////////////////// -// C++ language feature support - -// catch all support for C++11 -#if (__cplusplus >= 201103L) - -# define CATCH_CPP11_OR_GREATER - -# if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -# define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM -# define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE -# define CATCH_INTERNAL_CONFIG_CPP11_TUPLE -# endif - -# ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS -# define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS -# endif - -#endif // __cplusplus >= 201103L - -// Now set the actual defines based on the above + anything the user has configured -#if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_NULLPTR -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_NOEXCEPT -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_GENERATED_METHODS -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_IS_ENUM -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_TUPLE -#endif -#if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS) -#define CATCH_CONFIG_VARIADIC_MACROS -#endif - -// noexcept support: -#if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT) -# define CATCH_NOEXCEPT noexcept -# define CATCH_NOEXCEPT_IS(x) noexcept(x) -#else -# define CATCH_NOEXCEPT throw() -# define CATCH_NOEXCEPT_IS(x) -#endif - -namespace Catch { - - class NonCopyable { -#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - NonCopyable( NonCopyable const& ) = delete; - NonCopyable( NonCopyable && ) = delete; - NonCopyable& operator = ( NonCopyable const& ) = delete; - NonCopyable& operator = ( NonCopyable && ) = delete; -#else - NonCopyable( NonCopyable const& info ); - NonCopyable& operator = ( NonCopyable const& ); -#endif - - protected: - NonCopyable() {} - virtual ~NonCopyable(); - }; - - class SafeBool { - public: - typedef void (SafeBool::*type)() const; - - static type makeSafe( bool value ) { - return value ? &SafeBool::trueValue : 0; - } - private: - void trueValue() const {} - }; - - template - inline void deleteAll( ContainerT& container ) { - typename ContainerT::const_iterator it = container.begin(); - typename ContainerT::const_iterator itEnd = container.end(); - for(; it != itEnd; ++it ) - delete *it; - } - template - inline void deleteAllValues( AssociativeContainerT& container ) { - typename AssociativeContainerT::const_iterator it = container.begin(); - typename AssociativeContainerT::const_iterator itEnd = container.end(); - for(; it != itEnd; ++it ) - delete it->second; - } - - bool startsWith( std::string const& s, std::string const& prefix ); - bool endsWith( std::string const& s, std::string const& suffix ); - bool contains( std::string const& s, std::string const& infix ); - void toLowerInPlace( std::string& s ); - std::string toLower( std::string const& s ); - std::string trim( std::string const& str ); - bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); - - struct pluralise { - pluralise( std::size_t count, std::string const& label ); - - friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); - - std::size_t m_count; - std::string m_label; - }; - - struct SourceLineInfo { - - SourceLineInfo(); - SourceLineInfo( char const* _file, std::size_t _line ); - SourceLineInfo( SourceLineInfo const& other ); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - SourceLineInfo( SourceLineInfo && ) = default; - SourceLineInfo& operator = ( SourceLineInfo const& ) = default; - SourceLineInfo& operator = ( SourceLineInfo && ) = default; -# endif - bool empty() const; - bool operator == ( SourceLineInfo const& other ) const; - bool operator < ( SourceLineInfo const& other ) const; - - std::string file; - std::size_t line; - }; - - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); - - // This is just here to avoid compiler warnings with macro constants and boolean literals - inline bool isTrue( bool value ){ return value; } - inline bool alwaysTrue() { return true; } - inline bool alwaysFalse() { return false; } - - void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ); - - // Use this in variadic streaming macros to allow - // >> +StreamEndStop - // as well as - // >> stuff +StreamEndStop - struct StreamEndStop { - std::string operator+() { - return std::string(); - } - }; - template - T const& operator + ( T const& value, StreamEndStop ) { - return value; - } -} - -#define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) -#define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO ); - -#include - -namespace Catch { - - class NotImplementedException : public std::exception - { - public: - NotImplementedException( SourceLineInfo const& lineInfo ); - NotImplementedException( NotImplementedException const& ) {} - - virtual ~NotImplementedException() CATCH_NOEXCEPT {} - - virtual const char* what() const CATCH_NOEXCEPT; - - private: - std::string m_what; - SourceLineInfo m_lineInfo; - }; - -} // end namespace Catch - -/////////////////////////////////////////////////////////////////////////////// -#define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO ) - -// #included from: internal/catch_context.h -#define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED - -// #included from: catch_interfaces_generators.h -#define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED - -#include - -namespace Catch { - - struct IGeneratorInfo { - virtual ~IGeneratorInfo(); - virtual bool moveNext() = 0; - virtual std::size_t getCurrentIndex() const = 0; - }; - - struct IGeneratorsForTest { - virtual ~IGeneratorsForTest(); - - virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0; - virtual bool moveNext() = 0; - }; - - IGeneratorsForTest* createGeneratorsForTest(); - -} // end namespace Catch - -// #included from: catch_ptr.hpp -#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - // An intrusive reference counting smart pointer. - // T must implement addRef() and release() methods - // typically implementing the IShared interface - template - class Ptr { - public: - Ptr() : m_p( NULL ){} - Ptr( T* p ) : m_p( p ){ - if( m_p ) - m_p->addRef(); - } - Ptr( Ptr const& other ) : m_p( other.m_p ){ - if( m_p ) - m_p->addRef(); - } - ~Ptr(){ - if( m_p ) - m_p->release(); - } - void reset() { - if( m_p ) - m_p->release(); - m_p = NULL; - } - Ptr& operator = ( T* p ){ - Ptr temp( p ); - swap( temp ); - return *this; - } - Ptr& operator = ( Ptr const& other ){ - Ptr temp( other ); - swap( temp ); - return *this; - } - void swap( Ptr& other ) { std::swap( m_p, other.m_p ); } - T* get() { return m_p; } - const T* get() const{ return m_p; } - T& operator*() const { return *m_p; } - T* operator->() const { return m_p; } - bool operator !() const { return m_p == NULL; } - operator SafeBool::type() const { return SafeBool::makeSafe( m_p != NULL ); } - - private: - T* m_p; - }; - - struct IShared : NonCopyable { - virtual ~IShared(); - virtual void addRef() const = 0; - virtual void release() const = 0; - }; - - template - struct SharedImpl : T { - - SharedImpl() : m_rc( 0 ){} - - virtual void addRef() const { - ++m_rc; - } - virtual void release() const { - if( --m_rc == 0 ) - delete this; - } - - mutable unsigned int m_rc; - }; - -} // end namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#include -#include -#include - -namespace Catch { - - class TestCase; - class Stream; - struct IResultCapture; - struct IRunner; - struct IGeneratorsForTest; - struct IConfig; - - struct IContext - { - virtual ~IContext(); - - virtual IResultCapture* getResultCapture() = 0; - virtual IRunner* getRunner() = 0; - virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0; - virtual bool advanceGeneratorsForCurrentTest() = 0; - virtual Ptr getConfig() const = 0; - }; - - struct IMutableContext : IContext - { - virtual ~IMutableContext(); - virtual void setResultCapture( IResultCapture* resultCapture ) = 0; - virtual void setRunner( IRunner* runner ) = 0; - virtual void setConfig( Ptr const& config ) = 0; - }; - - IContext& getCurrentContext(); - IMutableContext& getCurrentMutableContext(); - void cleanUpContext(); - Stream createStream( std::string const& streamName ); - -} - -// #included from: internal/catch_test_registry.hpp -#define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED - -// #included from: catch_interfaces_testcase.h -#define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED - -#include - -namespace Catch { - - class TestSpec; - - struct ITestCase : IShared { - virtual void invoke () const = 0; - protected: - virtual ~ITestCase(); - }; - - class TestCase; - struct IConfig; - - struct ITestCaseRegistry { - virtual ~ITestCaseRegistry(); - virtual std::vector const& getAllTests() const = 0; - virtual void getFilteredTests( TestSpec const& testSpec, IConfig const& config, std::vector& matchingTestCases, bool negated = false ) const = 0; - - }; -} - -namespace Catch { - -template -class MethodTestCase : public SharedImpl { - -public: - MethodTestCase( void (C::*method)() ) : m_method( method ) {} - - virtual void invoke() const { - C obj; - (obj.*m_method)(); - } - -private: - virtual ~MethodTestCase() {} - - void (C::*m_method)(); -}; - -typedef void(*TestFunction)(); - -struct NameAndDesc { - NameAndDesc( const char* _name = "", const char* _description= "" ) - : name( _name ), description( _description ) - {} - - const char* name; - const char* description; -}; - -struct AutoReg { - - AutoReg( TestFunction function, - SourceLineInfo const& lineInfo, - NameAndDesc const& nameAndDesc ); - - template - AutoReg( void (C::*method)(), - char const* className, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ) { - registerTestCase( new MethodTestCase( method ), - className, - nameAndDesc, - lineInfo ); - } - - void registerTestCase( ITestCase* testCase, - char const* className, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ); - - ~AutoReg(); - -private: - AutoReg( AutoReg const& ); - void operator= ( AutoReg const& ); -}; - -} // end namespace Catch - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TESTCASE( ... ) \ - static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); }\ - static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )() - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... )\ - namespace{ \ - struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \ - void test(); \ - }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \ - } \ - void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test() - -#else - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \ - static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\ - static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )() - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\ - namespace{ \ - struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \ - void test(); \ - }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \ - } \ - void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test() - -#endif - -// #included from: internal/catch_capture.hpp -#define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED - -// #included from: catch_result_builder.h -#define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED - -// #included from: catch_result_type.h -#define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED - -namespace Catch { - - // ResultWas::OfType enum - struct ResultWas { enum OfType { - Unknown = -1, - Ok = 0, - Info = 1, - Warning = 2, - - FailureBit = 0x10, - - ExpressionFailed = FailureBit | 1, - ExplicitFailure = FailureBit | 2, - - Exception = 0x100 | FailureBit, - - ThrewException = Exception | 1, - DidntThrowException = Exception | 2, - - FatalErrorCondition = 0x200 | FailureBit - - }; }; - - inline bool isOk( ResultWas::OfType resultType ) { - return ( resultType & ResultWas::FailureBit ) == 0; - } - inline bool isJustInfo( int flags ) { - return flags == ResultWas::Info; - } - - // ResultDisposition::Flags enum - struct ResultDisposition { enum Flags { - Normal = 0x01, - - ContinueOnFailure = 0x02, // Failures fail test, but execution continues - FalseTest = 0x04, // Prefix expression with ! - SuppressFail = 0x08 // Failures are reported but do not fail the test - }; }; - - inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { - return static_cast( static_cast( lhs ) | static_cast( rhs ) ); - } - - inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } - inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } - inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } - -} // end namespace Catch - -// #included from: catch_assertionresult.h -#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED - -#include - -namespace Catch { - - struct AssertionInfo - { - AssertionInfo() {} - AssertionInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - std::string const& _capturedExpression, - ResultDisposition::Flags _resultDisposition ); - - std::string macroName; - SourceLineInfo lineInfo; - std::string capturedExpression; - ResultDisposition::Flags resultDisposition; - }; - - struct AssertionResultData - { - AssertionResultData() : resultType( ResultWas::Unknown ) {} - - std::string reconstructedExpression; - std::string message; - ResultWas::OfType resultType; - }; - - class AssertionResult { - public: - AssertionResult(); - AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); - ~AssertionResult(); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - AssertionResult( AssertionResult const& ) = default; - AssertionResult( AssertionResult && ) = default; - AssertionResult& operator = ( AssertionResult const& ) = default; - AssertionResult& operator = ( AssertionResult && ) = default; -# endif - - bool isOk() const; - bool succeeded() const; - ResultWas::OfType getResultType() const; - bool hasExpression() const; - bool hasMessage() const; - std::string getExpression() const; - std::string getExpressionInMacro() const; - bool hasExpandedExpression() const; - std::string getExpandedExpression() const; - std::string getMessage() const; - SourceLineInfo getSourceInfo() const; - std::string getTestMacroName() const; - - protected: - AssertionInfo m_info; - AssertionResultData m_resultData; - }; - -} // end namespace Catch - -namespace Catch { - - struct TestFailureException{}; - - template class ExpressionLhs; - - struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison; - - struct CopyableStream { - CopyableStream() {} - CopyableStream( CopyableStream const& other ) { - oss << other.oss.str(); - } - CopyableStream& operator=( CopyableStream const& other ) { - oss.str(""); - oss << other.oss.str(); - return *this; - } - std::ostringstream oss; - }; - - class ResultBuilder { - public: - ResultBuilder( char const* macroName, - SourceLineInfo const& lineInfo, - char const* capturedExpression, - ResultDisposition::Flags resultDisposition ); - - template - ExpressionLhs operator <= ( T const& operand ); - ExpressionLhs operator <= ( bool value ); - - template - ResultBuilder& operator << ( T const& value ) { - m_stream.oss << value; - return *this; - } - - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); - - ResultBuilder& setResultType( ResultWas::OfType result ); - ResultBuilder& setResultType( bool result ); - ResultBuilder& setLhs( std::string const& lhs ); - ResultBuilder& setRhs( std::string const& rhs ); - ResultBuilder& setOp( std::string const& op ); - - void endExpression(); - - std::string reconstructExpression() const; - AssertionResult build() const; - - void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal ); - void captureResult( ResultWas::OfType resultType ); - void captureExpression(); - void react(); - bool shouldDebugBreak() const; - bool allowThrows() const; - - private: - AssertionInfo m_assertionInfo; - AssertionResultData m_data; - struct ExprComponents { - ExprComponents() : testFalse( false ) {} - bool testFalse; - std::string lhs, rhs, op; - } m_exprComponents; - CopyableStream m_stream; - - bool m_shouldDebugBreak; - bool m_shouldThrow; - }; - -} // namespace Catch - -// Include after due to circular dependency: -// #included from: catch_expression_lhs.hpp -#define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED - -// #included from: catch_evaluate.hpp -#define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4389) // '==' : signed/unsigned mismatch -#endif - -#include - -namespace Catch { -namespace Internal { - - enum Operator { - IsEqualTo, - IsNotEqualTo, - IsLessThan, - IsGreaterThan, - IsLessThanOrEqualTo, - IsGreaterThanOrEqualTo - }; - - template struct OperatorTraits { static const char* getName(){ return "*error*"; } }; - template<> struct OperatorTraits { static const char* getName(){ return "=="; } }; - template<> struct OperatorTraits { static const char* getName(){ return "!="; } }; - template<> struct OperatorTraits { static const char* getName(){ return "<"; } }; - template<> struct OperatorTraits { static const char* getName(){ return ">"; } }; - template<> struct OperatorTraits { static const char* getName(){ return "<="; } }; - template<> struct OperatorTraits{ static const char* getName(){ return ">="; } }; - - template - inline T& opCast(T const& t) { return const_cast(t); } - -// nullptr_t support based on pull request #154 from Konstantin Baumann -#ifdef CATCH_CONFIG_CPP11_NULLPTR - inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } -#endif // CATCH_CONFIG_CPP11_NULLPTR - - // So the compare overloads can be operator agnostic we convey the operator as a template - // enum, which is used to specialise an Evaluator for doing the comparison. - template - class Evaluator{}; - - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs) { - return opCast( lhs ) == opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) != opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) < opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) > opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) >= opCast( rhs ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return opCast( lhs ) <= opCast( rhs ); - } - }; - - template - bool applyEvaluator( T1 const& lhs, T2 const& rhs ) { - return Evaluator::evaluate( lhs, rhs ); - } - - // This level of indirection allows us to specialise for integer types - // to avoid signed/ unsigned warnings - - // "base" overload - template - bool compare( T1 const& lhs, T2 const& rhs ) { - return Evaluator::evaluate( lhs, rhs ); - } - - // unsigned X to int - template bool compare( unsigned int lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned long lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned char lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - - // unsigned X to long - template bool compare( unsigned int lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned long lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned char lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - - // int to unsigned X - template bool compare( int lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( int lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( int lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // long to unsigned X - template bool compare( long lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // pointer to long (when comparing against NULL) - template bool compare( long lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, long rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } - - // pointer to int (when comparing against NULL) - template bool compare( int lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, int rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } - -#ifdef CATCH_CONFIG_CPP11_NULLPTR - // pointer to nullptr_t (when comparing against nullptr) - template bool compare( std::nullptr_t, T* rhs ) { - return Evaluator::evaluate( NULL, rhs ); - } - template bool compare( T* lhs, std::nullptr_t ) { - return Evaluator::evaluate( lhs, NULL ); - } -#endif // CATCH_CONFIG_CPP11_NULLPTR - -} // end of namespace Internal -} // end of namespace Catch - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -// #included from: catch_tostring.h -#define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED - -#include -#include -#include -#include -#include - -#ifdef __OBJC__ -// #included from: catch_objc_arc.hpp -#define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED - -#import - -#ifdef __has_feature -#define CATCH_ARC_ENABLED __has_feature(objc_arc) -#else -#define CATCH_ARC_ENABLED 0 -#endif - -void arcSafeRelease( NSObject* obj ); -id performOptionalSelector( id obj, SEL sel ); - -#if !CATCH_ARC_ENABLED -inline void arcSafeRelease( NSObject* obj ) { - [obj release]; -} -inline id performOptionalSelector( id obj, SEL sel ) { - if( [obj respondsToSelector: sel] ) - return [obj performSelector: sel]; - return nil; -} -#define CATCH_UNSAFE_UNRETAINED -#define CATCH_ARC_STRONG -#else -inline void arcSafeRelease( NSObject* ){} -inline id performOptionalSelector( id obj, SEL sel ) { -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-performSelector-leaks" -#endif - if( [obj respondsToSelector: sel] ) - return [obj performSelector: sel]; -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - return nil; -} -#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained -#define CATCH_ARC_STRONG __strong -#endif - -#endif - -#ifdef CATCH_CONFIG_CPP11_TUPLE -#include -#endif - -#ifdef CATCH_CONFIG_CPP11_IS_ENUM -#include -#endif - -namespace Catch { - -// Why we're here. -template -std::string toString( T const& value ); - -// Built in overloads - -std::string toString( std::string const& value ); -std::string toString( std::wstring const& value ); -std::string toString( const char* const value ); -std::string toString( char* const value ); -std::string toString( const wchar_t* const value ); -std::string toString( wchar_t* const value ); -std::string toString( int value ); -std::string toString( unsigned long value ); -std::string toString( unsigned int value ); -std::string toString( const double value ); -std::string toString( const float value ); -std::string toString( bool value ); -std::string toString( char value ); -std::string toString( signed char value ); -std::string toString( unsigned char value ); - -#ifdef CATCH_CONFIG_CPP11_NULLPTR -std::string toString( std::nullptr_t ); -#endif - -#ifdef __OBJC__ - std::string toString( NSString const * const& nsstring ); - std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ); - std::string toString( NSObject* const& nsObject ); -#endif - -namespace Detail { - - extern std::string unprintableString; - - struct BorgType { - template BorgType( T const& ); - }; - - struct TrueType { char sizer[1]; }; - struct FalseType { char sizer[2]; }; - - TrueType& testStreamable( std::ostream& ); - FalseType testStreamable( FalseType ); - - FalseType operator<<( std::ostream const&, BorgType const& ); - - template - struct IsStreamInsertable { - static std::ostream &s; - static T const&t; - enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) }; - }; - -#if defined(CATCH_CONFIG_CPP11_IS_ENUM) - template::value - > - struct EnumStringMaker - { - static std::string convert( T const& ) { return unprintableString; } - }; - - template - struct EnumStringMaker - { - static std::string convert( T const& v ) - { - return ::Catch::toString( - static_cast::type>(v) - ); - } - }; -#endif - template - struct StringMakerBase { -#if defined(CATCH_CONFIG_CPP11_IS_ENUM) - template - static std::string convert( T const& v ) - { - return EnumStringMaker::convert( v ); - } -#else - template - static std::string convert( T const& ) { return unprintableString; } -#endif - }; - - template<> - struct StringMakerBase { - template - static std::string convert( T const& _value ) { - std::ostringstream oss; - oss << _value; - return oss.str(); - } - }; - - std::string rawMemoryToString( const void *object, std::size_t size ); - - template - inline std::string rawMemoryToString( const T& object ) { - return rawMemoryToString( &object, sizeof(object) ); - } - -} // end namespace Detail - -template -struct StringMaker : - Detail::StringMakerBase::value> {}; - -template -struct StringMaker { - template - static std::string convert( U* p ) { - if( !p ) - return INTERNAL_CATCH_STRINGIFY( NULL ); - else - return Detail::rawMemoryToString( p ); - } -}; - -template -struct StringMaker { - static std::string convert( R C::* p ) { - if( !p ) - return INTERNAL_CATCH_STRINGIFY( NULL ); - else - return Detail::rawMemoryToString( p ); - } -}; - -namespace Detail { - template - std::string rangeToString( InputIterator first, InputIterator last ); -} - -//template -//struct StringMaker > { -// static std::string convert( std::vector const& v ) { -// return Detail::rangeToString( v.begin(), v.end() ); -// } -//}; - -template -std::string toString( std::vector const& v ) { - return Detail::rangeToString( v.begin(), v.end() ); -} - -#ifdef CATCH_CONFIG_CPP11_TUPLE - -// toString for tuples -namespace TupleDetail { - template< - typename Tuple, - std::size_t N = 0, - bool = (N < std::tuple_size::value) - > - struct ElementPrinter { - static void print( const Tuple& tuple, std::ostream& os ) - { - os << ( N ? ", " : " " ) - << Catch::toString(std::get(tuple)); - ElementPrinter::print(tuple,os); - } - }; - - template< - typename Tuple, - std::size_t N - > - struct ElementPrinter { - static void print( const Tuple&, std::ostream& ) {} - }; - -} - -template -struct StringMaker> { - - static std::string convert( const std::tuple& tuple ) - { - std::ostringstream os; - os << '{'; - TupleDetail::ElementPrinter>::print( tuple, os ); - os << " }"; - return os.str(); - } -}; -#endif // CATCH_CONFIG_CPP11_TUPLE - -namespace Detail { - template - std::string makeString( T const& value ) { - return StringMaker::convert( value ); - } -} // end namespace Detail - -/// \brief converts any type to a string -/// -/// The default template forwards on to ostringstream - except when an -/// ostringstream overload does not exist - in which case it attempts to detect -/// that and writes {?}. -/// Overload (not specialise) this template for custom typs that you don't want -/// to provide an ostream overload for. -template -std::string toString( T const& value ) { - return StringMaker::convert( value ); -} - - namespace Detail { - template - std::string rangeToString( InputIterator first, InputIterator last ) { - std::ostringstream oss; - oss << "{ "; - if( first != last ) { - oss << Catch::toString( *first ); - for( ++first ; first != last ; ++first ) - oss << ", " << Catch::toString( *first ); - } - oss << " }"; - return oss.str(); - } -} - -} // end namespace Catch - -namespace Catch { - -// Wraps the LHS of an expression and captures the operator and RHS (if any) - -// wrapping them all in a ResultBuilder object -template -class ExpressionLhs { - ExpressionLhs& operator = ( ExpressionLhs const& ); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - ExpressionLhs& operator = ( ExpressionLhs && ) = delete; -# endif - -public: - ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ) {} -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - ExpressionLhs( ExpressionLhs const& ) = default; - ExpressionLhs( ExpressionLhs && ) = default; -# endif - - template - ResultBuilder& operator == ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator != ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator < ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator > ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator <= ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - ResultBuilder& operator >= ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - ResultBuilder& operator == ( bool rhs ) { - return captureExpression( rhs ); - } - - ResultBuilder& operator != ( bool rhs ) { - return captureExpression( rhs ); - } - - void endExpression() { - bool value = m_lhs ? true : false; - m_rb - .setLhs( Catch::toString( value ) ) - .setResultType( value ) - .endExpression(); - } - - // Only simple binary expressions are allowed on the LHS. - // If more complex compositions are required then place the sub expression in parentheses - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); - -private: - template - ResultBuilder& captureExpression( RhsT const& rhs ) { - return m_rb - .setResultType( Internal::compare( m_lhs, rhs ) ) - .setLhs( Catch::toString( m_lhs ) ) - .setRhs( Catch::toString( rhs ) ) - .setOp( Internal::OperatorTraits::getName() ); - } - -private: - ResultBuilder& m_rb; - T m_lhs; -}; - -} // end namespace Catch - - -namespace Catch { - - template - inline ExpressionLhs ResultBuilder::operator <= ( T const& operand ) { - return ExpressionLhs( *this, operand ); - } - - inline ExpressionLhs ResultBuilder::operator <= ( bool value ) { - return ExpressionLhs( *this, value ); - } - -} // namespace Catch - -// #included from: catch_message.h -#define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED - -#include - -namespace Catch { - - struct MessageInfo { - MessageInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - ResultWas::OfType _type ); - - std::string macroName; - SourceLineInfo lineInfo; - ResultWas::OfType type; - std::string message; - unsigned int sequence; - - bool operator == ( MessageInfo const& other ) const { - return sequence == other.sequence; - } - bool operator < ( MessageInfo const& other ) const { - return sequence < other.sequence; - } - private: - static unsigned int globalCount; - }; - - struct MessageBuilder { - MessageBuilder( std::string const& macroName, - SourceLineInfo const& lineInfo, - ResultWas::OfType type ) - : m_info( macroName, lineInfo, type ) - {} - - template - MessageBuilder& operator << ( T const& value ) { - m_stream << value; - return *this; - } - - MessageInfo m_info; - std::ostringstream m_stream; - }; - - class ScopedMessage { - public: - ScopedMessage( MessageBuilder const& builder ); - ScopedMessage( ScopedMessage const& other ); - ~ScopedMessage(); - - MessageInfo m_info; - }; - -} // end namespace Catch - -// #included from: catch_interfaces_capture.h -#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED - -#include - -namespace Catch { - - class TestCase; - class AssertionResult; - struct AssertionInfo; - struct SectionInfo; - struct MessageInfo; - class ScopedMessageBuilder; - struct Counts; - - struct IResultCapture { - - virtual ~IResultCapture(); - - virtual void assertionEnded( AssertionResult const& result ) = 0; - virtual bool sectionStarted( SectionInfo const& sectionInfo, - Counts& assertions ) = 0; - virtual void sectionEnded( SectionInfo const& name, Counts const& assertions, double _durationInSeconds ) = 0; - virtual void pushScopedMessage( MessageInfo const& message ) = 0; - virtual void popScopedMessage( MessageInfo const& message ) = 0; - - virtual std::string getCurrentTestName() const = 0; - virtual const AssertionResult* getLastResult() const = 0; - - virtual void handleFatalErrorCondition( std::string const& message ) = 0; - }; - - IResultCapture& getResultCapture(); -} - -// #included from: catch_debugger.h -#define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED - -// #included from: catch_platform.h -#define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED - -#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -#define CATCH_PLATFORM_MAC -#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#define CATCH_PLATFORM_IPHONE -#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) -#define CATCH_PLATFORM_WINDOWS -#endif - -#include - -namespace Catch{ - - bool isDebuggerActive(); - void writeToDebugConsole( std::string const& text ); -} - -#ifdef CATCH_PLATFORM_MAC - - // The following code snippet based on: - // http://cocoawithlove.com/2008/03/break-into-debugger.html - #ifdef DEBUG - #if defined(__ppc64__) || defined(__ppc__) - #define CATCH_BREAK_INTO_DEBUGGER() \ - if( Catch::isDebuggerActive() ) { \ - __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ - : : : "memory","r0","r3","r4" ); \ - } - #else - #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__("int $3\n" : : );} - #endif - #endif - -#elif defined(_MSC_VER) - #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); } -#elif defined(__MINGW32__) - extern "C" __declspec(dllimport) void __stdcall DebugBreak(); - #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); } -#endif - -#ifndef CATCH_BREAK_INTO_DEBUGGER -#define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); -#endif - -// #included from: catch_interfaces_runner.h -#define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED - -namespace Catch { - class TestCase; - - struct IRunner { - virtual ~IRunner(); - virtual bool aborting() const = 0; - }; -} - -/////////////////////////////////////////////////////////////////////////////// -// In the event of a failure works out if the debugger needs to be invoked -// and/or an exception thrown and takes appropriate action. -// This needs to be done as a macro so the debugger will stop in the user -// source code rather than in Catch library code -#define INTERNAL_CATCH_REACT( resultBuilder ) \ - if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \ - resultBuilder.react(); - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - try { \ - ( __catchResult <= expr ).endExpression(); \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( Catch::ResultDisposition::Normal ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::isTrue( false && (expr) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \ - INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ - if( Catch::getResultCapture().getLastResult()->succeeded() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_ELSE( expr, resultDisposition, macroName ) \ - INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ - if( !Catch::getResultCapture().getLastResult()->succeeded() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_NO_THROW( expr, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - try { \ - expr; \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( resultDisposition ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS( expr, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - if( __catchResult.allowThrows() ) \ - try { \ - expr; \ - __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ - } \ - catch( ... ) { \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - } \ - else \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - if( __catchResult.allowThrows() ) \ - try { \ - expr; \ - __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ - } \ - catch( exceptionType ) { \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( resultDisposition ); \ - } \ - else \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, ... ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ - __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ - __catchResult.captureResult( messageType ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) -#else - #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, log ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ - __catchResult << log + ::Catch::StreamEndStop(); \ - __catchResult.captureResult( messageType ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) -#endif - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_INFO( log, macroName ) \ - Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log; - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CHECK_THAT( arg, matcher, resultDisposition, macroName ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg " " #matcher, resultDisposition ); \ - try { \ - std::string matcherAsString = ::Catch::Matchers::matcher.toString(); \ - __catchResult \ - .setLhs( Catch::toString( arg ) ) \ - .setRhs( matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString ) \ - .setOp( "matches" ) \ - .setResultType( ::Catch::Matchers::matcher.match( arg ) ); \ - __catchResult.captureExpression(); \ - } catch( ... ) { \ - __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -// #included from: internal/catch_section.h -#define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED - -// #included from: catch_section_info.h -#define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED - -namespace Catch { - - struct SectionInfo { - SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name, - std::string const& _description = std::string() ); - - std::string name; - std::string description; - SourceLineInfo lineInfo; - }; - -} // end namespace Catch - -// #included from: catch_totals.hpp -#define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED - -#include - -namespace Catch { - - struct Counts { - Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {} - - Counts operator - ( Counts const& other ) const { - Counts diff; - diff.passed = passed - other.passed; - diff.failed = failed - other.failed; - diff.failedButOk = failedButOk - other.failedButOk; - return diff; - } - Counts& operator += ( Counts const& other ) { - passed += other.passed; - failed += other.failed; - failedButOk += other.failedButOk; - return *this; - } - - std::size_t total() const { - return passed + failed + failedButOk; - } - bool allPassed() const { - return failed == 0 && failedButOk == 0; - } - bool allOk() const { - return failed == 0; - } - - std::size_t passed; - std::size_t failed; - std::size_t failedButOk; - }; - - struct Totals { - - Totals operator - ( Totals const& other ) const { - Totals diff; - diff.assertions = assertions - other.assertions; - diff.testCases = testCases - other.testCases; - return diff; - } - - Totals delta( Totals const& prevTotals ) const { - Totals diff = *this - prevTotals; - if( diff.assertions.failed > 0 ) - ++diff.testCases.failed; - else if( diff.assertions.failedButOk > 0 ) - ++diff.testCases.failedButOk; - else - ++diff.testCases.passed; - return diff; - } - - Totals& operator += ( Totals const& other ) { - assertions += other.assertions; - testCases += other.testCases; - return *this; - } - - Counts assertions; - Counts testCases; - }; -} - -// #included from: catch_timer.h -#define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED - -#ifdef CATCH_PLATFORM_WINDOWS -typedef unsigned long long uint64_t; -#else -#include -#endif - -namespace Catch { - - class Timer { - public: - Timer() : m_ticks( 0 ) {} - void start(); - unsigned int getElapsedMicroseconds() const; - unsigned int getElapsedMilliseconds() const; - double getElapsedSeconds() const; - - private: - uint64_t m_ticks; - }; - -} // namespace Catch - -#include - -namespace Catch { - - class Section : NonCopyable { - public: - Section( SectionInfo const& info ); - ~Section(); - - // This indicates whether the section should be executed or not - operator bool() const; - - private: - SectionInfo m_info; - - std::string m_name; - Counts m_assertions; - bool m_sectionIncluded; - Timer m_timer; - }; - -} // end namespace Catch - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define INTERNAL_CATCH_SECTION( ... ) \ - if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) -#else - #define INTERNAL_CATCH_SECTION( name, desc ) \ - if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) ) -#endif - -// #included from: internal/catch_generators.hpp -#define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED - -#include -#include -#include -#include - -namespace Catch { - -template -struct IGenerator { - virtual ~IGenerator() {} - virtual T getValue( std::size_t index ) const = 0; - virtual std::size_t size () const = 0; -}; - -template -class BetweenGenerator : public IGenerator { -public: - BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){} - - virtual T getValue( std::size_t index ) const { - return m_from+static_cast( index ); - } - - virtual std::size_t size() const { - return static_cast( 1+m_to-m_from ); - } - -private: - - T m_from; - T m_to; -}; - -template -class ValuesGenerator : public IGenerator { -public: - ValuesGenerator(){} - - void add( T value ) { - m_values.push_back( value ); - } - - virtual T getValue( std::size_t index ) const { - return m_values[index]; - } - - virtual std::size_t size() const { - return m_values.size(); - } - -private: - std::vector m_values; -}; - -template -class CompositeGenerator { -public: - CompositeGenerator() : m_totalSize( 0 ) {} - - // *** Move semantics, similar to auto_ptr *** - CompositeGenerator( CompositeGenerator& other ) - : m_fileInfo( other.m_fileInfo ), - m_totalSize( 0 ) - { - move( other ); - } - - CompositeGenerator& setFileInfo( const char* fileInfo ) { - m_fileInfo = fileInfo; - return *this; - } - - ~CompositeGenerator() { - deleteAll( m_composed ); - } - - operator T () const { - size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize ); - - typename std::vector*>::const_iterator it = m_composed.begin(); - typename std::vector*>::const_iterator itEnd = m_composed.end(); - for( size_t index = 0; it != itEnd; ++it ) - { - const IGenerator* generator = *it; - if( overallIndex >= index && overallIndex < index + generator->size() ) - { - return generator->getValue( overallIndex-index ); - } - index += generator->size(); - } - CATCH_INTERNAL_ERROR( "Indexed past end of generated range" ); - return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so - } - - void add( const IGenerator* generator ) { - m_totalSize += generator->size(); - m_composed.push_back( generator ); - } - - CompositeGenerator& then( CompositeGenerator& other ) { - move( other ); - return *this; - } - - CompositeGenerator& then( T value ) { - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( value ); - add( valuesGen ); - return *this; - } - -private: - - void move( CompositeGenerator& other ) { - std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) ); - m_totalSize += other.m_totalSize; - other.m_composed.clear(); - } - - std::vector*> m_composed; - std::string m_fileInfo; - size_t m_totalSize; -}; - -namespace Generators -{ - template - CompositeGenerator between( T from, T to ) { - CompositeGenerator generators; - generators.add( new BetweenGenerator( from, to ) ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2 ) { - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - generators.add( valuesGen ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2, T val3 ){ - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - valuesGen->add( val3 ); - generators.add( valuesGen ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2, T val3, T val4 ) { - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - valuesGen->add( val3 ); - valuesGen->add( val4 ); - generators.add( valuesGen ); - return generators; - } - -} // end namespace Generators - -using namespace Generators; - -} // end namespace Catch - -#define INTERNAL_CATCH_LINESTR2( line ) #line -#define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line ) - -#define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" ) - -// #included from: internal/catch_interfaces_exception.h -#define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED - -#include -// #included from: catch_interfaces_registry_hub.h -#define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED - -#include - -namespace Catch { - - class TestCase; - struct ITestCaseRegistry; - struct IExceptionTranslatorRegistry; - struct IExceptionTranslator; - struct IReporterRegistry; - struct IReporterFactory; - - struct IRegistryHub { - virtual ~IRegistryHub(); - - virtual IReporterRegistry const& getReporterRegistry() const = 0; - virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; - virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; - }; - - struct IMutableRegistryHub { - virtual ~IMutableRegistryHub(); - virtual void registerReporter( std::string const& name, IReporterFactory* factory ) = 0; - virtual void registerTest( TestCase const& testInfo ) = 0; - virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; - }; - - IRegistryHub& getRegistryHub(); - IMutableRegistryHub& getMutableRegistryHub(); - void cleanUp(); - std::string translateActiveException(); - -} - - -namespace Catch { - - typedef std::string(*exceptionTranslateFunction)(); - - struct IExceptionTranslator { - virtual ~IExceptionTranslator(); - virtual std::string translate() const = 0; - }; - - struct IExceptionTranslatorRegistry { - virtual ~IExceptionTranslatorRegistry(); - - virtual std::string translateActiveException() const = 0; - }; - - class ExceptionTranslatorRegistrar { - template - class ExceptionTranslator : public IExceptionTranslator { - public: - - ExceptionTranslator( std::string(*translateFunction)( T& ) ) - : m_translateFunction( translateFunction ) - {} - - virtual std::string translate() const { - try { - throw; - } - catch( T& ex ) { - return m_translateFunction( ex ); - } - } - - protected: - std::string(*m_translateFunction)( T& ); - }; - - public: - template - ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { - getMutableRegistryHub().registerTranslator - ( new ExceptionTranslator( translateFunction ) ); - } - }; -} - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) \ - static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature ); \ - namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ) ); }\ - static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature ) - -// #included from: internal/catch_approx.hpp -#define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED - -#include -#include - -namespace Catch { -namespace Detail { - - class Approx { - public: - explicit Approx ( double value ) - : m_epsilon( std::numeric_limits::epsilon()*100 ), - m_scale( 1.0 ), - m_value( value ) - {} - - Approx( Approx const& other ) - : m_epsilon( other.m_epsilon ), - m_scale( other.m_scale ), - m_value( other.m_value ) - {} - - static Approx custom() { - return Approx( 0 ); - } - - Approx operator()( double value ) { - Approx approx( value ); - approx.epsilon( m_epsilon ); - approx.scale( m_scale ); - return approx; - } - - friend bool operator == ( double lhs, Approx const& rhs ) { - // Thanks to Richard Harris for his help refining this formula - return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) ); - } - - friend bool operator == ( Approx const& lhs, double rhs ) { - return operator==( rhs, lhs ); - } - - friend bool operator != ( double lhs, Approx const& rhs ) { - return !operator==( lhs, rhs ); - } - - friend bool operator != ( Approx const& lhs, double rhs ) { - return !operator==( rhs, lhs ); - } - - Approx& epsilon( double newEpsilon ) { - m_epsilon = newEpsilon; - return *this; - } - - Approx& scale( double newScale ) { - m_scale = newScale; - return *this; - } - - std::string toString() const { - std::ostringstream oss; - oss << "Approx( " << Catch::toString( m_value ) << " )"; - return oss.str(); - } - - private: - double m_epsilon; - double m_scale; - double m_value; - }; -} - -template<> -inline std::string toString( Detail::Approx const& value ) { - return value.toString(); -} - -} // end namespace Catch - -// #included from: internal/catch_matchers.hpp -#define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED - -namespace Catch { -namespace Matchers { - namespace Impl { - - template - struct Matcher : SharedImpl - { - typedef ExpressionT ExpressionType; - - virtual ~Matcher() {} - virtual Ptr clone() const = 0; - virtual bool match( ExpressionT const& expr ) const = 0; - virtual std::string toString() const = 0; - }; - - template - struct MatcherImpl : Matcher { - - virtual Ptr > clone() const { - return Ptr >( new DerivedT( static_cast( *this ) ) ); - } - }; - - namespace Generic { - - template - class AllOf : public MatcherImpl, ExpressionT> { - public: - - AllOf() {} - AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {} - - AllOf& add( Matcher const& matcher ) { - m_matchers.push_back( matcher.clone() ); - return *this; - } - virtual bool match( ExpressionT const& expr ) const - { - for( std::size_t i = 0; i < m_matchers.size(); ++i ) - if( !m_matchers[i]->match( expr ) ) - return false; - return true; - } - virtual std::string toString() const { - std::ostringstream oss; - oss << "( "; - for( std::size_t i = 0; i < m_matchers.size(); ++i ) { - if( i != 0 ) - oss << " and "; - oss << m_matchers[i]->toString(); - } - oss << " )"; - return oss.str(); - } - - private: - std::vector > > m_matchers; - }; - - template - class AnyOf : public MatcherImpl, ExpressionT> { - public: - - AnyOf() {} - AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {} - - AnyOf& add( Matcher const& matcher ) { - m_matchers.push_back( matcher.clone() ); - return *this; - } - virtual bool match( ExpressionT const& expr ) const - { - for( std::size_t i = 0; i < m_matchers.size(); ++i ) - if( m_matchers[i]->match( expr ) ) - return true; - return false; - } - virtual std::string toString() const { - std::ostringstream oss; - oss << "( "; - for( std::size_t i = 0; i < m_matchers.size(); ++i ) { - if( i != 0 ) - oss << " or "; - oss << m_matchers[i]->toString(); - } - oss << " )"; - return oss.str(); - } - - private: - std::vector > > m_matchers; - }; - - } - - namespace StdString { - - inline std::string makeString( std::string const& str ) { return str; } - inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); } - - struct Equals : MatcherImpl { - Equals( std::string const& str ) : m_str( str ){} - Equals( Equals const& other ) : m_str( other.m_str ){} - - virtual ~Equals(); - - virtual bool match( std::string const& expr ) const { - return m_str == expr; - } - virtual std::string toString() const { - return "equals: \"" + m_str + "\""; - } - - std::string m_str; - }; - - struct Contains : MatcherImpl { - Contains( std::string const& substr ) : m_substr( substr ){} - Contains( Contains const& other ) : m_substr( other.m_substr ){} - - virtual ~Contains(); - - virtual bool match( std::string const& expr ) const { - return expr.find( m_substr ) != std::string::npos; - } - virtual std::string toString() const { - return "contains: \"" + m_substr + "\""; - } - - std::string m_substr; - }; - - struct StartsWith : MatcherImpl { - StartsWith( std::string const& substr ) : m_substr( substr ){} - StartsWith( StartsWith const& other ) : m_substr( other.m_substr ){} - - virtual ~StartsWith(); - - virtual bool match( std::string const& expr ) const { - return expr.find( m_substr ) == 0; - } - virtual std::string toString() const { - return "starts with: \"" + m_substr + "\""; - } - - std::string m_substr; - }; - - struct EndsWith : MatcherImpl { - EndsWith( std::string const& substr ) : m_substr( substr ){} - EndsWith( EndsWith const& other ) : m_substr( other.m_substr ){} - - virtual ~EndsWith(); - - virtual bool match( std::string const& expr ) const { - return expr.find( m_substr ) == expr.size() - m_substr.size(); - } - virtual std::string toString() const { - return "ends with: \"" + m_substr + "\""; - } - - std::string m_substr; - }; - } // namespace StdString - } // namespace Impl - - // The following functions create the actual matcher objects. - // This allows the types to be inferred - template - inline Impl::Generic::AllOf AllOf( Impl::Matcher const& m1, - Impl::Matcher const& m2 ) { - return Impl::Generic::AllOf().add( m1 ).add( m2 ); - } - template - inline Impl::Generic::AllOf AllOf( Impl::Matcher const& m1, - Impl::Matcher const& m2, - Impl::Matcher const& m3 ) { - return Impl::Generic::AllOf().add( m1 ).add( m2 ).add( m3 ); - } - template - inline Impl::Generic::AnyOf AnyOf( Impl::Matcher const& m1, - Impl::Matcher const& m2 ) { - return Impl::Generic::AnyOf().add( m1 ).add( m2 ); - } - template - inline Impl::Generic::AnyOf AnyOf( Impl::Matcher const& m1, - Impl::Matcher const& m2, - Impl::Matcher const& m3 ) { - return Impl::Generic::AnyOf().add( m1 ).add( m2 ).add( m3 ); - } - - inline Impl::StdString::Equals Equals( std::string const& str ) { - return Impl::StdString::Equals( str ); - } - inline Impl::StdString::Equals Equals( const char* str ) { - return Impl::StdString::Equals( Impl::StdString::makeString( str ) ); - } - inline Impl::StdString::Contains Contains( std::string const& substr ) { - return Impl::StdString::Contains( substr ); - } - inline Impl::StdString::Contains Contains( const char* substr ) { - return Impl::StdString::Contains( Impl::StdString::makeString( substr ) ); - } - inline Impl::StdString::StartsWith StartsWith( std::string const& substr ) { - return Impl::StdString::StartsWith( substr ); - } - inline Impl::StdString::StartsWith StartsWith( const char* substr ) { - return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) ); - } - inline Impl::StdString::EndsWith EndsWith( std::string const& substr ) { - return Impl::StdString::EndsWith( substr ); - } - inline Impl::StdString::EndsWith EndsWith( const char* substr ) { - return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) ); - } - -} // namespace Matchers - -using namespace Matchers; - -} // namespace Catch - -// #included from: internal/catch_interfaces_tag_alias_registry.h -#define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED - -// #included from: catch_tag_alias.h -#define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED - -#include - -namespace Catch { - - struct TagAlias { - TagAlias( std::string _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} - - std::string tag; - SourceLineInfo lineInfo; - }; - - struct RegistrarForTagAliases { - RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); - }; - -} // end namespace Catch - -#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } -// #included from: catch_option.hpp -#define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED - -namespace Catch { - - // An optional type - template - class Option { - public: - Option() : nullableValue( NULL ) {} - Option( T const& _value ) - : nullableValue( new( storage ) T( _value ) ) - {} - Option( Option const& _other ) - : nullableValue( _other ? new( storage ) T( *_other ) : NULL ) - {} - - ~Option() { - reset(); - } - - Option& operator= ( Option const& _other ) { - if( &_other != this ) { - reset(); - if( _other ) - nullableValue = new( storage ) T( *_other ); - } - return *this; - } - Option& operator = ( T const& _value ) { - reset(); - nullableValue = new( storage ) T( _value ); - return *this; - } - - void reset() { - if( nullableValue ) - nullableValue->~T(); - nullableValue = NULL; - } - - T& operator*() { return *nullableValue; } - T const& operator*() const { return *nullableValue; } - T* operator->() { return nullableValue; } - const T* operator->() const { return nullableValue; } - - T valueOr( T const& defaultValue ) const { - return nullableValue ? *nullableValue : defaultValue; - } - - bool some() const { return nullableValue != NULL; } - bool none() const { return nullableValue == NULL; } - - bool operator !() const { return nullableValue == NULL; } - operator SafeBool::type() const { - return SafeBool::makeSafe( some() ); - } - - private: - T* nullableValue; - char storage[sizeof(T)]; - }; - -} // end namespace Catch - -namespace Catch { - - struct ITagAliasRegistry { - virtual ~ITagAliasRegistry(); - virtual Option find( std::string const& alias ) const = 0; - virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; - - static ITagAliasRegistry const& get(); - }; - -} // end namespace Catch - -// These files are included here so the single_include script doesn't put them -// in the conditionally compiled sections -// #included from: internal/catch_test_case_info.h -#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED - -#include -#include - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - struct ITestCase; - - struct TestCaseInfo { - enum SpecialProperties{ - None = 0, - IsHidden = 1 << 1, - ShouldFail = 1 << 2, - MayFail = 1 << 3, - Throws = 1 << 4 - }; - - TestCaseInfo( std::string const& _name, - std::string const& _className, - std::string const& _description, - std::set const& _tags, - SourceLineInfo const& _lineInfo ); - - TestCaseInfo( TestCaseInfo const& other ); - - bool isHidden() const; - bool throws() const; - bool okToFail() const; - bool expectedToFail() const; - - std::string name; - std::string className; - std::string description; - std::set tags; - std::set lcaseTags; - std::string tagsAsString; - SourceLineInfo lineInfo; - SpecialProperties properties; - }; - - class TestCase : public TestCaseInfo { - public: - - TestCase( ITestCase* testCase, TestCaseInfo const& info ); - TestCase( TestCase const& other ); - - TestCase withName( std::string const& _newName ) const; - - void invoke() const; - - TestCaseInfo const& getTestCaseInfo() const; - - void swap( TestCase& other ); - bool operator == ( TestCase const& other ) const; - bool operator < ( TestCase const& other ) const; - TestCase& operator = ( TestCase const& other ); - - private: - Ptr test; - }; - - TestCase makeTestCase( ITestCase* testCase, - std::string const& className, - std::string const& name, - std::string const& description, - SourceLineInfo const& lineInfo ); -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - - -#ifdef __OBJC__ -// #included from: internal/catch_objc.hpp -#define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED - -#import - -#include - -// NB. Any general catch headers included here must be included -// in catch.hpp first to make sure they are included by the single -// header for non obj-usage - -/////////////////////////////////////////////////////////////////////////////// -// This protocol is really only here for (self) documenting purposes, since -// all its methods are optional. -@protocol OcFixture - -@optional - --(void) setUp; --(void) tearDown; - -@end - -namespace Catch { - - class OcMethod : public SharedImpl { - - public: - OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} - - virtual void invoke() const { - id obj = [[m_cls alloc] init]; - - performOptionalSelector( obj, @selector(setUp) ); - performOptionalSelector( obj, m_sel ); - performOptionalSelector( obj, @selector(tearDown) ); - - arcSafeRelease( obj ); - } - private: - virtual ~OcMethod() {} - - Class m_cls; - SEL m_sel; - }; - - namespace Detail{ - - inline std::string getAnnotation( Class cls, - std::string const& annotationName, - std::string const& testCaseName ) { - NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; - SEL sel = NSSelectorFromString( selStr ); - arcSafeRelease( selStr ); - id value = performOptionalSelector( cls, sel ); - if( value ) - return [(NSString*)value UTF8String]; - return ""; - } - } - - inline size_t registerTestMethods() { - size_t noTestMethods = 0; - int noClasses = objc_getClassList( NULL, 0 ); - - Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); - objc_getClassList( classes, noClasses ); - - for( int c = 0; c < noClasses; c++ ) { - Class cls = classes[c]; - { - u_int count; - Method* methods = class_copyMethodList( cls, &count ); - for( u_int m = 0; m < count ; m++ ) { - SEL selector = method_getName(methods[m]); - std::string methodName = sel_getName(selector); - if( startsWith( methodName, "Catch_TestCase_" ) ) { - std::string testCaseName = methodName.substr( 15 ); - std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); - std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); - const char* className = class_getName( cls ); - - getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) ); - noTestMethods++; - } - } - free(methods); - } - } - return noTestMethods; - } - - namespace Matchers { - namespace Impl { - namespace NSStringMatchers { - - template - struct StringHolder : MatcherImpl{ - StringHolder( NSString* substr ) : m_substr( [substr copy] ){} - StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} - StringHolder() { - arcSafeRelease( m_substr ); - } - - NSString* m_substr; - }; - - struct Equals : StringHolder { - Equals( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( ExpressionType const& str ) const { - return (str != nil || m_substr == nil ) && - [str isEqualToString:m_substr]; - } - - virtual std::string toString() const { - return "equals string: " + Catch::toString( m_substr ); - } - }; - - struct Contains : StringHolder { - Contains( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( ExpressionType const& str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location != NSNotFound; - } - - virtual std::string toString() const { - return "contains string: " + Catch::toString( m_substr ); - } - }; - - struct StartsWith : StringHolder { - StartsWith( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( ExpressionType const& str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location == 0; - } - - virtual std::string toString() const { - return "starts with: " + Catch::toString( m_substr ); - } - }; - struct EndsWith : StringHolder { - EndsWith( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( ExpressionType const& str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location == [str length] - [m_substr length]; - } - - virtual std::string toString() const { - return "ends with: " + Catch::toString( m_substr ); - } - }; - - } // namespace NSStringMatchers - } // namespace Impl - - inline Impl::NSStringMatchers::Equals - Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } - - inline Impl::NSStringMatchers::Contains - Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } - - inline Impl::NSStringMatchers::StartsWith - StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } - - inline Impl::NSStringMatchers::EndsWith - EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } - - } // namespace Matchers - - using namespace Matchers; - -} // namespace Catch - -/////////////////////////////////////////////////////////////////////////////// -#define OC_TEST_CASE( name, desc )\ -+(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \ -{\ -return @ name; \ -}\ -+(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \ -{ \ -return @ desc; \ -} \ --(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test ) - -#endif - -#ifdef CATCH_IMPL -// #included from: internal/catch_impl.hpp -#define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED - -// Collect all the implementation files together here -// These are the equivalent of what would usually be cpp files - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wweak-vtables" -#endif - -// #included from: ../catch_runner.hpp -#define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED - -// #included from: internal/catch_commandline.hpp -#define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED - -// #included from: catch_config.hpp -#define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED - -// #included from: catch_test_spec_parser.hpp -#define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -// #included from: catch_test_spec.hpp -#define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -#include -#include - -namespace Catch { - - class TestSpec { - struct Pattern : SharedImpl<> { - virtual ~Pattern(); - virtual bool matches( TestCaseInfo const& testCase ) const = 0; - }; - class NamePattern : public Pattern { - enum WildcardPosition { - NoWildcard = 0, - WildcardAtStart = 1, - WildcardAtEnd = 2, - WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd - }; - - public: - NamePattern( std::string const& name ) : m_name( toLower( name ) ), m_wildcard( NoWildcard ) { - if( startsWith( m_name, "*" ) ) { - m_name = m_name.substr( 1 ); - m_wildcard = WildcardAtStart; - } - if( endsWith( m_name, "*" ) ) { - m_name = m_name.substr( 0, m_name.size()-1 ); - m_wildcard = static_cast( m_wildcard | WildcardAtEnd ); - } - } - virtual ~NamePattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { - switch( m_wildcard ) { - case NoWildcard: - return m_name == toLower( testCase.name ); - case WildcardAtStart: - return endsWith( toLower( testCase.name ), m_name ); - case WildcardAtEnd: - return startsWith( toLower( testCase.name ), m_name ); - case WildcardAtBothEnds: - return contains( toLower( testCase.name ), m_name ); - } - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" -#endif - throw std::logic_error( "Unknown enum" ); -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - } - private: - std::string m_name; - WildcardPosition m_wildcard; - }; - class TagPattern : public Pattern { - public: - TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} - virtual ~TagPattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { - return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end(); - } - private: - std::string m_tag; - }; - class ExcludedPattern : public Pattern { - public: - ExcludedPattern( Ptr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} - virtual ~ExcludedPattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } - private: - Ptr m_underlyingPattern; - }; - - struct Filter { - std::vector > m_patterns; - - bool matches( TestCaseInfo const& testCase ) const { - // All patterns in a filter must match for the filter to be a match - for( std::vector >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) - if( !(*it)->matches( testCase ) ) - return false; - return true; - } - }; - - public: - bool hasFilters() const { - return !m_filters.empty(); - } - bool matches( TestCaseInfo const& testCase ) const { - // A TestSpec matches if any filter matches - for( std::vector::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it ) - if( it->matches( testCase ) ) - return true; - return false; - } - - private: - std::vector m_filters; - - friend class TestSpecParser; - }; -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -namespace Catch { - - class TestSpecParser { - enum Mode{ None, Name, QuotedName, Tag }; - Mode m_mode; - bool m_exclusion; - std::size_t m_start, m_pos; - std::string m_arg; - TestSpec::Filter m_currentFilter; - TestSpec m_testSpec; - ITagAliasRegistry const* m_tagAliases; - - public: - TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} - - TestSpecParser& parse( std::string const& arg ) { - m_mode = None; - m_exclusion = false; - m_start = std::string::npos; - m_arg = m_tagAliases->expandAliases( arg ); - for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) - visitChar( m_arg[m_pos] ); - if( m_mode == Name ) - addPattern(); - return *this; - } - TestSpec testSpec() { - addFilter(); - return m_testSpec; - } - private: - void visitChar( char c ) { - if( m_mode == None ) { - switch( c ) { - case ' ': return; - case '~': m_exclusion = true; return; - case '[': return startNewMode( Tag, ++m_pos ); - case '"': return startNewMode( QuotedName, ++m_pos ); - default: startNewMode( Name, m_pos ); break; - } - } - if( m_mode == Name ) { - if( c == ',' ) { - addPattern(); - addFilter(); - } - else if( c == '[' ) { - if( subString() == "exclude:" ) - m_exclusion = true; - else - addPattern(); - startNewMode( Tag, ++m_pos ); - } - } - else if( m_mode == QuotedName && c == '"' ) - addPattern(); - else if( m_mode == Tag && c == ']' ) - addPattern(); - } - void startNewMode( Mode mode, std::size_t start ) { - m_mode = mode; - m_start = start; - } - std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); } - template - void addPattern() { - std::string token = subString(); - if( startsWith( token, "exclude:" ) ) { - m_exclusion = true; - token = token.substr( 8 ); - } - if( !token.empty() ) { - Ptr pattern = new T( token ); - if( m_exclusion ) - pattern = new TestSpec::ExcludedPattern( pattern ); - m_currentFilter.m_patterns.push_back( pattern ); - } - m_exclusion = false; - m_mode = None; - } - void addFilter() { - if( !m_currentFilter.m_patterns.empty() ) { - m_testSpec.m_filters.push_back( m_currentFilter ); - m_currentFilter = TestSpec::Filter(); - } - } - }; - inline TestSpec parseTestSpec( std::string const& arg ) { - return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); - } - -} // namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -// #included from: catch_interfaces_config.h -#define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED - -#include -#include -#include - -namespace Catch { - - struct Verbosity { enum Level { - NoOutput = 0, - Quiet, - Normal - }; }; - - struct WarnAbout { enum What { - Nothing = 0x00, - NoAssertions = 0x01 - }; }; - - struct ShowDurations { enum OrNot { - DefaultForReporter, - Always, - Never - }; }; - struct RunTests { enum InWhatOrder { - InDeclarationOrder, - InLexicographicalOrder, - InRandomOrder - }; }; - - class TestSpec; - - struct IConfig : IShared { - - virtual ~IConfig(); - - virtual bool allowThrows() const = 0; - virtual std::ostream& stream() const = 0; - virtual std::string name() const = 0; - virtual bool includeSuccessfulResults() const = 0; - virtual bool shouldDebugBreak() const = 0; - virtual bool warnAboutMissingAssertions() const = 0; - virtual int abortAfter() const = 0; - virtual bool showInvisibles() const = 0; - virtual ShowDurations::OrNot showDurations() const = 0; - virtual TestSpec const& testSpec() const = 0; - virtual RunTests::InWhatOrder runOrder() const = 0; - virtual unsigned int rngSeed() const = 0; - virtual bool forceColour() const = 0; - }; -} - -// #included from: catch_stream.h -#define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED - -#include - -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - class Stream { - public: - Stream(); - Stream( std::streambuf* _streamBuf, bool _isOwned ); - void release(); - - std::streambuf* streamBuf; - - private: - bool isOwned; - }; - - std::ostream& cout(); - std::ostream& cerr(); -} - -#include -#include -#include -#include -#include - -#ifndef CATCH_CONFIG_CONSOLE_WIDTH -#define CATCH_CONFIG_CONSOLE_WIDTH 80 -#endif - -namespace Catch { - - struct ConfigData { - - ConfigData() - : listTests( false ), - listTags( false ), - listReporters( false ), - listTestNamesOnly( false ), - showSuccessfulTests( false ), - shouldDebugBreak( false ), - noThrow( false ), - showHelp( false ), - showInvisibles( false ), - forceColour( false ), - abortAfter( -1 ), - rngSeed( 0 ), - verbosity( Verbosity::Normal ), - warnings( WarnAbout::Nothing ), - showDurations( ShowDurations::DefaultForReporter ), - runOrder( RunTests::InDeclarationOrder ) - {} - - bool listTests; - bool listTags; - bool listReporters; - bool listTestNamesOnly; - - bool showSuccessfulTests; - bool shouldDebugBreak; - bool noThrow; - bool showHelp; - bool showInvisibles; - bool forceColour; - - int abortAfter; - unsigned int rngSeed; - - Verbosity::Level verbosity; - WarnAbout::What warnings; - ShowDurations::OrNot showDurations; - RunTests::InWhatOrder runOrder; - - std::string reporterName; - std::string outputFilename; - std::string name; - std::string processName; - - std::vector testsOrTags; - }; - - class Config : public SharedImpl { - private: - Config( Config const& other ); - Config& operator = ( Config const& other ); - virtual void dummy(); - public: - - Config() - : m_os( Catch::cout().rdbuf() ) - {} - - Config( ConfigData const& data ) - : m_data( data ), - m_os( Catch::cout().rdbuf() ) - { - if( !data.testsOrTags.empty() ) { - TestSpecParser parser( ITagAliasRegistry::get() ); - for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) - parser.parse( data.testsOrTags[i] ); - m_testSpec = parser.testSpec(); - } - } - - virtual ~Config() { - m_os.rdbuf( Catch::cout().rdbuf() ); - m_stream.release(); - } - - void setFilename( std::string const& filename ) { - m_data.outputFilename = filename; - } - - std::string const& getFilename() const { - return m_data.outputFilename ; - } - - bool listTests() const { return m_data.listTests; } - bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } - bool listTags() const { return m_data.listTags; } - bool listReporters() const { return m_data.listReporters; } - - std::string getProcessName() const { return m_data.processName; } - - bool shouldDebugBreak() const { return m_data.shouldDebugBreak; } - - void setStreamBuf( std::streambuf* buf ) { - m_os.rdbuf( buf ? buf : Catch::cout().rdbuf() ); - } - - void useStream( std::string const& streamName ) { - Stream stream = createStream( streamName ); - setStreamBuf( stream.streamBuf ); - m_stream.release(); - m_stream = stream; - } - - std::string getReporterName() const { return m_data.reporterName; } - - int abortAfter() const { return m_data.abortAfter; } - - TestSpec const& testSpec() const { return m_testSpec; } - - bool showHelp() const { return m_data.showHelp; } - bool showInvisibles() const { return m_data.showInvisibles; } - - // IConfig interface - virtual bool allowThrows() const { return !m_data.noThrow; } - virtual std::ostream& stream() const { return m_os; } - virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } - virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; } - virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; } - virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; } - virtual RunTests::InWhatOrder runOrder() const { return m_data.runOrder; } - virtual unsigned int rngSeed() const { return m_data.rngSeed; } - virtual bool forceColour() const { return m_data.forceColour; } - - private: - ConfigData m_data; - - Stream m_stream; - mutable std::ostream m_os; - TestSpec m_testSpec; - }; - -} // end namespace Catch - -// #included from: catch_clara.h -#define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED - -// Use Catch's value for console width (store Clara's off to the side, if present) -#ifdef CLARA_CONFIG_CONSOLE_WIDTH -#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH -#undef CLARA_CONFIG_CONSOLE_WIDTH -#endif -#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - -// Declare Clara inside the Catch namespace -#define STITCH_CLARA_OPEN_NAMESPACE namespace Catch { -// #included from: ../external/clara.h - -// Only use header guard if we are not using an outer namespace -#if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE) - -#ifndef STITCH_CLARA_OPEN_NAMESPACE -#define TWOBLUECUBES_CLARA_H_INCLUDED -#define STITCH_CLARA_OPEN_NAMESPACE -#define STITCH_CLARA_CLOSE_NAMESPACE -#else -#define STITCH_CLARA_CLOSE_NAMESPACE } -#endif - -#define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE - -// ----------- #included from tbc_text_format.h ----------- - -// Only use header guard if we are not using an outer namespace -#if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE) -#ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -#define TBC_TEXT_FORMAT_H_INCLUDED -#endif - -#include -#include -#include - -// Use optional outer namespace -#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE { -#endif - -namespace Tbc { - -#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH - const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - struct TextAttributes { - TextAttributes() - : initialIndent( std::string::npos ), - indent( 0 ), - width( consoleWidth-1 ), - tabChar( '\t' ) - {} - - TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } - TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } - TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } - TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } - - std::size_t initialIndent; // indent of first line, or npos - std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos - std::size_t width; // maximum width of text, including indent. Longer text will wrap - char tabChar; // If this char is seen the indent is changed to current pos - }; - - class Text { - public: - Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) - : attr( _attr ) - { - std::string wrappableChars = " [({.,/|\\-"; - std::size_t indent = _attr.initialIndent != std::string::npos - ? _attr.initialIndent - : _attr.indent; - std::string remainder = _str; - - while( !remainder.empty() ) { - if( lines.size() >= 1000 ) { - lines.push_back( "... message truncated due to excessive size" ); - return; - } - std::size_t tabPos = std::string::npos; - std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); - std::size_t pos = remainder.find_first_of( '\n' ); - if( pos <= width ) { - width = pos; - } - pos = remainder.find_last_of( _attr.tabChar, width ); - if( pos != std::string::npos ) { - tabPos = pos; - if( remainder[width] == '\n' ) - width--; - remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); - } - - if( width == remainder.size() ) { - spliceLine( indent, remainder, width ); - } - else if( remainder[width] == '\n' ) { - spliceLine( indent, remainder, width ); - if( width <= 1 || remainder.size() != 1 ) - remainder = remainder.substr( 1 ); - indent = _attr.indent; - } - else { - pos = remainder.find_last_of( wrappableChars, width ); - if( pos != std::string::npos && pos > 0 ) { - spliceLine( indent, remainder, pos ); - if( remainder[0] == ' ' ) - remainder = remainder.substr( 1 ); - } - else { - spliceLine( indent, remainder, width-1 ); - lines.back() += "-"; - } - if( lines.size() == 1 ) - indent = _attr.indent; - if( tabPos != std::string::npos ) - indent += tabPos; - } - } - } - - void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { - lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); - _remainder = _remainder.substr( _pos ); - } - - typedef std::vector::const_iterator const_iterator; - - const_iterator begin() const { return lines.begin(); } - const_iterator end() const { return lines.end(); } - std::string const& last() const { return lines.back(); } - std::size_t size() const { return lines.size(); } - std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } - std::string toString() const { - std::ostringstream oss; - oss << *this; - return oss.str(); - } - - inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { - for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); - it != itEnd; ++it ) { - if( it != _text.begin() ) - _stream << "\n"; - _stream << *it; - } - return _stream; - } - - private: - std::string str; - TextAttributes attr; - std::vector lines; - }; - -} // end namespace Tbc - -#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -} // end outer namespace -#endif - -#endif // TBC_TEXT_FORMAT_H_INCLUDED - -// ----------- end of #include from tbc_text_format.h ----------- -// ........... back in /Users/philnash/Dev/OSS/Clara/srcs/clara.h - -#undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE - -#include -#include -#include -#include - -// Use optional outer namespace -#ifdef STITCH_CLARA_OPEN_NAMESPACE -STITCH_CLARA_OPEN_NAMESPACE -#endif - -namespace Clara { - - struct UnpositionalTag {}; - - extern UnpositionalTag _; - -#ifdef CLARA_CONFIG_MAIN - UnpositionalTag _; -#endif - - namespace Detail { - -#ifdef CLARA_CONSOLE_WIDTH - const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - using namespace Tbc; - - inline bool startsWith( std::string const& str, std::string const& prefix ) { - return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix; - } - - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - - template struct IsBool { static const bool value = false; }; - template<> struct IsBool { static const bool value = true; }; - - template - void convertInto( std::string const& _source, T& _dest ) { - std::stringstream ss; - ss << _source; - ss >> _dest; - if( ss.fail() ) - throw std::runtime_error( "Unable to convert " + _source + " to destination type" ); - } - inline void convertInto( std::string const& _source, std::string& _dest ) { - _dest = _source; - } - inline void convertInto( std::string const& _source, bool& _dest ) { - std::string sourceLC = _source; - std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower ); - if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" ) - _dest = true; - else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" ) - _dest = false; - else - throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" ); - } - inline void convertInto( bool _source, bool& _dest ) { - _dest = _source; - } - template - inline void convertInto( bool, T& ) { - throw std::runtime_error( "Invalid conversion" ); - } - - template - struct IArgFunction { - virtual ~IArgFunction() {} -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - IArgFunction() = default; - IArgFunction( IArgFunction const& ) = default; -# endif - virtual void set( ConfigT& config, std::string const& value ) const = 0; - virtual void setFlag( ConfigT& config ) const = 0; - virtual bool takesArg() const = 0; - virtual IArgFunction* clone() const = 0; - }; - - template - class BoundArgFunction { - public: - BoundArgFunction() : functionObj( NULL ) {} - BoundArgFunction( IArgFunction* _functionObj ) : functionObj( _functionObj ) {} - BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : NULL ) {} - BoundArgFunction& operator = ( BoundArgFunction const& other ) { - IArgFunction* newFunctionObj = other.functionObj ? other.functionObj->clone() : NULL; - delete functionObj; - functionObj = newFunctionObj; - return *this; - } - ~BoundArgFunction() { delete functionObj; } - - void set( ConfigT& config, std::string const& value ) const { - functionObj->set( config, value ); - } - void setFlag( ConfigT& config ) const { - functionObj->setFlag( config ); - } - bool takesArg() const { return functionObj->takesArg(); } - - bool isSet() const { - return functionObj != NULL; - } - private: - IArgFunction* functionObj; - }; - - template - struct NullBinder : IArgFunction{ - virtual void set( C&, std::string const& ) const {} - virtual void setFlag( C& ) const {} - virtual bool takesArg() const { return true; } - virtual IArgFunction* clone() const { return new NullBinder( *this ); } - }; - - template - struct BoundDataMember : IArgFunction{ - BoundDataMember( M C::* _member ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - convertInto( stringValue, p.*member ); - } - virtual void setFlag( C& p ) const { - convertInto( true, p.*member ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundDataMember( *this ); } - M C::* member; - }; - template - struct BoundUnaryMethod : IArgFunction{ - BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - typename RemoveConstRef::type value; - convertInto( stringValue, value ); - (p.*member)( value ); - } - virtual void setFlag( C& p ) const { - typename RemoveConstRef::type value; - convertInto( true, value ); - (p.*member)( value ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundUnaryMethod( *this ); } - void (C::*member)( M ); - }; - template - struct BoundNullaryMethod : IArgFunction{ - BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - bool value; - convertInto( stringValue, value ); - if( value ) - (p.*member)(); - } - virtual void setFlag( C& p ) const { - (p.*member)(); - } - virtual bool takesArg() const { return false; } - virtual IArgFunction* clone() const { return new BoundNullaryMethod( *this ); } - void (C::*member)(); - }; - - template - struct BoundUnaryFunction : IArgFunction{ - BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {} - virtual void set( C& obj, std::string const& stringValue ) const { - bool value; - convertInto( stringValue, value ); - if( value ) - function( obj ); - } - virtual void setFlag( C& p ) const { - function( p ); - } - virtual bool takesArg() const { return false; } - virtual IArgFunction* clone() const { return new BoundUnaryFunction( *this ); } - void (*function)( C& ); - }; - - template - struct BoundBinaryFunction : IArgFunction{ - BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {} - virtual void set( C& obj, std::string const& stringValue ) const { - typename RemoveConstRef::type value; - convertInto( stringValue, value ); - function( obj, value ); - } - virtual void setFlag( C& obj ) const { - typename RemoveConstRef::type value; - convertInto( true, value ); - function( obj, value ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundBinaryFunction( *this ); } - void (*function)( C&, T ); - }; - - } // namespace Detail - - struct Parser { - Parser() : separators( " \t=:" ) {} - - struct Token { - enum Type { Positional, ShortOpt, LongOpt }; - Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {} - Type type; - std::string data; - }; - - void parseIntoTokens( int argc, char const * const * argv, std::vector& tokens ) const { - const std::string doubleDash = "--"; - for( int i = 1; i < argc && argv[i] != doubleDash; ++i ) - parseIntoTokens( argv[i] , tokens); - } - void parseIntoTokens( std::string arg, std::vector& tokens ) const { - while( !arg.empty() ) { - Parser::Token token( Parser::Token::Positional, arg ); - arg = ""; - if( token.data[0] == '-' ) { - if( token.data.size() > 1 && token.data[1] == '-' ) { - token = Parser::Token( Parser::Token::LongOpt, token.data.substr( 2 ) ); - } - else { - token = Parser::Token( Parser::Token::ShortOpt, token.data.substr( 1 ) ); - if( token.data.size() > 1 && separators.find( token.data[1] ) == std::string::npos ) { - arg = "-" + token.data.substr( 1 ); - token.data = token.data.substr( 0, 1 ); - } - } - } - if( token.type != Parser::Token::Positional ) { - std::size_t pos = token.data.find_first_of( separators ); - if( pos != std::string::npos ) { - arg = token.data.substr( pos+1 ); - token.data = token.data.substr( 0, pos ); - } - } - tokens.push_back( token ); - } - } - std::string separators; - }; - - template - struct CommonArgProperties { - CommonArgProperties() {} - CommonArgProperties( Detail::BoundArgFunction const& _boundField ) : boundField( _boundField ) {} - - Detail::BoundArgFunction boundField; - std::string description; - std::string detail; - std::string placeholder; // Only value if boundField takes an arg - - bool takesArg() const { - return !placeholder.empty(); - } - void validate() const { - if( !boundField.isSet() ) - throw std::logic_error( "option not bound" ); - } - }; - struct OptionArgProperties { - std::vector shortNames; - std::string longName; - - bool hasShortName( std::string const& shortName ) const { - return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end(); - } - bool hasLongName( std::string const& _longName ) const { - return _longName == longName; - } - }; - struct PositionalArgProperties { - PositionalArgProperties() : position( -1 ) {} - int position; // -1 means non-positional (floating) - - bool isFixedPositional() const { - return position != -1; - } - }; - - template - class CommandLine { - - struct Arg : CommonArgProperties, OptionArgProperties, PositionalArgProperties { - Arg() {} - Arg( Detail::BoundArgFunction const& _boundField ) : CommonArgProperties( _boundField ) {} - - using CommonArgProperties::placeholder; // !TBD - - std::string dbgName() const { - if( !longName.empty() ) - return "--" + longName; - if( !shortNames.empty() ) - return "-" + shortNames[0]; - return "positional args"; - } - std::string commands() const { - std::ostringstream oss; - bool first = true; - std::vector::const_iterator it = shortNames.begin(), itEnd = shortNames.end(); - for(; it != itEnd; ++it ) { - if( first ) - first = false; - else - oss << ", "; - oss << "-" << *it; - } - if( !longName.empty() ) { - if( !first ) - oss << ", "; - oss << "--" << longName; - } - if( !placeholder.empty() ) - oss << " <" << placeholder << ">"; - return oss.str(); - } - }; - - // NOTE: std::auto_ptr is deprecated in c++11/c++0x -#if defined(__cplusplus) && __cplusplus > 199711L - typedef std::unique_ptr ArgAutoPtr; -#else - typedef std::auto_ptr ArgAutoPtr; -#endif - - friend void addOptName( Arg& arg, std::string const& optName ) - { - if( optName.empty() ) - return; - if( Detail::startsWith( optName, "--" ) ) { - if( !arg.longName.empty() ) - throw std::logic_error( "Only one long opt may be specified. '" - + arg.longName - + "' already specified, now attempting to add '" - + optName + "'" ); - arg.longName = optName.substr( 2 ); - } - else if( Detail::startsWith( optName, "-" ) ) - arg.shortNames.push_back( optName.substr( 1 ) ); - else - throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" ); - } - friend void setPositionalArg( Arg& arg, int position ) - { - arg.position = position; - } - - class ArgBuilder { - public: - ArgBuilder( Arg* arg ) : m_arg( arg ) {} - - // Bind a non-boolean data member (requires placeholder string) - template - void bind( M C::* field, std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundDataMember( field ); - m_arg->placeholder = placeholder; - } - // Bind a boolean data member (no placeholder required) - template - void bind( bool C::* field ) { - m_arg->boundField = new Detail::BoundDataMember( field ); - } - - // Bind a method taking a single, non-boolean argument (requires a placeholder string) - template - void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); - m_arg->placeholder = placeholder; - } - - // Bind a method taking a single, boolean argument (no placeholder string required) - template - void bind( void (C::* unaryMethod)( bool ) ) { - m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); - } - - // Bind a method that takes no arguments (will be called if opt is present) - template - void bind( void (C::* nullaryMethod)() ) { - m_arg->boundField = new Detail::BoundNullaryMethod( nullaryMethod ); - } - - // Bind a free function taking a single argument - the object to operate on (no placeholder string required) - template - void bind( void (* unaryFunction)( C& ) ) { - m_arg->boundField = new Detail::BoundUnaryFunction( unaryFunction ); - } - - // Bind a free function taking a single argument - the object to operate on (requires a placeholder string) - template - void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundBinaryFunction( binaryFunction ); - m_arg->placeholder = placeholder; - } - - ArgBuilder& describe( std::string const& description ) { - m_arg->description = description; - return *this; - } - ArgBuilder& detail( std::string const& detail ) { - m_arg->detail = detail; - return *this; - } - - protected: - Arg* m_arg; - }; - - class OptBuilder : public ArgBuilder { - public: - OptBuilder( Arg* arg ) : ArgBuilder( arg ) {} - OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {} - - OptBuilder& operator[]( std::string const& optName ) { - addOptName( *ArgBuilder::m_arg, optName ); - return *this; - } - }; - - public: - - CommandLine() - : m_boundProcessName( new Detail::NullBinder() ), - m_highestSpecifiedArgPosition( 0 ), - m_throwOnUnrecognisedTokens( false ) - {} - CommandLine( CommandLine const& other ) - : m_boundProcessName( other.m_boundProcessName ), - m_options ( other.m_options ), - m_positionalArgs( other.m_positionalArgs ), - m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ), - m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens ) - { - if( other.m_floatingArg.get() ) - m_floatingArg.reset( new Arg( *other.m_floatingArg ) ); - } - - CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) { - m_throwOnUnrecognisedTokens = shouldThrow; - return *this; - } - - OptBuilder operator[]( std::string const& optName ) { - m_options.push_back( Arg() ); - addOptName( m_options.back(), optName ); - OptBuilder builder( &m_options.back() ); - return builder; - } - - ArgBuilder operator[]( int position ) { - m_positionalArgs.insert( std::make_pair( position, Arg() ) ); - if( position > m_highestSpecifiedArgPosition ) - m_highestSpecifiedArgPosition = position; - setPositionalArg( m_positionalArgs[position], position ); - ArgBuilder builder( &m_positionalArgs[position] ); - return builder; - } - - // Invoke this with the _ instance - ArgBuilder operator[]( UnpositionalTag ) { - if( m_floatingArg.get() ) - throw std::logic_error( "Only one unpositional argument can be added" ); - m_floatingArg.reset( new Arg() ); - ArgBuilder builder( m_floatingArg.get() ); - return builder; - } - - template - void bindProcessName( M C::* field ) { - m_boundProcessName = new Detail::BoundDataMember( field ); - } - template - void bindProcessName( void (C::*_unaryMethod)( M ) ) { - m_boundProcessName = new Detail::BoundUnaryMethod( _unaryMethod ); - } - - void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const { - typename std::vector::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it; - std::size_t maxWidth = 0; - for( it = itBegin; it != itEnd; ++it ) - maxWidth = (std::max)( maxWidth, it->commands().size() ); - - for( it = itBegin; it != itEnd; ++it ) { - Detail::Text usage( it->commands(), Detail::TextAttributes() - .setWidth( maxWidth+indent ) - .setIndent( indent ) ); - Detail::Text desc( it->description, Detail::TextAttributes() - .setWidth( width - maxWidth - 3 ) ); - - for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) { - std::string usageCol = i < usage.size() ? usage[i] : ""; - os << usageCol; - - if( i < desc.size() && !desc[i].empty() ) - os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' ) - << desc[i]; - os << "\n"; - } - } - } - std::string optUsage() const { - std::ostringstream oss; - optUsage( oss ); - return oss.str(); - } - - void argSynopsis( std::ostream& os ) const { - for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) { - if( i > 1 ) - os << " "; - typename std::map::const_iterator it = m_positionalArgs.find( i ); - if( it != m_positionalArgs.end() ) - os << "<" << it->second.placeholder << ">"; - else if( m_floatingArg.get() ) - os << "<" << m_floatingArg->placeholder << ">"; - else - throw std::logic_error( "non consecutive positional arguments with no floating args" ); - } - // !TBD No indication of mandatory args - if( m_floatingArg.get() ) { - if( m_highestSpecifiedArgPosition > 1 ) - os << " "; - os << "[<" << m_floatingArg->placeholder << "> ...]"; - } - } - std::string argSynopsis() const { - std::ostringstream oss; - argSynopsis( oss ); - return oss.str(); - } - - void usage( std::ostream& os, std::string const& procName ) const { - validate(); - os << "usage:\n " << procName << " "; - argSynopsis( os ); - if( !m_options.empty() ) { - os << " [options]\n\nwhere options are: \n"; - optUsage( os, 2 ); - } - os << "\n"; - } - std::string usage( std::string const& procName ) const { - std::ostringstream oss; - usage( oss, procName ); - return oss.str(); - } - - ConfigT parse( int argc, char const * const * argv ) const { - ConfigT config; - parseInto( argc, argv, config ); - return config; - } - - std::vector parseInto( int argc, char const * const * argv, ConfigT& config ) const { - std::string processName = argv[0]; - std::size_t lastSlash = processName.find_last_of( "/\\" ); - if( lastSlash != std::string::npos ) - processName = processName.substr( lastSlash+1 ); - m_boundProcessName.set( config, processName ); - std::vector tokens; - Parser parser; - parser.parseIntoTokens( argc, argv, tokens ); - return populate( tokens, config ); - } - - std::vector populate( std::vector const& tokens, ConfigT& config ) const { - validate(); - std::vector unusedTokens = populateOptions( tokens, config ); - unusedTokens = populateFixedArgs( unusedTokens, config ); - unusedTokens = populateFloatingArgs( unusedTokens, config ); - return unusedTokens; - } - - std::vector populateOptions( std::vector const& tokens, ConfigT& config ) const { - std::vector unusedTokens; - std::vector errors; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - typename std::vector::const_iterator it = m_options.begin(), itEnd = m_options.end(); - for(; it != itEnd; ++it ) { - Arg const& arg = *it; - - try { - if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) || - ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) { - if( arg.takesArg() ) { - if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional ) - errors.push_back( "Expected argument to option: " + token.data ); - else - arg.boundField.set( config, tokens[++i].data ); - } - else { - arg.boundField.setFlag( config ); - } - break; - } - } - catch( std::exception& ex ) { - errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" ); - } - } - if( it == itEnd ) { - if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens ) - unusedTokens.push_back( token ); - else if( errors.empty() && m_throwOnUnrecognisedTokens ) - errors.push_back( "unrecognised option: " + token.data ); - } - } - if( !errors.empty() ) { - std::ostringstream oss; - for( std::vector::const_iterator it = errors.begin(), itEnd = errors.end(); - it != itEnd; - ++it ) { - if( it != errors.begin() ) - oss << "\n"; - oss << *it; - } - throw std::runtime_error( oss.str() ); - } - return unusedTokens; - } - std::vector populateFixedArgs( std::vector const& tokens, ConfigT& config ) const { - std::vector unusedTokens; - int position = 1; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - typename std::map::const_iterator it = m_positionalArgs.find( position ); - if( it != m_positionalArgs.end() ) - it->second.boundField.set( config, token.data ); - else - unusedTokens.push_back( token ); - if( token.type == Parser::Token::Positional ) - position++; - } - return unusedTokens; - } - std::vector populateFloatingArgs( std::vector const& tokens, ConfigT& config ) const { - if( !m_floatingArg.get() ) - return tokens; - std::vector unusedTokens; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - if( token.type == Parser::Token::Positional ) - m_floatingArg->boundField.set( config, token.data ); - else - unusedTokens.push_back( token ); - } - return unusedTokens; - } - - void validate() const - { - if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() ) - throw std::logic_error( "No options or arguments specified" ); - - for( typename std::vector::const_iterator it = m_options.begin(), - itEnd = m_options.end(); - it != itEnd; ++it ) - it->validate(); - } - - private: - Detail::BoundArgFunction m_boundProcessName; - std::vector m_options; - std::map m_positionalArgs; - ArgAutoPtr m_floatingArg; - int m_highestSpecifiedArgPosition; - bool m_throwOnUnrecognisedTokens; - }; - -} // end namespace Clara - -STITCH_CLARA_CLOSE_NAMESPACE -#undef STITCH_CLARA_OPEN_NAMESPACE -#undef STITCH_CLARA_CLOSE_NAMESPACE - -#endif // TWOBLUECUBES_CLARA_H_INCLUDED -#undef STITCH_CLARA_OPEN_NAMESPACE - -// Restore Clara's value for console width, if present -#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#endif - -#include - -namespace Catch { - - inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; } - inline void abortAfterX( ConfigData& config, int x ) { - if( x < 1 ) - throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" ); - config.abortAfter = x; - } - inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); } - - inline void addWarning( ConfigData& config, std::string const& _warning ) { - if( _warning == "NoAssertions" ) - config.warnings = static_cast( config.warnings | WarnAbout::NoAssertions ); - else - throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" ); - } - inline void setOrder( ConfigData& config, std::string const& order ) { - if( startsWith( "declared", order ) ) - config.runOrder = RunTests::InDeclarationOrder; - else if( startsWith( "lexical", order ) ) - config.runOrder = RunTests::InLexicographicalOrder; - else if( startsWith( "random", order ) ) - config.runOrder = RunTests::InRandomOrder; - else - throw std::runtime_error( "Unrecognised ordering: '" + order + "'" ); - } - inline void setRngSeed( ConfigData& config, std::string const& seed ) { - if( seed == "time" ) { - config.rngSeed = static_cast( std::time(0) ); - } - else { - std::stringstream ss; - ss << seed; - ss >> config.rngSeed; - if( ss.fail() ) - throw std::runtime_error( "Argment to --rng-seed should be the word 'time' or a number" ); - } - } - inline void setVerbosity( ConfigData& config, int level ) { - // !TBD: accept strings? - config.verbosity = static_cast( level ); - } - inline void setShowDurations( ConfigData& config, bool _showDurations ) { - config.showDurations = _showDurations - ? ShowDurations::Always - : ShowDurations::Never; - } - inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) { - std::ifstream f( _filename.c_str() ); - if( !f.is_open() ) - throw std::domain_error( "Unable to load input file: " + _filename ); - - std::string line; - while( std::getline( f, line ) ) { - line = trim(line); - if( !line.empty() && !startsWith( line, "#" ) ) - addTestOrTags( config, "\"" + line + "\"," ); - } - } - - inline Clara::CommandLine makeCommandLineParser() { - - using namespace Clara; - CommandLine cli; - - cli.bindProcessName( &ConfigData::processName ); - - cli["-?"]["-h"]["--help"] - .describe( "display usage information" ) - .bind( &ConfigData::showHelp ); - - cli["-l"]["--list-tests"] - .describe( "list all/matching test cases" ) - .bind( &ConfigData::listTests ); - - cli["-t"]["--list-tags"] - .describe( "list all/matching tags" ) - .bind( &ConfigData::listTags ); - - cli["-s"]["--success"] - .describe( "include successful tests in output" ) - .bind( &ConfigData::showSuccessfulTests ); - - cli["-b"]["--break"] - .describe( "break into debugger on failure" ) - .bind( &ConfigData::shouldDebugBreak ); - - cli["-e"]["--nothrow"] - .describe( "skip exception tests" ) - .bind( &ConfigData::noThrow ); - - cli["-i"]["--invisibles"] - .describe( "show invisibles (tabs, newlines)" ) - .bind( &ConfigData::showInvisibles ); - - cli["-o"]["--out"] - .describe( "output filename" ) - .bind( &ConfigData::outputFilename, "filename" ); - - cli["-r"]["--reporter"] -// .placeholder( "name[:filename]" ) - .describe( "reporter to use (defaults to console)" ) - .bind( &ConfigData::reporterName, "name" ); - - cli["-n"]["--name"] - .describe( "suite name" ) - .bind( &ConfigData::name, "name" ); - - cli["-a"]["--abort"] - .describe( "abort at first failure" ) - .bind( &abortAfterFirst ); - - cli["-x"]["--abortx"] - .describe( "abort after x failures" ) - .bind( &abortAfterX, "no. failures" ); - - cli["-w"]["--warn"] - .describe( "enable warnings" ) - .bind( &addWarning, "warning name" ); - -// - needs updating if reinstated -// cli.into( &setVerbosity ) -// .describe( "level of verbosity (0=no output)" ) -// .shortOpt( "v") -// .longOpt( "verbosity" ) -// .placeholder( "level" ); - - cli[_] - .describe( "which test or tests to use" ) - .bind( &addTestOrTags, "test name, pattern or tags" ); - - cli["-d"]["--durations"] - .describe( "show test durations" ) - .bind( &setShowDurations, "yes/no" ); - - cli["-f"]["--input-file"] - .describe( "load test names to run from a file" ) - .bind( &loadTestNamesFromFile, "filename" ); - - // Less common commands which don't have a short form - cli["--list-test-names-only"] - .describe( "list all/matching test cases names only" ) - .bind( &ConfigData::listTestNamesOnly ); - - cli["--list-reporters"] - .describe( "list all reporters" ) - .bind( &ConfigData::listReporters ); - - cli["--order"] - .describe( "test case order (defaults to decl)" ) - .bind( &setOrder, "decl|lex|rand" ); - - cli["--rng-seed"] - .describe( "set a specific seed for random numbers" ) - .bind( &setRngSeed, "'time'|number" ); - - cli["--force-colour"] - .describe( "force colourised output" ) - .bind( &ConfigData::forceColour ); - - return cli; - } - -} // end namespace Catch - -// #included from: internal/catch_list.hpp -#define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED - -// #included from: catch_text.h -#define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED - -#define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - -#define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch -// #included from: ../external/tbc_text_format.h -// Only use header guard if we are not using an outer namespace -#ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -# ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED -# ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -# define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -# endif -# else -# define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED -# endif -#endif -#ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -#include -#include -#include - -// Use optional outer namespace -#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE { -#endif - -namespace Tbc { - -#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH - const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - struct TextAttributes { - TextAttributes() - : initialIndent( std::string::npos ), - indent( 0 ), - width( consoleWidth-1 ), - tabChar( '\t' ) - {} - - TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } - TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } - TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } - TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } - - std::size_t initialIndent; // indent of first line, or npos - std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos - std::size_t width; // maximum width of text, including indent. Longer text will wrap - char tabChar; // If this char is seen the indent is changed to current pos - }; - - class Text { - public: - Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) - : attr( _attr ) - { - std::string wrappableChars = " [({.,/|\\-"; - std::size_t indent = _attr.initialIndent != std::string::npos - ? _attr.initialIndent - : _attr.indent; - std::string remainder = _str; - - while( !remainder.empty() ) { - if( lines.size() >= 1000 ) { - lines.push_back( "... message truncated due to excessive size" ); - return; - } - std::size_t tabPos = std::string::npos; - std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); - std::size_t pos = remainder.find_first_of( '\n' ); - if( pos <= width ) { - width = pos; - } - pos = remainder.find_last_of( _attr.tabChar, width ); - if( pos != std::string::npos ) { - tabPos = pos; - if( remainder[width] == '\n' ) - width--; - remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); - } - - if( width == remainder.size() ) { - spliceLine( indent, remainder, width ); - } - else if( remainder[width] == '\n' ) { - spliceLine( indent, remainder, width ); - if( width <= 1 || remainder.size() != 1 ) - remainder = remainder.substr( 1 ); - indent = _attr.indent; - } - else { - pos = remainder.find_last_of( wrappableChars, width ); - if( pos != std::string::npos && pos > 0 ) { - spliceLine( indent, remainder, pos ); - if( remainder[0] == ' ' ) - remainder = remainder.substr( 1 ); - } - else { - spliceLine( indent, remainder, width-1 ); - lines.back() += "-"; - } - if( lines.size() == 1 ) - indent = _attr.indent; - if( tabPos != std::string::npos ) - indent += tabPos; - } - } - } - - void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { - lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); - _remainder = _remainder.substr( _pos ); - } - - typedef std::vector::const_iterator const_iterator; - - const_iterator begin() const { return lines.begin(); } - const_iterator end() const { return lines.end(); } - std::string const& last() const { return lines.back(); } - std::size_t size() const { return lines.size(); } - std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } - std::string toString() const { - std::ostringstream oss; - oss << *this; - return oss.str(); - } - - inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { - for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); - it != itEnd; ++it ) { - if( it != _text.begin() ) - _stream << "\n"; - _stream << *it; - } - return _stream; - } - - private: - std::string str; - TextAttributes attr; - std::vector lines; - }; - -} // end namespace Tbc - -#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -} // end outer namespace -#endif - -#endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -#undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE - -namespace Catch { - using Tbc::Text; - using Tbc::TextAttributes; -} - -// #included from: catch_console_colour.hpp -#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED - -namespace Catch { - - struct Colour { - enum Code { - None = 0, - - White, - Red, - Green, - Blue, - Cyan, - Yellow, - Grey, - - Bright = 0x10, - - BrightRed = Bright | Red, - BrightGreen = Bright | Green, - LightGrey = Bright | Grey, - BrightWhite = Bright | White, - - // By intention - FileName = LightGrey, - Warning = Yellow, - ResultError = BrightRed, - ResultSuccess = BrightGreen, - ResultExpectedFailure = Warning, - - Error = BrightRed, - Success = Green, - - OriginalExpression = Cyan, - ReconstructedExpression = Yellow, - - SecondaryText = LightGrey, - Headers = White - }; - - // Use constructed object for RAII guard - Colour( Code _colourCode ); - Colour( Colour const& other ); - ~Colour(); - - // Use static method for one-shot changes - static void use( Code _colourCode ); - - private: - bool m_moved; - }; - - inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; } - -} // end namespace Catch - -// #included from: catch_interfaces_reporter.h -#define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED - -#include -#include -#include -#include - -namespace Catch -{ - struct ReporterConfig { - explicit ReporterConfig( Ptr const& _fullConfig ) - : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} - - ReporterConfig( Ptr const& _fullConfig, std::ostream& _stream ) - : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} - - std::ostream& stream() const { return *m_stream; } - Ptr fullConfig() const { return m_fullConfig; } - - private: - std::ostream* m_stream; - Ptr m_fullConfig; - }; - - struct ReporterPreferences { - ReporterPreferences() - : shouldRedirectStdOut( false ) - {} - - bool shouldRedirectStdOut; - }; - - template - struct LazyStat : Option { - LazyStat() : used( false ) {} - LazyStat& operator=( T const& _value ) { - Option::operator=( _value ); - used = false; - return *this; - } - void reset() { - Option::reset(); - used = false; - } - bool used; - }; - - struct TestRunInfo { - TestRunInfo( std::string const& _name ) : name( _name ) {} - std::string name; - }; - struct GroupInfo { - GroupInfo( std::string const& _name, - std::size_t _groupIndex, - std::size_t _groupsCount ) - : name( _name ), - groupIndex( _groupIndex ), - groupsCounts( _groupsCount ) - {} - - std::string name; - std::size_t groupIndex; - std::size_t groupsCounts; - }; - - struct AssertionStats { - AssertionStats( AssertionResult const& _assertionResult, - std::vector const& _infoMessages, - Totals const& _totals ) - : assertionResult( _assertionResult ), - infoMessages( _infoMessages ), - totals( _totals ) - { - if( assertionResult.hasMessage() ) { - // Copy message into messages list. - // !TBD This should have been done earlier, somewhere - MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); - builder << assertionResult.getMessage(); - builder.m_info.message = builder.m_stream.str(); - - infoMessages.push_back( builder.m_info ); - } - } - virtual ~AssertionStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - AssertionStats( AssertionStats const& ) = default; - AssertionStats( AssertionStats && ) = default; - AssertionStats& operator = ( AssertionStats const& ) = default; - AssertionStats& operator = ( AssertionStats && ) = default; -# endif - - AssertionResult assertionResult; - std::vector infoMessages; - Totals totals; - }; - - struct SectionStats { - SectionStats( SectionInfo const& _sectionInfo, - Counts const& _assertions, - double _durationInSeconds, - bool _missingAssertions ) - : sectionInfo( _sectionInfo ), - assertions( _assertions ), - durationInSeconds( _durationInSeconds ), - missingAssertions( _missingAssertions ) - {} - virtual ~SectionStats(); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - SectionStats( SectionStats const& ) = default; - SectionStats( SectionStats && ) = default; - SectionStats& operator = ( SectionStats const& ) = default; - SectionStats& operator = ( SectionStats && ) = default; -# endif - - SectionInfo sectionInfo; - Counts assertions; - double durationInSeconds; - bool missingAssertions; - }; - - struct TestCaseStats { - TestCaseStats( TestCaseInfo const& _testInfo, - Totals const& _totals, - std::string const& _stdOut, - std::string const& _stdErr, - bool _aborting ) - : testInfo( _testInfo ), - totals( _totals ), - stdOut( _stdOut ), - stdErr( _stdErr ), - aborting( _aborting ) - {} - virtual ~TestCaseStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestCaseStats( TestCaseStats const& ) = default; - TestCaseStats( TestCaseStats && ) = default; - TestCaseStats& operator = ( TestCaseStats const& ) = default; - TestCaseStats& operator = ( TestCaseStats && ) = default; -# endif - - TestCaseInfo testInfo; - Totals totals; - std::string stdOut; - std::string stdErr; - bool aborting; - }; - - struct TestGroupStats { - TestGroupStats( GroupInfo const& _groupInfo, - Totals const& _totals, - bool _aborting ) - : groupInfo( _groupInfo ), - totals( _totals ), - aborting( _aborting ) - {} - TestGroupStats( GroupInfo const& _groupInfo ) - : groupInfo( _groupInfo ), - aborting( false ) - {} - virtual ~TestGroupStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestGroupStats( TestGroupStats const& ) = default; - TestGroupStats( TestGroupStats && ) = default; - TestGroupStats& operator = ( TestGroupStats const& ) = default; - TestGroupStats& operator = ( TestGroupStats && ) = default; -# endif - - GroupInfo groupInfo; - Totals totals; - bool aborting; - }; - - struct TestRunStats { - TestRunStats( TestRunInfo const& _runInfo, - Totals const& _totals, - bool _aborting ) - : runInfo( _runInfo ), - totals( _totals ), - aborting( _aborting ) - {} - virtual ~TestRunStats(); - -# ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestRunStats( TestRunStats const& _other ) - : runInfo( _other.runInfo ), - totals( _other.totals ), - aborting( _other.aborting ) - {} -# else - TestRunStats( TestRunStats const& ) = default; - TestRunStats( TestRunStats && ) = default; - TestRunStats& operator = ( TestRunStats const& ) = default; - TestRunStats& operator = ( TestRunStats && ) = default; -# endif - - TestRunInfo runInfo; - Totals totals; - bool aborting; - }; - - struct IStreamingReporter : IShared { - virtual ~IStreamingReporter(); - - // Implementing class must also provide the following static method: - // static std::string getDescription(); - - virtual ReporterPreferences getPreferences() const = 0; - - virtual void noMatchingTestCases( std::string const& spec ) = 0; - - virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; - virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; - - virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; - virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; - - virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; - - // The return value indicates if the messages buffer should be cleared: - virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; - virtual void sectionEnded( SectionStats const& sectionStats ) = 0; - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; - virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; - - virtual void skipTest( TestCaseInfo const& testInfo ) = 0; - }; - - struct IReporterFactory { - virtual ~IReporterFactory(); - virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0; - virtual std::string getDescription() const = 0; - }; - - struct IReporterRegistry { - typedef std::map FactoryMap; - - virtual ~IReporterRegistry(); - virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const = 0; - virtual FactoryMap const& getFactories() const = 0; - }; - -} - -#include -#include - -namespace Catch { - - inline std::size_t listTests( Config const& config ) { - - TestSpec testSpec = config.testSpec(); - if( config.testSpec().hasFilters() ) - Catch::cout() << "Matching test cases:\n"; - else { - Catch::cout() << "All available test cases:\n"; - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - } - - std::size_t matchedTests = 0; - TextAttributes nameAttr, tagsAttr; - nameAttr.setInitialIndent( 2 ).setIndent( 4 ); - tagsAttr.setIndent( 6 ); - - std::vector matchedTestCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - matchedTests++; - TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); - Colour::Code colour = testCaseInfo.isHidden() - ? Colour::SecondaryText - : Colour::None; - Colour colourGuard( colour ); - - Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl; - if( !testCaseInfo.tags.empty() ) - Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl; - } - - if( !config.testSpec().hasFilters() ) - Catch::cout() << pluralise( matchedTests, "test case" ) << "\n" << std::endl; - else - Catch::cout() << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl; - return matchedTests; - } - - inline std::size_t listTestsNamesOnly( Config const& config ) { - TestSpec testSpec = config.testSpec(); - if( !config.testSpec().hasFilters() ) - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - std::size_t matchedTests = 0; - std::vector matchedTestCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - matchedTests++; - TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); - Catch::cout() << testCaseInfo.name << std::endl; - } - return matchedTests; - } - - struct TagInfo { - TagInfo() : count ( 0 ) {} - void add( std::string const& spelling ) { - ++count; - spellings.insert( spelling ); - } - std::string all() const { - std::string out; - for( std::set::const_iterator it = spellings.begin(), itEnd = spellings.end(); - it != itEnd; - ++it ) - out += "[" + *it + "]"; - return out; - } - std::set spellings; - std::size_t count; - }; - - inline std::size_t listTags( Config const& config ) { - TestSpec testSpec = config.testSpec(); - if( config.testSpec().hasFilters() ) - Catch::cout() << "Tags for matching test cases:\n"; - else { - Catch::cout() << "All available tags:\n"; - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - } - - std::map tagCounts; - - std::vector matchedTestCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - for( std::set::const_iterator tagIt = it->getTestCaseInfo().tags.begin(), - tagItEnd = it->getTestCaseInfo().tags.end(); - tagIt != tagItEnd; - ++tagIt ) { - std::string tagName = *tagIt; - std::string lcaseTagName = toLower( tagName ); - std::map::iterator countIt = tagCounts.find( lcaseTagName ); - if( countIt == tagCounts.end() ) - countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; - countIt->second.add( tagName ); - } - } - - for( std::map::const_iterator countIt = tagCounts.begin(), - countItEnd = tagCounts.end(); - countIt != countItEnd; - ++countIt ) { - std::ostringstream oss; - oss << " " << std::setw(2) << countIt->second.count << " "; - Text wrapper( countIt->second.all(), TextAttributes() - .setInitialIndent( 0 ) - .setIndent( oss.str().size() ) - .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) ); - Catch::cout() << oss.str() << wrapper << "\n"; - } - Catch::cout() << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl; - return tagCounts.size(); - } - - inline std::size_t listReporters( Config const& /*config*/ ) { - Catch::cout() << "Available reporters:\n"; - IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); - IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it; - std::size_t maxNameLen = 0; - for(it = itBegin; it != itEnd; ++it ) - maxNameLen = (std::max)( maxNameLen, it->first.size() ); - - for(it = itBegin; it != itEnd; ++it ) { - Text wrapper( it->second->getDescription(), TextAttributes() - .setInitialIndent( 0 ) - .setIndent( 7+maxNameLen ) - .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) ); - Catch::cout() << " " - << it->first - << ":" - << std::string( maxNameLen - it->first.size() + 2, ' ' ) - << wrapper << "\n"; - } - Catch::cout() << std::endl; - return factories.size(); - } - - inline Option list( Config const& config ) { - Option listedCount; - if( config.listTests() ) - listedCount = listedCount.valueOr(0) + listTests( config ); - if( config.listTestNamesOnly() ) - listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); - if( config.listTags() ) - listedCount = listedCount.valueOr(0) + listTags( config ); - if( config.listReporters() ) - listedCount = listedCount.valueOr(0) + listReporters( config ); - return listedCount; - } - -} // end namespace Catch - -// #included from: internal/catch_runner_impl.hpp -#define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED - -// #included from: catch_test_case_tracker.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { -namespace SectionTracking { - - class TrackedSection { - - typedef std::map TrackedSections; - - public: - enum RunState { - NotStarted, - Executing, - ExecutingChildren, - Completed - }; - - TrackedSection( std::string const& name, TrackedSection* parent ) - : m_name( name ), m_runState( NotStarted ), m_parent( parent ) - {} - - RunState runState() const { return m_runState; } - - TrackedSection* findChild( std::string const& childName ); - TrackedSection* acquireChild( std::string const& childName ); - - void enter() { - if( m_runState == NotStarted ) - m_runState = Executing; - } - void leave(); - - TrackedSection* getParent() { - return m_parent; - } - bool hasChildren() const { - return !m_children.empty(); - } - - private: - std::string m_name; - RunState m_runState; - TrackedSections m_children; - TrackedSection* m_parent; - }; - - inline TrackedSection* TrackedSection::findChild( std::string const& childName ) { - TrackedSections::iterator it = m_children.find( childName ); - return it != m_children.end() - ? &it->second - : NULL; - } - inline TrackedSection* TrackedSection::acquireChild( std::string const& childName ) { - if( TrackedSection* child = findChild( childName ) ) - return child; - m_children.insert( std::make_pair( childName, TrackedSection( childName, this ) ) ); - return findChild( childName ); - } - inline void TrackedSection::leave() { - for( TrackedSections::const_iterator it = m_children.begin(), itEnd = m_children.end(); - it != itEnd; - ++it ) - if( it->second.runState() != Completed ) { - m_runState = ExecutingChildren; - return; - } - m_runState = Completed; - } - - class TestCaseTracker { - public: - TestCaseTracker( std::string const& testCaseName ) - : m_testCase( testCaseName, NULL ), - m_currentSection( &m_testCase ), - m_completedASectionThisRun( false ) - {} - - bool enterSection( std::string const& name ) { - TrackedSection* child = m_currentSection->acquireChild( name ); - if( m_completedASectionThisRun || child->runState() == TrackedSection::Completed ) - return false; - - m_currentSection = child; - m_currentSection->enter(); - return true; - } - void leaveSection() { - m_currentSection->leave(); - m_currentSection = m_currentSection->getParent(); - assert( m_currentSection != NULL ); - m_completedASectionThisRun = true; - } - - bool currentSectionHasChildren() const { - return m_currentSection->hasChildren(); - } - bool isCompleted() const { - return m_testCase.runState() == TrackedSection::Completed; - } - - class Guard { - public: - Guard( TestCaseTracker& tracker ) : m_tracker( tracker ) { - m_tracker.enterTestCase(); - } - ~Guard() { - m_tracker.leaveTestCase(); - } - private: - Guard( Guard const& ); - void operator = ( Guard const& ); - TestCaseTracker& m_tracker; - }; - - private: - void enterTestCase() { - m_currentSection = &m_testCase; - m_completedASectionThisRun = false; - m_testCase.enter(); - } - void leaveTestCase() { - m_testCase.leave(); - } - - TrackedSection m_testCase; - TrackedSection* m_currentSection; - bool m_completedASectionThisRun; - }; - -} // namespace SectionTracking - -using SectionTracking::TestCaseTracker; - -} // namespace Catch - -// #included from: catch_fatal_condition.hpp -#define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED - -namespace Catch { - - // Report the error condition then exit the process - inline void fatal( std::string const& message, int exitCode ) { - IContext& context = Catch::getCurrentContext(); - IResultCapture* resultCapture = context.getResultCapture(); - resultCapture->handleFatalErrorCondition( message ); - - if( Catch::alwaysTrue() ) // avoids "no return" warnings - exit( exitCode ); - } - -} // namespace Catch - -#if defined ( CATCH_PLATFORM_WINDOWS ) ///////////////////////////////////////// - -namespace Catch { - - struct FatalConditionHandler { - void reset() {} - }; - -} // namespace Catch - -#else // Not Windows - assumed to be POSIX compatible ////////////////////////// - -#include - -namespace Catch { - - struct SignalDefs { int id; const char* name; }; - extern SignalDefs signalDefs[]; - SignalDefs signalDefs[] = { - { SIGINT, "SIGINT - Terminal interrupt signal" }, - { SIGILL, "SIGILL - Illegal instruction signal" }, - { SIGFPE, "SIGFPE - Floating point error signal" }, - { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, - { SIGTERM, "SIGTERM - Termination request signal" }, - { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } - }; - - struct FatalConditionHandler { - - static void handleSignal( int sig ) { - for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) - if( sig == signalDefs[i].id ) - fatal( signalDefs[i].name, -sig ); - fatal( "", -sig ); - } - - FatalConditionHandler() : m_isSet( true ) { - for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) - signal( signalDefs[i].id, handleSignal ); - } - ~FatalConditionHandler() { - reset(); - } - void reset() { - if( m_isSet ) { - for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) - signal( signalDefs[i].id, SIG_DFL ); - m_isSet = false; - } - } - - bool m_isSet; - }; - -} // namespace Catch - -#endif // not Windows - -#include -#include - -namespace Catch { - - class StreamRedirect { - - public: - StreamRedirect( std::ostream& stream, std::string& targetString ) - : m_stream( stream ), - m_prevBuf( stream.rdbuf() ), - m_targetString( targetString ) - { - stream.rdbuf( m_oss.rdbuf() ); - } - - ~StreamRedirect() { - m_targetString += m_oss.str(); - m_stream.rdbuf( m_prevBuf ); - } - - private: - std::ostream& m_stream; - std::streambuf* m_prevBuf; - std::ostringstream m_oss; - std::string& m_targetString; - }; - - /////////////////////////////////////////////////////////////////////////// - - class RunContext : public IResultCapture, public IRunner { - - RunContext( RunContext const& ); - void operator =( RunContext const& ); - - public: - - explicit RunContext( Ptr const& config, Ptr const& reporter ) - : m_runInfo( config->name() ), - m_context( getCurrentMutableContext() ), - m_activeTestCase( NULL ), - m_config( config ), - m_reporter( reporter ), - m_prevRunner( m_context.getRunner() ), - m_prevResultCapture( m_context.getResultCapture() ), - m_prevConfig( m_context.getConfig() ) - { - m_context.setRunner( this ); - m_context.setConfig( m_config ); - m_context.setResultCapture( this ); - m_reporter->testRunStarting( m_runInfo ); - } - - virtual ~RunContext() { - m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); - m_context.setRunner( m_prevRunner ); - m_context.setConfig( NULL ); - m_context.setResultCapture( m_prevResultCapture ); - m_context.setConfig( m_prevConfig ); - } - - void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { - m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); - } - void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { - m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); - } - - Totals runTest( TestCase const& testCase ) { - Totals prevTotals = m_totals; - - std::string redirectedCout; - std::string redirectedCerr; - - TestCaseInfo testInfo = testCase.getTestCaseInfo(); - - m_reporter->testCaseStarting( testInfo ); - - m_activeTestCase = &testCase; - m_testCaseTracker = TestCaseTracker( testInfo.name ); - - do { - do { - runCurrentTest( redirectedCout, redirectedCerr ); - } - while( !m_testCaseTracker->isCompleted() && !aborting() ); - } - while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() ); - - Totals deltaTotals = m_totals.delta( prevTotals ); - m_totals.testCases += deltaTotals.testCases; - m_reporter->testCaseEnded( TestCaseStats( testInfo, - deltaTotals, - redirectedCout, - redirectedCerr, - aborting() ) ); - - m_activeTestCase = NULL; - m_testCaseTracker.reset(); - - return deltaTotals; - } - - Ptr config() const { - return m_config; - } - - private: // IResultCapture - - virtual void assertionEnded( AssertionResult const& result ) { - if( result.getResultType() == ResultWas::Ok ) { - m_totals.assertions.passed++; - } - else if( !result.isOk() ) { - m_totals.assertions.failed++; - } - - if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) ) - m_messages.clear(); - - // Reset working state - m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); - m_lastResult = result; - } - - virtual bool sectionStarted ( - SectionInfo const& sectionInfo, - Counts& assertions - ) - { - std::ostringstream oss; - oss << sectionInfo.name << "@" << sectionInfo.lineInfo; - - if( !m_testCaseTracker->enterSection( oss.str() ) ) - return false; - - m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; - - m_reporter->sectionStarting( sectionInfo ); - - assertions = m_totals.assertions; - - return true; - } - bool testForMissingAssertions( Counts& assertions ) { - if( assertions.total() != 0 || - !m_config->warnAboutMissingAssertions() || - m_testCaseTracker->currentSectionHasChildren() ) - return false; - m_totals.assertions.failed++; - assertions.failed++; - return true; - } - - virtual void sectionEnded( SectionInfo const& info, Counts const& prevAssertions, double _durationInSeconds ) { - if( std::uncaught_exception() ) { - m_unfinishedSections.push_back( UnfinishedSections( info, prevAssertions, _durationInSeconds ) ); - return; - } - - Counts assertions = m_totals.assertions - prevAssertions; - bool missingAssertions = testForMissingAssertions( assertions ); - - m_testCaseTracker->leaveSection(); - - m_reporter->sectionEnded( SectionStats( info, assertions, _durationInSeconds, missingAssertions ) ); - m_messages.clear(); - } - - virtual void pushScopedMessage( MessageInfo const& message ) { - m_messages.push_back( message ); - } - - virtual void popScopedMessage( MessageInfo const& message ) { - m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); - } - - virtual std::string getCurrentTestName() const { - return m_activeTestCase - ? m_activeTestCase->getTestCaseInfo().name - : ""; - } - - virtual const AssertionResult* getLastResult() const { - return &m_lastResult; - } - - virtual void handleFatalErrorCondition( std::string const& message ) { - ResultBuilder resultBuilder = makeUnexpectedResultBuilder(); - resultBuilder.setResultType( ResultWas::FatalErrorCondition ); - resultBuilder << message; - resultBuilder.captureExpression(); - - handleUnfinishedSections(); - - // Recreate section for test case (as we will lose the one that was in scope) - TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); - SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); - - Counts assertions; - assertions.failed = 1; - SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); - m_reporter->sectionEnded( testCaseSectionStats ); - - TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); - - Totals deltaTotals; - deltaTotals.testCases.failed = 1; - m_reporter->testCaseEnded( TestCaseStats( testInfo, - deltaTotals, - "", - "", - false ) ); - m_totals.testCases.failed++; - testGroupEnded( "", m_totals, 1, 1 ); - m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); - } - - public: - // !TBD We need to do this another way! - bool aborting() const { - return m_totals.assertions.failed == static_cast( m_config->abortAfter() ); - } - - private: - - void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { - TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); - SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); - m_reporter->sectionStarting( testCaseSection ); - Counts prevAssertions = m_totals.assertions; - double duration = 0; - try { - m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal ); - TestCaseTracker::Guard guard( *m_testCaseTracker ); - - Timer timer; - timer.start(); - if( m_reporter->getPreferences().shouldRedirectStdOut ) { - StreamRedirect coutRedir( Catch::cout(), redirectedCout ); - StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); - invokeActiveTestCase(); - } - else { - invokeActiveTestCase(); - } - duration = timer.getElapsedSeconds(); - } - catch( TestFailureException& ) { - // This just means the test was aborted due to failure - } - catch(...) { - makeUnexpectedResultBuilder().useActiveException(); - } - handleUnfinishedSections(); - m_messages.clear(); - - Counts assertions = m_totals.assertions - prevAssertions; - bool missingAssertions = testForMissingAssertions( assertions ); - - if( testCaseInfo.okToFail() ) { - std::swap( assertions.failedButOk, assertions.failed ); - m_totals.assertions.failed -= assertions.failedButOk; - m_totals.assertions.failedButOk += assertions.failedButOk; - } - - SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); - m_reporter->sectionEnded( testCaseSectionStats ); - } - - void invokeActiveTestCase() { - FatalConditionHandler fatalConditionHandler; // Handle signals - m_activeTestCase->invoke(); - fatalConditionHandler.reset(); - } - - private: - - ResultBuilder makeUnexpectedResultBuilder() const { - return ResultBuilder( m_lastAssertionInfo.macroName.c_str(), - m_lastAssertionInfo.lineInfo, - m_lastAssertionInfo.capturedExpression.c_str(), - m_lastAssertionInfo.resultDisposition ); - } - - void handleUnfinishedSections() { - // If sections ended prematurely due to an exception we stored their - // infos here so we can tear them down outside the unwind process. - for( std::vector::const_reverse_iterator it = m_unfinishedSections.rbegin(), - itEnd = m_unfinishedSections.rend(); - it != itEnd; - ++it ) - sectionEnded( it->info, it->prevAssertions, it->durationInSeconds ); - m_unfinishedSections.clear(); - } - - struct UnfinishedSections { - UnfinishedSections( SectionInfo const& _info, Counts const& _prevAssertions, double _durationInSeconds ) - : info( _info ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds ) - {} - - SectionInfo info; - Counts prevAssertions; - double durationInSeconds; - }; - - TestRunInfo m_runInfo; - IMutableContext& m_context; - TestCase const* m_activeTestCase; - Option m_testCaseTracker; - AssertionResult m_lastResult; - - Ptr m_config; - Totals m_totals; - Ptr m_reporter; - std::vector m_messages; - IRunner* m_prevRunner; - IResultCapture* m_prevResultCapture; - Ptr m_prevConfig; - AssertionInfo m_lastAssertionInfo; - std::vector m_unfinishedSections; - }; - - IResultCapture& getResultCapture() { - if( IResultCapture* capture = getCurrentContext().getResultCapture() ) - return *capture; - else - throw std::logic_error( "No result capture instance" ); - } - -} // end namespace Catch - -// #included from: internal/catch_version.h -#define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED - -namespace Catch { - - // Versioning information - struct Version { - Version( unsigned int _majorVersion, - unsigned int _minorVersion, - unsigned int _patchNumber, - std::string const& _branchName, - unsigned int _buildNumber ); - - unsigned int const majorVersion; - unsigned int const minorVersion; - unsigned int const patchNumber; - - // buildNumber is only used if branchName is not null - std::string const branchName; - unsigned int const buildNumber; - - friend std::ostream& operator << ( std::ostream& os, Version const& version ); - - private: - void operator=( Version const& ); - }; - - extern Version libraryVersion; -} - -#include -#include -#include - -namespace Catch { - - class Runner { - - public: - Runner( Ptr const& config ) - : m_config( config ) - { - openStream(); - makeReporter(); - } - - Totals runTests() { - - RunContext context( m_config.get(), m_reporter ); - - Totals totals; - - context.testGroupStarting( "all tests", 1, 1 ); // deprecated? - - TestSpec testSpec = m_config->testSpec(); - if( !testSpec.hasFilters() ) - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests - - std::vector testCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, *m_config, testCases ); - - int testsRunForGroup = 0; - for( std::vector::const_iterator it = testCases.begin(), itEnd = testCases.end(); - it != itEnd; - ++it ) { - testsRunForGroup++; - if( m_testsAlreadyRun.find( *it ) == m_testsAlreadyRun.end() ) { - - if( context.aborting() ) - break; - - totals += context.runTest( *it ); - m_testsAlreadyRun.insert( *it ); - } - } - std::vector skippedTestCases; - getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, *m_config, skippedTestCases, true ); - - for( std::vector::const_iterator it = skippedTestCases.begin(), itEnd = skippedTestCases.end(); - it != itEnd; - ++it ) - m_reporter->skipTest( *it ); - - context.testGroupEnded( "all tests", totals, 1, 1 ); - return totals; - } - - private: - void openStream() { - // Open output file, if specified - if( !m_config->getFilename().empty() ) { - m_ofs.open( m_config->getFilename().c_str() ); - if( m_ofs.fail() ) { - std::ostringstream oss; - oss << "Unable to open file: '" << m_config->getFilename() << "'"; - throw std::domain_error( oss.str() ); - } - m_config->setStreamBuf( m_ofs.rdbuf() ); - } - } - void makeReporter() { - std::string reporterName = m_config->getReporterName().empty() - ? "console" - : m_config->getReporterName(); - - m_reporter = getRegistryHub().getReporterRegistry().create( reporterName, m_config.get() ); - if( !m_reporter ) { - std::ostringstream oss; - oss << "No reporter registered with name: '" << reporterName << "'"; - throw std::domain_error( oss.str() ); - } - } - - private: - Ptr m_config; - std::ofstream m_ofs; - Ptr m_reporter; - std::set m_testsAlreadyRun; - }; - - class Session : NonCopyable { - static bool alreadyInstantiated; - - public: - - struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; }; - - Session() - : m_cli( makeCommandLineParser() ) { - if( alreadyInstantiated ) { - std::string msg = "Only one instance of Catch::Session can ever be used"; - Catch::cerr() << msg << std::endl; - throw std::logic_error( msg ); - } - alreadyInstantiated = true; - } - ~Session() { - Catch::cleanUp(); - } - - void showHelp( std::string const& processName ) { - Catch::cout() << "\nCatch v" << libraryVersion << "\n"; - - m_cli.usage( Catch::cout(), processName ); - Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; - } - - int applyCommandLine( int argc, char* const argv[], OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) { - try { - m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail ); - m_unusedTokens = m_cli.parseInto( argc, argv, m_configData ); - if( m_configData.showHelp ) - showHelp( m_configData.processName ); - m_config.reset(); - } - catch( std::exception& ex ) { - { - Colour colourGuard( Colour::Red ); - Catch::cerr() - << "\nError(s) in input:\n" - << Text( ex.what(), TextAttributes().setIndent(2) ) - << "\n\n"; - } - m_cli.usage( Catch::cout(), m_configData.processName ); - return (std::numeric_limits::max)(); - } - return 0; - } - - void useConfigData( ConfigData const& _configData ) { - m_configData = _configData; - m_config.reset(); - } - - int run( int argc, char* const argv[] ) { - - int returnCode = applyCommandLine( argc, argv ); - if( returnCode == 0 ) - returnCode = run(); - return returnCode; - } - - int run() { - if( m_configData.showHelp ) - return 0; - - try - { - config(); // Force config to be constructed - - std::srand( m_configData.rngSeed ); - - Runner runner( m_config ); - - // Handle list request - if( Option listed = list( config() ) ) - return static_cast( *listed ); - - return static_cast( runner.runTests().assertions.failed ); - } - catch( std::exception& ex ) { - Catch::cerr() << ex.what() << std::endl; - return (std::numeric_limits::max)(); - } - } - - Clara::CommandLine const& cli() const { - return m_cli; - } - std::vector const& unusedTokens() const { - return m_unusedTokens; - } - ConfigData& configData() { - return m_configData; - } - Config& config() { - if( !m_config ) - m_config = new Config( m_configData ); - return *m_config; - } - - private: - Clara::CommandLine m_cli; - std::vector m_unusedTokens; - ConfigData m_configData; - Ptr m_config; - }; - - bool Session::alreadyInstantiated = false; - -} // end namespace Catch - -// #included from: catch_registry_hub.hpp -#define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED - -// #included from: catch_test_case_registry_impl.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED - -#include -#include -#include -#include -#include - -namespace Catch { - - class TestRegistry : public ITestCaseRegistry { - struct LexSort { - bool operator() (TestCase i,TestCase j) const { return (i const& getAllTests() const { - return m_functionsInOrder; - } - - virtual std::vector const& getAllNonHiddenTests() const { - return m_nonHiddenFunctions; - } - - virtual void getFilteredTests( TestSpec const& testSpec, IConfig const& config, std::vector& matchingTestCases, bool negated = false ) const { - - for( std::vector::const_iterator it = m_functionsInOrder.begin(), - itEnd = m_functionsInOrder.end(); - it != itEnd; - ++it ) { - bool includeTest = testSpec.matches( *it ) && ( config.allowThrows() || !it->throws() ); - if( includeTest != negated ) - matchingTestCases.push_back( *it ); - } - sortTests( config, matchingTestCases ); - } - - private: - - static void sortTests( IConfig const& config, std::vector& matchingTestCases ) { - - switch( config.runOrder() ) { - case RunTests::InLexicographicalOrder: - std::sort( matchingTestCases.begin(), matchingTestCases.end(), LexSort() ); - break; - case RunTests::InRandomOrder: - { - RandomNumberGenerator rng; - std::random_shuffle( matchingTestCases.begin(), matchingTestCases.end(), rng ); - } - break; - case RunTests::InDeclarationOrder: - // already in declaration order - break; - } - } - std::set m_functions; - std::vector m_functionsInOrder; - std::vector m_nonHiddenFunctions; - size_t m_unnamedCount; - }; - - /////////////////////////////////////////////////////////////////////////// - - class FreeFunctionTestCase : public SharedImpl { - public: - - FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {} - - virtual void invoke() const { - m_fun(); - } - - private: - virtual ~FreeFunctionTestCase(); - - TestFunction m_fun; - }; - - inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) { - std::string className = classOrQualifiedMethodName; - if( startsWith( className, "&" ) ) - { - std::size_t lastColons = className.rfind( "::" ); - std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); - if( penultimateColons == std::string::npos ) - penultimateColons = 1; - className = className.substr( penultimateColons, lastColons-penultimateColons ); - } - return className; - } - - /////////////////////////////////////////////////////////////////////////// - - AutoReg::AutoReg( TestFunction function, - SourceLineInfo const& lineInfo, - NameAndDesc const& nameAndDesc ) { - registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo ); - } - - AutoReg::~AutoReg() {} - - void AutoReg::registerTestCase( ITestCase* testCase, - char const* classOrQualifiedMethodName, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ) { - - getMutableRegistryHub().registerTest - ( makeTestCase( testCase, - extractClassName( classOrQualifiedMethodName ), - nameAndDesc.name, - nameAndDesc.description, - lineInfo ) ); - } - -} // end namespace Catch - -// #included from: catch_reporter_registry.hpp -#define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED - -#include - -namespace Catch { - - class ReporterRegistry : public IReporterRegistry { - - public: - - virtual ~ReporterRegistry() { - deleteAllValues( m_factories ); - } - - virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const { - FactoryMap::const_iterator it = m_factories.find( name ); - if( it == m_factories.end() ) - return NULL; - return it->second->create( ReporterConfig( config ) ); - } - - void registerReporter( std::string const& name, IReporterFactory* factory ) { - m_factories.insert( std::make_pair( name, factory ) ); - } - - FactoryMap const& getFactories() const { - return m_factories; - } - - private: - FactoryMap m_factories; - }; -} - -// #included from: catch_exception_translator_registry.hpp -#define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED - -#ifdef __OBJC__ -#import "Foundation/Foundation.h" -#endif - -namespace Catch { - - class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { - public: - ~ExceptionTranslatorRegistry() { - deleteAll( m_translators ); - } - - virtual void registerTranslator( const IExceptionTranslator* translator ) { - m_translators.push_back( translator ); - } - - virtual std::string translateActiveException() const { - try { -#ifdef __OBJC__ - // In Objective-C try objective-c exceptions first - @try { - throw; - } - @catch (NSException *exception) { - return Catch::toString( [exception description] ); - } -#else - throw; -#endif - } - catch( TestFailureException& ) { - throw; - } - catch( std::exception& ex ) { - return ex.what(); - } - catch( std::string& msg ) { - return msg; - } - catch( const char* msg ) { - return msg; - } - catch(...) { - return tryTranslators( m_translators.begin() ); - } - } - - std::string tryTranslators( std::vector::const_iterator it ) const { - if( it == m_translators.end() ) - return "Unknown exception"; - - try { - return (*it)->translate(); - } - catch(...) { - return tryTranslators( it+1 ); - } - } - - private: - std::vector m_translators; - }; -} - -namespace Catch { - - namespace { - - class RegistryHub : public IRegistryHub, public IMutableRegistryHub { - - RegistryHub( RegistryHub const& ); - void operator=( RegistryHub const& ); - - public: // IRegistryHub - RegistryHub() { - } - virtual IReporterRegistry const& getReporterRegistry() const { - return m_reporterRegistry; - } - virtual ITestCaseRegistry const& getTestCaseRegistry() const { - return m_testCaseRegistry; - } - virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() { - return m_exceptionTranslatorRegistry; - } - - public: // IMutableRegistryHub - virtual void registerReporter( std::string const& name, IReporterFactory* factory ) { - m_reporterRegistry.registerReporter( name, factory ); - } - virtual void registerTest( TestCase const& testInfo ) { - m_testCaseRegistry.registerTest( testInfo ); - } - virtual void registerTranslator( const IExceptionTranslator* translator ) { - m_exceptionTranslatorRegistry.registerTranslator( translator ); - } - - private: - TestRegistry m_testCaseRegistry; - ReporterRegistry m_reporterRegistry; - ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; - }; - - // Single, global, instance - inline RegistryHub*& getTheRegistryHub() { - static RegistryHub* theRegistryHub = NULL; - if( !theRegistryHub ) - theRegistryHub = new RegistryHub(); - return theRegistryHub; - } - } - - IRegistryHub& getRegistryHub() { - return *getTheRegistryHub(); - } - IMutableRegistryHub& getMutableRegistryHub() { - return *getTheRegistryHub(); - } - void cleanUp() { - delete getTheRegistryHub(); - getTheRegistryHub() = NULL; - cleanUpContext(); - } - std::string translateActiveException() { - return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); - } - -} // end namespace Catch - -// #included from: catch_notimplemented_exception.hpp -#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED - -#include - -namespace Catch { - - NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo ) - : m_lineInfo( lineInfo ) { - std::ostringstream oss; - oss << lineInfo << ": function "; - oss << "not implemented"; - m_what = oss.str(); - } - - const char* NotImplementedException::what() const CATCH_NOEXCEPT { - return m_what.c_str(); - } - -} // end namespace Catch - -// #included from: catch_context_impl.hpp -#define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED - -// #included from: catch_stream.hpp -#define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED - -// #included from: catch_streambuf.h -#define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED - -#include - -namespace Catch { - - class StreamBufBase : public std::streambuf { - public: - virtual ~StreamBufBase() CATCH_NOEXCEPT; - }; -} - -#include -#include -#include - -namespace Catch { - - template - class StreamBufImpl : public StreamBufBase { - char data[bufferSize]; - WriterF m_writer; - - public: - StreamBufImpl() { - setp( data, data + sizeof(data) ); - } - - ~StreamBufImpl() CATCH_NOEXCEPT { - sync(); - } - - private: - int overflow( int c ) { - sync(); - - if( c != EOF ) { - if( pbase() == epptr() ) - m_writer( std::string( 1, static_cast( c ) ) ); - else - sputc( static_cast( c ) ); - } - return 0; - } - - int sync() { - if( pbase() != pptr() ) { - m_writer( std::string( pbase(), static_cast( pptr() - pbase() ) ) ); - setp( pbase(), epptr() ); - } - return 0; - } - }; - - /////////////////////////////////////////////////////////////////////////// - - struct OutputDebugWriter { - - void operator()( std::string const&str ) { - writeToDebugConsole( str ); - } - }; - - Stream::Stream() - : streamBuf( NULL ), isOwned( false ) - {} - - Stream::Stream( std::streambuf* _streamBuf, bool _isOwned ) - : streamBuf( _streamBuf ), isOwned( _isOwned ) - {} - - void Stream::release() { - if( isOwned ) { - delete streamBuf; - streamBuf = NULL; - isOwned = false; - } - } - -#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement this functions - std::ostream& cout() { - return std::cout; - } - std::ostream& cerr() { - return std::cerr; - } -#endif -} - -namespace Catch { - - class Context : public IMutableContext { - - Context() : m_config( NULL ), m_runner( NULL ), m_resultCapture( NULL ) {} - Context( Context const& ); - void operator=( Context const& ); - - public: // IContext - virtual IResultCapture* getResultCapture() { - return m_resultCapture; - } - virtual IRunner* getRunner() { - return m_runner; - } - virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) { - return getGeneratorsForCurrentTest() - .getGeneratorInfo( fileInfo, totalSize ) - .getCurrentIndex(); - } - virtual bool advanceGeneratorsForCurrentTest() { - IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); - return generators && generators->moveNext(); - } - - virtual Ptr getConfig() const { - return m_config; - } - - public: // IMutableContext - virtual void setResultCapture( IResultCapture* resultCapture ) { - m_resultCapture = resultCapture; - } - virtual void setRunner( IRunner* runner ) { - m_runner = runner; - } - virtual void setConfig( Ptr const& config ) { - m_config = config; - } - - friend IMutableContext& getCurrentMutableContext(); - - private: - IGeneratorsForTest* findGeneratorsForCurrentTest() { - std::string testName = getResultCapture()->getCurrentTestName(); - - std::map::const_iterator it = - m_generatorsByTestName.find( testName ); - return it != m_generatorsByTestName.end() - ? it->second - : NULL; - } - - IGeneratorsForTest& getGeneratorsForCurrentTest() { - IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); - if( !generators ) { - std::string testName = getResultCapture()->getCurrentTestName(); - generators = createGeneratorsForTest(); - m_generatorsByTestName.insert( std::make_pair( testName, generators ) ); - } - return *generators; - } - - private: - Ptr m_config; - IRunner* m_runner; - IResultCapture* m_resultCapture; - std::map m_generatorsByTestName; - }; - - namespace { - Context* currentContext = NULL; - } - IMutableContext& getCurrentMutableContext() { - if( !currentContext ) - currentContext = new Context(); - return *currentContext; - } - IContext& getCurrentContext() { - return getCurrentMutableContext(); - } - - Stream createStream( std::string const& streamName ) { - if( streamName == "stdout" ) return Stream( Catch::cout().rdbuf(), false ); - if( streamName == "stderr" ) return Stream( Catch::cerr().rdbuf(), false ); - if( streamName == "debug" ) return Stream( new StreamBufImpl, true ); - - throw std::domain_error( "Unknown stream: " + streamName ); - } - - void cleanUpContext() { - delete currentContext; - currentContext = NULL; - } -} - -// #included from: catch_console_colour_impl.hpp -#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED - -namespace Catch { - namespace { - - struct IColourImpl { - virtual ~IColourImpl() {} - virtual void use( Colour::Code _colourCode ) = 0; - }; - - struct NoColourImpl : IColourImpl { - void use( Colour::Code ) {} - - static IColourImpl* instance() { - static NoColourImpl s_instance; - return &s_instance; - } - }; - - } // anon namespace -} // namespace Catch - -#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) -# ifdef CATCH_PLATFORM_WINDOWS -# define CATCH_CONFIG_COLOUR_WINDOWS -# else -# define CATCH_CONFIG_COLOUR_ANSI -# endif -#endif - -#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// - -#ifndef NOMINMAX -#define NOMINMAX -#endif - -#ifdef __AFXDLL -#include -#else -#include -#endif - -namespace Catch { -namespace { - - class Win32ColourImpl : public IColourImpl { - public: - Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) - { - CONSOLE_SCREEN_BUFFER_INFO csbiInfo; - GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); - originalAttributes = csbiInfo.wAttributes; - } - - virtual void use( Colour::Code _colourCode ) { - switch( _colourCode ) { - case Colour::None: return setTextAttribute( originalAttributes ); - case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); - case Colour::Red: return setTextAttribute( FOREGROUND_RED ); - case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); - case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); - case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); - case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); - case Colour::Grey: return setTextAttribute( 0 ); - - case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); - case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); - case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); - case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); - - case Colour::Bright: throw std::logic_error( "not a colour" ); - } - } - - private: - void setTextAttribute( WORD _textAttribute ) { - SetConsoleTextAttribute( stdoutHandle, _textAttribute ); - } - HANDLE stdoutHandle; - WORD originalAttributes; - }; - - IColourImpl* platformColourInstance() { - static Win32ColourImpl s_instance; - return &s_instance; - } - -} // end anon namespace -} // end namespace Catch - -#elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// - -#include - -namespace Catch { -namespace { - - // use POSIX/ ANSI console terminal codes - // Thanks to Adam Strzelecki for original contribution - // (http://github.com/nanoant) - // https://github.com/philsquared/Catch/pull/131 - class PosixColourImpl : public IColourImpl { - public: - virtual void use( Colour::Code _colourCode ) { - switch( _colourCode ) { - case Colour::None: - case Colour::White: return setColour( "[0m" ); - case Colour::Red: return setColour( "[0;31m" ); - case Colour::Green: return setColour( "[0;32m" ); - case Colour::Blue: return setColour( "[0:34m" ); - case Colour::Cyan: return setColour( "[0;36m" ); - case Colour::Yellow: return setColour( "[0;33m" ); - case Colour::Grey: return setColour( "[1;30m" ); - - case Colour::LightGrey: return setColour( "[0;37m" ); - case Colour::BrightRed: return setColour( "[1;31m" ); - case Colour::BrightGreen: return setColour( "[1;32m" ); - case Colour::BrightWhite: return setColour( "[1;37m" ); - - case Colour::Bright: throw std::logic_error( "not a colour" ); - } - } - static IColourImpl* instance() { - static PosixColourImpl s_instance; - return &s_instance; - } - - private: - void setColour( const char* _escapeCode ) { - Catch::cout() << '\033' << _escapeCode; - } - }; - - IColourImpl* platformColourInstance() { - Ptr config = getCurrentContext().getConfig(); - return (config && config->forceColour()) || isatty(STDOUT_FILENO) - ? PosixColourImpl::instance() - : NoColourImpl::instance(); - } - -} // end anon namespace -} // end namespace Catch - -#else // not Windows or ANSI /////////////////////////////////////////////// - -namespace Catch { - - static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } - -} // end namespace Catch - -#endif // Windows/ ANSI/ None - -namespace Catch { - - Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); } - Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast( _other ).m_moved = true; } - Colour::~Colour(){ if( !m_moved ) use( None ); } - - void Colour::use( Code _colourCode ) { - static IColourImpl* impl = isDebuggerActive() - ? NoColourImpl::instance() - : platformColourInstance(); - impl->use( _colourCode ); - } - -} // end namespace Catch - -// #included from: catch_generators_impl.hpp -#define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { - - struct GeneratorInfo : IGeneratorInfo { - - GeneratorInfo( std::size_t size ) - : m_size( size ), - m_currentIndex( 0 ) - {} - - bool moveNext() { - if( ++m_currentIndex == m_size ) { - m_currentIndex = 0; - return false; - } - return true; - } - - std::size_t getCurrentIndex() const { - return m_currentIndex; - } - - std::size_t m_size; - std::size_t m_currentIndex; - }; - - /////////////////////////////////////////////////////////////////////////// - - class GeneratorsForTest : public IGeneratorsForTest { - - public: - ~GeneratorsForTest() { - deleteAll( m_generatorsInOrder ); - } - - IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) { - std::map::const_iterator it = m_generatorsByName.find( fileInfo ); - if( it == m_generatorsByName.end() ) { - IGeneratorInfo* info = new GeneratorInfo( size ); - m_generatorsByName.insert( std::make_pair( fileInfo, info ) ); - m_generatorsInOrder.push_back( info ); - return *info; - } - return *it->second; - } - - bool moveNext() { - std::vector::const_iterator it = m_generatorsInOrder.begin(); - std::vector::const_iterator itEnd = m_generatorsInOrder.end(); - for(; it != itEnd; ++it ) { - if( (*it)->moveNext() ) - return true; - } - return false; - } - - private: - std::map m_generatorsByName; - std::vector m_generatorsInOrder; - }; - - IGeneratorsForTest* createGeneratorsForTest() - { - return new GeneratorsForTest(); - } - -} // end namespace Catch - -// #included from: catch_assertionresult.hpp -#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED - -namespace Catch { - - AssertionInfo::AssertionInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - std::string const& _capturedExpression, - ResultDisposition::Flags _resultDisposition ) - : macroName( _macroName ), - lineInfo( _lineInfo ), - capturedExpression( _capturedExpression ), - resultDisposition( _resultDisposition ) - {} - - AssertionResult::AssertionResult() {} - - AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) - : m_info( info ), - m_resultData( data ) - {} - - AssertionResult::~AssertionResult() {} - - // Result was a success - bool AssertionResult::succeeded() const { - return Catch::isOk( m_resultData.resultType ); - } - - // Result was a success, or failure is suppressed - bool AssertionResult::isOk() const { - return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); - } - - ResultWas::OfType AssertionResult::getResultType() const { - return m_resultData.resultType; - } - - bool AssertionResult::hasExpression() const { - return !m_info.capturedExpression.empty(); - } - - bool AssertionResult::hasMessage() const { - return !m_resultData.message.empty(); - } - - std::string AssertionResult::getExpression() const { - if( isFalseTest( m_info.resultDisposition ) ) - return "!" + m_info.capturedExpression; - else - return m_info.capturedExpression; - } - std::string AssertionResult::getExpressionInMacro() const { - if( m_info.macroName.empty() ) - return m_info.capturedExpression; - else - return m_info.macroName + "( " + m_info.capturedExpression + " )"; - } - - bool AssertionResult::hasExpandedExpression() const { - return hasExpression() && getExpandedExpression() != getExpression(); - } - - std::string AssertionResult::getExpandedExpression() const { - return m_resultData.reconstructedExpression; - } - - std::string AssertionResult::getMessage() const { - return m_resultData.message; - } - SourceLineInfo AssertionResult::getSourceInfo() const { - return m_info.lineInfo; - } - - std::string AssertionResult::getTestMacroName() const { - return m_info.macroName; - } - -} // end namespace Catch - -// #included from: catch_test_case_info.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED - -namespace Catch { - - inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { - if( startsWith( tag, "." ) || - tag == "hide" || - tag == "!hide" ) - return TestCaseInfo::IsHidden; - else if( tag == "!throws" ) - return TestCaseInfo::Throws; - else if( tag == "!shouldfail" ) - return TestCaseInfo::ShouldFail; - else if( tag == "!mayfail" ) - return TestCaseInfo::MayFail; - else - return TestCaseInfo::None; - } - inline bool isReservedTag( std::string const& tag ) { - return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] ); - } - inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { - if( isReservedTag( tag ) ) { - { - Colour colourGuard( Colour::Red ); - Catch::cerr() - << "Tag name [" << tag << "] not allowed.\n" - << "Tag names starting with non alpha-numeric characters are reserved\n"; - } - { - Colour colourGuard( Colour::FileName ); - Catch::cerr() << _lineInfo << std::endl; - } - exit(1); - } - } - - TestCase makeTestCase( ITestCase* _testCase, - std::string const& _className, - std::string const& _name, - std::string const& _descOrTags, - SourceLineInfo const& _lineInfo ) - { - bool isHidden( startsWith( _name, "./" ) ); // Legacy support - - // Parse out tags - std::set tags; - std::string desc, tag; - bool inTag = false; - for( std::size_t i = 0; i < _descOrTags.size(); ++i ) { - char c = _descOrTags[i]; - if( !inTag ) { - if( c == '[' ) - inTag = true; - else - desc += c; - } - else { - if( c == ']' ) { - TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); - if( prop == TestCaseInfo::IsHidden ) - isHidden = true; - else if( prop == TestCaseInfo::None ) - enforceNotReservedTag( tag, _lineInfo ); - - tags.insert( tag ); - tag.clear(); - inTag = false; - } - else - tag += c; - } - } - if( isHidden ) { - tags.insert( "hide" ); - tags.insert( "." ); - } - - TestCaseInfo info( _name, _className, desc, tags, _lineInfo ); - return TestCase( _testCase, info ); - } - - TestCaseInfo::TestCaseInfo( std::string const& _name, - std::string const& _className, - std::string const& _description, - std::set const& _tags, - SourceLineInfo const& _lineInfo ) - : name( _name ), - className( _className ), - description( _description ), - tags( _tags ), - lineInfo( _lineInfo ), - properties( None ) - { - std::ostringstream oss; - for( std::set::const_iterator it = _tags.begin(), itEnd = _tags.end(); it != itEnd; ++it ) { - oss << "[" << *it << "]"; - std::string lcaseTag = toLower( *it ); - properties = static_cast( properties | parseSpecialTag( lcaseTag ) ); - lcaseTags.insert( lcaseTag ); - } - tagsAsString = oss.str(); - } - - TestCaseInfo::TestCaseInfo( TestCaseInfo const& other ) - : name( other.name ), - className( other.className ), - description( other.description ), - tags( other.tags ), - lcaseTags( other.lcaseTags ), - tagsAsString( other.tagsAsString ), - lineInfo( other.lineInfo ), - properties( other.properties ) - {} - - bool TestCaseInfo::isHidden() const { - return ( properties & IsHidden ) != 0; - } - bool TestCaseInfo::throws() const { - return ( properties & Throws ) != 0; - } - bool TestCaseInfo::okToFail() const { - return ( properties & (ShouldFail | MayFail ) ) != 0; - } - bool TestCaseInfo::expectedToFail() const { - return ( properties & (ShouldFail ) ) != 0; - } - - TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {} - - TestCase::TestCase( TestCase const& other ) - : TestCaseInfo( other ), - test( other.test ) - {} - - TestCase TestCase::withName( std::string const& _newName ) const { - TestCase other( *this ); - other.name = _newName; - return other; - } - - void TestCase::swap( TestCase& other ) { - test.swap( other.test ); - name.swap( other.name ); - className.swap( other.className ); - description.swap( other.description ); - tags.swap( other.tags ); - lcaseTags.swap( other.lcaseTags ); - tagsAsString.swap( other.tagsAsString ); - std::swap( TestCaseInfo::properties, static_cast( other ).properties ); - std::swap( lineInfo, other.lineInfo ); - } - - void TestCase::invoke() const { - test->invoke(); - } - - bool TestCase::operator == ( TestCase const& other ) const { - return test.get() == other.test.get() && - name == other.name && - className == other.className; - } - - bool TestCase::operator < ( TestCase const& other ) const { - return name < other.name; - } - TestCase& TestCase::operator = ( TestCase const& other ) { - TestCase temp( other ); - swap( temp ); - return *this; - } - - TestCaseInfo const& TestCase::getTestCaseInfo() const - { - return *this; - } - -} // end namespace Catch - -// #included from: catch_version.hpp -#define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED - -namespace Catch { - - Version::Version - ( unsigned int _majorVersion, - unsigned int _minorVersion, - unsigned int _patchNumber, - std::string const& _branchName, - unsigned int _buildNumber ) - : majorVersion( _majorVersion ), - minorVersion( _minorVersion ), - patchNumber( _patchNumber ), - branchName( _branchName ), - buildNumber( _buildNumber ) - {} - - std::ostream& operator << ( std::ostream& os, Version const& version ) { - os << version.majorVersion << "." - << version.minorVersion << "." - << version.patchNumber; - - if( !version.branchName.empty() ) { - os << "-" << version.branchName - << "." << version.buildNumber; - } - return os; - } - - Version libraryVersion( 1, 2, 1, "", 0 ); - -} - -// #included from: catch_message.hpp -#define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED - -namespace Catch { - - MessageInfo::MessageInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - ResultWas::OfType _type ) - : macroName( _macroName ), - lineInfo( _lineInfo ), - type( _type ), - sequence( ++globalCount ) - {} - - // This may need protecting if threading support is added - unsigned int MessageInfo::globalCount = 0; - - //////////////////////////////////////////////////////////////////////////// - - ScopedMessage::ScopedMessage( MessageBuilder const& builder ) - : m_info( builder.m_info ) - { - m_info.message = builder.m_stream.str(); - getResultCapture().pushScopedMessage( m_info ); - } - ScopedMessage::ScopedMessage( ScopedMessage const& other ) - : m_info( other.m_info ) - {} - - ScopedMessage::~ScopedMessage() { - getResultCapture().popScopedMessage( m_info ); - } - -} // end namespace Catch - -// #included from: catch_legacy_reporter_adapter.hpp -#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED - -// #included from: catch_legacy_reporter_adapter.h -#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED - -namespace Catch -{ - // Deprecated - struct IReporter : IShared { - virtual ~IReporter(); - - virtual bool shouldRedirectStdout() const = 0; - - virtual void StartTesting() = 0; - virtual void EndTesting( Totals const& totals ) = 0; - virtual void StartGroup( std::string const& groupName ) = 0; - virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0; - virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0; - virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0; - virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0; - virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0; - virtual void NoAssertionsInSection( std::string const& sectionName ) = 0; - virtual void NoAssertionsInTestCase( std::string const& testName ) = 0; - virtual void Aborted() = 0; - virtual void Result( AssertionResult const& result ) = 0; - }; - - class LegacyReporterAdapter : public SharedImpl - { - public: - LegacyReporterAdapter( Ptr const& legacyReporter ); - virtual ~LegacyReporterAdapter(); - - virtual ReporterPreferences getPreferences() const; - virtual void noMatchingTestCases( std::string const& ); - virtual void testRunStarting( TestRunInfo const& ); - virtual void testGroupStarting( GroupInfo const& groupInfo ); - virtual void testCaseStarting( TestCaseInfo const& testInfo ); - virtual void sectionStarting( SectionInfo const& sectionInfo ); - virtual void assertionStarting( AssertionInfo const& ); - virtual bool assertionEnded( AssertionStats const& assertionStats ); - virtual void sectionEnded( SectionStats const& sectionStats ); - virtual void testCaseEnded( TestCaseStats const& testCaseStats ); - virtual void testGroupEnded( TestGroupStats const& testGroupStats ); - virtual void testRunEnded( TestRunStats const& testRunStats ); - virtual void skipTest( TestCaseInfo const& ); - - private: - Ptr m_legacyReporter; - }; -} - -namespace Catch -{ - LegacyReporterAdapter::LegacyReporterAdapter( Ptr const& legacyReporter ) - : m_legacyReporter( legacyReporter ) - {} - LegacyReporterAdapter::~LegacyReporterAdapter() {} - - ReporterPreferences LegacyReporterAdapter::getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout(); - return prefs; - } - - void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {} - void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) { - m_legacyReporter->StartTesting(); - } - void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) { - m_legacyReporter->StartGroup( groupInfo.name ); - } - void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) { - m_legacyReporter->StartTestCase( testInfo ); - } - void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) { - m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description ); - } - void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) { - // Not on legacy interface - } - - bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) { - if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { - for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); - it != itEnd; - ++it ) { - if( it->type == ResultWas::Info ) { - ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal ); - rb << it->message; - rb.setResultType( ResultWas::Info ); - AssertionResult result = rb.build(); - m_legacyReporter->Result( result ); - } - } - } - m_legacyReporter->Result( assertionStats.assertionResult ); - return true; - } - void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) { - if( sectionStats.missingAssertions ) - m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name ); - m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions ); - } - void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) { - m_legacyReporter->EndTestCase - ( testCaseStats.testInfo, - testCaseStats.totals, - testCaseStats.stdOut, - testCaseStats.stdErr ); - } - void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) { - if( testGroupStats.aborting ) - m_legacyReporter->Aborted(); - m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals ); - } - void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) { - m_legacyReporter->EndTesting( testRunStats.totals ); - } - void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) { - } -} - -// #included from: catch_timer.hpp - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wc++11-long-long" -#endif - -#ifdef CATCH_PLATFORM_WINDOWS -#include -#else -#include -#endif - -namespace Catch { - - namespace { -#ifdef CATCH_PLATFORM_WINDOWS - uint64_t getCurrentTicks() { - static uint64_t hz=0, hzo=0; - if (!hz) { - QueryPerformanceFrequency( reinterpret_cast( &hz ) ); - QueryPerformanceCounter( reinterpret_cast( &hzo ) ); - } - uint64_t t; - QueryPerformanceCounter( reinterpret_cast( &t ) ); - return ((t-hzo)*1000000)/hz; - } -#else - uint64_t getCurrentTicks() { - timeval t; - gettimeofday(&t,NULL); - return static_cast( t.tv_sec ) * 1000000ull + static_cast( t.tv_usec ); - } -#endif - } - - void Timer::start() { - m_ticks = getCurrentTicks(); - } - unsigned int Timer::getElapsedMicroseconds() const { - return static_cast(getCurrentTicks() - m_ticks); - } - unsigned int Timer::getElapsedMilliseconds() const { - return static_cast(getElapsedMicroseconds()/1000); - } - double Timer::getElapsedSeconds() const { - return getElapsedMicroseconds()/1000000.0; - } - -} // namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif -// #included from: catch_common.hpp -#define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED - -namespace Catch { - - bool startsWith( std::string const& s, std::string const& prefix ) { - return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix; - } - bool endsWith( std::string const& s, std::string const& suffix ) { - return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix; - } - bool contains( std::string const& s, std::string const& infix ) { - return s.find( infix ) != std::string::npos; - } - void toLowerInPlace( std::string& s ) { - std::transform( s.begin(), s.end(), s.begin(), ::tolower ); - } - std::string toLower( std::string const& s ) { - std::string lc = s; - toLowerInPlace( lc ); - return lc; - } - std::string trim( std::string const& str ) { - static char const* whitespaceChars = "\n\r\t "; - std::string::size_type start = str.find_first_not_of( whitespaceChars ); - std::string::size_type end = str.find_last_not_of( whitespaceChars ); - - return start != std::string::npos ? str.substr( start, 1+end-start ) : ""; - } - - bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { - bool replaced = false; - std::size_t i = str.find( replaceThis ); - while( i != std::string::npos ) { - replaced = true; - str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); - if( i < str.size()-withThis.size() ) - i = str.find( replaceThis, i+withThis.size() ); - else - i = std::string::npos; - } - return replaced; - } - - pluralise::pluralise( std::size_t count, std::string const& label ) - : m_count( count ), - m_label( label ) - {} - - std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { - os << pluraliser.m_count << " " << pluraliser.m_label; - if( pluraliser.m_count != 1 ) - os << "s"; - return os; - } - - SourceLineInfo::SourceLineInfo() : line( 0 ){} - SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) - : file( _file ), - line( _line ) - {} - SourceLineInfo::SourceLineInfo( SourceLineInfo const& other ) - : file( other.file ), - line( other.line ) - {} - bool SourceLineInfo::empty() const { - return file.empty(); - } - bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const { - return line == other.line && file == other.file; - } - bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const { - return line < other.line || ( line == other.line && file < other.file ); - } - - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { -#ifndef __GNUG__ - os << info.file << "(" << info.line << ")"; -#else - os << info.file << ":" << info.line; -#endif - return os; - } - - void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) { - std::ostringstream oss; - oss << locationInfo << ": Internal Catch error: '" << message << "'"; - if( alwaysTrue() ) - throw std::logic_error( oss.str() ); - } -} - -// #included from: catch_section.hpp -#define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED - -namespace Catch { - - SectionInfo::SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name, - std::string const& _description ) - : name( _name ), - description( _description ), - lineInfo( _lineInfo ) - {} - - Section::Section( SectionInfo const& info ) - : m_info( info ), - m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) - { - m_timer.start(); - } - - Section::~Section() { - if( m_sectionIncluded ) - getResultCapture().sectionEnded( m_info, m_assertions, m_timer.getElapsedSeconds() ); - } - - // This indicates whether the section should be executed or not - Section::operator bool() const { - return m_sectionIncluded; - } - -} // end namespace Catch - -// #included from: catch_debugger.hpp -#define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED - -#include - -#ifdef CATCH_PLATFORM_MAC - - #include - #include - #include - #include - #include - - namespace Catch{ - - // The following function is taken directly from the following technical note: - // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html - - // Returns true if the current process is being debugged (either - // running under the debugger or has a debugger attached post facto). - bool isDebuggerActive(){ - - int mib[4]; - struct kinfo_proc info; - size_t size; - - // Initialize the flags so that, if sysctl fails for some bizarre - // reason, we get a predictable result. - - info.kp_proc.p_flag = 0; - - // Initialize mib, which tells sysctl the info we want, in this case - // we're looking for information about a specific process ID. - - mib[0] = CTL_KERN; - mib[1] = KERN_PROC; - mib[2] = KERN_PROC_PID; - mib[3] = getpid(); - - // Call sysctl. - - size = sizeof(info); - if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0) != 0 ) { - Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; - return false; - } - - // We're being debugged if the P_TRACED flag is set. - - return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); - } - } // namespace Catch - -#elif defined(_MSC_VER) - extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); - namespace Catch { - bool isDebuggerActive() { - return IsDebuggerPresent() != 0; - } - } -#elif defined(__MINGW32__) - extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); - namespace Catch { - bool isDebuggerActive() { - return IsDebuggerPresent() != 0; - } - } -#else - namespace Catch { - inline bool isDebuggerActive() { return false; } - } -#endif // Platform - -#ifdef CATCH_PLATFORM_WINDOWS - extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* ); - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - ::OutputDebugStringA( text.c_str() ); - } - } -#else - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - // !TBD: Need a version for Mac/ XCode and other IDEs - Catch::cout() << text; - } - } -#endif // Platform - -// #included from: catch_tostring.hpp -#define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED - -namespace Catch { - -namespace Detail { - - std::string unprintableString = "{?}"; - - namespace { - struct Endianness { - enum Arch { Big, Little }; - - static Arch which() { - union _{ - int asInt; - char asChar[sizeof (int)]; - } u; - - u.asInt = 1; - return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; - } - }; - } - - std::string rawMemoryToString( const void *object, std::size_t size ) - { - // Reverse order for little endian architectures - int i = 0, end = static_cast( size ), inc = 1; - if( Endianness::which() == Endianness::Little ) { - i = end-1; - end = inc = -1; - } - - unsigned char const *bytes = static_cast(object); - std::ostringstream os; - os << "0x" << std::setfill('0') << std::hex; - for( ; i != end; i += inc ) - os << std::setw(2) << static_cast(bytes[i]); - return os.str(); - } -} - -std::string toString( std::string const& value ) { - std::string s = value; - if( getCurrentContext().getConfig()->showInvisibles() ) { - for(size_t i = 0; i < s.size(); ++i ) { - std::string subs; - switch( s[i] ) { - case '\n': subs = "\\n"; break; - case '\t': subs = "\\t"; break; - default: break; - } - if( !subs.empty() ) { - s = s.substr( 0, i ) + subs + s.substr( i+1 ); - ++i; - } - } - } - return "\"" + s + "\""; -} -std::string toString( std::wstring const& value ) { - - std::string s; - s.reserve( value.size() ); - for(size_t i = 0; i < value.size(); ++i ) - s += value[i] <= 0xff ? static_cast( value[i] ) : '?'; - return Catch::toString( s ); -} - -std::string toString( const char* const value ) { - return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" ); -} - -std::string toString( char* const value ) { - return Catch::toString( static_cast( value ) ); -} - -std::string toString( const wchar_t* const value ) -{ - return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" ); -} - -std::string toString( wchar_t* const value ) -{ - return Catch::toString( static_cast( value ) ); -} - -std::string toString( int value ) { - std::ostringstream oss; - oss << value; - if( value >= 255 ) - oss << " (0x" << std::hex << value << ")"; - return oss.str(); -} - -std::string toString( unsigned long value ) { - std::ostringstream oss; - oss << value; - if( value >= 255 ) - oss << " (0x" << std::hex << value << ")"; - return oss.str(); -} - -std::string toString( unsigned int value ) { - return Catch::toString( static_cast( value ) ); -} - -template -std::string fpToString( T value, int precision ) { - std::ostringstream oss; - oss << std::setprecision( precision ) - << std::fixed - << value; - std::string d = oss.str(); - std::size_t i = d.find_last_not_of( '0' ); - if( i != std::string::npos && i != d.size()-1 ) { - if( d[i] == '.' ) - i++; - d = d.substr( 0, i+1 ); - } - return d; -} - -std::string toString( const double value ) { - return fpToString( value, 10 ); -} -std::string toString( const float value ) { - return fpToString( value, 5 ) + "f"; -} - -std::string toString( bool value ) { - return value ? "true" : "false"; -} - -std::string toString( char value ) { - return value < ' ' - ? toString( static_cast( value ) ) - : Detail::makeString( value ); -} - -std::string toString( signed char value ) { - return toString( static_cast( value ) ); -} - -std::string toString( unsigned char value ) { - return toString( static_cast( value ) ); -} - -#ifdef CATCH_CONFIG_CPP11_NULLPTR -std::string toString( std::nullptr_t ) { - return "nullptr"; -} -#endif - -#ifdef __OBJC__ - std::string toString( NSString const * const& nsstring ) { - if( !nsstring ) - return "nil"; - return "@" + toString([nsstring UTF8String]); - } - std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) { - if( !nsstring ) - return "nil"; - return "@" + toString([nsstring UTF8String]); - } - std::string toString( NSObject* const& nsObject ) { - return toString( [nsObject description] ); - } -#endif - -} // end namespace Catch - -// #included from: catch_result_builder.hpp -#define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED - -namespace Catch { - - ResultBuilder::ResultBuilder( char const* macroName, - SourceLineInfo const& lineInfo, - char const* capturedExpression, - ResultDisposition::Flags resultDisposition ) - : m_assertionInfo( macroName, lineInfo, capturedExpression, resultDisposition ), - m_shouldDebugBreak( false ), - m_shouldThrow( false ) - {} - - ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) { - m_data.resultType = result; - return *this; - } - ResultBuilder& ResultBuilder::setResultType( bool result ) { - m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; - return *this; - } - ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) { - m_exprComponents.lhs = lhs; - return *this; - } - ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) { - m_exprComponents.rhs = rhs; - return *this; - } - ResultBuilder& ResultBuilder::setOp( std::string const& op ) { - m_exprComponents.op = op; - return *this; - } - - void ResultBuilder::endExpression() { - m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition ); - captureExpression(); - } - - void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { - m_assertionInfo.resultDisposition = resultDisposition; - m_stream.oss << Catch::translateActiveException(); - captureResult( ResultWas::ThrewException ); - } - - void ResultBuilder::captureResult( ResultWas::OfType resultType ) { - setResultType( resultType ); - captureExpression(); - } - - void ResultBuilder::captureExpression() { - AssertionResult result = build(); - getResultCapture().assertionEnded( result ); - - if( !result.isOk() ) { - if( getCurrentContext().getConfig()->shouldDebugBreak() ) - m_shouldDebugBreak = true; - if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) ) - m_shouldThrow = true; - } - } - void ResultBuilder::react() { - if( m_shouldThrow ) - throw Catch::TestFailureException(); - } - - bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; } - bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); } - - AssertionResult ResultBuilder::build() const - { - assert( m_data.resultType != ResultWas::Unknown ); - - AssertionResultData data = m_data; - - // Flip bool results if testFalse is set - if( m_exprComponents.testFalse ) { - if( data.resultType == ResultWas::Ok ) - data.resultType = ResultWas::ExpressionFailed; - else if( data.resultType == ResultWas::ExpressionFailed ) - data.resultType = ResultWas::Ok; - } - - data.message = m_stream.oss.str(); - data.reconstructedExpression = reconstructExpression(); - if( m_exprComponents.testFalse ) { - if( m_exprComponents.op == "" ) - data.reconstructedExpression = "!" + data.reconstructedExpression; - else - data.reconstructedExpression = "!(" + data.reconstructedExpression + ")"; - } - return AssertionResult( m_assertionInfo, data ); - } - std::string ResultBuilder::reconstructExpression() const { - if( m_exprComponents.op == "" ) - return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs; - else if( m_exprComponents.op == "matches" ) - return m_exprComponents.lhs + " " + m_exprComponents.rhs; - else if( m_exprComponents.op != "!" ) { - if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 && - m_exprComponents.lhs.find("\n") == std::string::npos && - m_exprComponents.rhs.find("\n") == std::string::npos ) - return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs; - else - return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs; - } - else - return "{can't expand - use " + m_assertionInfo.macroName + "_FALSE( " + m_assertionInfo.capturedExpression.substr(1) + " ) instead of " + m_assertionInfo.macroName + "( " + m_assertionInfo.capturedExpression + " ) for better diagnostics}"; - } - -} // end namespace Catch - -// #included from: catch_tag_alias_registry.hpp -#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED - -// #included from: catch_tag_alias_registry.h -#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED - -#include - -namespace Catch { - - class TagAliasRegistry : public ITagAliasRegistry { - public: - virtual ~TagAliasRegistry(); - virtual Option find( std::string const& alias ) const; - virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; - void add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); - static TagAliasRegistry& get(); - - private: - std::map m_registry; - }; - -} // end namespace Catch - -#include -#include - -namespace Catch { - - TagAliasRegistry::~TagAliasRegistry() {} - - Option TagAliasRegistry::find( std::string const& alias ) const { - std::map::const_iterator it = m_registry.find( alias ); - if( it != m_registry.end() ) - return it->second; - else - return Option(); - } - - std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { - std::string expandedTestSpec = unexpandedTestSpec; - for( std::map::const_iterator it = m_registry.begin(), itEnd = m_registry.end(); - it != itEnd; - ++it ) { - std::size_t pos = expandedTestSpec.find( it->first ); - if( pos != std::string::npos ) { - expandedTestSpec = expandedTestSpec.substr( 0, pos ) + - it->second.tag + - expandedTestSpec.substr( pos + it->first.size() ); - } - } - return expandedTestSpec; - } - - void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { - - if( !startsWith( alias, "[@" ) || !endsWith( alias, "]" ) ) { - std::ostringstream oss; - oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo; - throw std::domain_error( oss.str().c_str() ); - } - if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { - std::ostringstream oss; - oss << "error: tag alias, \"" << alias << "\" already registered.\n" - << "\tFirst seen at " << find(alias)->lineInfo << "\n" - << "\tRedefined at " << lineInfo; - throw std::domain_error( oss.str().c_str() ); - } - } - - TagAliasRegistry& TagAliasRegistry::get() { - static TagAliasRegistry instance; - return instance; - - } - - ITagAliasRegistry::~ITagAliasRegistry() {} - ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); } - - RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { - try { - TagAliasRegistry::get().add( alias, tag, lineInfo ); - } - catch( std::exception& ex ) { - Colour colourGuard( Colour::Red ); - Catch::cerr() << ex.what() << std::endl; - exit(1); - } - } - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_xml.hpp -#define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED - -// #included from: catch_reporter_bases.hpp -#define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED - -#include - -namespace Catch { - - struct StreamingReporterBase : SharedImpl { - - StreamingReporterBase( ReporterConfig const& _config ) - : m_config( _config.fullConfig() ), - stream( _config.stream() ) - {} - - virtual ~StreamingReporterBase(); - - virtual void noMatchingTestCases( std::string const& ) {} - - virtual void testRunStarting( TestRunInfo const& _testRunInfo ) { - currentTestRunInfo = _testRunInfo; - } - virtual void testGroupStarting( GroupInfo const& _groupInfo ) { - currentGroupInfo = _groupInfo; - } - - virtual void testCaseStarting( TestCaseInfo const& _testInfo ) { - currentTestCaseInfo = _testInfo; - } - virtual void sectionStarting( SectionInfo const& _sectionInfo ) { - m_sectionStack.push_back( _sectionInfo ); - } - - virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) { - m_sectionStack.pop_back(); - } - virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) { - currentTestCaseInfo.reset(); - } - virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) { - currentGroupInfo.reset(); - } - virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) { - currentTestCaseInfo.reset(); - currentGroupInfo.reset(); - currentTestRunInfo.reset(); - } - - virtual void skipTest( TestCaseInfo const& ) { - // Don't do anything with this by default. - // It can optionally be overridden in the derived class. - } - - Ptr m_config; - std::ostream& stream; - - LazyStat currentTestRunInfo; - LazyStat currentGroupInfo; - LazyStat currentTestCaseInfo; - - std::vector m_sectionStack; - }; - - struct CumulativeReporterBase : SharedImpl { - template - struct Node : SharedImpl<> { - explicit Node( T const& _value ) : value( _value ) {} - virtual ~Node() {} - - typedef std::vector > ChildNodes; - T value; - ChildNodes children; - }; - struct SectionNode : SharedImpl<> { - explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {} - virtual ~SectionNode(); - - bool operator == ( SectionNode const& other ) const { - return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; - } - bool operator == ( Ptr const& other ) const { - return operator==( *other ); - } - - SectionStats stats; - typedef std::vector > ChildSections; - typedef std::vector Assertions; - ChildSections childSections; - Assertions assertions; - std::string stdOut; - std::string stdErr; - }; - - struct BySectionInfo { - BySectionInfo( SectionInfo const& other ) : m_other( other ) {} - BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} - bool operator() ( Ptr const& node ) const { - return node->stats.sectionInfo.lineInfo == m_other.lineInfo; - } - private: - void operator=( BySectionInfo const& ); - SectionInfo const& m_other; - }; - - typedef Node TestCaseNode; - typedef Node TestGroupNode; - typedef Node TestRunNode; - - CumulativeReporterBase( ReporterConfig const& _config ) - : m_config( _config.fullConfig() ), - stream( _config.stream() ) - {} - ~CumulativeReporterBase(); - - virtual void testRunStarting( TestRunInfo const& ) {} - virtual void testGroupStarting( GroupInfo const& ) {} - - virtual void testCaseStarting( TestCaseInfo const& ) {} - - virtual void sectionStarting( SectionInfo const& sectionInfo ) { - SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); - Ptr node; - if( m_sectionStack.empty() ) { - if( !m_rootSection ) - m_rootSection = new SectionNode( incompleteStats ); - node = m_rootSection; - } - else { - SectionNode& parentNode = *m_sectionStack.back(); - SectionNode::ChildSections::const_iterator it = - std::find_if( parentNode.childSections.begin(), - parentNode.childSections.end(), - BySectionInfo( sectionInfo ) ); - if( it == parentNode.childSections.end() ) { - node = new SectionNode( incompleteStats ); - parentNode.childSections.push_back( node ); - } - else - node = *it; - } - m_sectionStack.push_back( node ); - m_deepestSection = node; - } - - virtual void assertionStarting( AssertionInfo const& ) {} - - virtual bool assertionEnded( AssertionStats const& assertionStats ) { - assert( !m_sectionStack.empty() ); - SectionNode& sectionNode = *m_sectionStack.back(); - sectionNode.assertions.push_back( assertionStats ); - return true; - } - virtual void sectionEnded( SectionStats const& sectionStats ) { - assert( !m_sectionStack.empty() ); - SectionNode& node = *m_sectionStack.back(); - node.stats = sectionStats; - m_sectionStack.pop_back(); - } - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) { - Ptr node = new TestCaseNode( testCaseStats ); - assert( m_sectionStack.size() == 0 ); - node->children.push_back( m_rootSection ); - m_testCases.push_back( node ); - m_rootSection.reset(); - - assert( m_deepestSection ); - m_deepestSection->stdOut = testCaseStats.stdOut; - m_deepestSection->stdErr = testCaseStats.stdErr; - } - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) { - Ptr node = new TestGroupNode( testGroupStats ); - node->children.swap( m_testCases ); - m_testGroups.push_back( node ); - } - virtual void testRunEnded( TestRunStats const& testRunStats ) { - Ptr node = new TestRunNode( testRunStats ); - node->children.swap( m_testGroups ); - m_testRuns.push_back( node ); - testRunEndedCumulative(); - } - virtual void testRunEndedCumulative() = 0; - - virtual void skipTest( TestCaseInfo const& ) {} - - Ptr m_config; - std::ostream& stream; - std::vector m_assertions; - std::vector > > m_sections; - std::vector > m_testCases; - std::vector > m_testGroups; - - std::vector > m_testRuns; - - Ptr m_rootSection; - Ptr m_deepestSection; - std::vector > m_sectionStack; - - }; - - template - char const* getLineOfChars() { - static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; - if( !*line ) { - memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); - line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; - } - return line; - } - -} // end namespace Catch - -// #included from: ../internal/catch_reporter_registrars.hpp -#define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED - -namespace Catch { - - template - class LegacyReporterRegistrar { - - class ReporterFactory : public IReporterFactory { - virtual IStreamingReporter* create( ReporterConfig const& config ) const { - return new LegacyReporterAdapter( new T( config ) ); - } - - virtual std::string getDescription() const { - return T::getDescription(); - } - }; - - public: - - LegacyReporterRegistrar( std::string const& name ) { - getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); - } - }; - - template - class ReporterRegistrar { - - class ReporterFactory : public IReporterFactory { - - // *** Please Note ***: - // - If you end up here looking at a compiler error because it's trying to register - // your custom reporter class be aware that the native reporter interface has changed - // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via - // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter. - // However please consider updating to the new interface as the old one is now - // deprecated and will probably be removed quite soon! - // Please contact me via github if you have any questions at all about this. - // In fact, ideally, please contact me anyway to let me know you've hit this - as I have - // no idea who is actually using custom reporters at all (possibly no-one!). - // The new interface is designed to minimise exposure to interface changes in the future. - virtual IStreamingReporter* create( ReporterConfig const& config ) const { - return new T( config ); - } - - virtual std::string getDescription() const { - return T::getDescription(); - } - }; - - public: - - ReporterRegistrar( std::string const& name ) { - getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); - } - }; -} - -#define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \ - namespace{ Catch::LegacyReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } -#define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \ - namespace{ Catch::ReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } - -// #included from: ../internal/catch_xmlwriter.hpp -#define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { - - class XmlWriter { - public: - - class ScopedElement { - public: - ScopedElement( XmlWriter* writer ) - : m_writer( writer ) - {} - - ScopedElement( ScopedElement const& other ) - : m_writer( other.m_writer ){ - other.m_writer = NULL; - } - - ~ScopedElement() { - if( m_writer ) - m_writer->endElement(); - } - - ScopedElement& writeText( std::string const& text, bool indent = true ) { - m_writer->writeText( text, indent ); - return *this; - } - - template - ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { - m_writer->writeAttribute( name, attribute ); - return *this; - } - - private: - mutable XmlWriter* m_writer; - }; - - XmlWriter() - : m_tagIsOpen( false ), - m_needsNewline( false ), - m_os( &Catch::cout() ) - {} - - XmlWriter( std::ostream& os ) - : m_tagIsOpen( false ), - m_needsNewline( false ), - m_os( &os ) - {} - - ~XmlWriter() { - while( !m_tags.empty() ) - endElement(); - } - - XmlWriter& startElement( std::string const& name ) { - ensureTagClosed(); - newlineIfNecessary(); - stream() << m_indent << "<" << name; - m_tags.push_back( name ); - m_indent += " "; - m_tagIsOpen = true; - return *this; - } - - ScopedElement scopedElement( std::string const& name ) { - ScopedElement scoped( this ); - startElement( name ); - return scoped; - } - - XmlWriter& endElement() { - newlineIfNecessary(); - m_indent = m_indent.substr( 0, m_indent.size()-2 ); - if( m_tagIsOpen ) { - stream() << "/>\n"; - m_tagIsOpen = false; - } - else { - stream() << m_indent << "\n"; - } - m_tags.pop_back(); - return *this; - } - - XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) { - if( !name.empty() && !attribute.empty() ) { - stream() << " " << name << "=\""; - writeEncodedText( attribute ); - stream() << "\""; - } - return *this; - } - - XmlWriter& writeAttribute( std::string const& name, bool attribute ) { - stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\""; - return *this; - } - - template - XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { - if( !name.empty() ) - stream() << " " << name << "=\"" << attribute << "\""; - return *this; - } - - XmlWriter& writeText( std::string const& text, bool indent = true ) { - if( !text.empty() ){ - bool tagWasOpen = m_tagIsOpen; - ensureTagClosed(); - if( tagWasOpen && indent ) - stream() << m_indent; - writeEncodedText( text ); - m_needsNewline = true; - } - return *this; - } - - XmlWriter& writeComment( std::string const& text ) { - ensureTagClosed(); - stream() << m_indent << ""; - m_needsNewline = true; - return *this; - } - - XmlWriter& writeBlankLine() { - ensureTagClosed(); - stream() << "\n"; - return *this; - } - - void setStream( std::ostream& os ) { - m_os = &os; - } - - private: - XmlWriter( XmlWriter const& ); - void operator=( XmlWriter const& ); - - std::ostream& stream() { - return *m_os; - } - - void ensureTagClosed() { - if( m_tagIsOpen ) { - stream() << ">\n"; - m_tagIsOpen = false; - } - } - - void newlineIfNecessary() { - if( m_needsNewline ) { - stream() << "\n"; - m_needsNewline = false; - } - } - - void writeEncodedText( std::string const& text ) { - static const char* charsToEncode = "<&\""; - std::string mtext = text; - std::string::size_type pos = mtext.find_first_of( charsToEncode ); - while( pos != std::string::npos ) { - stream() << mtext.substr( 0, pos ); - - switch( mtext[pos] ) { - case '<': - stream() << "<"; - break; - case '&': - stream() << "&"; - break; - case '\"': - stream() << """; - break; - } - mtext = mtext.substr( pos+1 ); - pos = mtext.find_first_of( charsToEncode ); - } - stream() << mtext; - } - - bool m_tagIsOpen; - bool m_needsNewline; - std::vector m_tags; - std::string m_indent; - std::ostream* m_os; - }; - -} -namespace Catch { - class XmlReporter : public StreamingReporterBase { - public: - XmlReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ), - m_sectionDepth( 0 ) - {} - - virtual ~XmlReporter(); - - static std::string getDescription() { - return "Reports test results as an XML document"; - } - - public: // StreamingReporterBase - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = true; - return prefs; - } - - virtual void noMatchingTestCases( std::string const& s ) { - StreamingReporterBase::noMatchingTestCases( s ); - } - - virtual void testRunStarting( TestRunInfo const& testInfo ) { - StreamingReporterBase::testRunStarting( testInfo ); - m_xml.setStream( stream ); - m_xml.startElement( "Catch" ); - if( !m_config->name().empty() ) - m_xml.writeAttribute( "name", m_config->name() ); - } - - virtual void testGroupStarting( GroupInfo const& groupInfo ) { - StreamingReporterBase::testGroupStarting( groupInfo ); - m_xml.startElement( "Group" ) - .writeAttribute( "name", groupInfo.name ); - } - - virtual void testCaseStarting( TestCaseInfo const& testInfo ) { - StreamingReporterBase::testCaseStarting(testInfo); - m_xml.startElement( "TestCase" ).writeAttribute( "name", trim( testInfo.name ) ); - - if ( m_config->showDurations() == ShowDurations::Always ) - m_testCaseTimer.start(); - } - - virtual void sectionStarting( SectionInfo const& sectionInfo ) { - StreamingReporterBase::sectionStarting( sectionInfo ); - if( m_sectionDepth++ > 0 ) { - m_xml.startElement( "Section" ) - .writeAttribute( "name", trim( sectionInfo.name ) ) - .writeAttribute( "description", sectionInfo.description ); - } - } - - virtual void assertionStarting( AssertionInfo const& ) { } - - virtual bool assertionEnded( AssertionStats const& assertionStats ) { - const AssertionResult& assertionResult = assertionStats.assertionResult; - - // Print any info messages in tags. - if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { - for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); - it != itEnd; - ++it ) { - if( it->type == ResultWas::Info ) { - m_xml.scopedElement( "Info" ) - .writeText( it->message ); - } else if ( it->type == ResultWas::Warning ) { - m_xml.scopedElement( "Warning" ) - .writeText( it->message ); - } - } - } - - // Drop out if result was successful but we're not printing them. - if( !m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType()) ) - return true; - - // Print the expression if there is one. - if( assertionResult.hasExpression() ) { - m_xml.startElement( "Expression" ) - .writeAttribute( "success", assertionResult.succeeded() ) - .writeAttribute( "type", assertionResult.getTestMacroName() ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ); - - m_xml.scopedElement( "Original" ) - .writeText( assertionResult.getExpression() ); - m_xml.scopedElement( "Expanded" ) - .writeText( assertionResult.getExpandedExpression() ); - } - - // And... Print a result applicable to each result type. - switch( assertionResult.getResultType() ) { - case ResultWas::ThrewException: - m_xml.scopedElement( "Exception" ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ) - .writeText( assertionResult.getMessage() ); - break; - case ResultWas::FatalErrorCondition: - m_xml.scopedElement( "Fatal Error Condition" ) - .writeAttribute( "filename", assertionResult.getSourceInfo().file ) - .writeAttribute( "line", assertionResult.getSourceInfo().line ) - .writeText( assertionResult.getMessage() ); - break; - case ResultWas::Info: - m_xml.scopedElement( "Info" ) - .writeText( assertionResult.getMessage() ); - break; - case ResultWas::Warning: - // Warning will already have been written - break; - case ResultWas::ExplicitFailure: - m_xml.scopedElement( "Failure" ) - .writeText( assertionResult.getMessage() ); - break; - default: - break; - } - - if( assertionResult.hasExpression() ) - m_xml.endElement(); - - return true; - } - - virtual void sectionEnded( SectionStats const& sectionStats ) { - StreamingReporterBase::sectionEnded( sectionStats ); - if( --m_sectionDepth > 0 ) { - XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); - e.writeAttribute( "successes", sectionStats.assertions.passed ); - e.writeAttribute( "failures", sectionStats.assertions.failed ); - e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); - - if ( m_config->showDurations() == ShowDurations::Always ) - e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); - - m_xml.endElement(); - } - } - - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) { - StreamingReporterBase::testCaseEnded( testCaseStats ); - XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); - e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); - - if ( m_config->showDurations() == ShowDurations::Always ) - e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); - - m_xml.endElement(); - } - - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) { - StreamingReporterBase::testGroupEnded( testGroupStats ); - // TODO: Check testGroupStats.aborting and act accordingly. - m_xml.scopedElement( "OverallResults" ) - .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) - .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) - .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); - m_xml.endElement(); - } - - virtual void testRunEnded( TestRunStats const& testRunStats ) { - StreamingReporterBase::testRunEnded( testRunStats ); - m_xml.scopedElement( "OverallResults" ) - .writeAttribute( "successes", testRunStats.totals.assertions.passed ) - .writeAttribute( "failures", testRunStats.totals.assertions.failed ) - .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); - m_xml.endElement(); - } - - private: - Timer m_testCaseTimer; - XmlWriter m_xml; - int m_sectionDepth; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_junit.hpp -#define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED - -#include - -namespace Catch { - - class JunitReporter : public CumulativeReporterBase { - public: - JunitReporter( ReporterConfig const& _config ) - : CumulativeReporterBase( _config ), - xml( _config.stream() ) - {} - - ~JunitReporter(); - - static std::string getDescription() { - return "Reports test results in an XML format that looks like Ant's junitreport target"; - } - - virtual void noMatchingTestCases( std::string const& /*spec*/ ) {} - - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = true; - return prefs; - } - - virtual void testRunStarting( TestRunInfo const& runInfo ) { - CumulativeReporterBase::testRunStarting( runInfo ); - xml.startElement( "testsuites" ); - } - - virtual void testGroupStarting( GroupInfo const& groupInfo ) { - suiteTimer.start(); - stdOutForSuite.str(""); - stdErrForSuite.str(""); - unexpectedExceptions = 0; - CumulativeReporterBase::testGroupStarting( groupInfo ); - } - - virtual bool assertionEnded( AssertionStats const& assertionStats ) { - if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException ) - unexpectedExceptions++; - return CumulativeReporterBase::assertionEnded( assertionStats ); - } - - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) { - stdOutForSuite << testCaseStats.stdOut; - stdErrForSuite << testCaseStats.stdErr; - CumulativeReporterBase::testCaseEnded( testCaseStats ); - } - - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) { - double suiteTime = suiteTimer.getElapsedSeconds(); - CumulativeReporterBase::testGroupEnded( testGroupStats ); - writeGroup( *m_testGroups.back(), suiteTime ); - } - - virtual void testRunEndedCumulative() { - xml.endElement(); - } - - void writeGroup( TestGroupNode const& groupNode, double suiteTime ) { - XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); - TestGroupStats const& stats = groupNode.value; - xml.writeAttribute( "name", stats.groupInfo.name ); - xml.writeAttribute( "errors", unexpectedExceptions ); - xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); - xml.writeAttribute( "tests", stats.totals.assertions.total() ); - xml.writeAttribute( "hostname", "tbd" ); // !TBD - if( m_config->showDurations() == ShowDurations::Never ) - xml.writeAttribute( "time", "" ); - else - xml.writeAttribute( "time", suiteTime ); - xml.writeAttribute( "timestamp", "tbd" ); // !TBD - - // Write test cases - for( TestGroupNode::ChildNodes::const_iterator - it = groupNode.children.begin(), itEnd = groupNode.children.end(); - it != itEnd; - ++it ) - writeTestCase( **it ); - - xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false ); - xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false ); - } - - void writeTestCase( TestCaseNode const& testCaseNode ) { - TestCaseStats const& stats = testCaseNode.value; - - // All test cases have exactly one section - which represents the - // test case itself. That section may have 0-n nested sections - assert( testCaseNode.children.size() == 1 ); - SectionNode const& rootSection = *testCaseNode.children.front(); - - std::string className = stats.testInfo.className; - - if( className.empty() ) { - if( rootSection.childSections.empty() ) - className = "global"; - } - writeSection( className, "", rootSection ); - } - - void writeSection( std::string const& className, - std::string const& rootName, - SectionNode const& sectionNode ) { - std::string name = trim( sectionNode.stats.sectionInfo.name ); - if( !rootName.empty() ) - name = rootName + "/" + name; - - if( !sectionNode.assertions.empty() || - !sectionNode.stdOut.empty() || - !sectionNode.stdErr.empty() ) { - XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); - if( className.empty() ) { - xml.writeAttribute( "classname", name ); - xml.writeAttribute( "name", "root" ); - } - else { - xml.writeAttribute( "classname", className ); - xml.writeAttribute( "name", name ); - } - xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) ); - - writeAssertions( sectionNode ); - - if( !sectionNode.stdOut.empty() ) - xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false ); - if( !sectionNode.stdErr.empty() ) - xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false ); - } - for( SectionNode::ChildSections::const_iterator - it = sectionNode.childSections.begin(), - itEnd = sectionNode.childSections.end(); - it != itEnd; - ++it ) - if( className.empty() ) - writeSection( name, "", **it ); - else - writeSection( className, name, **it ); - } - - void writeAssertions( SectionNode const& sectionNode ) { - for( SectionNode::Assertions::const_iterator - it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end(); - it != itEnd; - ++it ) - writeAssertion( *it ); - } - void writeAssertion( AssertionStats const& stats ) { - AssertionResult const& result = stats.assertionResult; - if( !result.isOk() ) { - std::string elementName; - switch( result.getResultType() ) { - case ResultWas::ThrewException: - case ResultWas::FatalErrorCondition: - elementName = "error"; - break; - case ResultWas::ExplicitFailure: - elementName = "failure"; - break; - case ResultWas::ExpressionFailed: - elementName = "failure"; - break; - case ResultWas::DidntThrowException: - elementName = "failure"; - break; - - // We should never see these here: - case ResultWas::Info: - case ResultWas::Warning: - case ResultWas::Ok: - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - elementName = "internalError"; - break; - } - - XmlWriter::ScopedElement e = xml.scopedElement( elementName ); - - xml.writeAttribute( "message", result.getExpandedExpression() ); - xml.writeAttribute( "type", result.getTestMacroName() ); - - std::ostringstream oss; - if( !result.getMessage().empty() ) - oss << result.getMessage() << "\n"; - for( std::vector::const_iterator - it = stats.infoMessages.begin(), - itEnd = stats.infoMessages.end(); - it != itEnd; - ++it ) - if( it->type == ResultWas::Info ) - oss << it->message << "\n"; - - oss << "at " << result.getSourceInfo(); - xml.writeText( oss.str(), false ); - } - } - - XmlWriter xml; - Timer suiteTimer; - std::ostringstream stdOutForSuite; - std::ostringstream stdErrForSuite; - unsigned int unexpectedExceptions; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_console.hpp -#define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED - -namespace Catch { - - struct ConsoleReporter : StreamingReporterBase { - ConsoleReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ), - m_headerPrinted( false ) - {} - - virtual ~ConsoleReporter(); - static std::string getDescription() { - return "Reports test results as plain lines of text"; - } - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = false; - return prefs; - } - - virtual void noMatchingTestCases( std::string const& spec ) { - stream << "No test cases matched '" << spec << "'" << std::endl; - } - - virtual void assertionStarting( AssertionInfo const& ) { - } - - virtual bool assertionEnded( AssertionStats const& _assertionStats ) { - AssertionResult const& result = _assertionStats.assertionResult; - - bool printInfoMessages = true; - - // Drop out if result was successful and we're not printing those - if( !m_config->includeSuccessfulResults() && result.isOk() ) { - if( result.getResultType() != ResultWas::Warning ) - return false; - printInfoMessages = false; - } - - lazyPrint(); - - AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); - printer.print(); - stream << std::endl; - return true; - } - - virtual void sectionStarting( SectionInfo const& _sectionInfo ) { - m_headerPrinted = false; - StreamingReporterBase::sectionStarting( _sectionInfo ); - } - virtual void sectionEnded( SectionStats const& _sectionStats ) { - if( _sectionStats.missingAssertions ) { - lazyPrint(); - Colour colour( Colour::ResultError ); - if( m_sectionStack.size() > 1 ) - stream << "\nNo assertions in section"; - else - stream << "\nNo assertions in test case"; - stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; - } - if( m_headerPrinted ) { - if( m_config->showDurations() == ShowDurations::Always ) - stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl; - m_headerPrinted = false; - } - else { - if( m_config->showDurations() == ShowDurations::Always ) - stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl; - } - StreamingReporterBase::sectionEnded( _sectionStats ); - } - - virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) { - StreamingReporterBase::testCaseEnded( _testCaseStats ); - m_headerPrinted = false; - } - virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) { - if( currentGroupInfo.used ) { - printSummaryDivider(); - stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; - printTotals( _testGroupStats.totals ); - stream << "\n" << std::endl; - } - StreamingReporterBase::testGroupEnded( _testGroupStats ); - } - virtual void testRunEnded( TestRunStats const& _testRunStats ) { - printTotalsDivider( _testRunStats.totals ); - printTotals( _testRunStats.totals ); - stream << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - - class AssertionPrinter { - void operator= ( AssertionPrinter const& ); - public: - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) - : stream( _stream ), - stats( _stats ), - result( _stats.assertionResult ), - colour( Colour::None ), - message( result.getMessage() ), - messages( _stats.infoMessages ), - printInfoMessages( _printInfoMessages ) - { - switch( result.getResultType() ) { - case ResultWas::Ok: - colour = Colour::Success; - passOrFail = "PASSED"; - //if( result.hasMessage() ) - if( _stats.infoMessages.size() == 1 ) - messageLabel = "with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "with messages"; - break; - case ResultWas::ExpressionFailed: - if( result.isOk() ) { - colour = Colour::Success; - passOrFail = "FAILED - but was ok"; - } - else { - colour = Colour::Error; - passOrFail = "FAILED"; - } - if( _stats.infoMessages.size() == 1 ) - messageLabel = "with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "with messages"; - break; - case ResultWas::ThrewException: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "due to unexpected exception with message"; - break; - case ResultWas::FatalErrorCondition: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "due to a fatal error condition"; - break; - case ResultWas::DidntThrowException: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "because no exception was thrown where one was expected"; - break; - case ResultWas::Info: - messageLabel = "info"; - break; - case ResultWas::Warning: - messageLabel = "warning"; - break; - case ResultWas::ExplicitFailure: - passOrFail = "FAILED"; - colour = Colour::Error; - if( _stats.infoMessages.size() == 1 ) - messageLabel = "explicitly with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "explicitly with messages"; - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - passOrFail = "** internal error **"; - colour = Colour::Error; - break; - } - } - - void print() const { - printSourceInfo(); - if( stats.totals.assertions.total() > 0 ) { - if( result.isOk() ) - stream << "\n"; - printResultType(); - printOriginalExpression(); - printReconstructedExpression(); - } - else { - stream << "\n"; - } - printMessage(); - } - - private: - void printResultType() const { - if( !passOrFail.empty() ) { - Colour colourGuard( colour ); - stream << passOrFail << ":\n"; - } - } - void printOriginalExpression() const { - if( result.hasExpression() ) { - Colour colourGuard( Colour::OriginalExpression ); - stream << " "; - stream << result.getExpressionInMacro(); - stream << "\n"; - } - } - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - stream << "with expansion:\n"; - Colour colourGuard( Colour::ReconstructedExpression ); - stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n"; - } - } - void printMessage() const { - if( !messageLabel.empty() ) - stream << messageLabel << ":" << "\n"; - for( std::vector::const_iterator it = messages.begin(), itEnd = messages.end(); - it != itEnd; - ++it ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || it->type != ResultWas::Info ) - stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n"; - } - } - void printSourceInfo() const { - Colour colourGuard( Colour::FileName ); - stream << result.getSourceInfo() << ": "; - } - - std::ostream& stream; - AssertionStats const& stats; - AssertionResult const& result; - Colour::Code colour; - std::string passOrFail; - std::string messageLabel; - std::string message; - std::vector messages; - bool printInfoMessages; - }; - - void lazyPrint() { - - if( !currentTestRunInfo.used ) - lazyPrintRunInfo(); - if( !currentGroupInfo.used ) - lazyPrintGroupInfo(); - - if( !m_headerPrinted ) { - printTestCaseAndSectionHeader(); - m_headerPrinted = true; - } - } - void lazyPrintRunInfo() { - stream << "\n" << getLineOfChars<'~'>() << "\n"; - Colour colour( Colour::SecondaryText ); - stream << currentTestRunInfo->name - << " is a Catch v" << libraryVersion << " host application.\n" - << "Run with -? for options\n\n"; - - if( m_config->rngSeed() != 0 ) - stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; - - currentTestRunInfo.used = true; - } - void lazyPrintGroupInfo() { - if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) { - printClosedHeader( "Group: " + currentGroupInfo->name ); - currentGroupInfo.used = true; - } - } - void printTestCaseAndSectionHeader() { - assert( !m_sectionStack.empty() ); - printOpenHeader( currentTestCaseInfo->name ); - - if( m_sectionStack.size() > 1 ) { - Colour colourGuard( Colour::Headers ); - - std::vector::const_iterator - it = m_sectionStack.begin()+1, // Skip first section (test case) - itEnd = m_sectionStack.end(); - for( ; it != itEnd; ++it ) - printHeaderString( it->name, 2 ); - } - - SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; - - if( !lineInfo.empty() ){ - stream << getLineOfChars<'-'>() << "\n"; - Colour colourGuard( Colour::FileName ); - stream << lineInfo << "\n"; - } - stream << getLineOfChars<'.'>() << "\n" << std::endl; - } - - void printClosedHeader( std::string const& _name ) { - printOpenHeader( _name ); - stream << getLineOfChars<'.'>() << "\n"; - } - void printOpenHeader( std::string const& _name ) { - stream << getLineOfChars<'-'>() << "\n"; - { - Colour colourGuard( Colour::Headers ); - printHeaderString( _name ); - } - } - - // if string has a : in first line will set indent to follow it on - // subsequent lines - void printHeaderString( std::string const& _string, std::size_t indent = 0 ) { - std::size_t i = _string.find( ": " ); - if( i != std::string::npos ) - i+=2; - else - i = 0; - stream << Text( _string, TextAttributes() - .setIndent( indent+i) - .setInitialIndent( indent ) ) << "\n"; - } - - struct SummaryColumn { - - SummaryColumn( std::string const& _label, Colour::Code _colour ) - : label( _label ), - colour( _colour ) - {} - SummaryColumn addRow( std::size_t count ) { - std::ostringstream oss; - oss << count; - std::string row = oss.str(); - for( std::vector::iterator it = rows.begin(); it != rows.end(); ++it ) { - while( it->size() < row.size() ) - *it = " " + *it; - while( it->size() > row.size() ) - row = " " + row; - } - rows.push_back( row ); - return *this; - } - - std::string label; - Colour::Code colour; - std::vector rows; - - }; - - void printTotals( Totals const& totals ) { - if( totals.testCases.total() == 0 ) { - stream << Colour( Colour::Warning ) << "No tests ran\n"; - } - else if( totals.assertions.total() > 0 && totals.assertions.allPassed() ) { - stream << Colour( Colour::ResultSuccess ) << "All tests passed"; - stream << " (" - << pluralise( totals.assertions.passed, "assertion" ) << " in " - << pluralise( totals.testCases.passed, "test case" ) << ")" - << "\n"; - } - else { - - std::vector columns; - columns.push_back( SummaryColumn( "", Colour::None ) - .addRow( totals.testCases.total() ) - .addRow( totals.assertions.total() ) ); - columns.push_back( SummaryColumn( "passed", Colour::Success ) - .addRow( totals.testCases.passed ) - .addRow( totals.assertions.passed ) ); - columns.push_back( SummaryColumn( "failed", Colour::ResultError ) - .addRow( totals.testCases.failed ) - .addRow( totals.assertions.failed ) ); - columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) - .addRow( totals.testCases.failedButOk ) - .addRow( totals.assertions.failedButOk ) ); - - printSummaryRow( "test cases", columns, 0 ); - printSummaryRow( "assertions", columns, 1 ); - } - } - void printSummaryRow( std::string const& label, std::vector const& cols, std::size_t row ) { - for( std::vector::const_iterator it = cols.begin(); it != cols.end(); ++it ) { - std::string value = it->rows[row]; - if( it->label.empty() ) { - stream << label << ": "; - if( value != "0" ) - stream << value; - else - stream << Colour( Colour::Warning ) << "- none -"; - } - else if( value != "0" ) { - stream << Colour( Colour::LightGrey ) << " | "; - stream << Colour( it->colour ) - << value << " " << it->label; - } - } - stream << "\n"; - } - - static std::size_t makeRatio( std::size_t number, std::size_t total ) { - std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0; - return ( ratio == 0 && number > 0 ) ? 1 : ratio; - } - static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) { - if( i > j && i > k ) - return i; - else if( j > k ) - return j; - else - return k; - } - - void printTotalsDivider( Totals const& totals ) { - if( totals.testCases.total() > 0 ) { - std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() ); - std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() ); - std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() ); - while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 ) - findMax( failedRatio, failedButOkRatio, passedRatio )++; - while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 ) - findMax( failedRatio, failedButOkRatio, passedRatio )--; - - stream << Colour( Colour::Error ) << std::string( failedRatio, '=' ); - stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' ); - if( totals.testCases.allPassed() ) - stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' ); - else - stream << Colour( Colour::Success ) << std::string( passedRatio, '=' ); - } - else { - stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' ); - } - stream << "\n"; - } - void printSummaryDivider() { - stream << getLineOfChars<'-'>() << "\n"; - } - - private: - bool m_headerPrinted; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_compact.hpp -#define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED - -namespace Catch { - - struct CompactReporter : StreamingReporterBase { - - CompactReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - {} - - virtual ~CompactReporter(); - - static std::string getDescription() { - return "Reports test results on a single line, suitable for IDEs"; - } - - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = false; - return prefs; - } - - virtual void noMatchingTestCases( std::string const& spec ) { - stream << "No test cases matched '" << spec << "'" << std::endl; - } - - virtual void assertionStarting( AssertionInfo const& ) { - } - - virtual bool assertionEnded( AssertionStats const& _assertionStats ) { - AssertionResult const& result = _assertionStats.assertionResult; - - bool printInfoMessages = true; - - // Drop out if result was successful and we're not printing those - if( !m_config->includeSuccessfulResults() && result.isOk() ) { - if( result.getResultType() != ResultWas::Warning ) - return false; - printInfoMessages = false; - } - - AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); - printer.print(); - - stream << std::endl; - return true; - } - - virtual void testRunEnded( TestRunStats const& _testRunStats ) { - printTotals( _testRunStats.totals ); - stream << "\n" << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - class AssertionPrinter { - void operator= ( AssertionPrinter const& ); - public: - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) - : stream( _stream ) - , stats( _stats ) - , result( _stats.assertionResult ) - , messages( _stats.infoMessages ) - , itMessage( _stats.infoMessages.begin() ) - , printInfoMessages( _printInfoMessages ) - {} - - void print() { - printSourceInfo(); - - itMessage = messages.begin(); - - switch( result.getResultType() ) { - case ResultWas::Ok: - printResultType( Colour::ResultSuccess, passedString() ); - printOriginalExpression(); - printReconstructedExpression(); - if ( ! result.hasExpression() ) - printRemainingMessages( Colour::None ); - else - printRemainingMessages(); - break; - case ResultWas::ExpressionFailed: - if( result.isOk() ) - printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) ); - else - printResultType( Colour::Error, failedString() ); - printOriginalExpression(); - printReconstructedExpression(); - printRemainingMessages(); - break; - case ResultWas::ThrewException: - printResultType( Colour::Error, failedString() ); - printIssue( "unexpected exception with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::FatalErrorCondition: - printResultType( Colour::Error, failedString() ); - printIssue( "fatal error condition with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::DidntThrowException: - printResultType( Colour::Error, failedString() ); - printIssue( "expected exception, got none" ); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::Info: - printResultType( Colour::None, "info" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::Warning: - printResultType( Colour::None, "warning" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::ExplicitFailure: - printResultType( Colour::Error, failedString() ); - printIssue( "explicitly" ); - printRemainingMessages( Colour::None ); - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - printResultType( Colour::Error, "** internal error **" ); - break; - } - } - - private: - // Colour::LightGrey - - static Colour::Code dimColour() { return Colour::FileName; } - -#ifdef CATCH_PLATFORM_MAC - static const char* failedString() { return "FAILED"; } - static const char* passedString() { return "PASSED"; } -#else - static const char* failedString() { return "failed"; } - static const char* passedString() { return "passed"; } -#endif - - void printSourceInfo() const { - Colour colourGuard( Colour::FileName ); - stream << result.getSourceInfo() << ":"; - } - - void printResultType( Colour::Code colour, std::string passOrFail ) const { - if( !passOrFail.empty() ) { - { - Colour colourGuard( colour ); - stream << " " << passOrFail; - } - stream << ":"; - } - } - - void printIssue( std::string issue ) const { - stream << " " << issue; - } - - void printExpressionWas() { - if( result.hasExpression() ) { - stream << ";"; - { - Colour colour( dimColour() ); - stream << " expression was:"; - } - printOriginalExpression(); - } - } - - void printOriginalExpression() const { - if( result.hasExpression() ) { - stream << " " << result.getExpression(); - } - } - - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - { - Colour colour( dimColour() ); - stream << " for: "; - } - stream << result.getExpandedExpression(); - } - } - - void printMessage() { - if ( itMessage != messages.end() ) { - stream << " '" << itMessage->message << "'"; - ++itMessage; - } - } - - void printRemainingMessages( Colour::Code colour = dimColour() ) { - if ( itMessage == messages.end() ) - return; - - // using messages.end() directly yields compilation error: - std::vector::const_iterator itEnd = messages.end(); - const std::size_t N = static_cast( std::distance( itMessage, itEnd ) ); - - { - Colour colourGuard( colour ); - stream << " with " << pluralise( N, "message" ) << ":"; - } - - for(; itMessage != itEnd; ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || itMessage->type != ResultWas::Info ) { - stream << " '" << itMessage->message << "'"; - if ( ++itMessage != itEnd ) { - Colour colourGuard( dimColour() ); - stream << " and"; - } - } - } - } - - private: - std::ostream& stream; - AssertionStats const& stats; - AssertionResult const& result; - std::vector messages; - std::vector::const_iterator itMessage; - bool printInfoMessages; - }; - - // Colour, message variants: - // - white: No tests ran. - // - red: Failed [both/all] N test cases, failed [both/all] M assertions. - // - white: Passed [both/all] N test cases (no assertions). - // - red: Failed N tests cases, failed M assertions. - // - green: Passed [both/all] N tests cases with M assertions. - - std::string bothOrAll( std::size_t count ) const { - return count == 1 ? "" : count == 2 ? "both " : "all " ; - } - - void printTotals( const Totals& totals ) const { - if( totals.testCases.total() == 0 ) { - stream << "No tests ran."; - } - else if( totals.testCases.failed == totals.testCases.total() ) { - Colour colour( Colour::ResultError ); - const std::string qualify_assertions_failed = - totals.assertions.failed == totals.assertions.total() ? - bothOrAll( totals.assertions.failed ) : ""; - stream << - "Failed " << bothOrAll( totals.testCases.failed ) - << pluralise( totals.testCases.failed, "test case" ) << ", " - "failed " << qualify_assertions_failed << - pluralise( totals.assertions.failed, "assertion" ) << "."; - } - else if( totals.assertions.total() == 0 ) { - stream << - "Passed " << bothOrAll( totals.testCases.total() ) - << pluralise( totals.testCases.total(), "test case" ) - << " (no assertions)."; - } - else if( totals.assertions.failed ) { - Colour colour( Colour::ResultError ); - stream << - "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", " - "failed " << pluralise( totals.assertions.failed, "assertion" ) << "."; - } - else { - Colour colour( Colour::ResultSuccess ); - stream << - "Passed " << bothOrAll( totals.testCases.passed ) - << pluralise( totals.testCases.passed, "test case" ) << - " with " << pluralise( totals.assertions.passed, "assertion" ) << "."; - } - } - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter ) - -} // end namespace Catch - -namespace Catch { - NonCopyable::~NonCopyable() {} - IShared::~IShared() {} - StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {} - IContext::~IContext() {} - IResultCapture::~IResultCapture() {} - ITestCase::~ITestCase() {} - ITestCaseRegistry::~ITestCaseRegistry() {} - IRegistryHub::~IRegistryHub() {} - IMutableRegistryHub::~IMutableRegistryHub() {} - IExceptionTranslator::~IExceptionTranslator() {} - IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {} - IReporter::~IReporter() {} - IReporterFactory::~IReporterFactory() {} - IReporterRegistry::~IReporterRegistry() {} - IStreamingReporter::~IStreamingReporter() {} - AssertionStats::~AssertionStats() {} - SectionStats::~SectionStats() {} - TestCaseStats::~TestCaseStats() {} - TestGroupStats::~TestGroupStats() {} - TestRunStats::~TestRunStats() {} - CumulativeReporterBase::SectionNode::~SectionNode() {} - CumulativeReporterBase::~CumulativeReporterBase() {} - - StreamingReporterBase::~StreamingReporterBase() {} - ConsoleReporter::~ConsoleReporter() {} - CompactReporter::~CompactReporter() {} - IRunner::~IRunner() {} - IMutableContext::~IMutableContext() {} - IConfig::~IConfig() {} - XmlReporter::~XmlReporter() {} - JunitReporter::~JunitReporter() {} - TestRegistry::~TestRegistry() {} - FreeFunctionTestCase::~FreeFunctionTestCase() {} - IGeneratorInfo::~IGeneratorInfo() {} - IGeneratorsForTest::~IGeneratorsForTest() {} - TestSpec::Pattern::~Pattern() {} - TestSpec::NamePattern::~NamePattern() {} - TestSpec::TagPattern::~TagPattern() {} - TestSpec::ExcludedPattern::~ExcludedPattern() {} - - Matchers::Impl::StdString::Equals::~Equals() {} - Matchers::Impl::StdString::Contains::~Contains() {} - Matchers::Impl::StdString::StartsWith::~StartsWith() {} - Matchers::Impl::StdString::EndsWith::~EndsWith() {} - - void Config::dummy() {} -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#endif - -#ifdef CATCH_CONFIG_MAIN -// #included from: internal/catch_default_main.hpp -#define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED - -#ifndef __OBJC__ - -// Standard C/C++ main entry point -int main (int argc, char * const argv[]) { - return Catch::Session().run( argc, argv ); -} - -#else // __OBJC__ - -// Objective-C entry point -int main (int argc, char * const argv[]) { -#if !CATCH_ARC_ENABLED - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; -#endif - - Catch::registerTestMethods(); - int result = Catch::Session().run( argc, (char* const*)argv ); - -#if !CATCH_ARC_ENABLED - [pool drain]; -#endif - - return result; -} - -#endif // __OBJC__ - -#endif - -#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED -# undef CLARA_CONFIG_MAIN -#endif - -////// - -// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ -#ifdef CATCH_CONFIG_PREFIX_ALL - -#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" ) -#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE" ) - -#define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS" ) -#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" ) -#define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" ) - -#define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" ) -#define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE" ) -#define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" ) -#define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" ) -#define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" ) - -#define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" ) -#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" ) -#define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" ) - -#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" ) -#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" ) - -#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) -#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg ) -#define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" ) -#define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) -#define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" ) - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) - #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) - #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) - #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) - #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ ) - #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ ) -#else - #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) - #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) - #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) - #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) - #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg ) - #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg ) -#endif -#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) - -#define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) -#define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) - -#define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) - -// "BDD-style" convenience wrappers -#ifdef CATCH_CONFIG_VARIADIC_MACROS -#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) -#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) -#else -#define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags ) -#define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) -#endif -#define CATCH_GIVEN( desc ) CATCH_SECTION( "Given: " desc, "" ) -#define CATCH_WHEN( desc ) CATCH_SECTION( " When: " desc, "" ) -#define CATCH_AND_WHEN( desc ) CATCH_SECTION( " And: " desc, "" ) -#define CATCH_THEN( desc ) CATCH_SECTION( " Then: " desc, "" ) -#define CATCH_AND_THEN( desc ) CATCH_SECTION( " And: " desc, "" ) - -// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required -#else - -#define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "REQUIRE" ) -#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE" ) - -#define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "REQUIRE_THROWS" ) -#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" ) -#define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" ) - -#define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" ) -#define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE" ) -#define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" ) -#define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" ) -#define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" ) - -#define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS" ) -#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" ) -#define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" ) - -#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" ) -#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" ) - -#define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) -#define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg ) -#define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" ) -#define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) -#define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" ) - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) - #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) - #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) - #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) - #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ ) - #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ ) -#else - #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) - #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) - #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) - #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) - #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg ) - #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg ) -#endif -#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) - -#define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) -#define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) - -#define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) - -#endif - -#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) - -// "BDD-style" convenience wrappers -#ifdef CATCH_CONFIG_VARIADIC_MACROS -#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) -#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) -#else -#define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags ) -#define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) -#endif -#define GIVEN( desc ) SECTION( " Given: " desc, "" ) -#define WHEN( desc ) SECTION( " When: " desc, "" ) -#define AND_WHEN( desc ) SECTION( "And when: " desc, "" ) -#define THEN( desc ) SECTION( " Then: " desc, "" ) -#define AND_THEN( desc ) SECTION( " And: " desc, "" ) - -using Catch::Detail::Approx; - -// #included from: internal/catch_reenable_warnings.h - -#define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(pop) -# else -# pragma clang diagnostic pop -# endif -#elif defined __GNUC__ -# pragma GCC diagnostic pop -#endif - -#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED - diff --git a/third_party/libosmium/test/include/utils.hpp b/third_party/libosmium/test/include/utils.hpp deleted file mode 100644 index 662155abf..000000000 --- a/third_party/libosmium/test/include/utils.hpp +++ /dev/null @@ -1,18 +0,0 @@ - -#include -#include - -inline std::string with_data_dir(const char* filename) { - const char* data_dir = getenv("OSMIUM_TEST_DATA_DIR"); - - std::string result; - if (data_dir) { - result = data_dir; - result += '/'; - } - - result += filename; - - return result; -} - diff --git a/third_party/libosmium/test/include/win_mkstemp.hpp b/third_party/libosmium/test/include/win_mkstemp.hpp deleted file mode 100644 index 693c266f3..000000000 --- a/third_party/libosmium/test/include/win_mkstemp.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * mkstemp.c - * - * Provides a trivial replacement for the POSIX `mkstemp()' function, - * suitable for use in MinGW (Win32) applications. - * - * This file is part of the MinGW32 package set. - * - * Contributed by Keith Marshall - * Patched to VS2013 by alex85k - * THIS SOFTWARE IS NOT COPYRIGHTED - * - * This source code is offered for use in the public domain. You may - * use, modify or distribute it freely. - * - * This code is distributed in the hope that it will be useful but - * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY - * DISCLAIMED. This includes but is not limited to warranties of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - */ - -#ifndef WIN_MKSTEMP_H -#define WIN_MKSTEMP_H - -#include -#include -#include - -inline int mkstemp( char *templ ) -{ - int maxtry = 26, rtn = -1; - - while( maxtry-- && (rtn < 0) ) - { - char *r = _mktemp( templ ); - if( r == NULL ) - return -1; - rtn = sopen( r, O_RDWR | O_CREAT | O_EXCL | O_BINARY, SH_DENYRW, 0600 ); - } - return rtn; -} -#endif diff --git a/third_party/libosmium/test/t/area/test_area_id.cpp b/third_party/libosmium/test/t/area/test_area_id.cpp deleted file mode 100644 index fbd8d784c..000000000 --- a/third_party/libosmium/test/t/area/test_area_id.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "catch.hpp" - -#include - -TEST_CASE("area_id") { - - SECTION("object_id_to_area_id_conversion") { - REQUIRE( 46 == osmium::object_id_to_area_id( 23, osmium::item_type::way)); - REQUIRE( 47 == osmium::object_id_to_area_id( 23, osmium::item_type::relation)); - REQUIRE( 0 == osmium::object_id_to_area_id( 0, osmium::item_type::way)); - REQUIRE( 1 == osmium::object_id_to_area_id( 0, osmium::item_type::relation)); - REQUIRE(-24 == osmium::object_id_to_area_id(-12, osmium::item_type::way)); - REQUIRE(-25 == osmium::object_id_to_area_id(-12, osmium::item_type::relation)); - } - - SECTION("area_id_to_object_id_conversion") { - REQUIRE( 23 == osmium::area_id_to_object_id( 46)); - REQUIRE( 23 == osmium::area_id_to_object_id( 47)); - REQUIRE( 0 == osmium::area_id_to_object_id( 0)); - REQUIRE( 0 == osmium::area_id_to_object_id( 1)); - REQUIRE(-12 == osmium::area_id_to_object_id(-24)); - REQUIRE(-12 == osmium::area_id_to_object_id(-25)); - } - -} diff --git a/third_party/libosmium/test/t/area/test_node_ref_segment.cpp b/third_party/libosmium/test/t/area/test_node_ref_segment.cpp deleted file mode 100644 index 3261c24e1..000000000 --- a/third_party/libosmium/test/t/area/test_node_ref_segment.cpp +++ /dev/null @@ -1,129 +0,0 @@ -#include "catch.hpp" - -#include - -using osmium::area::detail::NodeRefSegment; - -TEST_CASE("NodeRefSegmentClass") { - - SECTION("instantiation_with_default_parameters") { - NodeRefSegment s; - REQUIRE(s.first().ref() == 0); - REQUIRE(s.first().location() == osmium::Location()); - REQUIRE(s.second().ref() == 0); - REQUIRE(s.second().location() == osmium::Location()); - } - - SECTION("instantiation") { - osmium::NodeRef nr1(1, { 1.2, 3.4 }); - osmium::NodeRef nr2(2, { 1.4, 3.1 }); - osmium::NodeRef nr3(3, { 1.2, 3.6 }); - osmium::NodeRef nr4(4, { 1.2, 3.7 }); - - NodeRefSegment s1(nr1, nr2, nullptr, nullptr); - REQUIRE(s1.first().ref() == 1); - REQUIRE(s1.second().ref() == 2); - - NodeRefSegment s2(nr2, nr3, nullptr, nullptr); - REQUIRE(s2.first().ref() == 3); - REQUIRE(s2.second().ref() == 2); - - NodeRefSegment s3(nr3, nr4, nullptr, nullptr); - REQUIRE(s3.first().ref() == 3); - REQUIRE(s3.second().ref() == 4); - } - - SECTION("intersection") { - NodeRefSegment s1({ 1, {0.0, 0.0}}, { 2, {2.0, 2.0}}, nullptr, nullptr); - NodeRefSegment s2({ 3, {0.0, 2.0}}, { 4, {2.0, 0.0}}, nullptr, nullptr); - NodeRefSegment s3({ 5, {2.0, 0.0}}, { 6, {4.0, 2.0}}, nullptr, nullptr); - NodeRefSegment s4({ 7, {1.0, 0.0}}, { 8, {3.0, 2.0}}, nullptr, nullptr); - NodeRefSegment s5({ 9, {0.0, 4.0}}, {10, {4.0, 0.0}}, nullptr, nullptr); - NodeRefSegment s6({11, {0.0, 0.0}}, {12, {1.0, 1.0}}, nullptr, nullptr); - NodeRefSegment s7({13, {1.0, 1.0}}, {14, {3.0, 3.0}}, nullptr, nullptr); - - REQUIRE(calculate_intersection(s1, s2) == osmium::Location(1.0, 1.0)); - REQUIRE(calculate_intersection(s1, s3) == osmium::Location()); - REQUIRE(calculate_intersection(s2, s3) == osmium::Location()); - REQUIRE(calculate_intersection(s1, s4) == osmium::Location()); - REQUIRE(calculate_intersection(s1, s5) == osmium::Location(2.0, 2.0)); - REQUIRE(calculate_intersection(s1, s1) == osmium::Location()); - REQUIRE(calculate_intersection(s1, s6) == osmium::Location()); - REQUIRE(calculate_intersection(s1, s7) == osmium::Location()); - } - - SECTION("intersection of very long segments") { - NodeRefSegment s1({ 1, {90.0, 90.0}}, { 2, {-90.0, -90.0}}, nullptr, nullptr); - NodeRefSegment s2({ 1, {-90.0, 90.0}}, { 2, {90.0, -90.0}}, nullptr, nullptr); - REQUIRE(calculate_intersection(s1, s2) == osmium::Location(0.0, 0.0)); - - NodeRefSegment s3({ 1, {-90.0, -90.0}}, { 2, {90.0, 90.0}}, nullptr, nullptr); - NodeRefSegment s4({ 1, {-90.0, 90.0}}, { 2, {90.0, -90.0}}, nullptr, nullptr); - REQUIRE(calculate_intersection(s3, s4) == osmium::Location(0.0, 0.0)); - - NodeRefSegment s5({ 1, {-90.0000001, -90.0}}, { 2, {90.0, 90.0}}, nullptr, nullptr); - NodeRefSegment s6({ 1, {-90.0, 90.0}}, { 2, {90.0, -90.0}}, nullptr, nullptr); - REQUIRE(calculate_intersection(s5, s6) == osmium::Location(0.0, 0.0)); - } - - SECTION("to_left_of") { - osmium::Location loc { 2.0, 2.0 }; - - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {0.0, 4.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {4.0, 0.0}}, {1, {4.0, 4.0}}, nullptr, nullptr).to_left_of(loc) == false); - REQUIRE(NodeRefSegment({0, {1.0, 0.0}}, {1, {1.0, 4.0}}, nullptr, nullptr).to_left_of(loc)); - - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {1.0, 4.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {2.0, 4.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {3.0, 4.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {4.0, 4.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {4.0, 3.0}}, nullptr, nullptr).to_left_of(loc) == false); - - REQUIRE(NodeRefSegment({0, {1.0, 3.0}}, {1, {2.0, 0.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {1.0, 3.0}}, {1, {3.0, 1.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {1.0, 3.0}}, {1, {3.0, 2.0}}, nullptr, nullptr).to_left_of(loc) == false); - - REQUIRE(NodeRefSegment({0, {0.0, 2.0}}, {1, {2.0, 2.0}}, nullptr, nullptr).to_left_of(loc) == false); - - REQUIRE(NodeRefSegment({0, {2.0, 0.0}}, {1, {2.0, 4.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {2.0, 0.0}}, {1, {2.0, 2.0}}, nullptr, nullptr).to_left_of(loc) == false); - REQUIRE(NodeRefSegment({0, {2.0, 2.0}}, {1, {2.0, 4.0}}, nullptr, nullptr).to_left_of(loc) == false); - - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {0.0, 1.0}}, nullptr, nullptr).to_left_of(loc) == false); - REQUIRE(NodeRefSegment({0, {1.0, 0.0}}, {1, {0.0, 1.0}}, nullptr, nullptr).to_left_of(loc) == false); - - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {1.0, 3.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {0.0, 2.0}}, {1, {2.0, 0.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {0.0, 2.0}}, {1, {3.0, 4.0}}, nullptr, nullptr).to_left_of(loc) == false); - - REQUIRE(NodeRefSegment({0, {1.0, 0.0}}, {1, {1.0, 2.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {0.0, 2.0}}, {1, {1.0, 2.0}}, nullptr, nullptr).to_left_of(loc) == false); - REQUIRE(NodeRefSegment({0, {0.0, 2.0}}, {1, {1.0, 4.0}}, nullptr, nullptr).to_left_of(loc) == false); - - REQUIRE(NodeRefSegment({0, {0.0, 0.0}}, {1, {0.0, 2.0}}, nullptr, nullptr).to_left_of(loc)); - REQUIRE(NodeRefSegment({0, {0.0, 2.0}}, {1, {4.0, 4.0}}, nullptr, nullptr).to_left_of(loc) == false); - - REQUIRE(NodeRefSegment({0, {0.0, 1.0}}, {1, {2.0, 2.0}}, nullptr, nullptr).to_left_of(loc) == false); - REQUIRE(NodeRefSegment({0, {2.0, 2.0}}, {1, {4.0, 0.0}}, nullptr, nullptr).to_left_of(loc) == false); - } - - SECTION("ordering") { - osmium::NodeRef node_ref1(1, { 1.0, 3.0 }); - osmium::NodeRef node_ref2(2, { 1.4, 2.9 }); - osmium::NodeRef node_ref3(3, { 1.2, 3.0 }); - osmium::NodeRef node_ref4(4, { 1.2, 3.3 }); - - REQUIRE(node_ref1 < node_ref2); - REQUIRE(node_ref2 < node_ref3); - REQUIRE(node_ref1 < node_ref3); - REQUIRE(node_ref1 >= node_ref1); - - REQUIRE( osmium::location_less()(node_ref1, node_ref2)); - REQUIRE(!osmium::location_less()(node_ref2, node_ref3)); - REQUIRE( osmium::location_less()(node_ref1, node_ref3)); - REQUIRE( osmium::location_less()(node_ref3, node_ref4)); - REQUIRE(!osmium::location_less()(node_ref1, node_ref1)); - } - -} - diff --git a/third_party/libosmium/test/t/basic/helper.hpp b/third_party/libosmium/test/t/basic/helper.hpp deleted file mode 100644 index 5a2130e4e..000000000 --- a/third_party/libosmium/test/t/basic/helper.hpp +++ /dev/null @@ -1,103 +0,0 @@ -#ifndef TEST_BASIC_HELPER_HPP -#define TEST_BASIC_HELPER_HPP - -#include -#include -#include - -#include - -inline void add_tags(osmium::memory::Buffer& buffer, osmium::builder::Builder& builder, const std::vector>& tags) { - osmium::builder::TagListBuilder tl_builder(buffer, &builder); - for (const auto& tag : tags) { - tl_builder.add_tag(tag.first, tag.second); - } -} - -inline osmium::Node& buffer_add_node(osmium::memory::Buffer& buffer, const char* user, const std::vector>& tags, const osmium::Location& location) { - osmium::builder::NodeBuilder builder(buffer); - builder.add_user(user); - add_tags(buffer, builder, tags); - buffer.commit(); - return builder.object().set_location(location); -} - -inline osmium::Way& buffer_add_way(osmium::memory::Buffer& buffer, const char* user, const std::vector>& tags, const std::vector& nodes) { - osmium::builder::WayBuilder builder(buffer); - builder.add_user(user); - add_tags(buffer, builder, tags); - { - osmium::builder::WayNodeListBuilder wnl_builder(buffer, &builder); - for (const osmium::object_id_type ref : nodes) { - wnl_builder.add_node_ref(ref); - } - } - buffer.commit(); - return builder.object(); -} - -inline osmium::Way& buffer_add_way(osmium::memory::Buffer& buffer, const char* user, const std::vector>& tags, const std::vector>& nodes) { - osmium::builder::WayBuilder builder(buffer); - builder.add_user(user); - add_tags(buffer, builder, tags); - { - osmium::builder::WayNodeListBuilder wnl_builder(buffer, &builder); - for (const auto& p : nodes) { - wnl_builder.add_node_ref(p.first, p.second); - } - } - buffer.commit(); - return builder.object(); -} - -inline osmium::Relation& buffer_add_relation( - osmium::memory::Buffer& buffer, - const char* user, - const std::vector>& tags, const std::vector>& members) { - osmium::builder::RelationBuilder builder(buffer); - builder.add_user(user); - add_tags(buffer, builder, tags); - { - osmium::builder::RelationMemberListBuilder rml_builder(buffer, &builder); - for (const auto& member : members) { - rml_builder.add_member(osmium::char_to_item_type(std::get<0>(member)), std::get<1>(member), std::get<2>(member)); - } - } - buffer.commit(); - return builder.object(); -} - -inline osmium::Area& buffer_add_area(osmium::memory::Buffer& buffer, const char* user, - const std::vector>& tags, - const std::vector>>>& rings) { - osmium::builder::AreaBuilder builder(buffer); - builder.add_user(user); - add_tags(buffer, builder, tags); - - for (const auto& ring : rings) { - if (ring.first) { - osmium::builder::OuterRingBuilder ring_builder(buffer, &builder); - for (const auto& p : ring.second) { - ring_builder.add_node_ref(p.first, p.second); - } - } else { - osmium::builder::InnerRingBuilder ring_builder(buffer, &builder); - for (const auto& p : ring.second) { - ring_builder.add_node_ref(p.first, p.second); - } - } - } - buffer.commit(); - return builder.object(); -} - -inline osmium::Changeset& buffer_add_changeset(osmium::memory::Buffer& buffer, const char* user, const std::vector>& tags) { - osmium::builder::ChangesetBuilder builder(buffer); - builder.add_user(user); - add_tags(buffer, builder, tags); - buffer.commit(); - return builder.object(); -} - -#endif // TEST_BASIC_HELPER_HPP diff --git a/third_party/libosmium/test/t/basic/test_box.cpp b/third_party/libosmium/test/t/basic/test_box.cpp deleted file mode 100644 index 768cf41f3..000000000 --- a/third_party/libosmium/test/t/basic/test_box.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -#include -#include -#include - -TEST_CASE("Box") { - - SECTION("instantiation") { - osmium::Box b; - REQUIRE(!b); - REQUIRE(!b.bottom_left()); - REQUIRE(!b.top_right()); - REQUIRE_THROWS_AS(b.size(), osmium::invalid_location); - } - - SECTION("instantiation_and_extend_with_undefined") { - osmium::Box b; - REQUIRE(!b); - b.extend(osmium::Location()); - REQUIRE(!b.bottom_left()); - REQUIRE(!b.top_right()); - } - - SECTION("instantiation_and_extend") { - osmium::Box b; - osmium::Location loc1 { 1.2, 3.4 }; - b.extend(loc1); - REQUIRE(!!b); - REQUIRE(!!b.bottom_left()); - REQUIRE(!!b.top_right()); - REQUIRE(b.contains(loc1)); - - osmium::Location loc2 { 3.4, 4.5 }; - osmium::Location loc3 { 5.6, 7.8 }; - - b.extend(loc2); - b.extend(loc3); - REQUIRE(b.bottom_left() == osmium::Location(1.2, 3.4)); - REQUIRE(b.top_right() == osmium::Location(5.6, 7.8)); - - // extend with undefined doesn't change anything - b.extend(osmium::Location()); - REQUIRE(b.bottom_left() == osmium::Location(1.2, 3.4)); - REQUIRE(b.top_right() == osmium::Location(5.6, 7.8)); - - REQUIRE(b.contains(loc1)); - REQUIRE(b.contains(loc2)); - REQUIRE(b.contains(loc3)); - - osmium::CRC crc32; - crc32.update(b); - REQUIRE(crc32().checksum() == 0xd381a838); - } - - SECTION("output_defined") { - osmium::Box b; - b.extend(osmium::Location(1.2, 3.4)); - b.extend(osmium::Location(5.6, 7.8)); - std::stringstream out; - out << b; - REQUIRE(out.str() == "(1.2,3.4,5.6,7.8)"); - REQUIRE(b.size() == Approx(19.36).epsilon(0.000001)); - } - - SECTION("output_undefined") { - osmium::Box b; - std::stringstream out; - out << b; - REQUIRE(out.str() == "(undefined)"); - } - - SECTION("box_inside_box") { - osmium::Box outer; - outer.extend(osmium::Location(1, 1)); - outer.extend(osmium::Location(10, 10)); - - osmium::Box inner; - inner.extend(osmium::Location(2, 2)); - inner.extend(osmium::Location(4, 4)); - - osmium::Box overlap; - overlap.extend(osmium::Location(3, 3)); - overlap.extend(osmium::Location(5, 5)); - - REQUIRE( osmium::geom::contains(inner, outer)); - REQUIRE(!osmium::geom::contains(outer, inner)); - - REQUIRE(!osmium::geom::contains(overlap, inner)); - REQUIRE(!osmium::geom::contains(inner, overlap)); - } - -} - diff --git a/third_party/libosmium/test/t/basic/test_changeset.cpp b/third_party/libosmium/test/t/basic/test_changeset.cpp deleted file mode 100644 index d1f3fde87..000000000 --- a/third_party/libosmium/test/t/basic/test_changeset.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "catch.hpp" - -#include - -#include -#include - -#include "helper.hpp" - -TEST_CASE("Basic Changeset") { - - osmium::CRC crc32; - - osmium::memory::Buffer buffer(10 * 1000); - - osmium::Changeset& cs1 = buffer_add_changeset(buffer, - "user", - {{"comment", "foo"}}); - - cs1.set_id(42) - .set_created_at(100) - .set_closed_at(200) - .set_num_changes(7) - .set_num_comments(3) - .set_uid(9); - - REQUIRE(42 == cs1.id()); - REQUIRE(9 == cs1.uid()); - REQUIRE(7 == cs1.num_changes()); - REQUIRE(3 == cs1.num_comments()); - REQUIRE(true == cs1.closed()); - REQUIRE(osmium::Timestamp(100) == cs1.created_at()); - REQUIRE(osmium::Timestamp(200) == cs1.closed_at()); - REQUIRE(1 == cs1.tags().size()); - REQUIRE(std::string("user") == cs1.user()); - - crc32.update(cs1); - REQUIRE(crc32().checksum() == 0x502e8c0e); - - osmium::Changeset& cs2 = buffer_add_changeset(buffer, - "user", - {{"comment", "foo"}, {"foo", "bar"}}); - - cs2.set_id(43) - .set_created_at(120) - .set_num_changes(21) - .set_num_comments(osmium::num_comments_type(0)) - .set_uid(9); - - REQUIRE(43 == cs2.id()); - REQUIRE(9 == cs2.uid()); - REQUIRE(21 == cs2.num_changes()); - REQUIRE(0 == cs2.num_comments()); - REQUIRE(false == cs2.closed()); - REQUIRE(osmium::Timestamp(120) == cs2.created_at()); - REQUIRE(osmium::Timestamp() == cs2.closed_at()); - REQUIRE(2 == cs2.tags().size()); - REQUIRE(std::string("user") == cs2.user()); - - REQUIRE(cs1 != cs2); - - REQUIRE(cs1 < cs2); - REQUIRE(cs1 <= cs2); - REQUIRE(false == (cs1 > cs2)); - REQUIRE(false == (cs1 >= cs2)); - -} - -TEST_CASE("Create changeset without helper") { - osmium::memory::Buffer buffer(10 * 1000); - osmium::builder::ChangesetBuilder builder(buffer); - - osmium::Changeset& cs1 = builder.object(); - cs1.set_id(42) - .set_created_at(100) - .set_closed_at(200) - .set_num_changes(7) - .set_num_comments(2) - .set_uid(9); - - builder.add_user("user"); - add_tags(buffer, builder, { - {"key1", "val1"}, - {"key2", "val2"} - }); - - { - osmium::builder::ChangesetDiscussionBuilder disc_builder(buffer, &builder); - disc_builder.add_comment(osmium::Timestamp(300), 10, "user2"); - disc_builder.add_comment_text("foo"); - disc_builder.add_comment(osmium::Timestamp(400), 9, "user"); - disc_builder.add_comment_text("bar"); - } - - buffer.commit(); - - REQUIRE(42 == cs1.id()); - REQUIRE(9 == cs1.uid()); - REQUIRE(7 == cs1.num_changes()); - REQUIRE(2 == cs1.num_comments()); - REQUIRE(true == cs1.closed()); - REQUIRE(osmium::Timestamp(100) == cs1.created_at()); - REQUIRE(osmium::Timestamp(200) == cs1.closed_at()); - REQUIRE(2 == cs1.tags().size()); - REQUIRE(std::string("user") == cs1.user()); - - auto cit = cs1.discussion().begin(); - - REQUIRE(cit != cs1.discussion().end()); - REQUIRE(cit->date() == osmium::Timestamp(300)); - REQUIRE(cit->uid() == 10); - REQUIRE(std::string("user2") == cit->user()); - REQUIRE(std::string("foo") == cit->text()); - - REQUIRE(++cit != cs1.discussion().end()); - REQUIRE(cit->date() == osmium::Timestamp(400)); - REQUIRE(cit->uid() == 9); - REQUIRE(std::string("user") == cit->user()); - REQUIRE(std::string("bar") == cit->text()); - - REQUIRE(++cit == cs1.discussion().end()); -} - diff --git a/third_party/libosmium/test/t/basic/test_crc.cpp b/third_party/libosmium/test/t/basic/test_crc.cpp deleted file mode 100644 index fcd50a13c..000000000 --- a/third_party/libosmium/test/t/basic/test_crc.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -#include "helper.hpp" - -TEST_CASE("CRC of basic datatypes") { - - osmium::CRC crc32; - - SECTION("Bool") { - crc32.update_bool(true); - crc32.update_bool(false); - - REQUIRE(crc32().checksum() == 0x58c223be); - } - - SECTION("Char") { - crc32.update_int8('x'); - crc32.update_int8('y'); - - REQUIRE(crc32().checksum() == 0x8fe62899); - } - - SECTION("Int16") { - crc32.update_int16(0x0123U); - crc32.update_int16(0x1234U); - - REQUIRE(crc32().checksum() == 0xda923744); - } - - SECTION("Int32") { - crc32.update_int32(0x01234567UL); - crc32.update_int32(0x12345678UL); - - REQUIRE(crc32().checksum() == 0x9b4e2af3); - } - - SECTION("Int64") { - crc32.update_int64(0x0123456789abcdefULL); - crc32.update_int64(0x123456789abcdef0ULL); - - REQUIRE(crc32().checksum() == 0x6d8b7267); - } - - SECTION("String") { - const char* str = "foobar"; - crc32.update_string(str); - - REQUIRE(crc32().checksum() == 0x9ef61f95); - } - - SECTION("Timestamp") { - osmium::Timestamp t("2015-07-12T13:10:46Z"); - crc32.update(t); - - REQUIRE(crc32().checksum() == 0x58a29d7); - } - - SECTION("Location") { - osmium::Location loc { 3.46, 2.001 }; - crc32.update(loc); - - REQUIRE(crc32().checksum() == 0xddee042c); - } - -} - diff --git a/third_party/libosmium/test/t/basic/test_entity_bits.cpp b/third_party/libosmium/test/t/basic/test_entity_bits.cpp deleted file mode 100644 index f15068b1c..000000000 --- a/third_party/libosmium/test/t/basic/test_entity_bits.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "catch.hpp" - -#include - -TEST_CASE("entity_bits") { - - SECTION("can_be_set_and_checked") { - osmium::osm_entity_bits::type entities = osmium::osm_entity_bits::node | osmium::osm_entity_bits::way; - REQUIRE(entities == (osmium::osm_entity_bits::node | osmium::osm_entity_bits::way)); - - entities |= osmium::osm_entity_bits::relation; - REQUIRE((entities & osmium::osm_entity_bits::object)); - - entities |= osmium::osm_entity_bits::area; - REQUIRE(entities == osmium::osm_entity_bits::object); - - REQUIRE(! (entities & osmium::osm_entity_bits::changeset)); - - entities &= osmium::osm_entity_bits::node; - REQUIRE((entities & osmium::osm_entity_bits::node)); - REQUIRE(! (entities & osmium::osm_entity_bits::way)); - REQUIRE(entities == osmium::osm_entity_bits::node); - - REQUIRE(osmium::osm_entity_bits::node == osmium::osm_entity_bits::from_item_type(osmium::item_type::node)); - REQUIRE(osmium::osm_entity_bits::way == osmium::osm_entity_bits::from_item_type(osmium::item_type::way)); - REQUIRE(osmium::osm_entity_bits::relation == osmium::osm_entity_bits::from_item_type(osmium::item_type::relation)); - REQUIRE(osmium::osm_entity_bits::changeset == osmium::osm_entity_bits::from_item_type(osmium::item_type::changeset)); - REQUIRE(osmium::osm_entity_bits::area == osmium::osm_entity_bits::from_item_type(osmium::item_type::area)); - } - -} diff --git a/third_party/libosmium/test/t/basic/test_location.cpp b/third_party/libosmium/test/t/basic/test_location.cpp deleted file mode 100644 index 3fd8d155a..000000000 --- a/third_party/libosmium/test/t/basic/test_location.cpp +++ /dev/null @@ -1,154 +0,0 @@ -#include "catch.hpp" - -#include -#include - -#include - -TEST_CASE("Location") { - -// fails on MSVC and doesn't really matter -// static_assert(std::is_literal_type::value, "osmium::Location not literal type"); - - SECTION("instantiation_with_default_parameters") { - osmium::Location loc; - REQUIRE(!loc); - REQUIRE_THROWS_AS(loc.lon(), osmium::invalid_location); - REQUIRE_THROWS_AS(loc.lat(), osmium::invalid_location); - } - - SECTION("instantiation_with_double_parameters") { - osmium::Location loc1(1.2, 4.5); - REQUIRE(!!loc1); - REQUIRE(12000000 == loc1.x()); - REQUIRE(45000000 == loc1.y()); - REQUIRE(1.2 == loc1.lon()); - REQUIRE(4.5 == loc1.lat()); - - osmium::Location loc2(loc1); - REQUIRE(4.5 == loc2.lat()); - - osmium::Location loc3 = loc1; - REQUIRE(4.5 == loc3.lat()); - } - - SECTION("instantiation_with_double_parameters_constructor_with_universal_initializer") { - osmium::Location loc { 2.2, 3.3 }; - REQUIRE(2.2 == loc.lon()); - REQUIRE(3.3 == loc.lat()); - } - - SECTION("instantiation_with_double_parameters_constructor_with_initializer_list") { - osmium::Location loc({ 4.4, 5.5 }); - REQUIRE(4.4 == loc.lon()); - REQUIRE(5.5 == loc.lat()); - } - - SECTION("instantiation_with_double_parameters_operator_equal") { - osmium::Location loc = { 5.5, 6.6 }; - REQUIRE(5.5 == loc.lon()); - REQUIRE(6.6 == loc.lat()); - } - - SECTION("equality") { - osmium::Location loc1(1.2, 4.5); - osmium::Location loc2(1.2, 4.5); - osmium::Location loc3(1.5, 1.5); - REQUIRE(loc1 == loc2); - REQUIRE(loc1 != loc3); - } - - SECTION("order") { - REQUIRE(osmium::Location(-1.2, 10.0) < osmium::Location(1.2, 10.0)); - REQUIRE(osmium::Location(1.2, 10.0) > osmium::Location(-1.2, 10.0)); - - REQUIRE(osmium::Location(10.2, 20.0) < osmium::Location(11.2, 20.2)); - REQUIRE(osmium::Location(10.2, 20.2) < osmium::Location(11.2, 20.0)); - REQUIRE(osmium::Location(11.2, 20.2) > osmium::Location(10.2, 20.0)); - } - - SECTION("validity") { - REQUIRE(osmium::Location(0.0, 0.0).valid()); - REQUIRE(osmium::Location(1.2, 4.5).valid()); - REQUIRE(osmium::Location(-1.2, 4.5).valid()); - REQUIRE(osmium::Location(-180.0, -90.0).valid()); - REQUIRE(osmium::Location(180.0, -90.0).valid()); - REQUIRE(osmium::Location(-180.0, 90.0).valid()); - REQUIRE(osmium::Location(180.0, 90.0).valid()); - - REQUIRE(!osmium::Location(200.0, 4.5).valid()); - REQUIRE(!osmium::Location(-1.2, -100.0).valid()); - REQUIRE(!osmium::Location(-180.0, 90.005).valid()); - } - - - SECTION("output_to_iterator_comma_separator") { - char buffer[100]; - osmium::Location loc(-3.2, 47.3); - *loc.as_string(buffer, ',') = 0; - REQUIRE(std::string("-3.2,47.3") == buffer); - } - - SECTION("output_to_iterator_space_separator") { - char buffer[100]; - osmium::Location loc(0.0, 7.0); - *loc.as_string(buffer, ' ') = 0; - REQUIRE(std::string("0 7") == buffer); - } - - SECTION("output_to_iterator_check_precision") { - char buffer[100]; - osmium::Location loc(-179.9999999, -90.0); - *loc.as_string(buffer, ' ') = 0; - REQUIRE(std::string("-179.9999999 -90") == buffer); - } - - SECTION("output_to_iterator_undefined_location") { - char buffer[100]; - osmium::Location loc; - REQUIRE_THROWS_AS(loc.as_string(buffer, ','), osmium::invalid_location); - } - - SECTION("output_to_string_comman_separator") { - std::string s; - osmium::Location loc(-3.2, 47.3); - loc.as_string(std::back_inserter(s), ','); - REQUIRE(s == "-3.2,47.3"); - } - - SECTION("output_to_string_space_separator") { - std::string s; - osmium::Location loc(0.0, 7.0); - loc.as_string(std::back_inserter(s), ' '); - REQUIRE(s == "0 7"); - } - - SECTION("output_to_string_check_precision") { - std::string s; - osmium::Location loc(-179.9999999, -90.0); - loc.as_string(std::back_inserter(s), ' '); - REQUIRE(s == "-179.9999999 -90"); - } - - SECTION("output_to_string_undefined_location") { - std::string s; - osmium::Location loc; - REQUIRE_THROWS_AS(loc.as_string(std::back_inserter(s), ','), osmium::invalid_location); - } - - SECTION("output_defined") { - osmium::Location p(-3.2, 47.3); - std::stringstream out; - out << p; - REQUIRE(out.str() == "(-3.2,47.3)"); - } - - SECTION("output_undefined") { - osmium::Location p; - std::stringstream out; - out << p; - REQUIRE(out.str() == "(undefined,undefined)"); - } - -} - diff --git a/third_party/libosmium/test/t/basic/test_node.cpp b/third_party/libosmium/test/t/basic/test_node.cpp deleted file mode 100644 index 9f8b181fe..000000000 --- a/third_party/libosmium/test/t/basic/test_node.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include "catch.hpp" - -#include - -#include -#include - -#include "helper.hpp" - -TEST_CASE("Basic_Node") { - - osmium::CRC crc32; - -SECTION("node_builder") { - osmium::memory::Buffer buffer(10000); - - osmium::Node& node = buffer_add_node(buffer, - "foo", - {{"amenity", "pub"}, {"name", "OSM BAR"}}, - {3.5, 4.7}); - - node.set_id(17) - .set_version(3) - .set_visible(true) - .set_changeset(333) - .set_uid(21) - .set_timestamp(123); - - REQUIRE(osmium::item_type::node == node.type()); - REQUIRE(node.type_is_in(osmium::osm_entity_bits::node)); - REQUIRE(node.type_is_in(osmium::osm_entity_bits::nwr)); - REQUIRE(17l == node.id()); - REQUIRE(17ul == node.positive_id()); - REQUIRE(3 == node.version()); - REQUIRE(true == node.visible()); - REQUIRE(false == node.deleted()); - REQUIRE(333 == node.changeset()); - REQUIRE(21 == node.uid()); - REQUIRE(std::string("foo") == node.user()); - REQUIRE(123 == uint32_t(node.timestamp())); - REQUIRE(osmium::Location(3.5, 4.7) == node.location()); - REQUIRE(2 == node.tags().size()); - - crc32.update(node); - REQUIRE(crc32().checksum() == 0x7dc553f9); - - node.set_visible(false); - REQUIRE(false == node.visible()); - REQUIRE(true == node.deleted()); -} - -SECTION("node_default_attributes") { - osmium::memory::Buffer buffer(10000); - - osmium::Node& node = buffer_add_node(buffer, "", {}, osmium::Location{}); - - REQUIRE(0l == node.id()); - REQUIRE(0ul == node.positive_id()); - REQUIRE(0 == node.version()); - REQUIRE(true == node.visible()); - REQUIRE(0 == node.changeset()); - REQUIRE(0 == node.uid()); - REQUIRE(std::string("") == node.user()); - REQUIRE(0 == uint32_t(node.timestamp())); - REQUIRE(osmium::Location() == node.location()); - REQUIRE(0 == node.tags().size()); -} - -SECTION("set_node_attributes_from_string") { - osmium::memory::Buffer buffer(10000); - - osmium::Node& node = buffer_add_node(buffer, - "foo", - {{"amenity", "pub"}, {"name", "OSM BAR"}}, - {3.5, 4.7}); - - node.set_id("-17") - .set_version("3") - .set_visible(true) - .set_changeset("333") - .set_uid("21"); - - REQUIRE(-17l == node.id()); - REQUIRE(17ul == node.positive_id()); - REQUIRE(3 == node.version()); - REQUIRE(true == node.visible()); - REQUIRE(333 == node.changeset()); - REQUIRE(21 == node.uid()); -} - -SECTION("large_id") { - osmium::memory::Buffer buffer(10000); - - osmium::Node& node = buffer_add_node(buffer, "", {}, osmium::Location{}); - - int64_t id = 3000000000l; - node.set_id(id); - - REQUIRE(id == node.id()); - REQUIRE(static_cast(id) == node.positive_id()); - - node.set_id(-id); - REQUIRE(-id == node.id()); - REQUIRE(static_cast(id) == node.positive_id()); -} - -SECTION("tags") { - osmium::memory::Buffer buffer(10000); - - osmium::Node& node = buffer_add_node(buffer, - "foo", - {{"amenity", "pub"}, {"name", "OSM BAR"}}, - {3.5, 4.7}); - - REQUIRE(nullptr == node.tags().get_value_by_key("fail")); - REQUIRE(std::string("pub") == node.tags().get_value_by_key("amenity")); - REQUIRE(std::string("pub") == node.get_value_by_key("amenity")); - - REQUIRE(std::string("default") == node.tags().get_value_by_key("fail", "default")); - REQUIRE(std::string("pub") == node.tags().get_value_by_key("amenity", "default")); - REQUIRE(std::string("pub") == node.get_value_by_key("amenity", "default")); -} - - -} diff --git a/third_party/libosmium/test/t/basic/test_node_ref.cpp b/third_party/libosmium/test/t/basic/test_node_ref.cpp deleted file mode 100644 index ac7ccbf4b..000000000 --- a/third_party/libosmium/test/t/basic/test_node_ref.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "catch.hpp" - -#include - -TEST_CASE("NodeRef") { - - SECTION("instantiation_with_default_parameters") { - osmium::NodeRef node_ref; - REQUIRE(node_ref.ref() == 0); -// REQUIRE(!node_ref.has_location()); - } - - SECTION("instantiation_with_id") { - osmium::NodeRef node_ref(7); - REQUIRE(node_ref.ref() == 7); - } - - SECTION("equality") { - osmium::NodeRef node_ref1(7, { 1.2, 3.4 }); - osmium::NodeRef node_ref2(7, { 1.4, 3.1 }); - osmium::NodeRef node_ref3(9, { 1.2, 3.4 }); - REQUIRE(node_ref1 == node_ref2); - REQUIRE(node_ref1 != node_ref3); - REQUIRE(!osmium::location_equal()(node_ref1, node_ref2)); - REQUIRE(!osmium::location_equal()(node_ref2, node_ref3)); - REQUIRE(osmium::location_equal()(node_ref1, node_ref3)); - } - - SECTION("set_location") { - osmium::NodeRef node_ref(7); - REQUIRE(!node_ref.location().valid()); - REQUIRE(node_ref.location() == osmium::Location()); - node_ref.set_location(osmium::Location(13.5, -7.2)); - REQUIRE(node_ref.location().lon() == 13.5); - REQUIRE(node_ref.location().valid()); - } - - SECTION("ordering") { - osmium::NodeRef node_ref1(1, { 1.0, 3.0 }); - osmium::NodeRef node_ref2(2, { 1.4, 2.9 }); - osmium::NodeRef node_ref3(3, { 1.2, 3.0 }); - osmium::NodeRef node_ref4(4, { 1.2, 3.3 }); - - REQUIRE(node_ref1 < node_ref2); - REQUIRE(node_ref2 < node_ref3); - REQUIRE(node_ref1 < node_ref3); - REQUIRE(node_ref1 >= node_ref1); - - REQUIRE(osmium::location_less()(node_ref1, node_ref2)); - REQUIRE(!osmium::location_less()(node_ref2, node_ref3)); - REQUIRE(osmium::location_less()(node_ref1, node_ref3)); - REQUIRE(osmium::location_less()(node_ref3, node_ref4)); - REQUIRE(!osmium::location_less()(node_ref1, node_ref1)); - } - -} - diff --git a/third_party/libosmium/test/t/basic/test_object_comparisons.cpp b/third_party/libosmium/test/t/basic/test_object_comparisons.cpp deleted file mode 100644 index ec9e6fae8..000000000 --- a/third_party/libosmium/test/t/basic/test_object_comparisons.cpp +++ /dev/null @@ -1,147 +0,0 @@ -#include "catch.hpp" - -#include -#include -#include - -TEST_CASE("Object_Comparisons") { - - SECTION("order") { - osmium::memory::Buffer buffer(10 * 1000); - - { - // add node 1 - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - buffer.commit(); - } - - { - // add node 2 - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - buffer.commit(); - } - - auto it = buffer.begin(); - osmium::Node& node1 = static_cast(*it); - osmium::Node& node2 = static_cast(*(++it)); - - node1.set_id(10); - node1.set_version(1); - node2.set_id(15); - node2.set_version(2); - REQUIRE(node1 < node2); - REQUIRE_FALSE(node1 > node2); - node1.set_id(20); - node1.set_version(1); - node2.set_id(20); - node2.set_version(2); - REQUIRE(node1 < node2); - REQUIRE_FALSE(node1 > node2); - node1.set_id(-10); - node1.set_version(2); - node2.set_id(-15); - node2.set_version(1); - REQUIRE(node1 < node2); - REQUIRE_FALSE(node1 > node2); - } - - SECTION("order_types") { - osmium::memory::Buffer buffer(10 * 1000); - - { - // add node 1 - osmium::builder::NodeBuilder node_builder(buffer); - osmium::Node& node = node_builder.object(); - REQUIRE(osmium::item_type::node == node.type()); - - node.set_id(3); - node.set_version(3); - node_builder.add_user("testuser"); - - buffer.commit(); - } - - { - // add node 2 - osmium::builder::NodeBuilder node_builder(buffer); - osmium::Node& node = node_builder.object(); - REQUIRE(osmium::item_type::node == node.type()); - - node.set_id(3); - node.set_version(4); - node_builder.add_user("testuser"); - - buffer.commit(); - } - - { - // add node 3 - osmium::builder::NodeBuilder node_builder(buffer); - osmium::Node& node = node_builder.object(); - REQUIRE(osmium::item_type::node == node.type()); - - node.set_id(3); - node.set_version(4); - node_builder.add_user("testuser"); - - buffer.commit(); - } - - { - // add way - osmium::builder::WayBuilder way_builder(buffer); - osmium::Way& way = way_builder.object(); - REQUIRE(osmium::item_type::way == way.type()); - - way.set_id(2); - way.set_version(2); - way_builder.add_user("testuser"); - - buffer.commit(); - } - - { - // add relation - osmium::builder::RelationBuilder relation_builder(buffer); - osmium::Relation& relation = relation_builder.object(); - REQUIRE(osmium::item_type::relation == relation.type()); - - relation.set_id(1); - relation.set_version(1); - relation_builder.add_user("testuser"); - - buffer.commit(); - } - - auto it = buffer.begin(); - const osmium::Node& node1 = static_cast(*it); - const osmium::Node& node2 = static_cast(*(++it)); - const osmium::Node& node3 = static_cast(*(++it)); - const osmium::Way& way = static_cast(*(++it)); - const osmium::Relation& relation = static_cast(*(++it)); - - REQUIRE(node1 < node2); - REQUIRE(node2 < way); - REQUIRE_FALSE(node2 > way); - REQUIRE(way < relation); - REQUIRE(node1 < relation); - - REQUIRE(osmium::object_order_type_id_version()(node1, node2)); - REQUIRE(osmium::object_order_type_id_reverse_version()(node2, node1)); - REQUIRE(osmium::object_order_type_id_version()(node1, way)); - REQUIRE(osmium::object_order_type_id_reverse_version()(node1, way)); - - REQUIRE_FALSE(osmium::object_equal_type_id_version()(node1, node2)); - REQUIRE(osmium::object_equal_type_id_version()(node2, node3)); - - REQUIRE(osmium::object_equal_type_id()(node1, node2)); - REQUIRE(osmium::object_equal_type_id()(node2, node3)); - - REQUIRE_FALSE(osmium::object_equal_type_id_version()(node1, way)); - REQUIRE_FALSE(osmium::object_equal_type_id_version()(node1, relation)); - REQUIRE_FALSE(osmium::object_equal_type_id()(node1, relation)); - } - -} diff --git a/third_party/libosmium/test/t/basic/test_relation.cpp b/third_party/libosmium/test/t/basic/test_relation.cpp deleted file mode 100644 index 66b201c90..000000000 --- a/third_party/libosmium/test/t/basic/test_relation.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include "catch.hpp" - -#include - -#include -#include - -#include "helper.hpp" - -TEST_CASE("Build relation") { - - osmium::CRC crc32; - - osmium::memory::Buffer buffer(10000); - - osmium::Relation& relation = buffer_add_relation(buffer, - "foo", { - {"type", "multipolygon"}, - {"name", "Sherwood Forest"} - }, { - std::make_tuple('w', 1, "inner"), - std::make_tuple('w', 2, ""), - std::make_tuple('w', 3, "outer") - }); - - relation.set_id(17) - .set_version(3) - .set_visible(true) - .set_changeset(333) - .set_uid(21) - .set_timestamp(123); - - REQUIRE(17 == relation.id()); - REQUIRE(3 == relation.version()); - REQUIRE(true == relation.visible()); - REQUIRE(333 == relation.changeset()); - REQUIRE(21 == relation.uid()); - REQUIRE(std::string("foo") == relation.user()); - REQUIRE(123 == uint32_t(relation.timestamp())); - REQUIRE(2 == relation.tags().size()); - REQUIRE(3 == relation.members().size()); - - int n=1; - for (auto& member : relation.members()) { - REQUIRE(osmium::item_type::way == member.type()); - REQUIRE(n == member.ref()); - switch (n) { - case 1: - REQUIRE(std::string("inner") == member.role()); - break; - case 2: - REQUIRE(std::string("") == member.role()); - break; - case 3: - REQUIRE(std::string("outer") == member.role()); - break; - default: - REQUIRE(false); - } - ++n; - } - - crc32.update(relation); - REQUIRE(crc32().checksum() == 0x2c2352e); -} - -TEST_CASE("Member role too long") { - osmium::memory::Buffer buffer(10000); - - osmium::builder::RelationMemberListBuilder builder(buffer); - - const char role[2000] = ""; - builder.add_member(osmium::item_type::node, 1, role, 1024); - REQUIRE_THROWS(builder.add_member(osmium::item_type::node, 1, role, 1025)); -} - diff --git a/third_party/libosmium/test/t/basic/test_timestamp.cpp b/third_party/libosmium/test/t/basic/test_timestamp.cpp deleted file mode 100644 index f80ffcf5f..000000000 --- a/third_party/libosmium/test/t/basic/test_timestamp.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -TEST_CASE("Timestamp") { - - SECTION("can be default initialized to invalid value") { - osmium::Timestamp t; - REQUIRE(0 == uint32_t(t)); - REQUIRE("" == t.to_iso()); - REQUIRE_FALSE(t.valid()); - } - - SECTION("invalid value is zero") { - osmium::Timestamp t(static_cast(0)); - REQUIRE(0 == uint32_t(t)); - REQUIRE("" == t.to_iso()); - REQUIRE_FALSE(t.valid()); - } - - SECTION("can be initialized from time_t") { - osmium::Timestamp t(static_cast(1)); - REQUIRE(1 == uint32_t(t)); - REQUIRE("1970-01-01T00:00:01Z" == t.to_iso()); - REQUIRE(t.valid()); - } - - SECTION("can be initialized from const char*") { - osmium::Timestamp t("2000-01-01T00:00:00Z"); - REQUIRE("2000-01-01T00:00:00Z" == t.to_iso()); - REQUIRE(t.valid()); - } - - SECTION("can be initialized from string") { - std::string s = "2000-01-01T00:00:00Z"; - osmium::Timestamp t(s); - REQUIRE("2000-01-01T00:00:00Z" == t.to_iso()); - REQUIRE(t.valid()); - } - - SECTION("throws if initialized from bad string") { - REQUIRE_THROWS_AS(osmium::Timestamp("x"), std::invalid_argument); - } - - SECTION("can be explicitly cast to time_t") { - osmium::Timestamp t(4242); - time_t x = t.seconds_since_epoch(); - REQUIRE(x == 4242); - } - - SECTION("uint32_t can be initialized from Timestamp") { - osmium::Timestamp t(4242); - uint32_t x { t }; - - REQUIRE(x == 4242); - } - - SECTION("can be compared") { - osmium::Timestamp t1(10); - osmium::Timestamp t2(50); - REQUIRE(t1 < t2); - REQUIRE(t1 > osmium::start_of_time()); - REQUIRE(t2 > osmium::start_of_time()); - REQUIRE(t1 < osmium::end_of_time()); - REQUIRE(t2 < osmium::end_of_time()); - } - - SECTION("can be written to stream") { - std::stringstream ss; - osmium::Timestamp t(1); - ss << t; - REQUIRE("1970-01-01T00:00:01Z" == ss.str()); - } - -} diff --git a/third_party/libosmium/test/t/basic/test_types_from_string.cpp b/third_party/libosmium/test/t/basic/test_types_from_string.cpp deleted file mode 100644 index 2481ae876..000000000 --- a/third_party/libosmium/test/t/basic/test_types_from_string.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "catch.hpp" - -#include -#include - -TEST_CASE("set ID from string") { - REQUIRE(osmium::string_to_object_id("0") == 0); - REQUIRE(osmium::string_to_object_id("17") == 17); - REQUIRE(osmium::string_to_object_id("-17") == -17); - REQUIRE(osmium::string_to_object_id("01") == 1); - - REQUIRE_THROWS_AS(osmium::string_to_object_id(""), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id(" "), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id(" 22"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("x"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("0x1"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("12a"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("12345678901234567890"), std::range_error); -} - -TEST_CASE("set type and ID from string") { - auto n17 = osmium::string_to_object_id("n17", osmium::osm_entity_bits::nwr); - REQUIRE(n17.first == osmium::item_type::node); - REQUIRE(n17.second == 17); - - auto w42 = osmium::string_to_object_id("w42", osmium::osm_entity_bits::nwr); - REQUIRE(w42.first == osmium::item_type::way); - REQUIRE(w42.second == 42); - - auto r_2 = osmium::string_to_object_id("r-2", osmium::osm_entity_bits::nwr); - REQUIRE(r_2.first == osmium::item_type::relation); - REQUIRE(r_2.second == -2); - - auto x3 = osmium::string_to_object_id("3", osmium::osm_entity_bits::nwr); - REQUIRE(x3.first == osmium::item_type::undefined); - REQUIRE(x3.second == 3); - - REQUIRE_THROWS_AS(osmium::string_to_object_id("", osmium::osm_entity_bits::nwr), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("n", osmium::osm_entity_bits::nwr), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("x3", osmium::osm_entity_bits::nwr), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("nx3", osmium::osm_entity_bits::nwr), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("n3", osmium::osm_entity_bits::way), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_id("n3a", osmium::osm_entity_bits::nwr), std::range_error); -} - -TEST_CASE("set object version from string") { - REQUIRE(osmium::string_to_object_version("0") == 0); - REQUIRE(osmium::string_to_object_version("1") == 1); - - REQUIRE_THROWS_AS(osmium::string_to_object_version("-1"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_version(""), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_version(" "), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_version(" 22"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_object_version("x"), std::range_error); -} - -TEST_CASE("set changeset id from string") { - REQUIRE(osmium::string_to_changeset_id("0") == 0); - REQUIRE(osmium::string_to_changeset_id("1") == 1); - - REQUIRE_THROWS_AS(osmium::string_to_changeset_id("-1"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_changeset_id(""), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_changeset_id(" "), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_changeset_id(" 22"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_changeset_id("x"), std::range_error); -} - -TEST_CASE("set user id from string") { - REQUIRE(osmium::string_to_user_id("0") == 0); - REQUIRE(osmium::string_to_user_id("1") == 1); - REQUIRE(osmium::string_to_user_id("-1") == -1); - - REQUIRE_THROWS_AS(osmium::string_to_user_id("-2"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_user_id(""), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_user_id(" "), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_user_id(" 22"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_user_id("x"), std::range_error); -} - -TEST_CASE("set num changes from string") { - REQUIRE(osmium::string_to_num_changes("0") == 0); - REQUIRE(osmium::string_to_num_changes("1") == 1); - - REQUIRE_THROWS_AS(osmium::string_to_num_changes("-1"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_num_changes(""), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_num_changes(" "), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_num_changes(" 22"), std::range_error); - REQUIRE_THROWS_AS(osmium::string_to_num_changes("x"), std::range_error); -} - diff --git a/third_party/libosmium/test/t/basic/test_way.cpp b/third_party/libosmium/test/t/basic/test_way.cpp deleted file mode 100644 index 370cd0105..000000000 --- a/third_party/libosmium/test/t/basic/test_way.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "catch.hpp" - -#include - -#include -#include -#include - -#include "helper.hpp" - -TEST_CASE("Build way") { - - osmium::CRC crc32; - -SECTION("way_builder") { - osmium::memory::Buffer buffer(10000); - - osmium::Way& way = buffer_add_way(buffer, - "foo", - {{"highway", "residential"}, {"name", "High Street"}}, - {1, 3, 2}); - - way.set_id(17) - .set_version(3) - .set_visible(true) - .set_changeset(333) - .set_uid(21) - .set_timestamp(123); - - REQUIRE(osmium::item_type::way == way.type()); - REQUIRE(way.type_is_in(osmium::osm_entity_bits::way)); - REQUIRE(way.type_is_in(osmium::osm_entity_bits::node | osmium::osm_entity_bits::way)); - REQUIRE(17 == way.id()); - REQUIRE(3 == way.version()); - REQUIRE(true == way.visible()); - REQUIRE(333 == way.changeset()); - REQUIRE(21 == way.uid()); - REQUIRE(std::string("foo") == way.user()); - REQUIRE(123 == uint32_t(way.timestamp())); - REQUIRE(2 == way.tags().size()); - REQUIRE(3 == way.nodes().size()); - REQUIRE(1 == way.nodes()[0].ref()); - REQUIRE(3 == way.nodes()[1].ref()); - REQUIRE(2 == way.nodes()[2].ref()); - REQUIRE(! way.is_closed()); - - crc32.update(way); - REQUIRE(crc32().checksum() == 0x7676d0c2); -} - -SECTION("closed_way") { - osmium::memory::Buffer buffer(10000); - - osmium::Way& way = buffer_add_way(buffer, - "foo", - {{"highway", "residential"}, {"name", "High Street"}}, - {1, 3, 1}); - - REQUIRE(way.is_closed()); -} - -SECTION("way_builder_with_helpers") { - osmium::memory::Buffer buffer(10000); - { - osmium::builder::WayBuilder builder(buffer); - builder.add_user("username"); - builder.add_tags({ - {"amenity", "restaurant"}, - {"name", "Zum goldenen Schwanen"} - }); - builder.add_node_refs({ - {22, {3.5, 4.7}}, - {67, {4.1, 2.2}} - }); - } - buffer.commit(); - osmium::Way& way = buffer.get(0); - - REQUIRE(std::string("username") == way.user()); - - REQUIRE(2 == way.tags().size()); - REQUIRE(std::string("amenity") == way.tags().begin()->key()); - REQUIRE(std::string("Zum goldenen Schwanen") == way.tags()["name"]); - - REQUIRE(2 == way.nodes().size()); - REQUIRE(22 == way.nodes()[0].ref()); - REQUIRE(4.1 == way.nodes()[1].location().lon()); -} - -} diff --git a/third_party/libosmium/test/t/buffer/test_buffer_basics.cpp b/third_party/libosmium/test/t/buffer/test_buffer_basics.cpp deleted file mode 100644 index ffe725168..000000000 --- a/third_party/libosmium/test/t/buffer/test_buffer_basics.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "catch.hpp" - -#include - -TEST_CASE("Buffer basics") { - - osmium::memory::Buffer invalid_buffer1; - osmium::memory::Buffer invalid_buffer2; - osmium::memory::Buffer empty_buffer1(1024); - osmium::memory::Buffer empty_buffer2(2048); - - REQUIRE(!invalid_buffer1); - REQUIRE(!invalid_buffer2); - REQUIRE(empty_buffer1); - REQUIRE(empty_buffer2); - - REQUIRE(invalid_buffer1 == invalid_buffer2); - REQUIRE(invalid_buffer1 != empty_buffer1); - REQUIRE(empty_buffer1 != empty_buffer2); - - REQUIRE(invalid_buffer1.capacity() == 0); - REQUIRE(invalid_buffer1.written() == 0); - REQUIRE(invalid_buffer1.committed() == 0); - - REQUIRE(empty_buffer1.capacity() == 1024); - REQUIRE(empty_buffer1.written() == 0); - REQUIRE(empty_buffer1.committed() == 0); - - REQUIRE(empty_buffer2.capacity() == 2048); - REQUIRE(empty_buffer2.written() == 0); - REQUIRE(empty_buffer2.committed() == 0); - -} - diff --git a/third_party/libosmium/test/t/buffer/test_buffer_node.cpp b/third_party/libosmium/test/t/buffer/test_buffer_node.cpp deleted file mode 100644 index ba2431b80..000000000 --- a/third_party/libosmium/test/t/buffer/test_buffer_node.cpp +++ /dev/null @@ -1,199 +0,0 @@ -#include "catch.hpp" - -#include -#include - -void check_node_1(osmium::Node& node) { - REQUIRE(1 == node.id()); - REQUIRE(3 == node.version()); - REQUIRE(true == node.visible()); - REQUIRE(333 == node.changeset()); - REQUIRE(21 == node.uid()); - REQUIRE(123 == uint32_t(node.timestamp())); - REQUIRE(osmium::Location(3.5, 4.7) == node.location()); - REQUIRE(std::string("testuser") == node.user()); - - for (osmium::memory::Item& item : node) { - REQUIRE(osmium::item_type::tag_list == item.type()); - } - - REQUIRE(node.tags().begin() == node.tags().end()); - REQUIRE(node.tags().empty()); - REQUIRE(0 == std::distance(node.tags().begin(), node.tags().end())); -} - -void check_node_2(osmium::Node& node) { - REQUIRE(2 == node.id()); - REQUIRE(3 == node.version()); - REQUIRE(true == node.visible()); - REQUIRE(333 == node.changeset()); - REQUIRE(21 == node.uid()); - REQUIRE(123 == uint32_t(node.timestamp())); - REQUIRE(osmium::Location(3.5, 4.7) == node.location()); - REQUIRE(std::string("testuser") == node.user()); - - for (osmium::memory::Item& item : node) { - REQUIRE(osmium::item_type::tag_list == item.type()); - } - - REQUIRE(!node.tags().empty()); - REQUIRE(2 == std::distance(node.tags().begin(), node.tags().end())); - - int n = 0; - for (const osmium::Tag& tag : node.tags()) { - switch (n) { - case 0: - REQUIRE(std::string("amenity") == tag.key()); - REQUIRE(std::string("bank") == tag.value()); - break; - case 1: - REQUIRE(std::string("name") == tag.key()); - REQUIRE(std::string("OSM Savings") == tag.value()); - break; - } - ++n; - } - REQUIRE(2 == n); -} - -TEST_CASE("Node in Buffer") { - - constexpr size_t buffer_size = 10000; - unsigned char data[buffer_size]; - - osmium::memory::Buffer buffer(data, buffer_size, 0); - - SECTION("Add node to buffer") { - - { - // add node 1 - osmium::builder::NodeBuilder node_builder(buffer); - osmium::Node& node = node_builder.object(); - REQUIRE(osmium::item_type::node == node.type()); - - node.set_id(1); - node.set_version(3); - node.set_visible(true); - node.set_changeset(333); - node.set_uid(21); - node.set_timestamp(123); - node.set_location(osmium::Location(3.5, 4.7)); - - node_builder.add_user("testuser"); - - buffer.commit(); - } - - { - // add node 2 - osmium::builder::NodeBuilder node_builder(buffer); - osmium::Node& node = node_builder.object(); - REQUIRE(osmium::item_type::node == node.type()); - - node.set_id(2); - node.set_version(3); - node.set_visible(true); - node.set_changeset(333); - node.set_uid(21); - node.set_timestamp(123); - node.set_location(osmium::Location(3.5, 4.7)); - - node_builder.add_user("testuser"); - - { - osmium::builder::TagListBuilder tag_builder(buffer, &node_builder); - tag_builder.add_tag("amenity", "bank"); - tag_builder.add_tag("name", "OSM Savings"); - } - - buffer.commit(); - } - - REQUIRE(2 == std::distance(buffer.begin(), buffer.end())); - int item_no = 0; - for (osmium::memory::Item& item : buffer) { - REQUIRE(osmium::item_type::node == item.type()); - - osmium::Node& node = static_cast(item); - - switch (item_no) { - case 0: - check_node_1(node); - break; - case 1: - check_node_2(node); - break; - default: - break; - } - - ++item_no; - - } - - } - - SECTION("Add buffer to another one") { - - { - // add node 1 - osmium::builder::NodeBuilder node_builder(buffer); - osmium::Node& node = node_builder.object(); - REQUIRE(osmium::item_type::node == node.type()); - - node.set_id(1); - node.set_version(3); - node.set_visible(true); - node.set_changeset(333); - node.set_uid(21); - node.set_timestamp(123); - node.set_location(osmium::Location(3.5, 4.7)); - - node_builder.add_user("testuser"); - - buffer.commit(); - } - - osmium::memory::Buffer buffer2(buffer_size, osmium::memory::Buffer::auto_grow::yes); - - buffer2.add_buffer(buffer); - buffer2.commit(); - - REQUIRE(buffer.committed() == buffer2.committed()); - const osmium::Node& node = buffer2.get(0); - REQUIRE(node.id() == 1); - REQUIRE(123 == uint32_t(node.timestamp())); - } - - SECTION("Use back_inserter on buffer") { - - { - // add node 1 - osmium::builder::NodeBuilder node_builder(buffer); - osmium::Node& node = node_builder.object(); - REQUIRE(osmium::item_type::node == node.type()); - - node.set_id(1); - node.set_version(3); - node.set_visible(true); - node.set_changeset(333); - node.set_uid(21); - node.set_timestamp(123); - node.set_location(osmium::Location(3.5, 4.7)); - - node_builder.add_user("testuser"); - - buffer.commit(); - } - - osmium::memory::Buffer buffer2(buffer_size, osmium::memory::Buffer::auto_grow::yes); - - std::copy(buffer.begin(), buffer.end(), std::back_inserter(buffer2)); - - REQUIRE(buffer.committed() == buffer2.committed()); - const osmium::Node& node = buffer2.get(0); - REQUIRE(node.id() == 1); - REQUIRE(123 == uint32_t(node.timestamp())); - } -} - diff --git a/third_party/libosmium/test/t/buffer/test_buffer_purge.cpp b/third_party/libosmium/test/t/buffer/test_buffer_purge.cpp deleted file mode 100644 index a72db1b5c..000000000 --- a/third_party/libosmium/test/t/buffer/test_buffer_purge.cpp +++ /dev/null @@ -1,186 +0,0 @@ -#include "catch.hpp" - -#include -#include - -struct CallbackClass { - - int count = 0; - - void moving_in_buffer(size_t old_offset, size_t new_offset) { - REQUIRE(old_offset > new_offset); - ++count; - } - -}; // struct CallbackClass - -TEST_CASE("Purge data from buffer") { - - constexpr size_t buffer_size = 10000; - - SECTION("purge empty buffer") { - osmium::memory::Buffer buffer(buffer_size); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 0); - - CallbackClass callback; - buffer.purge_removed(&callback); - - REQUIRE(callback.count == 0); - REQUIRE(buffer.committed() == 0); - } - - SECTION("purge buffer with one object but nothing to delete") { - osmium::memory::Buffer buffer(buffer_size); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - } - buffer.commit(); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 1); - size_t committed = buffer.committed(); - - CallbackClass callback; - buffer.purge_removed(&callback); - - REQUIRE(callback.count == 0); - REQUIRE(committed == buffer.committed()); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 1); - } - - SECTION("purge buffer with one object which gets deleted") { - osmium::memory::Buffer buffer(buffer_size); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - node_builder.object().set_removed(true); - } - buffer.commit(); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 1); - - CallbackClass callback; - buffer.purge_removed(&callback); - - REQUIRE(callback.count == 0); - REQUIRE(buffer.committed() == 0); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 0); - } - - SECTION("purge buffer with two objects, first gets deleted") { - osmium::memory::Buffer buffer(buffer_size); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - node_builder.object().set_removed(true); - } - buffer.commit(); - size_t size1 = buffer.committed(); - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - } - buffer.commit(); - size_t size2 = buffer.committed() - size1; - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 2); - - CallbackClass callback; - buffer.purge_removed(&callback); - - REQUIRE(callback.count == 1); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 1); - REQUIRE(buffer.committed() == size2); - } - - SECTION("purge buffer with two objects, second gets deleted") { - osmium::memory::Buffer buffer(buffer_size); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser_longer_name"); - } - buffer.commit(); - size_t size1 = buffer.committed(); - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - node_builder.object().set_removed(true); - } - buffer.commit(); - - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 2); - - CallbackClass callback; - buffer.purge_removed(&callback); - - REQUIRE(callback.count == 0); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 1); - REQUIRE(buffer.committed() == size1); - } - - SECTION("purge buffer with three objects, middle one gets deleted") { - osmium::memory::Buffer buffer(buffer_size); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser_longer_name"); - } - buffer.commit(); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - node_builder.object().set_removed(true); - } - buffer.commit(); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("sn"); - } - buffer.commit(); - - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 3); - - CallbackClass callback; - buffer.purge_removed(&callback); - - REQUIRE(callback.count == 1); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 2); - } - - SECTION("purge buffer with three objects, all get deleted") { - osmium::memory::Buffer buffer(buffer_size); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser_longer_name"); - node_builder.object().set_removed(true); - } - buffer.commit(); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("testuser"); - node_builder.object().set_removed(true); - } - buffer.commit(); - - { - osmium::builder::NodeBuilder node_builder(buffer); - node_builder.add_user("sn"); - node_builder.object().set_removed(true); - } - buffer.commit(); - - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 3); - - CallbackClass callback; - buffer.purge_removed(&callback); - - REQUIRE(callback.count == 0); - REQUIRE(std::distance(buffer.begin(), buffer.end()) == 0); - } - -} diff --git a/third_party/libosmium/test/t/geom/helper.hpp b/third_party/libosmium/test/t/geom/helper.hpp deleted file mode 100644 index e0cefe6d1..000000000 --- a/third_party/libosmium/test/t/geom/helper.hpp +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef TEST_GEOM_HELPER_HPP -#define TEST_GEOM_HELPER_HPP - -#include - -#include - -inline std::string geos_to_wkb(const geos::geom::Geometry* geometry) { - std::stringstream ss; - geos::io::WKBWriter wkb_writer; - wkb_writer.writeHEX(*geometry, ss); - return ss.str(); -} - -#endif // TEST_GEOM_HELPER_HPP diff --git a/third_party/libosmium/test/t/geom/test_exception.cpp b/third_party/libosmium/test/t/geom/test_exception.cpp deleted file mode 100644 index fe950434b..000000000 --- a/third_party/libosmium/test/t/geom/test_exception.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -TEST_CASE("Geometry exception") { - - SECTION("geometry_error") { - osmium::geometry_error e("some error message", "node", 17); - REQUIRE(e.id() == 17); - REQUIRE(std::string(e.what()) == "some error message (node_id=17)"); - } - -} - diff --git a/third_party/libosmium/test/t/geom/test_factory_with_projection.cpp b/third_party/libosmium/test/t/geom/test_factory_with_projection.cpp deleted file mode 100644 index 42fc864bb..000000000 --- a/third_party/libosmium/test/t/geom/test_factory_with_projection.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "catch.hpp" - -#include -#include -#include -#include -#include - -#include "helper.hpp" - -TEST_CASE("Projection") { - - SECTION("point_mercator") { - osmium::geom::WKTFactory factory(2); - - std::string wkt {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(std::string {"POINT(356222.37 467961.14)"} == wkt); - } - - SECTION("point_epsg_3857") { - osmium::geom::WKTFactory factory(osmium::geom::Projection(3857), 2); - - std::string wkt {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(std::string {"POINT(356222.37 467961.14)"} == wkt); - } - - SECTION("wkb_with_parameter") { - osmium::geom::WKBFactory wkb_factory(osmium::geom::Projection(3857), osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - osmium::geom::GEOSFactory geos_factory(osmium::geom::Projection(3857)); - - std::string wkb = wkb_factory.create_point(osmium::Location(3.2, 4.2)); - std::unique_ptr geos_point = geos_factory.create_point(osmium::Location(3.2, 4.2)); - REQUIRE(geos_to_wkb(geos_point.get()) == wkb); - } - - SECTION("cleanup") { - // trying to make valgrind happy, but there is still a memory leak in proj library - pj_deallocate_grids(); - } - -} diff --git a/third_party/libosmium/test/t/geom/test_geojson.cpp b/third_party/libosmium/test/t/geom/test_geojson.cpp deleted file mode 100644 index 8d7df3521..000000000 --- a/third_party/libosmium/test/t/geom/test_geojson.cpp +++ /dev/null @@ -1,236 +0,0 @@ -#include "catch.hpp" - -#include -#include - -#include "../basic/helper.hpp" - -TEST_CASE("GeoJSON_Geometry") { - -SECTION("point") { - osmium::geom::GeoJSONFactory<> factory; - - std::string json {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(std::string{"{\"type\":\"Point\",\"coordinates\":[3.2,4.2]}"} == json); -} - -SECTION("empty_point") { - osmium::geom::GeoJSONFactory<> factory; - - REQUIRE_THROWS_AS(factory.create_point(osmium::Location()), osmium::invalid_location); -} - -SECTION("linestring") { - osmium::geom::GeoJSONFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.2, 4.2}}, - {3, {3.5, 4.7}}, - {4, {3.5, 4.7}}, - {2, {3.6, 4.9}} - }); - - { - std::string json {factory.create_linestring(wnl)}; - REQUIRE(std::string{"{\"type\":\"LineString\",\"coordinates\":[[3.2,4.2],[3.5,4.7],[3.6,4.9]]}"} == json); - } - - { - std::string json {factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)}; - REQUIRE(std::string{"{\"type\":\"LineString\",\"coordinates\":[[3.6,4.9],[3.5,4.7],[3.2,4.2]]}"} == json); - } - - { - std::string json {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; - REQUIRE(std::string{"{\"type\":\"LineString\",\"coordinates\":[[3.2,4.2],[3.5,4.7],[3.5,4.7],[3.6,4.9]]}"} == json); - } - - { - std::string json {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; - REQUIRE(std::string{"{\"type\":\"LineString\",\"coordinates\":[[3.6,4.9],[3.5,4.7],[3.5,4.7],[3.2,4.2]]}"} == json); - } -} - -SECTION("empty_linestring") { - osmium::geom::GeoJSONFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, {}); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward), osmium::geometry_error); -} - -SECTION("linestring_with_two_same_locations") { - osmium::geom::GeoJSONFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.5, 4.7}}, - {2, {3.5, 4.7}} - }); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error); - - { - std::string json {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; - REQUIRE(std::string{"{\"type\":\"LineString\",\"coordinates\":[[3.5,4.7],[3.5,4.7]]}"} == json); - } - - { - std::string json {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; - REQUIRE(std::string{"{\"type\":\"LineString\",\"coordinates\":[[3.5,4.7],[3.5,4.7]]}"} == json); - } -} - -SECTION("linestring_with_undefined_location") { - osmium::geom::GeoJSONFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.5, 4.7}}, - {2, osmium::Location()} - }); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::invalid_location); -} - -SECTION("area_1outer_0inner") { - osmium::geom::GeoJSONFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {3.2, 4.2}}, - {2, {3.5, 4.7}}, - {3, {3.6, 4.9}}, - {1, {3.2, 4.2}} - }} - }); - - REQUIRE(!area.is_multipolygon()); - REQUIRE(std::distance(area.cbegin(), area.cend()) == 2); - REQUIRE(std::distance(area.cbegin(), area.cend()) == area.num_rings().first); - - { - std::string json {factory.create_multipolygon(area)}; - REQUIRE(std::string{"{\"type\":\"MultiPolygon\",\"coordinates\":[[[[3.2,4.2],[3.5,4.7],[3.6,4.9],[3.2,4.2]]]]}"} == json); - } -} - -SECTION("area_1outer_1inner") { - osmium::geom::GeoJSONFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {8.0, 1.0}}, - {7, {8.0, 8.0}}, - {8, {1.0, 8.0}}, - {5, {1.0, 1.0}} - }} - }); - - REQUIRE(!area.is_multipolygon()); - REQUIRE(std::distance(area.cbegin(), area.cend()) == 3); - REQUIRE(std::distance(area.cbegin(), area.cend()) == area.num_rings().first); - REQUIRE(std::distance(area.cbegin(), area.cend()) == area.num_rings().second); - - { - std::string json {factory.create_multipolygon(area)}; - REQUIRE(std::string{"{\"type\":\"MultiPolygon\",\"coordinates\":[[[[0.1,0.1],[9.1,0.1],[9.1,9.1],[0.1,9.1],[0.1,0.1]],[[1,1],[8,1],[8,8],[1,8],[1,1]]]]}"} == json); - } -} - -SECTION("area_2outer_2inner") { - osmium::geom::GeoJSONFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {4.0, 1.0}}, - {7, {4.0, 4.0}}, - {8, {1.0, 4.0}}, - {5, {1.0, 1.0}} - }}, - { false, { - {10, {5.0, 5.0}}, - {11, {5.0, 7.0}}, - {12, {7.0, 7.0}}, - {10, {5.0, 5.0}} - }}, - { true, { - {100, {10.0, 10.0}}, - {101, {11.0, 10.0}}, - {102, {11.0, 11.0}}, - {103, {10.0, 11.0}}, - {100, {10.0, 10.0}} - }} - }); - - REQUIRE(area.is_multipolygon()); - REQUIRE(std::distance(area.cbegin(), area.cend()) == 5); - REQUIRE(std::distance(area.cbegin(), area.cend()) == area.num_rings().first); - REQUIRE(std::distance(area.cbegin(), area.cend()) == area.num_rings().second); - - int outer_ring=0; - int inner_ring=0; - for (auto it_outer = area.cbegin(); it_outer != area.cend(); ++it_outer) { - if (outer_ring == 0) { - REQUIRE(it_outer->front().ref() == 1); - } else if (outer_ring == 1) { - REQUIRE(it_outer->front().ref() == 100); - } else { - REQUIRE(false); - } - for (auto it_inner = area.inner_ring_cbegin(it_outer); it_inner != area.inner_ring_cend(it_outer); ++it_inner) { - if (outer_ring == 0 && inner_ring == 0) { - REQUIRE(it_inner->front().ref() == 5); - } else if (outer_ring == 0 && inner_ring == 1) { - REQUIRE(it_inner->front().ref() == 10); - } else { - REQUIRE(false); - } - ++inner_ring; - } - inner_ring = 0; - ++outer_ring; - } - - { - std::string json {factory.create_multipolygon(area)}; - REQUIRE(std::string{"{\"type\":\"MultiPolygon\",\"coordinates\":[[[[0.1,0.1],[9.1,0.1],[9.1,9.1],[0.1,9.1],[0.1,0.1]],[[1,1],[4,1],[4,4],[1,4],[1,1]],[[5,5],[5,7],[7,7],[5,5]]],[[[10,10],[11,10],[11,11],[10,11],[10,10]]]]}"} == json); - } -} - -} - diff --git a/third_party/libosmium/test/t/geom/test_geos.cpp b/third_party/libosmium/test/t/geom/test_geos.cpp deleted file mode 100644 index d849e3b16..000000000 --- a/third_party/libosmium/test/t/geom/test_geos.cpp +++ /dev/null @@ -1,205 +0,0 @@ -#include "catch.hpp" - -#include -#include - -#include "../basic/helper.hpp" - -TEST_CASE("GEOS geometry factory - create point") { - osmium::geom::GEOSFactory<> factory; - - std::unique_ptr point {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(3.2 == point->getX()); - REQUIRE(4.2 == point->getY()); - REQUIRE(-1 == point->getSRID()); -} - -TEST_CASE("GEOS geometry factory - create point with non-default srid") { - osmium::geom::GEOSFactory<> factory(4326); - - std::unique_ptr point {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(3.2 == point->getX()); - REQUIRE(4.2 == point->getY()); - REQUIRE(4326 == point->getSRID()); -} - -TEST_CASE("GEOS geometry factory - create point with externally created GEOS factory") { - geos::geom::GeometryFactory geos_factory; - osmium::geom::GEOSFactory<> factory(geos_factory); - - std::unique_ptr point {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(3.2 == point->getX()); - REQUIRE(4.2 == point->getY()); - REQUIRE(0 == point->getSRID()); -} - -TEST_CASE("GEOS geometry factory - can not create from invalid location") { - osmium::geom::GEOSFactory<> factory; - - REQUIRE_THROWS_AS(factory.create_point(osmium::Location()), osmium::invalid_location); -} - -TEST_CASE("GEOS geometry factory - create linestring") { - osmium::geom::GEOSFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.2, 4.2}}, - {3, {3.5, 4.7}}, - {4, {3.5, 4.7}}, - {2, {3.6, 4.9}} - }); - - SECTION("from way node list") { - std::unique_ptr linestring {factory.create_linestring(wnl)}; - REQUIRE(3 == linestring->getNumPoints()); - - std::unique_ptr p0 = std::unique_ptr(linestring->getPointN(0)); - REQUIRE(3.2 == p0->getX()); - std::unique_ptr p2 = std::unique_ptr(linestring->getPointN(2)); - REQUIRE(3.6 == p2->getX()); - } - - SECTION("without duplicates and backwards") { - std::unique_ptr linestring {factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)}; - REQUIRE(3 == linestring->getNumPoints()); - std::unique_ptr p0 = std::unique_ptr(linestring->getPointN(0)); - REQUIRE(3.6 == p0->getX()); - std::unique_ptr p2 = std::unique_ptr(linestring->getPointN(2)); - REQUIRE(3.2 == p2->getX()); - } - - SECTION("with duplicates") { - std::unique_ptr linestring {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; - REQUIRE(4 == linestring->getNumPoints()); - std::unique_ptr p0 = std::unique_ptr(linestring->getPointN(0)); - REQUIRE(3.2 == p0->getX()); - } - - SECTION("with duplicates and backwards") { - std::unique_ptr linestring {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; - REQUIRE(4 == linestring->getNumPoints()); - std::unique_ptr p0 = std::unique_ptr(linestring->getPointN(0)); - REQUIRE(3.6 == p0->getX()); - } -} - -TEST_CASE("GEOS geometry factory - create area with one outer and no inner rings") { - osmium::geom::GEOSFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {3.2, 4.2}}, - {2, {3.5, 4.7}}, - {3, {3.6, 4.9}}, - {1, {3.2, 4.2}} - }} - }); - - std::unique_ptr mp {factory.create_multipolygon(area)}; - REQUIRE(1 == mp->getNumGeometries()); - - const geos::geom::Polygon* p0 = dynamic_cast(mp->getGeometryN(0)); - REQUIRE(0 == p0->getNumInteriorRing()); - - const geos::geom::LineString* l0e = p0->getExteriorRing(); - REQUIRE(4 == l0e->getNumPoints()); - - std::unique_ptr l0e_p0 = std::unique_ptr(l0e->getPointN(1)); - REQUIRE(3.5 == l0e_p0->getX()); -} - -TEST_CASE("GEOS geometry factory - create area with one outer and one inner ring") { - osmium::geom::GEOSFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {8.0, 1.0}}, - {7, {8.0, 8.0}}, - {8, {1.0, 8.0}}, - {5, {1.0, 1.0}} - }} - }); - - std::unique_ptr mp {factory.create_multipolygon(area)}; - REQUIRE(1 == mp->getNumGeometries()); - - const geos::geom::Polygon* p0 = dynamic_cast(mp->getGeometryN(0)); - REQUIRE(1 == p0->getNumInteriorRing()); - - const geos::geom::LineString* l0e = p0->getExteriorRing(); - REQUIRE(5 == l0e->getNumPoints()); - - const geos::geom::LineString* l0i0 = p0->getInteriorRingN(0); - REQUIRE(5 == l0i0->getNumPoints()); -} - -TEST_CASE("GEOS geometry factory - create area with two outer and two inner rings") { - osmium::geom::GEOSFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {4.0, 1.0}}, - {7, {4.0, 4.0}}, - {8, {1.0, 4.0}}, - {5, {1.0, 1.0}} - }}, - { false, { - {10, {5.0, 5.0}}, - {11, {5.0, 7.0}}, - {12, {7.0, 7.0}}, - {10, {5.0, 5.0}} - }}, - { true, { - {100, {10.0, 10.0}}, - {101, {11.0, 10.0}}, - {102, {11.0, 11.0}}, - {103, {10.0, 11.0}}, - {100, {10.0, 10.0}} - }} - }); - - std::unique_ptr mp {factory.create_multipolygon(area)}; - REQUIRE(2 == mp->getNumGeometries()); - - const geos::geom::Polygon* p0 = dynamic_cast(mp->getGeometryN(0)); - REQUIRE(2 == p0->getNumInteriorRing()); - - const geos::geom::LineString* l0e = p0->getExteriorRing(); - REQUIRE(5 == l0e->getNumPoints()); - - const geos::geom::Polygon* p1 = dynamic_cast(mp->getGeometryN(1)); - REQUIRE(0 == p1->getNumInteriorRing()); - - const geos::geom::LineString* l1e = p1->getExteriorRing(); - REQUIRE(5 == l1e->getNumPoints()); -} - diff --git a/third_party/libosmium/test/t/geom/test_geos_wkb.cpp b/third_party/libosmium/test/t/geom/test_geos_wkb.cpp deleted file mode 100644 index 0f54427e5..000000000 --- a/third_party/libosmium/test/t/geom/test_geos_wkb.cpp +++ /dev/null @@ -1,156 +0,0 @@ -#include "catch.hpp" - -#include -#include -#include - -#include "../basic/helper.hpp" -#include "helper.hpp" - -TEST_CASE("WKB_Geometry_with_GEOS") { - -SECTION("point") { - osmium::geom::WKBFactory<> wkb_factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - osmium::geom::GEOSFactory<> geos_factory; - - std::string wkb {wkb_factory.create_point(osmium::Location(3.2, 4.2))}; - - std::unique_ptr geos_point = geos_factory.create_point(osmium::Location(3.2, 4.2)); - REQUIRE(geos_to_wkb(geos_point.get()) == wkb); -} - - -SECTION("linestring") { - osmium::geom::WKBFactory<> wkb_factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - osmium::geom::GEOSFactory<> geos_factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.2, 4.2}}, - {3, {3.5, 4.7}}, - {4, {3.5, 4.7}}, - {2, {3.6, 4.9}} - }); - - { - std::string wkb = wkb_factory.create_linestring(wnl); - std::unique_ptr geos = geos_factory.create_linestring(wnl); - REQUIRE(geos_to_wkb(geos.get()) == wkb); - } - - { - std::string wkb = wkb_factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward); - std::unique_ptr geos = geos_factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward); - REQUIRE(geos_to_wkb(geos.get()) == wkb); - } - - { - std::string wkb = wkb_factory.create_linestring(wnl, osmium::geom::use_nodes::all); - std::unique_ptr geos = geos_factory.create_linestring(wnl, osmium::geom::use_nodes::all); - REQUIRE(geos_to_wkb(geos.get()) == wkb); - } - - { - std::string wkb = wkb_factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward); - std::unique_ptr geos = geos_factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward); - REQUIRE(geos_to_wkb(geos.get()) == wkb); - } -} - -SECTION("area_1outer_0inner") { - osmium::geom::WKBFactory<> wkb_factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - osmium::geom::GEOSFactory<> geos_factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {3.2, 4.2}}, - {2, {3.5, 4.7}}, - {3, {3.6, 4.9}}, - {1, {3.2, 4.2}} - }} - }); - - std::string wkb = wkb_factory.create_multipolygon(area); - std::unique_ptr geos = geos_factory.create_multipolygon(area); - REQUIRE(geos_to_wkb(geos.get()) == wkb); -} - -SECTION("area_1outer_1inner") { - osmium::geom::WKBFactory<> wkb_factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - osmium::geom::GEOSFactory<> geos_factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {8.0, 1.0}}, - {7, {8.0, 8.0}}, - {8, {1.0, 8.0}}, - {5, {1.0, 1.0}} - }} - }); - - std::string wkb = wkb_factory.create_multipolygon(area); - std::unique_ptr geos = geos_factory.create_multipolygon(area); - REQUIRE(geos_to_wkb(geos.get()) == wkb); -} - -SECTION("area_2outer_2inner") { - osmium::geom::WKBFactory<> wkb_factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - osmium::geom::GEOSFactory<> geos_factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {4.0, 1.0}}, - {7, {4.0, 4.0}}, - {8, {1.0, 4.0}}, - {5, {1.0, 1.0}} - }}, - { false, { - {10, {5.0, 5.0}}, - {11, {5.0, 7.0}}, - {12, {7.0, 7.0}}, - {10, {5.0, 5.0}} - }}, - { true, { - {100, {10.0, 10.0}}, - {101, {11.0, 10.0}}, - {102, {11.0, 11.0}}, - {103, {10.0, 11.0}}, - {100, {10.0, 10.0}} - }} - }); - - std::string wkb = wkb_factory.create_multipolygon(area); - std::unique_ptr geos = geos_factory.create_multipolygon(area); - REQUIRE(geos_to_wkb(geos.get()) == wkb); -} - -} - diff --git a/third_party/libosmium/test/t/geom/test_mercator.cpp b/third_party/libosmium/test/t/geom/test_mercator.cpp deleted file mode 100644 index cc16e55cf..000000000 --- a/third_party/libosmium/test/t/geom/test_mercator.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "catch.hpp" - -#include - -TEST_CASE("Mercator") { - - SECTION("mercator_projection") { - osmium::geom::MercatorProjection projection; - REQUIRE(3857 == projection.epsg()); - REQUIRE("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs" == projection.proj_string()); - } - - SECTION("low_level_mercator_functions") { - osmium::geom::Coordinates c1(17.839, -3.249); - osmium::geom::Coordinates r1 = osmium::geom::mercator_to_lonlat(osmium::geom::lonlat_to_mercator(c1)); - REQUIRE(r1.x == Approx(c1.x).epsilon(0.000001)); - REQUIRE(r1.y == Approx(c1.y).epsilon(0.000001)); - - osmium::geom::Coordinates c2(-89.2, 15.915); - osmium::geom::Coordinates r2 = osmium::geom::mercator_to_lonlat(osmium::geom::lonlat_to_mercator(c2)); - REQUIRE(r2.x == Approx(c2.x).epsilon(0.000001)); - REQUIRE(r2.y == Approx(c2.y).epsilon(0.000001)); - - osmium::geom::Coordinates c3(180.0, 85.0); - osmium::geom::Coordinates r3 = osmium::geom::mercator_to_lonlat(osmium::geom::lonlat_to_mercator(c3)); - REQUIRE(r3.x == Approx(c3.x).epsilon(0.000001)); - REQUIRE(r3.y == Approx(c3.y).epsilon(0.000001)); - } - - SECTION("mercator_bounds") { - osmium::Location mmax(180.0, osmium::geom::MERCATOR_MAX_LAT); - osmium::geom::Coordinates c = osmium::geom::lonlat_to_mercator(mmax); - REQUIRE(c.x == Approx(c.y).epsilon(0.001)); - REQUIRE(osmium::geom::detail::y_to_lat(osmium::geom::detail::lon_to_x(180.0)) == Approx(osmium::geom::MERCATOR_MAX_LAT).epsilon(0.0000001)); - } - -} diff --git a/third_party/libosmium/test/t/geom/test_ogr.cpp b/third_party/libosmium/test/t/geom/test_ogr.cpp deleted file mode 100644 index 28a10717d..000000000 --- a/third_party/libosmium/test/t/geom/test_ogr.cpp +++ /dev/null @@ -1,185 +0,0 @@ -#include "catch.hpp" - -#include -#include - -#include "../basic/helper.hpp" - -TEST_CASE("OGR_Geometry") { - -SECTION("point") { - osmium::geom::OGRFactory<> factory; - - std::unique_ptr point {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(3.2 == point->getX()); - REQUIRE(4.2 == point->getY()); -} - -SECTION("empty_point") { - osmium::geom::OGRFactory<> factory; - - REQUIRE_THROWS_AS(factory.create_point(osmium::Location()), osmium::invalid_location); -} - -SECTION("linestring") { - osmium::geom::OGRFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.2, 4.2}}, - {3, {3.5, 4.7}}, - {4, {3.5, 4.7}}, - {2, {3.6, 4.9}} - }); - - { - std::unique_ptr linestring {factory.create_linestring(wnl)}; - REQUIRE(3 == linestring->getNumPoints()); - - REQUIRE(3.2 == linestring->getX(0)); - REQUIRE(3.6 == linestring->getX(2)); - } - - { - std::unique_ptr linestring {factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)}; - REQUIRE(3 == linestring->getNumPoints()); - - REQUIRE(3.6 == linestring->getX(0)); - REQUIRE(3.2 == linestring->getX(2)); - } - - { - std::unique_ptr linestring {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; - REQUIRE(4 == linestring->getNumPoints()); - - REQUIRE(3.2 == linestring->getX(0)); - } - - { - std::unique_ptr linestring {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; - REQUIRE(4 == linestring->getNumPoints()); - - REQUIRE(3.6 == linestring->getX(0)); - } -} - -SECTION("area_1outer_0inner") { - osmium::geom::OGRFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {3.2, 4.2}}, - {2, {3.5, 4.7}}, - {3, {3.6, 4.9}}, - {1, {3.2, 4.2}} - }} - }); - - std::unique_ptr mp {factory.create_multipolygon(area)}; - REQUIRE(1 == mp->getNumGeometries()); - - const OGRPolygon* p0 = dynamic_cast(mp->getGeometryRef(0)); - REQUIRE(0 == p0->getNumInteriorRings()); - - const OGRLineString* l0e = p0->getExteriorRing(); - REQUIRE(4 == l0e->getNumPoints()); - - REQUIRE(3.5 == l0e->getX(1)); -} - -SECTION("area_1outer_1inner") { - osmium::geom::OGRFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {8.0, 1.0}}, - {7, {8.0, 8.0}}, - {8, {1.0, 8.0}}, - {5, {1.0, 1.0}} - }} - }); - - std::unique_ptr mp {factory.create_multipolygon(area)}; - REQUIRE(1 == mp->getNumGeometries()); - - const OGRPolygon* p0 = dynamic_cast(mp->getGeometryRef(0)); - REQUIRE(1 == p0->getNumInteriorRings()); - - const OGRLineString* l0e = p0->getExteriorRing(); - REQUIRE(5 == l0e->getNumPoints()); - - const OGRLineString* l0i0 = p0->getInteriorRing(0); - REQUIRE(5 == l0i0->getNumPoints()); -} - -SECTION("area_2outer_2inner") { - osmium::geom::OGRFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {4.0, 1.0}}, - {7, {4.0, 4.0}}, - {8, {1.0, 4.0}}, - {5, {1.0, 1.0}} - }}, - { false, { - {10, {5.0, 5.0}}, - {11, {5.0, 7.0}}, - {12, {7.0, 7.0}}, - {10, {5.0, 5.0}} - }}, - { true, { - {100, {10.0, 10.0}}, - {101, {11.0, 10.0}}, - {102, {11.0, 11.0}}, - {103, {10.0, 11.0}}, - {100, {10.0, 10.0}} - }} - }); - - std::unique_ptr mp {factory.create_multipolygon(area)}; - REQUIRE(2 == mp->getNumGeometries()); - - const OGRPolygon* p0 = dynamic_cast(mp->getGeometryRef(0)); - REQUIRE(2 == p0->getNumInteriorRings()); - - const OGRLineString* l0e = p0->getExteriorRing(); - REQUIRE(5 == l0e->getNumPoints()); - - const OGRPolygon* p1 = dynamic_cast(mp->getGeometryRef(1)); - REQUIRE(0 == p1->getNumInteriorRings()); - - const OGRLineString* l1e = p1->getExteriorRing(); - REQUIRE(5 == l1e->getNumPoints()); -} - -} - diff --git a/third_party/libosmium/test/t/geom/test_projection.cpp b/third_party/libosmium/test/t/geom/test_projection.cpp deleted file mode 100644 index 58854109e..000000000 --- a/third_party/libosmium/test/t/geom/test_projection.cpp +++ /dev/null @@ -1,149 +0,0 @@ -#include "catch.hpp" - -#include - -#include -#include -#include - -TEST_CASE("Projection") { - -SECTION("identity_projection") { - osmium::geom::IdentityProjection projection; - REQUIRE(4326 == projection.epsg()); - REQUIRE("+proj=longlat +datum=WGS84 +no_defs" == projection.proj_string()); -} - -SECTION("project_location_4326") { - osmium::geom::Projection projection(4326); - REQUIRE(4326 == projection.epsg()); - REQUIRE("+init=epsg:4326" == projection.proj_string()); - - const osmium::Location loc(1.0, 2.0); - const osmium::geom::Coordinates c {1.0, 2.0}; - REQUIRE(c == projection(loc)); -} - -SECTION("project_location_4326_string") { - osmium::geom::Projection projection("+init=epsg:4326"); - REQUIRE(-1 == projection.epsg()); - REQUIRE("+init=epsg:4326" == projection.proj_string()); - - const osmium::Location loc(1.0, 2.0); - const osmium::geom::Coordinates c {1.0, 2.0}; - REQUIRE(c == projection(loc)); -} - -SECTION("unknown_projection_string") { - REQUIRE_THROWS_AS(osmium::geom::Projection projection("abc"), osmium::projection_error); -} - -SECTION("unknown_epsg_code") { - REQUIRE_THROWS_AS(osmium::geom::Projection projection(9999999), osmium::projection_error); -} - -SECTION("project_location_3857") { - osmium::geom::Projection projection(3857); - REQUIRE(3857 == projection.epsg()); - REQUIRE("+init=epsg:3857" == projection.proj_string()); - - { - const osmium::Location loc(0.0, 0.0); - const osmium::geom::Coordinates c {0.0, 0.0}; - REQUIRE(projection(loc).x == Approx(c.x).epsilon(0.1)); - REQUIRE(projection(loc).y == Approx(c.y).epsilon(0.1)); - } - { - const osmium::Location loc(180.0, 0.0); - const osmium::geom::Coordinates c {20037508.34, 0.0}; - REQUIRE(projection(loc).x == Approx(c.x).epsilon(0.1)); - REQUIRE(projection(loc).y == Approx(c.y).epsilon(0.1)); - } - { - const osmium::Location loc(180.0, 0.0); - const osmium::geom::Coordinates c {20037508.34, 0.0}; - REQUIRE(projection(loc).x == Approx(c.x).epsilon(0.1)); - REQUIRE(projection(loc).y == Approx(c.y).epsilon(0.1)); - } - { - const osmium::Location loc(0.0, 85.0511288); - const osmium::geom::Coordinates c {0.0, 20037508.34}; - REQUIRE(projection(loc).x == Approx(c.x).epsilon(0.1)); - REQUIRE(projection(loc).y == Approx(c.y).epsilon(0.1)); - } -} - -SECTION("project_location_mercator") { - osmium::geom::MercatorProjection projection; - - { - const osmium::Location loc(0.0, 0.0); - const osmium::geom::Coordinates c {0.0, 0.0}; - REQUIRE(projection(loc).x == Approx(c.x).epsilon(0.1)); - REQUIRE(projection(loc).y == Approx(c.y).epsilon(0.1)); - } - { - const osmium::Location loc(180.0, 0.0); - const osmium::geom::Coordinates c {20037508.34, 0.0}; - REQUIRE(projection(loc).x == Approx(c.x).epsilon(0.1)); - REQUIRE(projection(loc).y == Approx(c.y).epsilon(0.1)); - } - { - const osmium::Location loc(180.0, 0.0); - const osmium::geom::Coordinates c {20037508.34, 0.0}; - REQUIRE(projection(loc).x == Approx(c.x).epsilon(0.1)); - REQUIRE(projection(loc).y == Approx(c.y).epsilon(0.1)); - } - { - const osmium::Location loc(0.0, 85.0511288); - const osmium::geom::Coordinates c {0.0, 20037508.34}; - REQUIRE(projection(loc).x == Approx(c.x).epsilon(0.1)); - REQUIRE(projection(loc).y == Approx(c.y).epsilon(0.1)); - } -} - -SECTION("compare_mercators") { - osmium::geom::MercatorProjection projection_merc; - osmium::geom::Projection projection_3857(3857); - REQUIRE(3857 == projection_3857.epsg()); - REQUIRE("+init=epsg:3857" == projection_3857.proj_string()); - - { - const osmium::Location loc(4.2, 27.3); - REQUIRE(projection_merc(loc).x == Approx(projection_3857(loc).x).epsilon(0.1)); - REQUIRE(projection_merc(loc).y == Approx(projection_3857(loc).y).epsilon(0.1)); - } - { - const osmium::Location loc(160.789, -42.42); - REQUIRE(projection_merc(loc).x == Approx(projection_3857(loc).x).epsilon(0.1)); - REQUIRE(projection_merc(loc).y == Approx(projection_3857(loc).y).epsilon(0.1)); - } - { - const osmium::Location loc(-0.001, 0.001); - REQUIRE(projection_merc(loc).x == Approx(projection_3857(loc).x).epsilon(0.1)); - REQUIRE(projection_merc(loc).y == Approx(projection_3857(loc).y).epsilon(0.1)); - } - { - const osmium::Location loc(-85.2, -85.2); - REQUIRE(projection_merc(loc).x == Approx(projection_3857(loc).x).epsilon(0.1)); - REQUIRE(projection_merc(loc).y == Approx(projection_3857(loc).y).epsilon(0.1)); - } -} - -SECTION("compare_mercators") { - osmium::geom::MercatorProjection projection_merc; - osmium::geom::Projection projection_3857(3857); - - std::random_device rd; - std::mt19937 gen(rd()); - std::uniform_real_distribution<> dis_x(-180.0, 180.0); - std::uniform_real_distribution<> dis_y(-90.0, 90.0); - - for (int n = 0; n < 100000; ++n) { - const osmium::Location loc(dis_x(gen), dis_y(gen)); - REQUIRE(projection_merc(loc).x == Approx(projection_3857(loc).x).epsilon(0.1)); - REQUIRE(projection_merc(loc).y == Approx(projection_3857(loc).y).epsilon(0.1)); - } -} - -} diff --git a/third_party/libosmium/test/t/geom/test_tile.cpp b/third_party/libosmium/test/t/geom/test_tile.cpp deleted file mode 100644 index e80cb9604..000000000 --- a/third_party/libosmium/test/t/geom/test_tile.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -#include "helper.hpp" - -#include "test_tile_data.hpp" - -TEST_CASE("Tile") { - - SECTION("x0.0 y0.0 zoom 0") { - osmium::Location l(0.0, 0.0); - - osmium::geom::Tile t(0, l); - - REQUIRE(t.x == 0); - REQUIRE(t.y == 0); - REQUIRE(t.z == 0); - } - - SECTION("x180.0 y90.0 zoom 0") { - osmium::Location l(180.0, 90.0); - - osmium::geom::Tile t(0, l); - - REQUIRE(t.x == 0); - REQUIRE(t.y == 0); - REQUIRE(t.z == 0); - } - - SECTION("x180.0 y90.0 zoom 4") { - osmium::Location l(180.0, 90.0); - - osmium::geom::Tile t(4, l); - - REQUIRE(t.x == (1 << 4) - 1); - REQUIRE(t.y == 0); - REQUIRE(t.z == 4); - } - - SECTION("x0.0 y0.0 zoom 4") { - osmium::Location l(0.0, 0.0); - - osmium::geom::Tile t(4, l); - - auto n = 1 << (4-1); - REQUIRE(t.x == n); - REQUIRE(t.y == n); - REQUIRE(t.z == 4); - } - - SECTION("equality") { - osmium::geom::Tile a(4, 3, 4); - osmium::geom::Tile b(4, 3, 4); - osmium::geom::Tile c(4, 4, 3); - REQUIRE(a == b); - REQUIRE(a != c); - REQUIRE(b != c); - } - - SECTION("order") { - osmium::geom::Tile a(2, 3, 4); - osmium::geom::Tile b(4, 3, 4); - osmium::geom::Tile c(4, 4, 3); - osmium::geom::Tile d(4, 4, 2); - REQUIRE(a < b); - REQUIRE(a < c); - REQUIRE(b < c); - REQUIRE(d < c); - } - - SECTION("tilelist") { - std::istringstream input_data(s); - while (input_data) { - double lon, lat; - uint32_t x, y, zoom; - input_data >> lon; - input_data >> lat; - input_data >> x; - input_data >> y; - input_data >> zoom; - - osmium::Location l(lon, lat); - osmium::geom::Tile t(zoom, l); - REQUIRE(t.x == x); - REQUIRE(t.y == y); - } - } - -} - diff --git a/third_party/libosmium/test/t/geom/test_tile_data.hpp b/third_party/libosmium/test/t/geom/test_tile_data.hpp deleted file mode 100644 index 8a22cfa51..000000000 --- a/third_party/libosmium/test/t/geom/test_tile_data.hpp +++ /dev/null @@ -1,477 +0,0 @@ - -#include - -static std::string s = R"(127.4864358 16.8380041 223904 118630 18 -163.1103174 39.4760232 121 48 7 --4.1372725 -22.5105386 31 36 6 -98.7193066 -36.2312406 1 1 1 -63.5773661 -13.47636 21 17 5 --88.4518148 37.9805485 260 395 10 --14.5903133 -28.2989812 3763 4767 13 --13.4971239 -34.4080035 14 19 5 --169.156223 -64.0900356 3 93 7 -27.1473191 -4.1993125 4713 4191 13 --160.9733129 54.3684314 13 81 8 -129.0194139 14.2576156 439 235 9 --69.5085993 -56.8253221 10057 22700 15 --77.8387486 18.1961517 1162 1837 12 --76.2695325 -18.2494296 147 282 9 --91.594905 7.6698071 1 3 3 --116.7926741 -20.6060813 179 571 10 -109.0552776 -1.9947569 52620 33131 16 --156.1846426 -79.3817554 33 449 9 --95.3403755 -27.8978407 1 4 3 --55.1827573 -73.2293796 44 103 7 --108.5207885 -48.0099293 50 167 8 -23.7540108 -15.3395164 9273 8898 14 --155.6662842 -68.3295899 0 0 0 -75.8139119 30.9914252 363 209 9 --135.8034544 64.7242469 0 1 2 --48.743352 70.9392876 23 13 6 --38.6968026 7.7867812 0 0 0 --18.5234838 11.8557704 29395 30594 16 --152.5632568 19.4069834 78 455 10 --63.2089431 -80.5909713 0 0 0 --94.1255611 -81.2028822 244 930 10 -175.0862205 -33.0865142 3 2 2 --179.6241926 -37.0256609 1 625 10 -135.6783824 -38.6011643 459739 323170 19 --139.6407533 -83.2495209 0 7 3 --14.1336447 -56.5465949 58 88 7 --30.7414568 -32.9543731 26 38 6 -10.3306861 73.2444693 1082 399 11 --84.8379263 29.2363222 16 26 6 --94.0685822 -39.5503996 7821 20309 15 --86.5944356 -41.7491891 265 642 10 -11.9182172 -80.5613703 34937 58784 16 -91.8773752 -32.1741317 0 0 0 -126.2879157 20.5759564 1742 904 11 --160.7743029 -47.3192128 27999 340565 19 --4.2449045 -50.3288332 31 42 6 --66.6857158 61.4380757 10 9 5 -169.7372317 -74.3365704 3 3 2 -87.4815328 75.6218888 95 21 7 -60.3544927 28.3165267 0 0 0 --48.9614619 -59.3292497 2 5 3 --123.2935018 -59.5454886 80 362 9 --31.5909316 -14.8985476 13 17 5 -58.1862173 59.0957666 2710 1209 12 --72.8881665 -2.2648849 1218 2073 12 --33.7267461 8.6006817 106512 124785 18 -175.723181 46.4929742 7 2 3 --127.1963326 76.0328786 0 0 0 --161.7444367 -26.7634497 13293 151310 18 --163.976298 -8.1169845 91 1070 11 -63.7757109 5.6049418 2 1 2 -12.7012434 22.1157713 70160 57276 17 -19.5832849 -25.0284049 1135 1171 11 --22.6619642 54.8831276 111 81 8 -78.7736907 24.0919863 5888 3530 13 -121.9003045 -64.6256685 107 94 7 --64.8766793 61.6655916 81 71 8 -113.0498445 -70.0016518 416 397 9 --51.5116259 68.1532424 46781 31217 17 --89.9005747 87.9523248 512 0 11 -59.2536822 -75.1520493 10 13 4 -17.375372 74.9259262 287448 93371 19 -75.6426945 8.4808632 186153 124873 18 -144.89589 75.1647661 14786 2875 14 -174.4350898 -29.268169 258091 153376 18 --91.8773113 50.6182166 0 0 0 -5.3822308 45.1391794 134991 94156 18 -43.0978373 -10.0764237 324909 276895 19 -55.6682917 -40.9015342 21451 20470 15 --37.584032 52.253723 6 5 4 -131.0141997 29.0271798 28309 13621 15 -69.8830721 -86.8548645 363918 524287 19 --107.7917548 -76.9626654 26290 110787 17 --57.1736642 49.9345991 2 2 3 -165.5170226 -84.9735363 982 1021 10 --139.7208984 -73.8754873 1 12 4 --154.5959463 -10.596718 4 33 6 --106.4164918 36.5042686 3348 6405 14 --92.9688259 -11.2262505 0 2 2 -138.2722283 8.1109779 7 3 3 -123.1389319 -40.3505677 862 637 10 --171.4780435 24.9112482 0 13 5 -89.3668763 -63.1809434 392293 381781 19 --79.6906176 -13.376312 9130 17612 15 -133.1329522 -28.9032634 445 298 9 -115.0369496 70.6965823 6 1 3 --74.8926697 -78.9770185 2391 7144 13 -51.9175766 73.0184277 164 50 8 -178.1319784 43.7111421 509 186 9 -162.4098389 61.1595443 0 0 0 -7.6241126 -75.6182944 2 3 2 -172.8902767 28.5068027 125 53 7 -156.4030739 -76.7309238 478 431 9 --131.3963189 62.2039684 1 2 3 -34.6057088 -36.2933264 2441 2491 12 --3.3896413 -48.2734347 15 20 5 -83.528842 -48.219886 2998 2675 12 -16.6000512 -31.6322244 17894 19421 15 --18.2425749 21.0749052 14 14 5 -35.6035336 46.9916228 78498 46105 17 --109.3453091 -34.2312523 12 38 6 -88.4909962 58.6104749 47 19 6 --129.7372783 21.7408241 571 1794 12 -25.7269392 -40.1240139 1 1 1 -26.3829579 5.248998 37570 31811 16 -141.1768247 -41.4653038 14617 10269 14 -151.3788752 -38.0160512 241302 161042 18 --92.7471483 -35.391745 15883 39664 16 -142.5902623 -14.1023743 28 17 5 -179.3461485 -86.7573357 3 3 2 --40.9746194 61.5689546 790 576 11 -128.6399735 -54.8895009 56186 44772 16 --141.391583 -63.8272 0 2 2 --3.5004218 19.3089998 4016 3648 13 -16.138208 -42.7868627 1 1 1 -78.502315 -18.91667 2 2 2 --44.6311826 -15.7483106 98572 142686 18 --120.431941 -39.3431529 0 0 0 --70.4915024 25.4763412 9967 13984 15 -118.0711114 -66.5691073 211 192 8 --114.945538 38.1764389 0 0 0 -142.991315 -46.3378741 14699 10577 14 -34.2770562 -84.7173756 312063 518834 19 -109.5563415 -85.9138266 105424 131071 17 --171.8032643 70.1948223 0 3 4 --90.8434294 89.7252122 126 0 9 -163.5677082 -53.9885419 3 2 2 -128.884016 -63.0732584 112461 95358 17 -116.5348575 -56.1616143 843 705 10 --171.5770602 37.9225943 11 197 9 -48.1396653 -49.3932234 5191 5392 13 --157.6786731 15.3895763 32507 239456 19 -15.7385145 -37.1364397 1113 1251 11 -137.5179466 61.2025671 1 0 1 --70.4767722 42.9798424 19938 24086 16 -27.8867901 43.4642562 9461 5991 14 -68.5677462 -84.9560937 11312 16334 14 --56.790151 -67.124147 179437 395476 19 -108.850832 43.3493384 26291 11996 15 --139.0655153 8.2673118 1 7 4 -59.3726661 83.3857699 21788 1515 15 --158.4718709 -12.2313178 1 17 5 -30.358316 -83.020501 2393 3871 12 --169.9667863 71.1152107 1 13 6 --89.9418297 -7.7258969 131156 273429 19 --16.5050312 47.1843923 116 89 8 --151.9641886 -36.3579042 5103 39881 16 -169.7406916 60.0950674 62 18 6 -32.6694543 -1.8435981 2 2 2 -97.7880811 77.5295169 50569 9674 16 -87.7554889 -85.6741368 389947 524287 19 --19.0174909 29.1940122 0 0 1 --86.6180019 82.6445919 1 0 2 --50.1997802 -21.1913243 1476 2294 12 -73.8710121 75.2201385 5 1 3 -41.7434624 79.1410045 322937 65770 19 --122.4312562 -68.4513916 10 48 6 --54.6116448 -23.1761137 1 2 2 --35.8774263 -51.5317442 102 170 8 -179.2976644 -76.2729885 127 107 7 --111.6934402 -85.2696836 1 7 3 --24.2137947 28.4102025 3 3 3 --168.0816395 -64.0317696 16 375 9 -43.2514876 6.4266793 2540 1974 12 -25.5877932 49.3486828 4 2 3 --133.3671657 -25.0795973 8 36 6 --140.2002274 -37.3713396 452 2507 12 -73.6326557 -21.9898207 360 288 9 --83.0901448 -69.1893461 2205 6305 13 --32.83227 -11.1061854 3348 4350 13 --151.8897244 14.6891958 0 0 0 --118.1125151 82.3085937 704 288 12 -119.9903922 1.4884267 53 31 6 --116.9455865 -48.1971821 0 2 2 -111.4279587 -52.6024326 828 688 10 --78.9207774 28.6183104 147207 218615 19 -45.1367631 24.1416251 40 27 6 -115.0905685 7.2971256 6714 3929 13 --58.0837371 -55.4033522 43 87 7 --44.6785779 83.0751777 6158 877 14 -80.2002966 84.3087089 2960 91 12 --167.3118039 -59.2698371 72 1445 11 -139.9974902 -74.5994693 455 419 9 --27.5858357 -36.1890547 6936 9960 14 -68.8572424 20.2096749 353 226 9 --168.7172825 69.1607462 2053 15104 16 -62.1361934 74.6007777 44079 11896 16 --102.9645124 65.3735325 112191 135144 19 -178.8434887 18.6231394 65325 29316 16 --138.0494072 -80.3786289 29 228 8 -33.3858934 62.9029909 155382 71699 18 --1.6915643 74.737228 1 0 2 -18.2680756 6.6441482 1 0 1 -34.0511738 -28.6862516 2 2 2 --24.0705994 -0.6026568 28386 32877 16 --176.8765092 -14.3252022 568 35403 16 -154.6553417 -79.7390666 1903 1809 11 -151.6055263 59.552346 14 4 4 --101.7681729 45.3498263 113933 187876 19 --52.3703658 -89.8260406 181 511 9 --85.7937259 16.5632413 2143 3713 13 -114.7030999 6.6846014 104 61 7 -13.6027861 88.6863877 2 0 2 -60.5726928 38.256536 43794 25219 16 -141.0903381 -35.4468007 7306 4959 13 --38.8182454 -55.2332792 200 350 9 -179.7818018 -79.6600052 523970 462627 19 --45.2102175 82.7381225 196301 32058 19 --36.5811826 -35.3991346 0 0 0 --26.7719575 -75.7014102 223154 435372 19 -77.3451937 -65.4613594 1 1 1 --37.3286225 38.3250599 51945 50407 17 -70.8235495 35.3870419 365288 206979 19 -99.8381373 -83.4101655 1 1 1 -25.8851923 67.415543 9370 3991 14 --12.3393758 68.5972027 7 3 4 --142.9400273 -36.2904852 1 9 4 -110.085689 -50.9514972 422467 348655 19 -121.5093657 53.9939447 54888 21044 16 -151.1307841 -33.0798435 58 38 6 -100.4346499 -57.0129759 6 5 3 -114.0564882 63.4987339 428250 141474 19 --17.3978586 19.2981593 57 57 7 --129.101039 -66.3423574 579 3067 12 -117.6639917 14.0568892 433504 241463 19 -97.7014577 69.1261732 202216 60490 18 --174.7931333 81.4174709 7583 46045 19 -47.205341 -48.8608019 20680 21495 15 -167.416796 -7.5063098 247 133 8 -63.6744589 21.3392888 0 0 0 --106.0719817 33.8353547 53832 104862 18 --48.4051268 27.0438152 191648 221209 19 -64.5675545 -27.0683253 5 4 3 -110.7800249 -35.8217841 0 0 0 -164.8954138 81.9558801 31393 2538 15 --54.4595565 -23.0128432 357 579 10 -43.2542709 67.694011 2540 989 12 -137.6537233 -78.7052092 28913 28450 15 -76.9271563 -60.0777348 0 0 0 --145.0240216 47.3869213 6367 22947 16 -136.2328853 -73.4534547 3598 3304 12 -48.8047148 74.3001023 81 23 7 --144.6978756 33.6270048 200 820 11 -64.6723407 -37.196427 21 19 5 --58.3356482 -19.0812366 22148 36307 16 -19.611535 -31.3013119 0 0 0 --63.8923439 -25.9560287 1 2 2 --152.5288047 -30.9747477 0 1 1 --99.8509683 -69.0258965 7295 25181 15 --22.9015207 -21.0915082 13 17 5 -161.4402438 61.1430241 15539 4652 14 --102.9499976 -1.2629414 1 4 3 --159.7995801 51.1570142 14 85 8 -10.5265485 -86.8526122 67 127 7 -47.1581041 -73.1628608 646 823 10 -2.7577906 -66.3257104 66540 98133 17 -96.9653593 -9.8258675 6 4 3 --55.4199846 25.3325116 2834 3499 13 --47.3590106 59.5085133 2 2 3 -179.1441501 22.1324479 7 3 3 -16.2649007 47.8480398 4 2 3 --27.8373963 -0.3926597 27700 32839 16 --99.7938802 -48.8013068 912 2685 12 -133.4858024 28.457146 3 1 2 --174.7621207 -25.8318084 238 9409 14 -106.856378 19.640472 203 113 8 -31.4361995 -80.2488406 76981 116886 17 -148.6539554 -70.0347611 116 99 7 -45.1821773 17.5961595 80 57 7 --30.3630114 71.3238998 54481 27877 17 -106.547704 44.9731358 6520 2947 13 --132.8057564 23.3928795 67 221 9 -116.6455816 -10.1097592 52 33 6 -172.5512559 -53.2307289 3 2 2 --114.2084519 42.834332 2994 6030 14 -91.0172087 87.6025 1 0 1 --101.666812 -84.7858729 7130 32495 15 --14.8074931 68.3277393 0 0 0 -140.3354277 -7.8709618 14 8 4 --130.4961987 -69.4777523 9011 50594 16 --121.239479 1.0896367 1 3 3 --141.2241052 3.4495348 56471 257117 19 -42.6041377 -19.1328846 2532 2269 12 -141.3750885 -1.8110503 468036 264781 19 --26.545021 -30.9641274 218 302 9 -87.6154866 10.1978751 5 3 3 -88.002559 -33.4108714 762 612 10 -170.9910642 -7.1925019 3993 2130 12 --66.5680487 -88.1144993 165197 524287 19 --71.5925378 45.720316 0 0 0 --16.457642 57.1688038 930 625 11 -20.8379624 -11.1485568 35 33 6 --72.9399538 -16.6504502 1 2 2 -52.8746845 -71.5213577 10598 12927 14 -93.2392918 12.5073156 48 29 6 --3.7803834 73.7748237 128319 49794 18 -93.5713795 -38.8308882 24 19 5 -87.3474619 -6.9970464 23 16 5 -161.2199467 48.5612779 30 11 5 -87.343969 -31.3153618 47 37 6 -60.5318627 58.0869948 42 19 6 -161.4388458 42.7612385 1 0 1 -14.1262999 -26.2101142 4 4 3 --135.776346 -21.4248586 503 2297 12 --100.3980364 82.0236388 1 0 3 --55.8093833 -87.2455194 0 0 0 --15.6397352 64.454076 935 540 11 -131.5974423 39.1251372 110 48 7 -56.8045509 27.5658629 168 107 8 -146.3634996 14.9287416 3 1 2 -51.5699041 74.0370231 82 23 7 -29.3100901 33.7208834 152414 104963 18 -19.0622442 1.6781772 141 126 8 --22.2575472 73.6467471 114864 50126 18 -125.0208495 47.8533914 3470 1426 12 --92.4804503 29.8409387 995 1691 12 -113.6362202 86.1158625 0 0 0 -113.6203756 28.4267778 26 13 5 -124.472202 25.8347062 13856 6974 14 -79.3654306 -33.7864728 46 38 6 --121.169233 -66.7642843 2 12 4 -179.5816311 1.0182064 0 0 0 -179.1123794 53.367624 0 0 0 --25.6611689 32.6575586 14048 13236 15 -92.3370554 58.8306651 12 4 4 -142.2756448 63.6603101 3 1 2 --162.8914282 -84.54406 6229 129034 17 --54.0759935 53.1086102 0 0 0 -9.1647045 -39.4876873 34436 40604 16 -59.3708822 -43.9789068 10894 10425 14 --16.6397572 46.5985252 929 723 11 --36.1053642 -67.6882841 0 1 1 --82.5851985 -69.5277766 4 12 4 -117.0059969 -63.2697116 432546 382068 19 -127.9740251 85.5341901 112129 0 17 --13.9255265 59.7720207 120931 76457 18 --167.7778382 41.7974194 69 761 11 --100.1217856 -70.5624949 454 1599 11 --42.4790343 -2.0016191 25034 33132 16 --8.0782317 65.9680074 30 16 6 --37.0481466 -55.2856125 203 350 9 -149.074382 16.7121888 58 28 6 --53.1010518 -15.8492068 0 0 0 -50.8517919 -30.8366257 42025 38674 16 --175.0355994 77.1929422 0 4 5 --33.3221217 72.5636809 6 3 4 --139.9201802 52.3400823 7296 21546 16 -86.0299659 23.4535286 1513 886 11 -105.6297238 -50.5521342 25998 21733 15 -104.2700533 36.5417507 206999 102450 18 -58.5238253 84.0320186 86843 3912 17 --121.9177826 65.4393267 1321 2108 13 --152.689211 57.4112922 39774 159515 19 -94.2583831 80.8625455 6240 801 13 -118.8199874 -37.6116567 53 39 6 -5.787144 7.0599251 4227 3934 13 -152.1682213 11.778732 236 119 8 -37.4503636 64.311498 2474 1084 12 -35.2616139 -59.8196291 38 45 6 --20.2808572 -26.9983008 29075 37875 16 --88.8541607 -20.4896703 66370 146320 18 -125.7726709 41.2603793 27 11 5 --55.4322696 22.1767236 11338 14313 15 --38.2393439 -56.4681037 6 11 4 --139.4517643 -81.3621632 3 29 5 --146.7954207 -74.6050826 6044 53642 16 -161.6654898 -71.7313805 15549 12957 14 --85.4720514 -73.177675 2 6 3 --25.7457381 -42.9842376 13 20 5 --2.0766311 51.0142455 0 0 1 --82.9179334 1.4865326 8836 16248 15 -140.5661302 61.5056993 28 9 5 --30.2614099 35.5786378 54518 51659 17 --49.2072142 -38.6965571 0 1 1 -124.6587534 9.5039576 433 242 9 --113.4516741 81.4585593 24229 11410 17 --4.5134723 68.229217 3 1 3 -75.4838529 -44.997406 2906 2622 12 -6.4715239 28.6900832 8486 6828 14 -91.9187555 -24.8192643 6187 4679 13 --28.2510181 -42.6238777 26 40 6 --151.1042237 -21.4553189 2630 18384 15 --149.6272551 0.4235911 1382 8172 14 --51.9171488 74.630423 0 0 0 --36.5660117 37.242858 101 99 8 -91.7136677 -30.9077617 772 604 10 -61.6846009 -85.9378164 5 7 3 -11.3772008 69.40183 34839 14980 16 -82.6825938 9.4496443 11954 7759 14 -61.8446231 -40.0114106 2751 2545 12 --51.6223196 -11.7880324 5 8 4 -113.0309076 -73.4376173 13336 13217 14 --169.3808275 -72.7209175 0 25 5 --98.5653414 -80.0893122 231 910 10 --20.4653707 29.9801495 3 3 3 -78.9156686 2.599349 0 0 0 -76.0635255 -71.0823347 2913 3216 12 --26.1185551 22.3616029 28013 28589 16 -177.8803853 -56.3662368 4071 2828 12 --157.7926463 78.4998022 15 34 8 -168.6834344 -34.5535211 7934 4934 13 --77.208013 -44.0964079 0 1 1 --56.6162078 28.1240365 10 13 5 -8.6548899 72.178831 137374 53767 18 --27.9342497 8.2525327 1 1 2 -91.6356971 -13.5230128 6181 4406 13 --161.9980398 -75.4443511 0 13 4 -46.8556576 -27.1078679 5162 4737 13 -147.2806954 -48.1491071 465 334 9 --168.2679875 -29.0171568 0 2 2 -10.0251187 -3.144812 8 8 4 -109.0281873 81.9713348 26307 2528 15 --129.6281276 -36.9614028 73359 320148 19 -7.3831244 -18.3270273 2132 2260 12 --34.4625217 53.2837646 52988 42524 17 -129.8855275 -26.30807 3525 2358 12 --69.6374195 -45.7769025 10045 21081 15 -59.9868336 50.3716565 43688 22120 16 -126.4653338 -75.607391 1743 1698 11 --34.6459616 53.2502443 51 41 7 -152.2415169 -71.7528837 1 1 1 --83.2126752 32.6685119 35239 52939 17 -178.6388805 70.5727365 31 7 5 --153.5646223 -81.9491561 2 29 5 -178.2668159 11.8222247 0 0 0 --27.136902 18.4287365 6 7 4 --104.7744923 -64.7769211 54777 193540 18 -58.2318889 9.5897974 2710 1938 12 -138.9707487 -65.2734433 14516 12149 14 --115.29331 -84.3402223 2944 16033 14 --66.3487123 -81.8340211 20 58 6 -76.1802855 40.4007156 364 193 9 --77.5026834 -30.653231 145 301 9 --52.6095007 -79.7155889 11595 28942 15 --2.5594899 -31.6276806 7 9 4 --58.6267217 41.4851391 2 2 3 --0.7245205 -70.7329433 509 801 10 -161.2822996 -79.0311957 124257 114418 17 -144.8720197 80.1059269 14785 1811 14 -159.3764075 -23.5100054 0 0 0 -82.3109493 -7.0673699 95504 68115 17 -94.3931949 63.0474034 97 34 7 -87.4523391 -73.2690527 3043 3297 12 -101.4256455 -0.8267694 12 8 4 --112.7666152 -82.3670281 12239 61007 16 --82.0948447 -38.0810449 8 19 5 -113.2906728 -19.193243 104 70 7 -16.953131 78.402684 35 8 6 --81.7974685 -53.9596787 34 86 7 -69.8051889 58.1416894 181902 78760 18 --9.2435464 -53.4296594 3 5 3 -30.0415066 11.4884737 4 3 3 -125.2704157 -69.6324197 54 49 6 --41.2060435 63.8501787 789 548 11 -120.407662 -4.9889504 6835 4209 13 -92.0345558 -8.0809262 24761 17121 15 -127.1061722 83.1311204 6988 428 13 --178.9414629 64.0086678 770 69897 18 -49.0743035 -4.3000419 10425 8387 14 --45.109002 -55.1435498 1534 2803 12 -3.2795498 75.95918 32 10 6 -)"; - diff --git a/third_party/libosmium/test/t/geom/test_wkb.cpp b/third_party/libosmium/test/t/geom/test_wkb.cpp deleted file mode 100644 index 730ee75ad..000000000 --- a/third_party/libosmium/test/t/geom/test_wkb.cpp +++ /dev/null @@ -1,133 +0,0 @@ -#include "catch.hpp" - -#include -#include - -#include "../basic/helper.hpp" - -#if __BYTE_ORDER == __LITTLE_ENDIAN - -TEST_CASE("WKB_Geometry_byte_order_dependent") { - -SECTION("point") { - osmium::geom::WKBFactory<> factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - - std::string wkb {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(std::string{"01010000009A99999999990940CDCCCCCCCCCC1040"} == wkb); -} - -SECTION("point_ewkb") { - osmium::geom::WKBFactory<> factory(osmium::geom::wkb_type::ewkb, osmium::geom::out_type::hex); - - std::string wkb {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(std::string{"0101000020E61000009A99999999990940CDCCCCCCCCCC1040"} == wkb); -} - -SECTION("linestring") { - osmium::geom::WKBFactory<> factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.2, 4.2}}, - {3, {3.5, 4.7}}, - {4, {3.5, 4.7}}, - {2, {3.6, 4.9}} - }); - - { - std::string wkb {factory.create_linestring(wnl)}; - REQUIRE(std::string{"0102000000030000009A99999999990940CDCCCCCCCCCC10400000000000000C40CDCCCCCCCCCC1240CDCCCCCCCCCC0C409A99999999991340"} == wkb); - } - - { - std::string wkb {factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)}; - REQUIRE(std::string{"010200000003000000CDCCCCCCCCCC0C409A999999999913400000000000000C40CDCCCCCCCCCC12409A99999999990940CDCCCCCCCCCC1040"} == wkb); - } - - { - std::string wkb {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; - REQUIRE(std::string{"0102000000040000009A99999999990940CDCCCCCCCCCC10400000000000000C40CDCCCCCCCCCC12400000000000000C40CDCCCCCCCCCC1240CDCCCCCCCCCC0C409A99999999991340"} == wkb); - } - - { - std::string wkb {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; - REQUIRE(std::string{"010200000004000000CDCCCCCCCCCC0C409A999999999913400000000000000C40CDCCCCCCCCCC12400000000000000C40CDCCCCCCCCCC12409A99999999990940CDCCCCCCCCCC1040"} == wkb); - } -} - -SECTION("linestring_ewkb") { - osmium::geom::WKBFactory<> factory(osmium::geom::wkb_type::ewkb, osmium::geom::out_type::hex); - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.2, 4.2}}, - {3, {3.5, 4.7}}, - {4, {3.5, 4.7}}, - {2, {3.6, 4.9}} - }); - - std::string ewkb {factory.create_linestring(wnl)}; - REQUIRE(std::string{"0102000020E6100000030000009A99999999990940CDCCCCCCCCCC10400000000000000C40CDCCCCCCCCCC1240CDCCCCCCCCCC0C409A99999999991340"} == ewkb); -} - -SECTION("linestring_with_two_same_locations") { - osmium::geom::WKBFactory<> factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.5, 4.7}}, - {2, {3.5, 4.7}} - }); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error); - - { - std::string wkb {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; - REQUIRE(std::string{"0102000000020000000000000000000C40CDCCCCCCCCCC12400000000000000C40CDCCCCCCCCCC1240"} == wkb); - } - - { - std::string wkb {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; - REQUIRE(std::string{"0102000000020000000000000000000C40CDCCCCCCCCCC12400000000000000C40CDCCCCCCCCCC1240"} == wkb); - } -} - -SECTION("linestring_with_undefined_location") { - osmium::geom::WKBFactory<> factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.5, 4.7}}, - {2, osmium::Location()} - }); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::invalid_location); -} - -} - -#endif - -TEST_CASE("WKB_Geometry_byte_order_independent") { - -SECTION("empty_point") { - osmium::geom::WKBFactory<> factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - - REQUIRE_THROWS_AS(factory.create_point(osmium::Location()), osmium::invalid_location); -} - -SECTION("empty_linestring") { - osmium::geom::WKBFactory<> factory(osmium::geom::wkb_type::wkb, osmium::geom::out_type::hex); - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, {}); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward), osmium::geometry_error); -} - -} - diff --git a/third_party/libosmium/test/t/geom/test_wkt.cpp b/third_party/libosmium/test/t/geom/test_wkt.cpp deleted file mode 100644 index 538307409..000000000 --- a/third_party/libosmium/test/t/geom/test_wkt.cpp +++ /dev/null @@ -1,206 +0,0 @@ -#include "catch.hpp" - -#include -#include - -#include "../basic/helper.hpp" - -TEST_CASE("WKT_Geometry") { - -SECTION("point") { - osmium::geom::WKTFactory<> factory; - - std::string wkt {factory.create_point(osmium::Location(3.2, 4.2))}; - REQUIRE(std::string{"POINT(3.2 4.2)"} == wkt); -} - -SECTION("empty_point") { - osmium::geom::WKTFactory<> factory; - - REQUIRE_THROWS_AS(factory.create_point(osmium::Location()), osmium::invalid_location); -} - -SECTION("linestring") { - osmium::geom::WKTFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.2, 4.2}}, - {3, {3.5, 4.7}}, - {4, {3.5, 4.7}}, - {2, {3.6, 4.9}} - }); - - { - std::string wkt {factory.create_linestring(wnl)}; - REQUIRE(std::string{"LINESTRING(3.2 4.2,3.5 4.7,3.6 4.9)"} == wkt); - } - - { - std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward)}; - REQUIRE(std::string{"LINESTRING(3.6 4.9,3.5 4.7,3.2 4.2)"} == wkt); - } - - { - std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; - REQUIRE(std::string{"LINESTRING(3.2 4.2,3.5 4.7,3.5 4.7,3.6 4.9)"} == wkt); - } - - { - std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; - REQUIRE(std::string{"LINESTRING(3.6 4.9,3.5 4.7,3.5 4.7,3.2 4.2)"} == wkt); - } -} - -SECTION("empty_linestring") { - osmium::geom::WKTFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, {}); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all), osmium::geometry_error); - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward), osmium::geometry_error); -} - -SECTION("linestring_with_two_same_locations") { - osmium::geom::WKTFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.5, 4.7}}, - {2, {3.5, 4.7}} - }); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::geometry_error); - - try { - factory.create_linestring(wnl); - } catch (osmium::geometry_error& e) { - REQUIRE(e.id() == 0); - REQUIRE(std::string(e.what()) == "need at least two points for linestring"); - } - - REQUIRE_THROWS_AS(factory.create_linestring(wnl, osmium::geom::use_nodes::unique, osmium::geom::direction::backward), osmium::geometry_error); - - { - std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all)}; - REQUIRE(std::string{"LINESTRING(3.5 4.7,3.5 4.7)"} == wkt); - } - - { - std::string wkt {factory.create_linestring(wnl, osmium::geom::use_nodes::all, osmium::geom::direction::backward)}; - REQUIRE(std::string{"LINESTRING(3.5 4.7,3.5 4.7)"} == wkt); - } -} - -SECTION("linestring_with_undefined_location") { - osmium::geom::WKTFactory<> factory; - - osmium::memory::Buffer buffer(10000); - auto& wnl = osmium::builder::build_way_node_list(buffer, { - {1, {3.5, 4.7}}, - {2, osmium::Location()} - }); - - REQUIRE_THROWS_AS(factory.create_linestring(wnl), osmium::invalid_location); -} - -SECTION("area_1outer_0inner") { - osmium::geom::WKTFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {3.2, 4.2}}, - {2, {3.5, 4.7}}, - {3, {3.6, 4.9}}, - {1, {3.2, 4.2}} - }} - }); - - { - std::string wkt {factory.create_multipolygon(area)}; - REQUIRE(std::string{"MULTIPOLYGON(((3.2 4.2,3.5 4.7,3.6 4.9,3.2 4.2)))"} == wkt); - } -} - -SECTION("area_1outer_1inner") { - osmium::geom::WKTFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {8.0, 1.0}}, - {7, {8.0, 8.0}}, - {8, {1.0, 8.0}}, - {5, {1.0, 1.0}} - }} - }); - - { - std::string wkt {factory.create_multipolygon(area)}; - REQUIRE(std::string{"MULTIPOLYGON(((0.1 0.1,9.1 0.1,9.1 9.1,0.1 9.1,0.1 0.1),(1 1,8 1,8 8,1 8,1 1)))"} == wkt); - } -} - -SECTION("area_2outer_2inner") { - osmium::geom::WKTFactory<> factory; - - osmium::memory::Buffer buffer(10000); - osmium::Area& area = buffer_add_area(buffer, - "foo", - {}, - { - { true, { - {1, {0.1, 0.1}}, - {2, {9.1, 0.1}}, - {3, {9.1, 9.1}}, - {4, {0.1, 9.1}}, - {1, {0.1, 0.1}} - }}, - { false, { - {5, {1.0, 1.0}}, - {6, {4.0, 1.0}}, - {7, {4.0, 4.0}}, - {8, {1.0, 4.0}}, - {5, {1.0, 1.0}} - }}, - { false, { - {10, {5.0, 5.0}}, - {11, {5.0, 7.0}}, - {12, {7.0, 7.0}}, - {10, {5.0, 5.0}} - }}, - { true, { - {100, {10.0, 10.0}}, - {101, {11.0, 10.0}}, - {102, {11.0, 11.0}}, - {103, {10.0, 11.0}}, - {100, {10.0, 10.0}} - }} - }); - - { - std::string wkt {factory.create_multipolygon(area)}; - REQUIRE(std::string{"MULTIPOLYGON(((0.1 0.1,9.1 0.1,9.1 9.1,0.1 9.1,0.1 0.1),(1 1,4 1,4 4,1 4,1 1),(5 5,5 7,7 7,5 5)),((10 10,11 10,11 11,10 11,10 10)))"} == wkt); - } -} - -} - diff --git a/third_party/libosmium/test/t/index/test_id_to_location.cpp b/third_party/libosmium/test/t/index/test_id_to_location.cpp deleted file mode 100644 index 4aca238b6..000000000 --- a/third_party/libosmium/test/t/index/test_id_to_location.cpp +++ /dev/null @@ -1,170 +0,0 @@ -#include "catch.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -template -void test_func_all(TIndex& index) { - osmium::unsigned_object_id_type id1 = 12; - osmium::unsigned_object_id_type id2 = 3; - osmium::Location loc1(1.2, 4.5); - osmium::Location loc2(3.5, -7.2); - - REQUIRE_THROWS_AS(index.get(id1), osmium::not_found); - - index.set(id1, loc1); - index.set(id2, loc2); - - index.sort(); - - REQUIRE_THROWS_AS(index.get(5), osmium::not_found); - REQUIRE_THROWS_AS(index.get(100), osmium::not_found); -} - -template -void test_func_real(TIndex& index) { - osmium::unsigned_object_id_type id1 = 12; - osmium::unsigned_object_id_type id2 = 3; - osmium::Location loc1(1.2, 4.5); - osmium::Location loc2(3.5, -7.2); - - index.set(id1, loc1); - index.set(id2, loc2); - - index.sort(); - - REQUIRE(loc1 == index.get(id1)); - REQUIRE(loc2 == index.get(id2)); - - REQUIRE_THROWS_AS(index.get(5), osmium::not_found); - REQUIRE_THROWS_AS(index.get(100), osmium::not_found); - - index.clear(); - - REQUIRE_THROWS_AS(index.get(id1), osmium::not_found); -} - -TEST_CASE("IdToLocation") { - - SECTION("Dummy") { - typedef osmium::index::map::Dummy index_type; - - index_type index1; - - REQUIRE(0 == index1.size()); - REQUIRE(0 == index1.used_memory()); - - test_func_all(index1); - - REQUIRE(0 == index1.size()); - REQUIRE(0 == index1.used_memory()); - } - - SECTION("DenseMemArray") { - typedef osmium::index::map::DenseMemArray index_type; - - index_type index1; - index1.reserve(1000); - test_func_all(index1); - - index_type index2; - index2.reserve(1000); - test_func_real(index2); - } - -#ifdef __linux__ - SECTION("DenseMmapArray") { - typedef osmium::index::map::DenseMmapArray index_type; - - index_type index1; - test_func_all(index1); - - index_type index2; - test_func_real(index2); - } -#else -# pragma message("not running 'DenseMapMmap' test case on this machine") -#endif - - SECTION("DenseFileArray") { - typedef osmium::index::map::DenseFileArray index_type; - - index_type index1; - test_func_all(index1); - - index_type index2; - test_func_real(index2); - } - -#ifdef OSMIUM_WITH_SPARSEHASH - - SECTION("SparseMemTable") { - typedef osmium::index::map::SparseMemTable index_type; - - index_type index1; - test_func_all(index1); - - index_type index2; - test_func_real(index2); - } - -#endif - - SECTION("SparseMemMap") { - typedef osmium::index::map::SparseMemMap index_type; - - index_type index1; - test_func_all(index1); - - index_type index2; - test_func_real(index2); - } - - SECTION("SparseMemArray") { - typedef osmium::index::map::SparseMemArray index_type; - - index_type index1; - - REQUIRE(0 == index1.size()); - REQUIRE(0 == index1.used_memory()); - - test_func_all(index1); - - REQUIRE(2 == index1.size()); - - index_type index2; - test_func_real(index2); - } - - SECTION("Dynamic map choice") { - typedef osmium::index::map::Map map_type; - const auto& map_factory = osmium::index::MapFactory::instance(); - - std::vector map_type_names = map_factory.map_types(); - REQUIRE(map_type_names.size() >= 5); - - for (const auto& map_type_name : map_type_names) { - std::unique_ptr index1 = map_factory.create_map(map_type_name); - index1->reserve(1000); - test_func_all(*index1); - - std::unique_ptr index2 = map_factory.create_map(map_type_name); - index2->reserve(1000); - test_func_real(*index2); - } - } - -} - diff --git a/third_party/libosmium/test/t/io/data.osm b/third_party/libosmium/test/t/io/data.osm deleted file mode 100644 index fffb77ad3..000000000 --- a/third_party/libosmium/test/t/io/data.osm +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/third_party/libosmium/test/t/io/data.osm.bz2 b/third_party/libosmium/test/t/io/data.osm.bz2 deleted file mode 100644 index 0f38797ebc6219cc4cfab63da1e4c7532007742a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 200 zcmV;(05|_aT4*^jL0KkKS>1wN)Bpf1-+(|6P=obXfdB>&FX!JtFaWu%VWE>CWMT|V zni^n)A)^`@MrvuMni>VP0*vRGkeVGfwh$BQp}GJmDS45V7?gcj zb6MgrsJw1U05MRY9u9kih6h<3!Cy`6J6>7k-Vu%3CaNFN`*T~(ZwD=aUKPh&41%;` zy+l623Sk*($Yw}S`K$wA=AHIf@W!|0Tq)u}-pdqlRIJn#Tp+|IQx|eYI8cz?f?d>a C4O0~W diff --git a/third_party/libosmium/test/t/io/data.osm.gz b/third_party/libosmium/test/t/io/data.osm.gz deleted file mode 100644 index 07edb9095b9ce78d51666d221ad9faba309ff5d5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 187 zcmV;s07U;EiwFoAN*GiE17u-zVJ>fTZ2(11%?g7s48HpmC6}JmR>l~^>TOTpF1rPr zxq@xQ*0IN55ZS_a_(<~owEf4=;!SIEF&L>UB?W~sS{EiG@58OU$i6GunEdYxRCNY1 zQJ@ubTn%JO*y8Jz p9ilDKkpg0TVVEdU-Y@fRRjGz4=7ZMUx8}lK@deEa=a1e1003pbRv`cY diff --git a/third_party/libosmium/test/t/io/data_bzip2.txt b/third_party/libosmium/test/t/io/data_bzip2.txt deleted file mode 100644 index 755d6af45..000000000 --- a/third_party/libosmium/test/t/io/data_bzip2.txt +++ /dev/null @@ -1 +0,0 @@ -TESTDATA diff --git a/third_party/libosmium/test/t/io/data_bzip2.txt.bz2 b/third_party/libosmium/test/t/io/data_bzip2.txt.bz2 deleted file mode 100644 index f0ee7e7d65cf069345fad9f6e75d03c6e88e0941..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 45 ycmZ>Y%CIzaj8qGb6yfW&V_;x$V_*U{I3CFko@L#wK3mY7sC2Bn<$~dI>%N diff --git a/third_party/libosmium/test/t/io/deleted_nodes.osh b/third_party/libosmium/test/t/io/deleted_nodes.osh deleted file mode 100644 index 639e05149..000000000 --- a/third_party/libosmium/test/t/io/deleted_nodes.osh +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/third_party/libosmium/test/t/io/deleted_nodes.osh.pbf b/third_party/libosmium/test/t/io/deleted_nodes.osh.pbf deleted file mode 100644 index 8a94870d14ad3d7a17b0a79dc1441cf51afa3ba1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 189 zcmV;u07Cx&000dN2~Sf^NM&JUWpWr!5JDPCc$`z>^DoW~PR>ZpP1FrD&@)rwa!JiA zPW8)ANi9|q^~fwP$uG)GPR#MlOUp0HO)SaG&ue1j$uG{$EX~z7)HBjE1OU}a74rZ9 z01FBSPg6}qVRT^_PY_NTOL&~);^Jc9Vk<39Es8f3auBlPVq#*_lHp=vWE5gMu=MJE rE(R$kCI%%S)&gQ9CI&_)u7Cgk|L6a^boV!YFC=yl69WSPqA(XSe-ljE diff --git a/third_party/libosmium/test/t/io/test_bzip2.cpp b/third_party/libosmium/test/t/io/test_bzip2.cpp deleted file mode 100644 index 5cc30b427..000000000 --- a/third_party/libosmium/test/t/io/test_bzip2.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "catch.hpp" -#include "utils.hpp" - -#include -#include -#include - -#include - -TEST_CASE("Bzip2") { - - SECTION("read_compressed_file") { - std::string input_file = with_data_dir("t/io/data_bzip2.txt.bz2"); - - int fd = ::open(input_file.c_str(), O_RDONLY); - REQUIRE(fd > 0); - - size_t size = 0; - std::string all; - { - osmium::io::Bzip2Decompressor decomp(fd); - for (std::string data = decomp.read(); !data.empty(); data = decomp.read()) { - size += data.size(); - all += data; - } - } - - REQUIRE(9 == size); - REQUIRE("TESTDATA\n" == all); - } - -} - diff --git a/third_party/libosmium/test/t/io/test_file_formats.cpp b/third_party/libosmium/test/t/io/test_file_formats.cpp deleted file mode 100644 index f0ba0c66f..000000000 --- a/third_party/libosmium/test/t/io/test_file_formats.cpp +++ /dev/null @@ -1,275 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -TEST_CASE("FileFormats") { - - SECTION("default_file_format") { - osmium::io::File f; - REQUIRE(osmium::io::file_format::unknown == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - REQUIRE_THROWS_AS(f.check(), std::runtime_error); - } - - SECTION("stdin_stdout_empty") { - osmium::io::File f {""}; - REQUIRE(osmium::io::file_format::unknown == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - REQUIRE_THROWS_AS(f.check(), std::runtime_error); - } - - SECTION("stdin_stdout_dash") { - osmium::io::File f {"-"}; - REQUIRE(osmium::io::file_format::unknown == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - REQUIRE_THROWS_AS(f.check(), std::runtime_error); - } - - SECTION("stdin_stdout_bz2") { - osmium::io::File f {"-", "osm.bz2"}; - REQUIRE("" == f.filename()); - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::bzip2 == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_osm") { - osmium::io::File f {"test.osm"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_pbf") { - osmium::io::File f {"test.pbf"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_osm_pbf") { - osmium::io::File f {"test.osm.pbf"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_opl") { - osmium::io::File f {"test.opl"}; - REQUIRE(osmium::io::file_format::opl == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_osm_opl") { - osmium::io::File f {"test.osm.opl"}; - REQUIRE(osmium::io::file_format::opl == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_osm_gz") { - osmium::io::File f {"test.osm.gz"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::gzip == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_opl_bz2") { - osmium::io::File f {"test.osm.opl.bz2"}; - REQUIRE(osmium::io::file_format::opl == f.format()); - REQUIRE(osmium::io::file_compression::bzip2 == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_osc_gz") { - osmium::io::File f {"test.osc.gz"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::gzip == f.compression()); - REQUIRE(true == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_opl_gz") { - osmium::io::File f {"test.osh.opl.gz"}; - REQUIRE(osmium::io::file_format::opl == f.format()); - REQUIRE(osmium::io::file_compression::gzip == f.compression()); - REQUIRE(true == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("detect_file_format_by_suffix_osh_pbf") { - osmium::io::File f {"test.osh.pbf"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(true == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_osm") { - osmium::io::File f {"test", "osm"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_pbf") { - osmium::io::File f {"test", "pbf"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_osm_pbf") { - osmium::io::File f {"test", "osm.pbf"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_opl") { - osmium::io::File f {"test", "opl"}; - REQUIRE(osmium::io::file_format::opl == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_osm_opl") { - osmium::io::File f {"test", "osm.opl"}; - REQUIRE(osmium::io::file_format::opl == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_osm_gz") { - osmium::io::File f {"test", "osm.gz"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::gzip == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_osm_opl_bz2") { - osmium::io::File f {"test", "osm.opl.bz2"}; - REQUIRE(osmium::io::file_format::opl == f.format()); - REQUIRE(osmium::io::file_compression::bzip2 == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_osc_gz") { - osmium::io::File f {"test", "osc.gz"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::gzip == f.compression()); - REQUIRE(true == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_osh_opl_gz") { - osmium::io::File f {"test", "osh.opl.gz"}; - REQUIRE(osmium::io::file_format::opl == f.format()); - REQUIRE(osmium::io::file_compression::gzip == f.compression()); - REQUIRE(true == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("override_file_format_by_suffix_osh_pbf") { - osmium::io::File f {"test", "osh.pbf"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(true == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("format_options_pbf_history") { - osmium::io::File f {"test", "pbf,history=true"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(true == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("format_options_pbf_foo") { - osmium::io::File f {"test.osm", "pbf,foo=bar"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE("bar" == f.get("foo")); - f.check(); - } - - SECTION("format_options_xml_abc_something") { - osmium::io::File f {"test.bla", "xml,abc,some=thing"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE("true" == f.get("abc")); - REQUIRE("thing" == f.get("some")); - REQUIRE(2 == std::distance(f.begin(), f.end())); - f.check(); - } - - SECTION("unknown_format_foo_bar") { - osmium::io::File f {"test.foo.bar"}; - REQUIRE(osmium::io::file_format::unknown == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE_THROWS_AS(f.check(), std::runtime_error); - } - - SECTION("unknown_format_foo") { - osmium::io::File f {"test", "foo"}; - REQUIRE_THROWS_AS(f.check(), std::runtime_error); - } - - SECTION("unknown_format_osm_foo") { - osmium::io::File f {"test", "osm.foo"}; - REQUIRE_THROWS_AS(f.check(), std::runtime_error); - } - - SECTION("unknown_format_bla_equals_foo") { - osmium::io::File f {"test", "bla=foo"}; - REQUIRE_THROWS_AS(f.check(), std::runtime_error); - } - - SECTION("url without format") { - osmium::io::File f {"http://www.example.com/api"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("url without format and filename") { - osmium::io::File f {"http://planet.osm.org/pbf/planet-latest.osm.pbf"}; - REQUIRE(osmium::io::file_format::pbf == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(false == f.has_multiple_object_versions()); - f.check(); - } - - SECTION("url with format") { - osmium::io::File f {"http://www.example.com/api", "osh"}; - REQUIRE(osmium::io::file_format::xml == f.format()); - REQUIRE(osmium::io::file_compression::none == f.compression()); - REQUIRE(true == f.has_multiple_object_versions()); - f.check(); - } - -} - diff --git a/third_party/libosmium/test/t/io/test_output_iterator.cpp b/third_party/libosmium/test/t/io/test_output_iterator.cpp deleted file mode 100644 index 7a1f57027..000000000 --- a/third_party/libosmium/test/t/io/test_output_iterator.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "catch.hpp" - -#include -#include -#include - -TEST_CASE("output iterator") { - - SECTION("should be copy constructable") { - osmium::io::Header header; - osmium::io::Writer writer("test.osm", header, osmium::io::overwrite::allow); - osmium::io::OutputIterator out1(writer); - - osmium::io::OutputIterator out2(out1); - } - - SECTION("should be copy assignable") { - osmium::io::Header header; - osmium::io::Writer writer1("test1.osm", header, osmium::io::overwrite::allow); - osmium::io::Writer writer2("test2.osm", header, osmium::io::overwrite::allow); - - osmium::io::OutputIterator out1(writer1); - osmium::io::OutputIterator out2(writer2); - - out2 = out1; - } - - SECTION("should be incrementable") { - osmium::io::Header header; - osmium::io::Writer writer("test.osm", header, osmium::io::overwrite::allow); - osmium::io::OutputIterator out(writer); - - ++out; - } - -} - diff --git a/third_party/libosmium/test/t/io/test_output_utils.cpp b/third_party/libosmium/test/t/io/test_output_utils.cpp deleted file mode 100644 index a76068348..000000000 --- a/third_party/libosmium/test/t/io/test_output_utils.cpp +++ /dev/null @@ -1,153 +0,0 @@ - -#include "catch.hpp" - -#include - -#include - -TEST_CASE("output formatted") { - - std::string out; - - SECTION("small results") { - osmium::io::detail::append_printf_formatted_string(out, "%d", 17); - REQUIRE(out == "17"); - } - - SECTION("several parameters") { - osmium::io::detail::append_printf_formatted_string(out, "%d %s", 17, "foo"); - REQUIRE(out == "17 foo"); - - } - - SECTION("string already containing something") { - out += "foo"; - osmium::io::detail::append_printf_formatted_string(out, " %d", 23); - REQUIRE(out == "foo 23"); - } - - SECTION("large results") { - const char* str = - "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" - "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" - "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" - "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" - "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; - - osmium::io::detail::append_printf_formatted_string(out, "%s", str); - - REQUIRE(out == str); - } - -} - -TEST_CASE("UTF8 encoding") { - - std::string out; - - SECTION("append to string") { - out += "1234"; - osmium::io::detail::append_utf8_encoded_string(out, "abc"); - REQUIRE(out == "1234abc"); - } - - SECTION("don't encode alphabetic characters") { - const char* s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - osmium::io::detail::append_utf8_encoded_string(out, s); - REQUIRE(out == s); - } - - SECTION("don't encode numeric characters") { - const char* s = "0123456789"; - osmium::io::detail::append_utf8_encoded_string(out, s); - REQUIRE(out == s); - } - - SECTION("don't encode lots of often used characters characters") { - const char* s = ".-;:_#+"; - osmium::io::detail::append_utf8_encoded_string(out, s); - REQUIRE(out == s); - } - - SECTION("encode characters that are special in OPL") { - osmium::io::detail::append_utf8_encoded_string(out, " \n,=@"); - REQUIRE(out == "%20%%0a%%2c%%3d%%40%"); - } - -// workaround for missing support for u8 string literals on Windows -#if !defined(_MSC_VER) - - SECTION("encode multibyte character") { - osmium::io::detail::append_utf8_encoded_string(out, u8"\u30dc_\U0001d11e_\U0001f6eb"); - REQUIRE(out == "%30dc%_%1d11e%_%1f6eb%"); - } - -#endif - -} - -TEST_CASE("html encoding") { - - std::string out; - - SECTION("do not encode normal characters") { - const char* s = "abc123,.-"; - osmium::io::detail::append_xml_encoded_string(out, s); - REQUIRE(out == s); - } - - SECTION("encode special XML characters") { - const char* s = "& \" \' < > \n \r \t"; - osmium::io::detail::append_xml_encoded_string(out, s); - REQUIRE(out == "& " ' < > "); - } - -} - -TEST_CASE("debug encoding") { - - std::string out; - - SECTION("do not encode normal characters") { - const char* s = "abc123,.-"; - osmium::io::detail::append_debug_encoded_string(out, s, "[", "]"); - REQUIRE(out == s); - } - - SECTION("encode some unicode characters") { - const char* s = u8"\n_\u30dc_\U0001d11e_\U0001f6eb"; - osmium::io::detail::append_debug_encoded_string(out, s, "[", "]"); - REQUIRE(out == "[]_[]_[]_[]"); - } - -} - -TEST_CASE("encoding of non-printable characters in the first 127 characters") { - - std::locale cloc("C"); - char s[] = "a\0"; - - for (char c = 1; c < 0x7f; ++c) { - std::string out; - s[0] = c; - - SECTION("utf8 encode") { - osmium::io::detail::append_utf8_encoded_string(out, s); - - if (!std::isprint(c, cloc)) { - REQUIRE(out[0] == '%'); - } - } - - SECTION("debug encode") { - osmium::io::detail::append_debug_encoded_string(out, s, "", ""); - - if (!std::isprint(c, cloc)) { - REQUIRE(out[0] == '<'); - } - } - - } - -} - diff --git a/third_party/libosmium/test/t/io/test_reader.cpp b/third_party/libosmium/test/t/io/test_reader.cpp deleted file mode 100644 index a83af52ab..000000000 --- a/third_party/libosmium/test/t/io/test_reader.cpp +++ /dev/null @@ -1,212 +0,0 @@ -#include "catch.hpp" -#include "utils.hpp" - -#include -#include -#include -#include -#include -#include - -struct CountHandler : public osmium::handler::Handler { - - int count = 0; - - void node(osmium::Node&) { - ++count; - } - -}; // class CountHandler - -struct ZeroPositionNodeCountHandler : public osmium::handler::Handler { - - // number of nodes seen at zero position, or visible with undefined - // location. - int count = 0; - int total_count = 0; // total number of nodes seen - const osmium::Location zero = osmium::Location(int32_t(0), int32_t(0)); - - void node(osmium::Node &n) { - // no nodes in the history file have a zero location, and - // no visible nodes should have an undefined location. - if ((n.location() == zero) || - (n.visible() && !n.location())) { - ++count; - } - ++total_count; - } - -}; // class ZeroPositionNodeCountHandler - - -TEST_CASE("Reader") { - - SECTION("reader can be initialized with file") { - osmium::io::File file(with_data_dir("t/io/data.osm")); - osmium::io::Reader reader(file); - osmium::handler::Handler handler; - - osmium::apply(reader, handler); - } - - SECTION("reader can be initialized with string") { - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - osmium::handler::Handler handler; - - osmium::apply(reader, handler); - } - - SECTION("should throw after eof") { - osmium::io::File file(with_data_dir("t/io/data.osm")); - osmium::io::Reader reader(file); - - REQUIRE(!reader.eof()); - - while (osmium::memory::Buffer buffer = reader.read()) { - } - - REQUIRE(reader.eof()); - - REQUIRE_THROWS_AS({ - reader.read(); - }, osmium::io_error); - } - - SECTION("should not hang when apply() is called twice on reader") { - osmium::io::File file(with_data_dir("t/io/data.osm")); - osmium::io::Reader reader(file); - osmium::handler::Handler handler; - - osmium::apply(reader, handler); - REQUIRE_THROWS_AS({ - osmium::apply(reader, handler); - }, osmium::io_error); - } - - SECTION("should work with a buffer with uncompressed data") { - int fd = osmium::io::detail::open_for_reading(with_data_dir("t/io/data.osm")); - REQUIRE(fd >= 0); - - const size_t buffer_size = 1000; - char buffer[buffer_size]; - auto length = ::read(fd, buffer, buffer_size); - REQUIRE(length > 0); - - osmium::io::File file(buffer, static_cast(length), "osm"); - osmium::io::Reader reader(file); - CountHandler handler; - - REQUIRE(handler.count == 0); - osmium::apply(reader, handler); - REQUIRE(handler.count == 1); - } - - SECTION("should work with a buffer with gzip-compressed data") { - int fd = osmium::io::detail::open_for_reading(with_data_dir("t/io/data.osm.gz")); - REQUIRE(fd >= 0); - - const size_t buffer_size = 1000; - char buffer[buffer_size]; - auto length = ::read(fd, buffer, buffer_size); - REQUIRE(length > 0); - - osmium::io::File file(buffer, static_cast(length), "osm.gz"); - osmium::io::Reader reader(file); - CountHandler handler; - - REQUIRE(handler.count == 0); - osmium::apply(reader, handler); - REQUIRE(handler.count == 1); - } - - SECTION("should work with a buffer with bzip2-compressed data") { - int fd = osmium::io::detail::open_for_reading(with_data_dir("t/io/data.osm.bz2")); - REQUIRE(fd >= 0); - - const size_t buffer_size = 1000; - char buffer[buffer_size]; - auto length = ::read(fd, buffer, buffer_size); - REQUIRE(length > 0); - - osmium::io::File file(buffer, static_cast(length), "osm.bz2"); - osmium::io::Reader reader(file); - CountHandler handler; - - REQUIRE(handler.count == 0); - osmium::apply(reader, handler); - REQUIRE(handler.count == 1); - } - - SECTION("should decode zero node positions in history (XML)") { - osmium::io::Reader reader(with_data_dir("t/io/deleted_nodes.osh"), - osmium::osm_entity_bits::node); - ZeroPositionNodeCountHandler handler; - - REQUIRE(handler.count == 0); - REQUIRE(handler.total_count == 0); - - osmium::apply(reader, handler); - - REQUIRE(handler.count == 0); - REQUIRE(handler.total_count == 2); - } - - SECTION("should decode zero node positions in history (PBF)") { - osmium::io::Reader reader(with_data_dir("t/io/deleted_nodes.osh.pbf"), - osmium::osm_entity_bits::node); - ZeroPositionNodeCountHandler handler; - - REQUIRE(handler.count == 0); - REQUIRE(handler.total_count == 0); - - osmium::apply(reader, handler); - - REQUIRE(handler.count == 0); - REQUIRE(handler.total_count == 2); - } - -} - -TEST_CASE("Reader failure modes") { - - SECTION("should fail with nonexistent file") { - REQUIRE_THROWS({ - osmium::io::Reader reader(with_data_dir("t/io/nonexistent-file.osm")); - }); - } - - SECTION("should fail with nonexistent file (gz)") { - REQUIRE_THROWS({ - osmium::io::Reader reader(with_data_dir("t/io/nonexistent-file.osm.gz")); - }); - } - - SECTION("should fail with nonexistent file (pbf)") { - REQUIRE_THROWS({ - osmium::io::Reader reader(with_data_dir("t/io/nonexistent-file.osm.pbf")); - }); - } - - SECTION("should work when there is an exception in main thread before getting header") { - try { - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - REQUIRE(!reader.eof()); - throw std::runtime_error("foo"); - } catch (...) { - } - - } - - SECTION("should work when there is an exception in main thread while reading") { - try { - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - REQUIRE(!reader.eof()); - auto header = reader.header(); - throw std::runtime_error("foo"); - } catch (...) { - } - - } - -} - diff --git a/third_party/libosmium/test/t/io/test_reader_with_mock_decompression.cpp b/third_party/libosmium/test/t/io/test_reader_with_mock_decompression.cpp deleted file mode 100644 index 566295aff..000000000 --- a/third_party/libosmium/test/t/io/test_reader_with_mock_decompression.cpp +++ /dev/null @@ -1,145 +0,0 @@ - -#include "catch.hpp" -#include "utils.hpp" - -#include - -#include -#include - -// The MockDecompressor behaves like other Decompressor classes, but "invents" -// OSM data in XML format that can be read. Through a parameter to the -// constructor it can be instructed to throw an exception in specific parts -// of its code. This is then used to test the internals of the Reader. - -class MockDecompressor : public osmium::io::Decompressor { - - std::string m_fail_in; - int m_read_count = 0; - -public: - - MockDecompressor(const std::string& fail_in) : - Decompressor(), - m_fail_in(fail_in) { - if (m_fail_in == "constructor") { - throw std::runtime_error("error constructor"); - } - } - - ~MockDecompressor() noexcept final = default; - - void add_node(std::string& s, int i) { - s += "\n"; - } - - std::string read() final { - std::string buffer; - ++m_read_count; - - if (m_read_count == 1) { - if (m_fail_in == "first read") { - throw std::runtime_error("error first read"); - } else { - buffer += "\n\n"; - for (int i = 0; i < 1000; ++i) { - add_node(buffer, i); - } - } - } else if (m_read_count == 2) { - if (m_fail_in == "second read") { - throw std::runtime_error("error second read"); - } else { - for (int i = 1000; i < 2000; ++i) { - add_node(buffer, i); - } - } - } else if (m_read_count == 3) { - buffer += ""; - } - - return buffer; - } - - void close() final { - if (m_fail_in == "close") { - throw std::runtime_error("error close"); - } - } - -}; // class MockDecompressor - -TEST_CASE("Test Reader using MockDecompressor") { - - std::string fail_in; - - osmium::io::CompressionFactory::instance().register_compression(osmium::io::file_compression::gzip, - [](int, osmium::io::fsync) { return nullptr; }, - [&](int) { return new MockDecompressor(fail_in); }, - [](const char*, size_t) { return nullptr; } - ); - - SECTION("fail in constructor") { - fail_in = "constructor"; - - try { - osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); - REQUIRE(false); - } catch (std::runtime_error& e) { - REQUIRE(std::string{e.what()} == "error constructor"); - } - } - - SECTION("fail in first read") { - fail_in = "first read"; - - try { - osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); - reader.read(); - REQUIRE(false); - } catch (std::runtime_error& e) { - REQUIRE(std::string{e.what()} == "error first read"); - } - } - - SECTION("fail in second read") { - fail_in = "second read"; - - try { - osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); - reader.read(); - reader.read(); - REQUIRE(false); - } catch (std::runtime_error& e) { - REQUIRE(std::string{e.what()} == "error second read"); - } - } - - SECTION("fail in close") { - fail_in = "close"; - - try { - osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); - reader.read(); - reader.read(); - reader.read(); - reader.close(); - REQUIRE(false); - } catch (std::runtime_error& e) { - REQUIRE(std::string{e.what()} == "error close"); - } - } - - SECTION("not failing") { - fail_in = "not"; - - osmium::io::Reader reader(with_data_dir("t/io/data.osm.gz")); - reader.read(); - reader.close(); - REQUIRE(true); - } - -} - diff --git a/third_party/libosmium/test/t/io/test_reader_with_mock_parser.cpp b/third_party/libosmium/test/t/io/test_reader_with_mock_parser.cpp deleted file mode 100644 index 7c7dcddba..000000000 --- a/third_party/libosmium/test/t/io/test_reader_with_mock_parser.cpp +++ /dev/null @@ -1,123 +0,0 @@ - -#include "catch.hpp" -#include "utils.hpp" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class MockParser : public osmium::io::detail::Parser { - - std::string m_fail_in; - -public: - - MockParser(osmium::io::detail::future_string_queue_type& input_queue, - osmium::io::detail::future_buffer_queue_type& output_queue, - std::promise& header_promise, - osmium::osm_entity_bits::type read_types, - const std::string& fail_in) : - Parser(input_queue, output_queue, header_promise, read_types), - m_fail_in(fail_in) { - } - - osmium::memory::Buffer create_testdata() { - osmium::memory::Buffer buffer(1000); - - { - osmium::builder::NodeBuilder nb(buffer); - nb.add_user("foo"); - } - buffer.commit(); - - return buffer; - } - - void run() final { - osmium::thread::set_thread_name("_osmium_mock_in"); - - if (m_fail_in == "header") { - throw std::runtime_error("error in header"); - } - - set_header_value(osmium::io::Header{}); - - send_to_output_queue(create_testdata()); - - if (m_fail_in == "read") { - throw std::runtime_error("error in read"); - } - } - -}; // class MockParser - -TEST_CASE("Test Reader using MockParser") { - - std::string fail_in; - - osmium::io::detail::ParserFactory::instance().register_parser( - osmium::io::file_format::xml, - [&](osmium::io::detail::future_string_queue_type& input_queue, - osmium::io::detail::future_buffer_queue_type& output_queue, - std::promise& header_promise, - osmium::osm_entity_bits::type read_which_entities) { - return std::unique_ptr(new MockParser(input_queue, output_queue, header_promise, read_which_entities, fail_in)); - }); - - SECTION("no failure") { - fail_in = ""; - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - auto header = reader.header(); - REQUIRE(reader.read()); - REQUIRE(!reader.read()); - REQUIRE(reader.eof()); - reader.close(); - } - - SECTION("throw in header") { - fail_in = "header"; - try { - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - reader.header(); - } catch (std::runtime_error& e) { - REQUIRE(std::string{e.what()} == "error in header"); - } - } - - SECTION("throw in read") { - fail_in = "read"; - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - reader.header(); - try { - reader.read(); - } catch (std::runtime_error& e) { - REQUIRE(std::string{e.what()} == "error in read"); - } - reader.close(); - } - - SECTION("throw in user code") { - fail_in = ""; - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - reader.header(); - try { - throw std::runtime_error("error in user code"); - } catch (std::runtime_error& e) { - REQUIRE(std::string{e.what()} == "error in user code"); - } - REQUIRE(reader.read()); - REQUIRE(!reader.read()); - REQUIRE(reader.eof()); - reader.close(); - } - -} - diff --git a/third_party/libosmium/test/t/io/test_string_table.cpp b/third_party/libosmium/test/t/io/test_string_table.cpp deleted file mode 100644 index ab977e8bc..000000000 --- a/third_party/libosmium/test/t/io/test_string_table.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "catch.hpp" - -#include - -TEST_CASE("String store") { - osmium::io::detail::StringStore ss(100); - - SECTION("empty") { - REQUIRE(ss.begin() == ss.end()); - } - - SECTION("add zero-length string") { - const char* s1 = ss.add(""); - REQUIRE(std::string(s1) == ""); - - auto it = ss.begin(); - REQUIRE(s1 == *it); - REQUIRE(std::string(*it) == ""); - REQUIRE(++it == ss.end()); - } - - SECTION("add strings") { - const char* s1 = ss.add("foo"); - const char* s2 = ss.add("bar"); - REQUIRE(s1 != s2); - REQUIRE(std::string(s1) == "foo"); - REQUIRE(std::string(s2) == "bar"); - - auto it = ss.begin(); - REQUIRE(s1 == *it++); - REQUIRE(s2 == *it++); - REQUIRE(it == ss.end()); - } - - SECTION("add zero-length string and longer strings") { - ss.add(""); - ss.add("xxx"); - ss.add("yyyyy"); - - auto it = ss.begin(); - REQUIRE(std::string(*it++) == ""); - REQUIRE(std::string(*it++) == "xxx"); - REQUIRE(std::string(*it++) == "yyyyy"); - REQUIRE(it == ss.end()); - } - - SECTION("add many strings") { - for (const char* teststring : {"a", "abc", "abcd", "abcde"}) { - int i = 0; - for (; i < 100; ++i) { - ss.add(teststring); - } - - for (const char* s : ss) { - REQUIRE(std::string(s) == teststring); - --i; - } - - REQUIRE(i == 0); - ss.clear(); - } - } - -} - -TEST_CASE("String table") { - osmium::io::detail::StringTable st; - - SECTION("empty") { - REQUIRE(st.size() == 1); - REQUIRE(std::next(st.begin()) == st.end()); - } - - SECTION("add strings") { - REQUIRE(st.add("foo") == 1); - REQUIRE(st.add("bar") == 2); - REQUIRE(st.add("bar") == 2); - REQUIRE(st.add("baz") == 3); - REQUIRE(st.add("foo") == 1); - REQUIRE(st.size() == 4); - - auto it = st.begin(); - REQUIRE(std::string("") == *it++); - REQUIRE(std::string("foo") == *it++); - REQUIRE(std::string("bar") == *it++); - REQUIRE(std::string("baz") == *it++); - REQUIRE(it == st.end()); - - st.clear(); - REQUIRE(st.size() == 1); - } - -} - diff --git a/third_party/libosmium/test/t/io/test_writer.cpp b/third_party/libosmium/test/t/io/test_writer.cpp deleted file mode 100644 index 45593cf60..000000000 --- a/third_party/libosmium/test/t/io/test_writer.cpp +++ /dev/null @@ -1,117 +0,0 @@ -#include "catch.hpp" -#include "utils.hpp" - -#include - -#include -#include -#include -#include -#include - -TEST_CASE("Writer") { - - osmium::io::Header header; - header.set("generator", "test_writer.cpp"); - - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(buffer); - REQUIRE(buffer.committed() > 0); - auto num = std::distance(buffer.cbegin(), buffer.cend()); - REQUIRE(num > 0); - REQUIRE(buffer.cbegin()->id() == 1); - - std::string filename; - - SECTION("Empty writes") { - - SECTION("Empty buffer") { - filename = "test-writer-out-empty-buffer.osm"; - osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); - osmium::memory::Buffer empty_buffer(1024); - writer(std::move(empty_buffer)); - writer.close(); - } - - SECTION("Invalid buffer") { - filename = "test-writer-out-invalid-buffer.osm"; - osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); - osmium::memory::Buffer invalid_buffer; - writer(std::move(invalid_buffer)); - writer.close(); - } - - osmium::io::Reader reader_check(filename); - osmium::memory::Buffer buffer_check = reader_check.read(); - REQUIRE(!buffer_check); - } - - SECTION("Successfull writes") { - - SECTION("Writer buffer") { - filename = "test-writer-out-buffer.osm"; - osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); - writer(std::move(buffer)); - writer.close(); - - REQUIRE_THROWS_AS({ - writer(osmium::memory::Buffer{}); - }, osmium::io_error); - } - - SECTION("Writer item") { - filename = "test-writer-out-item.osm"; - osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); - for (const auto& item : buffer) { - writer(item); - } - writer.close(); - } - - SECTION("Writer output iterator") { - filename = "test-writer-out-iterator.osm"; - osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); - auto it = osmium::io::make_output_iterator(writer); - std::copy(buffer.cbegin(), buffer.cend(), it); - writer.close(); - } - - osmium::io::Reader reader_check(filename); - osmium::memory::Buffer buffer_check = reader_check.read(); - REQUIRE(buffer_check); - REQUIRE(buffer_check.committed() > 0); - REQUIRE(std::distance(buffer_check.cbegin(), buffer_check.cend()) == num); - REQUIRE(buffer_check.cbegin()->id() == 1); - - } - - SECTION("Interrupted write") { - - int error = 0; - try { - - SECTION("fail after open") { - filename = "test-writer-out-fail1.osm"; - osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); - throw 1; - } - - SECTION("fail after write") { - filename = "test-writer-out-fail2.osm"; - osmium::io::Writer writer(filename, header, osmium::io::overwrite::allow); - writer(std::move(buffer)); - throw 2; - } - - } catch (int e) { - error = e; - } - - REQUIRE(error > 0); - - } - -} - - diff --git a/third_party/libosmium/test/t/io/test_writer_with_mock_compression.cpp b/third_party/libosmium/test/t/io/test_writer_with_mock_compression.cpp deleted file mode 100644 index c2d3bbd49..000000000 --- a/third_party/libosmium/test/t/io/test_writer_with_mock_compression.cpp +++ /dev/null @@ -1,99 +0,0 @@ - -#include "catch.hpp" -#include "utils.hpp" - -#include -#include - -#include -#include -#include - -class MockCompressor : public osmium::io::Compressor { - - std::string m_fail_in; - -public: - - MockCompressor(const std::string& fail_in) : - Compressor(osmium::io::fsync::no), - m_fail_in(fail_in) { - if (m_fail_in == "constructor") { - throw std::logic_error("constructor"); - } - } - - ~MockCompressor() noexcept final = default; - - void write(const std::string&) final { - if (m_fail_in == "write") { - throw std::logic_error("write"); - } - } - - void close() final { - if (m_fail_in == "close") { - throw std::logic_error("close"); - } - } - -}; // class MockCompressor - -TEST_CASE("Write with mock compressor") { - - std::string fail_in; - - osmium::io::CompressionFactory::instance().register_compression(osmium::io::file_compression::gzip, - [&](int, osmium::io::fsync) { return new MockCompressor(fail_in); }, - [](int) { return nullptr; }, - [](const char*, size_t) { return nullptr; } - ); - - osmium::io::Header header; - header.set("generator", "test_writer_with_mock_compression.cpp"); - - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(buffer); - REQUIRE(buffer.committed() > 0); - auto num = std::distance(buffer.cbegin(), buffer.cend()); - REQUIRE(num > 0); - - SECTION("fail on construction") { - - fail_in = "constructor"; - - REQUIRE_THROWS_AS({ - osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm.gz", header, osmium::io::overwrite::allow); - writer(std::move(buffer)); - writer.close(); - }, std::logic_error); - - } - - SECTION("fail on write") { - - fail_in = "write"; - - REQUIRE_THROWS_AS({ - osmium::io::Writer writer("test-writer-mock-fail-on-write.osm.gz", header, osmium::io::overwrite::allow); - writer(std::move(buffer)); - writer.close(); - }, std::logic_error); - - } - - SECTION("fail on close") { - - fail_in = "close"; - - REQUIRE_THROWS_AS({ - osmium::io::Writer writer("test-writer-mock-fail-on-close.osm.gz", header, osmium::io::overwrite::allow); - writer(std::move(buffer)); - writer.close(); - }, std::logic_error); - - } - -} - diff --git a/third_party/libosmium/test/t/io/test_writer_with_mock_encoder.cpp b/third_party/libosmium/test/t/io/test_writer_with_mock_encoder.cpp deleted file mode 100644 index a43d59183..000000000 --- a/third_party/libosmium/test/t/io/test_writer_with_mock_encoder.cpp +++ /dev/null @@ -1,105 +0,0 @@ - -#include "catch.hpp" -#include "utils.hpp" - -#include -#include - -#include -#include -#include -#include -#include - -class MockOutputFormat : public osmium::io::detail::OutputFormat { - - std::string m_fail_in; - -public: - - MockOutputFormat(const osmium::io::File&, osmium::io::detail::future_string_queue_type& output_queue, const std::string& fail_in) : - OutputFormat(output_queue), - m_fail_in(fail_in) { - } - - void write_header(const osmium::io::Header&) final { - if (m_fail_in == "header") { - throw std::logic_error("header"); - } - send_to_output_queue(std::string{"header"}); - } - - void write_buffer(osmium::memory::Buffer&&) final { - if (m_fail_in == "write") { - throw std::logic_error("write"); - } - send_to_output_queue(std::string{"write"}); - } - - void write_end() final { - if (m_fail_in == "write_end") { - throw std::logic_error("write_end"); - } - send_to_output_queue(std::string{"end"}); - } - -}; // class MockOutputFormat - -TEST_CASE("Test Writer with MockOutputFormat") { - - std::string fail_in; - - osmium::io::detail::OutputFormatFactory::instance().register_output_format( - osmium::io::file_format::xml, - [&](const osmium::io::File& file, osmium::io::detail::future_string_queue_type& output_queue) { - return new MockOutputFormat(file, output_queue, fail_in); - }); - - osmium::io::Header header; - header.set("generator", "test_writer_with_mock_encoder.cpp"); - - osmium::io::Reader reader(with_data_dir("t/io/data.osm")); - osmium::memory::Buffer buffer = reader.read(); - REQUIRE(buffer); - REQUIRE(buffer.committed() > 0); - auto num = std::distance(buffer.cbegin(), buffer.cend()); - REQUIRE(num > 0); - - SECTION("error in header") { - - fail_in = "header"; - - REQUIRE_THROWS_AS({ - osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow); - writer(std::move(buffer)); - writer.close(); - }, std::logic_error); - - } - - SECTION("error in write") { - - fail_in = "write"; - - REQUIRE_THROWS_AS({ - osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow); - writer(std::move(buffer)); - writer.close(); - }, std::logic_error); - - } - - SECTION("error in write_end") { - - fail_in = "write_end"; - - REQUIRE_THROWS_AS({ - osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow); - writer(std::move(buffer)); - writer.close(); - }, std::logic_error); - - } - -} - diff --git a/third_party/libosmium/test/t/tags/test_filter.cpp b/third_party/libosmium/test/t/tags/test_filter.cpp deleted file mode 100644 index eefa5b076..000000000 --- a/third_party/libosmium/test/t/tags/test_filter.cpp +++ /dev/null @@ -1,216 +0,0 @@ -#include "catch.hpp" - -#include - -#include -#include -#include -#include -#include -#include - -template -void check_filter(const osmium::TagList& tag_list, const TFilter filter, const std::vector& reference) { - REQUIRE(tag_list.size() == reference.size()); - auto t_it = tag_list.begin(); - for (auto it = reference.begin(); it != reference.end(); ++t_it, ++it) { - REQUIRE(filter(*t_it) == *it); - } - - typename TFilter::iterator fi_begin(filter, tag_list.begin(), tag_list.end()); - typename TFilter::iterator fi_end(filter, tag_list.end(), tag_list.end()); - - REQUIRE(std::distance(fi_begin, fi_end) == std::count(reference.begin(), reference.end(), true)); -} - -TEST_CASE("Filter") { - - SECTION("KeyFilter_matches_some_tags") { - osmium::tags::KeyFilter filter(false); - filter.add(true, "highway").add(true, "railway"); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, // match - { "name", "Main Street" }, // no match - { "source", "GPS" } // no match - }); - - std::vector results = { true, false, false }; - - check_filter(tag_list, filter, results); - } - - SECTION("KeyFilter_iterator_filters_tags") { - osmium::tags::KeyFilter filter(false); - filter.add(true, "highway").add(true, "source"); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tl = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, // match - { "name", "Main Street" }, // no match - { "source", "GPS" } // no match - }); - - osmium::tags::KeyFilter::iterator it(filter, tl.begin(), tl.end()); - const osmium::tags::KeyFilter::iterator end(filter, tl.end(), tl.end()); - - REQUIRE(2 == std::distance(it, end)); - - REQUIRE(it != end); - REQUIRE(std::string("highway") == it->key()); - REQUIRE(std::string("primary") == it->value()); - ++it; - REQUIRE(std::string("source") == it->key()); - REQUIRE(std::string("GPS") == it->value()); - REQUIRE(++it == end); - } - - SECTION("KeyValueFilter_matches_some_tags") { - osmium::tags::KeyValueFilter filter(false); - - filter.add(true, "highway", "residential").add(true, "highway", "primary").add(true, "railway"); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "railway", "tram" }, - { "source", "GPS" } - }); - - std::vector results = {true, true, false}; - - check_filter(tag_list, filter, results); - } - - SECTION("KeyValueFilter_ordering_matters") { - osmium::tags::KeyValueFilter filter1(false); - filter1.add(true, "highway").add(false, "highway", "road"); - - osmium::tags::KeyValueFilter filter2(false); - filter2.add(false, "highway", "road").add(true, "highway"); - - osmium::memory::Buffer buffer(10240); - - const osmium::TagList& tag_list1 = osmium::builder::build_tag_list(buffer, { - { "highway", "road" }, - { "name", "Main Street" } - }); - - const osmium::TagList& tag_list2 = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "name", "Main Street" } - }); - - check_filter(tag_list1, filter1, {true, false}); - check_filter(tag_list1, filter2, {false, false}); - check_filter(tag_list2, filter2, {true, false}); - } - - SECTION("KeyValueFilter_matches_against_taglist_with_any") { - osmium::tags::KeyValueFilter filter(false); - - filter.add(true, "highway", "primary").add(true, "name"); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "railway", "tram" }, - { "source", "GPS" } - }); - - REQUIRE( osmium::tags::match_any_of(tag_list, filter)); - REQUIRE(!osmium::tags::match_all_of(tag_list, filter)); - REQUIRE(!osmium::tags::match_none_of(tag_list, filter)); - } - - SECTION("KeyValueFilter_matches_against_taglist_with_all") { - osmium::tags::KeyValueFilter filter(false); - - filter.add(true, "highway", "primary").add(true, "name"); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "name", "Main Street" } - }); - - REQUIRE( osmium::tags::match_any_of(tag_list, filter)); - REQUIRE( osmium::tags::match_all_of(tag_list, filter)); - REQUIRE(!osmium::tags::match_none_of(tag_list, filter)); - } - - SECTION("KeyValueFilter_matches_against_taglist_with_none") { - osmium::tags::KeyValueFilter filter(false); - - filter.add(true, "highway", "road").add(true, "source"); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "name", "Main Street" } - }); - - REQUIRE(!osmium::tags::match_any_of(tag_list, filter)); - REQUIRE(!osmium::tags::match_all_of(tag_list, filter)); - REQUIRE( osmium::tags::match_none_of(tag_list, filter)); - } - - SECTION("KeyValueFilter_matches_against_taglist_with_any_called_with_rvalue") { - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "railway", "tram" }, - { "source", "GPS" } - }); - - REQUIRE(osmium::tags::match_any_of(tag_list, - osmium::tags::KeyValueFilter().add(true, "highway", "primary").add(true, "name"))); - } - - SECTION("RegexFilter_matches_some_tags") { - osmium::tags::RegexFilter filter(false); - filter.add(true, "highway", std::regex(".*_link")); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list1 = osmium::builder::build_tag_list(buffer, { - { "highway", "primary_link" }, - { "source", "GPS" } - }); - const osmium::TagList& tag_list2 = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "source", "GPS" } - }); - - check_filter(tag_list1, filter, {true, false}); - check_filter(tag_list2, filter, {false, false}); - } - - SECTION("RegexFilter_matches_some_tags_with_lvalue_regex") { - osmium::tags::RegexFilter filter(false); - std::regex r(".*straße"); - filter.add(true, "name", r); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "name", "Hauptstraße" } - }); - - check_filter(tag_list, filter, {false, true}); - } - - SECTION("KeyPrefixFilter_matches_some_tags") { - osmium::tags::KeyPrefixFilter filter(false); - filter.add(true, "name:"); - - osmium::memory::Buffer buffer(10240); - const osmium::TagList& tag_list = osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "name:de", "Hauptstraße" } - }); - - check_filter(tag_list, filter, {false, true}); - } - -} diff --git a/third_party/libosmium/test/t/tags/test_operators.cpp b/third_party/libosmium/test/t/tags/test_operators.cpp deleted file mode 100644 index 33a53c2a2..000000000 --- a/third_party/libosmium/test/t/tags/test_operators.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "catch.hpp" - -#include - -#include -#include -#include - -TEST_CASE("Operators") { - - SECTION("Equal") { - osmium::memory::Buffer buffer1(10240); - { - osmium::builder::TagListBuilder tl_builder(buffer1); - tl_builder.add_tag("highway", "primary"); - tl_builder.add_tag("name", "Main Street"); - tl_builder.add_tag("source", "GPS"); - } - buffer1.commit(); - - osmium::memory::Buffer buffer2(10240); - { - osmium::builder::TagListBuilder tl_builder(buffer2); - tl_builder.add_tag("highway", "primary"); - } - buffer2.commit(); - - const osmium::TagList& tl1 = buffer1.get(0); - const osmium::TagList& tl2 = buffer2.get(0); - - auto tagit1 = tl1.begin(); - auto tagit2 = tl2.begin(); - REQUIRE(*tagit1 == *tagit2); - ++tagit1; - REQUIRE(!(*tagit1 == *tagit2)); - } - - SECTION("Order") { - osmium::memory::Buffer buffer(10240); - { - osmium::builder::TagListBuilder tl_builder(buffer); - tl_builder.add_tag("highway", "residential"); - tl_builder.add_tag("highway", "primary"); - tl_builder.add_tag("name", "Main Street"); - tl_builder.add_tag("amenity", "post_box"); - } - buffer.commit(); - - const osmium::TagList& tl = buffer.get(0); - const osmium::Tag& t1 = *(tl.begin()); - const osmium::Tag& t2 = *(std::next(tl.begin(), 1)); - const osmium::Tag& t3 = *(std::next(tl.begin(), 2)); - const osmium::Tag& t4 = *(std::next(tl.begin(), 3)); - - REQUIRE(t2 < t1); - REQUIRE(t1 < t3); - REQUIRE(t2 < t3); - REQUIRE(t4 < t1); - } - -} diff --git a/third_party/libosmium/test/t/tags/test_tag_list.cpp b/third_party/libosmium/test/t/tags/test_tag_list.cpp deleted file mode 100644 index 295f51af8..000000000 --- a/third_party/libosmium/test/t/tags/test_tag_list.cpp +++ /dev/null @@ -1,113 +0,0 @@ -#include "catch.hpp" - -#include -#include -#include - -TEST_CASE("create tag list") { - osmium::memory::Buffer buffer(10240); - - SECTION("with TagListBuilder from char*") { - { - osmium::builder::TagListBuilder builder(buffer); - builder.add_tag("highway", "primary"); - builder.add_tag("name", "Main Street"); - } - buffer.commit(); - } - - SECTION("with TagListBuilder from char* with length") { - { - osmium::builder::TagListBuilder builder(buffer); - builder.add_tag("highway", strlen("highway"), "primary", strlen("primary")); - builder.add_tag("nameXX", 4, "Main Street", 11); - } - buffer.commit(); - } - - SECTION("with TagListBuilder from std::string") { - { - osmium::builder::TagListBuilder builder(buffer); - builder.add_tag(std::string("highway"), std::string("primary")); - const std::string source = "name"; - std::string gps = "Main Street"; - builder.add_tag(source, gps); - } - buffer.commit(); - } - - SECTION("with build_tag_list from initializer list") { - osmium::builder::build_tag_list(buffer, { - { "highway", "primary" }, - { "name", "Main Street" } - }); - } - - SECTION("with build_tag_list_from_map") { - osmium::builder::build_tag_list_from_map(buffer, std::map({ - { "highway", "primary" }, - { "name", "Main Street" } - })); - } - - SECTION("with build_tag_list_from_func") { - osmium::builder::build_tag_list_from_func(buffer, [](osmium::builder::TagListBuilder& tlb) { - tlb.add_tag("highway", "primary"); - tlb.add_tag("name", "Main Street"); - }); - } - - const osmium::TagList& tl = *buffer.begin(); - REQUIRE(osmium::item_type::tag_list == tl.type()); - REQUIRE(2 == tl.size()); - - auto it = tl.begin(); - REQUIRE(std::string("highway") == it->key()); - REQUIRE(std::string("primary") == it->value()); - ++it; - REQUIRE(std::string("name") == it->key()); - REQUIRE(std::string("Main Street") == it->value()); - ++it; - REQUIRE(it == tl.end()); - - REQUIRE(std::string("primary") == tl.get_value_by_key("highway")); - REQUIRE(nullptr == tl.get_value_by_key("foo")); - REQUIRE(std::string("default") == tl.get_value_by_key("foo", "default")); - - REQUIRE(std::string("Main Street") == tl["name"]); -} - -TEST_CASE("empty keys and values are okay") { - osmium::memory::Buffer buffer(10240); - - const osmium::TagList& tl = osmium::builder::build_tag_list(buffer, { - { "empty value", "" }, - { "", "empty key" } - }); - - REQUIRE(osmium::item_type::tag_list == tl.type()); - REQUIRE(2 == tl.size()); - - auto it = tl.begin(); - REQUIRE(std::string("empty value") == it->key()); - REQUIRE(std::string("") == it->value()); - ++it; - REQUIRE(std::string("") == it->key()); - REQUIRE(std::string("empty key") == it->value()); - ++it; - REQUIRE(it == tl.end()); - - REQUIRE(std::string("") == tl.get_value_by_key("empty value")); - REQUIRE(std::string("empty key") == tl.get_value_by_key("")); -} - -TEST_CASE("tag key or value is too long") { - osmium::memory::Buffer buffer(10240); - osmium::builder::TagListBuilder builder(buffer); - - const char kv[2000] = ""; - builder.add_tag(kv, 1, kv, 1000); - REQUIRE_THROWS(builder.add_tag(kv, 1500, kv, 1)); - REQUIRE_THROWS(builder.add_tag(kv, 1, kv, 1500)); -} - diff --git a/third_party/libosmium/test/t/thread/test_pool.cpp b/third_party/libosmium/test/t/thread/test_pool.cpp deleted file mode 100644 index c1047db49..000000000 --- a/third_party/libosmium/test/t/thread/test_pool.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "catch.hpp" - -#include -#include -#include - -#include -#include - -struct test_job_with_result { - int operator()() const { - return 42; - } -}; - -struct test_job_throw { - OSMIUM_NORETURN void operator()() const { - throw std::runtime_error("exception in pool thread"); - } -}; - -TEST_CASE("number of threads in pool") { - - // hardcoded setting - REQUIRE(osmium::thread::detail::get_pool_size( 1, 0, 2) == 1); - REQUIRE(osmium::thread::detail::get_pool_size( 4, 0, 2) == 4); - REQUIRE(osmium::thread::detail::get_pool_size( 4, 0, 4) == 4); - REQUIRE(osmium::thread::detail::get_pool_size(16, 0, 4) == 16); - REQUIRE(osmium::thread::detail::get_pool_size(16, 0, 16) == 16); - REQUIRE(osmium::thread::detail::get_pool_size( 8, 4, 2) == 8); - REQUIRE(osmium::thread::detail::get_pool_size( 8, 16, 2) == 8); - REQUIRE(osmium::thread::detail::get_pool_size(-2, 16, 2) == 1); - REQUIRE(osmium::thread::detail::get_pool_size(-2, 16, 8) == 6); - - // user decides through OSMIUM_POOL_THREADS env variable - REQUIRE(osmium::thread::detail::get_pool_size( 0, 0, 2) == 1); - REQUIRE(osmium::thread::detail::get_pool_size( 0, -2, 4) == 2); - REQUIRE(osmium::thread::detail::get_pool_size( 0, -1, 8) == 7); - REQUIRE(osmium::thread::detail::get_pool_size( 0, 0, 16) == 14); - REQUIRE(osmium::thread::detail::get_pool_size( 0, 1, 16) == 1); - REQUIRE(osmium::thread::detail::get_pool_size( 0, 2, 16) == 2); - REQUIRE(osmium::thread::detail::get_pool_size( 0, 4, 16) == 4); - REQUIRE(osmium::thread::detail::get_pool_size( 0, 8, 16) == 8); - - // outliers - REQUIRE(osmium::thread::detail::get_pool_size(-100, 0, 16) == 1); - REQUIRE(osmium::thread::detail::get_pool_size(1000, 0, 16) == 256); - -} - -TEST_CASE("thread") { - - auto& pool = osmium::thread::Pool::instance(); - - SECTION("can get access to thread pool") { - REQUIRE(pool.queue_empty()); - } - - SECTION("can send job to thread pool") { - auto future = pool.submit(test_job_with_result {}); - - REQUIRE(future.get() == 42); - } - - SECTION("can throw from job in thread pool") { - auto future = pool.submit(test_job_throw {}); - - REQUIRE_THROWS_AS(future.get(), std::runtime_error); - } - -} - diff --git a/third_party/libosmium/test/t/util/test_cast_with_assert.cpp b/third_party/libosmium/test/t/util/test_cast_with_assert.cpp deleted file mode 100644 index 0231f30e1..000000000 --- a/third_party/libosmium/test/t/util/test_cast_with_assert.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include "catch.hpp" - -// Define assert() to throw this error. This enables the tests to check that -// the assert() fails. -struct assert_error : public std::runtime_error { - assert_error(const char* what_arg) : std::runtime_error(what_arg) { - } -}; -#define assert(x) if (!(x)) { throw(assert_error(#x)); } - -#include - -TEST_CASE("static_cast_with_assert") { - - SECTION("same types is always okay") { - int f = 10; - auto t = osmium::static_cast_with_assert(f); - REQUIRE(t == f); - } - - SECTION("casting to larger type is always okay") { - int16_t f = 10; - auto t = osmium::static_cast_with_assert(f); - REQUIRE(t == f); - } - - - SECTION("cast int32_t -> int_16t should not trigger assert for small int") { - int32_t f = 100; - auto t = osmium::static_cast_with_assert(f); - REQUIRE(t == f); - } - - SECTION("cast int32_t -> int_16t should trigger assert for large int") { - int32_t f = 100000; - REQUIRE_THROWS_AS(osmium::static_cast_with_assert(f), assert_error); - } - - - SECTION("cast int16_t -> uint16_t should not trigger assert for zero") { - int16_t f = 0; - auto t = osmium::static_cast_with_assert(f); - REQUIRE(t == f); - } - - SECTION("cast int16_t -> uint16_t should not trigger assert for positive int") { - int16_t f = 1; - auto t = osmium::static_cast_with_assert(f); - REQUIRE(t == f); - } - - SECTION("cast int16_t -> uint16_t should trigger assert for negative int") { - int16_t f = -1; - REQUIRE_THROWS_AS(osmium::static_cast_with_assert(f), assert_error); - } - - - SECTION("cast uint32_t -> uint_16t should not trigger assert for zero") { - uint32_t f = 0; - auto t = osmium::static_cast_with_assert(f); - REQUIRE(t == f); - } - - SECTION("cast uint32_t -> uint_16t should not trigger assert for small int") { - uint32_t f = 100; - auto t = osmium::static_cast_with_assert(f); - REQUIRE(t == f); - } - - SECTION("cast int32_t -> int_16t should trigger assert for large int") { - uint32_t f = 100000; - REQUIRE_THROWS_AS(osmium::static_cast_with_assert(f), assert_error); - } - - - SECTION("cast uint16_t -> int16_t should not trigger assert for small int") { - uint16_t f = 1; - auto t = osmium::static_cast_with_assert(f); - REQUIRE(t == f); - } - - SECTION("cast uint16_t -> int16_t should trigger assert for large int") { - uint16_t f = 65000; - REQUIRE_THROWS_AS(osmium::static_cast_with_assert(f), assert_error); - } - - -} - diff --git a/third_party/libosmium/test/t/util/test_delta.cpp b/third_party/libosmium/test/t/util/test_delta.cpp deleted file mode 100644 index 667c9b443..000000000 --- a/third_party/libosmium/test/t/util/test_delta.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -TEST_CASE("delta encode int") { - - osmium::util::DeltaEncode x; - - SECTION("int") { - REQUIRE(x.update(17) == 17); - REQUIRE(x.update(10) == -7); - REQUIRE(x.update(-10) == -20); - } - -} - -TEST_CASE("delta decode int") { - - osmium::util::DeltaDecode x; - - SECTION("int") { - REQUIRE(x.update(17) == 17); - REQUIRE(x.update(10) == 27); - REQUIRE(x.update(-40) == -13); - } - -} - -TEST_CASE("delta encode unsigned int") { - - osmium::util::DeltaEncode x; - - SECTION("int") { - REQUIRE(x.update(17) == 17); - REQUIRE(x.update(10) == -7); - REQUIRE(x.update(0) == -10); - } - -} - -TEST_CASE("delta decode unsigned int") { - - osmium::util::DeltaDecode x; - - SECTION("int") { - REQUIRE(x.update(17) == 17); - REQUIRE(x.update(10) == 27); - REQUIRE(x.update(-15) == 12); - } - -} - -TEST_CASE("delta encode and decode") { - - std::vector a = { 5, -9, 22, 13, 0, 23 }; - - osmium::util::DeltaEncode de; - std::vector b; - for (int x : a) { - b.push_back(de.update(x)); - } - - osmium::util::DeltaDecode dd; - std::vector c; - for (int x : b) { - c.push_back(dd.update(x)); - } - -} - -TEST_CASE("delta encode iterator") { - std::vector data = { 4, 5, 13, 22, 12 }; - - auto l = [](std::vector::const_iterator it) -> int { - return *it; - }; - - typedef osmium::util::DeltaEncodeIterator::const_iterator, decltype(l), int> it_type; - it_type it(data.begin(), data.end(), l); - it_type end(data.end(), data.end(), l); - - REQUIRE(*it == 4); - ++it; - REQUIRE(*it++ == 1); - REQUIRE(*it == 8); - ++it; - REQUIRE(*it++ == 9); - REQUIRE(*it == -10); - ++it; - REQUIRE(it == end); -} - diff --git a/third_party/libosmium/test/t/util/test_double.cpp b/third_party/libosmium/test/t/util/test_double.cpp deleted file mode 100644 index 6cc87a03a..000000000 --- a/third_party/libosmium/test/t/util/test_double.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include "catch.hpp" - -#include - -TEST_CASE("Double") { - - SECTION("double2string") { - std::string s1; - osmium::util::double2string(s1, 1.123, 7); - REQUIRE(s1 == "1.123"); - - std::string s2; - osmium::util::double2string(s2, 1.000, 7); - REQUIRE(s2 == "1"); - - std::string s3; - osmium::util::double2string(s3, 0.0, 7); - REQUIRE(s3 == "0"); - - std::string s4; - osmium::util::double2string(s4, 0.020, 7); - REQUIRE(s4 == "0.02"); - - std::string s5; - osmium::util::double2string(s5, -0.020, 7); - REQUIRE(s5 == "-0.02"); - - std::string s6; - osmium::util::double2string(s6, -0.0, 7); - REQUIRE(s6 == "-0"); - } -} - diff --git a/third_party/libosmium/test/t/util/test_file.cpp b/third_party/libosmium/test/t/util/test_file.cpp deleted file mode 100644 index 475f28596..000000000 --- a/third_party/libosmium/test/t/util/test_file.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "catch.hpp" - -#include - -#ifdef _WIN32 -#include -// https://msdn.microsoft.com/en-us/library/ksazx244.aspx -// https://msdn.microsoft.com/en-us/library/a9yf33zb.aspx -class DoNothingInvalidParameterHandler { - - static void invalid_parameter_handler( - const wchar_t* expression, - const wchar_t* function, - const wchar_t* file, - unsigned int line, - uintptr_t pReserved - ) { - // do nothing - } - - _invalid_parameter_handler old_handler; - -public: - - DoNothingInvalidParameterHandler() : - old_handler(_set_invalid_parameter_handler(invalid_parameter_handler)) { - _CrtSetReportMode(_CRT_ASSERT, 0); - } - - ~DoNothingInvalidParameterHandler() { - _set_invalid_parameter_handler(old_handler); - } - -}; // class InvalidParameterHandler -#endif - - -TEST_CASE("file_size") { - -#ifdef _WIN32 - DoNothingInvalidParameterHandler handler; -#endif - - SECTION("illegal fd should throw") { - REQUIRE_THROWS_AS(osmium::util::file_size(-1), std::system_error); - } - - SECTION("unused fd should throw") { - // its unlikely that fd 1000 is open... - REQUIRE_THROWS_AS(osmium::util::file_size(1000), std::system_error); - } - -} - -TEST_CASE("resize_file") { - -#ifdef _WIN32 - DoNothingInvalidParameterHandler handler; -#endif - - SECTION("illegal fd should throw") { - REQUIRE_THROWS_AS(osmium::util::resize_file(-1, 10), std::system_error); - } - - SECTION("unused fd should throw") { - // its unlikely that fd 1000 is open... - REQUIRE_THROWS_AS(osmium::util::resize_file(1000, 10), std::system_error); - } - -} - diff --git a/third_party/libosmium/test/t/util/test_memory_mapping.cpp b/third_party/libosmium/test/t/util/test_memory_mapping.cpp deleted file mode 100644 index 29893f7c7..000000000 --- a/third_party/libosmium/test/t/util/test_memory_mapping.cpp +++ /dev/null @@ -1,419 +0,0 @@ -#include "catch.hpp" - -#include -#include - -#include -#include - -#if defined(_MSC_VER) || (defined(__GNUC__) && defined(_WIN32)) -#include "win_mkstemp.hpp" -#endif - -static const size_t huge = std::numeric_limits::max(); - -TEST_CASE("anonymous mapping") { - - SECTION("simple memory mapping should work") { - osmium::util::MemoryMapping mapping(1000, osmium::util::MemoryMapping::mapping_mode::write_private); - REQUIRE(mapping.get_addr() != nullptr); - - REQUIRE(mapping.size() >= 1000); - - volatile int* addr = mapping.get_addr(); - - REQUIRE(mapping.writable()); - - *addr = 42; - REQUIRE(*addr == 42); - - REQUIRE(!!mapping); - mapping.unmap(); - REQUIRE(!mapping); - mapping.unmap(); // second unmap is okay - } - - SECTION("memory mapping of zero length should work") { - osmium::util::MemoryMapping mapping(0, osmium::util::MemoryMapping::mapping_mode::write_private); - REQUIRE(mapping.get_addr() != nullptr); - - REQUIRE(mapping.size() == osmium::util::get_pagesize()); - - REQUIRE(!!mapping); - mapping.unmap(); - REQUIRE(!mapping); - } - - SECTION("moving a memory mapping should work") { - osmium::util::MemoryMapping mapping1(1000, osmium::util::MemoryMapping::mapping_mode::write_private); - int* addr1 = mapping1.get_addr(); - *addr1 = 42; - - REQUIRE(!!mapping1); - osmium::util::MemoryMapping mapping2(std::move(mapping1)); - REQUIRE(!!mapping2); - REQUIRE(!mapping1); - mapping1.unmap(); - - int* addr2 = mapping2.get_addr(); - REQUIRE(*addr2 == 42); - - mapping2.unmap(); - REQUIRE(!mapping2); - } - - SECTION("move assignment should work") { - osmium::util::MemoryMapping mapping1(1000, osmium::util::MemoryMapping::mapping_mode::write_private); - osmium::util::MemoryMapping mapping2(1000, osmium::util::MemoryMapping::mapping_mode::write_private); - - REQUIRE(!!mapping1); - REQUIRE(!!mapping2); - - int* addr1 = mapping1.get_addr(); - *addr1 = 42; - - mapping2 = std::move(mapping1); - REQUIRE(!!mapping2); - REQUIRE(!mapping1); - - int* addr2 = mapping2.get_addr(); - REQUIRE(*addr2 == 42); - - mapping2.unmap(); - REQUIRE(!mapping2); - } - -#ifdef __linux__ - SECTION("remapping to larger size should work") { - osmium::util::MemoryMapping mapping(1000, osmium::util::MemoryMapping::mapping_mode::write_private); - REQUIRE(mapping.size() >= 1000); - - size_t size1 = mapping.size(); - - int* addr1 = mapping.get_addr(); - *addr1 = 42; - - mapping.resize(8000); - REQUIRE(mapping.size() > size1); - - int* addr2 = mapping.get_addr(); - REQUIRE(*addr2 == 42); - } - - SECTION("remapping to smaller size should work") { - osmium::util::MemoryMapping mapping(8000, osmium::util::MemoryMapping::mapping_mode::write_private); - REQUIRE(mapping.size() >= 1000); - - size_t size1 = mapping.size(); - - int* addr1 = mapping.get_addr(); - *addr1 = 42; - - mapping.resize(500); - REQUIRE(mapping.size() < size1); - - int* addr2 = mapping.get_addr(); - REQUIRE(*addr2 == 42); - } -#endif - -} - -TEST_CASE("file-based mapping") { - - SECTION("writing to a mapped file should work") { - char filename[] = "test_mmap_write_XXXXXX"; - const int fd = mkstemp(filename); - REQUIRE(fd > 0); - - osmium::util::resize_file(fd, 100); - - { - osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd); - REQUIRE(mapping.writable()); - - REQUIRE(!!mapping); - REQUIRE(mapping.size() >= 100); - - *mapping.get_addr() = 1234; - - mapping.unmap(); - } - - REQUIRE(osmium::util::file_size(fd) == 100); - - { - osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::readonly, fd); - REQUIRE(!mapping.writable()); - - REQUIRE(!!mapping); - REQUIRE(mapping.size() >= 100); - REQUIRE(*mapping.get_addr() == 1234); - - mapping.unmap(); - } - - REQUIRE(0 == close(fd)); - REQUIRE(0 == unlink(filename)); - } - - SECTION("writing to a privately mapped file should work") { - char filename[] = "test_mmap_write_XXXXXX"; - const int fd = mkstemp(filename); - REQUIRE(fd > 0); - - osmium::util::resize_file(fd, 100); - - { - osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::write_private, fd); - REQUIRE(mapping.writable()); - - REQUIRE(!!mapping); - REQUIRE(mapping.size() >= 100); - - *mapping.get_addr() = 1234; - - mapping.unmap(); - } - - REQUIRE(osmium::util::file_size(fd) == 100); - - { - osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::readonly, fd); - REQUIRE(!mapping.writable()); - - REQUIRE(!!mapping); - REQUIRE(mapping.size() >= 100); - REQUIRE(*mapping.get_addr() == 0); // should not see the value set above - - mapping.unmap(); - } - - REQUIRE(0 == close(fd)); - REQUIRE(0 == unlink(filename)); - } - - SECTION("remapping to larger size should work") { - char filename[] = "test_mmap_grow_XXXXXX"; - const int fd = mkstemp(filename); - REQUIRE(fd > 0); - - osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd); - REQUIRE(mapping.size() >= 100); - size_t size1 = mapping.size(); - - int* addr1 = mapping.get_addr(); - *addr1 = 42; - - mapping.resize(8000); - REQUIRE(mapping.size() >= 8000); - REQUIRE(mapping.size() > size1); - - int* addr2 = mapping.get_addr(); - REQUIRE(*addr2 == 42); - - mapping.unmap(); - - REQUIRE(0 == close(fd)); - REQUIRE(0 == unlink(filename)); - } - - SECTION("remapping to smaller size should work") { - char filename[] = "test_mmap_shrink_XXXXXX"; - const int fd = mkstemp(filename); - REQUIRE(fd > 0); - - { - osmium::util::MemoryMapping mapping(8000, osmium::util::MemoryMapping::mapping_mode::write_shared, fd); - REQUIRE(mapping.size() >= 8000); - size_t size1 = mapping.size(); - - int* addr1 = mapping.get_addr(); - *addr1 = 42; - - mapping.resize(50); - REQUIRE(mapping.size() >= 50); - REQUIRE(mapping.size() < size1); - - int* addr2 = mapping.get_addr(); - REQUIRE(*addr2 == 42); - } - - REQUIRE(0 == close(fd)); - REQUIRE(0 == unlink(filename)); - } -} - -TEST_CASE("typed anonymous mapping") { - - SECTION("simple memory mapping should work") { - osmium::util::TypedMemoryMapping mapping(1000); - volatile uint32_t* addr = mapping.begin(); - - REQUIRE(mapping.writable()); - - *addr = 42; - REQUIRE(*addr == 42); - - REQUIRE(!!mapping); - mapping.unmap(); - REQUIRE(!mapping); - mapping.unmap(); // second unmap is okay - } - - SECTION("moving a memory mapping should work") { - osmium::util::TypedMemoryMapping mapping1(1000); - uint32_t* addr1 = mapping1.begin(); - *addr1 = 42; - - REQUIRE(!!mapping1); - osmium::util::TypedMemoryMapping mapping2(std::move(mapping1)); - REQUIRE(!!mapping2); - REQUIRE(!mapping1); - mapping1.unmap(); - - auto addr2 = mapping2.begin(); - REQUIRE(*addr2 == 42); - - mapping2.unmap(); - REQUIRE(!mapping2); - } - - SECTION("move assignment should work") { - osmium::util::TypedMemoryMapping mapping1(1000); - osmium::util::TypedMemoryMapping mapping2(1000); - - REQUIRE(!!mapping1); - REQUIRE(!!mapping2); - - auto addr1 = mapping1.begin(); - *addr1 = 42; - - mapping2 = std::move(mapping1); - REQUIRE(!!mapping2); - REQUIRE(!mapping1); - - auto addr2 = mapping2.begin(); - REQUIRE(*addr2 == 42); - - mapping2.unmap(); - REQUIRE(!mapping2); - } - -#ifdef __linux__ - SECTION("remapping to larger size should work") { - osmium::util::TypedMemoryMapping mapping(1000); - REQUIRE(mapping.size() >= 1000); - - auto addr1 = mapping.begin(); - *addr1 = 42; - - mapping.resize(8000); - - auto addr2 = mapping.begin(); - REQUIRE(*addr2 == 42); - } - - SECTION("remapping to smaller size should work") { - osmium::util::TypedMemoryMapping mapping(8000); - REQUIRE(mapping.size() >= 8000); - - auto addr1 = mapping.begin(); - *addr1 = 42; - - mapping.resize(500); - - auto addr2 = mapping.begin(); - REQUIRE(*addr2 == 42); - } -#endif - -} - -TEST_CASE("typed file-based mapping") { - - SECTION("writing to a mapped file should work") { - char filename[] = "test_mmap_file_size_XXXXXX"; - const int fd = mkstemp(filename); - REQUIRE(fd > 0); - - osmium::util::resize_file(fd, 100); - - { - osmium::util::TypedMemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd); - REQUIRE(mapping.writable()); - - REQUIRE(!!mapping); - REQUIRE(mapping.size() >= 100); - - *mapping.begin() = 1234; - - mapping.unmap(); - } - - { - osmium::util::TypedMemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::readonly, fd); - REQUIRE(!mapping.writable()); - - REQUIRE(!!mapping); - REQUIRE(mapping.size() >= 100); - REQUIRE(*mapping.begin() == 1234); - - mapping.unmap(); - } - - REQUIRE(0 == close(fd)); - REQUIRE(0 == unlink(filename)); - } - -} - -TEST_CASE("anonymous memory mapping class") { - - SECTION("simple memory mapping should work") { - osmium::util::AnonymousMemoryMapping mapping(1000); - REQUIRE(mapping.get_addr() != nullptr); - - volatile int* addr = mapping.get_addr(); - - REQUIRE(mapping.writable()); - - *addr = 42; - REQUIRE(*addr == 42); - - REQUIRE(!!mapping); - mapping.unmap(); - REQUIRE(!mapping); - mapping.unmap(); // second unmap is okay - } - -#ifdef __linux__ - SECTION("remapping to larger size should work") { - osmium::util::AnonymousMemoryMapping mapping(1000); - REQUIRE(mapping.size() >= 1000); - - int* addr1 = mapping.get_addr(); - *addr1 = 42; - - mapping.resize(2000); - - int* addr2 = mapping.get_addr(); - REQUIRE(*addr2 == 42); - } - - SECTION("remapping to smaller size should work") { - osmium::util::AnonymousMemoryMapping mapping(2000); - REQUIRE(mapping.size() >= 2000); - - int* addr1 = mapping.get_addr(); - *addr1 = 42; - - mapping.resize(500); - - int* addr2 = mapping.get_addr(); - REQUIRE(*addr2 == 42); - } -#endif - -} - diff --git a/third_party/libosmium/test/t/util/test_minmax.cpp b/third_party/libosmium/test/t/util/test_minmax.cpp deleted file mode 100644 index 8b40f856e..000000000 --- a/third_party/libosmium/test/t/util/test_minmax.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include "catch.hpp" - -#include -#include - -TEST_CASE("minmax numeric") { - - SECTION("min") { - osmium::min_op x; - REQUIRE(x() == std::numeric_limits::max()); - - x.update(17); - REQUIRE(x() == 17); - - x.update(10); - REQUIRE(x() == 10); - - x.update(22); - REQUIRE(x() == 10); - } - - SECTION("max") { - osmium::max_op x; - REQUIRE(x() == 0); - - x.update(17); - REQUIRE(x() == 17); - - x.update(10); - REQUIRE(x() == 17); - - x.update(22); - REQUIRE(x() == 22); - } - -} - -TEST_CASE("minmax timestamp") { - - SECTION("min") { - osmium::min_op x; - - x.update(osmium::Timestamp("2010-01-01T00:00:00Z")); - REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z"); - - x.update(osmium::Timestamp("2015-01-01T00:00:00Z")); - REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z"); - - x.update(osmium::Timestamp("2000-01-01T00:00:00Z")); - REQUIRE(x().to_iso() == "2000-01-01T00:00:00Z"); - } - - SECTION("max") { - osmium::max_op x; - - x.update(osmium::Timestamp("2010-01-01T00:00:00Z")); - REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z"); - - x.update(osmium::Timestamp("2015-01-01T00:00:00Z")); - REQUIRE(x().to_iso() == "2015-01-01T00:00:00Z"); - - x.update(osmium::Timestamp("2000-01-01T00:00:00Z")); - REQUIRE(x().to_iso() == "2015-01-01T00:00:00Z"); - - } - -} - diff --git a/third_party/libosmium/test/t/util/test_options.cpp b/third_party/libosmium/test/t/util/test_options.cpp deleted file mode 100644 index 8cba0950b..000000000 --- a/third_party/libosmium/test/t/util/test_options.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include "catch.hpp" - -#include - -#include - -TEST_CASE("Options") { - - osmium::util::Options o; - - SECTION("set a single value from string") { - o.set("foo", "bar"); - REQUIRE("bar" == o.get("foo")); - REQUIRE("" == o.get("empty")); - REQUIRE("default" == o.get("empty", "default")); - - REQUIRE(!o.is_true("foo")); - REQUIRE(!o.is_true("empty")); - - REQUIRE(o.is_not_false("foo")); - REQUIRE(o.is_not_false("empty")); - - REQUIRE(1 == o.size()); - } - - SECTION("set values from booleans") { - o.set("t", true); - o.set("f", false); - REQUIRE("true" == o.get("t")); - REQUIRE("false" == o.get("f")); - REQUIRE("" == o.get("empty")); - - REQUIRE(o.is_true("t")); - REQUIRE(!o.is_true("f")); - - REQUIRE(o.is_not_false("t")); - REQUIRE(!o.is_not_false("f")); - - REQUIRE(2 == o.size()); - } - - SECTION("set value from string with equal sign") { - o.set("foo=bar"); - REQUIRE("bar" == o.get("foo")); - REQUIRE(1 == o.size()); - } - - SECTION("set value from string without equal sign") { - o.set("foo"); - REQUIRE("true" == o.get("foo")); - - REQUIRE(o.is_true("foo")); - REQUIRE(o.is_not_false("foo")); - - REQUIRE(1 == o.size()); - } - -} - -TEST_CASE("Options with initializer list") { - - osmium::util::Options o{ { "foo", "true" }, { "bar", "17" } }; - - REQUIRE(o.get("foo") == "true"); - REQUIRE(o.get("bar") == "17"); - REQUIRE(o.is_true("foo")); - REQUIRE_FALSE(o.is_true("bar")); - REQUIRE(o.size() == 2); - - SECTION("Change existing value") { - o.set("foo", "false"); - REQUIRE_FALSE(o.is_true("foo")); - } - - SECTION("Add new value") { - o.set("new", "something"); - REQUIRE_FALSE(o.is_true("new")); - REQUIRE(o.get("new") == "something"); - } -} - diff --git a/third_party/libosmium/test/t/util/test_string.cpp b/third_party/libosmium/test/t/util/test_string.cpp deleted file mode 100644 index 0960afe9a..000000000 --- a/third_party/libosmium/test/t/util/test_string.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include "catch.hpp" - -#include - -TEST_CASE("split_string") { - - SECTION("split_string string") { - std::string str { "foo,baramba,baz" }; - std::vector result = {"foo", "baramba", "baz"}; - - REQUIRE(result == osmium::split_string(str, ',')); - REQUIRE(result == osmium::split_string(str, ',', true)); - } - - SECTION("split_string string without sep") { - std::string str { "foo" }; - std::vector result = {"foo"}; - - REQUIRE(result == osmium::split_string(str, ',')); - REQUIRE(result == osmium::split_string(str, ',', true)); - } - - SECTION("split_string string with empty at end") { - std::string str { "foo,bar," }; - std::vector result = {"foo", "bar", ""}; - std::vector resultc = {"foo", "bar"}; - - REQUIRE(result == osmium::split_string(str, ',')); - REQUIRE(resultc == osmium::split_string(str, ',', true)); - } - - SECTION("split_string string with empty in middle") { - std::string str { "foo,,bar" }; - std::vector result = {"foo", "", "bar"}; - std::vector resultc = {"foo", "bar"}; - - REQUIRE(result == osmium::split_string(str, ',')); - REQUIRE(resultc == osmium::split_string(str, ',', true)); - } - - SECTION("split_string string with empty at start") { - std::string str { ",bar,baz" }; - std::vector result = {"", "bar", "baz"}; - std::vector resultc = {"bar", "baz"}; - - REQUIRE(result == osmium::split_string(str, ',')); - REQUIRE(resultc == osmium::split_string(str, ',', true)); - } - - SECTION("split_string sep") { - std::string str { "," }; - std::vector result = {"", ""}; - std::vector resultc; - - REQUIRE(result == osmium::split_string(str, ',')); - REQUIRE(resultc == osmium::split_string(str, ',', true)); - } - - SECTION("split_string empty string") { - std::string str { "" }; - std::vector result; - - REQUIRE(result == osmium::split_string(str, ',')); - REQUIRE(result == osmium::split_string(str, ',', true)); - } - -} - diff --git a/third_party/libosmium/test/test_main.cpp b/third_party/libosmium/test/test_main.cpp deleted file mode 100644 index 0c7c351f4..000000000 --- a/third_party/libosmium/test/test_main.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#define CATCH_CONFIG_MAIN -#include "catch.hpp" diff --git a/third_party/libosmium/test/valgrind.supp b/third_party/libosmium/test/valgrind.supp deleted file mode 100644 index f6ef1f65a..000000000 --- a/third_party/libosmium/test/valgrind.supp +++ /dev/null @@ -1,47 +0,0 @@ -#----------------------------------------------------------------------------- -# -# This file describes messages that Valgrind should suppress, because they -# are about problems outside Libosmium that we can't fix anyway. -# -# See http://valgrind.org/docs/manual/manual-core.html#manual-core.suppress -# -#----------------------------------------------------------------------------- - -{ - dl_error1 - Memcheck:Cond - fun:index - fun:expand_dynamic_string_token - fun:fillin_rpath - fun:_dl_init_paths - fun:dl_main - fun:_dl_sysdep_start - fun:_dl_start -} -{ - dl_error2 - Memcheck:Cond - fun:index - fun:expand_dynamic_string_token - fun:_dl_map_object - fun:map_doit - fun:_dl_catch_error - fun:do_preload - fun:dl_main - fun:_dl_sysdep_start - fun:_dl_start -} -{ - libpoppler_leak - Memcheck:Leak - fun:malloc - fun:gmalloc - fun:copyString -} -{ - tmpfile - Memcheck:Leak - fun:malloc - fun:fdopen@@GLIBC_* - fun:tmpfile@@GLIBC_* -} From 6cd55e535cb830cd9f614b2f63e089b1a6830a0d Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 9 Feb 2016 09:38:25 -0800 Subject: [PATCH 144/701] Removes potentially dangerous and misleading lat, lon subscript oeprator --- include/extractor/query_node.hpp | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index 98d03210d..c97a986be 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -3,8 +3,6 @@ #include "util/typedefs.hpp" -#include - #include "osrm/coordinate.hpp" #include @@ -44,21 +42,6 @@ struct QueryNode return QueryNode(static_cast(90 * COORDINATE_PRECISION), static_cast(180 * COORDINATE_PRECISION), MAX_OSM_NODEID); } - - value_type operator[](const std::size_t n) const - { - switch (n) - { - case 1: - return lat; - case 0: - return lon; - default: - break; - } - BOOST_ASSERT_MSG(false, "should not happen"); - return std::numeric_limits::lowest(); - } }; } } From 6eebb1c089ef7bd3ee30b072e977b715b1e46c4e Mon Sep 17 00:00:00 2001 From: Dane Springmeyer Date: Wed, 10 Feb 2016 16:26:04 -0800 Subject: [PATCH 145/701] Support passing OSRM_SHARED_LIBRARY_PATH env variable for cucumber tests The need for this is that: - On OS X if libraries are stored in custom locations (not /usr/lib or /usr/local) and they do not embed an rpath (which is common to not have) then the developer needs to set DYLD_LIBRARY_PATH to ensure that osrm tools can find dependent libraries at runtime (this is normal and common). - But as of OS X > 10.11 DYLD_LIBRARY_PATH no longer is inherited. While it works in the main shell when running a command like `osrm-extract` you will find that when `osrm-extract` is run by cucumber (ruby child process) then DYLD_LIBRARY_PATH is blocked and the command cannot start. - So, this introduces the ability to pass in a variable that the cucumber tests will understand and can manually forward along to ensure that DYLD_LIBRARY_PATH is respected where it counts. The intended usage of this is therefore: # set the environment variable export OSRM_SHARED_LIBRARY_PATH=${DYLD_LIBRARY_PATH} # then run cucumber tests cucumber -p verify --- features/support/data.rb | 4 ++-- features/support/env.rb | 13 +++++++++++-- features/support/launch.rb | 4 ++-- features/support/run.rb | 2 +- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/features/support/data.rb b/features/support/data.rb index adc3d118c..7fc31dc68 100644 --- a/features/support/data.rb +++ b/features/support/data.rb @@ -258,7 +258,7 @@ def extract_data Dir.chdir TEST_FOLDER do log_preprocess_info log "== Extracting #{osm_file}.osm...", :preprocess - unless system "#{BIN_PATH}/osrm-extract #{osm_file}.osm #{@extract_args} --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" + unless system "#{LOAD_LIBRARIES}#{BIN_PATH}/osrm-extract #{osm_file}.osm #{@extract_args} --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" log "*** Exited with code #{$?.exitstatus}.", :preprocess raise ExtractError.new $?.exitstatus, "osrm-extract exited with code #{$?.exitstatus}." end @@ -277,7 +277,7 @@ def prepare_data Dir.chdir TEST_FOLDER do log_preprocess_info log "== Preparing #{extracted_file}.osm...", :preprocess - unless system "#{BIN_PATH}/osrm-prepare #{extracted_file}.osrm --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" + unless system "#{LOAD_LIBRARIES}#{BIN_PATH}/osrm-prepare #{extracted_file}.osrm --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" log "*** Exited with code #{$?.exitstatus}.", :preprocess raise PrepareError.new $?.exitstatus, "osrm-prepare exited with code #{$?.exitstatus}." end diff --git a/features/support/env.rb b/features/support/env.rb index 94d7d3625..35d23eccb 100644 --- a/features/support/env.rb +++ b/features/support/env.rb @@ -23,6 +23,15 @@ SHUTDOWN_TIMEOUT = 10 DEFAULT_LOAD_METHOD = 'datastore' OSRM_ROUTED_LOG_FILE = 'osrm-routed.log' +# OS X shim to ensure shared libraries from custom locations can be loaded +# This is needed in OS X >= 10.11 because DYLD_LIBRARY_PATH is blocked +# https://forums.developer.apple.com/thread/9233 +if ENV['OSRM_SHARED_LIBRARY_PATH'] + LOAD_LIBRARIES="DYLD_LIBRARY_PATH=#{ENV['OSRM_SHARED_LIBRARY_PATH']} " +else + LOAD_LIBRARIES="" +end + if ENV['OS']=~/Windows.*/ then TERMSIGNAL=9 else @@ -76,9 +85,9 @@ def verify_existance_of_binaries unless File.exists? "#{BIN_PATH}/#{bin}#{EXE}" raise "*** #{BIN_PATH}/#{bin}#{EXE} is missing. Build failed?" end - unless system "#{BIN_PATH}/#{bin}#{EXE} --help" + unless system "#{LOAD_LIBRARIES}#{BIN_PATH}/#{bin}#{EXE} --help > /dev/null 2>&1" log "*** Exited with code #{$?.exitstatus}.", :preprocess - raise "*** #{BIN_PATH}/#{bin}#{EXE} --help exited with code #{$?.exitstatus}." + raise "*** #{LOAD_LIBRARIES}#{BIN_PATH}/#{bin}#{EXE} --help exited with code #{$?.exitstatus}." end end end diff --git a/features/support/launch.rb b/features/support/launch.rb index d8d23aeaa..919078501 100644 --- a/features/support/launch.rb +++ b/features/support/launch.rb @@ -92,7 +92,7 @@ class OSRMLoader def osrm_up return if @@pid - @@pid = Process.spawn("#{BIN_PATH}/osrm-routed #{@input_file} --port #{OSRM_PORT}",:out=>OSRM_ROUTED_LOG_FILE, :err=>OSRM_ROUTED_LOG_FILE) + @@pid = Process.spawn("#{LOAD_LIBRARIES}#{BIN_PATH}/osrm-routed #{@input_file} --port #{OSRM_PORT}",:out=>OSRM_ROUTED_LOG_FILE, :err=>OSRM_ROUTED_LOG_FILE) Process.detach(@@pid) # avoid zombie processes end @@ -118,7 +118,7 @@ class OSRMLoader def osrm_up return if osrm_up? - @@pid = Process.spawn("#{BIN_PATH}/osrm-routed --shared-memory=1 --port #{OSRM_PORT}",:out=>OSRM_ROUTED_LOG_FILE, :err=>OSRM_ROUTED_LOG_FILE) + @@pid = Process.spawn("#{LOAD_LIBRARIES}#{BIN_PATH}/osrm-routed --shared-memory=1 --port #{OSRM_PORT}",:out=>OSRM_ROUTED_LOG_FILE, :err=>OSRM_ROUTED_LOG_FILE) Process.detach(@@pid) # avoid zombie processes end end diff --git a/features/support/run.rb b/features/support/run.rb index 42dc597a1..4c77adfcb 100644 --- a/features/support/run.rb +++ b/features/support/run.rb @@ -20,7 +20,7 @@ def run_bin bin, options opt.gsub! "{profile}", "#{PROFILES_PATH}/#{@profile}.lua" end - cmd = "#{QQ}#{BIN_PATH}/#{bin}#{EXE}#{QQ} #{opt} 2>error.log" + cmd = "#{QQ}#{LOAD_LIBRARIES}#{BIN_PATH}/#{bin}#{EXE}#{QQ} #{opt} 2>error.log" @stdout = `#{cmd}` @stderr = File.read 'error.log' @exit_code = $?.exitstatus From 7398bed9740d0d65068b487a69b0eded779baffc Mon Sep 17 00:00:00 2001 From: karenzshea Date: Tue, 9 Feb 2016 21:14:43 -0500 Subject: [PATCH 146/701] Include real coordinates in debug geojson mode --- include/contractor/contractor_config.hpp | 2 ++ include/util/debug_geometry.hpp | 37 ++++++++++++++++++++---- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/include/contractor/contractor_config.hpp b/include/contractor/contractor_config.hpp index 61c88b0a3..595dfecd9 100644 --- a/include/contractor/contractor_config.hpp +++ b/include/contractor/contractor_config.hpp @@ -23,6 +23,7 @@ struct ContractorConfig edge_based_graph_path = osrm_input_path.string() + ".ebg"; edge_segment_lookup_path = osrm_input_path.string() + ".edge_segment_lookup"; edge_penalty_path = osrm_input_path.string() + ".edge_penalties"; + node_based_graph_path = osrm_input_path.string() + ".nodes"; } boost::filesystem::path config_file_path; @@ -36,6 +37,7 @@ struct ContractorConfig std::string edge_segment_lookup_path; std::string edge_penalty_path; + std::string node_based_graph_path; bool use_cached_priority; unsigned requested_num_threads; diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index f76e0cd4f..ee3f87dd2 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -4,6 +4,7 @@ #include "contractor/contractor_config.hpp" #include "extractor/query_node.hpp" #include "osrm/coordinate.hpp" +#include #ifndef DEBUG_GEOMETRY @@ -69,6 +70,8 @@ boost::filesystem::ofstream dg_debug_turns_file; bool dg_output_turn_debug = false; bool dg_first_turn_debug = true; +std::unordered_map node_lookup_map; + inline void DEBUG_GEOMETRY_START(const contractor::ContractorConfig &config) { time_t raw_time; @@ -77,12 +80,28 @@ inline void DEBUG_GEOMETRY_START(const contractor::ContractorConfig &config) timeinfo = localtime(&raw_time); strftime(dg_time_buffer, 80, "%Y-%m-%d %H:%M %Z", timeinfo); + boost::filesystem::ifstream nodes_input_stream{config.node_based_graph_path, + std::ios_base::in | std::ios_base::binary}; + + extractor::QueryNode current_node; + unsigned number_of_coordinates = 0; + nodes_input_stream.read((char *)&number_of_coordinates, sizeof(unsigned)); + + for (unsigned i = 0; i < number_of_coordinates; ++i) + { + nodes_input_stream.read((char *)¤t_node, sizeof(extractor::QueryNode)); + node_lookup_map[current_node.node_id] = + util::FixedPointCoordinate(current_node.lat, current_node.lon); + } + nodes_input_stream.close(); + dg_output_debug_geometry = config.debug_geometry_path != ""; if (dg_output_debug_geometry) { debug_geometry_file.open(config.debug_geometry_path, std::ios::binary); debug_geometry_file << "{\"type\":\"FeatureCollection\", \"features\":[" << std::endl; + debug_geometry_file << std::setprecision(10); } } @@ -96,15 +115,21 @@ inline void DEBUG_GEOMETRY_EDGE(int new_segment_weight, if (!dg_first_debug_geometry) debug_geometry_file << "," << std::endl; debug_geometry_file << "{ \"type\":\"Feature\",\"properties\":{\"original\":false, " - "\"weight\":" << new_segment_weight / 10.0 << ",\"speed\":" - << static_cast(std::floor((segment_length / new_segment_weight) * - 10. * 3.6)) << ","; + "\"weight\":" + << new_segment_weight / 10.0 << ",\"speed\":" + << static_cast( + std::floor((segment_length / new_segment_weight) * 10. * 3.6)) + << ","; debug_geometry_file << "\"from_node\": " << previous_osm_node_id << ", \"to_node\": " << this_osm_node_id << ","; debug_geometry_file << "\"timestamp\": \"" << dg_time_buffer << "\"},"; - debug_geometry_file << "\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[!!" - << previous_osm_node_id << "!!],[!!" << this_osm_node_id << "!!]]}}" - << std::endl; + debug_geometry_file + << "\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[" + << node_lookup_map[previous_osm_node_id].lon / osrm::COORDINATE_PRECISION << "," + << node_lookup_map[previous_osm_node_id].lat / osrm::COORDINATE_PRECISION << "],[" + << node_lookup_map[this_osm_node_id].lon / osrm::COORDINATE_PRECISION << "," + << node_lookup_map[this_osm_node_id].lat / osrm::COORDINATE_PRECISION << "]]}}" + << std::endl; dg_first_debug_geometry = false; } } From a647cb9836d04d14040f3147552e2f4d0adfdc61 Mon Sep 17 00:00:00 2001 From: karenzshea Date: Thu, 11 Feb 2016 17:36:49 -0500 Subject: [PATCH 147/701] kick From d1c4a2679105616146ec7d80bfa76340d34ccf22 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 11 Feb 2016 19:19:28 -0800 Subject: [PATCH 148/701] Remove .restriction reference --- src/tools/extract.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index 9c63bfb4b..4550cff4f 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -28,12 +28,6 @@ parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_con // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( - /* - * TODO: re-enable this - "restrictions,r", - boost::program_options::value(&extractor_config.restrictions_path), - "Restrictions file in .osrm.restrictions format")( - */ "config,c", boost::program_options::value(&extractor_config.config_file_path) ->default_value("extractor.ini"), From 5de8f1803c79c7009082cc0a91b48f9e9c296856 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 28 Jan 2016 14:13:39 +0100 Subject: [PATCH 149/701] Folds mercator projections into coordinate_calculation --- include/util/coordinate_calculation.hpp | 12 +++++++++--- include/util/mercator.hpp | 26 ------------------------- include/util/static_rtree.hpp | 7 +++---- src/util/coordinate_calculation.cpp | 22 +++++++++++++++++++-- src/util/mercator.cpp | 10 ---------- 5 files changed, 32 insertions(+), 45 deletions(-) delete mode 100644 include/util/mercator.hpp delete mode 100644 src/util/mercator.cpp diff --git a/include/util/coordinate_calculation.hpp b/include/util/coordinate_calculation.hpp index ea80f8d6b..b7758f294 100644 --- a/include/util/coordinate_calculation.hpp +++ b/include/util/coordinate_calculation.hpp @@ -62,8 +62,14 @@ double bearing(const FixedPointCoordinate first_coordinate, double computeAngle(const FixedPointCoordinate first, const FixedPointCoordinate second, const FixedPointCoordinate third); -} -} -} + +namespace mercator +{ +double yToLat(const double value); +double latToY(const double latitude); +} // ns mercator +} // ns coordinate_calculation +} // ns util +} // ns osrm #endif // COORDINATE_CALCULATION diff --git a/include/util/mercator.hpp b/include/util/mercator.hpp deleted file mode 100644 index fa22c9db0..000000000 --- a/include/util/mercator.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef MERCATOR_HPP -#define MERCATOR_HPP - -#include - -namespace osrm -{ -namespace util -{ -namespace mercator -{ - -inline double yToLat(const double value) noexcept -{ - return 180. * M_1_PI * (2. * std::atan(std::exp(value * M_PI / 180.)) - M_PI_2); -} - -inline double latToY(const double latitude) noexcept -{ - return 180. * M_1_PI * std::log(std::tan(M_PI_4 + latitude * (M_PI / 180.) / 2.)); -} -} -} -} - -#endif // MERCATOR_HPP diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index c6f34f71d..dbf0ca18c 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -8,7 +8,6 @@ #include "util/bearing.hpp" #include "util/integer_range.hpp" -#include "util/mercator.hpp" #include "util/osrm_exception.hpp" #include "util/typedefs.hpp" @@ -140,8 +139,8 @@ class StaticRTree FixedPointCoordinate(coordinate_list.at(current_element.v).lat, coordinate_list.at(current_element.v).lon)); current_centroid.lat = - COORDINATE_PRECISION * - mercator::latToY(current_centroid.lat / COORDINATE_PRECISION); + COORDINATE_PRECISION * coordinate_calculation::mercator::latToY( + current_centroid.lat / COORDINATE_PRECISION); current_wrapper.m_hilbert_value = hilbertCode(current_centroid); } @@ -342,7 +341,7 @@ class StaticRTree { std::vector results; std::pair projected_coordinate = { - mercator::latToY(input_coordinate.lat / COORDINATE_PRECISION), + coordinate_calculation::mercator::latToY(input_coordinate.lat / COORDINATE_PRECISION), input_coordinate.lon / COORDINATE_PRECISION}; // initialize queue with root element diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index e0dfe006a..b54154fa6 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -1,6 +1,5 @@ #include "util/coordinate_calculation.hpp" -#include "util/mercator.hpp" #include "util/string_util.hpp" #include "util/trigonometry_table.hpp" @@ -90,6 +89,8 @@ double perpendicularDistance(const FixedPointCoordinate segment_source, FixedPointCoordinate &nearest_location, double &ratio) { + using namespace coordinate_calculation; + return perpendicularDistanceFromProjectedCoordinate( segment_source, segment_target, query_location, {mercator::latToY(query_location.lat / COORDINATE_PRECISION), @@ -119,6 +120,8 @@ perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate segment_ FixedPointCoordinate &nearest_location, double &ratio) { + using namespace coordinate_calculation; + BOOST_ASSERT(query_location.IsValid()); // initialize values @@ -222,6 +225,8 @@ double computeAngle(const FixedPointCoordinate first, const FixedPointCoordinate second, const FixedPointCoordinate third) { + using namespace coordinate_calculation; + const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION; const double v1y = mercator::latToY(first.lat / COORDINATE_PRECISION) - mercator::latToY(second.lat / COORDINATE_PRECISION); @@ -238,6 +243,19 @@ double computeAngle(const FixedPointCoordinate first, return angle; } + +namespace mercator +{ +double yToLat(const double value) +{ + return 180. * M_1_PI * (2. * std::atan(std::exp(value * M_PI / 180.)) - M_PI_2); } + +double latToY(const double latitude) +{ + return 180. * M_1_PI * std::log(std::tan(M_PI_4 + latitude * (M_PI / 180.) / 2.)); } -} +} // ns mercato // ns mercatorr +} // ns coordinate_calculation +} // ns util +} // ns osrm diff --git a/src/util/mercator.cpp b/src/util/mercator.cpp deleted file mode 100644 index 19c5e1d42..000000000 --- a/src/util/mercator.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "util/mercator.hpp" - -#include - -namespace osrm -{ -namespace util -{ -} -} From 64b36807d3ddc5d524df7ed70e5513a211d91bac Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 28 Jan 2016 14:27:05 +0100 Subject: [PATCH 150/701] Transforms osrm_exception to exception --- include/engine/datafacade/datafacade_base.hpp | 2 +- include/extractor/raster_source.hpp | 2 +- include/storage/shared_datatype.hpp | 2 +- include/storage/shared_memory.hpp | 2 +- include/util/{osrm_exception.hpp => exception.hpp} | 6 +++--- include/util/fingerprint_impl.hpp.in | 2 +- include/util/graph_loader.hpp | 2 +- include/util/routed_options.hpp | 2 +- include/util/static_rtree.hpp | 2 +- src/contractor/contractor.cpp | 2 +- src/extractor/edge_based_graph_factory.cpp | 2 +- src/extractor/extraction_containers.cpp | 2 +- src/extractor/restriction_parser.cpp | 2 +- src/extractor/scripting_environment.cpp | 2 +- src/storage/storage.cpp | 2 +- src/tools/components.cpp | 2 +- src/tools/io-benchmark.cpp | 2 +- src/tools/store.cpp | 2 +- src/util/{osrm_exception.cpp => exception.cpp} | 2 +- unit_tests/extractor/raster_source.cpp | 2 +- 20 files changed, 22 insertions(+), 22 deletions(-) rename include/util/{osrm_exception.hpp => exception.hpp} (88%) rename src/util/{osrm_exception.cpp => exception.cpp} (95%) diff --git a/include/engine/datafacade/datafacade_base.hpp b/include/engine/datafacade/datafacade_base.hpp index e737f2def..d64d7cb1c 100644 --- a/include/engine/datafacade/datafacade_base.hpp +++ b/include/engine/datafacade/datafacade_base.hpp @@ -8,7 +8,7 @@ #include "engine/phantom_node.hpp" #include "extractor/turn_instructions.hpp" #include "util/integer_range.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/string_util.hpp" #include "util/typedefs.hpp" diff --git a/include/extractor/raster_source.hpp b/include/extractor/raster_source.hpp index 104462619..499e9a262 100644 --- a/include/extractor/raster_source.hpp +++ b/include/extractor/raster_source.hpp @@ -1,7 +1,7 @@ #ifndef RASTER_SOURCE_HPP #define RASTER_SOURCE_HPP -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include #include diff --git a/include/storage/shared_datatype.hpp b/include/storage/shared_datatype.hpp index 69e409e42..22f7bdec2 100644 --- a/include/storage/shared_datatype.hpp +++ b/include/storage/shared_datatype.hpp @@ -1,7 +1,7 @@ #ifndef SHARED_DATA_TYPE_HPP #define SHARED_DATA_TYPE_HPP -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include diff --git a/include/storage/shared_memory.hpp b/include/storage/shared_memory.hpp index 7f14482e3..47238cfdf 100644 --- a/include/storage/shared_memory.hpp +++ b/include/storage/shared_memory.hpp @@ -1,7 +1,7 @@ #ifndef SHARED_MEMORY_HPP #define SHARED_MEMORY_HPP -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include diff --git a/include/util/osrm_exception.hpp b/include/util/exception.hpp similarity index 88% rename from include/util/osrm_exception.hpp rename to include/util/exception.hpp index 6c7c5e2f6..837bbfe87 100644 --- a/include/util/osrm_exception.hpp +++ b/include/util/exception.hpp @@ -1,5 +1,5 @@ -#ifndef OSRM_EXCEPTION_HPP -#define OSRM_EXCEPTION_HPP +#ifndef EXCEPTION_HPP +#define EXCEPTION_HPP #include #include @@ -27,4 +27,4 @@ class exception final : public std::exception } } -#endif /* OSRM_EXCEPTION_HPP */ +#endif /* EXCEPTION_HPP */ diff --git a/include/util/fingerprint_impl.hpp.in b/include/util/fingerprint_impl.hpp.in index 1a52269d1..7b31d6dd7 100644 --- a/include/util/fingerprint_impl.hpp.in +++ b/include/util/fingerprint_impl.hpp.in @@ -1,4 +1,4 @@ -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include #include diff --git a/include/util/graph_loader.hpp b/include/util/graph_loader.hpp index 224fb375b..233d7aa70 100644 --- a/include/util/graph_loader.hpp +++ b/include/util/graph_loader.hpp @@ -2,7 +2,7 @@ #define GRAPH_LOADER_HPP #include "util/fingerprint.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include "extractor/external_memory_node.hpp" #include "extractor/node_based_edge.hpp" diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index 070b0d694..c0b83b45b 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -3,7 +3,7 @@ #include "util/ini_file.hpp" #include "util/version.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index dbf0ca18c..e59948052 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -8,7 +8,7 @@ #include "util/bearing.hpp" #include "util/integer_range.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/typedefs.hpp" #include "osrm/coordinate.hpp" diff --git a/src/contractor/contractor.cpp b/src/contractor/contractor.cpp index 6b01c564a..291ced449 100644 --- a/src/contractor/contractor.cpp +++ b/src/contractor/contractor.cpp @@ -10,7 +10,7 @@ #include "util/io.hpp" #include "util/integer_range.hpp" #include "util/lua_util.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include "util/string_util.hpp" #include "util/timing_util.hpp" diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index cc615c905..6ffbb4bea 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -6,7 +6,7 @@ #include "util/lua_util.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/debug_geometry.hpp" diff --git a/src/extractor/extraction_containers.cpp b/src/extractor/extraction_containers.cpp index 26f8d7eb8..ed9e259ea 100644 --- a/src/extractor/extraction_containers.cpp +++ b/src/extractor/extraction_containers.cpp @@ -4,7 +4,7 @@ #include "util/coordinate_calculation.hpp" #include "util/range_table.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" #include "util/fingerprint.hpp" diff --git a/src/extractor/restriction_parser.cpp b/src/extractor/restriction_parser.cpp index 3df9e0754..3f1648563 100644 --- a/src/extractor/restriction_parser.cpp +++ b/src/extractor/restriction_parser.cpp @@ -3,7 +3,7 @@ #include "extractor/external_memory_node.hpp" #include "util/lua_util.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include diff --git a/src/extractor/scripting_environment.cpp b/src/extractor/scripting_environment.cpp index 247291f74..4fd77c1e1 100644 --- a/src/extractor/scripting_environment.cpp +++ b/src/extractor/scripting_environment.cpp @@ -7,7 +7,7 @@ #include "extractor/external_memory_node.hpp" #include "extractor/raster_source.hpp" #include "util/lua_util.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include "util/typedefs.hpp" diff --git a/src/storage/storage.cpp b/src/storage/storage.cpp index d5439c8c5..663b3a688 100644 --- a/src/storage/storage.cpp +++ b/src/storage/storage.cpp @@ -13,7 +13,7 @@ #include "storage/shared_barriers.hpp" #include "storage/shared_memory.hpp" #include "util/fingerprint.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include "util/typedefs.hpp" diff --git a/src/tools/components.cpp b/src/tools/components.cpp index 69e92cb3c..06baea021 100644 --- a/src/tools/components.cpp +++ b/src/tools/components.cpp @@ -6,7 +6,7 @@ #include "util/fingerprint.hpp" #include "util/graph_loader.hpp" #include "util/make_unique.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include diff --git a/src/tools/io-benchmark.cpp b/src/tools/io-benchmark.cpp index 8c08288a5..0ccf97ece 100644 --- a/src/tools/io-benchmark.cpp +++ b/src/tools/io-benchmark.cpp @@ -1,4 +1,4 @@ -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" diff --git a/src/tools/store.cpp b/src/tools/store.cpp index 7065cbb10..a1dc17c4a 100644 --- a/src/tools/store.cpp +++ b/src/tools/store.cpp @@ -1,5 +1,5 @@ #include "storage/storage.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include "util/simple_logger.hpp" #include "util/typedefs.hpp" #include "util/ini_file.hpp" diff --git a/src/util/osrm_exception.cpp b/src/util/exception.cpp similarity index 95% rename from src/util/osrm_exception.cpp rename to src/util/exception.cpp index 91ca7c4f5..394d8c07c 100644 --- a/src/util/osrm_exception.cpp +++ b/src/util/exception.cpp @@ -1,4 +1,4 @@ -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" // This function exists to 'anchor' the class, and stop the compiler from // copying vtable and RTTI info into every object file that includes diff --git a/unit_tests/extractor/raster_source.cpp b/unit_tests/extractor/raster_source.cpp index 2160372f1..5ce93514e 100644 --- a/unit_tests/extractor/raster_source.cpp +++ b/unit_tests/extractor/raster_source.cpp @@ -1,6 +1,6 @@ #include "extractor/raster_source.hpp" #include "util/typedefs.hpp" -#include "util/osrm_exception.hpp" +#include "util/exception.hpp" #include From ef171f3acd83608431db7416bf671a62b08748e4 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 28 Jan 2016 15:21:02 +0100 Subject: [PATCH 151/701] Properly use typed math constants instead of impl. specific hacks PI is not in the stdlib, neither is 1/pi, pi*2 and so on. Instead of relying on implementations providing these, use properly typed math constants. Main benefits: - portable and - returns constexpr, for compile-time computation References: - http://www.boost.org/doc/libs/1_60_0/libs/math/doc/html/math_toolkit/constants_intro.html - http://www.boost.org/doc/libs/1_60_0/libs/math/doc/html/math_toolkit/constants.html --- CMakeLists.txt | 2 -- .../engine/map_matching/bayes_classifier.hpp | 6 ++++- .../map_matching/hidden_markov_model.hpp | 3 ++- include/util/trigonometry_table.hpp | 23 +++++++++------- include/util/typedefs.hpp | 8 ------ src/util/coordinate_calculation.cpp | 26 +++++++++++++++---- 6 files changed, 42 insertions(+), 26 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f238c834..efc6d36bb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -163,7 +163,6 @@ elseif(${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU") # using GCC set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic -Wuninitialized -Wunreachable-code -Wstrict-overflow=1 -D_FORTIFY_SOURCE=2 ${COLOR_FLAG} -fPIC") if(WIN32) # using mingw - add_definitions(-D_USE_MATH_DEFINES) # define M_PI, M_1_PI etc. add_definitions(-DWIN32) set(OPTIONAL_SOCKET_LIBS ws2_32 wsock32) endif() @@ -175,7 +174,6 @@ elseif(${CMAKE_CXX_COMPILER_ID} STREQUAL "MSVC") set(BOOST_COMPONENTS ${BOOST_COMPONENTS} date_time chrono zlib) add_definitions(-D_CRT_SECURE_NO_WARNINGS) add_definitions(-DNOMINMAX) # avoid min and max macros that can break compilation - add_definitions(-D_USE_MATH_DEFINES) # define M_PI add_definitions(-D_WIN32_WINNT=0x0501) add_definitions(-DXML_STATIC) find_library(ws2_32_LIBRARY_PATH ws2_32) diff --git a/include/engine/map_matching/bayes_classifier.hpp b/include/engine/map_matching/bayes_classifier.hpp index f3c2e8eee..59b9fb5ae 100644 --- a/include/engine/map_matching/bayes_classifier.hpp +++ b/include/engine/map_matching/bayes_classifier.hpp @@ -6,6 +6,8 @@ #include #include +#include + namespace osrm { namespace engine @@ -23,8 +25,10 @@ struct NormalDistribution // FIXME implement log-probability version since its faster double density_function(const double val) const { + using namespace boost::math::constants; + const double x = val - mean; - return 1.0 / (std::sqrt(2. * M_PI) * standard_deviation) * + return 1.0 / (std::sqrt(two_pi()) * standard_deviation) * std::exp(-x * x / (standard_deviation * standard_deviation)); } diff --git a/include/engine/map_matching/hidden_markov_model.hpp b/include/engine/map_matching/hidden_markov_model.hpp index c387c1faf..91895b51e 100644 --- a/include/engine/map_matching/hidden_markov_model.hpp +++ b/include/engine/map_matching/hidden_markov_model.hpp @@ -4,6 +4,7 @@ #include "util/integer_range.hpp" #include +#include #include @@ -17,7 +18,7 @@ namespace engine namespace map_matching { -static const double log_2_pi = std::log(2. * M_PI); +static const double log_2_pi = std::log(2. * boost::math::constants::pi()); static const double IMPOSSIBLE_LOG_PROB = -std::numeric_limits::infinity(); static const double MINIMAL_LOG_PROB = std::numeric_limits::lowest(); static const std::size_t INVALID_STATE = std::numeric_limits::max(); diff --git a/include/util/trigonometry_table.hpp b/include/util/trigonometry_table.hpp index 69e0bb459..e66a52509 100644 --- a/include/util/trigonometry_table.hpp +++ b/include/util/trigonometry_table.hpp @@ -6,6 +6,8 @@ #include +#include + namespace osrm { namespace util @@ -356,19 +358,22 @@ constexpr unsigned short atan_table[4096] = { 0xffe0, 0xffea, 0xfff4, 0xffff}; // max value is pi/4 -constexpr double SCALING_FACTOR = 4. / M_PI * 0xFFFF; +const constexpr double SCALING_FACTOR = 4. / boost::math::constants::pi() * 0xFFFF; inline double atan2_lookup(double y, double x) { + + using namespace boost::math::constants; + if (std::abs(x) < std::numeric_limits::epsilon()) { if (y >= 0.) { - return M_PI / 2.; + return half_pi(); } else { - return -M_PI / 2.; + return -half_pi(); } } @@ -399,25 +404,25 @@ inline double atan2_lookup(double y, double x) case 0: break; case 1: - angle = M_PI - angle; + angle = pi() - angle; break; case 2: angle = -angle; break; case 3: - angle = -M_PI + angle; + angle = -pi() + angle; break; case 4: - angle = M_PI / 2.0 - angle; + angle = half_pi() - angle; break; case 5: - angle = M_PI / 2.0 + angle; + angle = half_pi() + angle; break; case 6: - angle = -M_PI / 2.0 + angle; + angle = -half_pi() + angle; break; case 7: - angle = -M_PI / 2.0 - angle; + angle = -half_pi() - angle; break; } return angle; diff --git a/include/util/typedefs.hpp b/include/util/typedefs.hpp index 614e7ebd6..8dc417a41 100644 --- a/include/util/typedefs.hpp +++ b/include/util/typedefs.hpp @@ -6,14 +6,6 @@ #include #include -// Necessary workaround for Windows as VS doesn't implement C99 -#ifdef _MSC_VER -#define WIN32_LEAN_AND_MEAN -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif -#endif - // OpenStreetMap node ids are higher than 2^32 OSRM_STRONG_TYPEDEF(uint64_t, OSMNodeID) OSRM_STRONG_TYPEDEF(uint32_t, OSMWayID) diff --git a/src/util/coordinate_calculation.cpp b/src/util/coordinate_calculation.cpp index b54154fa6..61fd77cab 100644 --- a/src/util/coordinate_calculation.cpp +++ b/src/util/coordinate_calculation.cpp @@ -4,6 +4,7 @@ #include "util/trigonometry_table.hpp" #include +#include #include @@ -193,9 +194,17 @@ perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate segment_ return approximate_distance; } -double degToRad(const double degree) { return degree * (static_cast(M_PI) / 180.0); } +double degToRad(const double degree) +{ + using namespace boost::math::constants; + return degree * (pi() / 180.0); +} -double radToDeg(const double radian) { return radian * (180.0 * static_cast(M_1_PI)); } +double radToDeg(const double radian) +{ + using namespace boost::math::constants; + return radian * (180.0 * (1. / pi())); +} double bearing(const FixedPointCoordinate first_coordinate, const FixedPointCoordinate second_coordinate) @@ -225,6 +234,7 @@ double computeAngle(const FixedPointCoordinate first, const FixedPointCoordinate second, const FixedPointCoordinate third) { + using namespace boost::math::constants; using namespace coordinate_calculation; const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION; @@ -234,7 +244,7 @@ double computeAngle(const FixedPointCoordinate first, const double v2y = mercator::latToY(third.lat / COORDINATE_PRECISION) - mercator::latToY(second.lat / COORDINATE_PRECISION); - double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / M_PI; + double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / pi(); while (angle < 0.) { @@ -248,12 +258,18 @@ namespace mercator { double yToLat(const double value) { - return 180. * M_1_PI * (2. * std::atan(std::exp(value * M_PI / 180.)) - M_PI_2); + using namespace boost::math::constants; + + return 180. * (1. / pi()) * + (2. * std::atan(std::exp(value * pi() / 180.)) - half_pi()); } double latToY(const double latitude) { - return 180. * M_1_PI * std::log(std::tan(M_PI_4 + latitude * (M_PI / 180.) / 2.)); + using namespace boost::math::constants; + + return 180. * (1. / pi()) * + std::log(std::tan((pi() / 4.) + latitude * (pi() / 180.) / 2.)); } } // ns mercato // ns mercatorr } // ns coordinate_calculation From 978b70c9986b466408537ae78854348c4994acb0 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 28 Jan 2016 16:57:05 +0100 Subject: [PATCH 152/701] Adds a comment as to why the char to typed enum class transformation is not possible --- include/extractor/travel_mode.hpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/include/extractor/travel_mode.hpp b/include/extractor/travel_mode.hpp index 1de8c2266..af16bcaee 100644 --- a/include/extractor/travel_mode.hpp +++ b/include/extractor/travel_mode.hpp @@ -6,6 +6,8 @@ namespace osrm namespace extractor { +// This is a char instead of a typed enum, so that we can +// pack it into e.g. a "TravelMode mode : 4" packed bitfield using TravelMode = unsigned char; } } From 60fc486cea57a9bc2656587d9a1a0f560ff4bed6 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 28 Jan 2016 17:41:56 +0100 Subject: [PATCH 153/701] Prefix exception header guard with osrm prefix --- include/util/exception.hpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/util/exception.hpp b/include/util/exception.hpp index 837bbfe87..6c7c5e2f6 100644 --- a/include/util/exception.hpp +++ b/include/util/exception.hpp @@ -1,5 +1,5 @@ -#ifndef EXCEPTION_HPP -#define EXCEPTION_HPP +#ifndef OSRM_EXCEPTION_HPP +#define OSRM_EXCEPTION_HPP #include #include @@ -27,4 +27,4 @@ class exception final : public std::exception } } -#endif /* EXCEPTION_HPP */ +#endif /* OSRM_EXCEPTION_HPP */ From f207d988f4426a9478d55c3541f410701eafcb74 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 2 Feb 2016 11:53:44 +0100 Subject: [PATCH 154/701] Removes floating point epsilon comparator --- include/util/floating_point.hpp | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 include/util/floating_point.hpp diff --git a/include/util/floating_point.hpp b/include/util/floating_point.hpp deleted file mode 100644 index 779f095db..000000000 --- a/include/util/floating_point.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef FLOATING_POINT_HPP -#define FLOATING_POINT_HPP - -#include - -#include -#include - -namespace osrm -{ -namespace util -{ - -template bool epsilon_compare(const FloatT number1, const FloatT number2) -{ - static_assert(std::is_floating_point::value, "type must be floating point"); - return (std::abs(number1 - number2) < std::numeric_limits::epsilon()); -} -} -} - -#endif // FLOATING_POINT_HPP From fbef77a9422f60cba460f16404b4aa1ad67f0088 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 2 Feb 2016 11:57:57 +0100 Subject: [PATCH 155/701] Documents why not to use boost::irange in favor of our hand-written irange --- include/util/integer_range.hpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/include/util/integer_range.hpp b/include/util/integer_range.hpp index ee706bd8b..29d428f80 100644 --- a/include/util/integer_range.hpp +++ b/include/util/integer_range.hpp @@ -12,6 +12,11 @@ namespace osrm namespace util { +// Warning: do not try to replace this with Boost's irange, as it is broken on Boost 1.55: +// auto r = boost::irange(0, 15); +// std::cout << r.size() << std::endl; +// results in -4294967281. Latest Boost versions fix this, but we still support older ones. + template class range { private: From ec01c2a119d422d220e05fcf7177651ef6128bd1 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 2 Feb 2016 13:12:24 +0100 Subject: [PATCH 156/701] Folds json_* utilities into json subfolder and adapts includes --- CMakeLists.txt | 2 +- include/engine/plugins/match.hpp | 4 ++-- include/engine/plugins/viaroute.hpp | 4 ++-- .../routing_algorithms/map_matching.hpp | 2 +- include/osrm/json_container.hpp | 5 +++- .../container.hpp} | 14 +++++------ .../util/{json_logger.hpp => json/logger.hpp} | 0 .../{json_renderer.hpp => json/renderer.hpp} | 23 +++++++------------ include/util/{json_util.hpp => json/util.hpp} | 0 include/util/matching_debug_info.hpp | 4 ++-- src/server/request_handler.cpp | 5 ++-- unit_tests/util/static_rtree.cpp | 1 - 12 files changed, 29 insertions(+), 35 deletions(-) rename include/util/{json_container.hpp => json/container.hpp} (90%) rename include/util/{json_logger.hpp => json/logger.hpp} (100%) rename include/util/{json_renderer.hpp => json/renderer.hpp} (88%) rename include/util/{json_util.hpp => json/util.hpp} (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index efc6d36bb..c293dbff2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -379,7 +379,7 @@ set_property(TARGET osrm-routed PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) file(GLOB VariantGlob third_party/variant/*.hpp) file(GLOB LibraryGlob include/osrm/*.hpp) set(EngineHeader include/engine/engine.hpp include/engine/engine_config.hpp include/engine/route_parameters.hpp) -set(UtilHeader include/util/coordinate.hpp include/util/json_container.hpp) +set(UtilHeader include/util/coordinate.hpp include/util/json/container.hpp) set(ExtractorHeader include/extractor/extractor.hpp include/extractor/extractor_config.hpp) set(ContractorHeader include/contractor/contractor.hpp include/contractor/contractor_config.hpp) #set(StorageHeader include/storage/storage.hpp include/storage/storage_config.hpp) diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 0de44148a..1b6a13f01 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -12,8 +12,8 @@ #include "engine/routing_algorithms/map_matching.hpp" #include "util/coordinate_calculation.hpp" #include "util/integer_range.hpp" -#include "util/json_logger.hpp" -#include "util/json_util.hpp" +#include "util/json/logger.hpp" +#include "util/json/util.hpp" #include "util/string_util.hpp" #include diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index b3d8bb00f..f34ddc675 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -8,11 +8,11 @@ #include "engine/search_engine.hpp" #include "util/for_each_pair.hpp" #include "util/integer_range.hpp" -#include "util/json_renderer.hpp" +#include "osrm/json_container.hpp" +#include "util/json/renderer.hpp" #include "util/make_unique.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" -#include "osrm/json_container.hpp" #include diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index f3422dd6d..61ba88121 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -5,7 +5,7 @@ #include "util/coordinate_calculation.hpp" #include "engine/map_matching/hidden_markov_model.hpp" -#include "util/json_logger.hpp" +#include "util/json/logger.hpp" #include "util/matching_debug_info.hpp" #include diff --git a/include/osrm/json_container.hpp b/include/osrm/json_container.hpp index 1b0787713..bcf02e1b4 100644 --- a/include/osrm/json_container.hpp +++ b/include/osrm/json_container.hpp @@ -1,8 +1,11 @@ #ifndef GLOBAL_JSON_CONTAINER_HPP #define GLOBAL_JSON_CONTAINER_HPP -#include "util/json_container.hpp" + +#include "util/json/container.hpp" + namespace osrm { namespace json = osrm::util::json; } + #endif diff --git a/include/util/json_container.hpp b/include/util/json/container.hpp similarity index 90% rename from include/util/json_container.hpp rename to include/util/json/container.hpp index d3a9ca4a8..d44b628b3 100644 --- a/include/util/json_container.hpp +++ b/include/util/json/container.hpp @@ -33,9 +33,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include #include #include +#include #include namespace osrm @@ -52,16 +52,16 @@ struct Array; struct String { - String() {} - String(const char *value) : value(value) {} - String(std::string value) : value(std::move(value)) {} + String() = default; + String(const char *value_) : value{value_} {} + String(std::string value_) : value{std::move(value_)} {} std::string value; }; struct Number { - Number() {} - Number(double value) : value(static_cast(value)) {} + Number() = default; + Number(double value_) : value{value_} {} double value; }; @@ -95,7 +95,7 @@ struct Array std::vector values; }; -} // namespace JSON +} // namespace json } // namespace util } // namespace osrm diff --git a/include/util/json_logger.hpp b/include/util/json/logger.hpp similarity index 100% rename from include/util/json_logger.hpp rename to include/util/json/logger.hpp diff --git a/include/util/json_renderer.hpp b/include/util/json/renderer.hpp similarity index 88% rename from include/util/json_renderer.hpp rename to include/util/json/renderer.hpp index 9569829f0..10d1876bc 100644 --- a/include/util/json_renderer.hpp +++ b/include/util/json/renderer.hpp @@ -9,6 +9,11 @@ #include "osrm/json_container.hpp" +#include +#include +#include +#include + namespace osrm { namespace util @@ -123,23 +128,11 @@ struct ArrayRenderer out.push_back(']'); } - void operator()(const True &) const - { - const std::string temp("true"); - out.insert(out.end(), temp.begin(), temp.end()); - } + void operator()(const True &) const { out.insert(end(out), {'t', 'r', 'u', 'e'}); } - void operator()(const False &) const - { - const std::string temp("false"); - out.insert(out.end(), temp.begin(), temp.end()); - } + void operator()(const False &) const { out.insert(end(out), {'f', 'a', 'l', 's', 'e'}); } - void operator()(const Null &) const - { - const std::string temp("null"); - out.insert(out.end(), temp.begin(), temp.end()); - } + void operator()(const Null &) const { out.insert(end(out), {'n', 'u', 'l', 'l'}); } private: std::vector &out; diff --git a/include/util/json_util.hpp b/include/util/json/util.hpp similarity index 100% rename from include/util/json_util.hpp rename to include/util/json/util.hpp diff --git a/include/util/matching_debug_info.hpp b/include/util/matching_debug_info.hpp index e90053378..bb5253456 100644 --- a/include/util/matching_debug_info.hpp +++ b/include/util/matching_debug_info.hpp @@ -1,8 +1,8 @@ #ifndef MATCHING_DEBUG_INFO_HPP #define MATCHING_DEBUG_INFO_HPP -#include "util/json_logger.hpp" -#include "util/json_util.hpp" +#include "util/json/logger.hpp" +#include "util/json/util.hpp" #include "engine/map_matching/hidden_markov_model.hpp" #include "osrm/coordinate.hpp" diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index 6df6c1e99..c87def7d8 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -4,14 +4,13 @@ #include "server/http/reply.hpp" #include "server/http/request.hpp" -#include "util/json_renderer.hpp" +#include "util/json/container.hpp" +#include "util/json/renderer.hpp" #include "util/simple_logger.hpp" #include "util/string_util.hpp" #include "util/xml_renderer.hpp" #include "util/typedefs.hpp" - #include "engine/route_parameters.hpp" -#include "util/json_container.hpp" #include "osrm/osrm.hpp" #include diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index fd3a19b69..3530fe048 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -3,7 +3,6 @@ #include "util/static_rtree.hpp" #include "extractor/query_node.hpp" #include "extractor/edge_based_node.hpp" -#include "util/floating_point.hpp" #include "util/typedefs.hpp" #include From aac21f932b0938580c9a779b7667d5602db11b58 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 2 Feb 2016 14:49:41 +0100 Subject: [PATCH 157/701] Refactors Base64 encoding and decoding, it's almost beautiful now --- include/engine/api_response_generator.hpp | 6 +- include/engine/object_encoder.hpp | 96 +++++++++++++---------- include/engine/plugins/distance_table.hpp | 3 +- include/engine/plugins/trip.hpp | 4 +- include/engine/plugins/viaroute.hpp | 8 +- 5 files changed, 65 insertions(+), 52 deletions(-) diff --git a/include/engine/api_response_generator.hpp b/include/engine/api_response_generator.hpp index cfdc5bdc1..0de8a7a24 100644 --- a/include/engine/api_response_generator.hpp +++ b/include/engine/api_response_generator.hpp @@ -277,10 +277,10 @@ ApiResponseGenerator::BuildHintData(const InternalRouteResult &raw_ std::string hint; for (const auto i : util::irange(0, raw_route.segment_end_coordinates.size())) { - ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates[i].source_phantom, hint); - json_location_hint_array.values.push_back(hint); + hint = encodeBase64(raw_route.segment_end_coordinates[i].source_phantom); + json_location_hint_array.values.push_back(std::move(hint)); } - ObjectEncoder::EncodeToBase64(raw_route.segment_end_coordinates.back().target_phantom, hint); + hint = encodeBase64(raw_route.segment_end_coordinates.back().target_phantom); json_location_hint_array.values.emplace_back(std::move(hint)); json_hint_object.values["locations"] = json_location_hint_array; diff --git a/include/engine/object_encoder.hpp b/include/engine/object_encoder.hpp index c9fe21b04..496e8eadb 100644 --- a/include/engine/object_encoder.hpp +++ b/include/engine/object_encoder.hpp @@ -11,59 +11,75 @@ #include #include +#include +#include + namespace osrm { namespace engine { -struct ObjectEncoder +namespace detail { - using base64_t = boost::archive::iterators::base64_from_binary< - boost::archive::iterators::transform_width>; +static_assert(CHAR_BIT == 8u, "we assume a byte holds 8 bits"); +static_assert(sizeof(char) == 1u, "we assume a char is one byte large"); - using binary_t = boost::archive::iterators::transform_width< - boost::archive::iterators::binary_from_base64, - 8, - 6>; +using Base64FromBinary = boost::archive::iterators::base64_from_binary< + boost::archive::iterators::transform_width>; - template static void EncodeToBase64(const ObjectT &object, std::string &encoded) - { - const char *char_ptr_to_object = reinterpret_cast(&object); - std::vector data(sizeof(object)); - std::copy(char_ptr_to_object, char_ptr_to_object + sizeof(ObjectT), data.begin()); +using BinaryFromBase64 = boost::archive::iterators::transform_width< + boost::archive::iterators::binary_from_base64, + 8, // get a view of 8 bit + 6 // from a sequence of 6 bit + >; +} // ns detail - unsigned char number_of_padded_chars = 0; // is in {0,1,2}; - while (data.size() % 3 != 0) - { - ++number_of_padded_chars; - data.push_back(0x00); - } +template std::string encodeBase64(const T &x) +{ + // static_assert(std::is_trivially_copyable::value, "requires a trivially copyable type"); - BOOST_ASSERT_MSG(0 == data.size() % 3, "base64 input data size is not a multiple of 3!"); - encoded.resize(sizeof(ObjectT)); - encoded.assign(base64_t(&data[0]), - base64_t(&data[0] + (data.size() - number_of_padded_chars))); - std::replace(begin(encoded), end(encoded), '+', '-'); - std::replace(begin(encoded), end(encoded), '/', '_'); - } + std::vector bytes{reinterpret_cast(&x), + reinterpret_cast(&x) + sizeof(T)}; + BOOST_ASSERT(!bytes.empty()); - template static void DecodeFromBase64(const std::string &input, ObjectT &object) - { - try - { - std::string encoded(input); - std::replace(begin(encoded), end(encoded), '-', '+'); - std::replace(begin(encoded), end(encoded), '_', '/'); + const auto next_divisible_by_three = ((bytes.size() / 3u) + 1u) * 3u; + BOOST_ASSERT(next_divisible_by_three >= bytes.size()); - std::copy(binary_t(encoded.begin()), binary_t(encoded.begin() + encoded.length()), - reinterpret_cast(&object)); - } - catch (...) - { - } - } -}; + const auto bytes_to_pad = next_divisible_by_three - bytes.size(); + BOOST_ASSERT(bytes_to_pad == 0 || bytes_to_pad == 1 || bytes_to_pad == 2); + + bytes.insert(end(bytes), bytes_to_pad, 0x00); + BOOST_ASSERT_MSG(0 == bytes.size() % 3, "base64 input data size is not a multiple of 3"); + + std::string encoded{detail::Base64FromBinary{bytes.data()}, + detail::Base64FromBinary{bytes.data() + (bytes.size() - bytes_to_pad)}}; + + std::replace(begin(encoded), end(encoded), '+', '-'); + std::replace(begin(encoded), end(encoded), '/', '_'); + + return encoded; } + +template T decodeBase64(std::string encoded) +{ + // static_assert(std::is_trivially_copyable::value, "requires a trivially copyable type"); + + std::replace(begin(encoded), end(encoded), '-', '+'); + std::replace(begin(encoded), end(encoded), '_', '/'); + + T rv; + + std::copy(detail::BinaryFromBase64{begin(encoded)}, + detail::BinaryFromBase64{begin(encoded) + encoded.length()}, + reinterpret_cast(&rv)); + + return rv; } +} // ns engine +} // ns osrm + #endif /* OBJECT_ENCODER_HPP */ diff --git a/include/engine/plugins/distance_table.hpp b/include/engine/plugins/distance_table.hpp index b1625ed93..1c6d5093f 100644 --- a/include/engine/plugins/distance_table.hpp +++ b/include/engine/plugins/distance_table.hpp @@ -94,8 +94,7 @@ template class DistanceTablePlugin final : public BasePlugin if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) { - PhantomNode current_phantom_node; - ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node); + auto current_phantom_node = decodeBase64(route_parameters.hints[i]); if (current_phantom_node.IsValid(facade->GetNumberOfNodes())) { if (route_parameters.is_source[i]) diff --git a/include/engine/plugins/trip.hpp b/include/engine/plugins/trip.hpp index db8440547..35abce2cb 100644 --- a/include/engine/plugins/trip.hpp +++ b/include/engine/plugins/trip.hpp @@ -64,8 +64,7 @@ template class RoundTripPlugin final : public BasePlugin if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) { - PhantomNode current_phantom_node; - ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node); + auto current_phantom_node = decodeBase64(route_parameters.hints[i]); if (current_phantom_node.IsValid(facade->GetNumberOfNodes())) { phantom_node_list.push_back(std::move(current_phantom_node)); @@ -317,7 +316,6 @@ template class RoundTripPlugin final : public BasePlugin // } // return s; // }(); - } else { diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index f34ddc675..fe041dd5c 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -83,8 +83,8 @@ template class ViaRoutePlugin final : public BasePlugin if (checksum_OK && i < route_parameters.hints.size() && !route_parameters.hints[i].empty()) { - ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], - phantom_node_pair_list[i].first); + phantom_node_pair_list[i].first = + decodeBase64(route_parameters.hints[i]); if (phantom_node_pair_list[i].first.IsValid(facade->GetNumberOfNodes())) { continue; @@ -111,8 +111,8 @@ template class ViaRoutePlugin final : public BasePlugin auto snapped_phantoms = snapPhantomNodes(phantom_node_pair_list); InternalRouteResult raw_route; - auto build_phantom_pairs = [&raw_route](const PhantomNode &first_node, - const PhantomNode &second_node) + auto build_phantom_pairs = + [&raw_route](const PhantomNode &first_node, const PhantomNode &second_node) { raw_route.segment_end_coordinates.push_back(PhantomNodes{first_node, second_node}); }; From c9f0158fdb57c2e9928ef9f20e34814486aec928 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Tue, 2 Feb 2016 15:09:32 +0100 Subject: [PATCH 158/701] Ifdef is_trivially_copyable behind gcc >= 5 guard --- include/engine/object_encoder.hpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/include/engine/object_encoder.hpp b/include/engine/object_encoder.hpp index 496e8eadb..94784de25 100644 --- a/include/engine/object_encoder.hpp +++ b/include/engine/object_encoder.hpp @@ -39,7 +39,9 @@ using BinaryFromBase64 = boost::archive::iterators::transform_width< template std::string encodeBase64(const T &x) { - // static_assert(std::is_trivially_copyable::value, "requires a trivially copyable type"); +#if not defined __GNUC__ or __GNUC__ > 4 + static_assert(std::is_trivially_copyable::value, "requires a trivially copyable type"); +#endif std::vector bytes{reinterpret_cast(&x), reinterpret_cast(&x) + sizeof(T)}; @@ -65,7 +67,9 @@ template std::string encodeBase64(const T &x) template T decodeBase64(std::string encoded) { - // static_assert(std::is_trivially_copyable::value, "requires a trivially copyable type"); +#if not defined __GNUC__ or __GNUC__ > 4 + static_assert(std::is_trivially_copyable::value, "requires a trivially copyable type"); +#endif std::replace(begin(encoded), end(encoded), '-', '+'); std::replace(begin(encoded), end(encoded), '_', '/'); From 4b8c0ac1431b2744cd5a966343e7a12898c77d42 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 12 Feb 2016 15:23:33 -0800 Subject: [PATCH 159/701] Revert "Folds json_* utilities into json subfolder and adapts includes" This reverts commit cd039c69c0a92a35889e3c875b8eb53cf07377bb. --- CMakeLists.txt | 2 +- include/engine/plugins/match.hpp | 4 ++-- include/engine/plugins/viaroute.hpp | 4 ++-- .../routing_algorithms/map_matching.hpp | 2 +- include/osrm/json_container.hpp | 5 +--- .../container.hpp => json_container.hpp} | 14 +++++------ .../util/{json/logger.hpp => json_logger.hpp} | 0 .../{json/renderer.hpp => json_renderer.hpp} | 23 ++++++++++++------- include/util/{json/util.hpp => json_util.hpp} | 0 include/util/matching_debug_info.hpp | 4 ++-- src/server/request_handler.cpp | 5 ++-- unit_tests/util/static_rtree.cpp | 1 + 12 files changed, 35 insertions(+), 29 deletions(-) rename include/util/{json/container.hpp => json_container.hpp} (90%) rename include/util/{json/logger.hpp => json_logger.hpp} (100%) rename include/util/{json/renderer.hpp => json_renderer.hpp} (88%) rename include/util/{json/util.hpp => json_util.hpp} (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index c293dbff2..efc6d36bb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -379,7 +379,7 @@ set_property(TARGET osrm-routed PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) file(GLOB VariantGlob third_party/variant/*.hpp) file(GLOB LibraryGlob include/osrm/*.hpp) set(EngineHeader include/engine/engine.hpp include/engine/engine_config.hpp include/engine/route_parameters.hpp) -set(UtilHeader include/util/coordinate.hpp include/util/json/container.hpp) +set(UtilHeader include/util/coordinate.hpp include/util/json_container.hpp) set(ExtractorHeader include/extractor/extractor.hpp include/extractor/extractor_config.hpp) set(ContractorHeader include/contractor/contractor.hpp include/contractor/contractor_config.hpp) #set(StorageHeader include/storage/storage.hpp include/storage/storage_config.hpp) diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 1b6a13f01..0de44148a 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -12,8 +12,8 @@ #include "engine/routing_algorithms/map_matching.hpp" #include "util/coordinate_calculation.hpp" #include "util/integer_range.hpp" -#include "util/json/logger.hpp" -#include "util/json/util.hpp" +#include "util/json_logger.hpp" +#include "util/json_util.hpp" #include "util/string_util.hpp" #include diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index fe041dd5c..6789e5ac0 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -8,11 +8,11 @@ #include "engine/search_engine.hpp" #include "util/for_each_pair.hpp" #include "util/integer_range.hpp" -#include "osrm/json_container.hpp" -#include "util/json/renderer.hpp" +#include "util/json_renderer.hpp" #include "util/make_unique.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" +#include "osrm/json_container.hpp" #include diff --git a/include/engine/routing_algorithms/map_matching.hpp b/include/engine/routing_algorithms/map_matching.hpp index 61ba88121..f3422dd6d 100644 --- a/include/engine/routing_algorithms/map_matching.hpp +++ b/include/engine/routing_algorithms/map_matching.hpp @@ -5,7 +5,7 @@ #include "util/coordinate_calculation.hpp" #include "engine/map_matching/hidden_markov_model.hpp" -#include "util/json/logger.hpp" +#include "util/json_logger.hpp" #include "util/matching_debug_info.hpp" #include diff --git a/include/osrm/json_container.hpp b/include/osrm/json_container.hpp index bcf02e1b4..1b0787713 100644 --- a/include/osrm/json_container.hpp +++ b/include/osrm/json_container.hpp @@ -1,11 +1,8 @@ #ifndef GLOBAL_JSON_CONTAINER_HPP #define GLOBAL_JSON_CONTAINER_HPP - -#include "util/json/container.hpp" - +#include "util/json_container.hpp" namespace osrm { namespace json = osrm::util::json; } - #endif diff --git a/include/util/json/container.hpp b/include/util/json_container.hpp similarity index 90% rename from include/util/json/container.hpp rename to include/util/json_container.hpp index d44b628b3..d3a9ca4a8 100644 --- a/include/util/json/container.hpp +++ b/include/util/json_container.hpp @@ -33,9 +33,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include +#include #include #include -#include #include namespace osrm @@ -52,16 +52,16 @@ struct Array; struct String { - String() = default; - String(const char *value_) : value{value_} {} - String(std::string value_) : value{std::move(value_)} {} + String() {} + String(const char *value) : value(value) {} + String(std::string value) : value(std::move(value)) {} std::string value; }; struct Number { - Number() = default; - Number(double value_) : value{value_} {} + Number() {} + Number(double value) : value(static_cast(value)) {} double value; }; @@ -95,7 +95,7 @@ struct Array std::vector values; }; -} // namespace json +} // namespace JSON } // namespace util } // namespace osrm diff --git a/include/util/json/logger.hpp b/include/util/json_logger.hpp similarity index 100% rename from include/util/json/logger.hpp rename to include/util/json_logger.hpp diff --git a/include/util/json/renderer.hpp b/include/util/json_renderer.hpp similarity index 88% rename from include/util/json/renderer.hpp rename to include/util/json_renderer.hpp index 10d1876bc..9569829f0 100644 --- a/include/util/json/renderer.hpp +++ b/include/util/json_renderer.hpp @@ -9,11 +9,6 @@ #include "osrm/json_container.hpp" -#include -#include -#include -#include - namespace osrm { namespace util @@ -128,11 +123,23 @@ struct ArrayRenderer out.push_back(']'); } - void operator()(const True &) const { out.insert(end(out), {'t', 'r', 'u', 'e'}); } + void operator()(const True &) const + { + const std::string temp("true"); + out.insert(out.end(), temp.begin(), temp.end()); + } - void operator()(const False &) const { out.insert(end(out), {'f', 'a', 'l', 's', 'e'}); } + void operator()(const False &) const + { + const std::string temp("false"); + out.insert(out.end(), temp.begin(), temp.end()); + } - void operator()(const Null &) const { out.insert(end(out), {'n', 'u', 'l', 'l'}); } + void operator()(const Null &) const + { + const std::string temp("null"); + out.insert(out.end(), temp.begin(), temp.end()); + } private: std::vector &out; diff --git a/include/util/json/util.hpp b/include/util/json_util.hpp similarity index 100% rename from include/util/json/util.hpp rename to include/util/json_util.hpp diff --git a/include/util/matching_debug_info.hpp b/include/util/matching_debug_info.hpp index bb5253456..e90053378 100644 --- a/include/util/matching_debug_info.hpp +++ b/include/util/matching_debug_info.hpp @@ -1,8 +1,8 @@ #ifndef MATCHING_DEBUG_INFO_HPP #define MATCHING_DEBUG_INFO_HPP -#include "util/json/logger.hpp" -#include "util/json/util.hpp" +#include "util/json_logger.hpp" +#include "util/json_util.hpp" #include "engine/map_matching/hidden_markov_model.hpp" #include "osrm/coordinate.hpp" diff --git a/src/server/request_handler.cpp b/src/server/request_handler.cpp index c87def7d8..6df6c1e99 100644 --- a/src/server/request_handler.cpp +++ b/src/server/request_handler.cpp @@ -4,13 +4,14 @@ #include "server/http/reply.hpp" #include "server/http/request.hpp" -#include "util/json/container.hpp" -#include "util/json/renderer.hpp" +#include "util/json_renderer.hpp" #include "util/simple_logger.hpp" #include "util/string_util.hpp" #include "util/xml_renderer.hpp" #include "util/typedefs.hpp" + #include "engine/route_parameters.hpp" +#include "util/json_container.hpp" #include "osrm/osrm.hpp" #include diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index 3530fe048..fd3a19b69 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -3,6 +3,7 @@ #include "util/static_rtree.hpp" #include "extractor/query_node.hpp" #include "extractor/edge_based_node.hpp" +#include "util/floating_point.hpp" #include "util/typedefs.hpp" #include From a6d406d2c3721642ffd18879311a94e5d47c1f07 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 12 Feb 2016 15:40:17 -0800 Subject: [PATCH 160/701] Fix headers for JSON abstractions --- include/util/json_container.hpp | 12 ++++++------ include/util/json_renderer.hpp | 5 +++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/include/util/json_container.hpp b/include/util/json_container.hpp index d3a9ca4a8..b5b14a143 100644 --- a/include/util/json_container.hpp +++ b/include/util/json_container.hpp @@ -33,9 +33,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include -#include #include #include +#include #include namespace osrm @@ -52,16 +52,16 @@ struct Array; struct String { - String() {} - String(const char *value) : value(value) {} - String(std::string value) : value(std::move(value)) {} + String() = default; + String(const char *value_) : value{value_} {} + String(std::string value_) : value{std::move(value_)} {} std::string value; }; struct Number { - Number() {} - Number(double value) : value(static_cast(value)) {} + Number() = default; + Number(double value_) : value{value_} {} double value; }; diff --git a/include/util/json_renderer.hpp b/include/util/json_renderer.hpp index 9569829f0..a1ac7a04a 100644 --- a/include/util/json_renderer.hpp +++ b/include/util/json_renderer.hpp @@ -9,6 +9,11 @@ #include "osrm/json_container.hpp" +#include +#include +#include +#include + namespace osrm { namespace util From eb6f01e65a997db3536100e72acc641a80a37310 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 12 Feb 2016 16:30:01 -0800 Subject: [PATCH 161/701] Rip out obsolete floating point header --- unit_tests/util/static_rtree.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/unit_tests/util/static_rtree.cpp b/unit_tests/util/static_rtree.cpp index fd3a19b69..3530fe048 100644 --- a/unit_tests/util/static_rtree.cpp +++ b/unit_tests/util/static_rtree.cpp @@ -3,7 +3,6 @@ #include "util/static_rtree.hpp" #include "extractor/query_node.hpp" #include "extractor/edge_based_node.hpp" -#include "util/floating_point.hpp" #include "util/typedefs.hpp" #include From 27fe85ac8b03a2b52fa8dbfd1cebe4f40c28e638 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 12 Feb 2016 18:10:44 -0800 Subject: [PATCH 162/701] Dividable-by-three instead of next-dividable-by-three --- include/engine/object_encoder.hpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/include/engine/object_encoder.hpp b/include/engine/object_encoder.hpp index 94784de25..00a1d21c1 100644 --- a/include/engine/object_encoder.hpp +++ b/include/engine/object_encoder.hpp @@ -47,13 +47,15 @@ template std::string encodeBase64(const T &x) reinterpret_cast(&x) + sizeof(T)}; BOOST_ASSERT(!bytes.empty()); - const auto next_divisible_by_three = ((bytes.size() / 3u) + 1u) * 3u; - BOOST_ASSERT(next_divisible_by_three >= bytes.size()); + std::size_t bytes_to_pad{0}; + + while (bytes.size() % 3 != 0) + { + bytes_to_pad += 1; + bytes.push_back(0); + } - const auto bytes_to_pad = next_divisible_by_three - bytes.size(); BOOST_ASSERT(bytes_to_pad == 0 || bytes_to_pad == 1 || bytes_to_pad == 2); - - bytes.insert(end(bytes), bytes_to_pad, 0x00); BOOST_ASSERT_MSG(0 == bytes.size() % 3, "base64 input data size is not a multiple of 3"); std::string encoded{detail::Base64FromBinary{bytes.data()}, From ab9426e260d4ab511f8ae35c34395ff54352b1b9 Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Mon, 15 Feb 2016 18:26:39 +0100 Subject: [PATCH 163/701] fix routing when requiring loop at a core node --- include/engine/routing_algorithms/routing_base.hpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index 156ebba9e..9773a7e2d 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -675,11 +675,11 @@ template class BasicRoutingInterface BOOST_ASSERT_MSG((SPECIAL_NODEID != middle && INVALID_EDGE_WEIGHT != distance), "no path found"); - if (distance != forward_heap.GetKey(middle) + reverse_heap.GetKey(middle)) + if (distance != forward_core_heap.GetKey(middle) + reverse_core_heap.GetKey(middle)) { // self loop - BOOST_ASSERT(forward_heap.GetData(middle).parent == middle && - reverse_heap.GetData(middle).parent == middle); + BOOST_ASSERT(forward_core_heap.GetData(middle).parent == middle && + reverse_core_heap.GetData(middle).parent == middle); packed_leg.push_back(middle); packed_leg.push_back(middle); } From f14352f49427711500b911b804e849ad7cfb16e4 Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Fri, 29 Jan 2016 12:42:08 +0100 Subject: [PATCH 164/701] modify turn angles and instructions --- features/bicycle/mode.feature | 14 +- features/bicycle/pushing.feature | 10 +- features/support/route.rb | 5 +- features/testbot/graph.feature | 4 +- features/testbot/loop.feature | 6 +- features/testbot/matching_turns.feature | 18 +- features/testbot/mode.feature | 16 +- features/testbot/post.feature | 12 +- features/testbot/turn_angles.feature | 74 ++ features/testbot/turns.feature | 26 +- features/testbot/uturn.feature | 4 +- features/testbot/via.feature | 42 +- include/engine/guidance/segment_list.hpp | 9 +- include/engine/plugins/viaroute.hpp | 2 - .../extractor/edge_based_graph_factory.hpp | 67 +- include/extractor/query_node.hpp | 4 +- include/extractor/turn_instructions.hpp | 143 +++- src/extractor/edge_based_graph_factory.cpp | 710 +++++++++++++++--- 18 files changed, 936 insertions(+), 230 deletions(-) create mode 100644 features/testbot/turn_angles.feature diff --git a/features/bicycle/mode.feature b/features/bicycle/mode.feature index 2bfa4de5b..47618894b 100644 --- a/features/bicycle/mode.feature +++ b/features/bicycle/mode.feature @@ -62,13 +62,13 @@ Feature: Bike - Mode flag | cd | primary | | When I route I should get - | from | to | route | turns | modes | - | a | d | ab,bc,cd | head,right,left,destination | 1,1,1 | - | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | - | c | a | bc,ab | head,left,destination | 2,1 | - | d | b | cd,bc | head,right,destination | 1,2 | - | a | c | ab,bc | head,right,destination | 1,1 | - | b | d | bc,cd | head,left,destination | 1,1 | + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,straight,straight,destination | 1,1,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | + | c | a | bc,ab | head,left,destination | 2,1 | + | d | b | cd,bc | head,right,destination | 1,2 | + | a | c | ab,bc | head,straight,destination | 1,1 | + | b | d | bc,cd | head,straight,destination | 1,1 | Scenario: Bike - Mode when pushing on pedestrain streets Given the node map diff --git a/features/bicycle/pushing.feature b/features/bicycle/pushing.feature index 5741fb1c0..56b79b611 100644 --- a/features/bicycle/pushing.feature +++ b/features/bicycle/pushing.feature @@ -98,11 +98,11 @@ Feature: Bike - Accessability of different way types | cd | primary | | When I route I should get - | from | to | route | turns | - | a | d | ab,bc,cd | head,right,left,destination | - | d | a | cd,bc,ab | head,right,left,destination | - | c | a | bc,ab | head,left,destination | - | d | b | cd,bc | head,right,destination | + | from | to | route | turns | + | a | d | ab,bc,cd | head,straight,straight,destination | + | d | a | cd,bc,ab | head,right,left,destination | + | c | a | bc,ab | head,left,destination | + | d | b | cd,bc | head,right,destination | @todo Scenario: Bike - Instructions when pushing bike on footway/pedestrian, etc. diff --git a/features/support/route.rb b/features/support/route.rb index 935c5be38..a0deacb8f 100644 --- a/features/support/route.rb +++ b/features/support/route.rb @@ -155,8 +155,9 @@ def turn_list instructions 13 => :stay_roundabout, 14 => :start_end_of_street, 15 => :destination, - 16 => :enter_contraflow, - 17 => :leave_contraflow + 16 => :name_changes, + 17 => :enter_contraflow, + 18 => :leave_contraflow } # replace instructions codes with strings # "11-3" (enter roundabout and leave a 3rd exit) gets converted to "enter_roundabout-3" diff --git a/features/testbot/graph.feature b/features/testbot/graph.feature index adff99868..cbbec0c18 100644 --- a/features/testbot/graph.feature +++ b/features/testbot/graph.feature @@ -36,5 +36,5 @@ Feature: Basic Routing | fy | last | When I route I should get - | from | to | route | turns | - | x | y | first,compr,last | head,right,left,destination | + | from | to | route | turns | + | x | y | first,compr,last | head,straight,straight,destination | diff --git a/features/testbot/loop.feature b/features/testbot/loop.feature index c69e7a251..2d581b46b 100644 --- a/features/testbot/loop.feature +++ b/features/testbot/loop.feature @@ -92,6 +92,6 @@ Feature: Avoid weird loops caused by rounding errors | cf | primary | When I route I should get - | waypoints | route | turns | - | a,2,d | ab,be,ef,ef,cf,cd | head,left,right,via,right,left,destination | - | a,1,d | ab,be,ef,ef,cf,cd | head,left,right,via,right,left,destination | + | waypoints | route | turns | + | a,2,d | ab,be,ef,ef,cf,cd | head,left,straight,via,straight,left,destination | + | a,1,d | ab,be,ef,ef,cf,cd | head,left,straight,via,straight,left,destination | diff --git a/features/testbot/matching_turns.feature b/features/testbot/matching_turns.feature index 8bca4a274..f807ca954 100644 --- a/features/testbot/matching_turns.feature +++ b/features/testbot/matching_turns.feature @@ -17,21 +17,13 @@ Feature: Turn directions/codes And the ways | nodes | | xa | - | xb | | xc | - | xd | | xe | - | xf | | xg | - | xh | | xi | - | xj | | xk | - | xl | | xm | - | xn | | xo | - | xp | When I match I should get | trace | route | turns | matchings | @@ -40,7 +32,7 @@ Feature: Turn directions/codes | ia | xi,xa | head,straight,destination | ia | | ic | xi,xc | head,slight_right,destination | ic | | ie | xi,xe | head,right,destination | ie | - + | ko | xk,xo | head,left,destination | ko | | ka | xk,xa | head,slight_left,destination | ka | | kc | xk,xc | head,straight,destination | kc | @@ -96,21 +88,13 @@ Feature: Turn directions/codes And the ways | nodes | | xa | - | xb | | xc | - | xd | | xe | - | xf | | xg | - | xh | | xi | - | xj | | xk | - | xl | | xm | - | xn | | xo | - | xp | When I match I should get | trace | route | turns | matchings | duration | diff --git a/features/testbot/mode.feature b/features/testbot/mode.feature index ef8cd257e..e055799d9 100644 --- a/features/testbot/mode.feature +++ b/features/testbot/mode.feature @@ -174,14 +174,14 @@ Feature: Testbot - Travel mode | ef | primary | | | When I route I should get - | from | to | route | turns | modes | - | a | d | ab,bc,cd | head,right,left,destination | 1,2,1 | - | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | - | c | a | bc,ab | head,left,destination | 2,1 | - | d | b | cd,bc | head,right,destination | 1,2 | - | a | c | ab,bc | head,right,destination | 1,2 | - | b | d | bc,cd | head,left,destination | 2,1 | - | a | f | ab,bc,cd,de,ef | head,right,left,straight,straight,destination | 1,2,1,1,1 | + | from | to | route | turns | modes | + | a | d | ab,bc,cd | head,right,left,destination | 1,2,1 | + | d | a | cd,bc,ab | head,right,left,destination | 1,2,1 | + | c | a | bc,ab | head,left,destination | 2,1 | + | d | b | cd,bc | head,right,destination | 1,2 | + | a | c | ab,bc | head,right,destination | 1,2 | + | b | d | bc,cd | head,left,destination | 2,1 | + | a | f | ab,bc,cd,de,ef | head,right,left,straight,straight,destination | 1,2,1,1,1 | Scenario: Testbot - Modes, triangle map Given the node map diff --git a/features/testbot/post.feature b/features/testbot/post.feature index ac53177c5..656e26d90 100644 --- a/features/testbot/post.feature +++ b/features/testbot/post.feature @@ -21,13 +21,13 @@ Feature: POST request | bc | | xy | | yz | - + When I route I should get - | from | to | route | turns | - | a | c | ab,bc | head,left,destination | - | c | a | bc,ab | head,right,destination | - | x | z | xy,yz | head,right,destination | - | z | x | yz,xy | head,left,destination | + | from | to | route | turns | + | a | c | ab,bc | head,straight,destination | + | c | a | bc,ab | head,straight,destination | + | x | z | xy,yz | head,straight,destination | + | z | x | yz,xy | head,straight,destination | Scenario: Testbot - match POST request Given a grid size of 10 meters diff --git a/features/testbot/turn_angles.feature b/features/testbot/turn_angles.feature new file mode 100644 index 000000000..ce1400369 --- /dev/null +++ b/features/testbot/turn_angles.feature @@ -0,0 +1,74 @@ +@routing @testbot @via +Feature: Via points + + Background: + Given the profile "testbot" + + And a grid size of 4 meters + + Scenario: Basic Right Turn + Given the node map + | a | b | c | d | e | f | g | + | | | | | | h | | + | | | | | | i | | + | | | | | | j | | + | | | | | | k | | + + And the ways + | nodes | oneway | + | abcdefg | yes | + | ehijk | yes | + + When I route I should get + | from | to | route | distance | turns | + | a | k | abcdefg,ehijk | 34m +-1 | head,right,destination | + + Scenario: Slight Turn + Given the node map + | a | b | c | d | e | f | g | | + | | | | | | h | i | | + | | | | | | | | j | + | | | | | | | | k | + + And the ways + | nodes | oneway | + | abcdefg | yes | + | ehijk | yes | + + When I route I should get + | from | to | route | distance | turns | + | a | k | abcdefg,ehijk | 34m +-1 | head,slight_right,destination | + + Scenario: Nearly Slight Turn + Given the node map + | a | b | c | d | e | f | g | | + | | | | | | h | | | + | | | | | | | i | | + | | | | | | | | j | + | | | | | | | | k | + + And the ways + | nodes | oneway | + | abcdefg | yes | + | ehijk | yes | + + When I route I should get + | from | to | route | distance | turns | + | a | k | abcdefg,ehijk | 37m +-1 | head,right,destination | + + Scenario: Nearly Slight Turn (Variation) + Given the node map + | a | b | c | d | e | f | g | | + | | | | | | h | | | + | | | | | | | i | | + | | | | | | | j | | + | | | | | | | | k | + + And the ways + | nodes | oneway | + | abcdefg | yes | + | ehijk | yes | + + When I route I should get + | from | to | route | distance | turns | + | a | k | abcdefg,ehijk | 37m +-1 | head,right,destination | diff --git a/features/testbot/turns.feature b/features/testbot/turns.feature index 6eba4f9e9..0e7382f3c 100644 --- a/features/testbot/turns.feature +++ b/features/testbot/turns.feature @@ -14,22 +14,14 @@ Feature: Turn directions/codes And the ways | nodes | - | xa | - | xb | - | xc | - | xd | - | xe | - | xf | - | xg | - | xh | | xi | - | xj | | xk | - | xl | | xm | - | xn | | xo | - | xp | + | xa | + | xc | + | xe | + | xg | When I route I should get | from | to | route | turns | @@ -116,8 +108,8 @@ Feature: Turn directions/codes | yz | When I route I should get - | from | to | route | turns | - | a | c | ab,bc | head,left,destination | - | c | a | bc,ab | head,right,destination | - | x | z | xy,yz | head,right,destination | - | z | x | yz,xy | head,left,destination | + | from | to | route | turns | + | a | c | ab,bc | head,straight,destination | + | c | a | bc,ab | head,straight,destination | + | x | z | xy,yz | head,straight,destination | + | z | x | yz,xy | head,straight,destination | diff --git a/features/testbot/uturn.feature b/features/testbot/uturn.feature index 032bec685..47ff6a87d 100644 --- a/features/testbot/uturn.feature +++ b/features/testbot/uturn.feature @@ -20,8 +20,8 @@ Feature: U-turns at via points | fg | When I route I should get - | waypoints | route | turns | - | a,e,c | ab,be,be,ef,fg,dg,cd | head,right,via,left,straight,left,left,destination | + | waypoints | route | turns | + | a,e,c | ab,be,be,ef,fg,dg,cd | head,right,via,straight,straight,straight,straight,destination | Scenario: Query param to allow U-turns at all via points Given the node map diff --git a/features/testbot/via.feature b/features/testbot/via.feature index 3af38a9d6..bfed93e3d 100644 --- a/features/testbot/via.feature +++ b/features/testbot/via.feature @@ -86,12 +86,12 @@ Feature: Via points | fa | yes | When I route I should get - | waypoints | route | distance | turns | - | 1,3 | ab,bc,cd | 400m +-1 | head,straight,straight,destination | - | 3,1 | cd,de,ef,fa,ab | 1000m +-1 | head,right,right,right,right,destination | - | 1,2,3 | ab,bc,bc,cd | 400m +-1 | head,straight,via,straight,destination | - | 1,3,2 | ab,bc,cd,cd,de,ef,fa,ab,bc | 1600m +-1 | head,straight,straight,via,right,right,right,right,straight,destination | - | 3,2,1 | cd,de,ef,fa,ab,bc,bc,cd,de,ef,fa,ab | 2400m +-1 | head,right,right,right,right,straight,via,straight,right,right,right,right,destination | + | waypoints | route | distance | turns | + | 1,3 | ab,bc,cd | 400m +-1 | head,straight,straight,destination | + | 3,1 | cd,de,ef,fa,ab | 1000m +-1 | head,straight,straight,straight,right,destination | + | 1,2,3 | ab,bc,bc,cd | 400m +-1 | head,straight,via,straight,destination | + | 1,3,2 | ab,bc,cd,cd,de,ef,fa,ab,bc | 1600m +-1 | head,straight,straight,via,straight,straight,straight,right,straight,destination | + | 3,2,1 | cd,de,ef,fa,ab,bc,bc,cd,de,ef,fa,ab | 2400m +-1 | head,straight,straight,straight,right,straight,via,straight,straight,straight,straight,right,destination | Scenario: Via points on ring on the same oneway # xa it to avoid only having a single ring, which cna trigger edge cases @@ -109,12 +109,12 @@ Feature: Via points | da | yes | When I route I should get - | waypoints | route | distance | turns | - | 1,3 | ab | 200m +-1 | head,destination | - | 3,1 | ab,bc,cd,da,ab | 800m +-1 | head,right,right,right,right,destination | - | 1,2,3 | ab,ab | 200m +-1 | head,via,destination | - | 1,3,2 | ab,ab,bc,cd,da,ab | 1100m +-1 | head,via,right,right,right,right,destination | - | 3,2,1 | ab,bc,cd,da,ab,ab,bc,cd,da,ab | 1800m | head,right,right,right,right,via,right,right,right,right,destination | + | waypoints | route | distance | turns | + | 1,3 | ab | 200m +-1 | head,destination | + | 3,1 | ab,bc,cd,da,ab | 800m +-1 | head,straight,straight,straight,right,destination | + | 1,2,3 | ab,ab | 200m +-1 | head,via,destination | + | 1,3,2 | ab,ab,bc,cd,da,ab | 1100m +-1 | head,via,straight,straight,straight,right,destination | + | 3,2,1 | ab,bc,cd,da,ab,ab,bc,cd,da,ab | 1800m | head,straight,straight,straight,right,via,straight,straight,straight,right,destination | # See issue #1896 Scenario: Via point at a dead end with oneway @@ -175,11 +175,11 @@ Feature: Via points | da | yes | When I route I should get - | waypoints | route | distance | turns | - | 2,1 | ab,bc,cd,da,ab | 1100m +-1 | head,right,right,right,right,destination | - | 4,3 | bc,cd,da,ab,bc | 1100m +-1 | head,right,right,right,right,destination | - | 6,5 | cd,da,ab,bc,cd | 1100m +-1 | head,right,right,right,right,destination | - | 8,7 | da,ab,bc,cd,da | 1100m +-1 | head,right,right,right,right,destination | + | waypoints | route | distance | turns | + | 2,1 | ab,bc,cd,da,ab | 1100m +-1 | head,straight,straight,straight,straight,destination | + | 4,3 | bc,cd,da,ab,bc | 1100m +-1 | head,straight,straight,straight,straight,destination | + | 6,5 | cd,da,ab,bc,cd | 1100m +-1 | head,straight,straight,straight,straight,destination | + | 8,7 | da,ab,bc,cd,da | 1100m +-1 | head,straight,straight,straight,straight,destination | Scenario: Multiple Via points on ring on the same oneway, forces one of the vertices to be top node Given the node map @@ -197,7 +197,7 @@ Feature: Via points | da | yes | When I route I should get - | waypoints | route | distance | turns | - | 3,2,1 | ab,bc,cd,da,ab,ab,bc,cd,da,ab | 3000m +-1 | head,right,right,right,right,via,right,right,right,right,destination | - | 6,5,4 | bc,cd,da,ab,bc,bc,cd,da,ab,bc | 3000m +-1 | head,right,right,right,right,via,right,right,right,right,destination | - | 9,8,7 | cd,da,ab,bc,cd,cd,da,ab,bc,cd | 3000m +-1 | head,right,right,right,right,via,right,right,right,right,destination | + | waypoints | route | distance | turns | + | 3,2,1 | ab,bc,cd,da,ab,ab,bc,cd,da,ab | 3000m +-1 | head,straight,straight,straight,straight,via,straight,straight,straight,straight,destination | + | 6,5,4 | bc,cd,da,ab,bc,bc,cd,da,ab,bc | 3000m +-1 | head,straight,straight,straight,straight,via,straight,straight,straight,straight,destination | + | 9,8,7 | cd,da,ab,bc,cd,cd,da,ab,bc,cd | 3000m +-1 | head,straight,straight,straight,straight,via,straight,straight,straight,straight,destination | diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index 011b31d8a..b9be5ad2e 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -106,7 +106,8 @@ SegmentList::SegmentList(const InternalRouteResult &raw_route, { const auto &source_phantom = raw_route.segment_end_coordinates[raw_index].target_phantom; - if (raw_route.target_traversed_in_reverse[raw_index] != raw_route.source_traversed_in_reverse[raw_index+1]) + if (raw_route.target_traversed_in_reverse[raw_index] != + raw_route.source_traversed_in_reverse[raw_index + 1]) { bool traversed_in_reverse = raw_route.target_traversed_in_reverse[raw_index]; const extractor::TravelMode travel_mode = @@ -264,6 +265,12 @@ void SegmentList::Finalize(const bool extract_alternative, segment_length = 0; segment_duration = 0; segment_start_index = i; + + if (segments[i].turn_instruction == extractor::TurnInstruction::NameChanges) + { + segments[i].turn_instruction = + extractor::TurnInstruction::GoStraight; // to not break the api + } } } diff --git a/include/engine/plugins/viaroute.hpp b/include/engine/plugins/viaroute.hpp index 6789e5ac0..1d3e6bef2 100644 --- a/include/engine/plugins/viaroute.hpp +++ b/include/engine/plugins/viaroute.hpp @@ -8,7 +8,6 @@ #include "engine/search_engine.hpp" #include "util/for_each_pair.hpp" #include "util/integer_range.hpp" -#include "util/json_renderer.hpp" #include "util/make_unique.hpp" #include "util/simple_logger.hpp" #include "util/timing_util.hpp" @@ -166,7 +165,6 @@ template class ViaRoutePlugin final : public BasePlugin return Status::Error; } } - return Status::Ok; } }; diff --git a/include/extractor/edge_based_graph_factory.hpp b/include/extractor/edge_based_graph_factory.hpp index 7957cb60b..e6335123e 100644 --- a/include/extractor/edge_based_graph_factory.hpp +++ b/include/extractor/edge_based_graph_factory.hpp @@ -16,6 +16,8 @@ #include "extractor/restriction_map.hpp" #include +#include +#include #include #include #include @@ -23,6 +25,7 @@ #include #include #include +#include #include @@ -70,10 +73,18 @@ class EdgeBasedGraphFactory unsigned GetHighestEdgeID(); - TurnInstruction - AnalyzeTurn(const NodeID u, const NodeID v, const NodeID w, const double angle) const; + // Basic analysis of a turn (u --(e1)-- v --(e2)-- w) + // with known angle. + // Handles special cases like u-turns and roundabouts + // For basic turns, the turn based on the angle-classification is returned + TurnInstruction AnalyzeTurn(const NodeID u, + const EdgeID e1, + const NodeID v, + const EdgeID e2, + const NodeID w, + const double angle) const; - int GetTurnPenalty(double angle, lua_State *lua_state) const; + std::int32_t GetTurnPenalty(double angle, lua_State *lua_state) const; private: using EdgeData = util::NodeBasedDynamicGraph::EdgeData; @@ -123,8 +134,54 @@ class EdgeBasedGraphFactory void FlushVectorToStream(std::ofstream &edge_data_file, std::vector &original_edge_data_vector) const; + + struct TurnCandidate + { + EdgeID eid; // the id of the arc + bool valid; // a turn may be relevant to good instructions, even if we cannot take the road + double angle; // the approximated angle of the turn + TurnInstruction instruction; // a proposed instruction + double confidence; // how close to the border is the turn? + + std::string toString() const + { + std::string result = "[turn] "; + result += std::to_string(eid); + result += " valid: "; + result += std::to_string(valid); + result += " angle: "; + result += std::to_string(angle); + result += " instruction: "; + result += std::to_string(static_cast(instruction)); + result += " confidence: "; + result += std::to_string(confidence); + return result; + } + }; + + // Use In Order to generate base turns + + // cannot be const due to the counters... + std::vector getTurnCandidates(NodeID from, EdgeID via_edge); + std::vector optimizeCandidates(NodeID via_edge, + std::vector turn_candidates) const; + std::vector suppressTurns(EdgeID via_edge, + std::vector turn_candidates) const; + + QueryNode getRepresentativeCoordinate(const NodeID src, + const NodeID tgt, + const EdgeID via_eid, + bool INVERTED) const; + + bool isObviousChoice(EdgeID coming_from_eid, + std::size_t turn_index, + const std::vector &turn_candidates) const; + + std::size_t restricted_turns_counter; + std::size_t skipped_uturns_counter; + std::size_t skipped_barrier_turns_counter; }; -} -} +} // namespace extractor +} // namespace osrm #endif /* EDGE_BASED_GRAPH_FACTORY_HPP_ */ diff --git a/include/extractor/query_node.hpp b/include/extractor/query_node.hpp index c97a986be..f62dd33b3 100644 --- a/include/extractor/query_node.hpp +++ b/include/extractor/query_node.hpp @@ -17,7 +17,7 @@ struct QueryNode using key_type = OSMNodeID; // type of NodeID using value_type = int; // type of lat,lons - explicit QueryNode(int lat, int lon, OSMNodeID node_id) + explicit QueryNode(int lat, int lon, key_type node_id) : lat(lat), lon(lon), node_id(std::move(node_id)) { } @@ -29,7 +29,7 @@ struct QueryNode int lat; int lon; - OSMNodeID node_id; + key_type node_id; static QueryNode min_value() { diff --git a/include/extractor/turn_instructions.hpp b/include/extractor/turn_instructions.hpp index 9a08c97da..7cca8d78e 100644 --- a/include/extractor/turn_instructions.hpp +++ b/include/extractor/turn_instructions.hpp @@ -1,6 +1,11 @@ #ifndef TURN_INSTRUCTIONS_HPP #define TURN_INSTRUCTIONS_HPP +#include +#include + +#include + namespace osrm { namespace extractor @@ -24,6 +29,7 @@ enum class TurnInstruction : unsigned char StayOnRoundAbout, StartAtEndOfStreet, ReachedYourDestination, + NameChanges, EnterAgainstAllowedDirection, LeaveAgainstAllowedDirection, InverseAccessRestrictionFlag = 127, @@ -31,37 +37,87 @@ enum class TurnInstruction : unsigned char AccessRestrictionPenalty = 129 }; +// shiftable turns to left and right +const constexpr bool shiftable_left[] = {false, false, true, true, true, false, false, true, true}; +const constexpr bool shiftable_right[] = {false, false, true, true, false, false, true, true, true}; + +inline TurnInstruction shiftTurnToLeft(TurnInstruction turn) +{ + BOOST_ASSERT_MSG(static_cast(turn) < 9, + "Shift turn only supports basic turn instructions"); + if (turn > TurnInstruction::TurnSlightLeft) + return turn; + else + return shiftable_left[static_cast(turn)] + ? (static_cast(static_cast(turn) - 1)) + : turn; +} + +inline TurnInstruction shiftTurnToRight(TurnInstruction turn) +{ + BOOST_ASSERT_MSG(static_cast(turn) < 9, + "Shift turn only supports basic turn instructions"); + if (turn > TurnInstruction::TurnSlightLeft) + return turn; + else + return shiftable_right[static_cast(turn)] + ? (static_cast(static_cast(turn) + 1)) + : turn; +} + +inline double angularDeviation(const double angle, const double from) +{ + const double deviation = std::abs(angle - from); + return std::min(360 - deviation, deviation); +} + +inline double getAngularPenalty(const double angle, TurnInstruction instruction) +{ + BOOST_ASSERT_MSG(static_cast(instruction) < 9, + "Angular penalty only supports basic turn instructions"); + const double center[] = {180, 180, 135, 90, 45, + 0, 315, 270, 225}; // centers of turns from getTurnDirection + return angularDeviation(center[static_cast(instruction)], angle); +} + +inline double getTurnConfidence(const double angle, TurnInstruction instruction) +{ + + // special handling of U-Turns and Roundabout + if (instruction >= TurnInstruction::HeadOn || instruction == TurnInstruction::UTurn || + instruction == TurnInstruction::NoTurn || instruction == TurnInstruction::EnterRoundAbout || + instruction == TurnInstruction::StayOnRoundAbout || instruction == TurnInstruction::LeaveRoundAbout ) + return 1.0; + + BOOST_ASSERT_MSG(static_cast(instruction) < 9, + "Turn confidence only supports basic turn instructions"); + const double deviations[] = {10, 10, 35, 50, 45, 0, 45, 50, 35}; + const double difference = getAngularPenalty(angle, instruction); + const double max_deviation = deviations[static_cast(instruction)]; + return 1.0 - (difference / max_deviation) * (difference / max_deviation); +} + // Translates between angles and their human-friendly directional representation inline TurnInstruction getTurnDirection(const double angle) { - if (angle >= 23 && angle < 67) - { + // An angle of zero is a u-turn + // 180 goes perfectly straight + // 0-180 are right turns + // 180-360 are left turns + if (angle > 0 && angle < 60) return TurnInstruction::TurnSharpRight; - } - if (angle >= 67 && angle < 113) - { + if (angle >= 60 && angle < 140) return TurnInstruction::TurnRight; - } - if (angle >= 113 && angle < 158) - { + if (angle >= 140 && angle < 170) return TurnInstruction::TurnSlightRight; - } - if (angle >= 158 && angle < 202) - { + if (angle >= 170 && angle <= 190) return TurnInstruction::GoStraight; - } - if (angle >= 202 && angle < 248) - { + if (angle > 190 && angle <= 220) return TurnInstruction::TurnSlightLeft; - } - if (angle >= 248 && angle < 292) - { + if (angle > 220 && angle <= 300) return TurnInstruction::TurnLeft; - } - if (angle >= 292 && angle < 336) - { + if (angle > 300 && angle < 360) return TurnInstruction::TurnSharpLeft; - } return TurnInstruction::UTurn; } @@ -75,6 +131,51 @@ inline bool isTurnNecessary(const TurnInstruction turn_instruction) } return true; } + +inline bool resolve(TurnInstruction &to_resolve, const TurnInstruction neighbor, bool resolve_right) +{ + const auto shifted_turn = + resolve_right ? shiftTurnToRight(to_resolve) : shiftTurnToLeft(to_resolve); + if (shifted_turn == neighbor || shifted_turn == to_resolve) + return false; + + to_resolve = shifted_turn; + return true; +} + +inline bool resolveTransitive(TurnInstruction &first, + TurnInstruction &second, + const TurnInstruction third, + bool resolve_right) +{ + if (resolve(second, third, resolve_right)) + { + first = resolve_right ? shiftTurnToRight(first) : shiftTurnToLeft(first); + return true; + } + return false; +} + +inline bool isSlightTurn(const TurnInstruction turn) +{ + return turn == TurnInstruction::GoStraight || turn == TurnInstruction::TurnSlightRight || + turn == TurnInstruction::TurnSlightLeft || turn == TurnInstruction::NoTurn; +} + +inline bool isSharpTurn(const TurnInstruction turn) +{ + return turn == TurnInstruction::TurnSharpLeft || turn == TurnInstruction::TurnSharpRight; +} + +inline bool isStraight(const TurnInstruction turn) +{ + return turn == TurnInstruction::GoStraight || turn == TurnInstruction::NoTurn; +} + +inline bool isConflict(const TurnInstruction first, const TurnInstruction second) +{ + return first == second || (isStraight(first) && isStraight(second)); +} } } diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 6ffbb4bea..12a5490f8 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -1,5 +1,6 @@ #include "extractor/edge_based_edge.hpp" #include "extractor/edge_based_graph_factory.hpp" +#include "util/coordinate.hpp" #include "util/coordinate_calculation.hpp" #include "util/percent.hpp" #include "util/integer_range.hpp" @@ -12,15 +13,38 @@ #include +#include +#include #include #include #include +#include +#include namespace osrm { namespace extractor { +// configuration of turn classification +const bool constexpr INVERT = true; +const bool constexpr RESOLVE_TO_RIGHT = true; +const bool constexpr RESOLVE_TO_LEFT = false; + +// what angle is interpreted as going straight +const double constexpr STRAIGHT_ANGLE = 180.; +// if a turn deviates this much from going straight, it will be kept straight +const double constexpr MAXIMAL_ALLOWED_NO_TURN_DEVIATION = 2.; +// angle that lies between two nearly indistinguishable roads +const double constexpr NARROW_TURN_ANGLE = 25.; +// angle difference that can be classified as straight, if its the only narrow turn +const double constexpr FUZZY_STRAIGHT_ANGLE = 15.; +const double constexpr DISTINCTION_RATIO = 2; + +// Configuration to find representative candidate for turn angle calculations +const double constexpr MINIMAL_SEGMENT_LENGTH = 1.; +const double constexpr DESIRED_SEGMENT_LENGTH = 10.; + EdgeBasedGraphFactory::EdgeBasedGraphFactory( std::shared_ptr node_based_graph, const CompressedEdgeContainer &compressed_edge_container, @@ -361,8 +385,12 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( { util::SimpleLogger().Write() << "generating edge-expanded edges"; - unsigned node_based_edge_counter = 0; - unsigned original_edges_counter = 0; + std::size_t node_based_edge_counter = 0; + std::size_t original_edges_counter = 0; + restricted_turns_counter = 0; + skipped_uturns_counter = 0; + skipped_barrier_turns_counter = 0; + std::size_t compressed = 0; std::ofstream edge_data_file(original_edge_data_filename.c_str(), std::ios::binary); std::ofstream edge_segment_file; @@ -383,11 +411,6 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( // Loop over all turns and generate new set of edges. // Three nested loop look super-linear, but we are dealing with a (kind of) // linear number of turns only. - unsigned restricted_turns_counter = 0; - unsigned skipped_uturns_counter = 0; - unsigned skipped_barrier_turns_counter = 0; - unsigned compressed = 0; - util::Percent progress(m_node_based_graph->GetNumberOfNodes()); #ifdef DEBUG_GEOMETRY @@ -397,79 +420,30 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( for (const auto node_u : util::irange(0u, m_node_based_graph->GetNumberOfNodes())) { // progress.printStatus(node_u); - for (const EdgeID e1 : m_node_based_graph->GetAdjacentEdgeRange(node_u)) + for (const EdgeID edge_form_u : m_node_based_graph->GetAdjacentEdgeRange(node_u)) { - if (m_node_based_graph->GetEdgeData(e1).reversed) + if (m_node_based_graph->GetEdgeData(edge_form_u).reversed) { continue; } ++node_based_edge_counter; - const NodeID node_v = m_node_based_graph->GetTarget(e1); - const NodeID only_restriction_to_node = - m_restriction_map->CheckForEmanatingIsOnlyTurn(node_u, node_v); - const bool is_barrier_node = m_barrier_nodes.find(node_v) != m_barrier_nodes.end(); + auto turn_candidates = getTurnCandidates(node_u, edge_form_u); + turn_candidates = optimizeCandidates(edge_form_u, turn_candidates); + turn_candidates = suppressTurns(edge_form_u, turn_candidates); - for (const EdgeID e2 : m_node_based_graph->GetAdjacentEdgeRange(node_v)) + const NodeID node_v = m_node_based_graph->GetTarget(edge_form_u); + + for (const auto turn : turn_candidates) { - if (m_node_based_graph->GetEdgeData(e2).reversed) - { + if (!turn.valid) continue; - } - const NodeID node_w = m_node_based_graph->GetTarget(e2); - if ((only_restriction_to_node != SPECIAL_NODEID) && - (node_w != only_restriction_to_node)) - { - // We are at an only_-restriction but not at the right turn. - ++restricted_turns_counter; - continue; - } - - if (is_barrier_node) - { - if (node_u != node_w) - { - ++skipped_barrier_turns_counter; - continue; - } - } - else - { - if (node_u == node_w && m_node_based_graph->GetOutDegree(node_v) > 1) - { - auto number_of_emmiting_bidirectional_edges = 0; - for (auto edge : m_node_based_graph->GetAdjacentEdgeRange(node_v)) - { - auto target = m_node_based_graph->GetTarget(edge); - auto reverse_edge = m_node_based_graph->FindEdge(target, node_v); - if (!m_node_based_graph->GetEdgeData(reverse_edge).reversed) - { - ++number_of_emmiting_bidirectional_edges; - } - } - if (number_of_emmiting_bidirectional_edges > 1) - { - ++skipped_uturns_counter; - continue; - } - } - } - - // only add an edge if turn is not a U-turn except when it is - // at the end of a dead-end street - if (m_restriction_map->CheckIfTurnIsRestricted(node_u, node_v, node_w) && - (only_restriction_to_node == SPECIAL_NODEID) && - (node_w != only_restriction_to_node)) - { - // We are at an only_-restriction but not at the right turn. - ++restricted_turns_counter; - continue; - } + const double turn_angle = turn.angle; // only add an edge if turn is not prohibited - const EdgeData &edge_data1 = m_node_based_graph->GetEdgeData(e1); - const EdgeData &edge_data2 = m_node_based_graph->GetEdgeData(e2); + const EdgeData &edge_data1 = m_node_based_graph->GetEdgeData(edge_form_u); + const EdgeData &edge_data2 = m_node_based_graph->GetEdgeData(turn.eid); BOOST_ASSERT(edge_data1.edge_id != edge_data2.edge_id); BOOST_ASSERT(!edge_data1.reversed); @@ -485,23 +459,9 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( speed_profile.traffic_signal_penalty); } - // unpack last node of first segment if packed - const auto first_coordinate = - m_node_info_list[(m_compressed_edge_container.HasEntryForID(e1) - ? m_compressed_edge_container.GetLastEdgeSourceID(e1) - : node_u)]; - - // unpack first node of second segment if packed - const auto third_coordinate = - m_node_info_list[(m_compressed_edge_container.HasEntryForID(e2) - ? m_compressed_edge_container.GetFirstEdgeTargetID(e2) - : node_w)]; - - const double turn_angle = util::coordinate_calculation::computeAngle( - first_coordinate, m_node_info_list[node_v], third_coordinate); - const int turn_penalty = GetTurnPenalty(turn_angle, lua_state); - TurnInstruction turn_instruction = AnalyzeTurn(node_u, node_v, node_w, turn_angle); + const TurnInstruction turn_instruction = turn.instruction; + if (turn_instruction == TurnInstruction::UTurn) { distance += speed_profile.u_turn_penalty; @@ -509,12 +469,10 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( util::DEBUG_UTURN(node_v, m_node_info_list, speed_profile.u_turn_penalty); } - util::DEBUG_TURN(node_v, m_node_info_list, first_coordinate, turn_angle, - turn_penalty); - distance += turn_penalty; - const bool edge_is_compressed = m_compressed_edge_container.HasEntryForID(e1); + const bool edge_is_compressed = + m_compressed_edge_container.HasEntryForID(edge_form_u); if (edge_is_compressed) { @@ -522,7 +480,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( } original_edge_data_vector.emplace_back( - (edge_is_compressed ? m_compressed_edge_container.GetPositionForID(e1) + (edge_is_compressed ? m_compressed_edge_container.GetPositionForID(edge_form_u) : node_v), edge_data1.name_id, turn_instruction, edge_is_compressed, edge_data2.travel_mode); @@ -563,7 +521,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( if (edge_is_compressed) { const auto node_based_edges = - m_compressed_edge_container.GetBucketReference(e1); + m_compressed_edge_container.GetBucketReference(edge_form_u); NodeID previous = node_u; const unsigned node_count = node_based_edges.size() + 1; @@ -638,6 +596,470 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( << " turns over barriers"; } +// requires sorted candidates +std::vector +EdgeBasedGraphFactory::optimizeCandidates(NodeID via_eid, + std::vector turn_candidates) const +{ + BOOST_ASSERT_MSG(std::is_sorted(turn_candidates.begin(), turn_candidates.end(), + [](const TurnCandidate &left, const TurnCandidate &right) + { + return left.angle < right.angle; + }), + "Turn Candidates not sorted by angle."); + if (turn_candidates.size() <= 1) + return turn_candidates; + + const auto getLeft = [&turn_candidates](std::size_t index) + { + return (index + 1) % turn_candidates.size(); + }; + const auto getRight = [&turn_candidates](std::size_t index) + { + return (index + turn_candidates.size() - 1) % turn_candidates.size(); + }; + + // handle availability of multiple u-turns (e.g. street with separated small parking roads) + if (turn_candidates[0].instruction == TurnInstruction::UTurn && turn_candidates[0].angle == 0) + { + if (turn_candidates[getLeft(0)].instruction == TurnInstruction::UTurn) + turn_candidates[getLeft(0)].instruction = TurnInstruction::TurnSharpLeft; + if (turn_candidates[getRight(0)].instruction == TurnInstruction::UTurn) + turn_candidates[getRight(0)].instruction = TurnInstruction::TurnSharpRight; + } + + const auto keepStraight = [](double angle) + { + return std::abs(angle - 180) < 5; + }; + + for (std::size_t turn_index = 0; turn_index < turn_candidates.size(); ++turn_index) + { + auto &turn = turn_candidates[turn_index]; + if (turn.instruction > TurnInstruction::TurnSlightLeft || + turn.instruction == TurnInstruction::UTurn) + continue; + auto &left = turn_candidates[getLeft(turn_index)]; + if (turn.angle == left.angle) + { + util::SimpleLogger().Write(logDEBUG) + << "[warning] conflicting turn angles, identical road duplicated? " + << m_node_info_list[m_node_based_graph->GetTarget(via_eid)].lat << " " + << m_node_info_list[m_node_based_graph->GetTarget(via_eid)].lon << std::endl; + } + if (isConflict(turn.instruction, left.instruction)) + { + // begin of a conflicting region + std::size_t conflict_begin = turn_index; + std::size_t conflict_end = getLeft(turn_index); + std::size_t conflict_size = 2; + while ( + isConflict(turn_candidates[getLeft(conflict_end)].instruction, turn.instruction) && + conflict_size < turn_candidates.size()) + { + conflict_end = getLeft(conflict_end); + ++conflict_size; + } + + turn_index = (conflict_end < conflict_begin) ? turn_candidates.size() : conflict_end; + + if (conflict_size > 3) + { + // check if some turns are invalid to find out about good handling + } + + auto &instruction_left_of_end = turn_candidates[getLeft(conflict_end)].instruction; + auto &instruction_right_of_begin = + turn_candidates[getRight(conflict_begin)].instruction; + auto &candidate_at_end = turn_candidates[conflict_end]; + auto &candidate_at_begin = turn_candidates[conflict_begin]; + if (conflict_size == 2) + { + if (turn.instruction == TurnInstruction::GoStraight) + { + if (instruction_left_of_end != TurnInstruction::TurnSlightLeft && + instruction_right_of_begin != TurnInstruction::TurnSlightRight) + { + std::int32_t resolved_count = 0; + //uses side-effects in resolve + if (!keepStraight(candidate_at_end.angle) && + !resolve(candidate_at_end.instruction, instruction_left_of_end, + RESOLVE_TO_LEFT)) + util::SimpleLogger().Write(logDEBUG) << "[warning] failed to resolve conflict"; + else + ++resolved_count; + //uses side-effects in resolve + if (!keepStraight(candidate_at_begin.angle) && + !resolve(candidate_at_begin.instruction, instruction_right_of_begin, + RESOLVE_TO_RIGHT)) + util::SimpleLogger().Write(logDEBUG) << "[warning] failed to resolve conflict"; + else + ++resolved_count; + if (resolved_count >= 1 && + (!keepStraight(candidate_at_begin.angle) || + !keepStraight(candidate_at_end.angle))) // should always be the + // case, theoretically + continue; + } + } + if (candidate_at_begin.confidence < candidate_at_end.confidence) + { // if right shift is cheaper, or only option + if (resolve(candidate_at_begin.instruction, instruction_right_of_begin, + RESOLVE_TO_RIGHT)) + continue; + else if (resolve(candidate_at_end.instruction, instruction_left_of_end, + RESOLVE_TO_LEFT)) + continue; + } + else + { + if (resolve(candidate_at_end.instruction, instruction_left_of_end, + RESOLVE_TO_LEFT)) + continue; + else if (resolve(candidate_at_begin.instruction, instruction_right_of_begin, + RESOLVE_TO_RIGHT)) + continue; + } + if (isSlightTurn(turn.instruction) || isSharpTurn(turn.instruction)) + { + auto resolve_direction = + (turn.instruction == TurnInstruction::TurnSlightRight || + turn.instruction == TurnInstruction::TurnSharpLeft) + ? RESOLVE_TO_RIGHT + : RESOLVE_TO_LEFT; + if (resolve_direction == RESOLVE_TO_RIGHT && + resolveTransitive( + candidate_at_begin.instruction, instruction_right_of_begin, + turn_candidates[getRight(getRight(conflict_begin))].instruction, + RESOLVE_TO_RIGHT)) + continue; + else if (resolve_direction == RESOLVE_TO_LEFT && + resolveTransitive( + candidate_at_end.instruction, instruction_left_of_end, + turn_candidates[getLeft(getLeft(conflict_end))].instruction, + RESOLVE_TO_LEFT)) + continue; + } + } + else if (conflict_size >= 3) + { + // a conflict of size larger than three cannot be handled with the current + // model. + // Handle it as best as possible and keep the rest of the conflicting turns + if (conflict_size > 3) + { + NodeID conflict_location = m_node_based_graph->GetTarget(via_eid); + util::SimpleLogger().Write(logDEBUG) + << "[warning] found conflict larget than size three at " + << m_node_info_list[conflict_location].lat << ", " + << m_node_info_list[conflict_location].lon; + } + + if (!resolve(candidate_at_begin.instruction, instruction_right_of_begin, + RESOLVE_TO_RIGHT)) + { + if (isSlightTurn(turn.instruction)) + resolveTransitive( + candidate_at_begin.instruction, instruction_right_of_begin, + turn_candidates[getRight(getRight(conflict_begin))].instruction, + RESOLVE_TO_RIGHT); + else if (isSharpTurn(turn.instruction)) + resolveTransitive( + candidate_at_end.instruction, instruction_left_of_end, + turn_candidates[getLeft(getLeft(conflict_end))].instruction, + RESOLVE_TO_LEFT); + } + if (!resolve(candidate_at_end.instruction, instruction_left_of_end, + RESOLVE_TO_LEFT)) + { + if (isSlightTurn(turn.instruction)) + resolveTransitive( + candidate_at_end.instruction, instruction_left_of_end, + turn_candidates[getLeft(getLeft(conflict_end))].instruction, + RESOLVE_TO_LEFT); + else if (isSharpTurn(turn.instruction)) + resolveTransitive( + candidate_at_begin.instruction, instruction_right_of_begin, + turn_candidates[getRight(getRight(conflict_begin))].instruction, + RESOLVE_TO_RIGHT); + } + } + } + } + return turn_candidates; +} + +bool EdgeBasedGraphFactory::isObviousChoice(EdgeID via_eid, + std::size_t turn_index, + const std::vector &turn_candidates) const +{ + const auto getLeft = [&turn_candidates](std::size_t index) + { + return (index + 1) % turn_candidates.size(); + }; + const auto getRight = [&turn_candidates](std::size_t index) + { + return (index + turn_candidates.size() - 1) % turn_candidates.size(); + }; + const auto &candidate = turn_candidates[turn_index]; + const EdgeData &in_data = m_node_based_graph->GetEdgeData(via_eid); + const EdgeData &out_data = m_node_based_graph->GetEdgeData(candidate.eid); + const auto &candidate_to_the_left = turn_candidates[getLeft(turn_index)]; + + const auto &candidate_to_the_right = turn_candidates[getRight(turn_index)]; + + const auto hasValidRatio = [](const TurnCandidate &left, const TurnCandidate ¢er, + const TurnCandidate &right) + { + auto angle_left = (left.angle > 180) ? angularDeviation(left.angle, STRAIGHT_ANGLE) : 180; + auto angle_right = + (right.angle < 180) ? angularDeviation(right.angle, STRAIGHT_ANGLE) : 180; + auto self_angle = angularDeviation(center.angle, STRAIGHT_ANGLE); + return angularDeviation(center.angle, STRAIGHT_ANGLE) < NARROW_TURN_ANGLE && + ((center.angle < STRAIGHT_ANGLE) + ? (angle_right > self_angle && angle_left / self_angle > DISTINCTION_RATIO) + : (angle_left > self_angle && angle_right / self_angle > DISTINCTION_RATIO)); + }; + // only valid turn + + return turn_candidates.size() == 1 || + // only non u-turn + (turn_candidates.size() == 2 && + candidate_to_the_left.instruction == TurnInstruction::UTurn) || // nearly straight turn + angularDeviation(candidate.angle, STRAIGHT_ANGLE) < MAXIMAL_ALLOWED_NO_TURN_DEVIATION || + hasValidRatio(candidate_to_the_left, candidate, candidate_to_the_right) || + (in_data.name_id != 0 && in_data.name_id == out_data.name_id && + angularDeviation(candidate.angle, STRAIGHT_ANGLE) < NARROW_TURN_ANGLE / 2); +} + +std::vector +EdgeBasedGraphFactory::suppressTurns(EdgeID via_eid, + std::vector turn_candidates) const +{ + // remove invalid candidates + BOOST_ASSERT_MSG(std::is_sorted(turn_candidates.begin(), turn_candidates.end(), + [](const TurnCandidate &left, const TurnCandidate &right) + { + return left.angle < right.angle; + }), + "Turn Candidates not sorted by angle."); + const auto end_valid = std::remove_if(turn_candidates.begin(), turn_candidates.end(), + [](const TurnCandidate &candidate) + { + return !candidate.valid; + }); + turn_candidates.erase(end_valid, turn_candidates.end()); + + const auto getLeft = [&turn_candidates](std::size_t index) + { + return (index + 1) % turn_candidates.size(); + }; + const auto getRight = [&turn_candidates](std::size_t index) + { + return (index + turn_candidates.size() - 1) % turn_candidates.size(); + }; + + const EdgeData &in_data = m_node_based_graph->GetEdgeData(via_eid); + + bool has_obvious_with_same_name = false; + double obvious_with_same_name_angle = 0; + for (std::size_t turn_index = 0; turn_index < turn_candidates.size(); ++turn_index) + { + if (m_node_based_graph->GetEdgeData(turn_candidates[turn_index].eid).name_id == + in_data.name_id && + isObviousChoice(via_eid, turn_index, turn_candidates)) + { + has_obvious_with_same_name = true; + obvious_with_same_name_angle = turn_candidates[turn_index].angle; + break; + } + } + + for (std::size_t turn_index = 0; turn_index < turn_candidates.size(); ++turn_index) + { + auto &candidate = turn_candidates[turn_index]; + const EdgeData &out_data = m_node_based_graph->GetEdgeData(candidate.eid); + if (candidate.valid && candidate.instruction != TurnInstruction::UTurn) + { + // TODO road category would be useful to indicate obviousness of turn + // check if turn can be omitted or at least changed + const auto &left = turn_candidates[getLeft(turn_index)]; + const auto &right = turn_candidates[getRight(turn_index)]; + + // make very slight instructions straight, if they are the only valid choice going with + // at most a slight turn + if (candidate.instruction < TurnInstruction::ReachViaLocation && + (!isSlightTurn(getTurnDirection(left.angle)) || !left.valid) && + (!isSlightTurn(getTurnDirection(right.angle)) || !right.valid) && + angularDeviation(candidate.angle, STRAIGHT_ANGLE) < FUZZY_STRAIGHT_ANGLE) + candidate.instruction = TurnInstruction::GoStraight; + + // TODO this smaller comparison for turns is DANGEROUS, has to be revised if turn + // instructions change + if (candidate.instruction < TurnInstruction::ReachViaLocation) + { + if (in_data.travel_mode == + out_data.travel_mode) // make sure to always announce mode changes + { + if (isObviousChoice(via_eid, turn_index, turn_candidates)) + { + + if (in_data.name_id == out_data.name_id) // same road + { + candidate.instruction = TurnInstruction::NoTurn; + } + + else if (!has_obvious_with_same_name) + { + // TODO discuss, we might want to keep the current name of the turn. But + // this would mean emitting a turn when you just keep on a road + candidate.instruction = TurnInstruction::NameChanges; + } + else if (candidate.angle < obvious_with_same_name_angle) + candidate.instruction = TurnInstruction::TurnSlightRight; + else + candidate.instruction = TurnInstruction::TurnSlightLeft; + } + else if (candidate.instruction == TurnInstruction::GoStraight && + has_obvious_with_same_name) + { + if (candidate.angle < obvious_with_same_name_angle) + candidate.instruction = TurnInstruction::TurnSlightRight; + else + candidate.instruction = TurnInstruction::TurnSlightLeft; + } + } + } + } + } + return turn_candidates; +} + +std::vector +EdgeBasedGraphFactory::getTurnCandidates(NodeID from_node, EdgeID via_eid) +{ + std::vector turn_candidates; + const NodeID turn_node = m_node_based_graph->GetTarget(via_eid); + const NodeID only_restriction_to_node = + m_restriction_map->CheckForEmanatingIsOnlyTurn(from_node, turn_node); + const bool is_barrier_node = m_barrier_nodes.find(turn_node) != m_barrier_nodes.end(); + + for (const EdgeID onto_edge : m_node_based_graph->GetAdjacentEdgeRange(turn_node)) + { + bool turn_is_valid = true; + if (m_node_based_graph->GetEdgeData(onto_edge).reversed) + { + turn_is_valid = false; + } + const NodeID to_node = m_node_based_graph->GetTarget(onto_edge); + + if (turn_is_valid && (only_restriction_to_node != SPECIAL_NODEID) && + (to_node != only_restriction_to_node)) + { + // We are at an only_-restriction but not at the right turn. + ++restricted_turns_counter; + turn_is_valid = false; + } + + if (turn_is_valid) + { + if (is_barrier_node) + { + if (from_node != to_node) + { + ++skipped_barrier_turns_counter; + turn_is_valid = false; + } + } + else + { + if (from_node == to_node && m_node_based_graph->GetOutDegree(turn_node) > 1) + { + auto number_of_emmiting_bidirectional_edges = 0; + for (auto edge : m_node_based_graph->GetAdjacentEdgeRange(turn_node)) + { + auto target = m_node_based_graph->GetTarget(edge); + auto reverse_edge = m_node_based_graph->FindEdge(target, turn_node); + if (!m_node_based_graph->GetEdgeData(reverse_edge).reversed) + { + ++number_of_emmiting_bidirectional_edges; + } + } + if (number_of_emmiting_bidirectional_edges > 1) + { + ++skipped_uturns_counter; + turn_is_valid = false; + } + } + } + } + + // only add an edge if turn is not a U-turn except when it is + // at the end of a dead-end street + if (m_restriction_map->CheckIfTurnIsRestricted(from_node, turn_node, to_node) && + (only_restriction_to_node == SPECIAL_NODEID) && (to_node != only_restriction_to_node)) + { + // We are at an only_-restriction but not at the right turn. + ++restricted_turns_counter; + turn_is_valid = false; + } + + // unpack first node of second segment if packed + + const auto first_coordinate = + getRepresentativeCoordinate(from_node, turn_node, via_eid, INVERT); + const auto third_coordinate = + getRepresentativeCoordinate(turn_node, to_node, onto_edge, !INVERT); + + const auto angle = util::coordinate_calculation::computeAngle( + first_coordinate, m_node_info_list[turn_node], third_coordinate); + + const auto turn = AnalyzeTurn(from_node, via_eid, turn_node, onto_edge, to_node, angle); + + auto confidence = getTurnConfidence(angle, turn); + if (!turn_is_valid) + confidence *= 0.8; // makes invalid turns more likely to be resolved in conflicts + + turn_candidates.push_back({onto_edge, turn_is_valid, angle, turn, confidence}); + } + + const auto ByAngle = [](const TurnCandidate &first, const TurnCandidate second) + { + return first.angle < second.angle; + }; + std::sort(std::begin(turn_candidates), std::end(turn_candidates), ByAngle); + + const auto getLeft = [&](std::size_t index) + { + return (index + 1) % turn_candidates.size(); + }; + + const auto getRight = [&](std::size_t index) + { + return (index + turn_candidates.size() - 1) % turn_candidates.size(); + }; + + const auto isInvalidEquivalent = [&](std::size_t this_turn, std::size_t valid_turn) + { + if (!turn_candidates[valid_turn].valid || turn_candidates[this_turn].valid) + return false; + + return angularDeviation(turn_candidates[this_turn].angle, + turn_candidates[valid_turn].angle) < NARROW_TURN_ANGLE; + }; + + for (std::size_t index = 0; index < turn_candidates.size(); ++index) + { + if (isInvalidEquivalent(index, getRight(index)) || + isInvalidEquivalent(index, getLeft(index))) + { + turn_candidates.erase(turn_candidates.begin() + index); + --index; + } + } + return turn_candidates; +}; + int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) const { @@ -658,22 +1080,22 @@ int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) co return 0; } +// node_u -- (edge_1) --> node_v -- (edge_2) --> node_w TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID node_u, + const EdgeID edge1, const NodeID node_v, + const EdgeID edge2, const NodeID node_w, const double angle) const { + + const EdgeData &data1 = m_node_based_graph->GetEdgeData(edge1); + const EdgeData &data2 = m_node_based_graph->GetEdgeData(edge2); if (node_u == node_w) { return TurnInstruction::UTurn; } - const EdgeID edge1 = m_node_based_graph->FindEdge(node_u, node_v); - const EdgeID edge2 = m_node_based_graph->FindEdge(node_v, node_w); - - const EdgeData &data1 = m_node_based_graph->GetEdgeData(edge1); - const EdgeData &data2 = m_node_based_graph->GetEdgeData(edge2); - // roundabouts need to be handled explicitely if (data1.roundabout && data2.roundabout) { @@ -700,19 +1122,89 @@ TurnInstruction EdgeBasedGraphFactory::AnalyzeTurn(const NodeID node_u, } } - // If street names stay the same and if we are certain that it is not a - // a segment of a roundabout, we skip it. - if (data1.name_id == data2.name_id && data1.travel_mode == data2.travel_mode) - { - // TODO: Here we should also do a small graph exploration to check for - // more complex situations - if (0 != data1.name_id || m_node_based_graph->GetOutDegree(node_v) <= 2) - { - return TurnInstruction::NoTurn; - } - } - + // assign a designated turn angle instruction purely based on the angle return getTurnDirection(angle); } + +QueryNode EdgeBasedGraphFactory::getRepresentativeCoordinate(const NodeID src, + const NodeID tgt, + const EdgeID via_eid, + bool INVERTED) const +{ + if (m_compressed_edge_container.HasEntryForID(via_eid)) + { + util::FixedPointCoordinate prev = util::FixedPointCoordinate( + m_node_info_list[INVERTED ? tgt : src].lat, + m_node_info_list[INVERTED ? tgt : src].lon), + cur; + // walk along the edge for the first 5 meters + const auto &geometry = m_compressed_edge_container.GetBucketReference(via_eid); + double dist = 0; + double this_dist = 0; + NodeID prev_id = INVERTED ? tgt : src; + + const auto selectBestCandidate = [this](const NodeID current, const double current_distance, + const NodeID previous, + const double previous_distance) + { + if (current_distance < DESIRED_SEGMENT_LENGTH || + current_distance - DESIRED_SEGMENT_LENGTH < + DESIRED_SEGMENT_LENGTH - previous_distance || + previous_distance < MINIMAL_SEGMENT_LENGTH) + { + return m_node_info_list[current]; + } + else + { + return m_node_info_list[previous]; + } + }; + + if (INVERTED) + { + for (auto itr = geometry.rbegin(), end = geometry.rend(); itr != end; ++itr) + { + const auto compressed_node = *itr; + cur = util::FixedPointCoordinate(m_node_info_list[compressed_node.first].lat, + m_node_info_list[compressed_node.first].lon); + this_dist = util::coordinate_calculation::haversineDistance(prev, cur); + if (dist + this_dist > DESIRED_SEGMENT_LENGTH) + { + return selectBestCandidate(compressed_node.first, dist + this_dist, prev_id, + dist); + } + dist += this_dist; + prev = cur; + prev_id = compressed_node.first; + } + cur = util::FixedPointCoordinate(m_node_info_list[src].lat, m_node_info_list[src].lon); + this_dist = util::coordinate_calculation::haversineDistance(prev, cur); + return selectBestCandidate(src, dist + this_dist, prev_id, dist); + } + else + { + for (auto itr = geometry.begin(), end = geometry.end(); itr != end; ++itr) + { + const auto compressed_node = *itr; + cur = util::FixedPointCoordinate(m_node_info_list[compressed_node.first].lat, + m_node_info_list[compressed_node.first].lon); + this_dist = util::coordinate_calculation::haversineDistance(prev, cur); + if (dist + this_dist > DESIRED_SEGMENT_LENGTH) + { + return selectBestCandidate(compressed_node.first, dist + this_dist, prev_id, + dist); + } + dist += this_dist; + prev = cur; + prev_id = compressed_node.first; + } + cur = util::FixedPointCoordinate(m_node_info_list[tgt].lat, m_node_info_list[tgt].lon); + this_dist = util::coordinate_calculation::haversineDistance(prev, cur); + return selectBestCandidate(tgt, dist + this_dist, prev_id, dist); + } + } + // default: If the edge is very short, or we do not have a compressed geometry + return m_node_info_list[INVERTED ? src : tgt]; } -} +} // namespace extractor +} // namespace osrm From 6b0fe683c9e8a43802ae702bc414a926efcf5f71 Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Mon, 15 Feb 2016 13:25:55 -0800 Subject: [PATCH 165/701] Expose the base type. Going via the operator<< leaves us with invalid geojson. --- include/util/debug_geometry.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index ee3f87dd2..00a3d2fb5 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -120,8 +120,8 @@ inline void DEBUG_GEOMETRY_EDGE(int new_segment_weight, << static_cast( std::floor((segment_length / new_segment_weight) * 10. * 3.6)) << ","; - debug_geometry_file << "\"from_node\": " << previous_osm_node_id - << ", \"to_node\": " << this_osm_node_id << ","; + debug_geometry_file << "\"from_node\": " << OSMNodeID_to_uint64_t(previous_osm_node_id) + << ", \"to_node\": " << OSMNodeID_to_uint64_t(this_osm_node_id) << ","; debug_geometry_file << "\"timestamp\": \"" << dg_time_buffer << "\"},"; debug_geometry_file << "\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[" From 65183e94c6c41c42a33adc33656e6ac5ba6eee2f Mon Sep 17 00:00:00 2001 From: Daniel Patterson Date: Mon, 15 Feb 2016 14:21:18 -0800 Subject: [PATCH 166/701] Use \n instead of std::endl to avoid unnecessary flushing. Cleanup some newlines to avoid blank lines in debug output. --- include/util/debug_geometry.hpp | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/include/util/debug_geometry.hpp b/include/util/debug_geometry.hpp index 00a3d2fb5..26b92ba78 100644 --- a/include/util/debug_geometry.hpp +++ b/include/util/debug_geometry.hpp @@ -100,7 +100,7 @@ inline void DEBUG_GEOMETRY_START(const contractor::ContractorConfig &config) if (dg_output_debug_geometry) { debug_geometry_file.open(config.debug_geometry_path, std::ios::binary); - debug_geometry_file << "{\"type\":\"FeatureCollection\", \"features\":[" << std::endl; + debug_geometry_file << "{\"type\":\"FeatureCollection\", \"features\":[\n"; debug_geometry_file << std::setprecision(10); } } @@ -113,7 +113,14 @@ inline void DEBUG_GEOMETRY_EDGE(int new_segment_weight, if (dg_output_debug_geometry) { if (!dg_first_debug_geometry) - debug_geometry_file << "," << std::endl; + { + debug_geometry_file << ",\n"; + } + else + { + debug_geometry_file << "\n"; + dg_first_debug_geometry = false; + } debug_geometry_file << "{ \"type\":\"Feature\",\"properties\":{\"original\":false, " "\"weight\":" << new_segment_weight / 10.0 << ",\"speed\":" @@ -128,9 +135,7 @@ inline void DEBUG_GEOMETRY_EDGE(int new_segment_weight, << node_lookup_map[previous_osm_node_id].lon / osrm::COORDINATE_PRECISION << "," << node_lookup_map[previous_osm_node_id].lat / osrm::COORDINATE_PRECISION << "],[" << node_lookup_map[this_osm_node_id].lon / osrm::COORDINATE_PRECISION << "," - << node_lookup_map[this_osm_node_id].lat / osrm::COORDINATE_PRECISION << "]]}}" - << std::endl; - dg_first_debug_geometry = false; + << node_lookup_map[this_osm_node_id].lat / osrm::COORDINATE_PRECISION << "]]}}"; } } @@ -138,7 +143,7 @@ inline void DEBUG_GEOMETRY_STOP() { if (dg_output_debug_geometry) { - debug_geometry_file << "\n]}" << std::endl; + debug_geometry_file << "\n]}" << "\n"; debug_geometry_file.close(); } } @@ -149,7 +154,7 @@ inline void DEBUG_TURNS_START(const std::string &debug_turns_path) if (dg_output_turn_debug) { dg_debug_turns_file.open(debug_turns_path); - dg_debug_turns_file << "{\"type\":\"FeatureCollection\", \"features\":[" << std::endl; + dg_debug_turns_file << "{\"type\":\"FeatureCollection\", \"features\":[" << "\n"; } } @@ -161,7 +166,7 @@ inline void DEBUG_SIGNAL(const NodeID node, { const extractor::QueryNode &nodeinfo = m_node_info_list[node]; if (!dg_first_turn_debug) - dg_debug_turns_file << "," << std::endl; + dg_debug_turns_file << "," << "\n"; dg_debug_turns_file << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"trafficlights\",\"cost\":" << traffic_signal_penalty / 10. << "},"; @@ -180,7 +185,7 @@ inline void DEBUG_UTURN(const NodeID node, { const extractor::QueryNode &nodeinfo = m_node_info_list[node]; if (!dg_first_turn_debug) - dg_debug_turns_file << "," << std::endl; + dg_debug_turns_file << "," << "\n"; dg_debug_turns_file << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"trafficlights\",\"cost\":" << traffic_signal_penalty / 10. << "},"; @@ -209,7 +214,7 @@ inline void DEBUG_TURN(const NodeID node, } if (!dg_first_turn_debug) - dg_debug_turns_file << "," << std::endl; + dg_debug_turns_file << "," << "\n"; dg_debug_turns_file << "{ \"type\":\"Feature\",\"properties\":{\"type\":\"turn\",\"cost\":" << turn_penalty / 10. << ",\"turn_angle\":" << static_cast(turn_angle) @@ -225,7 +230,7 @@ inline void DEBUG_TURNS_STOP() { if (dg_output_turn_debug) { - dg_debug_turns_file << "\n]}" << std::endl; + dg_debug_turns_file << "\n]}" << "\n"; dg_debug_turns_file.close(); } } From 2679c1cf0a5630d229f53eaedfe442cb55652c39 Mon Sep 17 00:00:00 2001 From: Moritz Kobitzsch Date: Sat, 13 Feb 2016 19:17:30 +0100 Subject: [PATCH 167/701] correct handling of travel modes --- features/testbot/mode.feature | 16 ++++++ include/engine/guidance/segment_list.hpp | 53 +++++++++---------- .../guidance/textual_route_annotation.hpp | 16 ++++-- .../routing_algorithms/routing_base.hpp | 26 +++++---- src/extractor/edge_based_graph_factory.cpp | 3 +- 5 files changed, 72 insertions(+), 42 deletions(-) diff --git a/features/testbot/mode.feature b/features/testbot/mode.feature index e055799d9..515465701 100644 --- a/features/testbot/mode.feature +++ b/features/testbot/mode.feature @@ -25,6 +25,22 @@ Feature: Testbot - Travel mode When I route I should get | from | to | route | modes | | a | d | foo,foo,foo | 1,3,1 | + | b | d | foo,foo | 3,1 | + + Scenario: Testbot - Compressed Modes + Given the node map + | a | b | c | d | e | f | g | + + And the ways + | nodes | highway | name | + | abc | residential | road | + | cde | river | liquid | + | efg | residential | solid | + + When I route I should get + | from | to | route | modes | turns | + | a | g | road,liquid,solid | 1,3,1 | head,straight,straight,destination | + | c | g | liquid,solid | 3,1 | head,straight,destination | Scenario: Testbot - Modes in each direction, different forward/backward speeds Given the node map diff --git a/include/engine/guidance/segment_list.hpp b/include/engine/guidance/segment_list.hpp index b9be5ad2e..0d7270121 100644 --- a/include/engine/guidance/segment_list.hpp +++ b/include/engine/guidance/segment_list.hpp @@ -154,7 +154,7 @@ void SegmentList::AddLeg(const std::vector &leg_data, const bool is_via_leg, const DataFacade *facade) { - for (const PathData &path_data : leg_data) + for (const auto &path_data : leg_data) { AppendSegment(facade->GetCoordinateOfNode(path_data.node), path_data); } @@ -196,32 +196,7 @@ template void SegmentList::AppendSegment(const FixedPointCoordinate coordinate, const PathData &path_point) { - // if the start location is on top of a node, the first movement might be zero-length, - // in which case we dont' add a new description, but instead update the existing one - if ((1 == segments.size()) && (segments.front().location == coordinate)) - { - if (path_point.segment_duration > 0) - { - segments.front().name_id = path_point.name_id; - segments.front().travel_mode = path_point.travel_mode; - } - return; - } - - // make sure mode changes are announced, even when there otherwise is no turn - const auto getTurn = [](const PathData &path_point, const extractor::TravelMode previous_mode) - { - if (extractor::TurnInstruction::NoTurn == path_point.turn_instruction && - previous_mode != path_point.travel_mode && path_point.segment_duration > 0) - { - return extractor::TurnInstruction::GoStraight; - } - return path_point.turn_instruction; - }; - - // TODO check why we require .front() here - const auto turn = segments.size() ? getTurn(path_point, segments.front().travel_mode) - : path_point.turn_instruction; + const auto turn = path_point.turn_instruction; segments.emplace_back(coordinate, path_point.name_id, path_point.segment_duration, 0.f, turn, path_point.travel_mode); @@ -236,6 +211,30 @@ void SegmentList::Finalize(const bool extract_alternative, if (segments.empty()) return; + // check if first two segments can be merged + BOOST_ASSERT(segments.size() >= 2); + if (segments[0].location == segments[1].location && + segments[1].turn_instruction == extractor::TurnInstruction::NoTurn) + { + segments[0].travel_mode = segments[1].travel_mode; + segments[0].name_id = segments[1].name_id; + // Other data?? + segments.erase(segments.begin() + 1); + } + + // announce mode changes + for (std::size_t i = 0; i + 1 < segments.size(); ++i) + { + auto &segment = segments[i]; + const auto next_mode = segments[i + 1].travel_mode; + if (segment.travel_mode != next_mode && + segment.turn_instruction == extractor::TurnInstruction::NoTurn) + { + segment.turn_instruction = extractor::TurnInstruction::GoStraight; + segment.necessary = true; + } + } + segments[0].length = 0.f; for (const auto i : util::irange(1, segments.size())) { diff --git a/include/engine/guidance/textual_route_annotation.hpp b/include/engine/guidance/textual_route_annotation.hpp index 085f952a9..e9fe49691 100644 --- a/include/engine/guidance/textual_route_annotation.hpp +++ b/include/engine/guidance/textual_route_annotation.hpp @@ -44,8 +44,9 @@ inline util::json::Array AnnotateRoute(const std::vector &ro extractor::TravelMode last_travel_mode = TRAVEL_MODE_DEFAULT; // Generate annotations for every segment - for (const SegmentInformation &segment : route_segments) + for (std::size_t i = 0; i < route_segments.size(); ++i) { + const auto &segment = route_segments[i]; util::json::Array json_instruction_row; extractor::TurnInstruction current_instruction = segment.turn_instruction; if (extractor::isTurnNecessary(current_instruction)) @@ -89,8 +90,17 @@ inline util::json::Array AnnotateRoute(const std::vector &ro json_instruction_row.values.push_back( static_cast(std::round(post_turn_bearing_value))); - json_instruction_row.values.push_back(segment.travel_mode); - last_travel_mode = segment.travel_mode; + if (i + 1 < route_segments.size()) + { + // anounce next travel mode with turn + json_instruction_row.values.push_back(route_segments[i + 1].travel_mode); + last_travel_mode = segment.travel_mode; + } + else + { + json_instruction_row.values.push_back(segment.travel_mode); + last_travel_mode = segment.travel_mode; + } // pre turn bearing const double pre_turn_bearing_value = (segment.pre_turn_bearing / 10.); diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index 9773a7e2d..96851b357 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -99,8 +99,7 @@ template class BasicRoutingInterface (!force_loop_forward || forward_heap.GetData(node).parent != node) // if loops are forced, they are so at the source - && - (!force_loop_reverse || reverse_heap.GetData(node).parent != node)) + && (!force_loop_reverse || reverse_heap.GetData(node).parent != node)) { middle_node_id = node; upper_bound = new_distance; @@ -290,7 +289,10 @@ template class BasicRoutingInterface unsigned name_index = facade->GetNameIndexFromEdgeID(ed.id); const extractor::TurnInstruction turn_instruction = facade->GetTurnInstructionForEdgeID(ed.id); - const extractor::TravelMode travel_mode = facade->GetTravelModeForEdgeID(ed.id); + const extractor::TravelMode travel_mode = + (unpacked_path.empty() && start_traversed_in_reverse) + ? phantom_node_pair.source_phantom.backward_travel_mode + : facade->GetTravelModeForEdgeID(ed.id); if (!facade->EdgeIsCompressed(ed.id)) { @@ -364,11 +366,11 @@ template class BasicRoutingInterface BOOST_ASSERT(i < id_vector.size()); BOOST_ASSERT(phantom_node_pair.target_phantom.forward_travel_mode > 0); unpacked_path.emplace_back( - PathData{id_vector[i], - phantom_node_pair.target_phantom.name_id, - extractor::TurnInstruction::NoTurn, - 0, - phantom_node_pair.target_phantom.forward_travel_mode}); + PathData{id_vector[i], phantom_node_pair.target_phantom.name_id, + extractor::TurnInstruction::NoTurn, 0, + target_traversed_in_reverse + ? phantom_node_pair.target_phantom.backward_travel_mode + : phantom_node_pair.target_phantom.forward_travel_mode}); } } @@ -560,6 +562,7 @@ template class BasicRoutingInterface const bool force_loop_reverse) const { NodeID middle = SPECIAL_NODEID; + distance = INVALID_EDGE_WEIGHT; std::vector> forward_entry_points; std::vector> reverse_entry_points; @@ -602,11 +605,10 @@ template class BasicRoutingInterface } } } - // TODO check if unordered_set might be faster // sort by id and increasing by distance - auto entry_point_comparator = - [](const std::pair &lhs, const std::pair &rhs) + auto entry_point_comparator = [](const std::pair &lhs, + const std::pair &rhs) { return lhs.first < rhs.first || (lhs.first == rhs.first && lhs.second < rhs.second); }; @@ -614,6 +616,8 @@ template class BasicRoutingInterface std::sort(reverse_entry_points.begin(), reverse_entry_points.end(), entry_point_comparator); NodeID last_id = SPECIAL_NODEID; + forward_core_heap.Clear(); + reverse_core_heap.Clear(); for (const auto p : forward_entry_points) { if (p.first == last_id) diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index 12a5490f8..b9cee60d7 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -180,6 +180,7 @@ void EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeI reverse_geometry[geometry_size - 1 - i].second, forward_dist_prefix_sum[i], reverse_dist_prefix_sum[i], m_compressed_edge_container.GetPositionForID(edge_id_1), false, INVALID_COMPONENTID, i, forward_data.travel_mode, reverse_data.travel_mode); + m_edge_based_node_is_startpoint.push_back(forward_data.startpoint || reverse_data.startpoint); current_edge_source_coordinate_id = current_edge_target_coordinate_id; @@ -483,7 +484,7 @@ void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges( (edge_is_compressed ? m_compressed_edge_container.GetPositionForID(edge_form_u) : node_v), edge_data1.name_id, turn_instruction, edge_is_compressed, - edge_data2.travel_mode); + edge_data1.travel_mode); ++original_edges_counter; From b80e96547ebafbf1aa9b31f552461509c7d8ea64 Mon Sep 17 00:00:00 2001 From: karenzshea Date: Fri, 12 Feb 2016 20:11:35 -0500 Subject: [PATCH 168/701] remove ini parsing --- include/util/ini_file.hpp | 28 ------- include/util/routed_options.hpp | 27 ++---- src/tools/contract.cpp | 22 +---- src/tools/extract.cpp | 27 +----- src/tools/routed.cpp | 1 - src/tools/store.cpp | 144 ++++++++++---------------------- 6 files changed, 57 insertions(+), 192 deletions(-) delete mode 100644 include/util/ini_file.hpp diff --git a/include/util/ini_file.hpp b/include/util/ini_file.hpp deleted file mode 100644 index 64c793277..000000000 --- a/include/util/ini_file.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef INI_FILE_HPP -#define INI_FILE_HPP - -#include -#include - -#include -#include - -namespace osrm -{ -namespace util -{ - -// support old capitalized option names by down-casing them with a regex replace -inline std::string read_file_lower_content(const boost::filesystem::path &path) -{ - boost::filesystem::fstream config_stream(path); - std::string ini_file_content((std::istreambuf_iterator(config_stream)), - std::istreambuf_iterator()); - std::transform(std::begin(ini_file_content), std::end(ini_file_content), - std::begin(ini_file_content), ::tolower); - return ini_file_content; -} -} -} - -#endif // INI_FILE_HPP diff --git a/include/util/routed_options.hpp b/include/util/routed_options.hpp index c0b83b45b..0a23bdd2f 100644 --- a/include/util/routed_options.hpp +++ b/include/util/routed_options.hpp @@ -1,13 +1,15 @@ #ifndef ROUTED_OPTIONS_HPP #define ROUTED_OPTIONS_HPP -#include "util/ini_file.hpp" #include "util/version.hpp" #include "util/exception.hpp" #include "util/simple_logger.hpp" #include #include +#include +#include +#include #include #include @@ -139,8 +141,7 @@ GenerateServerProgramOptions(const int argc, "Path to a configuration file") // ("trial", value(&trial)->implicit_value(true), "Quit after initialization"); - // declare a group of options that will be allowed both on command line - // as well as in a config file + // declare a group of options that will be allowed on command line boost::program_options::options_description config_options("Configuration"); config_options.add_options() // ("hsgrdata", value(&paths["hsgrdata"]), ".hsgr file") // @@ -172,8 +173,7 @@ GenerateServerProgramOptions(const int argc, ("max-matching-size", value(&max_locations_map_matching)->default_value(100), "Max. locations supported in map matching query"); - // hidden options, will be allowed both on command line and in config - // file, but will not be shown to the user + // hidden options, will be allowed on command line, but will not be shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options()("base,b", value(&paths["base"]), "base path to .osrm file"); @@ -186,9 +186,6 @@ GenerateServerProgramOptions(const int argc, boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); - boost::program_options::options_description config_file_options; - config_file_options.add(config_options).add(hidden_options); - boost::program_options::options_description visible_options( boost::filesystem::basename(argv[0]) + " []"); visible_options.add(generic_options).add(config_options); @@ -215,20 +212,6 @@ GenerateServerProgramOptions(const int argc, boost::program_options::notify(option_variables); - // parse config file - auto path_iterator = paths.find("config"); - if (path_iterator != paths.end() && boost::filesystem::is_regular_file(path_iterator->second) && - !option_variables.count("base")) - { - SimpleLogger().Write() << "Reading options from: " << path_iterator->second.string(); - std::string ini_file_contents = read_file_lower_content(path_iterator->second); - std::stringstream config_stream(ini_file_contents); - boost::program_options::store(parse_config_file(config_stream, config_file_options), - option_variables); - boost::program_options::notify(option_variables); - return INIT_OK_START_ENGINE; - } - if (1 > requested_num_threads) { throw exception("Number of threads must be a positive number"); diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index a5253decf..cafb26d45 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -28,13 +28,9 @@ parseArguments(int argc, char *argv[], contractor::ContractorConfig &contractor_ { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); - generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( - "config,c", - boost::program_options::value(&contractor_config.config_file_path) - ->default_value("contractor.ini"), - "Path to a configuration file."); + generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message"); - // declare a group of options that will be allowed both on command line and in config file + // declare a group of options that will be allowed on command line boost::program_options::options_description config_options("Configuration"); config_options.add_options()( "profile,p", @@ -62,8 +58,7 @@ parseArguments(int argc, char *argv[], contractor::ContractorConfig &contractor_ "Write out edge-weight debugging geometry data in GeoJSON format to this file"); #endif - // hidden options, will be allowed both on command line and in config file, but will not be - // shown to the user + // hidden options, will be allowed on command line, but will not be shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options()("input,i", boost::program_options::value( &contractor_config.osrm_input_path), @@ -77,9 +72,6 @@ parseArguments(int argc, char *argv[], contractor::ContractorConfig &contractor_ boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); - boost::program_options::options_description config_file_options; - config_file_options.add(config_options).add(hidden_options); - boost::program_options::options_description visible_options( "Usage: " + boost::filesystem::basename(argv[0]) + " [options]"); visible_options.add(generic_options).add(config_options); @@ -92,14 +84,6 @@ parseArguments(int argc, char *argv[], contractor::ContractorConfig &contractor_ .run(), option_variables); - const auto &temp_config_path = option_variables["config"].as(); - if (boost::filesystem::is_regular_file(temp_config_path)) - { - boost::program_options::store(boost::program_options::parse_config_file( - temp_config_path.string().c_str(), cmdline_options, true), - option_variables); - } - if (option_variables.count("version")) { util::SimpleLogger().Write() << OSRM_VERSION; diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index 4550cff4f..0782b0430 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -1,7 +1,6 @@ #include "extractor/extractor.hpp" #include "extractor/extractor_config.hpp" #include "util/simple_logger.hpp" -#include "util/ini_file.hpp" #include "util/version.hpp" #include @@ -27,13 +26,9 @@ parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_con { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); - generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( - "config,c", - boost::program_options::value(&extractor_config.config_file_path) - ->default_value("extractor.ini"), - "Path to a configuration file."); + generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message"); - // declare a group of options that will be allowed both on command line and in config file + // declare a group of options that will be allowed both on command line boost::program_options::options_description config_options("Configuration"); config_options.add_options()( "profile,p", @@ -61,7 +56,7 @@ parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_con "Write out GeoJSON with turn penalty data"); #endif // DEBUG_GEOMETRY - // hidden options, will be allowed both on command line and in config file, but will not be + // hidden options, will be allowed on command line, but will not be // shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options()("input,i", boost::program_options::value( @@ -76,9 +71,6 @@ parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_con boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); - boost::program_options::options_description config_file_options; - config_file_options.add(config_options).add(hidden_options); - boost::program_options::options_description visible_options( boost::filesystem::basename(argv[0]) + " [options]"); visible_options.add(generic_options).add(config_options); @@ -106,19 +98,6 @@ parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_con boost::program_options::notify(option_variables); - // parse config file - if (boost::filesystem::is_regular_file(extractor_config.config_file_path)) - { - util::SimpleLogger().Write() << "Reading options from: " - << extractor_config.config_file_path.string(); - std::string ini_file_contents = - util::read_file_lower_content(extractor_config.config_file_path); - std::stringstream config_stream(ini_file_contents); - boost::program_options::store(parse_config_file(config_stream, config_file_options), - option_variables); - boost::program_options::notify(option_variables); - } - if (!option_variables.count("input")) { util::SimpleLogger().Write() << visible_options; diff --git a/src/tools/routed.cpp b/src/tools/routed.cpp index 81f8eb6aa..960607af1 100644 --- a/src/tools/routed.cpp +++ b/src/tools/routed.cpp @@ -1,5 +1,4 @@ #include "server/server.hpp" -#include "util/ini_file.hpp" #include "util/routed_options.hpp" #include "util/simple_logger.hpp" diff --git a/src/tools/store.cpp b/src/tools/store.cpp index a1dc17c4a..51bc03f38 100644 --- a/src/tools/store.cpp +++ b/src/tools/store.cpp @@ -2,10 +2,9 @@ #include "util/exception.hpp" #include "util/simple_logger.hpp" #include "util/typedefs.hpp" -#include "util/ini_file.hpp" #include "util/version.hpp" -#include +#include #include using namespace osrm; @@ -18,10 +17,7 @@ bool generateDataStoreOptions(const int argc, // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); generic_options.add_options()("version,v", "Show version")("help,h", "Show this help message")( - "springclean,s", "Remove all regions in shared memory")( - "config,c", boost::program_options::value(&paths["config"]) - ->default_value("server.ini"), - "Path to a configuration file"); + "springclean,s", "Remove all regions in shared memory"); // declare a group of options that will be allowed both on command line // as well as in a config file @@ -46,8 +42,7 @@ bool generateDataStoreOptions(const int argc, boost::program_options::value(&paths["timestamp"]), ".timestamp file"); - // hidden options, will be allowed both on command line and in config - // file, but will not be shown to the user + // hidden options, will be allowed on command line but will not be shown to the user boost::program_options::options_description hidden_options("Hidden options"); hidden_options.add_options()( "base,b", boost::program_options::value(&paths["base"]), @@ -61,9 +56,6 @@ bool generateDataStoreOptions(const int argc, boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(config_options).add(hidden_options); - boost::program_options::options_description config_file_options; - config_file_options.add(config_options).add(hidden_options); - boost::program_options::options_description visible_options( boost::filesystem::basename(argv[0]) + " [] "); visible_options.add(generic_options).add(config_options); @@ -97,106 +89,62 @@ bool generateDataStoreOptions(const int argc, boost::program_options::notify(option_variables); - const bool parameter_present = - (paths.find("hsgrdata") != paths.end() && - !paths.find("hsgrdata")->second.string().empty()) || - (paths.find("nodesdata") != paths.end() && - !paths.find("nodesdata")->second.string().empty()) || - (paths.find("edgesdata") != paths.end() && - !paths.find("edgesdata")->second.string().empty()) || - (paths.find("geometry") != paths.end() && - !paths.find("geometry")->second.string().empty()) || - (paths.find("ramindex") != paths.end() && - !paths.find("ramindex")->second.string().empty()) || - (paths.find("fileindex") != paths.end() && - !paths.find("fileindex")->second.string().empty()) || - (paths.find("core") != paths.end() && !paths.find("core")->second.string().empty()) || - (paths.find("timestamp") != paths.end() && - !paths.find("timestamp")->second.string().empty()); + auto path_iterator = paths.find("base"); + BOOST_ASSERT(paths.end() != path_iterator); + std::string base_string = path_iterator->second.string(); - if (parameter_present) + path_iterator = paths.find("hsgrdata"); + if (path_iterator != paths.end()) { - if ((paths.find("config") != paths.end() && - boost::filesystem::is_regular_file(paths.find("config")->second)) || - option_variables.count("base")) - { - util::SimpleLogger().Write(logWARNING) << "conflicting parameters"; - util::SimpleLogger().Write() << visible_options; - return false; - } + path_iterator->second = base_string + ".hsgr"; } - // parse config file - auto path_iterator = paths.find("config"); - if (path_iterator != paths.end() && boost::filesystem::is_regular_file(path_iterator->second) && - !option_variables.count("base")) + path_iterator = paths.find("nodesdata"); + if (path_iterator != paths.end()) { - util::SimpleLogger().Write() << "Reading options from: " << path_iterator->second.string(); - std::string ini_file_contents = util::read_file_lower_content(path_iterator->second); - std::stringstream config_stream(ini_file_contents); - boost::program_options::store(parse_config_file(config_stream, config_file_options), - option_variables); - boost::program_options::notify(option_variables); + path_iterator->second = base_string + ".nodes"; } - else if (option_variables.count("base")) + + path_iterator = paths.find("edgesdata"); + if (path_iterator != paths.end()) { - path_iterator = paths.find("base"); - BOOST_ASSERT(paths.end() != path_iterator); - std::string base_string = path_iterator->second.string(); + path_iterator->second = base_string + ".edges"; + } - path_iterator = paths.find("hsgrdata"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".hsgr"; - } + path_iterator = paths.find("geometry"); + if (path_iterator != paths.end()) + { + path_iterator->second = base_string + ".geometry"; + } - path_iterator = paths.find("nodesdata"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".nodes"; - } + path_iterator = paths.find("ramindex"); + if (path_iterator != paths.end()) + { + path_iterator->second = base_string + ".ramIndex"; + } - path_iterator = paths.find("edgesdata"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".edges"; - } + path_iterator = paths.find("fileindex"); + if (path_iterator != paths.end()) + { + path_iterator->second = base_string + ".fileIndex"; + } - path_iterator = paths.find("geometry"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".geometry"; - } + path_iterator = paths.find("core"); + if (path_iterator != paths.end()) + { + path_iterator->second = base_string + ".core"; + } - path_iterator = paths.find("ramindex"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".ramIndex"; - } + path_iterator = paths.find("namesdata"); + if (path_iterator != paths.end()) + { + path_iterator->second = base_string + ".names"; + } - path_iterator = paths.find("fileindex"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".fileIndex"; - } - - path_iterator = paths.find("core"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".core"; - } - - path_iterator = paths.find("namesdata"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".names"; - } - - path_iterator = paths.find("timestamp"); - if (path_iterator != paths.end()) - { - path_iterator->second = base_string + ".timestamp"; - } + path_iterator = paths.find("timestamp"); + if (path_iterator != paths.end()) + { + path_iterator->second = base_string + ".timestamp"; } path_iterator = paths.find("hsgrdata"); From 3beb8c825b484553537efb7a08508e2ceb0138d2 Mon Sep 17 00:00:00 2001 From: karenzshea Date: Mon, 15 Feb 2016 18:44:04 -0500 Subject: [PATCH 169/701] cf --- src/tools/contract.cpp | 3 +-- src/tools/extract.cpp | 4 +--- src/tools/store.cpp | 4 +--- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index cafb26d45..290e5a919 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -23,8 +23,7 @@ enum class return_code : unsigned exit }; -return_code -parseArguments(int argc, char *argv[], contractor::ContractorConfig &contractor_config) +return_code parseArguments(int argc, char *argv[], contractor::ContractorConfig &contractor_config) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); diff --git a/src/tools/extract.cpp b/src/tools/extract.cpp index 0782b0430..4d9c7e636 100644 --- a/src/tools/extract.cpp +++ b/src/tools/extract.cpp @@ -21,8 +21,7 @@ enum class return_code : unsigned exit }; -return_code -parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_config) +return_code parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_config) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); @@ -113,7 +112,6 @@ parseArguments(int argc, char *argv[], extractor::ExtractorConfig &extractor_con return return_code::ok; } - int main(int argc, char *argv[]) try { util::LogPolicy::GetInstance().Unmute(); diff --git a/src/tools/store.cpp b/src/tools/store.cpp index 51bc03f38..ba01423fa 100644 --- a/src/tools/store.cpp +++ b/src/tools/store.cpp @@ -10,9 +10,7 @@ using namespace osrm; // generate boost::program_options object for the routing part -bool generateDataStoreOptions(const int argc, - const char *argv[], - storage::DataPaths &paths) +bool generateDataStoreOptions(const int argc, const char *argv[], storage::DataPaths &paths) { // declare a group of options that will be allowed only on command line boost::program_options::options_description generic_options("Options"); From 6ac3d902c9ad7321e250da7b160d2cdf43cddec9 Mon Sep 17 00:00:00 2001 From: karenzshea Date: Mon, 15 Feb 2016 20:49:49 -0500 Subject: [PATCH 170/701] update help output test --- features/options/extract/help.feature | 9 +++------ features/options/prepare/help.feature | 9 +++------ features/options/routed/help.feature | 3 --- src/tools/contract.cpp | 4 ++-- 4 files changed, 8 insertions(+), 17 deletions(-) diff --git a/features/options/extract/help.feature b/features/options/extract/help.feature index 722c4dc98..85b97a50a 100644 --- a/features/options/extract/help.feature +++ b/features/options/extract/help.feature @@ -11,13 +11,12 @@ Feature: osrm-extract command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "Configuration:" And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--generate-edge-lookup" And stdout should contain "--small-component-size" - And stdout should contain 20 lines + And stdout should contain 18 lines And it should exit with code 0 Scenario: osrm-extract - Help, short @@ -27,13 +26,12 @@ Feature: osrm-extract command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "Configuration:" And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--generate-edge-lookup" And stdout should contain "--small-component-size" - And stdout should contain 20 lines + And stdout should contain 18 lines And it should exit with code 0 Scenario: osrm-extract - Help, long @@ -43,11 +41,10 @@ Feature: osrm-extract command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "Configuration:" And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--generate-edge-lookup" And stdout should contain "--small-component-size" - And stdout should contain 20 lines + And stdout should contain 18 lines And it should exit with code 0 diff --git a/features/options/prepare/help.feature b/features/options/prepare/help.feature index 34ec3d5f3..6d19dcbeb 100644 --- a/features/options/prepare/help.feature +++ b/features/options/prepare/help.feature @@ -11,14 +11,13 @@ Feature: osrm-prepare command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "Configuration:" And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 21 lines + And stdout should contain 18 lines And it should exit with code 1 Scenario: osrm-prepare - Help, short @@ -28,14 +27,13 @@ Feature: osrm-prepare command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "Configuration:" And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 21 lines + And stdout should contain 18 lines And it should exit with code 0 Scenario: osrm-prepare - Help, long @@ -45,12 +43,11 @@ Feature: osrm-prepare command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "Configuration:" And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 21 lines + And stdout should contain 18 lines And it should exit with code 0 diff --git a/features/options/routed/help.feature b/features/options/routed/help.feature index 34c6ee2a8..e6ddd8bcd 100644 --- a/features/options/routed/help.feature +++ b/features/options/routed/help.feature @@ -11,7 +11,6 @@ Feature: osrm-routed command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "--trial" And stdout should contain "Configuration:" And stdout should contain "--hsgrdata arg" @@ -39,7 +38,6 @@ Feature: osrm-routed command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "--trial" And stdout should contain "Configuration:" And stdout should contain "--hsgrdata arg" @@ -67,7 +65,6 @@ Feature: osrm-routed command line options: help And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" - And stdout should contain "--config" And stdout should contain "--trial" And stdout should contain "Configuration:" And stdout should contain "--hsgrdata arg" diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index 290e5a919..685f36213 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -91,7 +91,7 @@ return_code parseArguments(int argc, char *argv[], contractor::ContractorConfig if (option_variables.count("help")) { - util::SimpleLogger().Write() << "\n" << visible_options; + util::SimpleLogger().Write() << visible_options; return return_code::exit; } @@ -99,7 +99,7 @@ return_code parseArguments(int argc, char *argv[], contractor::ContractorConfig if (!option_variables.count("input")) { - util::SimpleLogger().Write() << "\n" << visible_options; + util::SimpleLogger().Write() << visible_options; return return_code::fail; } From 0ebabfad7387bbd1f060783b1640b2d70d697ec2 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 15 Feb 2016 16:27:18 -0800 Subject: [PATCH 171/701] Finish Travis build as soon as a single job failed. Manually cancelling obviously failing builds is getting cumbersome. Hopefully this will speed things up as a side effect. References: - https://docs.travis-ci.com/user/customizing-the-build/#Fast-Finishing --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index e907dde5f..f8db11431 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,10 +11,11 @@ branches: - develop matrix: + fast_finish: true + include: # 1/ Linux Clang Builds - - os: linux compiler: clang addons: &clang38 From 908a9e9fa1aa818b634b5196758192dfd369ec6c Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 15 Feb 2016 18:56:38 -0800 Subject: [PATCH 172/701] Reorders Travis builds by most likely failing one --- .travis.yml | 86 +++++++++++++++++++++++++++++------------------------ 1 file changed, 47 insertions(+), 39 deletions(-) diff --git a/.travis.yml b/.travis.yml index f8db11431..e7509b1aa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,44 +15,37 @@ matrix: include: - # 1/ Linux Clang Builds + # Debug Builds - os: linux - compiler: clang - addons: &clang38 + compiler: gcc + addons: &gcc5 apt: - sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test'] - packages: ['clang-3.8', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] - env: COMPILER='clang++-3.8' BUILD_TYPE='Release' + sources: ['ubuntu-toolchain-r-test'] + packages: ['g++-5', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] + env: COMPILER='g++-5' BUILD_TYPE='Debug' - - os: linux - compiler: clang - addons: &clang38 - apt: - sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test'] - packages: ['clang-3.8', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] - env: COMPILER='clang++-3.8' BUILD_TYPE='Release' BUILD_SHARED_LIBS=ON - - - os: linux - compiler: clang - addons: *clang38 - env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' - - - # 2/ Linux GCC Builds - os: linux compiler: gcc addons: &gcc48 apt: sources: ['ubuntu-toolchain-r-test'] packages: ['g++-4.8', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] - env: COMPILER='g++-4.8' BUILD_TYPE='Release' - - - os: linux - compiler: gcc - addons: *gcc48 env: COMPILER='g++-4.8' BUILD_TYPE='Debug' + - os: linux + compiler: clang + addons: &clang38 + apt: + sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test'] + packages: ['clang-3.8', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] + env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' + - os: osx + osx_image: xcode7 + compiler: clang + env: COMPILER='clang++' BUILD_TYPE='Debug' + + # Release Builds - os: linux compiler: gcc addons: &gcc5 @@ -61,6 +54,28 @@ matrix: packages: ['g++-5', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] env: COMPILER='g++-5' BUILD_TYPE='Release' + - os: linux + compiler: gcc + addons: &gcc48 + apt: + sources: ['ubuntu-toolchain-r-test'] + packages: ['g++-4.8', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] + env: COMPILER='g++-4.8' BUILD_TYPE='Release' + + - os: linux + compiler: clang + addons: &clang38 + apt: + sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test'] + packages: ['clang-3.8', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] + env: COMPILER='clang++-3.8' BUILD_TYPE='Release' + + - os: osx + osx_image: xcode7 + compiler: clang + env: COMPILER='clang++' BUILD_TYPE='Release' + + # Shared Library - os: linux compiler: gcc addons: &gcc5 @@ -70,9 +85,12 @@ matrix: env: COMPILER='g++-5' BUILD_TYPE='Release' BUILD_SHARED_LIBS=ON - os: linux - compiler: gcc - addons: *gcc5 - env: COMPILER='g++-5' BUILD_TYPE='Debug' + compiler: clang + addons: &clang38 + apt: + sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test'] + packages: ['clang-3.8', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] + env: COMPILER='clang++-3.8' BUILD_TYPE='Release' BUILD_SHARED_LIBS=ON # Disabled until tests all pass on OSX: @@ -93,16 +111,6 @@ matrix: # compiler: clang # env: COMPILER='clang++' BUILD_TYPE='Release' BUILD_SHARED_LIBS=ON - - os: osx - osx_image: xcode7 - compiler: clang - env: COMPILER='clang++' BUILD_TYPE='Debug' - - - os: osx - osx_image: xcode7 - compiler: clang - env: COMPILER='clang++' BUILD_TYPE='Release' - #- os: osx # osx_image: xcode7 # compiler: clang From d38575a011d36bdddf585569cbd77f900a976ecc Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Wed, 17 Feb 2016 12:52:51 +0000 Subject: [PATCH 173/701] include lock_types.hpp --- src/engine/engine.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/engine/engine.cpp b/src/engine/engine.cpp index c9fe44ed1..2949de169 100644 --- a/src/engine/engine.cpp +++ b/src/engine/engine.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include From 47d56676f173d2ea7ab5192d26590b22cf26519f Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Wed, 17 Feb 2016 18:20:27 -0800 Subject: [PATCH 174/701] Don't bounds check by default in static rtree; fixes #1988 --- include/util/static_rtree.hpp | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/include/util/static_rtree.hpp b/include/util/static_rtree.hpp index e59948052..925c8c6eb 100644 --- a/include/util/static_rtree.hpp +++ b/include/util/static_rtree.hpp @@ -133,11 +133,14 @@ class StaticRTree EdgeDataT const ¤t_element = input_data_vector[element_counter]; // Get Hilbert-Value for centroid in mercartor projection + BOOST_ASSERT(current_element.u < coordinate_list.size()); + BOOST_ASSERT(current_element.v < coordinate_list.size()); + FixedPointCoordinate current_centroid = EdgeDataT::Centroid( - FixedPointCoordinate(coordinate_list.at(current_element.u).lat, - coordinate_list.at(current_element.u).lon), - FixedPointCoordinate(coordinate_list.at(current_element.v).lat, - coordinate_list.at(current_element.v).lon)); + FixedPointCoordinate(coordinate_list[current_element.u].lat, + coordinate_list[current_element.u].lon), + FixedPointCoordinate(coordinate_list[current_element.v].lat, + coordinate_list[current_element.v].lon)); current_centroid.lat = COORDINATE_PRECISION * coordinate_calculation::mercator::latToY( current_centroid.lat / COORDINATE_PRECISION); @@ -467,19 +470,22 @@ class StaticRTree { for (uint32_t i = 0; i < element_count; ++i) { + BOOST_ASSERT(objects[i].u < coordinate_list.size()); + BOOST_ASSERT(objects[i].v < coordinate_list.size()); + rectangle.min_lon = - std::min(rectangle.min_lon, std::min(coordinate_list.at(objects[i].u).lon, - coordinate_list.at(objects[i].v).lon)); + std::min(rectangle.min_lon, std::min(coordinate_list[objects[i].u].lon, + coordinate_list[objects[i].v].lon)); rectangle.max_lon = - std::max(rectangle.max_lon, std::max(coordinate_list.at(objects[i].u).lon, - coordinate_list.at(objects[i].v).lon)); + std::max(rectangle.max_lon, std::max(coordinate_list[objects[i].u].lon, + coordinate_list[objects[i].v].lon)); rectangle.min_lat = - std::min(rectangle.min_lat, std::min(coordinate_list.at(objects[i].u).lat, - coordinate_list.at(objects[i].v).lat)); + std::min(rectangle.min_lat, std::min(coordinate_list[objects[i].u].lat, + coordinate_list[objects[i].v].lat)); rectangle.max_lat = - std::max(rectangle.max_lat, std::max(coordinate_list.at(objects[i].u).lat, - coordinate_list.at(objects[i].v).lat)); + std::max(rectangle.max_lat, std::max(coordinate_list[objects[i].u].lat, + coordinate_list[objects[i].v].lat)); } BOOST_ASSERT(rectangle.min_lat != std::numeric_limits::min()); BOOST_ASSERT(rectangle.min_lon != std::numeric_limits::min()); From aae02cd1be7e99eb75117c7d8c9f39b858ad9019 Mon Sep 17 00:00:00 2001 From: Mortada Mehyar Date: Thu, 18 Feb 2016 23:05:11 -0500 Subject: [PATCH 175/701] fixed minor typos --- include/engine/map_matching/bayes_classifier.hpp | 4 ++-- include/engine/plugins/match.hpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/include/engine/map_matching/bayes_classifier.hpp b/include/engine/map_matching/bayes_classifier.hpp index 59b9fb5ae..c77fa843e 100644 --- a/include/engine/map_matching/bayes_classifier.hpp +++ b/include/engine/map_matching/bayes_classifier.hpp @@ -22,7 +22,7 @@ struct NormalDistribution { } - // FIXME implement log-probability version since its faster + // FIXME implement log-probability version since it's faster double density_function(const double val) const { using namespace boost::math::constants; @@ -43,7 +43,7 @@ struct LaplaceDistribution { } - // FIXME implement log-probability version since its faster + // FIXME implement log-probability version since it's faster double density_function(const double val) const { const double x = std::abs(val - location); diff --git a/include/engine/plugins/match.hpp b/include/engine/plugins/match.hpp index 0de44148a..23b113b26 100644 --- a/include/engine/plugins/match.hpp +++ b/include/engine/plugins/match.hpp @@ -46,7 +46,7 @@ template class MapMatchingPlugin : public BasePlugin MapMatchingPlugin(DataFacadeT *facade, const int max_locations_map_matching) : descriptor_string("match"), facade(facade), max_locations_map_matching(max_locations_map_matching), - // the values where derived from fitting a laplace distribution + // the values were derived from fitting a laplace distribution // to the values of manually classified traces classifier(map_matching::LaplaceDistribution(0.005986, 0.016646), map_matching::LaplaceDistribution(0.054385, 0.458432), From 69bc8a8b2214da798ffd39f6ebd98d82a1bf5103 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sun, 21 Feb 2016 01:38:06 +0100 Subject: [PATCH 176/701] Fix unpacking for self-loop nodes not in core. Fixes #1999 --- .../routing_algorithms/routing_base.hpp | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/include/engine/routing_algorithms/routing_base.hpp b/include/engine/routing_algorithms/routing_base.hpp index 96851b357..50c4b284c 100644 --- a/include/engine/routing_algorithms/routing_base.hpp +++ b/include/engine/routing_algorithms/routing_base.hpp @@ -679,18 +679,18 @@ template class BasicRoutingInterface BOOST_ASSERT_MSG((SPECIAL_NODEID != middle && INVALID_EDGE_WEIGHT != distance), "no path found"); - if (distance != forward_core_heap.GetKey(middle) + reverse_core_heap.GetKey(middle)) + // we need to unpack sub path from core heaps + if (facade->IsCoreNode(middle)) { - // self loop - BOOST_ASSERT(forward_core_heap.GetData(middle).parent == middle && - reverse_core_heap.GetData(middle).parent == middle); - packed_leg.push_back(middle); - packed_leg.push_back(middle); - } - else - { - // we need to unpack sub path from core heaps - if (facade->IsCoreNode(middle)) + if (distance != forward_core_heap.GetKey(middle) + reverse_core_heap.GetKey(middle)) + { + // self loop + BOOST_ASSERT(forward_core_heap.GetData(middle).parent == middle && + reverse_core_heap.GetData(middle).parent == middle); + packed_leg.push_back(middle); + packed_leg.push_back(middle); + } + else { std::vector packed_core_leg; RetrievePackedPathFromHeap(forward_core_heap, reverse_core_heap, middle, @@ -701,6 +701,17 @@ template class BasicRoutingInterface packed_leg.insert(packed_leg.end(), packed_core_leg.begin(), packed_core_leg.end()); RetrievePackedPathFromSingleHeap(reverse_heap, packed_core_leg.back(), packed_leg); } + } + else + { + if (distance != forward_heap.GetKey(middle) + reverse_heap.GetKey(middle)) + { + // self loop + BOOST_ASSERT(forward_heap.GetData(middle).parent == middle && + reverse_heap.GetData(middle).parent == middle); + packed_leg.push_back(middle); + packed_leg.push_back(middle); + } else { RetrievePackedPathFromHeap(forward_heap, reverse_heap, middle, packed_leg); From 19ac465fa48577e29dbebb3e7b28e7d4b79d7fed Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 1 Feb 2016 15:36:08 +0100 Subject: [PATCH 177/701] Provides a script to clang-format the repository in parallel --- scripts/format.sh | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100755 scripts/format.sh diff --git a/scripts/format.sh b/scripts/format.sh new file mode 100755 index 000000000..561db8756 --- /dev/null +++ b/scripts/format.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +# Runs the Clang Formatter in parallel on the code base. +# Return codes: +# - 1 there are files to be formatted +# - 0 everything looks fine + +set -eu -o pipefail + +find src include unit_tests example -type f -name '*.hpp' -o -name '*.cpp' \ + | xargs -I{} -P $(nproc) clang-format -i -style=file {} + + +dirty=$(git ls-files --modified) + +if [[ $dirty ]]; then + echo "The following files do not adhere to the .clang-format style file:" + echo $dirty + exit 1 +else + exit 0 +fi From 0b45678cccaa52150a167a5e99be592567403dad Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 1 Feb 2016 15:39:06 +0100 Subject: [PATCH 178/701] Adapts Travis to run the formatter script checking for violations --- .travis.yml | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index e7509b1aa..6f0dc7ecb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,7 +38,7 @@ matrix: apt: sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test'] packages: ['clang-3.8', 'libbz2-dev', 'libstxxl-dev', 'libstxxl1', 'libxml2-dev', 'libzip-dev', 'lua5.1', 'liblua5.1-0-dev', 'rubygems-integration', 'libtbb-dev', 'libgdal-dev', 'libluabind-dev', 'libboost-all-dev'] - env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' + env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' RUN_CLANG_FORMAT=ON - os: osx osx_image: xcode7 @@ -139,7 +139,7 @@ before_script: - rvm use 1.9.3 - gem install bundler - bundle install - - mkdir build && cd build + - mkdir build && pushd build - export CXX=${COMPILER} - export OSRM_PORT=5000 OSRM_TIMEOUT=60 - cmake .. -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS:-OFF} -DBUILD_TOOLS=1 @@ -156,10 +156,15 @@ script: - ./extractor-tests - ./engine-tests - ./util-tests - - cd .. + - popd - cucumber -p verify - make -C test/data - - mkdir example/build && cd example/build + - mkdir example/build && pushd example/build - cmake .. - make - ./osrm-example ../../test/data/berlin-latest.osrm + - popd + - | + if [ -n "$RUN_CLANG_FORMAT" ]; then + ./scripts/format.sh + fi From 47a9981571736c23bef9ffa0a66498e2b08e0a01 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Thu, 25 Feb 2016 01:08:23 +0100 Subject: [PATCH 179/701] Disabling style failing the tests for now --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 6f0dc7ecb..a460bb4e5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -166,5 +166,5 @@ script: - popd - | if [ -n "$RUN_CLANG_FORMAT" ]; then - ./scripts/format.sh + ./scripts/format.sh || true # we don't want to fail just yet fi From 04765d82ba563b8725d72117f0743331e97224df Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 26 Feb 2016 06:38:26 +0100 Subject: [PATCH 180/701] Fixes undefined behavior via One-Definition-Rule violations Heuristic find . -type f -name '*.hpp' |xargs ag -B 1 '^([^inline][a-zA-Z0-9_&\*::])+ (.*)\((.*)\)$' --- include/extractor/extraction_helper_functions.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/extractor/extraction_helper_functions.hpp b/include/extractor/extraction_helper_functions.hpp index b7df3ca9b..cbd5a64b5 100644 --- a/include/extractor/extraction_helper_functions.hpp +++ b/include/extractor/extraction_helper_functions.hpp @@ -17,7 +17,7 @@ namespace osrm namespace extractor { -bool simple_duration_is_valid(const std::string &s) +inline bool simple_duration_is_valid(const std::string &s) { boost::regex simple_format( "((\\d|\\d\\d):(\\d|\\d\\d):(\\d|\\d\\d))|((\\d|\\d\\d):(\\d|\\d\\d))|(\\d|\\d\\d)", @@ -32,7 +32,7 @@ bool simple_duration_is_valid(const std::string &s) return false; } -bool iso_8601_duration_is_valid(const std::string &s) +inline bool iso_8601_duration_is_valid(const std::string &s) { util::iso_8601_grammar iso_parser; const bool result = boost::spirit::qi::parse(s.begin(), s.end(), iso_parser); @@ -45,12 +45,12 @@ bool iso_8601_duration_is_valid(const std::string &s) return false; } -bool durationIsValid(const std::string &s) +inline bool durationIsValid(const std::string &s) { return simple_duration_is_valid(s) || iso_8601_duration_is_valid(s); } -unsigned parseDuration(const std::string &s) +inline unsigned parseDuration(const std::string &s) { if (simple_duration_is_valid(s)) { From 96a5e594b3e22cdbb370020c62bbc79ce6c81717 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 8 Feb 2016 12:18:16 -0800 Subject: [PATCH 181/701] Removes profiles from osrm-prepare, only needed in osrm-extract. Fixes #1950. --- include/contractor/contractor_config.hpp | 1 - src/tools/contract.cpp | 13 ------------- 2 files changed, 14 deletions(-) diff --git a/include/contractor/contractor_config.hpp b/include/contractor/contractor_config.hpp index 595dfecd9..846a99e55 100644 --- a/include/contractor/contractor_config.hpp +++ b/include/contractor/contractor_config.hpp @@ -28,7 +28,6 @@ struct ContractorConfig boost::filesystem::path config_file_path; boost::filesystem::path osrm_input_path; - boost::filesystem::path profile_path; std::string level_output_path; std::string core_output_path; diff --git a/src/tools/contract.cpp b/src/tools/contract.cpp index 685f36213..41add3c04 100644 --- a/src/tools/contract.cpp +++ b/src/tools/contract.cpp @@ -32,10 +32,6 @@ return_code parseArguments(int argc, char *argv[], contractor::ContractorConfig // declare a group of options that will be allowed on command line boost::program_options::options_description config_options("Configuration"); config_options.add_options()( - "profile,p", - boost::program_options::value(&contractor_config.profile_path) - ->default_value("profile.lua"), - "Path to LUA routing profile")( "threads,t", boost::program_options::value(&contractor_config.requested_num_threads) ->default_value(tbb::task_scheduler_init::default_num_threads()), @@ -147,17 +143,8 @@ int main(int argc, char *argv[]) try return EXIT_FAILURE; } - if (!boost::filesystem::is_regular_file(contractor_config.profile_path)) - { - util::SimpleLogger().Write(logWARNING) - << "Profile " << contractor_config.profile_path.string() << " not found!"; - return EXIT_FAILURE; - } - util::SimpleLogger().Write() << "Input file: " << contractor_config.osrm_input_path.filename().string(); - util::SimpleLogger().Write() << "Profile: " - << contractor_config.profile_path.filename().string(); util::SimpleLogger().Write() << "Threads: " << contractor_config.requested_num_threads; tbb::task_scheduler_init init(contractor_config.requested_num_threads); From 085bab749f0ba6f04e78ffa8ae4f6d499d7e7d19 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sun, 14 Feb 2016 19:35:37 +0100 Subject: [PATCH 182/701] osrm-prepare -> osrm-contract --- CMakeLists.txt | 8 ++--- .../{prepare => contract}/files.feature | 15 +++------ .../{prepare => contract}/help.feature | 32 ++++++++----------- .../{prepare => contract}/invalid.feature | 6 ++-- .../{prepare => contract}/version.feature | 10 +++--- features/raster/weights.feature | 6 ++-- features/step_definitions/options.rb | 4 +-- features/support/data.rb | 4 +-- features/support/env.rb | 2 +- features/support/exceptions.rb | 2 +- features/support/hash.rb | 2 +- features/support/run.rb | 2 +- 12 files changed, 41 insertions(+), 52 deletions(-) rename features/options/{prepare => contract}/files.feature (52%) rename features/options/{prepare => contract}/help.feature (61%) rename features/options/{prepare => contract}/invalid.feature (60%) rename features/options/{prepare => contract}/version.feature (74%) diff --git a/CMakeLists.txt b/CMakeLists.txt index efc6d36bb..f95c6b201 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -76,7 +76,7 @@ add_dependencies(UTIL FingerPrintConfigure) set_target_properties(UTIL PROPERTIES LINKER_LANGUAGE CXX) add_executable(osrm-extract src/tools/extract.cpp) -add_executable(osrm-prepare src/tools/contract.cpp) +add_executable(osrm-contract src/tools/contract.cpp) add_executable(osrm-routed src/tools/routed.cpp $ $) add_executable(osrm-datastore src/tools/store.cpp $) add_library(osrm src/osrm/osrm.cpp $ $) @@ -287,7 +287,7 @@ endif() # Binaries target_link_libraries(osrm-datastore osrm_store ${Boost_LIBRARIES}) target_link_libraries(osrm-extract osrm_extract ${Boost_LIBRARIES}) -target_link_libraries(osrm-prepare osrm_contract ${Boost_LIBRARIES}) +target_link_libraries(osrm-contract osrm_contract ${Boost_LIBRARIES}) target_link_libraries(osrm-routed osrm ${Boost_LIBRARIES} ${OPTIONAL_SOCKET_LIBS} ${ZLIB_LIBRARY}) set(EXTRACTOR_LIBRARIES @@ -372,7 +372,7 @@ endif() # (i.e., from /usr/local/bin/) the linker can find library dependencies. For # more info see http://www.cmake.org/Wiki/CMake_RPATH_handling set_property(TARGET osrm-extract PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) -set_property(TARGET osrm-prepare PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) +set_property(TARGET osrm-contract PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) set_property(TARGET osrm-datastore PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) set_property(TARGET osrm-routed PROPERTY INSTALL_RPATH_USE_LINK_PATH TRUE) @@ -390,7 +390,7 @@ install(FILES ${ContractorHeader} DESTINATION include/osrm/contractor) install(FILES ${LibraryGlob} DESTINATION include/osrm) install(FILES ${VariantGlob} DESTINATION include/variant) install(TARGETS osrm-extract DESTINATION bin) -install(TARGETS osrm-prepare DESTINATION bin) +install(TARGETS osrm-contract DESTINATION bin) install(TARGETS osrm-datastore DESTINATION bin) install(TARGETS osrm-routed DESTINATION bin) install(TARGETS osrm DESTINATION lib) diff --git a/features/options/prepare/files.feature b/features/options/contract/files.feature similarity index 52% rename from features/options/prepare/files.feature rename to features/options/contract/files.feature index 6e82a6b1b..5e50e14f2 100644 --- a/features/options/prepare/files.feature +++ b/features/options/contract/files.feature @@ -1,5 +1,5 @@ @prepare @options @files -Feature: osrm-prepare command line options: files +Feature: osrm-contract command line options: files # expansions: # {extracted_base} => path to current extracted input file # {profile} => path to current profile script @@ -13,18 +13,13 @@ Feature: osrm-prepare command line options: files | ab | And the data has been extracted - Scenario: osrm-prepare - Passing base file - When I run "osrm-prepare {extracted_base}.osrm --profile {profile}" + Scenario: osrm-contract - Passing base file + When I run "osrm-contract {extracted_base}.osrm" Then stderr should be empty And it should exit with code 0 - Scenario: osrm-prepare - Order of options should not matter - When I run "osrm-prepare --profile {profile} {extracted_base}.osrm" - Then stderr should be empty - And it should exit with code 0 - - Scenario: osrm-prepare - Missing input file - When I run "osrm-prepare over-the-rainbow.osrm --profile {profile}" + Scenario: osrm-contract - Missing input file + When I run "osrm-contract over-the-rainbow.osrm" And stderr should contain "over-the-rainbow.osrm" And stderr should contain "not found" And it should exit with code 1 diff --git a/features/options/prepare/help.feature b/features/options/contract/help.feature similarity index 61% rename from features/options/prepare/help.feature rename to features/options/contract/help.feature index 6d19dcbeb..4079efcbe 100644 --- a/features/options/prepare/help.feature +++ b/features/options/contract/help.feature @@ -1,53 +1,47 @@ @prepare @options @help -Feature: osrm-prepare command line options: help +Feature: osrm-contract command line options: help - Background: - Given the profile "testbot" - - Scenario: osrm-prepare - Help should be shown when no options are passed - When I run "osrm-prepare" + Scenario: osrm-contract - Help should be shown when no options are passed + When I run "osrm-contract" Then stderr should be empty - And stdout should contain "osrm-prepare [options]:" + And stdout should contain "osrm-contract [options]:" And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" And stdout should contain "Configuration:" - And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 18 lines + And stdout should contain 17 lines And it should exit with code 1 - Scenario: osrm-prepare - Help, short - When I run "osrm-prepare -h" + Scenario: osrm-contract - Help, short + When I run "osrm-contract -h" Then stderr should be empty - And stdout should contain "osrm-prepare [options]:" + And stdout should contain "osrm-contract [options]:" And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" And stdout should contain "Configuration:" - And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 18 lines + And stdout should contain 17 lines And it should exit with code 0 - Scenario: osrm-prepare - Help, long - When I run "osrm-prepare --help" + Scenario: osrm-contract - Help, long + When I run "osrm-contract --help" Then stderr should be empty - And stdout should contain "osrm-prepare [options]:" + And stdout should contain "osrm-contract [options]:" And stdout should contain "Options:" And stdout should contain "--version" And stdout should contain "--help" And stdout should contain "Configuration:" - And stdout should contain "--profile" And stdout should contain "--threads" And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 18 lines + And stdout should contain 17 lines And it should exit with code 0 diff --git a/features/options/prepare/invalid.feature b/features/options/contract/invalid.feature similarity index 60% rename from features/options/prepare/invalid.feature rename to features/options/contract/invalid.feature index 7450390a8..38ee3ace9 100644 --- a/features/options/prepare/invalid.feature +++ b/features/options/contract/invalid.feature @@ -1,11 +1,11 @@ @prepare @options @invalid -Feature: osrm-prepare command line options: invalid options +Feature: osrm-contract command line options: invalid options Background: Given the profile "testbot" - Scenario: osrm-prepare - Non-existing option - When I run "osrm-prepare --fly-me-to-the-moon" + Scenario: osrm-contract - Non-existing option + When I run "osrm-contract --fly-me-to-the-moon" Then stdout should be empty And stderr should contain "option" And stderr should contain "fly-me-to-the-moon" diff --git a/features/options/prepare/version.feature b/features/options/contract/version.feature similarity index 74% rename from features/options/prepare/version.feature rename to features/options/contract/version.feature index 7a821c626..be99bbed1 100644 --- a/features/options/prepare/version.feature +++ b/features/options/contract/version.feature @@ -1,5 +1,5 @@ @prepare @options @version -Feature: osrm-prepare command line options: version +Feature: osrm-contract command line options: version # the regex will match these two formats: # v0.3.7.0 # this is the normal format when you build from a git clone # -128-NOTFOUND # if you build from a shallow clone (used on Travis) @@ -7,15 +7,15 @@ Feature: osrm-prepare command line options: version Background: Given the profile "testbot" - Scenario: osrm-prepare - Version, short - When I run "osrm-prepare --v" + Scenario: osrm-contract - Version, short + When I run "osrm-contract --v" Then stderr should be empty And stdout should contain 1 line And stdout should contain /(v\d{1,2}\.\d{1,2}\.\d{1,2}|\w*-\d+-\w+)/ And it should exit with code 0 - Scenario: osrm-prepare - Version, long - When I run "osrm-prepare --version" + Scenario: osrm-contract - Version, long + When I run "osrm-contract --version" Then stderr should be empty And stdout should contain 1 line And stdout should contain /(v\d{1,2}\.\d{1,2}\.\d{1,2}|\w*-\d+-\w+)/ diff --git a/features/raster/weights.feature b/features/raster/weights.feature index 1d521d076..ade8458f5 100644 --- a/features/raster/weights.feature +++ b/features/raster/weights.feature @@ -32,7 +32,7 @@ Feature: Raster - weights Scenario: Weighting not based on raster sources Given the profile "testbot" When I run "osrm-extract {osm_base}.osm -p {profile}" - And I run "osrm-prepare {osm_base}.osm" + And I run "osrm-contract {osm_base}.osm" And I route I should get | from | to | route | speed | | a | b | ab | 36 km/h | @@ -45,7 +45,7 @@ Feature: Raster - weights Given the profile "rasterbot" When I run "osrm-extract {osm_base}.osm -p {profile}" Then stdout should contain "evaluating segment" - And I run "osrm-prepare {osm_base}.osm" + And I run "osrm-contract {osm_base}.osm" And I route I should get | from | to | route | speed | | a | b | ab | 8 km/h | @@ -63,7 +63,7 @@ Feature: Raster - weights Given the profile "rasterbot-interp" When I run "osrm-extract {osm_base}.osm -p {profile}" Then stdout should contain "evaluating segment" - And I run "osrm-prepare {osm_base}.osm" + And I run "osrm-contract {osm_base}.osm" And I route I should get | from | to | route | speed | | a | b | ab | 8 km/h | diff --git a/features/step_definitions/options.rb b/features/step_definitions/options.rb index 62329d514..6a033803d 100644 --- a/features/step_definitions/options.rb +++ b/features/step_definitions/options.rb @@ -10,8 +10,8 @@ When(/^I run "osrm\-extract\s?(.*?)"$/) do |options| run_bin 'osrm-extract', options end -When(/^I run "osrm\-prepare\s?(.*?)"$/) do |options| - run_bin 'osrm-prepare', options +When(/^I run "osrm\-contract\s?(.*?)"$/) do |options| + run_bin 'osrm-contract', options end When(/^I run "osrm\-datastore\s?(.*?)"$/) do |options| diff --git a/features/support/data.rb b/features/support/data.rb index 7fc31dc68..c0f46967e 100644 --- a/features/support/data.rb +++ b/features/support/data.rb @@ -277,9 +277,9 @@ def prepare_data Dir.chdir TEST_FOLDER do log_preprocess_info log "== Preparing #{extracted_file}.osm...", :preprocess - unless system "#{LOAD_LIBRARIES}#{BIN_PATH}/osrm-prepare #{extracted_file}.osrm --profile #{PROFILES_PATH}/#{@profile}.lua >>#{PREPROCESS_LOG_FILE} 2>&1" + unless system "#{LOAD_LIBRARIES}#{BIN_PATH}/osrm-contract #{extracted_file}.osrm >>#{PREPROCESS_LOG_FILE} 2>&1" log "*** Exited with code #{$?.exitstatus}.", :preprocess - raise PrepareError.new $?.exitstatus, "osrm-prepare exited with code #{$?.exitstatus}." + raise PrepareError.new $?.exitstatus, "osrm-contract exited with code #{$?.exitstatus}." end begin ["osrm.hsgr","osrm.fileIndex","osrm.geometry","osrm.nodes","osrm.ramIndex","osrm.core","osrm.edges"].each do |file| diff --git a/features/support/env.rb b/features/support/env.rb index 35d23eccb..80bda262d 100644 --- a/features/support/env.rb +++ b/features/support/env.rb @@ -81,7 +81,7 @@ def verify_osrm_is_not_running end def verify_existance_of_binaries - ["osrm-extract", "osrm-prepare", "osrm-routed"].each do |bin| + ["osrm-extract", "osrm-contract", "osrm-routed"].each do |bin| unless File.exists? "#{BIN_PATH}/#{bin}#{EXE}" raise "*** #{BIN_PATH}/#{bin}#{EXE} is missing. Build failed?" end diff --git a/features/support/exceptions.rb b/features/support/exceptions.rb index d04dc385c..e3d37b30a 100644 --- a/features/support/exceptions.rb +++ b/features/support/exceptions.rb @@ -45,7 +45,7 @@ end class PrepareError < OSRMError def initialize code, msg - super 'osrm-prepare', code, msg, PREPROCESS_LOG_FILE, 3 + super 'osrm-contract', code, msg, PREPROCESS_LOG_FILE, 3 end end diff --git a/features/support/hash.rb b/features/support/hash.rb index 6980b6645..cfc1fe758 100644 --- a/features/support/hash.rb +++ b/features/support/hash.rb @@ -37,7 +37,7 @@ def bin_extract_hash end def bin_prepare_hash - @bin_prepare_hash ||= hash_of_files "#{BIN_PATH}/osrm-prepare#{EXE}" + @bin_prepare_hash ||= hash_of_files "#{BIN_PATH}/osrm-contract#{EXE}" end def bin_routed_hash diff --git a/features/support/run.rb b/features/support/run.rb index 4c77adfcb..5f86a9ecb 100644 --- a/features/support/run.rb +++ b/features/support/run.rb @@ -25,4 +25,4 @@ def run_bin bin, options @stderr = File.read 'error.log' @exit_code = $?.exitstatus end -end \ No newline at end of file +end From 8feb300d15bf30acfaf3c0973bf941f5b9bc576d Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Sun, 14 Feb 2016 19:36:11 +0100 Subject: [PATCH 183/701] Add changelog entry for breakage --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..3a386d3b6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +# 5.0.0 + - Renmaed osrm-prepare into osrm-contract + - osrm-contract does not need a profile parameter anymore From 7fb5b9886e0e0fce486134ee190b9e31d1bcaf61 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Mon, 15 Feb 2016 20:05:23 +0100 Subject: [PATCH 184/701] Fix test data prepare --- test/data/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/data/Makefile b/test/data/Makefile index a21afa7f5..318360380 100755 --- a/test/data/Makefile +++ b/test/data/Makefile @@ -2,7 +2,7 @@ BERLIN_URL:=https://s3.amazonaws.com/mapbox/node-osrm/testing/berlin-latest.osm. TOOL_ROOT:=../../build PROFILE_ROOT:=../../profiles OSRM_EXTRACT:=$(TOOL_ROOT)/osrm-extract -OSRM_PREPARE:=$(TOOL_ROOT)/osrm-prepare +OSRM_PREPARE:=$(TOOL_ROOT)/osrm-contract PROFILE:=$(PROFILE_ROOT)/car.lua all: berlin-latest.osrm.hsgr @@ -21,7 +21,7 @@ berlin-latest.osrm: berlin-latest.osm.pbf $(PROFILE) $(OSRM_EXTRACT) berlin-latest.osrm.hsgr: berlin-latest.osrm $(PROFILE) $(OSRM_PREPARE) @echo "Running osrm-prepare..." - $(OSRM_PREPARE) berlin-latest.osrm -p $(PROFILE) + $(OSRM_CONTRACT) berlin-latest.osrm -p $(PROFILE) checksum: md5sum berlin-latest.osm.pbf > data.md5sum From a27902205b767ff3e1370872f4d6c90470a5e503 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 15 Feb 2016 16:15:34 -0800 Subject: [PATCH 185/701] Fixes spelling in changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a386d3b6..d3b55596e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,3 @@ # 5.0.0 - - Renmaed osrm-prepare into osrm-contract + - Renamed osrm-prepare into osrm-contract - osrm-contract does not need a profile parameter anymore From 52a8bb414c32f44b09e3569d0f1435a546a1595c Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 15 Feb 2016 16:16:24 -0800 Subject: [PATCH 186/701] Fixes Rakefile wrt. osrm-contract --- Rakefile | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Rakefile b/Rakefile index 1c848bb07..7b3d905a7 100644 --- a/Rakefile +++ b/Rakefile @@ -98,7 +98,7 @@ task :crop do end desc "Reprocess OSM data." -task :process => [:extract,:prepare] do +task :process => [:extract,:contract] do end desc "Extract OSM data." @@ -108,10 +108,10 @@ task :extract do end end -desc "Prepare OSM data." -task :prepare do +desc "Contract OSM data." +task :contract do Dir.chdir DATA_FOLDER do - raise "Error while preparing data." unless system "../#{BUILD_FOLDER}/osrm-prepare #{osm_data_area_name}.osrm --profile ../profiles/#{PROFILE}.lua" + raise "Error while contracting data." unless system "../#{BUILD_FOLDER}/osrm-contract #{osm_data_area_name}.osrm" end end @@ -161,17 +161,17 @@ task :down do end end -desc "Kill all osrm-extract, osrm-prepare and osrm-routed processes." +desc "Kill all osrm-extract, osrm-contract and osrm-routed processes." task :kill do each_process('osrm-routed') { |pid,state| Process.kill 'KILL', pid } - each_process('osrm-prepare') { |pid,state| Process.kill 'KILL', pid } + each_process('osrm-contract') { |pid,state| Process.kill 'KILL', pid } each_process('osrm-extract') { |pid,state| Process.kill 'KILL', pid } wait_for_shutdown 'osrm-routed' - wait_for_shutdown 'osrm-prepare' + wait_for_shutdown 'osrm-contract' wait_for_shutdown 'osrm-extract' end -desc "Get PIDs of all osrm-extract, osrm-prepare and osrm-routed processes." +desc "Get PIDs of all osrm-extract, osrm-contract and osrm-routed processes." task :pid do each_process 'osrm-routed' do |pid,state| puts "#{pid}\t#{state}" From da88cb6a4395002f8756e015508fa2284a657e24 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 15 Feb 2016 16:16:49 -0800 Subject: [PATCH 187/701] Extractor comments wrt. osrm-contract --- src/extractor/extractor.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/extractor/extractor.cpp b/src/extractor/extractor.cpp index 3d239893c..772d4b54d 100644 --- a/src/extractor/extractor.cpp +++ b/src/extractor/extractor.cpp @@ -67,8 +67,8 @@ namespace extractor * * The result of this process are the following files: * .names : Names of all streets, stored as long consecutive string with prefix sum based index - * .osrm : Nodes and edges in a intermediate format that easy to digest for osrm-prepare - * .restrictions : Turn restrictions that are used my osrm-prepare to construct the edge-expanded + * .osrm : Nodes and edges in a intermediate format that easy to digest for osrm-contract + * .restrictions : Turn restrictions that are used by osrm-contract to construct the edge-expanded * graph * */ @@ -304,7 +304,7 @@ int Extractor::run() << "Expansion : " << (number_of_node_based_nodes / TIMER_SEC(expansion)) << " nodes/sec and " << ((max_edge_id + 1) / TIMER_SEC(expansion)) << " edges/sec"; util::SimpleLogger().Write() << "To prepare the data for routing, run: " - << "./osrm-prepare " << config.output_file_name << std::endl; + << "./osrm-contract " << config.output_file_name << std::endl; } catch (const std::exception &e) { From 152f739527a7ec7c4706b15956215be48b443acd Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Mon, 15 Feb 2016 16:17:08 -0800 Subject: [PATCH 188/701] Adapts test data Makefile to no longer pass parameters to osrm-contract --- test/data/Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/data/Makefile b/test/data/Makefile index 318360380..075abe406 100755 --- a/test/data/Makefile +++ b/test/data/Makefile @@ -2,7 +2,7 @@ BERLIN_URL:=https://s3.amazonaws.com/mapbox/node-osrm/testing/berlin-latest.osm. TOOL_ROOT:=../../build PROFILE_ROOT:=../../profiles OSRM_EXTRACT:=$(TOOL_ROOT)/osrm-extract -OSRM_PREPARE:=$(TOOL_ROOT)/osrm-contract +OSRM_CONTRACT:=$(TOOL_ROOT)/osrm-contract PROFILE:=$(PROFILE_ROOT)/car.lua all: berlin-latest.osrm.hsgr @@ -19,9 +19,9 @@ berlin-latest.osrm: berlin-latest.osm.pbf $(PROFILE) $(OSRM_EXTRACT) @echo "Running osrm-extract..." $(OSRM_EXTRACT) berlin-latest.osm.pbf -p $(PROFILE) -berlin-latest.osrm.hsgr: berlin-latest.osrm $(PROFILE) $(OSRM_PREPARE) - @echo "Running osrm-prepare..." - $(OSRM_CONTRACT) berlin-latest.osrm -p $(PROFILE) +berlin-latest.osrm.hsgr: berlin-latest.osrm $(PROFILE) $(OSRM_CONTRACT) + @echo "Running osrm-contract..." + $(OSRM_CONTRACT) berlin-latest.osrm checksum: md5sum berlin-latest.osm.pbf > data.md5sum From 51ae14ec230ca6f2b16388ffcbb73c70ef34fc56 Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 18 Feb 2016 19:13:38 -0800 Subject: [PATCH 189/701] Extra ; --- src/extractor/edge_based_graph_factory.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/extractor/edge_based_graph_factory.cpp b/src/extractor/edge_based_graph_factory.cpp index b9cee60d7..bbabb64fe 100644 --- a/src/extractor/edge_based_graph_factory.cpp +++ b/src/extractor/edge_based_graph_factory.cpp @@ -1059,7 +1059,7 @@ EdgeBasedGraphFactory::getTurnCandidates(NodeID from_node, EdgeID via_eid) } } return turn_candidates; -}; +} int EdgeBasedGraphFactory::GetTurnPenalty(double angle, lua_State *lua_state) const { From b787b993b66a5a9a207c6dbf213d28f70c70abfd Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Thu, 18 Feb 2016 19:14:01 -0800 Subject: [PATCH 190/701] Adapt contract cucumber tests to new argparser output --- features/options/contract/help.feature | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/features/options/contract/help.feature b/features/options/contract/help.feature index 4079efcbe..872a9869b 100644 --- a/features/options/contract/help.feature +++ b/features/options/contract/help.feature @@ -13,7 +13,7 @@ Feature: osrm-contract command line options: help And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 17 lines + And stdout should contain 15 lines And it should exit with code 1 Scenario: osrm-contract - Help, short @@ -28,7 +28,7 @@ Feature: osrm-contract command line options: help And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 17 lines + And stdout should contain 15 lines And it should exit with code 0 Scenario: osrm-contract - Help, long @@ -43,5 +43,5 @@ Feature: osrm-contract command line options: help And stdout should contain "--core" And stdout should contain "--level-cache" And stdout should contain "--segment-speed-file" - And stdout should contain 17 lines + And stdout should contain 15 lines And it should exit with code 0 From 042740877c07f1e657bb92799eb0a5f5bb4524ef Mon Sep 17 00:00:00 2001 From: "Daniel J. Hofmann" Date: Fri, 26 Feb 2016 10:02:04 +0100 Subject: [PATCH 191/701] Update dependency script to libosmium 2.6.1 --- scripts/update_depdendencies.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/update_depdendencies.sh b/scripts/update_depdendencies.sh index 8e2757249..37f9316a9 100755 --- a/scripts/update_depdendencies.sh +++ b/scripts/update_depdendencies.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash OSMIUM_REPO=https://github.com/osmcode/libosmium.git -OSMIUM_TAG=v2.5.4 +OSMIUM_TAG=v2.6.1 VARIANT_REPO=https://github.com/mapbox/variant.git VARIANT_TAG=v1.0 From ae85d86d8f2fd6fbd594838adead2e201fb8e7e4 Mon Sep 17 00:00:00 2001 From: Patrick Niklaus Date: Tue, 1 Mar 2016 17:54:39 +0100 Subject: [PATCH 192/701] Remove libosmium --- third_party/libosmium/.gitignore | 2 - third_party/libosmium/.travis.yml | 159 -- third_party/libosmium/.ycm_extra_conf.py | 48 - third_party/libosmium/CHANGELOG.md | 275 -- third_party/libosmium/CMakeLists.txt | 508 ---- third_party/libosmium/CONTRIBUTING.md | 143 - third_party/libosmium/EXTERNAL_LICENSES.txt | 233 -- third_party/libosmium/LICENSE.txt | 23 - third_party/libosmium/Makefile | 25 - third_party/libosmium/README.md | 114 - third_party/libosmium/appveyor.yml | 109 - .../libosmium/benchmarks/CMakeLists.txt | 49 - third_party/libosmium/benchmarks/README.md | 41 - .../libosmium/benchmarks/download_data.sh | 12 - .../benchmarks/osmium_benchmark_count.cpp | 53 - .../benchmarks/osmium_benchmark_count_tag.cpp | 54 - .../benchmarks/osmium_benchmark_index_map.cpp | 39 - ...mium_benchmark_static_vs_dynamic_index.cpp | 135 - .../benchmarks/osmium_benchmark_write_pbf.cpp | 34 - .../benchmarks/run_benchmark_count.sh | 22 - .../benchmarks/run_benchmark_count_tag.sh | 22 - .../benchmarks/run_benchmark_index_map.sh | 27 - .../run_benchmark_static_vs_dynamic_index.sh | 21 - .../benchmarks/run_benchmark_write_pbf.sh | 28 - .../libosmium/benchmarks/run_benchmarks.sh | 15 - third_party/libosmium/benchmarks/setup.sh | 34 - third_party/libosmium/cmake/FindGem.cmake | 153 -- third_party/libosmium/cmake/FindOsmium.cmake | 318 --- third_party/libosmium/cmake/README | 3 - third_party/libosmium/cmake/build.bat | 15 - third_party/libosmium/cmake/iwyu.sh | 43 - third_party/libosmium/doc/CMakeLists.txt | 33 - third_party/libosmium/doc/Doxyfile.in | 2313 ----------------- third_party/libosmium/doc/README.md | 8 - third_party/libosmium/doc/doc.txt | 26 - third_party/libosmium/doc/header.html | 56 - third_party/libosmium/doc/osmium.css | 22 - third_party/libosmium/examples/CMakeLists.txt | 92 - .../libosmium/examples/osmium_area_test.cpp | 136 - .../libosmium/examples/osmium_convert.cpp | 111 - .../libosmium/examples/osmium_count.cpp | 56 - .../examples/osmium_create_node_cache.cpp | 55 - .../libosmium/examples/osmium_debug.cpp | 50 - .../examples/osmium_filter_discussions.cpp | 72 - .../libosmium/examples/osmium_index.cpp | 237 -- .../libosmium/examples/osmium_read.cpp | 30 - .../libosmium/examples/osmium_serdump.cpp | 206 -- .../examples/osmium_use_node_cache.cpp | 68 - third_party/libosmium/include/gdalcpp.hpp | 406 --- .../include/osmium/area/assembler.hpp | 787 ------ .../osmium/area/detail/node_ref_segment.hpp | 274 -- .../include/osmium/area/detail/proto_ring.hpp | 277 -- .../osmium/area/detail/segment_list.hpp | 218 -- .../osmium/area/multipolygon_collector.hpp | 201 -- .../include/osmium/area/problem_reporter.hpp | 149 -- .../area/problem_reporter_exception.hpp | 96 - .../osmium/area/problem_reporter_ogr.hpp | 139 - .../osmium/area/problem_reporter_stream.hpp | 96 - .../libosmium/include/osmium/builder/attr.hpp | 877 ------- .../include/osmium/builder/builder.hpp | 237 -- .../include/osmium/builder/builder_helper.hpp | 120 - .../osmium/builder/osm_object_builder.hpp | 407 --- .../libosmium/include/osmium/diff_handler.hpp | 66 - .../include/osmium/diff_iterator.hpp | 135 - .../libosmium/include/osmium/diff_visitor.hpp | 104 - .../include/osmium/dynamic_handler.hpp | 190 -- .../osmium/experimental/flex_reader.hpp | 137 - third_party/libosmium/include/osmium/fwd.hpp | 70 - .../include/osmium/geom/coordinates.hpp | 96 - .../libosmium/include/osmium/geom/factory.hpp | 419 --- .../libosmium/include/osmium/geom/geojson.hpp | 160 -- .../libosmium/include/osmium/geom/geos.hpp | 240 -- .../include/osmium/geom/haversine.hpp | 94 - .../osmium/geom/mercator_projection.hpp | 110 - .../libosmium/include/osmium/geom/ogr.hpp | 178 -- .../include/osmium/geom/projection.hpp | 170 -- .../include/osmium/geom/rapid_geojson.hpp | 190 -- .../include/osmium/geom/relations.hpp | 57 - .../libosmium/include/osmium/geom/tile.hpp | 101 - .../libosmium/include/osmium/geom/util.hpp | 75 - .../libosmium/include/osmium/geom/wkb.hpp | 273 -- .../libosmium/include/osmium/geom/wkt.hpp | 156 -- .../libosmium/include/osmium/handler.hpp | 94 - .../include/osmium/handler/chain.hpp | 128 - .../include/osmium/handler/check_order.hpp | 136 - .../include/osmium/handler/disk_store.hpp | 111 - .../libosmium/include/osmium/handler/dump.hpp | 294 --- .../handler/node_locations_for_ways.hpp | 180 -- .../osmium/handler/object_relations.hpp | 106 - .../include/osmium/index/bool_vector.hpp | 85 - .../index/detail/create_map_with_fd.hpp | 70 - .../osmium/index/detail/mmap_vector_anon.hpp | 67 - .../osmium/index/detail/mmap_vector_base.hpp | 180 -- .../osmium/index/detail/mmap_vector_file.hpp | 74 - .../include/osmium/index/detail/tmpfile.hpp | 62 - .../osmium/index/detail/vector_map.hpp | 246 -- .../osmium/index/detail/vector_multimap.hpp | 186 -- .../libosmium/include/osmium/index/index.hpp | 100 - .../libosmium/include/osmium/index/map.hpp | 275 -- .../include/osmium/index/map/all.hpp | 46 - .../osmium/index/map/dense_file_array.hpp | 67 - .../osmium/index/map/dense_mem_array.hpp | 57 - .../osmium/index/map/dense_mmap_array.hpp | 60 - .../include/osmium/index/map/dummy.hpp | 88 - .../osmium/index/map/sparse_file_array.hpp | 67 - .../osmium/index/map/sparse_mem_array.hpp | 60 - .../osmium/index/map/sparse_mem_map.hpp | 116 - .../osmium/index/map/sparse_mem_table.hpp | 147 -- .../osmium/index/map/sparse_mmap_array.hpp | 60 - .../include/osmium/index/multimap.hpp | 127 - .../include/osmium/index/multimap/all.hpp | 41 - .../include/osmium/index/multimap/hybrid.hpp | 204 -- .../index/multimap/sparse_file_array.hpp | 54 - .../index/multimap/sparse_mem_array.hpp | 58 - .../index/multimap/sparse_mem_multimap.hpp | 151 -- .../index/multimap/sparse_mmap_array.hpp | 58 - .../osmium/index/node_locations_map.hpp | 70 - .../include/osmium/io/any_compression.hpp | 48 - .../libosmium/include/osmium/io/any_input.hpp | 52 - .../include/osmium/io/any_output.hpp | 53 - .../include/osmium/io/bzip2_compression.hpp | 321 --- .../include/osmium/io/compression.hpp | 321 --- .../include/osmium/io/debug_output.hpp | 39 - .../osmium/io/detail/debug_output_format.hpp | 485 ---- .../include/osmium/io/detail/input_format.hpp | 211 -- .../osmium/io/detail/o5m_input_format.hpp | 636 ----- .../osmium/io/detail/opl_output_format.hpp | 261 -- .../osmium/io/detail/output_format.hpp | 184 -- .../include/osmium/io/detail/pbf.hpp | 89 - .../include/osmium/io/detail/pbf_decoder.hpp | 777 ------ .../osmium/io/detail/pbf_input_format.hpp | 242 -- .../osmium/io/detail/pbf_output_format.hpp | 643 ----- .../osmium/io/detail/protobuf_tags.hpp | 170 -- .../include/osmium/io/detail/queue_util.hpp | 157 -- .../include/osmium/io/detail/read_thread.hpp | 133 - .../include/osmium/io/detail/read_write.hpp | 180 -- .../include/osmium/io/detail/string_table.hpp | 265 -- .../include/osmium/io/detail/string_util.hpp | 209 -- .../include/osmium/io/detail/write_thread.hpp | 107 - .../osmium/io/detail/xml_input_format.hpp | 679 ----- .../osmium/io/detail/xml_output_format.hpp | 473 ---- .../include/osmium/io/detail/zlib.hpp | 115 - .../libosmium/include/osmium/io/error.hpp | 70 - .../libosmium/include/osmium/io/file.hpp | 328 --- .../include/osmium/io/file_compression.hpp | 72 - .../include/osmium/io/file_format.hpp | 84 - .../include/osmium/io/gzip_compression.hpp | 277 -- .../libosmium/include/osmium/io/header.hpp | 122 - .../include/osmium/io/input_iterator.hpp | 178 -- .../libosmium/include/osmium/io/o5m_input.hpp | 45 - .../include/osmium/io/opl_output.hpp | 39 - .../include/osmium/io/output_iterator.hpp | 136 - .../libosmium/include/osmium/io/overwrite.hpp | 39 - .../libosmium/include/osmium/io/pbf_input.hpp | 48 - .../include/osmium/io/pbf_output.hpp | 48 - .../libosmium/include/osmium/io/reader.hpp | 380 --- .../include/osmium/io/reader_iterator.hpp | 51 - .../libosmium/include/osmium/io/writer.hpp | 344 --- .../include/osmium/io/writer_options.hpp | 60 - .../libosmium/include/osmium/io/xml_input.hpp | 48 - .../include/osmium/io/xml_output.hpp | 47 - .../include/osmium/memory/buffer.hpp | 747 ------ .../include/osmium/memory/collection.hpp | 159 -- .../libosmium/include/osmium/memory/item.hpp | 177 -- .../include/osmium/memory/item_iterator.hpp | 228 -- .../osmium/object_pointer_collection.hpp | 112 - third_party/libosmium/include/osmium/osm.hpp | 48 - .../libosmium/include/osmium/osm/area.hpp | 215 -- .../libosmium/include/osmium/osm/box.hpp | 253 -- .../include/osmium/osm/changeset.hpp | 458 ---- .../libosmium/include/osmium/osm/crc.hpp | 242 -- .../include/osmium/osm/diff_object.hpp | 272 -- .../libosmium/include/osmium/osm/entity.hpp | 80 - .../include/osmium/osm/entity_bits.hpp | 105 - .../include/osmium/osm/item_type.hpp | 208 -- .../libosmium/include/osmium/osm/location.hpp | 285 -- .../libosmium/include/osmium/osm/node.hpp | 76 - .../libosmium/include/osmium/osm/node_ref.hpp | 231 -- .../include/osmium/osm/node_ref_list.hpp | 187 -- .../libosmium/include/osmium/osm/object.hpp | 438 ---- .../include/osmium/osm/object_comparisons.hpp | 110 - .../libosmium/include/osmium/osm/relation.hpp | 192 -- .../libosmium/include/osmium/osm/segment.hpp | 105 - .../libosmium/include/osmium/osm/tag.hpp | 139 - .../include/osmium/osm/timestamp.hpp | 274 -- .../libosmium/include/osmium/osm/types.hpp | 66 - .../include/osmium/osm/types_from_string.hpp | 189 -- .../include/osmium/osm/undirected_segment.hpp | 100 - .../libosmium/include/osmium/osm/way.hpp | 117 - .../include/osmium/relations/collector.hpp | 559 ---- .../osmium/relations/detail/member_meta.hpp | 158 -- .../osmium/relations/detail/relation_meta.hpp | 136 - .../libosmium/include/osmium/tags/filter.hpp | 162 -- .../include/osmium/tags/regex_filter.hpp | 58 - .../libosmium/include/osmium/tags/taglist.hpp | 67 - .../osmium/thread/function_wrapper.hpp | 123 - .../libosmium/include/osmium/thread/pool.hpp | 208 -- .../libosmium/include/osmium/thread/queue.hpp | 199 -- .../include/osmium/thread/sorted_queue.hpp | 159 -- .../libosmium/include/osmium/thread/util.hpp | 116 - .../libosmium/include/osmium/util/cast.hpp | 103 - .../include/osmium/util/compatibility.hpp | 53 - .../libosmium/include/osmium/util/config.hpp | 72 - .../libosmium/include/osmium/util/delta.hpp | 174 -- .../libosmium/include/osmium/util/double.hpp | 97 - .../libosmium/include/osmium/util/endian.hpp | 45 - .../libosmium/include/osmium/util/file.hpp | 121 - .../libosmium/include/osmium/util/memory.hpp | 99 - .../include/osmium/util/memory_mapping.hpp | 768 ------ .../libosmium/include/osmium/util/minmax.hpp | 120 - .../libosmium/include/osmium/util/options.hpp | 205 -- .../libosmium/include/osmium/util/string.hpp | 102 - .../include/osmium/util/verbose_output.hpp | 144 - .../libosmium/include/osmium/visitor.hpp | 253 -- .../libosmium/include/protozero/byteswap.hpp | 71 - .../libosmium/include/protozero/config.hpp | 57 - .../libosmium/include/protozero/exception.hpp | 68 - .../include/protozero/pbf_builder.hpp | 137 - .../include/protozero/pbf_message.hpp | 94 - .../include/protozero/pbf_reader.hpp | 1071 -------- .../libosmium/include/protozero/pbf_types.hpp | 49 - .../include/protozero/pbf_writer.hpp | 661 ----- .../libosmium/include/protozero/varint.hpp | 132 - .../libosmium/include/protozero/version.hpp | 22 - third_party/libosmium/include/utf8.h | 34 - third_party/libosmium/include/utf8/checked.h | 327 --- third_party/libosmium/include/utf8/core.h | 329 --- .../libosmium/include/utf8/unchecked.h | 228 -- third_party/libosmium/osmium.imp | 11 - 229 files changed, 40229 deletions(-) delete mode 100644 third_party/libosmium/.gitignore delete mode 100644 third_party/libosmium/.travis.yml delete mode 100644 third_party/libosmium/.ycm_extra_conf.py delete mode 100644 third_party/libosmium/CHANGELOG.md delete mode 100644 third_party/libosmium/CMakeLists.txt delete mode 100644 third_party/libosmium/CONTRIBUTING.md delete mode 100644 third_party/libosmium/EXTERNAL_LICENSES.txt delete mode 100644 third_party/libosmium/LICENSE.txt delete mode 100644 third_party/libosmium/Makefile delete mode 100644 third_party/libosmium/README.md delete mode 100644 third_party/libosmium/appveyor.yml delete mode 100644 third_party/libosmium/benchmarks/CMakeLists.txt delete mode 100644 third_party/libosmium/benchmarks/README.md delete mode 100755 third_party/libosmium/benchmarks/download_data.sh delete mode 100644 third_party/libosmium/benchmarks/osmium_benchmark_count.cpp delete mode 100644 third_party/libosmium/benchmarks/osmium_benchmark_count_tag.cpp delete mode 100644 third_party/libosmium/benchmarks/osmium_benchmark_index_map.cpp delete mode 100644 third_party/libosmium/benchmarks/osmium_benchmark_static_vs_dynamic_index.cpp delete mode 100644 third_party/libosmium/benchmarks/osmium_benchmark_write_pbf.cpp delete mode 100755 third_party/libosmium/benchmarks/run_benchmark_count.sh delete mode 100755 third_party/libosmium/benchmarks/run_benchmark_count_tag.sh delete mode 100755 third_party/libosmium/benchmarks/run_benchmark_index_map.sh delete mode 100755 third_party/libosmium/benchmarks/run_benchmark_static_vs_dynamic_index.sh delete mode 100755 third_party/libosmium/benchmarks/run_benchmark_write_pbf.sh delete mode 100755 third_party/libosmium/benchmarks/run_benchmarks.sh delete mode 100755 third_party/libosmium/benchmarks/setup.sh delete mode 100644 third_party/libosmium/cmake/FindGem.cmake delete mode 100644 third_party/libosmium/cmake/FindOsmium.cmake delete mode 100644 third_party/libosmium/cmake/README delete mode 100644 third_party/libosmium/cmake/build.bat delete mode 100755 third_party/libosmium/cmake/iwyu.sh delete mode 100644 third_party/libosmium/doc/CMakeLists.txt delete mode 100644 third_party/libosmium/doc/Doxyfile.in delete mode 100644 third_party/libosmium/doc/README.md delete mode 100644 third_party/libosmium/doc/doc.txt delete mode 100644 third_party/libosmium/doc/header.html delete mode 100644 third_party/libosmium/doc/osmium.css delete mode 100644 third_party/libosmium/examples/CMakeLists.txt delete mode 100644 third_party/libosmium/examples/osmium_area_test.cpp delete mode 100644 third_party/libosmium/examples/osmium_convert.cpp delete mode 100644 third_party/libosmium/examples/osmium_count.cpp delete mode 100644 third_party/libosmium/examples/osmium_create_node_cache.cpp delete mode 100644 third_party/libosmium/examples/osmium_debug.cpp delete mode 100644 third_party/libosmium/examples/osmium_filter_discussions.cpp delete mode 100644 third_party/libosmium/examples/osmium_index.cpp delete mode 100644 third_party/libosmium/examples/osmium_read.cpp delete mode 100644 third_party/libosmium/examples/osmium_serdump.cpp delete mode 100644 third_party/libosmium/examples/osmium_use_node_cache.cpp delete mode 100644 third_party/libosmium/include/gdalcpp.hpp delete mode 100644 third_party/libosmium/include/osmium/area/assembler.hpp delete mode 100644 third_party/libosmium/include/osmium/area/detail/node_ref_segment.hpp delete mode 100644 third_party/libosmium/include/osmium/area/detail/proto_ring.hpp delete mode 100644 third_party/libosmium/include/osmium/area/detail/segment_list.hpp delete mode 100644 third_party/libosmium/include/osmium/area/multipolygon_collector.hpp delete mode 100644 third_party/libosmium/include/osmium/area/problem_reporter.hpp delete mode 100644 third_party/libosmium/include/osmium/area/problem_reporter_exception.hpp delete mode 100644 third_party/libosmium/include/osmium/area/problem_reporter_ogr.hpp delete mode 100644 third_party/libosmium/include/osmium/area/problem_reporter_stream.hpp delete mode 100644 third_party/libosmium/include/osmium/builder/attr.hpp delete mode 100644 third_party/libosmium/include/osmium/builder/builder.hpp delete mode 100644 third_party/libosmium/include/osmium/builder/builder_helper.hpp delete mode 100644 third_party/libosmium/include/osmium/builder/osm_object_builder.hpp delete mode 100644 third_party/libosmium/include/osmium/diff_handler.hpp delete mode 100644 third_party/libosmium/include/osmium/diff_iterator.hpp delete mode 100644 third_party/libosmium/include/osmium/diff_visitor.hpp delete mode 100644 third_party/libosmium/include/osmium/dynamic_handler.hpp delete mode 100644 third_party/libosmium/include/osmium/experimental/flex_reader.hpp delete mode 100644 third_party/libosmium/include/osmium/fwd.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/coordinates.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/factory.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/geojson.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/geos.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/haversine.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/mercator_projection.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/ogr.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/projection.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/rapid_geojson.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/relations.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/tile.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/util.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/wkb.hpp delete mode 100644 third_party/libosmium/include/osmium/geom/wkt.hpp delete mode 100644 third_party/libosmium/include/osmium/handler.hpp delete mode 100644 third_party/libosmium/include/osmium/handler/chain.hpp delete mode 100644 third_party/libosmium/include/osmium/handler/check_order.hpp delete mode 100644 third_party/libosmium/include/osmium/handler/disk_store.hpp delete mode 100644 third_party/libosmium/include/osmium/handler/dump.hpp delete mode 100644 third_party/libosmium/include/osmium/handler/node_locations_for_ways.hpp delete mode 100644 third_party/libosmium/include/osmium/handler/object_relations.hpp delete mode 100644 third_party/libosmium/include/osmium/index/bool_vector.hpp delete mode 100644 third_party/libosmium/include/osmium/index/detail/create_map_with_fd.hpp delete mode 100644 third_party/libosmium/include/osmium/index/detail/mmap_vector_anon.hpp delete mode 100644 third_party/libosmium/include/osmium/index/detail/mmap_vector_base.hpp delete mode 100644 third_party/libosmium/include/osmium/index/detail/mmap_vector_file.hpp delete mode 100644 third_party/libosmium/include/osmium/index/detail/tmpfile.hpp delete mode 100644 third_party/libosmium/include/osmium/index/detail/vector_map.hpp delete mode 100644 third_party/libosmium/include/osmium/index/detail/vector_multimap.hpp delete mode 100644 third_party/libosmium/include/osmium/index/index.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/all.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/dense_file_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/dense_mem_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/dense_mmap_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/dummy.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/sparse_file_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/sparse_mem_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/sparse_mem_map.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/sparse_mem_table.hpp delete mode 100644 third_party/libosmium/include/osmium/index/map/sparse_mmap_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/multimap.hpp delete mode 100644 third_party/libosmium/include/osmium/index/multimap/all.hpp delete mode 100644 third_party/libosmium/include/osmium/index/multimap/hybrid.hpp delete mode 100644 third_party/libosmium/include/osmium/index/multimap/sparse_file_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/multimap/sparse_mem_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/multimap/sparse_mem_multimap.hpp delete mode 100644 third_party/libosmium/include/osmium/index/multimap/sparse_mmap_array.hpp delete mode 100644 third_party/libosmium/include/osmium/index/node_locations_map.hpp delete mode 100644 third_party/libosmium/include/osmium/io/any_compression.hpp delete mode 100644 third_party/libosmium/include/osmium/io/any_input.hpp delete mode 100644 third_party/libosmium/include/osmium/io/any_output.hpp delete mode 100644 third_party/libosmium/include/osmium/io/bzip2_compression.hpp delete mode 100644 third_party/libosmium/include/osmium/io/compression.hpp delete mode 100644 third_party/libosmium/include/osmium/io/debug_output.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/debug_output_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/input_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/o5m_input_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/opl_output_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/output_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/pbf.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/pbf_decoder.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/pbf_input_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/pbf_output_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/protobuf_tags.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/queue_util.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/read_thread.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/read_write.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/string_table.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/string_util.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/write_thread.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/xml_input_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/xml_output_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/detail/zlib.hpp delete mode 100644 third_party/libosmium/include/osmium/io/error.hpp delete mode 100644 third_party/libosmium/include/osmium/io/file.hpp delete mode 100644 third_party/libosmium/include/osmium/io/file_compression.hpp delete mode 100644 third_party/libosmium/include/osmium/io/file_format.hpp delete mode 100644 third_party/libosmium/include/osmium/io/gzip_compression.hpp delete mode 100644 third_party/libosmium/include/osmium/io/header.hpp delete mode 100644 third_party/libosmium/include/osmium/io/input_iterator.hpp delete mode 100644 third_party/libosmium/include/osmium/io/o5m_input.hpp delete mode 100644 third_party/libosmium/include/osmium/io/opl_output.hpp delete mode 100644 third_party/libosmium/include/osmium/io/output_iterator.hpp delete mode 100644 third_party/libosmium/include/osmium/io/overwrite.hpp delete mode 100644 third_party/libosmium/include/osmium/io/pbf_input.hpp delete mode 100644 third_party/libosmium/include/osmium/io/pbf_output.hpp delete mode 100644 third_party/libosmium/include/osmium/io/reader.hpp delete mode 100644 third_party/libosmium/include/osmium/io/reader_iterator.hpp delete mode 100644 third_party/libosmium/include/osmium/io/writer.hpp delete mode 100644 third_party/libosmium/include/osmium/io/writer_options.hpp delete mode 100644 third_party/libosmium/include/osmium/io/xml_input.hpp delete mode 100644 third_party/libosmium/include/osmium/io/xml_output.hpp delete mode 100644 third_party/libosmium/include/osmium/memory/buffer.hpp delete mode 100644 third_party/libosmium/include/osmium/memory/collection.hpp delete mode 100644 third_party/libosmium/include/osmium/memory/item.hpp delete mode 100644 third_party/libosmium/include/osmium/memory/item_iterator.hpp delete mode 100644 third_party/libosmium/include/osmium/object_pointer_collection.hpp delete mode 100644 third_party/libosmium/include/osmium/osm.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/area.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/box.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/changeset.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/crc.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/diff_object.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/entity.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/entity_bits.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/item_type.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/location.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/node.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/node_ref.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/node_ref_list.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/object.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/object_comparisons.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/relation.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/segment.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/tag.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/timestamp.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/types.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/types_from_string.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/undirected_segment.hpp delete mode 100644 third_party/libosmium/include/osmium/osm/way.hpp delete mode 100644 third_party/libosmium/include/osmium/relations/collector.hpp delete mode 100644 third_party/libosmium/include/osmium/relations/detail/member_meta.hpp delete mode 100644 third_party/libosmium/include/osmium/relations/detail/relation_meta.hpp delete mode 100644 third_party/libosmium/include/osmium/tags/filter.hpp delete mode 100644 third_party/libosmium/include/osmium/tags/regex_filter.hpp delete mode 100644 third_party/libosmium/include/osmium/tags/taglist.hpp delete mode 100644 third_party/libosmium/include/osmium/thread/function_wrapper.hpp delete mode 100644 third_party/libosmium/include/osmium/thread/pool.hpp delete mode 100644 third_party/libosmium/include/osmium/thread/queue.hpp delete mode 100644 third_party/libosmium/include/osmium/thread/sorted_queue.hpp delete mode 100644 third_party/libosmium/include/osmium/thread/util.hpp delete mode 100644 third_party/libosmium/include/osmium/util/cast.hpp delete mode 100644 third_party/libosmium/include/osmium/util/compatibility.hpp delete mode 100644 third_party/libosmium/include/osmium/util/config.hpp delete mode 100644 third_party/libosmium/include/osmium/util/delta.hpp delete mode 100644 third_party/libosmium/include/osmium/util/double.hpp delete mode 100644 third_party/libosmium/include/osmium/util/endian.hpp delete mode 100644 third_party/libosmium/include/osmium/util/file.hpp delete mode 100644 third_party/libosmium/include/osmium/util/memory.hpp delete mode 100644 third_party/libosmium/include/osmium/util/memory_mapping.hpp delete mode 100644 third_party/libosmium/include/osmium/util/minmax.hpp delete mode 100644 third_party/libosmium/include/osmium/util/options.hpp delete mode 100644 third_party/libosmium/include/osmium/util/string.hpp delete mode 100644 third_party/libosmium/include/osmium/util/verbose_output.hpp delete mode 100644 third_party/libosmium/include/osmium/visitor.hpp delete mode 100644 third_party/libosmium/include/protozero/byteswap.hpp delete mode 100644 third_party/libosmium/include/protozero/config.hpp delete mode 100644 third_party/libosmium/include/protozero/exception.hpp delete mode 100644 third_party/libosmium/include/protozero/pbf_builder.hpp delete mode 100644 third_party/libosmium/include/protozero/pbf_message.hpp delete mode 100644 third_party/libosmium/include/protozero/pbf_reader.hpp delete mode 100644 third_party/libosmium/include/protozero/pbf_types.hpp delete mode 100644 third_party/libosmium/include/protozero/pbf_writer.hpp delete mode 100644 third_party/libosmium/include/protozero/varint.hpp delete mode 100644 third_party/libosmium/include/protozero/version.hpp delete mode 100644 third_party/libosmium/include/utf8.h delete mode 100644 third_party/libosmium/include/utf8/checked.h delete mode 100644 third_party/libosmium/include/utf8/core.h delete mode 100644 third_party/libosmium/include/utf8/unchecked.h delete mode 100644 third_party/libosmium/osmium.imp diff --git a/third_party/libosmium/.gitignore b/third_party/libosmium/.gitignore deleted file mode 100644 index 50139035b..000000000 --- a/third_party/libosmium/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.swp -.ycm_extra_conf.pyc diff --git a/third_party/libosmium/.travis.yml b/third_party/libosmium/.travis.yml deleted file mode 100644 index ac0d270e2..000000000 --- a/third_party/libosmium/.travis.yml +++ /dev/null @@ -1,159 +0,0 @@ -#----------------------------------------------------------------------------- -# -# Configuration for continuous integration service at travis-ci.org -# -#----------------------------------------------------------------------------- - -language: cpp - -sudo: false - -matrix: - include: - - # 1/ Linux Clang Builds - - os: linux - compiler: clang - addons: - apt: - sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['clang-3.5', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='clang++-3.5' BUILD_TYPE='Release' - - - os: linux - compiler: clang - addons: - apt: - sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['clang-3.5', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='clang++-3.5' BUILD_TYPE='Dev' - - - - os: linux - compiler: clang - addons: - apt: - sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['clang-3.6', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='clang++-3.6' BUILD_TYPE='Release' - - - os: linux - compiler: clang - addons: - apt: - sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['clang-3.6', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='clang++-3.6' BUILD_TYPE='Dev' - - - - os: linux - compiler: clang - addons: - apt: - sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['clang-3.7', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='clang++-3.7' BUILD_TYPE='Release' - - - os: linux - compiler: clang - addons: - apt: - sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['clang-3.7', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='clang++-3.7' BUILD_TYPE='Dev' - - - # 2/ Linux GCC Builds - - os: linux - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['g++-4.8', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='g++-4.8' COMPILER_FLAGS='-Wno-return-type' BUILD_TYPE='Release' - - - os: linux - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['g++-4.8', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='g++-4.8' COMPILER_FLAGS='-Wno-return-type' BUILD_TYPE='Dev' - - - - os: linux - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['g++-4.9', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='g++-4.9' BUILD_TYPE='Release' - - - os: linux - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['g++-4.9', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='g++-4.9' BUILD_TYPE='Dev' - - - - os: linux - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['g++-5', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='g++-5' BUILD_TYPE='Release' - - - os: linux - compiler: gcc - addons: - apt: - sources: ['ubuntu-toolchain-r-test', 'boost-latest'] - packages: ['g++-5', 'libboost1.55-all-dev', 'libgdal-dev', 'libgeos++-dev', 'libproj-dev', 'libsparsehash-dev', 'spatialite-bin'] - env: COMPILER='g++-5' BUILD_TYPE='Dev' - - - # 3/ OSX Clang Builds - - os: osx - osx_image: xcode6.4 - compiler: clang - env: COMPILER='clang++' BUILD_TYPE='Dev' - - - os: osx - osx_image: xcode6.4 - compiler: clang - env: COMPILER='clang++' BUILD_TYPE='Release' - - - - os: osx - osx_image: xcode7 - compiler: clang - env: COMPILER='clang++' BUILD_TYPE='Dev' - - - os: osx - osx_image: xcode7 - compiler: clang - env: COMPILER='clang++' BUILD_TYPE='Release' - - -install: - - DEPS_DIR="${TRAVIS_BUILD_DIR}/deps" - - mkdir -p ${DEPS_DIR} && cd ${DEPS_DIR} - - git clone --quiet --depth 1 https://github.com/osmcode/osm-testdata.git - - | - if [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then - brew remove gdal - brew install cmake boost google-sparsehash gdal - fi - -before_script: - - cd ${TRAVIS_BUILD_DIR} - - mkdir build && cd build - - CXX=${COMPILER} CXXFLAGS=${COMPILER_FLAGS} cmake -LA .. -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DOSM_TESTDATA="${TRAVIS_BUILD_DIR}/deps/osm-testdata" - -script: - - make VERBOSE=1 - - ctest --output-on-failure - diff --git a/third_party/libosmium/.ycm_extra_conf.py b/third_party/libosmium/.ycm_extra_conf.py deleted file mode 100644 index 2b8730616..000000000 --- a/third_party/libosmium/.ycm_extra_conf.py +++ /dev/null @@ -1,48 +0,0 @@ -#----------------------------------------------------------------------------- -# -# Configuration for YouCompleteMe Vim plugin -# -# http://valloric.github.io/YouCompleteMe/ -# -#----------------------------------------------------------------------------- - -from os.path import realpath, dirname - -basedir = dirname(realpath(__file__)) - -# some default flags -# for more information install clang-3.2-doc package and -# check UsersManual.html -flags = [ -'-Werror', -'-Wall', -'-Wextra', -'-pedantic', -'-Wno-return-type', -'-Wno-unused-parameter', -'-Wno-unused-variable', - -'-std=c++11', - -# '-x' and 'c++' also required -# use 'c' for C projects -'-x', -'c++', - -# libosmium include dirs -'-I%s/include' % basedir, -'-I%s/test/include' % basedir, -'-I%s/test/data-test/include' % basedir, - -# include third party libraries -'-I/usr/include/gdal', -] - -# youcompleteme is calling this function to get flags -# You can also set database for flags. Check: JSONCompilationDatabase.html in -# clang-3.2-doc package -def FlagsForFile( filename ): - return { - 'flags': flags, - 'do_cache': True - } diff --git a/third_party/libosmium/CHANGELOG.md b/third_party/libosmium/CHANGELOG.md deleted file mode 100644 index 2ca6518c8..000000000 --- a/third_party/libosmium/CHANGELOG.md +++ /dev/null @@ -1,275 +0,0 @@ - -# Change Log - -All notable changes to this project will be documented in this file. -This project adheres to [Semantic Versioning](http://semver.org/). - -## [unreleased] - - -### Added - -### Changed - -### Fixed - - -## [2.6.0] - 2016-02-04 - -### Added - -- The new handler osmium::handler::CheckOrder can be used to check that a - file is properly ordered. -- Add new method to build OSM nodes, ways, relations, changesets, and areas - in buffers that wraps the older Builder classes. The new code is much easier - to use and very flexible. There is no documentation yet, but the tests in - `test/t/builder/test_attr.cpp` can give you an idea how it works. -- Add util class to get memory usage of current process on Linux. - -### Changed - -- New Buffer memory management speeds up Buffer use, because it doesn't clear - the memory unnecessarily. - -### Fixed - -- osmium::Box::extend() function now ignores invalid locations. -- Install of external library headers. -- Check way has at least one node before calling `is_closed()` in area - assembler. -- Declaration/definition of some friend functions was in the wrong namespace. - - -## [2.5.4] - 2015-12-03 - -### Changed - -- Included gdalcpp.hpp header was updated to version 1.1.1. -- Included protozero library was updated to version 1.2.3. -- Workarounds for missing constexpr support in Visual Studio removed. All - constexpr features we need are supported now. -- Some code cleanup after running clang-tidy on the code. -- Re-added `Buffer::value_type` typedef. Turns out it is needed when using - `std::back_inserter` on the Buffer. - -### Fixed - -- Bugs with Timestamp code on 32 bit platforms. This necessitated - some changes in Timestamp which might lead to changes in user - code. -- Bug in segment intersection code (which appeared on i686 platform). - - -## [2.5.3] - 2015-11-17 - -### Added - -- `osmium::make_diff_iterator()` helper function. - -### Changed - -- Deprecated `osmium::Buffer::set_full_callback()`. -- Removed DataFile class which was never used anywhere. -- Removed unused and obscure `Buffer::value_type` typedef. - -### Fixed - -- Possible overrun in Buffer when using the full-callback. -- Incorrect swapping of Buffer. - - -## [2.5.2] - 2015-11-06 - -# Fixed - -- Writing data through an OutputIterator was extremly slow due to - lock contention. - - -## [2.5.1] - 2015-11-05 - -### Added - -- Header `osmium/fwd.hpp` with forward declarations of the most commonly - used Osmium classes. - -### Changed - -- Moved `osmium/io/overwrite.hpp` to `osmium/io/writer_options.hpp` - If you still include the old file, you'll get a warning. - - -## [2.5.0] - 2015-11-04 - -### Added - -- Helper functions to make input iterator ranges and output iterators. -- Add support for reading o5m and o5c files. -- Option for osmium::io::Writer to fsync file after writing. -- Lots of internal asserts() and other robustness checks. - -### Changed - -- Updated included protozero library to version 1.2.0. -- Complete overhaul of the I/O system making it much more robust against - wrong data and failures during I/O operations. -- Speed up PBF writing by running parts of it in parallel. -- OutputIterator doesn't hold an internal buffer any more, but it uses - one in Writer. Calling flush() on the OutputIterator isn't needed any - more. -- Reader now throws when trying to read after eof or an error. -- I/O functions that used to throw std::runtime_error now throw - osmium::io_error or derived. -- Optional parameters on osmium::io::Writer now work in any order. - -### Fixed - -- PBF reader now decodes locations of invisible nodes properly. -- Invalid Delta encode iterator dereference. -- Lots of includes fixed to include (only) what's used. -- Dangling reference in area assembly code. - - -## [2.4.1] - 2015-08-29 - -### Fixed - -- CRC calculation of tags and changesets. - - -## [2.4.0] - 2015-08-29 - -### Added - -- Checks that user names, member roles and tag keys and values are not longer - than 256 * 4 bytes. That is the maximum length 256 Unicode characters - can have in UTF-8 encoding. -- Support for GDAL 2. GDAL 1 still works. - -### Changed - -- Improved CMake build scripts. -- Updated internal version of Protozero to 1.1.0. -- Removed `toogr*` examples. They are in their own repository now. - See https://github.com/osmcode/osm-gis-export. -- Files about to be memory-mapped (for instance index files) are now set - to binary mode on Windows so the application doesn't have to do this. - -### Fixed - -- Hanging program when trying to open file with an unknown file format. -- Building problems with old boost versions. -- Initialization errors in PBF writer. -- Bug in byte swap code. -- Output on Windows now always uses binary mode, even when writing to - stdout, so OSM xml and opl files always use LF line endings. - - -## [2.3.0] - 2015-08-18 - -### Added - -- Allow instantiating osmium::geom::GEOSFactory with existing GEOS factory. -- Low-level functions to support generating a architecture- and endian- - independant CRC from OSM data. This is intended to be uses with boost::crc. -- Add new debug output format. This format is not intended to be read - automatically, but for human consumption. It formats the data nicely. -- Make writing of metadata configurable for XML and OPL output (use - `add_metadata=false` as file option). - -### Changed - -- Changed `add_user()` and `add_role()` in builders to use string length - without the 0-termination. -- Improved code setting file format from suffix/format argument. -- Memory mapping utility class now supports readonly, private writable or - shared writable operation. -- Allow empty version (0) in PBF files. -- Use utf8cpp header-only lib instead of boost for utf8 decoding. The library - is included in the libosmium distribution. -- New PBF reader and writer based on the protozero. A complete rewrite of the - code for reading and writing OSM PBF files. It doesn't use the Google - protobuf library and it doesn't use the OSMPBF/OSM-Binary library any more. - Instead is uses the protozero lightweight protobuf header library which is - included in the code. Not only does the new code have less dependencies, it - is faster and more robust. https://github.com/mapbox/protozero - -### Fixed - -- Various smaller bug fixes. -- Add encoding for relation member roles in OPL format. -- Change character encoding to new format in OPL: variable length hex code - between % characters instead of a % followed by 4-digit hex code. This is - necessary because unicode characters can be longer than the 4-digit hex - code. -- XML writer: The linefeed, carriage return, and tab characters are now - escaped properly. -- Reading large XML files could block. - -## [2.2.0] - 2015-07-04 - -### Added - -- Conversion functions for some low-level types. -- BoolVector index class. -- `min_op`/`max_op` utility functions. -- More tests here and there. -- Helper methods `is_between()` and `is_visible_at()` to DiffObject. -- GeoJSON factory using the RapidJSON library. -- Support for tile calculations. -- Create simple polygons from ways in geom factories. -- `MemoryMapping` and `TypedMemoryMapping` helper classes. -- `close()` function to `mmap_vector_base` class. -- Function on `Buffer` class to get iterator to specific offset. -- Explicit cast operator from `osmium::Timestamp` to `uint32_t`. - -### Changed - -- Throw exception on illegal values in functions parsing strings to get ids, - versions, etc. -- Improved error message for geometry exceptions. - -### Fixed - -- Throw exception from `dump_as_array()` and `dump_as_list()` functions if not - implemented in an index. -- After writing OSM files, program could stall up to a second. -- Dense location store was written out only partially. -- Use `uint64_t` as counter in benchmarks, so there can be no overflows. -- Example programs now read packed XML files, too. -- Refactoring of memory mapping code. Removes leak on Windows. -- Better check for invalid locations. -- Mark `cbegin()` and `cend()` of `mmap_vector_base` as const functions. - -## [2.1.0] - 2015-03-31 - -### Added - -- When writing PBF files, sorting the PBF stringtables is now optional. -- More tests and documentation. - -### Changed - -- Some functions are now declared `noexcept`. -- XML parser fails now if the top-level element is not `osm` or `osmChange`. - -### Fixed - -- Race condition in PBF reader. -- Multipolygon collector was accessing non-existent NodeRef. -- Doxygen documentation wan't showing all classes/functions due to a bug in - Doxygen (up to version 1.8.8). This version contains a workaround to fix - this. - -[unreleased]: https://github.com/osmcode/libosmium/compare/v2.6.0...HEAD -[2.6.0]: https://github.com/osmcode/libosmium/compare/v2.5.4...v2.6.0 -[2.5.4]: https://github.com/osmcode/libosmium/compare/v2.5.3...v2.5.4 -[2.5.3]: https://github.com/osmcode/libosmium/compare/v2.5.2...v2.5.3 -[2.5.2]: https://github.com/osmcode/libosmium/compare/v2.5.1...v2.5.2 -[2.5.1]: https://github.com/osmcode/libosmium/compare/v2.5.0...v2.5.1 -[2.5.0]: https://github.com/osmcode/libosmium/compare/v2.4.1...v2.5.0 -[2.4.1]: https://github.com/osmcode/libosmium/compare/v2.4.0...v2.4.1 -[2.4.0]: https://github.com/osmcode/libosmium/compare/v2.3.0...v2.4.0 -[2.3.0]: https://github.com/osmcode/libosmium/compare/v2.2.0...v2.3.0 -[2.2.0]: https://github.com/osmcode/libosmium/compare/v2.1.0...v2.2.0 -[2.1.0]: https://github.com/osmcode/libosmium/compare/v2.0.0...v2.1.0 - diff --git a/third_party/libosmium/CMakeLists.txt b/third_party/libosmium/CMakeLists.txt deleted file mode 100644 index 73394674e..000000000 --- a/third_party/libosmium/CMakeLists.txt +++ /dev/null @@ -1,508 +0,0 @@ -#----------------------------------------------------------------------------- -# -# CMake Config -# -# Libosmium -# -#----------------------------------------------------------------------------- - -cmake_minimum_required(VERSION 2.8 FATAL_ERROR) -list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") - - -#----------------------------------------------------------------------------- -# -# Project version -# -#----------------------------------------------------------------------------- - -set(CMAKE_CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo;MinSizeRel;Dev;Coverage" - CACHE STRING - "List of available configuration types" - FORCE) - -project(libosmium) - -set(LIBOSMIUM_VERSION_MAJOR 2) -set(LIBOSMIUM_VERSION_MINOR 6) -set(LIBOSMIUM_VERSION_PATCH 0) - -set(LIBOSMIUM_VERSION - "${LIBOSMIUM_VERSION_MAJOR}.${LIBOSMIUM_VERSION_MINOR}.${LIBOSMIUM_VERSION_PATCH}") - -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - - -#----------------------------------------------------------------------------- -# -# Build options -# -# (Change with -DOPTION=VALUE on cmake command line.) -# -#----------------------------------------------------------------------------- - -if(CMAKE_BUILD_TYPE STREQUAL "Dev") - set(dev_build ON) -else() - set(dev_build OFF) -endif() - -option(BUILD_EXAMPLES "compile example programs" ON) -option(BUILD_TESTING "compile unit tests, please run them with ctest" ON) - -option(BUILD_HEADERS "compile every header file on its own" ${dev_build}) -option(BUILD_BENCHMARKS "compile benchmark programs" ${dev_build}) -option(BUILD_DATA_TESTS "compile data tests, please run them with ctest" ${dev_build}) - -option(INSTALL_GDALCPP "also install gdalcpp headers" OFF) -option(INSTALL_PROTOZERO "also install protozero headers" OFF) -option(INSTALL_UTFCPP "also install utfcpp headers" OFF) - - -#----------------------------------------------------------------------------- -# -# Coverage support -# -#----------------------------------------------------------------------------- - -include(CheckCXXCompilerFlag) -check_cxx_compiler_flag("-fkeep-inline-functions" HAS_KEEP_INLINE_FUNCTIONS) -if(HAS_KEEP_INLINE_FUNCTIONS) - set(extra_coverage_flags_ "-fkeep-inline-functions") -endif() - -set(CMAKE_CXX_FLAGS_COVERAGE - "-g -O0 -fno-inline-functions -fno-inline --coverage ${extra_coverage_flags_}" - CACHE STRING "Flags used by the compiler during coverage builds.") - -set(CMAKE_EXE_LINKER_FLAGS_COVERAGE - "--coverage" - CACHE STRING "Flags used by the linker during coverage builds.") - -if(CMAKE_BUILD_TYPE STREQUAL "Coverage") - if(BUILD_EXAMPLES OR BUILD_HEADERS OR BUILD_BENCHMARKS OR BUILD_DATA_TESTS) - message(WARNING "Coverage builds don't work for anything but the unit tests") - endif() - - if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - string(REGEX REPLACE "^([0-9]+)\\.([0-9]+).*$" "llvm-cov-\\1.\\2" - gcov_ ${CMAKE_CXX_COMPILER_VERSION}) - else() - set(gcov_ "gcov") - endif() - - find_program(GCOV ${gcov_} DOC "Coverage tool") - find_program(GCOVR "gcovr" DOC "Coverage report tool") - - set(coverage_report_dir "${CMAKE_BINARY_DIR}/coverage") - file(MAKE_DIRECTORY ${coverage_report_dir}) - add_custom_target(coverage - ${GCOVR} - ${CMAKE_BINARY_DIR} - --root=${CMAKE_SOURCE_DIR} - --html --html-details - #--verbose - #--keep - '--filter=.*include/osmium.*' - --sort-percentage - --gcov-executable=${GCOV} - --output=${coverage_report_dir}/index.html) -endif() - - -#----------------------------------------------------------------------------- -# -# Find external dependencies -# -#----------------------------------------------------------------------------- - -find_package(Boost 1.38) -mark_as_advanced(CLEAR BOOST_ROOT) - -if(Boost_FOUND) - include_directories(SYSTEM ${Boost_INCLUDE_DIRS}) -else() - set(BOOST_ROOT "NOT FOUND: please choose" CACHE PATH "") - message(FATAL_ERROR "PLEASE, specify the directory where the Boost library is installed in BOOST_ROOT") -endif() - -# set OSMIUM_INCLUDE_DIR so FindOsmium will not set anything different -set(OSMIUM_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include") - -include_directories(${OSMIUM_INCLUDE_DIR}) - -find_package(Osmium COMPONENTS io gdal geos proj sparsehash) - -# The find_package put the directory where it found the libosmium includes -# into OSMIUM_INCLUDE_DIRS. We remove it again, because we want to make -# sure to use our own include directory already set up above. -list(FIND OSMIUM_INCLUDE_DIRS "${OSMIUM_INCLUDE_DIR}" _own_index) -list(REMOVE_AT OSMIUM_INCLUDE_DIRS ${_own_index}) -set(_own_index) - -include_directories(SYSTEM ${OSMIUM_INCLUDE_DIRS}) - -if(MSVC) - find_path(GETOPT_INCLUDE_DIR getopt.h) - find_library(GETOPT_LIBRARY NAMES wingetopt) - if(GETOPT_INCLUDE_DIR AND GETOPT_LIBRARY) - include_directories(SYSTEM ${GETOPT_INCLUDE_DIR}) - list(APPEND OSMIUM_LIBRARIES ${GETOPT_LIBRARY}) - else() - set(GETOPT_MISSING 1) - endif() -endif() - - -#----------------------------------------------------------------------------- -# -# Decide which C++ version to use (Minimum/default: C++11). -# -#----------------------------------------------------------------------------- -if(NOT MSVC) - if(NOT USE_CPP_VERSION) - set(USE_CPP_VERSION c++11) - endif() - message(STATUS "Use C++ version: ${USE_CPP_VERSION}") - # following only available from cmake 2.8.12: - # add_compile_options(-std=${USE_CPP_VERSION}) - # so using this instead: - add_definitions(-std=${USE_CPP_VERSION}) -endif() - - -#----------------------------------------------------------------------------- -# -# Compiler and Linker flags -# -#----------------------------------------------------------------------------- -if(MSVC) - set(USUAL_COMPILE_OPTIONS "/Ox") - set(USUAL_LINK_OPTIONS "/debug") -else() - set(USUAL_COMPILE_OPTIONS "-O3 -g") - set(USUAL_LINK_OPTIONS "") -endif() - -if(WIN32) - add_definitions(-DWIN32 -D_WIN32 -DMSWIN32 -DBGDWIN32 - -DWINVER=0x0500 -D_WIN32_WINNT=0x0500 -D_WIN32_IE=0x0600) -endif() - -set(CMAKE_CXX_FLAGS_DEV "${USUAL_COMPILE_OPTIONS}" - CACHE STRING "Flags used by the compiler during developer builds." - FORCE) - -set(CMAKE_EXE_LINKER_FLAGS_DEV "${USUAL_LINK_OPTIONS}" - CACHE STRING "Flags used by the linker during developer builds." - FORCE) -mark_as_advanced( - CMAKE_CXX_FLAGS_DEV - CMAKE_EXE_LINKER_FLAGS_DEV -) - -set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${USUAL_COMPILE_OPTIONS}" - CACHE STRING "Flags used by the compiler during RELWITHDEBINFO builds." - FORCE) - - -#----------------------------------------------------------------------------- -# -# Build Type -# -#----------------------------------------------------------------------------- -# In 'Dev' mode: compile with very strict warnings and turn them into errors. -if(CMAKE_BUILD_TYPE STREQUAL "Dev") - if(NOT MSVC) - add_definitions(-Werror) - endif() - add_definitions(${OSMIUM_WARNING_OPTIONS}) -# add_definitions(${OSMIUM_WARNING_OPTIONS} ${OSMIUM_DRACONIC_CLANG_OPTIONS} -Wno-documentation -Wno-format-nonliteral -Wno-deprecated -Wno-covered-switch-default -Wno-shadow) -endif() - -# Force RelWithDebInfo build type if none was given -if(CMAKE_BUILD_TYPE) - set(build_type ${CMAKE_BUILD_TYPE}) -else() - set(build_type "RelWithDebInfo") -endif() - -set(CMAKE_BUILD_TYPE ${build_type} - CACHE STRING - "Choose the type of build, options are: ${CMAKE_CONFIGURATION_TYPES}." - FORCE) - - -#----------------------------------------------------------------------------- -# -# Unit and data tests -# -#----------------------------------------------------------------------------- -enable_testing() - -if(BUILD_TESTING OR BUILD_DATA_TESTS) - find_program(MEMORYCHECK_COMMAND valgrind) - - set(MEMORYCHECK_COMMAND_OPTIONS - "--trace-children=yes --leak-check=full --show-reachable=yes --error-exitcode=1") - - set(MEMORYCHECK_SUPPRESSIONS_FILE "${PROJECT_SOURCE_DIR}/test/valgrind.supp") -endif() - -if(BUILD_TESTING) - add_subdirectory(test) -endif() - -if(BUILD_DATA_TESTS) - add_subdirectory(test/data-tests) -endif() - - -#----------------------------------------------------------------------------- -# -# Optional "cppcheck" target that checks C++ code -# -#----------------------------------------------------------------------------- -message(STATUS "Looking for cppcheck") -find_program(CPPCHECK cppcheck) - -if(CPPCHECK) - message(STATUS "Looking for cppcheck - found") - set(CPPCHECK_OPTIONS - --enable=warning,style,performance,portability,information,missingInclude --force -Uassert) - - # cpp doesn't find system includes for some reason, suppress that report - set(CPPCHECK_OPTIONS ${CPPCHECK_OPTIONS} --suppress=missingIncludeSystem) - - file(GLOB_RECURSE ALL_INCLUDES include/osmium/*.hpp) - file(GLOB ALL_EXAMPLES examples/*.cpp) - file(GLOB ALL_BENCHMARKS benchmarks/*.cpp) - file(GLOB ALL_UNIT_TESTS test/t/*/test_*.cpp) - file(GLOB ALL_DATA_TESTS test/data-tests/*.cpp) - - if(Osmium_DEBUG) - message(STATUS "Checking includes : ${ALL_INCLUDES}") - message(STATUS "Checking example code : ${ALL_EXAMPLES}") - message(STATUS "Checking benchmarks : ${ALL_BENCHMARKS}") - message(STATUS "Checking unit test code: ${ALL_UNIT_TESTS}") - message(STATUS "Checking data test code: ${ALL_DATA_TESTS}") - endif() - - set(CPPCHECK_FILES - ${ALL_INCLUDES} - ${ALL_EXAMPLES} - ${ALL_BENCHMARKS} - ${ALL_UNIT_TESTS} - ${ALL_DATA_TESTS}) - - add_custom_target(cppcheck - ${CPPCHECK} - --std=c++11 ${CPPCHECK_OPTIONS} - -I ${CMAKE_SOURCE_DIR}/include - ${CPPCHECK_FILES} - ) -else() - message(STATUS "Looking for cppcheck - not found") - message(STATUS " Build target 'cppcheck' will not be available.") -endif() - - -#----------------------------------------------------------------------------- -# -# Examples, benchmarks and documentation -# -#----------------------------------------------------------------------------- - -if(BUILD_EXAMPLES) - add_subdirectory(examples) -endif() - -if(BUILD_BENCHMARKS) - add_subdirectory(benchmarks) -endif() - -add_subdirectory(doc) - - -#----------------------------------------------------------------------------- -# -# Headers -# -# This will try to compile include files on their own to detect missing -# include directives and other dependency-related problems. Note that if this -# work, it is not enough to be sure it will compile in production code. -# But if it reports an error we know we are missing something. -# -#----------------------------------------------------------------------------- -if(BUILD_HEADERS) - file(GLOB_RECURSE - ALL_HPPS - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/include" - include/osmium/*.hpp) - - file(MAKE_DIRECTORY header_check) - - foreach(hpp ${ALL_HPPS}) - string(REPLACE ".hpp" "" tmp ${hpp}) - string(REPLACE "/" "__" libname ${tmp}) - - # Create a dummy .cpp file that includes the header file we want to - # check. - set(DUMMYCPP ${CMAKE_BINARY_DIR}/header_check/${libname}.cpp) - file(WRITE ${DUMMYCPP} "#include <${hpp}>\n") - - # There is no way in CMake to just compile but not link a C++ file, - # so we pretend to build a library here. - add_library(${libname} STATIC ${DUMMYCPP} include/${hpp}) - - #### this is better but only supported from cmake 3.0: - ###add_library(${libname} OBJECT ${DUMMYCPP} include/${hpp}) - - endforeach() -endif() - - -#----------------------------------------------------------------------------- -# -# Optional "clang-tidy" target -# -#----------------------------------------------------------------------------- -message(STATUS "Looking for clang-tidy") -find_program(CLANG_TIDY NAMES clang-tidy clang-tidy-3.9 clang-tidy-3.8 clang-tidy-3.7 clang-tidy-3.6 clang-tidy-3.5) - -if(CLANG_TIDY) - message(STATUS "Looking for clang-tidy - found") - - if(BUILD_EXAMPLES) - file(GLOB CT_ALL_EXAMPLES examples/*.cpp) - endif() - - if(BUILD_TESTING) - file(GLOB CT_ALL_UNIT_TESTS test/t/*/test_*.cpp) - endif() - - if(BUILD_HEADERS) - file(GLOB_RECURSE CT_ALL_INCLUDES ${CMAKE_BINARY_DIR}/header_check/osmium__*.cpp) - endif() - - if(BUILD_BENCHMARKS) - file(GLOB CT_ALL_BENCHMARKS benchmarks/*.cpp) - endif() - - if(BUILD_DATA_TESTS) - file(GLOB CT_ALL_DATA_TESTS test/data-tests/*.cpp) - endif() - - if(Osmium_DEBUG) - message(STATUS "Checking example code : ${CT_ALL_EXAMPLES}") - message(STATUS "Checking unit test code: ${CT_ALL_UNIT_TESTS}") - message(STATUS "Checking includes : ${CT_ALL_INCLUDES}") - message(STATUS "Checking benchmarks : ${CT_ALL_BENCHMARKS}") - message(STATUS "Checking data test code: ${CT_ALL_DATA_TESTS}") - endif() - - set(CT_CHECK_FILES - ${CT_ALL_EXAMPLES} - ${CT_ALL_UNIT_TESTS} - ${CT_ALL_INCLUDES} - ${CT_ALL_BENCHMARKS} - ${CT_ALL_DATA_TESTS}) - - # For a list of check options, see: - # http://clang.llvm.org/extra/clang-tidy/checks/list.html - - list(APPEND CT_CHECKS "cert-*" - "-cert-err60-cpp") # even the std lib doesn't do this - - # disabled, because it is slow -# list(APPEND CT_CHECKS "clang-analyzer-*") - - list(APPEND CT_CHECKS "google-*" - "-google-explicit-constructor" - "-google-readability-casting" - "-google-readability-function") - - list(APPEND CT_CHECKS "llvm-*" - "-llvm-include-order") - - list(APPEND CT_CHECKS "misc-*" - "-misc-argument-comment") - - list(APPEND CT_CHECKS "modernize-*") - - list(APPEND CT_CHECKS "readability-*" - "-readability-identifier-naming" - "-readability-named-parameter") - - string(REPLACE ";" "," ALL_CHECKS "${CT_CHECKS}") - - add_custom_target(clang-tidy - ${CLANG_TIDY} - -p ${CMAKE_BINARY_DIR} - -header-filter='include/osmium/.*' - -checks="${ALL_CHECKS}" - ${CT_CHECK_FILES} - ) -else() - message(STATUS "Looking for clang-tidy - not found") - message(STATUS " Build target 'clang-tidy' will not be available.") -endif() - -#----------------------------------------------------------------------------- -# -# Installation -# -# External libraries are only installed if the options are set in case they -# are installed from somewhere else. -# -#----------------------------------------------------------------------------- -install(DIRECTORY include/osmium DESTINATION include) - -if(INSTALL_GDALCPP) - install(FILES include/gdalcpp.hpp DESTINATION include) -endif() - -if(INSTALL_PROTOZERO) - install(DIRECTORY include/protozero DESTINATION include) -endif() - -if(INSTALL_UTFCPP) - install(FILES include/utf8.h DESTINATION include) - install(DIRECTORY include/utf8 DESTINATION include) -endif() - - -#----------------------------------------------------------------------------- -# -# Packaging -# -#----------------------------------------------------------------------------- - -set(CPACK_PACKAGE_VERSION_MAJOR ${LIBOSMIUM_VERSION_MAJOR}) -set(CPACK_PACKAGE_VERSION_MINOR ${LIBOSMIUM_VERSION_MINOR}) -set(CPACK_PACKAGE_VERSION_PATCH ${LIBOSMIUM_VERSION_PATCH}) - -if(WIN32) - set(CPACK_GENERATOR ZIP) -else() - set(CPACK_GENERATOR TGZ) -endif() - -include(CPack) - - -#----------------------------------------------------------------------------- -# -# Print warnings at the end -# -#----------------------------------------------------------------------------- -if(BUILD_DATA_TESTS AND OSM_TESTDATA STREQUAL "OSM_TESTDATA-NOTFOUND") - message("\n========================== WARNING ==========================") - message("osm-testdata directory not found, data tests were disabled!\n") - message("You can get it from https://github.com/osmcode/osm-testdata") - message("Clone it into the same directory libosmium is in") - message("or set the OSM_TESTDATA cmake variable to its path.") - message("=============================================================\n") -endif() - -#----------------------------------------------------------------------------- diff --git a/third_party/libosmium/CONTRIBUTING.md b/third_party/libosmium/CONTRIBUTING.md deleted file mode 100644 index 1064b94de..000000000 --- a/third_party/libosmium/CONTRIBUTING.md +++ /dev/null @@ -1,143 +0,0 @@ - -# Notes for Developers - -Read this if you want to contribute to Libosmium. - - -## Versioning - -Osmium is currently considered in beta and doesn't use versioning yet. Proper -versions will be introduced as soon as it is somewhat stable. - - -## Namespace - -All Osmium code MUST be in the `osmium` namespace or one of its sub-namespaces. - - -## Include-Only - -Osmium is a include-only library. You can't compile the library itself. There -is no libosmium.so. - -One drawback ist that you can't have static data in classes, because there -is no place to put this data. - -All free functions must be declared `inline`. - - -## Coding Conventions - -These coding conventions have been changing over time and some code is still -different. - -* All include files have `#ifdef` guards around them, macros are the path name - in all uppercase where the slashes (`/`) have been changed to underscore (`_`). -* Class names begin with uppercase chars and use CamelCase. Smaller helper - classes are usually defined as struct and have lowercase names. -* Macros (and only macros) are all uppercase. Use macros sparingly, usually - a simple (maybe constexpr) inline function is better. Undef macros after use - if possible. -* Macros should only be used for controlling which parts of the code should be - included when compiling or to avoid major code repetitions. -* Variables, attributes, and function names are lowercase with - `underscores_between_words`. -* Class attribute names start with `m_` (member). -* Use `descriptive_variable_names`, exceptions are well-established conventions - like `i` for a loop variable. Iterators are usually called `it`. -* Declare variables where they are first used (C++ style), not at the beginning - of a function (old C style). -* Names from external namespaces (even `std`) are always mentioned explicitly. - Do not use `using` (except for `std::swap`). This way we can't even by - accident pollute the namespace of the code using Osmium. -* Always use the standard swap idiom: `using std::swap; swap(foo, bar);`. -* `#include` directives appear in three "blocks" after the copyright notice. - The blocks are separated by blank lines. First block contains `#include`s for - standard C/C++ includes, second block for any external libs used, third - block for osmium internal includes. Within each block `#include`s are usually - sorted by path name. All `#include`s use `<>` syntax not `""`. -* Names not to be used from outside the library should be in a namespace - called `detail` under the namespace where they would otherwise appear. If - whole include files are never meant to be included from outside they should - be in a subdirectory called `detail`. -* All files have suffix `.hpp`. -* Closing } of all classes and namespaces should have a trailing comment - with the name of the class/namespace. -* All constructors with one (or more arguments if they have a default) should - be declared "explicit" unless there is a reason for them not to be. Document - that reason. -* If a class has any of the special methods (copy/move constructor/assigment, - destructor) it should have all of them, possibly marking them as default or - deleted. -* Typedefs have `names_like_this_type` which end in `_type`. Typedefs should - use the new `using foo_type = bar` syntax instead of the old - `typedef bar foo_type`. -* Template parameters are single uppercase letters or start with uppercase `T` - and use CamelCase. -* Always use `typename` in templates, not `class`: `template `. -* The ellipsis in variadic template never has a space to the left of it and - always has a space to the right: `template ` etc. - -Keep to the indentation and other styles used in the code. Use `make indent` -in the toplevel directory to fix indentation and styling. It calls `astyle` -with the right parameters. This program is in the `astyle` Debian package. - - -## C++11 - -Osmium uses C++11 and you can use its features such as auto, lambdas, -threading, etc. There are a few features we do not use, because even modern -compilers don't support them yet. This list might change as we get more data -about which compilers support which feature and what operating system versions -or distributions have which versions of these compilers installed. - -GCC 4.6 - too old, not supported (Ubuntu 12.04 LTS) -GCC 4.7.2 - can probably not be supported (Debian wheezy) -GCC 4.7.3 - probably works -GCC 4.8 - works and is supported from here on -clang 3.0 - too old, not supported (Debian wheezy, Ubuntu 12.04 LTS) -clang 3.2 - probably works -clang 3.5 - works and is supported from here on - -Use `include/osmium/util/compatibility.hpp` if there are compatibility problems -between compilers due to different C++11 support. - - -## Checking your code - -The Osmium makefiles use pretty draconian warning options for the compiler. -This is good. Code MUST never produce any warnings, even with those settings. -If absolutely necessary pragmas can be used to disable certain warnings in -specific areas of the code. - -If the static code checker `cppcheck` is installed, the CMake configuration -will add a new build target `cppcheck` that will check all `.cpp` and `.hpp` -files. Cppcheck finds some bugs that gcc/clang doesn't. But take the result -with a grain of salt, it also sometimes produces wrong warnings. - -Set `BUILD_HEADERS=ON` in the CMake config to enable compiling all include -files on their own to check whether dependencies are all okay. All include -files MUST include all other include files they depend on. - -Call `cmake/iwyu.sh` to check for proper includes and forward declarations. -This uses the clang-based `include-what-you-use` program. Note that it does -produce some false reports and crashes often. The `osmium.imp` file can be -used to define mappings for iwyu. See the IWYU tool at -. - - -## Testing - -There are a unit tests using the Catch Unit Test Framework in the `test` -directory and some data tests in `test/osm-testdata`. They are built by the -default cmake config. Run `ctest` to run them. Many more tests are needed. - - -## Documenting the code - -All namespaces, classes, functions, attributes, etc. should be documented. - -Osmium uses the Doxygen (www.doxygen.org) source code documentation system. -If it is installed, the CMake configuration will add a new build target, so -you can build it with `make doc`. - diff --git a/third_party/libosmium/EXTERNAL_LICENSES.txt b/third_party/libosmium/EXTERNAL_LICENSES.txt deleted file mode 100644 index 7b06fcf41..000000000 --- a/third_party/libosmium/EXTERNAL_LICENSES.txt +++ /dev/null @@ -1,233 +0,0 @@ - -==== For protozero from https://github.com/mapbox/protozero - -protozero copyright (c) Mapbox. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -==== For protozero from https://github.com/mapbox/protozero - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - -==== For utf8.h - -Copyright 2006 Nemanja Trifunovic - -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. - diff --git a/third_party/libosmium/LICENSE.txt b/third_party/libosmium/LICENSE.txt deleted file mode 100644 index 36b7cd93c..000000000 --- a/third_party/libosmium/LICENSE.txt +++ /dev/null @@ -1,23 +0,0 @@ -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. diff --git a/third_party/libosmium/Makefile b/third_party/libosmium/Makefile deleted file mode 100644 index 7b2b83d7b..000000000 --- a/third_party/libosmium/Makefile +++ /dev/null @@ -1,25 +0,0 @@ - -all: - mkdir -p build && cd build && cmake .. && $(MAKE) - -doc: - mkdir -p build && cd build && cmake .. && $(MAKE) doc - -clean: - if test -d build; then cd build && $(MAKE) clean; fi - -distclean: - rm -fr build - -#deb: -# debuild -I -us -uc -# -#deb-clean: -# debuild clean - -indent: - astyle --style=java --indent-namespaces --indent-switches --pad-header --lineend=linux --suffix=none --recursive include/\*.hpp examples/\*.cpp test/\*.cpp -# astyle --style=java --indent-namespaces --indent-switches --pad-header --unpad-paren --align-pointer=type --lineend=linux --suffix=none --recursive include/\*.hpp examples/\*.cpp test/\*.cpp - -.PHONY: clean distclean deb deb-clean doc indent - diff --git a/third_party/libosmium/README.md b/third_party/libosmium/README.md deleted file mode 100644 index 68fc2f61b..000000000 --- a/third_party/libosmium/README.md +++ /dev/null @@ -1,114 +0,0 @@ -# Libosmium - -http://osmcode.org/libosmium - -A fast and flexible C++ library for working with OpenStreetMap data. - -[![Build Status](https://secure.travis-ci.org/osmcode/libosmium.png)](https://travis-ci.org/osmcode/libosmium) -[![Build status](https://ci.appveyor.com/api/projects/status/mkbg6e6stdgq7c1b?svg=true)](https://ci.appveyor.com/project/Mapbox/libosmium) - -Libosmium is developed on Linux, but also works on OSX and Windows (with some -limitations). - -There are a few applications that use the Osmium library in the examples -directory. See the [osmium-contrib](http://github.com/osmcode/osmium-contrib) -repository for more example code. - -## Prerequisites - -Because Libosmium uses many C++11 features you need a modern compiler and -standard C++ library. Osmium needs at least GCC 4.8 or clang (LLVM) 3.4. -(Some parts may work with older versions.) - -Different parts of Libosmium (and the applications built on top of it) need -different libraries. You DO NOT NEED to install all of them, just install those -you need for your programs. - -For details see the -[list of dependencies](https://github.com/osmcode/libosmium/wiki/Libosmium-dependencies). - -The following external (header-only) libraries are included in the libosmium -repository: -* [gdalcpp](https://github.com/joto/gdalcpp) -* [protozero](https://github.com/mapbox/protozero) -* [utfcpp](http://utfcpp.sourceforge.net/) - -If you want (some of) those libraries to be installed along with libosmium -itself when calling `make install`, you have to use the CMake options -`INSTALL_GDALCPP`, `INSTALL_PROTOZERO`, and/or `INSTALL_UTFCPP`. - - -## Directories - -* benchmarks: Some benchmarks checking different parts of Libosmium. - -* cmake: CMake configuration scripts. - -* doc: Config for documentation. - -* examples: Osmium example applications. - -* include: C/C++ include files. All of Libosmium is in those header files - which are needed for building Osmium applications. - -* test: Tests (see below). - - -## Building - -Osmium is a header-only library, so there is nothing to build for the -library itself. - -But there are some tests and examples that can be build. Libosmium uses -cmake: - - mkdir build - cd build - cmake .. - make - -This will build the examples and tests. Call `ctest` to run the tests. - -For more see the -[Libosmium Wiki](https://github.com/osmcode/libosmium/wiki/Building-Libosmium). - - -## Testing - -See the -[Libosmium Wiki](https://github.com/osmcode/libosmium/wiki/Testing-Libosmium) -for instructions. - - -## Osmium on 32bit Machines - -Osmium works well on 64 bit machines, but on 32 bit machines there are some -problems. Be aware that not everything will work on 32 bit architectures. -This is mostly due to the 64 bit needed for node IDs. Also Osmium hasn't been -tested well on 32 bit systems. Here are some issues you might run into: - -* Google Sparsehash does not work on 32 bit machines in our use case. -* The `mmap` system call is called with a `size_t` argument, so it can't - give you more than 4GByte of memory on 32 bit systems. This might be a - problem. - -Please report any issues you have and we might be able to solve them. - - -## Switching from the old Osmium - -If you have been using the old version of Osmium at -https://github.com/joto/osmium you might want to read about the -[changes needed](https://github.com/osmcode/libosmium/wiki/Changes-from-old-versions-of-Osmium). - - -## License - -Libosmium is available under the Boost Software License. See LICENSE.txt. - - -## Authors - -Libosmium was mainly written and is maintained by Jochen Topf -(jochen@topf.org). See the git commit log for other authors. - diff --git a/third_party/libosmium/appveyor.yml b/third_party/libosmium/appveyor.yml deleted file mode 100644 index 8244d98e7..000000000 --- a/third_party/libosmium/appveyor.yml +++ /dev/null @@ -1,109 +0,0 @@ -#----------------------------------------------------------------------------- -# -# Configuration for continuous integration service at appveyor.com -# -#----------------------------------------------------------------------------- - -environment: - matrix: - - config: Dev - - config: RelWithDebInfo - -shallow_clone: true - -# Operating system (build VM template) -os: Visual Studio 2015 - -# scripts that are called at very beginning, before repo cloning -init: - -# clone directory -clone_folder: c:\projects\libosmium - -platform: x64 - -install: - # show all available env vars - - set - - echo cmake on AppVeyor - - cmake -version - - call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 - - set PATH=c:\projects\libosmium\cmake-3.1.0-win32-x86\bin;%PATH% - - set LODEPSDIR=c:\projects\libosmium\libosmium-deps - - set PROJ_LIB=%LODEPSDIR%\proj\share - - set GDAL_DATA=%LODEPSDIR%\gdal\data - #geos.dll - - set PATH=%LODEPSDIR%\geos\lib;%PATH% - #gdal.dll - - set PATH=%LODEPSDIR%\gdal\lib;%PATH% - #libexpat.dll - - set PATH=%LODEPSDIR%\expat\lib;%PATH% - #libtiff.dll - - set PATH=%LODEPSDIR%\libtiff\lib;%PATH% - #jpeg.dll - - set PATH=%LODEPSDIR%\jpeg\lib;%PATH% - #zlibwapi.dll - - set PATH=%LODEPSDIR%\zlib\lib;%PATH% - #convert backslashes in bzip2 path to forward slashes - #cmake cannot find it otherwise - - set LIBBZIP2=%LODEPSDIR%\bzip2\lib\libbz2.lib - - set LIBBZIP2=%LIBBZIP2:\=/% - - ps: Start-FileDownload https://mapbox.s3.amazonaws.com/windows-builds/windows-build-deps/cmake-3.1.0-win32-x86.7z -FileName cm.7z - - ps: Start-FileDownload https://mapbox.s3.amazonaws.com/windows-builds/windows-build-deps/libosmium-deps-win-14.0-x64.7z -FileName lodeps.7z - - 7z x cm.7z | %windir%\system32\find "ing archive" - - 7z x lodeps.7z | %windir%\system32\find "ing archive" - - echo %LODEPSDIR% - - dir %LODEPSDIR% - - echo our own cmake - - cmake -version - - cd c:\projects - - git clone --depth 1 https://github.com/osmcode/osm-testdata.git - -build_script: - - cd c:\projects\libosmium - - mkdir build - - cd build - - echo %config% - # This will produce lots of LNK4099 warnings which can be ignored. - # Unfortunately they can't be disabled, see - # http://stackoverflow.com/questions/661606/visual-c-how-to-disable-specific-linker-warnings - - cmake -LA -G "Visual Studio 14 Win64" - -DOsmium_DEBUG=TRUE - -DCMAKE_BUILD_TYPE=%config% - -DBUILD_HEADERS=OFF - -DBOOST_ROOT=%LODEPSDIR%\boost - -DBoost_PROGRAM_OPTIONS_LIBRARY=%LODEPSDIR%\boost\lib\libboost_program_options-vc140-mt-1_58.lib - -DZLIB_LIBRARY=%LODEPSDIR%\zlib\lib\zlibwapi.lib - -DBZIP2_LIBRARY_RELEASE=%LIBBZIP2% - -DCMAKE_PREFIX_PATH=%LODEPSDIR%\zlib;%LODEPSDIR%\expat;%LODEPSDIR%\bzip2;%LODEPSDIR%\geos;%LODEPSDIR%\gdal;%LODEPSDIR%\proj;%LODEPSDIR%\sparsehash;%LODEPSDIR%\wingetopt - .. - - msbuild libosmium.sln /p:Configuration=%config% /toolsversion:14.0 /p:Platform=x64 /p:PlatformToolset=v140 - #- cmake .. -LA -G "NMake Makefiles" - # -DOsmium_DEBUG=TRUE - # -DCMAKE_BUILD_TYPE=%config% - # -DBOOST_ROOT=%LODEPSDIR%\boost - # -DBoost_PROGRAM_OPTIONS_LIBRARY=%LODEPSDIR%\boost\lib\libboost_program_options-vc140-mt-1_57.lib - # -DZLIB_LIBRARY=%LODEPSDIR%\zlib\lib\zlibwapi.lib - # -DZLIB_INCLUDE_DIR=%LODEPSDIR%\zlib\include - # -DEXPAT_LIBRARY=%LODEPSDIR%\expat\lib\libexpat.lib - # -DEXPAT_INCLUDE_DIR=%LODEPSDIR%\expat\include - # -DBZIP2_LIBRARIES=%LIBBZIP2% - # -DBZIP2_INCLUDE_DIR=%LODEPSDIR%\bzip2\include - # -DGDAL_LIBRARY=%LODEPSDIR%\gdal\lib\gdal_i.lib - # -DGDAL_INCLUDE_DIR=%LODEPSDIR%\gdal\include - # -DGEOS_LIBRARY=%LODEPSDIR%\geos\lib\geos.lib - # -DGEOS_INCLUDE_DIR=%LODEPSDIR%\geos\include - # -DPROJ_LIBRARY=%LODEPSDIR%\proj\lib\proj.lib - # -DPROJ_INCLUDE_DIR=%LODEPSDIR%\proj\include - # -DSPARSEHASH_INCLUDE_DIR=%LODEPSDIR%\sparsehash\include - # -DGETOPT_LIBRARY=%LODEPSDIR%\wingetopt\lib\wingetopt.lib - # -DGETOPT_INCLUDE_DIR=%LODEPSDIR%\wingetopt\include - #- nmake - -test_script: - # "-E testdata-overview" exempts one test we know fails on Appveyor - # because we currently don't have spatialite support. - - ctest --output-on-failure - -C %config% - -E testdata-overview - diff --git a/third_party/libosmium/benchmarks/CMakeLists.txt b/third_party/libosmium/benchmarks/CMakeLists.txt deleted file mode 100644 index e46c83349..000000000 --- a/third_party/libosmium/benchmarks/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ -#----------------------------------------------------------------------------- -# -# CMake Config -# -# Libosmium benchmarks -# -#----------------------------------------------------------------------------- - -message(STATUS "Configuring benchmarks") - -set(BENCHMARKS - count - count_tag - index_map - static_vs_dynamic_index - write_pbf - CACHE STRING "Benchmark programs" -) - - -#----------------------------------------------------------------------------- -# -# Configure benchmarks -# -#----------------------------------------------------------------------------- - -message(STATUS "Configuring benchmarks - Building these benchmarks:") -foreach(benchmark ${BENCHMARKS}) - message(STATUS " - osmium_benchmark_${benchmark}") - add_executable(osmium_benchmark_${benchmark} - "osmium_benchmark_${benchmark}.cpp") - target_link_libraries(osmium_benchmark_${benchmark} - ${OSMIUM_IO_LIBRARIES} - ${BENCHMARK_LIBS_${benchmark}}) - configure_file(run_benchmark_${benchmark}.sh - ${CMAKE_CURRENT_BINARY_DIR}/run_benchmark_${benchmark}.sh - @ONLY) -endforeach() - -foreach(file setup run_benchmarks) - configure_file(${file}.sh ${CMAKE_CURRENT_BINARY_DIR}/${file}.sh @ONLY) -endforeach() - - -#----------------------------------------------------------------------------- -message(STATUS "Configuring benchmarks - done") - - -#----------------------------------------------------------------------------- diff --git a/third_party/libosmium/benchmarks/README.md b/third_party/libosmium/benchmarks/README.md deleted file mode 100644 index f10045ca0..000000000 --- a/third_party/libosmium/benchmarks/README.md +++ /dev/null @@ -1,41 +0,0 @@ - -# Benchmarks - -Benchmarks check the performance of different parts of Libosmium. - -## Preparations - -To run the benchmarks first make a directory for the data files somewhere -(outside the repository) and set the `DATA_DIR` environment variable: - - export DATA_DIR=benchmark_data - mkdir $DATA_DIR - -Then copy the OSM files you want to do the benchmarks with into this directory. -You can use the `download_data.sh` script to download a selection of OSM files -in different sizes, but you can use a different selection, too. The benchmarks -will use whatever files you have in the `DATA_DIR` directory. - -The download script will start the data files names with a number in order of -the size of the file from smallest to largest. You can use the same convention -or use a different one. Benchmarks will be run on the files in alphabetical -order. - -The files don't have to be in that directory, you can add soft links from that -directory to the real file locations if that suits you. - -## Compiling the benchmarks - -To build the benchmarks set the `BUILD_BENCHMARKS` option when configuring with -CMake and run the compilation by calling `make` (or whatever build tool you -are using). - -## Running the benchmarks - -Go to the build directory and run `benchmarks/run_benchmarks.sh`. You can also -run each benchmark on its own by calling the respective script in the -`benchmarks` directory. - -Results of the benchmarks will be printed to stdout, you might want to redirect -them into a file. - diff --git a/third_party/libosmium/benchmarks/download_data.sh b/third_party/libosmium/benchmarks/download_data.sh deleted file mode 100755 index 8a6a8ff50..000000000 --- a/third_party/libosmium/benchmarks/download_data.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -# -# download_data.sh -# - -cd $DATA_DIR -curl --location --output 1_liechtenstein.osm.pbf http://download.geofabrik.de/europe/liechtenstein-latest.osm.pbf # about 1 MB -curl --location --output 2_bremen.osm.pbf http://download.geofabrik.de/europe/germany/bremen-latest.osm.pbf # about 13 MB -curl --location --output 3_sachsen.osm.pbf http://download.geofabrik.de/europe/germany/sachsen-latest.osm.pbf # about 120 MB -curl --location --output 4_germany.osm.pbf http://download.geofabrik.de/europe/germany-latest.osm.pbf # about 2 GB -curl --location --output 5_planet.osm.pbf http://planet.osm.org/pbf/planet-latest.osm.pbf # about 26 GB - diff --git a/third_party/libosmium/benchmarks/osmium_benchmark_count.cpp b/third_party/libosmium/benchmarks/osmium_benchmark_count.cpp deleted file mode 100644 index d50c53dc8..000000000 --- a/third_party/libosmium/benchmarks/osmium_benchmark_count.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - - The code in this file is released into the Public Domain. - -*/ - -#include -#include - -#include -#include -#include - -struct CountHandler : public osmium::handler::Handler { - - uint64_t nodes = 0; - uint64_t ways = 0; - uint64_t relations = 0; - - void node(osmium::Node&) { - ++nodes; - } - - void way(osmium::Way&) { - ++ways; - } - - void relation(osmium::Relation&) { - ++relations; - } - -}; - - -int main(int argc, char* argv[]) { - if (argc != 2) { - std::cerr << "Usage: " << argv[0] << " OSMFILE\n"; - exit(1); - } - - std::string input_filename = argv[1]; - - osmium::io::Reader reader(input_filename); - - CountHandler handler; - osmium::apply(reader, handler); - reader.close(); - - std::cout << "Nodes: " << handler.nodes << "\n"; - std::cout << "Ways: " << handler.ways << "\n"; - std::cout << "Relations: " << handler.relations << "\n"; -} - diff --git a/third_party/libosmium/benchmarks/osmium_benchmark_count_tag.cpp b/third_party/libosmium/benchmarks/osmium_benchmark_count_tag.cpp deleted file mode 100644 index 8fa696a4e..000000000 --- a/third_party/libosmium/benchmarks/osmium_benchmark_count_tag.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - - The code in this file is released into the Public Domain. - -*/ - -#include -#include - -#include -#include -#include - -struct CountHandler : public osmium::handler::Handler { - - uint64_t counter = 0; - uint64_t all = 0; - - void node(osmium::Node& node) { - ++all; - const char* amenity = node.tags().get_value_by_key("amenity"); - if (amenity && !strcmp(amenity, "post_box")) { - ++counter; - } - } - - void way(osmium::Way&) { - ++all; - } - - void relation(osmium::Relation&) { - ++all; - } - -}; - - -int main(int argc, char* argv[]) { - if (argc != 2) { - std::cerr << "Usage: " << argv[0] << " OSMFILE\n"; - exit(1); - } - - std::string input_filename = argv[1]; - - osmium::io::Reader reader(input_filename); - - CountHandler handler; - osmium::apply(reader, handler); - reader.close(); - - std::cout << "r_all=" << handler.all << " r_counter=" << handler.counter << "\n"; -} - diff --git a/third_party/libosmium/benchmarks/osmium_benchmark_index_map.cpp b/third_party/libosmium/benchmarks/osmium_benchmark_index_map.cpp deleted file mode 100644 index 025782618..000000000 --- a/third_party/libosmium/benchmarks/osmium_benchmark_index_map.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - - The code in this file is released into the Public Domain. - -*/ - -#include - -#include -#include -#include - -#include -#include - -typedef osmium::index::map::Map index_type; - -typedef osmium::handler::NodeLocationsForWays location_handler_type; - -int main(int argc, char* argv[]) { - if (argc != 3) { - std::cerr << "Usage: " << argv[0] << " OSMFILE FORMAT\n"; - exit(1); - } - - std::string input_filename = argv[1]; - std::string location_store = argv[2]; - - osmium::io::Reader reader(input_filename); - - const auto& map_factory = osmium::index::MapFactory::instance(); - std::unique_ptr index = map_factory.create_map(location_store); - location_handler_type location_handler(*index); - location_handler.ignore_errors(); - - osmium::apply(reader, location_handler); - reader.close(); -} - diff --git a/third_party/libosmium/benchmarks/osmium_benchmark_static_vs_dynamic_index.cpp b/third_party/libosmium/benchmarks/osmium_benchmark_static_vs_dynamic_index.cpp deleted file mode 100644 index 66e2a0bd9..000000000 --- a/third_party/libosmium/benchmarks/osmium_benchmark_static_vs_dynamic_index.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - - This benchmarks compares the run time for statically vs. dynamically - configured index maps. You can configure index maps at compile-time using - typedefs or at run-time using polymorphism. - - This will read the input file into a buffer and then run the - NodeLocationForWays handler multiple times over the complete data. The - number of runs depends on the size of the input, but is never smaller - than 10. - - Do not run this with very large input files! It will need about 10 times - as much RAM as the file size of the input file. - - The code in this file is released into the Public Domain. - -*/ - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -typedef osmium::index::map::SparseMemArray static_index_type; -const std::string location_store="sparse_mem_array"; - -typedef osmium::index::map::Map dynamic_index_type; - -typedef osmium::handler::NodeLocationsForWays static_location_handler_type; -typedef osmium::handler::NodeLocationsForWays dynamic_location_handler_type; - -int main(int argc, char* argv[]) { - if (argc != 2) { - std::cerr << "Usage: " << argv[0] << " OSMFILE\n"; - exit(1); - } - - std::string input_filename = argv[1]; - - osmium::memory::Buffer buffer = osmium::io::read_file(input_filename); - - const auto& map_factory = osmium::index::MapFactory::instance(); - - const auto buffer_size = buffer.committed() / (1024*1024); // buffer size in MBytes - const int runs = std::max(10, static_cast(5000ull / buffer_size)); - - std::cout << "input: filename=" << input_filename << " buffer_size=" << buffer_size << "MBytes\n"; - std::cout << "runs: " << runs << "\n"; - - double static_min = std::numeric_limits::max(); - double static_sum = 0; - double static_max = 0; - - double dynamic_min = std::numeric_limits::max(); - double dynamic_sum = 0; - double dynamic_max = 0; - - for (int i = 0; i < runs; ++i) { - - { - // static index - osmium::memory::Buffer tmp_buffer(buffer.committed()); - for (const auto& item : buffer) { - tmp_buffer.add_item(item); - tmp_buffer.commit(); - } - - static_index_type static_index; - static_location_handler_type static_location_handler(static_index); - - auto start = std::chrono::steady_clock::now(); - osmium::apply(tmp_buffer, static_location_handler); - auto end = std::chrono::steady_clock::now(); - - double duration = std::chrono::duration(end-start).count(); - - if (duration < static_min) static_min = duration; - if (duration > static_max) static_max = duration; - static_sum += duration; - } - - { - // dynamic index - osmium::memory::Buffer tmp_buffer(buffer.committed()); - for (const auto& item : buffer) { - tmp_buffer.add_item(item); - tmp_buffer.commit(); - } - - std::unique_ptr index = map_factory.create_map(location_store); - dynamic_location_handler_type dynamic_location_handler(*index); - dynamic_location_handler.ignore_errors(); - - auto start = std::chrono::steady_clock::now(); - osmium::apply(tmp_buffer, dynamic_location_handler); - auto end = std::chrono::steady_clock::now(); - - double duration = std::chrono::duration(end-start).count(); - - if (duration < dynamic_min) dynamic_min = duration; - if (duration > dynamic_max) dynamic_max = duration; - dynamic_sum += duration; - } - } - - double static_avg = static_sum/runs; - double dynamic_avg = dynamic_sum/runs; - - std::cout << "static min=" << static_min << "ms avg=" << static_avg << "ms max=" << static_max << "ms\n"; - std::cout << "dynamic min=" << dynamic_min << "ms avg=" << dynamic_avg << "ms max=" << dynamic_max << "ms\n"; - - double rfactor = 100.0; - double diff_min = std::round((dynamic_min - static_min) * rfactor) / rfactor; - double diff_avg = std::round((dynamic_avg - static_avg) * rfactor) / rfactor; - double diff_max = std::round((dynamic_max - static_max) * rfactor) / rfactor; - - double prfactor = 10.0; - double percent_min = std::round((100.0 * diff_min / static_min) * prfactor) / prfactor; - double percent_avg = std::round((100.0 * diff_avg / static_avg) * prfactor) / prfactor; - double percent_max = std::round((100.0 * diff_max / static_max) * prfactor) / prfactor; - - std::cout << "difference:"; - std::cout << " min=" << diff_min << "ms (" << percent_min << "%)"; - std::cout << " avg=" << diff_avg << "ms (" << percent_avg << "%)"; - std::cout << " max=" << diff_max << "ms (" << percent_max << "%)\n"; -} - diff --git a/third_party/libosmium/benchmarks/osmium_benchmark_write_pbf.cpp b/third_party/libosmium/benchmarks/osmium_benchmark_write_pbf.cpp deleted file mode 100644 index 869f3a8f8..000000000 --- a/third_party/libosmium/benchmarks/osmium_benchmark_write_pbf.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - - The code in this file is released into the Public Domain. - -*/ - -#include -#include - -#include -#include - -int main(int argc, char* argv[]) { - if (argc != 3) { - std::cerr << "Usage: " << argv[0] << " INPUT-FILE OUTPUT-FILE\n"; - exit(1); - } - - std::string input_filename = argv[1]; - std::string output_filename = argv[2]; - - osmium::io::Reader reader(input_filename); - osmium::io::File output_file(output_filename, "pbf"); - osmium::io::Header header; - osmium::io::Writer writer(output_file, header, osmium::io::overwrite::allow); - - while (osmium::memory::Buffer buffer = reader.read()) { - writer(std::move(buffer)); - } - - writer.close(); - reader.close(); -} - diff --git a/third_party/libosmium/benchmarks/run_benchmark_count.sh b/third_party/libosmium/benchmarks/run_benchmark_count.sh deleted file mode 100755 index d71508f76..000000000 --- a/third_party/libosmium/benchmarks/run_benchmark_count.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh -# -# run_benchmark_count.sh -# - -set -e - -BENCHMARK_NAME=count - -. @CMAKE_BINARY_DIR@/benchmarks/setup.sh - -CMD=$OB_DIR/osmium_benchmark_$BENCHMARK_NAME - -echo "# file size num mem time cpu_kernel cpu_user cpu_percent cmd options" -for data in $OB_DATA_FILES; do - filename=`basename $data` - filesize=`stat --format="%s" --dereference $data` - for n in $OB_SEQ; do - $OB_TIME_CMD -f "$filename $filesize $n $OB_TIME_FORMAT" $CMD $data 2>&1 >/dev/null | sed -e "s%$DATA_DIR/%%" | sed -e "s%$OB_DIR/%%" - done -done - diff --git a/third_party/libosmium/benchmarks/run_benchmark_count_tag.sh b/third_party/libosmium/benchmarks/run_benchmark_count_tag.sh deleted file mode 100755 index 4fa6a1068..000000000 --- a/third_party/libosmium/benchmarks/run_benchmark_count_tag.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh -# -# run_benchmark_count_tag.sh -# - -set -e - -BENCHMARK_NAME=count_tag - -. @CMAKE_BINARY_DIR@/benchmarks/setup.sh - -CMD=$OB_DIR/osmium_benchmark_$BENCHMARK_NAME - -echo "# file size num mem time cpu_kernel cpu_user cpu_percent cmd options" -for data in $OB_DATA_FILES; do - filename=`basename $data` - filesize=`stat --format="%s" --dereference $data` - for n in $OB_SEQ; do - $OB_TIME_CMD -f "$filename $filesize $n $OB_TIME_FORMAT" $CMD $data 2>&1 >/dev/null | sed -e "s%$DATA_DIR/%%" | sed -e "s%$OB_DIR/%%" - done -done - diff --git a/third_party/libosmium/benchmarks/run_benchmark_index_map.sh b/third_party/libosmium/benchmarks/run_benchmark_index_map.sh deleted file mode 100755 index 30984d460..000000000 --- a/third_party/libosmium/benchmarks/run_benchmark_index_map.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/sh -# -# run_benchmark_index_map.sh -# - -set -e - -BENCHMARK_NAME=index_map - -. @CMAKE_BINARY_DIR@/benchmarks/setup.sh - -CMD=$OB_DIR/osmium_benchmark_$BENCHMARK_NAME - -#MAPS="sparse_mem_map sparse_mem_table sparse_mem_array sparse_mmap_array sparse_file_array dense_mem_array dense_mmap_array dense_file_array" -MAPS="sparse_mem_map sparse_mem_table sparse_mem_array sparse_mmap_array sparse_file_array" - -echo "# file size num mem time cpu_kernel cpu_user cpu_percent cmd options" -for data in $OB_DATA_FILES; do - filename=`basename $data` - filesize=`stat --format="%s" --dereference $data` - for map in $MAPS; do - for n in $OB_SEQ; do - $OB_TIME_CMD -f "$filename $filesize $n $OB_TIME_FORMAT" $CMD $data $map 2>&1 >/dev/null | sed -e "s%$DATA_DIR/%%" | sed -e "s%$OB_DIR/%%" - done - done -done - diff --git a/third_party/libosmium/benchmarks/run_benchmark_static_vs_dynamic_index.sh b/third_party/libosmium/benchmarks/run_benchmark_static_vs_dynamic_index.sh deleted file mode 100755 index 05e32f126..000000000 --- a/third_party/libosmium/benchmarks/run_benchmark_static_vs_dynamic_index.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -# -# run_benchmark_static_vs_dynamic_index.sh -# - -set -e - -BENCHMARK_NAME=static_vs_dynamic_index - -. @CMAKE_BINARY_DIR@/benchmarks/setup.sh - -CMD=$OB_DIR/osmium_benchmark_$BENCHMARK_NAME - -for data in $OB_DATA_FILES; do - filesize=`stat --format="%s" --dereference $data` - if [ $filesize -lt 500000000 ]; then - echo "========================" - $CMD $data - fi -done - diff --git a/third_party/libosmium/benchmarks/run_benchmark_write_pbf.sh b/third_party/libosmium/benchmarks/run_benchmark_write_pbf.sh deleted file mode 100755 index 814309770..000000000 --- a/third_party/libosmium/benchmarks/run_benchmark_write_pbf.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/sh -# -# run_benchmark_write_pbf.sh -# -# Will read the input file and after reading it into memory completely, -# write it to /dev/null. Because this will need the time to read *and* write -# the file, it will report the times for reading and writing. You can -# subtract the times needed for the "count" benchmark to (roughly) get the -# write times. -# - -set -e - -BENCHMARK_NAME=write_pbf - -. @CMAKE_BINARY_DIR@/benchmarks/setup.sh - -CMD=$OB_DIR/osmium_benchmark_$BENCHMARK_NAME - -echo "# file size num mem time cpu_kernel cpu_user cpu_percent cmd options" -for data in $OB_DATA_FILES; do - filename=`basename $data` - filesize=`stat --format="%s" --dereference $data` - for n in $OB_SEQ; do - $OB_TIME_CMD -f "$filename $filesize $n $OB_TIME_FORMAT" $CMD $data /dev/null 2>&1 >/dev/null | sed -e "s%$DATA_DIR/%%" | sed -e "s%$OB_DIR/%%" - done -done - diff --git a/third_party/libosmium/benchmarks/run_benchmarks.sh b/third_party/libosmium/benchmarks/run_benchmarks.sh deleted file mode 100755 index 6a20c0214..000000000 --- a/third_party/libosmium/benchmarks/run_benchmarks.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# -# run_benchmarks.sh -# -# Run all benchmarks. -# - -set -e - -for benchmark in @CMAKE_BINARY_DIR@/benchmarks/run_benchmark_*.sh; do - name=`basename $benchmark` - echo "Running $name..." - $benchmark -done - diff --git a/third_party/libosmium/benchmarks/setup.sh b/third_party/libosmium/benchmarks/setup.sh deleted file mode 100755 index 9733bfe1b..000000000 --- a/third_party/libosmium/benchmarks/setup.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/sh -# -# setup.sh -# - -if [ -z $DATA_DIR ]; then - echo "Please set DATA_DIR environment variable before running benchmark" - exit 1 -fi - -OB_DIR=@CMAKE_BINARY_DIR@/benchmarks - -OB_RUNS=3 -OB_SEQ=`seq -s' ' 1 $OB_RUNS` - -OB_TIME_CMD=/usr/bin/time -OB_TIME_FORMAT="%M %e %S %U %P %C" - -OB_DATA_FILES=`find -L $DATA_DIR -mindepth 1 -maxdepth 1 -type f | sort` - -echo "BENCHMARK: $BENCHMARK_NAME" -echo "---------------------" -echo "CPU:" -grep '^model name' /proc/cpuinfo | tail -1 -grep '^cpu MHz' /proc/cpuinfo | tail -1 -grep '^cpu cores' /proc/cpuinfo | tail -1 -grep '^siblings' /proc/cpuinfo | tail -1 - -echo "---------------------" -echo "MEMORY:" -free -echo "---------------------" -echo "RESULTS:" - diff --git a/third_party/libosmium/cmake/FindGem.cmake b/third_party/libosmium/cmake/FindGem.cmake deleted file mode 100644 index f5389d1e8..000000000 --- a/third_party/libosmium/cmake/FindGem.cmake +++ /dev/null @@ -1,153 +0,0 @@ -# Author thomas.roehr@dfki.de -# -# Version 0.3 2013-07-02 -# - rely on `gem content` to find library and header -# - introduce GEM_OS_PKG to allow search via pkgconfig -# Version 0.2 2010-01-14 -# - add support for searching for multiple gems -# Version 0.1 2010-12-15 -# - support basic search functionality -# - tested to find rice -# -# OUTPUT: -# -# GEM_INCLUDE_DIRS After successful search contains the include directores -# -# GEM_LIBRARIES After successful search contains the full path of each found library -# -# -# Usage: -# set(GEM_DEBUG TRUE) -# find_package(Gem COMPONENTS rice hoe) -# include_directories(${GEM_INCLUDE_DIRS}) -# target_link_libraries(${GEM_LIBRARIES} -# -# in case pkg-config should be used to search for the os pkg, set GEM_OS_PKG, i.e. -# set(GEM_OS_PKG TRUE) -# -# Check for how 'gem' should be called -include(FindPackageHandleStandardArgs) -find_program(GEM_EXECUTABLE - NAMES "gem${RUBY_VERSION_MAJOR}${RUBY_VERSION_MINOR}" - "gem${RUBY_VERSION_MAJOR}.${RUBY_VERSION_MINOR}" - "gem-${RUBY_VERSION_MAJOR}${RUBY_VERSION_MINOR}" - "gem-${RUBY_VERSION_MAJOR}.${RUBY_VERSION_MINOR}" - "gem${RUBY_VERSION_MAJOR}${RUBY_VERSION_MINOR}${RUBY_VERSION_PATCH}" - "gem${RUBY_VERSION_MAJOR}.${RUBY_VERSION_MINOR}.${RUBY_VERSION_PATCH}" - "gem-${RUBY_VERSION_MAJOR}${RUBY_VERSION_MINOR}${RUBY_VERSION_PATCH}" - "gem-${RUBY_VERSION_MAJOR}.${RUBY_VERSION_MINOR}.${RUBY_VERSION_PATCH}" - "gem") - -# Making backward compatible -if(Gem_DEBUG) - set(GEM_DEBUG TRUE) -endif() - -if(NOT GEM_EXECUTABLE) - MESSAGE(FATAL_ERROR "Could not find the gem executable - install 'gem' first") -endif() - -if(NOT Gem_FIND_COMPONENTS) - MESSAGE(FATAL_ERROR "If searching for a Gem you have to provide COMPONENTS with the name of the gem") -endif() - -foreach(Gem_NAME ${Gem_FIND_COMPONENTS}) - set(GEM_${Gem_NAME}_FOUND TRUE) - list(APPEND components_found_vars GEM_${Gem_NAME}_FOUND) - # If the gem is installed as a gem - if(NOT GEM_OS_PKG) - set(GEM_HOME ENV{GEM_HOME}) - - # Use `gem content ` to extract current information about installed gems - # Store the information into ${GEM_LOCAL_INFO} - EXECUTE_PROCESS(COMMAND ${GEM_EXECUTABLE} content ${Gem_NAME} - RESULT_VARIABLE GEM_RUN_RESULT - OUTPUT_VARIABLE GEM_LOCAL_INFO) - - if(GEM_RUN_RESULT STREQUAL "0") - list(APPEND FOUND_GEMS ${Gem_NAME}) - set(_library_NAME_PATTERN lib${Gem_NAME}.a - lib${Gem_NAME}.so - lib${Gem_NAME}.dylib - ${Gem_NAME}.a - ${Gem_NAME}.so - ${Gem_NAME}.dylib - .*.a - .*.so - .*.dylib - ) - - set(_header_SUFFIX_PATTERN - .h - .hh - .hpp - ) - - # Create a list from the output results of the gem command - string(REPLACE "\n" ";" GEM_CONTENT_LIST "${GEM_LOCAL_INFO}") - foreach(_gem_CONTENT_PATH ${GEM_CONTENT_LIST}) - - # Convert so that only '/' Unix path separator are being using - # needed to do proper regex matching - FILE(TO_CMAKE_PATH ${_gem_CONTENT_PATH} gem_CONTENT_PATH) - - # Identify library -- checking for a library in the gems 'lib' (sub)directory - # Search for an existing library, but only within the gems folder - foreach(_library_NAME ${_library_NAME_PATTERN}) - STRING(REGEX MATCH ".*${Gem_NAME}.*/lib/.*${_library_NAME}$" GEM_PATH_INFO "${gem_CONTENT_PATH}") - if(NOT "${GEM_PATH_INFO}" STREQUAL "") - list(APPEND GEM_LIBRARIES ${GEM_PATH_INFO}) - break() - endif() - endforeach() - - # Identify headers - # Checking for available headers in an include directory - foreach(_header_PATTERN ${_header_SUFFIX_PATTERN}) - STRING(REGEX MATCH ".*${Gem_NAME}.*/include/.*${_header_PATTERN}$" GEM_PATH_INFO "${gem_CONTENT_PATH}") - if(NOT "${GEM_PATH_INFO}" STREQUAL "") - STRING(REGEX REPLACE "(.*${Gem_NAME}.*/include/).*${_header_PATTERN}$" "\\1" GEM_PATH_INFO "${gem_CONTENT_PATH}") - list(APPEND GEM_INCLUDE_DIRS ${GEM_PATH_INFO}) - break() - endif() - endforeach() - endforeach() - else() - set(GEM_${Gem_NAME}_FOUND FALSE) - endif() - else(NOT GEM_OS_PKG) - pkg_check_modules(GEM_PKG ${Gem_NAME}) - set(GEM_${GEM_NAME}_FOUND GEM_PKG_FOUND) - set(GEM_INCLUDE_DIRS ${GEM_PKG_INCLUDE_DIRS}) - set(GEM_LIBRARIES ${GEM_PKG_LIBRARIES} ${GEM_PKG_STATIC_LIBRARIES}) - list(APPEND GEM_LIBRARIES ${GEM_PKG_LDFLAGS} ${GEM_PKG_STATIC_LDFLAGS}) - list(APPEND GEM_LIBRARIES ${GEM_PKG_LDFLAGS_OTHER} ${GEM_PKG_STATIC_LDFLAGS_OTHER}) - - if(GEM_DEBUG) - message(STATUS "GEM_OS_PKG is defined") - message(STATUS "GEM_INCLUDE_DIRS ${GEM_INCLUDE_DIRS}") - message(STATUS "GEM_STATIC_LIBRARY_DIRS ${GEM_PKG_STATIC_LIBRARY_DIRS}") - message(STATUS "GEM_LIBRARY_DIRS ${GEM_PKG_STATIC_LIBRARY_DIRS}") - message(STATUS "GEM_STATIC_LIBRARIES ${GEM_PKG_STATIC_LIBRARIES}") - message(STATUS "GEM_LIBRARIES ${GEM_LIBRARIES}") - endif() - endif() - - if(GEM_DEBUG) - message(STATUS "${Gem_NAME} library dir: ${GEM_LIBRARIES}") - message(STATUS "${Gem_NAME} include dir: ${GEM_INCLUDE_DIRS}") - endif() -endforeach() - -# Compact the lists -if(DEFINED GEM_LIBRARIES) - LIST(REMOVE_DUPLICATES GEM_LIBRARIES) -endif() -if(DEFINED GEM_INCLUDE_DIRS) - LIST(REMOVE_DUPLICATES GEM_INCLUDE_DIRS) -endif() - -find_package_handle_standard_args(GEM - REQUIRED_VARS ${components_found_vars} - FAIL_MESSAGE "Could not find all required gems") - diff --git a/third_party/libosmium/cmake/FindOsmium.cmake b/third_party/libosmium/cmake/FindOsmium.cmake deleted file mode 100644 index fba8ffb92..000000000 --- a/third_party/libosmium/cmake/FindOsmium.cmake +++ /dev/null @@ -1,318 +0,0 @@ -#---------------------------------------------------------------------- -# -# FindOsmium.cmake -# -# Find the Libosmium headers and, optionally, several components needed for -# different Libosmium functions. -# -#---------------------------------------------------------------------- -# -# Usage: -# -# Copy this file somewhere into your project directory, where cmake can -# find it. Usually this will be a directory called "cmake" which you can -# add to the CMake module search path with the following line in your -# CMakeLists.txt: -# -# list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") -# -# Then add the following in your CMakeLists.txt: -# -# find_package(Osmium REQUIRED COMPONENTS ) -# include_directories(SYSTEM ${OSMIUM_INCLUDE_DIRS}) -# -# For the substitute a space separated list of one or more of the -# following components: -# -# pbf - include libraries needed for PBF input and output -# xml - include libraries needed for XML input and output -# io - include libraries needed for any type of input/output -# geos - include if you want to use any of the GEOS functions -# gdal - include if you want to use any of the OGR functions -# proj - include if you want to use any of the Proj.4 functions -# sparsehash - include if you use the sparsehash index -# -# You can check for success with something like this: -# -# if(NOT OSMIUM_FOUND) -# message(WARNING "Libosmium not found!\n") -# endif() -# -#---------------------------------------------------------------------- -# -# Variables: -# -# OSMIUM_FOUND - True if Osmium found. -# OSMIUM_INCLUDE_DIRS - Where to find include files. -# OSMIUM_XML_LIBRARIES - Libraries needed for XML I/O. -# OSMIUM_PBF_LIBRARIES - Libraries needed for PBF I/O. -# OSMIUM_IO_LIBRARIES - Libraries needed for XML or PBF I/O. -# OSMIUM_LIBRARIES - All libraries Osmium uses somewhere. -# -#---------------------------------------------------------------------- - -# Look for the header file. -find_path(OSMIUM_INCLUDE_DIR osmium/osm.hpp - PATH_SUFFIXES include - PATHS - ../libosmium - ~/Library/Frameworks - /Library/Frameworks - /opt/local # DarwinPorts - /opt -) - -set(OSMIUM_INCLUDE_DIRS "${OSMIUM_INCLUDE_DIR}") - -#---------------------------------------------------------------------- -# -# Check for optional components -# -#---------------------------------------------------------------------- -if(Osmium_FIND_COMPONENTS) - foreach(_component ${Osmium_FIND_COMPONENTS}) - string(TOUPPER ${_component} _component_uppercase) - set(Osmium_USE_${_component_uppercase} TRUE) - endforeach() -endif() - -#---------------------------------------------------------------------- -# Component 'io' is an alias for 'pbf' and 'xml' -if(Osmium_USE_IO) - set(Osmium_USE_PBF TRUE) - set(Osmium_USE_XML TRUE) -endif() - -#---------------------------------------------------------------------- -# Component 'ogr' is an alias for 'gdal' -if(Osmium_USE_OGR) - set(Osmium_USE_GDAL TRUE) -endif() - -#---------------------------------------------------------------------- -# Component 'pbf' -if(Osmium_USE_PBF) - find_package(ZLIB) - find_package(Threads) - - list(APPEND OSMIUM_EXTRA_FIND_VARS ZLIB_FOUND Threads_FOUND) - if(ZLIB_FOUND AND Threads_FOUND) - list(APPEND OSMIUM_PBF_LIBRARIES - ${ZLIB_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - ) - if(WIN32) - list(APPEND OSMIUM_PBF_LIBRARIES ws2_32) - endif() - list(APPEND OSMIUM_INCLUDE_DIRS - ${ZLIB_INCLUDE_DIR} - ) - else() - message(WARNING "Osmium: Can not find some libraries for PBF input/output, please install them or configure the paths.") - endif() -endif() - -#---------------------------------------------------------------------- -# Component 'xml' -if(Osmium_USE_XML) - find_package(EXPAT) - find_package(BZip2) - find_package(ZLIB) - find_package(Threads) - - list(APPEND OSMIUM_EXTRA_FIND_VARS EXPAT_FOUND BZIP2_FOUND ZLIB_FOUND Threads_FOUND) - if(EXPAT_FOUND AND BZIP2_FOUND AND ZLIB_FOUND AND Threads_FOUND) - list(APPEND OSMIUM_XML_LIBRARIES - ${EXPAT_LIBRARIES} - ${BZIP2_LIBRARIES} - ${ZLIB_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - ) - list(APPEND OSMIUM_INCLUDE_DIRS - ${EXPAT_INCLUDE_DIR} - ${BZIP2_INCLUDE_DIR} - ${ZLIB_INCLUDE_DIR} - ) - else() - message(WARNING "Osmium: Can not find some libraries for XML input/output, please install them or configure the paths.") - endif() -endif() - -#---------------------------------------------------------------------- -list(APPEND OSMIUM_IO_LIBRARIES - ${OSMIUM_PBF_LIBRARIES} - ${OSMIUM_XML_LIBRARIES} -) - -list(APPEND OSMIUM_LIBRARIES - ${OSMIUM_IO_LIBRARIES} -) - -#---------------------------------------------------------------------- -# Component 'geos' -if(Osmium_USE_GEOS) - find_path(GEOS_INCLUDE_DIR geos/geom.h) - find_library(GEOS_LIBRARY NAMES geos) - - list(APPEND OSMIUM_EXTRA_FIND_VARS GEOS_INCLUDE_DIR GEOS_LIBRARY) - if(GEOS_INCLUDE_DIR AND GEOS_LIBRARY) - SET(GEOS_FOUND 1) - list(APPEND OSMIUM_LIBRARIES ${GEOS_LIBRARY}) - list(APPEND OSMIUM_INCLUDE_DIRS ${GEOS_INCLUDE_DIR}) - else() - message(WARNING "Osmium: GEOS library is required but not found, please install it or configure the paths.") - endif() -endif() - -#---------------------------------------------------------------------- -# Component 'gdal' (alias 'ogr') -if(Osmium_USE_GDAL) - find_package(GDAL) - - list(APPEND OSMIUM_EXTRA_FIND_VARS GDAL_FOUND) - if(GDAL_FOUND) - list(APPEND OSMIUM_LIBRARIES ${GDAL_LIBRARIES}) - list(APPEND OSMIUM_INCLUDE_DIRS ${GDAL_INCLUDE_DIRS}) - else() - message(WARNING "Osmium: GDAL library is required but not found, please install it or configure the paths.") - endif() -endif() - -#---------------------------------------------------------------------- -# Component 'proj' -if(Osmium_USE_PROJ) - find_path(PROJ_INCLUDE_DIR proj_api.h) - find_library(PROJ_LIBRARY NAMES proj) - - list(APPEND OSMIUM_EXTRA_FIND_VARS PROJ_INCLUDE_DIR PROJ_LIBRARY) - if(PROJ_INCLUDE_DIR AND PROJ_LIBRARY) - set(PROJ_FOUND 1) - list(APPEND OSMIUM_LIBRARIES ${PROJ_LIBRARY}) - list(APPEND OSMIUM_INCLUDE_DIRS ${PROJ_INCLUDE_DIR}) - else() - message(WARNING "Osmium: PROJ.4 library is required but not found, please install it or configure the paths.") - endif() -endif() - -#---------------------------------------------------------------------- -# Component 'sparsehash' -if(Osmium_USE_SPARSEHASH) - find_path(SPARSEHASH_INCLUDE_DIR google/sparsetable) - - list(APPEND OSMIUM_EXTRA_FIND_VARS SPARSEHASH_INCLUDE_DIR) - if(SPARSEHASH_INCLUDE_DIR) - # Find size of sparsetable::size_type. This does not work on older - # CMake versions because they can do this check only in C, not in C++. - if (NOT CMAKE_VERSION VERSION_LESS 3.0) - include(CheckTypeSize) - set(CMAKE_REQUIRED_INCLUDES ${SPARSEHASH_INCLUDE_DIR}) - set(CMAKE_EXTRA_INCLUDE_FILES "google/sparsetable") - check_type_size("google::sparsetable::size_type" SPARSETABLE_SIZE_TYPE LANGUAGE CXX) - set(CMAKE_EXTRA_INCLUDE_FILES) - set(CMAKE_REQUIRED_INCLUDES) - else() - set(SPARSETABLE_SIZE_TYPE ${CMAKE_SIZEOF_VOID_P}) - endif() - - # Sparsetable::size_type must be at least 8 bytes (64bit), otherwise - # OSM object IDs will not fit. - if(SPARSETABLE_SIZE_TYPE GREATER 7) - set(SPARSEHASH_FOUND 1) - add_definitions(-DOSMIUM_WITH_SPARSEHASH=${SPARSEHASH_FOUND}) - list(APPEND OSMIUM_INCLUDE_DIRS ${SPARSEHASH_INCLUDE_DIR}) - else() - message(WARNING "Osmium: Disabled Google SparseHash library on 32bit system (size_type=${SPARSETABLE_SIZE_TYPE}).") - endif() - else() - message(WARNING "Osmium: Google SparseHash library is required but not found, please install it or configure the paths.") - endif() -endif() - -#---------------------------------------------------------------------- - -list(REMOVE_DUPLICATES OSMIUM_INCLUDE_DIRS) - -if(OSMIUM_XML_LIBRARIES) - list(REMOVE_DUPLICATES OSMIUM_XML_LIBRARIES) -endif() - -if(OSMIUM_PBF_LIBRARIES) - list(REMOVE_DUPLICATES OSMIUM_PBF_LIBRARIES) -endif() - -if(OSMIUM_IO_LIBRARIES) - list(REMOVE_DUPLICATES OSMIUM_IO_LIBRARIES) -endif() - -if(OSMIUM_LIBRARIES) - list(REMOVE_DUPLICATES OSMIUM_LIBRARIES) -endif() - -#---------------------------------------------------------------------- -# -# Check that all required libraries are available -# -#---------------------------------------------------------------------- -if (OSMIUM_EXTRA_FIND_VARS) - list(REMOVE_DUPLICATES OSMIUM_EXTRA_FIND_VARS) -endif() -# Handle the QUIETLY and REQUIRED arguments and set OSMIUM_FOUND to TRUE if -# all listed variables are TRUE. -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Osmium REQUIRED_VARS OSMIUM_INCLUDE_DIR ${OSMIUM_EXTRA_FIND_VARS}) -unset(OSMIUM_EXTRA_FIND_VARS) - -#---------------------------------------------------------------------- -# -# Add compiler flags -# -#---------------------------------------------------------------------- -add_definitions(-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64) - -if(MSVC) - add_definitions(-wd4996) - - # Disable warning C4068: "unknown pragma" because we want it to ignore - # pragmas for other compilers. - add_definitions(-wd4068) - - # Disable warning C4715: "not all control paths return a value" because - # it generates too many false positives. - add_definitions(-wd4715) - - # Disable warning C4351: new behavior: elements of array '...' will be - # default initialized. The new behaviour is correct and we don't support - # old compilers anyway. - add_definitions(-wd4351) - - add_definitions(-DNOMINMAX -DWIN32_LEAN_AND_MEAN -D_CRT_SECURE_NO_WARNINGS) -endif() - -if(APPLE) -# following only available from cmake 2.8.12: -# add_compile_options(-stdlib=libc++) -# so using this instead: - add_definitions(-stdlib=libc++) - set(LDFLAGS ${LDFLAGS} -stdlib=libc++) -endif() - -#---------------------------------------------------------------------- - -# This is a set of recommended warning options that can be added when compiling -# libosmium code. -if(MSVC) - set(OSMIUM_WARNING_OPTIONS "/W3 /wd4514" CACHE STRING "Recommended warning options for libosmium") -else() - set(OSMIUM_WARNING_OPTIONS "-Wall -Wextra -pedantic -Wredundant-decls -Wdisabled-optimization -Wctor-dtor-privacy -Wnon-virtual-dtor -Woverloaded-virtual -Wsign-promo -Wold-style-cast" CACHE STRING "Recommended warning options for libosmium") -endif() - -set(OSMIUM_DRACONIC_CLANG_OPTIONS "-Wdocumentation -Wunused-exception-parameter -Wmissing-declarations -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-unused-macros -Wno-exit-time-destructors -Wno-global-constructors -Wno-padded -Wno-switch-enum -Wno-missing-prototypes -Wno-weak-vtables -Wno-cast-align -Wno-float-equal") - -if(Osmium_DEBUG) - message(STATUS "OSMIUM_XML_LIBRARIES=" ${OSMIUM_XML_LIBRARIES}) - message(STATUS "OSMIUM_PBF_LIBRARIES=" ${OSMIUM_PBF_LIBRARIES}) - message(STATUS "OSMIUM_IO_LIBRARIES=" ${OSMIUM_IO_LIBRARIES}) - message(STATUS "OSMIUM_LIBRARIES=" ${OSMIUM_LIBRARIES}) - message(STATUS "OSMIUM_INCLUDE_DIRS=" ${OSMIUM_INCLUDE_DIRS}) -endif() - diff --git a/third_party/libosmium/cmake/README b/third_party/libosmium/cmake/README deleted file mode 100644 index 4a035f7b2..000000000 --- a/third_party/libosmium/cmake/README +++ /dev/null @@ -1,3 +0,0 @@ - -FindGem.cmake from https://github.com/rock-core/base-cmake - diff --git a/third_party/libosmium/cmake/build.bat b/third_party/libosmium/cmake/build.bat deleted file mode 100644 index 5ffab124e..000000000 --- a/third_party/libosmium/cmake/build.bat +++ /dev/null @@ -1,15 +0,0 @@ -call "%VS120COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64 -set CMAKE_PREFIX_PATH=C:\PROJ -set VERSION=Debug -set TESTS=ON -set ALLHPPS=ON -set PREFIX=d:\libs18d -set BOOST_ROOT=d:\boost - -cmake .. -G "Visual Studio 12 Win64" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=%PREFIX% -DBOOST_ROOT=%BOOST_ROOT% -DBoost_USE_STATIC_LIBS=ON -DBUILD_TESTING=%TESTS% -DBUILD_TRY_HPPS=%ALLHPPS$ -T CTP_Nov2013 -msbuild /clp:Verbosity=minimal /nologo libosmium.sln /flp1:logfile=build_errors.txt;errorsonly /flp2:logfile=build_warnings.txt;warningsonly -set PATH=%PATH%;%PREFIX%/bin - -del test\osm-testdata\*.db -del test\osm-testdata\*.json -if "%TESTS%"=="ON" ctest -VV >build_tests.log diff --git a/third_party/libosmium/cmake/iwyu.sh b/third_party/libosmium/cmake/iwyu.sh deleted file mode 100755 index ceea106c3..000000000 --- a/third_party/libosmium/cmake/iwyu.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/sh -# -# This will run IWYU (Include What You Use) on includes files. The iwyu -# program isn't very reliable and crashes often, but is still useful. -# -# TODO: This script should be integrated with cmake in some way... -# - -cmdline="iwyu -Xiwyu --mapping_file=osmium.imp -std=c++11 -I include" - -log=build/iwyu.log - -mkdir -p build/check_reports - -echo "INCLUDE WHAT YOU USE REPORT:" >$log - -allok=yes - -for file in `find include/osmium -name \*.hpp | sort`; do - mkdir -p `dirname build/check_reports/$file` - ifile="build/check_reports/${file%.hpp}.iwyu" - $cmdline $file >$ifile 2>&1 - if grep -q 'has correct #includes/fwd-decls' ${ifile}; then - echo "\n\033[1m\033[32m========\033[0m \033[1m${file}\033[0m" >>$log - echo "[OK] ${file}" - elif grep -q 'Assertion failed' ${ifile}; then - echo "\n\033[1m======== ${file}\033[0m" >>$log - echo "[--] ${file}" - allok=no - else - echo "\n\033[1m\033[31m========\033[0m \033[1m${file}\033[0m" >>$log - echo "[ ] ${file}" - allok=no - fi - cat $ifile >>$log -done - -if [ "$allok" = "yes" ]; then - echo "All files OK" -else - echo "There were errors" -fi - diff --git a/third_party/libosmium/doc/CMakeLists.txt b/third_party/libosmium/doc/CMakeLists.txt deleted file mode 100644 index 5ea819b92..000000000 --- a/third_party/libosmium/doc/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -#----------------------------------------------------------------------------- -# -# CMake Config -# -# Libosmium documentation -# -#----------------------------------------------------------------------------- - -message(STATUS "Configuring documentation") - -message(STATUS "Looking for doxygen") -find_package(Doxygen) - -if(DOXYGEN_FOUND) - message(STATUS "Looking for doxygen - found") - configure_file(header.html ${CMAKE_CURRENT_BINARY_DIR}/header.html @ONLY) - configure_file(Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY) - add_custom_target(doc - ${DOXYGEN_EXECUTABLE} - ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} - COMMENT "Generating API documentation with Doxygen" VERBATIM - ) -else() - message(STATUS "Looking for doxygen - not found") - message(STATUS " Disabled making of documentation.") -endif() - -#----------------------------------------------------------------------------- -message(STATUS "Configuring documentation - done") - - -#----------------------------------------------------------------------------- diff --git a/third_party/libosmium/doc/Doxyfile.in b/third_party/libosmium/doc/Doxyfile.in deleted file mode 100644 index d5ed13d2e..000000000 --- a/third_party/libosmium/doc/Doxyfile.in +++ /dev/null @@ -1,2313 +0,0 @@ -# Doxyfile 1.8.7 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a double hash (##) is considered a comment and is placed in -# front of the TAG it is preceding. -# -# All text after a single hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists, items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (\" \"). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all text -# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv -# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv -# for the list of possible encodings. -# The default value is: UTF-8. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by -# double-quotes, unless you are using Doxywizard) that should identify the -# project for which the documentation is generated. This name is used in the -# title of most generated pages and in a few other places. -# The default value is: My Project. - -PROJECT_NAME = "Libosmium" - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. This -# could be handy for archiving the generated documentation or if some version -# control system is used. - -PROJECT_NUMBER = @LIBOSMIUM_VERSION@ - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer a -# quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = "Fast and flexible C++ library for working with OpenStreetMap data" - -# With the PROJECT_LOGO tag one can specify an logo or icon that is included in -# the documentation. The maximum height of the logo should not exceed 55 pixels -# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo -# to the output directory. - -PROJECT_LOGO = - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path -# into which the generated documentation will be written. If a relative path is -# entered, it will be relative to the location where doxygen was started. If -# left blank the current directory will be used. - -OUTPUT_DIRECTORY = "@PROJECT_BINARY_DIR@/doc" - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub- -# directories (in 2 levels) under the output directory of each output format and -# will distribute the generated files over these directories. Enabling this -# option can be useful when feeding doxygen a huge amount of source files, where -# putting all generated files in the same directory would otherwise causes -# performance problems for the file system. -# The default value is: NO. - -CREATE_SUBDIRS = NO - -# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII -# characters to appear in the names of generated files. If set to NO, non-ASCII -# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode -# U+3044. -# The default value is: NO. - -ALLOW_UNICODE_NAMES = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, -# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), -# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, -# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), -# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, -# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, -# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, -# Ukrainian and Vietnamese. -# The default value is: English. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member -# descriptions after the members that are listed in the file and class -# documentation (similar to Javadoc). Set to NO to disable this. -# The default value is: YES. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief -# description of a member or function before the detailed description -# -# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. -# The default value is: YES. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator that is -# used to form the text in various listings. Each string in this list, if found -# as the leading text of the brief description, will be stripped from the text -# and the result, after processing the whole list, is used as the annotated -# text. Otherwise, the brief description is used as-is. If left blank, the -# following values are used ($name is automatically replaced with the name of -# the entity):The $name class, The $name widget, The $name file, is, provides, -# specifies, contains, represents, a, an and the. - -ABBREVIATE_BRIEF = - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# doxygen will generate a detailed section even if there is only a brief -# description. -# The default value is: NO. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. -# The default value is: NO. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path -# before files name in the file list and in the header files. If set to NO the -# shortest path that makes the file name unique will be used -# The default value is: YES. - -FULL_PATH_NAMES = YES - -# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. -# Stripping is only done if one of the specified strings matches the left-hand -# part of the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the path to -# strip. -# -# Note that you can specify absolute paths here, but also relative paths, which -# will be relative from the directory where doxygen is started. -# This tag requires that the tag FULL_PATH_NAMES is set to YES. - -STRIP_FROM_PATH = @PROJECT_SOURCE_DIR@/include - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the -# path mentioned in the documentation of a class, which tells the reader which -# header file to include in order to use a class. If left blank only the name of -# the header file containing the class definition is used. Otherwise one should -# specify the list of include paths that are normally passed to the compiler -# using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but -# less readable) file names. This can be useful is your file systems doesn't -# support long names like on DOS, Mac, or CD-ROM. -# The default value is: NO. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the -# first line (until the first dot) of a Javadoc-style comment as the brief -# description. If set to NO, the Javadoc-style will behave just like regular Qt- -# style comments (thus requiring an explicit @brief command for a brief -# description.) -# The default value is: NO. - -JAVADOC_AUTOBRIEF = NO - -# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first -# line (until the first dot) of a Qt-style comment as the brief description. If -# set to NO, the Qt-style will behave just like regular Qt-style comments (thus -# requiring an explicit \brief command for a brief description.) -# The default value is: NO. - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a -# multi-line C++ special comment block (i.e. a block of //! or /// comments) as -# a brief description. This used to be the default behavior. The new default is -# to treat a multi-line C++ comment block as a detailed description. Set this -# tag to YES if you prefer the old behavior instead. -# -# Note that setting this tag to YES also means that rational rose comments are -# not recognized any more. -# The default value is: NO. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the -# documentation from any documented member that it re-implements. -# The default value is: YES. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a -# new page for each member. If set to NO, the documentation of a member will be -# part of the file/class/namespace that contains it. -# The default value is: NO. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen -# uses this value to replace tabs by spaces in code fragments. -# Minimum value: 1, maximum value: 16, default value: 4. - -TAB_SIZE = 8 - -# This tag can be used to specify a number of aliases that act as commands in -# the documentation. An alias has the form: -# name=value -# For example adding -# "sideeffect=@par Side Effects:\n" -# will allow you to put the command \sideeffect (or @sideeffect) in the -# documentation, which will result in a user-defined paragraph with heading -# "Side Effects:". You can put \n's in the value part of an alias to insert -# newlines. - -ALIASES = - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding "class=itcl::class" -# will allow you to use the command class in the itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources -# only. Doxygen will then generate output that is more tailored for C. For -# instance, some of the names that are used will be different. The list of all -# members will be omitted, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or -# Python sources only. Doxygen will then generate output that is more tailored -# for that language. For instance, namespaces will be presented as packages, -# qualified scopes will look different, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources. Doxygen will then generate output that is tailored for Fortran. -# The default value is: NO. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for VHDL. -# The default value is: NO. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given -# extension. Doxygen has a built-in mapping, but you can override or extend it -# using this tag. The format is ext=language, where ext is a file extension, and -# language is one of the parsers supported by doxygen: IDL, Java, Javascript, -# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: -# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: -# Fortran. In the later case the parser tries to guess whether the code is fixed -# or free formatted code, this is the default for Fortran type files), VHDL. For -# instance to make doxygen treat .inc files as Fortran files (default is PHP), -# and .f files as C (default is Fortran), use: inc=Fortran f=C. -# -# Note For files without extension you can use no_extension as a placeholder. -# -# Note that for custom extensions you also need to set FILE_PATTERNS otherwise -# the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments -# according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you can -# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in -# case of backward compatibilities issues. -# The default value is: YES. - -MARKDOWN_SUPPORT = YES - -# When enabled doxygen tries to link words that correspond to documented -# classes, or namespaces to their corresponding documentation. Such a link can -# be prevented in individual cases by by putting a % sign in front of the word -# or globally by setting AUTOLINK_SUPPORT to NO. -# The default value is: YES. - -AUTOLINK_SUPPORT = YES - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should set this -# tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); -# versus func(std::string) {}). This also make the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. -# The default value is: NO. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. -# The default value is: NO. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: -# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen -# will parse them like normal C++ but will assume all classes use public instead -# of private inheritance when no explicit protection keyword is present. -# The default value is: NO. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate -# getter and setter methods for a property. Setting this option to YES will make -# doxygen to replace the get and set methods by a property in the documentation. -# This will only work if the methods are indeed getting or setting a simple -# type. If this is not the case, or you want to show the methods anyway, you -# should set this option to NO. -# The default value is: YES. - -IDL_PROPERTY_SUPPORT = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. -# The default value is: NO. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES to allow class member groups of the same type -# (for instance a group of public functions) to be put as a subgroup of that -# type (e.g. under the Public Functions section). Set it to NO to prevent -# subgrouping. Alternatively, this can be done per class using the -# \nosubgrouping command. -# The default value is: YES. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions -# are shown inside the group in which they are included (e.g. using \ingroup) -# instead of on a separate page (for HTML and Man pages) or section (for LaTeX -# and RTF). -# -# Note that this feature does not work in combination with -# SEPARATE_MEMBER_PAGES. -# The default value is: NO. - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions -# with only public data fields or simple typedef fields will be shown inline in -# the documentation of the scope in which they are defined (i.e. file, -# namespace, or group documentation), provided this scope is documented. If set -# to NO, structs, classes, and unions are shown on a separate page (for HTML and -# Man pages) or section (for LaTeX and RTF). -# The default value is: NO. - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or -# enum is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically be -# useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. -# The default value is: NO. - -TYPEDEF_HIDES_STRUCT = NO - -# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This -# cache is used to resolve symbols given their name and scope. Since this can be -# an expensive process and often the same symbol appears multiple times in the -# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small -# doxygen will become slower. If the cache is too large, memory is wasted. The -# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range -# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 -# symbols. At the end of a run doxygen will report the cache usage and suggest -# the optimal cache size from a speed point of view. -# Minimum value: 0, maximum value: 9, default value: 0. - -LOOKUP_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. Private -# class members and static file members will be hidden unless the -# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. -# Note: This will also disable the warnings about undocumented members that are -# normally produced when WARNINGS is set to YES. -# The default value is: NO. - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will -# be included in the documentation. -# The default value is: NO. - -EXTRACT_PRIVATE = YES - -# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal -# scope will be included in the documentation. -# The default value is: NO. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file will be -# included in the documentation. -# The default value is: NO. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined -# locally in source files will be included in the documentation. If set to NO -# only classes defined in header files are included. Does not have any effect -# for Java sources. -# The default value is: YES. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local methods, -# which are defined in the implementation section but not in the interface are -# included in the documentation. If set to NO only methods in the interface are -# included. -# The default value is: NO. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base name of -# the file that contains the anonymous namespace. By default anonymous namespace -# are hidden. -# The default value is: NO. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all -# undocumented members inside documented classes or files. If set to NO these -# members will be included in the various overviews, but no documentation -# section is generated. This option has no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. If set -# to NO these classes will be included in the various overviews. This option has -# no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend -# (class|struct|union) declarations. If set to NO these declarations will be -# included in the documentation. -# The default value is: NO. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any -# documentation blocks found inside the body of a function. If set to NO these -# blocks will be appended to the function's detailed documentation block. -# The default value is: NO. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation that is typed after a -# \internal command is included. If the tag is set to NO then the documentation -# will be excluded. Set it to YES to include the internal documentation. -# The default value is: NO. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file -# names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. -# The default value is: system dependent. - -CASE_SENSE_NAMES = YES - -# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with -# their full class and namespace scopes in the documentation. If set to YES the -# scope will be hidden. -# The default value is: NO. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of -# the files that are included by a file in the documentation of that file. -# The default value is: YES. - -SHOW_INCLUDE_FILES = YES - -# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each -# grouped member an include statement to the documentation, telling the reader -# which file to include in order to use the member. -# The default value is: NO. - -SHOW_GROUPED_MEMB_INC = NO - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include -# files with double quotes in the documentation rather than with sharp brackets. -# The default value is: NO. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the -# documentation for inline members. -# The default value is: YES. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the -# (detailed) documentation of file and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. -# The default value is: YES. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief -# descriptions of file, namespace and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. Note that -# this will also influence the order of the classes in the class list. -# The default value is: NO. - -SORT_BRIEF_DOCS = NO - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the -# (brief and detailed) documentation of class members so that constructors and -# destructors are listed first. If set to NO the constructors will appear in the -# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. -# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief -# member documentation. -# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting -# detailed member documentation. -# The default value is: NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy -# of group names into alphabetical order. If set to NO the group names will -# appear in their defined order. -# The default value is: NO. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by -# fully-qualified names, including namespaces. If set to NO, the class list will -# be sorted only by class name, not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the alphabetical -# list. -# The default value is: NO. - -SORT_BY_SCOPE_NAME = NO - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper -# type resolution of all parameters of a function it will reject a match between -# the prototype and the implementation of a member function even if there is -# only one candidate or it is obvious which candidate to choose by doing a -# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still -# accept a match between prototype and implementation in such cases. -# The default value is: NO. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the -# todo list. This list is created by putting \todo commands in the -# documentation. -# The default value is: YES. - -GENERATE_TODOLIST = YES - -# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the -# test list. This list is created by putting \test commands in the -# documentation. -# The default value is: YES. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug -# list. This list is created by putting \bug commands in the documentation. -# The default value is: YES. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO) -# the deprecated list. This list is created by putting \deprecated commands in -# the documentation. -# The default value is: YES. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional documentation -# sections, marked by \if ... \endif and \cond -# ... \endcond blocks. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the -# initial value of a variable or macro / define can have for it to appear in the -# documentation. If the initializer consists of more lines than specified here -# it will be hidden. Use a value of 0 to hide initializers completely. The -# appearance of the value of individual variables and macros / defines can be -# controlled using \showinitializer or \hideinitializer command in the -# documentation regardless of this setting. -# Minimum value: 0, maximum value: 10000, default value: 30. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at -# the bottom of the documentation of classes and structs. If set to YES the list -# will mention the files that were used to generate the documentation. -# The default value is: YES. - -SHOW_USED_FILES = YES - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This -# will remove the Files entry from the Quick Index and from the Folder Tree View -# (if specified). -# The default value is: YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces -# page. This will remove the Namespaces entry from the Quick Index and from the -# Folder Tree View (if specified). -# The default value is: YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command command input-file, where command is the value of the -# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided -# by doxygen. Whatever the program writes to standard output is used as the file -# version. For an example see the documentation. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. To create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. You can -# optionally specify a file name after the option, if omitted DoxygenLayout.xml -# will be used as the name of the layout file. -# -# Note that if you run doxygen from a directory containing a file called -# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE -# tag is left empty. - -LAYOUT_FILE = - -# The CITE_BIB_FILES tag can be used to specify one or more bib files containing -# the reference definitions. This must be a list of .bib files. The .bib -# extension is automatically appended if omitted. This requires the bibtex tool -# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. -# For LaTeX the style of the bibliography can be controlled using -# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the -# search path. Do not use file names with spaces, bibtex cannot handle them. See -# also \cite for info how to create references. - -CITE_BIB_FILES = - -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated to -# standard output by doxygen. If QUIET is set to YES this implies that the -# messages are off. -# The default value is: NO. - -QUIET = YES - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES -# this implies that the warnings are on. -# -# Tip: Turn warnings on while writing the documentation. -# The default value is: YES. - -WARNINGS = YES - -# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate -# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag -# will automatically be disabled. -# The default value is: YES. - -WARN_IF_UNDOCUMENTED = YES - -# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some parameters -# in a documented function, or documenting parameters that don't exist or using -# markup commands wrongly. -# The default value is: YES. - -WARN_IF_DOC_ERROR = YES - -# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that -# are documented, but have no documentation for their parameters or return -# value. If set to NO doxygen will only warn about wrong or incomplete parameter -# documentation, but not about the absence of documentation. -# The default value is: NO. - -WARN_NO_PARAMDOC = NO - -# The WARN_FORMAT tag determines the format of the warning messages that doxygen -# can produce. The string should contain the $file, $line, and $text tags, which -# will be replaced by the file and line number from which the warning originated -# and the warning text. Optionally the format may contain $version, which will -# be replaced by the version of the file (if it could be obtained via -# FILE_VERSION_FILTER) -# The default value is: $file:$line: $text. - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning and error -# messages should be written. If left blank the output is written to standard -# error (stderr). - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag is used to specify the files and/or directories that contain -# documented source files. You may enter file names like myfile.cpp or -# directories like /usr/src/myproject. Separate the files or directories with -# spaces. -# Note: If this tag is empty the current directory is searched. - -INPUT = @PROJECT_SOURCE_DIR@/include/osmium \ - @PROJECT_SOURCE_DIR@/doc/doc.txt - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses -# libiconv (or the iconv built into libc) for the transcoding. See the libiconv -# documentation (see: http://www.gnu.org/software/libiconv) for the list of -# possible encodings. -# The default value is: UTF-8. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank the -# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, -# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, -# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, -# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, -# *.qsf, *.as and *.js. - -FILE_PATTERNS = *.hpp - -# The RECURSIVE tag can be used to specify whether or not subdirectories should -# be searched for input files as well. -# The default value is: NO. - -RECURSIVE = YES - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. -# The default value is: NO. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories for example use the pattern */test/* - -EXCLUDE_PATTERNS = detail - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories use the pattern */test/* - -EXCLUDE_SYMBOLS = *::detail - -# The EXAMPLE_PATH tag can be used to specify one or more files or directories -# that contain example code fragments that are included (see the \include -# command). - -EXAMPLE_PATH = - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank all -# files are included. - -EXAMPLE_PATTERNS = - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude commands -# irrespective of the value of the RECURSIVE tag. -# The default value is: NO. - -EXAMPLE_RECURSIVE = NO - -# The IMAGE_PATH tag can be used to specify one or more files or directories -# that contain images that are to be included in the documentation (see the -# \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command: -# -# -# -# where is the value of the INPUT_FILTER tag, and is the -# name of an input file. Doxygen will then use the output that the filter -# program writes to standard output. If FILTER_PATTERNS is specified, this tag -# will be ignored. -# -# Note that the filter must not add or remove lines; it is applied before the -# code is scanned, but not when the output code is generated. If lines are added -# or removed, the anchors will not be placed correctly. - -INPUT_FILTER = "grep -v static_assert" - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. The filters are a list of the form: pattern=filter -# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how -# filters are used. If the FILTER_PATTERNS tag is empty or if none of the -# patterns match the file name, INPUT_FILTER is applied. - -FILTER_PATTERNS = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER ) will also be used to filter the input files that are used for -# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). -# The default value is: NO. - -FILTER_SOURCE_FILES = YES - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and -# it is also possible to disable source filtering for a specific pattern using -# *.ext= (so without naming a filter). -# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. - -FILTER_SOURCE_PATTERNS = - -# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that -# is part of the input, its contents will be placed on the main page -# (index.html). This can be useful if you have a project on for instance GitHub -# and want to reuse the introduction page also for the doxygen output. - -USE_MDFILE_AS_MAINPAGE = - -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will be -# generated. Documented entities will be cross-referenced with these sources. -# -# Note: To get rid of all source code in the generated output, make sure that -# also VERBATIM_HEADERS is set to NO. -# The default value is: NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body of functions, -# classes and enums directly into the documentation. -# The default value is: NO. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any -# special comment blocks from generated source code fragments. Normal C, C++ and -# Fortran comments will always remain visible. -# The default value is: YES. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES then for each documented -# function all documented functions referencing it will be listed. -# The default value is: NO. - -REFERENCED_BY_RELATION = NO - -# If the REFERENCES_RELATION tag is set to YES then for each documented function -# all documented entities called/used by that function will be listed. -# The default value is: NO. - -REFERENCES_RELATION = NO - -# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set -# to YES, then the hyperlinks from functions in REFERENCES_RELATION and -# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will -# link to the documentation. -# The default value is: YES. - -REFERENCES_LINK_SOURCE = YES - -# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the -# source code will show a tooltip with additional information such as prototype, -# brief description and links to the definition and documentation. Since this -# will make the HTML file larger and loading of large files a bit slower, you -# can opt to disable this feature. -# The default value is: YES. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -SOURCE_TOOLTIPS = YES - -# If the USE_HTAGS tag is set to YES then the references to source code will -# point to the HTML generated by the htags(1) tool instead of doxygen built-in -# source browser. The htags tool is part of GNU's global source tagging system -# (see http://www.gnu.org/software/global/global.html). You will need version -# 4.8.6 or higher. -# -# To use it do the following: -# - Install the latest version of global -# - Enable SOURCE_BROWSER and USE_HTAGS in the config file -# - Make sure the INPUT points to the root of the source tree -# - Run doxygen as normal -# -# Doxygen will invoke htags (and that will in turn invoke gtags), so these -# tools must be available from the command line (i.e. in the search path). -# -# The result: instead of the source browser generated by doxygen, the links to -# source code will now point to the output of htags. -# The default value is: NO. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a -# verbatim copy of the header file for each class for which an include is -# specified. Set to NO to disable this. -# See also: Section \class. -# The default value is: YES. - -VERBATIM_HEADERS = YES - -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all -# compounds will be generated. Enable this if the project contains a lot of -# classes, structs, unions or interfaces. -# The default value is: YES. - -ALPHABETICAL_INDEX = NO - -# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in -# which the alphabetical index list will be split. -# Minimum value: 1, maximum value: 20, default value: 5. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all classes will -# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag -# can be used to specify a prefix (or a list of prefixes) that should be ignored -# while generating the index headers. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output -# The default value is: YES. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each -# generated HTML page (for example: .htm, .php, .asp). -# The default value is: .html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a user-defined HTML header file for -# each generated HTML page. If the tag is left blank doxygen will generate a -# standard header. -# -# To get valid HTML the header file that includes any scripts and style sheets -# that doxygen needs, which is dependent on the configuration options used (e.g. -# the setting GENERATE_TREEVIEW). It is highly recommended to start with a -# default header using -# doxygen -w html new_header.html new_footer.html new_stylesheet.css -# YourConfigFile -# and then modify the file new_header.html. See also section "Doxygen usage" -# for information on how to generate the default header that doxygen normally -# uses. -# Note: The header is subject to change so you typically have to regenerate the -# default header when upgrading to a newer version of doxygen. For a description -# of the possible markers and block names see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_HEADER = header.html - -# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each -# generated HTML page. If the tag is left blank doxygen will generate a standard -# footer. See HTML_HEADER for more information on how to generate a default -# footer and what special commands can be used inside the footer. See also -# section "Doxygen usage" for information on how to generate the default footer -# that doxygen normally uses. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FOOTER = - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style -# sheet that is used by each HTML page. It can be used to fine-tune the look of -# the HTML output. If left blank doxygen will generate a default style sheet. -# See also section "Doxygen usage" for information on how to generate the style -# sheet that doxygen normally uses. -# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as -# it is more robust and this tag (HTML_STYLESHEET) will in the future become -# obsolete. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_STYLESHEET = - -# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user- -# defined cascading style sheet that is included after the standard style sheets -# created by doxygen. Using this option one can overrule certain style aspects. -# This is preferred over using HTML_STYLESHEET since it does not replace the -# standard style sheet and is therefor more robust against future updates. -# Doxygen will copy the style sheet file to the output directory. For an example -# see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_STYLESHEET = "@PROJECT_SOURCE_DIR@/doc/osmium.css" - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that the -# files will be copied as-is; there are no commands or markers available. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_FILES = - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen -# will adjust the colors in the stylesheet and background images according to -# this color. Hue is specified as an angle on a colorwheel, see -# http://en.wikipedia.org/wiki/Hue for more information. For instance the value -# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 -# purple, and 360 is red again. -# Minimum value: 0, maximum value: 359, default value: 220. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_HUE = 220 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors -# in the HTML output. For a value of 0 the output will use grayscales only. A -# value of 255 will produce the most vivid colors. -# Minimum value: 0, maximum value: 255, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_SAT = 100 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the -# luminance component of the colors in the HTML output. Values below 100 -# gradually make the output lighter, whereas values above 100 make the output -# darker. The value divided by 100 is the actual gamma applied, so 80 represents -# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not -# change the gamma. -# Minimum value: 40, maximum value: 240, default value: 80. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting this -# to NO can help when comparing the output of multiple runs. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_TIMESTAMP = NO - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_DYNAMIC_SECTIONS = NO - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries -# shown in the various tree structured indices initially; the user can expand -# and collapse entries dynamically later on. Doxygen will expand the tree to -# such a level that at most the specified number of entries are visible (unless -# a fully collapsed tree already exceeds this amount). So setting the number of -# entries 1 will produce a full collapsed tree by default. 0 is a special value -# representing an infinite number of entries and will result in a full expanded -# tree by default. -# Minimum value: 0, maximum value: 9999, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_INDEX_NUM_ENTRIES = 100 - -# If the GENERATE_DOCSET tag is set to YES, additional index files will be -# generated that can be used as input for Apple's Xcode 3 integrated development -# environment (see: http://developer.apple.com/tools/xcode/), introduced with -# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a -# Makefile in the HTML output directory. Running make will produce the docset in -# that directory and running make install will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at -# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_DOCSET = NO - -# This tag determines the name of the docset feed. A documentation feed provides -# an umbrella under which multiple documentation sets from a single provider -# (such as a company or product suite) can be grouped. -# The default value is: Doxygen generated docs. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# This tag specifies a string that should uniquely identify the documentation -# set bundle. This should be a reverse domain-name style string, e.g. -# com.mycompany.MyDocSet. Doxygen will append .docset to the name. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify -# the documentation publisher. This should be a reverse domain-name style -# string, e.g. com.mycompany.MyDocSet.documentation. -# The default value is: org.doxygen.Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_ID = org.doxygen.Publisher - -# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. -# The default value is: Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_NAME = Publisher - -# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three -# additional HTML index files: index.hhp, index.hhc, and index.hhk. The -# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop -# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on -# Windows. -# -# The HTML Help Workshop contains a compiler that can convert all HTML output -# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML -# files are now used as the Windows 98 help format, and will replace the old -# Windows help format (.hlp) on all Windows platforms in the future. Compressed -# HTML files also contain an index, a table of contents, and you can search for -# words in the documentation. The HTML workshop also contains a viewer for -# compressed HTML files. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_HTMLHELP = NO - -# The CHM_FILE tag can be used to specify the file name of the resulting .chm -# file. You can add a path in front of the file if the result should not be -# written to the html output directory. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_FILE = - -# The HHC_LOCATION tag can be used to specify the location (absolute path -# including file name) of the HTML help compiler ( hhc.exe). If non-empty -# doxygen will try to run the HTML help compiler on the generated index.hhp. -# The file has to be specified with full path. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -HHC_LOCATION = - -# The GENERATE_CHI flag controls if a separate .chi index file is generated ( -# YES) or that it should be included in the master .chm file ( NO). -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -GENERATE_CHI = NO - -# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc) -# and project file content. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_INDEX_ENCODING = - -# The BINARY_TOC flag controls whether a binary table of contents is generated ( -# YES) or a normal table of contents ( NO) in the .chm file. Furthermore it -# enables the Previous and Next buttons. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members to -# the table of contents of the HTML help documentation and to the tree view. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and -# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that -# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help -# (.qch) of the generated HTML documentation. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify -# the file name of the resulting .qch file. The path specified is relative to -# the HTML output folder. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help -# Project output. For more information please see Qt Help Project / Namespace -# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_NAMESPACE = - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt -# Help Project output. For more information please see Qt Help Project / Virtual -# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- -# folders). -# The default value is: doc. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_VIRTUAL_FOLDER = doc - -# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom -# filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the -# custom filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this -# project's filter section matches. Qt Help Project / Filter Attributes (see: -# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_SECT_FILTER_ATTRS = - -# The QHG_LOCATION tag can be used to specify the location of Qt's -# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the -# generated .qhp file. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be -# generated, together with the HTML files, they form an Eclipse help plugin. To -# install this plugin and make it available under the help contents menu in -# Eclipse, the contents of the directory containing the HTML and XML files needs -# to be copied into the plugins directory of eclipse. The name of the directory -# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. -# After copying Eclipse needs to be restarted before the help appears. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the Eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have this -# name. Each documentation set should have its own identifier. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# If you want full control over the layout of the generated HTML pages it might -# be necessary to disable the index and replace it with your own. The -# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top -# of each HTML page. A value of NO enables the index and the value YES disables -# it. Since the tabs in the index contain the same information as the navigation -# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. If the tag -# value is set to YES, a side panel will be generated containing a tree-like -# index structure (just like the one that is generated for HTML Help). For this -# to work a browser that supports JavaScript, DHTML, CSS and frames is required -# (i.e. any modern browser). Windows users are probably better off using the -# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can -# further fine-tune the look of the index. As an example, the default style -# sheet generated by doxygen has an example that shows how to put an image at -# the root of the tree instead of the PROJECT_NAME. Since the tree basically has -# the same information as the tab index, you could consider setting -# DISABLE_INDEX to YES when enabling this option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_TREEVIEW = NONE - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that -# doxygen will group on one line in the generated HTML documentation. -# -# Note that a value of 0 will completely suppress the enum values from appearing -# in the overview section. -# Minimum value: 0, maximum value: 20, default value: 4. -# This tag requires that the tag GENERATE_HTML is set to YES. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used -# to set the initial width (in pixels) of the frame in which the tree is shown. -# Minimum value: 0, maximum value: 1500, default value: 250. -# This tag requires that the tag GENERATE_HTML is set to YES. - -TREEVIEW_WIDTH = 250 - -# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to -# external symbols imported via tag files in a separate window. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of LaTeX formulas included as images in -# the HTML documentation. When you change the font size after a successful -# doxygen run you need to manually remove any form_*.png images from the HTML -# output directory to force them to be regenerated. -# Minimum value: 8, maximum value: 50, default value: 10. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are not -# supported properly for IE 6.0, but are supported on all modern browsers. -# -# Note that when changing this option you need to delete any form_*.png files in -# the HTML output directory before the changes have effect. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see -# http://www.mathjax.org) which uses client side Javascript for the rendering -# instead of using prerendered bitmaps. Use this if you do not have LaTeX -# installed or if you want to formulas look prettier in the HTML output. When -# enabled you may also need to install MathJax separately and configure the path -# to it using the MATHJAX_RELPATH option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -USE_MATHJAX = NO - -# When MathJax is enabled you can set the default output format to be used for -# the MathJax output. See the MathJax site (see: -# http://docs.mathjax.org/en/latest/output.html) for more details. -# Possible values are: HTML-CSS (which is slower, but has the best -# compatibility), NativeMML (i.e. MathML) and SVG. -# The default value is: HTML-CSS. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_FORMAT = HTML-CSS - -# When MathJax is enabled you need to specify the location relative to the HTML -# output directory using the MATHJAX_RELPATH option. The destination directory -# should contain the MathJax.js script. For instance, if the mathjax directory -# is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax -# Content Delivery Network so you can quickly see the result without installing -# MathJax. However, it is strongly recommended to install a local copy of -# MathJax from http://www.mathjax.org before deployment. -# The default value is: http://cdn.mathjax.org/mathjax/latest. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest - -# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax -# extension names that should be enabled during MathJax rendering. For example -# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_EXTENSIONS = - -# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces -# of code that will be used on startup of the MathJax code. See the MathJax site -# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an -# example see the documentation. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_CODEFILE = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box for -# the HTML output. The underlying search engine uses javascript and DHTML and -# should work on any modern browser. Note that when using HTML help -# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) -# there is already a search function so this one should typically be disabled. -# For large projects the javascript based search engine can be slow, then -# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to -# search using the keyboard; to jump to the search box use + S -# (what the is depends on the OS and browser, but it is typically -# , /