1 // Copyright 2014-2017 The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #pragma once 16 17 #include "aemu/base/sockets/SocketUtils.h" 18 19 #include <utility> 20 21 namespace android { 22 namespace base { 23 24 class ScopedSocket { 25 public: 26 constexpr ScopedSocket() = default; ScopedSocket(int socket)27 constexpr ScopedSocket(int socket) : mSocket(socket) {} ScopedSocket(ScopedSocket && other)28 ScopedSocket(ScopedSocket&& other) : mSocket(other.release()) {} ~ScopedSocket()29 ~ScopedSocket() { close(); } 30 31 ScopedSocket& operator=(ScopedSocket&& other) { 32 reset(other.release()); 33 return *this; 34 } 35 valid()36 bool valid() const { return mSocket >= 0; } 37 get()38 int get() const { return mSocket; } 39 close()40 void close() { 41 if (valid()) { 42 socketClose(release()); 43 } 44 } 45 release()46 int release() { 47 int result = mSocket; 48 mSocket = -1; 49 return result; 50 } 51 reset(int socket)52 void reset(int socket) { 53 close(); 54 mSocket = socket; 55 } 56 swap(ScopedSocket * other)57 void swap(ScopedSocket* other) { 58 std::swap(mSocket, other->mSocket); 59 } 60 61 private: 62 int mSocket = -1; 63 }; 64 swap(ScopedSocket & one,ScopedSocket & two)65inline void swap(ScopedSocket& one, ScopedSocket& two) { 66 one.swap(&two); 67 } 68 69 } // namespace base 70 } // namespace android 71