From b9d5b6d0b027fc365d084c952f0fc0be23585511 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Tue, 10 Nov 2020 23:38:42 -0500 Subject: [PATCH] Add a ValueOr method to Optional This allows easier use of the "the value in the Optional or this default value I have" pattern. --- src/lib/core/Optional.h | 11 +++++++++++ src/protocols/echo/EchoClient.cpp | 3 +-- src/transport/SecurePairingSession.cpp | 4 ++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/lib/core/Optional.h b/src/lib/core/Optional.h index 380c3bf10bd2a3..d49ed49d88fcf6 100644 --- a/src/lib/core/Optional.h +++ b/src/lib/core/Optional.h @@ -59,6 +59,17 @@ class Optional return mValue; } + /** Gets the current value of the optional if the optional has a value; + otherwise returns the provided default value. */ + const T & ValueOr(const T & defaultValue) const + { + if (HasValue()) + { + return mValue; + } + return defaultValue; + } + /** Checks if the optional contains a value or not */ bool HasValue() const { return mHasValue; } diff --git a/src/protocols/echo/EchoClient.cpp b/src/protocols/echo/EchoClient.cpp index 1731a7c215cf21..33de0f00104b93 100644 --- a/src/protocols/echo/EchoClient.cpp +++ b/src/protocols/echo/EchoClient.cpp @@ -117,8 +117,7 @@ void EchoClient::OnMessageReceived(ExchangeContext * ec, const PacketHeader & pa // Call the registered OnEchoResponseReceived handler, if any. if (echoApp->OnEchoResponseReceived != nullptr) { - echoApp->OnEchoResponseReceived(packetHeader.GetSourceNodeId().HasValue() ? packetHeader.GetSourceNodeId().Value() : 0, - payload); + echoApp->OnEchoResponseReceived(packetHeader.GetSourceNodeId().ValueOr(0), payload); } exit: diff --git a/src/transport/SecurePairingSession.cpp b/src/transport/SecurePairingSession.cpp index 780654bd82676d..c46c392b1cfbbe 100644 --- a/src/transport/SecurePairingSession.cpp +++ b/src/transport/SecurePairingSession.cpp @@ -104,8 +104,8 @@ CHIP_ERROR SecurePairingSession::ToSerializable(SecurePairingSessionSerializable { CHIP_ERROR error = CHIP_NO_ERROR; - const NodeId localNodeId = (mLocalNodeId.HasValue()) ? mLocalNodeId.Value() : kUndefinedNodeId; - const NodeId peerNodeId = (mPeerNodeId.HasValue()) ? mPeerNodeId.Value() : kUndefinedNodeId; + const NodeId localNodeId = mLocalNodeId.ValueOr(kUndefinedNodeId); + const NodeId peerNodeId = mPeerNodeId.ValueOr(kUndefinedNodeId); VerifyOrExit(CanCastTo(mKeLen), error = CHIP_ERROR_INTERNAL); VerifyOrExit(CanCastTo(localNodeId), error = CHIP_ERROR_INTERNAL); VerifyOrExit(CanCastTo(peerNodeId), error = CHIP_ERROR_INTERNAL);