| 1 |
/** |
| 2 |
* Search algorithms |
| 3 |
* @author Lobaskin Vasily |
| 4 |
* @data 31 March 2020 |
| 5 |
* @copyright Boost Software License, Version 1.0 |
| 6 |
*/ |
| 7 |
|
| 8 |
#include <type_traits> |
| 9 |
|
| 10 |
namespace network { |
| 11 |
namespace algorithm { |
| 12 |
|
| 13 |
template <typename ContainerT, class SequenceT, typename SplitterT, |
| 14 |
typename std::enable_if<std::is_fundamental<SplitterT>::value>::type |
| 15 |
* = nullptr> |
| 16 |
bool split(ContainerT &container, SequenceT const &str, SplitterT symbol) { |
| 17 |
using PartT = typename ContainerT::value_type; |
| 18 |
static_assert(std::is_same<typename SequenceT::value_type, SplitterT>::value, |
| 19 |
"Splitter type doesn't match sequence inner type"); |
| 20 |
|
| 21 |
std::size_t sequenceStart = 0; |
| 22 |
for (std::size_t i = 0, len = str.size(); i <= len; ++i) { |
| 23 |
if (str[i] != symbol && i != len) continue; |
| 24 |
|
| 25 |
std::size_t substrLen = i - sequenceStart; |
| 26 |
if (substrLen > 0) { |
| 27 |
PartT part{str.cbegin() + sequenceStart, str.cbegin() + i}; |
| 28 |
container.emplace_back(std::move(part)); |
| 29 |
} else { |
| 30 |
container.emplace_back(PartT{}); |
| 31 |
} |
| 32 |
sequenceStart = i + 1; |
| 33 |
} |
| 34 |
|
| 35 |
return true; |
| 36 |
} |
| 37 |
|
| 38 |
template <typename ContainerT, class SequenceT, typename SplitterT, |
| 39 |
typename std::enable_if<!std::is_fundamental<SplitterT>::value>::type |
| 40 |
* = nullptr> |
| 41 |
bool split(ContainerT &container, SequenceT const &str, SplitterT splitter) { |
| 42 |
using PartT = typename ContainerT::value_type; |
| 43 |
static_assert( |
| 44 |
std::is_same<typename ContainerT::value_type, std::string>::value, |
| 45 |
"Invalid container type, only string is supported"); |
| 46 |
|
| 47 |
bool isEqual = false; |
| 48 |
std::size_t sequenceLen = splitter.size(); |
| 49 |
std::size_t sequenceStart = 0; |
| 50 |
for (std::size_t i = 0, len = str.size(); i <= len; ++i) { |
| 51 |
isEqual = true; |
| 52 |
for (std::size_t j = 0; j < sequenceLen; ++j) { |
| 53 |
if (str[i + j] != splitter[j]) { |
| 54 |
isEqual = false; |
| 55 |
break; |
| 56 |
} |
| 57 |
} |
| 58 |
if (!isEqual && i != len) continue; |
| 59 |
|
| 60 |
std::size_t substrLen = i - sequenceStart; |
| 61 |
if (substrLen > 0) { |
| 62 |
PartT part{str.cbegin() + sequenceStart, str.cbegin() + i}; |
| 63 |
container.emplace_back(std::move(part)); |
| 64 |
} else { |
| 65 |
container.emplace_back(PartT{}); |
| 66 |
} |
| 67 |
sequenceStart = i + sequenceLen; |
| 68 |
i += sequenceLen - 1; |
| 69 |
} |
| 70 |
|
| 71 |
return true; |
| 72 |
} |
| 73 |
|
| 74 |
} // namespace algorithm |
| 75 |
} // namespace network |