From fcce11249be00ca0c7f8c2e75938de4b3e5f26da Mon Sep 17 00:00:00 2001 From: tqcq <99722391+tqcq@users.noreply.github.com> Date: Mon, 4 Mar 2024 18:20:17 +0800 Subject: [PATCH] optimize StartsWith,EndsWith --- include/sled/apply.h | 58 ++++++++++++++++++++++++++++++++++++++++++++ src/strings/utils.cc | 15 +++--------- 2 files changed, 62 insertions(+), 11 deletions(-) create mode 100644 include/sled/apply.h diff --git a/include/sled/apply.h b/include/sled/apply.h new file mode 100644 index 0000000..11909a0 --- /dev/null +++ b/include/sled/apply.h @@ -0,0 +1,58 @@ +#pragma once +#ifndef SLED_APPLY_H +#define SLED_APPLY_H +#include +#include + +namespace sled { +namespace detail { +template +struct Sequence {}; + +template +struct MakeSeq : MakeSeq {}; + +template +struct MakeSeq<0, Seq...> { + using type = Sequence; +}; + +template +ReturnT +ApplyImpl(const Func &func, const Tuple &tuple, const Sequence &) +{ + return std::bind(func, std::get(tuple)...)(); +} + +struct VoidTag {}; + +}// namespace detail + +template::value, ReturnT>::type + * = nullptr> +ReturnT +apply(const Func &func, const Tuple &tuple) +{ + return detail::ApplyImpl( + func, tuple, + typename detail::MakeSeq::value>::type()); +} + +template::value, + detail::VoidTag>::type * = nullptr> +void +apply(const Func &func, const Tuple &tuple) +{ + detail::ApplyImpl( + func, tuple, + typename detail::MakeSeq::value>::type()); +} + +}// namespace sled +#endif// SLED_APPLY_H diff --git a/src/strings/utils.cc b/src/strings/utils.cc index 50560bd..a5c981a 100644 --- a/src/strings/utils.cc +++ b/src/strings/utils.cc @@ -50,22 +50,15 @@ Trim(const std::string &str, const std::string &chars) std::string TrimLeft(const std::string &str, const std::string &chars) { - size_t start = 0; - while (start < str.size() - && chars.find_first_of(str[start]) != std::string::npos) { - ++start; - } - return str.substr(start); + size_t start = str.find_first_not_of(chars); + return start == std::string::npos ? "" : str.substr(start); } std::string TrimRight(const std::string &str, const std::string &chars) { - size_t end = str.size(); - while (end > 0 && chars.find_first_of(str[end - 1]) != std::string::npos) { - --end; - } - return str.substr(0, end); + size_t end = str.find_last_not_of(chars); + return end == std::string::npos ? "" : str.substr(0, end + 1); } bool