Add BytePointer to help with pointer conversions
This behaves mostly like a pointer, but pointer maths works in bytes, not the native object size. It avoids casting to char* and back when doing byte-based pointer math, making the code easier to read. Change-Id: I6a8681a398345f0c7d419a2cfe7244d972ffa62f Reviewed-on: https://review.haiku-os.org/c/1086 Reviewed-by: waddlesplash <[email protected]>
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2019, Adrien Destugues, [email protected].
|
||||
* Distributed under the terms of the MIT License.
|
||||
*/
|
||||
#ifndef _BYTE_POINTER_H
|
||||
#define _BYTE_POINTER_H
|
||||
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
|
||||
// Behaves like a char* pointer, but -> and & return the right pointed type.
|
||||
// Assumes the offsets passed to + and += maintain the alignment for the type.
|
||||
template<class T> struct BytePointer {
|
||||
char* address;
|
||||
|
||||
BytePointer(void* base) { address = (char*)base; }
|
||||
|
||||
T* operator&() { return reinterpret_cast<T*>(address); }
|
||||
T* operator->() { return reinterpret_cast<T*>(address); }
|
||||
void operator+=(size_t offset) { address += offset; }
|
||||
char* operator+(size_t offset) const { return address + offset; }
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user