2015-11-13 17:17:37 +11:00
|
|
|
/*
|
2018-08-04 15:14:06 +10:00
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
2015-11-13 17:17:37 +11:00
|
|
|
*
|
2018-05-10 13:53:06 +10:00
|
|
|
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
|
2015-11-13 17:17:37 +11:00
|
|
|
*/
|
|
|
|
|
2018-12-19 17:55:24 +11:00
|
|
|
#pragma once
|
2015-11-13 17:17:37 +11:00
|
|
|
|
2018-12-19 17:55:24 +11:00
|
|
|
#include "../view.hpp"
|
2018-05-10 12:50:37 +10:00
|
|
|
|
2015-11-13 17:17:37 +11:00
|
|
|
#include <cstddef>
|
2018-08-13 14:51:33 +10:00
|
|
|
#include <cstdlib>
|
|
|
|
|
|
|
|
#if defined(PLATFORM_WIN32)
|
|
|
|
inline int
|
|
|
|
posix_memalign (void **ptr, std::size_t align, std::size_t size)
|
|
|
|
{
|
|
|
|
*ptr = _aligned_malloc (size, align);
|
|
|
|
return *ptr ? 0 : errno;
|
|
|
|
}
|
|
|
|
#endif
|
2015-11-13 17:17:37 +11:00
|
|
|
|
2018-12-19 17:55:24 +11:00
|
|
|
namespace cruft::alloc {
|
2015-11-13 17:17:37 +11:00
|
|
|
class malloc {
|
|
|
|
public:
|
2018-05-10 13:53:06 +10:00
|
|
|
template <typename T>
|
2018-08-05 14:42:02 +10:00
|
|
|
cruft::view<T*> allocate (size_t count)
|
2018-05-10 13:53:06 +10:00
|
|
|
{
|
|
|
|
return {
|
|
|
|
reinterpret_cast<T*> (malloc (sizeof (T) * count)),
|
|
|
|
count
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename T>
|
2018-08-05 14:42:02 +10:00
|
|
|
cruft::view<T*>
|
2018-05-10 13:53:06 +10:00
|
|
|
allocate (size_t count, size_t align)
|
|
|
|
{
|
|
|
|
void* ptr;
|
2023-07-21 14:19:39 +10:00
|
|
|
auto err = posix_memalign (&ptr, align, sizeof (T) * count);
|
|
|
|
if (err or !ptr)
|
2018-05-10 13:53:06 +10:00
|
|
|
throw std::bad_alloc ();
|
|
|
|
|
|
|
|
return { reinterpret_cast<T*> (ptr), count };
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
void
|
2018-08-05 14:42:02 +10:00
|
|
|
deallocate (cruft::view<std::byte*> ptr)
|
2018-05-10 13:53:06 +10:00
|
|
|
{
|
|
|
|
::free (ptr.data ());
|
|
|
|
}
|
2015-11-13 17:17:37 +11:00
|
|
|
};
|
2016-10-10 17:58:59 +11:00
|
|
|
}
|