type_utils

Overview

A utility class to encapsulate the cast to a single location. It serves as a utility for working with pointers, raw memory, and type casting in a safe and generic manner.

Type type_utils offers a comprehensive set of functions for handling type conversions. These functions improve clarity of code.

Usage

The usage guidelines and pre-condition apply for type_utils:

Usage guidance

Contiguous Memory
The cast_to_type and cast_const_to_type functions assume that the raw data pointers (uint8_t*) point to continuous memory, it could vector, deque, array of type T(underlying memory is continuous and equally spaced of size of one object of given type T). The optional index parameter (idx) allows access to a specific object in the array.

Destruction
The destroy function assumes that it is safe to call the destructor of an object using placement new and explicit destructor invocation.”

Pre-Condition

Pointer Initialization
Raw data pointers (uint8_t*) must be properly initialized and should point to valid memory locations.”

Examples

The following example shows the usage of cast_to_type() function:

int16_t data[4] = {55, 55 , 35, 25};
uint8_t* raw_data = reinterpret_cast<uint8_t*>(data);
estd::type_utils<int>::cast_to_type(raw_data, 2);

The next piece of code shows the usage of cast_to_raw() function:

int value = 42;
int* int_ptr = &value;
estd::type_utils<int>::cast_to_raw(int_ptr);
// Now, you can manipulate raw_ptr to read or modify the underlying bytes.

The following example shows the usage of cast_const_to_type() function:

int16_t data[4] = {55, 55 , 35, 25};
uint8_t* raw_data = reinterpret_cast<uint8_t*>(data);
estd::type_utils<uint16_t>::cast_const_to_type(raw_data, 2);
// *result = 12;     //Cannot modify the value, since its a const data

The next piece of code shows the usage of cast_from_void() function:

int value = 42;
void* void_ptr = &value;
estd::type_utils<int>::cast_from_void(void_ptr);
// Now, you can use int_ptr as a pointer to an integer.

The following example shows the usage of const_cast_from_void() function:

int data = 10;
void* vPtr = &data;
estd::type_utils<int>::const_cast_from_void(vPtr);
//  *cPtr = 20;     //Cannot modify the value, since its a const data
// Now, you have a const int pointer.

The next piece of code shows the usage of cast_to_void() function:

int value = 42;
int* int_ptr = &value;
estd::type_utils<int>::cast_to_void(int_ptr);
// Now, void_ptr can be used to store or pass the integer pointer.

The following example shows the usage of const_cast_to_void() function:

const int value = 42;
const int* int_ptr = &value;
estd::type_utils<int>::const_cast_to_void(int_ptr);
// Now, void_ptr can be used to store or pass the integer pointer.