What is the Cast Module?
The Cast module provides checked type conversions to prevent silent truncation and overflow. Instead of C-style casts (which truncate silently), these functions detect out-of-range values and return status codes.
Key idea:** Know when data is lost. Silent truncation is a security hole.
Quick Start
#include "rte/cast/rte_cast.h"
int32_t large = 100000;
int16_t small = (int16_t)large;
int32_t large = 100000;
int16_t small;
log_error("Value %d too large for int16_t", large);
return rc;
}
rte_status_t
Common result/status codes.
@ RTE_STATUS_INVALID_PARAM
Available Conversions
Upcasting (safe):**
- int8 → int16, int32, int64
- uint8 → uint16, uint32, uint64
- int16 → int32, int64
- uint16 → uint32, uint64
- etc.
Always safe (no overflow possible)
Downcasting (checked):**
- int32 → int16, int8
- uint32 → uint16, uint8
- Returns INVALID_PARAM if out of range
Value only modified if success
Signed to Unsigned:**
- int32 → uint32 (negative → error)
- int8 → uint8 (negative → error)
Zero and positive values OK
Floating Point (if supported):**
- float → int32 (checks for infinity, NaN)
- double → float (checks for overflow)
- Non-finite values return error
Practical Examples
Example 1: ADC Reading Conversion
uint16_t adc_raw = read_adc();
int16_t temp_units;
rte_status_t rc = rte_cast_uint16_to_int16(adc_raw, &temp_units);
log_error("ADC value out of range");
}
#define RTE_SAFESTATE(level, reason)
Explicitly enters the given safe-state level with a reason code, capturing the call site automaticall...
@ RTE_SAFESTATE_LEVEL_SAFE
Example 2: CAN ID Conversion
uint32_t can_id = receive_can_id();
if (can_id > 0x1FFFFFFF) {
log_error("Invalid CAN ID: 0x%x", can_id);
}
Example 3: Pointer to Integer Conversion
void *ptr = get_pointer();
uint32_t addr32;
log_error("Pointer too large for uint32_t");
}
Best Practices
- Always Use Checked Casts for Downcasting
- Never (type)value for size reduction
- Always check with rte_cast_*
- Handle errors, don't ignore them
- Upcasting is Safe
- int8 → int32: safe (no loss)
- Can use direct cast if confident
- Or use cast functions for consistency
- Handle Errors Appropriately
- For safety-critical: trigger safe-state
- For non-critical: log warning
- Always have error path
- Document Assumptions
- Comment why cast is safe
- Document expected ranges
- Help future maintainers
See Also