fork(1) download
  1. #include <cstdint>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <type_traits>
  5.  
  6. using namespace std;
  7.  
  8. constexpr uint16_t MM_len = 128;
  9. uint8_t MM_data[MM_len] = {};
  10. uint16_t MM_index = 0;
  11.  
  12. // add() variant to copy a buffer into MM_data. Returns updated MM_index or 0
  13. uint16_t add(uint16_t count, uint8_t *arrayOfBytes)
  14. {
  15. if (!MM_data || count > MM_len - MM_index)
  16. return 0;
  17. std::copy_n(arrayOfBytes, count, &MM_data[MM_index]);
  18. MM_index += count;
  19. return MM_index;
  20. }
  21.  
  22. // Terminate args recursion
  23. uint16_t add() { return 0; }
  24.  
  25. // add() - add a single data element MSB first to MM_data. Returns updated MM_index or 0
  26. template <class T> uint16_t add(T v) {
  27. uint16_t sz = sizeof(T); // Size of value to be added
  28.  
  29. // Will it fit?
  30. if (MM_data && sz <= (MM_len - MM_index)) {
  31. // Yes. Copy it MSB first
  32. while (sz) {
  33. sz--;
  34. MM_data[MM_index++] = (v >> (sz << 3)) & 0xFF;
  35. }
  36. // Return updated MM_index (logical length of message so far)
  37. return MM_index;
  38. }
  39. // No, will not fit - return 0
  40. return 0;
  41. }
  42.  
  43. // First arg is uint8_t
  44. template <class... Args>
  45. typename std::enable_if<(sizeof...(Args) > 0), uint16_t>::type
  46. add(uint8_t v, Args... args) {
  47. return add(v) + add(args...);
  48. }
  49.  
  50. // First arg is uint16_t
  51. template <class... Args>
  52. typename std::enable_if<(sizeof...(Args) > 0), uint16_t>::type
  53. add(uint16_t v, Args... args) {
  54. return add(v) + add(args...);
  55. }
  56.  
  57. // First arg is uint32_t
  58. template <class... Args>
  59. typename std::enable_if<(sizeof...(Args) > 0), uint16_t>::type
  60. add(uint32_t v, Args... args) {
  61. return add(v) + add(args...);
  62. }
  63.  
  64. auto main() -> int
  65. {
  66. uint8_t a[] = { 4, 5, 6 };
  67. add(uint16_t{ 1 }, uint8_t{ 2 }, uint32_t{ 3 });
  68. add(3, &a[0]);
  69. for (uint16_t i = 0; i < MM_index; ++i)
  70. cout << int{ MM_data[i] } << " ";
  71. cout << endl;
  72. }
  73.  
Success #stdin #stdout 0s 4100KB
stdin
Standard input is empty
stdout
0 1 2 0 0 0 3 4 5 6