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  munmap();
13 }
14 
15 const byte* FileBase::mmap(size_t& size)
16 {
17  if (mmapBuf.empty()) {
18  size = getSize();
19  MemBuffer<byte> tmpBuf(size);
20  read(tmpBuf.data(), size);
21  std::swap(mmapBuf, tmpBuf);
22  }
23  return mmapBuf.data();
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  byte 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
vecN< N, T > min(const vecN< N, T > &x, const vecN< N, T > &y)
Definition: gl_vec.hh:268
virtual const std::string getOriginalName()
Definition: FileBase.cc:58
uint8_t byte
8 bit unsigned integer
Definition: openmsx.hh:26
string_ref getFilename(string_ref path)
Returns the file portion of a path name.
virtual ~FileBase()
Definition: FileBase.cc:10
virtual const std::string getURL() const =0
virtual void read(void *buffer, size_t num)=0
virtual void write(const void *buffer, size_t num)=0
virtual const byte * mmap(size_t &size)
Definition: FileBase.cc:15
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
virtual const std::string getLocalReference()
Definition: FileBase.cc:51
std::string str() const
Definition: string_ref.cc:12
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
size_t size() const
virtual void truncate(size_t size)
Definition: FileBase.cc:31
bool empty() const
No memory allocated?
Definition: MemBuffer.hh:112
virtual void seek(size_t pos)=0