CppADCodeGen  HEAD
A C++ Algorithmic Differentiation Package with Source Code Generation
operation_node_name_streambuf.hpp
1 #ifndef CPPAD_CG_OPERATION_NODE_NAME_STREAMBUF_INCLUDED
2 #define CPPAD_CG_OPERATION_NODE_NAME_STREAMBUF_INCLUDED
3 /* --------------------------------------------------------------------------
4  * CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation:
5  * Copyright (C) 2016 Ciengis
6  * Copyright (C) 2018 Joao Leal
7  *
8  * CppADCodeGen is distributed under multiple licenses:
9  *
10  * - Eclipse Public License Version 1.0 (EPL1), and
11  * - GNU General Public License Version 3 (GPL3).
12  *
13  * EPL1 terms and conditions can be found in the file "epl-v10.txt", while
14  * terms and conditions for the GPL3 can be found in the file "gpl3.txt".
15  * ----------------------------------------------------------------------------
16  * Author: Joao Leal
17  */
18 
19 namespace CppAD {
20 namespace cg {
21 
31 template<class Base>
32 class OperationNodeNameStreambuf : public std::streambuf {
33 private:
34  using char_type = typename std::streambuf::char_type;
35  using int_type = typename std::streambuf::int_type;
36  using pos_type = typename std::streambuf::pos_type;
37 private:
38  thread_local static OperationNodeNameStreambuf<Base>* BUF;
39 private:
40  OperationNode <Base>* node_;
41 public:
43  node_(nullptr) {
44  if (BUF != nullptr) {
45  throw CGException("Only one OperationNodeNameStreambuf can exist at a time in each thread");
46  }
47  if (CGOStreamFunc<Base>::FUNC() != nullptr) {
48  throw CGException("CGOStreamFunc<Base>::FUNC already defined in this thread");
49  }
50  BUF = this;
51  CGOStreamFunc<Base>::FUNC() = registerNode;
52  }
53 
54  virtual ~OperationNodeNameStreambuf() {
55  BUF = nullptr;
56  CGOStreamFunc<Base>::FUNC() = nullptr;
57  }
58 
59  std::streamsize xsputn(const char_type* s,
60  std::streamsize n) override {
61  if (node_ != nullptr && n > 0) {
62  node_->setName(std::string(s, n));
63  node_ = nullptr;
64  }
65  return n;
66  }
67 
68  //int_type overflow(int_type c) override {
69  // return traits_type::eof();
70  //}
71 
72 private:
73  static std::ostream& registerNode(std::ostream& os,
74  const CG<Base>& c) {
75  if(c.isVariable()) {
76  BUF->node_ = c.getOperationNode();
77  }
78  return os;
79  }
80 };
81 
82 template<class Base>
84 
85 } // END cg namespace
86 } // END CppAD namespace
87 
88 #endif
bool isVariable() const
Definition: variable.hpp:30
void setName(const std::string &name)