-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmemoryfilemapper.cpp
More file actions
114 lines (92 loc) · 2.21 KB
/
Copy pathmemoryfilemapper.cpp
File metadata and controls
114 lines (92 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "memoryfilemapper.h"
#include <QDataStream>
#include <QFile>
namespace {
//MUST be a multiple of the OS allocation granularity
//(e.g. this will normally be 64Kb)
const qint32 MEM_BLOCK_SIZE = 0x10000*2; //actually, this is 128Kb
}
MemoryFileMapper::MemoryFileMapper(QObject *parent)
: QObject(parent)
{
m_file = new QFile(this);
}
MemoryFileMapper::~MemoryFileMapper()
{
Close();
}
bool MemoryFileMapper::Open(const QString& filePath)
{
bool done = false;
do
{
m_file->close();
m_file->setFileName(filePath);
if(!m_file->open(QIODevice::ReadOnly)) {
break;
}
done = true;
} while(0);
return done;
}
bool MemoryFileMapper::Close(void)
{
bool done = false;
do
{
if(m_file) {
m_file->close();
}
done = true;
} while(0);
return done;
}
//
// Return the logical size of the MemoryFileMapper.
//
MemoryFileMapper::FileSizeType MemoryFileMapper::Size()
{
FileSizeType s = 0;
if(m_file) {
s = m_file->size();
}
return s;
}
bool MemoryFileMapper::CopyContent(MemoryFileMapper::FileSizeType offset,
MemoryFileMapper::FileSizeType length,
QByteArray& to)
{
// If we had the entire file mapped into memory at once, then
// we could do a simple memcpy to render the data in one go.
//
// However, we have to do the copies in sections. When
// we get a pointer to the file with AdjustedAddress, this
// pointer only covers a range -MEM_BLOCK_SIZE/4 to +MEM_BLOCK_SIZE/4,
// so we have to break the copies up into smaller units.
//
int oldBufferSize = to.size();
QDataStream stream(&to, QIODevice::ReadWrite);
int copiedLength = 0;
while(copiedLength < length)
{
int len = qMin((length-copiedLength), FileSizeType(MEM_BLOCK_SIZE / 4));
uchar* from = m_file->map(offset, len);
if(!from) {
break;
}
int r = stream.writeRawData((const char*)from, len);
m_file->unmap(from);
if(-1==r) {
break;
}
Q_ASSERT(r==len);
if(r!=len) {
break;
}
copiedLength += len;
offset += len; //advance the adjustedAddress position
}
// target buffer won't be resized
Q_ASSERT(oldBufferSize == to.size());
return (copiedLength==length);
}