FileReader.hxx 2.44 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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
 * 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 "Reader.hxx"
#include "fs/AllocatedPath.hxx"
25
#include "util/Compiler.h"
26

27
#ifdef _WIN32
28
#include <windows.h>
29
#else
30
#include "system/UniqueFileDescriptor.hxx"
31 32 33
#endif

class Path;
34
class FileInfo;
35 36 37 38

class FileReader final : public Reader {
	AllocatedPath path;

39
#ifdef _WIN32
40 41
	HANDLE handle;
#else
42
	UniqueFileDescriptor fd;
43 44 45
#endif

public:
46
	explicit FileReader(Path _path);
47

48
#ifdef _WIN32
49
	FileReader(FileReader &&other) noexcept
50
		:path(std::move(other.path)),
51
		 handle(std::exchange(other.handle, INVALID_HANDLE_VALUE)) {}
52

53
	~FileReader() noexcept {
54 55 56
		if (IsDefined())
			Close();
	}
57 58 59 60 61
#else
	FileReader(FileReader &&other) noexcept
		:path(std::move(other.path)),
		 fd(std::move(other.fd)) {}
#endif
62 63


64
protected:
65
	bool IsDefined() const noexcept {
66
#ifdef _WIN32
67 68
		return handle != INVALID_HANDLE_VALUE;
#else
69
		return fd.IsDefined();
70 71 72
#endif
	}

73
public:
74
#ifndef _WIN32
75
	FileDescriptor GetFD() const noexcept {
76 77 78 79
		return fd;
	}
#endif

80
	void Close() noexcept;
81

82
	FileInfo GetFileInfo() const;
83

84
	gcc_pure
85
	uint64_t GetSize() const noexcept {
86
#ifdef _WIN32
87 88 89 90 91 92 93 94 95 96
		LARGE_INTEGER size;
		return GetFileSizeEx(handle, &size)
			? size.QuadPart
			: 0;
#else
		return fd.GetSize();
#endif
	}

	gcc_pure
97
	uint64_t GetPosition() const noexcept {
98
#ifdef _WIN32
99 100 101 102 103 104 105 106 107 108 109
		LARGE_INTEGER zero;
		zero.QuadPart = 0;
		LARGE_INTEGER position;
		return SetFilePointerEx(handle, zero, &position, FILE_CURRENT)
			? position.QuadPart
			: 0;
#else
		return fd.Tell();
#endif
	}

110 111 112 113
	void Rewind() {
		Seek(0);
	}

114
	void Seek(off_t offset);
115
	void Skip(off_t offset);
116

117
	/* virtual methods from class Reader */
118
	size_t Read(void *data, size_t size) override;
119 120 121
};

#endif