__sso_allocator 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // The LLVM Compiler Infrastructure
  5. //
  6. // This file is dual licensed under the MIT and the University of Illinois Open
  7. // Source Licenses. See LICENSE.TXT for details.
  8. //
  9. //===----------------------------------------------------------------------===//
  10. #ifndef _LIBCPP___SSO_ALLOCATOR
  11. #define _LIBCPP___SSO_ALLOCATOR
  12. #include <__config>
  13. #include <type_traits>
  14. #include <new>
  15. #include <__undef___deallocate>
  16. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  17. #pragma GCC system_header
  18. #endif
  19. _LIBCPP_BEGIN_NAMESPACE_STD
  20. template <class _Tp, size_t _Np> class _LIBCPP_HIDDEN __sso_allocator;
  21. template <size_t _Np>
  22. class _LIBCPP_HIDDEN __sso_allocator<void, _Np>
  23. {
  24. public:
  25. typedef const void* const_pointer;
  26. typedef void value_type;
  27. };
  28. template <class _Tp, size_t _Np>
  29. class _LIBCPP_HIDDEN __sso_allocator
  30. {
  31. typename aligned_storage<sizeof(_Tp) * _Np>::type buf_;
  32. bool __allocated_;
  33. public:
  34. typedef size_t size_type;
  35. typedef _Tp* pointer;
  36. typedef _Tp value_type;
  37. _LIBCPP_INLINE_VISIBILITY __sso_allocator() throw() : __allocated_(false) {}
  38. _LIBCPP_INLINE_VISIBILITY __sso_allocator(const __sso_allocator&) throw() : __allocated_(false) {}
  39. template <class _Up> _LIBCPP_INLINE_VISIBILITY __sso_allocator(const __sso_allocator<_Up, _Np>&) throw()
  40. : __allocated_(false) {}
  41. private:
  42. __sso_allocator& operator=(const __sso_allocator&);
  43. public:
  44. _LIBCPP_INLINE_VISIBILITY pointer allocate(size_type __n, typename __sso_allocator<void, _Np>::const_pointer = 0)
  45. {
  46. if (!__allocated_ && __n <= _Np)
  47. {
  48. __allocated_ = true;
  49. return (pointer)&buf_;
  50. }
  51. return static_cast<pointer>(_VSTD::__allocate(__n * sizeof(_Tp)));
  52. }
  53. _LIBCPP_INLINE_VISIBILITY void deallocate(pointer __p, size_type)
  54. {
  55. if (__p == (pointer)&buf_)
  56. __allocated_ = false;
  57. else
  58. _VSTD::__deallocate(__p);
  59. }
  60. _LIBCPP_INLINE_VISIBILITY size_type max_size() const throw() {return size_type(~0) / sizeof(_Tp);}
  61. _LIBCPP_INLINE_VISIBILITY
  62. bool operator==(__sso_allocator& __a) const {return &buf_ == &__a.buf_;}
  63. _LIBCPP_INLINE_VISIBILITY
  64. bool operator!=(__sso_allocator& __a) const {return &buf_ != &__a.buf_;}
  65. };
  66. _LIBCPP_END_NAMESPACE_STD
  67. #endif // _LIBCPP___SSO_ALLOCATOR