Greatly improved chunk-encoded parser and test

This commit is contained in:
Alex Hultman
2022-10-08 04:32:59 +02:00
parent 5062696f63
commit e4e04940c5
2 changed files with 83 additions and 37 deletions
+14 -21
View File
@@ -21,32 +21,30 @@ void runTest(unsigned int maxConsume) {
/* Encode them in chunked encoding */
std::stringstream ss;
for (std::string_view chunk : chunks) {
// if length is 0 then append trailer also
/* Generic chunked encoding format */
ss << std::hex << chunk.length() << "\r\n" << chunk << "\r\n";
// every null chunk is followed by an empty trailer
/* Every null chunk is followed by an empty trailer */
if (chunk.length() == 0) {
ss << "\r\n";
}
}
/* Consume them, checking that we get what we expect */
std::string buffer = ss.str();
/* Begin with a clear state and the full data */
unsigned int state = 0;
unsigned int chunkOffset = 0;
std::string_view chunkEncoded = buffer;
while (chunkEncoded.length()) {
/* Parse a small part of the given data */
std::string_view data = chunkEncoded.substr(0, std::min<size_t>(maxConsume, chunkEncoded.length()));
chunkEncoded.remove_prefix(data.length());
unsigned int consumed = UINT_MAX;
int chunkOffset = 0;
while (consumed) {
/* Consume up to maxConsume */
std::string_view indata = chunkEncoded.substr(0, std::min<size_t>(maxConsume, chunkEncoded.length()));
consumed = uWS::consumeChunkedEncoding(indata, state, [&](std::string_view chunk) {
/* Print for logging */
std::cout << "<" << chunk << ">";
/* Whatever chunk we emit, or part of chunk, it must match the expected one */
for (auto chunk : uWS::ChunkIterator(data, &state)) {
std::cout << "<" << chunk << ">" << std::endl;
/* Run check here */
if (!chunk.length() && chunks[chunkOffset].length()) {
std::cout << "We got emitted an empty chunk but expected a non-empty one" << std::endl;
std::abort();
@@ -61,17 +59,12 @@ void runTest(unsigned int maxConsume) {
std::cerr << "Chunk does not match! Should be <" << chunks[chunkOffset] << ">" << std::endl;
std::abort();
}
});
if (consumed != indata.length()) {
std::cerr << "Chunk parser did not consume exactly the bytes passed!" << std::endl;
std::abort();
}
chunkEncoded.remove_prefix(consumed);
}
}
int main() {
for (int i = 0; i < 1000; i++) {
for (int i = 1; i < 1000; i++) {
runTest(i);
}