blob: 97e7a7967103ca769ca66daf19c0af539d1c828d [file] [log] [blame]
James Robinson646469d2014-10-03 15:33:28 -07001// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Viet-Trung Luu2fcb5be2015-11-30 12:16:33 -08005#ifndef MOJO_EDK_PLATFORM_SCOPED_PLATFORM_HANDLE_H_
6#define MOJO_EDK_PLATFORM_SCOPED_PLATFORM_HANDLE_H_
James Robinson646469d2014-10-03 15:33:28 -07007
Viet-Trung Luu2fcb5be2015-11-30 12:16:33 -08008#include "mojo/edk/platform/platform_handle.h"
Viet-Trung Luu2ef94242015-06-24 16:21:42 -07009#include "mojo/public/c/system/macros.h"
Viet-Trung Luud90ecca2015-09-16 16:11:23 -070010#include "mojo/public/cpp/system/macros.h"
James Robinson646469d2014-10-03 15:33:28 -070011
12namespace mojo {
Viet-Trung Luu2fcb5be2015-11-30 12:16:33 -080013namespace platform {
James Robinson646469d2014-10-03 15:33:28 -070014
Viet-Trung Luu7e4b2512015-09-17 10:39:26 -070015// Scoper for |PlatformHandle|s, which are just file descriptors.
Viet-Trung Luu535e5d92015-09-18 11:12:49 -070016class ScopedPlatformHandle {
James Robinson646469d2014-10-03 15:33:28 -070017 public:
18 ScopedPlatformHandle() {}
19 explicit ScopedPlatformHandle(PlatformHandle handle) : handle_(handle) {}
20 ~ScopedPlatformHandle() { handle_.CloseIfNecessary(); }
21
22 // Move-only constructor and operator=.
Michael Graczykb01dd3b2015-04-03 13:55:48 -070023 ScopedPlatformHandle(ScopedPlatformHandle&& other)
24 : handle_(other.release()) {}
25
26 ScopedPlatformHandle& operator=(ScopedPlatformHandle&& other) {
27 if (this != &other)
28 handle_ = other.release();
James Robinson646469d2014-10-03 15:33:28 -070029 return *this;
30 }
31
32 const PlatformHandle& get() const { return handle_; }
33
34 void swap(ScopedPlatformHandle& other) {
35 PlatformHandle temp = handle_;
36 handle_ = other.handle_;
37 other.handle_ = temp;
38 }
39
Viet-Trung Luu2ef94242015-06-24 16:21:42 -070040 PlatformHandle release() MOJO_WARN_UNUSED_RESULT {
James Robinson646469d2014-10-03 15:33:28 -070041 PlatformHandle rv = handle_;
42 handle_ = PlatformHandle();
43 return rv;
44 }
45
46 void reset(PlatformHandle handle = PlatformHandle()) {
47 handle_.CloseIfNecessary();
48 handle_ = handle;
49 }
50
51 bool is_valid() const { return handle_.is_valid(); }
52
Viet-Trung Luua76b9b42015-12-07 15:43:24 -080053 // Forwards to |PlatformHandle::Duplicate()|.
54 ScopedPlatformHandle Duplicate() const { return handle_.Duplicate(); }
55
James Robinson646469d2014-10-03 15:33:28 -070056 private:
57 PlatformHandle handle_;
Viet-Trung Luu6b5d61d2015-10-13 10:12:12 -070058
59 MOJO_MOVE_ONLY_TYPE(ScopedPlatformHandle);
James Robinson646469d2014-10-03 15:33:28 -070060};
61
Viet-Trung Luu2fcb5be2015-11-30 12:16:33 -080062} // namespace platform
James Robinson646469d2014-10-03 15:33:28 -070063} // namespace mojo
64
Viet-Trung Luu2fcb5be2015-11-30 12:16:33 -080065#endif // MOJO_EDK_PLATFORM_SCOPED_PLATFORM_HANDLE_H_