Skip to content

Instantly share code, notes, and snippets.

@sticilface
Created March 21, 2019 16:28
Show Gist options
  • Save sticilface/84440593f2190d89711b07352d276387 to your computer and use it in GitHub Desktop.
Save sticilface/84440593f2190d89711b07352d276387 to your computer and use it in GitHub Desktop.
custom PSRAM STL allocator
template <typename T>
class spram_allocator
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
spram_allocator(){}
~spram_allocator(){}
template <class U> struct rebind { typedef spram_allocator<U> other; };
template <class U> spram_allocator(const spram_allocator<U>&){}
pointer address(reference x) const {return &x;}
const_pointer address(const_reference x) const {return &x;}
size_type max_size() const throw() {return size_t(-1) / sizeof(value_type);}
pointer allocate(size_type n, const void * hint = 0)
{
return static_cast<pointer>(ps_malloc(n*sizeof(T)));
}
void deallocate(pointer p, size_type n)
{
free(p);
}
template< class U, class... Args >
void construct( U* p, Args&&... args )
{
::new((void *) p ) U(std::forward<Args>(args)...);
}
void destroy(pointer p)
{
p->~T();
}
};
@kitecraft
Copy link

Thank you.

For others:
This works well for putting things like std::vector into PSRam. But, if you want to use it with std::string, you need to add the following to the bottom of the file:

template<class T, class U>
bool operator==(const spram_allocator&, const spram_allocator&) { return true; }

template<class T, class U>
bool operator!=(const spram_allocator&, const spram_allocator&) { return false; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment