blob: c740f28062244b83ddd8e0727f771a6f8b4ad050 [file] [log] [blame]
sleffler@chromium.org22fab402012-03-30 15:46:20 +09001// Copyright (c) 2012 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
reillyg41176c52015-06-11 15:19:11 +09005#include <algorithm>
6
cmasone54c7c082015-04-28 06:41:34 +09007#include "base/bind.h"
rvargas@chromium.org966a0bb2014-06-07 09:02:22 +09008#include "base/files/file.h"
cmasone54c7c082015-04-28 06:41:34 +09009#include "base/location.h"
sleffler@chromium.org48d575f2012-05-11 02:41:10 +090010#include "base/logging.h"
cmasone54c7c082015-04-28 06:41:34 +090011#include "base/threading/worker_pool.h"
sleffler@chromium.org22fab402012-03-30 15:46:20 +090012#include "dbus/file_descriptor.h"
13
reillyg41176c52015-06-11 15:19:11 +090014using std::swap;
15
sleffler@chromium.org22fab402012-03-30 15:46:20 +090016namespace dbus {
17
cmasone54c7c082015-04-28 06:41:34 +090018void CHROME_DBUS_EXPORT FileDescriptor::Deleter::operator()(
19 FileDescriptor* fd) {
20 base::WorkerPool::PostTask(
21 FROM_HERE, base::Bind(&base::DeletePointer<FileDescriptor>, fd), false);
22}
23
reillyg41176c52015-06-11 15:19:11 +090024FileDescriptor::FileDescriptor(RValue other)
25 : value_(-1), owner_(false), valid_(false) {
26 Swap(other.object);
27}
28
sleffler@chromium.org22fab402012-03-30 15:46:20 +090029FileDescriptor::~FileDescriptor() {
30 if (owner_)
rvargas@chromium.org966a0bb2014-06-07 09:02:22 +090031 base::File auto_closer(value_);
sleffler@chromium.org22fab402012-03-30 15:46:20 +090032}
33
reillyg41176c52015-06-11 15:19:11 +090034FileDescriptor& FileDescriptor::operator=(RValue other) {
35 Swap(other.object);
36 return *this;
37}
38
sleffler@chromium.org48d575f2012-05-11 02:41:10 +090039int FileDescriptor::value() const {
40 CHECK(valid_);
41 return value_;
42}
43
44int FileDescriptor::TakeValue() {
45 CHECK(valid_); // NB: check first so owner_ is unchanged if this triggers
46 owner_ = false;
47 return value_;
48}
49
50void FileDescriptor::CheckValidity() {
rvargas@chromium.org966a0bb2014-06-07 09:02:22 +090051 base::File file(value_);
reillyg0a19be32015-06-26 07:27:57 +090052 if (!file.IsValid()) {
53 valid_ = false;
54 return;
55 }
56
rvargas@chromium.org966a0bb2014-06-07 09:02:22 +090057 base::File::Info info;
58 bool ok = file.GetInfo(&info);
59 file.TakePlatformFile(); // Prevent |value_| from being closed by |file|.
sleffler@chromium.org48d575f2012-05-11 02:41:10 +090060 valid_ = (ok && !info.is_directory);
61}
62
reillyg41176c52015-06-11 15:19:11 +090063void FileDescriptor::Swap(FileDescriptor* other) {
64 swap(value_, other->value_);
65 swap(owner_, other->owner_);
66 swap(valid_, other->valid_);
67}
68
sleffler@chromium.org22fab402012-03-30 15:46:20 +090069} // namespace dbus