| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2010 The Chromium 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 // Implement a very basic memory allocator that make direct system calls |
| 6 // instead of relying on libc. |
| 7 // This allocator is not thread-safe. |
| 8 |
| 9 #ifndef ALLOCATOR_H__ |
| 10 #define ALLOCATOR_H__ |
| 11 |
| 12 #include <cstddef> |
| 13 |
| 14 namespace playground { |
| 15 |
| 16 class SystemAllocatorHelper { |
| 17 protected: |
| 18 static void *sys_allocate(size_t size); |
| 19 static void sys_deallocate(void* p, size_t size); |
| 20 }; |
| 21 |
| 22 template <class T> |
| 23 class SystemAllocator : SystemAllocatorHelper { |
| 24 public: |
| 25 typedef T value_type; |
| 26 typedef T* pointer; |
| 27 typedef const T* const_pointer; |
| 28 typedef T& reference; |
| 29 typedef const T& const_reference; |
| 30 typedef size_t size_type; |
| 31 typedef std::ptrdiff_t difference_type; |
| 32 |
| 33 template <class U> |
| 34 struct rebind { |
| 35 typedef SystemAllocator<U> other; |
| 36 }; |
| 37 |
| 38 pointer address(reference value) const { |
| 39 return &value; |
| 40 } |
| 41 |
| 42 const_pointer address(const_reference value) const { |
| 43 return &value; |
| 44 } |
| 45 |
| 46 SystemAllocator() throw() { } |
| 47 SystemAllocator(const SystemAllocator& src) throw() { } |
| 48 template <class U> SystemAllocator(const SystemAllocator<U>& src) throw() { } |
| 49 ~SystemAllocator() throw() { } |
| 50 |
| 51 size_type max_size() const throw() { |
| 52 return (1 << 30) / sizeof(T); |
| 53 } |
| 54 |
| 55 pointer allocate(size_type num, const void* = 0) { |
| 56 if (num > max_size()) { |
| 57 return NULL; |
| 58 } |
| 59 return (pointer)sys_allocate(num * sizeof(T)); |
| 60 } |
| 61 |
| 62 void construct(pointer p, const T& value) { |
| 63 new(reinterpret_cast<void *>(p))T(value); |
| 64 } |
| 65 |
| 66 void destroy(pointer p) { |
| 67 p->~T(); |
| 68 } |
| 69 |
| 70 void deallocate(pointer p, size_type num) { |
| 71 sys_deallocate(p, num * sizeof(T)); |
| 72 } |
| 73 }; |
| 74 |
| 75 template <class T1, class T2> |
| 76 bool operator== (const SystemAllocator<T1>&, const SystemAllocator<T2>&) |
| 77 throw() { |
| 78 return true; |
| 79 } |
| 80 template <class T1, class T2> |
| 81 bool operator!= (const SystemAllocator<T1>&, const SystemAllocator<T2>&) |
| 82 throw() { |
| 83 return false; |
| 84 } |
| 85 |
| 86 } // namespace |
| 87 |
| 88 #endif // ALLOCATOR_H__ |
| OLD | NEW |