File: format.cpp

package info (click to toggle)
openmw 0.50.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,076 kB
  • sloc: cpp: 380,958; xml: 2,192; sh: 1,449; python: 911; makefile: 26; javascript: 5
file content (43 lines) | stat: -rw-r--r-- 1,234 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "format.hpp"

#include <cstring>
#include <istream>
#include <stdexcept>
#include <string>

namespace ESM
{
    namespace
    {
        bool isValidFormat(std::uint32_t value)
        {
            return value == static_cast<std::uint32_t>(Format::Tes3)
                || value == static_cast<std::uint32_t>(Format::Tes4);
        }

        Format toFormat(std::uint32_t value)
        {
            if (!isValidFormat(value))
                throw std::runtime_error("Invalid format: " + std::to_string(value));
            return static_cast<Format>(value);
        }
    }

    Format readFormat(std::istream& stream)
    {
        std::uint32_t format = 0;
        stream.read(reinterpret_cast<char*>(&format), sizeof(format));
        if (stream.gcount() != sizeof(format))
            throw std::runtime_error("Not enough bytes to read file header");
        return toFormat(format);
    }

    Format parseFormat(std::string_view value)
    {
        if (value.size() != sizeof(std::uint32_t))
            throw std::logic_error("Invalid format value: " + std::string(value));
        std::uint32_t format;
        std::memcpy(&format, value.data(), sizeof(std::uint32_t));
        return toFormat(format);
    }
}