From b1c54532df55f5433e948c3bae1d5e5f1f006194 Mon Sep 17 00:00:00 2001 From: ToruNiina Date: Thu, 14 Feb 2019 15:48:05 +0900 Subject: [PATCH] feat: improve array serialization - make multiline array more clean - short-circuit for empty array --- toml/serializer.hpp | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/toml/serializer.hpp b/toml/serializer.hpp index 480fc3c..d42e45c 100644 --- a/toml/serializer.hpp +++ b/toml/serializer.hpp @@ -203,6 +203,10 @@ struct serializer } return token; } + if(v.empty()) + { + return std::string("[]"); + } // not an array of tables. normal array. first, try to make it inline. { @@ -216,11 +220,28 @@ struct serializer // if the length exceeds this->width_, print multiline array std::string token; + std::string current_line; token += "[\n"; for(const auto& item : v) { - token += toml::visit(*this, item); - token += ",\n"; + const auto next_elem = toml::visit(*this, item); + if(current_line.size() + next_elem.size() + 1 < this->width_) + { + current_line += next_elem; + current_line += ','; + } + else if(current_line.empty()) + { + // the next elem cannot be within the width. + token += next_elem; + token += ",\n"; + } + else + { + token += current_line; + token += ",\n"; + current_line = next_elem; + } } token += "]\n"; return token;