Skip to content

ethercat alignment check for reinterpret cast #533

@jbbjarnason

Description

@jbbjarnason
          @jbbjarnason You are missing alignment check for reinterpret cast, on x86_64 it will work unaligned but will be slow, on some older arms it will just crash, on modern >= armv7 unaligned should work but same as on x64 very slow

And I would use some span_cast as below to avoid mistakes with size

template<typename T, typename... Args>
concept same_as_any_of = std::disjunction_v<std::is_same<T, Args>...>;

template<typename T>
concept byte_like = same_as_any_of<T, std::byte, char, uint8_t>;

template<typename T>
concept trivially_copyable_non_byte = std::is_trivially_copyable_v<T> && !byte_like<T>;

template<byte_like SrcType, trivially_copyable_non_byte DstType>
[[nodiscard]] 
constexpr auto span_cast(std::span<SrcType> src) -> std::span<const DstType> {
    assert((reinterpret_cast<std::uintptr_t>(src.data()) % alignof(DstType) == 0) && "Data must be aligned to the destination type");
    std::size_t dst_size = src.size_bytes() / sizeof(DstType);
    return {reinterpret_cast<const DstType*>(src.data()), dst_size};
}

Originally posted by @arturbac in #524 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions