initial commit
[menupp.git] / src / node.hpp
blobc733316d19e541aac1e971e0e300f4d6c534c56a
1 #ifndef MENUPP_NODE_HPP_
2 #define MENUPP_NODE_HPP_
4 #include "common.hpp"
6 namespace Menu
9 struct INode;
11 class NodeId
13 INode* _ptr = nullptr;
14 int _n_child = -1;
16 public:
17 NodeId() {}
18 NodeId(INode* ptr, size_t n_child)
19 : _ptr(ptr), _n_child(static_cast<int>(n_child))
22 static const NodeId ROOT;
24 bool is_valid() const { return _n_child >= 0; }
26 bool is_root() const { return is_valid() && !_ptr; }
28 INode* addr() const { return _ptr; }
30 int n() const { return _n_child; }
32 NodeId parent() const;
34 INode* get(INode& root);
36 friend std::ostream& operator<<(std::ostream& os, const NodeId& nid)
37 { return os << '(' << nid._ptr << ", " << nid._n_child << ')'; }
39 friend bool operator==(const NodeId& x, const NodeId& y)
40 { return x._ptr == y._ptr && x._n_child == y._n_child; }
42 friend bool operator!=(const NodeId& x, const NodeId& y)
43 { return !(x == y); }
46 const NodeId NodeId::ROOT { nullptr, 0 };
48 struct INode
50 virtual ~INode() = default;
51 virtual void set_id(NodeId id) = 0;
52 virtual NodeId id() const = 0;
53 virtual void dump(std::ostream& os, size_t indent = 4, size_t total_indent = 0) const = 0;
54 virtual NodeId move(Move m) = 0;
55 virtual INode* get(size_t n) = 0;
56 virtual const char* label() const = 0;
58 friend std::ostream& operator<<(std::ostream& os, const INode& node);
61 NodeId NodeId::parent() const
63 return (_ptr
64 ? _ptr->id()
65 : (is_valid()
66 ? (is_root() ? NodeId() : ROOT)
67 : NodeId()));
70 INode* NodeId::get(INode& root)
72 return is_valid()
73 ? (is_root()
74 ? &root
75 : _ptr->get(static_cast<size_t>(_n_child)))
76 : nullptr;
79 std::ostream& operator<<(std::ostream& os, const INode& node)
80 { node.dump(os, 4); return os; }
84 #endif // MENUPP_NODE_HPP_