openMSX
FileBase.cc
Go to the documentation of this file.
1 #include "FileBase.hh"
2 #include "FileOperations.hh"
3 #include <algorithm>
4 #include <cstring>
5 
6 using std::string;
7 
8 namespace openmsx {
9 
11 {
12  auto size = getSize();
13  if (mmapBuf.empty()) {
14  auto pos = getPos();
15  seek(0);
16 
17  MemBuffer<uint8_t> tmpBuf(size);
18  read(tmpBuf.data(), size);
19  std::swap(mmapBuf, tmpBuf);
20 
21  seek(pos);
22  }
23  return {mmapBuf.data(), size};
24 }
25 
27 {
28  mmapBuf.clear();
29 }
30 
31 void FileBase::truncate(size_t newSize)
32 {
33  auto oldSize = getSize();
34  if (newSize < oldSize) {
35  // default truncate() can't shrink file
36  return;
37  }
38  auto remaining = newSize - oldSize;
39  seek(oldSize);
40 
41  static const size_t BUF_SIZE = 4096;
42  uint8_t buf[BUF_SIZE];
43  memset(buf, 0, sizeof(buf));
44  while (remaining) {
45  auto chunkSize = std::min(BUF_SIZE, remaining);
46  write(buf, chunkSize);
47  remaining -= chunkSize;
48  }
49 }
50 
52 {
53  // default implementation, file is not backed (uncompressed) on
54  // the local file system
55  return {};
56 }
57 
59 {
60  // default implementation just returns filename portion of URL
62 }
63 
64 } // namespace openmsx
virtual std::string getLocalReference()
Definition: FileBase.cc:51
string_view getFilename(string_view path)
Returns the file portion of a path name.
void swap(optional< T > &x, optional< T > &y) noexcept(noexcept(x.swap(y)))
Definition: optional.hh:816
virtual std::string getURL() const =0
vecN< N, T > min(const vecN< N, T > &x, const vecN< N, T > &y)
Definition: gl_vec.hh:269
Definition: span.hh:34
virtual std::string getOriginalName()
Definition: FileBase.cc:58
virtual void read(void *buffer, size_t num)=0
virtual void write(const void *buffer, size_t num)=0
virtual void munmap()
Definition: FileBase.cc:26
virtual size_t getSize()=0
void clear()
Free the allocated memory block and set the current size to 0.
Definition: MemBuffer.hh:134
const T * data() const
Returns pointer to the start of the memory buffer.
Definition: MemBuffer.hh:90
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
virtual span< uint8_t > mmap()
Definition: FileBase.cc:10
virtual void truncate(size_t size)
Definition: FileBase.cc:31
std::string str() const
Definition: string_view.cc:12
virtual size_t getPos()=0
bool empty() const
No memory allocated?
Definition: MemBuffer.hh:112
constexpr auto size(const C &c) -> decltype(c.size())
Definition: span.hh:62
virtual void seek(size_t pos)=0