diff --git a/src/ruc/file.cpp b/src/ruc/file.cpp index e2b2d32..f9ce208 100644 --- a/src/ruc/file.cpp +++ b/src/ruc/file.cpp @@ -6,8 +6,8 @@ #include // int32_t #include -#include // ifstream, ios, ofstream -#include // make_unique +#include // std::ifstream, std::ofstream +#include // std::make_shared, std::shared_ptr #include #include @@ -19,24 +19,7 @@ namespace ruc { File::File(std::string_view path) : m_path(path) { - // Create input stream object and open file - std::ifstream file(path.data(), std::ios::in); - VERIFY(file.is_open(), "failed to open file: '{}'", path); - - // Get length of the file - file.seekg(0, std::ios::end); - int32_t size = file.tellg(); - file.seekg(0, std::ios::beg); - VERIFY(size != -1, "failed to read file length: '{}'", path); - - // Allocate memory filled with zeros - auto buffer = std::make_unique(size); - - // Fill buffer with file contents - file.read(buffer.get(), size); - file.close(); - - m_data = std::string(buffer.get(), size); + m_data = std::string(File::raw(path).get()); } File::~File() @@ -54,6 +37,38 @@ File File::create(std::string_view path) return File(path); } +int32_t File::length(std::string_view path, std::ifstream& file) +{ + file.seekg(0, std::ios::end); + int32_t length = file.tellg(); + file.seekg(0, std::ios::beg); + VERIFY(length != -1, "failed to read file length: '{}'", path); + + return length; +} + +std::shared_ptr File::raw(std::string_view path) +{ + // Create input stream object and open file + std::ifstream file(path.data()); + VERIFY(file.is_open(), "failed to open file: '{}'", path); + + // Get length of the file + int32_t size = File::length(path, file); + + // Allocate memory filled with zeros + auto buffer = std::make_shared(size + 1); + + // Fill buffer with file contents + file.read(buffer.get(), size); + file.close(); + + // Null termination + buffer[size] = '\0'; + + return buffer; +} + // ----------------------------------------- void File::clear() diff --git a/src/ruc/file.h b/src/ruc/file.h index 022ab74..200055b 100644 --- a/src/ruc/file.h +++ b/src/ruc/file.h @@ -6,6 +6,8 @@ #pragma once +#include // int32_t +#include // std::shared_ptr #include #include @@ -17,6 +19,8 @@ public: virtual ~File(); static File create(std::string_view path); + static int32_t length(std::string_view path, std::ifstream& file); + static std::shared_ptr raw(std::string_view path); void clear(); File& append(std::string_view data); diff --git a/src/ruc/format/formatter.h b/src/ruc/format/formatter.h index 89562e6..e479278 100644 --- a/src/ruc/format/formatter.h +++ b/src/ruc/format/formatter.h @@ -331,8 +331,6 @@ struct Formatter : Formatter { } // namespace ruc::format -using ruc::format::Formatter; - #if 0 TODO: