summaryrefslogtreecommitdiff
path: root/include/libcamera/base/unique_fd.h
blob: ae4d96b75797c1996d68dd3668b241fb95d427bc (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
60
61
62
63
64
65
66
67
68
69
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2021, Google Inc.
 *
 * unique_fd.h - File descriptor wrapper that owns a file descriptor.
 */

#pragma once

#include <utility>

#include <libcamera/base/class.h>
#include <libcamera/base/compiler.h>

namespace libcamera {

class UniqueFD final
{
public:
	UniqueFD()
		: fd_(-1)
	{
	}

	explicit UniqueFD(int fd)
		: fd_(fd)
	{
	}

	UniqueFD(UniqueFD &&other)
		: fd_(other.release())
	{
	}

	~UniqueFD()
	{
		reset();
	}

	UniqueFD &operator=(UniqueFD &&other)
	{
		reset(other.release());
		return *this;
	}

	__nodiscard int release()
	{
		int fd = fd_;
		fd_ = -1;
		return fd;
	}

	void reset(int fd = -1);

	void swap(UniqueFD &other)
	{
		std::swap(fd_, other.fd_);
	}

	int get() const { return fd_; }
	bool isValid() const { return fd_ >= 0; }

private:
	LIBCAMERA_DISABLE_COPY(UniqueFD)

	int fd_;
};

} /* namespace libcamera */