rbtree.h 32 KB

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