-
Notifications
You must be signed in to change notification settings - Fork 528
Expand file tree
/
Copy pathBinaryReader.h
More file actions
79 lines (57 loc) · 2.3 KB
/
BinaryReader.h
File metadata and controls
79 lines (57 loc) · 2.3 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//--------------------------------------------------------------------------------------
// File: BinaryReader.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// https://go.microsoft.com/fwlink/?LinkId=248929
// https://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#pragma once
#include <memory>
#include <exception>
#include <stdexcept>
#include <type_traits>
#include "PlatformHelpers.h"
namespace DirectX
{
// Helper for reading binary data, either from the filesystem a memory buffer.
class BinaryReader
{
public:
explicit BinaryReader(_In_z_ wchar_t const* fileName) noexcept(false);
BinaryReader(_In_reads_bytes_(dataSize) uint8_t const* dataBlob, size_t dataSize) noexcept;
BinaryReader(BinaryReader&&) noexcept;
BinaryReader& operator= (BinaryReader&&) noexcept;
BinaryReader(BinaryReader const&) = delete;
BinaryReader& operator= (BinaryReader const&) = delete;
// Reads a single value.
template<typename T> T const& Read()
{
return *ReadArray<T>(1);
}
// Reads an array of values.
template<typename T> T const* ReadArray(size_t elementCount)
{
static_assert(std::is_standard_layout<T>::value, "Can only read plain-old-data types");
uint64_t byteCount = uint64_t(sizeof(T)) * uint64_t(elementCount);
if (byteCount > UINT32_MAX)
throw std::overflow_error("ReadArray");
uint8_t const* newPos = mPos + static_cast<size_t>(byteCount);
if (newPos < mPos)
throw std::overflow_error("ReadArray");
if (newPos > mEnd)
throw std::runtime_error("End of file");
auto result = reinterpret_cast<T const*>(mPos);
mPos = newPos;
return result;
}
// Lower level helper reads directly from the filesystem into memory.
static HRESULT ReadEntireFile(_In_z_ wchar_t const* fileName, _Inout_ std::unique_ptr<uint8_t[]>& data, _Out_ size_t* dataSize);
private:
// The data currently being read.
uint8_t const* mPos;
uint8_t const* mEnd;
std::unique_ptr<uint8_t[]> mOwnedData;
};
}