From c25d48fd0c74d8ba7dde98529b32a6e97f2be2d9 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Sun, 22 Jul 2018 19:41:23 -0700 Subject: [PATCH] HttpParser: Add Reset() function (#1210) This allows reuse of the HttpParser object for multiple requests. --- wpiutil/src/main/native/cpp/HttpParser.cpp | 12 ++++++++++++ wpiutil/src/main/native/include/wpi/HttpParser.h | 11 +++++++++++ wpiutil/src/test/native/cpp/HttpParserTest.cpp | 16 ++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/wpiutil/src/main/native/cpp/HttpParser.cpp b/wpiutil/src/main/native/cpp/HttpParser.cpp index f0105851a7..4560b38508 100644 --- a/wpiutil/src/main/native/cpp/HttpParser.cpp +++ b/wpiutil/src/main/native/cpp/HttpParser.cpp @@ -162,3 +162,15 @@ HttpParser::HttpParser(Type type) { return self.m_aborted; }; } + +void HttpParser::Reset(Type type) { + http_parser_init(&m_parser, + static_cast(static_cast(type))); + m_parser.data = this; + m_maxLength = 1024; + m_state = kStart; + m_urlBuf.clear(); + m_fieldBuf.clear(); + m_valueBuf.clear(); + m_aborted = false; +} diff --git a/wpiutil/src/main/native/include/wpi/HttpParser.h b/wpiutil/src/main/native/include/wpi/HttpParser.h index 3ff91c94c4..b8b39de204 100644 --- a/wpiutil/src/main/native/include/wpi/HttpParser.h +++ b/wpiutil/src/main/native/include/wpi/HttpParser.h @@ -36,8 +36,19 @@ class HttpParser { */ static uint32_t GetParserVersion(); + /** + * Constructor. + * @param type Type of parser (request or response or both) + */ explicit HttpParser(Type type); + /** + * Reset the parser to initial state. + * This allows reusing the same parser object from request to request. + * @param type Type of parser (request or response or both) + */ + void Reset(Type type); + /** * Set the maximum accepted length for URLs, field names, and field values. * The default is 1024. diff --git a/wpiutil/src/test/native/cpp/HttpParserTest.cpp b/wpiutil/src/test/native/cpp/HttpParserTest.cpp index bf236de299..8de2bc6474 100644 --- a/wpiutil/src/test/native/cpp/HttpParserTest.cpp +++ b/wpiutil/src/test/native/cpp/HttpParserTest.cpp @@ -190,4 +190,20 @@ TEST(HttpParserTest, HeadersCompleteUpgrade) { ASSERT_FALSE(p.HasError()); } +TEST(HttpParserTest, Reset) { + HttpParser p{HttpParser::kRequest}; + int callbacks = 0; + p.headersComplete.connect([&](bool) { ++callbacks; }); + p.Execute("GET / HTTP/1.1\r\n"); + ASSERT_EQ(callbacks, 0); + p.Execute("\r\n"); + ASSERT_EQ(callbacks, 1); + p.Reset(HttpParser::kRequest); + p.Execute("GET / HTTP/1.1\r\n"); + ASSERT_EQ(callbacks, 1); + p.Execute("\r\n"); + ASSERT_EQ(callbacks, 2); + ASSERT_FALSE(p.HasError()); +} + } // namespace wpi