make Range::size() constexpr
[folly.git] / folly / Optional.h
index dcc184aa585eafb0022dc0715580cb44696e59c6..09b831f8ae2804317d6a0a74559e1ad6824bb1ff 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2014 Facebook, Inc.
+ * Copyright 2016 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef FOLLY_OPTIONAL_H_
-#define FOLLY_OPTIONAL_H_
+#pragma once
 
 /*
  * Optional - For conditional initialization of values, like boost::optional,
  *    cout << *v << endl;
  *  }
  */
-#include <cassert>
 #include <cstddef>
+#include <new>
+#include <stdexcept>
 #include <type_traits>
 #include <utility>
 
-#include <boost/operators.hpp>
-
-#include <folly/Portability.h>
-
 namespace folly {
 
 namespace detail { struct NoneHelper {}; }
@@ -82,14 +78,23 @@ const None none = nullptr;
 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
 #endif // __GNUC__
 
+class OptionalEmptyException : public std::runtime_error {
+ public:
+  OptionalEmptyException()
+      : std::runtime_error("Empty Optional cannot be unwrapped") {}
+};
+
 template<class Value>
 class Optional {
  public:
+  typedef Value value_type;
+
   static_assert(!std::is_reference<Value>::value,
                 "Optional may not be used with reference types");
+  static_assert(!std::is_abstract<Value>::value,
+                "Optional may not be used with abstract types");
 
-  Optional()
-    : hasValue_(false) {
+  Optional() noexcept {
   }
 
   Optional(const Optional& src)
@@ -97,8 +102,6 @@ class Optional {
 
     if (src.hasValue()) {
       construct(src.value());
-    } else {
-      hasValue_ = false;
     }
   }
 
@@ -108,13 +111,10 @@ class Optional {
     if (src.hasValue()) {
       construct(std::move(src.value()));
       src.clear();
-    } else {
-      hasValue_ = false;
     }
   }
 
-  /* implicit */ Optional(const None&) noexcept
-    : hasValue_(false) {
+  /* implicit */ Optional(const None&) noexcept {
   }
 
   /* implicit */ Optional(Value&& newValue)
@@ -127,10 +127,6 @@ class Optional {
     construct(newValue);
   }
 
-  ~Optional() noexcept {
-    clear();
-  }
-
   void assign(const None&) {
     clear();
   }
@@ -156,7 +152,7 @@ class Optional {
 
   void assign(Value&& newValue) {
     if (hasValue()) {
-      value_ = std::move(newValue);
+      storage_.value = std::move(newValue);
     } else {
       construct(std::move(newValue));
     }
@@ -164,7 +160,7 @@ class Optional {
 
   void assign(const Value& newValue) {
     if (hasValue()) {
-      value_ = newValue;
+      storage_.value = newValue;
     } else {
       construct(newValue);
     }
@@ -197,30 +193,41 @@ class Optional {
   }
 
   void clear() {
-    if (hasValue()) {
-      hasValue_ = false;
-      value_.~Value();
-    }
+    storage_.clear();
+  }
+
+  const Value& value() const& {
+    require_value();
+    return storage_.value;
   }
 
-  const Value& value() const {
-    assert(hasValue());
-    return value_;
+  Value& value() & {
+    require_value();
+    return storage_.value;
   }
 
-  Value& value() {
-    assert(hasValue());
-    return value_;
+  Value value() && {
+    require_value();
+    return std::move(storage_.value);
   }
 
-  bool hasValue() const { return hasValue_; }
+  const Value* get_pointer() const&  {
+    return storage_.hasValue ? &storage_.value : nullptr;
+  }
+  Value* get_pointer() & {
+    return storage_.hasValue ? &storage_.value : nullptr;
+  }
+  Value* get_pointer() && = delete;
+
+  bool hasValue() const { return storage_.hasValue; }
 
   explicit operator bool() const {
     return hasValue();
   }
 
-  const Value& operator*() const { return value(); }
-        Value& operator*()       { return value(); }
+  const Value& operator*() const&  { return value(); }
+        Value& operator*()      &  { return value(); }
+        Value  operator*()      && { return std::move(value()); }
 
   const Value* operator->() const { return &value(); }
         Value* operator->()       { return &value(); }
@@ -228,26 +235,74 @@ class Optional {
   // Return a copy of the value if set, or a given default if not.
   template <class U>
   Value value_or(U&& dflt) const& {
-    return hasValue_ ? value_ : std::forward<U>(dflt);
+    if (storage_.hasValue) {
+      return storage_.value;
+    }
+
+    return std::forward<U>(dflt);
   }
 
   template <class U>
   Value value_or(U&& dflt) && {
-    return hasValue_ ? std::move(value_) : std::forward<U>(dflt);
+    if (storage_.hasValue) {
+      return std::move(storage_.value);
+    }
+
+    return std::forward<U>(dflt);
   }
 
  private:
+  void require_value() const {
+    if (!storage_.hasValue) {
+      throw OptionalEmptyException();
+    }
+  }
+
   template<class... Args>
   void construct(Args&&... args) {
-    const void* ptr = &value_;
+    const void* ptr = &storage_.value;
     // for supporting const types
     new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
-    hasValue_ = true;
+    storage_.hasValue = true;
   }
 
-  // uninitialized
-  union { Value value_; };
-  bool hasValue_;
+  struct StorageTriviallyDestructible {
+    // uninitialized
+    union { Value value; };
+    bool hasValue;
+
+    StorageTriviallyDestructible() : hasValue{false} {}
+
+    void clear() {
+      hasValue = false;
+    }
+  };
+
+  struct StorageNonTriviallyDestructible {
+    // uninitialized
+    union { Value value; };
+    bool hasValue;
+
+    StorageNonTriviallyDestructible() : hasValue{false} {}
+
+    ~StorageNonTriviallyDestructible() {
+      clear();
+    }
+
+    void clear() {
+      if (hasValue) {
+        hasValue = false;
+        value.~Value();
+      }
+    }
+  };
+
+  using Storage =
+    typename std::conditional<std::is_trivially_destructible<Value>::value,
+                              StorageTriviallyDestructible,
+                              StorageNonTriviallyDestructible>::type;
+
+  Storage storage_;
 };
 
 #if defined(__GNUC__) && !defined(__clang__)
@@ -256,12 +311,12 @@ class Optional {
 
 template<class T>
 const T* get_pointer(const Optional<T>& opt) {
-  return opt ? &opt.value() : nullptr;
+  return opt.get_pointer();
 }
 
 template<class T>
 T* get_pointer(Optional<T>& opt) {
-  return opt ? &opt.value() : nullptr;
+  return opt.get_pointer();
 }
 
 template<class T>
@@ -338,7 +393,7 @@ bool operator>=(const Optional<V>& a, const Optional<V>& b) {
   return !(a < b);
 }
 
-// To supress comparability of Optional<T> with T, despite implicit conversion.
+// Suppress comparability of Optional<T> with T, despite implicit conversion.
 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
@@ -351,5 +406,3 @@ template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
 ///////////////////////////////////////////////////////////////////////////////
 
 } // namespace folly
-
-#endif // FOLLY_OPTIONAL_H_