libcruft-util/pointer.hpp
Danny Robson f6056153e3 rename root namespace from util to cruft
This places, at long last, the core library code into the same namespace
as the extended library code.
2018-08-05 14:42:02 +10:00

80 lines
2.2 KiB
C++

/*
* 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/.
*
* Copyright 2011-2017 Danny Robson <danny@nerdcruft.net>
*/
#ifndef CRUFT_UTIL_POINTER_HPP
#define CRUFT_UTIL_POINTER_HPP
#include "view.hpp"
#include <cstddef>
#include <cstdint>
namespace cruft {
///////////////////////////////////////////////////////////////////////////
/// round the pointer upwards to satisfy the provided alignment
template <typename T>
constexpr T*
align (T *_ptr, size_t alignment)
{
// we perform this as two steps to avoid unnecessarily incrementing when
// remainder is zero.
auto ptr = reinterpret_cast<uintptr_t> (_ptr);
if (ptr % alignment)
ptr += alignment - ptr % alignment;
return reinterpret_cast<T*> (ptr);
}
///////////////////////////////////////////////////////////////////////////
template <typename ValueT>
constexpr cruft::view<ValueT*>
align (cruft::view<ValueT*> value, size_t alignment)
{
return {
align (value.begin (), alignment),
value.end ()
};
}
///------------------------------------------------------------------------
/// round the pointer upwards to satisfy the provided alignment
constexpr inline uintptr_t
align (uintptr_t ptr, size_t alignment)
{
// 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));
}
}
#endif