1 /* 2 * unique_fd.h - A unique file descriptor implementation 3 * 4 * Copyright (c) 2021 Rockchip Electronics Co., Ltd 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 * 18 * Author: Cody Xie <cody.xie@rock-chips.com> 19 */ 20 #ifndef _UNIQUE_FD_H_ 21 #define _UNIQUE_FD_H_ 22 23 #include <unistd.h> 24 25 namespace XCam { 26 27 class UniqueFd final { 28 public: UniqueFd()29 UniqueFd() : fd_(-1) {} UniqueFd(int fd)30 explicit UniqueFd(int fd) : fd_(fd) {} 31 32 UniqueFd(const UniqueFd&) = delete; 33 UniqueFd& operator=(const UniqueFd&) = delete; 34 35 UniqueFd& operator=(UniqueFd&& rhs) { 36 fd_ = Set(rhs.Release()); 37 return *this; 38 } 39 ~UniqueFd()40 ~UniqueFd() { 41 if (fd_ > 0) { 42 close(fd_); 43 } 44 } 45 Release()46 int Release() { 47 int old_fd = fd_; 48 fd_ = -1; 49 return old_fd; 50 } 51 Get()52 int Get() const { return fd_; } 53 Set(int fd)54 int Set(int fd) { 55 if (fd_ >= 0) { 56 close(fd_); 57 } 58 fd_ = fd; 59 return fd_; 60 } 61 62 private: 63 int fd_; 64 }; 65 66 } // namespace XCam 67 68 #endif // _UNIQUE_FD_H_ 69