From 885b0b4669a53eecebd01ec31e87a0690f0e9d3b Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Wed, 30 Aug 2017 15:38:13 +1000 Subject: [PATCH] pointer: add some comments... --- pointer.hpp | 44 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/pointer.hpp b/pointer.hpp index c5ef3b13..bd55ccfc 100644 --- a/pointer.hpp +++ b/pointer.hpp @@ -11,11 +11,11 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * Copyright 2011 Danny Robson + * Copyright 2011-2017 Danny Robson */ -#ifndef __POINTER_HPP -#define __POINTER_HPP +#ifndef CRUFT_UTIL_POINTER_HPP +#define CRUFT_UTIL_POINTER_HPP #include #include @@ -23,10 +23,13 @@ namespace util { /////////////////////////////////////////////////////////////////////////// + /// round the pointer upwards to satisfy the provided alignment template - 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 (_ptr); if (ptr % alignment) ptr += alignment - ptr % alignment; @@ -34,13 +37,36 @@ namespace util { } - //------------------------------------------------------------------------- - inline uintptr_t + ///------------------------------------------------------------------------ + /// round the pointer upwards to satisfy the provided alignment + constexpr inline uintptr_t align (uintptr_t ptr, size_t alignment) { - return reinterpret_cast ( - align (reinterpret_cast (ptr), 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 + constexpr auto + align (T *t) + { + return align (t, alignof (T)); + } + + + ///------------------------------------------------------------------------ + /// round the pointer upwards to the nearest valid alignment for T + template + constexpr auto + align (uintptr_t ptr) + { + return align (ptr, alignof (T)); } }