summaryrefslogtreecommitdiffstatshomepage
path: root/src/devices/bus/gameboy/gbxfile.cpp
blob: 9058697b709142d28e07515010ceaad01a7a810c (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
// license:BSD-3-Clause
// copyright-holders:Vas Crabb
/***************************************************************************

 GBX file format helpers

 ***************************************************************************/

#include "emu.h"
#include "gbxfile.h"

#include <cstring>


namespace bus::gameboy::gbxfile {

bool get_data(
		memory_region *region,
		leader_1_0 &leader,
		u8 const *&extra,
		u32 &extralen)
{
	// no region, no dice
	if (!region)
		return false;

	// needs to contain enough data for the trailer at the very least
	auto const bytes(region->bytes());
	if (bytes < sizeof(trailer))
		return false;

	// check for supported format
	u8 *const base(&region->as_u8());
	trailer t;
	std::memcpy(&t, &base[bytes - sizeof(t)], sizeof(t));
	t.swap();
	if ((MAGIC_GBX != t.magic) || (1 != t.ver_maj))
		return false;

	// check that the footer fits and the leader doesn't overlap the trailer
	if ((bytes < t.size) || ((sizeof(leader) + sizeof(t)) > t.size))
		return false;

	// get leader in host byte order
	std::memcpy(&leader, &base[bytes - t.size], sizeof(leader));
	leader.swap();

	// get pointer to extra data if there's any
	extralen = t.size - sizeof(leader) - sizeof(t);
	if (extralen)
		extra = &base[bytes - t.size + sizeof(leader)];
	else
		extra = nullptr;

	// all good
	return true;
}

} // namespace bus::gameboy::gbxfile