1
0
mirror of https://gitlab.com/OpenMW/openmw.git synced 2024-12-29 12:20:41 +00:00

Do not truncate too long strings on writing ESM

This commit is contained in:
elsid 2023-02-11 00:01:59 +01:00
parent c0c723bb1b
commit beb017e699
No known key found for this signature in database
GPG Key ID: 4DE04C198CBA7625
4 changed files with 60 additions and 2 deletions

View File

@ -91,6 +91,7 @@ file(GLOB UNITTEST_SRC_FILES
esm3/readerscache.cpp
esm3/testsaveload.cpp
esm3/testesmwriter.cpp
nifosg/testnifloader.cpp
)

View File

@ -0,0 +1,54 @@
#include <components/esm3/esmwriter.hpp>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <memory>
#include <random>
namespace ESM
{
namespace
{
using namespace ::testing;
struct Esm3EsmWriterTest : public Test
{
std::minstd_rand mRandom;
std::uniform_int_distribution<short> mRefIdDistribution{ 'a', 'z' };
std::string generateRandomString(std::size_t size)
{
std::string result;
std::generate_n(
std::back_inserter(result), size, [&] { return static_cast<char>(mRefIdDistribution(mRandom)); });
return result;
}
};
TEST_F(Esm3EsmWriterTest, saveShouldThrowExceptionOnWhenTruncatingHeaderStrings)
{
const std::string author = generateRandomString(33);
const std::string description = generateRandomString(257);
std::stringstream stream;
ESMWriter writer;
writer.setAuthor(author);
writer.setDescription(description);
writer.setFormatVersion(CurrentSaveGameFormatVersion);
EXPECT_THROW(writer.save(stream), std::runtime_error);
}
TEST_F(Esm3EsmWriterTest, writeFixedStringShouldThrowExceptionOnTruncate)
{
std::stringstream stream;
ESMWriter writer;
writer.setFormatVersion(CurrentSaveGameFormatVersion);
writer.save(stream);
EXPECT_THROW(writer.writeFixedSizeString(generateRandomString(33), 32), std::runtime_error);
}
}
}

View File

@ -167,11 +167,14 @@ namespace ESM
endRecord(name);
}
void ESMWriter::writeFixedSizeString(const std::string& data, int size)
void ESMWriter::writeFixedSizeString(const std::string& data, std::size_t size)
{
std::string string;
if (!data.empty())
string = mEncoder ? mEncoder->getLegacyEnc(data) : data;
if (string.size() > size)
throw std::runtime_error("Fixed string data is too long: \"" + string + "\" ("
+ std::to_string(string.size()) + " > " + std::to_string(size) + ")");
string.resize(size);
write(string.c_str(), string.size());
}

View File

@ -136,7 +136,7 @@ namespace ESM
void startSubRecord(NAME name);
void endRecord(NAME name);
void endRecord(uint32_t name);
void writeFixedSizeString(const std::string& data, int size);
void writeFixedSizeString(const std::string& data, std::size_t size);
void writeHString(const std::string& data);
void writeHCString(const std::string& data);
void writeName(NAME data);