rbtree.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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 <exception>
  27. #include <ostream>
  28. #include <algorithm>
  29. #include <stack>
  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. template <typename T>
  52. class RBTree;
  53. /// \brief \c RBNode is used by RBTree to store any data related to one domain
  54. /// name.
  55. ///
  56. /// This is meant to be used only from RBTree. It is meaningless to inherit it
  57. /// or create instances of it from elsewhere. For that reason, the constructor
  58. /// is private.
  59. ///
  60. /// It serves three roles. One is to keep structure of the \c RBTree as a
  61. /// red-black tree. For that purpose, it has left, right and parent pointers
  62. /// and color member. These are private and accessed only from within the tree.
  63. ///
  64. /// The second one is to store data for one domain name. The data related
  65. /// functions can be used to access and set the data.
  66. ///
  67. /// The third role is to keep the hierarchy of domains. The down pointer points
  68. /// to a subtree of subdomains. Note that we can traverse the hierarchy down,
  69. /// but not up.
  70. ///
  71. /// One special kind of node is non-terminal node. It has subdomains with
  72. /// RRsets, but doesn't have any RRsets itself.
  73. template <typename T>
  74. class RBNode : public boost::noncopyable {
  75. private:
  76. /// The RBNode is meant for use from within RBTree, so it has access to
  77. /// it.
  78. template <typename U>
  79. friend class RBTree;
  80. /// \name Constructors
  81. ///
  82. /// \note The existence of a RBNode without a RBTree is meaningless.
  83. /// Therefore the constructors are private.
  84. //@{
  85. /// \brief Default constructor.
  86. ///
  87. /// This constructor is provided specifically for generating a special
  88. /// "null" node.
  89. RBNode();
  90. /// \brief Constructor from the node name.
  91. ///
  92. /// \param name The *relative* domain name (if this will live inside
  93. /// a.b.c and is called d.e.a.b.c, then you pass d.e).
  94. RBNode(const isc::dns::Name& name);
  95. //@}
  96. public:
  97. /// \brief Alias for shared pointer to the data.
  98. typedef boost::shared_ptr<T> NodeDataPtr;
  99. /// \brief Destructor
  100. ///
  101. /// It might seem strange that constructors are private and destructor
  102. /// public, but this is needed because of shared pointers need access
  103. /// to the destructor.
  104. ///
  105. /// You should never call anything like:
  106. /// \code delete pointer_to_node; \endcode
  107. /// The RBTree handles both creation and destructoion of nodes.
  108. ~RBNode();
  109. /// \name Getter functions.
  110. //@{
  111. /// \brief Return the name of current node.
  112. ///
  113. /// It's relative to its containing node.
  114. ///
  115. /// To get the absolute name of one node, the node path from the top node
  116. /// to current node has to be recorded.
  117. const isc::dns::Name& getName() const { return (name_); }
  118. /// \brief Return the data stored in this node.
  119. ///
  120. /// You should not delete the data, it is handled by shared pointers.
  121. NodeDataPtr& getData() { return (data_); }
  122. /// \brief Return the data stored in this node.
  123. const NodeDataPtr& getData() const { return (data_); }
  124. /// \brief return whether the node has related data.
  125. ///
  126. /// There can be empty nodes inside the RBTree. They are usually the
  127. /// non-terminal domains, but it is possible (yet probably meaningless)
  128. /// empty nodes anywhere.
  129. bool isEmpty() const { return (data_.get() == NULL); }
  130. /// \brief return the next node which is bigger than current node
  131. /// in the same tree
  132. const RBNode<T>* successor() const;
  133. //@}
  134. /// \name Setter functions.
  135. //@{
  136. /// \brief Set the data stored in the node.
  137. void setData(const NodeDataPtr& data) { data_ = data; }
  138. //@}
  139. /// \name Callback related methods
  140. ///
  141. /// See the description of \c RBTree<T>::find() about callbacks.
  142. ///
  143. /// These methods never throw an exception.
  144. //@{
  145. /// Return if callback is enabled at the node.
  146. bool isCallbackEnabled() const { return (callback_required_); }
  147. /// Enable callback at the node.
  148. void enableCallback() { callback_required_ = true; }
  149. /// Disable callback at the node.
  150. void disableCallback() { callback_required_ = false; }
  151. //@}
  152. private:
  153. /// \brief Define rbnode color
  154. enum RBNodeColor {BLACK, RED};
  155. /// This is a factory class method of a special singleton null node.
  156. static RBNode<T>* NULL_NODE() {
  157. static RBNode<T> null_node;
  158. return (&null_node);
  159. }
  160. /// \name Data to maintain the rbtree structure.
  161. //@{
  162. RBNode<T>* parent_;
  163. RBNode<T>* left_;
  164. RBNode<T>* right_;
  165. RBNodeColor color_;
  166. //@}
  167. /// \brief Relative name of the node.
  168. isc::dns::Name name_;
  169. /// \brief Data stored here.
  170. NodeDataPtr data_;
  171. /// \brief The subdomain tree.
  172. ///
  173. /// This points to the root node of trees of subdomains of this domain.
  174. ///
  175. /// \par Adding down pointer to \c RBNode has two purposes:
  176. /// \li Accelerate the search process, with sub domain tree, it splits the
  177. /// big flat tree into several hierarchy trees.
  178. /// \li It saves memory useage as it allows storing only relative names,
  179. /// avoiding storage of the same domain labels multiple times.
  180. RBNode<T>* down_;
  181. /// \brief If callback should be called when traversing this node in
  182. /// RBTree::find().
  183. ///
  184. /// \todo It might be needed to put it into more general attributes field.
  185. bool callback_required_;
  186. };
  187. // This is only to support NULL nodes.
  188. template <typename T>
  189. RBNode<T>::RBNode() :
  190. parent_(this),
  191. left_(this),
  192. right_(this),
  193. color_(BLACK),
  194. // dummy name, the value doesn't matter:
  195. name_(isc::dns::Name::ROOT_NAME()),
  196. down_(this),
  197. callback_required_(false)
  198. {
  199. }
  200. template <typename T>
  201. RBNode<T>::RBNode(const isc::dns::Name& name) :
  202. parent_(NULL_NODE()),
  203. left_(NULL_NODE()),
  204. right_(NULL_NODE()),
  205. color_(RED),
  206. name_(name),
  207. down_(NULL_NODE()),
  208. callback_required_(false)
  209. {
  210. }
  211. template <typename T>
  212. RBNode<T>::~RBNode() {
  213. }
  214. template <typename T>
  215. const RBNode<T> *
  216. RBNode<T>::successor()const {
  217. const RBNode<T>* current = this;
  218. // If it has right node, the successor is the left-most node of the right
  219. // subtree.
  220. if (right_ != NULL_NODE()) {
  221. current = right_;
  222. while (current->left_ != NULL_NODE()) {
  223. current = current->left_;
  224. }
  225. return (current);
  226. }
  227. // Otherwise go up until we find the first left branch on our path to
  228. // root. If found, the parent of the branch is the successor.
  229. // Otherwise, we return the null node
  230. const RBNode<T>* parent = current->parent_;
  231. while (parent != NULL_NODE() && current == parent->right_) {
  232. current = parent;
  233. parent = parent->parent_;
  234. }
  235. return (parent);
  236. }
  237. // note: the following class description is documented using multiline comments
  238. // because the verbatim diagram contain a backslash, which could be interpreted
  239. // as escape of newline in singleline comment.
  240. /**
  241. * \brief \c RBTree class represents all the domains with the same suffix.
  242. * It can be used to store the domains in one zone, for example.
  243. *
  244. * RBTree is a generic map from domain names to any kind of data. Internally,
  245. * it uses a red-black tree. However, it isn't one tree containing everything.
  246. * Subdomains are trees, so this structure is recursive - trees inside trees.
  247. * But, from the interface point of view, it is opaque data structure.
  248. *
  249. * \c RBTree splits the domain space into hierarchy red black trees; nodes
  250. * in one tree has the same base name. The benefit of this struct is that:
  251. * - Enhances the query performace compared with one big flat red black tree.
  252. * - Decreases the memory footprint, as it doesn't store the suffix labels
  253. * multiple times.
  254. *
  255. * Depending on different usage, rbtree will support different search policy.
  256. * Whether return empty node to end user is one policy among them. the default
  257. * policy will NOT return empty node to end user, pass ture will get empty node
  258. * during find is needed.
  259. * \note The search policy only affect find behavior of rbtree, but when
  260. * inserting one name, if the node already exist not matter it's insert
  261. * explictly by end user or empty node created by the rbtree itself,
  262. * insert will return ALREADYEXISTS not matter we want expose empty node
  263. * or not.
  264. *
  265. * \anchor diagram
  266. *
  267. * with the following names:
  268. * - a
  269. * - b
  270. * - c
  271. * - x.d.e.f
  272. * - z.d.e.f
  273. * - g.h
  274. * - o.w.y.d.e.f
  275. * - p.w.y.d.e.f
  276. * - q.w.y.d.e.f
  277. *
  278. * the tree will looks like:
  279. * \verbatim
  280. b
  281. / \
  282. a d.e.f
  283. /|\
  284. c | g.h
  285. |
  286. w.y
  287. /|\
  288. x | z
  289. |
  290. p
  291. / \
  292. o q
  293. \endverbatim
  294. * \todo
  295. * - add remove interface
  296. * - add iterator to iterate over the whole \c RBTree. This may be necessary,
  297. * for example, to support AXFR.
  298. * - since \c RBNode only has down pointer without up pointer, the node path
  299. * during finding should be recorded for later use
  300. */
  301. template <typename T>
  302. class RBTree : public boost::noncopyable {
  303. friend class RBNode<T>;
  304. public:
  305. /// \brief The return value for the \c find() and insert() methods
  306. enum Result {
  307. SUCCESS, ///< Insert was successful
  308. /// \brief The node returned from find mathes exactly the name given
  309. EXACTMATCH,
  310. PARTIALMATCH, ///< A superdomain node was found
  311. NOTFOUND, ///< Not even any superdomain was found
  312. /// \brief Returned by insert() if a node of the name already exists
  313. ALREADYEXISTS,
  314. };
  315. /// save the nodes along the path from root to the target node
  316. typedef typename std::stack<const RBNode<T>*> NodeChain;
  317. /// \name Constructor and Destructor
  318. //@{
  319. /// The constructor.
  320. ///
  321. /// It never throws an exception.
  322. explicit RBTree(bool returnEmptyNode = false);
  323. /// \b Note: RBTree is not intended to be inherited so the destructor
  324. /// is not virtual
  325. ~RBTree();
  326. //@}
  327. /// \name Find methods
  328. ///
  329. /// \brief Find the node that gives a longest match against the given name.
  330. ///
  331. /// \anchor find
  332. ///
  333. /// These methods search the RBTree for a node whose name is a longest
  334. /// against name. The found node, if any, is returned via the node pointer.
  335. ///
  336. /// By default, nodes that don't have data (see RBNode::isEmpty) are
  337. /// ignored and the result can be NOTFOUND even if there's a node whose
  338. /// name mathes. The plan is to introduce a "no data OK" mode for this
  339. /// method, that would match any node of the tree regardless of wheather
  340. /// the node has any data or not.
  341. ///
  342. /// The case with "no data OK" mode is not as easy as it seems. For example
  343. /// in the diagram shown in the class description, the name y.d.e.f is
  344. /// logically contained in the tree as part of the node w.y. It cannot be
  345. /// identified simply by checking whether existing nodes (such as
  346. /// d.e.f or w.y) has data.
  347. ///
  348. /// These methods involves operations on names that can throw an exception.
  349. /// If that happens the exception will be propagated to the caller.
  350. /// The callback function should generally not throw an exception, but
  351. /// if it throws, the exception will be propagated to the caller.
  352. ///
  353. /// The \c name parameter says what should be found. The node parameter
  354. /// is output only and in case of EXACTMATCH and PARTIALMATCH, it is set
  355. /// to a pointer to the found node.
  356. ///
  357. /// They return:
  358. /// - EXACTMATCH when a node with the same name as requested exists.
  359. /// - PARTIALMATCH when a node with the same name does not exist (or is
  360. /// empty), but there's a (nonempty) superdomain of the requested one.
  361. /// The superdomain with longest name is returned through the node
  362. /// parameter. Beware that if you store a zone in the tree, you may get
  363. /// PARTIALMATCH with zone apex when the given domain name is not there.
  364. /// You should not try to delegate into another zone in that case.
  365. /// - NOTFOUND if there's no node with the same name nor any superdomain
  366. /// of it. In that case, node parameter is left intact.
  367. //@{
  368. /// \brief Find with callback.
  369. ///
  370. /// \anchor callback
  371. ///
  372. /// This version of find calls the callback whenever traversing (on the
  373. /// way from root down the tree) a marked node on the way down through the
  374. /// domain namespace (see RBNode::enableCallback and related functions).
  375. ///
  376. /// If you return true from the callback, the search is stopped and a
  377. /// PARTIALMATCH is returned with the given node. Note that this node
  378. /// doesn't really need to be the one with longest possible match.
  379. ///
  380. /// This callback mechanism was designed with zone cut (delegation)
  381. /// processing in mind. The marked nodes would be the ones at delegation
  382. /// points. It is not expected that any other applications would need
  383. /// callbacks; they should use the versions of find without callbacks.
  384. /// The callbacks are not general functors for the same reason - we don't
  385. /// expect it to be needed.
  386. ///
  387. /// \param name Target to be found
  388. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  389. /// it will store a pointer to the matching node
  390. /// \param callback If non \c NULL, a call back function to be called
  391. /// at marked nodes (see above).
  392. /// \param callback_arg A caller supplied argument to be passed to
  393. /// \c callback.
  394. ///
  395. /// \return As described above, but in case of callback returning true,
  396. /// it returns immediately with the current node.
  397. template <typename CBARG>
  398. Result find(const isc::dns::Name& name, RBNode<T>** node,
  399. bool (*callback)(const RBNode<T>&, CBARG),
  400. CBARG callback_arg) const;
  401. /// \brief Find with callback returning immutable node.
  402. ///
  403. /// It has the same behaviour as the find with \ref callback version.
  404. template <typename CBARG>
  405. Result find(const isc::dns::Name& name, const RBNode<T>** node,
  406. bool (*callback)(const RBNode<T>&, CBARG),
  407. CBARG callback_arg) const;
  408. /// \brief Simple find.
  409. ///
  410. /// Acts as described in the \ref find section.
  411. Result find(const isc::dns::Name& name, RBNode<T>** node) const {
  412. return (find<void*>(name, node, NULL, NULL));
  413. }
  414. /// \brief Simple find returning immutable node.
  415. ///
  416. /// Acts as described in the \ref find section, but returns immutable node
  417. /// pointer.
  418. Result find(const isc::dns::Name& name, const RBNode<T>** node) const {
  419. return (find<void*>(name, node, NULL, NULL));
  420. }
  421. /// \param name What should be found.
  422. /// \param node_path It will save all the ancestor nodes
  423. /// to the tree containing node. If we looked for o.w.y.d.e.f in the
  424. /// \ref diagram, the node_path will have w.y node and d.e.f node.
  425. /// with the node path, we can also get the next node of current node
  426. /// \param node The found node.
  427. template <typename CBARG>
  428. Result findEx(const isc::dns::Name& name, NodeChain &node_path,
  429. RBNode<T>** node,
  430. bool (*callback)(const RBNode<T>&, CBARG),
  431. CBARG callback_arg) const;
  432. /// \brief Simple find returning immutable node.
  433. ///
  434. /// Acts as described in the \ref findEx section, but returns immutable
  435. /// node pointer.
  436. template <typename CBARG>
  437. Result findEx(const isc::dns::Name& name, NodeChain &node_path,
  438. const RBNode<T>** node,
  439. bool (*callback)(const RBNode<T>&, CBARG),
  440. CBARG callback_arg) const;
  441. /// \brief return the next node which is bigger than node
  442. /// \param node_path store the path from base to sub domains in reverse order
  443. /// the node_path is fetched through findEx function call, next_node_path will
  444. /// store the node path to next_node, which can be used in turn to find
  445. /// the next node of next node.
  446. const RBNode<T>* nextNode(const RBNode<T> *node,
  447. const NodeChain &node_path,
  448. NodeChain &next_node_path) const;
  449. //@}
  450. /// \brief Get the total number of nodes in the tree
  451. ///
  452. /// It includes nodes internally created as a result of adding a domain
  453. /// name that is a subdomain of an existing node of the tree.
  454. /// This function is mainly intended to be used for debugging.
  455. int getNodeCount() const { return (node_count_); }
  456. /// \name Debug function
  457. //@{
  458. /// \brief Print the nodes in the trees.
  459. ///
  460. /// \param os A \c std::ostream object to which the tree is printed.
  461. /// \param depth A factor of the initial indentation. Each line
  462. /// will begin with space character repeating <code>5 * depth</code>
  463. /// times.
  464. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  465. //@}
  466. /// \name Modify functions
  467. //@{
  468. /// \brief Insert the domain name into the tree.
  469. ///
  470. /// It either finds an already existing node of the given name or inserts
  471. /// a new one, if none exists yet. In any case, the inserted_node parameter
  472. /// is set to point to that node. You can fill data into it or modify it.
  473. /// So, if you don't know if a node exists or not and you need to modify
  474. /// it, just call insert and act by the result.
  475. ///
  476. /// Please note that the tree can add some empty nodes by itself, so don't
  477. /// assume that if you didn't insert a node of that name it doesn't exist.
  478. ///
  479. /// This method normally involves resource allocation. If it fails
  480. /// the corresponding standard exception will be thrown.
  481. ///
  482. /// This method does not provide the strong exception guarantee in its
  483. /// strict sense; if an exception is thrown in the middle of this
  484. /// method, the internal structure may change. However, it should
  485. /// still retain the same property as a mapping container before this
  486. /// method is called. For example, the result of \c find() should be
  487. /// the same. This method provides the weak exception guarantee in its
  488. /// normal sense.
  489. ///
  490. /// \param name The name to be inserted into the tree.
  491. /// \param inserted_node This is an output parameter and is set to the
  492. /// node.
  493. ///
  494. /// \return
  495. /// - SUCCESS The node was added.
  496. /// - ALREADYEXISTS There was already a node of that name, so it was not
  497. /// added.
  498. Result insert(const isc::dns::Name& name, RBNode<T>** inserted_node);
  499. /// \brief Swaps two tree's contents.
  500. ///
  501. /// This acts the same as many std::*.swap functions, exchanges the
  502. /// contents. This doesn't throw anything.
  503. void swap(RBTree<T>& other) {
  504. std::swap(root_, other.root_);
  505. std::swap(NULLNODE, other.NULLNODE);
  506. std::swap(node_count_, other.node_count_);
  507. }
  508. //@}
  509. private:
  510. /// \name RBTree balance functions
  511. //@{
  512. void insertRebalance(RBNode<T>** root, RBNode<T>* node);
  513. RBNode<T>* rightRotate(RBNode<T>** root, RBNode<T>* node);
  514. RBNode<T>* leftRotate(RBNode<T>** root, RBNode<T>* node);
  515. //@}
  516. /// \name Helper functions
  517. //@{
  518. /// \brief delete tree whose root is equal to node
  519. void deleteHelper(RBNode<T> *node);
  520. /// \brief find the node with name
  521. ///
  522. /// Internal searching function.
  523. ///
  524. void dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  525. unsigned int depth) const;
  526. /// \brief Indentation helper function for dumpTree
  527. static void indent(std::ostream& os, unsigned int depth);
  528. /// Split one node into two nodes, keep the old node and create one new
  529. /// node, old node will hold the base name, new node will be the down node
  530. /// of old node, new node will hold the sub_name, the data
  531. /// of old node will be move into new node, and old node became non-terminal
  532. void nodeFission(RBNode<T>& node, const isc::dns::Name& sub_name);
  533. //@}
  534. RBNode<T>* NULLNODE;
  535. RBNode<T>* root_;
  536. /// the node count of current tree
  537. unsigned int node_count_;
  538. /// search policy for rbtree
  539. const bool needsReturnEmptyNode_;
  540. };
  541. template <typename T>
  542. RBTree<T>::RBTree(bool returnEmptyNode) :
  543. NULLNODE(RBNode<T>::NULL_NODE()),
  544. root_(NULLNODE),
  545. node_count_(0),
  546. needsReturnEmptyNode_(returnEmptyNode)
  547. {
  548. }
  549. template <typename T>
  550. RBTree<T>::~RBTree() {
  551. deleteHelper(root_);
  552. assert(node_count_ == 0);
  553. }
  554. template <typename T>
  555. void
  556. RBTree<T>::deleteHelper(RBNode<T>* root) {
  557. if (root == NULLNODE) {
  558. return;
  559. }
  560. RBNode<T>* node = root;
  561. while (root->left_ != NULLNODE || root->right_ != NULLNODE) {
  562. while (node->left_ != NULLNODE || node->right_ != NULLNODE) {
  563. node = (node->left_ != NULLNODE) ? node->left_ : node->right_;
  564. }
  565. RBNode<T>* parent = node->parent_;
  566. if (parent->left_ == node) {
  567. parent->left_ = NULLNODE;
  568. } else {
  569. parent->right_ = NULLNODE;
  570. }
  571. deleteHelper(node->down_);
  572. delete node;
  573. --node_count_;
  574. node = parent;
  575. }
  576. deleteHelper(root->down_);
  577. delete root;
  578. --node_count_;
  579. }
  580. template <typename T>
  581. template <typename CBARG>
  582. typename RBTree<T>::Result
  583. RBTree<T>::find(const isc::dns::Name& name, RBNode<T>** node,
  584. bool (*callback)(const RBNode<T>&, CBARG),
  585. CBARG callback_arg) const
  586. {
  587. NodeChain node_path;
  588. return (findEx(name, node_path, node, callback, callback_arg));
  589. }
  590. template <typename T>
  591. template <typename CBARG>
  592. typename RBTree<T>::Result
  593. RBTree<T>::find(const isc::dns::Name& name, const RBNode<T>** node,
  594. bool (*callback)(const RBNode<T>&, CBARG),
  595. CBARG callback_arg) const
  596. {
  597. NodeChain node_path;
  598. RBNode<T>* target_node = NULLNODE;
  599. const Result ret =
  600. findEx(name, node_path, &target_node, callback, callback_arg);
  601. if (ret != NOTFOUND) {
  602. *node = target_node;
  603. }
  604. return (ret);
  605. }
  606. template <typename T>
  607. template <typename CBARG>
  608. typename RBTree<T>::Result
  609. RBTree<T>::findEx(const isc::dns::Name& target_name,
  610. NodeChain &node_path,
  611. RBNode<T>** target,
  612. bool (*callback)(const RBNode<T>&, CBARG),
  613. CBARG callback_arg) const
  614. {
  615. using namespace helper;
  616. RBNode<T>* node = root_;
  617. Result ret = NOTFOUND;
  618. isc::dns::Name name = target_name;
  619. while (node != NULLNODE) {
  620. const isc::dns::NameComparisonResult compare_result =
  621. name.compare(node->name_);
  622. const isc::dns::NameComparisonResult::NameRelation relation =
  623. compare_result.getRelation();
  624. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  625. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  626. *target = node;
  627. ret = EXACTMATCH;
  628. }
  629. break;
  630. } else {
  631. const int common_label_count = compare_result.getCommonLabels();
  632. // If the common label count is 1, there is no common label between
  633. // the two names, except the trailing "dot".
  634. if (common_label_count == 1) {
  635. node = (compare_result.getOrder() < 0) ?
  636. node->left_ : node->right_;
  637. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  638. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  639. ret = PARTIALMATCH;
  640. *target = node;
  641. if (callback != NULL && node->callback_required_) {
  642. if ((callback)(*node, callback_arg)) {
  643. break;
  644. }
  645. }
  646. }
  647. node_path.push(node);
  648. name = name - node->name_;
  649. node = node->down_;
  650. } else {
  651. break;
  652. }
  653. }
  654. }
  655. return (ret);
  656. }
  657. template <typename T>
  658. template <typename CBARG>
  659. typename RBTree<T>::Result
  660. RBTree<T>::findEx(const isc::dns::Name& target_name,
  661. NodeChain &node_path,
  662. const RBNode<T>** target,
  663. bool (*callback)(const RBNode<T>&, CBARG),
  664. CBARG callback_arg) const
  665. {
  666. RBNode<T>* node = NULLNODE;
  667. const Result ret =
  668. findEx(target_name, node_path, &node, callback, callback_arg);
  669. if (ret != NOTFOUND) {
  670. *target = node;
  671. }
  672. return (ret);
  673. }
  674. template <typename T>
  675. const RBNode<T>*
  676. RBTree<T>::nextNode(const RBNode<T>* node, const NodeChain& node_path,
  677. NodeChain& next_node_path) const
  678. {
  679. next_node_path = node_path;
  680. // if node has sub domain, the next domain is the smallest
  681. // domain in sub domain tree
  682. if (node->down_ != NULLNODE) {
  683. next_node_path.push(node);
  684. const RBNode<T>* left_most = node->down_;
  685. while (left_most->left_ != NULLNODE) {
  686. left_most = left_most->left_;
  687. }
  688. return (left_most);
  689. }
  690. // otherwise found the successor node in current level
  691. const RBNode<T>* successor = node->successor();
  692. if (successor != NULLNODE) {
  693. return (successor);
  694. }
  695. // if no successor found move to up level, the next successor
  696. // is the successor of up node in the up level tree, if
  697. // up node doesn't has successor we gonna keep moving to up
  698. // level
  699. while (!next_node_path.empty()) {
  700. const RBNode<T>* up_node_successor = next_node_path.top()->successor();
  701. next_node_path.pop();
  702. if (up_node_successor != NULLNODE) {
  703. return (up_node_successor);
  704. }
  705. }
  706. return (NULLNODE);
  707. }
  708. template <typename T>
  709. typename RBTree<T>::Result
  710. RBTree<T>::insert(const isc::dns::Name& target_name,
  711. RBNode<T>** new_node)
  712. {
  713. using namespace helper;
  714. RBNode<T>* parent = NULLNODE;
  715. RBNode<T>* current = root_;
  716. RBNode<T>* up_node = NULLNODE;
  717. isc::dns::Name name = target_name;
  718. int order = -1;
  719. while (current != NULLNODE) {
  720. const isc::dns::NameComparisonResult compare_result =
  721. name.compare(current->name_);
  722. const isc::dns::NameComparisonResult::NameRelation relation =
  723. compare_result.getRelation();
  724. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  725. if (new_node != NULL) {
  726. *new_node = current;
  727. }
  728. return (ALREADYEXISTS);
  729. } else {
  730. const int common_label_count = compare_result.getCommonLabels();
  731. if (common_label_count == 1) {
  732. parent = current;
  733. order = compare_result.getOrder();
  734. current = order < 0 ? current->left_ : current->right_;
  735. } else {
  736. // insert sub domain to sub tree
  737. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  738. parent = NULLNODE;
  739. up_node = current;
  740. name = name - current->name_;
  741. current = current->down_;
  742. } else {
  743. // The number of labels in common is fewer
  744. // than the number of labels at the current
  745. // node, so the current node must be adjusted
  746. // to have just the common suffix, and a down
  747. // pointer made to a new tree.
  748. const isc::dns::Name common_ancestor = name.split(
  749. name.getLabelCount() - common_label_count,
  750. common_label_count);
  751. nodeFission(*current, common_ancestor);
  752. }
  753. }
  754. }
  755. }
  756. RBNode<T>** current_root = (up_node != NULLNODE) ?
  757. &(up_node->down_) : &root_;
  758. // using auto_ptr here is avoid memory leak in case of exceptoin raised
  759. // after the RBNode creation, if we can make sure no exception will be
  760. // raised until the end of the function, we can remove it for optimization
  761. std::auto_ptr<RBNode<T> > node(new RBNode<T>(name));
  762. node->parent_ = parent;
  763. if (parent == NULLNODE) {
  764. *current_root = node.get();
  765. //node is the new root of sub tree, so its init color
  766. // is BLACK
  767. node->color_ = RBNode<T>::BLACK;
  768. } else if (order < 0) {
  769. parent->left_ = node.get();
  770. } else {
  771. parent->right_ = node.get();
  772. }
  773. insertRebalance(current_root, node.get());
  774. if (new_node != NULL) {
  775. *new_node = node.get();
  776. }
  777. ++node_count_;
  778. node.release();
  779. return (SUCCESS);
  780. }
  781. template <typename T>
  782. void
  783. RBTree<T>::nodeFission(RBNode<T>& node, const isc::dns::Name& base_name) {
  784. using namespace helper;
  785. const isc::dns::Name sub_name = node.name_ - base_name;
  786. // using auto_ptr here is to avoid memory leak in case of exception raised
  787. // after the RBNode creation
  788. std::auto_ptr<RBNode<T> > down_node(new RBNode<T>(sub_name));
  789. node.name_ = base_name;
  790. // the rest of this function should be exception free so that it keeps
  791. // consistent behavior (i.e., a weak form of strong exception guarantee)
  792. // even if code after the call to this function throws an exception.
  793. std::swap(node.data_, down_node->data_);
  794. std::swap(node.callback_required_, down_node->callback_required_);
  795. down_node->down_ = node.down_;
  796. node.down_ = down_node.get();
  797. // root node of sub tree, the initial color is BLACK
  798. down_node->color_ = RBNode<T>::BLACK;
  799. ++node_count_;
  800. down_node.release();
  801. }
  802. template <typename T>
  803. void
  804. RBTree<T>::insertRebalance(RBNode<T>** root, RBNode<T>* node) {
  805. RBNode<T>* uncle;
  806. while (node != *root && node->parent_->color_ == RBNode<T>::RED) {
  807. if (node->parent_ == node->parent_->parent_->left_) {
  808. uncle = node->parent_->parent_->right_;
  809. if (uncle->color_ == RBNode<T>::RED) {
  810. node->parent_->color_ = RBNode<T>::BLACK;
  811. uncle->color_ = RBNode<T>::BLACK;
  812. node->parent_->parent_->color_ = RBNode<T>::RED;
  813. node = node->parent_->parent_;
  814. } else {
  815. if (node == node->parent_->right_) {
  816. node = node->parent_;
  817. leftRotate(root, node);
  818. }
  819. node->parent_->color_ = RBNode<T>::BLACK;
  820. node->parent_->parent_->color_ = RBNode<T>::RED;
  821. rightRotate(root, node->parent_->parent_);
  822. }
  823. } else {
  824. uncle = node->parent_->parent_->left_;
  825. if (uncle->color_ == RBNode<T>::RED) {
  826. node->parent_->color_ = RBNode<T>::BLACK;
  827. uncle->color_ = RBNode<T>::BLACK;
  828. node->parent_->parent_->color_ = RBNode<T>::RED;
  829. node = node->parent_->parent_;
  830. } else {
  831. if (node == node->parent_->left_) {
  832. node = node->parent_;
  833. rightRotate(root, node);
  834. }
  835. node->parent_->color_ = RBNode<T>::BLACK;
  836. node->parent_->parent_->color_ = RBNode<T>::RED;
  837. leftRotate(root, node->parent_->parent_);
  838. }
  839. }
  840. }
  841. (*root)->color_ = RBNode<T>::BLACK;
  842. }
  843. template <typename T>
  844. RBNode<T>*
  845. RBTree<T>::leftRotate(RBNode<T>** root, RBNode<T>* node) {
  846. RBNode<T>* right = node->right_;
  847. node->right_ = right->left_;
  848. if (right->left_ != NULLNODE)
  849. right->left_->parent_ = node;
  850. right->parent_ = node->parent_;
  851. if (node->parent_ != NULLNODE) {
  852. if (node == node->parent_->left_) {
  853. node->parent_->left_ = right;
  854. } else {
  855. node->parent_->right_ = right;
  856. }
  857. } else {
  858. *root = right;
  859. }
  860. right->left_ = node;
  861. node->parent_ = right;
  862. return (node);
  863. }
  864. template <typename T>
  865. RBNode<T>*
  866. RBTree<T>::rightRotate(RBNode<T>** root, RBNode<T>* node) {
  867. RBNode<T>* left = node->left_;
  868. node->left_ = left->right_;
  869. if (left->right_ != NULLNODE)
  870. left->right_->parent_ = node;
  871. left->parent_ = node->parent_;
  872. if (node->parent_ != NULLNODE) {
  873. if (node == node->parent_->right_) {
  874. node->parent_->right_ = left;
  875. } else {
  876. node->parent_->left_ = left;
  877. }
  878. } else {
  879. *root = left;
  880. }
  881. left->right_ = node;
  882. node->parent_ = left;
  883. return (node);
  884. }
  885. template <typename T>
  886. void
  887. RBTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  888. indent(os, depth);
  889. os << "tree has " << node_count_ << " node(s)\n";
  890. dumpTreeHelper(os, root_, depth);
  891. }
  892. template <typename T>
  893. void
  894. RBTree<T>::dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  895. unsigned int depth) const
  896. {
  897. if (node == NULLNODE) {
  898. indent(os, depth);
  899. os << "NULL\n";
  900. return;
  901. }
  902. indent(os, depth);
  903. os << node->name_.toText() << " ("
  904. << ((node->color_ == RBNode<T>::BLACK) ? "black" : "red") << ")";
  905. os << ((node->isEmpty()) ? "[invisible] \n" : "\n");
  906. if (node->down_ != NULLNODE) {
  907. indent(os, depth + 1);
  908. os << "begin down from " << node->name_.toText() << "\n";
  909. dumpTreeHelper(os, node->down_, depth + 1);
  910. indent(os, depth + 1);
  911. os << "end down from " << node->name_.toText() << "\n";
  912. }
  913. dumpTreeHelper(os, node->left_, depth + 1);
  914. dumpTreeHelper(os, node->right_, depth + 1);
  915. }
  916. template <typename T>
  917. void
  918. RBTree<T>::indent(std::ostream& os, unsigned int depth) {
  919. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  920. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  921. }
  922. }
  923. }
  924. #endif // _RBTREE_H
  925. // Local Variables:
  926. // mode: c++
  927. // End: