Implement subscript operator returning sections

This commit is contained in:
TheAssassin
2018-11-09 01:44:02 +01:00
parent a647205226
commit 2c40482bc0
3 changed files with 30 additions and 1 deletions

View File

@@ -148,3 +148,14 @@ bool DesktopFileReader::operator!=(const DesktopFileReader& other) const {
boost::filesystem::path DesktopFileReader::path() const {
return d->path;
}
section_t DesktopFileReader::operator[](const std::string& name) {
auto it = d->sections.find(name);
// the map would lazy-initialize a new entry in case the section doesn't exist
// therefore explicitly checking whether the section exists, throwing an exception in case it does not
if (it == d->sections.end())
throw std::range_error("could not find section " + name);
return it->second;
}

View File

@@ -1,12 +1,16 @@
#pragma once
// system includes
#include <memory>
#include <istream>
#include <memory>
#include <unordered_map>
// library includes
#include <boost/filesystem.hpp>
// local includes
#include "desktopfileentry.h"
class DesktopFileReader {
private:
// opaque data class pattern
@@ -44,4 +48,8 @@ public:
// returns desktop file path
boost::filesystem::path path() const;
// get a specific section from the parsed data
// throws std::range_error if section does not exist
std::unordered_map<std::string, DesktopFileEntry> operator[](const std::string& name);
};

View File

@@ -104,6 +104,16 @@ TEST_F(DesktopFileReaderFixture, testParseSimpleDesktopFile) {
reader = DesktopFileReader(ss);
}
TEST_F(DesktopFileReaderFixture, testParseFileGetNonExistingSection) {
std::stringstream ss;
ss << "[Desktop File]" << std::endl;
DesktopFileReader reader;
reader = DesktopFileReader(ss);
ASSERT_THROW(reader["Non-existing Section"], std::range_error);
}
TEST_F(DesktopFileReaderFixture, testParseFileMissingSectionHeader) {
std::stringstream ss;
ss << "Name=name" << std::endl