summaryrefslogtreecommitdiff
path: root/tb/mem.impl.hpp
blob: f7bb424ac6a79fa42804b64b1d7c7d1198f3c324 (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
75
76
77
78
79
80
81
#ifndef TALLER_MEM_IMPL_HPP
#define TALLER_MEM_IMPL_HPP

#include <cassert>
#include <cstdint>
#include <memory>

namespace taller::avalon
{
	template<typename Cell>
	mem<Cell>::mem(std::uint32_t base, std::uint32_t size)
	: slave(base, size, sizeof(Cell)),
	  block(std::make_unique<Cell[]>(size >> word_bits()))
	{}

	template<typename Cell>
	template<typename F>
	void mem<Cell>::load(F loader, std::size_t offset)
	{
		auto base = base_address();
		auto bits = word_bits();
		std::size_t size = address_span();
		std::size_t addr = base_address() + offset;

		while(addr >= base && addr < base + size)
		{
			std::size_t read = loader(&block[(addr - base) >> bits], (base + size - addr) >> bits);
			if(read == 0)
			{
				break;
			}

			addr += read << bits;
		}
	}

	template<typename Cell>
	bool mem<Cell>::read(std::uint32_t addr, std::uint32_t &data)
	{
		data = block[addr];
		return ready();
	}

	template<typename Cell>
	bool mem<Cell>::write(std::uint32_t addr, std::uint32_t data, unsigned byte_enable)
	{
		std::uint32_t bytes = 0;

		if(byte_enable & 0b1000)
		{
			bytes |= 0xff << 24;
		}

		if(byte_enable & 0b0100)
		{
			bytes |= 0xff << 16;
		}

		if(byte_enable & 0b0010)
		{
			bytes |= 0xff << 8;
		}

		if(byte_enable & 0b0001)
		{
			bytes |= 0xff;
		}

		block[addr] = (data & bytes) | (block[addr] & ~bytes);
		return ready();
	}

	template<typename Cell>
	bool mem<Cell>::ready() noexcept
	{
		count = count > 0 ? count - 1 : 2;
		return count == 0;
	}
}

#endif