Skip to content

Commit

Permalink
ini: Write \r\n instead of \n
Browse files Browse the repository at this point in the history
  • Loading branch information
glebm committed Nov 5, 2024
1 parent b170192 commit 1892f6a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
17 changes: 8 additions & 9 deletions Source/utils/ini.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -373,30 +373,29 @@ bool OrderByValueIndex(const std::pair<std::string, T> &a, const std::pair<std::
return a.second.index < b.second.index;
};

// Appends a possibly multi-line comment, converting \r\n to \n.
// Appends a possibly multi-line comment, converting \n to \r\n.
void AppendComment(std::string_view comment, std::string &out)
{
bool prevR = false;
for (const char c : comment) {
if (prevR) {
prevR = c != '\r';
out += c;
} else if (c == '\r') {
if (c == '\r') {
prevR = true;
} else {
out += c;
if (c == '\n' && !prevR) out += '\r';
prevR = false;
}
out += c;
}
}

void AppendSection(std::string_view sectionName, std::string &out)
{
out.append("[").append(sectionName).append("]\n");
out.append("[").append(sectionName).append("]\r\n");
}

void AppendKeyValue(std::string_view key, std::string_view value, std::string &out)
{
out.append(key).append("=").append(value).append("\n");
out.append(key).append("=").append(value).append("\r\n");
}

} // namespace
Expand All @@ -409,7 +408,7 @@ std::string Ini::serialize() const

std::vector<std::pair<std::string, ValuesData>> entries;
for (auto &[sectionName, section] : sections) {
if (!result.empty()) result += '\n';
if (!result.empty()) result.append("\r\n");
if (!section.comment.empty()) AppendComment(section.comment, result);
AppendSection(sectionName, result);
entries.assign(section.entries.begin(), section.entries.end());
Expand Down
18 changes: 17 additions & 1 deletion test/ini_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,22 @@ using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Field;

std::string ReplaceNewlines(std::string_view s)
{
std::string out;
bool prevR = false;
for (const char c : s) {
if (c == '\r') {
prevR = true;
} else {
if (c == '\n' && !prevR) out += '\r';
prevR = false;
}
out += c;
}
return out;
}

} // namespace

TEST(IniTest, BasicTest)
Expand Down Expand Up @@ -59,7 +75,7 @@ key = value
const std::vector<std::string> newMulti { "x", "y", "z" };
result->set("sectionA", "multi", newMulti);
result->set("sectionA", "float", 10.5F);
EXPECT_EQ(result->serialize(), std::string_view(R"(; Section A comment
EXPECT_EQ(result->serialize(), ReplaceNewlines(R"(; Section A comment
[sectionA]
key1=newValue
key2=value2
Expand Down

0 comments on commit 1892f6a

Please sign in to comment.