Upstream tarball 9440
[amule.git] / src / FileArea.cpp
blobb3e5ebcfa44190b612e1abbcecad997df27616ec
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 1998 Vadim Zeitlin ( zeitlin@dptmaths.ens-cachan.fr )
6 //
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
9 // respective authors.
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #include "FileArea.h" // Interface declarations.
28 #include "Logger.h" // Needed for AddDebugLogLineM
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
35 #ifdef HAVE_SYS_MMAN_H
36 #include <sys/mman.h>
37 #endif
40 CFileArea::CFileArea()
41 : m_buffer(NULL), m_mmap_buffer(NULL), m_length(0),
42 m_fd(CFile::fd_invalid)
47 CFileArea::~CFileArea()
49 Close();
52 bool CFileArea::Close()
54 if (m_fd != CFile::fd_invalid)
56 close(m_fd);
57 m_fd = CFile::fd_invalid;
59 if (m_buffer != NULL && m_mmap_buffer == NULL)
61 delete[] m_buffer;
62 m_buffer = NULL;
64 #ifdef HAVE_MMAP
65 #warning using experimental MMAP file reading
66 if (m_mmap_buffer)
68 munmap(m_mmap_buffer, m_length);
69 m_mmap_buffer = NULL;
71 #endif
72 return true;
76 void CFileArea::Read(const CFile& file, size_t count)
78 Close();
80 #ifdef HAVE_MMAP
81 const uint64 pageSize = 8192u;
82 uint64 offset = file.GetPosition();
83 uint64 offStart = offset & (~(pageSize-1));
84 uint64 offEnd = (offset + count + pageSize - 1) & (~(pageSize-1));
85 m_length = offEnd - offStart;
86 void *p = mmap(NULL, m_length, PROT_READ, MAP_SHARED, file.fd(), offStart);
87 if (p != MAP_FAILED)
89 m_mmap_buffer = (byte*) p;
90 m_buffer = m_mmap_buffer + (offset - offStart);
91 file.Seek(offset + count);
92 return;
94 #endif
95 m_buffer = new byte[count];
96 file.Read(m_buffer, count);
99 bool CFileArea::Flush()
101 /* currently we don't support write */
102 return true;