/* * 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 */ #pragma once #include #include namespace cruft { /////////////////////////////////////////////////////////////////////////// /// round the pointer upwards to satisfy the provided alignment constexpr inline uintptr_t align_up (uintptr_t ptr, size_t alignment) { // we perform this as two steps to avoid unnecessarily incrementing when // remainder is zero. if (auto mod = ptr % alignment; mod) ptr += alignment - mod; return ptr; } /////////////////////////////////////////////////////////////////////////// /// round the pointer upwards to satisfy the provided alignment template constexpr T* align_up (T *_ptr, size_t alignment) { // we perform this as two steps to avoid unnecessarily incrementing when // remainder is zero. return reinterpret_cast( align_up (reinterpret_cast (_ptr), alignment) ); } ///------------------------------------------------------------------------ /// round the pointer upwards to the nearest valid alignment for T template constexpr auto align_up (T *t) { return align_up (t, alignof (T)); } ///------------------------------------------------------------------------ /// round the pointer upwards to the nearest valid alignment for T template constexpr auto align_up (uintptr_t ptr) { return align_up (ptr, alignof (T)); } /////////////////////////////////////////////////////////////////////////// constexpr inline uintptr_t align_down (uintptr_t ptr, size_t alignment) { return ptr - ptr % alignment; } //------------------------------------------------------------------------- template constexpr T* align_down (T *ptr, size_t alignment) { return reinterpret_cast ( align_down (reinterpret_cast (ptr), alignment) ); } }