1 // Copyright 2019 PDFium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef CORE_FXCRT_FX_MEMORY_WRAPPERS_H_ 6 #define CORE_FXCRT_FX_MEMORY_WRAPPERS_H_ 7 8 #include <limits> 9 #include <type_traits> 10 #include <utility> 11 12 #include "core/fxcrt/fx_memory.h" 13 14 // Used with std::unique_ptr to FX_Free raw memory. 15 struct FxFreeDeleter { operatorFxFreeDeleter16 inline void operator()(void* ptr) const { FX_Free(ptr); } 17 }; 18 19 // Used with std::vector<> to put purely numeric vectors into 20 // the same "general" parition used by FX_Alloc(). Otherwise, 21 // replacing FX_Alloc/FX_Free pairs with std::vector<> may undo 22 // some of the nice segregation that we get from partition alloc. 23 template <class T> 24 struct FxAllocAllocator { 25 public: 26 static_assert(std::is_arithmetic<T>::value, 27 "Only numeric types allowed in this partition"); 28 29 using value_type = T; 30 using pointer = T*; 31 using const_pointer = const T*; 32 using reference = T&; 33 using const_reference = const T&; 34 using size_type = size_t; 35 using difference_type = ptrdiff_t; 36 37 template <class U> 38 struct rebind { 39 using other = FxAllocAllocator<U>; 40 }; 41 42 FxAllocAllocator() noexcept = default; 43 FxAllocAllocator(const FxAllocAllocator& other) noexcept = default; 44 ~FxAllocAllocator() = default; 45 46 template <typename U> FxAllocAllocatorFxAllocAllocator47 FxAllocAllocator(const FxAllocAllocator<U>& other) noexcept {} 48 addressFxAllocAllocator49 pointer address(reference x) const noexcept { return &x; } addressFxAllocAllocator50 const_pointer address(const_reference x) const noexcept { return &x; } 51 pointer allocate(size_type n, const void* hint = 0) { 52 return static_cast<pointer>(FX_AllocOrDie(n, sizeof(value_type))); 53 } deallocateFxAllocAllocator54 void deallocate(pointer p, size_type n) { FX_Free(p); } max_sizeFxAllocAllocator55 size_type max_size() const noexcept { 56 return std::numeric_limits<size_type>::max() / sizeof(value_type); 57 } 58 59 template <class U, class... Args> constructFxAllocAllocator60 void construct(U* p, Args&&... args) { 61 new (reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); 62 } 63 64 template <class U> destroyFxAllocAllocator65 void destroy(U* p) { 66 p->~U(); 67 } 68 69 // There's no state, so they are all the same, 70 bool operator==(const FxAllocAllocator& that) { return true; } 71 bool operator!=(const FxAllocAllocator& that) { return false; } 72 }; 73 74 #endif // CORE_FXCRT_FX_MEMORY_WRAPPERS_H_ 75