rbtree.h 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994
  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 <util/memory_segment.h>
  25. #include <dns/name.h>
  26. #include <dns/labelsequence.h>
  27. #include <boost/utility.hpp>
  28. #include <boost/shared_ptr.hpp>
  29. #include <boost/interprocess/offset_ptr.hpp>
  30. #include <boost/static_assert.hpp>
  31. #include <ostream>
  32. #include <algorithm>
  33. #include <cassert>
  34. namespace isc {
  35. namespace datasrc {
  36. /// Forward declare RBTree class here is convinent for following friend
  37. /// class declare inside RBNode and RBTreeNodeChain
  38. template <typename T>
  39. class RBTree;
  40. /// \brief \c RBNode is used by RBTree to store any data related to one domain
  41. /// name.
  42. ///
  43. /// This is meant to be used only from RBTree. It is meaningless to inherit it
  44. /// or create instances of it from elsewhere. For that reason, the constructor
  45. /// (and the allocator, see below) is private.
  46. ///
  47. /// It serves three roles. One is to keep structure of the \c RBTree as a
  48. /// red-black tree. For that purpose, it has left, right and parent pointers
  49. /// and color member. These are private and accessed only from within the tree.
  50. ///
  51. /// The second one is to store data for one domain name. The data related
  52. /// functions can be used to access and set the data.
  53. ///
  54. /// The third role is to keep the hierarchy of domains. The down pointer
  55. /// points to a subtree of subdomains. The parent pointer of a subtree's
  56. /// root node points to the parent leaf of the upper tree.
  57. ///
  58. /// One special kind of node is non-terminal node. It has subdomains with
  59. /// RRsets, but doesn't have any RRsets itself.
  60. ///
  61. /// In order to keep memory footprint as small as possible, the node data
  62. /// are heavily packed. Specifically, some internal node properties (such as
  63. /// the node color) are encoded as part of "flags", some of the flag bits
  64. /// can also be set by the user application. Each node is associated with
  65. /// a sequence of domain name labels, which is essentially the search/insert
  66. /// key for the node (see also the description of RBTree). This is encoded
  67. /// as opaque binary immediately following the main node object. The size
  68. /// of the allocated space for the labels data is encoded by borrowing some
  69. /// bits of the "flags" field.
  70. template <typename T>
  71. class RBNode : public boost::noncopyable {
  72. private:
  73. /// The RBNode is meant for use from within RBTree, so it has access to
  74. /// it.
  75. friend class RBTree<T>;
  76. /// \brief Just a type alias
  77. ///
  78. /// We are going to use a lot of these offset pointers here and they
  79. /// have a long name.
  80. typedef boost::interprocess::offset_ptr<RBNode<T> > RBNodePtr;
  81. /// \name Constructors
  82. ///
  83. /// \note The existence of a RBNode without a RBTree is meaningless.
  84. /// Therefore the constructors are private.
  85. //@{
  86. /// \brief Constructor from normal nodes.
  87. RBNode(size_t labels_capacity);
  88. /// \brief Destructor
  89. ~RBNode();
  90. //@}
  91. /// \brief Accessor to the memory region for node labels.
  92. ///
  93. /// The only valid usage of the returned pointer is to pass it to the
  94. /// corresponding constructor of \c dns::LabelSequence.
  95. const void* getLabelsData() const { return (this + 1); }
  96. /// \brief Accessor to the memory region for node labels, mutable version.
  97. ///
  98. /// The only valid usage of the returned pointer is to pass it to
  99. /// \c LabelSequence::serialize() with the node's labels_capacity_ member
  100. /// (which should be sufficiently large for the \c LabelSequence in that
  101. /// context).
  102. void* getLabelsData() { return (this + 1); }
  103. /// \brief Allocate and construct \c RBNode
  104. ///
  105. /// This static method allocates memory for a new \c RBNode object
  106. /// from the given memory segment, constructs the object, and returns
  107. /// a pointer to it.
  108. ///
  109. /// \throw std::bad_alloc Memory allocation fails.
  110. ///
  111. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  112. /// \c RBNode is allocated.
  113. static RBNode<T>* create(util::MemorySegment& mem_sgmt,
  114. const dns::LabelSequence& labels)
  115. {
  116. const size_t labels_len = labels.getSerializedLength();
  117. void* p = mem_sgmt.allocate(sizeof(RBNode<T>) + labels_len);
  118. RBNode<T>* node = new(p) RBNode<T>(labels_len);
  119. labels.serialize(node->getLabelsData(), labels_len);
  120. return (node);
  121. }
  122. /// \brief Destruct and deallocate \c RBNode
  123. ///
  124. /// \throw none
  125. ///
  126. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  127. /// \c rbnode.
  128. /// \param rbnode A non NULL pointer to a valid \c RBNode object
  129. /// that was originally created by the \c create() method (the behavior
  130. /// is undefined if this condition isn't met).
  131. static void destroy(util::MemorySegment& mem_sgmt, RBNode<T>* rbnode) {
  132. const size_t labels_capacity = rbnode->labels_capacity_;
  133. rbnode->~RBNode<T>();
  134. mem_sgmt.deallocate(rbnode, sizeof(RBNode<T>) + labels_capacity);
  135. }
  136. /// \brief Reset node's label sequence to a new one.
  137. ///
  138. /// The new labels must be a sub sequence of the current label sequence;
  139. /// otherwise the serialize() method will throw an exception.
  140. void resetLabels(const dns::LabelSequence& labels) {
  141. labels.serialize(getLabelsData(), labels_capacity_);
  142. }
  143. public:
  144. /// \brief Alias for shared pointer to the data.
  145. typedef boost::shared_ptr<T> NodeDataPtr;
  146. /// Node flags.
  147. ///
  148. /// Each flag value defines a non default property for a specific node.
  149. /// These are defined as bitmask type values for the convenience of
  150. /// internal implementation, but applications are expected to use
  151. /// each flag separately via the enum definitions.
  152. ///
  153. /// All (settable) flags are off by default; they must be explicitly
  154. /// set to on by the \c setFlag() method.
  155. enum Flags {
  156. FLAG_CALLBACK = 1, ///< Callback enabled. See \ref callback
  157. FLAG_RED = 2, ///< Node color; 1 if node is red, 0 if node is black.
  158. FLAG_SUBTREE_ROOT = 4, ///< Set if the node is the root of a subtree
  159. FLAG_USER1 = 0x400000U, ///< Application specific flag
  160. FLAG_USER2 = 0x200000U, ///< Application specific flag
  161. FLAG_USER3 = 0x100000U, ///< Application specific flag
  162. FLAG_MAX = 0x400000U // for integrity check
  163. };
  164. private:
  165. // Some flag values are expected to be used for internal purposes
  166. // (e.g., representing the node color) in future versions, so we
  167. // limit the settable flags via the \c setFlag() method to those
  168. // explicitly defined in \c Flags. This constant represents all
  169. // such flags.
  170. static const uint32_t SETTABLE_FLAGS = (FLAG_CALLBACK | FLAG_USER1 |
  171. FLAG_USER2 | FLAG_USER3);
  172. public:
  173. /// \name Getter functions.
  174. //@{
  175. /// \brief Return the name of current node.
  176. ///
  177. /// It's relative to its containing node.
  178. ///
  179. /// To get the absolute name of one node, the node path from the top node
  180. /// to current node has to be recorded.
  181. ///
  182. /// \note We should eventually deprecate this method and revise all its
  183. /// usage with \c getLabels(). At this point the only user of this method
  184. /// is getAbsoluteName()::getAbsoluteName(), which would have to be revised
  185. /// using \c LabelSequence. Until then we keep this interface as a
  186. /// simplest form of wrapper; it's not efficient, but should be replaced
  187. /// before we need to worry about that.
  188. const isc::dns::Name getName() const {
  189. return (dns::Name(dns::LabelSequence(getLabelsData()).toText()));
  190. }
  191. /// \brief Return the label sequence of the node.
  192. ///
  193. /// This method returns the label sequence corresponding to this node
  194. /// in the form of \c dns::LabelSequence object. Any modification to
  195. /// the tree can invalidate the returned \c LabelSequence object or copy
  196. /// of it; in general, it's expected to be used in a very limited scope.
  197. dns::LabelSequence getLabels() const {
  198. return (dns::LabelSequence(getLabelsData()));
  199. }
  200. /// \brief Return the absolute label sequence of the node.
  201. ///
  202. /// This method returns the label sequence corresponding to the full
  203. /// name of the node; i.e. the entire name as it appears in the zone.
  204. ///
  205. /// It takes the (partial) name of the node itself, and extends it
  206. /// with all upper nodes.
  207. ///
  208. /// \note Care must be taken with the buffer that is used here; this
  209. /// method overwrites its data, so it should not be associated with
  210. /// any other LabelSequence during the lifetime of the LabelSequence
  211. /// returned by this method. See LabelSequence::extend(), which is used
  212. /// by this method.
  213. ///
  214. /// \param buf A data buffer where the label sequence will be built.
  215. /// The data in this buffer will be overwritten by this call.
  216. /// \return A LabelSequence with the absolute name of this node.
  217. isc::dns::LabelSequence getAbsoluteLabels(
  218. uint8_t buf[isc::dns::LabelSequence::MAX_SERIALIZED_LENGTH]) const;
  219. /// \brief Return the data stored in this node.
  220. ///
  221. /// You should not delete the data, it is handled by shared pointers.
  222. NodeDataPtr& getData() { return (data_); }
  223. /// \brief Return the data stored in this node.
  224. const NodeDataPtr& getData() const { return (data_); }
  225. /// \brief return whether the node has related data.
  226. ///
  227. /// There can be empty nodes inside the RBTree. They are usually the
  228. /// non-terminal domains, but it is possible (yet probably meaningless)
  229. /// empty nodes anywhere.
  230. bool isEmpty() const { return (data_.get() == NULL); }
  231. //@}
  232. /// \name Setter functions.
  233. //@{
  234. /// \brief Set the data stored in the node.
  235. void setData(const NodeDataPtr& data) { data_ = data; }
  236. //@}
  237. /// \name Node flag manipulation methods
  238. //@{
  239. /// Get the status of a node flag.
  240. ///
  241. /// This method returns whether the given node flag is set (enabled)
  242. /// on the node. The \c flag parameter is expected to be one of the
  243. /// defined \c Flags constants. For simplicity, the method interface
  244. /// does not prohibit passing an undefined flag or combined flags, but
  245. /// the return value in such a case will be meaningless for the caller
  246. /// (an application would have to use an ugly cast for such an unintended
  247. /// form of call, which will hopefully avoid accidental misuse).
  248. ///
  249. /// \exception None
  250. /// \param flag The flag to be tested.
  251. /// \return \c true if the \c flag is set; \c false otherwise.
  252. bool getFlag(Flags flag) const {
  253. return ((flags_ & flag) != 0);
  254. }
  255. /// Set or clear a node flag.
  256. ///
  257. /// This method changes the status of the specified node flag to either
  258. /// "on" (enabled) or "off" (disabled). The new status is specified by
  259. /// the \c on parameter.
  260. /// Like the \c getFlag() method, \c flag is expected to be one of the
  261. /// defined \c Flags constants. If an undefined or unsettable flag is
  262. /// specified, \c isc::InvalidParameter exception will be thrown.
  263. ///
  264. /// \exception isc::InvalidParameter Unsettable flag is specified
  265. /// \exception None otherwise
  266. /// \param flag The node flag to be changed.
  267. /// \param on If \c true, set the flag to on; otherwise set it to off.
  268. void setFlag(Flags flag, bool on = true) {
  269. if ((flag & ~SETTABLE_FLAGS) != 0) {
  270. isc_throw(isc::InvalidParameter,
  271. "Unsettable RBTree flag is being set");
  272. }
  273. if (on) {
  274. flags_ |= flag;
  275. } else {
  276. flags_ &= ~flag;
  277. }
  278. }
  279. //@}
  280. private:
  281. /// \name Callback related methods
  282. ///
  283. /// See the description of \c RBTree<T>::find() at \ref callback
  284. /// about callbacks.
  285. ///
  286. /// These methods never throw an exception.
  287. //@{
  288. /// Return if callback is enabled at the node.
  289. //@}
  290. /// \brief Define rbnode color
  291. enum RBNodeColor {BLACK, RED};
  292. /// \brief Returns the color of this node
  293. RBNodeColor getColor() const {
  294. if ((flags_ & FLAG_RED) != 0) {
  295. return (RED);
  296. } else {
  297. return (BLACK);
  298. }
  299. }
  300. /// \brief Sets the color of this node
  301. void setColor(const RBNodeColor color) {
  302. if (color == RED) {
  303. flags_ |= FLAG_RED;
  304. } else {
  305. flags_ &= ~FLAG_RED;
  306. }
  307. }
  308. void setSubTreeRoot(bool root) {
  309. if (root) {
  310. flags_ |= FLAG_SUBTREE_ROOT;
  311. } else {
  312. flags_ &= ~FLAG_SUBTREE_ROOT;
  313. }
  314. }
  315. bool isSubTreeRoot() const {
  316. return ((flags_ & FLAG_SUBTREE_ROOT) != 0);
  317. }
  318. public:
  319. /// \brief returns the parent of the root of its subtree
  320. ///
  321. /// This method takes a node and returns the parent of the root of
  322. /// its subtree (i.e, it returns the node's immediate ancestor in
  323. /// the tree-of-tree hierarchy). If the node is at the top level
  324. /// (which should be absolute), it will return \c NULL.
  325. ///
  326. /// This method never throws an exception.
  327. const RBNode<T>* getUpperNode() const;
  328. private:
  329. /// \brief return the next node which is bigger than current node
  330. /// in the same subtree
  331. ///
  332. /// The next successor for this node is the next bigger node in terms of
  333. /// the DNSSEC order relation within the same single subtree.
  334. /// Note that it may NOT be the next bigger node in the entire RBTree;
  335. /// RBTree is a tree in tree, and the real next node may reside in
  336. /// an upper or lower subtree of the subtree where this node belongs.
  337. /// For example, if this node has a sub domain, the real next node is
  338. /// the smallest node in the sub domain tree.
  339. ///
  340. /// If this node is the biggest node within the subtree, this method
  341. /// returns \c NULL.
  342. ///
  343. /// This method never throws an exception.
  344. const RBNode<T>* successor() const;
  345. /// \brief return the next node which is smaller than current node
  346. /// in the same subtree
  347. ///
  348. /// The predecessor for this node is the next smaller node in terms of
  349. /// the DNSSEC order relation within the same single subtree.
  350. /// Note that it may NOT be the next smaller node in the entire RBTree;
  351. /// RBTree is a tree in tree, and the real next node may reside in
  352. /// an upper or lower subtree of the subtree where this node belongs.
  353. /// For example, if the predecessor node has a sub domain, the real next
  354. /// node is the largest node in the sub domain tree.
  355. ///
  356. /// If this node is the smallest node within the subtree, this method
  357. /// returns \c NULL.
  358. ///
  359. /// This method never throws an exception.
  360. const RBNode<T>* predecessor() const;
  361. /// \brief private shared implementation of successor and predecessor
  362. ///
  363. /// As the two mentioned functions are merely mirror images of each other,
  364. /// it makes little sense to keep both versions. So this is the body of the
  365. /// functions and we call it with the correct pointers.
  366. ///
  367. /// Not to be called directly, not even by friends.
  368. ///
  369. /// The overhead of the member pointers should be optimised out, as this
  370. /// will probably get completely inlined into predecessor and successor
  371. /// methods.
  372. const RBNode<T>*
  373. abstractSuccessor(typename RBNode<T>::RBNodePtr RBNode<T>::*left,
  374. typename RBNode<T>::RBNodePtr RBNode<T>::*right)
  375. const;
  376. /// \name Data to maintain the rbtree structure.
  377. ///
  378. /// We keep them as offset pointers. This is part of a future plan, when we
  379. /// want to share the image of the tree between multiple processes.
  380. /// However, whenever we have a chance, we switch to bare pointers during
  381. /// the processing. The pointers on stack are never shared and the offset
  382. /// pointers have non-trivial performance impact.
  383. //@{
  384. RBNodePtr parent_;
  385. /// \brief Access the parent_ as bare pointer.
  386. RBNode<T>* getParent() {
  387. return (parent_.get());
  388. }
  389. /// \brief Access the parent_ as bare pointer, const.
  390. const RBNode<T>* getParent() const {
  391. return (parent_.get());
  392. }
  393. RBNodePtr left_;
  394. /// \brief Access the left_ as bare pointer.
  395. RBNode<T>* getLeft() {
  396. return (left_.get());
  397. }
  398. /// \brief Access the left_ as bare pointer, const.
  399. const RBNode<T>* getLeft() const {
  400. return (left_.get());
  401. }
  402. RBNodePtr right_;
  403. /// \brief Access the right_ as bare pointer.
  404. RBNode<T>* getRight() {
  405. return (right_.get());
  406. }
  407. /// \brief Access the right_ as bare pointer, const.
  408. const RBNode<T>* getRight() const {
  409. return (right_.get());
  410. }
  411. //@}
  412. /// \brief Data stored here.
  413. NodeDataPtr data_;
  414. /// \brief The subdomain tree.
  415. ///
  416. /// This points to the root node of trees of subdomains of this domain.
  417. ///
  418. /// \par Adding down pointer to \c RBNode has two purposes:
  419. /// \li Accelerate the search process, with sub domain tree, it splits the
  420. /// big flat tree into several hierarchy trees.
  421. /// \li It saves memory usage as it allows storing only relative names,
  422. /// avoiding storage of the same domain labels multiple times.
  423. RBNodePtr down_;
  424. /// \brief Access the down_ as bare pointer.
  425. RBNode<T>* getDown() {
  426. return (down_.get());
  427. }
  428. /// \brief Access the down_ as bare pointer, const.
  429. const RBNode<T>* getDown() const {
  430. return (down_.get());
  431. }
  432. /// \brief Internal or user-configurable flags of node's properties.
  433. ///
  434. /// See the \c Flags enum for available flags.
  435. ///
  436. /// For memory efficiency reasons, we only use a subset of the 32-bit
  437. /// space, and use the rest to store the allocated size for the node's
  438. /// label sequence data.
  439. uint32_t flags_ : 23; // largest flag being 0x400000
  440. BOOST_STATIC_ASSERT((1 << 23) > FLAG_MAX); // assumption check
  441. const uint32_t labels_capacity_ : 9; // size for labelseq; range is 0..511
  442. // Make sure the reserved space for labels_capacity_ is sufficiently
  443. // large. In effect, we use the knowledge of the implementation of the
  444. // serialization, but we still only use its public interface, and the
  445. // public interface of this class doesn't rely on this assumption.
  446. // So we can change this implementation without affecting its users if
  447. // a future change to LabelSequence breaks this assumption.
  448. BOOST_STATIC_ASSERT((1 << 9) > dns::LabelSequence::MAX_SERIALIZED_LENGTH);
  449. };
  450. template <typename T>
  451. RBNode<T>::RBNode(size_t labels_capacity) :
  452. parent_(NULL),
  453. left_(NULL),
  454. right_(NULL),
  455. down_(NULL),
  456. flags_(FLAG_RED | FLAG_SUBTREE_ROOT),
  457. labels_capacity_(labels_capacity)
  458. {
  459. }
  460. template <typename T>
  461. RBNode<T>::~RBNode() {
  462. }
  463. template <typename T>
  464. const RBNode<T>*
  465. RBNode<T>::getUpperNode() const {
  466. const RBNode<T>* current = this;
  467. // current would never be equal to NULL here (in a correct tree
  468. // implementation)
  469. while (!current->isSubTreeRoot()) {
  470. current = current->getParent();
  471. }
  472. return (current->getParent());
  473. }
  474. template <typename T>
  475. isc::dns::LabelSequence
  476. RBNode<T>::getAbsoluteLabels(
  477. uint8_t buf[isc::dns::LabelSequence::MAX_SERIALIZED_LENGTH]) const
  478. {
  479. isc::dns::LabelSequence result(getLabels(), buf);
  480. const RBNode<T>* upper = getUpperNode();
  481. while (upper != NULL) {
  482. result.extend(upper->getLabels(), buf);
  483. upper = upper->getUpperNode();
  484. }
  485. return (result);
  486. }
  487. template <typename T>
  488. const RBNode<T>*
  489. RBNode<T>::abstractSuccessor(typename RBNode<T>::RBNodePtr RBNode<T>::*left,
  490. typename RBNode<T>::RBNodePtr RBNode<T>::*right)
  491. const
  492. {
  493. // This function is written as a successor. It becomes predecessor if
  494. // the left and right pointers are swapped. So in case of predecessor,
  495. // the left pointer points to right and vice versa. Don't get confused
  496. // by the idea, just imagine the pointers look into a mirror.
  497. const RBNode<T>* current = this;
  498. // If it has right node, the successor is the left-most node of the right
  499. // subtree.
  500. if ((current->*right).get() != NULL) {
  501. current = (current->*right).get();
  502. const RBNode<T>* left_n;
  503. while ((left_n = (current->*left).get()) != NULL) {
  504. current = left_n;
  505. }
  506. return (current);
  507. }
  508. // Otherwise go up until we find the first left branch on our path to
  509. // root. If found, the parent of the branch is the successor.
  510. // Otherwise, we return the null node
  511. const RBNode<T>* parent = current->getParent();
  512. while ((!current->isSubTreeRoot()) &&
  513. (current == (parent->*right).get())) {
  514. current = parent;
  515. parent = parent->getParent();
  516. }
  517. if (!current->isSubTreeRoot()) {
  518. return (parent);
  519. } else {
  520. return (NULL);
  521. }
  522. }
  523. template <typename T>
  524. const RBNode<T>*
  525. RBNode<T>::successor() const {
  526. return (abstractSuccessor(&RBNode<T>::left_, &RBNode<T>::right_));
  527. }
  528. template <typename T>
  529. const RBNode<T>*
  530. RBNode<T>::predecessor() const {
  531. // Swap the left and right pointers for the abstractSuccessor
  532. return (abstractSuccessor(&RBNode<T>::right_, &RBNode<T>::left_));
  533. }
  534. /// \brief RBTreeNodeChain stores detailed information of \c RBTree::find()
  535. /// result.
  536. ///
  537. /// - The \c RBNode that was last compared with the search name, and
  538. /// the comparison result at that point in the form of
  539. /// \c isc::dns::NameComparisonResult.
  540. /// - A sequence of nodes that forms a path to the found node.
  541. ///
  542. /// The comparison result can be used to handle some rare cases such as
  543. /// empty node processing.
  544. /// The node sequence keeps track of the nodes to reach any given node from
  545. /// the root of RBTree.
  546. ///
  547. /// Currently, RBNode does not have "up" pointers in them (i.e., back pointers
  548. /// from the root of one level of tree of trees to the node in the parent
  549. /// tree whose down pointer points to that root node) for memory usage
  550. /// reasons, so there is no other way to find the path back to the root from
  551. /// any given RBNode.
  552. ///
  553. /// \note This design may change in future versions. In particular, it's
  554. /// quite likely we want to have that pointer if we want to optimize name
  555. /// compression by exploiting the structure of the zone. If and when that
  556. /// happens we should also revisit the need for the chaining.
  557. /// Also, the class name may not be appropriate now that it contains other
  558. /// information than a node "chain", and the chain itself may even be
  559. /// deprecated. Something like "RBTreeFindContext" may be a better name.
  560. /// This point should be revisited later.
  561. ///
  562. /// RBTreeNodeChain is constructed and manipulated only inside the \c RBTree
  563. /// class.
  564. /// \c RBTree uses it as an inner data structure to iterate over the whole
  565. /// RBTree.
  566. /// This is the reason why manipulation methods such as \c push() and \c pop()
  567. /// are private (and not shown in the doxygen document).
  568. template <typename T>
  569. class RBTreeNodeChain {
  570. /// RBTreeNodeChain is initialized by RBTree, only RBTree has
  571. /// knowledge to manipulate it.
  572. friend class RBTree<T>;
  573. public:
  574. /// \name Constructors and Assignment Operator.
  575. ///
  576. /// \note The copy constructor and the assignment operator are
  577. /// intentionally defined as private, making this class non copyable.
  578. /// This may have to be changed in a future version with newer need.
  579. /// For now we explicitly disable copy to avoid accidental copy happens
  580. /// unintentionally.
  581. //{@
  582. /// The default constructor.
  583. ///
  584. /// \exception None
  585. RBTreeNodeChain() : node_count_(0), last_compared_(NULL),
  586. // XXX: meaningless initial values:
  587. last_comparison_(0, 0,
  588. isc::dns::NameComparisonResult::EQUAL)
  589. {}
  590. private:
  591. RBTreeNodeChain(const RBTreeNodeChain<T>&);
  592. RBTreeNodeChain<T>& operator=(const RBTreeNodeChain<T>&);
  593. //@}
  594. public:
  595. /// Clear the state of the chain.
  596. ///
  597. /// This method re-initializes the internal state of the chain so that
  598. /// it can be reused for subsequent operations.
  599. ///
  600. /// \exception None
  601. void clear() {
  602. node_count_ = 0;
  603. last_compared_ = NULL;
  604. }
  605. /// Return the \c RBNode that was last compared in \c RBTree::find().
  606. ///
  607. /// If this chain has been passed to \c RBTree::find() and there has
  608. /// been name comparison against the search name, the last compared
  609. /// \c RBNode is recorded within the chain. This method returns that
  610. /// node.
  611. /// If \c RBTree::find() hasn't been called with this chain or name
  612. /// comparison hasn't taken place (which is possible if the tree is empty),
  613. /// this method returns \c NULL.
  614. ///
  615. /// \exception None
  616. const RBNode<T>* getLastComparedNode() const {
  617. return (last_compared_);
  618. }
  619. /// Return the result of last name comparison in \c RBTree::find().
  620. ///
  621. /// Like \c getLastComparedNode(), \c RBTree::find() records the result
  622. /// of the last name comparison in the chain. This method returns the
  623. /// result.
  624. /// The return value of this method is only meaningful when comparison
  625. /// has taken place, i.e, when \c getLastComparedNode() would return a
  626. /// non \c NULL value.
  627. ///
  628. /// \exception None
  629. const isc::dns::NameComparisonResult& getLastComparisonResult() const {
  630. return (last_comparison_);
  631. }
  632. /// \brief Return the number of levels stored in the chain.
  633. ///
  634. /// It's equal to the number of nodes in the chain; for an empty
  635. /// chain, 0 will be returned.
  636. ///
  637. /// \exception None
  638. unsigned int getLevelCount() const { return (node_count_); }
  639. /// \brief return the absolute name for the node which this
  640. /// \c RBTreeNodeChain currently refers to.
  641. ///
  642. /// The chain must not be empty.
  643. ///
  644. /// \exception isc::BadValue the chain is empty.
  645. /// \exception std::bad_alloc memory allocation for the new name fails.
  646. isc::dns::Name getAbsoluteName() const {
  647. if (isEmpty()) {
  648. isc_throw(isc::BadValue,
  649. "RBTreeNodeChain::getAbsoluteName is called on an empty "
  650. "chain");
  651. }
  652. const RBNode<T>* top_node = top();
  653. isc::dns::Name absolute_name = top_node->getName();
  654. int node_count = node_count_ - 1;
  655. while (node_count > 0) {
  656. top_node = nodes_[node_count - 1];
  657. absolute_name = absolute_name.concatenate(top_node->getName());
  658. --node_count;
  659. }
  660. return (absolute_name);
  661. }
  662. private:
  663. // the following private functions check invariants about the internal
  664. // state using assert() instead of exception. The state of a chain
  665. // can only be modified by operations within this file, so if any of the
  666. // assumptions fails it means an internal bug.
  667. /// \brief return whether node chain has node in it.
  668. ///
  669. /// \exception None
  670. bool isEmpty() const { return (node_count_ == 0); }
  671. /// \brief return the top node for the node chain
  672. ///
  673. /// RBTreeNodeChain store all the nodes along top node to
  674. /// root node of RBTree
  675. ///
  676. /// \exception None
  677. const RBNode<T>* top() const {
  678. assert(!isEmpty());
  679. return (nodes_[node_count_ - 1]);
  680. }
  681. /// \brief pop the top node from the node chain
  682. ///
  683. /// After pop, up/super node of original top node will be
  684. /// the top node
  685. ///
  686. /// \exception None
  687. void pop() {
  688. assert(!isEmpty());
  689. --node_count_;
  690. }
  691. /// \brief add the node into the node chain
  692. ///
  693. /// If the node chain isn't empty, the node should be
  694. /// the sub domain of the original top node in node chain
  695. /// otherwise the node should be the root node of RBTree.
  696. ///
  697. /// \exception None
  698. void push(const RBNode<T>* node) {
  699. assert(node_count_ < RBT_MAX_LEVEL);
  700. nodes_[node_count_++] = node;
  701. }
  702. private:
  703. // The max label count for one domain name is Name::MAX_LABELS (128).
  704. // Since each node in rbtree stores at least one label, it's also equal
  705. // to the possible maximum level.
  706. const static int RBT_MAX_LEVEL = isc::dns::Name::MAX_LABELS;
  707. int node_count_;
  708. const RBNode<T>* nodes_[RBT_MAX_LEVEL];
  709. const RBNode<T>* last_compared_;
  710. isc::dns::NameComparisonResult last_comparison_;
  711. };
  712. // note: the following class description is documented using multiline comments
  713. // because the verbatim diagram contain a backslash, which could be interpreted
  714. // as escape of newline in singleline comment.
  715. /**
  716. * \brief \c RBTree class represents all the domains with the same suffix.
  717. * It can be used to store the domains in one zone, for example.
  718. *
  719. * RBTree is a generic map from domain names to any kind of data. Internally,
  720. * it uses a red-black tree. However, it isn't one tree containing everything.
  721. * Subdomains are trees, so this structure is recursive - trees inside trees.
  722. * But, from the interface point of view, it is opaque data structure.
  723. *
  724. * \c RBTree splits the domain space into hierarchy red black trees; nodes
  725. * in one tree has the same base name. The benefit of this struct is that:
  726. * - Enhances the query performace compared with one big flat red black tree.
  727. * - Decreases the memory footprint, as it doesn't store the suffix labels
  728. * multiple times.
  729. *
  730. * Depending on different usage, rbtree will support different search policies.
  731. * Whether to return an empty node to end user is one policy among them.
  732. * The default policy is to NOT return an empty node to end user;
  733. * to change the behavior, specify \c true for the constructor parameter
  734. * \c returnEmptyNode.
  735. * \note The search policy only affects the \c find() behavior of RBTree.
  736. * When inserting one name into RBTree, if the node with the name already
  737. * exists in the RBTree and it's an empty node which doesn't have any data,
  738. * the \c insert() method will still return \c ALREADYEXISTS regardless of
  739. * the search policy.
  740. *
  741. * \anchor diagram
  742. *
  743. * with the following names:
  744. * - a
  745. * - b
  746. * - c
  747. * - x.d.e.f
  748. * - z.d.e.f
  749. * - g.h
  750. * - o.w.y.d.e.f
  751. * - p.w.y.d.e.f
  752. * - q.w.y.d.e.f
  753. *
  754. * the tree will look like:
  755. * \verbatim
  756. .
  757. |
  758. b
  759. / \
  760. a d.e.f
  761. /|\
  762. c | g.h
  763. |
  764. w.y
  765. /|\
  766. x | z
  767. |
  768. p
  769. / \
  770. o q
  771. \endverbatim
  772. * \todo
  773. * - add remove interface
  774. */
  775. template <typename T>
  776. class RBTree : public boost::noncopyable {
  777. friend class RBNode<T>;
  778. public:
  779. /// \brief The return value for the \c find() and insert() methods
  780. enum Result {
  781. SUCCESS, ///< Insert was successful
  782. /// \brief The node returned from find mathes exactly the name given
  783. EXACTMATCH,
  784. PARTIALMATCH, ///< A superdomain node was found
  785. NOTFOUND, ///< Not even any superdomain was found
  786. /// \brief Returned by insert() if a node of the name already exists
  787. ALREADYEXISTS,
  788. };
  789. /// \brief Allocate and construct \c RBTree
  790. ///
  791. /// This static method allocates memory for a new \c RBTree object
  792. /// from the given memory segment, constructs the object, and returns
  793. /// a pointer to it.
  794. ///
  795. /// \throw std::bad_alloc Memory allocation fails.
  796. ///
  797. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  798. /// \c RBTree is allocated.
  799. static RBTree* create(util::MemorySegment& mem_sgmt,
  800. bool return_empty_node = false)
  801. {
  802. void* p = mem_sgmt.allocate(sizeof(RBTree<T>));
  803. return (new(p) RBTree<T>(return_empty_node));
  804. }
  805. /// \brief Destruct and deallocate \c RBTree
  806. ///
  807. /// This method also destroys and deallocates all nodes inserted to the
  808. /// tree.
  809. ///
  810. /// \note The memory segment (\c mem_sgmt) must be the same one that
  811. /// was originally used to allocate memory for the tree (and for all
  812. /// nodes inserted to the tree, due to the requirement of \c insert()),
  813. /// since the tree itself doesn't maintain a reference to the segment.
  814. /// This is not a robust interface, but since we plan to share the tree
  815. /// structure by multiple processes via shared memory or possibly allow
  816. /// the memory image to be dumped to a file for later reload, there
  817. /// doesn't seem to be an easy way to store such reference in the data
  818. /// itself. We should probably consider a wrapper interface that
  819. /// encapsulates the corresponding segment and always use it for any
  820. /// allocation/deallocation of tree related data (the tree itself, their
  821. /// nodes, and node data) to keep the usage as safe as possible.
  822. ///
  823. /// \throw none
  824. ///
  825. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  826. /// \c rbtree and for all nodes inserted to the tree.
  827. /// \param rbtree A non NULL pointer to a valid \c RBTree object
  828. /// that was originally created by the \c create() method (the behavior
  829. /// is undefined if this condition isn't met).
  830. static void destroy(util::MemorySegment& mem_sgmt, RBTree<T>* rbtree) {
  831. rbtree->deleteAllNodes(mem_sgmt);
  832. rbtree->~RBTree<T>();
  833. mem_sgmt.deallocate(rbtree, sizeof(RBTree<T>));
  834. }
  835. private:
  836. /// \name Constructor and Destructor
  837. //@{
  838. /// \brief The constructor.
  839. ///
  840. /// An object of this class is always expected to be created by the
  841. /// allocator (\c create()), so the constructor is hidden as private.
  842. ///
  843. /// It never throws an exception.
  844. explicit RBTree(bool returnEmptyNode = false);
  845. /// \brief The destructor.
  846. ///
  847. /// An object of this class is always expected to be destroyed explicitly
  848. /// by \c destroy(), so the constructor is hidden as private.
  849. ///
  850. /// \note RBTree is not intended to be inherited so the destructor
  851. /// is not virtual
  852. ~RBTree();
  853. //@}
  854. public:
  855. /// \name Find methods
  856. ///
  857. /// \brief Find the node that gives a longest match against the given name.
  858. ///
  859. /// \anchor find
  860. ///
  861. /// These methods search the RBTree for a node whose name is longest
  862. /// against name. The found node, if any, is returned via the node pointer.
  863. ///
  864. /// By default, nodes that don't have data (see RBNode::isEmpty) are
  865. /// ignored and the result can be NOTFOUND even if there's a node whose
  866. /// name matches. If the \c RBTree is constructed with its
  867. /// \c returnEmptyNode parameter being \c true, empty nodes will also
  868. /// be match candidates.
  869. ///
  870. /// \note Even when \c returnEmptyNode is \c true, not all empty nodes
  871. /// in terms of the DNS protocol may necessarily be found by this method.
  872. /// For example, in the \ref diagram shown in the class description,
  873. /// the name y.d.e.f is logically contained in the tree as part of the
  874. /// node w.y, but the \c find() variants cannot find the former for
  875. /// the search key of y.d.e.f, no matter how the \c RBTree is constructed.
  876. /// The caller of this method must use a different way to identify the
  877. /// hidden match when necessary.
  878. ///
  879. /// These methods involve operations on names that can throw an exception.
  880. /// If that happens the exception will be propagated to the caller.
  881. /// The callback function should generally not throw an exception, but
  882. /// if it throws, the exception will be propagated to the caller.
  883. ///
  884. /// The \c name parameter says what should be found. The node parameter
  885. /// is output-only, and in case of EXACTMATCH or PARTIALMATCH, it is set
  886. /// to a pointer to the found node.
  887. ///
  888. /// They return:
  889. /// - EXACTMATCH when a node with the same name as requested exists.
  890. /// - PARTIALMATCH when a node with the same name does not exist (or is
  891. /// empty), but there's a (nonempty) superdomain of the requested one.
  892. /// The superdomain with longest name is returned through the node
  893. /// parameter. Beware that if you store a zone in the tree, you may get
  894. /// PARTIALMATCH with zone apex when the given domain name is not there.
  895. /// You should not try to delegate into another zone in that case.
  896. /// - NOTFOUND if there's no node with the same name nor any superdomain
  897. /// of it. In that case, node parameter is left intact.
  898. //@{
  899. /// \brief Simple find.
  900. ///
  901. /// Acts as described in the \ref find section.
  902. Result find(const isc::dns::Name& name, RBNode<T>** node) const {
  903. RBTreeNodeChain<T> node_path;
  904. const isc::dns::LabelSequence ls(name);
  905. return (find<void*>(ls, node, node_path, NULL, NULL));
  906. }
  907. /// \brief Simple find returning immutable node.
  908. ///
  909. /// Acts as described in the \ref find section, but returns immutable node
  910. /// pointer.
  911. Result find(const isc::dns::Name& name, const RBNode<T>** node) const {
  912. RBTreeNodeChain<T> node_path;
  913. RBNode<T> *target_node = NULL;
  914. const isc::dns::LabelSequence ls(name);
  915. Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
  916. if (ret != NOTFOUND) {
  917. *node = target_node;
  918. }
  919. return (ret);
  920. }
  921. /// \brief Simple find, with node_path tracking
  922. ///
  923. /// Acts as described in the \ref find section.
  924. Result find(const isc::dns::Name& name, RBNode<T>** node,
  925. RBTreeNodeChain<T>& node_path) const
  926. {
  927. const isc::dns::LabelSequence ls(name);
  928. return (find<void*>(ls, node, node_path, NULL, NULL));
  929. }
  930. /// \brief Simple find returning immutable node, with node_path tracking
  931. ///
  932. /// Acts as described in the \ref find section, but returns immutable node
  933. /// pointer.
  934. Result find(const isc::dns::Name& name, const RBNode<T>** node,
  935. RBTreeNodeChain<T>& node_path) const
  936. {
  937. RBNode<T> *target_node = NULL;
  938. const isc::dns::LabelSequence ls(name);
  939. Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
  940. if (ret != NOTFOUND) {
  941. *node = target_node;
  942. }
  943. return (ret);
  944. }
  945. /// \brief Simple find returning immutable node.
  946. ///
  947. /// Acts as described in the \ref find section, but returns immutable
  948. /// node pointer.
  949. template <typename CBARG>
  950. Result find(const isc::dns::Name& name,
  951. const RBNode<T>** node,
  952. RBTreeNodeChain<T>& node_path,
  953. bool (*callback)(const RBNode<T>&, CBARG),
  954. CBARG callback_arg) const
  955. {
  956. RBNode<T>* target_node = NULL;
  957. const isc::dns::LabelSequence ls(name);
  958. Result ret = find(ls, &target_node, node_path, callback,
  959. callback_arg);
  960. if (ret != NOTFOUND) {
  961. *node = target_node;
  962. }
  963. return (ret);
  964. }
  965. /// \brief Find with callback and node chain
  966. /// \anchor callback
  967. ///
  968. /// This version of \c find() is specifically designed for the backend
  969. /// of the \c InMemoryZoneFinder class, and implements all necessary
  970. /// features for that purpose. Other applications shouldn't need these
  971. /// additional features, and should normally use the simpler versions.
  972. ///
  973. /// This version of \c find() calls the callback whenever traversing (on
  974. /// the way from root down the tree) a marked node on the way down through
  975. /// the domain namespace (see \c RBNode::FLAG_CALLBACK).
  976. ///
  977. /// Also, this version takes a \c LabelSequence object, not a \c Name
  978. /// object to be as efficient as possible; operations on the former
  979. /// needed for the search are generally much more efficient than those
  980. /// for the latter. Since \c Name objects are more commonly used
  981. /// in other parts of the implementation, other versions take a \c Name
  982. /// and convert it to \c LabelSequence. This conversion is cheap,
  983. /// while the other direction isn't, and since there would be cases
  984. /// where an implementation primarily handles \c LabelSequence objects
  985. /// as an efficient representation of names, it would make most sense
  986. /// to provide the interface that takes \c LabelSequence.
  987. ///
  988. /// If you return true from the callback, the search is stopped and a
  989. /// PARTIALMATCH is returned with the given node. Note that this node
  990. /// doesn't really need to be the one with longest possible match.
  991. ///
  992. /// The callback is not called for the node which matches exactly
  993. /// (EXACTMATCH is returned). This is typically the last node in the
  994. /// traversal during a successful search.
  995. ///
  996. /// This callback mechanism was designed with zone cut (delegation)
  997. /// processing in mind. The marked nodes would be the ones at delegation
  998. /// points. It is not expected that any other applications would need
  999. /// callbacks; they should use the versions of find without callbacks.
  1000. /// The callbacks are not general functors for the same reason - we don't
  1001. /// expect it to be needed.
  1002. ///
  1003. /// Another special feature of this version is the ability to record
  1004. /// more detailed information regarding the search result.
  1005. ///
  1006. /// This information will be returned via the \c node_path parameter,
  1007. /// which is an object of class \c RBTreeNodeChain.
  1008. /// The passed parameter must be empty.
  1009. ///
  1010. /// On success, the node sequence stored in \c node_path will contain all
  1011. /// the ancestor nodes from the found node towards the root.
  1012. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  1013. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  1014. /// chain will be o, w.y and d.e.f will be stored below it.
  1015. ///
  1016. /// This feature can be used to get the absolute name for a node;
  1017. /// to do so, we need to travel upside from the node toward the root,
  1018. /// concatenating all ancestor labels. A node chain can also be used to
  1019. /// find the next and previous nodes of a given node in the entire RBTree;
  1020. /// the \c nextNode() and \c previousNode() methods take a node
  1021. /// chain as a parameter.
  1022. ///
  1023. /// \exception isc::BadValue node_path is not empty.
  1024. ///
  1025. /// \param target_labels_orig Target to be found
  1026. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  1027. /// it will store a pointer to the matching node
  1028. /// \param node_path Other search details will be stored (see the
  1029. /// description)
  1030. /// \param callback If non- \c NULL, a call back function to be called
  1031. /// at marked nodes (see the description).
  1032. /// \param callback_arg A caller supplied argument to be passed to
  1033. /// \c callback.
  1034. ///
  1035. /// \return As in the description, but in case of callback returning
  1036. /// \c true, it returns immediately with the current node.
  1037. template <typename CBARG>
  1038. Result find(const isc::dns::LabelSequence& target_labels_orig,
  1039. RBNode<T>** node,
  1040. RBTreeNodeChain<T>& node_path,
  1041. bool (*callback)(const RBNode<T>&, CBARG),
  1042. CBARG callback_arg) const;
  1043. /// \brief Simple find returning immutable node.
  1044. ///
  1045. /// Acts as described in the \ref find section, but returns immutable
  1046. /// node pointer.
  1047. template <typename CBARG>
  1048. Result find(const isc::dns::LabelSequence& target_labels,
  1049. const RBNode<T>** node,
  1050. RBTreeNodeChain<T>& node_path,
  1051. bool (*callback)(const RBNode<T>&, CBARG),
  1052. CBARG callback_arg) const
  1053. {
  1054. RBNode<T>* target_node = NULL;
  1055. Result ret = find(target_labels, &target_node, node_path,
  1056. callback, callback_arg);
  1057. if (ret != NOTFOUND) {
  1058. *node = target_node;
  1059. }
  1060. return (ret);
  1061. }
  1062. //@}
  1063. /// \brief return the next bigger node in DNSSEC order from a given node
  1064. /// chain.
  1065. ///
  1066. /// This method identifies the next bigger node of the node currently
  1067. /// referenced in \c node_path and returns it.
  1068. /// This method also updates the passed \c node_path so that it will store
  1069. /// the path for the returned next node.
  1070. /// It will be convenient when we want to iterate over the all nodes
  1071. /// of \c RBTree; we can do this by calling this method repeatedly
  1072. /// starting from the root node.
  1073. ///
  1074. /// \note \c nextNode() will iterate over all the nodes in RBTree including
  1075. /// empty nodes. If empty node isn't desired, it's easy to add logic to
  1076. /// check return node and keep invoking \c nextNode() until the non-empty
  1077. /// node is retrieved.
  1078. ///
  1079. /// \exception isc::BadValue node_path is empty.
  1080. ///
  1081. /// \param node_path A node chain that stores all the nodes along the path
  1082. /// from root to node.
  1083. ///
  1084. /// \return An \c RBNode that is next bigger than \c node; if \c node is
  1085. /// the largest, \c NULL will be returned.
  1086. const RBNode<T>* nextNode(RBTreeNodeChain<T>& node_path) const;
  1087. /// \brief return the next smaller node in DNSSEC order from a node
  1088. /// searched by RBTree::find().
  1089. ///
  1090. /// This acts similarly to \c nextNode(), but it walks in the other
  1091. /// direction. But unlike \c nextNode(), this can start even if the
  1092. /// node requested by \c find() was not found. In that case, it will
  1093. /// identify the node that is previous to the queried name.
  1094. ///
  1095. /// \note \c previousNode() will iterate over all the nodes in RBTree
  1096. /// including empty nodes. If empty node isn't desired, it's easy to add
  1097. /// logic to check return node and keep invoking \c previousNode() until the
  1098. /// non-empty node is retrieved.
  1099. ///
  1100. /// \exception isc::BadValue node_path is empty.
  1101. ///
  1102. /// \param node_path A node chain that stores all the nodes along the path
  1103. /// from root to node and the result of \c find(). This will get modified.
  1104. /// You should not use the node_path again except for repetitive calls
  1105. /// of this method.
  1106. ///
  1107. /// \return An \c RBNode that is next smaller than \c node; if \c node is
  1108. /// the smallest, \c NULL will be returned.
  1109. const RBNode<T>* previousNode(RBTreeNodeChain<T>& node_path) const;
  1110. /// \brief Get the total number of nodes in the tree
  1111. ///
  1112. /// It includes nodes internally created as a result of adding a domain
  1113. /// name that is a subdomain of an existing node of the tree.
  1114. /// This function is mainly intended to be used for debugging.
  1115. int getNodeCount() const { return (node_count_); }
  1116. /// \name Debug function
  1117. //@{
  1118. /// \brief Print the nodes in the trees.
  1119. ///
  1120. /// \param os A \c std::ostream object to which the tree is printed.
  1121. /// \param depth A factor of the initial indentation. Each line
  1122. /// will begin with space character repeating <code>5 * depth</code>
  1123. /// times.
  1124. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  1125. /// \brief Print the nodes in the trees for processing with
  1126. /// Graphviz's dot.
  1127. ///
  1128. /// \param os A \c std::ostream object to which the tree is printed.
  1129. /// \param show_pointers Show node and parent pointers in the node
  1130. void dumpDot(std::ostream& os, bool show_pointers = false) const;
  1131. //@}
  1132. /// \name Modify functions
  1133. //@{
  1134. /// \brief Insert the domain name into the tree.
  1135. ///
  1136. /// It either finds an already existing node of the given name, or inserts
  1137. /// a new one if none exists yet. In any case, the \c inserted_node parameter
  1138. /// is set to point to that node. You can fill data into it or modify it.
  1139. /// So, if you don't know if a node exists or not and you need to modify
  1140. /// it, just call insert and act by the result.
  1141. ///
  1142. /// Please note that the tree can add some empty nodes by itself, so don't
  1143. /// assume that if you didn't insert a node of that name it doesn't exist.
  1144. ///
  1145. /// This method normally involves resource allocation. If it fails
  1146. /// the corresponding standard exception will be thrown.
  1147. ///
  1148. /// This method does not provide the strong exception guarantee in its
  1149. /// strict sense; if an exception is thrown in the middle of this
  1150. /// method, the internal structure may change. However, it should
  1151. /// still retain the same property as a mapping container before this
  1152. /// method is called. For example, the result of \c find() should be
  1153. /// the same. This method provides the weak exception guarantee in its
  1154. /// normal sense.
  1155. ///
  1156. /// \param mem_sgmt A \c MemorySegment object for allocating memory of
  1157. /// a new node to be inserted. Must be the same segment as that used
  1158. /// for creating the tree itself.
  1159. /// \param name The name to be inserted into the tree.
  1160. /// \param inserted_node This is an output parameter and is set to the
  1161. /// node.
  1162. ///
  1163. /// \return
  1164. /// - SUCCESS The node was added.
  1165. /// - ALREADYEXISTS There was already a node of that name, so it was not
  1166. /// added.
  1167. Result insert(util::MemorySegment& mem_sgmt, const isc::dns::Name& name,
  1168. RBNode<T>** inserted_node);
  1169. /// \brief Delete all tree nodes.
  1170. ///
  1171. /// \throw none.
  1172. ///
  1173. /// \param mem_sgmt The \c MemorySegment object used to insert the nodes
  1174. /// (which was also used for creating the tree due to the requirement of
  1175. /// \c inert()).
  1176. void deleteAllNodes(util::MemorySegment& mem_sgmt);
  1177. /// \brief Swaps two tree's contents.
  1178. ///
  1179. /// This and \c other trees must have been created with the same
  1180. /// memory segment (see the discussion in \c create()); otherwise the
  1181. /// behavior is undefined.
  1182. ///
  1183. /// This acts the same as many std::*.swap functions, exchanges the
  1184. /// contents. This doesn't throw anything.
  1185. void swap(RBTree<T>& other) {
  1186. std::swap(root_, other.root_);
  1187. std::swap(node_count_, other.node_count_);
  1188. }
  1189. //@}
  1190. private:
  1191. /// \name RBTree balance functions
  1192. //@{
  1193. void insertRebalance(typename RBNode<T>::RBNodePtr* root, RBNode<T>* node);
  1194. RBNode<T>* rightRotate(typename RBNode<T>::RBNodePtr* root,
  1195. RBNode<T>* node);
  1196. RBNode<T>* leftRotate(typename RBNode<T>::RBNodePtr* root,
  1197. RBNode<T>* node);
  1198. //@}
  1199. /// \name Helper functions
  1200. //@{
  1201. /// \brief delete tree whose root is equal to node
  1202. void deleteHelper(util::MemorySegment& mem_sgmt, RBNode<T> *node);
  1203. /// \brief Print the information of given RBNode.
  1204. void dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  1205. unsigned int depth) const;
  1206. /// \brief Print the information of given RBNode for dot.
  1207. int dumpDotHelper(std::ostream& os, const RBNode<T>* node,
  1208. int* nodecount, bool show_pointers) const;
  1209. /// \brief Indentation helper function for dumpTree
  1210. static void indent(std::ostream& os, unsigned int depth);
  1211. /// Split one node into two nodes for "prefix" and "suffix" parts of
  1212. /// the labels of the original node, respectively. The given node
  1213. /// will hold the prefix, while a newly created node will hold the prefix.
  1214. /// Note that the original node still represents the same domain name in
  1215. /// the entire tree. This ensures that a pointer to a node keeps its
  1216. /// semantics even if the tree structure is changed (as long as the node
  1217. /// itself remains valid).
  1218. void nodeFission(util::MemorySegment& mem_sgmt, RBNode<T>& node,
  1219. const isc::dns::LabelSequence& new_prefix,
  1220. const isc::dns::LabelSequence& new_suffix);
  1221. //@}
  1222. typename RBNode<T>::RBNodePtr root_;
  1223. /// the node count of current tree
  1224. unsigned int node_count_;
  1225. /// search policy for rbtree
  1226. const bool needsReturnEmptyNode_;
  1227. };
  1228. template <typename T>
  1229. RBTree<T>::RBTree(bool returnEmptyNode) :
  1230. root_(NULL),
  1231. node_count_(0),
  1232. needsReturnEmptyNode_(returnEmptyNode)
  1233. {
  1234. }
  1235. template <typename T>
  1236. RBTree<T>::~RBTree() {
  1237. assert(node_count_ == 0);
  1238. }
  1239. template <typename T>
  1240. void
  1241. RBTree<T>::deleteHelper(util::MemorySegment& mem_sgmt, RBNode<T>* root) {
  1242. if (root == NULL) {
  1243. return;
  1244. }
  1245. RBNode<T>* node = root;
  1246. while (root->getLeft() != NULL || root->getRight() != NULL) {
  1247. RBNode<T>* left(NULL);
  1248. RBNode<T>* right(NULL);
  1249. while ((left = node->getLeft()) != NULL ||
  1250. (right = node->getRight()) != NULL) {
  1251. node = (left != NULL) ? left : right;
  1252. }
  1253. RBNode<T>* parent = node->getParent();
  1254. if (parent->getLeft() == node) {
  1255. parent->left_ = NULL;
  1256. } else {
  1257. parent->right_ = NULL;
  1258. }
  1259. deleteHelper(mem_sgmt, node->getDown());
  1260. RBNode<T>::destroy(mem_sgmt, node);
  1261. --node_count_;
  1262. node = parent;
  1263. }
  1264. deleteHelper(mem_sgmt, root->getDown());
  1265. RBNode<T>::destroy(mem_sgmt, root);
  1266. --node_count_;
  1267. }
  1268. template <typename T>
  1269. template <typename CBARG>
  1270. typename RBTree<T>::Result
  1271. RBTree<T>::find(const isc::dns::LabelSequence& target_labels_orig,
  1272. RBNode<T>** target,
  1273. RBTreeNodeChain<T>& node_path,
  1274. bool (*callback)(const RBNode<T>&, CBARG),
  1275. CBARG callback_arg) const
  1276. {
  1277. if (!node_path.isEmpty()) {
  1278. isc_throw(isc::BadValue, "RBTree::find is given a non empty chain");
  1279. }
  1280. RBNode<T>* node = root_.get();
  1281. Result ret = NOTFOUND;
  1282. dns::LabelSequence target_labels(target_labels_orig);
  1283. while (node != NULL) {
  1284. node_path.last_compared_ = node;
  1285. node_path.last_comparison_ = target_labels.compare(node->getLabels());
  1286. const isc::dns::NameComparisonResult::NameRelation relation =
  1287. node_path.last_comparison_.getRelation();
  1288. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1289. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1290. node_path.push(node);
  1291. *target = node;
  1292. ret = EXACTMATCH;
  1293. }
  1294. break;
  1295. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1296. // If the two labels have no hierarchical relationship in terms
  1297. // of matching, we should continue the binary search.
  1298. node = (node_path.last_comparison_.getOrder() < 0) ?
  1299. node->getLeft() : node->getRight();
  1300. } else {
  1301. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1302. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1303. ret = PARTIALMATCH;
  1304. *target = node;
  1305. if (callback != NULL &&
  1306. node->getFlag(RBNode<T>::FLAG_CALLBACK)) {
  1307. if ((callback)(*node, callback_arg)) {
  1308. break;
  1309. }
  1310. }
  1311. }
  1312. node_path.push(node);
  1313. target_labels.stripRight(
  1314. node_path.last_comparison_.getCommonLabels());
  1315. node = node->getDown();
  1316. } else {
  1317. break;
  1318. }
  1319. }
  1320. }
  1321. return (ret);
  1322. }
  1323. template <typename T>
  1324. const RBNode<T>*
  1325. RBTree<T>::nextNode(RBTreeNodeChain<T>& node_path) const {
  1326. if (node_path.isEmpty()) {
  1327. isc_throw(isc::BadValue, "RBTree::nextNode is given an empty chain");
  1328. }
  1329. const RBNode<T>* node = node_path.top();
  1330. // if node has sub domain, the next domain is the smallest
  1331. // domain in sub domain tree
  1332. const RBNode<T>* down = node->getDown();
  1333. if (down != NULL) {
  1334. const RBNode<T>* left_most = down;
  1335. while (left_most->getLeft() != NULL) {
  1336. left_most = left_most->getLeft();
  1337. }
  1338. node_path.push(left_most);
  1339. return (left_most);
  1340. }
  1341. // try to find a successor.
  1342. // if no successor found move to up level, the next successor
  1343. // is the successor of up node in the up level tree, if
  1344. // up node doesn't have successor we gonna keep moving to up
  1345. // level
  1346. while (!node_path.isEmpty()) {
  1347. const RBNode<T>* up_node_successor = node_path.top()->successor();
  1348. node_path.pop();
  1349. if (up_node_successor != NULL) {
  1350. node_path.push(up_node_successor);
  1351. return (up_node_successor);
  1352. }
  1353. }
  1354. return (NULL);
  1355. }
  1356. template <typename T>
  1357. const RBNode<T>*
  1358. RBTree<T>::previousNode(RBTreeNodeChain<T>& node_path) const {
  1359. if (getNodeCount() == 0) {
  1360. // Special case for empty trees. It would look every time like
  1361. // we didn't search, because the last compared is empty. This is
  1362. // a slight hack and not perfect, but this is better than throwing
  1363. // on empty tree. And we probably won't meet an empty tree in practice
  1364. // anyway.
  1365. return (NULL);
  1366. }
  1367. if (node_path.last_compared_ == NULL) {
  1368. isc_throw(isc::BadValue,
  1369. "RBTree::previousNode() called before find()");
  1370. }
  1371. // If the relation isn't EQUAL, it means the find was called previously
  1372. // and didn't find the exact node. Therefore we need to locate the place
  1373. // to start iterating the chain of domains.
  1374. //
  1375. // The logic here is not too complex, we just need to take care to handle
  1376. // all the cases and decide where to go from there.
  1377. switch (node_path.last_comparison_.getRelation()) {
  1378. case dns::NameComparisonResult::COMMONANCESTOR:
  1379. case dns::NameComparisonResult::NONE:
  1380. // We compared with a leaf in the tree and wanted to go to one of
  1381. // the children. But the child was not there. It now depends on the
  1382. // direction in which we wanted to go.
  1383. if (node_path.last_comparison_.getOrder() < 0) {
  1384. // We wanted to go left. So the one we compared with is
  1385. // the one higher than we wanted. If we just put it into
  1386. // the node_path, then the following algorithm below will find
  1387. // the smaller one.
  1388. //
  1389. // This is exactly the same as with superdomain below.
  1390. // Therefore, we just fall through to the next case.
  1391. } else {
  1392. // We wanted to go right. That means we want to output the
  1393. // one which is the largest in the tree defined by the
  1394. // compared one (it is either the compared one, or some
  1395. // subdomain of it). There probably is not an easy trick
  1396. // for this, so we just find the correct place.
  1397. const RBNode<T>* current(node_path.last_compared_);
  1398. while (current != NULL) {
  1399. node_path.push(current);
  1400. // Go a level down and as much right there as possible
  1401. current = current->getDown();
  1402. if (current != NULL) {
  1403. const RBNode<T>* right;
  1404. while ((right = current->getRight()) != NULL) {
  1405. current = right;
  1406. }
  1407. }
  1408. }
  1409. // Now, the one on top of the path is the one we want. We
  1410. // return it now and leave it there, so we can search for
  1411. // previous of it the next time we'are called.
  1412. node_path.last_comparison_ =
  1413. dns::NameComparisonResult(0, 0,
  1414. dns::NameComparisonResult::EQUAL);
  1415. return (node_path.top());
  1416. }
  1417. // No break; here - we want to fall through. See above.
  1418. case dns::NameComparisonResult::SUPERDOMAIN:
  1419. // This is the case there's a "compressed" node and we looked for
  1420. // only part of it. The node itself is larger than we wanted, but
  1421. // if we put it to the node_path and then go one step left from it,
  1422. // we get the correct result.
  1423. node_path.push(node_path.last_compared_);
  1424. // Correct the comparison result, so we won't trigger this case
  1425. // next time previousNode is called. We already located the correct
  1426. // place to start. The value is partly nonsense, but that doesn't
  1427. // matter any more.
  1428. node_path.last_comparison_ =
  1429. dns::NameComparisonResult(0, 0,
  1430. dns::NameComparisonResult::EQUAL);
  1431. break;
  1432. case dns::NameComparisonResult::SUBDOMAIN:
  1433. // A subdomain means we returned the one above the searched one
  1434. // already and it is on top of the stack. This is was smaller
  1435. // than the one already, but we want to return yet smaller one.
  1436. // So we act as if it was EQUAL.
  1437. break;
  1438. case dns::NameComparisonResult::EQUAL:
  1439. // The find gave us an exact match or the previousNode was called
  1440. // already, which located the exact node. The rest of the function
  1441. // goes one domain left and returns it for us.
  1442. break;
  1443. }
  1444. // So, the node_path now contains the path to a node we want previous for.
  1445. // We just need to go one step left.
  1446. if (node_path.isEmpty()) {
  1447. // We got past the first one. So, we're returning NULL from
  1448. // now on.
  1449. return (NULL);
  1450. }
  1451. const RBNode<T>* node(node_path.top());
  1452. // Try going left in this tree
  1453. node = node->predecessor();
  1454. if (node == NULL) {
  1455. // We are the smallest ones in this tree. We go one level
  1456. // up. That one is the smaller one than us.
  1457. node_path.pop();
  1458. if (node_path.isEmpty()) {
  1459. // We're past the first one
  1460. return (NULL);
  1461. } else {
  1462. return (node_path.top());
  1463. }
  1464. }
  1465. // Exchange the node at the top of the path, as we move horizontaly
  1466. // through the domain tree
  1467. node_path.pop();
  1468. node_path.push(node);
  1469. // Try going as deep as possible, keeping on the right side of the trees
  1470. const RBNode<T>* down;
  1471. while ((down = node->getDown()) != NULL) {
  1472. // Move to the tree below
  1473. node = down;
  1474. if (node != NULL) {
  1475. // And get as much to the right of the tree as possible
  1476. const RBNode<T>* right;
  1477. while ((right = node->getRight()) != NULL) {
  1478. node = right;
  1479. }
  1480. }
  1481. // Now, we found the right-most node in the sub-tree, we need to
  1482. // include it in the path
  1483. node_path.push(node);
  1484. }
  1485. // Now, if the current node has no down_ pointer any more, it's the
  1486. // correct one.
  1487. return (node);
  1488. }
  1489. template <typename T>
  1490. typename RBTree<T>::Result
  1491. RBTree<T>::insert(util::MemorySegment& mem_sgmt,
  1492. const isc::dns::Name& target_name, RBNode<T>** new_node)
  1493. {
  1494. RBNode<T>* parent = NULL;
  1495. RBNode<T>* current = root_.get();
  1496. RBNode<T>* up_node = NULL;
  1497. isc::dns::LabelSequence target_labels(target_name);
  1498. int order = -1;
  1499. while (current != NULL) {
  1500. const dns::LabelSequence current_labels(current->getLabels());
  1501. const isc::dns::NameComparisonResult compare_result =
  1502. target_labels.compare(current_labels);
  1503. const isc::dns::NameComparisonResult::NameRelation relation =
  1504. compare_result.getRelation();
  1505. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1506. if (new_node != NULL) {
  1507. *new_node = current;
  1508. }
  1509. return (ALREADYEXISTS);
  1510. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1511. parent = current;
  1512. order = compare_result.getOrder();
  1513. current = order < 0 ? current->getLeft() : current->getRight();
  1514. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1515. // insert sub domain to sub tree
  1516. parent = NULL;
  1517. up_node = current;
  1518. target_labels.stripRight(compare_result.getCommonLabels());
  1519. current = current->getDown();
  1520. } else {
  1521. // The number of labels in common is fewer than the number of
  1522. // labels at the current node, so the current node must be
  1523. // adjusted to have just the common suffix, and a down pointer
  1524. // made to a new tree.
  1525. dns::LabelSequence common_ancestor = target_labels;
  1526. common_ancestor.stripLeft(target_labels.getLabelCount() -
  1527. compare_result.getCommonLabels());
  1528. dns::LabelSequence new_prefix = current_labels;
  1529. new_prefix.stripRight(compare_result.getCommonLabels());
  1530. nodeFission(mem_sgmt, *current, new_prefix, common_ancestor);
  1531. current = current->getParent();
  1532. }
  1533. }
  1534. typename RBNode<T>::RBNodePtr* current_root = (up_node != NULL) ?
  1535. &(up_node->down_) : &root_;
  1536. // Once a new node is created, no exception will be thrown until the end
  1537. // of the function, so we can simply create and hold a new node pointer.
  1538. RBNode<T>* node = RBNode<T>::create(mem_sgmt, target_labels);
  1539. node->parent_ = parent;
  1540. if (parent == NULL) {
  1541. *current_root = node;
  1542. // node is the new root of sub tree, so its init color is BLACK
  1543. node->setColor(RBNode<T>::BLACK);
  1544. node->setSubTreeRoot(true);
  1545. node->parent_ = up_node;
  1546. } else if (order < 0) {
  1547. node->setSubTreeRoot(false);
  1548. parent->left_ = node;
  1549. } else {
  1550. node->setSubTreeRoot(false);
  1551. parent->right_ = node;
  1552. }
  1553. insertRebalance(current_root, node);
  1554. if (new_node != NULL) {
  1555. *new_node = node;
  1556. }
  1557. ++node_count_;
  1558. return (SUCCESS);
  1559. }
  1560. template <typename T>
  1561. void
  1562. RBTree<T>::deleteAllNodes(util::MemorySegment& mem_sgmt) {
  1563. deleteHelper(mem_sgmt, root_.get());
  1564. root_ = NULL;
  1565. }
  1566. template <typename T>
  1567. void
  1568. RBTree<T>::nodeFission(util::MemorySegment& mem_sgmt, RBNode<T>& node,
  1569. const isc::dns::LabelSequence& new_prefix,
  1570. const isc::dns::LabelSequence& new_suffix)
  1571. {
  1572. // Create and reset the labels.
  1573. // Once a new node is created, no exception will be thrown until
  1574. // the end of the function, and it will keep consistent behavior
  1575. // (i.e., a weak form of strong exception guarantee) even if code
  1576. // after the call to this function throws an exception.
  1577. RBNode<T>* up_node = RBNode<T>::create(mem_sgmt, new_suffix);
  1578. node.resetLabels(new_prefix);
  1579. up_node->parent_ = node.getParent();
  1580. if (node.getParent() != NULL) {
  1581. if (node.getParent()->getLeft() == &node) {
  1582. node.getParent()->left_ = up_node;
  1583. } else if (node.getParent()->getRight() == &node) {
  1584. node.getParent()->right_ = up_node;
  1585. } else {
  1586. node.getParent()->down_ = up_node;
  1587. }
  1588. } else {
  1589. this->root_ = up_node;
  1590. }
  1591. up_node->down_ = &node;
  1592. node.parent_ = up_node;
  1593. // inherit the left/right pointers from the original node, and set
  1594. // the original node's left/right pointers to NULL.
  1595. up_node->left_ = node.getLeft();
  1596. if (node.getLeft() != NULL) {
  1597. node.getLeft()->parent_ = up_node;
  1598. }
  1599. up_node->right_ = node.getRight();
  1600. if (node.getRight() != NULL) {
  1601. node.getRight()->parent_ = up_node;
  1602. }
  1603. node.left_ = NULL;
  1604. node.right_ = NULL;
  1605. // set color of both nodes; the initial subtree node color is BLACK
  1606. up_node->setColor(node.getColor());
  1607. node.setColor(RBNode<T>::BLACK);
  1608. // set the subtree root flag of both nodes
  1609. up_node->setSubTreeRoot(node.isSubTreeRoot());
  1610. node.setSubTreeRoot(true);
  1611. ++node_count_;
  1612. }
  1613. template <typename T>
  1614. void
  1615. RBTree<T>::insertRebalance(typename RBNode<T>::RBNodePtr* root,
  1616. RBNode<T>* node)
  1617. {
  1618. RBNode<T>* uncle;
  1619. RBNode<T>* parent;
  1620. while (node != (*root).get() &&
  1621. (parent = node->getParent())->getColor() == RBNode<T>::RED) {
  1622. // Here, node->parent_ is not NULL and it is also red, so
  1623. // node->parent_->parent_ is also not NULL.
  1624. if (parent == parent->getParent()->getLeft()) {
  1625. uncle = parent->getParent()->getRight();
  1626. if (uncle != NULL && uncle->getColor() == RBNode<T>::RED) {
  1627. parent->setColor(RBNode<T>::BLACK);
  1628. uncle->setColor(RBNode<T>::BLACK);
  1629. parent->getParent()->setColor(RBNode<T>::RED);
  1630. node = parent->getParent();
  1631. } else {
  1632. if (node == parent->getRight()) {
  1633. node = parent;
  1634. leftRotate(root, node);
  1635. parent = node->getParent();
  1636. }
  1637. parent->setColor(RBNode<T>::BLACK);
  1638. parent->getParent()->setColor(RBNode<T>::RED);
  1639. rightRotate(root, parent->getParent());
  1640. }
  1641. } else {
  1642. uncle = parent->getParent()->getLeft();
  1643. if (uncle != NULL && uncle->getColor() == RBNode<T>::RED) {
  1644. parent->setColor(RBNode<T>::BLACK);
  1645. uncle->setColor(RBNode<T>::BLACK);
  1646. parent->getParent()->setColor(RBNode<T>::RED);
  1647. node = parent->getParent();
  1648. } else {
  1649. if (node == parent->getLeft()) {
  1650. node = parent;
  1651. rightRotate(root, node);
  1652. parent = node->getParent();
  1653. }
  1654. parent->setColor(RBNode<T>::BLACK);
  1655. parent->getParent()->setColor(RBNode<T>::RED);
  1656. leftRotate(root, parent->getParent());
  1657. }
  1658. }
  1659. }
  1660. (*root)->setColor(RBNode<T>::BLACK);
  1661. }
  1662. template <typename T>
  1663. RBNode<T>*
  1664. RBTree<T>::leftRotate(typename RBNode<T>::RBNodePtr* root, RBNode<T>* node) {
  1665. RBNode<T>* const right = node->getRight();
  1666. RBNode<T>* const rleft = right->getLeft();
  1667. node->right_ = rleft;
  1668. if (rleft != NULL) {
  1669. rleft->parent_ = node;
  1670. }
  1671. RBNode<T>* const parent = node->getParent();
  1672. right->parent_ = parent;
  1673. if (!node->isSubTreeRoot()) {
  1674. right->setSubTreeRoot(false);
  1675. if (node == parent->getLeft()) {
  1676. parent->left_ = right;
  1677. } else {
  1678. parent->right_ = right;
  1679. }
  1680. } else {
  1681. right->setSubTreeRoot(true);
  1682. *root = right;
  1683. }
  1684. right->left_ = node;
  1685. node->parent_ = right;
  1686. node->setSubTreeRoot(false);
  1687. return (node);
  1688. }
  1689. template <typename T>
  1690. RBNode<T>*
  1691. RBTree<T>::rightRotate(typename RBNode<T>::RBNodePtr* root, RBNode<T>* node) {
  1692. RBNode<T>* const left = node->getLeft();
  1693. RBNode<T>* const lright = left->getRight();
  1694. node->left_ = lright;
  1695. if (lright != NULL) {
  1696. lright->parent_ = node;
  1697. }
  1698. RBNode<T>* const parent = node->getParent();
  1699. left->parent_ = parent;
  1700. if (!node->isSubTreeRoot()) {
  1701. left->setSubTreeRoot(false);
  1702. if (node == parent->getRight()) {
  1703. parent->right_ = left;
  1704. } else {
  1705. parent->left_ = left;
  1706. }
  1707. } else {
  1708. left->setSubTreeRoot(true);
  1709. *root = left;
  1710. }
  1711. left->right_ = node;
  1712. node->parent_ = left;
  1713. node->setSubTreeRoot(false);
  1714. return (node);
  1715. }
  1716. template <typename T>
  1717. void
  1718. RBTree<T>::dumpTree(std::ostream& os, unsigned int depth) const {
  1719. indent(os, depth);
  1720. os << "tree has " << node_count_ << " node(s)\n";
  1721. dumpTreeHelper(os, root_.get(), depth);
  1722. }
  1723. template <typename T>
  1724. void
  1725. RBTree<T>::dumpTreeHelper(std::ostream& os, const RBNode<T>* node,
  1726. unsigned int depth) const
  1727. {
  1728. if (node == NULL) {
  1729. indent(os, depth);
  1730. os << "NULL\n";
  1731. return;
  1732. }
  1733. indent(os, depth);
  1734. os << node->getLabels() << " ("
  1735. << ((node->getColor() == RBNode<T>::BLACK) ? "black" : "red")
  1736. << ")";
  1737. if (node->isEmpty()) {
  1738. os << " [invisible]";
  1739. }
  1740. if (node->isSubTreeRoot()) {
  1741. os << " [subtreeroot]";
  1742. }
  1743. os << "\n";
  1744. const RBNode<T>* down = node->getDown();
  1745. if (down != NULL) {
  1746. indent(os, depth + 1);
  1747. os << "begin down from " << node->getLabels() << "\n";
  1748. dumpTreeHelper(os, down, depth + 1);
  1749. indent(os, depth + 1);
  1750. os << "end down from " << node->getLabels() << "\n";
  1751. }
  1752. dumpTreeHelper(os, node->getLeft(), depth + 1);
  1753. dumpTreeHelper(os, node->getRight(), depth + 1);
  1754. }
  1755. template <typename T>
  1756. void
  1757. RBTree<T>::indent(std::ostream& os, unsigned int depth) {
  1758. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1759. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1760. }
  1761. template <typename T>
  1762. void
  1763. RBTree<T>::dumpDot(std::ostream& os, bool show_pointers) const {
  1764. int nodecount = 0;
  1765. os << "digraph g {\n";
  1766. os << "node [shape = record,height=.1];\n";
  1767. dumpDotHelper(os, root_.get(), &nodecount, show_pointers);
  1768. os << "}\n";
  1769. }
  1770. template <typename T>
  1771. int
  1772. RBTree<T>::dumpDotHelper(std::ostream& os, const RBNode<T>* node,
  1773. int* nodecount, bool show_pointers) const
  1774. {
  1775. if (node == NULL) {
  1776. return 0;
  1777. }
  1778. int l = dumpDotHelper(os, node->getLeft(), nodecount, show_pointers);
  1779. int r = dumpDotHelper(os, node->getRight(), nodecount, show_pointers);
  1780. int d = dumpDotHelper(os, node->getDown(), nodecount, show_pointers);
  1781. *nodecount += 1;
  1782. os << "node" << *nodecount <<
  1783. "[label = \"<f0> |<f1> " << node->getLabels() <<
  1784. "|<f2>";
  1785. if (show_pointers) {
  1786. os << "|<f3> n=" << node << "|<f4> p=" << node->getParent();
  1787. }
  1788. os << "\"] [";
  1789. if (node->getColor() == RBNode<T>::RED) {
  1790. os << "color=red";
  1791. } else {
  1792. os << "color=black";
  1793. }
  1794. if (node->isSubTreeRoot()) {
  1795. os << ",penwidth=3";
  1796. }
  1797. if (node->isEmpty()) {
  1798. os << ",style=filled,fillcolor=lightgrey";
  1799. }
  1800. os << "];\n";
  1801. if (node->getLeft() != NULL) {
  1802. os << "\"node" << *nodecount << "\":f0 -> \"node" << l << "\":f1;\n";
  1803. }
  1804. if (node->getDown() != NULL) {
  1805. os << "\"node" << *nodecount << "\":f1 -> \"node" << d << "\":f1 [penwidth=5];\n";
  1806. }
  1807. if (node->getRight() != NULL) {
  1808. os << "\"node" << *nodecount << "\":f2 -> \"node" << r << "\":f1;\n";
  1809. }
  1810. return (*nodecount);
  1811. }
  1812. }
  1813. }
  1814. #endif // _RBTREE_H
  1815. // Local Variables:
  1816. // mode: c++
  1817. // End: