txStack.h (2415B)
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* This Source Code Form is subject to the terms of the Mozilla Public 3 * License, v. 2.0. If a copy of the MPL was not distributed with this 4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 5 6 #ifndef txStack_h___ 7 #define txStack_h___ 8 9 #include "nsTArray.h" 10 11 class txStack : private nsTArray<void*> { 12 public: 13 /** 14 * Returns the specified object from the top of this stack, 15 * without removing it from the stack. 16 * 17 * @return a pointer to the object that is the top of this stack. 18 */ 19 inline void* peek() { 20 NS_ASSERTION(!isEmpty(), "peeking at empty stack"); 21 return !isEmpty() ? ElementAt(Length() - 1) : nullptr; 22 } 23 24 /** 25 * Adds the specified object to the top of this stack. 26 * 27 * @param obj a pointer to the object that is to be added to the 28 * top of this stack. 29 */ 30 inline void push(void* aObject) { AppendElement(aObject); } 31 32 /** 33 * Removes and returns the specified object from the top of this 34 * stack. 35 * 36 * @return a pointer to the object that was the top of this stack. 37 */ 38 inline void* pop() { 39 void* object = nullptr; 40 NS_ASSERTION(!isEmpty(), "popping from empty stack"); 41 if (!isEmpty()) { 42 object = PopLastElement(); 43 } 44 return object; 45 } 46 47 /** 48 * Returns true if there are no objects in the stack. 49 * 50 * @return true if there are no objects in the stack. 51 */ 52 inline bool isEmpty() { return IsEmpty(); } 53 54 /** 55 * Returns the number of elements in the Stack. 56 * 57 * @return the number of elements in the Stack. 58 */ 59 inline int32_t size() { return Length(); } 60 61 private: 62 friend class txStackIterator; 63 }; 64 65 class txStackIterator { 66 public: 67 /** 68 * Creates an iterator for the given stack. 69 * 70 * @param aStack the stack to create an iterator for. 71 */ 72 inline explicit txStackIterator(txStack* aStack) 73 : mStack(aStack), mPosition(0) {} 74 75 /** 76 * Returns true if there is more objects on the stack. 77 * 78 * @return . 79 */ 80 inline bool hasNext() { return (mPosition < mStack->Length()); } 81 82 /** 83 * Returns the next object pointer from the stack. 84 * 85 * @return . 86 */ 87 inline void* next() { 88 if (mPosition == mStack->Length()) { 89 return nullptr; 90 } 91 return mStack->ElementAt(mPosition++); 92 } 93 94 private: 95 txStack* mStack; 96 uint32_t mPosition; 97 }; 98 99 #endif /* txStack_h___ */