galaxy 1.0.0
Real-Time C++23 Game Programming Framework. Built on data-driven design principles and agile software engineering.
Loading...
Searching...
No Matches
PhysfsStream.cpp
Go to the documentation of this file.
1
7
8#include <physfs.h>
9
11
12#include "PhysfsStream.hpp"
13
14namespace galaxy
15{
16 namespace fs
17 {
19 : m_file(nullptr)
20 {
21 }
22
23 PhysfsStream::PhysfsStream(const std::string& filename) noexcept
24 : m_file(nullptr)
25 {
26 open(filename);
27 }
28
30 {
31 close();
32 }
33
34 bool PhysfsStream::is_open() const noexcept
35 {
36 return m_file != nullptr;
37 }
38
39 bool PhysfsStream::open(const std::string& filename) noexcept
40 {
41 if (!filename.empty())
42 {
43 close();
44
45 m_file = PHYSFS_openRead(filename.c_str());
47 return is_open();
48 }
49 else
50 {
51 return false;
52 }
53 }
54
55 void PhysfsStream::close() noexcept
56 {
57 if (is_open())
58 {
59 logging::physfs_check(PHYSFS_close(m_file));
60 m_file = nullptr;
61 }
62 }
63
64 std::optional<std::size_t> PhysfsStream::read(void* data, std::size_t size)
65 {
66 if (!is_open())
67 {
68 return -1;
69 }
70
71 // PHYSFS_readBytes returns the number of bytes read or -1 on error.
72 // We request to read size amount of bytes.
73 return PHYSFS_readBytes(m_file, data, static_cast<PHYSFS_uint32>(size));
74 }
75
76 std::optional<std::size_t> PhysfsStream::seek(std::size_t position)
77 {
78 if (!is_open())
79 {
80 return -1;
81 }
82
83 // PHYSFS_seek return 0 on error and non zero on success.
84 if (PHYSFS_seek(m_file, position))
85 {
86 return tell();
87 }
88 else
89 {
90 return -1;
91 }
92 }
93
94 std::optional<std::size_t> PhysfsStream::tell()
95 {
96 if (!is_open())
97 {
98 return -1;
99 }
100
101 // PHYSFS_tell returns the offset in bytes or -1 on error just like SFML wants.
102 return PHYSFS_tell(m_file);
103 }
104
105 std::optional<std::size_t> PhysfsStream::getSize()
106 {
107 if (!is_open())
108 {
109 return -1;
110 }
111
112 // PHYSFS_fileLength also the returns length of file or -1 on error just like SFML wants.
113 return PHYSFS_fileLength(m_file);
114 }
115 } // namespace fs
116} // namespace galaxy
bool open(const std::string &filename) noexcept
Open file in physfs.
std::optional< std::size_t > read(void *data, std::size_t size) override
Read data from the stream.
std::optional< std::size_t > seek(std::size_t position) override
Change the current reading position.
PhysfsStream() noexcept
Constructor.
std::optional< std::size_t > tell() override
Get the current reading position in the stream.
virtual ~PhysfsStream() noexcept
Virtual destructor.
PHYSFS_File * m_file
Handle to physfs file data.
void close() noexcept
Close the open physfs handle.
std::optional< std::size_t > getSize() override
Return the size of the stream.
bool is_open() const noexcept
Is the physfs file open.
bool physfs_check(const int code) noexcept
Call a physfs function with error handling and logs a message for you.
Timer.hpp galaxy.
Definition Async.hpp:17