21 namespace fs = std::filesystem;
29 static bool exists(
const std::string& file)
31 std::ifstream f(file.c_str());
43 static std::vector<uint8_t> slurp(
44 const std::string& file,
bool optional =
false)
46 std::ifstream f(file, std::ios::binary | std::ios::ate);
54 std::cerr <<
"Could not open file " << file << std::endl;
58 auto size = f.tellg();
59 f.seekg(0, std::ios::beg);
61 std::vector<uint8_t> data(size);
62 f.read(
reinterpret_cast<char*
>(data.data()), size);
66 std::cerr <<
"Could not read file " << file << std::endl;
80 static std::string slurp_string(
81 const std::string& file,
bool optional =
false)
83 auto v = slurp(file, optional);
84 return {v.begin(), v.end()};
87 static std::optional<std::string> try_slurp_string(
const std::string& file)
89 if (!fs::exists(file))
93 return files::slurp_string(file);
105 static nlohmann::json slurp_json(
106 const std::string& file,
bool optional =
false)
108 auto v = slurp(file, optional);
114 return nlohmann::json::parse(v.begin(), v.end());
123 static void dump(
const std::vector<uint8_t>& data,
const std::string& file)
126 ofstream f(file, ios::binary | ios::trunc);
127 f.write(
reinterpret_cast<const char*
>(data.data()), data.size());
130 throw logic_error(
"Failed to write to file: " + file);
140 static void dump(
const std::string& data,
const std::string& file)
142 dump(std::vector<uint8_t>(data.begin(), data.end()), file);
145 static void rename(
const fs::path& src,
const fs::path& dst)
148 fs::rename(src, dst, ec);
151 throw std::logic_error(fmt::format(
152 "Could not rename file {} to {}: {}",
159 static void create_directory(
const fs::path& dir)
162 fs::create_directory(dir, ec);
163 if (ec && ec != std::errc::file_exists)
165 throw std::logic_error(fmt::format(
166 "Could not create directory {}: {}", dir.string(), ec.message()));