1 // Copyright 2016 The PDFium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com 6 7 #ifndef CORE_FXCRT_STRING_DATA_TEMPLATE_H_ 8 #define CORE_FXCRT_STRING_DATA_TEMPLATE_H_ 9 10 #include <stddef.h> 11 #include <stdint.h> 12 13 namespace fxcrt { 14 15 template <typename CharType> 16 class StringDataTemplate { 17 public: 18 static StringDataTemplate* Create(size_t nLen); 19 static StringDataTemplate* Create(const CharType* pStr, size_t nLen); 20 Retain()21 void Retain() { ++m_nRefs; } 22 void Release(); 23 CanOperateInPlace(size_t nTotalLen)24 bool CanOperateInPlace(size_t nTotalLen) const { 25 return m_nRefs <= 1 && nTotalLen <= m_nAllocLength; 26 } 27 28 void CopyContents(const StringDataTemplate& other); 29 void CopyContents(const CharType* pStr, size_t nLen); 30 void CopyContentsAt(size_t offset, const CharType* pStr, size_t nLen); 31 32 // To ensure ref counts do not overflow, consider the worst possible case: 33 // the entire address space contains nothing but pointers to this object. 34 // Since the count increments with each new pointer, the largest value is 35 // the number of pointers that can fit into the address space. The size of 36 // the address space itself is a good upper bound on it. 37 intptr_t m_nRefs = 0; 38 39 // These lengths are in terms of number of characters, not bytes, and do not 40 // include the terminating NUL character, but the underlying buffer is sized 41 // to be capable of holding it. 42 size_t m_nDataLength; 43 const size_t m_nAllocLength; 44 45 // Not really 1, variable size. 46 CharType m_String[1]; 47 48 private: 49 StringDataTemplate(size_t dataLen, size_t allocLen); 50 ~StringDataTemplate() = delete; 51 }; 52 53 extern template class StringDataTemplate<char>; 54 extern template class StringDataTemplate<wchar_t>; 55 56 } // namespace fxcrt 57 58 using fxcrt::StringDataTemplate; 59 60 #endif // CORE_FXCRT_STRING_DATA_TEMPLATE_H_ 61