Vanetza
 
Loading...
Searching...
No Matches
byte_buffer.hpp
1#ifndef BYTE_BUFFER_HPP_7NOEQO4F
2#define BYTE_BUFFER_HPP_7NOEQO4F
3
4#include <cstdint>
5#include <type_traits>
6#include <vector>
7
8namespace vanetza
9{
10
11typedef std::vector<uint8_t> ByteBuffer;
12
13/**
14 * Cast byte buffer to a POD object
15 * \param buffer byte buffer containing requested object
16 * \return pointer to object or nullptr if cast is impossible
17 */
18template<typename MASK>
19MASK* buffer_cast(ByteBuffer& buffer)
20{
21 static_assert(std::is_pod<MASK>::value, "MASK has to be POD data type");
22 static_assert(std::is_object<MASK>::value, "MASK has to be an object");
23
24 MASK* mask = nullptr;
25 if (sizeof(MASK) <= buffer.size()) {
26 mask = reinterpret_cast<MASK*>(&buffer[0]);
27 }
28 return mask;
29}
30
31template<typename MASK>
32const MASK* buffer_cast(const ByteBuffer& buffer)
33{
34 // const_cast is safe, const qualifier is added to return type
35 return buffer_cast<MASK>(const_cast<ByteBuffer&>(buffer));
36}
37
38/**
39 * Create byte buffer with copy of POD object
40 * \param obj POD object
41 * \return ByteBuffer object with copy
42 */
43template<class T>
44ByteBuffer buffer_copy(const T& object)
45{
46 static_assert(std::is_pod<T>::value, "T has to be POD data type");
47 auto ptr = reinterpret_cast<const uint8_t*>(&object);
48 return ByteBuffer(ptr, ptr + sizeof(T));
49}
50
51} // namespace vanetza
52
53#endif /* BYTE_BUFFER_HPP_7NOEQO4F */
54