Skip to content

Commit

Permalink
Add a ValueOr method to Optional
Browse files Browse the repository at this point in the history
This allows easier use of the "the value in the Optional or this
default value I have" pattern.
  • Loading branch information
bzbarsky-apple committed Nov 11, 2020
1 parent e1f34b3 commit 63c6301
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
11 changes: 11 additions & 0 deletions src/lib/core/Optional.h
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down
3 changes: 1 addition & 2 deletions src/protocols/echo/EchoClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions src/transport/SecurePairingSession.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ CHIP_ERROR SecurePairingSession::Serialize(SecurePairingSessionSerialized & outp
{
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<uint16_t>(mKeLen), error = CHIP_ERROR_INTERNAL);
VerifyOrExit(CanCastTo<uint64_t>(localNodeId), error = CHIP_ERROR_INTERNAL);
VerifyOrExit(CanCastTo<uint64_t>(peerNodeId), error = CHIP_ERROR_INTERNAL);
Expand Down

0 comments on commit 63c6301

Please sign in to comment.