uc_bit_array_copy.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2015 Pavel Kirienko <pavel.kirienko@gmail.com>
3  */
4 
6 #include <climits>
7 #include <cstring>
8 #include <cstddef>
9 
10 namespace uavcan
11 {
12 void bitarrayCopy(const unsigned char* src, std::size_t src_offset, std::size_t src_len,
13  unsigned char* dst, std::size_t dst_offset)
14 {
15  /*
16  * Should never be called on a zero-length buffer. The caller will also ensure that the bit
17  * offsets never exceed one byte.
18  */
19 
20  UAVCAN_ASSERT(src_len > 0U);
21  UAVCAN_ASSERT(src_offset < 8U && dst_offset < 8U);
22 
23  const std::size_t last_bit = src_offset + src_len;
24  while (last_bit - src_offset)
25  {
26  const uint8_t src_bit_offset = src_offset % 8U;
27  const uint8_t dst_bit_offset = dst_offset % 8U;
28 
29  // The number of bits to copy
30  const uint8_t max_offset = uavcan::max(src_bit_offset, dst_bit_offset);
31  const std::size_t copy_bits = uavcan::min(last_bit - src_offset, std::size_t(8U - max_offset));
32 
33  /*
34  * The mask indicating which bits of dest to update:
35  * dst_byte_offset copy_bits write_mask
36  * 0 8 11111111
37  * 0 7 11111110
38  * ...
39  * 0 1 10000000
40  * ...
41  * 4 4 00001111
42  * 4 3 00001110
43  * 4 2 00001100
44  * 4 1 00001000
45  * ...
46  * 7 1 00000001
47  */
48  const uint8_t write_mask = uint8_t(uint8_t(0xFF00U >> copy_bits) >> dst_bit_offset);
49 
50  // The value to be extracted from src, shifted into the dst location
51  const uint8_t src_data = uint8_t((src[src_offset / 8U] << src_bit_offset) >> dst_bit_offset);
52 
53  dst[dst_offset / 8U] = uint8_t((dst[dst_offset / 8U] & ~write_mask) | (src_data & write_mask));
54 
55  src_offset += copy_bits;
56  dst_offset += copy_bits;
57  }
58 }
59 }
std::size_t
unsigned long size_t
Definition: coverity_scan_model.cpp:19
uavcan::bitarrayCopy
void bitarrayCopy(const unsigned char *src_org, std::size_t src_offset, std::size_t src_len, unsigned char *dst_org, std::size_t dst_offset)
Definition: uc_bit_array_copy.cpp:12
bit_stream.hpp
uavcan::uint8_t
std::uint8_t uint8_t
Definition: std.hpp:24
uavcan::max
const UAVCAN_EXPORT T & max(const T &a, const T &b)
Definition: templates.hpp:291
uavcan::min
const UAVCAN_EXPORT T & min(const T &a, const T &b)
Definition: templates.hpp:281
uavcan
Definition: libuavcan/libuavcan/include/uavcan/build_config.hpp:204
UAVCAN_ASSERT
#define UAVCAN_ASSERT(x)
Definition: libuavcan/libuavcan/include/uavcan/build_config.hpp:184


uavcan_communicator
Author(s):
autogenerated on Fri Dec 13 2024 03:10:03