| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| #ifndef THIRD_PARTY_GEMMA_CPP_COMPRESSION_IO_H_ |
| #define THIRD_PARTY_GEMMA_CPP_COMPRESSION_IO_H_ |
|
|
| #include <stddef.h> |
| #include <stdint.h> |
|
|
| #include <memory> |
| #include <string> |
| #include <utility> |
|
|
| #include "hwy/base.h" |
|
|
| namespace gcpp { |
|
|
| |
| |
| |
| struct Path; |
|
|
| |
| class File { |
| public: |
| File() = default; |
| virtual ~File() = default; |
|
|
| |
| File(const File& other) = delete; |
| const File& operator=(const File& other) = delete; |
|
|
| |
| virtual uint64_t FileSize() const = 0; |
|
|
| |
| virtual bool Read(uint64_t offset, uint64_t size, void* to) const = 0; |
|
|
| |
| virtual bool Write(const void* from, uint64_t size, uint64_t offset) = 0; |
| }; |
|
|
| |
| |
| std::unique_ptr<File> OpenFileOrNull(const Path& filename, const char* mode); |
|
|
| |
| |
| struct Path { |
| Path() {} |
| explicit Path(const char* p) : path(p) {} |
| explicit Path(std::string p) : path(std::move(p)) {} |
|
|
| Path& operator=(const char* other) { |
| path = other; |
| return *this; |
| } |
|
|
| std::string Shortened() const { |
| constexpr size_t kMaxLen = 48; |
| constexpr size_t kCutPoint = kMaxLen / 2 - 5; |
| if (path.size() > kMaxLen) { |
| return std::string(begin(path), begin(path) + kCutPoint) + " ... " + |
| std::string(end(path) - kCutPoint, end(path)); |
| } |
| if (path.empty()) return "[no path specified]"; |
| return path; |
| } |
|
|
| bool Empty() const { return path.empty(); } |
|
|
| |
| bool Exists() const { return !!OpenFileOrNull(*this, "r"); } |
|
|
| std::string path; |
| }; |
|
|
| static inline HWY_MAYBE_UNUSED std::string ReadFileToString(const Path& path) { |
| std::unique_ptr<File> file = OpenFileOrNull(path, "r"); |
| if (!file) { |
| HWY_ABORT("Failed to open %s", path.path.c_str()); |
| } |
| const size_t size = file->FileSize(); |
| if (size == 0) { |
| HWY_ABORT("Empty file %s", path.path.c_str()); |
| } |
| std::string content(size, ' '); |
| if (!file->Read(0, size, content.data())) { |
| HWY_ABORT("Failed to read %s", path.path.c_str()); |
| } |
| return content; |
| } |
|
|
| } |
|
|
| #endif |
|
|