nsAttrValueOrString.h (2772B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 /* 8 * A wrapper to contain either an nsAttrValue or an nsAString. This is useful 9 * because constructing an nsAttrValue from an nsAString can be expensive when 10 * the buffer of the string is not shared. 11 * 12 * This treats nsAttrValueOrString(nullptr) as the empty string, 13 * to help with contexts where a null pointer denotes an empty value. 14 * 15 * Since a raw pointer to the passed-in string is kept, this class should only 16 * be used on the stack. 17 */ 18 19 #ifndef nsAttrValueOrString_h___ 20 #define nsAttrValueOrString_h___ 21 22 #include "nsAttrValue.h" 23 #include "nsString.h" 24 25 class MOZ_STACK_CLASS nsAttrValueOrString { 26 public: 27 explicit nsAttrValueOrString(const nsAString& aValue) 28 : mAttrValue(nullptr), mStringPtr(&aValue), mCheapString(nullptr) {} 29 30 explicit nsAttrValueOrString(const nsAString* aValue) 31 : mAttrValue(nullptr), mStringPtr(aValue), mCheapString(nullptr) {} 32 33 explicit nsAttrValueOrString(const nsAttrValue& aValue) 34 : mAttrValue(&aValue), mStringPtr(nullptr), mCheapString(nullptr) {} 35 36 explicit nsAttrValueOrString(const nsAttrValue* aValue) 37 : mAttrValue(aValue), mStringPtr(nullptr), mCheapString(nullptr) {} 38 39 void ResetToAttrValue(const nsAttrValue& aValue) { 40 mAttrValue = &aValue; 41 mStringPtr = nullptr; 42 // No need to touch mCheapString here. If we need to use it, we will reset 43 // it to the rigthe value anyway. 44 } 45 46 /** 47 * Returns a reference to the string value of the contents of this object. 48 * 49 * When this object points to a string or an nsAttrValue of string or atom 50 * type this should be fairly cheap. Other nsAttrValue types will be 51 * serialized the first time this is called and cached from thereon. 52 */ 53 const nsAString& String() const; 54 55 /** 56 * Compares the string representation of this object with the string 57 * representation of an nsAttrValue. 58 */ 59 bool EqualsAsStrings(const nsAttrValue& aOther) const { 60 if (mStringPtr) { 61 return aOther.Equals(*mStringPtr, eCaseMatters); 62 } 63 return aOther.EqualsAsStrings(*mAttrValue); 64 } 65 66 /* 67 * Returns true if the value stored is empty 68 */ 69 bool IsEmpty() const { 70 if (mStringPtr) { 71 return mStringPtr->IsEmpty(); 72 } 73 if (mAttrValue) { 74 return mAttrValue->IsEmptyString(); 75 } 76 return true; 77 } 78 79 protected: 80 const nsAttrValue* mAttrValue; 81 mutable const nsAString* mStringPtr; 82 mutable nsCheapString mCheapString; 83 }; 84 85 #endif // nsAttrValueOrString_h___