rbtree.h 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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 <exceptions/exceptions.h>
  24. #include <dns/name.h>
  25. #include <boost/utility.hpp>
  26. #include <boost/shared_ptr.hpp>
  27. #include <exceptions/exceptions.h>
  28. #include <ostream>
  29. #include <algorithm>
  30. #include <cassert>
  31. namespace isc {
  32. namespace datasrc {
  33. namespace helper {
  34. /// \brief Helper function to remove the base domain from super domain.
  35. ///
  36. /// The precondition of this function is the super_name contains the
  37. /// sub_name so
  38. /// \code Name a("a.b.c");
  39. /// Name b("b.c");
  40. /// Name c = a - b;
  41. /// \endcode
  42. /// c will contain "a".
  43. ///
  44. /// \note Functions in this namespace is not intended to be used outside of
  45. /// RBTree implementation.
  46. inline isc::dns::Name
  47. operator-(const isc::dns::Name& super_name, const isc::dns::Name& sub_name) {
  48. return (super_name.split(0, super_name.getLabelCount() -
  49. sub_name.getLabelCount()));
  50. }
  51. }
  52. /// Forward declare RBTree class here is convinent for following friend
  53. /// class declare inside RBNode and RBTreeNodeChain
  54. template <typename T>
  55. class RBTree;
  56. /// \brief \c RBNode is used by RBTree to store any data related to one domain
  57. /// name.
  58. ///
  59. /// This is meant to be used only from RBTree. It is meaningless to inherit it
  60. /// or create instances of it from elsewhere. For that reason, the constructor
  61. /// is private.
  62. ///
  63. /// It serves three roles. One is to keep structure of the \c RBTree as a
  64. /// red-black tree. For that purpose, it has left, right and parent pointers
  65. /// and color member. These are private and accessed only from within the tree.
  66. ///
  67. /// The second one is to store data for one domain name. The data related
  68. /// functions can be used to access and set the data.
  69. ///
  70. /// The third role is to keep the hierarchy of domains. The down pointer points
  71. /// to a subtree of subdomains. Note that we can traverse the hierarchy down,
  72. /// but not up.
  73. ///
  74. /// One special kind of node is non-terminal node. It has subdomains with
  75. /// RRsets, but doesn't have any RRsets itself.
  76. template <typename T>
  77. class RBNode : public boost::noncopyable {
  78. private:
  79. /// The RBNode is meant for use from within RBTree, so it has access to
  80. /// it.
  81. friend class RBTree<T>;
  82. /// \name Constructors
  83. ///
  84. /// \note The existence of a RBNode without a RBTree is meaningless.
  85. /// Therefore the constructors are private.
  86. //@{
  87. /// \brief Default constructor.
  88. ///
  89. /// This constructor is provided specifically for generating a special
  90. /// "null" node.
  91. RBNode();
  92. /// \brief Constructor from the node name.
  93. ///
  94. /// \param name The *relative* domain name (if this will live inside
  95. /// a.b.c and is called d.e.a.b.c, then you pass d.e).
  96. RBNode(const isc::dns::Name& name);
  97. //@}
  98. public:
  99. /// \brief Alias for shared pointer to the data.
  100. typedef boost::shared_ptr<T> NodeDataPtr;
  101. /// Node flags.
  102. ///
  103. /// Each flag value defines a non default property for a specific node.
  104. /// These are defined as bitmask type values for the convenience of
  105. /// internal implementation, but applications are expected to use
  106. /// each flag separately via the enum definitions.
  107. ///
  108. /// All (settable) flags are off by default; they must be explicitly
  109. /// set to on by the \c setFlag() method.
  110. enum Flags {
  111. FLAG_CALLBACK = 1, ///< Callback enabled. See \ref callback
  112. FLAG_USER1 = 0x80000000U, ///< Application specific flag
  113. FLAG_USER2 = 0x40000000U, ///< Application specific flag
  114. FLAG_USER3 = 0x20000000U ///< Application specific flag
  115. };
  116. private:
  117. // Some flag values are expected to be used for internal purposes
  118. // (e.g., representing the node color) in future versions, so we
  119. // limit the settable flags via the \c setFlag() method to those
  120. // explicitly defined in \c Flags. This constant represents all
  121. // such flags.
  122. static const uint32_t SETTABLE_FLAGS = (FLAG_CALLBACK | FLAG_USER1 |
  123. FLAG_USER2 | FLAG_USER3);
  124. public:
  125. /// \brief Destructor
  126. ///
  127. /// It might seem strange that constructors are private and destructor
  128. /// public, but this is needed because of shared pointers need access
  129. /// to the destructor.
  130. ///
  131. /// You should never call anything like:
  132. /// \code delete pointer_to_node; \endcode
  133. /// The RBTree handles both creation and destructoion of nodes.
  134. ~RBNode();
  135. /// \name Getter functions.
  136. //@{
  137. /// \brief Return the name of current node.
  138. ///
  139. /// It's relative to its containing node.
  140. ///
  141. /// To get the absolute name of one node, the node path from the top node
  142. /// to current node has to be recorded.
  143. const isc::dns::Name& getName() const { return (name_); }
  144. /// \brief Return the data stored in this node.
  145. ///
  146. /// You should not delete the data, it is handled by shared pointers.
  147. NodeDataPtr& getData() { return (data_); }
  148. /// \brief Return the data stored in this node.
  149. const NodeDataPtr& getData() const { return (data_); }
  150. /// \brief return whether the node has related data.
  151. ///
  152. /// There can be empty nodes inside the RBTree. They are usually the
  153. /// non-terminal domains, but it is possible (yet probably meaningless)
  154. /// empty nodes anywhere.
  155. bool isEmpty() const { return (data_.get() == NULL); }
  156. //@}
  157. /// \name Setter functions.
  158. //@{
  159. /// \brief Set the data stored in the node.
  160. void setData(const NodeDataPtr& data) { data_ = data; }
  161. //@}
  162. /// \name Node flag manipulation methods
  163. //@{
  164. /// Get the status of a node flag.
  165. ///
  166. /// This method returns whether the given node flag is set (enabled)
  167. /// on the node. The \c flag parameter is expected to be one of the
  168. /// defined \c Flags constants. For simplicity, the method interface
  169. /// does not prohibit passing an undefined flag or combined flags, but
  170. /// the return value in such a case will be meaningless for the caller
  171. /// (an application would have to use an ugly cast for such an unintended
  172. /// form of call, which will hopefully avoid accidental misuse).
  173. ///
  174. /// \exception None
  175. /// \param flag The flag to be tested.
  176. /// \return \c true if the \c flag is set; \c false otherwise.
  177. bool getFlag(Flags flag) const {
  178. return ((flags_ & flag) != 0);
  179. }
  180. /// Set or clear a node flag.
  181. ///
  182. /// This method changes the status of the specified node flag to either
  183. /// "on" (enabled) or "off" (disabled). The new status is specified by
  184. /// the \c on parameter.
  185. /// Like the \c getFlag() method, \c flag is expected to be one of the
  186. /// defined \c Flags constants. If an undefined or unsettable flag is
  187. /// specified, \c isc::InvalidParameter exception will be thrown.
  188. ///
  189. /// \exception isc::InvalidParameter Unsettable flag is specified
  190. /// \exception None otherwise
  191. /// \param flag The node flag to be changed.
  192. /// \param on If \c true, set the flag to on; otherwise set it to off.
  193. void setFlag(Flags flag, bool on = true) {
  194. if ((flag & ~SETTABLE_FLAGS) != 0) {
  195. isc_throw(isc::InvalidParameter,
  196. "Unsettable RBTree flag is being set");
  197. }
  198. if (on) {
  199. flags_ |= flag;
  200. } else {
  201. flags_ &= ~flag;
  202. }
  203. }
  204. //@}
  205. private:
  206. /// \name Callback related methods
  207. ///
  208. /// See the description of \c RBTree<T>::find() at \ref callback
  209. /// about callbacks.
  210. ///
  211. /// These methods never throw an exception.
  212. //@{
  213. /// Return if callback is enabled at the node.
  214. //@}
  215. private:
  216. /// \brief Define rbnode color
  217. enum RBNodeColor {BLACK, RED};
  218. /// This is a factory class method of a special singleton null node.
  219. static RBNode<T>* NULL_NODE() {
  220. static RBNode<T> null_node;
  221. return (&null_node);
  222. }
  223. /// \brief return the next node which is bigger than current node
  224. /// in the same subtree
  225. ///
  226. /// The next successor for this node is the next bigger node in terms of
  227. /// the DNSSEC order relation within the same single subtree.
  228. /// Note that it may NOT be the next bigger node in the entire RBTree;
  229. /// RBTree is a tree in tree, and the real next node may reside in
  230. /// an upper or lower subtree of the subtree where this node belongs.
  231. /// For example, if this node has a sub domain, the real next node is
  232. /// the smallest node in the sub domain tree.
  233. ///
  234. /// If this node is the biggest node within the subtree, this method
  235. /// returns \c NULL_NODE().
  236. ///
  237. /// This method never throws an exception.
  238. const RBNode<T>* successor() const;
  239. /// \brief return the next node which is smaller than current node
  240. /// in the same subtree
  241. ///
  242. /// The predecessor for this node is the next smaller node in terms of
  243. /// the DNSSEC order relation within the same single subtree.
  244. /// Note that it may NOT be the next smaller node in the entire RBTree;
  245. /// RBTree is a tree in tree, and the real next node may reside in
  246. /// an upper or lower subtree of the subtree where this node belongs.
  247. /// For example, if the predecessor node has a sub domain, the real next
  248. /// node is the largest node in the sub domain tree.
  249. ///
  250. /// If this node is the smallest node within the subtree, this method
  251. /// returns \c NULL_NODE().
  252. ///
  253. /// This method never throws an exception.
  254. const RBNode<T>* predecessor() const;
  255. /// \brief private shared implementation of successor and predecessor
  256. ///
  257. /// As the two mentioned functions are merely mirror images of each other,
  258. /// it makes little sense to keep both versions. So this is the body of the
  259. /// functions and we call it with the correct pointers.
  260. ///
  261. /// Not to be called directly, not even by friends.
  262. ///
  263. /// The overhead of the member pointers should be optimised out, as this
  264. /// will probably get completely inlined into predecessor and successor
  265. /// methods.
  266. const RBNode<T>* abstractSuccessor(RBNode<T>* RBNode<T>::*left,
  267. RBNode<T>* RBNode<T>::*right) const;
  268. /// \name Data to maintain the rbtree structure.
  269. //@{
  270. RBNode<T>* parent_;
  271. RBNode<T>* left_;
  272. RBNode<T>* right_;
  273. RBNodeColor color_;
  274. //@}
  275. /// \brief Relative name of the node.
  276. isc::dns::Name name_;
  277. /// \brief Data stored here.
  278. NodeDataPtr data_;
  279. /// \brief The subdomain tree.
  280. ///
  281. /// This points to the root node of trees of subdomains of this domain.
  282. ///
  283. /// \par Adding down pointer to \c RBNode has two purposes:
  284. /// \li Accelerate the search process, with sub domain tree, it splits the
  285. /// big flat tree into several hierarchy trees.
  286. /// \li It saves memory useage as it allows storing only relative names,
  287. /// avoiding storage of the same domain labels multiple times.
  288. RBNode<T>* down_;
  289. /// \brief If callback should be called when traversing this node in
  290. /// RBTree::find().
  291. ///
  292. /// \todo It might be needed to put it into more general attributes field.
  293. uint32_t flags_;
  294. };
  295. // This is only to support NULL nodes.
  296. template <typename T>
  297. RBNode<T>::RBNode() :
  298. parent_(NULL),
  299. left_(NULL),
  300. right_(NULL),
  301. color_(BLACK),
  302. // dummy name, the value doesn't matter:
  303. name_(isc::dns::Name::ROOT_NAME()),
  304. down_(NULL),
  305. flags_(0)
  306. {
  307. // Some compilers object to use of "this" in initializer lists.
  308. parent_ = this;
  309. left_ = this;
  310. right_ = this;
  311. down_ = this;
  312. }
  313. template <typename T>
  314. RBNode<T>::RBNode(const isc::dns::Name& name) :
  315. parent_(NULL_NODE()),
  316. left_(NULL_NODE()),
  317. right_(NULL_NODE()),
  318. color_(RED),
  319. name_(name),
  320. down_(NULL_NODE()),
  321. flags_(0)
  322. {
  323. }
  324. template <typename T>
  325. RBNode<T>::~RBNode() {
  326. }
  327. template <typename T>
  328. const RBNode<T>*
  329. RBNode<T>::abstractSuccessor(RBNode<T>* RBNode<T>::*left, RBNode<T>*
  330. RBNode<T>::*right) const
  331. {
  332. // This function is written as a successor. It becomes predecessor if
  333. // the left and right pointers are swapped. So in case of predecessor,
  334. // the left pointer points to right and vice versa. Don't get confused
  335. // by the idea, just imagine the pointers look into a mirror.
  336. const RBNode<T>* current = this;
  337. // If it has right node, the successor is the left-most node of the right
  338. // subtree.
  339. if (current->*right != RBNode<T>::NULL_NODE()) {
  340. current = current->*right;
  341. while (current->*left != RBNode<T>::NULL_NODE()) {
  342. current = current->*left;
  343. }
  344. return (current);
  345. }
  346. // Otherwise go up until we find the first left branch on our path to
  347. // root. If found, the parent of the branch is the successor.
  348. // Otherwise, we return the null node
  349. const RBNode<T>* parent = current->parent_;
  350. while (parent != RBNode<T>::NULL_NODE() && current == parent->*right) {
  351. current = parent;
  352. parent = parent->parent_;
  353. }
  354. return (parent);
  355. }
  356. template <typename T>
  357. const RBNode<T>*
  358. RBNode<T>::successor() const {
  359. return (abstractSuccessor(&RBNode<T>::left_, &RBNode<T>::right_));
  360. }
  361. template <typename T>
  362. const RBNode<T>*
  363. RBNode<T>::predecessor() const {
  364. // Swap the left and right pointers for the abstractSuccessor
  365. return (abstractSuccessor(&RBNode<T>::right_, &RBNode<T>::left_));
  366. }
  367. /// \brief RBTreeNodeChain stores detailed information of \c RBTree::find()
  368. /// result.
  369. ///
  370. /// - The \c RBNode that was last compared with the search name, and
  371. /// the comparison result at that point in the form of
  372. /// \c isc::dns::NameComparisonResult.
  373. /// - A sequence of nodes that forms a path to the found node (which is
  374. /// not yet implemented).
  375. ///
  376. /// The comparison result can be used to handle some rare cases such as
  377. /// empty node processing.
  378. /// The node sequence keeps track of the nodes to reach any given node from
  379. /// the root of RBTree.
  380. ///
  381. /// Currently, RBNode does not have "up" pointers in them (i.e., back pointers
  382. /// from the root of one level of tree of trees to the node in the parent
  383. /// tree whose down pointer points to that root node) for memory usage
  384. /// reasons, so there is no other way to find the path back to the root from
  385. /// any given RBNode.
  386. ///
  387. /// \note This design may change in future versions. In particular, it's
  388. /// quite likely we want to have that pointer if we want to optimize name
  389. /// compression by exploiting the structure of the zone. If and when that
  390. /// happens we should also revisit the need for the chaining.
  391. /// Also, the class name may not be appropriate now that it contains other
  392. /// information than a node "chain", and the chain itself may even be
  393. /// deprecated. Something like "RBTreeFindContext" may be a better name.
  394. /// This point should be revisited later.
  395. ///
  396. /// RBTreeNodeChain is constructed and manipulated only inside the \c RBTree
  397. /// class.
  398. /// \c RBTree uses it as an inner data structure to iterate over the whole
  399. /// RBTree.
  400. /// This is the reason why manipulation methods such as \c push() and \c pop()
  401. /// are private (and not shown in the doxygen document).
  402. template <typename T>
  403. class RBTreeNodeChain {
  404. /// RBTreeNodeChain is initialized by RBTree, only RBTree has
  405. /// knowledge to manipuate it.
  406. friend class RBTree<T>;
  407. public:
  408. /// \name Constructors and Assignment Operator.
  409. ///
  410. /// \note The copy constructor and the assignment operator are
  411. /// intentionally defined as private, making this class non copyable.
  412. /// This may have to be changed in a future version with newer need.
  413. /// For now we explicitly disable copy to avoid accidental copy happens
  414. /// unintentionally.
  415. //{@
  416. /// The default constructor.
  417. ///
  418. /// \exception None
  419. RBTreeNodeChain() : node_count_(0), last_compared_(NULL),
  420. // XXX: meaningless initial values:
  421. last_comparison_(0, 0,
  422. isc::dns::NameComparisonResult::EQUAL)
  423. {}
  424. private:
  425. RBTreeNodeChain(const RBTreeNodeChain<T>&);
  426. RBTreeNodeChain<T>& operator=(const RBTreeNodeChain<T>&);
  427. //@}
  428. public:
  429. /// Clear the state of the chain.
  430. ///
  431. /// This method re-initializes the internal state of the chain so that
  432. /// it can be reused for subsequent operations.
  433. ///
  434. /// \exception None
  435. void clear() {
  436. node_count_ = 0;
  437. last_compared_ = NULL;
  438. }
  439. /// Return the \c RBNode that was last compared in \c RBTree::find().
  440. ///
  441. /// If this chain has been passed to \c RBTree::find() and there has
  442. /// been name comparison against the search name, the last compared
  443. /// \c RBNode is recorded within the chain. This method returns that
  444. /// node.
  445. /// If \c RBTree::find() hasn't been called with this chain or name
  446. /// comparison hasn't taken place (which is possible if the tree is empty),
  447. /// this method returns \c NULL.
  448. ///
  449. /// \exception None
  450. const RBNode<T>* getLastComparedNode() const {
  451. return (last_compared_);
  452. }
  453. /// Return the result of last name comparison in \c RBTree::find().
  454. ///
  455. /// Like \c getLastComparedNode(), \c RBTree::find() records the result
  456. /// of the last name comparison in the chain. This method returns the
  457. /// result.
  458. /// The return value of this method is only meaningful when comparison
  459. /// has taken place, i.e, when \c getLastComparedNode() would return a
  460. /// non \c NULL value.
  461. ///
  462. /// \exception None
  463. const isc::dns::NameComparisonResult& getLastComparisonResult() const {
  464. return (last_comparison_);
  465. }
  466. /// \brief Return the number of levels stored in the chain.
  467. ///
  468. /// It's equal to the number of nodes in the chain; for an empty
  469. /// chain, 0 will be returned.
  470. ///
  471. /// \exception None
  472. unsigned int getLevelCount() const { return (node_count_); }
  473. /// \brief return the absolute name for the node which this
  474. /// \c RBTreeNodeChain currently refers to.
  475. ///
  476. /// The chain must not be empty.
  477. ///
  478. /// \exception isc::BadValue the chain is empty.
  479. /// \exception std::bad_alloc memory allocation for the new name fails.
  480. isc::dns::Name getAbsoluteName() const {
  481. if (isEmpty()) {
  482. isc_throw(isc::BadValue,
  483. "RBTreeNodeChain::getAbsoluteName is called on an empty "
  484. "chain");
  485. }
  486. const RBNode<T>* top_node = top();
  487. isc::dns::Name absolute_name = top_node->getName();
  488. int node_count = node_count_ - 1;
  489. while (node_count > 0) {
  490. top_node = nodes_[node_count - 1];
  491. absolute_name = absolute_name.concatenate(top_node->getName());
  492. --node_count;
  493. }
  494. return (absolute_name);
  495. }
  496. private:
  497. // the following private functions check invariants about the internal
  498. // state using assert() instead of exception. The state of a chain
  499. // can only be modified operations within this file, so if any of the
  500. // assumptions fails it means an internal bug.
  501. /// \brief return whther node chain has node in it.
  502. ///
  503. /// \exception None
  504. bool isEmpty() const { return (node_count_ == 0); }
  505. /// \brief return the top node for the node chain
  506. ///
  507. /// RBTreeNodeChain store all the nodes along top node to
  508. /// root node of RBTree
  509. ///
  510. /// \exception None
  511. const RBNode<T>* top() const {
  512. assert(!isEmpty());
  513. return (nodes_[node_count_ - 1]);
  514. }
  515. /// \brief pop the top node from the node chain
  516. ///
  517. /// After pop, up/super node of original top node will be
  518. /// the top node
  519. ///
  520. /// \exception None
  521. void pop() {
  522. assert(!isEmpty());
  523. --node_count_;
  524. }
  525. /// \brief add the node into the node chain
  526. ///
  527. /// If the node chain isn't empty, the node should be
  528. /// the sub domain of the original top node in node chain
  529. /// otherwise the node should be the root node of RBTree.
  530. ///
  531. /// \exception None
  532. void push(const RBNode<T>* node) {
  533. assert(node_count_ < RBT_MAX_LEVEL);
  534. nodes_[node_count_++] = node;
  535. }
  536. private:
  537. // The max label count for one domain name is Name::MAX_LABELS (128).
  538. // Since each node in rbtree stores at least one label, it's also equal
  539. // to the possible maximum level.
  540. const static int RBT_MAX_LEVEL = isc::dns::Name::MAX_LABELS;
  541. int node_count_;
  542. const RBNode<T>* nodes_[RBT_MAX_LEVEL];
  543. const RBNode<T>* last_compared_;
  544. isc::dns::NameComparisonResult last_comparison_;
  545. };
  546. // note: the following class description is documented using multiline comments
  547. // because the verbatim diagram contain a backslash, which could be interpreted
  548. // as escape of newline in singleline comment.
  549. /**
  550. * \brief \c RBTree class represents all the domains with the same suffix.
  551. * It can be used to store the domains in one zone, for example.
  552. *
  553. * RBTree is a generic map from domain names to any kind of data. Internally,
  554. * it uses a red-black tree. However, it isn't one tree containing everything.
  555. * Subdomains are trees, so this structure is recursive - trees inside trees.
  556. * But, from the interface point of view, it is opaque data structure.
  557. *
  558. * \c RBTree splits the domain space into hierarchy red black trees; nodes
  559. * in one tree has the same base name. The benefit of this struct is that:
  560. * - Enhances the query performace compared with one big flat red black tree.
  561. * - Decreases the memory footprint, as it doesn't store the suffix labels
  562. * multiple times.
  563. *
  564. * Depending on different usage, rbtree will support different search policies.
  565. * Whether to return an empty node to end user is one policy among them.
  566. * The default policy is to NOT return an empty node to end user;
  567. * to change the behavior, specify \c true for the constructor parameter
  568. * \c returnEmptyNode.
  569. * \note The search policy only affects the \c find() behavior of RBTree.
  570. * When inserting one name into RBTree, if the node with the name already
  571. * exists in the RBTree and it's an empty node which doesn't have any data,
  572. * the \c insert() method will still return \c ALREADYEXISTS regardless of
  573. * the search policy.
  574. *
  575. * \anchor diagram
  576. *
  577. * with the following names:
  578. * - a
  579. * - b
  580. * - c
  581. * - x.d.e.f
  582. * - z.d.e.f
  583. * - g.h
  584. * - o.w.y.d.e.f
  585. * - p.w.y.d.e.f
  586. * - q.w.y.d.e.f
  587. *
  588. * the tree will look like:
  589. * \verbatim
  590. b
  591. / \
  592. a d.e.f
  593. /|\
  594. c | g.h
  595. |
  596. w.y
  597. /|\
  598. x | z
  599. |
  600. p
  601. / \
  602. o q
  603. \endverbatim
  604. * \todo
  605. * - add remove interface
  606. * - add iterator to iterate over the whole \c RBTree. This may be necessary,
  607. * for example, to support AXFR.
  608. */
  609. template <typename T>
  610. class RBTree : public boost::noncopyable {
  611. friend class RBNode<T>;
  612. public:
  613. /// \brief The return value for the \c find() and insert() methods
  614. enum Result {
  615. SUCCESS, ///< Insert was successful
  616. /// \brief The node returned from find mathes exactly the name given
  617. EXACTMATCH,
  618. PARTIALMATCH, ///< A superdomain node was found
  619. NOTFOUND, ///< Not even any superdomain was found
  620. /// \brief Returned by insert() if a node of the name already exists
  621. ALREADYEXISTS,
  622. };
  623. /// \name Constructor and Destructor
  624. //@{
  625. /// The constructor.
  626. ///
  627. /// It never throws an exception.
  628. explicit RBTree(bool returnEmptyNode = false);
  629. /// \b Note: RBTree is not intended to be inherited so the destructor
  630. /// is not virtual
  631. ~RBTree();
  632. //@}
  633. /// \name Find methods
  634. ///
  635. /// \brief Find the node that gives a longest match against the given name.
  636. ///
  637. /// \anchor find
  638. ///
  639. /// These methods search the RBTree for a node whose name is longest
  640. /// against name. The found node, if any, is returned via the node pointer.
  641. ///
  642. /// By default, nodes that don't have data (see RBNode::isEmpty) are
  643. /// ignored and the result can be NOTFOUND even if there's a node whose
  644. /// name matches. If the \c RBTree is constructed with its
  645. /// \c returnEmptyNode parameter being \c true, an empty node will also
  646. /// be match candidates.
  647. ///
  648. /// \note Even when \c returnEmptyNode is \c true, not all empty nodes
  649. /// in terms of the DNS protocol may necessarily be found by this method.
  650. /// For example, in the \ref diagram shown in the class description,
  651. /// the name y.d.e.f is logically contained in the tree as part of the
  652. /// node w.y, but the \c find() variants cannot find the former for
  653. /// the search key of y.d.e.f, no matter how the \c RBTree is constructed.
  654. /// The caller of this method must use a different way to identify the
  655. /// hidden match when necessary.
  656. ///
  657. /// These methods involve operations on names that can throw an exception.
  658. /// If that happens the exception will be propagated to the caller.
  659. /// The callback function should generally not throw an exception, but
  660. /// if it throws, the exception will be propagated to the caller.
  661. ///
  662. /// The \c name parameter says what should be found. The node parameter
  663. /// is output only and in case of EXACTMATCH and PARTIALMATCH, it is set
  664. /// to a pointer to the found node.
  665. ///
  666. /// They return:
  667. /// - EXACTMATCH when a node with the same name as requested exists.
  668. /// - PARTIALMATCH when a node with the same name does not exist (or is
  669. /// empty), but there's a (nonempty) superdomain of the requested one.
  670. /// The superdomain with longest name is returned through the node
  671. /// parameter. Beware that if you store a zone in the tree, you may get
  672. /// PARTIALMATCH with zone apex when the given domain name is not there.
  673. /// You should not try to delegate into another zone in that case.
  674. /// - NOTFOUND if there's no node with the same name nor any superdomain
  675. /// of it. In that case, node parameter is left intact.
  676. //@{
  677. /// \brief Simple find.
  678. ///
  679. /// Acts as described in the \ref find section.
  680. Result find(const isc::dns::Name& name, RBNode<T>** node) const {
  681. RBTreeNodeChain<T> node_path;
  682. return (find<void*>(name, node, node_path, NULL, NULL));
  683. }
  684. /// \brief Simple find returning immutable node.
  685. ///
  686. /// Acts as described in the \ref find section, but returns immutable node
  687. /// pointer.
  688. Result find(const isc::dns::Name& name, const RBNode<T>** node) const {
  689. RBTreeNodeChain<T> node_path;
  690. RBNode<T> *target_node = NULL;
  691. Result ret = (find<void*>(name, &target_node, node_path, NULL, NULL));
  692. if (ret != NOTFOUND) {
  693. *node = target_node;
  694. }
  695. return (ret);
  696. }
  697. /// \brief Find with callback and node chain.
  698. /// \anchor callback
  699. ///
  700. /// This version of \c find() is specifically designed for the backend
  701. /// of the \c InMemoryZoneFinder class, and implements all necessary
  702. /// features for that purpose. Other applications shouldn't need these
  703. /// additional features, and should normally use the simpler versions.
  704. ///
  705. /// This version of \c find() calls the callback whenever traversing (on
  706. /// the way from root down the tree) a marked node on the way down through
  707. /// the domain namespace (see \c RBNode::enableCallback and related
  708. /// functions).
  709. ///
  710. /// If you return true from the callback, the search is stopped and a
  711. /// PARTIALMATCH is returned with the given node. Note that this node
  712. /// doesn't really need to be the one with longest possible match.
  713. ///
  714. /// This callback mechanism was designed with zone cut (delegation)
  715. /// processing in mind. The marked nodes would be the ones at delegation
  716. /// points. It is not expected that any other applications would need
  717. /// callbacks; they should use the versions of find without callbacks.
  718. /// The callbacks are not general functors for the same reason - we don't
  719. /// expect it to be needed.
  720. ///
  721. /// Another special feature of this version is the ability to record
  722. /// more detailed information regarding the search result.
  723. ///
  724. /// This information will be returned via the \c node_path parameter,
  725. /// which is an object of class \c RBTreeNodeChain.
  726. /// The passed parameter must be empty.
  727. ///
  728. /// \note The rest of the description isn't yet implemented. It will be
  729. /// handled in Trac ticket #517.
  730. ///
  731. /// On success, the node sequence stoed in \c node_path will contain all
  732. /// the ancestor nodes from the found node towards the root.
  733. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  734. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  735. /// chain will be o, w.f and d.e.f will be stored below it.
  736. ///
  737. /// This feature can be used to get the absolute name for a node;
  738. /// to do so, we need to travel upside from the node toward the root,
  739. /// concatenating all ancestor names. With the current implementation
  740. /// it's not possible without a node chain, because there is a no pointer
  741. /// from the root of a subtree to the parent subtree (this may change
  742. /// in a future version). A node chain can also be used to find the next
  743. /// node of a given node in the entire RBTree; the \c nextNode() method
  744. /// takes a node chain as a parameter.
  745. ///
  746. /// \exception isc::BadValue node_path is not empty (not yet implemented).
  747. ///
  748. /// \param name Target to be found
  749. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  750. /// it will store a pointer to the matching node
  751. /// \param node_path Other search details will be stored (see the
  752. /// description)
  753. /// \param callback If non \c NULL, a call back function to be called
  754. /// at marked nodes (see above).
  755. /// \param callback_arg A caller supplied argument to be passed to
  756. /// \c callback.
  757. ///
  758. /// \return As described above, but in case of callback returning true,
  759. /// it returns immediately with the current node.
  760. template <typename CBARG>
  761. Result find(const isc::dns::Name& name,
  762. RBNode<T>** node,
  763. RBTreeNodeChain<T>& node_path,
  764. bool (*callback)(const RBNode<T>&, CBARG),
  765. CBARG callback_arg) const;
  766. /// \brief Simple find returning immutable node.
  767. ///
  768. /// Acts as described in the \ref find section, but returns immutable
  769. /// node pointer.
  770. template <typename CBARG>
  771. Result find(const isc::dns::Name& name,
  772. const RBNode<T>** node,
  773. RBTreeNodeChain<T>& node_path,
  774. bool (*callback)(const RBNode<T>&, CBARG),
  775. CBARG callback_arg) const
  776. {
  777. RBNode<T>* target_node = NULL;
  778. Result ret = find(name, &target_node, node_path, callback,
  779. callback_arg);
  780. if (ret != NOTFOUND) {
  781. *node = target_node;
  782. }
  783. return (ret);
  784. }
  785. //@}
  786. /// \brief return the next bigger node in DNSSEC order from a given node
  787. /// chain.
  788. ///
  789. /// This method identifies the next bigger node of the node currently
  790. /// referenced in \c node_path and returns it.
  791. /// This method also updates the passed \c node_path so that it will store
  792. /// the path for the returned next node.
  793. /// It will be convenient when we want to iterate over the all nodes
  794. /// of \c RBTree; we can do this by calling this method repeatedly
  795. /// starting from the root node.
  796. ///
  797. /// \note \c nextNode() will iterate over all the nodes in RBTree including
  798. /// empty nodes. If empty node isn't desired, it's easy to add logic to
  799. /// check return node and keep invoking \c nextNode() until the non-empty
  800. /// node is retrieved.
  801. ///
  802. /// \exception isc::BadValue node_path is empty.
  803. ///
  804. /// \param node_path A node chain that stores all the nodes along the path
  805. /// from root to node.
  806. ///
  807. /// \return An \c RBNode that is next bigger than \c node; if \c node is
  808. /// the largest, \c NULL will be returned.
  809. const RBNode<T>* nextNode(RBTreeNodeChain<T>& node_path) const;
  810. /// \brief return the next smaller node in DNSSEC order from a node
  811. /// searched by RBTree::find().
  812. ///
  813. /// This acts similarly to \c nextNode(), but it walks in the other
  814. /// direction. But unlike that, this can start even if the node requested
  815. /// by find was not found. In that case, it will identify the node that is
  816. /// previous to the queried name.
  817. ///
  818. /// \note \c previousNode() will iterate over all the nodes in RBTree
  819. /// including empty nodes. If empty node isn't desired, it's easy to add
  820. /// logic to check return node and keep invoking \c previousNode() until the
  821. /// non-empty node is retrieved.
  822. ///
  823. /// \exception isc::BadValue node_path is empty.
  824. ///
  825. /// \param node_path A node chain that stores all the nodes along the path
  826. /// from root to node and the result of \c find(). This will get modified.
  827. ///
  828. /// \return An \c RBNode that is next smaller than \c node; if \c node is
  829. /// the smallest, \c NULL will be returned.
  830. const RBNode<T>* previousNode(RBTreeNodeChain<T>& node_path) const;
  831. /// \brief Get the total number of nodes in the tree
  832. ///
  833. /// It includes nodes internally created as a result of adding a domain
  834. /// name that is a subdomain of an existing node of the tree.
  835. /// This function is mainly intended to be used for debugging.
  836. int getNodeCount() const { return (node_count_); }
  837. /// \name Debug function
  838. //@{
  839. /// \brief Print the nodes in the trees.
  840. ///
  841. /// \param os A \c std::ostream object to which the tree is printed.
  842. /// \param depth A factor of the initial indentation. Each line
  843. /// will begin with space character repeating <code>5 * depth</code>
  844. /// times.
  845. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  846. //@}
  847. /// \name Modify functions
  848. //@{
  849. /// \brief Insert the domain name into the tree.
  850. ///
  851. /// It either finds an already existing node of the given name or inserts
  852. /// a new one, if none exists yet. In any case, the inserted_node parameter
  853. /// is set to point to that node. You can fill data into it or modify it.
  854. /// So, if you don't know if a node exists or not and you need to modify
  855. /// it, just call insert and act by the result.
  856. ///
  857. /// Please note that the tree can add some empty nodes by itself, so don't
  858. /// assume that if you didn't insert a node of that name it doesn't exist.
  859. ///
  860. /// This method normally involves resource allocation. If it fails
  861. /// the corresponding standard exception will be thrown.
  862. ///
  863. /// This method does not provide the strong exception guarantee in its
  864. /// strict sense; if an exception is thrown in the middle of this
  865. /// method, the internal structure may change. However, it should
  866. /// still retain the same property as a mapping container before this
  867. /// method is called. For example, the result of \c find() should be
  868. /// the same. This method provides the weak exception guarantee in its
  869. /// normal sense.
  870. ///
  871. /// \param name The name to be inserted into the tree.
  872. /// \param inserted_node This is an output parameter and is set to the
  873. /// node.
  874. ///
  875. /// \return
  876. /// - SUCCESS The node was added.
  877. /// - ALREADYEXISTS There was already a node of that name, so it was not
  878. /// added.
  879. Result insert(const isc::dns::Name& name, RBNode<T>** inserted_node);
  880. /// \brief Swaps two tree's contents.
  881. ///
  882. /// This acts the same as many std::*.swap functions, exchanges the
  883. /// contents. This doesn't throw anything.
  884. void swap(RBTree<T>& other) {
  885. std::swap(root_, other.root_);
  886. std::swap(NULLNODE, other.NULLNODE);
  887. std::swap(node_count_, other.node_count_);
  888. }
  889. //@}
  890. private:
  891. /// \name RBTree balance functions
  892. //@{
  893. void insertRebalance(RBNode<T>** root, RBNode<T>* node);
  894. RBNode<T>* rightRotate(RBNode<T>** root, RBNode<T>* node);
  895. RBNode<T>* leftRotate(RBNode<T>** root, RBNode<T>* node);
  896. //@}
  897. /// \name Helper functions
  898. //@{
  899. /// \brief delete tree whose root is equal to node
  900. void deleteHelper(RBNode<T> *node);
  901. /// \brief Print the information of given RBNode.
  902. void dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  903. unsigned int depth) const;
  904. /// \brief Indentation helper function for dumpTree
  905. static void indent(std::ostream& os, unsigned int depth);
  906. /// Split one node into two nodes, keep the old node and create one new
  907. /// node, old node will hold the base name, new node will be the down node
  908. /// of old node, new node will hold the sub_name, the data
  909. /// of old node will be move into new node, and old node became non-terminal
  910. void nodeFission(RBNode<T>& node, const isc::dns::Name& sub_name);
  911. //@}
  912. RBNode<T>* NULLNODE;
  913. RBNode<T>* root_;
  914. /// the node count of current tree
  915. unsigned int node_count_;
  916. /// search policy for rbtree
  917. const bool needsReturnEmptyNode_;
  918. };
  919. template <typename T>
  920. RBTree<T>::RBTree(bool returnEmptyNode) :
  921. NULLNODE(RBNode<T>::NULL_NODE()),
  922. root_(NULLNODE),
  923. node_count_(0),
  924. needsReturnEmptyNode_(returnEmptyNode)
  925. {
  926. }
  927. template <typename T>
  928. RBTree<T>::~RBTree() {
  929. deleteHelper(root_);
  930. assert(node_count_ == 0);
  931. }
  932. template <typename T>
  933. void
  934. RBTree<T>::deleteHelper(RBNode<T>* root) {
  935. if (root == NULLNODE) {
  936. return;
  937. }
  938. RBNode<T>* node = root;
  939. while (root->left_ != NULLNODE || root->right_ != NULLNODE) {
  940. while (node->left_ != NULLNODE || node->right_ != NULLNODE) {
  941. node = (node->left_ != NULLNODE) ? node->left_ : node->right_;
  942. }
  943. RBNode<T>* parent = node->parent_;
  944. if (parent->left_ == node) {
  945. parent->left_ = NULLNODE;
  946. } else {
  947. parent->right_ = NULLNODE;
  948. }
  949. deleteHelper(node->down_);
  950. delete node;
  951. --node_count_;
  952. node = parent;
  953. }
  954. deleteHelper(root->down_);
  955. delete root;
  956. --node_count_;
  957. }
  958. template <typename T>
  959. template <typename CBARG>
  960. typename RBTree<T>::Result
  961. RBTree<T>::find(const isc::dns::Name& target_name,
  962. RBNode<T>** target,
  963. RBTreeNodeChain<T>& node_path,
  964. bool (*callback)(const RBNode<T>&, CBARG),
  965. CBARG callback_arg) const
  966. {
  967. using namespace helper;
  968. if (!node_path.isEmpty()) {
  969. isc_throw(isc::BadValue, "RBTree::find is given a non empty chain");
  970. }
  971. RBNode<T>* node = root_;
  972. Result ret = NOTFOUND;
  973. isc::dns::Name name = target_name;
  974. while (node != NULLNODE) {
  975. node_path.last_compared_ = node;
  976. node_path.last_comparison_ = name.compare(node->name_);
  977. const isc::dns::NameComparisonResult::NameRelation relation =
  978. node_path.last_comparison_.getRelation();
  979. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  980. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  981. node_path.push(node);
  982. *target = node;
  983. ret = EXACTMATCH;
  984. }
  985. break;
  986. } else {
  987. const int common_label_count =
  988. node_path.last_comparison_.getCommonLabels();
  989. // If the common label count is 1, there is no common label between
  990. // the two names, except the trailing "dot". In this case the two
  991. // sequences of labels have essentially no hierarchical
  992. // relationship in terms of matching, so we should continue the
  993. // binary search. One important exception is when the node
  994. // represents the root name ("."), in which case the comparison
  995. // result must indeed be considered subdomain matching. (We use
  996. // getLength() to check if the name is root, which is an equivalent
  997. // but cheaper way).
  998. if (common_label_count == 1 && node->name_.getLength() != 1) {
  999. node = (node_path.last_comparison_.getOrder() < 0) ?
  1000. node->left_ : node->right_;
  1001. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1002. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1003. ret = PARTIALMATCH;
  1004. *target = node;
  1005. if (callback != NULL &&
  1006. node->getFlag(RBNode<T>::FLAG_CALLBACK)) {
  1007. if ((callback)(*node, callback_arg)) {
  1008. break;
  1009. }
  1010. }
  1011. }
  1012. node_path.push(node);
  1013. name = name - node->name_;
  1014. node = node->down_;
  1015. } else {
  1016. break;
  1017. }
  1018. }
  1019. }
  1020. return (ret);
  1021. }
  1022. template <typename T>
  1023. const RBNode<T>*
  1024. RBTree<T>::nextNode(RBTreeNodeChain<T>& node_path) const {
  1025. if (node_path.isEmpty()) {
  1026. isc_throw(isc::BadValue, "RBTree::nextNode is given an empty chain");
  1027. }
  1028. const RBNode<T>* node = node_path.top();
  1029. // if node has sub domain, the next domain is the smallest
  1030. // domain in sub domain tree
  1031. if (node->down_ != NULLNODE) {
  1032. const RBNode<T>* left_most = node->down_;
  1033. while (left_most->left_ != NULLNODE) {
  1034. left_most = left_most->left_;
  1035. }
  1036. node_path.push(left_most);
  1037. return (left_most);
  1038. }
  1039. // node_path go to up level
  1040. node_path.pop();
  1041. // otherwise found the successor node in current level
  1042. const RBNode<T>* successor = node->successor();
  1043. if (successor != NULLNODE) {
  1044. node_path.push(successor);
  1045. return (successor);
  1046. }
  1047. // if no successor found move to up level, the next successor
  1048. // is the successor of up node in the up level tree, if
  1049. // up node doesn't have successor we gonna keep moving to up
  1050. // level
  1051. while (!node_path.isEmpty()) {
  1052. const RBNode<T>* up_node_successor = node_path.top()->successor();
  1053. node_path.pop();
  1054. if (up_node_successor != NULLNODE) {
  1055. node_path.push(up_node_successor);
  1056. return (up_node_successor);
  1057. }
  1058. }
  1059. return (NULL);
  1060. }
  1061. template <typename T>
  1062. const RBNode<T>*
  1063. RBTree<T>::previousNode(RBTreeNodeChain<T>& node_path) const {
  1064. if (node_path.isEmpty()) {
  1065. isc_throw(isc::BadValue, "RBTree::nextNode is given an empty chain");
  1066. }
  1067. const RBNode<T>* node(node_path.top());
  1068. // Try going left in this tree
  1069. node = node->predecessor();
  1070. if (node == NULLNODE) {
  1071. // We are the smallest ones in this tree. We go one level
  1072. // up. That one is the smaller one than us.
  1073. if (node_path.getLevelCount() == 1) {
  1074. // This was the root of the tree. We can't go up, sorry, we end.
  1075. return (NULL);
  1076. }
  1077. node_path.pop();
  1078. return (node_path.top());
  1079. }
  1080. // Exchange the node at the top of the path, as we move horizontaly
  1081. // through the domain tree
  1082. node_path.pop();
  1083. node_path.push(node);
  1084. // Try going as deep as possible, keeping on the right side of the trees
  1085. while (node->down_ != NULLNODE) {
  1086. // Move to the tree below
  1087. node = node->down_;
  1088. // And get as much to the right of the tree as possible
  1089. while (node->right_ != NULLNODE) {
  1090. node = node->right_;
  1091. }
  1092. // Now, we found the right-most node in the sub-tree, we need to
  1093. // include it in the path
  1094. node_path.push(node);
  1095. }
  1096. // Now, if the current node has no down_ pointer any more, it's the
  1097. // correct one.
  1098. return (node);
  1099. }
  1100. template <typename T>
  1101. typename RBTree<T>::Result
  1102. RBTree<T>::insert(const isc::dns::Name& target_name, RBNode<T>** new_node) {
  1103. using namespace helper;
  1104. RBNode<T>* parent = NULLNODE;
  1105. RBNode<T>* current = root_;
  1106. RBNode<T>* up_node = NULLNODE;
  1107. isc::dns::Name name = target_name;
  1108. int order = -1;
  1109. while (current != NULLNODE) {
  1110. const isc::dns::NameComparisonResult compare_result =
  1111. name.compare(current->name_);
  1112. const isc::dns::NameComparisonResult::NameRelation relation =
  1113. compare_result.getRelation();
  1114. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1115. if (new_node != NULL) {
  1116. *new_node = current;
  1117. }
  1118. return (ALREADYEXISTS);
  1119. } else {
  1120. const int common_label_count = compare_result.getCommonLabels();
  1121. // Note: see find() for the check of getLength().
  1122. if (common_label_count == 1 && current->name_.getLength() != 1) {
  1123. parent = current;
  1124. order = compare_result.getOrder();
  1125. current = order < 0 ? current->left_ : current->right_;
  1126. } else {
  1127. // insert sub domain to sub tree
  1128. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1129. parent = NULLNODE;
  1130. up_node = current;
  1131. name = name - current->name_;
  1132. current = current->down_;
  1133. } else {
  1134. // The number of labels in common is fewer
  1135. // than the number of labels at the current
  1136. // node, so the current node must be adjusted
  1137. // to have just the common suffix, and a down
  1138. // pointer made to a new tree.
  1139. const isc::dns::Name common_ancestor = name.split(
  1140. name.getLabelCount() - common_label_count,
  1141. common_label_count);
  1142. nodeFission(*current, common_ancestor);
  1143. }
  1144. }
  1145. }
  1146. }
  1147. RBNode<T>** current_root = (up_node != NULLNODE) ?
  1148. &(up_node->down_) : &root_;
  1149. // using auto_ptr here is avoid memory leak in case of exceptoin raised
  1150. // after the RBNode creation, if we can make sure no exception will be
  1151. // raised until the end of the function, we can remove it for optimization
  1152. std::auto_ptr<RBNode<T> > node(new RBNode<T>(name));
  1153. node->parent_ = parent;
  1154. if (parent == NULLNODE) {
  1155. *current_root = node.get();
  1156. //node is the new root of sub tree, so its init color
  1157. // is BLACK
  1158. node->color_ = RBNode<T>::BLACK;
  1159. } else if (order < 0) {
  1160. parent->left_ = node.get();
  1161. } else {
  1162. parent->right_ = node.get();
  1163. }
  1164. insertRebalance(current_root, node.get());
  1165. if (new_node != NULL) {
  1166. *new_node = node.get();
  1167. }
  1168. ++node_count_;
  1169. node.release();
  1170. return (SUCCESS);
  1171. }
  1172. // Note: when we redesign this (still keeping the basic concept), we should
  1173. // change this part so the newly created node will be used for the inserted
  1174. // name (and therefore the name for the existing node doesn't change).
  1175. // Otherwise, things like shortcut links between nodes won't work.
  1176. template <typename T>
  1177. void
  1178. RBTree<T>::nodeFission(RBNode<T>& node, const isc::dns::Name& base_name) {
  1179. using namespace helper;
  1180. const isc::dns::Name sub_name = node.name_ - base_name;
  1181. // using auto_ptr here is to avoid memory leak in case of exception raised
  1182. // after the RBNode creation
  1183. std::auto_ptr<RBNode<T> > down_node(new RBNode<T>(sub_name));
  1184. node.name_ = base_name;
  1185. // the rest of this function should be exception free so that it keeps
  1186. // consistent behavior (i.e., a weak form of strong exception guarantee)
  1187. // even if code after the call to this function throws an exception.
  1188. std::swap(node.data_, down_node->data_);
  1189. std::swap(node.flags_, down_node->flags_);
  1190. down_node->down_ = node.down_;
  1191. node.down_ = down_node.get();
  1192. // root node of sub tree, the initial color is BLACK
  1193. down_node->color_ = RBNode<T>::BLACK;
  1194. ++node_count_;
  1195. down_node.release();
  1196. }
  1197. template <typename T>
  1198. void
  1199. RBTree<T>::insertRebalance(RBNode<T>** root, RBNode<T>* node) {
  1200. RBNode<T>* uncle;
  1201. while (node != *root && node->parent_->color_ == RBNode<T>::RED) {
  1202. if (node->parent_ == node->parent_->parent_->left_) {
  1203. uncle = node->parent_->parent_->right_;
  1204. if (uncle->color_ == RBNode<T>::RED) {
  1205. node->parent_->color_ = RBNode<T>::BLACK;
  1206. uncle->color_ = RBNode<T>::BLACK;
  1207. node->parent_->parent_->color_ = RBNode<T>::RED;
  1208. node = node->parent_->parent_;
  1209. } else {
  1210. if (node == node->parent_->right_) {
  1211. node = node->parent_;
  1212. leftRotate(root, node);
  1213. }
  1214. node->parent_->color_ = RBNode<T>::BLACK;
  1215. node->parent_->parent_->color_ = RBNode<T>::RED;
  1216. rightRotate(root, node->parent_->parent_);
  1217. }
  1218. } else {
  1219. uncle = node->parent_->parent_->left_;
  1220. if (uncle->color_ == RBNode<T>::RED) {
  1221. node->parent_->color_ = RBNode<T>::BLACK;
  1222. uncle->color_ = RBNode<T>::BLACK;
  1223. node->parent_->parent_->color_ = RBNode<T>::RED;
  1224. node = node->parent_->parent_;
  1225. } else {
  1226. if (node == node->parent_->left_) {
  1227. node = node->parent_;
  1228. rightRotate(root, node);
  1229. }
  1230. node->parent_->color_ = RBNode<T>::BLACK;
  1231. node->parent_->parent_->color_ = RBNode<T>::RED;
  1232. leftRotate(root, node->parent_->parent_);
  1233. }
  1234. }
  1235. }
  1236. (*root)->color_ = RBNode<T>::BLACK;
  1237. }
  1238. template <typename T>
  1239. RBNode<T>*
  1240. RBTree<T>::leftRotate(RBNode<T>** root, RBNode<T>* node) {
  1241. RBNode<T>* right = node->right_;
  1242. node->right_ = right->left_;
  1243. if (right->left_ != NULLNODE)
  1244. right->left_->parent_ = node;
  1245. right->parent_ = node->parent_;
  1246. if (node->parent_ != NULLNODE) {
  1247. if (node == node->parent_->left_) {
  1248. node->parent_->left_ = right;
  1249. } else {
  1250. node->parent_->right_ = right;
  1251. }
  1252. } else {
  1253. *root = right;
  1254. }
  1255. right->left_ = node;
  1256. node->parent_ = right;
  1257. return (node);
  1258. }
  1259. template <typename T>
  1260. RBNode<T>*
  1261. RBTree<T>::rightRotate(RBNode<T>** root, RBNode<T>* node) {
  1262. RBNode<T>* left = node->left_;
  1263. node->left_ = left->right_;
  1264. if (left->right_ != NULLNODE)
  1265. left->right_->parent_ = node;
  1266. left->parent_ = node->parent_;
  1267. if (node->parent_ != NULLNODE) {
  1268. if (node == node->parent_->right_) {
  1269. node->parent_->right_ = left;
  1270. } else {
  1271. node->parent_->left_ = left;
  1272. }
  1273. } else {
  1274. *root = left;
  1275. }
  1276. left->right_ = node;
  1277. node->parent_ = left;
  1278. return (node);
  1279. }
  1280. template <typename T>
  1281. void
  1282. RBTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  1283. indent(os, depth);
  1284. os << "tree has " << node_count_ << " node(s)\n";
  1285. dumpTreeHelper(os, root_, depth);
  1286. }
  1287. template <typename T>
  1288. void
  1289. RBTree<T>::dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  1290. unsigned int depth) const
  1291. {
  1292. if (node == NULLNODE) {
  1293. indent(os, depth);
  1294. os << "NULL\n";
  1295. return;
  1296. }
  1297. indent(os, depth);
  1298. os << node->name_.toText() << " ("
  1299. << ((node->color_ == RBNode<T>::BLACK) ? "black" : "red") << ")";
  1300. os << ((node->isEmpty()) ? "[invisible] \n" : "\n");
  1301. if (node->down_ != NULLNODE) {
  1302. indent(os, depth + 1);
  1303. os << "begin down from " << node->name_.toText() << "\n";
  1304. dumpTreeHelper(os, node->down_, depth + 1);
  1305. indent(os, depth + 1);
  1306. os << "end down from " << node->name_.toText() << "\n";
  1307. }
  1308. dumpTreeHelper(os, node->left_, depth + 1);
  1309. dumpTreeHelper(os, node->right_, depth + 1);
  1310. }
  1311. template <typename T>
  1312. void
  1313. RBTree<T>::indent(std::ostream& os, unsigned int depth) {
  1314. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1315. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1316. }
  1317. }
  1318. }
  1319. #endif // _RBTREE_H
  1320. // Local Variables:
  1321. // mode: c++
  1322. // End: