Remove template helper constants
[folly.git] / folly / Optional.h
index 38f198fdc5f8fc0cb02cd95d4c8880769beac1e0..f8d39cb8cc39e0ce9b4407041e5a9d329be7e825 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2015 Facebook, Inc.
+ * Copyright 2017 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 <cstddef>
+#include <functional>
+#include <new>
 #include <stdexcept>
 #include <type_traits>
 #include <utility>
 
+#include <folly/Launder.h>
+#include <folly/Portability.h>
+#include <folly/Utility.h>
+
 namespace folly {
 
-namespace detail { struct NoneHelper {}; }
+namespace detail {
+struct NoneHelper {};
+
+// Allow each translation unit to control its own -fexceptions setting.
+// If exceptions are disabled, std::terminate() will be called instead of
+// throwing OptionalEmptyException when the condition fails.
+[[noreturn]] void throw_optional_empty_exception();
+}
 
 typedef int detail::NoneHelper::*None;
 
 const None none = nullptr;
 
-/**
- * gcc-4.7 warns about use of uninitialized memory around the use of storage_
- * even though this is explicitly initialized at each point.
- */
-#if defined(__GNUC__) && !defined(__clang__)
-# pragma GCC diagnostic push
-# pragma GCC diagnostic ignored "-Wuninitialized"
-# pragma GCC diagnostic ignored "-Wpragmas"
-# 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>
+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() noexcept
-    : hasValue_(false) {
-  }
+  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(const Optional& src)
-    noexcept(std::is_nothrow_copy_constructible<Value>::value) {
+  Optional() noexcept {}
 
+  Optional(const Optional& src) noexcept(
+      std::is_nothrow_copy_constructible<Value>::value) {
     if (src.hasValue()) {
-      construct(src.value());
-    } else {
-      hasValue_ = false;
+      storage_.construct(src.value());
     }
   }
 
-  Optional(Optional&& src)
-    noexcept(std::is_nothrow_move_constructible<Value>::value) {
-
+  Optional(Optional&& src) noexcept(
+      std::is_nothrow_move_constructible<Value>::value) {
     if (src.hasValue()) {
-      construct(std::move(src.value()));
+      storage_.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)
-    noexcept(std::is_nothrow_move_constructible<Value>::value) {
-    construct(std::move(newValue));
+  /* implicit */ Optional(Value&& newValue) noexcept(
+      std::is_nothrow_move_constructible<Value>::value) {
+    storage_.construct(std::move(newValue));
   }
 
-  /* implicit */ Optional(const Value& newValue)
-    noexcept(std::is_nothrow_copy_constructible<Value>::value) {
-    construct(newValue);
+  /* implicit */ Optional(const Value& newValue) noexcept(
+      std::is_nothrow_copy_constructible<Value>::value) {
+    storage_.construct(newValue);
   }
 
-  ~Optional() noexcept {
-    clear();
+  template <typename... Args>
+  explicit Optional(in_place_t, Args&&... args) noexcept(
+      std::is_nothrow_constructible<Value, Args...>::value) {
+    storage_.construct(std::forward<Args>(args)...);
   }
 
   void assign(const None&) {
@@ -162,131 +158,211 @@ class Optional {
 
   void assign(Value&& newValue) {
     if (hasValue()) {
-      value_ = std::move(newValue);
+      *storage_.value_pointer() = std::move(newValue);
     } else {
-      construct(std::move(newValue));
+      storage_.construct(std::move(newValue));
     }
   }
 
   void assign(const Value& newValue) {
     if (hasValue()) {
-      value_ = newValue;
+      *storage_.value_pointer() = newValue;
     } else {
-      construct(newValue);
+      storage_.construct(newValue);
     }
   }
 
-  template<class Arg>
+  template <class Arg>
   Optional& operator=(Arg&& arg) {
     assign(std::forward<Arg>(arg));
     return *this;
   }
 
-  Optional& operator=(Optional &&other)
-    noexcept (std::is_nothrow_move_assignable<Value>::value) {
-
+  Optional& operator=(Optional&& other) noexcept(
+      std::is_nothrow_move_assignable<Value>::value) {
     assign(std::move(other));
     return *this;
   }
 
-  Optional& operator=(const Optional &other)
-    noexcept (std::is_nothrow_copy_assignable<Value>::value) {
-
+  Optional& operator=(const Optional& other) noexcept(
+      std::is_nothrow_copy_assignable<Value>::value) {
     assign(other);
     return *this;
   }
 
-  template<class... Args>
+  template <class... Args>
   void emplace(Args&&... args) {
     clear();
-    construct(std::forward<Args>(args)...);
+    storage_.construct(std::forward<Args>(args)...);
   }
 
   void clear() {
-    if (hasValue()) {
-      hasValue_ = false;
-      value_.~Value();
-    }
+    storage_.clear();
   }
 
-  const Value& value() const& {
+  const Value& value() const & {
     require_value();
-    return value_;
+    return *storage_.value_pointer();
   }
 
   Value& value() & {
     require_value();
-    return value_;
+    return *storage_.value_pointer();
+  }
+
+  Value&& value() && {
+    require_value();
+    return std::move(*storage_.value_pointer());
   }
 
-  Value value() && {
+  const Value&& value() const && {
     require_value();
-    return std::move(value_);
+    return std::move(*storage_.value_pointer());
   }
 
-  const Value* get_pointer() const&  { return hasValue_ ? &value_ : nullptr; }
-        Value* get_pointer()      &  { return hasValue_ ? &value_ : nullptr; }
-        Value* get_pointer()      && = delete;
+  const Value* get_pointer() const & {
+    return storage_.value_pointer();
+  }
+  Value* get_pointer() & {
+    return storage_.value_pointer();
+  }
+  Value* get_pointer() && = delete;
 
-  bool hasValue() const { return hasValue_; }
+  bool hasValue() const {
+    return storage_.hasValue();
+  }
 
   explicit operator bool() const {
     return hasValue();
   }
 
-  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();
+  }
+  const Value&& operator*() const && {
+    return std::move(value());
+  }
+  Value&& operator*() && {
+    return std::move(value());
+  }
 
-  const Value* operator->() const { return &value(); }
-        Value* operator->()       { return &value(); }
+  const Value* operator->() const {
+    return &value();
+  }
+  Value* operator->() {
+    return &value();
+  }
 
   // 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);
+  Value value_or(U&& dflt) const & {
+    if (storage_.hasValue()) {
+      return *storage_.value_pointer();
+    }
+
+    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_pointer());
+    }
+
+    return std::forward<U>(dflt);
   }
 
  private:
   void require_value() const {
-    if (!hasValue_) {
-      throw OptionalEmptyException();
+    if (!storage_.hasValue()) {
+      detail::throw_optional_empty_exception();
     }
   }
 
-  template<class... Args>
-  void construct(Args&&... args) {
-    const void* ptr = &value_;
-    // for supporting const types
-    new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
-    hasValue_ = true;
-  }
+  struct StorageTriviallyDestructible {
+   protected:
+    bool hasValue_;
+    typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
+        value_[1];
 
-  // uninitialized
-  union { Value value_; };
-  bool hasValue_;
-};
+   public:
+    StorageTriviallyDestructible() : hasValue_{false} {}
+    void clear() {
+      hasValue_ = false;
+    }
+  };
 
-#if defined(__GNUC__) && !defined(__clang__)
-#pragma GCC diagnostic pop
-#endif
+  struct StorageNonTriviallyDestructible {
+   protected:
+    bool hasValue_;
+    typename std::aligned_storage<sizeof(Value), alignof(Value)>::type
+        value_[1];
+
+   public:
+    StorageNonTriviallyDestructible() : hasValue_{false} {}
+    ~StorageNonTriviallyDestructible() {
+      clear();
+    }
+
+    void clear() {
+      if (hasValue_) {
+        hasValue_ = false;
+        launder(reinterpret_cast<Value*>(value_))->~Value();
+      }
+    }
+  };
+
+  struct Storage : std::conditional<
+                       std::is_trivially_destructible<Value>::value,
+                       StorageTriviallyDestructible,
+                       StorageNonTriviallyDestructible>::type {
+    bool hasValue() const {
+      return this->hasValue_;
+    }
+
+    Value* value_pointer() {
+      if (this->hasValue_) {
+        return launder(reinterpret_cast<Value*>(this->value_));
+      }
+      return nullptr;
+    }
 
-template<class T>
+    Value const* value_pointer() const {
+      if (this->hasValue_) {
+        return launder(reinterpret_cast<Value const*>(this->value_));
+      }
+      return nullptr;
+    }
+
+    template <class... Args>
+    void construct(Args&&... args) {
+      new (raw_pointer()) Value(std::forward<Args>(args)...);
+      this->hasValue_ = true;
+    }
+
+   private:
+    void* raw_pointer() {
+      return static_cast<void*>(this->value_);
+    }
+  };
+
+  Storage storage_;
+};
+
+template <class T>
 const T* get_pointer(const Optional<T>& opt) {
   return opt.get_pointer();
 }
 
-template<class T>
+template <class T>
 T* get_pointer(Optional<T>& opt) {
   return opt.get_pointer();
 }
 
-template<class T>
+template <class T>
 void swap(Optional<T>& a, Optional<T>& b) {
   if (a.hasValue() && b.hasValue()) {
     // both full
@@ -297,8 +373,7 @@ void swap(Optional<T>& a, Optional<T>& b) {
   }
 }
 
-template<class T,
-         class Opt = Optional<typename std::decay<T>::type>>
+template <class T, class Opt = Optional<typename std::decay<T>::type>>
 Opt make_optional(T&& v) {
   return Opt(std::forward<T>(v));
 }
@@ -306,72 +381,99 @@ Opt make_optional(T&& v) {
 ///////////////////////////////////////////////////////////////////////////////
 // Comparisons.
 
-template<class V>
-bool operator==(const Optional<V>& a, const V& b) {
+template <class U, class V>
+bool operator==(const Optional<U>& a, const V& b) {
   return a.hasValue() && a.value() == b;
 }
 
-template<class V>
-bool operator!=(const Optional<V>& a, const V& b) {
+template <class U, class V>
+bool operator!=(const Optional<U>& a, const V& b) {
   return !(a == b);
 }
 
-template<class V>
-bool operator==(const V& a, const Optional<V>& b) {
+template <class U, class V>
+bool operator==(const U& a, const Optional<V>& b) {
   return b.hasValue() && b.value() == a;
 }
 
-template<class V>
-bool operator!=(const V& a, const Optional<V>& b) {
+template <class U, class V>
+bool operator!=(const U& a, const Optional<V>& b) {
   return !(a == b);
 }
 
-template<class V>
-bool operator==(const Optional<V>& a, const Optional<V>& b) {
-  if (a.hasValue() != b.hasValue()) { return false; }
-  if (a.hasValue())                 { return a.value() == b.value(); }
+template <class U, class V>
+bool operator==(const Optional<U>& a, const Optional<V>& b) {
+  if (a.hasValue() != b.hasValue()) {
+    return false;
+  }
+  if (a.hasValue()) {
+    return a.value() == b.value();
+  }
   return true;
 }
 
-template<class V>
-bool operator!=(const Optional<V>& a, const Optional<V>& b) {
+template <class U, class V>
+bool operator!=(const Optional<U>& a, const Optional<V>& b) {
   return !(a == b);
 }
 
-template<class V>
-bool operator< (const Optional<V>& a, const Optional<V>& b) {
-  if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
-  if (a.hasValue())                 { return a.value()    < b.value(); }
+template <class U, class V>
+bool operator<(const Optional<U>& a, const Optional<V>& b) {
+  if (a.hasValue() != b.hasValue()) {
+    return a.hasValue() < b.hasValue();
+  }
+  if (a.hasValue()) {
+    return a.value() < b.value();
+  }
   return false;
 }
 
-template<class V>
-bool operator> (const Optional<V>& a, const Optional<V>& b) {
+template <class U, class V>
+bool operator>(const Optional<U>& a, const Optional<V>& b) {
   return b < a;
 }
 
-template<class V>
-bool operator<=(const Optional<V>& a, const Optional<V>& b) {
+template <class U, class V>
+bool operator<=(const Optional<U>& a, const Optional<V>& b) {
   return !(b < a);
 }
 
-template<class V>
-bool operator>=(const Optional<V>& a, const Optional<V>& b) {
+template <class U, class V>
+bool operator>=(const Optional<U>& a, const Optional<V>& b) {
   return !(a < b);
 }
 
 // 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;
-template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
-template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
-template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
-template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
-template<class V> bool operator> (const V& other, const Optional<V>&) = 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;
+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 V& other, const Optional<V>&) = delete;
+template <class V>
+bool operator<=(const V& other, const Optional<V>&) = delete;
+template <class V>
+bool operator>=(const V& other, const Optional<V>&) = delete;
+template <class V>
+bool operator>(const V& other, const Optional<V>&) = delete;
 
 ///////////////////////////////////////////////////////////////////////////////
 
 } // namespace folly
 
-#endif // FOLLY_OPTIONAL_H_
+// Allow usage of Optional<T> in std::unordered_map and std::unordered_set
+FOLLY_NAMESPACE_STD_BEGIN
+template <class T>
+struct hash<folly::Optional<T>> {
+  size_t operator()(folly::Optional<T> const& obj) const {
+    if (!obj.hasValue()) {
+      return 0;
+    }
+    return hash<typename remove_const<T>::type>()(*obj);
+  }
+};
+FOLLY_NAMESPACE_STD_END