GCC Code Coverage Report
Directory: . Exec Total Coverage
File: src/util/maybe.h Lines: 14 27 51.9 %
Date: 2021-03-22 Branches: 2 22 9.1 %

Line Exec Source
1
/*********************                                                        */
2
/*! \file maybe.h
3
 ** \verbatim
4
 ** Top contributors (to current version):
5
 **   Tim King, Mathias Preiner
6
 ** This file is part of the CVC4 project.
7
 ** Copyright (c) 2009-2021 by the authors listed in the file AUTHORS
8
 ** in the top-level source directory and their institutional affiliations.
9
 ** All rights reserved.  See the file COPYING in the top-level source
10
 ** directory for licensing information.\endverbatim
11
 **
12
 ** \brief This provides a templated Maybe construct.
13
 **
14
 ** This class provides a templated Maybe<T> construct.
15
 ** This follows the rough pattern of the Maybe monad in haskell.
16
 ** A Maybe is an algebraic type that is either Nothing | Just T
17
 **
18
 ** T must support T() and operator=.
19
 **
20
 ** This has a couple of uses:
21
 ** - There is no reasonable value or particularly clean way to represent
22
 **   Nothing using a value of T
23
 ** - High level of assurance that a value is not used before it is set.
24
 **/
25
#include "cvc4_public.h"
26
27
#ifndef CVC4__UTIL__MAYBE_H
28
#define CVC4__UTIL__MAYBE_H
29
30
#include <ostream>
31
32
#include "base/exception.h"
33
34
namespace CVC4 {
35
36
template <class T>
37
26976
class Maybe
38
{
39
 public:
40
37485
  Maybe() : d_just(false), d_value(){}
41
  Maybe(const T& val): d_just(true), d_value(val){}
42
43
4
  Maybe& operator=(const T& v){
44
4
    d_just = true;
45
4
    d_value = v;
46
4
    return *this;
47
  }
48
49
8
  inline bool nothing() const { return !d_just; }
50
2
  inline bool just() const { return d_just; }
51
  explicit operator bool() const noexcept { return just(); }
52
53
2
  void clear() {
54
2
    if(just()){
55
      d_just = false;
56
      d_value = T();
57
    }
58
2
  }
59
60
8
  const T& value() const
61
  {
62
8
    if (nothing())
63
    {
64
      throw Exception("Maybe::value() requires the maybe to be set.");
65
    }
66
8
    return d_value;
67
  }
68
69
 private:
70
  bool d_just;
71
  T d_value;
72
};
73
74
template <class T>
75
inline std::ostream& operator<<(std::ostream& out, const Maybe<T>& m){
76
  out << "{";
77
  if(m.nothing()){
78
    out << "Nothing";
79
  }else{
80
    out << "Just ";
81
    out << m.value();
82
  }
83
  out << "}";
84
  return out;
85
}
86
87
}/* CVC4 namespace */
88
89
#endif /* CVC4__UTIL__MAYBE_H */