dingusppc/devices/nvram.cpp

81 lines
1.8 KiB
C++
Raw Normal View History

2020-01-05 17:38:32 +00:00
//DingusPPC
//Written by divingkatae and maximum
//(c)2018-20 (theweirdo) spatium
//Please ask for permission
//if you want to distribute this.
//(divingkatae#1017 or powermax#2286 on Discord)
#include <iostream>
#include <fstream>
#include <cstring>
#include <cinttypes>
#include "nvram.h"
2020-01-07 10:52:38 +00:00
/** @file Non-volatile RAM implementation.
*/
using namespace std;
2020-01-07 10:52:38 +00:00
/** the signature for NVRAM backing file identification. */
static char NVRAM_FILE_ID[] = "DINGUSPPCNVRAM";
2020-01-07 10:52:38 +00:00
NVram::NVram(std::string file_name, uint32_t ram_size)
{
2020-01-07 10:52:38 +00:00
this->file_name = file_name;
this->ram_size = ram_size;
this->storage = new uint8_t[ram_size];
this->init();
}
NVram::~NVram()
{
2020-01-07 10:52:38 +00:00
this->save();
if (this->storage)
delete this->storage;
}
2020-01-07 10:52:38 +00:00
uint8_t NVram::read_byte(uint32_t offset)
{
return (this->storage[offset]);
}
2020-01-07 10:52:38 +00:00
void NVram::write_byte(uint32_t offset, uint8_t val)
{
this->storage[offset] = val;
}
2020-01-07 10:52:38 +00:00
void NVram::init() {
char sig[sizeof(NVRAM_FILE_ID)];
uint16_t data_size;
2020-01-07 10:52:38 +00:00
ifstream f(this->file_name, ios::in | ios::binary);
2020-01-07 10:52:38 +00:00
if (f.fail() || !f.read(sig, sizeof(NVRAM_FILE_ID)) ||
!f.read((char *)&data_size, sizeof(data_size)) ||
memcmp(sig, NVRAM_FILE_ID, sizeof(NVRAM_FILE_ID)) ||
data_size != this->ram_size ||
!f.read((char *)this->storage, this->ram_size))
{
2020-01-07 10:52:38 +00:00
cout << "WARN: Could not restore NVRAM content from the given file." << endl;
memset(this->storage, 0, sizeof(this->ram_size));
}
2020-01-07 10:52:38 +00:00
f.close();
}
2020-01-07 10:52:38 +00:00
void NVram::save()
{
ofstream f(this->file_name, ios::out | ios::binary);
2020-01-05 17:38:32 +00:00
2020-01-07 10:52:38 +00:00
/* write file identification */
f.write(NVRAM_FILE_ID, sizeof(NVRAM_FILE_ID));
f.write((char *)&this->ram_size, sizeof(this->ram_size));
2020-01-05 17:38:32 +00:00
2020-01-07 10:52:38 +00:00
/* write NVRAM content */
f.write((char *)this->storage, this->ram_size);
2020-01-07 10:52:38 +00:00
f.close();
}