romPool.cpp (1567B)
1 #include "romPool.h" 2 3 #include "config.h" 4 5 #include "baseLib/filesystem.h" 6 #include "baseLib/md5.h" 7 8 #include "networkLib/logging.h" 9 10 namespace bridgeServer 11 { 12 RomPool::RomPool(Config& _config) : m_config(_config) 13 { 14 findRoms(); 15 } 16 17 const RomData& RomPool::getRom(const baseLib::MD5& _hash) 18 { 19 std::scoped_lock lock(m_mutex); 20 21 auto it = m_roms.find(_hash); 22 if(it == m_roms.end()) 23 findRoms(); 24 it = m_roms.find(_hash); 25 if(it != m_roms.end()) 26 return it->second; 27 static RomData empty; 28 return empty; 29 } 30 31 void RomPool::addRom(const std::string& _name, const RomData& _data) 32 { 33 std::scoped_lock lock(m_mutex); 34 35 const auto hash = baseLib::MD5(_data); 36 if(m_roms.find(hash) != m_roms.end()) 37 return; 38 39 if(baseLib::filesystem::writeFile(getRootPath() + _name + '_' + hash.toString() + ".bin", _data)) 40 m_roms.insert({hash, _data}); 41 } 42 43 std::string RomPool::getRootPath() const 44 { 45 return m_config.romsPath; 46 } 47 48 void RomPool::findRoms() 49 { 50 std::vector<std::string> files; 51 baseLib::filesystem::findFiles(files, getRootPath(), {}, 0, 16 * 1024 * 1024); 52 53 for (const auto& file : files) 54 { 55 std::vector<uint8_t> romData; 56 57 if(!baseLib::filesystem::readFile(romData, file)) 58 { 59 LOGNET(networkLib::LogLevel::Error, "Failed to load file " << file); 60 continue; 61 } 62 63 const auto hash = baseLib::MD5(romData); 64 65 if(m_roms.find(hash) != m_roms.end()) 66 continue; 67 68 m_roms.insert({hash, std::move(romData)}); 69 LOGNET(networkLib::LogLevel::Info, "Loaded ROM " << baseLib::filesystem::getFilenameWithoutPath(file)); 70 } 71 } 72 }