aboutsummaryrefslogtreecommitdiff
path: root/src/zencore/stream.cpp
blob: a800ce1214aeaace6a273b16255529c326bc0837 (plain) (blame)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright Epic Games, Inc. All Rights Reserved.

#include <stdarg.h>
#include <zencore/memoryview.h>
#include <zencore/stream.h>
#include <zencore/testing.h>

#include <algorithm>
#include <stdexcept>

namespace zen {

void
BinaryWriter::Write(std::initializer_list<const MemoryView> Buffers)
{
	size_t TotalByteCount = 0;
	for (const MemoryView& View : Buffers)
	{
		TotalByteCount += View.GetSize();
	}
	const size_t NeedEnd = m_Offset + TotalByteCount;
	if (NeedEnd > m_Buffer.size())
	{
		m_Buffer.resize(NeedEnd);
	}
	for (const MemoryView& View : Buffers)
	{
		size_t Size = View.GetSize();
		memcpy(m_Buffer.data() + m_Offset, View.GetData(), Size);
		m_Offset += Size;
	}
}

void
BinaryWriter::Write(const void* data, size_t ByteCount, uint64_t Offset)
{
	const size_t NeedEnd = Offset + ByteCount;

	if (NeedEnd > m_Buffer.size())
	{
		m_Buffer.resize(NeedEnd);
	}

	memcpy(m_Buffer.data() + Offset, data, ByteCount);
}

void
BinaryWriter::Reset()
{
	m_Buffer.clear();
	m_Offset = 0;
}

//////////////////////////////////////////////////////////////////////////

void
BufferReader::Seek(uint64_t InPos)
{
	// Validate range
	m_Offset = InPos;
}

int64_t
BufferReader::Tell()
{
	return CurrentOffset();
}

void
BufferReader::Serialize(void* V, int64_t Length)
{
	Read(V, Length);
}

//////////////////////////////////////////////////////////////////////////
//
// Testing related code follows...
//

#if ZEN_WITH_TESTS

TEST_CASE("binary.writer.span")
{
	BinaryWriter	 Writer;
	const MemoryView View1("apa", 3);
	const MemoryView View2(" ", 1);
	const MemoryView View3("banan", 5);
	Writer.Write({View1, View2, View3});
	MemoryView Result = Writer.GetView();
	CHECK(Result.GetSize() == 9);
	CHECK(memcmp(Result.GetData(), "apa banan", 9) == 0);
}

void
stream_forcelink()
{
}

#endif

}  // namespace zen