utils.h (1312B)
1 #pragma once 2 3 #include <cstdint> 4 #include <iostream> 5 #include <vector> 6 7 8 namespace virusLib 9 { 10 static uint16_t swap16(const uint32_t _val) 11 { 12 return (_val & 0xff) << 8 | (_val & 0xff00) >> 8; 13 } 14 15 static uint32_t swap32(const uint32_t _val) 16 { 17 return ((_val & 0xff) << 24) | ((_val & 0xff00) << 8) | ((_val & 0xff0000) >> 8) | (_val >> 24); 18 } 19 20 struct membuf : std::streambuf 21 { 22 explicit membuf(const std::vector<char>& base) 23 { 24 char* p(const_cast<char*>(base.data())); 25 this->setg(p, p, p + base.size()); 26 } 27 28 protected: 29 pos_type seekpos(pos_type sp, std::ios_base::openmode which) override 30 { 31 return seekoff(sp - pos_type(off_type(0)), std::ios_base::beg, which); 32 } 33 34 pos_type seekoff(off_type off, 35 std::ios_base::seekdir dir, 36 std::ios_base::openmode which = std::ios_base::in) override 37 { 38 if (dir == std::ios_base::cur) 39 gbump(static_cast<int>(off)); 40 else if (dir == std::ios_base::end) 41 setg(eback(), egptr() + off, egptr()); 42 else if (dir == std::ios_base::beg) 43 setg(eback(), eback() + off, egptr()); 44 return gptr() - eback(); 45 } 46 }; 47 48 struct imemstream : virtual membuf, std::istream 49 { 50 explicit imemstream(const std::vector<char>& base) 51 : membuf(base), std::istream(static_cast<std::streambuf*>(this)) 52 { 53 } 54 }; 55 }