Home | History | Annotate | Download | only in src
      1 /*
      2     Copyright 2011 Google Inc.
      3 
      4     Licensed under the Apache License, Version 2.0 (the "License");
      5     you may not use this file except in compliance with the License.
      6     You may obtain a copy of the License at
      7 
      8          http://www.apache.org/licenses/LICENSE-2.0
      9 
     10     Unless required by applicable law or agreed to in writing, software
     11     distributed under the License is distributed on an "AS IS" BASIS,
     12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13     See the License for the specific language governing permissions and
     14     limitations under the License.
     15  */
     16 
     17 #ifndef GrRedBlackTree_DEFINED
     18 #define GrRedBlackTree_DEFINED
     19 
     20 #include "GrNoncopyable.h"
     21 
     22 template <typename T>
     23 class GrLess {
     24 public:
     25     bool operator()(const T& a, const T& b) const { return a < b; }
     26 };
     27 
     28 template <typename T>
     29 class GrLess<T*> {
     30 public:
     31     bool operator()(const T* a, const T* b) const { return *a < *b; }
     32 };
     33 
     34 /**
     35  * In debug build this will cause full traversals of the tree when the validate
     36  * is called on insert and remove. Useful for debugging but very slow.
     37  */
     38 #define DEEP_VALIDATE 0
     39 
     40 /**
     41  * A sorted tree that uses the red-black tree algorithm. Allows duplicate
     42  * entries. Data is of type T and is compared using functor C. A single C object
     43  * will be created and used for all comparisons.
     44  */
     45 template <typename T, typename C = GrLess<T> >
     46 class GrRedBlackTree : public GrNoncopyable {
     47 public:
     48     /**
     49      * Creates an empty tree.
     50      */
     51     GrRedBlackTree();
     52     virtual ~GrRedBlackTree();
     53 
     54     /**
     55      * Class used to iterater through the tree. The valid range of the tree
     56      * is given by [begin(), end()). It is legal to dereference begin() but not
     57      * end(). The iterator has preincrement and predecrement operators, it is
     58      * legal to decerement end() if the tree is not empty to get the last
     59      * element. However, a last() helper is provided.
     60      */
     61     class Iter;
     62 
     63     /**
     64      * Add an element to the tree. Duplicates are allowed.
     65      * @param t     the item to add.
     66      * @return  an iterator to the item.
     67      */
     68     Iter insert(const T& t);
     69 
     70     /**
     71      * Removes all items in the tree.
     72      */
     73     void reset();
     74 
     75     /**
     76      * @return true if there are no items in the tree, false otherwise.
     77      */
     78     bool empty() const {return 0 == fCount;}
     79 
     80     /**
     81      * @return the number of items in the tree.
     82      */
     83     int  count() const {return fCount;}
     84 
     85     /**
     86      * @return  an iterator to the first item in sorted order, or end() if empty
     87      */
     88     Iter begin();
     89     /**
     90      * Gets the last valid iterator. This is always valid, even on an empty.
     91      * However, it can never be dereferenced. Useful as a loop terminator.
     92      * @return  an iterator that is just beyond the last item in sorted order.
     93      */
     94     Iter end();
     95     /**
     96      * @return  an iterator that to the last item in sorted order, or end() if
     97      * empty.
     98      */
     99     Iter last();
    100 
    101     /**
    102      * Finds an occurrence of an item.
    103      * @param t     the item to find.
    104      * @return an iterator to a tree element equal to t or end() if none exists.
    105      */
    106     Iter find(const T& t);
    107     /**
    108      * Finds the first of an item in iterator order.
    109      * @param t     the item to find.
    110      * @return  an iterator to the first element equal to t or end() if
    111      *          none exists.
    112      */
    113     Iter findFirst(const T& t);
    114     /**
    115      * Finds the last of an item in iterator order.
    116      * @param t     the item to find.
    117      * @return  an iterator to the last element equal to t or end() if
    118      *          none exists.
    119      */
    120     Iter findLast(const T& t);
    121     /**
    122      * Gets the number of items in the tree equal to t.
    123      * @param t     the item to count.
    124      * @return  number of items equal to t in the tree
    125      */
    126     int countOf(const T& t) const;
    127 
    128     /**
    129      * Removes the item indicated by an iterator. The iterator will not be valid
    130      * afterwards.
    131      *
    132      * @param iter      iterator of item to remove. Must be valid (not end()).
    133      */
    134     void remove(const Iter& iter) { deleteAtNode(iter.fN); }
    135 
    136     static void UnitTest();
    137 
    138 private:
    139     enum Color {
    140         kRed_Color,
    141         kBlack_Color
    142     };
    143 
    144     enum Child {
    145         kLeft_Child  = 0,
    146         kRight_Child = 1
    147     };
    148 
    149     struct Node {
    150         T       fItem;
    151         Color   fColor;
    152 
    153         Node*   fParent;
    154         Node*   fChildren[2];
    155     };
    156 
    157     void rotateRight(Node* n);
    158     void rotateLeft(Node* n);
    159 
    160     static Node* SuccessorNode(Node* x);
    161     static Node* PredecessorNode(Node* x);
    162 
    163     void deleteAtNode(Node* x);
    164     static void RecursiveDelete(Node* x);
    165 
    166     int onCountOf(const Node* n, const T& t) const;
    167 
    168 #if GR_DEBUG
    169     void validate() const;
    170     int checkNode(Node* n, int* blackHeight) const;
    171     // checks relationship between a node and its children. allowRedRed means
    172     // node may be in an intermediate state where a red parent has a red child.
    173     bool validateChildRelations(const Node* n, bool allowRedRed) const;
    174     // place to stick break point if validateChildRelations is failing.
    175     bool validateChildRelationsFailed() const { return false; }
    176 #else
    177     void validate() const {}
    178 #endif
    179 
    180     int     fCount;
    181     Node*   fRoot;
    182     Node*   fFirst;
    183     Node*   fLast;
    184 
    185     const C fComp;
    186 };
    187 
    188 template <typename T, typename C>
    189 class GrRedBlackTree<T,C>::Iter {
    190 public:
    191     Iter() {};
    192     Iter(const Iter& i) {fN = i.fN; fTree = i.fTree;}
    193     Iter& operator =(const Iter& i) {
    194         fN = i.fN;
    195         fTree = i.fTree;
    196         return *this;
    197     }
    198     // altering the sort value of the item using this method will cause
    199     // errors.
    200     T& operator *() const { return fN->fItem; }
    201     bool operator ==(const Iter& i) const {
    202         return fN == i.fN && fTree == i.fTree;
    203     }
    204     bool operator !=(const Iter& i) const { return !(*this == i); }
    205     Iter& operator ++() {
    206         GrAssert(*this != fTree->end());
    207         fN = SuccessorNode(fN);
    208         return *this;
    209     }
    210     Iter& operator --() {
    211         GrAssert(*this != fTree->begin());
    212         if (NULL != fN) {
    213             fN = PredecessorNode(fN);
    214         } else {
    215             *this = fTree->last();
    216         }
    217         return *this;
    218     }
    219 
    220 private:
    221     friend class GrRedBlackTree;
    222     explicit Iter(Node* n, GrRedBlackTree* tree) {
    223         fN = n;
    224         fTree = tree;
    225     }
    226     Node* fN;
    227     GrRedBlackTree* fTree;
    228 };
    229 
    230 template <typename T, typename C>
    231 GrRedBlackTree<T,C>::GrRedBlackTree() : fComp() {
    232     fRoot = NULL;
    233     fFirst = NULL;
    234     fLast = NULL;
    235     fCount = 0;
    236     validate();
    237 }
    238 
    239 template <typename T, typename C>
    240 GrRedBlackTree<T,C>::~GrRedBlackTree() {
    241     RecursiveDelete(fRoot);
    242 }
    243 
    244 template <typename T, typename C>
    245 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::begin() {
    246     return Iter(fFirst, this);
    247 }
    248 
    249 template <typename T, typename C>
    250 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::end() {
    251     return Iter(NULL, this);
    252 }
    253 
    254 template <typename T, typename C>
    255 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::last() {
    256     return Iter(fLast, this);
    257 }
    258 
    259 template <typename T, typename C>
    260 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::find(const T& t) {
    261     Node* n = fRoot;
    262     while (NULL != n) {
    263         if (fComp(t, n->fItem)) {
    264             n = n->fChildren[kLeft_Child];
    265         } else {
    266             if (!fComp(n->fItem, t)) {
    267                 return Iter(n, this);
    268             }
    269             n = n->fChildren[kRight_Child];
    270         }
    271     }
    272     return end();
    273 }
    274 
    275 template <typename T, typename C>
    276 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::findFirst(const T& t) {
    277     Node* n = fRoot;
    278     Node* leftMost = NULL;
    279     while (NULL != n) {
    280         if (fComp(t, n->fItem)) {
    281             n = n->fChildren[kLeft_Child];
    282         } else {
    283             if (!fComp(n->fItem, t)) {
    284                 // found one. check if another in left subtree.
    285                 leftMost = n;
    286                 n = n->fChildren[kLeft_Child];
    287             } else {
    288                 n = n->fChildren[kRight_Child];
    289             }
    290         }
    291     }
    292     return Iter(leftMost, this);
    293 }
    294 
    295 template <typename T, typename C>
    296 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::findLast(const T& t) {
    297     Node* n = fRoot;
    298     Node* rightMost = NULL;
    299     while (NULL != n) {
    300         if (fComp(t, n->fItem)) {
    301             n = n->fChildren[kLeft_Child];
    302         } else {
    303             if (!fComp(n->fItem, t)) {
    304                 // found one. check if another in right subtree.
    305                 rightMost = n;
    306             }
    307             n = n->fChildren[kRight_Child];
    308         }
    309     }
    310     return Iter(rightMost, this);
    311 }
    312 
    313 template <typename T, typename C>
    314 int GrRedBlackTree<T,C>::countOf(const T& t) const {
    315     return onCountOf(fRoot, t);
    316 }
    317 
    318 template <typename T, typename C>
    319 int GrRedBlackTree<T,C>::onCountOf(const Node* n, const T& t) const {
    320     // this is count*log(n) :(
    321     while (NULL != n) {
    322         if (fComp(t, n->fItem)) {
    323             n = n->fChildren[kLeft_Child];
    324         } else {
    325             if (!fComp(n->fItem, t)) {
    326                 int count = 1;
    327                 count += onCountOf(n->fChildren[kLeft_Child], t);
    328                 count += onCountOf(n->fChildren[kRight_Child], t);
    329                 return count;
    330             }
    331             n = n->fChildren[kRight_Child];
    332         }
    333     }
    334     return 0;
    335 
    336 }
    337 
    338 template <typename T, typename C>
    339 void GrRedBlackTree<T,C>::reset() {
    340     RecursiveDelete(fRoot);
    341     fRoot = NULL;
    342     fFirst = NULL;
    343     fLast = NULL;
    344     fCount = 0;
    345 }
    346 
    347 template <typename T, typename C>
    348 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::insert(const T& t) {
    349     validate();
    350 
    351     ++fCount;
    352 
    353     Node* x = new Node;
    354     x->fChildren[kLeft_Child] = NULL;
    355     x->fChildren[kRight_Child] = NULL;
    356     x->fItem = t;
    357 
    358     Node* returnNode = x;
    359 
    360     Node* gp = NULL;
    361     Node* p = NULL;
    362     Node* n = fRoot;
    363     Child pc = kLeft_Child; // suppress uninit warning
    364     Child gpc;
    365 
    366     bool first = true;
    367     bool last = true;
    368     while (NULL != n) {
    369         gpc = pc;
    370         pc = fComp(x->fItem, n->fItem) ? kLeft_Child : kRight_Child;
    371         first = first && kLeft_Child == pc;
    372         last = last && kRight_Child == pc;
    373         gp = p;
    374         p = n;
    375         n = p->fChildren[pc];
    376     }
    377     if (last) {
    378         fLast = x;
    379     }
    380     if (first) {
    381         fFirst = x;
    382     }
    383 
    384     if (NULL == p) {
    385         fRoot = x;
    386         x->fColor = kBlack_Color;
    387         x->fParent = NULL;
    388         GrAssert(1 == fCount);
    389         return Iter(returnNode, this);
    390     }
    391     p->fChildren[pc] = x;
    392     x->fColor = kRed_Color;
    393     x->fParent = p;
    394 
    395     do {
    396         // assumptions at loop start.
    397         GrAssert(NULL != x);
    398         GrAssert(kRed_Color == x->fColor);
    399         // can't have a grandparent but no parent.
    400         GrAssert(!(NULL != gp && NULL == p));
    401         // make sure pc and gpc are correct
    402         GrAssert(NULL == p  || p->fChildren[pc] == x);
    403         GrAssert(NULL == gp || gp->fChildren[gpc] == p);
    404 
    405         // if x's parent is black then we didn't violate any of the
    406         // red/black properties when we added x as red.
    407         if (kBlack_Color == p->fColor) {
    408             return Iter(returnNode, this);
    409         }
    410         // gp must be valid because if p was the root then it is black
    411         GrAssert(NULL != gp);
    412         // gp must be black since it's child, p, is red.
    413         GrAssert(kBlack_Color == gp->fColor);
    414 
    415 
    416         // x and its parent are red, violating red-black property.
    417         Node* u = gp->fChildren[1-gpc];
    418         // if x's uncle (p's sibling) is also red then we can flip
    419         // p and u to black and make gp red. But then we have to recurse
    420         // up to gp since it's parent may also be red.
    421         if (NULL != u && kRed_Color == u->fColor) {
    422             p->fColor = kBlack_Color;
    423             u->fColor = kBlack_Color;
    424             gp->fColor = kRed_Color;
    425             x = gp;
    426             p = x->fParent;
    427             if (NULL == p) {
    428                 // x (prev gp) is the root, color it black and be done.
    429                 GrAssert(fRoot == x);
    430                 x->fColor = kBlack_Color;
    431                 validate();
    432                 return Iter(returnNode, this);
    433             }
    434             gp = p->fParent;
    435             pc = (p->fChildren[kLeft_Child] == x) ? kLeft_Child :
    436                                                     kRight_Child;
    437             if (NULL != gp) {
    438                 gpc = (gp->fChildren[kLeft_Child] == p) ? kLeft_Child :
    439                                                           kRight_Child;
    440             }
    441             continue;
    442         } break;
    443     } while (true);
    444     // Here p is red but u is black and we still have to resolve the fact
    445     // that x and p are both red.
    446     GrAssert(NULL == gp->fChildren[1-gpc] || kBlack_Color == gp->fChildren[1-gpc]->fColor);
    447     GrAssert(kRed_Color == x->fColor);
    448     GrAssert(kRed_Color == p->fColor);
    449     GrAssert(kBlack_Color == gp->fColor);
    450 
    451     // make x be on the same side of p as p is of gp. If it isn't already
    452     // the case then rotate x up to p and swap their labels.
    453     if (pc != gpc) {
    454         if (kRight_Child == pc) {
    455             rotateLeft(p);
    456             Node* temp = p;
    457             p = x;
    458             x = temp;
    459             pc = kLeft_Child;
    460         } else {
    461             rotateRight(p);
    462             Node* temp = p;
    463             p = x;
    464             x = temp;
    465             pc = kRight_Child;
    466         }
    467     }
    468     // we now rotate gp down, pulling up p to be it's new parent.
    469     // gp's child, u, that is not affected we know to be black. gp's new
    470     // child is p's previous child (x's pre-rotation sibling) which must be
    471     // black since p is red.
    472     GrAssert(NULL == p->fChildren[1-pc] ||
    473              kBlack_Color == p->fChildren[1-pc]->fColor);
    474     // Since gp's two children are black it can become red if p is made
    475     // black. This leaves the black-height of both of p's new subtrees
    476     // preserved and removes the red/red parent child relationship.
    477     p->fColor = kBlack_Color;
    478     gp->fColor = kRed_Color;
    479     if (kLeft_Child == pc) {
    480         rotateRight(gp);
    481     } else {
    482         rotateLeft(gp);
    483     }
    484     validate();
    485     return Iter(returnNode, this);
    486 }
    487 
    488 
    489 template <typename T, typename C>
    490 void GrRedBlackTree<T,C>::rotateRight(Node* n) {
    491     /*            d?              d?
    492      *           /               /
    493      *          n               s
    494      *         / \     --->    / \
    495      *        s   a?          c?  n
    496      *       / \                 / \
    497      *      c?  b?              b?  a?
    498      */
    499     Node* d = n->fParent;
    500     Node* s = n->fChildren[kLeft_Child];
    501     GrAssert(NULL != s);
    502     Node* b = s->fChildren[kRight_Child];
    503 
    504     if (NULL != d) {
    505         Child c = d->fChildren[kLeft_Child] == n ? kLeft_Child :
    506                                              kRight_Child;
    507         d->fChildren[c] = s;
    508     } else {
    509         GrAssert(fRoot == n);
    510         fRoot = s;
    511     }
    512     s->fParent = d;
    513     s->fChildren[kRight_Child] = n;
    514     n->fParent = s;
    515     n->fChildren[kLeft_Child] = b;
    516     if (NULL != b) {
    517         b->fParent = n;
    518     }
    519 
    520     GR_DEBUGASSERT(validateChildRelations(d, true));
    521     GR_DEBUGASSERT(validateChildRelations(s, true));
    522     GR_DEBUGASSERT(validateChildRelations(n, false));
    523     GR_DEBUGASSERT(validateChildRelations(n->fChildren[kRight_Child], true));
    524     GR_DEBUGASSERT(validateChildRelations(b, true));
    525     GR_DEBUGASSERT(validateChildRelations(s->fChildren[kLeft_Child], true));
    526 }
    527 
    528 template <typename T, typename C>
    529 void GrRedBlackTree<T,C>::rotateLeft(Node* n) {
    530 
    531     Node* d = n->fParent;
    532     Node* s = n->fChildren[kRight_Child];
    533     GrAssert(NULL != s);
    534     Node* b = s->fChildren[kLeft_Child];
    535 
    536     if (NULL != d) {
    537         Child c = d->fChildren[kRight_Child] == n ? kRight_Child :
    538                                                    kLeft_Child;
    539         d->fChildren[c] = s;
    540     } else {
    541         GrAssert(fRoot == n);
    542         fRoot = s;
    543     }
    544     s->fParent = d;
    545     s->fChildren[kLeft_Child] = n;
    546     n->fParent = s;
    547     n->fChildren[kRight_Child] = b;
    548     if (NULL != b) {
    549         b->fParent = n;
    550     }
    551 
    552     GR_DEBUGASSERT(validateChildRelations(d, true));
    553     GR_DEBUGASSERT(validateChildRelations(s, true));
    554     GR_DEBUGASSERT(validateChildRelations(n, true));
    555     GR_DEBUGASSERT(validateChildRelations(n->fChildren[kLeft_Child], true));
    556     GR_DEBUGASSERT(validateChildRelations(b, true));
    557     GR_DEBUGASSERT(validateChildRelations(s->fChildren[kRight_Child], true));
    558 }
    559 
    560 template <typename T, typename C>
    561 typename GrRedBlackTree<T,C>::Node* GrRedBlackTree<T,C>::SuccessorNode(Node* x) {
    562     GrAssert(NULL != x);
    563     if (NULL != x->fChildren[kRight_Child]) {
    564         x = x->fChildren[kRight_Child];
    565         while (NULL != x->fChildren[kLeft_Child]) {
    566             x = x->fChildren[kLeft_Child];
    567         }
    568         return x;
    569     }
    570     while (NULL != x->fParent && x == x->fParent->fChildren[kRight_Child]) {
    571         x = x->fParent;
    572     }
    573     return x->fParent;
    574 }
    575 
    576 template <typename T, typename C>
    577 typename GrRedBlackTree<T,C>::Node* GrRedBlackTree<T,C>::PredecessorNode(Node* x) {
    578     GrAssert(NULL != x);
    579     if (NULL != x->fChildren[kLeft_Child]) {
    580         x = x->fChildren[kLeft_Child];
    581         while (NULL != x->fChildren[kRight_Child]) {
    582             x = x->fChildren[kRight_Child];
    583         }
    584         return x;
    585     }
    586     while (NULL != x->fParent && x == x->fParent->fChildren[kLeft_Child]) {
    587         x = x->fParent;
    588     }
    589     return x->fParent;
    590 }
    591 
    592 template <typename T, typename C>
    593 void GrRedBlackTree<T,C>::deleteAtNode(Node* x) {
    594     GrAssert(NULL != x);
    595     validate();
    596     --fCount;
    597 
    598     bool hasLeft =  NULL != x->fChildren[kLeft_Child];
    599     bool hasRight = NULL != x->fChildren[kRight_Child];
    600     Child c = hasLeft ? kLeft_Child : kRight_Child;
    601 
    602     if (hasLeft && hasRight) {
    603         // first and last can't have two children.
    604         GrAssert(fFirst != x);
    605         GrAssert(fLast != x);
    606         // if x is an interior node then we find it's successor
    607         // and swap them.
    608         Node* s = x->fChildren[kRight_Child];
    609         while (NULL != s->fChildren[kLeft_Child]) {
    610             s = s->fChildren[kLeft_Child];
    611         }
    612         GrAssert(NULL != s);
    613         // this might be expensive relative to swapping node ptrs around.
    614         // depends on T.
    615         x->fItem = s->fItem;
    616         x = s;
    617         c = kRight_Child;
    618     } else if (NULL == x->fParent) {
    619         // if x was the root we just replace it with its child and make
    620         // the new root (if the tree is not empty) black.
    621         GrAssert(fRoot == x);
    622         fRoot = x->fChildren[c];
    623         if (NULL != fRoot) {
    624             fRoot->fParent = NULL;
    625             fRoot->fColor = kBlack_Color;
    626             if (x == fLast) {
    627                 GrAssert(c == kLeft_Child);
    628                 fLast = fRoot;
    629             } else if (x == fFirst) {
    630                 GrAssert(c == kRight_Child);
    631                 fFirst = fRoot;
    632             }
    633         } else {
    634             GrAssert(fFirst == fLast && x == fFirst);
    635             fFirst = NULL;
    636             fLast = NULL;
    637             GrAssert(0 == fCount);
    638         }
    639         delete x;
    640         validate();
    641         return;
    642     }
    643 
    644     Child pc;
    645     Node* p = x->fParent;
    646     pc = p->fChildren[kLeft_Child] == x ? kLeft_Child : kRight_Child;
    647 
    648     if (NULL == x->fChildren[c]) {
    649         if (fLast == x) {
    650             fLast = p;
    651             GrAssert(p == PredecessorNode(x));
    652         } else if (fFirst == x) {
    653             fFirst = p;
    654             GrAssert(p == SuccessorNode(x));
    655         }
    656         // x has two implicit black children.
    657         Color xcolor = x->fColor;
    658         p->fChildren[pc] = NULL;
    659         delete x;
    660         x = NULL;
    661         // when x is red it can be with an implicit black leaf without
    662         // violating any of the red-black tree properties.
    663         if (kRed_Color == xcolor) {
    664             validate();
    665             return;
    666         }
    667         // s is p's other child (x's sibling)
    668         Node* s = p->fChildren[1-pc];
    669 
    670         //s cannot be an implicit black node because the original
    671         // black-height at x was >= 2 and s's black-height must equal the
    672         // initial black height of x.
    673         GrAssert(NULL != s);
    674         GrAssert(p == s->fParent);
    675 
    676         // assigned in loop
    677         Node* sl;
    678         Node* sr;
    679         bool slRed;
    680         bool srRed;
    681 
    682         do {
    683             // When we start this loop x may already be deleted it is/was
    684             // p's child on its pc side. x's children are/were black. The
    685             // first time through the loop they are implict children.
    686             // On later passes we will be walking up the tree and they will
    687             // be real nodes.
    688             // The x side of p has a black-height that is one less than the
    689             // s side. It must be rebalanced.
    690             GrAssert(NULL != s);
    691             GrAssert(p == s->fParent);
    692             GrAssert(NULL == x || x->fParent == p);
    693 
    694             //sl and sr are s's children, which may be implicit.
    695             sl = s->fChildren[kLeft_Child];
    696             sr = s->fChildren[kRight_Child];
    697 
    698             // if the s is red we will rotate s and p, swap their colors so
    699             // that x's new sibling is black
    700             if (kRed_Color == s->fColor) {
    701                 // if s is red then it's parent must be black.
    702                 GrAssert(kBlack_Color == p->fColor);
    703                 // s's children must also be black since s is red. They can't
    704                 // be implicit since s is red and it's black-height is >= 2.
    705                 GrAssert(NULL != sl && kBlack_Color == sl->fColor);
    706                 GrAssert(NULL != sr && kBlack_Color == sr->fColor);
    707                 p->fColor = kRed_Color;
    708                 s->fColor = kBlack_Color;
    709                 if (kLeft_Child == pc) {
    710                     rotateLeft(p);
    711                     s = sl;
    712                 } else {
    713                     rotateRight(p);
    714                     s = sr;
    715                 }
    716                 sl = s->fChildren[kLeft_Child];
    717                 sr = s->fChildren[kRight_Child];
    718             }
    719             // x and s are now both black.
    720             GrAssert(kBlack_Color == s->fColor);
    721             GrAssert(NULL == x || kBlack_Color == x->fColor);
    722             GrAssert(p == s->fParent);
    723             GrAssert(NULL == x || p == x->fParent);
    724 
    725             // when x is deleted its subtree will have reduced black-height.
    726             slRed = (NULL != sl && kRed_Color == sl->fColor);
    727             srRed = (NULL != sr && kRed_Color == sr->fColor);
    728             if (!slRed && !srRed) {
    729                 // if s can be made red that will balance out x's removal
    730                 // to make both subtrees of p have the same black-height.
    731                 if (kBlack_Color == p->fColor) {
    732                     s->fColor = kRed_Color;
    733                     // now subtree at p has black-height of one less than
    734                     // p's parent's other child's subtree. We move x up to
    735                     // p and go through the loop again. At the top of loop
    736                     // we assumed x and x's children are black, which holds
    737                     // by above ifs.
    738                     // if p is the root there is no other subtree to balance
    739                     // against.
    740                     x = p;
    741                     p = x->fParent;
    742                     if (NULL == p) {
    743                         GrAssert(fRoot == x);
    744                         validate();
    745                         return;
    746                     } else {
    747                         pc = p->fChildren[kLeft_Child] == x ? kLeft_Child :
    748                                                               kRight_Child;
    749 
    750                     }
    751                     s = p->fChildren[1-pc];
    752                     GrAssert(NULL != s);
    753                     GrAssert(p == s->fParent);
    754                     continue;
    755                 } else if (kRed_Color == p->fColor) {
    756                     // we can make p black and s red. This balance out p's
    757                     // two subtrees and keep the same black-height as it was
    758                     // before the delete.
    759                     s->fColor = kRed_Color;
    760                     p->fColor = kBlack_Color;
    761                     validate();
    762                     return;
    763                 }
    764             }
    765             break;
    766         } while (true);
    767         // if we made it here one or both of sl and sr is red.
    768         // s and x are black. We make sure that a red child is on
    769         // the same side of s as s is of p.
    770         GrAssert(slRed || srRed);
    771         if (kLeft_Child == pc && !srRed) {
    772             s->fColor = kRed_Color;
    773             sl->fColor = kBlack_Color;
    774             rotateRight(s);
    775             sr = s;
    776             s = sl;
    777             //sl = s->fChildren[kLeft_Child]; don't need this
    778         } else if (kRight_Child == pc && !slRed) {
    779             s->fColor = kRed_Color;
    780             sr->fColor = kBlack_Color;
    781             rotateLeft(s);
    782             sl = s;
    783             s = sr;
    784             //sr = s->fChildren[kRight_Child]; don't need this
    785         }
    786         // now p is either red or black, x and s are red and s's 1-pc
    787         // child is red.
    788         // We rotate p towards x, pulling s up to replace p. We make
    789         // p be black and s takes p's old color.
    790         // Whether p was red or black, we've increased its pc subtree
    791         // rooted at x by 1 (balancing the imbalance at the start) and
    792         // we've also its subtree rooted at s's black-height by 1. This
    793         // can be balanced by making s's red child be black.
    794         s->fColor = p->fColor;
    795         p->fColor = kBlack_Color;
    796         if (kLeft_Child == pc) {
    797             GrAssert(NULL != sr && kRed_Color == sr->fColor);
    798             sr->fColor = kBlack_Color;
    799             rotateLeft(p);
    800         } else {
    801             GrAssert(NULL != sl && kRed_Color == sl->fColor);
    802             sl->fColor = kBlack_Color;
    803             rotateRight(p);
    804         }
    805     }
    806     else {
    807         // x has exactly one implicit black child. x cannot be red.
    808         // Proof by contradiction: Assume X is red. Let c0 be x's implicit
    809         // child and c1 be its non-implicit child. c1 must be black because
    810         // red nodes always have two black children. Then the two subtrees
    811         // of x rooted at c0 and c1 will have different black-heights.
    812         GrAssert(kBlack_Color == x->fColor);
    813         // So we know x is black and has one implicit black child, c0. c1
    814         // must be red, otherwise the subtree at c1 will have a different
    815         // black-height than the subtree rooted at c0.
    816         GrAssert(kRed_Color == x->fChildren[c]->fColor);
    817         // replace x with c1, making c1 black, preserves all red-black tree
    818         // props.
    819         Node* c1 = x->fChildren[c];
    820         if (x == fFirst) {
    821             GrAssert(c == kRight_Child);
    822             fFirst = c1;
    823             while (NULL != fFirst->fChildren[kLeft_Child]) {
    824                 fFirst = fFirst->fChildren[kLeft_Child];
    825             }
    826             GrAssert(fFirst == SuccessorNode(x));
    827         } else if (x == fLast) {
    828             GrAssert(c == kLeft_Child);
    829             fLast = c1;
    830             while (NULL != fLast->fChildren[kRight_Child]) {
    831                 fLast = fLast->fChildren[kRight_Child];
    832             }
    833             GrAssert(fLast == PredecessorNode(x));
    834         }
    835         c1->fParent = p;
    836         p->fChildren[pc] = c1;
    837         c1->fColor = kBlack_Color;
    838         delete x;
    839         validate();
    840     }
    841     validate();
    842 }
    843 
    844 template <typename T, typename C>
    845 void GrRedBlackTree<T,C>::RecursiveDelete(Node* x) {
    846     if (NULL != x) {
    847         RecursiveDelete(x->fChildren[kLeft_Child]);
    848         RecursiveDelete(x->fChildren[kRight_Child]);
    849         delete x;
    850     }
    851 }
    852 
    853 #if GR_DEBUG
    854 template <typename T, typename C>
    855 void GrRedBlackTree<T,C>::validate() const {
    856     if (fCount) {
    857         GrAssert(NULL == fRoot->fParent);
    858         GrAssert(NULL != fFirst);
    859         GrAssert(NULL != fLast);
    860 
    861         GrAssert(kBlack_Color == fRoot->fColor);
    862         if (1 == fCount) {
    863             GrAssert(fFirst == fRoot);
    864             GrAssert(fLast == fRoot);
    865             GrAssert(0 == fRoot->fChildren[kLeft_Child]);
    866             GrAssert(0 == fRoot->fChildren[kRight_Child]);
    867         }
    868     } else {
    869         GrAssert(NULL == fRoot);
    870         GrAssert(NULL == fFirst);
    871         GrAssert(NULL == fLast);
    872     }
    873 #if DEEP_VALIDATE
    874     int bh;
    875     int count = checkNode(fRoot, &bh);
    876     GrAssert(count == fCount);
    877 #endif
    878 }
    879 
    880 template <typename T, typename C>
    881 int GrRedBlackTree<T,C>::checkNode(Node* n, int* bh) const {
    882     if (NULL != n) {
    883         GrAssert(validateChildRelations(n, false));
    884         if (kBlack_Color == n->fColor) {
    885             *bh += 1;
    886         }
    887         GrAssert(!fComp(n->fItem, fFirst->fItem));
    888         GrAssert(!fComp(fLast->fItem, n->fItem));
    889         int leftBh = *bh;
    890         int rightBh = *bh;
    891         int cl = checkNode(n->fChildren[kLeft_Child], &leftBh);
    892         int cr = checkNode(n->fChildren[kRight_Child], &rightBh);
    893         GrAssert(leftBh == rightBh);
    894         *bh = leftBh;
    895         return 1 + cl + cr;
    896     }
    897     return 0;
    898 }
    899 
    900 template <typename T, typename C>
    901 bool GrRedBlackTree<T,C>::validateChildRelations(const Node* n,
    902                                                  bool allowRedRed) const {
    903     if (NULL != n) {
    904         if (NULL != n->fChildren[kLeft_Child] ||
    905             NULL != n->fChildren[kRight_Child]) {
    906             if (n->fChildren[kLeft_Child] == n->fChildren[kRight_Child]) {
    907                 return validateChildRelationsFailed();
    908             }
    909             if (n->fChildren[kLeft_Child] == n->fParent &&
    910                 NULL != n->fParent) {
    911                 return validateChildRelationsFailed();
    912             }
    913             if (n->fChildren[kRight_Child] == n->fParent &&
    914                 NULL != n->fParent) {
    915                 return validateChildRelationsFailed();
    916             }
    917             if (NULL != n->fChildren[kLeft_Child]) {
    918                 if (!allowRedRed &&
    919                     kRed_Color == n->fChildren[kLeft_Child]->fColor &&
    920                     kRed_Color == n->fColor) {
    921                     return validateChildRelationsFailed();
    922                 }
    923                 if (n->fChildren[kLeft_Child]->fParent != n) {
    924                     return validateChildRelationsFailed();
    925                 }
    926                 if (!(fComp(n->fChildren[kLeft_Child]->fItem, n->fItem) ||
    927                       (!fComp(n->fChildren[kLeft_Child]->fItem, n->fItem) &&
    928                        !fComp(n->fItem, n->fChildren[kLeft_Child]->fItem)))) {
    929                     return validateChildRelationsFailed();
    930                 }
    931             }
    932             if (NULL != n->fChildren[kRight_Child]) {
    933                 if (!allowRedRed &&
    934                     kRed_Color == n->fChildren[kRight_Child]->fColor &&
    935                     kRed_Color == n->fColor) {
    936                     return validateChildRelationsFailed();
    937                 }
    938                 if (n->fChildren[kRight_Child]->fParent != n) {
    939                     return validateChildRelationsFailed();
    940                 }
    941                 if (!(fComp(n->fItem, n->fChildren[kRight_Child]->fItem) ||
    942                       (!fComp(n->fChildren[kRight_Child]->fItem, n->fItem) &&
    943                        !fComp(n->fItem, n->fChildren[kRight_Child]->fItem)))) {
    944                     return validateChildRelationsFailed();
    945                 }
    946             }
    947         }
    948     }
    949     return true;
    950 }
    951 #endif
    952 
    953 #include "GrRandom.h"
    954 
    955 template <typename T, typename C>
    956 void GrRedBlackTree<T,C>::UnitTest() {
    957     GrRedBlackTree<int> tree;
    958     typedef GrRedBlackTree<int>::Iter iter;
    959 
    960     GrRandom r;
    961 
    962     int count[100] = {0};
    963     // add 10K ints
    964     for (int i = 0; i < 10000; ++i) {
    965         int x = r.nextU()%100;
    966         Iter xi = tree.insert(x);
    967         GrAssert(*xi == x);
    968         ++count[x];
    969     }
    970 
    971     tree.insert(0);
    972     ++count[0];
    973     tree.insert(99);
    974     ++count[99];
    975     GrAssert(*tree.begin() == 0);
    976     GrAssert(*tree.last() == 99);
    977     GrAssert(--(++tree.begin()) == tree.begin());
    978     GrAssert(--tree.end() == tree.last());
    979     GrAssert(tree.count() == 10002);
    980 
    981     int c = 0;
    982     // check that we iterate through the correct number of
    983     // elements and they are properly sorted.
    984     for (Iter a = tree.begin(); tree.end() != a; ++a) {
    985         Iter b = a;
    986         ++b;
    987         ++c;
    988         GrAssert(b == tree.end() || *a <= *b);
    989     }
    990     GrAssert(c == tree.count());
    991 
    992     // check that the tree reports the correct number of each int
    993     // and that we can iterate through them correctly both forward
    994     // and backward.
    995     for (int i = 0; i < 100; ++i) {
    996         int c;
    997         c = tree.countOf(i);
    998         GrAssert(c == count[i]);
    999         c = 0;
   1000         Iter iter = tree.findFirst(i);
   1001         while (iter != tree.end() && *iter == i) {
   1002             ++c;
   1003             ++iter;
   1004         }
   1005         GrAssert(count[i] == c);
   1006         c = 0;
   1007         iter = tree.findLast(i);
   1008         if (iter != tree.end()) {
   1009             do {
   1010                 if (*iter == i) {
   1011                     ++c;
   1012                 } else {
   1013                     break;
   1014                 }
   1015                 if (iter != tree.begin()) {
   1016                     --iter;
   1017                 } else {
   1018                     break;
   1019                 }
   1020             } while (true);
   1021         }
   1022         GrAssert(c == count[i]);
   1023     }
   1024     // remove all the ints between 25 and 74. Randomly chose to remove
   1025     // the first, last, or any entry for each.
   1026     for (int i = 25; i < 75; ++i) {
   1027         while (0 != tree.countOf(i)) {
   1028             --count[i];
   1029             int x = r.nextU() % 3;
   1030             Iter iter;
   1031             switch (x) {
   1032             case 0:
   1033                 iter = tree.findFirst(i);
   1034                 break;
   1035             case 1:
   1036                 iter = tree.findLast(i);
   1037                 break;
   1038             case 2:
   1039             default:
   1040                 iter = tree.find(i);
   1041                 break;
   1042             }
   1043             tree.remove(iter);
   1044         }
   1045         GrAssert(0 == count[i]);
   1046         GrAssert(tree.findFirst(i) == tree.end());
   1047         GrAssert(tree.findLast(i) == tree.end());
   1048         GrAssert(tree.find(i) == tree.end());
   1049     }
   1050     // remove all of the 0 entries. (tests removing begin())
   1051     GrAssert(*tree.begin() == 0);
   1052     GrAssert(*(--tree.end()) == 99);
   1053     while (0 != tree.countOf(0)) {
   1054         --count[0];
   1055         tree.remove(tree.find(0));
   1056     }
   1057     GrAssert(0 == count[0]);
   1058     GrAssert(tree.findFirst(0) == tree.end());
   1059     GrAssert(tree.findLast(0) == tree.end());
   1060     GrAssert(tree.find(0) == tree.end());
   1061     GrAssert(0 < *tree.begin());
   1062 
   1063     // remove all the 99 entries (tests removing last()).
   1064     while (0 != tree.countOf(99)) {
   1065         --count[99];
   1066         tree.remove(tree.find(99));
   1067     }
   1068     GrAssert(0 == count[99]);
   1069     GrAssert(tree.findFirst(99) == tree.end());
   1070     GrAssert(tree.findLast(99) == tree.end());
   1071     GrAssert(tree.find(99) == tree.end());
   1072     GrAssert(99 > *(--tree.end()));
   1073     GrAssert(tree.last() == --tree.end());
   1074 
   1075     // Make sure iteration still goes through correct number of entries
   1076     // and is still sorted correctly.
   1077     c = 0;
   1078     for (Iter a = tree.begin(); tree.end() != a; ++a) {
   1079         Iter b = a;
   1080         ++b;
   1081         ++c;
   1082         GrAssert(b == tree.end() || *a <= *b);
   1083     }
   1084     GrAssert(c == tree.count());
   1085 
   1086     // repeat check that correct number of each entry is in the tree
   1087     // and iterates correctly both forward and backward.
   1088     for (int i = 0; i < 100; ++i) {
   1089         GrAssert(tree.countOf(i) == count[i]);
   1090         int c = 0;
   1091         Iter iter = tree.findFirst(i);
   1092         while (iter != tree.end() && *iter == i) {
   1093             ++c;
   1094             ++iter;
   1095         }
   1096         GrAssert(count[i] == c);
   1097         c = 0;
   1098         iter = tree.findLast(i);
   1099         if (iter != tree.end()) {
   1100             do {
   1101                 if (*iter == i) {
   1102                     ++c;
   1103                 } else {
   1104                     break;
   1105                 }
   1106                 if (iter != tree.begin()) {
   1107                     --iter;
   1108                 } else {
   1109                     break;
   1110                 }
   1111             } while (true);
   1112         }
   1113         GrAssert(count[i] == c);
   1114     }
   1115 
   1116     // remove all entries
   1117     while (!tree.empty()) {
   1118         tree.remove(tree.begin());
   1119     }
   1120 
   1121     // test reset on empty tree.
   1122     tree.reset();
   1123 }
   1124 
   1125 #endif
   1126