Advertisement
bueddl

binary io lib example

Aug 10th, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. // This file is part of mvcpp - a web based model-view-controller.
  2.  
  3. // mvcpp is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7.  
  8. // mvcpp is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12.  
  13. // You should have received a copy of the GNU General Public License
  14. // along with mvcpp. If not, see <http://www.gnu.org/licenses/>.
  15. //
  16. // (C) Copyright 2016 by Sebastian Büttner <sebastian.buettner@powerserverplus.net>
  17.  
  18. #include <io/buffer.hpp>
  19. #include <io/binary_reader.hpp>
  20. #include <io/binary_writer.hpp>
  21.  
  22. #include <iostream>
  23. #include <arpa/inet.h>
  24.  
  25. struct my_header
  26. {
  27.   uint16_t data_length;
  28. };
  29.  
  30. namespace io
  31. {
  32.  
  33. template<typename T, typename Traits>
  34. struct pack_traits<T, Traits, my_header>
  35. {
  36.   static void pack(basic_binary_writer<T, Traits> &writer, const my_header &header)
  37.   {
  38.     writer << ::htons(header.data_length);
  39.   }
  40.  
  41.   static void unpack(basic_binary_reader<T, Traits> &reader, my_header &header)
  42.   {
  43.     reader >> header.data_length;
  44.     ::ntohs(header.data_length);
  45.   }
  46. };
  47.  
  48. }
  49.  
  50. int main()
  51. {
  52.   io::buffer buf;
  53.  
  54.   {
  55.     auto writer = io::make_binary_writer(buf);
  56.  
  57.     my_header header{
  58.       .data_length = 1024,
  59.     };
  60.     writer << header;
  61.   }
  62.  
  63.   {
  64.     auto reader = io::make_binary_reader(buf);
  65.  
  66.     my_header header;
  67.     reader >> header;
  68.     std::cout << "header.data_length = " << header.data_length << std::endl;
  69.   }
  70.  
  71.   return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement