maybe_null.t.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // maybe_null.t.h
  3. // pointers
  4. //
  5. // Created by Sam Jaffe on 12/2/16.
  6. //
  7. #pragma once
  8. #include <cxxtest/TestSuite.h>
  9. #include <memory>
  10. #ifndef DEBUG
  11. #define DEBUG
  12. #endif
  13. #include "pointer/maybe_null.hpp"
  14. class maybe_null_TestSuite : public CxxTest::TestSuite {
  15. public:
  16. using ptr_base = std::shared_ptr<int>;
  17. using ptr_t = maybe_null<ptr_base>;
  18. public:
  19. void test_can_hold_nullptr() const {
  20. ptr_t mn{nullptr};
  21. TS_ASSERT_EQUALS(bool(mn), false);
  22. }
  23. void test_is_valid_wo_nullptr() const {
  24. ptr_t mn = make_with(5);
  25. TS_ASSERT_EQUALS(bool(mn), true);
  26. }
  27. void test_nullptr_throws_or_false() const {
  28. ptr_t mn{nullptr};
  29. TS_ASSERT_THROWS(*mn, unchecked_pointer_exception);
  30. }
  31. void test_object_contains_ptr() const {
  32. ptr_base i{new int};
  33. ptr_t n{i};
  34. TS_ASSERT_EQUALS(bool(n), true);
  35. TS_ASSERT_EQUALS(n.get(), i.get());
  36. TS_ASSERT_EQUALS(*n, *i);
  37. }
  38. void test_object_sets_value() const {
  39. static int const value1{5};
  40. static int const value2{4};
  41. ptr_base i{new int{value1}};
  42. ptr_t n{i};
  43. TS_ASSERT_EQUALS(bool(n), true);
  44. TS_ASSERT_EQUALS(*n, value1);
  45. *n = value2;
  46. TS_ASSERT_EQUALS(bool(n), true);
  47. TS_ASSERT_EQUALS(*i, value2);
  48. }
  49. void test_do_not_own() const {
  50. bool has_delete{false};
  51. struct test_t {
  52. ~test_t() { _r = true; }
  53. bool & _r;
  54. };
  55. test_t * test_struct = new test_t{has_delete};
  56. maybe_null<test_t *>{test_struct};
  57. TS_ASSERT_EQUALS(has_delete, false);
  58. delete test_struct;
  59. TS_ASSERT_EQUALS(has_delete, true);
  60. }
  61. void test_type_conversion() {
  62. struct base {};
  63. struct derived : public base {};
  64. derived d;
  65. maybe_null<derived*> m{&d};
  66. maybe_null<base*> b = m;
  67. TS_ASSERT_EQUALS(b.get(), m.get());
  68. }
  69. private:
  70. template <typename T>
  71. static maybe_null<std::shared_ptr<T>> make_with(T p) {
  72. return maybe_null<std::shared_ptr<T>>(std::make_shared<T>(p));
  73. }
  74. };