summaryrefslogtreecommitdiff
path: root/lib/nes/sys/types/address.hh
blob: d8b857b53c9ed9cba1efc6783c4c384b646be4ee (plain)
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
#pragma once

#include "nes/common/types.hh"

namespace nes::sys
{
	/// An address on the NES (for simplicity, we share the same type for CPU and PPU, even though the PPU only uses
	/// 14 bit addresses).
	class address
	{
		u16 absolute_{ 0 };

	public:
		/// Create a zero address.
		constexpr explicit address() = default;

		/// Create an address from its absolute value.
		constexpr explicit address(u16 const absolute)
			: absolute_{ absolute }
		{
		}

		/// Create an address from its page and offset combination.
		constexpr explicit address(u8 const page, u8 const offset)
			: address{ static_cast<u16>((page << 8) | (offset << 0)) }
		{
		}

		/// Get the absolute address value.
		constexpr auto get_absolute() const -> u16
		{
			return absolute_;
		}

		/// Get the address page (the first 8 bits).
		constexpr auto get_page() const -> u8
		{
			return static_cast<u8>((get_absolute() & 0xFF00) >> 8);
		}

		/// Get the offset within the page (the last 8 bits).
		constexpr auto get_offset() const -> u8
		{
			return static_cast<u8>((get_absolute() & 0x00FF) >> 0);
		}
	};

	constexpr auto operator==(address const a, address const b) -> bool { return a.get_absolute() == b.get_absolute(); }
	constexpr auto operator!=(address const a, address const b) -> bool { return a.get_absolute() != b.get_absolute(); }
	constexpr auto operator<(address const a, address const b) -> bool { return a.get_absolute() < b.get_absolute(); }
	constexpr auto operator>(address const a, address const b) -> bool { return a.get_absolute() > b.get_absolute(); }
	constexpr auto operator<=(address const a, address const b) -> bool { return a.get_absolute() <= b.get_absolute(); }
	constexpr auto operator>=(address const a, address const b) -> bool { return a.get_absolute() >= b.get_absolute(); }

	constexpr auto operator+(address const a, u32 const b) -> address
	{
		return address{ static_cast<u16>(a.get_absolute() + b) };
	}

	constexpr auto operator+(u32 const a, address const b) -> address
	{
		return address{ static_cast<u16>(a + b.get_absolute()) };
	}

	constexpr auto operator-(address const a, u32 const b) -> address
	{
		return address{ static_cast<u16>(a.get_absolute() - b) };
	}

	constexpr auto operator%(address const a, u32 const b) -> address
	{
		return address{ static_cast<u16>(a.get_absolute() % b) };
	}
} // namespace nes::sys