From b42c52475d6e86f6ae0ed01f502bd0b611974578 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Mon, 17 Oct 2016 10:42:02 +0300 Subject: utils: code dedupe --- utils/helpers/bmp.hpp | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ utils/helpers/file.hpp | 18 +++++++++++++++--- 2 files changed, 66 insertions(+), 3 deletions(-) create mode 100644 utils/helpers/bmp.hpp (limited to 'utils/helpers') diff --git a/utils/helpers/bmp.hpp b/utils/helpers/bmp.hpp new file mode 100644 index 0000000..dc3cdac --- /dev/null +++ b/utils/helpers/bmp.hpp @@ -0,0 +1,51 @@ +// Copyright (c) 2016 Egor Tensin +// This file is part of the "AES tools" project. +// For details, see https://github.com/egor-tensin/aes-tools. +// Distributed under the MIT License. + +#include + +#include +#include + +#include +#include +#include + +namespace bmp +{ + class BmpFile + { + public: + BmpFile(std::vector&& buffer) + : buffer{std::move(buffer)} + , header_size{extract_pixels_offset()} + { } + + const void* get_buffer() const { return buffer.data(); } + + std::size_t get_size() const { return buffer.size(); } + + std::size_t get_header_size() const { return header_size; } + + const void* get_pixels() const { return buffer.data() + get_header_size(); } + + std::size_t get_pixels_size() const { return get_size() - get_header_size(); } + + void replace_pixels(std::vector&& pixels) + { + buffer.resize(get_header_size() + pixels.size()); + std::memcpy(buffer.data() + get_header_size(), pixels.data(), pixels.size()); + } + + private: + std::size_t extract_pixels_offset() const + { + const auto header = reinterpret_cast(get_buffer()); + return header->bfOffBits; + } + + std::vector buffer; + std::size_t header_size; + }; +} diff --git a/utils/helpers/file.hpp b/utils/helpers/file.hpp index a327c35..febe98f 100644 --- a/utils/helpers/file.hpp +++ b/utils/helpers/file.hpp @@ -3,10 +3,12 @@ // For details, see https://github.com/egor-tensin/aes-tools. // Distributed under the MIT License. +#include #include #include #include +#include #include #include @@ -17,7 +19,9 @@ namespace file std::ifstream ifs; ifs.exceptions(std::ifstream::badbit | std::ifstream::failbit); ifs.open(path, std::ifstream::binary | std::ifstream::ate); - return ifs.tellg(); + const auto size = static_cast(ifs.tellg()); + assert(size <= static_cast(std::numeric_limits::max())); + return static_cast(size); } inline std::vector read_file(const std::string& path) @@ -38,11 +42,19 @@ namespace file inline void write_file( const std::string& path, - const std::vector& src) + const void* buffer, + const std::size_t size) { std::ofstream ofs; ofs.exceptions(std::ofstream::badbit | std::ofstream::failbit); ofs.open(path, std::ofstream::binary); - ofs.write(reinterpret_cast(src.data()), src.size()); + ofs.write(reinterpret_cast(buffer), size); + } + + inline void write_file( + const std::string& path, + const std::vector& src) + { + write_file(path, src.data(), src.size()); } } -- cgit v1.2.3