xref: /aosp_15_r20/external/pdfium/core/fxcrt/small_buffer.h (revision 3ac0a46f773bac49fa9476ec2b1cf3f8da5ec3a4)
1 // Copyright 2017 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_SMALL_BUFFER_H_
8 #define CORE_FXCRT_SMALL_BUFFER_H_
9 
10 #include <string.h>
11 
12 #include <array>
13 #include <memory>
14 
15 #include "core/fxcrt/fx_memory_wrappers.h"
16 
17 namespace fxcrt {
18 
19 template <class T, size_t FixedSize>
20 class SmallBuffer {
21  public:
SmallBuffer(size_t actual_size)22   explicit SmallBuffer(size_t actual_size) : m_pSize(actual_size) {
23     if (actual_size > FixedSize) {
24       m_pDynamicData.reset(FX_Alloc(T, actual_size));
25       return;
26     }
27     if (actual_size)
28       memset(m_FixedData.data(), 0, sizeof(T) * actual_size);
29   }
size()30   size_t size() const { return m_pSize; }
data()31   T* data() {
32     return m_pDynamicData ? m_pDynamicData.get() : m_FixedData.data();
33   }
begin()34   T* begin() { return data(); }
end()35   T* end() { return begin() + size(); }
36 
37   // Callers shouldn't need to know these details.
fixed_for_test()38   T* fixed_for_test() { return m_FixedData.data(); }
dynamic_for_test()39   T* dynamic_for_test() { return m_pDynamicData.get(); }
40 
41  private:
42   const size_t m_pSize;
43   std::unique_ptr<T, FxFreeDeleter> m_pDynamicData;
44   std::array<T, FixedSize> m_FixedData;
45 };
46 
47 }  // namespace fxcrt
48 
49 #endif  // CORE_FXCRT_SMALL_BUFFER_H_
50