Sponge
CS144's user-space TCP library
doctests
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
7
std::string
buffer
;
8
buffer
.
push_back
(0x32);
// manually added to beginning of string
9
{
10
NetUnparser
p;
11
p.
u32
(
buffer
,
val1
);
12
p.
u16
(
buffer
,
val2
);
13
p.
u8
(
buffer
,
val3
);
14
p.
u32
(
buffer
,
val4
);
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
}
NetUnparser::u8
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
std::string
std::string::push_back
T push_back(T... args)
val1
const uint32_t val1
Definition:
parser_example.cc:1
buffer
std::string buffer
Definition:
parser_example.cc:7
out1
uint32_t out1
Definition:
parser_example.cc:19
NetUnparser::u16
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
val2
const uint16_t val2
Definition:
parser_example.cc:2
NetUnparser
Definition:
parser.hh:65
std::runtime_error
NetParser
Definition:
parser.hh:25
NetUnparser::u32
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
out0
uint8_t out0
Definition:
parser_example.cc:18
val4
const uint32_t val4
Definition:
parser_example.cc:4
out4
uint32_t out4
Definition:
parser_example.cc:19
out3
uint8_t out3
Definition:
parser_example.cc:18
val3
const uint8_t val3
Definition:
parser_example.cc:3
out2
uint16_t out2
Definition:
parser_example.cc:20
Generated by
1.8.17