Skip to content

Commit 288fdc0

Browse files
sipaPieter Wuille
authored andcommitted
Native versions for AllocateFileRange()
1 parent 2835080 commit 288fdc0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/util.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@
33
// Distributed under the MIT/X11 software license, see the accompanying
44
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
55

6+
#ifndef WIN32
7+
// for posix_fallocate
8+
#ifdef __linux__
9+
#define _POSIX_C_SOURCE 200112L
10+
#endif
11+
#include <fcntl.h>
12+
#include <sys/stat.h>
13+
#endif
14+
615
#include "util.h"
716
#include "sync.h"
817
#include "version.h"
@@ -1155,6 +1164,35 @@ int GetFilesize(FILE* file)
11551164
// this function tries to make a particular range of a file allocated (corresponding to disk space)
11561165
// it is advisory, and the range specified in the arguments will never contain live data
11571166
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1167+
#if defined(WIN32)
1168+
// Windows-specific version
1169+
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1170+
LARGE_INTEGER nFileSize;
1171+
int64 nEndPos = (int64)offset + length;
1172+
nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1173+
nFileSize.u.HighPart = nEndPos >> 32;
1174+
SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1175+
SetEndOfFile(hFile);
1176+
#elif defined(MAC_OSX)
1177+
// OSX specific version
1178+
fstore_t fst;
1179+
fst.fst_flags = F_ALLOCATECONTIG;
1180+
fst.fst_posmode = F_PEOFPOSMODE;
1181+
fst.fst_offset = 0;
1182+
fst.fst_length = (off_t)offset + length;
1183+
fst.fst_bytesalloc = 0;
1184+
if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1185+
fst.fst_flags = F_ALLOCATEALL;
1186+
fcntl(fileno(file), F_PREALLOCATE, &fst);
1187+
}
1188+
ftruncate(fileno(file), fst.fst_length);
1189+
#elif defined(__linux__)
1190+
// Version using posix_fallocate
1191+
off_t nEndPos = (off_t)offset + length;
1192+
posix_fallocate(fileno(file), 0, nEndPos);
1193+
#else
1194+
// Fallback version
1195+
// TODO: just write one byte per block
11581196
static const char buf[65536] = {};
11591197
fseek(file, offset, SEEK_SET);
11601198
while (length > 0) {
@@ -1164,6 +1202,7 @@ void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
11641202
fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
11651203
length -= now;
11661204
}
1205+
#endif
11671206
}
11681207

11691208
void ShrinkDebugFile()

0 commit comments

Comments
 (0)