Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
piiswrong committed Dec 5, 2016
1 parent 37b5ca2 commit ea76561
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
11 changes: 6 additions & 5 deletions include/dmlc/optional.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class optional {
*reinterpret_cast<T*>(&val) = value;
}
/*! \brief construct an optional object with another optional object */
optional (const optional<T>& other) {
optional(const optional<T>& other) {
is_none = other.is_none;
if (!is_none) {
*reinterpret_cast<T*>(&val) =
Expand Down Expand Up @@ -87,7 +87,7 @@ class optional {
return *this;
}
/*! \brief non-const dereference operator */
T& operator*() {
T& operator*() { // NOLINT(*)
return *reinterpret_cast<T*>(&val);
}
/*! \brief const dereference operator */
Expand All @@ -105,11 +105,12 @@ class optional {
}
/*! \brief whether this object is holding a value */
explicit operator bool() const { return !is_none; }

private:
// whether this is none
bool is_none;
// on stack storage of value
std::aligned_storage<sizeof(T), sizeof(void*)> val;
typename std::aligned_storage<sizeof(T), sizeof(void*)>::type val;
};

/*! \brief serialize an optional object to string.
Expand All @@ -123,7 +124,7 @@ class optional {
*/
template<typename T>
std::ostream &operator<<(std::ostream &os, const optional<T> &t) {
if (bool(t)) {
if (t) {
os << *t;
} else {
os << "None";
Expand Down Expand Up @@ -164,6 +165,6 @@ std::istream &operator>>(std::istream &is, optional<T> &t) {

DMLC_DECLARE_TYPE_NAME(optional<int>, "optional<int>");

} // namespace optional
} // namespace dmlc

#endif // DMLC_OPTIONAL_H_
49 changes: 49 additions & 0 deletions test/unittest/unittest_optional.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright by Contributors

#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <dmlc/optional.h>
#include <gtest/gtest.h>


TEST(Optional, basics) {
dmlc::optional<int> x;
CHECK(!bool(x));
x = 1;
CHECK(bool(x));
CHECK_EQ(x.value(), 1);
x = dmlc::nullopt;
CHECK(!bool(x));
}

TEST(Optional, parsing) {
dmlc::optional<int> x;
{
std::ostringstream os;
os << x;
CHECK_EQ(os.str(), "None");
}

{
x = 1;
std::ostringstream os;
os << x;
CHECK_EQ(os.str(), "1");
}

{
std::string none("None");
std::istringstream is(none);
is >> x;
CHECK(!bool(x));
}

{
std::string one("1");
std::istringstream is(one);
is >> x;
CHECK_EQ(x.value(), 1);
}
}

0 comments on commit ea76561

Please sign in to comment.