1
0
Fork 0
mirror of https://github.com/OpenMW/openmw.git synced 2025-01-20 07:23:53 +00:00
openmw/components/esm/reader.cpp

87 lines
2.5 KiB
C++
Raw Normal View History

2022-01-30 10:07:39 +00:00
#include "reader.hpp"
//#ifdef NDEBUG
//#undef NDEBUG
//#endif
#include <cassert>
#include <stdexcept>
#include <components/files/constrainedfilestream.hpp>
#include "components/esm3/esmreader.hpp"
#include "components/esm4/reader.hpp"
namespace ESM
{
Reader* Reader::getReader(const std::string &filename)
{
Files::IStreamPtr esmStream(Files::openConstrainedFileStream(filename));
2022-01-30 10:07:39 +00:00
std::uint32_t modVer = 0; // get the first 4 bytes of the record header only
esmStream->read((char*)&modVer, sizeof(modVer));
if (esmStream->gcount() == sizeof(modVer))
{
esmStream->seekg(0);
if (modVer == ESM4::REC_TES4)
{
2022-04-15 00:15:39 +00:00
return new ESM4::Reader(std::move(esmStream), filename);
2022-01-30 10:07:39 +00:00
}
else
{
//return new ESM3::ESMReader(esmStream, filename);
}
}
throw std::runtime_error("Unknown file format");
}
bool Reader::getStringImpl(std::string& str, std::size_t size,
2022-04-24 16:51:30 +00:00
std::istream& stream, const ToUTF8::StatelessUtf8Encoder* encoder, bool hasNull)
2022-01-30 10:07:39 +00:00
{
std::size_t newSize = size;
if (encoder)
{
std::string input(size, '\0');
2022-04-15 00:15:39 +00:00
stream.read(input.data(), size);
if (stream.gcount() == static_cast<std::streamsize>(size))
2022-01-30 10:07:39 +00:00
{
encoder->getUtf8(input, ToUTF8::BufferAllocationPolicy::FitToRequiredSize, str);
2022-01-30 10:07:39 +00:00
return true;
}
}
else
{
if (hasNull)
newSize -= 1; // don't read the null terminator yet
str.resize(newSize); // assumed C++11
2022-04-15 00:15:39 +00:00
stream.read(&str[0], newSize);
if (static_cast<std::size_t>(stream.gcount()) == newSize)
2022-01-30 10:07:39 +00:00
{
if (hasNull)
{
char ch;
2022-04-15 00:15:39 +00:00
stream.read(&ch, 1); // read the null terminator
2022-01-30 10:07:39 +00:00
assert (ch == '\0'
&& "ESM4::Reader::getString string is not terminated with a null");
}
#if 0
else
{
// NOTE: normal ESMs don't but omwsave has locals or spells with null terminator
assert (str[newSize - 1] != '\0'
&& "ESM4::Reader::getString string is unexpectedly terminated with a null");
}
#endif
return true;
}
}
str.clear();
return false; // FIXME: throw instead?
}
}