diff --git a/.gitignore b/.gitignore index 3dde80f..aa7dccb 100755 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ build .cache subprojects/* -!subprojects/nlohmann_json.wrap +!subprojects/catch2.wrap diff --git a/README.md b/README.md index bbe72b0..ff4c6c7 100755 --- a/README.md +++ b/README.md @@ -10,3 +10,4 @@ Тесты пишутся по необходимости и при наличии нужного настроения!!! Но вы всегда можете это исправить. :) + diff --git a/bin/main.cpp b/bin/main.cpp new file mode 100644 index 0000000..f9a7762 --- /dev/null +++ b/bin/main.cpp @@ -0,0 +1,10 @@ +#include + +#include "hack/patterns/ring_buffer.hpp" + +auto main(int argc, char *argv[]) -> int +{ + hack::patterns::ring_buffer rb; + for (int i = 1; i < 12; ++i) rb.put(i); + while(!rb.empty()) std::cout << rb.get().value() << std::endl; +} diff --git a/bin/meson.build b/bin/meson.build new file mode 100755 index 0000000..016e053 --- /dev/null +++ b/bin/meson.build @@ -0,0 +1,7 @@ +executable( + meson.project_name(), + 'main.cpp', + dependencies : deps, + cpp_args: args, + include_directories : inc +) diff --git a/examples/algorithms/main.cpp b/examples/algorithms/main.cpp deleted file mode 100644 index 2373317..0000000 --- a/examples/algorithms/main.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include -#include - -#include "hack/logger/logger.hpp" -#include "hack/algorithms/sort.hpp" - -auto main(int argc, char *argv[]) -> int -{ - {// ex: sort - std::vector v { 4, 4, 6, 1, 4, 3, 2 }; - std::forward_list l { 8, 7, 5, 9, 0, 1, 3, 2, 6, 4 }; - - hack::algorithms::sort(v); - hack::algorithms::sort(l); - - hack::log log; - log(v); - log(l); - } -} - - diff --git a/examples/concepts/main.cpp b/examples/concepts/main.cpp deleted file mode 100644 index e47baaa..0000000 --- a/examples/concepts/main.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include -#include - -#include "hack/logger/logger.hpp" -#include "hack/concepts/concepts.hpp" - -template -void test_map(const T& m) -{ - hack::log()("is map", m); -} - -template -void test_associative(const T& m) -{ - hack::log()("is associative", m); -} - -template -void test_unordered_set(const T& m) -{ - hack::log()("is unordered set", m); -} - -auto main(int argc, char *argv[]) -> int -{ - std::map m { { "a", 1 }, { "b", 2 } }; - test_map(m); - test_associative(m); - - auto t = std::make_tuple("a", 1, "b", 2); - test_associative(t); - - std::vector v { 1, 2, 3 }; - // test_associative(v); error !!! - - std::unordered_set us { 1, 2, 3 }; - test_unordered_set(us); - test_associative(us); -} - - diff --git a/examples/containers/main.cpp b/examples/containers/main.cpp deleted file mode 100644 index 7269744..0000000 --- a/examples/containers/main.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include - -#include "hack/logger/logger.hpp" -#include "hack/containers/containers.hpp" - -auto main(int argc, char *argv[]) -> int -{ - hack::log()("============================================================"); - hack::log()("container::vector_multiset"); - - {// ex: containers::vector - std::vector v; - hack::containers::vector::multiset(v, "asdf", "qwer", "zcv"); - hack::log()(v); - - hack::containers::vector::remove_at(v, 1); - hack::log()(v); - - hack::containers::vector::multiset(v, "aa", "bb", "cc"); - hack::log()(v); - - auto it = std::find(v.begin(), v.end(), "aa"); - hack::log()(*it); - hack::containers::vector::remove_at(v, it); - hack::log()(v); - } - - {// ex: containers::utils::count - std::vector v { "aa", "bb", "cc" }; - auto r = hack::containers::utils::count(v, "aa", "bb"); - hack::log()(r); - } - - {// ex: containers::set - std::set s; - hack::containers::set::multiset(s, 1, 2, 3); - hack::warn()("TODO: реализовать в log вывод set контейнера!"); - } -} - diff --git a/examples/iterators/main.cpp b/examples/iterators/main.cpp deleted file mode 100644 index fc3d4ba..0000000 --- a/examples/iterators/main.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include - -#include "hack/logger/logger.hpp" -#include "hack/iterators/associative_ostream_iterator.hpp" -#include "hack/concepts/concepts.hpp" - -template -static void print_t(const T& data) -{ - std::cout << "{"; - std::copy(data.cbegin(), data.cend(), hack::iterators::associative_ostream_iterator(data.size(), std::cout)); - std::cout << "}"; -} - -auto main(int argc, char *argv[]) -> int -{ - std::map m { { "a", 1 }, { "b", 2 } }; - - for (auto& [key, value] : m) - hack::log()(key, value); - - print_t(m); -} - - diff --git a/examples/logger/main.cpp b/examples/logger/main.cpp deleted file mode 100644 index 55a9163..0000000 --- a/examples/logger/main.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include -#include - -#include "hack/logger/logger.hpp" - -auto main(int argc, char *argv[]) -> int -{ - std::set s { 1, 2, 3 }; - hack::log()(s); - - std::vector v { 1, 2, 3 }; - hack::log()(v, s); - - std::unordered_set us { 1, 2, 3 }; - - hack::log()(v, s, us); -} diff --git a/examples/macros/main.cpp b/examples/macros/main.cpp deleted file mode 100644 index 501fb4a..0000000 --- a/examples/macros/main.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include - -#include "hack/logger/logger.hpp" -#include "hack/macros/macros.hpp" - -auto main(int argc, char *argv[]) -> int -{ - std::string s { MAKE_STR(test) }; - hack::log()(s); -} - - diff --git a/examples/memory/main.cpp b/examples/memory/main.cpp deleted file mode 100644 index b2cf024..0000000 --- a/examples/memory/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include - -#include "hack/logger/logger.hpp" -#include "hack/memory/make_ptr.hpp" - -auto main(int argc, char *argv[]) -> int -{ - auto a = hack::memory::make_unique(5); - hack::log()(*a); - - auto arr = hack::memory::make_unique(5); - arr[0] = 1; - hack::log()(arr[0]); -} - - diff --git a/examples/security/main.cpp b/examples/security/main.cpp deleted file mode 100644 index d7dca94..0000000 --- a/examples/security/main.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include - -#include "hack/logger/logger.hpp" -#include "hack/security/uuid.hpp" -#include "hack/security/is_link.hpp" -#include "hack/security/is_string.hpp" -#include "hack/security/validate_email.hpp" - -auto main(int argc, char *argv[]) -> int -{ - auto uuid = hack::security::generate_uuid(); - hack::log()(uuid); - - hack::log()(hack::security::validate_uuid(uuid)); - - std::string url = "https://google.com"; - hack::log()(hack::security::is_link(url)); - - hack::log()(hack::security::is_string::value); - - std::string email = "asdf@asdf.com"; - hack::log()(hack::security::validate_email(email));; -} - - diff --git a/examples/string/main.cpp b/examples/string/main.cpp deleted file mode 100644 index 32d60c6..0000000 --- a/examples/string/main.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include - -#include "hack/logger/logger.hpp" -#include "hack/string/string.hpp" -#include "hack/string/string_concat_helper.hpp" -#include "hack/string/utf8_len.hpp" - -auto main(int argc, char *argv[]) -> int -{ - {// ex: split string - std::string str { "asdf,qwer,zxcv" }; - std::string str_int { "1 2 3" }; - hack::string::v_str v = hack::string::split_str(str, ','); - auto v_int = hack::string::split_stoi(str_int, ' '); - hack::log log; - for (const auto& c : v) log(c); - for (const auto& c : v_int) log(c); - - std::string str_2 { "qqq,aaa:eee,ggg" }; - hack::string::v_str v_2 = hack::string::split_str(str_2, ",:"); - for (const auto& c : v_2) log(c); - } - - {// ex: string::str_concat - std::string name = "tro"; - std::string surname = "lolo"; - const auto full_name = hack::string::str_concat + name + ", " + surname; - hack::log()(full_name); - hack::log()(hack::string::str_concat + "super", + "string"); - } - - {// ex: utf8_size - std::string str = "hi hi"; - auto s = hack::string::utf8_len(str); - hack::log()(s); - - s = hack::string::utf8_len("asdf"); - hack::log()(s); - } -} - - diff --git a/examples/utils/main.cpp b/examples/utils/main.cpp deleted file mode 100644 index 04de5ec..0000000 --- a/examples/utils/main.cpp +++ /dev/null @@ -1,83 +0,0 @@ -#include "hack/logger/logger.hpp" -#include "hack/utils/utils.hpp" -#include "hack/utils/singleton.hpp" - -int f(int a) -{ - hack::log()("f implementatioln"); - return ++a; -} - -int plus(int a) -{ - return ++a; -} - -int minus(int a) -{ - return --a; -} - -struct counter_test -{ - counter_test() : id { ++hack::utils::counter::id } { } - int id; -}; - -struct counter_test_2 -{ - counter_test_2() : id { ++hack::utils::counter::id } { } - int id; -}; - -struct test_singleton : public hack::utils::singleton -{ - void print() - { - hack::log()("Print singleton"); - } -}; - -auto main(int argc, char *argv[]) -> int -{ - {// ex: utils::func_memory - int a = 12; - auto cach_f = hack::utils::func_memory(f); - hack::log()("result 1", cach_f(a)); - hack::log()("result 2", cach_f(a)); - } - - {// ex: utils::func_concat - int a = 1; - auto combine ( hack::utils::func_concat(plus, minus, plus, f) ); - hack::log("")("func_concat result: ", combine(a), a); - } - - // {// ex: utils::exec - // hack::log()(hack::utils::unix_cmd("ls")); - // hack::log()(hack::utils::unix_cmd("pwd")); - // auto t = hack::utils::unix_cmd("pwd"); - // hack::log::type_trace(t); - // } - - {// ex: counter - counter_test a, b, c; - counter_test_2 a1, b1, c1; - hack::log()(c.id); - hack::log()(c1.id); - } - - {// ex: case as string - switch(hack::utils::case_int("test")) - { - case hack::utils::case_int("test"): hack::log()("wow"); break; - case hack::utils::case_int("no_test"): hack::log()("ups"); break; - } - } - - {// ex: singleton - test_singleton::instance().print(); - } -} - - diff --git a/meson.build b/meson.build index 30ffad7..a166c21 100755 --- a/meson.build +++ b/meson.build @@ -31,8 +31,8 @@ args = [] inc = [] deps = [ dependency('uuid'), - subproject('nlohmann_json').get_variable('nlohmann_json_dep'), ] subdir('src') +subdir('bin') subdir('tests') diff --git a/run.sh b/run.sh index d0da7f1..ec9e74e 100755 --- a/run.sh +++ b/run.sh @@ -4,16 +4,24 @@ PROJECT_NAME=$(basename $PWD) run() { command meson compile -C build - if [[ -z "$1" ]]; then - cd build - ./tests/$PROJECT_NAME - cd .. - else - meson test $1 -C build - fi + cd build + ./bin/$PROJECT_NAME + cd .. } -if [ -d "build" ]; then +# run test [name_test] +# example: run test pattrens +if [ $1 = "test" ]; then + echo "" + meson test $2 -C build + echo "" + awk '/^-------------------------------------------------------------------------------/{flag=1} /===============================================================================/{flag=0} flag' ./build/meson-logs/testlog.txt +elif [ $1 = "tests" ]; then + echo "" + meson test -C build + echo "" + # awk '/^-------------------------------------------------------------------------------/{flag=1} /===============================================================================/{flag=0} flag' ./build/meson-logs/testlog.txt +elif [ -d "build" ]; then run else command meson setup build diff --git a/src/hack/algorithms/sort.hpp b/src/hack/algorithms/sort.hpp deleted file mode 100644 index 51460ed..0000000 --- a/src/hack/algorithms/sort.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include - -namespace hack::algorithms -{ - // общая сортировка диапозонов, у кого-то есть своя локалная сортировка, а у кого-то - // нет. А тут чтоб не реализовывать, есть общая. - template - void sort_imp(Range& r, long) - { - std::sort(std::begin(r), std::end(r)); - } - - template().sort())> - auto sort_imp(Range& r, int) -> void - { - r.sort(); - } - - template - void sort(Range& r) - { - sort_imp(r, 0); - } -} - - diff --git a/src/hack/concepts/concepts.hpp b/src/hack/concepts/concepts.hpp deleted file mode 100755 index cc408f8..0000000 --- a/src/hack/concepts/concepts.hpp +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace hack::concepts -{ - template - concept is_map = std::same_as> || - std::same_as>; - - template - concept is_tuple = requires (T t) { std::tuple_cat(t, std::make_tuple(1, "tuple")); }; - - template - concept is_set = std::same_as>; - - template - concept is_unordered_set = std::same_as>; - - template - concept is_forward_list = std::same_as>; - - template - concept is_string = std::is_convertible_v; - - template - concept is_sequence_container = std::same_as> || std::same_as> || (std::is_array_v && N > 0); - - template - concept is_associative_container = is_map || is_tuple || is_set || is_unordered_set; - - - template - concept not_defined = !std::enable_if_t || - is_sequence_container || - is_map || - is_tuple || - is_set || - is_unordered_set || - is_forward_list || - std::is_array() || - is_string), bool>() == true; - -} diff --git a/src/hack/containers/containers.hpp b/src/hack/containers/containers.hpp deleted file mode 100644 index 8f854fd..0000000 --- a/src/hack/containers/containers.hpp +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include "vector.hpp" -#include "utils.hpp" -#include "set.hpp" diff --git a/src/hack/containers/set.hpp b/src/hack/containers/set.hpp deleted file mode 100755 index a65ca69..0000000 --- a/src/hack/containers/set.hpp +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -namespace hack::containers::set -{ - // множественная вставка элементов - template - void multiset(Range& r, Args... args) - { - (r.insert(args), ...); - } -} diff --git a/src/hack/containers/utils.hpp b/src/hack/containers/utils.hpp deleted file mode 100755 index 5a5aac2..0000000 --- a/src/hack/containers/utils.hpp +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include - -namespace hack::containers::utils -{ - // подсчитывает кол-во присутствующих элементов в диапозоне - template - int count(Range r, Args... args) - { - return (std::count(std::cbegin(r), std::cend(r), args) + ...); - } -} diff --git a/src/hack/containers/vector.hpp b/src/hack/containers/vector.hpp deleted file mode 100755 index d987fec..0000000 --- a/src/hack/containers/vector.hpp +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once - -#include -#include - -namespace hack::containers::vector -{ - // множественная вставка элементов - template - void multiset(Range& r, Args... args) - { - constexpr std::size_t t = sizeof... (args); - r.reserve(t); - (r.emplace_back(std::forward(args)), ...); - } - - // удаление элемента вектора по его индексу, если не важна сортировка - template - void remove_at(std::vector& v, std::size_t idx) - { - if (idx < v.size()) - { - v[idx] = std::move(v.back()); - v.pop_back(); - } - } - - // удаление элемента вектора по его итератору, если не важна сортировка - template - void remove_at(std::vector& v, typename std::vector::iterator it) - { - if (it != v.end()) - { - *it = std::move(v.back()); - v.pop_back(); - } - } -} diff --git a/src/hack/exception/exception.hpp b/src/hack/exception/exception.hpp deleted file mode 100644 index 89a1811..0000000 --- a/src/hack/exception/exception.hpp +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -#include -#include - -#include "nlohmann/json.hpp" - -#define DEF_LINE() std::experimental::source_location::current().line() -#define DEF_LOCATION() std::experimental::source_location::current() - -#include "hack/view/color.hpp" -#include "hack/logger/logger.hpp" -#include "hack/utils/json_converter.hpp" - -namespace hack -{ - using JSON = nlohmann::json; - - class exception : public utils::json_converter - { - public: - exception(const std::experimental::source_location loc = DEF_LOCATION()) : m_location { loc } {} - ~exception() = default; - - public: - void message(const std::string v) noexcept { m_message = v; } - void description(const std::string v) noexcept { m_description = v; } - void system_error(const std::exception& e) noexcept { m_system_error = e.what(); } - void service(const std::string v) noexcept { m_service = v; } - - template - void params(std::string key, Param value) { m_params[key] = value; } - - // если что-то не значительное, но в больших обемах, то можно использовать этот метод - // на выходе будет что-то типа { "arg_1" : 123, "arg_2" : "value" } - template - void variadic_params(Args... args) - { - int i = 0; - ([&] { m_params["arg_" + std::to_string(++i)] = args; }(), ...); - } - - template - void transaction(Transaction& tr) - { - m_params["transaction"] = tr.convert_to_json(); - tr.m_data.m_result["status"] = "error"; - tr.m_data.m_result["result"] = m_message; - } - - void log() - { - std::cout << view::color::bold << view::color::red <<"["+m_service+"] " << view::color::reset - << m_location.file_name() << ":" - << view::color::italic << view::color::yellow << m_location.function_name() << "()" << view::color::reset - << view::color::bold << view::color::blue << "[" << m_location.line() << "]" << view::color::reset << ": " - << m_message << std::endl; - - if (!m_description.empty()) - std::cout << view::color::bold << view::color::red <<"["+m_service+"] " << view::color::reset - << m_location.file_name() << ":" - << view::color::italic << view::color::yellow << m_location.function_name() << "()" << view::color::reset - << view::color::bold << view::color::blue << "[" << m_location.line() << "]" << view::color::reset << ": " - << m_description << std::endl; - - if (!m_system_error.empty()) - std::cout << view::color::bold << view::color::red <<"["+m_service+"] " << view::color::reset - << m_location.file_name() << ":" - << view::color::italic << view::color::yellow << m_location.function_name() << "()" << view::color::reset - << view::color::bold << view::color::blue << "[" << m_location.line() << "]" << view::color::reset << ": " - << m_system_error << std::endl; - } - - JSON convert_to_json() override - { - JSON j; - j["description"] = m_description; - j["system_error"] = m_system_error; - j["location"] = m_location.file_name(); - j["function_name"] = m_location.function_name(); - j["message"] = m_message; - j["service"] = m_service; - j["params"] = m_params; - - return j; - } - - private: - std::string m_message { "no valid data" }; - std::string m_description; - std::string m_system_error; - std::string m_service; - std::experimental::source_location m_location; - JSON m_params; - }; -} diff --git a/src/hack/iterators/associative_ostream_iterator.hpp b/src/hack/iterators/associative_ostream_iterator.hpp deleted file mode 100755 index 223d19a..0000000 --- a/src/hack/iterators/associative_ostream_iterator.hpp +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include - -namespace hack::iterators -{ - template - class associative_ostream_iterator - { - using iterator_category = std::output_iterator_tag; - using traits = std::char_traits; - using ostream_type = std::basic_ostream; - - private: - std::basic_ostream* os_; - const std::string devider_ = ", "; - std::size_t size_; - - public: - associative_ostream_iterator(std::size_t size, ostream_type& os) : os_ { &os }, size_ { size } { } - - auto& operator=(const T& item) - { - --size_; - const auto& [key, value] = item; - *os_ << "{ " << key << ":" << value << " }" << (size_ != 0 ? devider_ : ""); - return *this; - } - - auto& operator*() - { - return *this; - } - - auto& operator++() - { - return *this; - } - }; -} diff --git a/src/hack/iterators/sequence_ostream_iterator.hpp b/src/hack/iterators/sequence_ostream_iterator.hpp deleted file mode 100755 index afe78da..0000000 --- a/src/hack/iterators/sequence_ostream_iterator.hpp +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include - -namespace hack::iterators -{ - template - class sequence_ostream_iterator - { - using iterator_category = std::output_iterator_tag; - using traits = std::char_traits; - using ostream_type = std::basic_ostream; - - private: - std::basic_ostream* os_; - std::string devider_ = ", "; - std::size_t size_; - - public: - sequence_ostream_iterator(std::size_t size, ostream_type& os) : os_ { &os }, size_ { size } { } - - auto& operator=(T const& item) - { - --size_; - *os_ << item << (size_ != 0 ? devider_ : ""); - return *this; - } - - auto& operator*() - { - return *this; - } - - auto& operator++() - { - return *this; - } - }; -} diff --git a/src/hack/logger/logger.hpp b/src/hack/logger/logger.hpp deleted file mode 100755 index 93cd93e..0000000 --- a/src/hack/logger/logger.hpp +++ /dev/null @@ -1,224 +0,0 @@ -#pragma once - -#include -#include - -// #include "boost/type_index.hpp" - -#include "hack/view/color.hpp" -#include "hack/concepts/concepts.hpp" -#include "hack/iterators/sequence_ostream_iterator.hpp" -#include "hack/iterators/associative_ostream_iterator.hpp" -#include "hack/math/matrix.hpp" - -namespace hack -{ - class log - { - public: - log(std::string devider_ = ", ", std::experimental::source_location location_ = std::experimental::source_location::current()) : location { location_ } - { - this->devider = devider_; - } - - log(log&) = delete; - log(log&&) = delete; - - public: - template - void operator() (const Args&... args) - { - count = sizeof...(Args); - prepare(make_type_view, location); - print(args...); - } - - // template - // static void type_trace(const Args&... args) - // { - // std::cout << make_type_view << ": " << view::color::reset; - // count = sizeof...(Args); - // print(boost::typeindex::type_id().pretty_name()...); - // } - - private: - std::experimental::source_location location; - inline static int count = 0; - inline static std::string devider = " "; - - private: - template - void prepare(T t, U u) - { - std::cout << t - << u.file_name() << ":" << view::color::reset - << view::color::italic << view::color::yellow << u.function_name() << "()" << view::color::reset - << view::color::bold << view::color::blue << "[" << u.line() << "]" << view::color::reset << ": "; - } - - static void print() { std::cout << std::endl; } - - static std::ostream& make_type_view(std::ostream &os) - { - os << view::color::bold << view::color::green << "[ok]" << view::color::reset << view::color::green; - return os; - } - - template - static void print(const T& data, const Args&... args) - { - --count; - print_t(data); - print(args...); - } - - template - static void print_t(const T& data) - { - std::cout << data << (count != 0 ? devider : ""); - } - - template - static void print_t(const T& data) - { - std::cout << data << (count != 0 ? devider : ""); - } - - template - static void print_t(const T& data) - { - std::cout << "{ "; - std::copy(data.cbegin(), data.cend(), iterators::sequence_ostream_iterator(data.size(), std::cout)); - std::cout << " }" << (count != 0 ? devider : ""); - } - - template - static void print_t(const T& data) - { - std::cout << "{ "; - std::copy(data.cbegin(), data.cend(), iterators::sequence_ostream_iterator(data.size(), std::cout)); - std::cout << " }" << (count != 0 ? devider : ""); - } - - template - static void print_t(const T& data) - { - std::cout << "{ "; - std::copy(data.cbegin(), data.cend(), iterators::sequence_ostream_iterator(data.size(), std::cout)); - std::cout << " }" << (count != 0 ? devider : ""); - } - - template - static void print_t(const T& data) - { - std::cout << "{ "; - std::copy(data.cbegin(), data.cend(), iterators::sequence_ostream_iterator(std::distance(data.cbegin(), data.cend()), std::cout)); - std::cout << " }" << (count != 0 ? devider : ""); - } - - template - static void print_t(const T& data) - { - std::cout << "{"; - std::copy(data.begin(), data.cend(), iterators::associative_ostream_iterator(data.size(), std::cout)); - std::cout << "}" << (count != 0 ? devider : ""); - } - - template - static void print_t(const T& data) - { - print_t(data, std::make_index_sequence::value>{}); - } - - template - static void print_t(const T& data, std::index_sequence) - { - std::cout << "{ "; - ((std::cout << std::get(data) << (idx != std::tuple_size::value - 1 ? devider : "")), ...); - std::cout << " }" << (count != 0 ? devider : ""); - } - - template - static void print_t(const matrix& data) - { - std::size_t index = data.size(); - for (auto& r : data) - { - --index; - std::cout << "{ "; - print_t(std::get(r)); - std::cout << " }" << (index != 0 ? ", " : ""); - } - } - - template - static void print_t(const T& data) - { - std::cout << data << (count != 0 ? devider : ""); - } - - friend class warn; - friend class error; - }; - - class warn : public log - { - public: - warn(std::string devider_ = ", ", std::experimental::source_location location_ = std::experimental::source_location::current()) : location { location_ } - { - this->devider = devider_; - } - - warn(warn&) = delete; - warn(warn&&) = delete; - - public: - template - void operator() (const Args&... args) - { - prepare(make_type_view, location); - count = sizeof...(Args); - print(args...); - } - - private: - std::experimental::source_location location; - - private: - static std::ostream& make_type_view(std::ostream &os) - { - os << view::color::bold << view::color::yellow << "[WARN]" << view::color::reset << view::color::yellow; - return os; - } - }; - - class error : public log - { - public: - error(std::string devider_ = ", ", std::experimental::source_location location_ = std::experimental::source_location::current()) : location { location_ } - { - this->devider = devider_; - } - error(error&) = delete; - error(error&&) = delete; - - public: - template - void operator() (const Args&... args) - { - prepare(make_type_view, location); - count = sizeof...(Args); - print(args...); - } - - private: - std::experimental::source_location location; - - private: - static std::ostream& make_type_view(std::ostream &os) - { - os << view::color::bold << view::color::red << "[ERROR]" << view::color::reset << view::color::red; - return os; - } - }; -} diff --git a/src/hack/macros/macros.hpp b/src/hack/macros/macros.hpp deleted file mode 100644 index 9dea60a..0000000 --- a/src/hack/macros/macros.hpp +++ /dev/null @@ -1,3 +0,0 @@ -#define MAKE_STR2(x) #x -#define MAKE_STR(x) MAKE_STR2(x) - diff --git a/src/hack/math/matrix.hpp b/src/hack/math/matrix.hpp deleted file mode 100755 index 1d97c33..0000000 --- a/src/hack/math/matrix.hpp +++ /dev/null @@ -1,165 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -namespace hack::matrix_utils -{ - template - struct generate_tuple - { - using type = decltype(std::tuple_cat(typename generate_tuple::type{}, std::make_tuple(T{}))); - }; - - template - struct generate_tuple - { - using type = std::tuple; - }; - - template - class proxy - { - using next_index_t = decltype(std::tuple_cat(index_t{}, std::make_tuple(std::size_t{}))); - - public: - proxy(const std::weak_ptr& local_storage, const index_t& index) : local_storage_ { local_storage }, index_ { index } {}; - - auto operator[](std::size_t index) const - { - return proxy{ local_storage_, std::tuple_cat(index_, std::make_tuple(index)) }; - } - - auto& operator=(const T& value) - { - std::shared_ptr(local_storage_)->set_value(index_, value); - return *this; - } - - operator T() const - { - return std::shared_ptr(local_storage_)->get_value(index_); - } - - private: - std::weak_ptr local_storage_; - index_t index_; - }; -} - -namespace hack -{ - template - auto subtuple_s(const std::tuple& t, std::index_sequence) - { - return std::make_tuple(std::get(t)...); - } - - template - auto subtuple(const std::tuple& t) - { - return subtuple_s(t, std::make_index_sequence()); - } - - template - class matrix - { - using index_t = typename matrix_utils::generate_tuple::type; - using vector_t = decltype(std::tuple_cat(index_t{}, std::make_tuple(T{}))); - using index_data_t = std::vector; - - public: - matrix() noexcept : local_storage_ { new index_data{} } { } - matrix(std::initializer_list l) noexcept : local_storage_ { new index_data{} } - { - local_storage_->values.insert(local_storage_->values.end(), l.begin(), l.end()); - } - matrix(matrix& mt) noexcept : local_storage_ { mt.local_storage_ } { } - matrix(matrix&& mt) noexcept : local_storage_ { mt.local_storage_ } { } - - matrix& operator=(matrix&& mt) - { - if (this == &mt) return *this; - local_storage_.reset(); - local_storage_ = mt.local_storage_; - return *this; - } - - matrix& operator=(const matrix& mt) - { - if (this == &mt) return *this; - local_storage_ = mt.local_storage_; - return *this; - } - - auto operator[](std::size_t index) - { - return matrix_utils::proxy>{ local_storage_, std::make_tuple(index) }; - } - - int size() const - { - return local_storage_->values.size(); - } - - auto begin() noexcept - { - return local_storage_->values.begin(); - } - - auto begin() const noexcept - { - return local_storage_->values.begin(); - } - - auto end() noexcept - { - return local_storage_->values.end(); - } - - auto end() const noexcept - { - return local_storage_->values.end(); - } - - auto cbegin() const noexcept - { - return local_storage_->values.cbegin(); - } - - auto cend() const noexcept - { - return local_storage_->values.cend(); - } - - private: - struct index_data - { - void set_value(const index_t& index, const T& v) - { - auto value = std::tuple_cat(index, std::make_tuple(v)); - values.push_back(value); - } - - auto get_value(const index_t& index) - { - auto it = std::find_if(values.begin(), values.end(), [&](auto a) { return subtuple(a) == index; }); - return std::get(*it); - } - - index_data_t values; - }; - - private: - std::shared_ptr local_storage_; - }; - - template - bool operator==(const matrix& lhs, const matrix& rhs) - { - return std::equal(lhs.cbegin(), lhs.cend(), rhs.cbegin()); - } -} diff --git a/src/hack/math/max.hpp b/src/hack/math/max.hpp deleted file mode 100755 index bac525e..0000000 --- a/src/hack/math/max.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include -#include - -namespace hack -{ - // std::common_type_t - делает сравнение по правилу тенарного оператора - // и выводит низводящий возвращающий тип. Т.е. если в качестве одного из - // параметров передалась ссылка, то произойдет низведление до типа ссылки - template> - inline RT max(T a, U b) - { - return std::max(a, b); - } -} diff --git a/src/hack/math/vector.hpp b/src/hack/math/vector.hpp deleted file mode 100755 index 578ae17..0000000 --- a/src/hack/math/vector.hpp +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace hack -{ - template - struct generate_tuple - { - using type = decltype(std::tuple_cat(std::make_tuple(T{}), typename generate_tuple::type{})); - }; - - template - struct generate_tuple - { - using type = std::tuple; - }; -} - -namespace hack -{ - template - class vector - { - using value_t = decltype(typename generate_tuple::type{}); - - public: - vector(Args... args) : value_ { args... } - { - if (std::tuple_size{} < 2) throw std::out_of_range("You try make no valid vector!"); - } - vector& operator=(const vector& v) - { - if (this == &v) return *this; - value_ = v.value_; - return *this; - } - - public: - value_t get_value() { return value_; }; - - auto x() const - { - return std::get<0>(value_); - } - - auto y() const - { - return std::get<1>(value_); - } - - auto z() const - { - if (std::tuple_size{} < 3) throw std::out_of_range("You try get no valid vector data!"); - return std::get<2>(value_); - } - - auto w() const - { - if (std::tuple_size{} < 4) throw std::out_of_range("You try get no valid vector data!"); - return std::get<3>(value_); - } - - auto length() - { - return std::sqrt(length_idx(std::make_index_sequence::value>{})); - } - - /* - dest.x = a.x + ((b.x - a.x) * t); - dest.y = a.y + ((b.y - a.y) * t); - */ - value_t lerp(vector& v, float t) - { - return lerp_idx(v.get_value(), t, std::make_index_sequence::value>{}); - } - - private: - template - auto length_idx(std::index_sequence) - { - return ((std::get(value_) * std::get(value_)) + ...); - } - - template - auto lerp_idx(const value_t& v, float t, std::index_sequence) - { - return std::make_tuple((std::get(value_) + (std::get(v) - std::get(value_)) * t)...); - } - - private: - value_t value_; - }; -} diff --git a/src/hack/memory/make_ptr.hpp b/src/hack/memory/make_ptr.hpp deleted file mode 100644 index 1f7da50..0000000 --- a/src/hack/memory/make_ptr.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include -#include - -#include "hack/concepts/concepts.hpp" - -namespace hack::memory -{ - // обсуждение тут: https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique - template - typename std::enable_if::value, std::unique_ptr>::type make_unique(Args &&...args) - { - return std::unique_ptr(new T(std::forward(args)...)); - } - - template - typename std::enable_if::value, std::unique_ptr>::type make_unique(std::size_t n) - { - using RT = std::remove_extent::type; - return std::unique_ptr(new RT[n]); - } -} diff --git a/src/hack/patterns/ring_buffer.hpp b/src/hack/patterns/ring_buffer.hpp new file mode 100644 index 0000000..50d5f55 --- /dev/null +++ b/src/hack/patterns/ring_buffer.hpp @@ -0,0 +1,114 @@ + +#include +#include +#include +#include + +namespace hack::patterns +{ + template + class ring_buffer + { + using MUTEX = std::lock_guard; + + public: + explicit ring_buffer() = default; + + public: + void put(T item) noexcept + { + MUTEX lock(m_mutex); + m_data[m_head] = item; + head_refresh(); + } + + // указываем размер, который хотим положить + // т.к. может нужно положить только часть из переданного массива + void put(const std::vector& source, std::size_t size) + { + for (std::size_t i = 0; i < size; ++i) + { + m_data[m_head] = source[i]; + head_refresh(); + } + } + + // если знаем, что нужно класть весь массив + void put(const std::vector& source) + { + MUTEX lock(m_mutex); + for (std::size_t i = 0; i < source.size(); ++i) + { + m_data[m_head] = source[i]; + head_refresh(); + } + } + + std::optional get() noexcept + { + MUTEX lock(m_mutex); + + if(empty()) return std::nullopt; + + auto val = m_data[m_tail]; + m_tail = (m_tail + 1) % BUFFER_SIZE; + m_full = false; + + return val; + } + + bool empty() noexcept + { + MUTEX lock(m_mutex); + return (!m_full && (m_head == m_tail)); + } + + size_t size() noexcept + { + MUTEX lock(m_mutex); + + std::size_t size; + if(!m_full) + size = (m_head >= m_tail) ? m_head - m_tail : BUFFER_SIZE - (m_tail - m_head); + else + size = BUFFER_SIZE; + + return size; + } + + void reset() noexcept + { + MUTEX lock(m_mutex); + m_head = m_tail; + m_full = false; + } + + bool full() const noexcept + { + return m_full; + } + + std::size_t capacity() const noexcept + { + return BUFFER_SIZE; + } + + private: + void head_refresh() + { + if (m_full) m_tail = (m_tail + 1) % BUFFER_SIZE; + m_head = (m_head + 1) % BUFFER_SIZE; + m_full = m_head == m_tail; + } + + private: + std::size_t m_head{ 0 }; + bool m_full{ false }; + std::size_t m_tail{ 0 }; + + private: + std::recursive_mutex m_mutex; + std::array m_data; + }; +} + diff --git a/src/hack/security/is_link.hpp b/src/hack/security/is_link.hpp deleted file mode 100755 index 2dc045f..0000000 --- a/src/hack/security/is_link.hpp +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace hack::security -{ - inline bool is_link(const std::string& s) - { - static const std::regex e("^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$", std::regex_constants::icase); - return std::regex_match (s, e); - } -} diff --git a/src/hack/security/is_string.hpp b/src/hack/security/is_string.hpp deleted file mode 100755 index fb1520f..0000000 --- a/src/hack/security/is_string.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace hack::security -{ - template - struct is_string : public std::disjunction>, - std::is_same>, - std::is_same>> {}; -} diff --git a/src/hack/security/uuid.hpp b/src/hack/security/uuid.hpp deleted file mode 100755 index 50c90fd..0000000 --- a/src/hack/security/uuid.hpp +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace hack::security -{ - inline std::string generate_uuid() - { - std::string uuid; - uuid_t uuid_obj; - uuid_generate_time_safe(uuid_obj); - char uuid_ch[UUID_STR_LEN]; - uuid_unparse_lower(uuid_obj, uuid_ch); - std::stringstream ss; - ss << uuid_ch; - ss >> uuid; - return uuid; - } - - inline bool validate_uuid(const std::string& s) - { - static const std::regex e("^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$", std::regex_constants::icase); - return std::regex_match(s, e); - } -} diff --git a/src/hack/security/validate_email.hpp b/src/hack/security/validate_email.hpp deleted file mode 100755 index 44a8e0d..0000000 --- a/src/hack/security/validate_email.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include -#include - -namespace hack::security -{ - inline bool validate_email(std::string& email) - { - const std::regex pattern("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+"); - return std::regex_match(email, pattern); - } -} diff --git a/src/hack/string/string.hpp b/src/hack/string/string.hpp deleted file mode 100755 index 00ae825..0000000 --- a/src/hack/string/string.hpp +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace hack::string -{ - using v_str = std::vector; - using v_int_str = std::vector; - - template - v_str split_str(const std::string& str, T t) - { - v_str v; - - std::string::size_type begin = 0; - std::string::size_type end = str.find_first_of(t); - - while(end != std::string::npos) - { - v.emplace_back(str.substr(begin, end - begin)); - begin = ++end; - end = str.find_first_of(t, begin); - } - v.emplace_back(str.substr(begin)); - - return v; - } - - template - v_int_str split_stoi(const std::string& str, T t) - { - v_int_str v; - - std::string::size_type begin = 0; - std::string::size_type end = str.find_first_of(t); - - while(end != std::string::npos) - { - v.emplace_back(std::stoi(str.substr(begin, end - begin))); - begin = ++end; - end = str.find_first_of(t, begin); - } - v.emplace_back(std::stoi(str.substr(begin))); - - return v; - } -} diff --git a/src/hack/string/string_concat_helper.hpp b/src/hack/string/string_concat_helper.hpp deleted file mode 100755 index d79aa8a..0000000 --- a/src/hack/string/string_concat_helper.hpp +++ /dev/null @@ -1,79 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace hack::string -{ - template - class string_concat_helper; - - template - class string_concat_helper - { - using string_part = string_concat_helper; - using string_long = string_concat_helper; - - private: - const String& data; - string_part tail; - - public: - string_concat_helper(const String& data_, string_part tail_) : data { data_ } , tail { tail_ } {} - - int size() const - { - return data.size() + tail.size(); - } - - template - void save(It end) const - { - const auto begin = end - data.size(); - std::copy(data.cbegin(), data.cend(), begin); - tail.save(begin); - } - - operator std::string() const - { - std::string result(size(), '\0'); - save(result.end()); - return result; - } - - string_long operator+(const std::string& other) const - { - return string_long(other, *this); - } - }; - - template <> - class string_concat_helper<> - { - using string_part = string_concat_helper; - - public: - int size() const - { - return 0; - } - - template - void save(It) const { } - - string_part operator+(const std::string& other) const - { - return string_part(other, *this); - } - }; - - template - Stream& operator<<(Stream& stream, string_concat_helper strings) - { - return stream << static_cast(strings); - } - - inline string_concat_helper<> str_concat; -} diff --git a/src/hack/string/utf8_len.hpp b/src/hack/string/utf8_len.hpp deleted file mode 100755 index 3fdfb6e..0000000 --- a/src/hack/string/utf8_len.hpp +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include -#include - -namespace hack::string -{ - // подсчет кол-ва символов - // В шестнадцатеричной системе счисления, 0xC0 представляет собой число 192. В бинарной системе это 11000000. - // Это число используется как маска для проверки байта в UTF-8 последовательности. И проверка в коде использует битовую операцию "И" (&) с маской 0xC0, чтобы проверить, является ли текущий - // байт началом UTF-8 последовательности. В UTF-8 первый байт символа, который не является частью - // многобайтовой последовательности, должен начинаться с битов 0 или 110 (в шестнадцатеричной системе это 0x00 или 0xC0). - // Проверка (c & 0xC0) != 0x80 используется для определения, является ли текущий байт продолжением UTF-8 многобайтовой последовательности. - // Валидные байты продолжения в UTF-8 должны начинаться с бита 10 (в бинарной системе это 0x80 или 10000000). - inline std::size_t utf8_len(const std::string& s) - { - std::size_t length = 0; - std::size_t i = 0; - - while (i < s.size()) - { - auto c = s[i]; - if ((c & 0xC0) != 0x80) - ++length; - ++i; - } - return length; - } -} - diff --git a/src/hack/utils/json_converter.hpp b/src/hack/utils/json_converter.hpp deleted file mode 100644 index 602980f..0000000 --- a/src/hack/utils/json_converter.hpp +++ /dev/null @@ -1,16 +0,0 @@ -// Данный интерфейс предназначен для более понятного и не меняющегося апи по преобразованию данных в json формат и обратно. -// Любой класс, который этого требует должен наследоваться от этого интерфейса чтобы не городить зоопарк разноименных для этого методов. -// Возможно в будущем я либо напишу рефлектор либо это будет вынесено в отдельную hack_cpp - -#pragma once - -namespace hack::utils -{ - template - struct json_converter - { - json_converter() = default; - virtual ~json_converter() = default; - virtual JSON convert_to_json() = 0; - }; -} diff --git a/src/hack/utils/singleton.hpp b/src/hack/utils/singleton.hpp deleted file mode 100644 index 94d15a2..0000000 --- a/src/hack/utils/singleton.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -namespace hack::utils -{ - struct no_copy - { - no_copy() = default; - no_copy(const no_copy&&) = delete; - no_copy operator=(const no_copy&&) = delete; - }; - - struct no_move - { - no_move() = default; - no_move(no_move&&) = delete; - no_move operator=(no_move&&) = delete; - }; - - template - struct singleton : public no_move, no_copy - { - static T& instance() - { - static T t; - return t; - } - }; -} diff --git a/src/hack/utils/utils.hpp b/src/hack/utils/utils.hpp deleted file mode 100755 index 97674c2..0000000 --- a/src/hack/utils/utils.hpp +++ /dev/null @@ -1,84 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace hack::utils -{ - // HERE - // это возможно нужно все перенести по отдельным файлам для понимания и расширения - template - auto func_memory(Result (*f)(Args...)) - { - std::map, Result> cache; - - return [f, cache](Args... args) mutable -> Result - { - const auto key = std::make_tuple(args...); - const auto cached = cache.find(key); - - if (cached == cache.end()) - { - auto result = f(args...); - cache[key] = result; - return result; - } - return cached->second; - }; - } - - // обединяет фукнкции в один вызов при одинаковых переменных - // все переменный захватываются по значению - template - auto func_concat(T t, Args... args) - { - if constexpr (sizeof...(args) > 0) - { - return [=](auto... params) - { - return t(func_concat(args...)(params...)); - }; - } - else - { - return [=](auto... params) - { - return t(params...); - }; - } - } - - // вызов unix команд из с++ кода - inline std::string unix_cmd(const std::string& cmd) - { - std::string result; - std::array buffer; - std::unique_ptr pipe(popen(cmd.c_str(), "r"), pclose); - - if (!pipe) throw std::runtime_error("bash cmd failed"); - - while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) - { - result += buffer.data(); - } - - return result; - } - - template - struct counter - { - inline static T id = value; - }; - - // this function can will use - // as switch wiht string - // switch(case_int("key")) - // case case_int("test"): hack::log()("wow!"); - // case case_int("no_test"): hack::log()("wow!"); - inline constexpr uint32_t case_int(const char* str, uint32_t hash = 2166136261UL) - { - return *str ? case_int(str + 1, (hash ^ *str) * 16777619ULL) : hash; - } -} diff --git a/src/hack/view/color.hpp b/src/hack/view/color.hpp deleted file mode 100755 index 3f3d37d..0000000 --- a/src/hack/view/color.hpp +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -#include - -namespace hack::view::color -{ - template - std::basic_ostream& reset(std::basic_ostream &os) - { - return os << "\033[0m"; - } - - template - std::basic_ostream& bold(std::basic_ostream &os) - { - return os << "\033[1m"; - } - - template - std::basic_ostream& italic(std::basic_ostream &os) - { - return os << "\033[3m"; - } - - template - std::basic_ostream& black(std::basic_ostream &os) - { - return os << "\033[30m"; - } - - template - std::basic_ostream& red(std::basic_ostream &os) - { - return os << "\033[31m"; - } - - template - std::basic_ostream& green(std::basic_ostream &os) - { - return os << "\033[32m"; - } - - template - std::basic_ostream& yellow(std::basic_ostream &os) - { - return os << "\033[33m"; - } - - template - std::basic_ostream& blue(std::basic_ostream &os) - { - return os << "\033[34m"; - } - - template - std::basic_ostream& magenta(std::basic_ostream &os) - { - return os << "\033[35m"; - } - - template - std::basic_ostream& cyan(std::basic_ostream &os) - { - return os << "\033[36m"; - } - - template - std::basic_ostream& white(std::basic_ostream &os) - { - return os << "\033[37m"; - } -} diff --git a/src/meson.build b/src/meson.build index 58d3c79..76e3c7d 100755 --- a/src/meson.build +++ b/src/meson.build @@ -1,44 +1,7 @@ inc += include_directories('.') headers = [ - 'hack/algorithms/sort.hpp', - - 'hack/concepts/concepts.hpp', - - 'hack/containers/containers.hpp', - 'hack/containers/set.hpp', - 'hack/containers/utils.hpp', - 'hack/containers/vector.hpp', - - 'hack/exception/exception.hpp', - - 'hack/iterators/associative_ostream_iterator.hpp', - 'hack/iterators/sequence_ostream_iterator.hpp', - - 'hack/logger/logger.hpp', - - 'hack/macros/macros.hpp', - - 'hack/math/matrix.hpp', - 'hack/math/max.hpp', - 'hack/math/vector.hpp', - - 'hack/memory/make_ptr.hpp', - - 'hack/security/is_link.hpp', - 'hack/security/is_string.hpp', - 'hack/security/uuid.hpp', - 'hack/security/validate_email.hpp', - - 'hack/string/string.hpp', - 'hack/string/string_concat_helper.hpp', - 'hack/string/utf8_len.hpp', - - 'hack/utils/singleton.hpp', - 'hack/utils/json_converter.hpp', - 'hack/utils/utils.hpp', - - 'hack/view/color.hpp', + 'hack/patterns/ring_buffer.hpp', ] sources = [] diff --git a/subprojects/catch2.wrap b/subprojects/catch2.wrap new file mode 100644 index 0000000..f9bf436 --- /dev/null +++ b/subprojects/catch2.wrap @@ -0,0 +1,11 @@ +[wrap-file] +directory = Catch2-3.7.1 +source_url = https://github.com/catchorg/Catch2/archive/v3.7.1.tar.gz +source_filename = Catch2-3.7.1.tar.gz +source_hash = c991b247a1a0d7bb9c39aa35faf0fe9e19764213f28ffba3109388e62ee0269c +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/catch2_3.7.1-1/Catch2-3.7.1.tar.gz +wrapdb_version = 3.7.1-1 + +[provide] +catch2 = catch2_dep +catch2-with-main = catch2_with_main_dep diff --git a/subprojects/nlohmann_json.wrap b/subprojects/nlohmann_json.wrap deleted file mode 100644 index bf5d700..0000000 --- a/subprojects/nlohmann_json.wrap +++ /dev/null @@ -1,10 +0,0 @@ -[wrap-file] -directory = nlohmann_json-3.11.2 -lead_directory_missing = true -source_url = https://github.com/nlohmann/json/releases/download/v3.11.2/include.zip -source_filename = nlohmann_json-3.11.2.zip -source_hash = e5c7a9f49a16814be27e4ed0ee900ecd0092bfb7dbfca65b5a421b774dccaaed -wrapdb_version = 3.11.2-1 - -[provide] -nlohmann_json = nlohmann_json_dep diff --git a/tests/base_test_fib.cpp b/tests/base_test_fib.cpp new file mode 100644 index 0000000..9dcb125 --- /dev/null +++ b/tests/base_test_fib.cpp @@ -0,0 +1,20 @@ +#include + +static int Factorial(int number) +{ + // return number <= 1 ? number : Factorial(number - 1) * number; // fail + return number <= 1 ? 1 : Factorial(number - 1) * number; // pass +} + +TEST_CASE("[base_test_fib] Factorial of 0 is 1 (fail)", "[single-file]") +{ + REQUIRE(Factorial(0) == 1); +} + +TEST_CASE("[base_test_fib] Factorials of 1 and higher are computed (pass)", "[single-file]") +{ + REQUIRE(Factorial(1) == 1); + REQUIRE(Factorial(2) == 2); + REQUIRE(Factorial(3) == 6); + REQUIRE(Factorial(10) == 3628800); +} diff --git a/tests/main.cpp b/tests/main.cpp deleted file mode 100644 index 7f91c9c..0000000 --- a/tests/main.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include - -#include "hack/exception/exception.hpp" - -auto main(int argc, char *argv[]) -> int -{ - hack::exception ex; - ex.service("test service"); - ex.log(); -} - - diff --git a/tests/meson.build b/tests/meson.build old mode 100755 new mode 100644 index 016e053..14e8b04 --- a/tests/meson.build +++ b/tests/meson.build @@ -1,7 +1,5 @@ -executable( - meson.project_name(), - 'main.cpp', - dependencies : deps, - cpp_args: args, - include_directories : inc -) +catch2_with_main_dep = dependency('catch2-with-main') +dep = [hack_dep, catch2_with_main_dep] + +test('patterns', executable('patterns', ['patterns/ring_buffer.cpp'], dependencies : dep)) + diff --git a/tests/patterns/ring_buffer.cpp b/tests/patterns/ring_buffer.cpp new file mode 100644 index 0000000..c4ce2d2 --- /dev/null +++ b/tests/patterns/ring_buffer.cpp @@ -0,0 +1,59 @@ +#include "catch2/catch_test_macros.hpp" +#include "hack/patterns/ring_buffer.hpp" + +TEST_CASE("patterns") +{ + SECTION("ring buffer") + { + // single value + hack::patterns::ring_buffer rb1; + REQUIRE(rb1.empty() == true); + + for (int i = 1; i < 13; ++i) rb1.put(i); + REQUIRE(rb1.empty() == false); + REQUIRE(rb1.size() == 10); + + while(!rb1.empty()) REQUIRE(rb1.get().has_value() == true); + REQUIRE(rb1.empty() == true); + REQUIRE(rb1.size() == 0); + + rb1.put(123); + rb1.put(23); + rb1.put(3); + REQUIRE(rb1.get().value() == 123); + REQUIRE(rb1.empty() == false); + REQUIRE(rb1.size() == 2); + + REQUIRE(rb1.get().value() == 23); + REQUIRE(rb1.empty() == false); + REQUIRE(rb1.size() == 1); + + rb1.reset(); + REQUIRE(rb1.empty() == true); + REQUIRE(rb1.size() == 0); + REQUIRE(rb1.get().has_value() == false); + + // vector value + std::vector v { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + hack::patterns::ring_buffer rb2; + REQUIRE(rb2.empty() == true); + + rb2.put(v); + REQUIRE(rb2.get().value() == 1); + REQUIRE(rb2.get().value() == 2); + + v.emplace_back(17); + rb2.put(v); + REQUIRE(rb2.get().value() == 2); + REQUIRE(rb2.get().value() == 3); + REQUIRE(rb2.get().value() == 4); + REQUIRE(rb2.get().value() == 5); + REQUIRE(rb2.get().value() == 6); + REQUIRE(rb2.get().value() == 7); + REQUIRE(rb2.get().value() == 8); + REQUIRE(rb2.get().value() == 9); + REQUIRE(rb2.get().value() == 10); + REQUIRE(rb2.get().value() == 17); + } +} +