From 592b165f35d8608b957ff05c4d8caacdbb501e95 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 17 Jun 2020 03:01:11 +1000 Subject: Fix problem where items without a section (e.g. the empty section) were added into whichever section they were created after. --- SimpleIni.h | 13 +++++++++++++ tests/Makefile | 2 +- tests/tests.vcxproj | 1 + tests/ts-bugfix.cpp | 26 ++++++++++++++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 tests/ts-bugfix.cpp diff --git a/SimpleIni.h b/SimpleIni.h index a09a6cc..843a73f 100644 --- a/SimpleIni.h +++ b/SimpleIni.h @@ -2424,6 +2424,19 @@ CSimpleIniTempl::Save( oSections.sort(typename Entry::LoadOrder()); #endif + // if there is an empty section name, then it must be written out first + // regardless of the load order + typename TNamesDepend::iterator is = oSections.begin(); + for (; is != oSections.end(); ++is) { + if (!*is->pItem) { + // move the empty section name to the front of the section list + if (is != oSections.begin()) { + oSections.splice(oSections.begin(), oSections, is, std::next(is)); + } + break; + } + } + // write the file comment if we have one bool bNeedNewLine = false; if (m_pFileComment) { diff --git a/tests/Makefile b/tests/Makefile index ae3082e..09049f7 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -3,7 +3,7 @@ CFLAGS=-Wall -std=c++11 CPPFLAGS=-Wall -std=c++11 LDFLAGS=-lpthread -lgtest -lgtest_main -lpthread -L/usr/lib -OBJS=ts-roundtrip.o ts-snippets.o ts-utf8.o +OBJS=ts-roundtrip.o ts-snippets.o ts-utf8.o ts-bugfix.o BIN=./tests diff --git a/tests/tests.vcxproj b/tests/tests.vcxproj index 5fe1d76..dc42113 100644 --- a/tests/tests.vcxproj +++ b/tests/tests.vcxproj @@ -37,6 +37,7 @@ + diff --git a/tests/ts-bugfix.cpp b/tests/ts-bugfix.cpp new file mode 100644 index 0000000..e449092 --- /dev/null +++ b/tests/ts-bugfix.cpp @@ -0,0 +1,26 @@ +#include "pch.h" +#include "../SimpleIni.h" + +TEST(TestBugFix, TestEmptySection) { + CSimpleIniA ini; + ini.SetValue("foo", "skey", "sval"); + ini.SetValue("", "rkey", "rval"); + ini.SetValue("bar", "skey", "sval"); + + std::string output; + ini.Save(output); + + std::string expected = + "rkey = rval\n" + "\n" + "\n" + "[foo]\n" + "skey = sval\n" + "\n" + "\n" + "[bar]\n" + "skey = sval\n"; + + output.erase(std::remove(output.begin(), output.end(), '\r'), output.end()); + ASSERT_STREQ(expected.c_str(), output.c_str()); +} -- cgit v1.2.3