summaryrefslogtreecommitdiff
path: root/include/libcamera/base/shared_fd.h
blob: e53a8b88601e234a6caea59e209b05ed6c6281a2 (plain)
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
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * shared_fd.h - File descriptor wrapper with shared ownership
 */

#pragma once

#include <memory>

namespace libcamera {

class UniqueFD;

class SharedFD final
{
public:
	explicit SharedFD(const int &fd = -1);
	explicit SharedFD(int &&fd);
	explicit SharedFD(UniqueFD fd);
	SharedFD(const SharedFD &other);
	SharedFD(SharedFD &&other);
	~SharedFD();

	SharedFD &operator=(const SharedFD &other);
	SharedFD &operator=(SharedFD &&other);

	bool isValid() const { return fd_ != nullptr; }
	int get() const { return fd_ ? fd_->fd() : -1; }
	UniqueFD dup() const;

private:
	class Descriptor
	{
	public:
		Descriptor(int fd, bool duplicate);
		~Descriptor();

		int fd() const { return fd_; }

	private:
		int fd_;
	};

	std::shared_ptr<Descriptor> fd_;
};

static inline bool operator==(const SharedFD &lhs, const SharedFD &rhs)
{
	return lhs.get() == rhs.get();
}

static inline bool operator!=(const SharedFD &lhs, const SharedFD &rhs)
{
	return !(lhs == rhs);
}

} /* namespace libcamera */