blob: eb5bb630501d47534e05f910e2f8ea4c2e6cf5f9 [file] [log] [blame]
Changyeon Job927b882019-11-21 10:16:33 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "unique_fd.h"
18
19#include <errno.h>
20#include <string.h>
21
Changyeon Joffdf3db2020-03-06 15:23:02 -080022#include <android-base/logging.h>
Changyeon Job927b882019-11-21 10:16:33 -080023
24namespace android {
25namespace automotive {
26namespace evs {
27namespace V1_1 {
28namespace implementation {
29
30UniqueFd::UniqueFd() : fd_(-1) {}
31
32UniqueFd::UniqueFd(int fd) : fd_(fd) {
33}
34
35UniqueFd::~UniqueFd() {
36 InternalClose();
37}
38
39UniqueFd::UniqueFd(UniqueFd&& other) : fd_(other.fd_) {
40 other.fd_ = -1;
41}
42
43UniqueFd& UniqueFd::operator=(UniqueFd&& other) {
44 InternalClose();
45 fd_ = other.fd_;
46 other.fd_ = -1;
47 return *this;
48}
49
50void UniqueFd::Reset(int new_fd) {
51 InternalClose();
52 fd_ = new_fd;
53}
54
55UniqueFd UniqueFd::Dup() const {
56 return (fd_ >= 0) ? UniqueFd(InternalDup()) : UniqueFd(fd_);
57}
58
59UniqueFd::operator bool() const {
60 return fd_ >= 0;
61}
62
63int UniqueFd::Get() const {
64 return fd_;
65}
66
67int UniqueFd::GetUnowned() const {
68 return InternalDup();
69}
70
71int UniqueFd::Release() {
72 int ret = fd_;
73 fd_ = -1;
74 return ret;
75}
76
77void UniqueFd::InternalClose() {
78 if (fd_ >= 0) {
79 int err = close(fd_);
Changyeon Joffdf3db2020-03-06 15:23:02 -080080 if (err < 0) {
81 PLOG(FATAL) << "Error closing UniqueFd";
82 }
Changyeon Job927b882019-11-21 10:16:33 -080083 }
84 fd_ = -1;
85}
86
87int UniqueFd::InternalDup() const {
88 int new_fd = fd_ >= 0 ? dup(fd_) : fd_;
Changyeon Joffdf3db2020-03-06 15:23:02 -080089 if (new_fd < 0 && fd_ >= 0) {
90 PLOG(FATAL) << "Error duplicating UniqueFd";
91 }
Changyeon Job927b882019-11-21 10:16:33 -080092 return new_fd;
93}
94
95} // namespace implementation
96} // namespace V1_1
97} // namespace evs
98} // namespace automotive
99} // namespace android