libcruft-util/pointer.hpp

80 lines
2.2 KiB
C++
Raw Normal View History

2015-11-17 17:21:14 +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-17 17:21:14 +11:00
*
2017-08-30 15:38:13 +10:00
* Copyright 2011-2017 Danny Robson <danny@nerdcruft.net>
2015-11-17 17:21:14 +11:00
*/
2017-08-30 15:38:13 +10:00
#ifndef CRUFT_UTIL_POINTER_HPP
#define CRUFT_UTIL_POINTER_HPP
2015-11-17 17:21:14 +11:00
#include "view.hpp"
2015-11-17 17:21:14 +11:00
#include <cstddef>
#include <cstdint>
namespace util {
///////////////////////////////////////////////////////////////////////////
2017-08-30 15:38:13 +10:00
/// round the pointer upwards to satisfy the provided alignment
2015-11-17 17:21:14 +11:00
template <typename T>
2017-08-30 15:38:13 +10:00
constexpr T*
2015-11-17 17:21:14 +11:00
align (T *_ptr, size_t alignment)
{
2017-08-30 15:38:13 +10:00
// we perform this as two steps to avoid unnecessarily incrementing when
// remainder is zero.
2015-11-17 17:21:14 +11:00
auto ptr = reinterpret_cast<uintptr_t> (_ptr);
if (ptr % alignment)
ptr += alignment - ptr % alignment;
return reinterpret_cast<T*> (ptr);
}
2016-03-11 09:40:12 +11:00
///////////////////////////////////////////////////////////////////////////
template <typename ValueT>
constexpr util::view<ValueT*>
align (util::view<ValueT*> value, size_t alignment)
{
return {
align (value.begin (), alignment),
value.end ()
};
}
2017-08-30 15:38:13 +10:00
///------------------------------------------------------------------------
/// round the pointer upwards to satisfy the provided alignment
constexpr inline uintptr_t
2016-03-11 09:40:12 +11:00
align (uintptr_t ptr, size_t alignment)
{
2017-08-30 15:38:13 +10:00
// we perform this as two steps to avoid unnecessarily incrementing when
// remainder is zero.
if (ptr % alignment)
ptr += alignment - ptr % alignment;
return ptr;
}
///------------------------------------------------------------------------
/// round the pointer upwards to the nearest valid alignment for T
template <typename T>
constexpr auto
align (T *t)
{
return align (t, alignof (T));
}
///------------------------------------------------------------------------
/// round the pointer upwards to the nearest valid alignment for T
template <typename T>
constexpr auto
align (uintptr_t ptr)
{
return align (ptr, alignof (T));
2016-03-11 09:40:12 +11:00
}
2015-11-17 17:21:14 +11:00
}
#endif