rbtree.h 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef _RBTREE_H
  15. #define _RBTREE_H 1
  16. //! \file datasrc/rbtree.h
  17. ///
  18. /// \note The purpose of the RBTree is to provide a generic map with
  19. /// domain names as the key that can be used by various BIND 10 modules or
  20. /// even by other applications. However, because of some unresolved design
  21. /// issue, the design and interface are not fixed, and RBTree isn't ready
  22. /// to be used as a base data structure by other modules.
  23. #include <dns/name.h>
  24. #include <boost/utility.hpp>
  25. #include <boost/shared_ptr.hpp>
  26. #include <exceptions/exceptions.h>
  27. #include <ostream>
  28. #include <algorithm>
  29. #include <cassert>
  30. namespace isc {
  31. namespace datasrc {
  32. namespace helper {
  33. /// \brief Helper function to remove the base domain from super domain.
  34. ///
  35. /// The precondition of this function is the super_name contains the
  36. /// sub_name so
  37. /// \code Name a("a.b.c");
  38. /// Name b("b.c");
  39. /// Name c = a - b;
  40. /// \endcode
  41. /// c will contain "a".
  42. ///
  43. /// \note Functions in this namespace is not intended to be used outside of
  44. /// RBTree implementation.
  45. inline isc::dns::Name
  46. operator-(const isc::dns::Name& super_name, const isc::dns::Name& sub_name) {
  47. return (super_name.split(0, super_name.getLabelCount() -
  48. sub_name.getLabelCount()));
  49. }
  50. }
  51. /// Forward declare RBTree class here is convinent for following friend
  52. /// class declare inside RBNode and RBTreeNodeChain
  53. template <typename T>
  54. class RBTree;
  55. /// \brief \c RBNode is used by RBTree to store any data related to one domain
  56. /// name.
  57. ///
  58. /// This is meant to be used only from RBTree. It is meaningless to inherit it
  59. /// or create instances of it from elsewhere. For that reason, the constructor
  60. /// is private.
  61. ///
  62. /// It serves three roles. One is to keep structure of the \c RBTree as a
  63. /// red-black tree. For that purpose, it has left, right and parent pointers
  64. /// and color member. These are private and accessed only from within the tree.
  65. ///
  66. /// The second one is to store data for one domain name. The data related
  67. /// functions can be used to access and set the data.
  68. ///
  69. /// The third role is to keep the hierarchy of domains. The down pointer points
  70. /// to a subtree of subdomains. Note that we can traverse the hierarchy down,
  71. /// but not up.
  72. ///
  73. /// One special kind of node is non-terminal node. It has subdomains with
  74. /// RRsets, but doesn't have any RRsets itself.
  75. template <typename T>
  76. class RBNode : public boost::noncopyable {
  77. private:
  78. /// The RBNode is meant for use from within RBTree, so it has access to
  79. /// it.
  80. friend class RBTree<T>;
  81. /// \name Constructors
  82. ///
  83. /// \note The existence of a RBNode without a RBTree is meaningless.
  84. /// Therefore the constructors are private.
  85. //@{
  86. /// \brief Default constructor.
  87. ///
  88. /// This constructor is provided specifically for generating a special
  89. /// "null" node.
  90. RBNode();
  91. /// \brief Constructor from the node name.
  92. ///
  93. /// \param name The *relative* domain name (if this will live inside
  94. /// a.b.c and is called d.e.a.b.c, then you pass d.e).
  95. RBNode(const isc::dns::Name& name);
  96. //@}
  97. public:
  98. /// \brief Alias for shared pointer to the data.
  99. typedef boost::shared_ptr<T> NodeDataPtr;
  100. /// \brief Destructor
  101. ///
  102. /// It might seem strange that constructors are private and destructor
  103. /// public, but this is needed because of shared pointers need access
  104. /// to the destructor.
  105. ///
  106. /// You should never call anything like:
  107. /// \code delete pointer_to_node; \endcode
  108. /// The RBTree handles both creation and destructoion of nodes.
  109. ~RBNode();
  110. /// \name Getter functions.
  111. //@{
  112. /// \brief Return the name of current node.
  113. ///
  114. /// It's relative to its containing node.
  115. ///
  116. /// To get the absolute name of one node, the node path from the top node
  117. /// to current node has to be recorded.
  118. const isc::dns::Name& getName() const { return (name_); }
  119. /// \brief Return the data stored in this node.
  120. ///
  121. /// You should not delete the data, it is handled by shared pointers.
  122. NodeDataPtr& getData() { return (data_); }
  123. /// \brief Return the data stored in this node.
  124. const NodeDataPtr& getData() const { return (data_); }
  125. /// \brief return whether the node has related data.
  126. ///
  127. /// There can be empty nodes inside the RBTree. They are usually the
  128. /// non-terminal domains, but it is possible (yet probably meaningless)
  129. /// empty nodes anywhere.
  130. bool isEmpty() const { return (data_.get() == NULL); }
  131. //@}
  132. /// \name Setter functions.
  133. //@{
  134. /// \brief Set the data stored in the node.
  135. void setData(const NodeDataPtr& data) { data_ = data; }
  136. //@}
  137. /// \name Callback related methods
  138. ///
  139. /// See the description of \c RBTree<T>::find() about callbacks.
  140. ///
  141. /// These methods never throw an exception.
  142. //@{
  143. /// Return if callback is enabled at the node.
  144. bool isCallbackEnabled() const { return (callback_required_); }
  145. /// Enable callback at the node.
  146. void enableCallback() { callback_required_ = true; }
  147. /// Disable callback at the node.
  148. void disableCallback() { callback_required_ = false; }
  149. //@}
  150. private:
  151. /// \brief Define rbnode color
  152. enum RBNodeColor {BLACK, RED};
  153. /// This is a factory class method of a special singleton null node.
  154. static RBNode<T>* NULL_NODE() {
  155. static RBNode<T> null_node;
  156. return (&null_node);
  157. }
  158. /// \brief return the next node which is bigger than current node
  159. /// in the same subtree
  160. ///
  161. /// The next successor for this node is the next bigger node in terms of
  162. /// the DNSSEC order relation within the same single subtree.
  163. /// Note that it may NOT be the next bigger node in the entire RBTree;
  164. /// RBTree is a tree in tree, and the real next node may reside in
  165. /// an upper or lower subtree of the subtree where this node belongs.
  166. /// For example, if this node has a sub domain, the real next node is
  167. /// the smallest node in the sub domain tree.
  168. ///
  169. /// If this node is the biggest node within the subtree, this method
  170. /// returns \c NULL_NODE().
  171. ///
  172. /// This method never throws an exception.
  173. const RBNode<T>* successor() const;
  174. /// \name Data to maintain the rbtree structure.
  175. //@{
  176. RBNode<T>* parent_;
  177. RBNode<T>* left_;
  178. RBNode<T>* right_;
  179. RBNodeColor color_;
  180. //@}
  181. /// \brief Relative name of the node.
  182. isc::dns::Name name_;
  183. /// \brief Data stored here.
  184. NodeDataPtr data_;
  185. /// \brief The subdomain tree.
  186. ///
  187. /// This points to the root node of trees of subdomains of this domain.
  188. ///
  189. /// \par Adding down pointer to \c RBNode has two purposes:
  190. /// \li Accelerate the search process, with sub domain tree, it splits the
  191. /// big flat tree into several hierarchy trees.
  192. /// \li It saves memory useage as it allows storing only relative names,
  193. /// avoiding storage of the same domain labels multiple times.
  194. RBNode<T>* down_;
  195. /// \brief If callback should be called when traversing this node in
  196. /// RBTree::find().
  197. ///
  198. /// \todo It might be needed to put it into more general attributes field.
  199. bool callback_required_;
  200. };
  201. // This is only to support NULL nodes.
  202. template <typename T>
  203. RBNode<T>::RBNode() :
  204. parent_(this),
  205. left_(this),
  206. right_(this),
  207. color_(BLACK),
  208. // dummy name, the value doesn't matter:
  209. name_(isc::dns::Name::ROOT_NAME()),
  210. down_(this),
  211. callback_required_(false)
  212. {
  213. }
  214. template <typename T>
  215. RBNode<T>::RBNode(const isc::dns::Name& name) :
  216. parent_(NULL_NODE()),
  217. left_(NULL_NODE()),
  218. right_(NULL_NODE()),
  219. color_(RED),
  220. name_(name),
  221. down_(NULL_NODE()),
  222. callback_required_(false)
  223. {
  224. }
  225. template <typename T>
  226. RBNode<T>::~RBNode() {
  227. }
  228. template <typename T>
  229. const RBNode<T>*
  230. RBNode<T>::successor() const {
  231. const RBNode<T>* current = this;
  232. // If it has right node, the successor is the left-most node of the right
  233. // subtree.
  234. if (right_ != NULL_NODE()) {
  235. current = right_;
  236. while (current->left_ != NULL_NODE()) {
  237. current = current->left_;
  238. }
  239. return (current);
  240. }
  241. // Otherwise go up until we find the first left branch on our path to
  242. // root. If found, the parent of the branch is the successor.
  243. // Otherwise, we return the null node
  244. const RBNode<T>* parent = current->parent_;
  245. while (parent != NULL_NODE() && current == parent->right_) {
  246. current = parent;
  247. parent = parent->parent_;
  248. }
  249. return (parent);
  250. }
  251. /// \brief RBTreeNodeChain is used to keep track of the sequence of
  252. /// nodes to reach any given node from the root of RBTree.
  253. ///
  254. /// Currently, RBNode does not have "up" pointers in them (i.e., back pointers
  255. /// from the root of one level of tree of trees to the node in the parent
  256. /// tree whose down pointer points to that root node) for memory usage
  257. /// reasons, so there is no other way to find the path back to the root from
  258. /// any given RBNode.
  259. ///
  260. /// \note This design may change in future versions. In particular, it's
  261. /// quite likely we want to have that pointer if we want to optimize name
  262. /// compression by exploiting the structure of the zone. If and when that
  263. /// happens we should also revisit the need for the chaining.
  264. ///
  265. /// RBTreeNodeChain is constructed and manipulated only inside the \c RBTree
  266. /// class.
  267. /// \c RBTree uses it as an inner data structure to iterate over the whole
  268. /// RBTree.
  269. /// This is the reason why manipulation methods such as \c push() and \c pop()
  270. /// are private (and not shown in the doxygen document).
  271. template <typename T>
  272. class RBTreeNodeChain {
  273. /// RBTreeNodeChain is initialized by RBTree, only RBTree has
  274. /// knowledge to manipuate it.
  275. friend class RBTree<T>;
  276. public:
  277. /// \name Constructors and Assignment Operator.
  278. ///
  279. /// \note The copy constructor and the assignment operator are
  280. /// intentionally defined as private, making this class non copyable.
  281. /// This may have to be changed in a future version with newer need.
  282. /// For now we explicitly disable copy to avoid accidental copy happens
  283. /// unintentionally.
  284. //{@
  285. /// The default constructor.
  286. ///
  287. /// \exception None
  288. RBTreeNodeChain() : node_count_(0) {}
  289. private:
  290. RBTreeNodeChain(const RBTreeNodeChain<T>&);
  291. RBTreeNodeChain<T>& operator=(const RBTreeNodeChain<T>&);
  292. //@}
  293. public:
  294. /// \brief Return the number of levels stored in the chain.
  295. ///
  296. /// It's equal to the number of nodes in the chain; for an empty
  297. /// chain, 0 will be returned.
  298. ///
  299. /// \exception None
  300. unsigned int getLevelCount() const { return (node_count_); }
  301. /// \brief return the absolute name for the node which this
  302. /// \c RBTreeNodeChain currently refers to.
  303. ///
  304. /// The chain must not be empty.
  305. ///
  306. /// \exception isc::BadValue the chain is empty.
  307. /// \exception std::bad_alloc memory allocation for the new name fails.
  308. isc::dns::Name getAbsoluteName() const {
  309. if (isEmpty()) {
  310. isc_throw(isc::BadValue,
  311. "RBTreeNodeChain::getAbsoluteName is called on an empty "
  312. "chain");
  313. }
  314. const RBNode<T>* top_node = top();
  315. isc::dns::Name absolute_name = top_node->getName();
  316. int node_count = node_count_ - 1;
  317. while (node_count > 0) {
  318. top_node = nodes_[node_count - 1];
  319. absolute_name = absolute_name.concatenate(top_node->getName());
  320. --node_count;
  321. }
  322. return (absolute_name);
  323. }
  324. private:
  325. // the following private functions check invariants about the internal
  326. // state using assert() instead of exception. The state of a chain
  327. // can only be modified operations within this file, so if any of the
  328. // assumptions fails it means an internal bug.
  329. /// \brief return whther node chain has node in it.
  330. ///
  331. /// \exception None
  332. bool isEmpty() const { return (node_count_ == 0); }
  333. /// \brief return the top node for the node chain
  334. ///
  335. /// RBTreeNodeChain store all the nodes along top node to
  336. /// root node of RBTree
  337. ///
  338. /// \exception None
  339. const RBNode<T>* top() const {
  340. assert(!isEmpty());
  341. return (nodes_[node_count_ - 1]);
  342. }
  343. /// \brief pop the top node from the node chain
  344. ///
  345. /// After pop, up/super node of original top node will be
  346. /// the top node
  347. ///
  348. /// \exception None
  349. void pop() {
  350. assert(!isEmpty());
  351. --node_count_;
  352. }
  353. /// \brief add the node into the node chain
  354. ///
  355. /// If the node chain isn't empty, the node should be
  356. /// the sub domain of the original top node in node chain
  357. /// otherwise the node should be the root node of RBTree.
  358. ///
  359. /// \exception None
  360. void push(const RBNode<T>* node) {
  361. assert(node_count_ < RBT_MAX_LEVEL);
  362. nodes_[node_count_++] = node;
  363. }
  364. private:
  365. // The max label count for one domain name is Name::MAX_LABELS (128).
  366. // Since each node in rbtree stores at least one label, and the root
  367. // name always shares the same level with some others (which means
  368. // all top level nodes except the one for the root name contain at least
  369. // two labels), the possible maximum level is MAX_LABELS - 1.
  370. // It's also the possible maximum nodes stored in a chain.
  371. const static int RBT_MAX_LEVEL = isc::dns::Name::MAX_LABELS - 1;
  372. const RBNode<T>* nodes_[RBT_MAX_LEVEL];
  373. int node_count_;
  374. };
  375. // note: the following class description is documented using multiline comments
  376. // because the verbatim diagram contain a backslash, which could be interpreted
  377. // as escape of newline in singleline comment.
  378. /**
  379. * \brief \c RBTree class represents all the domains with the same suffix.
  380. * It can be used to store the domains in one zone, for example.
  381. *
  382. * RBTree is a generic map from domain names to any kind of data. Internally,
  383. * it uses a red-black tree. However, it isn't one tree containing everything.
  384. * Subdomains are trees, so this structure is recursive - trees inside trees.
  385. * But, from the interface point of view, it is opaque data structure.
  386. *
  387. * \c RBTree splits the domain space into hierarchy red black trees; nodes
  388. * in one tree has the same base name. The benefit of this struct is that:
  389. * - Enhances the query performace compared with one big flat red black tree.
  390. * - Decreases the memory footprint, as it doesn't store the suffix labels
  391. * multiple times.
  392. *
  393. * Depending on different usage, rbtree will support different search policies.
  394. * Whether to return an empty node to end user is one policy among them.
  395. * The default policy is to NOT return an empty node to end user;
  396. * to change the behavior, specify \c true for the constructor parameter
  397. * \c returnEmptyNode.
  398. * \note The search policy only affects the \c find() behavior of RBTree.
  399. * When inserting one name into RBTree, if the node with the name already
  400. * exists in the RBTree and it's an empty node which doesn't have any data,
  401. * the \c insert() method will still return \c ALREADYEXISTS regardless of
  402. * the search policy.
  403. *
  404. * \anchor diagram
  405. *
  406. * with the following names:
  407. * - a
  408. * - b
  409. * - c
  410. * - x.d.e.f
  411. * - z.d.e.f
  412. * - g.h
  413. * - o.w.y.d.e.f
  414. * - p.w.y.d.e.f
  415. * - q.w.y.d.e.f
  416. *
  417. * the tree will look like:
  418. * \verbatim
  419. b
  420. / \
  421. a d.e.f
  422. /|\
  423. c | g.h
  424. |
  425. w.y
  426. /|\
  427. x | z
  428. |
  429. p
  430. / \
  431. o q
  432. \endverbatim
  433. * \todo
  434. * - add remove interface
  435. * - add iterator to iterate over the whole \c RBTree. This may be necessary,
  436. * for example, to support AXFR.
  437. */
  438. template <typename T>
  439. class RBTree : public boost::noncopyable {
  440. friend class RBNode<T>;
  441. public:
  442. /// \brief The return value for the \c find() and insert() methods
  443. enum Result {
  444. SUCCESS, ///< Insert was successful
  445. /// \brief The node returned from find mathes exactly the name given
  446. EXACTMATCH,
  447. PARTIALMATCH, ///< A superdomain node was found
  448. NOTFOUND, ///< Not even any superdomain was found
  449. /// \brief Returned by insert() if a node of the name already exists
  450. ALREADYEXISTS,
  451. };
  452. /// \name Constructor and Destructor
  453. //@{
  454. /// The constructor.
  455. ///
  456. /// It never throws an exception.
  457. explicit RBTree(bool returnEmptyNode = false);
  458. /// \b Note: RBTree is not intended to be inherited so the destructor
  459. /// is not virtual
  460. ~RBTree();
  461. //@}
  462. /// \name Find methods
  463. ///
  464. /// \brief Find the node that gives a longest match against the given name.
  465. ///
  466. /// \anchor find
  467. ///
  468. /// These methods search the RBTree for a node whose name is longest
  469. /// against name. The found node, if any, is returned via the node pointer.
  470. ///
  471. /// By default, nodes that don't have data (see RBNode::isEmpty) are
  472. /// ignored and the result can be NOTFOUND even if there's a node whose
  473. /// name matches. If the \c RBTree is constructed with its
  474. /// \c returnEmptyNode parameter being \c true, an empty node will also
  475. /// be match candidates.
  476. ///
  477. /// \note Even when \c returnEmptyNode is \c true, not all empty nodes
  478. /// in terms of the DNS protocol may necessarily be found by this method.
  479. /// For example, in the \ref diagram shown in the class description,
  480. /// the name y.d.e.f is logically contained in the tree as part of the
  481. /// node w.y, but the \c find() variants cannot find the former for
  482. /// the search key of y.d.e.f, no matter how the \c RBTree is constructed.
  483. /// The caller of this method must use a different way to identify the
  484. /// hidden match when necessary.
  485. ///
  486. /// These methods involve operations on names that can throw an exception.
  487. /// If that happens the exception will be propagated to the caller.
  488. /// The callback function should generally not throw an exception, but
  489. /// if it throws, the exception will be propagated to the caller.
  490. ///
  491. /// The \c name parameter says what should be found. The node parameter
  492. /// is output only and in case of EXACTMATCH and PARTIALMATCH, it is set
  493. /// to a pointer to the found node.
  494. ///
  495. /// They return:
  496. /// - EXACTMATCH when a node with the same name as requested exists.
  497. /// - PARTIALMATCH when a node with the same name does not exist (or is
  498. /// empty), but there's a (nonempty) superdomain of the requested one.
  499. /// The superdomain with longest name is returned through the node
  500. /// parameter. Beware that if you store a zone in the tree, you may get
  501. /// PARTIALMATCH with zone apex when the given domain name is not there.
  502. /// You should not try to delegate into another zone in that case.
  503. /// - NOTFOUND if there's no node with the same name nor any superdomain
  504. /// of it. In that case, node parameter is left intact.
  505. //@{
  506. /// \brief Simple find.
  507. ///
  508. /// Acts as described in the \ref find section.
  509. Result find(const isc::dns::Name& name, RBNode<T>** node) const {
  510. RBTreeNodeChain<T> node_path;
  511. return (find<void*>(name, node, node_path, NULL, NULL));
  512. }
  513. /// \brief Simple find returning immutable node.
  514. ///
  515. /// Acts as described in the \ref find section, but returns immutable node
  516. /// pointer.
  517. Result find(const isc::dns::Name& name, const RBNode<T>** node) const {
  518. RBTreeNodeChain<T> node_path;
  519. RBNode<T> *target_node = NULL;
  520. Result ret = (find<void*>(name, &target_node, node_path, NULL, NULL));
  521. if (ret != NOTFOUND) {
  522. *node = target_node;
  523. }
  524. return (ret);
  525. }
  526. /// \brief Find with callback and node chain.
  527. ///
  528. /// This version of \c find() is specifically designed for the backend
  529. /// of the \c MemoryZone class, and implements all necessary features
  530. /// for that purpose. Other applications shouldn't need these additional
  531. /// features, and should normally use the simpler versions.
  532. ///
  533. /// This version of \c find() calls the callback whenever traversing (on
  534. /// the way from root down the tree) a marked node on the way down through
  535. /// the domain namespace (see RBNode::enableCallback and related
  536. /// functions).
  537. ///
  538. /// If you return true from the callback, the search is stopped and a
  539. /// PARTIALMATCH is returned with the given node. Note that this node
  540. /// doesn't really need to be the one with longest possible match.
  541. ///
  542. /// This callback mechanism was designed with zone cut (delegation)
  543. /// processing in mind. The marked nodes would be the ones at delegation
  544. /// points. It is not expected that any other applications would need
  545. /// callbacks; they should use the versions of find without callbacks.
  546. /// The callbacks are not general functors for the same reason - we don't
  547. /// expect it to be needed.
  548. ///
  549. /// Another special feature of this version is the ability to provide
  550. /// a node chain containing a path to the found node. The chain will be
  551. /// returned via the \c node_path parameter.
  552. /// The passed parameter must be empty.
  553. /// On success, it will contain all the ancestor nodes from the found
  554. /// node towards the root.
  555. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  556. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  557. /// chain will be o, w.f and d.e.f will be stored below it.
  558. ///
  559. /// This feature can be used to get the absolute name for a node;
  560. /// to do so, we need to travel upside from the node toward the root,
  561. /// concatenating all ancestor names. With the current implementation
  562. /// it's not possible without a node chain, because there is a no pointer
  563. /// from the root of a subtree to the parent subtree (this may change
  564. /// in a future version). A node chain can also be used to find the next
  565. /// node of a given node in the entire RBTree; the \c nextNode() method
  566. /// takes a node chain as a parameter.
  567. ///
  568. /// \exception isc::BadValue node_path is not empty.
  569. ///
  570. /// \param name Target to be found
  571. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  572. /// it will store a pointer to the matching node
  573. /// \param node_path It will store all the ancestor nodes in the RBTree
  574. /// from the found node to the root. The found node is stored.
  575. /// \param callback If non \c NULL, a call back function to be called
  576. /// at marked nodes (see above).
  577. /// \param callback_arg A caller supplied argument to be passed to
  578. /// \c callback.
  579. ///
  580. /// \return As described above, but in case of callback returning true,
  581. /// it returns immediately with the current node.
  582. template <typename CBARG>
  583. Result find(const isc::dns::Name& name,
  584. RBNode<T>** node,
  585. RBTreeNodeChain<T>& node_path,
  586. bool (*callback)(const RBNode<T>&, CBARG),
  587. CBARG callback_arg) const;
  588. /// \brief Simple find returning immutable node.
  589. ///
  590. /// Acts as described in the \ref find section, but returns immutable
  591. /// node pointer.
  592. template <typename CBARG>
  593. Result find(const isc::dns::Name& name,
  594. const RBNode<T>** node,
  595. RBTreeNodeChain<T>& node_path,
  596. bool (*callback)(const RBNode<T>&, CBARG),
  597. CBARG callback_arg) const
  598. {
  599. RBNode<T>* target_node = NULL;
  600. Result ret = find(name, &target_node, node_path, callback,
  601. callback_arg);
  602. if (ret != NOTFOUND) {
  603. *node = target_node;
  604. }
  605. return (ret);
  606. }
  607. //@}
  608. /// \brief return the next bigger node in DNSSEC order from a given node
  609. /// chain.
  610. ///
  611. /// This method identifies the next bigger node of the node currently
  612. /// referenced in \c node_path and returns it.
  613. /// This method also updates the passed \c node_path so that it will store
  614. /// the path for the returned next node.
  615. /// It will be convenient when we want to iterate over the all nodes
  616. /// of \c RBTree; we can do this by calling this method repeatedly
  617. /// starting from the root node.
  618. ///
  619. /// \note \c nextNode() will iterate over all the nodes in RBTree including
  620. /// empty nodes. If empty node isn't desired, it's easy to add logic to
  621. /// check return node and keep invoking \c nextNode() until the non-empty
  622. /// node is retrieved.
  623. ///
  624. /// \exception isc::BadValue node_path is empty.
  625. ///
  626. /// \param node_path A node chain that stores all the nodes along the path
  627. /// from root to node.
  628. ///
  629. /// \return An \c RBNode that is next bigger than \c node; if \c node is
  630. /// the largest, \c NULL will be returned.
  631. const RBNode<T>* nextNode(RBTreeNodeChain<T>& node_path) const;
  632. /// \brief Get the total number of nodes in the tree
  633. ///
  634. /// It includes nodes internally created as a result of adding a domain
  635. /// name that is a subdomain of an existing node of the tree.
  636. /// This function is mainly intended to be used for debugging.
  637. int getNodeCount() const { return (node_count_); }
  638. /// \name Debug function
  639. //@{
  640. /// \brief Print the nodes in the trees.
  641. ///
  642. /// \param os A \c std::ostream object to which the tree is printed.
  643. /// \param depth A factor of the initial indentation. Each line
  644. /// will begin with space character repeating <code>5 * depth</code>
  645. /// times.
  646. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  647. //@}
  648. /// \name Modify functions
  649. //@{
  650. /// \brief Insert the domain name into the tree.
  651. ///
  652. /// It either finds an already existing node of the given name or inserts
  653. /// a new one, if none exists yet. In any case, the inserted_node parameter
  654. /// is set to point to that node. You can fill data into it or modify it.
  655. /// So, if you don't know if a node exists or not and you need to modify
  656. /// it, just call insert and act by the result.
  657. ///
  658. /// Please note that the tree can add some empty nodes by itself, so don't
  659. /// assume that if you didn't insert a node of that name it doesn't exist.
  660. ///
  661. /// This method normally involves resource allocation. If it fails
  662. /// the corresponding standard exception will be thrown.
  663. ///
  664. /// This method does not provide the strong exception guarantee in its
  665. /// strict sense; if an exception is thrown in the middle of this
  666. /// method, the internal structure may change. However, it should
  667. /// still retain the same property as a mapping container before this
  668. /// method is called. For example, the result of \c find() should be
  669. /// the same. This method provides the weak exception guarantee in its
  670. /// normal sense.
  671. ///
  672. /// \param name The name to be inserted into the tree.
  673. /// \param inserted_node This is an output parameter and is set to the
  674. /// node.
  675. ///
  676. /// \return
  677. /// - SUCCESS The node was added.
  678. /// - ALREADYEXISTS There was already a node of that name, so it was not
  679. /// added.
  680. Result insert(const isc::dns::Name& name, RBNode<T>** inserted_node);
  681. /// \brief Swaps two tree's contents.
  682. ///
  683. /// This acts the same as many std::*.swap functions, exchanges the
  684. /// contents. This doesn't throw anything.
  685. void swap(RBTree<T>& other) {
  686. std::swap(root_, other.root_);
  687. std::swap(NULLNODE, other.NULLNODE);
  688. std::swap(node_count_, other.node_count_);
  689. }
  690. //@}
  691. private:
  692. /// \name RBTree balance functions
  693. //@{
  694. void insertRebalance(RBNode<T>** root, RBNode<T>* node);
  695. RBNode<T>* rightRotate(RBNode<T>** root, RBNode<T>* node);
  696. RBNode<T>* leftRotate(RBNode<T>** root, RBNode<T>* node);
  697. //@}
  698. /// \name Helper functions
  699. //@{
  700. /// \brief delete tree whose root is equal to node
  701. void deleteHelper(RBNode<T> *node);
  702. /// \brief Print the information of given RBNode.
  703. void dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  704. unsigned int depth) const;
  705. /// \brief Indentation helper function for dumpTree
  706. static void indent(std::ostream& os, unsigned int depth);
  707. /// Split one node into two nodes, keep the old node and create one new
  708. /// node, old node will hold the base name, new node will be the down node
  709. /// of old node, new node will hold the sub_name, the data
  710. /// of old node will be move into new node, and old node became non-terminal
  711. void nodeFission(RBNode<T>& node, const isc::dns::Name& sub_name);
  712. //@}
  713. RBNode<T>* NULLNODE;
  714. RBNode<T>* root_;
  715. /// the node count of current tree
  716. unsigned int node_count_;
  717. /// search policy for rbtree
  718. const bool needsReturnEmptyNode_;
  719. };
  720. template <typename T>
  721. RBTree<T>::RBTree(bool returnEmptyNode) :
  722. NULLNODE(RBNode<T>::NULL_NODE()),
  723. root_(NULLNODE),
  724. node_count_(0),
  725. needsReturnEmptyNode_(returnEmptyNode)
  726. {
  727. }
  728. template <typename T>
  729. RBTree<T>::~RBTree() {
  730. deleteHelper(root_);
  731. assert(node_count_ == 0);
  732. }
  733. template <typename T>
  734. void
  735. RBTree<T>::deleteHelper(RBNode<T>* root) {
  736. if (root == NULLNODE) {
  737. return;
  738. }
  739. RBNode<T>* node = root;
  740. while (root->left_ != NULLNODE || root->right_ != NULLNODE) {
  741. while (node->left_ != NULLNODE || node->right_ != NULLNODE) {
  742. node = (node->left_ != NULLNODE) ? node->left_ : node->right_;
  743. }
  744. RBNode<T>* parent = node->parent_;
  745. if (parent->left_ == node) {
  746. parent->left_ = NULLNODE;
  747. } else {
  748. parent->right_ = NULLNODE;
  749. }
  750. deleteHelper(node->down_);
  751. delete node;
  752. --node_count_;
  753. node = parent;
  754. }
  755. deleteHelper(root->down_);
  756. delete root;
  757. --node_count_;
  758. }
  759. template <typename T>
  760. template <typename CBARG>
  761. typename RBTree<T>::Result
  762. RBTree<T>::find(const isc::dns::Name& target_name,
  763. RBNode<T>** target,
  764. RBTreeNodeChain<T>& node_path,
  765. bool (*callback)(const RBNode<T>&, CBARG),
  766. CBARG callback_arg) const
  767. {
  768. using namespace helper;
  769. if (!node_path.isEmpty()) {
  770. isc_throw(isc::BadValue, "RBTree::find is given a non empty chain");
  771. }
  772. RBNode<T>* node = root_;
  773. Result ret = NOTFOUND;
  774. isc::dns::Name name = target_name;
  775. while (node != NULLNODE) {
  776. const isc::dns::NameComparisonResult compare_result =
  777. name.compare(node->name_);
  778. const isc::dns::NameComparisonResult::NameRelation relation =
  779. compare_result.getRelation();
  780. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  781. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  782. node_path.push(node);
  783. *target = node;
  784. ret = EXACTMATCH;
  785. }
  786. break;
  787. } else {
  788. const int common_label_count = compare_result.getCommonLabels();
  789. // If the common label count is 1, there is no common label between
  790. // the two names, except the trailing "dot".
  791. if (common_label_count == 1) {
  792. node = (compare_result.getOrder() < 0) ?
  793. node->left_ : node->right_;
  794. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  795. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  796. ret = PARTIALMATCH;
  797. *target = node;
  798. if (callback != NULL && node->callback_required_) {
  799. if ((callback)(*node, callback_arg)) {
  800. break;
  801. }
  802. }
  803. }
  804. node_path.push(node);
  805. name = name - node->name_;
  806. node = node->down_;
  807. } else {
  808. break;
  809. }
  810. }
  811. }
  812. return (ret);
  813. }
  814. template <typename T>
  815. const RBNode<T>*
  816. RBTree<T>::nextNode(RBTreeNodeChain<T>& node_path) const {
  817. if (node_path.isEmpty()) {
  818. isc_throw(isc::BadValue, "RBTree::nextNode is given an empty chain");
  819. }
  820. const RBNode<T>* node = node_path.top();
  821. // if node has sub domain, the next domain is the smallest
  822. // domain in sub domain tree
  823. if (node->down_ != NULLNODE) {
  824. const RBNode<T>* left_most = node->down_;
  825. while (left_most->left_ != NULLNODE) {
  826. left_most = left_most->left_;
  827. }
  828. node_path.push(left_most);
  829. return (left_most);
  830. }
  831. // node_path go to up level
  832. node_path.pop();
  833. // otherwise found the successor node in current level
  834. const RBNode<T>* successor = node->successor();
  835. if (successor != NULLNODE) {
  836. node_path.push(successor);
  837. return (successor);
  838. }
  839. // if no successor found move to up level, the next successor
  840. // is the successor of up node in the up level tree, if
  841. // up node doesn't have successor we gonna keep moving to up
  842. // level
  843. while (!node_path.isEmpty()) {
  844. const RBNode<T>* up_node_successor = node_path.top()->successor();
  845. node_path.pop();
  846. if (up_node_successor != NULLNODE) {
  847. node_path.push(up_node_successor);
  848. return (up_node_successor);
  849. }
  850. }
  851. return (NULL);
  852. }
  853. template <typename T>
  854. typename RBTree<T>::Result
  855. RBTree<T>::insert(const isc::dns::Name& target_name, RBNode<T>** new_node) {
  856. using namespace helper;
  857. RBNode<T>* parent = NULLNODE;
  858. RBNode<T>* current = root_;
  859. RBNode<T>* up_node = NULLNODE;
  860. isc::dns::Name name = target_name;
  861. int order = -1;
  862. while (current != NULLNODE) {
  863. const isc::dns::NameComparisonResult compare_result =
  864. name.compare(current->name_);
  865. const isc::dns::NameComparisonResult::NameRelation relation =
  866. compare_result.getRelation();
  867. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  868. if (new_node != NULL) {
  869. *new_node = current;
  870. }
  871. return (ALREADYEXISTS);
  872. } else {
  873. const int common_label_count = compare_result.getCommonLabels();
  874. if (common_label_count == 1) {
  875. parent = current;
  876. order = compare_result.getOrder();
  877. current = order < 0 ? current->left_ : current->right_;
  878. } else {
  879. // insert sub domain to sub tree
  880. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  881. parent = NULLNODE;
  882. up_node = current;
  883. name = name - current->name_;
  884. current = current->down_;
  885. } else {
  886. // The number of labels in common is fewer
  887. // than the number of labels at the current
  888. // node, so the current node must be adjusted
  889. // to have just the common suffix, and a down
  890. // pointer made to a new tree.
  891. const isc::dns::Name common_ancestor = name.split(
  892. name.getLabelCount() - common_label_count,
  893. common_label_count);
  894. nodeFission(*current, common_ancestor);
  895. }
  896. }
  897. }
  898. }
  899. RBNode<T>** current_root = (up_node != NULLNODE) ?
  900. &(up_node->down_) : &root_;
  901. // using auto_ptr here is avoid memory leak in case of exceptoin raised
  902. // after the RBNode creation, if we can make sure no exception will be
  903. // raised until the end of the function, we can remove it for optimization
  904. std::auto_ptr<RBNode<T> > node(new RBNode<T>(name));
  905. node->parent_ = parent;
  906. if (parent == NULLNODE) {
  907. *current_root = node.get();
  908. //node is the new root of sub tree, so its init color
  909. // is BLACK
  910. node->color_ = RBNode<T>::BLACK;
  911. } else if (order < 0) {
  912. parent->left_ = node.get();
  913. } else {
  914. parent->right_ = node.get();
  915. }
  916. insertRebalance(current_root, node.get());
  917. if (new_node != NULL) {
  918. *new_node = node.get();
  919. }
  920. ++node_count_;
  921. node.release();
  922. return (SUCCESS);
  923. }
  924. template <typename T>
  925. void
  926. RBTree<T>::nodeFission(RBNode<T>& node, const isc::dns::Name& base_name) {
  927. using namespace helper;
  928. const isc::dns::Name sub_name = node.name_ - base_name;
  929. // using auto_ptr here is to avoid memory leak in case of exception raised
  930. // after the RBNode creation
  931. std::auto_ptr<RBNode<T> > down_node(new RBNode<T>(sub_name));
  932. node.name_ = base_name;
  933. // the rest of this function should be exception free so that it keeps
  934. // consistent behavior (i.e., a weak form of strong exception guarantee)
  935. // even if code after the call to this function throws an exception.
  936. std::swap(node.data_, down_node->data_);
  937. std::swap(node.callback_required_, down_node->callback_required_);
  938. down_node->down_ = node.down_;
  939. node.down_ = down_node.get();
  940. // root node of sub tree, the initial color is BLACK
  941. down_node->color_ = RBNode<T>::BLACK;
  942. ++node_count_;
  943. down_node.release();
  944. }
  945. template <typename T>
  946. void
  947. RBTree<T>::insertRebalance(RBNode<T>** root, RBNode<T>* node) {
  948. RBNode<T>* uncle;
  949. while (node != *root && node->parent_->color_ == RBNode<T>::RED) {
  950. if (node->parent_ == node->parent_->parent_->left_) {
  951. uncle = node->parent_->parent_->right_;
  952. if (uncle->color_ == RBNode<T>::RED) {
  953. node->parent_->color_ = RBNode<T>::BLACK;
  954. uncle->color_ = RBNode<T>::BLACK;
  955. node->parent_->parent_->color_ = RBNode<T>::RED;
  956. node = node->parent_->parent_;
  957. } else {
  958. if (node == node->parent_->right_) {
  959. node = node->parent_;
  960. leftRotate(root, node);
  961. }
  962. node->parent_->color_ = RBNode<T>::BLACK;
  963. node->parent_->parent_->color_ = RBNode<T>::RED;
  964. rightRotate(root, node->parent_->parent_);
  965. }
  966. } else {
  967. uncle = node->parent_->parent_->left_;
  968. if (uncle->color_ == RBNode<T>::RED) {
  969. node->parent_->color_ = RBNode<T>::BLACK;
  970. uncle->color_ = RBNode<T>::BLACK;
  971. node->parent_->parent_->color_ = RBNode<T>::RED;
  972. node = node->parent_->parent_;
  973. } else {
  974. if (node == node->parent_->left_) {
  975. node = node->parent_;
  976. rightRotate(root, node);
  977. }
  978. node->parent_->color_ = RBNode<T>::BLACK;
  979. node->parent_->parent_->color_ = RBNode<T>::RED;
  980. leftRotate(root, node->parent_->parent_);
  981. }
  982. }
  983. }
  984. (*root)->color_ = RBNode<T>::BLACK;
  985. }
  986. template <typename T>
  987. RBNode<T>*
  988. RBTree<T>::leftRotate(RBNode<T>** root, RBNode<T>* node) {
  989. RBNode<T>* right = node->right_;
  990. node->right_ = right->left_;
  991. if (right->left_ != NULLNODE)
  992. right->left_->parent_ = node;
  993. right->parent_ = node->parent_;
  994. if (node->parent_ != NULLNODE) {
  995. if (node == node->parent_->left_) {
  996. node->parent_->left_ = right;
  997. } else {
  998. node->parent_->right_ = right;
  999. }
  1000. } else {
  1001. *root = right;
  1002. }
  1003. right->left_ = node;
  1004. node->parent_ = right;
  1005. return (node);
  1006. }
  1007. template <typename T>
  1008. RBNode<T>*
  1009. RBTree<T>::rightRotate(RBNode<T>** root, RBNode<T>* node) {
  1010. RBNode<T>* left = node->left_;
  1011. node->left_ = left->right_;
  1012. if (left->right_ != NULLNODE)
  1013. left->right_->parent_ = node;
  1014. left->parent_ = node->parent_;
  1015. if (node->parent_ != NULLNODE) {
  1016. if (node == node->parent_->right_) {
  1017. node->parent_->right_ = left;
  1018. } else {
  1019. node->parent_->left_ = left;
  1020. }
  1021. } else {
  1022. *root = left;
  1023. }
  1024. left->right_ = node;
  1025. node->parent_ = left;
  1026. return (node);
  1027. }
  1028. template <typename T>
  1029. void
  1030. RBTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  1031. indent(os, depth);
  1032. os << "tree has " << node_count_ << " node(s)\n";
  1033. dumpTreeHelper(os, root_, depth);
  1034. }
  1035. template <typename T>
  1036. void
  1037. RBTree<T>::dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  1038. unsigned int depth) const
  1039. {
  1040. if (node == NULLNODE) {
  1041. indent(os, depth);
  1042. os << "NULL\n";
  1043. return;
  1044. }
  1045. indent(os, depth);
  1046. os << node->name_.toText() << " ("
  1047. << ((node->color_ == RBNode<T>::BLACK) ? "black" : "red") << ")";
  1048. os << ((node->isEmpty()) ? "[invisible] \n" : "\n");
  1049. if (node->down_ != NULLNODE) {
  1050. indent(os, depth + 1);
  1051. os << "begin down from " << node->name_.toText() << "\n";
  1052. dumpTreeHelper(os, node->down_, depth + 1);
  1053. indent(os, depth + 1);
  1054. os << "end down from " << node->name_.toText() << "\n";
  1055. }
  1056. dumpTreeHelper(os, node->left_, depth + 1);
  1057. dumpTreeHelper(os, node->right_, depth + 1);
  1058. }
  1059. template <typename T>
  1060. void
  1061. RBTree<T>::indent(std::ostream& os, unsigned int depth) {
  1062. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1063. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1064. }
  1065. }
  1066. }
  1067. #endif // _RBTREE_H
  1068. // Local Variables:
  1069. // mode: c++
  1070. // End: