Skip to content

Commit

Permalink
Optional: allow holding non-default-constructable-type (#9223)
Browse files Browse the repository at this point in the history
  • Loading branch information
kghost authored Aug 30, 2021
1 parent 62165b1 commit 814806f
Show file tree
Hide file tree
Showing 11 changed files with 412 additions and 50 deletions.
1 change: 1 addition & 0 deletions build/config/compiler/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ config("disabled_warnings") {
cflags = [
"-Wno-deprecated-declarations",
"-Wno-unknown-warning-option",
"-Wno-maybe-uninitialized",
"-Wno-missing-field-initializers",
"-Wno-unused-parameter",
]
Expand Down
40 changes: 40 additions & 0 deletions src/lib/core/InPlace.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* @file
* This file defines the chip::Optional class to handle values which may
* or may not be present.
*
*/
#pragma once

#include <core/CHIPCore.h>
#include <lib/core/InPlace.h>
#include <lib/support/Variant.h>

namespace chip {

/// InPlace is disambiguation tags that can be passed to the constructors to indicate that the contained object should be
/// constructed in-place
struct InPlaceType
{
explicit InPlaceType() = default;
};
constexpr InPlaceType InPlace{};

} // namespace chip
148 changes: 115 additions & 33 deletions src/lib/core/Optional.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
*/
#pragma once

#include <assert.h>
#include <core/CHIPCore.h>
#include <lib/core/InPlace.h>
#include <lib/support/Variant.h>

namespace chip {

Expand All @@ -36,79 +38,159 @@ class Optional
{
public:
constexpr Optional() : mHasValue(false) {}
explicit Optional(const T & value) : mValue(value), mHasValue(true) {}
~Optional()
{
if (mHasValue)
{
mValue.mData.~T();
}
}

explicit Optional(const T & value) : mHasValue(true) { new (&mValue.mData) T(value); }

template <class... Args>
constexpr explicit Optional(InPlaceType, Args &&... args) : mHasValue(true)
{
new (&mValue.mData) T(std::forward<Args>(args)...);
}

constexpr Optional(const Optional & other) = default;
constexpr Optional(Optional && other) = default;
constexpr Optional(const Optional & other) : mHasValue(other.mHasValue)
{
if (mHasValue)
{
new (&mValue.mData) T(other.mValue.mData);
}
}

constexpr Optional(Optional && other) : mHasValue(other.mHasValue)
{
if (mHasValue)
{
new (&mValue.mData) T(std::move(other.mValue.mData));
other.mValue.mData.~T();
other.mHasValue = false;
}
}

/**
* Assignment operator implementation.
*
* NOTE: Manually implemented instead of =default since other::mValue may not be initialized
* if it has no value.
*/
constexpr Optional & operator=(const Optional & other)
{
if (other.HasValue())
if (mHasValue)
{
SetValue(other.Value());
mValue.mData.~T();
}
else
mHasValue = other.mHasValue;
if (mHasValue)
{
ClearValue();
new (&mValue.mData) T(other.mValue.mData);
}
return *this;
}

constexpr Optional & operator=(Optional && other)
{
if (mHasValue)
{
mValue.mData.~T();
}
mHasValue = other.mHasValue;
if (mHasValue)
{
new (&mValue.mData) T(std::move(other.mValue.mData));
other.mValue.mData.~T();
other.mHasValue = false;
}
return *this;
}

/// Constructs the contained value in-place
template <class... Args>
constexpr T & Emplace(Args &&... args)
{
if (mHasValue)
{
mValue.mData.~T();
}
mHasValue = true;
new (&mValue.mData) T(std::forward<Args>(args)...);
return mValue.mData;
}

/** Make the optional contain a specific value */
constexpr void SetValue(const T & value)
{
mValue = value;
if (mHasValue)
{
mValue.mData.~T();
}
mHasValue = true;
new (&mValue.mData) T(value);
}

/** Make the optional contain a specific value */
constexpr void SetValue(T && value)
{
if (mHasValue)
{
mValue.mData.~T();
}
mHasValue = true;
new (&mValue.mData) T(std::move(value));
}

/** Invalidate the value inside the optional. Optional now has no value */
constexpr void ClearValue() { mHasValue = false; }
constexpr void ClearValue()
{
if (mHasValue)
{
mValue.mData.~T();
}
mHasValue = false;
}

/** Gets the current value of the optional. Valid IFF `HasValue`. */
const T & Value() const
{
assert(HasValue());
return mValue;
VerifyOrDie(HasValue());
return mValue.mData;
}

/** 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;
}
const T & ValueOr(const T & defaultValue) const { return HasValue() ? Value() : defaultValue; }

/** Checks if the optional contains a value or not */
constexpr bool HasValue() const { return mHasValue; }

/** Comparison operator, handling missing values. */
bool operator==(const Optional & other) const
{
return (mHasValue == other.mHasValue) && (!other.mHasValue || (mValue == other.mValue));
return (mHasValue == other.mHasValue) && (!other.mHasValue || (mValue.mData == other.mValue.mData));
}

/** Comparison operator, handling missing values. */
bool operator!=(const Optional & other) const { return !(*this == other); }

/** Convenience method to create an optional without a valid value. */
static Optional<T> Missing() { return Optional<T>(); }

/** Convenience method to create an optional containing the specified value. */
static Optional<T> Value(const T & value) { return Optional(value); }
template <class... Args>
static Optional<T> Value(Args &&... args)
{
return Optional(InPlace, std::forward<Args>(args)...);
}

private:
T mValue; ///< Value IFF optional contains a value
bool mHasValue; ///< True IFF optional contains a value
bool mHasValue;
union Value
{
Value() {}
~Value() {}
T mData;
} mValue;
};

template <class T, class... Args>
constexpr Optional<T> MakeOptional(Args &&... args)
{
return Optional<T>(InPlace, std::forward<Args>(args)...);
}

} // namespace chip
1 change: 1 addition & 0 deletions src/lib/core/tests/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ chip_test_suite("tests") {
"TestCHIPCallback.cpp",
"TestCHIPErrorStr.cpp",
"TestCHIPTLV.cpp",
"TestOptional.cpp",
"TestReferenceCounted.cpp",
]

Expand Down
Loading

0 comments on commit 814806f

Please sign in to comment.