diff --git a/CMakeLists.txt b/CMakeLists.txt index 077f1267..ca9e8c95 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,6 +51,7 @@ xo_export_cmake_config(${PROJECT_NAME} ${PROJECT_VERSION} ${PROJECT_NAME}Targets # ---------------------------------------------------------------- # dependencies +xo_headeronly_dependency(${SELF_LIB} xo_flatstring) #xo_headeronly_dependency(${SELF_LIB} randomgen) # etc.. diff --git a/cmake/xo_ratioConfig.cmake.in b/cmake/xo_ratioConfig.cmake.in index e5ee1778..b7a5a0a2 100644 --- a/cmake/xo_ratioConfig.cmake.in +++ b/cmake/xo_ratioConfig.cmake.in @@ -6,7 +6,7 @@ include(CMakeFindDependencyMacro) # must coordinate with xo_dependency() calls # in xo-reactor/src/reactor/CMakeLists.txt # -#find_dependency(reflect) +find_dependency(xo_flatstring) #find_dependency(subsys) #find_dependency(Eigen3) #find_dependency(webutil) diff --git a/include/xo/ratio/ratio.hpp b/include/xo/ratio/ratio.hpp index a7848518..a8f09e58 100644 --- a/include/xo/ratio/ratio.hpp +++ b/include/xo/ratio/ratio.hpp @@ -6,6 +6,7 @@ #pragma once #include "ratio_concept.hpp" +#include "xo/flatstring/flatstring.hpp" #include #include //#include @@ -196,7 +197,42 @@ namespace xo { * For example: to int or double **/ template - constexpr Repr to() const { return num_ / static_cast(den_); } + constexpr Repr to() const noexcept { return num_ / static_cast(den_); } + + /** @brief convert to short human-friendly flatstring representation + * + * Example: + * @code + * ratio(7,1).to_str<5>(); // "7" + * ratio(1,7).to_str<5>(); // "(1/7)" + * ratio(-1,7).to_str<10>(); // "(-1/7)" + * ratio(-1,7).to_str<5>(); // "(-1/" + * @endcode + **/ + template + constexpr flatstring to_str() const noexcept { + if (this->is_integer()) { + return flatstring::from_int(num_); + } else { + auto num_str = flatstring::from_int(num_); + auto den_str = flatstring::from_int(den_); + + /* tmp capacity will be about 2N+3 */ + auto tmp = flatstring_concat(flatstring("("), + num_str, + flatstring("/"), + den_str, + flatstring(")")); + + flatstring retval; + retval.assign(tmp); + + return retval; + } + } + + /** @brief negate operator **/ + constexpr ratio operator-() const { return ratio(-num_, den_); } /** @brief convert to representation using different integer types **/ template