rbtree.h 42 KB

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