87 lines
2.2 KiB
C++
87 lines
2.2 KiB
C++
#include "echoion/standalone/MessageChunker.hpp"
|
|
|
|
#include <string_view>
|
|
|
|
namespace Echoion::Standalone
|
|
{
|
|
std::vector<std::string> chunkMessage(const std::string& message,
|
|
std::size_t limit)
|
|
{
|
|
if (limit == 0 || message.empty()) {
|
|
return message.empty() ? std::vector<std::string>{}
|
|
: std::vector<std::string>{message};
|
|
}
|
|
if (message.size() <= limit) {
|
|
return {message};
|
|
}
|
|
|
|
const auto isBlank = [](const std::string& value) {
|
|
return value.find_first_not_of(" \t\r\n") == std::string::npos;
|
|
};
|
|
std::vector<std::string> chunks;
|
|
std::string current;
|
|
int detailsDepth = 0;
|
|
const auto flush = [&] {
|
|
if (!current.empty() && !isBlank(current)) {
|
|
chunks.push_back(current);
|
|
}
|
|
current.clear();
|
|
};
|
|
|
|
std::size_t position = 0;
|
|
while (position < message.size()) {
|
|
const auto newline = message.find('\n', position);
|
|
std::string line = newline == std::string::npos
|
|
? message.substr(position)
|
|
: message.substr(position, newline - position + 1);
|
|
position = newline == std::string::npos ? message.size() : newline + 1;
|
|
|
|
const bool opens = line.starts_with(":::details");
|
|
std::string_view trimmed = line;
|
|
while (!trimmed.empty() &&
|
|
(trimmed.back() == '\n' || trimmed.back() == '\r' ||
|
|
trimmed.back() == ' ' || trimmed.back() == '\t')) {
|
|
trimmed.remove_suffix(1);
|
|
}
|
|
const bool closes = trimmed == ":::";
|
|
|
|
if (detailsDepth == 0 && !current.empty() &&
|
|
(opens || current.size() + line.size() > limit)) {
|
|
flush();
|
|
}
|
|
|
|
// A details block must remain syntactically complete even if it is
|
|
// longer than the preferred message limit. Normal lines are split at
|
|
// a UTF-8 code-point boundary.
|
|
if (detailsDepth == 0 && !opens) {
|
|
while (line.size() > limit) {
|
|
std::size_t cut = limit;
|
|
while (cut > 0 &&
|
|
(static_cast<unsigned char>(line[cut]) & 0xc0) == 0x80) {
|
|
--cut;
|
|
}
|
|
if (cut == 0) {
|
|
cut = limit;
|
|
}
|
|
flush();
|
|
auto piece = line.substr(0, cut);
|
|
if (!isBlank(piece)) {
|
|
chunks.push_back(std::move(piece));
|
|
}
|
|
line.erase(0, cut);
|
|
}
|
|
}
|
|
|
|
current += line;
|
|
if (opens) {
|
|
++detailsDepth;
|
|
}
|
|
if (closes && detailsDepth > 0) {
|
|
--detailsDepth;
|
|
}
|
|
}
|
|
flush();
|
|
return chunks;
|
|
}
|
|
}
|