optional.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. /*************************************************************************
  2. *
  3. * Copyright 2016 Realm Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. **************************************************************************/
  18. #pragma once
  19. #ifndef REALM_UTIL_OPTIONAL_HPP
  20. #define REALM_UTIL_OPTIONAL_HPP
  21. #include <realm/util/assert.hpp>
  22. #include <realm/util/backtrace.hpp>
  23. #include <stdexcept> // std::logic_error
  24. #include <functional> // std::less
  25. namespace realm {
  26. namespace util {
  27. template <class T>
  28. class Optional;
  29. // some() should be the equivalent of the proposed C++17 `make_optional`.
  30. template <class T, class... Args>
  31. Optional<T> some(Args&&...);
  32. template <class T>
  33. struct Some;
  34. // Note: Should conform with the future std::nullopt_t and std::in_place_t.
  35. struct None {
  36. constexpr explicit None(int)
  37. {
  38. }
  39. };
  40. static constexpr None none{0};
  41. struct InPlace {
  42. constexpr InPlace()
  43. {
  44. }
  45. };
  46. static constexpr InPlace in_place;
  47. // Note: Should conform with the future std::bad_optional_access.
  48. struct BadOptionalAccess : ExceptionWithBacktrace<std::logic_error> {
  49. using ExceptionWithBacktrace<std::logic_error>::ExceptionWithBacktrace;
  50. };
  51. } // namespace util
  52. namespace _impl {
  53. template <class T, bool = std::is_trivially_destructible<T>::value>
  54. struct OptionalStorage;
  55. template <class T, class U>
  56. struct TypeIsAssignableToOptional {
  57. // Constraints from [optional.object.assign.18]
  58. static const bool value = (std::is_same<typename std::remove_reference<U>::type, T>::value &&
  59. std::is_constructible<T, U>::value && std::is_assignable<T&, U>::value);
  60. };
  61. } // namespace _impl
  62. namespace util {
  63. // Note: Should conform with the future std::optional.
  64. template <class T>
  65. class Optional : private realm::_impl::OptionalStorage<T> {
  66. public:
  67. using value_type = T;
  68. constexpr Optional();
  69. constexpr Optional(None);
  70. Optional(Optional<T>&& other) noexcept;
  71. Optional(const Optional<T>& other);
  72. constexpr Optional(T&& value);
  73. constexpr Optional(const T& value);
  74. template <class... Args>
  75. constexpr Optional(InPlace tag, Args&&...);
  76. // FIXME: std::optional specifies an std::initializer_list constructor overload as well.
  77. Optional<T>& operator=(None) noexcept;
  78. Optional<T>& operator=(Optional<T>&& other) noexcept(std::is_nothrow_move_assignable<T>::value);
  79. Optional<T>& operator=(const Optional<T>& other) noexcept(std::is_nothrow_copy_assignable<T>::value);
  80. template <class U, class = typename std::enable_if<_impl::TypeIsAssignableToOptional<T, U>::value>::type>
  81. Optional<T>& operator=(U&& value);
  82. explicit constexpr operator bool() const;
  83. constexpr const T& value() const; // Throws
  84. T& value(); // Throws, FIXME: Can be constexpr with C++14
  85. constexpr const T& operator*() const; // Throws
  86. T& operator*(); // Throws, FIXME: Can be constexpr with C++14
  87. constexpr const T* operator->() const; // Throws
  88. T* operator->(); // Throws, FIXME: Can be constexpr with C++14
  89. template <class U>
  90. constexpr T value_or(U&& value) const &;
  91. template <class U>
  92. T value_or(U&& value) &&;
  93. void swap(Optional<T>& other); // FIXME: Add noexcept() clause
  94. template <class... Args>
  95. void emplace(Args&&...);
  96. // FIXME: std::optional specifies an std::initializer_list overload for `emplace` as well.
  97. void reset();
  98. private:
  99. using Storage = realm::_impl::OptionalStorage<T>;
  100. using Storage::m_engaged;
  101. using Storage::m_value;
  102. constexpr bool is_engaged() const
  103. {
  104. return m_engaged;
  105. }
  106. void set_engaged(bool b)
  107. {
  108. m_engaged = b;
  109. }
  110. };
  111. /// An Optional<void> is functionally equivalent to a bool.
  112. /// Note: C++17 does not (yet) specify this specialization, but it is convenient
  113. /// as a "safer bool", especially in the presence of `fmap`.
  114. /// Disabled for compliance with std::optional.
  115. // template <>
  116. // class Optional<void> {
  117. // public:
  118. // Optional() {}
  119. // Optional(None) {}
  120. // Optional(Optional<void>&&) = default;
  121. // Optional(const Optional<void>&) = default;
  122. // explicit operator bool() const { return m_engaged; }
  123. // private:
  124. // bool m_engaged = false;
  125. // friend struct Some<void>;
  126. // };
  127. /// An Optional<T&> is a non-owning nullable pointer that throws on dereference.
  128. // FIXME: Visual Studio 2015's constexpr support isn't sufficient to allow Optional<T&> to compile
  129. // in constexpr contexts.
  130. template <class T>
  131. class Optional<T&> {
  132. public:
  133. using value_type = T&;
  134. using target_type = typename std::decay<T>::type;
  135. constexpr Optional()
  136. {
  137. }
  138. constexpr Optional(None)
  139. {
  140. } // FIXME: Was a delegating constructor, but not fully supported in VS2015
  141. Optional(const Optional<T&>& other) = default;
  142. template <class U>
  143. Optional(const Optional<U&>& other) noexcept
  144. : m_ptr(other.m_ptr)
  145. {
  146. }
  147. template <class U>
  148. Optional(std::reference_wrapper<U> ref) noexcept
  149. : m_ptr(&ref.get())
  150. {
  151. }
  152. constexpr Optional(T& init_value) noexcept
  153. : m_ptr(&init_value)
  154. {
  155. }
  156. Optional(T&& value) = delete; // Catches accidental references to rvalue temporaries.
  157. Optional<T&>& operator=(None) noexcept
  158. {
  159. m_ptr = nullptr;
  160. return *this;
  161. }
  162. Optional<T&>& operator=(const Optional<T&>& other)
  163. {
  164. m_ptr = other.m_ptr;
  165. return *this;
  166. }
  167. template <class U>
  168. Optional<T&>& operator=(std::reference_wrapper<U> ref) noexcept
  169. {
  170. m_ptr = &ref.get();
  171. return *this;
  172. }
  173. explicit constexpr operator bool() const noexcept
  174. {
  175. return m_ptr;
  176. }
  177. constexpr const target_type& value() const; // Throws
  178. target_type& value(); // Throws
  179. constexpr const target_type& operator*() const
  180. {
  181. return value();
  182. }
  183. target_type& operator*()
  184. {
  185. return value();
  186. }
  187. constexpr const target_type* operator->() const
  188. {
  189. return &value();
  190. }
  191. target_type* operator->()
  192. {
  193. return &value();
  194. }
  195. void swap(Optional<T&> other); // FIXME: Add noexcept() clause
  196. private:
  197. T* m_ptr = nullptr;
  198. template <class U>
  199. friend class Optional;
  200. };
  201. template <class T>
  202. struct RemoveOptional {
  203. using type = T;
  204. };
  205. template <class T>
  206. struct RemoveOptional<Optional<T>> {
  207. using type = typename RemoveOptional<T>::type; // Remove recursively
  208. };
  209. /// Implementation:
  210. template <class T>
  211. struct Some {
  212. template <class... Args>
  213. static Optional<T> some(Args&&... args)
  214. {
  215. return Optional<T>{std::forward<Args>(args)...};
  216. }
  217. };
  218. /// Disabled for compliance with std::optional.
  219. // template <>
  220. // struct Some<void> {
  221. // static Optional<void> some()
  222. // {
  223. // Optional<void> opt;
  224. // opt.m_engaged = true;
  225. // return opt;
  226. // }
  227. // };
  228. template <class T, class... Args>
  229. Optional<T> some(Args&&... args)
  230. {
  231. return Some<T>::some(std::forward<Args>(args)...);
  232. }
  233. template <class T>
  234. constexpr Optional<T>::Optional()
  235. : Storage(none)
  236. {
  237. }
  238. template <class T>
  239. constexpr Optional<T>::Optional(None)
  240. : Storage(none)
  241. {
  242. }
  243. template <class T>
  244. Optional<T>::Optional(Optional<T>&& other) noexcept
  245. : Storage(none)
  246. {
  247. if (other.m_engaged) {
  248. new (&m_value) T(std::move(other.m_value));
  249. m_engaged = true;
  250. }
  251. }
  252. template <class T>
  253. Optional<T>::Optional(const Optional<T>& other)
  254. : Storage(none)
  255. {
  256. if (other.m_engaged) {
  257. new (&m_value) T(other.m_value);
  258. m_engaged = true;
  259. }
  260. }
  261. template <class T>
  262. constexpr Optional<T>::Optional(T&& r_value)
  263. : Storage(std::move(r_value))
  264. {
  265. }
  266. template <class T>
  267. constexpr Optional<T>::Optional(const T& l_value)
  268. : Storage(l_value)
  269. {
  270. }
  271. template <class T>
  272. template <class... Args>
  273. constexpr Optional<T>::Optional(InPlace, Args&&... args)
  274. : Storage(std::forward<Args>(args)...)
  275. {
  276. }
  277. template <class T>
  278. void Optional<T>::reset()
  279. {
  280. if (m_engaged) {
  281. m_value.~T();
  282. m_engaged = false;
  283. }
  284. }
  285. template <class T>
  286. Optional<T>& Optional<T>::operator=(None) noexcept
  287. {
  288. reset();
  289. return *this;
  290. }
  291. template <class T>
  292. Optional<T>& Optional<T>::operator=(Optional<T>&& other) noexcept(std::is_nothrow_move_assignable<T>::value)
  293. {
  294. if (m_engaged) {
  295. if (other.m_engaged) {
  296. m_value = std::move(other.m_value);
  297. }
  298. else {
  299. reset();
  300. }
  301. }
  302. else {
  303. if (other.m_engaged) {
  304. new (&m_value) T(std::move(other.m_value));
  305. m_engaged = true;
  306. }
  307. }
  308. return *this;
  309. }
  310. template <class T>
  311. Optional<T>& Optional<T>::operator=(const Optional<T>& other) noexcept(std::is_nothrow_copy_assignable<T>::value)
  312. {
  313. if (m_engaged) {
  314. if (other.m_engaged) {
  315. m_value = other.m_value;
  316. }
  317. else {
  318. reset();
  319. }
  320. }
  321. else {
  322. if (other.m_engaged) {
  323. new (&m_value) T(other.m_value);
  324. m_engaged = true;
  325. }
  326. }
  327. return *this;
  328. }
  329. template <class T>
  330. template <class U, class>
  331. Optional<T>& Optional<T>::operator=(U&& r_value)
  332. {
  333. if (m_engaged) {
  334. m_value = std::forward<U>(r_value);
  335. }
  336. else {
  337. new (&m_value) T(std::forward<U>(r_value));
  338. m_engaged = true;
  339. }
  340. return *this;
  341. }
  342. template <class T>
  343. constexpr Optional<T>::operator bool() const
  344. {
  345. return m_engaged;
  346. }
  347. template <class T>
  348. constexpr const T& Optional<T>::value() const
  349. {
  350. return m_value;
  351. }
  352. template <class T>
  353. T& Optional<T>::value()
  354. {
  355. REALM_ASSERT(m_engaged);
  356. return m_value;
  357. }
  358. template <class T>
  359. constexpr const typename Optional<T&>::target_type& Optional<T&>::value() const
  360. {
  361. return *m_ptr;
  362. }
  363. template <class T>
  364. typename Optional<T&>::target_type& Optional<T&>::value()
  365. {
  366. REALM_ASSERT(m_ptr);
  367. return *m_ptr;
  368. }
  369. template <class T>
  370. constexpr const T& Optional<T>::operator*() const
  371. {
  372. return value();
  373. }
  374. template <class T>
  375. T& Optional<T>::operator*()
  376. {
  377. return value();
  378. }
  379. template <class T>
  380. constexpr const T* Optional<T>::operator->() const
  381. {
  382. return &value();
  383. }
  384. template <class T>
  385. T* Optional<T>::operator->()
  386. {
  387. return &value();
  388. }
  389. template <class T>
  390. template <class U>
  391. constexpr T Optional<T>::value_or(U&& otherwise) const &
  392. {
  393. return m_engaged ? T{m_value} : T{std::forward<U>(otherwise)};
  394. }
  395. template <class T>
  396. template <class U>
  397. T Optional<T>::value_or(U&& otherwise) &&
  398. {
  399. if (is_engaged()) {
  400. return T(std::move(m_value));
  401. }
  402. else {
  403. return T(std::forward<U>(otherwise));
  404. }
  405. }
  406. template <class T>
  407. void Optional<T>::swap(Optional<T>& other)
  408. {
  409. // FIXME: This might be optimizable.
  410. Optional<T> tmp = std::move(other);
  411. other = std::move(*this);
  412. *this = std::move(tmp);
  413. }
  414. template <class T>
  415. template <class... Args>
  416. void Optional<T>::emplace(Args&&... args)
  417. {
  418. reset();
  419. new (&m_value) T(std::forward<Args>(args)...);
  420. m_engaged = true;
  421. }
  422. template <class T>
  423. constexpr Optional<typename std::decay<T>::type> make_optional(T&& value)
  424. {
  425. using Type = typename std::decay<T>::type;
  426. return some<Type>(std::forward<T>(value));
  427. }
  428. template <class T>
  429. bool operator==(const Optional<T>& lhs, const Optional<T>& rhs)
  430. {
  431. if (!lhs && !rhs) {
  432. return true;
  433. }
  434. if (lhs && rhs) {
  435. return *lhs == *rhs;
  436. }
  437. return false;
  438. }
  439. template <class T>
  440. bool operator!=(const Optional<T>& lhs, const Optional<T>& rhs)
  441. {
  442. return !(lhs == rhs);
  443. }
  444. template <class T>
  445. bool operator<(const Optional<T>& lhs, const Optional<T>& rhs)
  446. {
  447. if (!rhs) {
  448. return false;
  449. }
  450. if (!lhs) {
  451. return true;
  452. }
  453. return std::less<T>{}(*lhs, *rhs);
  454. }
  455. template <class T>
  456. bool operator>(const util::Optional<T>& lhs, const util::Optional<T>& rhs)
  457. {
  458. if (!lhs) {
  459. return false;
  460. }
  461. if (!rhs) {
  462. return true;
  463. }
  464. return std::greater<T>{}(*lhs, *rhs);
  465. }
  466. template <class T>
  467. bool operator==(const Optional<T>& lhs, None)
  468. {
  469. return !bool(lhs);
  470. }
  471. template <class T>
  472. bool operator!=(const Optional<T>& lhs, None)
  473. {
  474. return bool(lhs);
  475. }
  476. template <class T>
  477. bool operator<(const Optional<T>& lhs, None)
  478. {
  479. static_cast<void>(lhs);
  480. return false;
  481. }
  482. template <class T>
  483. bool operator==(None, const Optional<T>& rhs)
  484. {
  485. return !bool(rhs);
  486. }
  487. template <class T>
  488. bool operator!=(None, const Optional<T>& rhs)
  489. {
  490. return bool(rhs);
  491. }
  492. template <class T>
  493. bool operator<(None, const Optional<T>& rhs)
  494. {
  495. return bool(rhs);
  496. }
  497. template <class T, class U>
  498. bool operator==(const Optional<T>& lhs, const U& rhs)
  499. {
  500. return lhs ? *lhs == rhs : false;
  501. }
  502. template <class T>
  503. bool operator<(const Optional<T>& lhs, const T& rhs)
  504. {
  505. return lhs ? std::less<T>{}(*lhs, rhs) : true;
  506. }
  507. template <class T, class U>
  508. bool operator==(const T& lhs, const Optional<U>& rhs)
  509. {
  510. return rhs ? lhs == *rhs : false;
  511. }
  512. template <class T>
  513. bool operator<(const T& lhs, const Optional<T>& rhs)
  514. {
  515. return rhs ? std::less<T>{}(lhs, *rhs) : false;
  516. }
  517. template <class T, class F>
  518. auto operator>>(Optional<T> lhs, F&& rhs) -> decltype(fmap(lhs, std::forward<F>(rhs)))
  519. {
  520. return fmap(lhs, std::forward<F>(rhs));
  521. }
  522. template <class OS, class T>
  523. OS& operator<<(OS& os, const Optional<T>& rhs)
  524. {
  525. if (rhs) {
  526. os << "some(" << *rhs << ")";
  527. }
  528. else {
  529. os << "none";
  530. }
  531. return os;
  532. }
  533. template <class T>
  534. T unwrap(T&& value)
  535. {
  536. return value;
  537. }
  538. template <class T>
  539. T unwrap(util::Optional<T>&& value)
  540. {
  541. return *value;
  542. }
  543. template <class T>
  544. T unwrap(const util::Optional<T>& value)
  545. {
  546. return *value;
  547. }
  548. template <class T>
  549. T unwrap(util::Optional<T>& value)
  550. {
  551. return *value;
  552. }
  553. } // namespace util
  554. namespace _impl {
  555. // T is trivially destructible.
  556. template <class T>
  557. struct OptionalStorage<T, true> {
  558. union {
  559. T m_value;
  560. char m_null_state;
  561. };
  562. bool m_engaged = false;
  563. constexpr OptionalStorage(realm::util::None)
  564. : m_null_state()
  565. {
  566. }
  567. constexpr OptionalStorage(T&& value)
  568. : m_value(std::move(value))
  569. , m_engaged(true)
  570. {
  571. }
  572. template <class... Args>
  573. constexpr OptionalStorage(Args&&... args)
  574. : m_value(args...)
  575. , m_engaged(true)
  576. {
  577. }
  578. };
  579. // T is not trivially destructible.
  580. template <class T>
  581. struct OptionalStorage<T, false> {
  582. union {
  583. T m_value;
  584. char m_null_state;
  585. };
  586. bool m_engaged = false;
  587. constexpr OptionalStorage(realm::util::None)
  588. : m_null_state()
  589. {
  590. }
  591. constexpr OptionalStorage(T&& value)
  592. : m_value(std::move(value))
  593. , m_engaged(true)
  594. {
  595. }
  596. template <class... Args>
  597. constexpr OptionalStorage(Args&&... args)
  598. : m_value(args...)
  599. , m_engaged(true)
  600. {
  601. }
  602. ~OptionalStorage()
  603. {
  604. if (m_engaged)
  605. m_value.~T();
  606. }
  607. };
  608. } // namespace _impl
  609. using util::none;
  610. } // namespace realm
  611. // for convienence, inject a default hash implementation into the std namespace
  612. namespace std
  613. {
  614. template<typename T>
  615. struct hash<realm::util::Optional<T>>
  616. {
  617. std::size_t operator()(realm::util::Optional<T> const& o) const noexcept
  618. {
  619. if (bool(o) == false) {
  620. return 0; // any choice will collide with some std::hash
  621. } else {
  622. return std::hash<T>{}(*o);
  623. }
  624. }
  625. };
  626. }
  627. #endif // REALM_UTIL_OPTIONAL_HPP