Sponge
CS144's user-space TCP library
parser_example.cc
Go to the documentation of this file.
1 const uint32_t val1 = 0xdeadbeef;
2 const uint16_t val2 = 0xc0c0;
3 const uint8_t val3 = 0xff;
4 const uint32_t val4 = 0x0c05fefe;
5 
6 // first, let's serialize it
8 buffer.push_back(0x32); // manually added to beginning of string
9 {
10  NetUnparser p;
13  p.u8(buffer, val3);
15 } // p goes out of scope, data is in buffer
16 
17 // now let's deserialize it
18 uint8_t out0, out3;
19 uint32_t out1, out4;
20 uint16_t out2;
21 {
22  NetParser p{std::string(buffer)}; // NOTE: starting at offset 0
23  out0 = p.u8(); // buffer[0], which we manually set to 0x32 above
24  out1 = p.u32(); // parse out val1
25  out2 = p.u16(); // val2
26  out3 = p.u8(); // val3
27  out4 = p.u32(); // val4
28 } // p goes out of scope
29 
30 if (out0 != 0x32 || out1 != val1 || out2 != val2 || out3 != val3 || out4 != val4) {
31  throw std::runtime_error("bad parse");
32 }
uint8_t out3
const uint8_t val3
const uint32_t val4
const uint16_t val2
const uint32_t val1
std::string buffer
uint32_t out4
uint16_t out2
uint32_t out1
uint8_t out0
T push_back(T... args)
static void u32(std::string &s, const uint32_t val)
Write a 32-bit integer into the data stream in network byte order.
Definition: parser.cc:68
static void u16(std::string &s, const uint16_t val)
Write a 16-bit integer into the data stream in network byte order.
Definition: parser.cc:70
static void u8(std::string &s, const uint8_t val)
Write an 8-bit integer into the data stream in network byte order.
Definition: parser.cc:72