fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdint>
  4.  
  5. template<class It>
  6. struct range_t {
  7. It b, e;
  8. It begin() const { return b; }
  9. It end() const { return e; }
  10. std::size_t size() const { return end()-begin(); }
  11. };
  12.  
  13. template<class It>
  14. range_t<It> range(It s, It f) { return {s,f}; }
  15.  
  16. template<class T>
  17. range_t< unsigned char* > as_bytes( T* t ) {
  18. static_assert( std::is_trivially_copyable<T>::value, "bad idea if not trivilaly copyable" );
  19. auto* ptr = reinterpret_cast<unsigned char*>(t);
  20. return range(ptr, ptr+sizeof(T));
  21. }
  22. template<class T>
  23. range_t< unsigned char const* > as_bytes( T const* t ) {
  24. static_assert( std::is_trivially_copyable<T>::value, "bad idea if not trivilaly copyable" );
  25. auto* ptr = reinterpret_cast<unsigned char const*>(t);
  26. return range(ptr, ptr+sizeof(T));
  27. }
  28.  
  29. template<class T>
  30. void push_bytes_in( std::vector<std::uint8_t>& target, T const* data ) {
  31. auto bytes = as_bytes(data);
  32. target.insert( target.end(), bytes.begin(), bytes.end() );
  33. }
  34. template<class T>
  35. bool pop_bytes_out( std::vector<std::uint8_t>& src, T* data ) {
  36. auto bytes = as_bytes(data);
  37. if (bytes.size() > src.size()) return false;
  38. std::copy( src.end()-bytes.size(), src.end(), bytes.begin() );
  39. src.resize( src.size()-bytes.size() );
  40. return true;
  41. }
  42.  
  43. struct some_data {
  44. int x, y;
  45. char buff[1024];
  46. };
  47.  
  48.  
  49.  
  50. int main() {
  51. std::vector<std::uint8_t> bytes;
  52.  
  53. some_data data{1,2, "hello"};
  54. push_bytes_in( bytes, &data );
  55. some_data d2;
  56. if (!pop_bytes_out( bytes, &d2)) {
  57. std::cout << "failed\n";
  58. return -1;
  59. }
  60. std::cout << d2.buff << "\n";
  61. }
Success #stdin #stdout 0s 4240KB
stdin
Standard input is empty
stdout
hello