diff --git a/include/mbgl/gfx/vertex_attribute.hpp b/include/mbgl/gfx/vertex_attribute.hpp index 4cb09d969..a5916d210 100644 --- a/include/mbgl/gfx/vertex_attribute.hpp +++ b/include/mbgl/gfx/vertex_attribute.hpp @@ -389,7 +389,11 @@ public: protected: template - static bool isConstant(const Evaluated& evaluated) { + static bool isConstant(const Evaluated& evaluated) noexcept { + using PropType = decltype(evaluated.template get()); + using MethodType = decltype(&std::remove_reference_t::isConstant); + static_assert(std::is_nothrow_invocable_v, "isConstant() must be noexcept"); + return evaluated.template get().isConstant(); } diff --git a/include/mbgl/map/camera.hpp b/include/mbgl/map/camera.hpp index efdd23309..3bdacf5e8 100644 --- a/include/mbgl/map/camera.hpp +++ b/include/mbgl/map/camera.hpp @@ -139,21 +139,21 @@ struct FreeCameraOptions { std::optional orientation = std::nullopt; /** Helper function for setting the mercator position as Lat&Lng and altitude in meters */ - void setLocation(const LatLngAltitude& location); + void setLocation(const LatLngAltitude& location) noexcept; /** Helper function for converting mercator position into Lat&Lng and altitude in meters. This function fails to return a value if `position` is invalid or is not set */ - std::optional getLocation() const; + std::optional getLocation() const noexcept; /** Helper function for setting orientation of the camera by defining a focus point on the map. Up vector is required in certain scenarios where bearing can't be deduced from the viewing direction */ - void lookAtPoint(const LatLng& location, const std::optional& upVector = std::nullopt); + void lookAtPoint(const LatLng& location, const std::optional& upVector = std::nullopt) noexcept; /** Helper function for setting the orientation of the camera as a pitch and a bearing. Both values are in degrees */ - void setPitchBearing(double pitch, double bearing); + void setPitchBearing(double pitch, double bearing) noexcept; }; } // namespace mbgl diff --git a/include/mbgl/math/clamp.hpp b/include/mbgl/math/clamp.hpp index 38d430547..563a1a8d4 100644 --- a/include/mbgl/math/clamp.hpp +++ b/include/mbgl/math/clamp.hpp @@ -2,11 +2,13 @@ #include +#include + namespace mbgl { namespace util { template -T clamp(T value, T min_, T max_) { +auto clamp(std::enable_if_t, T> value, T min_, T max_) noexcept { return max(min_, min(max_, value)); } diff --git a/include/mbgl/style/color_ramp_property_value.hpp b/include/mbgl/style/color_ramp_property_value.hpp index ebcc3f68c..187408cce 100644 --- a/include/mbgl/style/color_ramp_property_value.hpp +++ b/include/mbgl/style/color_ramp_property_value.hpp @@ -15,24 +15,24 @@ class ColorRampPropertyValue { private: std::shared_ptr value; - friend bool operator==(const ColorRampPropertyValue& lhs, const ColorRampPropertyValue& rhs) { + friend bool operator==(const ColorRampPropertyValue& lhs, const ColorRampPropertyValue& rhs) noexcept { return (lhs.isUndefined() && rhs.isUndefined()) || (lhs.value && rhs.value && *(lhs.value) == *(rhs.value)); } - friend bool operator!=(const ColorRampPropertyValue& lhs, const ColorRampPropertyValue& rhs) { + friend bool operator!=(const ColorRampPropertyValue& lhs, const ColorRampPropertyValue& rhs) noexcept { return !(lhs == rhs); } public: ColorRampPropertyValue() noexcept = default; - ColorRampPropertyValue(std::shared_ptr value_) + ColorRampPropertyValue(std::shared_ptr value_) noexcept : value(std::move(value_)) {} - bool isUndefined() const { return value == nullptr; } + bool isUndefined() const noexcept { return value == nullptr; } // noop, needed for batch evaluation of paint property values to compile template - Color evaluate(const Evaluator&, TimePoint = {}) const { + Color evaluate(const Evaluator&, TimePoint = {}) const noexcept { return {}; } @@ -41,10 +41,10 @@ public: return *expression::fromExpressionValue(*result); } - bool isDataDriven() const { return false; } - bool hasDataDrivenPropertyDifference(const ColorRampPropertyValue&) const { return false; } + bool isDataDriven() const noexcept { return false; } + bool hasDataDrivenPropertyDifference(const ColorRampPropertyValue&) const noexcept { return false; } - const expression::Expression& getExpression() const { return *value; } + const expression::Expression& getExpression() const noexcept { return *value; } using Dependency = style::expression::Dependency; Dependency getDependencies() const noexcept { return value ? value->dependencies : Dependency::None; } diff --git a/include/mbgl/style/expression/assertion.hpp b/include/mbgl/style/expression/assertion.hpp index aee30724c..888e0e0d4 100644 --- a/include/mbgl/style/expression/assertion.hpp +++ b/include/mbgl/style/expression/assertion.hpp @@ -20,7 +20,7 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; diff --git a/include/mbgl/style/expression/at.hpp b/include/mbgl/style/expression/at.hpp index 58fa54b67..dee926036 100644 --- a/include/mbgl/style/expression/at.hpp +++ b/include/mbgl/style/expression/at.hpp @@ -20,7 +20,7 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; - bool operator==(const Expression& e) const override { + bool operator==(const Expression& e) const noexcept override { if (e.getKind() == Kind::At) { auto rhs = static_cast(&e); return *index == *(rhs->index) && *input == *(rhs->input); diff --git a/include/mbgl/style/expression/boolean_operator.hpp b/include/mbgl/style/expression/boolean_operator.hpp index 5c231397c..b01373beb 100644 --- a/include/mbgl/style/expression/boolean_operator.hpp +++ b/include/mbgl/style/expression/boolean_operator.hpp @@ -19,7 +19,7 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; std::string getOperator() const override { return "any"; } @@ -38,7 +38,7 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; std::string getOperator() const override { return "all"; } diff --git a/include/mbgl/style/expression/case.hpp b/include/mbgl/style/expression/case.hpp index d381825be..33d255184 100644 --- a/include/mbgl/style/expression/case.hpp +++ b/include/mbgl/style/expression/case.hpp @@ -26,7 +26,7 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; diff --git a/include/mbgl/style/expression/coalesce.hpp b/include/mbgl/style/expression/coalesce.hpp index bb2475b00..ffb099965 100644 --- a/include/mbgl/style/expression/coalesce.hpp +++ b/include/mbgl/style/expression/coalesce.hpp @@ -14,8 +14,8 @@ namespace expression { class Coalesce : public Expression { public: using Args = std::vector>; - Coalesce(const type::Type& type_, Args args_) - : Expression(Kind::Coalesce, type_, collectDependencies(args_)), + Coalesce(type::Type type_, Args args_) + : Expression(Kind::Coalesce, std::move(type_), collectDependencies(args_)), args(std::move(args_)) {} static ParseResult parse(const mbgl::style::conversion::Convertible& value, ParsingContext& ctx); @@ -24,11 +24,11 @@ public: void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; - std::size_t getLength() const { return args.size(); } + std::size_t getLength() const noexcept { return args.size(); } Expression* getChild(std::size_t i) const { return args.at(i).get(); } diff --git a/include/mbgl/style/expression/coercion.hpp b/include/mbgl/style/expression/coercion.hpp index 14ca5d036..bc6ad68d7 100644 --- a/include/mbgl/style/expression/coercion.hpp +++ b/include/mbgl/style/expression/coercion.hpp @@ -21,7 +21,7 @@ public: mbgl::Value serialize() const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; diff --git a/include/mbgl/style/expression/collator_expression.hpp b/include/mbgl/style/expression/collator_expression.hpp index 390d8f2ae..311b82f0a 100644 --- a/include/mbgl/style/expression/collator_expression.hpp +++ b/include/mbgl/style/expression/collator_expression.hpp @@ -21,7 +21,7 @@ public: void eachChild(const std::function&) const override; - bool operator==(const Expression&) const override; + bool operator==(const Expression&) const noexcept override; std::vector> possibleOutputs() const override { // Technically the set of possible outputs is the combinatoric set of diff --git a/include/mbgl/style/expression/comparison.hpp b/include/mbgl/style/expression/comparison.hpp index ccd08c46e..e82ff6111 100644 --- a/include/mbgl/style/expression/comparison.hpp +++ b/include/mbgl/style/expression/comparison.hpp @@ -20,10 +20,10 @@ public: BasicComparison(std::string op, std::unique_ptr lhs, std::unique_ptr rhs); void eachChild(const std::function& visit) const override; - bool operator==(const Expression&) const override; + bool operator==(const Expression&) const noexcept override; EvaluationResult evaluate(const EvaluationContext&) const override; std::vector> possibleOutputs() const override; - std::string getOperator() const override; + std::string getOperator() const override { return op; } private: std::string op; @@ -43,10 +43,10 @@ public: std::unique_ptr collator); void eachChild(const std::function& visit) const override; - bool operator==(const Expression&) const override; + bool operator==(const Expression&) const noexcept override; EvaluationResult evaluate(const EvaluationContext&) const override; std::vector> possibleOutputs() const override; - std::string getOperator() const override; + std::string getOperator() const override { return op; } private: std::string op; diff --git a/include/mbgl/style/expression/compound_expression.hpp b/include/mbgl/style/expression/compound_expression.hpp index d4edb5121..5819349d2 100644 --- a/include/mbgl/style/expression/compound_expression.hpp +++ b/include/mbgl/style/expression/compound_expression.hpp @@ -33,13 +33,13 @@ public: std::string getOperator() const override; EvaluationResult evaluate(const EvaluationContext& evaluationParams) const override; - std::vector> possibleOutputs() const override; + std::vector> possibleOutputs() const override { return {std::nullopt}; } void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; - std::optional getParameterCount() const; + std::optional getParameterCount() const noexcept; - static bool exists(const std::string& name); + static bool exists(const std::string& name) noexcept; protected: const detail::SignatureBase& signature; diff --git a/include/mbgl/style/expression/distance.hpp b/include/mbgl/style/expression/distance.hpp index 3fc44b9a2..280f1fe12 100644 --- a/include/mbgl/style/expression/distance.hpp +++ b/include/mbgl/style/expression/distance.hpp @@ -22,21 +22,20 @@ namespace expression { class Distance final : public Expression { public: Distance(GeoJSON geoJSONSource_, Feature::geometry_type geometries_); - ~Distance() override; EvaluationResult evaluate(const EvaluationContext&) const override; static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); - void eachChild(const std::function&) const override {} + void eachChild(const std::function&) const noexcept override {} - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; - std::vector> possibleOutputs() const override; + std::vector> possibleOutputs() const override { return {std::nullopt}; } mbgl::Value serialize() const override; - std::string getOperator() const override; + std::string getOperator() const override { return "distance"; } private: GeoJSON geoJSONSource; diff --git a/include/mbgl/style/expression/dsl.hpp b/include/mbgl/style/expression/dsl.hpp index a928ebdbf..9b6a157eb 100644 --- a/include/mbgl/style/expression/dsl.hpp +++ b/include/mbgl/style/expression/dsl.hpp @@ -29,11 +29,12 @@ std::unique_ptr createExpression(const mbgl::style::conversion::Conv std::unique_ptr error(std::string); std::unique_ptr literal(const char* value); +std::unique_ptr literal(Value&& value); std::unique_ptr literal(const Value& value); std::unique_ptr literal(std::initializer_list value); std::unique_ptr literal(std::initializer_list value); -std::unique_ptr assertion(const type::Type&, +std::unique_ptr assertion(type::Type, std::unique_ptr, std::unique_ptr def = nullptr); std::unique_ptr number(std::unique_ptr, std::unique_ptr def = nullptr); @@ -61,9 +62,9 @@ std::unique_ptr step(std::unique_ptr input, double input1, std::unique_ptr output1); -Interpolator linear(); -Interpolator exponential(double base); -Interpolator cubicBezier(double x1, double y1, double x2, double y2); +Interpolator linear() noexcept; +Interpolator exponential(double base) noexcept; +Interpolator cubicBezier(double x1, double y1, double x2, double y2) noexcept; std::unique_ptr interpolate(Interpolator interpolator, std::unique_ptr input, diff --git a/include/mbgl/style/expression/error.hpp b/include/mbgl/style/expression/error.hpp index b1385b420..aedcf5e64 100644 --- a/include/mbgl/style/expression/error.hpp +++ b/include/mbgl/style/expression/error.hpp @@ -16,11 +16,11 @@ public: void eachChild(const std::function&) const override {} - bool operator==(const Expression& e) const override { return e.getKind() == Kind::Error; } + bool operator==(const Expression& e) const noexcept override { return e.getKind() == Kind::Error; } EvaluationResult evaluate(const EvaluationContext&) const override { return EvaluationError{message}; } - std::vector> possibleOutputs() const override { return {}; } + std::vector> possibleOutputs() const noexcept override { return {}; } std::string getOperator() const override { return "error"; } diff --git a/include/mbgl/style/expression/expression.hpp b/include/mbgl/style/expression/expression.hpp index 7a7fe00c6..b53951305 100644 --- a/include/mbgl/style/expression/expression.hpp +++ b/include/mbgl/style/expression/expression.hpp @@ -29,23 +29,23 @@ public: class EvaluationContext { public: EvaluationContext() = default; - explicit EvaluationContext(float zoom_) + explicit EvaluationContext(float zoom_) noexcept : zoom(zoom_) {} - explicit EvaluationContext(GeometryTileFeature const* feature_) + explicit EvaluationContext(GeometryTileFeature const* feature_) noexcept : feature(feature_) {} - EvaluationContext(float zoom_, GeometryTileFeature const* feature_) + EvaluationContext(float zoom_, GeometryTileFeature const* feature_) noexcept : zoom(zoom_), feature(feature_) {} - EvaluationContext(std::optional accumulated_, GeometryTileFeature const* feature_) + EvaluationContext(std::optional accumulated_, GeometryTileFeature const* feature_) noexcept(false) : accumulated(std::move(accumulated_)), feature(feature_) {} - EvaluationContext(float zoom_, GeometryTileFeature const* feature_, const FeatureState* state_) + EvaluationContext(float zoom_, GeometryTileFeature const* feature_, const FeatureState* state_) noexcept : zoom(zoom_), feature(feature_), featureState(state_) {} EvaluationContext(std::optional zoom_, GeometryTileFeature const* feature_, - std::optional colorRampParameter_) + std::optional colorRampParameter_) noexcept : zoom(std::move(zoom_)), feature(feature_), colorRampParameter(std::move(colorRampParameter_)) {} @@ -86,38 +86,45 @@ class Result : private variant { public: using variant::variant; using Value = T; + using Variant = variant; Result() = default; + static_assert(std::is_nothrow_constructible_v); + template VARIANT_INLINE Result(U&& val) - : variant(val) {} + : Variant(std::forward(val)) {} - explicit operator bool() const { return this->template is(); } + template + VARIANT_INLINE Result(const U& val) + : Variant(val) {} + + explicit operator bool() const noexcept { return this->template is(); } // optional does some type trait magic for this one, so this might // be problematic as is. - const T* operator->() const { + const T* operator->() const noexcept { assert(this->template is()); return std::addressof(this->template get()); } - T* operator->() { + T* operator->() noexcept { assert(this->template is()); return std::addressof(this->template get()); } - T& operator*() { + T& operator*() noexcept { assert(this->template is()); return this->template get(); } - const T& operator*() const { + const T& operator*() const noexcept { assert(this->template is()); return this->template get(); } - const EvaluationError& error() const { + const EvaluationError& error() const noexcept { assert(this->template is()); return this->template get(); } @@ -133,7 +140,7 @@ public: : Result(toExpressionValue(arr)) {} // used only for the special (private) "error" expression - EvaluationResult(const type::ErrorType&) { assert(false); } + EvaluationResult(const type::ErrorType&) noexcept { assert(false); } }; /** @@ -217,11 +224,12 @@ public: virtual EvaluationResult evaluate(const EvaluationContext& params) const = 0; virtual void eachChild(const std::function&) const = 0; - virtual bool operator==(const Expression&) const = 0; - bool operator!=(const Expression& rhs) const { return !operator==(rhs); } - Kind getKind() const { return kind; } - const type::Type& getType() const { return type; } + virtual bool operator==(const Expression&) const = 0; + bool operator!=(const Expression& rhs) const noexcept { return !operator==(rhs); } + + Kind getKind() const noexcept { return kind; }; + const type::Type& getType() const noexcept { return type; }; EvaluationResult evaluate(std::optional zoom, const Feature& feature, @@ -258,33 +266,47 @@ public: protected: template - static bool childrenEqual(const T& lhs, const T& rhs) { + static bool childrenEqual(const T& lhs, const T& rhs) noexcept { if (lhs.size() != rhs.size()) return false; for (auto leftChild = lhs.begin(), rightChild = rhs.begin(); leftChild != lhs.end(); leftChild++, rightChild++) { - if (!Expression::childEqual(*leftChild, *rightChild)) return false; + if (!Expression::childEqual(*leftChild, *rightChild)) { + return false; + } } return true; } - static bool childEqual(const std::unique_ptr& lhs, const std::unique_ptr& rhs) { + static bool childEqual(const std::unique_ptr& lhs, const std::unique_ptr& rhs) noexcept { return *lhs == *rhs; } - template + template >> static bool childEqual(const std::pair>& lhs, - const std::pair>& rhs) { + const std::pair>& rhs) noexcept { return lhs.first == rhs.first && *(lhs.second) == *(rhs.second); } - template + template >, typename = void> static bool childEqual(const std::pair>& lhs, - const std::pair>& rhs) { + const std::pair>& rhs) noexcept { + return lhs.first == rhs.first && *(lhs.second) == *(rhs.second); + } + + template >> + static bool childEqual(const std::pair>& lhs, + const std::pair>& rhs) noexcept { +#if __clang_major__ > 16 + // On older compilers, this assignment doesn't do overload resolution + // in the same way that `lhs==rhs` does and produces ambiguity errors. + bool (*equality_method)(const T&, const T&) noexcept = &std::operator==; + static_assert(std::is_nothrow_invocable_v); +#endif return lhs.first == rhs.first && *(lhs.second) == *(rhs.second); } static bool childEqual(const std::pair, std::unique_ptr>& lhs, - const std::pair, std::unique_ptr>& rhs) { + const std::pair, std::unique_ptr>& rhs) noexcept { return *(lhs.first) == *(rhs.first) && *(lhs.second) == *(rhs.second); } diff --git a/include/mbgl/style/expression/format_expression.hpp b/include/mbgl/style/expression/format_expression.hpp index fa2fe341b..b13939e8f 100644 --- a/include/mbgl/style/expression/format_expression.hpp +++ b/include/mbgl/style/expression/format_expression.hpp @@ -32,15 +32,15 @@ public: void eachChild(const std::function&) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; - std::vector> possibleOutputs() const override { + std::vector> possibleOutputs() const noexcept override { // Technically the combinatoric set of all children // Usually, this.text will be undefined anyway return {std::nullopt}; } - const std::vector& getSections() const { return sections; } + const std::vector& getSections() const noexcept { return sections; } mbgl::Value serialize() const override; std::string getOperator() const override { return "format"; } diff --git a/include/mbgl/style/expression/format_section_override.hpp b/include/mbgl/style/expression/format_section_override.hpp index f56a2a3e9..214fb3f49 100644 --- a/include/mbgl/style/expression/format_section_override.hpp +++ b/include/mbgl/style/expression/format_section_override.hpp @@ -10,11 +10,9 @@ namespace expression { template class FormatSectionOverride final : public Expression { public: - FormatSectionOverride(const type::Type& type_, - PossiblyEvaluatedPropertyValue defaultValue_, - std::string propertyName_) + FormatSectionOverride(type::Type type_, PossiblyEvaluatedPropertyValue defaultValue_, std::string propertyName_) : Expression(Kind::FormatSectionOverride, - type_, + std::move(type_), defaultValue_.getDependencies() | Dependency::Override | Dependency::Feature), defaultValue(std::move(defaultValue_)), propertyName(std::move(propertyName_)) {} diff --git a/include/mbgl/style/expression/get_covering_stops.hpp b/include/mbgl/style/expression/get_covering_stops.hpp index 94764e078..38dd3f726 100644 --- a/include/mbgl/style/expression/get_covering_stops.hpp +++ b/include/mbgl/style/expression/get_covering_stops.hpp @@ -10,7 +10,9 @@ namespace style { namespace expression { /// Return the smallest range of stops that covers the interval [lower, upper] -Range getCoveringStops(const std::map>& stops, double lower, double upper); +Range getCoveringStops(const std::map>& stops, + double lower, + double upper) noexcept; } // namespace expression } // namespace style diff --git a/include/mbgl/style/expression/image_expression.hpp b/include/mbgl/style/expression/image_expression.hpp index 5a3ce3b11..899d69880 100644 --- a/include/mbgl/style/expression/image_expression.hpp +++ b/include/mbgl/style/expression/image_expression.hpp @@ -17,7 +17,7 @@ public: void eachChild(const std::function&) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override { return {std::nullopt}; } diff --git a/include/mbgl/style/expression/in.hpp b/include/mbgl/style/expression/in.hpp index 66830a137..ac74e3372 100644 --- a/include/mbgl/style/expression/in.hpp +++ b/include/mbgl/style/expression/in.hpp @@ -17,11 +17,11 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; - std::string getOperator() const override; + std::string getOperator() const override { return "in"; } private: std::unique_ptr needle; diff --git a/include/mbgl/style/expression/index_of.hpp b/include/mbgl/style/expression/index_of.hpp index 6269a3908..364b9551e 100644 --- a/include/mbgl/style/expression/index_of.hpp +++ b/include/mbgl/style/expression/index_of.hpp @@ -19,10 +19,10 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; - std::string getOperator() const override; + std::string getOperator() const override { return "index-of"; } private: EvaluationResult evaluateForArrayInput(const std::vector& array, diff --git a/include/mbgl/style/expression/interpolate.hpp b/include/mbgl/style/expression/interpolate.hpp index d2715a0eb..70d3aa0b4 100644 --- a/include/mbgl/style/expression/interpolate.hpp +++ b/include/mbgl/style/expression/interpolate.hpp @@ -24,8 +24,8 @@ public: std::unique_ptr input_, std::map> stops_); - const std::unique_ptr& getInput() const { return input; } - const Interpolator& getInterpolator() const { return interpolator; } + const std::unique_ptr& getInput() const noexcept { return input; } + const Interpolator& getInterpolator() const noexcept { return interpolator; } void eachChild(const std::function& visit) const override { visit(*input); @@ -41,7 +41,7 @@ public: } // Return the smallest range of stops that covers the interval [lower, upper] - Range getCoveringStops(const double lower, const double upper) const { + Range getCoveringStops(const double lower, const double upper) const noexcept { return ::mbgl::style::expression::getCoveringStops(stops, lower, upper); } @@ -50,9 +50,9 @@ public: [&](const auto& interp) { return interp.interpolationFactor(inputLevels, inputValue); }); } - bool operator==(const Expression& e) const override { + bool operator==(const Expression& e) const noexcept override { if (e.getKind() == Kind::Interpolate) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); if (interpolator != rhs->interpolator || *input != *(rhs->input) || stops.size() != rhs->stops.size()) { return false; } diff --git a/include/mbgl/style/expression/interpolator.hpp b/include/mbgl/style/expression/interpolator.hpp index 18840b377..37708d601 100644 --- a/include/mbgl/style/expression/interpolator.hpp +++ b/include/mbgl/style/expression/interpolator.hpp @@ -10,27 +10,27 @@ namespace expression { class ExponentialInterpolator { public: - ExponentialInterpolator(double base_) + ExponentialInterpolator(double base_) noexcept : base(base_) {} double base; - double interpolationFactor(const Range& inputLevels, const double input) const { + double interpolationFactor(const Range& inputLevels, const double input) const noexcept { return util::interpolationFactor( static_cast(base), Range{static_cast(inputLevels.min), static_cast(inputLevels.max)}, static_cast(input)); } - bool operator==(const ExponentialInterpolator& rhs) const { return base == rhs.base; } + bool operator==(const ExponentialInterpolator& rhs) const noexcept { return base == rhs.base; } }; class CubicBezierInterpolator { public: - CubicBezierInterpolator(double x1_, double y1_, double x2_, double y2_) + CubicBezierInterpolator(double x1_, double y1_, double x2_, double y2_) noexcept : ub(x1_, y1_, x2_, y2_) {} - double interpolationFactor(const Range& inputLevels, const double input) const { + double interpolationFactor(const Range& inputLevels, const double input) const noexcept { return ub.solve(util::interpolationFactor( 1.0f, Range{static_cast(inputLevels.min), static_cast(inputLevels.max)}, @@ -38,7 +38,7 @@ public: 1e-6); } - bool operator==(const CubicBezierInterpolator& rhs) const { return ub == rhs.ub; } + bool operator==(const CubicBezierInterpolator& rhs) const noexcept { return ub == rhs.ub; } util::UnitBezier ub; }; diff --git a/include/mbgl/style/expression/is_constant.hpp b/include/mbgl/style/expression/is_constant.hpp index 69827538e..f15ea671f 100644 --- a/include/mbgl/style/expression/is_constant.hpp +++ b/include/mbgl/style/expression/is_constant.hpp @@ -10,8 +10,8 @@ namespace expression { template bool isGlobalPropertyConstant(const Expression& expression, const T& properties) { if (expression.getKind() == Kind::CompoundExpression) { - auto e = static_cast(&expression); - for (const std::string& property : properties) { + const auto* e = static_cast(&expression); + for (const auto& property : properties) { if (e->getOperator() == property) { return false; } diff --git a/include/mbgl/style/expression/length.hpp b/include/mbgl/style/expression/length.hpp index f66b3039e..29e89415a 100644 --- a/include/mbgl/style/expression/length.hpp +++ b/include/mbgl/style/expression/length.hpp @@ -19,7 +19,7 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; std::string getOperator() const override { return "length"; } diff --git a/include/mbgl/style/expression/let.hpp b/include/mbgl/style/expression/let.hpp index 89007a0fa..2855b5679 100644 --- a/include/mbgl/style/expression/let.hpp +++ b/include/mbgl/style/expression/let.hpp @@ -26,9 +26,9 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; - bool operator==(const Expression& e) const override { + bool operator==(const Expression& e) const noexcept override { if (e.getKind() == Kind::Let) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return *result == *(rhs->result); } return false; @@ -36,7 +36,7 @@ public: std::vector> possibleOutputs() const override; - Expression* getResult() const { return result.get(); } + Expression* getResult() const noexcept { return result.get(); } mbgl::Value serialize() const override; std::string getOperator() const override { return "let"; } @@ -58,7 +58,7 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; - bool operator==(const Expression& e) const override { + bool operator==(const Expression& e) const noexcept override { if (e.getKind() == Kind::Var) { auto rhs = static_cast(&e); return *value == *(rhs->value); @@ -71,7 +71,7 @@ public: mbgl::Value serialize() const override; std::string getOperator() const override { return "var"; } - const std::shared_ptr& getBoundExpression() const { return value; } + const std::shared_ptr& getBoundExpression() const noexcept { return value; } private: std::string name; diff --git a/include/mbgl/style/expression/literal.hpp b/include/mbgl/style/expression/literal.hpp index d8ca0d31a..32205039f 100644 --- a/include/mbgl/style/expression/literal.hpp +++ b/include/mbgl/style/expression/literal.hpp @@ -16,19 +16,23 @@ public: : Expression(Kind::Literal, typeOf(value_), Dependency::None), value(value_) {} - Literal(const type::Array& type_, std::vector value_) - : Expression(Kind::Literal, type_, Dependency::None), + Literal(Value&& value_) + : Expression(Kind::Literal, typeOf(value_), Dependency::None), + value(std::move(value_)) {} + + Literal(type::Array type_, std::vector value_) + : Expression(Kind::Literal, std::move(type_), Dependency::None), value(std::move(value_)) {} EvaluationResult evaluate(const EvaluationContext&) const override { return value; } static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); - void eachChild(const std::function&) const override {} + void eachChild(const std::function&) const noexcept override {} - bool operator==(const Expression& e) const override { + bool operator==(const Expression& e) const noexcept override { if (e.getKind() == Kind::Literal) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return value == rhs->value; } return false; @@ -36,7 +40,7 @@ public: std::vector> possibleOutputs() const override { return {{value}}; } - Value getValue() const { return value; } + const Value& getValue() const noexcept { return value; } mbgl::Value serialize() const override; std::string getOperator() const override { return "literal"; } diff --git a/include/mbgl/style/expression/match.hpp b/include/mbgl/style/expression/match.hpp index 431856252..24ac90497 100644 --- a/include/mbgl/style/expression/match.hpp +++ b/include/mbgl/style/expression/match.hpp @@ -15,11 +15,12 @@ class Match : public Expression { public: using Branches = std::unordered_map>; - Match(const type::Type& type_, + Match(type::Type type_, std::unique_ptr input_, Branches branches_, std::unique_ptr otherwise_) - : Expression(Kind::Match, type_, depsOf(input_) | depsOf(otherwise_) | collectDependencies(branches_)), + : Expression( + Kind::Match, std::move(type_), depsOf(input_) | depsOf(otherwise_) | collectDependencies(branches_)), input(std::move(input_)), branches(std::move(branches_)), otherwise(std::move(otherwise_)) {} @@ -28,7 +29,7 @@ public: void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; diff --git a/include/mbgl/style/expression/number_format.hpp b/include/mbgl/style/expression/number_format.hpp index ed6f2e7df..4fac4ee6f 100644 --- a/include/mbgl/style/expression/number_format.hpp +++ b/include/mbgl/style/expression/number_format.hpp @@ -21,7 +21,7 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; mbgl::Value serialize() const override; diff --git a/include/mbgl/style/expression/parsing_context.hpp b/include/mbgl/style/expression/parsing_context.hpp index 01b47bcdf..d11d7e00e 100644 --- a/include/mbgl/style/expression/parsing_context.hpp +++ b/include/mbgl/style/expression/parsing_context.hpp @@ -91,7 +91,7 @@ public: std::string getKey() const { return key; } std::optional getExpected() const { return expected; } - const std::vector& getErrors() const { return *errors; } + const std::vector& getErrors() const noexcept { return *errors; } std::string getCombinedErrors() const; /** @@ -150,7 +150,7 @@ public: ctx.errors->clear(); } - void clearErrors() { errors->clear(); } + void clearErrors() noexcept { errors->clear(); } private: ParsingContext(std::string key_, @@ -177,7 +177,7 @@ private: std::shared_ptr> errors; }; -bool isExpression(const std::string&); +bool isExpression(const std::string&) noexcept; } // namespace expression } // namespace style diff --git a/include/mbgl/style/expression/slice.hpp b/include/mbgl/style/expression/slice.hpp index 60bfbd401..85d5a8040 100644 --- a/include/mbgl/style/expression/slice.hpp +++ b/include/mbgl/style/expression/slice.hpp @@ -19,10 +19,10 @@ public: EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function&) const override; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; - std::string getOperator() const override; + std::string getOperator() const override { return "slice"; } private: EvaluationResult evaluateForStringInput(const std::string& input, int fromIndexValue, int toIndexValue) const; diff --git a/include/mbgl/style/expression/step.hpp b/include/mbgl/style/expression/step.hpp index 4999ed5d8..ac47fcd3b 100644 --- a/include/mbgl/style/expression/step.hpp +++ b/include/mbgl/style/expression/step.hpp @@ -16,18 +16,16 @@ namespace expression { class Step : public Expression { public: - Step(const type::Type& type_, - std::unique_ptr input_, - std::map> stops_); + Step(type::Type type_, std::unique_ptr input_, std::map> stops_); EvaluationResult evaluate(const EvaluationContext& params) const override; void eachChild(const std::function& visit) const override; void eachStop(const std::function& visit) const; - const std::unique_ptr& getInput() const { return input; } - Range getCoveringStops(double lower, double upper) const; + const std::unique_ptr& getInput() const noexcept { return input; } + Range getCoveringStops(double lower, double upper) const noexcept; - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; diff --git a/include/mbgl/style/expression/value.hpp b/include/mbgl/style/expression/value.hpp index 88349a4a5..6bcc49f61 100644 --- a/include/mbgl/style/expression/value.hpp +++ b/include/mbgl/style/expression/value.hpp @@ -33,21 +33,26 @@ using ValueBase = variant>, mapbox::util::recursive_wrapper>>; struct Value : ValueBase { - using ValueBase::ValueBase; - - VARIANT_INLINE Value() - : ValueBase() {} + VARIANT_INLINE Value() noexcept {} template VARIANT_INLINE Value(T&& val) + : ValueBase(std::forward(val)) {} + + template + VARIANT_INLINE Value(const T& val) : ValueBase(val) {} // Javascript's Number.MAX_SAFE_INTEGER - static uint64_t maxSafeInteger() { return 9007199254740991ULL; } + static constexpr uint64_t maxSafeInteger() noexcept { return 9007199254740991ULL; } - static bool isSafeInteger(uint64_t x) { return x <= maxSafeInteger(); }; - static bool isSafeInteger(int64_t x) { return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); } - static bool isSafeInteger(double x) { return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); } + static constexpr bool isSafeInteger(uint64_t x) noexcept { return x <= maxSafeInteger(); }; + static constexpr bool isSafeInteger(int64_t x) noexcept { + return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); + } + static constexpr bool isSafeInteger(double x) noexcept { + return static_cast(x > 0 ? x : -x) <= maxSafeInteger(); + } }; constexpr NullValue Null = NullValue(); diff --git a/include/mbgl/style/expression/within.hpp b/include/mbgl/style/expression/within.hpp index 883aa2809..94c203212 100644 --- a/include/mbgl/style/expression/within.hpp +++ b/include/mbgl/style/expression/within.hpp @@ -19,14 +19,14 @@ public: static ParseResult parse(const mbgl::style::conversion::Convertible&, ParsingContext&); - void eachChild(const std::function&) const override {} + void eachChild(const std::function&) const noexcept override {} - bool operator==(const Expression& e) const override; + bool operator==(const Expression& e) const noexcept override; std::vector> possibleOutputs() const override; mbgl::Value serialize() const override; - std::string getOperator() const override; + std::string getOperator() const override { return "within"; } private: GeoJSON geoJSONSource; diff --git a/include/mbgl/style/layer_properties.hpp b/include/mbgl/style/layer_properties.hpp index 60c6ef2ed..cd89ed5ed 100644 --- a/include/mbgl/style/layer_properties.hpp +++ b/include/mbgl/style/layer_properties.hpp @@ -16,6 +16,7 @@ public: virtual ~LayerProperties() = default; /// Returns constants mask for the data-driven properties. virtual unsigned long constantsMask() const { return 0u; } + Immutable baseImpl; /// Contains render passes used by the renderer, see `mbgl::RenderPass`. uint8_t renderPasses = 0u; @@ -23,7 +24,7 @@ public: virtual expression::Dependency getDependencies() const noexcept = 0; protected: - LayerProperties(Immutable impl) + LayerProperties(Immutable impl) noexcept : baseImpl(std::move(impl)) {} }; diff --git a/include/mbgl/style/property_expression.hpp b/include/mbgl/style/property_expression.hpp index 0c625f972..6730b8e8b 100644 --- a/include/mbgl/style/property_expression.hpp +++ b/include/mbgl/style/property_expression.hpp @@ -14,7 +14,7 @@ namespace style { class PropertyExpressionBase { public: - explicit PropertyExpressionBase(std::unique_ptr); + explicit PropertyExpressionBase(std::unique_ptr) noexcept; bool isZoomConstant() const noexcept { return isZoomConstant_; } bool isFeatureConstant() const noexcept { return isFeatureConstant_; } @@ -48,10 +48,12 @@ protected: template class PropertyExpression final : public PropertyExpressionBase { + static_assert(std::is_nothrow_move_constructible_v); + public: // Second parameter to be used only for conversions from legacy functions. PropertyExpression(std::unique_ptr expression_, - std::optional defaultValue_ = std::nullopt) + std::optional defaultValue_ = std::nullopt) noexcept : PropertyExpressionBase(std::move(expression_)), defaultValue(std::move(defaultValue_)) {} @@ -137,6 +139,8 @@ public: return expression::fromExpressionValues(expression->possibleOutputs()); } + using Expression = expression::Expression; + friend bool operator==(const PropertyExpression& lhs, const PropertyExpression& rhs) { return *lhs.expression == *rhs.expression; } diff --git a/include/mbgl/style/property_value.hpp b/include/mbgl/style/property_value.hpp index c8f7964aa..3f51c5bbc 100644 --- a/include/mbgl/style/property_value.hpp +++ b/include/mbgl/style/property_value.hpp @@ -14,40 +14,42 @@ private: Value value; - friend bool operator==(const PropertyValue& lhs, const PropertyValue& rhs) { return lhs.value == rhs.value; } + friend bool operator==(const PropertyValue& lhs, const PropertyValue& rhs) noexcept { + return lhs.value == rhs.value; + } - friend bool operator!=(const PropertyValue& lhs, const PropertyValue& rhs) { return !(lhs == rhs); } + friend bool operator!=(const PropertyValue& lhs, const PropertyValue& rhs) noexcept { return !(lhs == rhs); } public: PropertyValue() = default; PropertyValue(T constant) - : value(std::move(constant)) {} + : value(std::forward(constant)) {} - PropertyValue(PropertyExpression expression) + PropertyValue(PropertyExpression expression) noexcept : value(std::move(expression)) {} - bool isUndefined() const { return value.template is(); } + bool isUndefined() const noexcept { return value.template is(); } - bool isConstant() const { return value.template is(); } + bool isConstant() const noexcept { return value.template is(); } - bool isExpression() const { return value.template is>(); } + bool isExpression() const noexcept { return value.template is>(); } - bool isDataDriven() const { + bool isDataDriven() const noexcept { return value.match([](const Undefined&) { return false; }, [](const T&) { return false; }, [](const PropertyExpression& fn) { return !fn.isFeatureConstant(); }); } - bool isZoomConstant() const { + bool isZoomConstant() const noexcept { return value.match([](const Undefined&) { return true; }, [](const T&) { return true; }, [](const PropertyExpression& fn) { return fn.isZoomConstant(); }); } - const T& asConstant() const { return value.template get(); } + const T& asConstant() const noexcept { return value.template get(); } - const PropertyExpression& asExpression() const { return value.template get>(); } + const PropertyExpression& asExpression() const noexcept { return value.template get>(); } template auto match(Ts&&... ts) const { @@ -59,15 +61,15 @@ public: return Value::visit(value, evaluator); } - bool hasDataDrivenPropertyDifference(const PropertyValue& other) const { + bool hasDataDrivenPropertyDifference(const PropertyValue& other) const noexcept { return *this != other && (isDataDriven() || other.isDataDriven()); } using Dependency = style::expression::Dependency; Dependency getDependencies() const noexcept { - return value.match([](const Undefined&) noexcept { return Dependency::None; }, - [](const T&) noexcept { return Dependency::None; }, - [](const PropertyExpression& ex) noexcept { return ex.getDependencies(); }); + return value.match([](const Undefined&) { return Dependency::None; }, + [](const T&) { return Dependency::None; }, + [](const PropertyExpression& ex) { return ex.getDependencies(); }); } }; diff --git a/include/mbgl/util/compression.hpp b/include/mbgl/util/compression.hpp index d89015a1e..638553240 100644 --- a/include/mbgl/util/compression.hpp +++ b/include/mbgl/util/compression.hpp @@ -16,7 +16,7 @@ enum CompressionFormat { std::string compress(const std::string& raw, int windowBits = CompressionFormat::ZLIB); std::string decompress(const std::string& raw, int windowBits = CompressionFormat::DETECT); -std::uint32_t crc32(const void* raw, size_t size); +std::uint32_t crc32(const void* raw, size_t size) noexcept; } // namespace util } // namespace mbgl diff --git a/include/mbgl/util/geo.hpp b/include/mbgl/util/geo.hpp index bc8460f13..97d8b933a 100644 --- a/include/mbgl/util/geo.hpp +++ b/include/mbgl/util/geo.hpp @@ -52,16 +52,16 @@ public: } } - double latitude() const { return lat; } - double longitude() const { return lon; } + double latitude() const noexcept { return lat; } + double longitude() const noexcept { return lon; } - LatLng wrapped() const { return {lat, lon, Wrapped}; } + LatLng wrapped() const noexcept { return {lat, lon, Wrapped}; } - void wrap() { lon = util::wrap(lon, -util::LONGITUDE_MAX, util::LONGITUDE_MAX); } + void wrap() noexcept { lon = util::wrap(lon, -util::LONGITUDE_MAX, util::LONGITUDE_MAX); } // If the distance from start to end longitudes is between half and full // world, unwrap the start longitude to ensure the shortest path is taken. - void unwrapForShortestPath(const LatLng& end) { + void unwrapForShortestPath(const LatLng& end) noexcept { const double delta = std::abs(end.lon - lon); if (delta <= util::LONGITUDE_MAX || delta >= util::DEGREES_MAX) return; if (lon > 0 && end.lon < 0) @@ -71,31 +71,31 @@ public: } // Constructs a LatLng object with the top left position of the specified tile. - LatLng(const CanonicalTileID& id); - LatLng(const UnwrappedTileID& id); + LatLng(const CanonicalTileID& id) noexcept; + LatLng(const UnwrappedTileID& id) noexcept; - friend bool operator==(const LatLng& a, const LatLng& b) { return a.lat == b.lat && a.lon == b.lon; } + friend bool operator==(const LatLng& a, const LatLng& b) noexcept { return a.lat == b.lat && a.lon == b.lon; } - friend bool operator!=(const LatLng& a, const LatLng& b) { return !(a == b); } + friend bool operator!=(const LatLng& a, const LatLng& b) noexcept { return !(a == b); } }; class LatLngBounds { public: // Return a bounds covering the entire (unwrapped) world. - static LatLngBounds world() { return {{-90, -180}, {90, 180}}; } + static LatLngBounds world() noexcept { return {{-90, -180}, {90, 180}}; } // Return the bounds consisting of the single point. static LatLngBounds singleton(const LatLng& a) { return {a, a}; } // Return the convex hull of two points; the smallest bounds that contains both. - static LatLngBounds hull(const LatLng& a, const LatLng& b) { + static LatLngBounds hull(const LatLng& a, const LatLng& b) noexcept { LatLngBounds bounds(a, a); bounds.extend(b); return bounds; } // Return a bounds that may serve as the identity element for the extend operation. - static LatLngBounds empty() { + static LatLngBounds empty() noexcept { LatLngBounds bounds = world(); std::swap(bounds.sw, bounds.ne); return bounds; @@ -106,61 +106,63 @@ public: /// /// Note: this is different than LatLngBounds::world() since arbitrary /// unwrapped coordinates are also inside the bounds. - LatLngBounds() + LatLngBounds() noexcept : sw({-90, -180}), ne({90, 180}), bounded(false) {} // Constructs a LatLngBounds object with the tile's exact boundaries. - LatLngBounds(const CanonicalTileID&); + LatLngBounds(const CanonicalTileID&) noexcept; - bool valid() const { return (sw.latitude() <= ne.latitude()) && (sw.longitude() <= ne.longitude()); } + bool valid() const noexcept { return (sw.latitude() <= ne.latitude()) && (sw.longitude() <= ne.longitude()); } - double south() const { return sw.latitude(); } - double west() const { return sw.longitude(); } - double north() const { return ne.latitude(); } - double east() const { return ne.longitude(); } + double south() const noexcept { return sw.latitude(); } + double west() const noexcept { return sw.longitude(); } + double north() const noexcept { return ne.latitude(); } + double east() const noexcept { return ne.longitude(); } - LatLng southwest() const { return sw; } - LatLng northeast() const { return ne; } - LatLng southeast() const { return {south(), east()}; } - LatLng northwest() const { return {north(), west()}; } + LatLng southwest() const noexcept { return sw; } + LatLng northeast() const noexcept { return ne; } + LatLng southeast() const noexcept { return {south(), east()}; } + LatLng northwest() const noexcept { return {north(), west()}; } - LatLng center() const { return {(sw.latitude() + ne.latitude()) / 2, (sw.longitude() + ne.longitude()) / 2}; } + LatLng center() const noexcept { + return {(sw.latitude() + ne.latitude()) / 2, (sw.longitude() + ne.longitude()) / 2}; + } - LatLng constrain(const LatLng& p) const; + LatLng constrain(const LatLng& p) const noexcept; - void extend(const LatLng& point) { + void extend(const LatLng& point) noexcept { sw = LatLng(std::min(point.latitude(), sw.latitude()), std::min(point.longitude(), sw.longitude())); ne = LatLng(std::max(point.latitude(), ne.latitude()), std::max(point.longitude(), ne.longitude())); } - void extend(const LatLngBounds& bounds) { + void extend(const LatLngBounds& bounds) noexcept { extend(bounds.sw); extend(bounds.ne); } - bool isEmpty() const { return sw.latitude() > ne.latitude() || sw.longitude() > ne.longitude(); } + bool isEmpty() const noexcept { return sw.latitude() > ne.latitude() || sw.longitude() > ne.longitude(); } - bool crossesAntimeridian() const { return (sw.wrapped().longitude() > ne.wrapped().longitude()); } + bool crossesAntimeridian() const noexcept { return (sw.wrapped().longitude() > ne.wrapped().longitude()); } - bool contains(const CanonicalTileID& tileID) const; - bool contains(const LatLng& point, LatLng::WrapMode wrap = LatLng::Unwrapped) const; - bool contains(const LatLngBounds& area, LatLng::WrapMode wrap = LatLng::Unwrapped) const; + bool contains(const CanonicalTileID& tileID) const noexcept; + bool contains(const LatLng& point, LatLng::WrapMode wrap = LatLng::Unwrapped) const noexcept; + bool contains(const LatLngBounds& area, LatLng::WrapMode wrap = LatLng::Unwrapped) const noexcept; - bool intersects(LatLngBounds area, LatLng::WrapMode wrap = LatLng::Unwrapped) const; + bool intersects(LatLngBounds area, LatLng::WrapMode wrap = LatLng::Unwrapped) const noexcept; private: LatLng sw; LatLng ne; bool bounded = true; - LatLngBounds(LatLng sw_, LatLng ne_) + LatLngBounds(LatLng sw_, LatLng ne_) noexcept : sw(sw_), ne(ne_) {} - bool containsLatitude(double latitude) const; - bool containsLongitude(double longitude, LatLng::WrapMode wrap) const; + bool containsLatitude(double latitude) const noexcept; + bool containsLongitude(double longitude, LatLng::WrapMode wrap) const noexcept; friend bool operator==(const LatLngBounds& a, const LatLngBounds& b) { return (!a.bounded && !b.bounded) || (a.bounded && b.bounded && a.sw == b.sw && a.ne == b.ne); @@ -205,12 +207,12 @@ public: } } - double top() const { return _top; } - double left() const { return _left; } - double bottom() const { return _bottom; } - double right() const { return _right; } + double top() const noexcept { return _top; } + double left() const noexcept { return _left; } + double bottom() const noexcept { return _bottom; } + double right() const noexcept { return _right; } - bool isFlush() const { return _top == 0 && _left == 0 && _bottom == 0 && _right == 0; } + bool isFlush() const noexcept { return _top == 0 && _left == 0 && _bottom == 0 && _right == 0; } void operator+=(const EdgeInsets& o) { _top += o._top; @@ -219,7 +221,7 @@ public: _right += o._right; } - EdgeInsets operator+(const EdgeInsets& o) const { + EdgeInsets operator+(const EdgeInsets& o) const noexcept { return { _top + o._top, _left + o._left, @@ -228,13 +230,13 @@ public: }; } - ScreenCoordinate getCenter(uint16_t width, uint16_t height) const; + ScreenCoordinate getCenter(uint16_t width, uint16_t height) const noexcept; - friend bool operator==(const EdgeInsets& a, const EdgeInsets& b) { + friend bool operator==(const EdgeInsets& a, const EdgeInsets& b) noexcept { return a._top == b._top && a._left == b._left && a._bottom == b._bottom && a._right == b._right; } - friend bool operator!=(const EdgeInsets& a, const EdgeInsets& b) { return !(a == b); } + friend bool operator!=(const EdgeInsets& a, const EdgeInsets& b) noexcept { return !(a == b); } }; struct LatLngAltitude { diff --git a/include/mbgl/util/identity.hpp b/include/mbgl/util/identity.hpp index 8163a3a97..cd667d2d1 100644 --- a/include/mbgl/util/identity.hpp +++ b/include/mbgl/util/identity.hpp @@ -12,25 +12,25 @@ namespace util { */ class SimpleIdentity final { private: - constexpr SimpleIdentity(std::int64_t id) + constexpr SimpleIdentity(std::int64_t id) noexcept : uniqueID(id) {} public: - SimpleIdentity(); + SimpleIdentity() noexcept; SimpleIdentity(const SimpleIdentity&) = default; ~SimpleIdentity() = default; static const SimpleIdentity Empty; - bool operator<(const SimpleIdentity& other) const { return uniqueID < other.uniqueID; } - bool operator==(const SimpleIdentity& other) const { return uniqueID == other.uniqueID; } - bool operator!=(const SimpleIdentity& other) const { return uniqueID != other.uniqueID; } + bool operator<(const SimpleIdentity& other) const noexcept { return uniqueID < other.uniqueID; } + bool operator==(const SimpleIdentity& other) const noexcept { return uniqueID == other.uniqueID; } + bool operator!=(const SimpleIdentity& other) const noexcept { return uniqueID != other.uniqueID; } - std::int64_t id() const { return uniqueID; } - bool isEmpty() const { return uniqueID != emptyID; } + std::int64_t id() const noexcept { return uniqueID; } + bool isEmpty() const noexcept { return uniqueID != emptyID; } - operator bool() const { return isEmpty(); } - bool operator!() const { return !isEmpty(); } + operator bool() const noexcept { return isEmpty(); } + bool operator!() const noexcept { return !isEmpty(); } private: static constexpr std::int64_t emptyID = 0; @@ -46,7 +46,7 @@ protected: SimpleIdentifiable(const SimpleIdentifiable&) = default; virtual ~SimpleIdentifiable() = default; - const util::SimpleIdentity& getId() const { return uniqueID; } + const util::SimpleIdentity& getId() const noexcept { return uniqueID; } protected: util::SimpleIdentity uniqueID; diff --git a/include/mbgl/util/ignore.hpp b/include/mbgl/util/ignore.hpp index e2fbe878c..4bbcf83fc 100644 --- a/include/mbgl/util/ignore.hpp +++ b/include/mbgl/util/ignore.hpp @@ -13,15 +13,15 @@ namespace util { /// https://github.com/mapbox/cpp/blob/1bb519ef25edd6169f1d6d8a65414044616590a9/docs/structural-metaprogramming.md /// for more details. template -void ignore(Ts&&...) {} +void ignore(Ts&&...) noexcept {} // std::initializer_list overload, for situations where you need sequenced // modifications. template -void ignore(const std::initializer_list&) {} +void ignore(const std::initializer_list&) noexcept {} // Handle the zero-argument case. -inline void ignore(const std::initializer_list&) {} +inline void ignore(const std::initializer_list&) noexcept {} } // namespace util } // namespace mbgl diff --git a/include/mbgl/util/immutable.hpp b/include/mbgl/util/immutable.hpp index 687303bcc..0543d61d8 100644 --- a/include/mbgl/util/immutable.hpp +++ b/include/mbgl/util/immutable.hpp @@ -28,12 +28,12 @@ public: Mutable(const Mutable&) = delete; Mutable& operator=(const Mutable&) = delete; - T* get() { return ptr.get(); } - T* operator->() { return ptr.get(); } - T& operator*() { return *ptr; } + T* get() noexcept { return ptr.get(); } + T* operator->() noexcept { return ptr.get(); } + T& operator*() noexcept { return *ptr; } private: - Mutable(std::shared_ptr&& s) + Mutable(std::shared_ptr&& s) noexcept : ptr(std::move(s)) {} std::shared_ptr ptr; @@ -45,7 +45,7 @@ private: friend Mutable makeMutable(Args&&...); // NOLINTNEXTLINE(readability-redundant-declaration) template - friend Mutable staticMutableCast(const Mutable&); + friend Mutable staticMutableCast(const Mutable&) noexcept; }; template @@ -54,7 +54,7 @@ Mutable makeMutable(Args&&... args) { } template -Mutable staticMutableCast(const Mutable& u) { +Mutable staticMutableCast(const Mutable& u) noexcept { return Mutable(std::static_pointer_cast(u.ptr)); } @@ -73,18 +73,18 @@ template class Immutable { public: template - Immutable(Mutable&& s) + Immutable(Mutable&& s) noexcept : ptr(std::const_pointer_cast(std::move(s.ptr))) {} template - Immutable(Immutable s) + Immutable(Immutable s) noexcept : ptr(std::move(s.ptr)) {} Immutable(Immutable&&) noexcept = default; Immutable(const Immutable&) = default; template - Immutable& operator=(Mutable&& s) { + Immutable& operator=(Mutable&& s) noexcept { ptr = std::const_pointer_cast(std::move(s.ptr)); return *this; } @@ -92,16 +92,16 @@ public: Immutable& operator=(Immutable&&) noexcept = default; Immutable& operator=(const Immutable&) = default; - const T* get() const { return ptr.get(); } - const T* operator->() const { return ptr.get(); } - const T& operator*() const { return *ptr; } + const T* get() const noexcept { return ptr.get(); } + const T* operator->() const noexcept { return ptr.get(); } + const T& operator*() const noexcept { return *ptr; } - friend bool operator==(const Immutable& lhs, const Immutable& rhs) { return lhs.ptr == rhs.ptr; } + friend bool operator==(const Immutable& lhs, const Immutable& rhs) noexcept { return lhs.ptr == rhs.ptr; } - friend bool operator!=(const Immutable& lhs, const Immutable& rhs) { return lhs.ptr != rhs.ptr; } + friend bool operator!=(const Immutable& lhs, const Immutable& rhs) noexcept { return lhs.ptr != rhs.ptr; } private: - Immutable(std::shared_ptr&& s) + Immutable(std::shared_ptr&& s) noexcept : ptr(std::move(s)) {} std::shared_ptr ptr; @@ -111,11 +111,11 @@ private: // NOLINTNEXTLINE(readability-redundant-declaration) template - friend Immutable staticImmutableCast(const Immutable&); + friend Immutable staticImmutableCast(const Immutable&) noexcept; }; template -Immutable staticImmutableCast(const Immutable& u) { +Immutable staticImmutableCast(const Immutable& u) noexcept { return Immutable(std::static_pointer_cast(u.ptr)); } diff --git a/include/mbgl/util/indexed_tuple.hpp b/include/mbgl/util/indexed_tuple.hpp index 4fc1e99c1..a1ac364a8 100644 --- a/include/mbgl/util/indexed_tuple.hpp +++ b/include/mbgl/util/indexed_tuple.hpp @@ -41,7 +41,7 @@ public: template IndexedTuple(Us&&... other) - : std::tuple(std::forward(other)...){}; + : std::tuple(std::forward(other)...) {} template IndexedTuple, TypeList> concat( @@ -54,7 +54,9 @@ public: return static_cast&>(*this) == static_cast&>(other); } - bool operator!=(const IndexedTuple, TypeList>& other) const { return !(*this == other); } + bool operator!=(const IndexedTuple, TypeList>& other) const noexcept { + return !(*this == other); + } }; template diff --git a/include/mbgl/util/interpolate.hpp b/include/mbgl/util/interpolate.hpp index d893f8a4b..13b6ef3f4 100644 --- a/include/mbgl/util/interpolate.hpp +++ b/include/mbgl/util/interpolate.hpp @@ -15,7 +15,7 @@ namespace mbgl { namespace util { -float interpolationFactor(float base, Range range, float z); +float interpolationFactor(float base, Range range, float z) noexcept; template struct Interpolator; @@ -37,9 +37,9 @@ struct Interpolator { template <> struct Interpolator { - float operator()(const float& a, const float& b, const float t) const { return a * (1.0f - t) + b * t; } + float operator()(const float& a, const float& b, const float t) const noexcept { return a * (1.0f - t) + b * t; } - float operator()(const float& a, const float& b, const double t) const { + float operator()(const float& a, const float& b, const double t) const noexcept { return static_cast(a * (1.0 - t) + b * t); } }; @@ -50,12 +50,12 @@ private: using Array = std::array; template - Array operator()(const Array& a, const Array& b, const double t, std::index_sequence) { + Array operator()(const Array& a, const Array& b, const double t, std::index_sequence) noexcept { return {{interpolate(a[I], b[I], t)...}}; } public: - Array operator()(const Array& a, const Array& b, const double t) { + Array operator()(const Array& a, const Array& b, const double t) noexcept { return operator()(a, b, t, std::make_index_sequence()); } }; @@ -66,12 +66,12 @@ private: using Array = std::array; template - Array operator()(const Array& a, const Array& b, const float t, std::index_sequence) { + Array operator()(const Array& a, const Array& b, const float t, std::index_sequence) noexcept { return {{interpolate(a[I], b[I], t)...}}; } public: - Array operator()(const Array& a, const Array& b, const float t) { + Array operator()(const Array& a, const Array& b, const float t) noexcept { return operator()(a, b, t, std::make_index_sequence()); } }; @@ -105,7 +105,7 @@ struct Interpolator> { template <> struct Interpolator { public: - style::Position operator()(const style::Position& a, const style::Position& b, const float t) { + style::Position operator()(const style::Position& a, const style::Position& b, const float t) noexcept { auto pos = style::Position(); auto interpolated = interpolate(a.getCartesian(), b.getCartesian(), t); pos.setCartesian(interpolated); @@ -116,11 +116,11 @@ public: template <> struct Interpolator { public: - Color operator()(const Color& a, const Color& b, const float t) { + Color operator()(const Color& a, const Color& b, const float t) noexcept { return {interpolate(a.r, b.r, t), interpolate(a.g, b.g, t), interpolate(a.b, b.b, t), interpolate(a.a, b.a, t)}; } - Color operator()(const Color& a, const Color& b, const double t) { + Color operator()(const Color& a, const Color& b, const double t) noexcept { return {interpolate(a.r, b.r, t), interpolate(a.g, b.g, t), interpolate(a.b, b.b, t), interpolate(a.a, b.a, t)}; } }; @@ -128,7 +128,7 @@ public: template <> struct Interpolator { public: - style::Rotation operator()(const style::Rotation& a, const style::Rotation& b, const double t) { + style::Rotation operator()(const style::Rotation& a, const style::Rotation& b, const double t) noexcept { assert(a.period() == b.period()); auto period = a.period(); auto aAngle = std::fmod(a.getAngle(), period); diff --git a/include/mbgl/util/logging.hpp b/include/mbgl/util/logging.hpp index fc6776d4c..67d5b6e26 100644 --- a/include/mbgl/util/logging.hpp +++ b/include/mbgl/util/logging.hpp @@ -38,30 +38,30 @@ public: Log(); ~Log(); - static void useLogThread(bool enable); + static void useLogThread(bool enable) noexcept; template - static void Debug(Event event, Args&&... args) { + static void Debug(Event event, Args&&... args) noexcept { Record(EventSeverity::Debug, event, ::std::forward(args)...); } template - static void Info(Event event, Args&&... args) { + static void Info(Event event, Args&&... args) noexcept { Record(EventSeverity::Info, event, ::std::forward(args)...); } template - static void Warning(Event event, Args&&... args) { + static void Warning(Event event, Args&&... args) noexcept { Record(EventSeverity::Warning, event, ::std::forward(args)...); } template - static void Error(Event event, Args&&... args) { + static void Error(Event event, Args&&... args) noexcept { Record(EventSeverity::Error, event, ::std::forward(args)...); } template - static void Record(EventSeverity severity, Event event, Args&&... args) { + static void Record(EventSeverity severity, Event event, Args&&... args) noexcept { if (!includes(severity, disabledEventSeverities) && !includes(event, disabledEvents) && !includes({severity, event}, disabledEventPermutations)) { record(severity, event, ::std::forward(args)...); @@ -71,8 +71,8 @@ public: private: static Log* get() noexcept; - static void record(EventSeverity severity, Event event, const std::string& msg); - static void record(EventSeverity severity, Event event, int64_t code, const std::string& msg); + static void record(EventSeverity severity, Event event, const std::string& msg) noexcept; + static void record(EventSeverity severity, Event event, int64_t code, const std::string& msg) noexcept; static void record(EventSeverity severity, Event event, int64_t code, diff --git a/include/mbgl/util/projection.hpp b/include/mbgl/util/projection.hpp index a01749669..86f1ebcbb 100644 --- a/include/mbgl/util/projection.hpp +++ b/include/mbgl/util/projection.hpp @@ -40,9 +40,9 @@ public: class Projection { public: // Map pixel width at given scale. - static double worldSize(double scale) { return scale * util::tileSize_D; } + static double worldSize(double scale) noexcept { return scale * util::tileSize_D; } - static double getMetersPerPixelAtLatitude(double lat, double zoom) { + static double getMetersPerPixelAtLatitude(double lat, double zoom) noexcept { const double constrainedZoom = util::clamp(zoom, util::MIN_ZOOM, util::MAX_ZOOM); const double constrainedScale = std::pow(2.0, constrainedZoom); const double constrainedLatitude = util::clamp(lat, -util::LATITUDE_MAX, util::LATITUDE_MAX); @@ -50,7 +50,7 @@ public: worldSize(constrainedScale); } - static ProjectedMeters projectedMetersForLatLng(const LatLng& latLng) { + static ProjectedMeters projectedMetersForLatLng(const LatLng& latLng) noexcept { const double constrainedLatitude = util::clamp(latLng.latitude(), -util::LATITUDE_MAX, util::LATITUDE_MAX); const double constrainedLongitude = util::clamp(latLng.longitude(), -util::LONGITUDE_MAX, util::LONGITUDE_MAX); @@ -74,10 +74,12 @@ public: return {latitude, longitude}; } - static Point project(const LatLng& latLng, double scale) { return project_(latLng, worldSize(scale)); } + static Point project(const LatLng& latLng, double scale) noexcept { + return project_(latLng, worldSize(scale)); + } /// Returns point on tile - static Point project(const LatLng& latLng, int32_t zoom) { return project_(latLng, 1 << zoom); } + static Point project(const LatLng& latLng, int32_t zoom) noexcept { return project_(latLng, 1 << zoom); } static LatLng unproject(const Point& p, double scale, LatLng::WrapMode wrapMode = LatLng::Unwrapped) { auto p2 = p * util::DEGREES_MAX / worldSize(scale); @@ -87,7 +89,7 @@ public: } private: - static Point project_(const LatLng& latLng, double worldSize) { + static Point project_(const LatLng& latLng, double worldSize) noexcept { const double latitude = util::clamp(latLng.latitude(), -util::LATITUDE_MAX, util::LATITUDE_MAX); return Point{util::LONGITUDE_MAX + latLng.longitude(), util::LONGITUDE_MAX - diff --git a/include/mbgl/util/range.hpp b/include/mbgl/util/range.hpp index f5e4ac535..dc16b5df4 100644 --- a/include/mbgl/util/range.hpp +++ b/include/mbgl/util/range.hpp @@ -16,12 +16,12 @@ public: }; template -bool operator==(const Range& a, const Range& b) { +constexpr bool operator==(const Range& a, const Range& b) { return a.min == b.min && a.max == b.max; } template -bool operator!=(const Range& a, const Range& b) { +constexpr bool operator!=(const Range& a, const Range& b) { return !(a == b); } diff --git a/include/mbgl/util/size.hpp b/include/mbgl/util/size.hpp index 815ba54cb..13777ebe7 100644 --- a/include/mbgl/util/size.hpp +++ b/include/mbgl/util/size.hpp @@ -8,25 +8,25 @@ class Size { public: constexpr Size() = default; - constexpr Size(const uint32_t width_, const uint32_t height_) + constexpr Size(const uint32_t width_, const uint32_t height_) noexcept : width(width_), height(height_) {} - constexpr uint32_t area() const { return width * height; } + constexpr uint32_t area() const noexcept { return width * height; } - constexpr float aspectRatio() const { return static_cast(width) / static_cast(height); } + constexpr float aspectRatio() const noexcept { return static_cast(width) / static_cast(height); } - constexpr bool isEmpty() const { return width == 0 || height == 0; } + constexpr bool isEmpty() const noexcept { return width == 0 || height == 0; } uint32_t width = 0; uint32_t height = 0; }; -constexpr inline bool operator==(const Size& a, const Size& b) { +constexpr inline bool operator==(const Size& a, const Size& b) noexcept { return a.width == b.width && a.height == b.height; } -constexpr inline bool operator!=(const Size& a, const Size& b) { +constexpr inline bool operator!=(const Size& a, const Size& b) noexcept { return !(a == b); } diff --git a/include/mbgl/util/suppress_copies.hpp b/include/mbgl/util/suppress_copies.hpp index a389084e7..0eaf46806 100644 --- a/include/mbgl/util/suppress_copies.hpp +++ b/include/mbgl/util/suppress_copies.hpp @@ -8,15 +8,15 @@ namespace util { template struct SuppressCopies { SuppressCopies() = default; - SuppressCopies(SuppressCopies const&) {} + SuppressCopies(SuppressCopies const&) noexcept {} SuppressCopies(SuppressCopies&& other) - : value(std::forward(other.value)) {} - SuppressCopies& operator=(SuppressCopies o) { + : value(std::forward(other.value)) noexcept {} + SuppressCopies& operator=(SuppressCopies o) noexcept { std::swap(value, o.value); return *this; } - operator T&() { return value; } - T& get() { return value; } + operator T&() noexcept { return value; } + T& get() noexcept { return value; } private: T value; diff --git a/include/mbgl/util/tileset.hpp b/include/mbgl/util/tileset.hpp index d4bb5348f..5019be04f 100644 --- a/include/mbgl/util/tileset.hpp +++ b/include/mbgl/util/tileset.hpp @@ -44,12 +44,12 @@ public: // TileJSON also includes center and zoom but they are not used by mbgl. - friend bool operator==(const Tileset& lhs, const Tileset& rhs) { + friend bool operator==(const Tileset& lhs, const Tileset& rhs) noexcept { return std::tie(lhs.tiles, lhs.zoomRange, lhs.attribution, lhs.scheme, lhs.bounds) == std::tie(rhs.tiles, rhs.zoomRange, rhs.attribution, rhs.scheme, rhs.bounds); } - friend bool operator!=(const Tileset& lhs, const Tileset& rhs) { return !(lhs == rhs); } + friend bool operator!=(const Tileset& lhs, const Tileset& rhs) noexcept { return !(lhs == rhs); } }; } // namespace mbgl diff --git a/include/mbgl/util/tiny_unordered_map.hpp b/include/mbgl/util/tiny_unordered_map.hpp index 99fea52e2..44164d032 100644 --- a/include/mbgl/util/tiny_unordered_map.hpp +++ b/include/mbgl/util/tiny_unordered_map.hpp @@ -77,7 +77,7 @@ public: : TinyUnorderedMap(values_.begin(), values_.end()) {} /// Move constructor - TinyUnorderedMap(TinyUnorderedMap&& rhs) + TinyUnorderedMap(TinyUnorderedMap&& rhs) noexcept : linearSize(rhs.linearSize), keys(std::move(rhs.keys)), values(std::move(rhs.values)) { @@ -127,7 +127,7 @@ public: } /// Swap all contents with another instance - TinyUnorderedMap& swap(TinyUnorderedMap& other) { + TinyUnorderedMap& swap(TinyUnorderedMap& other) noexcept { this->Super::swap(other); std::swap(keys, other.keys); std::swap(values, other.values); @@ -154,7 +154,7 @@ public: std::size_t count(const Key& key) const noexcept { return find(key) ? 1 : 0; } - void clear() { + void clear() noexcept { linearSize = 0; this->Super::clear(); } diff --git a/include/mbgl/util/unitbezier.hpp b/include/mbgl/util/unitbezier.hpp index e6fcf3fbf..5b821b5a2 100644 --- a/include/mbgl/util/unitbezier.hpp +++ b/include/mbgl/util/unitbezier.hpp @@ -33,7 +33,7 @@ namespace util { struct UnitBezier { /// Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). - constexpr UnitBezier(double p1x, double p1y, double p2x, double p2y) + constexpr UnitBezier(double p1x, double p1y, double p2x, double p2y) noexcept : cx(3.0 * p1x), bx(3.0 * (p2x - p1x) - (3.0 * p1x)), ax(1.0 - (3.0 * p1x) - (3.0 * (p2x - p1x) - (3.0 * p1x))), @@ -41,26 +41,26 @@ struct UnitBezier { by(3.0 * (p2y - p1y) - (3.0 * p1y)), ay(1.0 - (3.0 * p1y) - (3.0 * (p2y - p1y) - (3.0 * p1y))) {} - std::pair getP1() const { return {cx / 3.0, cy / 3.0}; } + std::pair getP1() const noexcept { return {cx / 3.0, cy / 3.0}; } - std::pair getP2() const { + std::pair getP2() const noexcept { return { (bx + (3.0 * cx / 3.0) + cx) / 3.0, (by + (3.0 * cy / 3.0) + cy) / 3.0, }; } - double sampleCurveX(double t) const { + double sampleCurveX(double t) const noexcept { // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. return ((ax * t + bx) * t + cx) * t; } - double sampleCurveY(double t) const { return ((ay * t + by) * t + cy) * t; } + double sampleCurveY(double t) const noexcept { return ((ay * t + by) * t + cy) * t; } - double sampleCurveDerivativeX(double t) const { return (3.0 * ax * t + 2.0 * bx) * t + cx; } + double sampleCurveDerivativeX(double t) const noexcept { return (3.0 * ax * t + 2.0 * bx) * t + cx; } /// Given an x value, find a parametric value it came from. - double solveCurveX(double x, double epsilon) const { + double solveCurveX(double x, double epsilon) const noexcept { double t0; double t1; double t2; @@ -99,9 +99,9 @@ struct UnitBezier { return t2; } - double solve(double x, double epsilon) const { return sampleCurveY(solveCurveX(x, epsilon)); } + double solve(double x, double epsilon) const noexcept { return sampleCurveY(solveCurveX(x, epsilon)); } - bool operator==(const UnitBezier& rhs) const { + bool operator==(const UnitBezier& rhs) const noexcept { return std::tie(cx, bx, ax, cy, by, ay) == std::tie(rhs.cx, rhs.bx, rhs.ax, rhs.cy, rhs.by, rhs.ay); } diff --git a/platform/default/src/mbgl/util/compression.cpp b/platform/default/src/mbgl/util/compression.cpp index f138b78af..cad08e117 100644 --- a/platform/default/src/mbgl/util/compression.cpp +++ b/platform/default/src/mbgl/util/compression.cpp @@ -101,7 +101,7 @@ std::string decompress(const std::string &raw, int windowBits) { return result; } -std::uint32_t crc32(const void *raw, size_t size) { +std::uint32_t crc32(const void *raw, size_t size) noexcept { auto hash = ::crc32(0L, Z_NULL, 0); if (raw) { const auto *p = static_cast(raw); diff --git a/src/mbgl/programs/symbol_program.hpp b/src/mbgl/programs/symbol_program.hpp index f209d16d8..5c01eb939 100644 --- a/src/mbgl/programs/symbol_program.hpp +++ b/src/mbgl/programs/symbol_program.hpp @@ -94,10 +94,10 @@ public: class ConstantSymbolSizeBinder final : public SymbolSizeBinder { public: - ConstantSymbolSizeBinder(const float /*tileZoom*/, const float& size, const float /*defaultValue*/) + ConstantSymbolSizeBinder(const float /*tileZoom*/, const float& size, const float /*defaultValue*/) noexcept : layoutSize(size) {} - ConstantSymbolSizeBinder(const float /*tileZoom*/, const style::Undefined&, const float defaultValue) + ConstantSymbolSizeBinder(const float /*tileZoom*/, const style::Undefined&, const float defaultValue) noexcept : layoutSize(defaultValue) {} ConstantSymbolSizeBinder(const float tileZoom, @@ -111,7 +111,7 @@ public: zoomLevels, Range{expression_.evaluate(zoomLevels.min), expression_.evaluate(zoomLevels.max)}); } - Range getVertexSizeData(const GeometryTileFeature&) override { return {0.0f, 0.0f}; }; + Range getVertexSizeData(const GeometryTileFeature&) noexcept override { return {0.0f, 0.0f}; }; ZoomEvaluatedSize evaluateForZoom(float currentZoom) const override { float size = layoutSize; @@ -143,7 +143,7 @@ class SourceFunctionSymbolSizeBinder final : public SymbolSizeBinder { public: SourceFunctionSymbolSizeBinder(const float /*tileZoom*/, style::PropertyExpression expression_, - const float defaultValue_) + const float defaultValue_) noexcept : expression(std::move(expression_)), defaultValue(defaultValue_) {} @@ -152,7 +152,7 @@ public: return {size, size}; }; - ZoomEvaluatedSize evaluateForZoom(float) const override { + ZoomEvaluatedSize evaluateForZoom(float) const noexcept override { const float unused = 0.0f; return {true, false, unused, unused, unused}; } @@ -165,7 +165,7 @@ class CompositeFunctionSymbolSizeBinder final : public SymbolSizeBinder { public: CompositeFunctionSymbolSizeBinder(const float tileZoom, style::PropertyExpression expression_, - const float defaultValue_) + const float defaultValue_) noexcept : expression(std::move(expression_)), defaultValue(defaultValue_), layoutZoom(tileZoom + 1), diff --git a/src/mbgl/renderer/possibly_evaluated_property_value.hpp b/src/mbgl/renderer/possibly_evaluated_property_value.hpp index 5f34de402..1f4cde4c6 100644 --- a/src/mbgl/renderer/possibly_evaluated_property_value.hpp +++ b/src/mbgl/renderer/possibly_evaluated_property_value.hpp @@ -18,16 +18,16 @@ private: public: PossiblyEvaluatedPropertyValue() = default; - PossiblyEvaluatedPropertyValue(Value v) + PossiblyEvaluatedPropertyValue(Value v) noexcept : value(std::move(v)) {} - bool isConstant() const { return value.template is(); } + bool isConstant() const noexcept { return value.template is(); } std::optional constant() const { return value.match([&](const T& t) { return std::optional(t); }, [&](const auto&) { return std::nullopt; }); } - T constantOr(const T& t) const { return constant().value_or(t); } + T constantOr(const T& t) const noexcept { return constant().value_or(t); } template auto match(Ts&&... ts) const { @@ -60,9 +60,8 @@ public: using Dependency = style::expression::Dependency; Dependency getDependencies() const noexcept { - return value.match( - [](const T&) noexcept { return Dependency::None; }, - [](const style::PropertyExpression& expression) noexcept { return expression.getDependencies(); }); + return value.match([](const T&) { return Dependency::None; }, + [](const style::PropertyExpression& expression) { return expression.getDependencies(); }); } }; @@ -75,10 +74,10 @@ private: public: PossiblyEvaluatedPropertyValue() = default; - PossiblyEvaluatedPropertyValue(Value v) + PossiblyEvaluatedPropertyValue(Value v) noexcept : value(std::move(v)) {} - bool isConstant() const { return value.template is>(); } + bool isConstant() const noexcept { return value.template is>(); } std::optional> constant() const { return value.match([&](const Faded& t) { return std::optional>(t); }, @@ -115,9 +114,8 @@ public: using Dependency = style::expression::Dependency; Dependency getDependencies() const noexcept { - return value.match( - [](const Faded&) noexcept { return Dependency::None; }, - [](const style::PropertyExpression& expression) noexcept { return expression.getDependencies(); }); + return value.match([](const Faded&) { return Dependency::None; }, + [](const style::PropertyExpression& expression) { return expression.getDependencies(); }); } }; @@ -127,7 +125,7 @@ template struct Interpolator> { PossiblyEvaluatedPropertyValue operator()(const PossiblyEvaluatedPropertyValue& a, const PossiblyEvaluatedPropertyValue& b, - const double t) const { + const double t) const noexcept { if (a.isConstant() && b.isConstant()) { return {interpolate(*a.constant(), *b.constant(), t)}; } else { @@ -137,7 +135,7 @@ struct Interpolator> { PossiblyEvaluatedPropertyValue operator()(const PossiblyEvaluatedPropertyValue& a, const PossiblyEvaluatedPropertyValue& b, - const float t) const { + const float t) const noexcept { if (a.isConstant() && b.isConstant()) { return {interpolate(*a.constant(), *b.constant(), t)}; } else { diff --git a/src/mbgl/style/conversion/filter.cpp b/src/mbgl/style/conversion/filter.cpp index d72d64c31..4649e4f92 100644 --- a/src/mbgl/style/conversion/filter.cpp +++ b/src/mbgl/style/conversion/filter.cpp @@ -167,7 +167,7 @@ ParseResult convertLegacyHasFilter(const Convertible& values, Error& error) { } else if (*property == "$id") { return createExpression("filter-has-id", std::vector>(), error); } else { - return createExpression("filter-has", {std::make_unique(*property)}, error); + return createExpression("filter-has", {std::make_unique(std::move(*property))}, error); } } diff --git a/src/mbgl/style/conversion/function.cpp b/src/mbgl/style/conversion/function.cpp index 7ff13584f..75bd885bb 100644 --- a/src/mbgl/style/conversion/function.cpp +++ b/src/mbgl/style/conversion/function.cpp @@ -22,7 +22,9 @@ namespace conversion { using namespace expression; using namespace expression::dsl; -const static std::string tokenReservedChars = "{}"; +namespace { +const std::string_view tokenReservedChars = "{}"; +} bool hasTokens(const std::string& source) { auto pos = source.begin(); @@ -194,6 +196,8 @@ struct Converter { } }; +namespace { + enum class FunctionType { Interval, Exponential, @@ -202,17 +206,17 @@ enum class FunctionType { Invalid }; -static bool interpolatable(type::Type type) { +bool interpolatable(type::Type type) noexcept { return type.match([&](const type::NumberType&) { return true; }, [&](const type::ColorType&) { return true; }, [&](const type::Array& array) { return array.N && array.itemType == type::Number; }, [&](const auto&) { return false; }); } -static std::optional> convertLiteral(type::Type type, - const Convertible& value, - Error& error, - bool convertTokens = false) { +std::optional> convertLiteral(type::Type type, + const Convertible& value, + Error& error, + bool convertTokens = false) { return type.match( [&](const type::NumberType&) -> std::optional> { auto result = convert(value, error); @@ -320,10 +324,10 @@ static std::optional> convertLiteral(type::Type type }); } -static std::optional>> convertStops(const type::Type& type, - const Convertible& value, - Error& error, - bool convertTokens) { +std::optional>> convertStops(const type::Type& type, + const Convertible& value, + Error& error, + bool convertTokens) { auto stopsValue = objectMember(value, "stops"); if (!stopsValue) { error.message = "function value must specify stops"; @@ -371,7 +375,7 @@ static std::optional>> convertStops return {std::move(stops)}; } -static void omitFirstStop(std::map>& stops) { +void omitFirstStop(std::map>& stops) { double min = std::numeric_limits::max(); for (auto& s : stops) { if (s.first < min) { @@ -432,7 +436,7 @@ std::optional>> convertBranches(const ty return {std::move(stops)}; } -static std::optional convertBase(const Convertible& value, Error& error) { +std::optional convertBase(const Convertible& value, Error& error) { auto baseValue = objectMember(value, "base"); if (!baseValue) { @@ -448,16 +452,16 @@ static std::optional convertBase(const Convertible& value, Error& error) return *base; } -static std::unique_ptr step(const type::Type& type, - std::unique_ptr input, - std::map> stops) { - return std::make_unique(type, std::move(input), std::move(stops)); +std::unique_ptr step(type::Type type, + std::unique_ptr input, + std::map> stops) { + return std::make_unique(std::move(type), std::move(input), std::move(stops)); } -static std::unique_ptr interpolate(type::Type type, - Interpolator interpolator, - std::unique_ptr input, - std::map> stops) { +std::unique_ptr interpolate(type::Type type, + Interpolator interpolator, + std::unique_ptr input, + std::map> stops) { ParsingContext ctx; auto result = createInterpolate(std::move(type), std::move(interpolator), std::move(input), std::move(stops), ctx); if (!result) { @@ -468,22 +472,23 @@ static std::unique_ptr interpolate(type::Type type, } template -std::unique_ptr categorical(const type::Type& type, +std::unique_ptr categorical(type::Type type, const std::string& property, std::map> branches, std::unique_ptr def) { std::unordered_map> convertedBranches; + convertedBranches.reserve(branches.size()); for (auto& b : branches) { convertedBranches[b.first] = std::move(b.second); } - return std::make_unique>(type, + return std::make_unique>(std::move(type), get(literal(property)), std::move(convertedBranches), def ? std::move(def) : error("replaced with default")); } template <> -std::unique_ptr categorical(const type::Type& type, +std::unique_ptr categorical(type::Type type, const std::string& property, std::map> branches, std::unique_ptr def) { @@ -496,28 +501,29 @@ std::unique_ptr categorical(const type::Type& type, : std::move(it->second); std::vector convertedBranches; + convertedBranches.reserve(2); convertedBranches.emplace_back(eq(get(literal(property)), literal(Value(true))), std::move(trueCase)); convertedBranches.emplace_back(eq(get(literal(property)), literal(Value(false))), std::move(falseCase)); return std::make_unique( - type, std::move(convertedBranches), def ? std::move(def) : error("replaced with default")); + std::move(type), std::move(convertedBranches), def ? std::move(def) : error("replaced with default")); } -static std::unique_ptr numberOrDefault(const type::Type& type, - std::unique_ptr get, - std::unique_ptr expr, - std::unique_ptr def) { +std::unique_ptr numberOrDefault(type::Type type, + std::unique_ptr get, + std::unique_ptr expr, + std::unique_ptr def) { if (!def) { return expr; } std::vector branches; branches.emplace_back(eq(compound("typeof", std::move(get)), literal("number")), std::move(expr)); - return std::make_unique(type, std::move(branches), std::move(def)); + return std::make_unique(std::move(type), std::move(branches), std::move(def)); } -static std::optional> convertIntervalFunction( - const type::Type& type, +std::optional> convertIntervalFunction( + type::Type type, const Convertible& value, Error& error, const std::function(bool)>& makeInput, @@ -529,11 +535,12 @@ static std::optional> convertIntervalFunction( } omitFirstStop(*stops); - return numberOrDefault(type, makeInput(false), step(type, makeInput(true), std::move(*stops)), std::move(def)); + auto expr = step(type, makeInput(true), std::move(*stops)); + return numberOrDefault(std::move(type), makeInput(false), std::move(expr), std::move(def)); } -static std::optional> convertExponentialFunction( - const type::Type& type, +std::optional> convertExponentialFunction( + type::Type type, const Convertible& value, Error& error, const std::function(bool)>& makeInput, @@ -548,17 +555,15 @@ static std::optional> convertExponentialFunction( return std::nullopt; } - return numberOrDefault(type, - makeInput(false), - interpolate(type, exponential(*base), makeInput(true), std::move(*stops)), - std::move(def)); + auto expr = interpolate(type, exponential(*base), makeInput(true), std::move(*stops)); + return numberOrDefault(std::move(type), makeInput(false), std::move(expr), std::move(def)); } -static std::optional> convertCategoricalFunction(const type::Type& type, - const Convertible& value, - Error& err, - const std::string& property, - std::unique_ptr def) { +std::optional> convertCategoricalFunction(type::Type type, + const Convertible& value, + Error& err, + const std::string& property, + std::unique_ptr def) { auto stopsValue = objectMember(value, "stops"); if (!stopsValue) { err.message = "function value must specify stops"; @@ -592,7 +597,7 @@ static std::optional> convertCategoricalFunction(con if (!branches) { return std::nullopt; } - return categorical(type, property, std::move(*branches), std::move(def)); + return categorical(std::move(type), property, std::move(*branches), std::move(def)); } if (toNumber(arrayMember(first, 0))) { @@ -600,7 +605,7 @@ static std::optional> convertCategoricalFunction(con if (!branches) { return std::nullopt; } - return categorical(type, property, std::move(*branches), std::move(def)); + return categorical(std::move(type), property, std::move(*branches), std::move(def)); } if (toString(arrayMember(first, 0))) { @@ -608,7 +613,7 @@ static std::optional> convertCategoricalFunction(con if (!branches) { return std::nullopt; } - return categorical(type, property, std::move(*branches), std::move(def)); + return categorical(std::move(type), property, std::move(*branches), std::move(def)); } err.message = "stop domain value must be a number, string, or boolean"; @@ -690,12 +695,14 @@ std::optional> composite(type::Type type, } if (interpolatable(type)) { - return interpolate(type, linear(), zoom(), std::move(stops)); + return interpolate(std::move(type), linear(), zoom(), std::move(stops)); } else { - return step(type, zoom(), std::move(stops)); + return step(std::move(type), zoom(), std::move(stops)); } } +} // namespace + std::optional> convertFunctionToExpression(type::Type type, const Convertible& value, Error& err, diff --git a/src/mbgl/style/expression/assertion.cpp b/src/mbgl/style/expression/assertion.cpp index 939ebb366..07457c32a 100644 --- a/src/mbgl/style/expression/assertion.cpp +++ b/src/mbgl/style/expression/assertion.cpp @@ -76,7 +76,7 @@ ParseResult Assertion::parse(const Convertible& value, ParsingContext& ctx) { parsed.push_back(std::move(*input)); } - return ParseResult(std::make_unique(type, std::move(parsed))); + return ParseResult(std::make_unique(std::move(type), std::move(parsed))); } std::string Assertion::getOperator() const { @@ -105,7 +105,7 @@ void Assertion::eachChild(const std::function& visit) c } }; -bool Assertion::operator==(const Expression& e) const { +bool Assertion::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Assertion) { auto rhs = static_cast(&e); return getType() == rhs->getType() && Expression::childrenEqual(inputs, rhs->inputs); diff --git a/src/mbgl/style/expression/boolean_operator.cpp b/src/mbgl/style/expression/boolean_operator.cpp index ea2a75af1..8f3fc10cb 100644 --- a/src/mbgl/style/expression/boolean_operator.cpp +++ b/src/mbgl/style/expression/boolean_operator.cpp @@ -20,9 +20,9 @@ void Any::eachChild(const std::function& visit) const { } } -bool Any::operator==(const Expression& e) const { +bool Any::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Any) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return Expression::childrenEqual(inputs, rhs->inputs); } return false; @@ -47,9 +47,9 @@ void All::eachChild(const std::function& visit) const { } } -bool All::operator==(const Expression& e) const { +bool All::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::All) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return Expression::childrenEqual(inputs, rhs->inputs); } return false; diff --git a/src/mbgl/style/expression/case.cpp b/src/mbgl/style/expression/case.cpp index 90818a3d9..91603ae19 100644 --- a/src/mbgl/style/expression/case.cpp +++ b/src/mbgl/style/expression/case.cpp @@ -28,9 +28,9 @@ void Case::eachChild(const std::function& visit) const visit(*otherwise); } -bool Case::operator==(const Expression& e) const { +bool Case::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Case) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return *otherwise == *(rhs->otherwise) && Expression::childrenEqual(branches, rhs->branches); } return false; diff --git a/src/mbgl/style/expression/coalesce.cpp b/src/mbgl/style/expression/coalesce.cpp index aff148c24..c1317dc7a 100644 --- a/src/mbgl/style/expression/coalesce.cpp +++ b/src/mbgl/style/expression/coalesce.cpp @@ -35,9 +35,9 @@ void Coalesce::eachChild(const std::function& visit) co } } -bool Coalesce::operator==(const Expression& e) const { +bool Coalesce::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Coalesce) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return Expression::childrenEqual(args, rhs->args); } return false; @@ -91,7 +91,8 @@ ParseResult Coalesce::parse(const Convertible& value, ParsingContext& ctx) { return type::checkSubtype(*expectedType, arg->getType()); }); - return ParseResult(std::make_unique(needsAnnotation ? type::Value : *outputType, std::move(args))); + return ParseResult( + std::make_unique(needsAnnotation ? type::Value : std::move(*outputType), std::move(args))); } } // namespace expression diff --git a/src/mbgl/style/expression/coercion.cpp b/src/mbgl/style/expression/coercion.cpp index 0429d34fa..c491afefd 100644 --- a/src/mbgl/style/expression/coercion.cpp +++ b/src/mbgl/style/expression/coercion.cpp @@ -12,7 +12,7 @@ using CoerceFunction = EvaluationResult (*)(const Value&); namespace { -EvaluationResult toBoolean(const Value& v) { +EvaluationResult toBoolean(const Value& v) noexcept { return v.match([&](double f) { return static_cast(f); }, [&](const std::string& s) { return s.length() > 0; }, [&](bool b) { return b; }, @@ -50,7 +50,7 @@ EvaluationResult toColor(const Value& colorValue) { } }, [&colorValue](const std::vector& components) -> EvaluationResult { - std::size_t len = components.size(); + const std::size_t len = components.size(); bool isNumeric = std::all_of(components.begin(), components.end(), [](const Value& item) -> bool { return item.template is(); }); @@ -132,14 +132,15 @@ mbgl::Value Coercion::serialize() const { }; std::string Coercion::getOperator() const { - return getType().match([](const type::BooleanType&) { return "to-boolean"; }, - [](const type::ColorType&) { return "to-color"; }, - [](const type::NumberType&) { return "to-number"; }, - [](const type::StringType&) { return "to-string"; }, - [](const auto&) { - assert(false); - return ""; - }); + auto s = getType().match([](const type::BooleanType&) -> std::string_view { return "to-boolean"; }, + [](const type::ColorType&) -> std::string_view { return "to-color"; }, + [](const type::NumberType&) -> std::string_view { return "to-number"; }, + [](const type::StringType&) -> std::string_view { return "to-string"; }, + [](const auto&) noexcept -> std::string_view { + assert(false); + return ""; + }); + return std::string(s); } using namespace mbgl::style::conversion; @@ -203,9 +204,9 @@ void Coercion::eachChild(const std::function& visit) co } }; -bool Coercion::operator==(const Expression& e) const { +bool Coercion::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Coercion) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return getType() == rhs->getType() && Expression::childrenEqual(inputs, rhs->inputs); } return false; diff --git a/src/mbgl/style/expression/collator_expression.cpp b/src/mbgl/style/expression/collator_expression.cpp index 9355cf45c..0f2340ce7 100644 --- a/src/mbgl/style/expression/collator_expression.cpp +++ b/src/mbgl/style/expression/collator_expression.cpp @@ -75,7 +75,7 @@ void CollatorExpression::eachChild(const std::function& } } -bool CollatorExpression::operator==(const Expression& e) const { +bool CollatorExpression::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::CollatorExpression) { const auto* rhs = static_cast(&e); const bool lLocSet = locale && *locale; @@ -108,7 +108,7 @@ EvaluationResult CollatorExpression::evaluate(const EvaluationContext& params) c return diacriticSensitiveResult.error(); } - if (locale) { + if (locale && *locale) { if (auto localeResult = (*locale)->evaluate(params)) { return Collator(caseSensitiveResult->get(), diacriticSensitiveResult->get(), diff --git a/src/mbgl/style/expression/comparison.cpp b/src/mbgl/style/expression/comparison.cpp index 393bdfd29..027e69b40 100644 --- a/src/mbgl/style/expression/comparison.cpp +++ b/src/mbgl/style/expression/comparison.cpp @@ -8,7 +8,7 @@ namespace mbgl { namespace style { namespace expression { -static bool isComparableType(const std::string& op, const type::Type& type) { +static bool isComparableType(const std::string& op, const type::Type& type) noexcept { if (op == "==" || op == "!=") { return type == type::String || type == type::Number || type == type::Boolean || type == type::Null || type == type::Value; @@ -17,13 +17,13 @@ static bool isComparableType(const std::string& op, const type::Type& type) { } } -bool eq(const Value& a, const Value& b) { +bool eq(const Value& a, const Value& b) noexcept { return a == b; } -bool neq(const Value& a, const Value& b) { +bool neq(const Value& a, const Value& b) noexcept { return a != b; } -bool lt(const Value& lhs, const Value& rhs) { +bool lt(const Value& lhs, const Value& rhs) noexcept { return lhs.match([&](const std::string& a) { return a < rhs.get(); }, [&](double a) { return a < rhs.get(); }, [&](const auto&) { @@ -31,7 +31,7 @@ bool lt(const Value& lhs, const Value& rhs) { return false; }); } -bool gt(const Value& lhs, const Value& rhs) { +bool gt(const Value& lhs, const Value& rhs) noexcept { return lhs.match([&](const std::string& a) { return a > rhs.get(); }, [&](double a) { return a > rhs.get(); }, [&](const auto&) { @@ -39,7 +39,7 @@ bool gt(const Value& lhs, const Value& rhs) { return false; }); } -bool lteq(const Value& lhs, const Value& rhs) { +bool lteq(const Value& lhs, const Value& rhs) noexcept { return lhs.match([&](const std::string& a) { return a <= rhs.get(); }, [&](double a) { return a <= rhs.get(); }, [&](const auto&) { @@ -47,7 +47,7 @@ bool lteq(const Value& lhs, const Value& rhs) { return false; }); } -bool gteq(const Value& lhs, const Value& rhs) { +bool gteq(const Value& lhs, const Value& rhs) noexcept { return lhs.match([&](const std::string& a) { return a >= rhs.get(); }, [&](double a) { return a >= rhs.get(); }, [&](const auto&) { @@ -56,26 +56,26 @@ bool gteq(const Value& lhs, const Value& rhs) { }); } -bool eqCollate(const std::string& a, const std::string& b, const Collator& c) { +bool eqCollate(const std::string& a, const std::string& b, const Collator& c) noexcept { return c.compare(a, b) == 0; } -bool neqCollate(const std::string& a, const std::string& b, const Collator& c) { +bool neqCollate(const std::string& a, const std::string& b, const Collator& c) noexcept { return !eqCollate(a, b, c); } -bool ltCollate(const std::string& a, const std::string& b, const Collator& c) { +bool ltCollate(const std::string& a, const std::string& b, const Collator& c) noexcept { return c.compare(a, b) < 0; } -bool gtCollate(const std::string& a, const std::string& b, const Collator& c) { +bool gtCollate(const std::string& a, const std::string& b, const Collator& c) noexcept { return c.compare(a, b) > 0; } -bool lteqCollate(const std::string& a, const std::string& b, const Collator& c) { +bool lteqCollate(const std::string& a, const std::string& b, const Collator& c) noexcept { return c.compare(a, b) <= 0; } -bool gteqCollate(const std::string& a, const std::string& b, const Collator& c) { +bool gteqCollate(const std::string& a, const std::string& b, const Collator& c) noexcept { return c.compare(a, b) >= 0; } -static BasicComparison::CompareFunctionType getBasicCompareFunction(const std::string& op) { +static BasicComparison::CompareFunctionType getBasicCompareFunction(const std::string& op) noexcept { if (op == "==") return eq; else if (op == "!=") @@ -92,7 +92,7 @@ static BasicComparison::CompareFunctionType getBasicCompareFunction(const std::s return nullptr; } -static CollatorComparison::CompareFunctionType getCollatorComparisonFunction(const std::string& op) { +static CollatorComparison::CompareFunctionType getCollatorComparisonFunction(const std::string& op) noexcept { if (op == "==") return eqCollate; else if (op == "!=") @@ -148,13 +148,9 @@ void BasicComparison::eachChild(const std::function& vi visit(*rhs); } -std::string BasicComparison::getOperator() const { - return op; -} - -bool BasicComparison::operator==(const Expression& e) const { +bool BasicComparison::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Comparison) { - auto comp = static_cast(&e); + const auto* comp = static_cast(&e); return comp->op == op && *comp->lhs == *lhs && *comp->rhs == *rhs; } return false; @@ -207,13 +203,9 @@ void CollatorComparison::eachChild(const std::function& visit(*collator); } -std::string CollatorComparison::getOperator() const { - return op; -} - -bool CollatorComparison::operator==(const Expression& e) const { +bool CollatorComparison::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Comparison) { - auto comp = static_cast(&e); + const auto* comp = static_cast(&e); return comp->op == op && *comp->collator == *collator && *comp->lhs == *lhs && *comp->rhs == *rhs; } return false; diff --git a/src/mbgl/style/expression/compound_expression.cpp b/src/mbgl/style/expression/compound_expression.cpp index 56909a85a..6ab2ecf3d 100644 --- a/src/mbgl/style/expression/compound_expression.cpp +++ b/src/mbgl/style/expression/compound_expression.cpp @@ -1247,14 +1247,10 @@ EvaluationResult CompoundExpression::evaluate(const EvaluationContext& evaluatio return signature.apply(evaluationParams, args); } -std::optional CompoundExpression::getParameterCount() const { +std::optional CompoundExpression::getParameterCount() const noexcept { return signature.params.match( - [&](const VarargsType&) -> std::optional { return std::nullopt; }, - [&](const std::vector& p) -> std::optional { return p.size(); }); -} - -std::vector> CompoundExpression::possibleOutputs() const { - return {std::nullopt}; + [&](const VarargsType&) noexcept -> std::optional { return std::nullopt; }, + [&](const std::vector& p) noexcept -> std::optional { return p.size(); }); } void CompoundExpression::eachChild(const std::function& visit) const { @@ -1263,7 +1259,7 @@ void CompoundExpression::eachChild(const std::function& } } -bool CompoundExpression::operator==(const Expression& e) const { +bool CompoundExpression::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::CompoundExpression) { auto rhs = static_cast(&e); return signature.name == rhs->signature.name && signature.result == rhs->signature.result && @@ -1272,7 +1268,7 @@ bool CompoundExpression::operator==(const Expression& e) const { return false; } -bool CompoundExpression::exists(const std::string& name) { +bool CompoundExpression::exists(const std::string& name) noexcept { return compoundExpressionRegistry.contains(name.c_str()); } diff --git a/src/mbgl/style/expression/distance.cpp b/src/mbgl/style/expression/distance.cpp index 9a7b07baa..811db39bb 100644 --- a/src/mbgl/style/expression/distance.cpp +++ b/src/mbgl/style/expression/distance.cpp @@ -20,20 +20,20 @@ namespace mbgl { namespace { -const std::size_t MinPointsSize = 100; -const std::size_t MinLinePointsSize = 50; -const double InvalidDistance = std::numeric_limits::quiet_NaN(); -const double InfiniteDistance = std::numeric_limits::infinity(); -const mapbox::cheap_ruler::CheapRuler::Unit UnitInMeters = mapbox::cheap_ruler::CheapRuler::Unit::Meters; +constexpr std::size_t MinPointsSize = 100; +constexpr std::size_t MinLinePointsSize = 50; +constexpr double InvalidDistance = std::numeric_limits::quiet_NaN(); +constexpr double InfiniteDistance = std::numeric_limits::infinity(); +constexpr mapbox::cheap_ruler::CheapRuler::Unit UnitInMeters = mapbox::cheap_ruler::CheapRuler::Unit::Meters; // Inclusive index range for multipoint or linestring container using IndexRange = std::pair; -std::size_t getRangeSize(const IndexRange& range) { +inline std::size_t getRangeSize(const IndexRange& range) noexcept { return range.second - range.first + 1; } -bool isRangeSafe(const IndexRange& range, const std::size_t threshold) { +bool isRangeSafe(const IndexRange& range, const std::size_t threshold) noexcept { auto ret = (range.second >= range.first && range.second < threshold); if (!ret) { mbgl::Log::Error(mbgl::Event::Style, "Index is out of range"); @@ -42,31 +42,33 @@ bool isRangeSafe(const IndexRange& range, const std::size_t threshold) { } std::pair, std::optional> splitRange(const IndexRange& range, bool isLine) { - if (range.first > range.second) return std::make_pair(std::nullopt, std::nullopt); - auto size = getRangeSize(range); + if (range.first > range.second) { + return std::make_pair(std::nullopt, std::nullopt); + } + const auto size = getRangeSize(range); if (isLine) { if (size == 2) { return std::make_pair(range, std::nullopt); } - auto size1 = size / 2; - IndexRange range1(range.first, range.first + size1); - IndexRange range2(range.first + size1, range.second); - return std::make_pair(std::move(range1), std::move(range2)); + const auto size1 = size / 2; + return std::make_pair(IndexRange{range.first, range.first + size1}, + IndexRange{range.first + size1, range.second}); } else { if (size == 1) { return std::make_pair(range, std::nullopt); } - auto size1 = size / 2 - 1; - IndexRange range1(range.first, range.first + size1); - IndexRange range2(range.first + size1 + 1, range.second); - return std::make_pair(std::move(range1), std::move(range2)); + const auto size1 = size / 2 - 1; + return std::make_pair(IndexRange{range.first, range.first + size1}, + IndexRange{range.first + size1 + 1, range.second}); } } using DistanceBBox = GeometryBBox; -DistanceBBox getBBox(const mapbox::geometry::multi_point& points, const IndexRange& range) { - if (!isRangeSafe(range, points.size())) return DefaultDistanceBBox; +DistanceBBox getBBox(const mapbox::geometry::multi_point& points, const IndexRange& range) noexcept { + if (!isRangeSafe(range, points.size())) { + return DefaultDistanceBBox; + } DistanceBBox bbox = DefaultDistanceBBox; for (std::size_t i = range.first; i <= range.second; ++i) { @@ -75,8 +77,11 @@ DistanceBBox getBBox(const mapbox::geometry::multi_point& points, const return bbox; } -DistanceBBox getBBox(const mapbox::geometry::line_string& line, const IndexRange& range) { - if (!isRangeSafe(range, line.size())) return DefaultDistanceBBox; +DistanceBBox getBBox(const mapbox::geometry::line_string& line, const IndexRange& range) noexcept { + if (!isRangeSafe(range, line.size())) { + return DefaultDistanceBBox; + } + DistanceBBox bbox = DefaultDistanceBBox; for (std::size_t i = range.first; i <= range.second; ++i) { updateBBox(bbox, line[i]); @@ -84,7 +89,7 @@ DistanceBBox getBBox(const mapbox::geometry::line_string& line, const In return bbox; } -DistanceBBox getBBox(const mapbox::geometry::polygon& polygon) { +DistanceBBox getBBox(const mapbox::geometry::polygon& polygon) noexcept { DistanceBBox bbox = DefaultDistanceBBox; for (const auto& ring : polygon) { for (const auto& p : ring) { @@ -94,7 +99,7 @@ DistanceBBox getBBox(const mapbox::geometry::polygon& polygon) { return bbox; } -bool isMultiPointValid(const mapbox::geometry::multi_point& points) { +bool isMultiPointValid(const mapbox::geometry::multi_point& points) noexcept { if (points.empty()) { mbgl::Log::Error(mbgl::Event::Style, "Invalid MultiPoint with empty geometry points"); return false; @@ -102,7 +107,7 @@ bool isMultiPointValid(const mapbox::geometry::multi_point& points) { return true; } -bool isLineStringValid(const mapbox::geometry::line_string& line) { +bool isLineStringValid(const mapbox::geometry::line_string& line) noexcept { if (line.size() < 2) { mbgl::Log::Error(mbgl::Event::Style, "Invalid LineString with fewer than 2 geometry points"); return false; @@ -110,7 +115,7 @@ bool isLineStringValid(const mapbox::geometry::line_string& line) { return true; } -bool isPolygonValid(const mapbox::geometry::polygon& polygon) { +bool isPolygonValid(const mapbox::geometry::polygon& polygon) noexcept { if (polygon.empty()) { mbgl::Log::Error(mbgl::Event::Style, "Invalid Polygon with empty rings"); return false; @@ -131,7 +136,7 @@ bool isPolygonValid(const mapbox::geometry::polygon& polygon) { // and {dx, dy} to calculate the distance. Distance will be 0.0 if bounding box are overlapping. double bboxToBBoxDistance(const DistanceBBox& bbox1, const DistanceBBox& bbox2, - mapbox::cheap_ruler::CheapRuler& ruler) { + const mapbox::cheap_ruler::CheapRuler& ruler) noexcept { if (bbox1 == DefaultDistanceBBox || bbox2 == DefaultDistanceBBox) { return InvalidDistance; } @@ -158,7 +163,7 @@ double bboxToBBoxDistance(const DistanceBBox& bbox1, double pointToLineDistance(const mapbox::geometry::point& point, const mapbox::geometry::line_string& line, - mapbox::cheap_ruler::CheapRuler& ruler) { + const mapbox::cheap_ruler::CheapRuler& ruler) noexcept { const auto nearestPoint = std::get<0>(ruler.pointOnLine(line, point)); return ruler.distance(point, nearestPoint); } @@ -168,21 +173,24 @@ double segmentToSegmentDistance(const mapbox::geometry::point& p1, const mapbox::geometry::point& p2, const mapbox::geometry::point& q1, const mapbox::geometry::point& q2, - mapbox::cheap_ruler::CheapRuler& ruler) { - auto dist1 = std::min(pointToLineDistance(p1, mapbox::geometry::line_string{q1, q2}, ruler), - pointToLineDistance(p2, mapbox::geometry::line_string{q1, q2}, ruler)); - auto dist2 = std::min(pointToLineDistance(q1, mapbox::geometry::line_string{p1, p2}, ruler), - pointToLineDistance(q2, mapbox::geometry::line_string{p1, p2}, ruler)); + const mapbox::cheap_ruler::CheapRuler& ruler) noexcept { + const auto dist1 = std::min(pointToLineDistance(p1, mapbox::geometry::line_string{q1, q2}, ruler), + pointToLineDistance(p2, mapbox::geometry::line_string{q1, q2}, ruler)); + const auto dist2 = std::min(pointToLineDistance(q1, mapbox::geometry::line_string{p1, p2}, ruler), + pointToLineDistance(q2, mapbox::geometry::line_string{p1, p2}, ruler)); return std::min(dist1, dist2); } double lineToLineDistance(const mapbox::geometry::line_string& line1, - IndexRange& range1, + const IndexRange& range1, const mapbox::geometry::line_string& line2, - IndexRange& range2, - mapbox::cheap_ruler::CheapRuler& ruler) { - bool rangeSafe = isRangeSafe(range1, line1.size()) && isRangeSafe(range2, line2.size()); - if (!rangeSafe) return InvalidDistance; + const IndexRange& range2, + const mapbox::cheap_ruler::CheapRuler& ruler) noexcept { + const bool rangeSafe = isRangeSafe(range1, line1.size()) && isRangeSafe(range2, line2.size()); + if (!rangeSafe) { + return InvalidDistance; + } + double dist = InfiniteDistance; for (std::size_t i = range1.first; i < range1.second; ++i) { const auto& p1 = line1[i]; @@ -190,7 +198,9 @@ double lineToLineDistance(const mapbox::geometry::line_string& line1, for (std::size_t j = range2.first; j < range2.second; ++j) { const auto& q1 = line2[j]; const auto& q2 = line2[j + 1]; - if (segmentIntersectSegment(p1, p2, q1, q2)) return 0.0; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } dist = std::min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); } } @@ -198,17 +208,22 @@ double lineToLineDistance(const mapbox::geometry::line_string& line1, } double pointsToPointsDistance(const mapbox::geometry::multi_point& points1, - IndexRange& range1, + const IndexRange& range1, const mapbox::geometry::multi_point& points2, - IndexRange& range2, - mapbox::cheap_ruler::CheapRuler& ruler) { - bool rangeSafe = isRangeSafe(range1, points1.size()) && isRangeSafe(range2, points2.size()); - if (!rangeSafe) return InvalidDistance; + const IndexRange& range2, + const mapbox::cheap_ruler::CheapRuler& ruler) noexcept { + const bool rangeSafe = isRangeSafe(range1, points1.size()) && isRangeSafe(range2, points2.size()); + if (!rangeSafe) { + return InvalidDistance; + } + double dist = InfiniteDistance; for (std::size_t i = range1.first; i <= range1.second; ++i) { for (std::size_t j = range2.first; j <= range2.second; ++j) { dist = std::min(dist, ruler.distance(points1[i], points2[j])); - if (dist == 0.0) return dist; + if (dist == 0.0) { + return dist; + } } } return dist; @@ -216,19 +231,25 @@ double pointsToPointsDistance(const mapbox::geometry::multi_point& point double pointToPolygonDistance(const mapbox::geometry::point& point, const mapbox::geometry::polygon& polygon, - mapbox::cheap_ruler::CheapRuler& ruler) { - if (pointWithinPolygon(point, polygon, true /*trueOnBoundary*/)) return 0.0; + const mapbox::cheap_ruler::CheapRuler& ruler) noexcept { + if (pointWithinPolygon(point, polygon, true /*trueOnBoundary*/)) { + return 0.0; + } double dist = InfiniteDistance; for (const auto& ring : polygon) { if (ring.front() != ring.back()) { dist = std::min( dist, pointToLineDistance(point, mapbox::geometry::line_string{ring.back(), ring.front()}, ruler)); - if (dist == 0.0) return dist; + if (dist == 0.0) { + return dist; + } } const auto nearestPoint = std::get<0>(ruler.pointOnLine(ring, point)); dist = std::min(dist, ruler.distance(point, nearestPoint)); - if (dist == 0.0) return dist; + if (dist == 0.0) { + return dist; + } } return dist; } @@ -236,10 +257,15 @@ double pointToPolygonDistance(const mapbox::geometry::point& point, double lineToPolygonDistance(const mapbox::geometry::line_string& line, const IndexRange& range, const mapbox::geometry::polygon& polygon, - mapbox::cheap_ruler::CheapRuler& ruler) { - if (!isRangeSafe(range, line.size())) return InvalidDistance; + const mapbox::cheap_ruler::CheapRuler& ruler) noexcept { + if (!isRangeSafe(range, line.size())) { + return InvalidDistance; + } + for (std::size_t i = range.first; i <= range.second; ++i) { - if (pointWithinPolygon(line[i], polygon, true /*trueOnBoundary*/)) return 0.0; + if (pointWithinPolygon(line[i], polygon, true /*trueOnBoundary*/)) { + return 0.0; + } } double dist = InfiniteDistance; @@ -250,7 +276,9 @@ double lineToPolygonDistance(const mapbox::geometry::line_string& line, for (std::size_t j = 0, len = ring.size(), k = len - 1; j < len; k = j++) { const auto& q1 = ring[k]; const auto& q2 = ring[j]; - if (segmentIntersectSegment(p1, p2, q1, q2)) return 0.0; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } dist = std::min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); } } @@ -262,7 +290,7 @@ double lineToPolygonDistance(const mapbox::geometry::line_string& line, // quadratic, performance improvement is needed. double polygonToPolygonDistance(const mapbox::geometry::polygon& polygon1, const mapbox::geometry::polygon& polygon2, - mapbox::cheap_ruler::CheapRuler& ruler, + const mapbox::cheap_ruler::CheapRuler& ruler, double currentMiniDist = InfiniteDistance) { const auto bbox1 = getBBox(polygon1); const auto bbox2 = getBBox(polygon2); @@ -270,16 +298,20 @@ double polygonToPolygonDistance(const mapbox::geometry::polygon& polygon return currentMiniDist; } const auto polygonIntersect = [](const mapbox::geometry::polygon& poly1, - const mapbox::geometry::polygon& poly2) { + const mapbox::geometry::polygon& poly2) noexcept { for (const auto& ring : poly1) { for (std::size_t i = 0; i <= ring.size() - 1; ++i) { - if (pointWithinPolygon(ring[i], poly2, true /*trueOnBoundary*/)) return true; + if (pointWithinPolygon(ring[i], poly2, true /*trueOnBoundary*/)) { + return true; + } } } return false; }; if (boxWithinBox(bbox1, bbox2)) { - if (polygonIntersect(polygon1, polygon2)) return 0.0; + if (polygonIntersect(polygon1, polygon2)) { + return 0.0; + } } else if (polygonIntersect(polygon2, polygon1)) { return 0.0; } @@ -293,7 +325,9 @@ double polygonToPolygonDistance(const mapbox::geometry::polygon& polygon for (std::size_t j = 0, len2 = ring2.size(), k = len2 - 1; j < len2; k = j++) { const auto& q1 = ring2[k]; const auto& q2 = ring2[j]; - if (segmentIntersectSegment(p1, p2, q1, q2)) return 0.0; + if (segmentIntersectSegment(p1, p2, q1, q2)) { + return 0.0; + } dist = std::min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler)); } } @@ -305,7 +339,7 @@ double polygonToPolygonDistance(const mapbox::geometry::polygon& polygon // using DistPair = std::tuple; struct Comparator { - bool operator()(DistPair& left, DistPair& right) { return std::get<0>(left) < std::get<0>(right); } + bool operator()(DistPair& left, DistPair& right) noexcept { return std::get<0>(left) < std::get<0>(right); } }; // The priority queue will ensure the top element would always be the pair that has the biggest distance using DistQueue = std::priority_queue, Comparator>; @@ -315,19 +349,25 @@ using DistQueue = std::priority_queue, Comparator double pointsToPolygonDistance(const mapbox::geometry::multi_point& points, const mapbox::geometry::polygon& polygon, - mapbox::cheap_ruler::CheapRuler& ruler, + const mapbox::cheap_ruler::CheapRuler& ruler, double currentMiniDist = InfiniteDistance) { auto miniDist = std::min(ruler.distance(points[0], polygon[0][0]), currentMiniDist); - if (miniDist == 0.0) return miniDist; + if (miniDist == 0.0) { + return miniDist; + } + DistQueue distQueue; distQueue.push(std::forward_as_tuple(0, IndexRange(0, points.size() - 1), IndexRange(0, 0))); const auto polyBBox = getBBox(polygon); while (!distQueue.empty()) { - auto distPair = distQueue.top(); + const auto distPair = distQueue.top(); distQueue.pop(); - if (std::get<0>(distPair) >= miniDist) continue; - auto& range = std::get<1>(distPair); + if (std::get<0>(distPair) >= miniDist) { + continue; + } + + const auto& range = std::get<1>(distPair); // In case the set size are relatively small, we could use brute-force directly if (getRangeSize(range) <= MinLinePointsSize) { @@ -336,21 +376,25 @@ double pointsToPolygonDistance(const mapbox::geometry::multi_point& poin return InvalidDistance; } for (std::size_t i = range.first; i <= range.second; ++i) { - auto tempDist = pointToPolygonDistance(points[i], polygon, ruler); + const auto tempDist = pointToPolygonDistance(points[i], polygon, ruler); miniDist = std::min(miniDist, tempDist); - if (miniDist == 0.0) return 0.0; + if (miniDist == 0.0) { + return 0.0; + } } } else { - auto newRangesA = splitRange(range, false /*isLine*/); + const auto newRangesA = splitRange(range, false /*isLine*/); const auto updateQueue = - [&distQueue, &miniDist, &ruler, &points, &polyBBox](std::optional& rangeA) { - if (!rangeA) return; - auto tempDist = bboxToBBoxDistance(getBBox(points, *rangeA), polyBBox, ruler); - // Insert new pair to the queue if the bbox distance is less - // than miniDist, The pair with biggest distance will be at - // the top - if (tempDist < miniDist) + [&distQueue, &miniDist, &ruler, &points, &polyBBox](const std::optional& rangeA) { + if (!rangeA) { + return; + } + const auto tempDist = bboxToBBoxDistance(getBBox(points, *rangeA), polyBBox, ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { distQueue.push(std::make_tuple(tempDist, std::move(*rangeA), IndexRange(0, 0))); + } }; updateQueue(newRangesA.first); updateQueue(newRangesA.second); @@ -361,37 +405,46 @@ double pointsToPolygonDistance(const mapbox::geometry::multi_point& poin double lineToPolygonDistance(const mapbox::geometry::line_string& line, const mapbox::geometry::polygon& polygon, - mapbox::cheap_ruler::CheapRuler& ruler, + const mapbox::cheap_ruler::CheapRuler& ruler, double currentMiniDist = InfiniteDistance) { auto miniDist = std::min(ruler.distance(line[0], polygon[0][0]), currentMiniDist); - if (miniDist == 0.0) return miniDist; + if (miniDist == 0.0) { + return miniDist; + } + DistQueue distQueue; distQueue.push(std::forward_as_tuple(0, IndexRange(0, line.size() - 1), IndexRange(0, 0))); const auto polyBBox = getBBox(polygon); while (!distQueue.empty()) { - auto distPair = distQueue.top(); + const auto distPair = distQueue.top(); distQueue.pop(); - if (std::get<0>(distPair) >= miniDist) continue; - auto& range = std::get<1>(distPair); + if (std::get<0>(distPair) >= miniDist) { + continue; + } + + const auto& range = std::get<1>(distPair); // In case the set size are relatively small, we could use brute-force directly if (getRangeSize(range) <= MinLinePointsSize) { - auto tempDist = lineToPolygonDistance(line, range, polygon, ruler); - if (std::isnan(tempDist)) return tempDist; + const auto tempDist = lineToPolygonDistance(line, range, polygon, ruler); + if (std::isnan(tempDist) || tempDist == 0.0) { + return tempDist; + } miniDist = std::min(miniDist, tempDist); - if (miniDist == 0.0) return 0.0; } else { - auto newRangesA = splitRange(range, true /*isLine*/); + const auto newRangesA = splitRange(range, true /*isLine*/); const auto updateQueue = - [&distQueue, &miniDist, &ruler, &line, &polyBBox](std::optional& rangeA) { - if (!rangeA) return; - auto tempDist = bboxToBBoxDistance(getBBox(line, *rangeA), polyBBox, ruler); - // Insert new pair to the queue if the bbox distance is less - // than miniDist, The pair with biggest distance will be at - // the top - if (tempDist < miniDist) + [&distQueue, &miniDist, &ruler, &line, &polyBBox](const std::optional& rangeA) { + if (!rangeA) { + return; + } + const auto tempDist = bboxToBBoxDistance(getBBox(line, *rangeA), polyBBox, ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { distQueue.push(std::make_tuple(tempDist, std::move(*rangeA), IndexRange(0, 0))); + } }; updateQueue(newRangesA.first); updateQueue(newRangesA.second); @@ -402,38 +455,48 @@ double lineToPolygonDistance(const mapbox::geometry::line_string& line, double lineToLineDistance(const mapbox::geometry::line_string& line1, const mapbox::geometry::line_string& line2, - mapbox::cheap_ruler::CheapRuler& ruler, + const mapbox::cheap_ruler::CheapRuler& ruler, double currentMiniDist = InfiniteDistance) { auto miniDist = std::min(ruler.distance(line1[0], line2[0]), currentMiniDist); - if (miniDist == 0.0) return miniDist; + if (miniDist == 0.0) { + return miniDist; + } + DistQueue distQueue; distQueue.push(std::forward_as_tuple(0, IndexRange(0, line1.size() - 1), IndexRange(0, line2.size() - 1))); while (!distQueue.empty()) { - auto distPair = distQueue.top(); + const auto distPair = distQueue.top(); distQueue.pop(); - if (std::get<0>(distPair) >= miniDist) continue; - auto& rangeA = std::get<1>(distPair); - auto& rangeB = std::get<2>(distPair); + if (std::get<0>(distPair) >= miniDist) { + continue; + } + + const auto& rangeA = std::get<1>(distPair); + const auto& rangeB = std::get<2>(distPair); // In case the set size are relatively small, we could use brute-force directly if (getRangeSize(rangeA) <= MinLinePointsSize && getRangeSize(rangeB) <= MinLinePointsSize) { - auto tempDist = lineToLineDistance(line1, rangeA, line2, rangeB, ruler); - if (std::isnan(tempDist)) return tempDist; + const auto tempDist = lineToLineDistance(line1, rangeA, line2, rangeB, ruler); + if (std::isnan(tempDist) || tempDist == 0.0) { + return tempDist; + } miniDist = std::min(miniDist, tempDist); - if (miniDist == 0.0) return 0.0; } else { - auto newRangesA = splitRange(rangeA, true /*isLine*/); - auto newRangesB = splitRange(rangeB, true /*isLine*/); + const auto newRangesA = splitRange(rangeA, true /*isLine*/); + const auto newRangesB = splitRange(rangeB, true /*isLine*/); const auto updateQueue = [&distQueue, &miniDist, &ruler, &line1, &line2]( - std::optional& range1, std::optional& range2) { - if (!range1 || !range2) return; - auto tempDist = bboxToBBoxDistance(getBBox(line1, *range1), getBBox(line2, *range2), ruler); - // Insert new pair to the queue if the bbox distance is less - // than miniDist, The pair with biggest distance will be at - // the top - if (tempDist < miniDist) + const std::optional& range1, + const std::optional& range2) { + if (!range1 || !range2) { + return; + } + const auto tempDist = bboxToBBoxDistance(getBBox(line1, *range1), getBBox(line2, *range2), ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { distQueue.push(std::make_tuple(tempDist, std::move(*range1), std::move(*range2))); + } }; updateQueue(newRangesA.first, newRangesB.first); updateQueue(newRangesA.first, newRangesB.second); @@ -446,39 +509,48 @@ double lineToLineDistance(const mapbox::geometry::line_string& line1, double pointsToPointsDistance(const mapbox::geometry::multi_point& pointSet1, const mapbox::geometry::multi_point& pointSet2, - mapbox::cheap_ruler::CheapRuler& ruler) { + const mapbox::cheap_ruler::CheapRuler& ruler) { auto miniDist = ruler.distance(pointSet1[0], pointSet2[0]); - if (miniDist == 0.0) return miniDist; + if (miniDist == 0.0) { + return miniDist; + } + DistQueue distQueue; distQueue.push(std::forward_as_tuple(0, IndexRange(0, pointSet1.size() - 1), IndexRange(0, pointSet2.size() - 1))); while (!distQueue.empty()) { - auto distPair = distQueue.top(); + const auto distPair = distQueue.top(); distQueue.pop(); if (std::get<0>(distPair) >= miniDist) { continue; } - auto& rangeA = std::get<1>(distPair); - auto& rangeB = std::get<2>(distPair); + + const auto& rangeA = std::get<1>(distPair); + const auto& rangeB = std::get<2>(distPair); // In case the set size are relatively small, we could use brute-force directly if (getRangeSize(rangeA) <= MinPointsSize && getRangeSize(rangeB) <= MinPointsSize) { - auto tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); - if (std::isnan(tempDist)) return tempDist; + const auto tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler); + if (std::isnan(tempDist) || tempDist == 0.0) { + return tempDist; + } miniDist = std::min(miniDist, tempDist); - if (miniDist == 0.0) return 0.0; } else { - auto newRangesA = splitRange(rangeA, false /*isLine*/); - auto newRangesB = splitRange(rangeB, false /*isLine*/); + const auto newRangesA = splitRange(rangeA, false /*isLine*/); + const auto newRangesB = splitRange(rangeB, false /*isLine*/); const auto updateQueue = [&distQueue, &miniDist, &ruler, &pointSet1, &pointSet2]( - std::optional& range1, std::optional& range2) { - if (!range1 || !range2) return; - auto tempDist = bboxToBBoxDistance(getBBox(pointSet1, *range1), getBBox(pointSet2, *range2), ruler); - // Insert new pair to the queue if the bbox distance is less - // than miniDist, The pair with biggest distance will be at - // the top - if (tempDist < miniDist) + const std::optional& range1, + const std::optional& range2) { + if (!range1 || !range2) { + return; + } + const auto tempDist = bboxToBBoxDistance( + getBBox(pointSet1, *range1), getBBox(pointSet2, *range2), ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { distQueue.push(std::make_tuple(tempDist, std::move(*range1), std::move(*range2))); + } }; updateQueue(newRangesA.first, newRangesB.first); updateQueue(newRangesA.first, newRangesB.second); @@ -491,45 +563,55 @@ double pointsToPointsDistance(const mapbox::geometry::multi_point& point double pointsToLineDistance(const mapbox::geometry::multi_point& points, const mapbox::geometry::line_string& line, - mapbox::cheap_ruler::CheapRuler& ruler, + const mapbox::cheap_ruler::CheapRuler& ruler, double currentMiniDist = InfiniteDistance) { auto miniDist = std::min(currentMiniDist, ruler.distance(points[0], line[0])); - if (miniDist == 0.0) return miniDist; + if (miniDist == 0.0) { + return miniDist; + } + DistQueue distQueue; distQueue.push(std::forward_as_tuple(0, IndexRange(0, points.size() - 1), IndexRange(0, line.size() - 1))); while (!distQueue.empty()) { - auto distPair = distQueue.top(); + const auto distPair = distQueue.top(); distQueue.pop(); - if (std::get<0>(distPair) >= miniDist) continue; - auto& rangeA = std::get<1>(distPair); - auto& rangeB = std::get<2>(distPair); + if (std::get<0>(distPair) >= miniDist) { + continue; + } + + const auto& rangeA = std::get<1>(distPair); + const auto& rangeB = std::get<2>(distPair); // In case the set size are relatively small, we could use brute-force directly if (getRangeSize(rangeA) <= MinPointsSize && getRangeSize(rangeB) <= MinLinePointsSize) { - bool rangeSafe = isRangeSafe(rangeA, points.size()) && isRangeSafe(rangeB, line.size()); - if (!rangeSafe) { + if (!isRangeSafe(rangeA, points.size()) && isRangeSafe(rangeB, line.size())) { mbgl::Log::Error(mbgl::Event::Style, "Index is out of range"); return InvalidDistance; } - auto subLine = mapbox::geometry::multi_point(line.begin() + rangeB.first, - line.begin() + rangeB.second + 1); + const auto subLine = mapbox::geometry::multi_point(line.begin() + rangeB.first, + line.begin() + rangeB.second + 1); for (std::size_t i = rangeA.first; i <= rangeA.second; ++i) { miniDist = std::min(miniDist, pointToLineDistance(points[i], subLine, ruler)); - if (miniDist == 0.0) return 0.0; + if (miniDist == 0.0) { + return 0.0; + } } } else { - auto newRangesA = splitRange(rangeA, false /*isLine*/); - auto newRangesB = splitRange(rangeB, true /*isLine*/); + const auto newRangesA = splitRange(rangeA, false /*isLine*/); + const auto newRangesB = splitRange(rangeB, true /*isLine*/); const auto updateQueue = [&distQueue, &miniDist, &ruler, &points, &line]( - std::optional& range1, std::optional& range2) { - if (!range1 || !range2) return; - auto tempDist = bboxToBBoxDistance(getBBox(points, *range1), getBBox(line, *range2), ruler); - // Insert new pair to the queue if the bbox distance is less - // than miniDist, The pair with biggest distance will be at - // the top - if (tempDist < miniDist) + const std::optional& range1, + const std::optional& range2) { + if (!range1 || !range2) { + return; + } + const auto tempDist = bboxToBBoxDistance(getBBox(points, *range1), getBBox(line, *range2), ruler); + // Insert new pair to the queue if the bbox distance is less than + // miniDist, The pair with biggest distance will be at the top + if (tempDist < miniDist) { distQueue.push(std::make_tuple(tempDist, std::move(*range1), std::move(*range2))); + } }; updateQueue(newRangesA.first, newRangesB.first); updateQueue(newRangesA.first, newRangesB.second); @@ -542,29 +624,35 @@ double pointsToLineDistance(const mapbox::geometry::multi_point& points, double pointsToLinesDistance(const mapbox::geometry::multi_point& points, const mapbox::geometry::multi_line_string& lines, - mapbox::cheap_ruler::CheapRuler& ruler) { + const mapbox::cheap_ruler::CheapRuler& ruler) { double dist = InfiniteDistance; for (const auto& line : lines) { dist = std::min(dist, pointsToLineDistance(points, line, ruler, dist)); - if (dist == 0.0) return dist; + if (dist == 0.0) { + return dist; + } } return dist; } double lineToLinesDistance(const mapbox::geometry::line_string& line, const mapbox::geometry::multi_line_string& lines, - mapbox::cheap_ruler::CheapRuler& ruler) { + const mapbox::cheap_ruler::CheapRuler& ruler) { double dist = InfiniteDistance; for (const auto& l : lines) { dist = std::min(dist, lineToLineDistance(line, l, ruler, dist)); - if (dist == 0.0) return dist; + if (dist == 0.0) { + return dist; + } } return dist; } double pointsToGeometryDistance(const mapbox::geometry::multi_point& points, const Feature::geometry_type& geoSet) { - if (!isMultiPointValid(points)) return InvalidDistance; + if (!isMultiPointValid(points)) { + return InvalidDistance; + } mapbox::cheap_ruler::CheapRuler ruler(points.front().y, UnitInMeters); return geoSet.match( [&points, &ruler](const mapbox::geometry::point& p) { @@ -603,7 +691,9 @@ double pointsToGeometryDistance(const mapbox::geometry::multi_point& poi } double lineToGeometryDistance(const mapbox::geometry::line_string& line, const Feature::geometry_type& geoSet) { - if (!isLineStringValid(line)) return InvalidDistance; + if (!isLineStringValid(line)) { + return InvalidDistance; + } mapbox::cheap_ruler::CheapRuler ruler(line.front().y, UnitInMeters); return geoSet.match( [&line, &ruler](const mapbox::geometry::point& p) { @@ -643,43 +733,48 @@ double lineToGeometryDistance(const mapbox::geometry::line_string& line, double polygonToGeometryDistance(const mapbox::geometry::polygon& polygon, const Feature::geometry_type& geoSet) { - if (!isPolygonValid(polygon)) return InvalidDistance; + if (!isPolygonValid(polygon)) { + return InvalidDistance; + } mapbox::cheap_ruler::CheapRuler ruler(polygon.front().front().y, UnitInMeters); return geoSet.match( [&polygon, &ruler](const mapbox::geometry::point& p) { return pointToPolygonDistance(p, polygon, ruler); }, [&polygon, &ruler](const mapbox::geometry::multi_point& points) { - if (!isMultiPointValid(points)) return InvalidDistance; - return pointsToPolygonDistance(points, polygon, ruler); + return isMultiPointValid(points) ? pointsToPolygonDistance(points, polygon, ruler) : InvalidDistance; }, [&polygon, &ruler](const mapbox::geometry::line_string& line) { - if (!isLineStringValid(line)) return InvalidDistance; - return lineToPolygonDistance(line, polygon, ruler); + return isLineStringValid(line) ? lineToPolygonDistance(line, polygon, ruler) : InvalidDistance; }, [&polygon, &ruler](const mapbox::geometry::multi_line_string& lines) { double dist = InfiniteDistance; for (const auto& line : lines) { - if (!isLineStringValid(line)) return InvalidDistance; - auto tempDist = lineToPolygonDistance(line, polygon, ruler, dist); - if (std::isnan(tempDist)) return tempDist; + if (!isLineStringValid(line)) { + return InvalidDistance; + } + const auto tempDist = lineToPolygonDistance(line, polygon, ruler, dist); + if (std::isnan(tempDist) || tempDist == 0.0) { + return tempDist; + } dist = std::min(dist, tempDist); - if (dist == 0.0) return dist; } return dist; }, [&polygon, &ruler](const mapbox::geometry::polygon& polygon1) { - if (!isPolygonValid(polygon1)) return InvalidDistance; - return polygonToPolygonDistance(polygon, polygon1, ruler); + return isPolygonValid(polygon1) ? polygonToPolygonDistance(polygon, polygon1, ruler) : InvalidDistance; }, [&polygon, &ruler](const mapbox::geometry::multi_polygon& polygons) { double dist = InfiniteDistance; for (const auto& polygon1 : polygons) { - if (!isPolygonValid(polygon1)) return InvalidDistance; - auto tempDist = polygonToPolygonDistance(polygon, polygon1, ruler, dist); - if (std::isnan(tempDist)) return tempDist; + if (!isPolygonValid(polygon1)) { + return InvalidDistance; + } + const auto tempDist = polygonToPolygonDistance(polygon, polygon1, ruler, dist); + if (std::isnan(tempDist) || tempDist == 0.0) { + return tempDist; + } dist = std::min(dist, tempDist); - if (dist == 0.0) return dist; } return dist; }, @@ -703,10 +798,11 @@ double calculateDistance(const GeometryTileFeature& feature, [&geoSet](const mapbox::geometry::multi_line_string& lines) -> double { double dist = InfiniteDistance; for (const auto& line : lines) { - auto tempDist = lineToGeometryDistance(line, geoSet); - if (std::isnan(tempDist)) return tempDist; + const auto tempDist = lineToGeometryDistance(line, geoSet); + if (std::isnan(tempDist) || tempDist == 0.0) { + return tempDist; + } dist = std::min(dist, tempDist); - if (dist == 0.0) return dist; } return dist; }, @@ -716,20 +812,21 @@ double calculateDistance(const GeometryTileFeature& feature, [&geoSet](const mapbox::geometry::multi_polygon& polygons) -> double { double dist = InfiniteDistance; for (const auto& polygon : polygons) { - auto tempDist = polygonToGeometryDistance(polygon, geoSet); - if (std::isnan(tempDist)) return tempDist; + const auto tempDist = polygonToGeometryDistance(polygon, geoSet); + if (std::isnan(tempDist) || tempDist == 0.0) { + return tempDist; + } dist = std::min(dist, tempDist); - if (dist == 0.0) return dist; } return dist; }, - [](const auto&) -> double { return InvalidDistance; }); + [](const auto&) { return InvalidDistance; }); } std::optional parseValue(const style::conversion::Convertible& value, style::expression::ParsingContext& ctx) { if (isArray(value)) { // object value, quoted with ["distance", GeoJSONObj] - auto length = arrayLength(value); + const auto length = arrayLength(value); if (length != 2) { ctx.error("'distance' expression requires one argument, but found " + util::toString(arrayLength(value) - 1) + " instead."); @@ -799,7 +896,7 @@ EvaluationResult Distance::evaluate(const EvaluationContext& params) const { } ParseResult Distance::parse(const Convertible& value, ParsingContext& ctx) { - auto parsedValue = parseValue(value, ctx); + const auto parsedValue = parseValue(value, ctx); if (!parsedValue) { return ParseResult(); } @@ -882,7 +979,7 @@ mbgl::Value Distance::serialize() const { return std::vector{{getOperator(), serialized}}; } -bool Distance::operator==(const Expression& e) const { +bool Distance::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Distance) { auto rhs = static_cast(&e); return geoJSONSource == rhs->geoJSONSource && geometries == rhs->geometries; @@ -890,14 +987,6 @@ bool Distance::operator==(const Expression& e) const { return false; } -std::vector> Distance::possibleOutputs() const { - return {std::nullopt}; -} - -std::string Distance::getOperator() const { - return "distance"; -} - } // namespace expression } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/expression/dsl.cpp b/src/mbgl/style/expression/dsl.cpp index f9215c1c8..26657949e 100644 --- a/src/mbgl/style/expression/dsl.cpp +++ b/src/mbgl/style/expression/dsl.cpp @@ -58,12 +58,17 @@ std::unique_ptr literal(const Value& value) { return std::make_unique(value); } +std::unique_ptr literal(Value&& value) { + return std::make_unique(std::move(value)); +} + std::unique_ptr literal(std::initializer_list value) { std::vector values; + values.reserve(value.size()); for (auto i : value) { values.emplace_back(i); } - return literal(values); + return literal(std::move(values)); } std::unique_ptr literal(std::initializer_list value) { @@ -74,14 +79,14 @@ std::unique_ptr literal(std::initializer_list value) { return literal(values); } -std::unique_ptr assertion(const type::Type& type, +std::unique_ptr assertion(type::Type type, std::unique_ptr value, std::unique_ptr def) { std::vector> v = vec(std::move(value)); if (def) { v.push_back(std::move(def)); } - return std::make_unique(type, std::move(v)); + return std::make_unique(std::move(type), std::move(v)); } std::unique_ptr number(std::unique_ptr value, std::unique_ptr def) { @@ -96,15 +101,17 @@ std::unique_ptr boolean(std::unique_ptr value, std::uniq return assertion(type::Boolean, std::move(value), std::move(def)); } -std::unique_ptr coercion(const type::Type& type, +namespace { +std::unique_ptr coercion(type::Type type, std::unique_ptr value, std::unique_ptr def) { std::vector> v = vec(std::move(value)); if (def) { v.push_back(std::move(def)); } - return std::make_unique(type, std::move(v)); + return std::make_unique(std::move(type), std::move(v)); } +} // namespace std::unique_ptr toColor(std::unique_ptr value, std::unique_ptr def) { return coercion(type::Color, std::move(value), std::move(def)); @@ -162,18 +169,18 @@ std::unique_ptr step(std::unique_ptr input, std::map> stops; stops[-std::numeric_limits::infinity()] = std::move(output0); stops[input1] = std::move(output1); - return std::make_unique(type, std::move(input), std::move(stops)); + return std::make_unique(std::move(type), std::move(input), std::move(stops)); } -Interpolator linear() { +Interpolator linear() noexcept { return ExponentialInterpolator(1.0); } -Interpolator exponential(double base) { +Interpolator exponential(double base) noexcept { return ExponentialInterpolator(base); } -Interpolator cubicBezier(double x1, double y1, double x2, double y2) { +Interpolator cubicBezier(double x1, double y1, double x2, double y2) noexcept { return CubicBezierInterpolator(x1, y1, x2, y2); } diff --git a/src/mbgl/style/expression/format_expression.cpp b/src/mbgl/style/expression/format_expression.cpp index f166508b0..c3058ea10 100644 --- a/src/mbgl/style/expression/format_expression.cpp +++ b/src/mbgl/style/expression/format_expression.cpp @@ -110,9 +110,9 @@ void FormatExpression::eachChild(const std::function& f } } -bool FormatExpression::operator==(const Expression& e) const { +bool FormatExpression::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::FormatExpression) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); if (sections.size() != rhs->sections.size()) { return false; } diff --git a/src/mbgl/style/expression/get_covering_stops.cpp b/src/mbgl/style/expression/get_covering_stops.cpp index 1f4b08408..bf3840cb8 100644 --- a/src/mbgl/style/expression/get_covering_stops.cpp +++ b/src/mbgl/style/expression/get_covering_stops.cpp @@ -1,15 +1,21 @@ #include +#include + namespace mbgl { namespace style { namespace expression { Range getCoveringStops(const std::map>& stops, const double lower, - const double upper) { + const double upper) noexcept { assert(!stops.empty()); + if (stops.empty()) { + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + auto minIt = stops.lower_bound(lower); - auto maxIt = stops.lower_bound(upper); + const auto maxIt = stops.lower_bound(upper); // lower_bound yields first element >= lowerZoom, but we want the *last* // element <= lowerZoom, so if we found a stop > lowerZoom, back up by one. diff --git a/src/mbgl/style/expression/image_expression.cpp b/src/mbgl/style/expression/image_expression.cpp index 7c4776ebf..d304616f5 100644 --- a/src/mbgl/style/expression/image_expression.cpp +++ b/src/mbgl/style/expression/image_expression.cpp @@ -35,9 +35,9 @@ void ImageExpression::eachChild(const std::function& fn fn(*imageID); } -bool ImageExpression::operator==(const Expression& e) const { +bool ImageExpression::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::ImageExpression) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return *imageID == *rhs->imageID; } return false; diff --git a/src/mbgl/style/expression/in.cpp b/src/mbgl/style/expression/in.cpp index 5f0f632aa..cb57e4b64 100644 --- a/src/mbgl/style/expression/in.cpp +++ b/src/mbgl/style/expression/in.cpp @@ -10,20 +10,20 @@ namespace style { namespace expression { namespace { -bool isComparableType(const type::Type& type) { +bool isComparableType(const type::Type& type) noexcept { return type == type::Boolean || type == type::String || type == type::Number || type == type::Null || type == type::Value; } -bool isComparableRuntimeType(const type::Type& type) { +bool isComparableRuntimeType(const type::Type& type) noexcept { return type == type::Boolean || type == type::String || type == type::Number || type == type::Null; } -bool isSearchableType(const type::Type& type) { +bool isSearchableType(const type::Type& type) noexcept { return type == type::String || type.is() || type == type::Null || type == type::Value; } -bool isSearchableRuntimeType(const type::Type& type) { +bool isSearchableRuntimeType(const type::Type& type) noexcept { return type == type::String || type.is() || type == type::Null; } } // namespace @@ -87,7 +87,7 @@ using namespace mbgl::style::conversion; ParseResult In::parse(const Convertible& value, ParsingContext& ctx) { assert(isArray(value)); - std::size_t length = arrayLength(value); + const std::size_t length = arrayLength(value); if (length != 3) { ctx.error("Expected 2 arguments, but found " + util::toString(length - 1) + " instead."); return ParseResult(); @@ -99,8 +99,8 @@ ParseResult In::parse(const Convertible& value, ParsingContext& ctx) { ParseResult haystack = ctx.parse(arrayMember(value, 2), 2, {type::Value}); if (!haystack) return ParseResult(); - type::Type needleType = (*needle)->getType(); - type::Type haystackType = (*haystack)->getType(); + const type::Type needleType = (*needle)->getType(); + const type::Type haystackType = (*haystack)->getType(); if (!isComparableType(needleType)) { ctx.error( @@ -120,7 +120,7 @@ ParseResult In::parse(const Convertible& value, ParsingContext& ctx) { return ParseResult(std::make_unique(std::move(*needle), std::move(*haystack))); } -bool In::operator==(const Expression& e) const { +bool In::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::In) { auto rhs = static_cast(&e); return *needle == *(rhs->needle) && *haystack == *(rhs->haystack); @@ -132,10 +132,6 @@ std::vector> In::possibleOutputs() const { return {{true}, {false}}; } -std::string In::getOperator() const { - return "in"; -} - } // namespace expression } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/expression/index_of.cpp b/src/mbgl/style/expression/index_of.cpp index 93924d20d..e1e0e4543 100644 --- a/src/mbgl/style/expression/index_of.cpp +++ b/src/mbgl/style/expression/index_of.cpp @@ -115,7 +115,7 @@ ParseResult IndexOf::parse(const Convertible &value, ParsingContext &ctx) { std::make_unique(std::move(*keyword), std::move(*input), fromIndex ? std::move(*fromIndex) : nullptr)); } -bool IndexOf::operator==(const Expression &e) const { +bool IndexOf::operator==(const Expression &e) const noexcept { if (e.getKind() == Kind::IndexOf) { auto rhs = static_cast(&e); const auto fromIndexEqual = (fromIndex && rhs->fromIndex && *fromIndex == *(rhs->fromIndex)) || @@ -129,10 +129,6 @@ std::vector> IndexOf::possibleOutputs() const { return {std::nullopt}; } -std::string IndexOf::getOperator() const { - return "index-of"; -} - } // namespace expression } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/expression/is_constant.cpp b/src/mbgl/style/expression/is_constant.cpp index 1c946230c..574a08a74 100644 --- a/src/mbgl/style/expression/is_constant.cpp +++ b/src/mbgl/style/expression/is_constant.cpp @@ -52,8 +52,11 @@ bool isFeatureConstant(const Expression& expression) { return featureConstant; } +namespace { +const auto zoomProperty = std::array{"zoom"}; +} bool isZoomConstant(const Expression& e) { - return isGlobalPropertyConstant(e, std::array{{"zoom"}}); + return isGlobalPropertyConstant(e, zoomProperty); } bool isRuntimeConstant(const Expression& expression) { diff --git a/src/mbgl/style/expression/length.cpp b/src/mbgl/style/expression/length.cpp index 1f73d4f48..41815b978 100644 --- a/src/mbgl/style/expression/length.cpp +++ b/src/mbgl/style/expression/length.cpp @@ -25,7 +25,7 @@ void Length::eachChild(const std::function& visit) cons visit(*input); } -bool Length::operator==(const Expression& e) const { +bool Length::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Length) { auto eq = static_cast(&e); return *eq->input == *input; diff --git a/src/mbgl/style/expression/let.cpp b/src/mbgl/style/expression/let.cpp index 254c5dcf7..e2db0dd8c 100644 --- a/src/mbgl/style/expression/let.cpp +++ b/src/mbgl/style/expression/let.cpp @@ -107,7 +107,7 @@ ParseResult Var::parse(const Convertible& value_, ParsingContext& ctx) { return ParseResult(); } - return ParseResult(std::make_unique(name_, std::move(*bindingValue))); + return ParseResult(std::make_unique(std::move(name_), std::move(*bindingValue))); } mbgl::Value Var::serialize() const { diff --git a/src/mbgl/style/expression/literal.cpp b/src/mbgl/style/expression/literal.cpp index f980acf9f..6760e5528 100644 --- a/src/mbgl/style/expression/literal.cpp +++ b/src/mbgl/style/expression/literal.cpp @@ -75,7 +75,7 @@ ParseResult Literal::parse(const Convertible& value, ParsingContext& ctx) { util::toString(arrayLength(value) - 1) + " instead."); return ParseResult(); } - const std::optional parsedValue = parseValue(arrayMember(value, 1), ctx); + std::optional parsedValue = parseValue(arrayMember(value, 1), ctx); if (!parsedValue) { return ParseResult(); } @@ -87,15 +87,15 @@ ParseResult Literal::parse(const Convertible& value, ParsingContext& ctx) { auto expected = ctx.getExpected()->template get(); if (type.N && (*type.N == 0) && (!expected.N || (*expected.N == 0))) { return ParseResult( - std::make_unique(expected, parsedValue->template get>())); + std::make_unique(std::move(expected), parsedValue->template get>())); } } - return ParseResult(std::make_unique(*parsedValue)); + return ParseResult(std::make_unique(std::move(*parsedValue))); } else { // bare primitive value (string, number, boolean, null) const std::optional parsedValue = parseValue(value, ctx); - return ParseResult(std::make_unique(*parsedValue)); + return ParseResult(std::make_unique(std::move(*parsedValue))); } } diff --git a/src/mbgl/style/expression/match.cpp b/src/mbgl/style/expression/match.cpp index 949ad881e..ac497257a 100644 --- a/src/mbgl/style/expression/match.cpp +++ b/src/mbgl/style/expression/match.cpp @@ -18,9 +18,9 @@ void Match::eachChild(const std::function& visit) co } template -bool Match::operator==(const Expression& e) const { +bool Match::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Match) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return (*input == *(rhs->input) && *otherwise == *(rhs->otherwise) && Expression::childrenEqual(branches, rhs->branches)); } @@ -220,8 +220,8 @@ static ParseResult create(type::Type outputType, index += 2; } - return ParseResult( - std::make_unique>(outputType, std::move(input), std::move(typedBranches), std::move(otherwise))); + return ParseResult(std::make_unique>( + std::move(outputType), std::move(input), std::move(typedBranches), std::move(otherwise))); } ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { @@ -309,10 +309,12 @@ ParseResult parseMatch(const Convertible& value, ParsingContext& ctx) { return inputType->match( [&](const type::NumberType&) { - return create(*outputType, std::move(*input), std::move(branches), std::move(*otherwise), ctx); + return create( + std::move(*outputType), std::move(*input), std::move(branches), std::move(*otherwise), ctx); }, [&](const type::StringType&) { - return create(*outputType, std::move(*input), std::move(branches), std::move(*otherwise), ctx); + return create( + std::move(*outputType), std::move(*input), std::move(branches), std::move(*otherwise), ctx); }, [&](const auto&) { // unreachable: inputType is set by parseInputValue(), which only diff --git a/src/mbgl/style/expression/number_format.cpp b/src/mbgl/style/expression/number_format.cpp index 2e1339b91..3f699cda8 100644 --- a/src/mbgl/style/expression/number_format.cpp +++ b/src/mbgl/style/expression/number_format.cpp @@ -85,7 +85,7 @@ void NumberFormat::eachChild(const std::function& visit if (maxFractionDigits) visit(*maxFractionDigits); } -bool NumberFormat::operator==(const Expression& e) const { +bool NumberFormat::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::NumberFormat) { auto rhs = static_cast(&e); if ((locale && (!rhs->locale || *locale != *rhs->locale)) || (!locale && rhs->locale)) { diff --git a/src/mbgl/style/expression/parsing_context.cpp b/src/mbgl/style/expression/parsing_context.cpp index bf24d115a..5f37c1456 100644 --- a/src/mbgl/style/expression/parsing_context.cpp +++ b/src/mbgl/style/expression/parsing_context.cpp @@ -43,20 +43,23 @@ namespace mbgl { namespace style { namespace expression { -bool isConstant(const Expression& expression) { - if (expression.getKind() == Kind::Var) { - auto varExpression = static_cast(&expression); - return isConstant(*varExpression->getBoundExpression()); - } +namespace { +const auto requiredProps = std::array{"zoom", "heatmap-density", "line-progress", "accumulated"}; - if (expression.getKind() == Kind::CompoundExpression) { - auto compound = static_cast(&expression); +bool isConstant(const Expression& expression) { + const auto kind = expression.getKind(); + + if (kind == Kind::Var) { + const auto* varExpression = static_cast(&expression); + return isConstant(*varExpression->getBoundExpression()); + } else if (kind == Kind::CompoundExpression) { + const auto* compound = static_cast(&expression); if (compound->getOperator() == "error") { return false; } } - bool isTypeAnnotation = expression.getKind() == Kind::Coercion || expression.getKind() == Kind::Assertion; + const bool isTypeAnnotation = kind == Kind::Coercion || kind == Kind::Assertion; bool childrenConstant = true; expression.eachChild([&](const Expression& child) { @@ -73,15 +76,10 @@ bool isConstant(const Expression& expression) { childrenConstant = childrenConstant && child.getKind() == Kind::Literal; } }); - if (!childrenConstant) { - return false; - } - return isFeatureConstant(expression) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "heatmap-density"}}) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "line-progress"}}) && - isGlobalPropertyConstant(expression, std::array{{"zoom", "accumulated"}}); + return childrenConstant && isFeatureConstant(expression) && isGlobalPropertyConstant(expression, requiredProps); } +} // namespace using namespace mbgl::style::conversion; @@ -143,7 +141,7 @@ MAPBOX_ETERNAL_CONSTEXPR const auto expressionRegistry = {"index-of", IndexOf::parse}, {"slice", Slice::parse}}); -bool isExpression(const std::string& name) { +bool isExpression(const std::string& name) noexcept { return expressionRegistry.contains(name.c_str()); } @@ -182,14 +180,14 @@ ParseResult ParsingContext::parse(const Convertible& value, return parsed; } - auto annotate = [](std::unique_ptr expression, - const type::Type& type, - TypeAnnotationOption typeAnnotation) -> std::unique_ptr { + const auto annotate = [](std::unique_ptr expression, + type::Type type, + TypeAnnotationOption typeAnnotation) -> std::unique_ptr { switch (typeAnnotation) { case TypeAnnotationOption::assert: - return std::make_unique(type, dsl::vec(std::move(expression))); + return std::make_unique(std::move(type), dsl::vec(std::move(expression))); case TypeAnnotationOption::coerce: - return std::make_unique(type, dsl::vec(std::move(expression))); + return std::make_unique(std::move(type), dsl::vec(std::move(expression))); case TypeAnnotationOption::omit: return expression; } @@ -204,12 +202,12 @@ ParseResult ParsingContext::parse(const Convertible& value, if ((*expected == type::String || *expected == type::Number || *expected == type::Boolean || *expected == type::Object || expected->is()) && actual == type::Value) { - parsed = { - annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::assert))}; + parsed = {annotate( + std::move(*parsed), std::move(*expected), typeAnnotationOption.value_or(TypeAnnotationOption::assert))}; } else if ((*expected == type::Color || *expected == type::Formatted || *expected == type::Image) && (actual == type::Value || actual == type::String)) { - parsed = { - annotate(std::move(*parsed), *expected, typeAnnotationOption.value_or(TypeAnnotationOption::coerce))}; + parsed = {annotate( + std::move(*parsed), std::move(*expected), typeAnnotationOption.value_or(TypeAnnotationOption::coerce))}; } else { checkType((*parsed)->getType()); if (!errors->empty()) { @@ -237,7 +235,7 @@ ParseResult ParsingContext::parse(const Convertible& value, return ParseResult( std::make_unique(type.get(), evaluated->get>())); } else { - return ParseResult(std::make_unique(*evaluated)); + return ParseResult(std::make_unique(std::move(*evaluated))); } } diff --git a/src/mbgl/style/expression/slice.cpp b/src/mbgl/style/expression/slice.cpp index 4919ad185..90bed4eaf 100644 --- a/src/mbgl/style/expression/slice.cpp +++ b/src/mbgl/style/expression/slice.cpp @@ -10,7 +10,7 @@ namespace expression { namespace { -int normalizeIndex(int index, int length) { +int normalizeIndex(int index, int length) noexcept { if (index < 0) { index += length; } @@ -133,7 +133,7 @@ ParseResult Slice::parse(const Convertible &value, ParsingContext &ctx) { std::make_unique(std::move(*input), std::move(*fromIndex), toIndex ? std::move(*toIndex) : nullptr)); } -bool Slice::operator==(const Expression &e) const { +bool Slice::operator==(const Expression &e) const noexcept { if (e.getKind() == Kind::Slice) { auto rhs = static_cast(&e); const auto toIndexEqual = (toIndex && rhs->toIndex && *toIndex == *(rhs->toIndex)) || @@ -147,10 +147,6 @@ std::vector> Slice::possibleOutputs() const { return {std::nullopt}; } -std::string Slice::getOperator() const { - return "slice"; -} - } // namespace expression } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/expression/step.cpp b/src/mbgl/style/expression/step.cpp index 940b8cfd8..646f6c84a 100644 --- a/src/mbgl/style/expression/step.cpp +++ b/src/mbgl/style/expression/step.cpp @@ -9,10 +9,8 @@ namespace mbgl { namespace style { namespace expression { -Step::Step(const type::Type& type_, - std::unique_ptr input_, - std::map> stops_) - : Expression(Kind::Step, type_, depsOf(input_) | collectDependencies(stops_)), +Step::Step(type::Type type_, std::unique_ptr input_, std::map> stops_) + : Expression(Kind::Step, std::move(type_), depsOf(input_) | collectDependencies(stops_)), input(std::move(input_)), stops(std::move(stops_)) { assert(input->getType() == type::Number); @@ -56,7 +54,7 @@ void Step::eachStop(const std::function& visit) } } -bool Step::operator==(const Expression& e) const { +bool Step::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Step) { auto rhs = static_cast(&e); return *input == *(rhs->input) && Expression::childrenEqual(stops, rhs->stops); @@ -74,7 +72,7 @@ std::vector> Step::possibleOutputs() const { return result; } -Range Step::getCoveringStops(const double lower, const double upper) const { +Range Step::getCoveringStops(const double lower, const double upper) const noexcept { return ::mbgl::style::expression::getCoveringStops(stops, lower, upper); } @@ -174,7 +172,7 @@ ParseResult Step::parse(const mbgl::style::conversion::Convertible& value, Parsi assert(outputType); - return ParseResult(std::make_unique(*outputType, std::move(*input), std::move(stops))); + return ParseResult(std::make_unique(std::move(*outputType), std::move(*input), std::move(stops))); } mbgl::Value Step::serialize() const { diff --git a/src/mbgl/style/expression/value.cpp b/src/mbgl/style/expression/value.cpp index a06923916..3bc06a432 100644 --- a/src/mbgl/style/expression/value.cpp +++ b/src/mbgl/style/expression/value.cpp @@ -108,12 +108,12 @@ struct FromMBGLValue { return result; } - Value operator()(const std::string& s) { return s; } - Value operator()(const bool b) { return b; } - Value operator()(const NullValue) { return Null; } - Value operator()(const double v) { return v; } - Value operator()(const uint64_t& v) { return static_cast(v); } - Value operator()(const int64_t& v) { return static_cast(v); } + Value operator()(const std::string& s) noexcept { return s; } + Value operator()(const bool b) noexcept { return b; } + Value operator()(const NullValue) noexcept { return Null; } + Value operator()(const double v) noexcept { return v; } + Value operator()(const uint64_t& v) noexcept { return static_cast(v); } + Value operator()(const int64_t& v) noexcept { return static_cast(v); } }; Value ValueConverter::toExpressionValue(const mbgl::Value& value) { diff --git a/src/mbgl/style/expression/within.cpp b/src/mbgl/style/expression/within.cpp index 429a2d8b3..f7576c839 100644 --- a/src/mbgl/style/expression/within.cpp +++ b/src/mbgl/style/expression/within.cpp @@ -16,13 +16,13 @@ namespace mbgl { namespace { -Point latLonToTileCoodinates(const Point& point, const mbgl::CanonicalTileID& canonical) { +Point latLonToTileCoodinates(const Point& point, const mbgl::CanonicalTileID& canonical) noexcept { const double size = util::EXTENT * std::pow(2, canonical.z); - auto x = (point.x + util::LONGITUDE_MAX) * size / util::DEGREES_MAX; - auto y = (util::LONGITUDE_MAX - - util::rad2deg(std::log(std::tan(point.y * M_PI / util::DEGREES_MAX + M_PI / 4.0)))) * - size / util::DEGREES_MAX; + const auto x = (point.x + util::LONGITUDE_MAX) * size / util::DEGREES_MAX; + const auto y = (util::LONGITUDE_MAX - + util::rad2deg(std::log(std::tan(point.y * M_PI / util::DEGREES_MAX + M_PI / 4.0)))) * + size / util::DEGREES_MAX; Point p; p.x = (util::clamp( @@ -72,7 +72,7 @@ MultiPolygon getTilePolygons(const Feature::geometry_type& polygonGeoSe [](const auto&) { return MultiPolygon(); }); } -void updatePoint(Point& p, WithinBBox& bbox, const WithinBBox& polyBBox, const int64_t worldSize) { +void updatePoint(Point& p, WithinBBox& bbox, const WithinBBox& polyBBox, const int64_t worldSize) noexcept { if (p.x < polyBBox[0] || p.x > polyBBox[2]) { const auto getShift = [](Point& point, const int64_t polygonSide, const int64_t size) -> int64_t { if (point.x - polygonSide > size / 2) { @@ -325,9 +325,9 @@ mbgl::Value Within::serialize() const { return std::vector{{getOperator(), serialized}}; } -bool Within::operator==(const Expression& e) const { +bool Within::operator==(const Expression& e) const noexcept { if (e.getKind() == Kind::Within) { - auto rhs = static_cast(&e); + const auto* rhs = static_cast(&e); return geoJSONSource == rhs->geoJSONSource && geometries == rhs->geometries; } return false; @@ -337,10 +337,6 @@ std::vector> Within::possibleOutputs() const { return {{true}, {false}}; } -std::string Within::getOperator() const { - return "within"; -} - } // namespace expression } // namespace style } // namespace mbgl diff --git a/src/mbgl/style/layers/background_layer_properties.cpp b/src/mbgl/style/layers/background_layer_properties.cpp index ec4b71f2a..567d9e98a 100644 --- a/src/mbgl/style/layers/background_layer_properties.cpp +++ b/src/mbgl/style/layers/background_layer_properties.cpp @@ -27,7 +27,7 @@ unsigned long BackgroundLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const BackgroundLayer::Impl& BackgroundLayerProperties::layerImpl() const { +const BackgroundLayer::Impl& BackgroundLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/background_layer_properties.hpp b/src/mbgl/style/layers/background_layer_properties.hpp index 9459d2241..63ce00bfa 100644 --- a/src/mbgl/style/layers/background_layer_properties.hpp +++ b/src/mbgl/style/layers/background_layer_properties.hpp @@ -47,7 +47,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const BackgroundLayer::Impl& layerImpl() const; + const BackgroundLayer::Impl& layerImpl() const noexcept; // Data members. CrossfadeParameters crossfade; BackgroundPaintProperties::PossiblyEvaluated evaluated; diff --git a/src/mbgl/style/layers/circle_layer_properties.cpp b/src/mbgl/style/layers/circle_layer_properties.cpp index dc1639850..26b844797 100644 --- a/src/mbgl/style/layers/circle_layer_properties.cpp +++ b/src/mbgl/style/layers/circle_layer_properties.cpp @@ -25,7 +25,7 @@ unsigned long CircleLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const CircleLayer::Impl& CircleLayerProperties::layerImpl() const { +const CircleLayer::Impl& CircleLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/circle_layer_properties.hpp b/src/mbgl/style/layers/circle_layer_properties.hpp index 565fbd265..37e6007b0 100644 --- a/src/mbgl/style/layers/circle_layer_properties.hpp +++ b/src/mbgl/style/layers/circle_layer_properties.hpp @@ -95,7 +95,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const CircleLayer::Impl& layerImpl() const; + const CircleLayer::Impl& layerImpl() const noexcept; // Data members. CirclePaintProperties::PossiblyEvaluated evaluated; }; diff --git a/src/mbgl/style/layers/fill_extrusion_layer_properties.cpp b/src/mbgl/style/layers/fill_extrusion_layer_properties.cpp index 2f306511b..6786deb7c 100644 --- a/src/mbgl/style/layers/fill_extrusion_layer_properties.cpp +++ b/src/mbgl/style/layers/fill_extrusion_layer_properties.cpp @@ -27,7 +27,7 @@ unsigned long FillExtrusionLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const FillExtrusionLayer::Impl& FillExtrusionLayerProperties::layerImpl() const { +const FillExtrusionLayer::Impl& FillExtrusionLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/fill_extrusion_layer_properties.hpp b/src/mbgl/style/layers/fill_extrusion_layer_properties.hpp index 4349bd14a..c7c466661 100644 --- a/src/mbgl/style/layers/fill_extrusion_layer_properties.hpp +++ b/src/mbgl/style/layers/fill_extrusion_layer_properties.hpp @@ -72,7 +72,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const FillExtrusionLayer::Impl& layerImpl() const; + const FillExtrusionLayer::Impl& layerImpl() const noexcept; // Data members. CrossfadeParameters crossfade; FillExtrusionPaintProperties::PossiblyEvaluated evaluated; diff --git a/src/mbgl/style/layers/fill_layer_properties.cpp b/src/mbgl/style/layers/fill_layer_properties.cpp index 96b8eca29..646c02d58 100644 --- a/src/mbgl/style/layers/fill_layer_properties.cpp +++ b/src/mbgl/style/layers/fill_layer_properties.cpp @@ -27,7 +27,7 @@ unsigned long FillLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const FillLayer::Impl& FillLayerProperties::layerImpl() const { +const FillLayer::Impl& FillLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/fill_layer_properties.hpp b/src/mbgl/style/layers/fill_layer_properties.hpp index 56cc1bef5..7073d909a 100644 --- a/src/mbgl/style/layers/fill_layer_properties.hpp +++ b/src/mbgl/style/layers/fill_layer_properties.hpp @@ -76,7 +76,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const FillLayer::Impl& layerImpl() const; + const FillLayer::Impl& layerImpl() const noexcept; // Data members. CrossfadeParameters crossfade; FillPaintProperties::PossiblyEvaluated evaluated; diff --git a/src/mbgl/style/layers/heatmap_layer_properties.cpp b/src/mbgl/style/layers/heatmap_layer_properties.cpp index 5d92433d6..15b8789e0 100644 --- a/src/mbgl/style/layers/heatmap_layer_properties.cpp +++ b/src/mbgl/style/layers/heatmap_layer_properties.cpp @@ -25,7 +25,7 @@ unsigned long HeatmapLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const HeatmapLayer::Impl& HeatmapLayerProperties::layerImpl() const { +const HeatmapLayer::Impl& HeatmapLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/heatmap_layer_properties.hpp b/src/mbgl/style/layers/heatmap_layer_properties.hpp index c1c351447..5997f5b7c 100644 --- a/src/mbgl/style/layers/heatmap_layer_properties.hpp +++ b/src/mbgl/style/layers/heatmap_layer_properties.hpp @@ -55,7 +55,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const HeatmapLayer::Impl& layerImpl() const; + const HeatmapLayer::Impl& layerImpl() const noexcept; // Data members. HeatmapPaintProperties::PossiblyEvaluated evaluated; }; diff --git a/src/mbgl/style/layers/hillshade_layer_properties.cpp b/src/mbgl/style/layers/hillshade_layer_properties.cpp index 7d7c30e38..3e01303ac 100644 --- a/src/mbgl/style/layers/hillshade_layer_properties.cpp +++ b/src/mbgl/style/layers/hillshade_layer_properties.cpp @@ -25,7 +25,7 @@ unsigned long HillshadeLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const HillshadeLayer::Impl& HillshadeLayerProperties::layerImpl() const { +const HillshadeLayer::Impl& HillshadeLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/hillshade_layer_properties.hpp b/src/mbgl/style/layers/hillshade_layer_properties.hpp index 4b35f01a5..cf073f1ce 100644 --- a/src/mbgl/style/layers/hillshade_layer_properties.hpp +++ b/src/mbgl/style/layers/hillshade_layer_properties.hpp @@ -61,7 +61,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const HillshadeLayer::Impl& layerImpl() const; + const HillshadeLayer::Impl& layerImpl() const noexcept; // Data members. HillshadePaintProperties::PossiblyEvaluated evaluated; }; diff --git a/src/mbgl/style/layers/layer_properties.cpp.ejs b/src/mbgl/style/layers/layer_properties.cpp.ejs index cebc64114..d637ecfb5 100644 --- a/src/mbgl/style/layers/layer_properties.cpp.ejs +++ b/src/mbgl/style/layers/layer_properties.cpp.ejs @@ -36,7 +36,7 @@ unsigned long <%- camelize(type) %>LayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const <%- camelize(type) %>Layer::Impl& <%- camelize(type) %>LayerProperties::layerImpl() const { +const <%- camelize(type) %>Layer::Impl& <%- camelize(type) %>LayerProperties::layerImpl() const noexcept { return static_castLayer::Impl&>(*baseImpl); } diff --git a/src/mbgl/style/layers/layer_properties.hpp.ejs b/src/mbgl/style/layers/layer_properties.hpp.ejs index 314317ab3..c81bf6133 100644 --- a/src/mbgl/style/layers/layer_properties.hpp.ejs +++ b/src/mbgl/style/layers/layer_properties.hpp.ejs @@ -78,7 +78,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const <%- camelize(type) %>Layer::Impl& layerImpl() const; + const <%- camelize(type) %>Layer::Impl& layerImpl() const noexcept; // Data members. <% if (type === 'background' || type === 'fill' || type === 'line' || type === 'fill-extrusion') { -%> CrossfadeParameters crossfade; diff --git a/src/mbgl/style/layers/line_layer_properties.cpp b/src/mbgl/style/layers/line_layer_properties.cpp index d5e7199ce..10dd40d2e 100644 --- a/src/mbgl/style/layers/line_layer_properties.cpp +++ b/src/mbgl/style/layers/line_layer_properties.cpp @@ -27,7 +27,7 @@ unsigned long LineLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const LineLayer::Impl& LineLayerProperties::layerImpl() const { +const LineLayer::Impl& LineLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/line_layer_properties.hpp b/src/mbgl/style/layers/line_layer_properties.hpp index 1fe89ff90..09615261a 100644 --- a/src/mbgl/style/layers/line_layer_properties.hpp +++ b/src/mbgl/style/layers/line_layer_properties.hpp @@ -125,7 +125,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const LineLayer::Impl& layerImpl() const; + const LineLayer::Impl& layerImpl() const noexcept; // Data members. CrossfadeParameters crossfade; LinePaintProperties::PossiblyEvaluated evaluated; diff --git a/src/mbgl/style/layers/location_indicator_layer_properties.cpp b/src/mbgl/style/layers/location_indicator_layer_properties.cpp index 0391551ea..f724a2ea6 100644 --- a/src/mbgl/style/layers/location_indicator_layer_properties.cpp +++ b/src/mbgl/style/layers/location_indicator_layer_properties.cpp @@ -25,7 +25,7 @@ unsigned long LocationIndicatorLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const LocationIndicatorLayer::Impl& LocationIndicatorLayerProperties::layerImpl() const { +const LocationIndicatorLayer::Impl& LocationIndicatorLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/location_indicator_layer_properties.hpp b/src/mbgl/style/layers/location_indicator_layer_properties.hpp index b8523e046..95ad7b6bd 100644 --- a/src/mbgl/style/layers/location_indicator_layer_properties.hpp +++ b/src/mbgl/style/layers/location_indicator_layer_properties.hpp @@ -102,7 +102,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const LocationIndicatorLayer::Impl& layerImpl() const; + const LocationIndicatorLayer::Impl& layerImpl() const noexcept; // Data members. LocationIndicatorPaintProperties::PossiblyEvaluated evaluated; }; diff --git a/src/mbgl/style/layers/raster_layer_properties.cpp b/src/mbgl/style/layers/raster_layer_properties.cpp index eccc8e26f..fb6237545 100644 --- a/src/mbgl/style/layers/raster_layer_properties.cpp +++ b/src/mbgl/style/layers/raster_layer_properties.cpp @@ -25,7 +25,7 @@ unsigned long RasterLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const RasterLayer::Impl& RasterLayerProperties::layerImpl() const { +const RasterLayer::Impl& RasterLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/raster_layer_properties.hpp b/src/mbgl/style/layers/raster_layer_properties.hpp index 5bc97bb16..5da2ce39d 100644 --- a/src/mbgl/style/layers/raster_layer_properties.hpp +++ b/src/mbgl/style/layers/raster_layer_properties.hpp @@ -71,7 +71,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const RasterLayer::Impl& layerImpl() const; + const RasterLayer::Impl& layerImpl() const noexcept; // Data members. RasterPaintProperties::PossiblyEvaluated evaluated; }; diff --git a/src/mbgl/style/layers/symbol_layer_properties.cpp b/src/mbgl/style/layers/symbol_layer_properties.cpp index f29279e49..ddcfc40fb 100644 --- a/src/mbgl/style/layers/symbol_layer_properties.cpp +++ b/src/mbgl/style/layers/symbol_layer_properties.cpp @@ -25,7 +25,7 @@ unsigned long SymbolLayerProperties::constantsMask() const { return evaluated.constantsMask(); } -const SymbolLayer::Impl& SymbolLayerProperties::layerImpl() const { +const SymbolLayer::Impl& SymbolLayerProperties::layerImpl() const noexcept { return static_cast(*baseImpl); } diff --git a/src/mbgl/style/layers/symbol_layer_properties.hpp b/src/mbgl/style/layers/symbol_layer_properties.hpp index 89ba28055..296fc9e63 100644 --- a/src/mbgl/style/layers/symbol_layer_properties.hpp +++ b/src/mbgl/style/layers/symbol_layer_properties.hpp @@ -353,7 +353,7 @@ public: expression::Dependency getDependencies() const noexcept override; - const SymbolLayer::Impl& layerImpl() const; + const SymbolLayer::Impl& layerImpl() const noexcept; // Data members. SymbolPaintProperties::PossiblyEvaluated evaluated; }; diff --git a/src/mbgl/style/properties.hpp b/src/mbgl/style/properties.hpp index 85844b1ec..a35f1ddd2 100644 --- a/src/mbgl/style/properties.hpp +++ b/src/mbgl/style/properties.hpp @@ -63,11 +63,11 @@ public: } } - bool hasTransition() const { return bool(prior); } + bool hasTransition() const noexcept { return bool(prior); } - bool isUndefined() const { return value.isUndefined(); } + bool isUndefined() const noexcept { return value.isUndefined(); } - const Value& getValue() const { return value; } + const Value& getValue() const noexcept { return value; } private: mutable std::optional>> prior; @@ -100,9 +100,12 @@ template struct ConstantsMask> { template static unsigned long getMask(const Properties& properties) { - std::bitset result; - util::ignore({result.set(TypeIndex::value, properties.template get().isConstant())...}); - return result.to_ulong(); + const auto result = std::apply( + [](auto... v) { return (v | ...); }, + std::make_tuple( + 0ul, + (((properties.template get().isConstant()) ? (1ul << (TypeIndex::value)) : 0ul))...)); + return result; } }; @@ -268,7 +271,7 @@ public: return result; } - unsigned long constantsMask() const { return ConstantsMask::getMask(*this); } + unsigned long constantsMask() const noexcept { return ConstantsMask::getMask(*this); } }; class Unevaluated : public Tuple { diff --git a/src/mbgl/style/property_expression.cpp b/src/mbgl/style/property_expression.cpp index 745fc90b0..fda1768af 100644 --- a/src/mbgl/style/property_expression.cpp +++ b/src/mbgl/style/property_expression.cpp @@ -3,13 +3,12 @@ namespace mbgl { namespace style { -PropertyExpressionBase::PropertyExpressionBase(std::unique_ptr expression_) +PropertyExpressionBase::PropertyExpressionBase(std::unique_ptr expression_) noexcept : expression(std::move(expression_)), isZoomConstant_(expression::isZoomConstant(*expression)), isFeatureConstant_(expression::isFeatureConstant(*expression)), isRuntimeConstant_(expression::isRuntimeConstant(*expression)), zoomCurve(isZoomConstant_ ? nullptr : expression::findZoomCurveChecked(*expression)) {} - float PropertyExpressionBase::interpolationFactor(const Range& inputLevels, const float inputValue) const noexcept { return zoomCurve.match( diff --git a/src/mbgl/util/bounding_volumes.cpp b/src/mbgl/util/bounding_volumes.cpp index b57009a22..03d513746 100644 --- a/src/mbgl/util/bounding_volumes.cpp +++ b/src/mbgl/util/bounding_volumes.cpp @@ -7,21 +7,21 @@ namespace mbgl { namespace { -vec3 toVec3(const vec4& v) { +vec3 toVec3(const vec4& v) noexcept { return vec3{{v[0], v[1], v[2]}}; } -double vec4Dot(const vec4& a, const vec4& b) { +double vec4Dot(const vec4& a, const vec4& b) noexcept { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } template -Point ProjectPointsToAxis(const std::array& points, const vec3& origin, const vec3& axis) { +Point ProjectPointsToAxis(const std::array& points, const vec3& origin, const vec3& axis) noexcept { double min = std::numeric_limits::max(); double max = -std::numeric_limits::max(); for (const vec3& point : points) { - double projectedPoint = vec3Dot(vec3Sub(point, origin), axis); + const double projectedPoint = vec3Dot(vec3Sub(point, origin), axis); min = std::min(projectedPoint, min); max = std::max(projectedPoint, max); } @@ -33,21 +33,21 @@ Point ProjectPointsToAxis(const std::array& points, const vec3& namespace util { -AABB::AABB() +AABB::AABB() noexcept : min({{0, 0, 0}}), max({{0, 0, 0}}) {} -AABB::AABB(const vec3& min_, const vec3& max_) +AABB::AABB(const vec3& min_, const vec3& max_) noexcept : min(min_), max(max_) {} -vec3 AABB::closestPoint(const vec3& point) const { +constexpr vec3 AABB::closestPoint(const vec3& point) const noexcept { return {{std::max(std::min(max[0], point[0]), min[0]), std::max(std::min(max[1], point[1]), min[1]), std::max(std::min(max[2], point[2]), min[2])}}; } -vec3 AABB::distanceXYZ(const vec3& point) const { +vec3 AABB::distanceXYZ(const vec3& point) const noexcept { vec3 vec = vec3Sub(closestPoint(point), point); vec[0] = std::abs(vec[0]); @@ -57,7 +57,7 @@ vec3 AABB::distanceXYZ(const vec3& point) const { return vec; } -AABB AABB::quadrant(int idx) const { +AABB AABB::quadrant(int idx) const noexcept { assert(idx >= 0 && idx < 4); vec3 quadrantMin = min; vec3 quadrantMax = max; @@ -79,18 +79,18 @@ AABB AABB::quadrant(int idx) const { return {quadrantMin, quadrantMax}; } -bool AABB::intersects(const AABB& aabb) const { +bool AABB::intersects(const AABB& aabb) const noexcept { if (min[0] > aabb.max[0] || aabb.min[0] > max[0]) return false; if (min[1] > aabb.max[1] || aabb.min[1] > max[1]) return false; if (min[2] > aabb.max[2] || aabb.min[2] > max[2]) return false; return true; } -bool AABB::operator==(const AABB& aabb) const { +bool AABB::operator==(const AABB& aabb) const noexcept { return min == aabb.min && max == aabb.max; } -bool AABB::operator!=(const AABB& aabb) const { +bool AABB::operator!=(const AABB& aabb) const noexcept { return !(*this == aabb); } diff --git a/src/mbgl/util/bounding_volumes.hpp b/src/mbgl/util/bounding_volumes.hpp index bca183d84..68e18dec1 100644 --- a/src/mbgl/util/bounding_volumes.hpp +++ b/src/mbgl/util/bounding_volumes.hpp @@ -15,21 +15,21 @@ enum class IntersectionResult : int { class AABB { public: - AABB(); - AABB(const vec3& min_, const vec3& max_); + AABB() noexcept; + AABB(const vec3& min_, const vec3& max_) noexcept; - vec3 closestPoint(const vec3& point) const; + constexpr vec3 closestPoint(const vec3& point) const noexcept; // Computes the shortest manhattan distance to the provided point - vec3 distanceXYZ(const vec3& point) const; + vec3 distanceXYZ(const vec3& point) const noexcept; // Creates an aabb covering one quadrant of the aabb on XZ-plane. - AABB quadrant(int idx) const; + AABB quadrant(int idx) const noexcept; - bool intersects(const AABB& aabb) const; + bool intersects(const AABB& aabb) const noexcept; - bool operator==(const AABB& aabb) const; - bool operator!=(const AABB& aabb) const; + bool operator==(const AABB& aabb) const noexcept; + bool operator!=(const AABB& aabb) const noexcept; vec3 min; vec3 max; @@ -65,4 +65,4 @@ private: }; } // namespace util -} // namespace mbgl \ No newline at end of file +} // namespace mbgl diff --git a/src/mbgl/util/camera.cpp b/src/mbgl/util/camera.cpp index bc009e638..1a06ecfd0 100644 --- a/src/mbgl/util/camera.cpp +++ b/src/mbgl/util/camera.cpp @@ -11,48 +11,48 @@ namespace mbgl { namespace { -double vec2Len(const vec2& v) { +double vec2Len(const vec2& v) noexcept { return std::sqrt(v[0] * v[0] + v[1] * v[1]); }; -double vec2Dot(const vec2& a, const vec2& b) { +double vec2Dot(const vec2& a, const vec2& b) noexcept { return a[0] * b[0] + a[1] * b[1]; }; -vec2 vec2Scale(const vec2& v, double s) { +vec2 vec2Scale(const vec2& v, double s) noexcept { return vec2{{v[0] * s, v[1] * s}}; }; } // namespace namespace util { -static double mercatorXfromLng(double lng) { +static double mercatorXfromLng(double lng) noexcept { return (180.0 + lng) / 360.0; } -static double mercatorYfromLat(double lat) { +static double mercatorYfromLat(double lat) noexcept { return (180.0 - (180.0 / M_PI * std::log(std::tan(M_PI_4 + lat * M_PI / 360.0)))) / 360.0; } -static double latFromMercatorY(double y) { +static double latFromMercatorY(double y) noexcept { return util::rad2deg(2.0 * std::atan(std::exp(M_PI - y * util::M2PI)) - M_PI_2); } -static double lngFromMercatorX(double x) { +static double lngFromMercatorX(double x) noexcept { return x * 360.0 - 180.0; } -static double* getColumn(mat4& matrix, int col) { +static double* getColumn(mat4& matrix, int col) noexcept { assert(col >= 0 && col < 4); return &matrix[col * 4]; } -static const double* getColumn(const mat4& matrix, int col) { +static const double* getColumn(const mat4& matrix, int col) noexcept { assert(col >= 0 && col < 4); return &matrix[col * 4]; } -static vec3 toMercator(const LatLng& location, double altitudeMeters) { +static vec3 toMercator(const LatLng& location, double altitudeMeters) noexcept { const double pixelsPerMeter = 1.0 / Projection::getMetersPerPixelAtLatitude(location.latitude(), 0.0); const double worldSize = Projection::worldSize(std::pow(2.0, 0.0)); @@ -61,15 +61,15 @@ static vec3 toMercator(const LatLng& location, double altitudeMeters) { altitudeMeters * pixelsPerMeter / worldSize}}; } -static Quaternion orientationFromPitchBearing(double pitch, double bearing) { +static Quaternion orientationFromPitchBearing(double pitch, double bearing) noexcept { // Both angles have to be negated to achieve CW rotation around the axis of rotation - Quaternion rotBearing = Quaternion::fromAxisAngle({{0.0, 0.0, 1.0}}, -bearing); - Quaternion rotPitch = Quaternion::fromAxisAngle({{1.0, 0.0, 0.0}}, -pitch); + const Quaternion rotBearing = Quaternion::fromAxisAngle({{0.0, 0.0, 1.0}}, -bearing); + const Quaternion rotPitch = Quaternion::fromAxisAngle({{1.0, 0.0, 0.0}}, -pitch); return rotBearing.multiply(rotPitch); } -static void updateTransform(mat4& transform, const Quaternion& orientation) { +static void updateTransform(mat4& transform, const Quaternion& orientation) noexcept { // Construct rotation matrix from orientation mat4 m = orientation.toRotationMatrix(); @@ -89,23 +89,23 @@ static void updateTransform(mat4& transform, const vec3& position) { getColumn(transform, 3)[2] = position[2]; } -Camera::Camera() +Camera::Camera() noexcept : orientation(Quaternion::identity) { matrix::identity(transform); } -vec3 Camera::getPosition() const { +vec3 Camera::getPosition() const noexcept { const double* p = getColumn(transform, 3); return {{p[0], p[1], p[2]}}; } -mat4 Camera::getCameraToWorld(double scale, bool flippedY) const { +mat4 Camera::getCameraToWorld(double scale, bool flippedY) const noexcept { mat4 cameraToWorld; matrix::invert(cameraToWorld, getWorldToCamera(scale, flippedY)); return cameraToWorld; } -mat4 Camera::getWorldToCamera(double scale, bool flippedY) const { +mat4 Camera::getWorldToCamera(double scale, bool flippedY) const noexcept { // transformation chain from world space to camera space: // 1. Height value (z) of renderables is in meters. Scale z coordinate by pixelsPerMeter // 2. Transform from pixel coordinates to camera space with cameraMatrix^-1 @@ -140,30 +140,30 @@ mat4 Camera::getWorldToCamera(double scale, bool flippedY) const { return result; } -mat4 Camera::getCameraToClipPerspective(double fovy, double aspectRatio, double nearZ, double farZ) const { +mat4 Camera::getCameraToClipPerspective(double fovy, double aspectRatio, double nearZ, double farZ) const noexcept { mat4 projection; matrix::perspective(projection, fovy, aspectRatio, nearZ, farZ); return projection; } -vec3 Camera::forward() const { +vec3 Camera::forward() const noexcept { const double* column = getColumn(transform, 2); // The forward direction is towards the map, [0, 0, -1] return {{-column[0], -column[1], -column[2]}}; } -vec3 Camera::right() const { +vec3 Camera::right() const noexcept { const double* column = getColumn(transform, 0); return {{column[0], column[1], column[2]}}; } -vec3 Camera::up() const { +vec3 Camera::up() const noexcept { const double* column = getColumn(transform, 1); // Up direction has to be flipped due to y-axis pointing towards south return {{-column[0], -column[1], -column[2]}}; } -void Camera::getOrientation(double& pitch, double& bearing) const { +void Camera::getOrientation(double& pitch, double& bearing) const noexcept { const vec3 f = forward(); const vec3 r = right(); @@ -171,24 +171,24 @@ void Camera::getOrientation(double& pitch, double& bearing) const { pitch = std::atan2(std::sqrt(f[0] * f[0] + f[1] * f[1]), -f[2]); } -void Camera::setOrientation(double pitch, double bearing) { +void Camera::setOrientation(double pitch, double bearing) noexcept { orientation = orientationFromPitchBearing(pitch, bearing); updateTransform(transform, orientation); } -void Camera::setOrientation(const Quaternion& orientation_) { +void Camera::setOrientation(const Quaternion& orientation_) noexcept { orientation = orientation_; updateTransform(transform, orientation); } -void Camera::setPosition(const vec3& position) { +void Camera::setPosition(const vec3& position) noexcept { updateTransform(transform, position); } -std::optional Camera::orientationFromFrame(const vec3& forward, const vec3& up) { +std::optional Camera::orientationFromFrame(const vec3& forward, const vec3& up) noexcept { vec3 upVector = up; - vec2 xyForward = {{forward[0], forward[1]}}; + const vec2 xyForward = {{forward[0], forward[1]}}; vec2 xyUp = {{up[0], up[1]}}; const double epsilon = 1e-15; @@ -215,11 +215,11 @@ std::optional Camera::orientationFromFrame(const vec3& forward, cons } } // namespace util -void FreeCameraOptions::setLocation(const LatLngAltitude& location) { +void FreeCameraOptions::setLocation(const LatLngAltitude& location) noexcept { position = util::toMercator(location.location, location.altitude); } -std::optional FreeCameraOptions::getLocation() const { +std::optional FreeCameraOptions::getLocation() const noexcept { if (!position) { return std::nullopt; } @@ -238,7 +238,7 @@ std::optional FreeCameraOptions::getLocation() const { return LatLngAltitude{location, altitude}; } -void FreeCameraOptions::lookAtPoint(const LatLng& location, const std::optional& upVector) { +void FreeCameraOptions::lookAtPoint(const LatLng& location, const std::optional& upVector) noexcept { orientation = std::nullopt; if (!position) { return; @@ -257,7 +257,7 @@ void FreeCameraOptions::lookAtPoint(const LatLng& location, const std::optional< } } -void FreeCameraOptions::setPitchBearing(double pitch, double bearing) { +void FreeCameraOptions::setPitchBearing(double pitch, double bearing) noexcept { orientation = util::orientationFromPitchBearing(util::deg2rad(pitch), util::deg2rad(bearing)).m; } diff --git a/src/mbgl/util/camera.hpp b/src/mbgl/util/camera.hpp index fd74efc97..d17e95bcf 100644 --- a/src/mbgl/util/camera.hpp +++ b/src/mbgl/util/camera.hpp @@ -13,27 +13,27 @@ namespace util { class Camera { public: - Camera(); + Camera() noexcept; - vec3 getPosition() const; - mat4 getCameraToWorld(double scale, bool flippedY) const; - mat4 getWorldToCamera(double scale, bool flippedY) const; - mat4 getCameraToClipPerspective(double fovy, double aspectRatio, double nearZ, double farZ) const; + vec3 getPosition() const noexcept; + mat4 getCameraToWorld(double scale, bool flippedY) const noexcept; + mat4 getWorldToCamera(double scale, bool flippedY) const noexcept; + mat4 getCameraToClipPerspective(double fovy, double aspectRatio, double nearZ, double farZ) const noexcept; - vec3 forward() const; - vec3 right() const; - vec3 up() const; + vec3 forward() const noexcept; + vec3 right() const noexcept; + vec3 up() const noexcept; - const Quaternion& getOrientation() const { return orientation; } - void getOrientation(double& pitch, double& bearing) const; - void setOrientation(double pitch, double bearing); - void setOrientation(const Quaternion& orientation_); - void setPosition(const vec3& position); + const Quaternion& getOrientation() const noexcept { return orientation; } + void getOrientation(double& pitch, double& bearing) const noexcept; + void setOrientation(double pitch, double bearing) noexcept; + void setOrientation(const Quaternion& orientation_) noexcept; + void setPosition(const vec3& position) noexcept; // Computes orientation using forward and up vectors of the provided // coordinate frame. Only bearing and pitch components will be used. Does // not return a value if input is invalid - static std::optional orientationFromFrame(const vec3& forward, const vec3& up); + static std::optional orientationFromFrame(const vec3& forward, const vec3& up) noexcept; private: Quaternion orientation; diff --git a/src/mbgl/util/geo.cpp b/src/mbgl/util/geo.cpp index 0f5d10c50..4cfb65bc7 100644 --- a/src/mbgl/util/geo.cpp +++ b/src/mbgl/util/geo.cpp @@ -11,38 +11,38 @@ namespace mbgl { namespace { -double lat_(const uint8_t z, const int64_t y) { +double lat_(const uint8_t z, const int64_t y) noexcept { const double n = M_PI - 2.0 * M_PI * y / std::pow(2.0, z); return util::rad2deg(std::atan(0.5 * (std::exp(n) - std::exp(-n)))); } -double lon_(const uint8_t z, const int64_t x) { +double lon_(const uint8_t z, const int64_t x) noexcept { return x / std::pow(2.0, z) * util::DEGREES_MAX - util::LONGITUDE_MAX; } } // end namespace -LatLng::LatLng(const CanonicalTileID& id) +LatLng::LatLng(const CanonicalTileID& id) noexcept : lat(lat_(id.z, id.y)), lon(lon_(id.z, id.x)) {} -LatLng::LatLng(const UnwrappedTileID& id) +LatLng::LatLng(const UnwrappedTileID& id) noexcept : lat(lat_(id.canonical.z, id.canonical.y)), lon(lon_(id.canonical.z, id.canonical.x) + id.wrap * util::DEGREES_MAX) {} -LatLngBounds::LatLngBounds(const CanonicalTileID& id) +LatLngBounds::LatLngBounds(const CanonicalTileID& id) noexcept : sw({lat_(id.z, id.y + 1), lon_(id.z, id.x)}), ne({lat_(id.z, id.y), lon_(id.z, id.x + 1)}) {} -bool LatLngBounds::contains(const CanonicalTileID& tileID) const { +bool LatLngBounds::contains(const CanonicalTileID& tileID) const noexcept { return util::TileRange::fromLatLngBounds(*this, tileID.z).contains(tileID); } -bool LatLngBounds::contains(const LatLng& point, LatLng::WrapMode wrap /*= LatLng::Unwrapped*/) const { +bool LatLngBounds::contains(const LatLng& point, LatLng::WrapMode wrap /*= LatLng::Unwrapped*/) const noexcept { return containsLatitude(point.latitude()) && containsLongitude(point.longitude(), wrap); } -bool LatLngBounds::contains(const LatLngBounds& area, LatLng::WrapMode wrap /*= LatLng::Unwrapped*/) const { +bool LatLngBounds::contains(const LatLngBounds& area, LatLng::WrapMode wrap /*= LatLng::Unwrapped*/) const noexcept { bool containsAreaLatitude = area.north() <= north() && area.south() >= south(); if (!containsAreaLatitude) { return false; @@ -52,8 +52,8 @@ bool LatLngBounds::contains(const LatLngBounds& area, LatLng::WrapMode wrap /*= if (containsUnwrapped) { return true; } else if (wrap == LatLng::Wrapped) { - LatLngBounds wrapped(sw.wrapped(), ne.wrapped()); - LatLngBounds other(area.sw.wrapped(), area.ne.wrapped()); + const LatLngBounds wrapped(sw.wrapped(), ne.wrapped()); + const LatLngBounds other(area.sw.wrapped(), area.ne.wrapped()); if (crossesAntimeridian() && !area.crossesAntimeridian()) { return (other.east() <= util::LONGITUDE_MAX && other.west() >= wrapped.west()) || (other.east() <= wrapped.east() && other.west() >= -util::LONGITUDE_MAX); @@ -64,18 +64,18 @@ bool LatLngBounds::contains(const LatLngBounds& area, LatLng::WrapMode wrap /*= return false; } -bool LatLngBounds::intersects(const LatLngBounds area, LatLng::WrapMode wrap /*= LatLng::Unwrapped*/) const { - bool latitudeIntersects = area.north() > south() && area.south() < north(); +bool LatLngBounds::intersects(const LatLngBounds area, LatLng::WrapMode wrap /*= LatLng::Unwrapped*/) const noexcept { + const bool latitudeIntersects = area.north() > south() && area.south() < north(); if (!latitudeIntersects) { return false; } - bool longitudeIntersects = area.east() > west() && area.west() < east(); + const bool longitudeIntersects = area.east() > west() && area.west() < east(); if (longitudeIntersects) { return true; } else if (wrap == LatLng::Wrapped) { - LatLngBounds wrapped(sw.wrapped(), ne.wrapped()); - LatLngBounds other(area.sw.wrapped(), area.ne.wrapped()); + const LatLngBounds wrapped(sw.wrapped(), ne.wrapped()); + const LatLngBounds other(area.sw.wrapped(), area.ne.wrapped()); if (crossesAntimeridian()) { return area.crossesAntimeridian() || other.east() > wrapped.west() || other.west() < wrapped.east(); } else if (other.crossesAntimeridian()) { @@ -87,7 +87,7 @@ bool LatLngBounds::intersects(const LatLngBounds area, LatLng::WrapMode wrap /*= return false; } -LatLng LatLngBounds::constrain(const LatLng& p) const { +LatLng LatLngBounds::constrain(const LatLng& p) const noexcept { if (!bounded) { return p; } @@ -106,11 +106,11 @@ LatLng LatLngBounds::constrain(const LatLng& p) const { return LatLng{lat, lng}; } -bool LatLngBounds::containsLatitude(double latitude) const { +bool LatLngBounds::containsLatitude(double latitude) const noexcept { return latitude >= south() && latitude <= north(); } -bool LatLngBounds::containsLongitude(double longitude, LatLng::WrapMode wrap) const { +bool LatLngBounds::containsLongitude(double longitude, LatLng::WrapMode wrap) const noexcept { if (longitude >= west() && longitude <= east()) { return true; } @@ -129,7 +129,7 @@ bool LatLngBounds::containsLongitude(double longitude, LatLng::WrapMode wrap) co return false; } -ScreenCoordinate EdgeInsets::getCenter(uint16_t width, uint16_t height) const { +ScreenCoordinate EdgeInsets::getCenter(uint16_t width, uint16_t height) const noexcept { return { (width - left() - right()) / 2.0 + left(), (height - top() - bottom()) / 2.0 + top(), diff --git a/src/mbgl/util/geometry_util.cpp b/src/mbgl/util/geometry_util.cpp index 86079cf15..3e5cff42e 100644 --- a/src/mbgl/util/geometry_util.cpp +++ b/src/mbgl/util/geometry_util.cpp @@ -5,7 +5,7 @@ namespace mbgl { template -void updateBBox(GeometryBBox& bbox, const Point& p) { +void updateBBox(GeometryBBox& bbox, const Point& p) noexcept { bbox[0] = std::min(p.x, bbox[0]); bbox[1] = std::min(p.y, bbox[1]); bbox[2] = std::max(p.x, bbox[2]); @@ -14,7 +14,7 @@ void updateBBox(GeometryBBox& bbox, const Point& p) { // check if bbox1 is within bbox2 template -bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2) { +bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2) noexcept { if (bbox1[0] <= bbox2[0]) return false; if (bbox1[2] >= bbox2[2]) return false; if (bbox1[1] <= bbox2[1]) return false; @@ -23,13 +23,13 @@ bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2) { } template -bool rayIntersect(const Point& p, const Point& p1, const Point& p2) { +bool rayIntersect(const Point& p, const Point& p1, const Point& p2) noexcept { return ((p1.y > p.y) != (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x); } // check if point p is on line segment with end points p1 and p2 template -bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2) { +bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2) noexcept { // requirements of point p on line segment: // 1. colinear: cross product of vector p->p1(x1, y1) and vector p->p2(x2, y2) equals to 0 // 2. p is between p1 and p2 @@ -41,21 +41,21 @@ bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2) } template -bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, const Point& d) { +bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, const Point& d) noexcept { // a, b are end points for line segment1, c and d are end points for line segment2 - const auto perp = [](const Point& v1, const Point& v2) { + const auto perp = [](const Point& v1, const Point& v2) noexcept { return (v1.x * v2.y - v1.y * v2.x); }; // check if two segments are parallel or not // precondition is end point a, b is inside polygon, if line a->b is // parallel to polygon edge c->d, then a->b won't intersect with c->d - auto vectorP = Point(b.x - a.x, b.y - a.y); - auto vectorQ = Point(d.x - c.x, d.y - c.y); + const auto vectorP = Point(b.x - a.x, b.y - a.y); + const auto vectorQ = Point(d.x - c.x, d.y - c.y); if (perp(vectorQ, vectorP) == 0) return false; // check if p1 and p2 are in different sides of line segment q1->q2 - const auto twoSided = [](const Point& p1, const Point& p2, const Point& q1, const Point& q2) { + const auto twoSided = [](const Point& p1, const Point& p2, const Point& q1, const Point& q2) noexcept { // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3) T x1 = p1.x - q1.x; T y1 = p1.y - q1.y; @@ -75,7 +75,7 @@ bool segmentIntersectSegment(const Point& a, const Point& b, const Point -bool lineIntersectPolygon(const Point& p1, const Point& p2, const Polygon& polygon) { +bool lineIntersectPolygon(const Point& p1, const Point& p2, const Polygon& polygon) noexcept { for (auto ring : polygon) { auto length = ring.size(); // loop through every edge of the ring @@ -90,7 +90,7 @@ bool lineIntersectPolygon(const Point& p1, const Point& p2, const Polygon< // ray casting algorithm for detecting if point is in polygon template -bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary) { +bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary) noexcept { bool within = false; for (const auto& ring : polygon) { const auto length = ring.size(); @@ -106,7 +106,7 @@ bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool t } template -bool pointWithinPolygons(const Point& point, const MultiPolygon& polygons, bool trueOnBoundary) { +bool pointWithinPolygons(const Point& point, const MultiPolygon& polygons, bool trueOnBoundary) noexcept { for (const auto& polygon : polygons) { if (pointWithinPolygon(point, polygon, trueOnBoundary)) return true; } @@ -114,7 +114,7 @@ bool pointWithinPolygons(const Point& point, const MultiPolygon& polygons, } template -bool lineStringWithinPolygon(const LineString& line, const Polygon& polygon) { +bool lineStringWithinPolygon(const LineString& line, const Polygon& polygon) noexcept { const auto length = line.size(); // First, check if geometry points of line segments are all inside polygon for (std::size_t i = 0; i < length; ++i) { @@ -133,35 +133,41 @@ bool lineStringWithinPolygon(const LineString& line, const Polygon& polygo } template -bool lineStringWithinPolygons(const LineString& line, const MultiPolygon& polygons) { +bool lineStringWithinPolygons(const LineString& line, const MultiPolygon& polygons) noexcept { for (const auto& polygon : polygons) { if (lineStringWithinPolygon(line, polygon)) return true; } return false; } -template void updateBBox(GeometryBBox& bbox, const Point& p); -template bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2); +template void updateBBox(GeometryBBox& bbox, const Point& p) noexcept; +template bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2) noexcept; template bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, - const Point& d); -template bool rayIntersect(const Point& p, const Point& p1, const Point& p2); -template bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2); -template bool lineIntersectPolygon(const Point& p1, const Point& p2, const Polygon& polygon); -template bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary); + const Point& d) noexcept; +template bool rayIntersect(const Point& p, const Point& p1, const Point& p2) noexcept; +template bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2) noexcept; +template bool lineIntersectPolygon(const Point& p1, + const Point& p2, + const Polygon& polygon) noexcept; +template bool pointWithinPolygon(const Point& point, + const Polygon& polygon, + bool trueOnBoundary) noexcept; template bool pointWithinPolygons(const Point& point, const MultiPolygon& polygons, - bool trueOnBoundary); -template bool lineStringWithinPolygon(const LineString& line, const Polygon& polygon); -template bool lineStringWithinPolygons(const LineString& line, const MultiPolygon& polygons); + bool trueOnBoundary) noexcept; +template bool lineStringWithinPolygon(const LineString& line, const Polygon& polygon) noexcept; +template bool lineStringWithinPolygons(const LineString& line, const MultiPolygon& polygons) noexcept; -template void updateBBox(GeometryBBox& bbox, const Point& p); -template bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2); +template void updateBBox(GeometryBBox& bbox, const Point& p) noexcept; +template bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2) noexcept; template bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, - const Point& d); -template bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary); + const Point& d) noexcept; +template bool pointWithinPolygon(const Point& point, + const Polygon& polygon, + bool trueOnBoundary) noexcept; } // namespace mbgl diff --git a/src/mbgl/util/geometry_util.hpp b/src/mbgl/util/geometry_util.hpp index 528f06396..9885f5fe6 100644 --- a/src/mbgl/util/geometry_util.hpp +++ b/src/mbgl/util/geometry_util.hpp @@ -20,34 +20,34 @@ const GeometryBBox DefaultDistanceBBox = std::array{{std::num -std::numeric_limits::infinity()}}; template -void updateBBox(GeometryBBox& bbox, const Point& p); +void updateBBox(GeometryBBox& bbox, const Point& p) noexcept; // check if bbox1 is within bbox2 template -bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2); +bool boxWithinBox(const GeometryBBox& bbox1, const GeometryBBox& bbox2) noexcept; template -bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, const Point& d); +bool segmentIntersectSegment(const Point& a, const Point& b, const Point& c, const Point& d) noexcept; template -bool rayIntersect(const Point& p, const Point& p1, const Point& p2); +bool rayIntersect(const Point& p, const Point& p1, const Point& p2) noexcept; template -bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2); +bool pointOnBoundary(const Point& p, const Point& p1, const Point& p2) noexcept; template -bool lineIntersectPolygon(const Point& p1, const Point& p2, const Polygon& polygon); +bool lineIntersectPolygon(const Point& p1, const Point& p2, const Polygon& polygon) noexcept; template -bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary = false); +bool pointWithinPolygon(const Point& point, const Polygon& polygon, bool trueOnBoundary = false) noexcept; template -bool pointWithinPolygons(const Point& point, const MultiPolygon& polygons, bool trueOnBoundary = false); +bool pointWithinPolygons(const Point& point, const MultiPolygon& polygons, bool trueOnBoundary = false) noexcept; template -bool lineStringWithinPolygon(const LineString& line, const Polygon& polygon); +bool lineStringWithinPolygon(const LineString& line, const Polygon& polygon) noexcept; template -bool lineStringWithinPolygons(const LineString& line, const MultiPolygon& polygons); +bool lineStringWithinPolygons(const LineString& line, const MultiPolygon& polygons) noexcept; } // namespace mbgl diff --git a/src/mbgl/util/hash.hpp b/src/mbgl/util/hash.hpp index f35b15d47..94d7344ec 100644 --- a/src/mbgl/util/hash.hpp +++ b/src/mbgl/util/hash.hpp @@ -26,7 +26,7 @@ using TIterVal = std::enable_if_t:: } // namespace detail template -constexpr T factor() { +constexpr T factor() noexcept { // Default factor prime value from 64-bit FNV hash. if constexpr (sizeof(T) == 8) return 1099511628211; // for 32-bit hash @@ -36,7 +36,7 @@ constexpr T factor() { /// Generate a hash key from a collection of integer values which doesn't depend on their order. /// Adapted from https://stackoverflow.com/a/76993810/135138 template , TKey factor = factor()> -TKey order_independent_hash(std::remove_const_t cur, const TIter end) { +TKey order_independent_hash(std::remove_const_t cur, const TIter end) noexcept { detail::TIterVal sum = 0, product = 1; for (; cur != end; ++cur) { const auto& value = *cur; diff --git a/src/mbgl/util/identity.cpp b/src/mbgl/util/identity.cpp index 7ebb47ec7..65bd81ece 100644 --- a/src/mbgl/util/identity.cpp +++ b/src/mbgl/util/identity.cpp @@ -12,7 +12,7 @@ namespace util { const SimpleIdentity SimpleIdentity::Empty = {emptyID}; -SimpleIdentity::SimpleIdentity() +SimpleIdentity::SimpleIdentity() noexcept : uniqueID(nextId++) {} } // namespace util diff --git a/src/mbgl/util/interpolate.cpp b/src/mbgl/util/interpolate.cpp index 1ac96038b..7741fe8a7 100644 --- a/src/mbgl/util/interpolate.cpp +++ b/src/mbgl/util/interpolate.cpp @@ -5,7 +5,7 @@ namespace mbgl { namespace util { -float interpolationFactor(float base, Range range, float z) { +float interpolationFactor(float base, Range range, float z) noexcept { const float zoomDiff = range.max - range.min; const float zoomProgress = z - range.min; if (zoomDiff == 0) { diff --git a/src/mbgl/util/logging.cpp b/src/mbgl/util/logging.cpp index 89a5e08e3..1b5fb9fde 100644 --- a/src/mbgl/util/logging.cpp +++ b/src/mbgl/util/logging.cpp @@ -6,6 +6,7 @@ #include #include +#include #include namespace mbgl { @@ -23,13 +24,20 @@ public: Impl() : scheduler(Scheduler::GetSequenced()) {} - void record(EventSeverity severity, Event event, int64_t code, const std::string& msg) { + void record(EventSeverity severity, Event event, int64_t code, const std::string& msg) try { if (useThread) { auto threadName = platform::getCurrentThreadName(); scheduler->schedule([=]() { Log::record(severity, event, code, msg, threadName); }); } else { Log::record(severity, event, code, msg, {}); } + } catch (...) { + // ignore exceptions during logging + // What would we do, log them? +#if !defined(NDEBUG) + [[maybe_unused]] auto ex = std::current_exception(); + assert(!"unhandled exception while logging"); +#endif } private: @@ -46,7 +54,7 @@ Log* Log::get() noexcept { return &instance; } -void Log::useLogThread(bool enable) { +void Log::useLogThread(bool enable) noexcept { useThread = enable; } @@ -62,11 +70,11 @@ std::unique_ptr Log::removeObserver() { return observer; } -void Log::record(EventSeverity severity, Event event, const std::string& msg) { +void Log::record(EventSeverity severity, Event event, const std::string& msg) noexcept { get()->impl->record(severity, event, -1, msg); } -void Log::record(EventSeverity severity, Event event, int64_t code, const std::string& msg) { +void Log::record(EventSeverity severity, Event event, int64_t code, const std::string& msg) noexcept { get()->impl->record(severity, event, code, msg); } diff --git a/src/mbgl/util/mat3.cpp b/src/mbgl/util/mat3.cpp index 96c73935c..8bc06c01d 100644 --- a/src/mbgl/util/mat3.cpp +++ b/src/mbgl/util/mat3.cpp @@ -27,7 +27,7 @@ namespace mbgl { namespace matrix { -void identity(mat3& out) { +void identity(mat3& out) noexcept { out[0] = 1.0f; out[1] = 0.0f; out[2] = 0.0f; @@ -39,16 +39,16 @@ void identity(mat3& out) { out[8] = 1.0f; } -void translate(mat3& out, const mat3& a, double x, double y) { - double a00 = a[0]; - double a01 = a[1]; - double a02 = a[2]; - double a10 = a[3]; - double a11 = a[4]; - double a12 = a[5]; - double a20 = a[6]; - double a21 = a[7]; - double a22 = a[8]; +void translate(mat3& out, const mat3& a, double x, double y) noexcept { + const double a00 = a[0]; + const double a01 = a[1]; + const double a02 = a[2]; + const double a10 = a[3]; + const double a11 = a[4]; + const double a12 = a[5]; + const double a20 = a[6]; + const double a21 = a[7]; + const double a22 = a[8]; out[0] = a00; out[1] = a01; @@ -63,18 +63,18 @@ void translate(mat3& out, const mat3& a, double x, double y) { out[8] = x * a02 + y * a12 + a22; } -void rotate(mat3& out, const mat3& a, double rad) { - double s = std::sin(rad); - double c = std::cos(rad); - double a00 = a[0]; - double a01 = a[1]; - double a02 = a[2]; - double a10 = a[3]; - double a11 = a[4]; - double a12 = a[5]; - double a20 = a[6]; - double a21 = a[7]; - double a22 = a[8]; +void rotate(mat3& out, const mat3& a, double rad) noexcept { + const double s = std::sin(rad); + const double c = std::cos(rad); + const double a00 = a[0]; + const double a01 = a[1]; + const double a02 = a[2]; + const double a10 = a[3]; + const double a11 = a[4]; + const double a12 = a[5]; + const double a20 = a[6]; + const double a21 = a[7]; + const double a22 = a[8]; out[0] = c * a00 + s * a10; out[1] = c * a01 + s * a11; @@ -89,7 +89,7 @@ void rotate(mat3& out, const mat3& a, double rad) { out[8] = a22; } -void scale(mat3& out, const mat3& a, double x, double y) { +void scale(mat3& out, const mat3& a, double x, double y) noexcept { out[0] = x * a[0]; out[1] = x * a[1]; out[2] = x * a[2]; @@ -101,7 +101,7 @@ void scale(mat3& out, const mat3& a, double x, double y) { out[8] = a[8]; } -void transformMat3f(vec3f& out, const vec3f& a, const mat3& m) { +void transformMat3f(vec3f& out, const vec3f& a, const mat3& m) noexcept { out[0] = static_cast(m[0]) * a[0] + static_cast(m[3]) * a[1] + static_cast(m[6]) * a[2]; out[1] = static_cast(m[1]) * a[0] + static_cast(m[4]) * a[1] + static_cast(m[7]) * a[2]; out[2] = static_cast(m[2]) * a[0] + static_cast(m[5]) * a[1] + static_cast(m[8]) * a[2]; diff --git a/src/mbgl/util/mat3.hpp b/src/mbgl/util/mat3.hpp index cb43505ba..893a8f635 100644 --- a/src/mbgl/util/mat3.hpp +++ b/src/mbgl/util/mat3.hpp @@ -22,50 +22,54 @@ #pragma once -#include -#include #include +#include +#include +#include + namespace mbgl { using mat3 = std::array; -inline vec3 vec3Cross(const vec3& a, const vec3& b) { +constexpr inline vec3 vec3Cross(const vec3& a, const vec3& b) noexcept { return vec3{{a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]}}; } -inline double vec3Dot(const vec3& a, const vec3& b) { +constexpr inline double vec3Dot(const vec3& a, const vec3& b) noexcept { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } -inline double vec3LengthSq(const vec3& a) { +constexpr inline double vec3LengthSq(const vec3& a) noexcept { return vec3Dot(a, a); } -inline double vec3Length(const vec3& a) { +inline double vec3Length(const vec3& a) noexcept { return std::sqrt(vec3LengthSq(a)); } -inline vec3 vec3Scale(const vec3& a, double s) { +constexpr inline vec3 vec3Scale(const vec3& a, double s) noexcept { return vec3{{a[0] * s, a[1] * s, a[2] * s}}; } -inline vec3 vec3Normalize(const vec3& a) { - return vec3Scale(a, 1.0 / vec3Length(a)); +inline vec3 vec3Normalize(const vec3& a) noexcept { + const auto length = vec3Length(a); + assert(length != 0); + return vec3Scale(a, 1.0 / length); } -inline vec3 vec3Sub(const vec3& a, const vec3& b) { +constexpr inline vec3 vec3Sub(const vec3& a, const vec3& b) noexcept { return vec3{{a[0] - b[0], a[1] - b[1], a[2] - b[2]}}; } namespace matrix { -void identity(mat3& out); -void translate(mat3& out, const mat3& a, double x, double y); -void rotate(mat3& out, const mat3& a, double rad); -void scale(mat3& out, const mat3& a, double x, double y); +void identity(mat3& out) noexcept; +void translate(mat3& out, const mat3& a, double x, double y) noexcept; +void rotate(mat3& out, const mat3& a, double rad) noexcept; +void scale(mat3& out, const mat3& a, double x, double y) noexcept; -void transformMat3f(vec3f& out, const vec3f& a, const mat3& m); +void transformMat3f(vec3f& out, const vec3f& a, const mat3& m) noexcept; } // namespace matrix } // namespace mbgl diff --git a/src/mbgl/util/quaternion.cpp b/src/mbgl/util/quaternion.cpp index 322eeba31..dd4ce4bb1 100644 --- a/src/mbgl/util/quaternion.cpp +++ b/src/mbgl/util/quaternion.cpp @@ -6,65 +6,54 @@ namespace mbgl { Quaternion Quaternion::identity = Quaternion(0.0, 0.0, 0.0, 1.0); -Quaternion Quaternion::conjugate() const { +Quaternion Quaternion::conjugate() const noexcept { return {-x, -y, -z, w}; } -Quaternion Quaternion::normalized() const { +Quaternion Quaternion::normalized() const noexcept { const double len = length(); assert(len > 0.0); return {x / len, y / len, z / len, w / len}; } -Quaternion Quaternion::fromAxisAngle(const vec3& axis, double angleRad) { +Quaternion Quaternion::fromAxisAngle(const vec3& axis, double angleRad) noexcept { const double coss = std::cos(0.5 * angleRad); const double sins = std::sin(0.5 * angleRad); - - Quaternion q; - q.x = sins * axis[0]; - q.y = sins * axis[1]; - q.z = sins * axis[2]; - q.w = coss; - return q; + return {sins * axis[0], sins * axis[1], sins * axis[2], coss}; } -Quaternion Quaternion::fromEulerAngles(double x, double y, double z) { - double cz = std::cos(z * 0.5); - double sz = std::sin(z * 0.5); - double cy = std::cos(y * 0.5); - double sy = std::sin(y * 0.5); - double cx = std::cos(x * 0.5); - double sx = std::sin(x * 0.5); +Quaternion Quaternion::fromEulerAngles(double x, double y, double z) noexcept { + const double cz = std::cos(z * 0.5); + const double sz = std::sin(z * 0.5); + const double cy = std::cos(y * 0.5); + const double sy = std::sin(y * 0.5); + const double cx = std::cos(x * 0.5); + const double sx = std::sin(x * 0.5); - Quaternion q; - q.x = sx * cy * cz - cx * sy * sz; - q.y = cx * sy * cz + sx * cy * sz; - q.z = cx * cy * sz - sx * sy * cz; - q.w = cx * cy * cz + sx * sy * sz; - - return q; + return {sx * cy * cz - cx * sy * sz, + cx * sy * cz + sx * cy * sz, + cx * cy * sz - sx * sy * cz, + cx * cy * cz + sx * sy * sz}; } -Quaternion Quaternion::multiply(const Quaternion& o) const { - Quaternion q; - q.w = w * o.w - x * o.x - y * o.y - z * o.z; - q.x = w * o.x + x * o.w + y * o.z - z * o.y; - q.y = w * o.y + y * o.w + z * o.x - x * o.z; - q.z = w * o.z + z * o.w + x * o.y - y * o.x; - return q; +Quaternion Quaternion::multiply(const Quaternion& o) const noexcept { + return {w * o.x + x * o.w + y * o.z - z * o.y, + w * o.y + y * o.w + z * o.x - x * o.z, + w * o.z + z * o.w + x * o.y - y * o.x, + w * o.w - x * o.x - y * o.y - z * o.z}; } -double Quaternion::length() const { +double Quaternion::length() const noexcept { return std::sqrt(x * x + y * y + z * z + w * w); } -vec3 Quaternion::transform(const vec3& v) const { +vec3 Quaternion::transform(const vec3& v) const noexcept { const Quaternion src = {v[0], v[1], v[2], 0.0}; const Quaternion res = multiply(src).multiply(conjugate()); return {res.x, res.y, res.z}; } -mat4 Quaternion::toRotationMatrix() const { +mat4 Quaternion::toRotationMatrix() const noexcept { mat4 mat; const double tx = 2.0 * x; @@ -100,12 +89,12 @@ mat4 Quaternion::toRotationMatrix() const { return mat; } -bool operator!=(const Quaternion& a, const Quaternion& b) { +bool operator!=(const Quaternion& a, const Quaternion& b) noexcept { return !(a == b); } -bool operator==(const Quaternion& a, const Quaternion& b) { +bool operator==(const Quaternion& a, const Quaternion& b) noexcept { return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; } -} // namespace mbgl \ No newline at end of file +} // namespace mbgl diff --git a/src/mbgl/util/quaternion.hpp b/src/mbgl/util/quaternion.hpp index 43c051f8e..37ff71501 100644 --- a/src/mbgl/util/quaternion.hpp +++ b/src/mbgl/util/quaternion.hpp @@ -13,30 +13,30 @@ struct Quaternion { }; }; - Quaternion() + Quaternion() noexcept : Quaternion(0.0, 0.0, 0.0, 0.0) {} - Quaternion(double x_, double y_, double z_, double w_) + Quaternion(double x_, double y_, double z_, double w_) noexcept : x(x_), y(y_), z(z_), w(w_) {} - Quaternion(const vec4& vec) + Quaternion(const vec4& vec) noexcept : m(vec) {} - Quaternion conjugate() const; - Quaternion normalized() const; - Quaternion multiply(const Quaternion& o) const; - double length() const; - vec3 transform(const vec3& v) const; - mat4 toRotationMatrix() const; + Quaternion conjugate() const noexcept; + Quaternion normalized() const noexcept; + Quaternion multiply(const Quaternion& o) const noexcept; + double length() const noexcept; + vec3 transform(const vec3& v) const noexcept; + mat4 toRotationMatrix() const noexcept; - static Quaternion fromAxisAngle(const vec3& axis, double angleRad); - static Quaternion fromEulerAngles(double x, double y, double z); + static Quaternion fromAxisAngle(const vec3& axis, double angleRad) noexcept; + static Quaternion fromEulerAngles(double x, double y, double z) noexcept; static Quaternion identity; }; -bool operator==(const Quaternion&, const Quaternion&); -bool operator!=(const Quaternion&, const Quaternion&); +bool operator==(const Quaternion&, const Quaternion&) noexcept; +bool operator!=(const Quaternion&, const Quaternion&) noexcept; } // namespace mbgl diff --git a/src/mbgl/util/tile_cover.cpp b/src/mbgl/util/tile_cover.cpp index 9186dcd47..0046a0dba 100644 --- a/src/mbgl/util/tile_cover.cpp +++ b/src/mbgl/util/tile_cover.cpp @@ -36,8 +36,8 @@ struct edge { // scan-line conversion void scanSpans(edge e0, edge e1, int32_t ymin, int32_t ymax, ScanLine& scanLine) { - double y0 = ::fmax(ymin, std::floor(e1.y0)); - double y1 = ::fmin(ymax, std::ceil(e1.y1)); + const double y0 = ::fmax(ymin, std::floor(e1.y0)); + const double y1 = ::fmin(ymax, std::ceil(e1.y1)); // sort edges by x-coordinate if ((e0.x0 == e1.x0 && e0.y0 == e1.y0) ? (e0.x0 + e1.dy / e0.dy * e0.dx < e1.x1) @@ -46,10 +46,10 @@ void scanSpans(edge e0, edge e1, int32_t ymin, int32_t ymax, ScanLine& scanLine) } // scan lines! - double m0 = e0.dx / e0.dy; - double m1 = e1.dx / e1.dy; - double d0 = e0.dx > 0; // use y + 1 to compute x0 - double d1 = e1.dx < 0; // use y + 1 to compute x1 + const double m0 = e0.dx / e0.dy; + const double m1 = e1.dx / e1.dy; + const double d0 = e0.dx > 0; // use y + 1 to compute x0 + const double d1 = e1.dx < 0; // use y + 1 to compute x1 for (double y = y0; y < y1; y++) { double x0 = m0 * ::fmax(0, ::fmin(e0.dy, y + d0 - e0.y0)) + e0.x0; double x1 = m1 * ::fmax(0, ::fmin(e1.dy, y + d1 - e1.y0)) + e1.x0; @@ -105,6 +105,9 @@ std::vector tileCover(const Point& tl, std::vector t; + // skip the first few allocations, assuming we usually end up with at least a few tiles + t.reserve(8); + auto scanLine = [&](int32_t x0, int32_t x1, int32_t y) { int32_t x; if (y >= 0 && y <= tiles) { @@ -124,7 +127,7 @@ std::vector tileCover(const Point& tl, scanTriangle(br, bl, tl, 0, tiles, scanLine); // Sort first by distance, then by x/y. - std::sort(t.begin(), t.end(), [](const ID& a, const ID& b) { + std::sort(t.begin(), t.end(), [](const ID& a, const ID& b) noexcept { return std::tie(a.sqDist, a.x, a.y) < std::tie(b.sqDist, b.x, b.y); }); @@ -142,7 +145,7 @@ std::vector tileCover(const Point& tl, } // namespace -int32_t coveringZoomLevel(double zoom, style::SourceType type, uint16_t size) { +int32_t coveringZoomLevel(double zoom, style::SourceType type, uint16_t size) noexcept { zoom += util::log2(util::tileSize_D / size); if (type == style::SourceType::Raster || type == style::SourceType::Video) { return static_cast(std::round(zoom)); @@ -174,10 +177,10 @@ std::vector tileCover(const TransformState& state, const uint8_t overscaledZoom = overscaledZ.value_or(z); const bool flippedY = state.getViewportMode() == ViewportMode::FlippedY; - auto centerPoint = + const auto centerPoint = TileCoordinate::fromScreenCoordinate(state, z, {state.getSize().width / 2.0, state.getSize().height / 2.0}).p; - vec3 centerCoord = {{centerPoint.x, centerPoint.y, 0.0}}; + const vec3 centerCoord = {{centerPoint.x, centerPoint.y, 0.0}}; const Frustum frustum = Frustum::fromInvProjMatrix(state.getInvProjectionMatrix(), worldSize, z, flippedY); @@ -253,14 +256,13 @@ std::vector tileCover(const TransformState& state, const uint32_t childY = (node.y << 1) + (i >> 1); // Create child node and push to the stack for traversal - Node child = node; + stack.emplace_back(node); + Node& child = stack.back(); child.aabb = node.aabb.quadrant(i); child.zoom = node.zoom + 1; child.x = childX; child.y = childY; - - stack.push_back(child); } } @@ -283,8 +285,8 @@ std::vector tileCover(const LatLngBounds& bounds_, uint8_t z) { return {}; } - LatLngBounds bounds = LatLngBounds::hull({std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west()}, - {std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east()}); + const LatLngBounds bounds = LatLngBounds::hull({std::max(bounds_.south(), -util::LATITUDE_MAX), bounds_.west()}, + {std::min(bounds_.north(), util::LATITUDE_MAX), bounds_.east()}); return tileCover(Projection::project(bounds.northwest(), z), Projection::project(bounds.northeast(), z), @@ -307,20 +309,20 @@ std::vector tileCover(const Geometry& geometry, uint8_t // Taken from https://github.com/mapbox/sphericalmercator#xyzbbox-zoom-tms_style-srs // Computes the projected tiles for the lower left and upper right points of the bounds // and uses that to compute the tile cover count -uint64_t tileCount(const LatLngBounds& bounds, uint8_t zoom) { +uint64_t tileCount(const LatLngBounds& bounds, uint8_t zoom) noexcept { if (zoom == 0) { return 1; } - auto sw = Projection::project(bounds.southwest(), zoom); - auto ne = Projection::project(bounds.northeast(), zoom); - auto maxTile = std::pow(2.0, zoom); - auto x1 = floor(sw.x); - auto x2 = ceil(ne.x) - 1; - auto y1 = util::clamp(floor(sw.y), 0.0, maxTile - 1); - auto y2 = util::clamp(floor(ne.y), 0.0, maxTile - 1); + const auto sw = Projection::project(bounds.southwest(), zoom); + const auto ne = Projection::project(bounds.northeast(), zoom); + const auto maxTile = std::pow(2.0, zoom); + const auto x1 = floor(sw.x); + const auto x2 = ceil(ne.x) - 1; + const auto y1 = util::clamp(floor(sw.y), 0.0, maxTile - 1); + const auto y2 = util::clamp(floor(ne.y), 0.0, maxTile - 1); - auto dx = x1 > x2 ? (maxTile - x1) + x2 : x2 - x1; - auto dy = y1 - y2; + const auto dx = x1 > x2 ? (maxTile - x1) + x2 : x2 - x1; + const auto dy = y1 - y2; return static_cast((dx + 1) * (dy + 1)); } @@ -342,12 +344,12 @@ TileCover::TileCover(const LatLngBounds& bounds_, uint8_t z) { bounds = LatLngBounds::world(); } - auto sw = Projection::project(bounds.southwest(), z); - auto ne = Projection::project(bounds.northeast(), z); - auto se = Projection::project(bounds.southeast(), z); - auto nw = Projection::project(bounds.northwest(), z); + const auto sw = Projection::project(bounds.southwest(), z); + const auto ne = Projection::project(bounds.northeast(), z); + const auto se = Projection::project(bounds.southeast(), z); + const auto nw = Projection::project(bounds.northwest(), z); - Polygon p({{sw, nw, ne, se, sw}}); + const Polygon p({{sw, nw, ne, se, sw}}); impl = std::make_unique(z, p, false); } diff --git a/src/mbgl/util/tile_cover.hpp b/src/mbgl/util/tile_cover.hpp index d3f8cbf04..972fdc5ed 100644 --- a/src/mbgl/util/tile_cover.hpp +++ b/src/mbgl/util/tile_cover.hpp @@ -31,7 +31,7 @@ private: std::unique_ptr impl; }; -int32_t coveringZoomLevel(double z, style::SourceType type, uint16_t tileSize); +int32_t coveringZoomLevel(double z, style::SourceType type, uint16_t tileSize) noexcept; std::vector tileCover(const TransformState&, uint8_t z, @@ -40,7 +40,7 @@ std::vector tileCover(const LatLngBounds&, uint8_t z); std::vector tileCover(const Geometry&, uint8_t z); // Compute only the count of tiles needed for tileCover -uint64_t tileCount(const LatLngBounds&, uint8_t z); +uint64_t tileCount(const LatLngBounds&, uint8_t z) noexcept; uint64_t tileCount(const Geometry&, uint8_t z); } // namespace util diff --git a/src/mbgl/util/tile_range.hpp b/src/mbgl/util/tile_range.hpp index 9f8da3596..9dfea38db 100644 --- a/src/mbgl/util/tile_range.hpp +++ b/src/mbgl/util/tile_range.hpp @@ -14,7 +14,7 @@ public: Range zoomRange; // Compute the range of tiles covered by the bounds at maxZoom. - static TileRange fromLatLngBounds(const LatLngBounds& bounds, uint8_t minZoom, uint8_t maxZoom) { + static TileRange fromLatLngBounds(const LatLngBounds& bounds, uint8_t minZoom, uint8_t maxZoom) noexcept { if (minZoom > maxZoom) { std::swap(minZoom, maxZoom); } @@ -33,9 +33,11 @@ public: } // Compute the range of tiles covered by the bounds. - static TileRange fromLatLngBounds(const LatLngBounds& bounds, uint8_t z) { return fromLatLngBounds(bounds, z, z); } + static TileRange fromLatLngBounds(const LatLngBounds& bounds, uint8_t z) noexcept { + return fromLatLngBounds(bounds, z, z); + } - bool contains(const CanonicalTileID& tileID) { + bool contains(const CanonicalTileID& tileID) noexcept { if (tileID.z <= zoomRange.max && tileID.z >= zoomRange.min) { if (tileID.z == 0) { return true; diff --git a/test/style/style_parser.test.cpp b/test/style/style_parser.test.cpp index 00c7abbf4..4acfce448 100644 --- a/test/style/style_parser.test.cpp +++ b/test/style/style_parser.test.cpp @@ -190,10 +190,11 @@ TEST(StyleParser, SpriteAsArrayMultiple) { TEST(StyleParser, FontStacks) { style::Parser parser; parser.parse(util::read_file("test/fixtures/style_parser/font_stacks.json")); - std::set expected; - expected.insert(FontStack({"a"})); - expected.insert(FontStack({"a", "b"})); - expected.insert(FontStack({"a", "b", "c"})); + std::set expected = { + {"a"}, + {"a", "b"}, + {"a", "b", "c"}, + }; std::set result = parser.fontStacks(); ASSERT_EQ(expected, result); }