rbtree.h 38 KB

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