1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "mozilla/ipc/ScopedPort.h"
8 #include "mozilla/ipc/NodeController.h"
9 #include "chrome/common/ipc_message_utils.h"
10
11 namespace mozilla::ipc {
12
Reset()13 void ScopedPort::Reset() {
14 if (mValid) {
15 mController->ClosePort(mPort);
16 }
17 mValid = false;
18 mPort = {};
19 mController = nullptr;
20 }
21
Release()22 auto ScopedPort::Release() -> PortRef {
23 if (!mValid) {
24 return {};
25 }
26 mValid = false;
27 mController = nullptr;
28 return std::exchange(mPort, PortRef{});
29 }
30
31 ScopedPort::ScopedPort() = default;
32
~ScopedPort()33 ScopedPort::~ScopedPort() { Reset(); }
34
ScopedPort(PortRef aPort,NodeController * aController)35 ScopedPort::ScopedPort(PortRef aPort, NodeController* aController)
36 : mValid(true), mPort(std::move(aPort)), mController(aController) {
37 MOZ_ASSERT(mPort.is_valid() && mController);
38 }
39
ScopedPort(ScopedPort && aOther)40 ScopedPort::ScopedPort(ScopedPort&& aOther)
41 : mValid(std::exchange(aOther.mValid, false)),
42 mPort(std::move(aOther.mPort)),
43 mController(std::move(aOther.mController)) {}
44
operator =(ScopedPort && aOther)45 ScopedPort& ScopedPort::operator=(ScopedPort&& aOther) {
46 if (this != &aOther) {
47 Reset();
48 mValid = std::exchange(aOther.mValid, false);
49 mPort = std::move(aOther.mPort);
50 mController = std::move(aOther.mController);
51 }
52 return *this;
53 }
54
55 } // namespace mozilla::ipc
56
Write(Message * aMsg,paramType && aParam)57 void IPC::ParamTraits<mozilla::ipc::ScopedPort>::Write(Message* aMsg,
58 paramType&& aParam) {
59 aMsg->WriteBool(aParam.IsValid());
60 if (!aParam.IsValid()) {
61 return;
62 }
63 aMsg->WritePort(std::move(aParam));
64 }
65
Read(const Message * aMsg,PickleIterator * aIter,paramType * aResult)66 bool IPC::ParamTraits<mozilla::ipc::ScopedPort>::Read(const Message* aMsg,
67 PickleIterator* aIter,
68 paramType* aResult) {
69 bool isValid = false;
70 if (!aMsg->ReadBool(aIter, &isValid)) {
71 return false;
72 }
73 if (!isValid) {
74 *aResult = {};
75 return true;
76 }
77 return aMsg->ConsumePort(aIter, aResult);
78 }
79