Example
std::string resize_and_overwrite(const std::string& str, std::size_t size) {
std::string ret;
const auto step = std::size(str);
ret.resize_and_overwrite(step * size, [&](auto* buf, auto n) {
for (auto i = 0u; i < size; i++) {
std::memcpy(buf + i * step, std::data(str), step);
}
return step * size;
});
return ret;
}
int main(){
std::cout << resize_and_overwrite("quantlab", 4); // prints quantlabquantlabquantlabquantlab
}
Puzzle
- Can you implement
change
function which appliesresize_and_overwrite
string's routine to satisfy tests?
auto change(...) -> void ; // TODO
int main() {
using namespace boost::ut;
"resize and overwrite"_test = [] {
should("not change empty string") = [] {
std::string s;
auto data = std::data(s);
change(s);
expect(std::empty(s) >> fatal);
expect(s[0] == 0_c);
expect(std::data(s) == data);
};
should("change trading to quantlab") = [] {
std::string s = "trading";
change(s);
expect(s == "quantlab");
expect((std::size(s) == 8_u) >> fatal);
expect(s.capacity() >= 100_i);
expect(s[8] == 0_c);
};
};
}
Solutions
auto change(std::string& s) -> void {
if (std::empty(s)) { return; }
s.resize_and_overwrite(100, [](char* buf, std::size_t n) -> std::size_t {
constexpr std::string_view ql{"quantlab"};
auto end_ptr = std::copy(std::cbegin(ql), std::cend(ql), buf);
*end_ptr = 0;
return end_ptr - buf;
});
}
constexpr auto change(std::string& str) -> void {
if (std::empty(str)) {
return;
}
str.resize_and_overwrite(100, [](char* data,
[[maybe_unused]] std::size_t count) {
std::ignore = std::copy(std::cbegin(configuration::desired_string),
std::cend(configuration::desired_string), data);
return std::size(configuration::desired_string);
});
}
void change(std::string &s) {
if (std::empty(s)) return;
s.resize_and_overwrite(100, [] (char *buf, size_t) {
constexpr auto &value = "quantlab";
constexpr auto size = sizeof(value) - 1;
std::memcpy(buf, value, size);
return size;
});
}
void change(auto& s){
if(s == "trading"){
s.resize_and_overwrite(100, [](char * c, std::size_t count){
std::memcpy(c, "quantlabaa", 10);
return 8;
});
}
} ; // TODO
auto change(std::string& s) -> void
{
if(not s.empty())
{
std::string q = "quantlab";
s.resize_and_overwrite(q.size()*14, [&](auto* buf, auto n) {
std::memcpy(buf, std::data(q), q.size());
return q.size();
});
}
}
constexpr auto change = [](auto& str) {
if (std::empty(str)) {
str.resize_and_overwrite(0, [](auto...) -> std::size_t { return {}; });
} else {
str.resize_and_overwrite(100, [](auto* data, auto n) {
constexpr std::string_view quantlab = "quantlab";
std::copy(std::cbegin(quantlab), std::cend(quantlab), data);
return std::size(quantlab);
});
}
};