GraphLab: Distributed Graph-Parallel API  2.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
conditional_addition_wrapper.hpp
1 /**
2  * Copyright (c) 2009 Carnegie Mellon University.
3  * All rights reserved.
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,
12  * software distributed under the License is distributed on an "AS
13  * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
14  * express or implied. See the License for the specific language
15  * governing permissions and limitations under the License.
16  *
17  * For more about this software visit:
18  *
19  * http://www.graphlab.ml.cmu.edu
20  *
21  */
22 
23 #ifndef GRAPHLAB_CONDITIONAL_ADDITION_WRAPPER_HPP
24 #define GRAPHLAB_CONDITIONAL_ADDITION_WRAPPER_HPP
25 #include <algorithm>
26 #include <graphlab/serialization/oarchive.hpp>
27 #include <graphlab/serialization/iarchive.hpp>
28 
29 
30 
31 namespace graphlab {
32 
33  template <typename T>
34  struct conditional_addition_wrapper {
35  public:
36  bool has_value;
37  T value;
38  conditional_addition_wrapper() : has_value(false), value(T()) {};
39  explicit conditional_addition_wrapper(const T& t,
40  bool has_value = true)
41  :has_value(has_value), value(t) {};
42 
43  void set(const T& t) {
44  value = t;
45  has_value = true;
46  }
47  void swap(T& t) {
48  std::swap(value, t);
49  has_value = true;
50  }
51  void clear() {
52  has_value = false;
53  value = T();
54  }
55 
56  bool empty() const {
57  return !has_value;
58  }
59 
60  bool not_empty() const {
61  return has_value;
62  }
63 
64 
65  conditional_addition_wrapper&
66  operator+=(const conditional_addition_wrapper<T>& c) {
67  if (has_value && c.has_value) {
68  // if we both have value, do the regular +=
69  value += c.value;
70  }
71  else if (!has_value && c.has_value) {
72  // I have no value, but other has value. Use the other
73  has_value = true;
74  value = c.value;
75  }
76  return *this;
77  }
78 
79  conditional_addition_wrapper& operator+=(const T& c) {
80  if (has_value) {
81  value += c;
82  }
83  else if (!has_value) {
84  // I have no value, but other has value. Use the other
85  has_value = true;
86  value = c;
87  }
88  return *this;
89  }
90 
91 
92  void save(oarchive& oarc) const {
93  oarc << has_value;
94  if (has_value) oarc << value;
95  }
96 
97 
98  void load(iarchive& iarc) {
99  iarc >> has_value;
100  if (has_value) iarc >> value;
101  else value = T();
102  }
103 
104  };
105 } // namespace graphlab
106 #endif