// Leer y escribir un archivo completo como bytes. Viene hecho: es fácil hacerlo mal.
#ifndef BYTE_FILE_H
#define BYTE_FILE_H

#include <fstream>
#include <iterator>
#include <stdexcept>
#include <string>

#include "bit_io.h"

// istreambuf_iterator entrega cada byte tal cual: no salta espacios, y no se detiene en 0x00 ni en 0xFF.
// El modo binario evita que el sistema traduzca fines de línea; en Linux no cambia nada, en Windows sí.
inline Bytes read_file(const std::string& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        throw std::runtime_error("no se pudo abrir " + path);
    }
    // Cada char pasa a uint8_t: 0xC3 vale 195 aquí, tenga o no signo el char.
    return Bytes(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}

inline void write_file(const std::string& path, const Bytes& bytes) {
    std::ofstream out(path, std::ios::binary);
    if (!out) {
        throw std::runtime_error("no se pudo crear " + path);
    }
    out.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
    out.close();
    if (!out) {
        throw std::runtime_error("no se pudo escribir " + path);
    }
}

#endif
