FileReader.hxx 2.43 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifndef MPD_FILE_READER_HXX
#define MPD_FILE_READER_HXX

#include "check.h"
#include "Reader.hxx"
#include "fs/AllocatedPath.hxx"
26
#include "Compiler.h"
27

28
#ifndef _WIN32
29 30 31
#include "system/FileDescriptor.hxx"
#endif

32
#ifdef _WIN32
33 34 35 36
#include <windows.h>
#endif

class Path;
37
class FileInfo;
38 39 40 41

class FileReader final : public Reader {
	AllocatedPath path;

42
#ifdef _WIN32
43 44
	HANDLE handle;
#else
45
	FileDescriptor fd;
46 47 48
#endif

public:
49
	explicit FileReader(Path _path);
50

51
#ifdef _WIN32
52 53 54 55 56 57 58 59 60 61 62 63 64
	FileReader(FileReader &&other)
		:path(std::move(other.path)),
		 handle(other.handle) {
		other.handle = INVALID_HANDLE_VALUE;
	}
#else
	FileReader(FileReader &&other)
		:path(std::move(other.path)),
		 fd(other.fd) {
		other.fd.SetUndefined();
	}
#endif

65 66 67 68 69 70
	~FileReader() {
		if (IsDefined())
			Close();
	}


71
protected:
72
	bool IsDefined() const {
73
#ifdef _WIN32
74 75
		return handle != INVALID_HANDLE_VALUE;
#else
76
		return fd.IsDefined();
77 78 79
#endif
	}

80
public:
81
#ifndef _WIN32
82 83 84 85 86
	FileDescriptor GetFD() const {
		return fd;
	}
#endif

87 88
	void Close();

89
	FileInfo GetFileInfo() const;
90

91
	gcc_pure
92
	uint64_t GetSize() const noexcept {
93
#ifdef _WIN32
94 95 96 97 98 99 100 101 102 103
		LARGE_INTEGER size;
		return GetFileSizeEx(handle, &size)
			? size.QuadPart
			: 0;
#else
		return fd.GetSize();
#endif
	}

	gcc_pure
104
	uint64_t GetPosition() const noexcept {
105
#ifdef _WIN32
106 107 108 109 110 111 112 113 114 115 116
		LARGE_INTEGER zero;
		zero.QuadPart = 0;
		LARGE_INTEGER position;
		return SetFilePointerEx(handle, zero, &position, FILE_CURRENT)
			? position.QuadPart
			: 0;
#else
		return fd.Tell();
#endif
	}

117 118 119 120
	void Rewind() {
		Seek(0);
	}

121
	void Seek(off_t offset);
122
	void Skip(off_t offset);
123

124
	/* virtual methods from class Reader */
125
	size_t Read(void *data, size_t size) override;
126 127 128
};

#endif