From 7988966140ec4fc4b129ea3bf616d5ac93e10867 Mon Sep 17 00:00:00 2001 From: Dima Date: Fri, 4 Mar 2022 23:48:17 -0500 Subject: [PATCH] And ran the top-level `clang-format-10`, let's see ... --- blocks/html/html.h | 4 +- blocks/html/html_http.h | 2 +- blocks/html/tags.h | 3 +- blocks/html/test.cc | 4 +- blocks/http/api.h | 2 +- blocks/http/chunked_demo.cc | 107 +- blocks/http/impl/posix_client.h | 5 +- blocks/http/impl/posix_server.h | 7 +- blocks/http/test.cc | 1013 ++++---- blocks/http/types.h | 52 +- blocks/json/json.h | 42 +- blocks/json/test.cc | 5 +- blocks/mmq/mmpq.h | 8 +- blocks/mmq/test.cc | 2 +- blocks/persistence/exceptions.h | 2 +- blocks/persistence/file.h | 14 +- blocks/persistence/memory.h | 4 +- blocks/persistence/test.cc | 15 +- blocks/self_modifying_config/test.cc | 15 +- blocks/ss/exceptions.h | 2 +- blocks/ss/idx_ts.h | 10 +- blocks/ss/persister.h | 5 +- blocks/ss/pubsub.h | 10 +- blocks/ss/signature.h | 10 +- blocks/ss/types.h | 5 +- blocks/url/exceptions.h | 2 +- blocks/url/url.h | 12 +- blocks/xterm/example.cc | 12 +- blocks/xterm/multiline.cc | 28 +- blocks/xterm/progress.h | 16 +- blocks/xterm/vt100.h | 10 +- bricks/c++17/test.cc | 4 +- bricks/dflags/test.cc | 25 +- bricks/dot/graphviz.h | 4 +- bricks/file/file.h | 80 +- bricks/file/test.cc | 99 +- bricks/graph/gnuplot.h | 2 +- bricks/net/http/headers/headers.h | 6 +- bricks/net/http/test.cc | 424 ++-- bricks/net/tcp/impl/posix.h | 61 +- bricks/net/tcp/test.cc | 194 +- bricks/strings/chunk.h | 8 +- bricks/strings/fixed_size_serializer.h | 7 +- bricks/strings/group_by_lines.h | 87 +- bricks/strings/join.h | 9 +- bricks/strings/printf.h | 6 +- bricks/strings/regex.h | 13 +- bricks/strings/split.h | 18 +- bricks/strings/test.cc | 94 +- bricks/strings/util.h | 5 +- bricks/sync/locks.h | 3 +- bricks/sync/owned_borrowed.h | 6 +- bricks/sync/test.cc | 93 +- bricks/sync/waitable_atomic.h | 13 +- bricks/system/current.inl.h | 2 +- bricks/system/syscalls.h | 4 +- bricks/template/combine.h | 10 +- bricks/template/test.cc | 17 +- bricks/template/typelist.h | 34 +- bricks/template/weed.h | 4 +- bricks/time/chrono.h | 29 +- bricks/time/test.cc | 13 +- bricks/util/accumulative_scoped_deleter.h | 3 +- bricks/util/base64.h | 5 +- bricks/util/comparators.h | 3 +- bricks/util/iterator.h | 6 +- bricks/util/object_interface.h | 8 +- bricks/util/random.h | 8 +- bricks/util/singleton.h | 4 +- bricks/util/test.cc | 37 +- compact_tsv/gen.cc | 33 +- compact_tsv/test.cc | 58 +- compact_tsv/unpack_fast.cc | 20 +- examples/benchmark/generic/benchmark.h | 3 +- examples/benchmark/generic/scenario_storage.h | 58 +- examples/benchmark/http/benchmark.cc | 3 +- examples/benchmark/http/server.h | 9 +- examples/benchmark/lockfree/benchmark.cc | 15 +- examples/benchmark/storage/replay.cc | 56 +- examples/cookies_server/cookies.cc | 16 +- .../step2_confirm_timestamps_are_valid.cc | 28 +- .../step3_rides_by_months_unoptimized.cc | 2 +- ...step4_rides_by_months_still_unoptimized.cc | 2 +- .../step6_rides_by_months_readfullfile.cc | 4 +- .../tier3_cook_binary/step1_cook.cc | 16 +- .../schema_integers.h | 12 +- .../tier4_cook_binary_integers/step1_cook.cc | 14 +- .../nyc_taxi_dataset_service.h | 4 +- examples/dump_schema/dump_schema.cc | 10 +- examples/ejs/cpp/ejs.cc | 77 +- examples/embedded_db/db.cc | 74 +- examples/embedded_db/schema.h | 4 +- examples/event_collector/event_collector.h | 46 +- examples/event_collector/test.cc | 4 +- examples/event_store/event_store.h | 66 +- examples/event_store/test.cc | 104 +- examples/flow_tool/flow_tool.h | 3 +- examples/flow_tool/schema.h | 10 +- examples/flow_tool/test.cc | 15 +- examples/gradient_boosted_trees/evaluate.cc | 54 +- examples/gradient_boosted_trees/train.h | 2 +- examples/iris/iris.h | 3 +- examples/iris/step2_render.cc | 67 +- examples/iris/step3_optimize.cc | 101 +- examples/iris/test.cc | 64 +- examples/karl/service_generator.cc | 4 +- examples/karl/service_karl.cc | 6 +- examples/optimize/main.h | 7 +- examples/optimize/optimize.cc | 6 +- examples/type_evolution/schema.h | 20 +- examples/type_evolution/test.cc | 33 +- fncas/fncas/base.h | 2 +- fncas/fncas/differentiate.h | 20 +- fncas/fncas/exceptions.h | 2 +- fncas/fncas/jit.h | 26 +- fncas/fncas/logger.h | 6 +- fncas/fncas/mathutil.h | 14 +- fncas/fncas/node.h | 25 +- fncas/fncas/optimize.h | 6 +- fncas/test.cc | 71 +- fncas/x64_native_jit/x64_native_jit.h | 6 +- integrations/adwords/conversion_tracking.h | 6 +- integrations/adwords/exceptions.h | 4 +- integrations/exceptions.h | 2 +- integrations/onesignal/exceptions.h | 4 +- .../onesignal/ios_notifications_sender.h | 4 +- integrations/segment/schema_web.h | 6 +- karl/claire.h | 15 +- karl/constants.h | 4 +- karl/exceptions.h | 2 +- karl/integrations/nodejs/karl_server.cc | 11 +- karl/karl.h | 548 ++--- karl/locator.h | 2 +- karl/render.h | 2 +- karl/respond_with_schema.h | 2 +- karl/schema_claire.h | 4 +- karl/schema_karl.h | 30 +- karl/test.cc | 179 +- karl/test_service/annotator.h | 2 +- karl/test_service/filter.h | 2 +- karl/test_service/http_subscriber.h | 9 +- karl/test_service/is_prime.h | 12 +- midichlorians/client/ios/midichlorians_impl.h | 8 +- midichlorians/client/test.cc | 22 +- midichlorians/midichlorians_data_dictionary.h | 12 +- midichlorians/server/server.h | 24 +- midichlorians/server/test.cc | 5 +- nlp/nlp.h | 4 +- port.h | 25 +- profiler/profiler.h | 2 +- regression_tests/typesystem/struct_fields.cc | 2 +- .../typesystem/typelist_dynamic.cc | 2 +- ripcurrent/ripcurrent.h | 21 +- ripcurrent/test.cc | 74 +- ripcurrent/types.h | 6 +- storage/api.h | 262 ++- storage/api_types.h | 10 +- storage/base.h | 4 +- storage/container/dictionary.h | 48 +- storage/container/many_to_many.h | 65 +- storage/container/one_to_many.h | 71 +- storage/container/one_to_one.h | 80 +- storage/container/sfinae.h | 2 +- storage/exceptions.h | 2 +- storage/persister/stream.h | 13 +- storage/rest/hypermedia.h | 6 +- storage/rest/plain.h | 19 +- storage/rest/simple.h | 6 +- storage/rest/structured.h | 41 +- storage/rest/types.h | 45 +- storage/semantics.h | 16 +- storage/storage.h | 166 +- storage/test_helpers.cc | 16 +- storage/tests_flip/test.cc | 215 +- storage/tests_rest/test.cc | 638 ++--- storage/tests_smoke/test.cc | 2045 +++++++++-------- stream/replicator.h | 29 +- stream/stream.h | 18 +- stream/stream_impl.h | 3 +- stream/test.cc | 233 +- typesystem/base.h | 12 +- typesystem/evolution/macros.h | 12 +- typesystem/evolution/test.cc | 820 ++++--- typesystem/evolution/type_evolution.h | 2 +- typesystem/exceptions.h | 2 +- typesystem/helpers.h | 22 +- typesystem/optional.h | 2 +- typesystem/reflection/reflection.h | 12 +- typesystem/reflection/test.cc | 103 +- typesystem/reflection/types.h | 21 +- typesystem/schema/json_schema_format.h | 4 +- typesystem/schema/schema.h | 50 +- typesystem/schema/test.cc | 26 +- typesystem/serialization/exceptions_base.h | 8 +- typesystem/serialization/json/enum.h | 2 +- typesystem/serialization/json/exceptions.h | 4 +- .../serialization/json/immutable_optional.h | 6 +- typesystem/serialization/json/json.h | 24 +- typesystem/serialization/json/map.h | 6 +- typesystem/serialization/json/optional.h | 6 +- typesystem/serialization/json/pair.h | 2 +- typesystem/serialization/json/primitives.h | 4 +- typesystem/serialization/json/set.h | 2 +- typesystem/serialization/json/struct.h | 4 +- typesystem/serialization/json/tuple.h | 8 +- typesystem/serialization/json/typeid.h | 2 +- typesystem/serialization/json/unordered_map.h | 2 +- typesystem/serialization/json/unordered_set.h | 2 +- typesystem/serialization/json/variant.h | 9 +- typesystem/serialization/json/vector.h | 2 +- typesystem/serialization/test.cc | 23 +- typesystem/struct.h | 71 +- typesystem/test.cc | 83 +- typesystem/typename.h | 10 +- typesystem/types.h | 12 +- typesystem/variant.h | 2 +- utils/json_schema/infer.h | 29 +- utils/json_schema/test.cc | 28 +- utils/nginx/config.h | 7 +- utils/nginx/exceptions.h | 2 +- utils/nginx/nginx.h | 15 +- utils/nginx/test.cc | 3 +- utils/operational_transformation/ot.h | 4 +- 223 files changed, 5310 insertions(+), 5457 deletions(-) diff --git a/blocks/html/html.h b/blocks/html/html.h index a3e3bba17..69a43ff5a 100644 --- a/blocks/html/html.h +++ b/blocks/html/html.h @@ -150,7 +150,7 @@ struct HTMLGeneratorOStreamScope final : HTMLGeneratorScope { #define CURRENT_HTML_SWITCH(x, y) x y #define HTML(...) CURRENT_HTML_SWITCH(CURRENT_HTML_SWITCH_N(CURRENT_HTML_NARGS(__VA_ARGS__)), (__VA_ARGS__)) -} // namespace current::html +} // namespace html } // namespace current // The `htmltag` namespace is intentionally in the global scope, not within `::current`, so that it can be amended to. @@ -168,7 +168,7 @@ struct _ final { } }; -} // namespace ::htmltag +} // namespace htmltag #include "tags.h" diff --git a/blocks/html/html_http.h b/blocks/html/html_http.h index cc04b91c5..0979b05ac 100644 --- a/blocks/html/html_http.h +++ b/blocks/html/html_http.h @@ -52,7 +52,7 @@ struct HTMLGeneratorHTTPResponseScope final : HTMLGeneratorScope { std::ostream& OutputStream() override { return html_contents; } }; -} // namespace current::html +} // namespace html } // namespace current #endif // BLOCKS_HTML_HTTP_H diff --git a/blocks/html/tags.h b/blocks/html/tags.h index 89c46efe0..996ebcca3 100644 --- a/blocks/html/tags.h +++ b/blocks/html/tags.h @@ -78,7 +78,6 @@ namespace htmltag { #define CURRENT_HTML_TAG(...) \ CURRENT_HTML_TAG_SWITCH(CURRENT_HTML_TAG_SWITCH_N(CURRENT_HTML_TAG_NARGS(__VA_ARGS__)), (__VA_ARGS__)) - // clang-format off #define CURRENT_HTML_START_ONLY_TAG_COUNT_3(tag, param1, param2) \ @@ -148,6 +147,6 @@ CURRENT_HTML_TAG(table, border, cellpadding); CURRENT_HTML_TAG(tr); CURRENT_HTML_TAG(td, align, colspan, valign); -} // namespace ::htmltag +} // namespace htmltag #endif // BLOCKS_HTML_TAGS_H diff --git a/blocks/html/test.cc b/blocks/html/test.cc index ee707598a..5865c5438 100644 --- a/blocks/html/test.cc +++ b/blocks/html/test.cc @@ -141,7 +141,7 @@ TEST(HTMLTest, Smoke) { { const auto scope = current::html::HTMLGeneratorOStreamScope(oss); HTML(table, border(0)); // Number, not a string. - } + } EXPECT_EQ("
", oss.str()); } { @@ -149,7 +149,7 @@ TEST(HTMLTest, Smoke) { { const auto scope = current::html::HTMLGeneratorOStreamScope(oss); HTML(input, value(42)); // Number, not a string. - } + } EXPECT_EQ("", oss.str()); } } diff --git a/blocks/http/api.h b/blocks/http/api.h index cb64583e3..14509a71a 100644 --- a/blocks/http/api.h +++ b/blocks/http/api.h @@ -78,8 +78,8 @@ inline typename current::weed::call_with_type HTTP(TS&&... par using current::http::HTTP; using current::http::Request; -using current::http::Response; using current::http::ReRegisterRoute; +using current::http::Response; using HTTPRoutesScope = typename HTTP_IMPL::server_impl_t::HTTPRoutesScope; using HTTPRoutesScopeEntry = current::http::HTTPServerPOSIX::HTTPRoutesScopeEntry; diff --git a/blocks/http/chunked_demo.cc b/blocks/http/chunked_demo.cc index ce5c159f0..108dc5b74 100644 --- a/blocks/http/chunked_demo.cc +++ b/blocks/http/chunked_demo.cc @@ -105,9 +105,9 @@ y:0.183947} #include "../../bricks/strings/printf.h" #include "../../bricks/time/chrono.h" -using current::time::Now; -using current::strings::Printf; using current::net::http::Headers; +using current::strings::Printf; +using current::time::Now; DEFINE_int32(port, 8181, "The port to serve chunked response on."); @@ -150,58 +150,55 @@ CURRENT_STRUCT(ExampleMeta) { // TODO(dkorolev): Finish multithreading. Need to notify active connections and wait for them to finish. int main() { - HTTP(FLAGS_port) - .Register("/layout", - [](Request r) { - LayoutItem layout; - LayoutItem row; - layout.col.push_back(row); - r(layout, - // "layout", <-- @dkorolev, remove this source file entirely, as it's obsolete. - HTTPResponseCode.OK, - Headers({{"Connection", "close"}, {"Access-Control-Allow-Origin", "*"}}), - "application/json; charset=utf-8"); - }); - HTTP(FLAGS_port) - .Register("/meta", - [](Request r) { - r(ExampleMeta(), - // "meta", <-- @dkorolev, remove this source file entirely, as it's obsolete. - HTTPResponseCode.OK, - Headers({{"Connection", "close"}, {"Access-Control-Allow-Origin", "*"}}), - "application/json; charset=utf-8"); - }); - HTTP(FLAGS_port) - .Register("/data", - [](Request r) { - std::thread([](Request&& r) { - // Since we are in another thread, need to catch exceptions ourselves. - try { - auto response = r.connection.SendChunkedHTTPResponse( - HTTPResponseCode.OK, - {{"Connection", "keep-alive"}, {"Access-Control-Allow-Origin", "*"}}, - "application/json; charset=utf-8"); - std::string data; - const double begin = static_cast(Now().count()); - const double t = atof(r.url.query["t"].c_str()); - const double end = (t > 0) ? (begin + t * 1e3) : 1e18; - double current; - while ((current = static_cast(Now().count())) < end) { - std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100 + 100)); - const double x = current; - const double y = sin(5e-3 * (current - begin)); - data += Printf("{\"x\":%lf,\"y\":%lf}\n", x, y); - const double f = (rand() % 101) * (rand() % 101) * (rand() % 101) * 1e-6; - const size_t n = static_cast(data.length() * f); - if (n) { - response.Send(data.substr(0, n)); - data = data.substr(n); - } - } - } catch (const current::Exception& e) { - std::cerr << "Exception in data serving thread: " << e.what() << std::endl; - } - }, std::move(r)).detach(); - }); + HTTP(FLAGS_port).Register("/layout", [](Request r) { + LayoutItem layout; + LayoutItem row; + layout.col.push_back(row); + r(layout, + // "layout", <-- @dkorolev, remove this source file entirely, as it's obsolete. + HTTPResponseCode.OK, + Headers({{"Connection", "close"}, {"Access-Control-Allow-Origin", "*"}}), + "application/json; charset=utf-8"); + }); + HTTP(FLAGS_port).Register("/meta", [](Request r) { + r(ExampleMeta(), + // "meta", <-- @dkorolev, remove this source file entirely, as it's obsolete. + HTTPResponseCode.OK, + Headers({{"Connection", "close"}, {"Access-Control-Allow-Origin", "*"}}), + "application/json; charset=utf-8"); + }); + HTTP(FLAGS_port).Register("/data", [](Request r) { + std::thread( + [](Request&& r) { + // Since we are in another thread, need to catch exceptions ourselves. + try { + auto response = r.connection.SendChunkedHTTPResponse( + HTTPResponseCode.OK, + {{"Connection", "keep-alive"}, {"Access-Control-Allow-Origin", "*"}}, + "application/json; charset=utf-8"); + std::string data; + const double begin = static_cast(Now().count()); + const double t = atof(r.url.query["t"].c_str()); + const double end = (t > 0) ? (begin + t * 1e3) : 1e18; + double current; + while ((current = static_cast(Now().count())) < end) { + std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100 + 100)); + const double x = current; + const double y = sin(5e-3 * (current - begin)); + data += Printf("{\"x\":%lf,\"y\":%lf}\n", x, y); + const double f = (rand() % 101) * (rand() % 101) * (rand() % 101) * 1e-6; + const size_t n = static_cast(data.length() * f); + if (n) { + response.Send(data.substr(0, n)); + data = data.substr(n); + } + } + } catch (const current::Exception& e) { + std::cerr << "Exception in data serving thread: " << e.what() << std::endl; + } + }, + std::move(r)) + .detach(); + }); HTTP(FLAGS_port).Join(); } diff --git a/blocks/http/impl/posix_client.h b/blocks/http/impl/posix_client.h index b686744b4..9cf8c8573 100644 --- a/blocks/http/impl/posix_client.h +++ b/blocks/http/impl/posix_client.h @@ -57,7 +57,7 @@ struct HTTPRedirectHelper : current::net::HTTPDefaultHelper { current::net::HTTPDefaultHelper::OnHeader(key, value); } }; -} // namespace current::http::impl +} // namespace impl template class GenericHTTPClientPOSIX final { @@ -94,8 +94,7 @@ class GenericHTTPClientPOSIX final { port = 80; } } - current::net::Connection connection( - current::net::Connection(current::net::ClientSocket(parsed_url.host, port))); + current::net::Connection connection(current::net::Connection(current::net::ClientSocket(parsed_url.host, port))); connection.BlockingWrite( request_method_ + ' ' + parsed_url.path + parsed_url.ComposeParameters() + " HTTP/1.1\r\n", true); connection.BlockingWrite("Host: " + parsed_url.host + "\r\n", true); diff --git a/blocks/http/impl/posix_server.h b/blocks/http/impl/posix_server.h index c98e917f2..e57ee877c 100644 --- a/blocks/http/impl/posix_server.h +++ b/blocks/http/impl/posix_server.h @@ -163,7 +163,9 @@ class HTTPServerPOSIX final { // Since instances of `HTTPServerPOSIX` are created via a singleton, // a listening thread will only be created once per port, on the first access to that port. explicit HTTPServerPOSIX(current::net::BarePort port) - : terminating_(false), port_(static_cast(port)), thread_([this, port]() { Thread(current::net::Socket(port)); }) {} + : terminating_(false), + port_(static_cast(port)), + thread_([this, port]() { Thread(current::net::Socket(port)); }) {} explicit HTTPServerPOSIX(current::net::ReservedLocalPort reserved_port) : terminating_(false), port_(reserved_port), @@ -223,7 +225,8 @@ class HTTPServerPOSIX final { const URLPathArgs::CountMask path_args_count_mask, F& handler) { std::lock_guard lock(mutex_); - return DoRegisterHandler(path, [&handler](Request r) { handler(std::move(r)); }, path_args_count_mask, POLICY); + return DoRegisterHandler( + path, [&handler](Request r) { handler(std::move(r)); }, path_args_count_mask, POLICY); } template diff --git a/blocks/http/test.cc b/blocks/http/test.cc index aebbd03cc..a9d643746 100644 --- a/blocks/http/test.cc +++ b/blocks/http/test.cc @@ -52,21 +52,21 @@ SOFTWARE. using std::string; -using current::strings::Printf; -using current::Singleton; -using current::FileSystem; using current::FileException; +using current::FileSystem; +using current::Singleton; +using current::strings::Printf; using current::net::Connection; using current::net::HTTPResponseCodeValue; using current::net::http::Headers; using current::net::DefaultInternalServerErrorMessage; -using current::net::DefaultNotFoundMessage; using current::net::DefaultMethodNotAllowedMessage; +using current::net::DefaultNotFoundMessage; -using current::net::HTTPRedirectNotAllowedException; using current::net::HTTPRedirectLoopException; +using current::net::HTTPRedirectNotAllowedException; using current::net::SocketResolveAddressException; DEFINE_string(net_api_test_tmpdir, ".current", "Local path for the test to create temporary files in."); @@ -126,16 +126,13 @@ TEST(HTTPAPI, RegisterWithURLPathParams) { }; const auto scope = HTTP(port).Register("/", URLPathArgs::CountMask::Any, handler) + - HTTP(port) - .Register("/user", URLPathArgs::CountMask::One | URLPathArgs::CountMask::Two, handler) + + HTTP(port).Register("/user", URLPathArgs::CountMask::One | URLPathArgs::CountMask::Two, handler) + HTTP(port).Register("/user/a", URLPathArgs::CountMask::One, handler) + HTTP(port).Register("/user/a/1", URLPathArgs::CountMask::None, handler); ASSERT_THROW(HTTP(port).Register("/", handler), HandlerAlreadyExistsException); - ASSERT_THROW(HTTP(port).Register("/user", URLPathArgs::CountMask::Two, handler), - HandlerAlreadyExistsException); - ASSERT_THROW(HTTP(port).Register("/user/a", URLPathArgs::CountMask::One, handler), - HandlerAlreadyExistsException); + ASSERT_THROW(HTTP(port).Register("/user", URLPathArgs::CountMask::Two, handler), HandlerAlreadyExistsException); + ASSERT_THROW(HTTP(port).Register("/user/a", URLPathArgs::CountMask::One, handler), HandlerAlreadyExistsException); ASSERT_THROW(HTTP(port).Register("/user/a/1", handler), HandlerAlreadyExistsException); const auto run = [port](const std::string& path) -> std::string { @@ -299,14 +296,10 @@ TEST(HTTPAPI, URLParameters) { const auto scope = http_server.Register("/query", [](Request r) { r("x=" + r.url.query["x"]); }); EXPECT_EQ("x=", HTTP(GET(Printf("http://localhost:%d/query", port))).body); EXPECT_EQ("x=42", HTTP(GET(Printf("http://localhost:%d/query?x=42", port))).body); - EXPECT_EQ("x=test passed", - HTTP(GET(Printf("http://localhost:%d/query?x=test+passed", port))).body); - EXPECT_EQ("x=test passed", - HTTP(GET(Printf("http://localhost:%d/query?x=test%%20passed", port))).body); - EXPECT_EQ("x=test/passed", - HTTP(GET(Printf("http://localhost:%d/query?x=test%%2fpassed", port))).body); - EXPECT_EQ("x=test/passed", - HTTP(GET(Printf("http://localhost:%d/query?x=test%%2Fpassed", port))).body); + EXPECT_EQ("x=test passed", HTTP(GET(Printf("http://localhost:%d/query?x=test+passed", port))).body); + EXPECT_EQ("x=test passed", HTTP(GET(Printf("http://localhost:%d/query?x=test%%20passed", port))).body); + EXPECT_EQ("x=test/passed", HTTP(GET(Printf("http://localhost:%d/query?x=test%%2fpassed", port))).body); + EXPECT_EQ("x=test/passed", HTTP(GET(Printf("http://localhost:%d/query?x=test%%2Fpassed", port))).body); } TEST(HTTPAPI, InvalidHEXInURLParameters) { @@ -339,21 +332,19 @@ TEST(HTTPAPI, HeadersAndCookies) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/headers_and_cookies", - [](Request r) { - EXPECT_TRUE(r.headers.Has("Header1")); - EXPECT_TRUE(r.headers.Has("Header2")); - EXPECT_EQ("foo", r.headers["Header1"].value); - EXPECT_EQ("bar", r.headers["Header2"].value); - EXPECT_EQ("x=1; y=2", r.headers.CookiesAsString()); - Response response("OK"); - response.headers.Set("X-Current-H1", "header1"); - response.SetCookie("cookie1", "value1"); - response.headers.Set("X-Current-H2", "header2"); - response.SetCookie("cookie2", "value2"); - r(response); - }); + const auto scope = http_server.Register("/headers_and_cookies", [](Request r) { + EXPECT_TRUE(r.headers.Has("Header1")); + EXPECT_TRUE(r.headers.Has("Header2")); + EXPECT_EQ("foo", r.headers["Header1"].value); + EXPECT_EQ("bar", r.headers["Header2"].value); + EXPECT_EQ("x=1; y=2", r.headers.CookiesAsString()); + Response response("OK"); + response.headers.Set("X-Current-H1", "header1"); + response.SetCookie("cookie1", "value1"); + response.headers.Set("X-Current-H2", "header2"); + response.SetCookie("cookie2", "value2"); + r(response); + }); const auto response = HTTP(GET(Printf("http://localhost:%d/headers_and_cookies", port)) .SetHeader("Header1", "foo") .SetCookie("x", "1") @@ -372,16 +363,14 @@ TEST(HTTPAPI, ConnectionIPAndPort) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/foo", - [port](Request r) { - const auto& c = r.connection; - EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip); - EXPECT_EQ(port, c.LocalIPAndPort().port); - EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip); - EXPECT_LT(0, c.RemoteIPAndPort().port); - r("bar", HTTPResponseCode.OK); - }); + const auto scope = http_server.Register("/foo", [port](Request r) { + const auto& c = r.connection; + EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip); + EXPECT_EQ(port, c.LocalIPAndPort().port); + EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip); + EXPECT_LT(0, c.RemoteIPAndPort().port); + r("bar", HTTPResponseCode.OK); + }); const string url = Printf("http://localhost:%d/foo", port); const auto response = HTTP(GET(url)); EXPECT_EQ(200, static_cast(response.code)); @@ -395,12 +384,9 @@ TEST(HTTPAPI, RespondsWithString) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = - http_server - .Register("/responds_with_string", - [](Request r) { - r("test_string", HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "application/json"); - }); + const auto scope = http_server.Register("/responds_with_string", [](Request r) { + r("test_string", HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "application/json"); + }); const string url = Printf("http://localhost:%d/responds_with_string", port); const auto response = HTTP(GET(url)); EXPECT_EQ(200, static_cast(response.code)); @@ -415,14 +401,9 @@ TEST(HTTPAPI, RespondsWithObject) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/responds_with_object", - [](Request r) { - r(HTTPAPITestObject(), - HTTPResponseCode.OK, - Headers({{"foo", "bar"}}), - "application/json"); - }); + const auto scope = http_server.Register("/responds_with_object", [](Request r) { + r(HTTPAPITestObject(), HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "application/json"); + }); const string url = Printf("http://localhost:%d/responds_with_object", port); const auto response = HTTP(GET(url)); EXPECT_EQ(200, static_cast(response.code)); @@ -456,12 +437,10 @@ TEST(HTTPAPI, HandlesRespondTwiceWithString) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/respond_twice", - [](Request r) { - r("OK"); - r("FAIL"); - }); + const auto scope = http_server.Register("/respond_twice", [](Request r) { + r("OK"); + r("FAIL"); + }); const string url = Printf("http://localhost:%d/respond_twice", port); const auto response = HTTP(GET(url)); EXPECT_EQ(200, static_cast(response.code)); @@ -476,19 +455,17 @@ TEST(HTTPAPI, HandlesRespondTwiceWithResponse) { std::string result = ""; std::atomic_bool result_ready(false); - const auto scope = http_server - .Register("/respond_twice", - [&result, &result_ready](Request r) { - r(Response("OK", HTTPResponseCode.OK)); - try { - r(Response("FAIL", HTTPResponseCode(762))); - result = "Error, second response did not throw."; - result_ready = true; - } catch (const current::net::AttemptedToSendHTTPResponseMoreThanOnce&) { - result = "OK, second response did throw."; - result_ready = true; - } - }); + const auto scope = http_server.Register("/respond_twice", [&result, &result_ready](Request r) { + r(Response("OK", HTTPResponseCode.OK)); + try { + r(Response("FAIL", HTTPResponseCode(762))); + result = "Error, second response did not throw."; + result_ready = true; + } catch (const current::net::AttemptedToSendHTTPResponseMoreThanOnce&) { + result = "OK, second response did throw."; + result_ready = true; + } + }); const string url = Printf("http://localhost:%d/respond_twice", port); const auto response = HTTP(GET(url)); EXPECT_EQ(200, static_cast(response.code)); @@ -508,26 +485,16 @@ TEST(HTTPAPI, RedirectToRelativeURL) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/from", - [](Request r) { - r("", - HTTPResponseCode.Found, - Headers({{"Location", "/to"}}), - current::net::constants::kDefaultHTMLContentType); - }) + - http_server.Register("/to", [](Request r) { r("Done."); }); + const auto scope = http_server.Register("/from", [](Request r) { + r("", HTTPResponseCode.Found, Headers({{"Location", "/to"}}), current::net::constants::kDefaultHTMLContentType); + }) + http_server.Register("/to", [](Request r) { r("Done."); }); // Redirect not allowed by default. ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/from", port))), HTTPRedirectNotAllowedException); // Redirect allowed when `.AllowRedirects()` is set. const auto response = HTTP(GET(Printf("http://localhost:%d/from", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(response.code)); EXPECT_EQ("Done.", response.body); - EXPECT_EQ(( - port == 80 - ? "http://localhost/to" - : Printf("http://localhost:%d/to", port) - ), response.url); + EXPECT_EQ((port == 80 ? "http://localhost/to" : Printf("http://localhost:%d/to", port)), response.url); } TEST(HTTPAPI, RedirectToFullURL) { @@ -541,15 +508,12 @@ TEST(HTTPAPI, RedirectToFullURL) { // Need a live port for the redirect target because the HTTP client is following the redirect // and tries to connect to the redirect target, otherwise throws a `SocketConnectException`. const auto scope_redirect_to = HTTP(std::move(second_reserved_port)).Register("/to", [](Request r) { r("Done."); }); - const auto scope = - http_server - .Register("/from", - [second_port](Request r) { - r("", - HTTPResponseCode.Found, - Headers({{"Location", Printf("http://localhost:%d/to", second_port)}}), - current::net::constants::kDefaultHTMLContentType); - }); + const auto scope = http_server.Register("/from", [second_port](Request r) { + r("", + HTTPResponseCode.Found, + Headers({{"Location", Printf("http://localhost:%d/to", second_port)}}), + current::net::constants::kDefaultHTMLContentType); + }); // Redirect not allowed by default. ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/from", port))), HTTPRedirectNotAllowedException); // Redirect allowed when `.AllowRedirects()` is set. @@ -593,30 +557,13 @@ TEST(HTTPAPI, RedirectLoop) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/p1", - [](Request r) { - r("", - HTTPResponseCode.Found, - Headers({{"Location", "/p2"}}), - current::net::constants::kDefaultHTMLContentType); - }) + - http_server - .Register("/p2", - [](Request r) { - r("", - HTTPResponseCode.Found, - Headers({{"Location", "/p3"}}), - current::net::constants::kDefaultHTMLContentType); - }) + - http_server - .Register("/p3", - [](Request r) { - r("", - HTTPResponseCode.Found, - Headers({{"Location", "/p1"}}), - current::net::constants::kDefaultHTMLContentType); - }); + const auto scope = http_server.Register("/p1", [](Request r) { + r("", HTTPResponseCode.Found, Headers({{"Location", "/p2"}}), current::net::constants::kDefaultHTMLContentType); + }) + http_server.Register("/p2", [](Request r) { + r("", HTTPResponseCode.Found, Headers({{"Location", "/p3"}}), current::net::constants::kDefaultHTMLContentType); + }) + http_server.Register("/p3", [](Request r) { + r("", HTTPResponseCode.Found, Headers({{"Location", "/p1"}}), current::net::constants::kDefaultHTMLContentType); + }); { bool thrown = false; try { @@ -647,11 +594,9 @@ TEST(HTTPAPI, ResponseDotNotation) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/response_dot_notation", - [](Request r) { - r(Response("OK").Code(HTTPResponseCode.Created).SetHeader("X-Foo", "bar")); - }); + const auto scope = http_server.Register("/response_dot_notation", [](Request r) { + r(Response("OK").Code(HTTPResponseCode.Created).SetHeader("X-Foo", "bar")); + }); const auto response = HTTP(GET(Printf("http://localhost:%d/response_dot_notation", port))); EXPECT_EQ("OK", response.body); EXPECT_EQ(201, static_cast(response.code)); @@ -659,22 +604,15 @@ TEST(HTTPAPI, ResponseDotNotation) { EXPECT_EQ("bar", response.headers.Get("X-Foo")); } -static Response BuildResponse() { - return Response("").Code(HTTPResponseCode.NoContent).SetHeader("X-Meh", "foo"); -} +static Response BuildResponse() { return Response("").Code(HTTPResponseCode.NoContent).SetHeader("X-Meh", "foo"); } TEST(HTTPAPI, ResponseDotNotationReturnedFromAFunction) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/response_returned_from_function", - [](Request r) { - r(BuildResponse()); - }); - const auto response = - HTTP(GET(Printf("http://localhost:%d/response_returned_from_function", port))); + const auto scope = http_server.Register("/response_returned_from_function", [](Request r) { r(BuildResponse()); }); + const auto response = HTTP(GET(Printf("http://localhost:%d/response_returned_from_function", port))); EXPECT_EQ("", response.body); EXPECT_EQ(204, static_cast(response.code)); EXPECT_TRUE(response.headers.Has("X-Meh")); @@ -702,14 +640,12 @@ TEST(HTTPAPI, FourOhFiveMethodNotAllowed) { auto& http_server = HTTP(std::move(reserved_port)); EXPECT_EQ("

METHOD NOT ALLOWED

\n", DefaultMethodNotAllowedMessage()); - const auto scope = http_server - .Register("/method_not_allowed", - [](Request r) { - r(DefaultMethodNotAllowedMessage(), - HTTPResponseCode.MethodNotAllowed, - current::net::http::Headers(), - current::net::constants::kDefaultHTMLContentType); - }); + const auto scope = http_server.Register("/method_not_allowed", [](Request r) { + r(DefaultMethodNotAllowedMessage(), + HTTPResponseCode.MethodNotAllowed, + current::net::http::Headers(), + current::net::constants::kDefaultHTMLContentType); + }); const string url = Printf("http://localhost:%d/method_not_allowed", port); const auto response = HTTP(GET(url)); EXPECT_EQ(405, static_cast(response.code)); @@ -742,12 +678,10 @@ TEST(HTTPAPI, DefaultInternalServerErrorCausedByExceptionInHandler) { auto& http_server = HTTP(std::move(reserved_port)); EXPECT_EQ("

INTERNAL SERVER ERROR

\n", DefaultInternalServerErrorMessage()); - const auto scope = http_server - .Register("/oh_snap", - [](Request) { - // Only `current::Exception` is caught and handled. - CURRENT_THROW(current::Exception()); - }); + const auto scope = http_server.Register("/oh_snap", [](Request) { + // Only `current::Exception` is caught and handled. + CURRENT_THROW(current::Exception()); + }); const string url = Printf("http://localhost:%d/oh_snap", port); const auto response = HTTP(GET(url)); EXPECT_EQ(500, static_cast(response.code)); @@ -771,8 +705,7 @@ TEST(HTTPAPI, HandlerIsCapturedByReference) { Helper copy(helper); EXPECT_EQ(0u, helper.counter); EXPECT_EQ(0u, copy.counter); - const auto scope = http_server.Register("/incr", helper) + - http_server.Register("/incr_same", helper) + + const auto scope = http_server.Register("/incr", helper) + http_server.Register("/incr_same", helper) + http_server.Register("/incr_copy", copy); EXPECT_EQ("Incremented two.", HTTP(GET(Printf("http://localhost:%d/incr", port))).body); EXPECT_EQ(1u, helper.counter); @@ -795,8 +728,7 @@ TEST(HTTPAPI, HandlerSupportsStaticMethods) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server.Register("/foo", Static::Foo) + - http_server.Register("/bar", Static::Bar); + const auto scope = http_server.Register("/foo", Static::Foo) + http_server.Register("/bar", Static::Bar); EXPECT_EQ("foo", HTTP(GET(Printf("http://localhost:%d/foo", port))).body); EXPECT_EQ("bar", HTTP(GET(Printf("http://localhost:%d/bar", port))).body); } @@ -813,33 +745,31 @@ TEST(HTTPAPI, GetToFile) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/stars", - [](Request r) { - const size_t n = atoi(r.url.query["n"].c_str()); - auto response = r.connection.SendChunkedHTTPResponse(); - const auto sleep = []() { - const uint64_t delay_between_chunks = []() { - bool& reduce = Singleton().yes; - if (!reduce) { - reduce = true; - return 10; - } else { - return 1; - } - }(); - std::this_thread::sleep_for(std::chrono::milliseconds(delay_between_chunks)); - }; - sleep(); - for (size_t i = 0; i < n; ++i) { - response.Send("*"); - sleep(); - response.Send(std::vector({'a', 'b'})); - sleep(); - response.Send(std::vector({0x31, 0x32})); - sleep(); - } - }); + const auto scope = http_server.Register("/stars", [](Request r) { + const size_t n = atoi(r.url.query["n"].c_str()); + auto response = r.connection.SendChunkedHTTPResponse(); + const auto sleep = []() { + const uint64_t delay_between_chunks = []() { + bool& reduce = Singleton().yes; + if (!reduce) { + reduce = true; + return 10; + } else { + return 1; + } + }(); + std::this_thread::sleep_for(std::chrono::milliseconds(delay_between_chunks)); + }; + sleep(); + for (size_t i = 0; i < n; ++i) { + response.Send("*"); + sleep(); + response.Send(std::vector({'a', 'b'})); + sleep(); + response.Send(std::vector({0x31, 0x32})); + sleep(); + } + }); current::FileSystem::MkDir(FLAGS_net_api_test_tmpdir, FileSystem::MkDirParameters::Silent); const string file_name = FLAGS_net_api_test_tmpdir + "/some_test_file_for_http_get"; const auto test_file_scope = FileSystem::ScopedRmFile(file_name); @@ -856,16 +786,14 @@ TEST(HTTPAPI, ChunkedResponseWithHeaders) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/chunked_with_header", - [](Request r) { - EXPECT_EQ("GET", r.method); - auto response = r.connection.SendChunkedHTTPResponse( - HTTPResponseCode.OK, Headers({{"header", "yeah"}}), "text/plain"); - response.Send("A"); - response.Send("B"); - response.Send("C"); - }); + const auto scope = http_server.Register("/chunked_with_header", [](Request r) { + EXPECT_EQ("GET", r.method); + auto response = + r.connection.SendChunkedHTTPResponse(HTTPResponseCode.OK, Headers({{"header", "yeah"}}), "text/plain"); + response.Send("A"); + response.Send("B"); + response.Send("C"); + }); const auto response = HTTP(GET(Printf("http://localhost:%d/chunked_with_header", port))); EXPECT_EQ(200, static_cast(response.code)); EXPECT_EQ("ABC", response.body); @@ -881,15 +809,13 @@ TEST(HTTPAPI, GetByChunksPrototype) { auto& http_server = HTTP(std::move(reserved_port)); // Handler returning the result chunk by chunk. - const auto scope = http_server - .Register("/chunks", - [](Request r) { - auto response = r.connection.SendChunkedHTTPResponse( - HTTPResponseCode.OK, Headers({{"header", "oh-well"}}), "text/plain"); - response.Send("1\n"); - response.Send("23\n"); - response.Send("456\n"); - }); + const auto scope = http_server.Register("/chunks", [](Request r) { + auto response = + r.connection.SendChunkedHTTPResponse(HTTPResponseCode.OK, Headers({{"header", "oh-well"}}), "text/plain"); + response.Send("1\n"); + response.Send("23\n"); + response.Send("456\n"); + }); const string url = Printf("http://localhost:%d/chunks", port); { // A conventional GET, ignoring chunk boundaries and concatenating all the data together. @@ -951,10 +877,12 @@ TEST(HTTPAPI, GetByChunksPrototype) { std::vector headers; std::vector chunk_by_chunk_response; - const auto header_callback = - [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }; - const auto chunk_callback = - [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }; + const auto header_callback = [&headers](const std::string& k, const std::string& v) { + headers.push_back(k + '=' + v); + }; + const auto chunk_callback = [&chunk_by_chunk_response](const std::string& s) { + chunk_by_chunk_response.push_back(s); + }; const auto done_callback = [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); }; current::http::GenericHTTPClientPOSIX client( @@ -972,11 +900,11 @@ TEST(HTTPAPI, GetByChunksPrototype) { std::vector headers; std::vector chunk_by_chunk_response; - const auto response = - HTTP(ChunkedGET(url, - [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }, - [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }, - [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); })); + const auto response = HTTP(ChunkedGET( + url, + [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }, + [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }, + [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); })); EXPECT_EQ(200, static_cast(response)); EXPECT_EQ("1\n|23\n|456\n|DONE", current::strings::Join(chunk_by_chunk_response, '|')); EXPECT_EQ(4u, headers.size()); @@ -1039,72 +967,74 @@ TEST(HTTPAPI, ChunkedBodySemantics) { std::vector headers; std::vector chunk_by_chunk_response; - const auto response = - HTTP(ChunkedGET(url, - [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }, - [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }, - [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); })); + const auto response = HTTP(ChunkedGET( + url, + [&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }, + [&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }, + [&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); })); EXPECT_EQ(200, static_cast(response)); - EXPECT_EQ( - "{\"s\":|\"foo\"|}\n{\"s\":\"bar\"}\n|{\"s\":\"baz\"}|DONE", - current::strings::Join(chunk_by_chunk_response, '|')); + EXPECT_EQ("{\"s\":|\"foo\"|}\n{\"s\":\"bar\"}\n|{\"s\":\"baz\"}|DONE", + current::strings::Join(chunk_by_chunk_response, '|')); EXPECT_EQ(4u, headers.size()); - EXPECT_EQ("Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive" - "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked", - current::strings::Join(headers, '|')); + EXPECT_EQ( + "Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive" + "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked", + current::strings::Join(headers, '|')); } { std::vector headers; std::vector chunk_by_chunk_response; - const auto response = HTTP(ChunkedGET(url) - .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }) - .OnChunk([&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }) - .OnDone([&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); })); + const auto response = + HTTP(ChunkedGET(url) + .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }) + .OnChunk([&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }) + .OnDone([&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); })); EXPECT_EQ(200, static_cast(response)); - EXPECT_EQ( - "{\"s\":|\"foo\"|}\n{\"s\":\"bar\"}\n|{\"s\":\"baz\"}|DONE", - current::strings::Join(chunk_by_chunk_response, '|')); + EXPECT_EQ("{\"s\":|\"foo\"|}\n{\"s\":\"bar\"}\n|{\"s\":\"baz\"}|DONE", + current::strings::Join(chunk_by_chunk_response, '|')); EXPECT_EQ(4u, headers.size()); - EXPECT_EQ("Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive" - "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked", - current::strings::Join(headers, '|')); + EXPECT_EQ( + "Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive" + "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked", + current::strings::Join(headers, '|')); } { std::vector headers; std::vector chunk_by_chunk_response; - const auto response = HTTP(ChunkedPOST(url, "test") - .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }) - .OnChunk([&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }) - .OnDone([&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); })); + const auto response = + HTTP(ChunkedPOST(url, "test") + .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }) + .OnChunk([&chunk_by_chunk_response](const std::string& s) { chunk_by_chunk_response.push_back(s); }) + .OnDone([&chunk_by_chunk_response]() { chunk_by_chunk_response.push_back("DONE"); })); EXPECT_EQ(200, static_cast(response)); - EXPECT_EQ( - "{\"s\":|\"foo\"|}\n{\"s\":\"test\"}\n|{\"s\":\"baz\"}|DONE", - current::strings::Join(chunk_by_chunk_response, '|')); + EXPECT_EQ("{\"s\":|\"foo\"|}\n{\"s\":\"test\"}\n|{\"s\":\"baz\"}|DONE", + current::strings::Join(chunk_by_chunk_response, '|')); EXPECT_EQ(4u, headers.size()); - EXPECT_EQ("Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive" - "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked", - current::strings::Join(headers, '|')); + EXPECT_EQ( + "Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive" + "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked", + current::strings::Join(headers, '|')); } { std::vector headers; std::vector line_by_line_response; - const auto response = HTTP(ChunkedPOST(url, "passed") - .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }) - .OnLine([&line_by_line_response](const std::string& s) { line_by_line_response.push_back(s); })); + const auto response = + HTTP(ChunkedPOST(url, "passed") + .OnHeader([&headers](const std::string& k, const std::string& v) { headers.push_back(k + '=' + v); }) + .OnLine([&line_by_line_response](const std::string& s) { line_by_line_response.push_back(s); })); EXPECT_EQ(200, static_cast(response)); - EXPECT_EQ( - "{\"s\":\"foo\"}|{\"s\":\"passed\"}|{\"s\":\"baz\"}", - current::strings::Join(line_by_line_response, '|')); + EXPECT_EQ("{\"s\":\"foo\"}|{\"s\":\"passed\"}|{\"s\":\"baz\"}", current::strings::Join(line_by_line_response, '|')); EXPECT_EQ(4u, headers.size()); - EXPECT_EQ("Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive" - "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked", - current::strings::Join(headers, '|')); + EXPECT_EQ( + "Content-Type=application/stream+json; charset=utf-8|Connection=keep-alive" + "|TestHeaderName=TestHeaderValue|Transfer-Encoding=chunked", + current::strings::Join(headers, '|')); } { @@ -1125,14 +1055,11 @@ TEST(HTTPAPI, PostFromBufferToBuffer) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/post", - [](Request r) { - ASSERT_FALSE(r.body.empty()); - r("Data: " + r.body); - }); - const auto response = - HTTP(POST(Printf("http://localhost:%d/post", port), "No shit!", "application/octet-stream")); + const auto scope = http_server.Register("/post", [](Request r) { + ASSERT_FALSE(r.body.empty()); + r("Data: " + r.body); + }); + const auto response = HTTP(POST(Printf("http://localhost:%d/post", port), "No shit!", "application/octet-stream")); EXPECT_EQ("Data: No shit!", response.body); } @@ -1141,17 +1068,13 @@ TEST(HTTPAPI, PostAStringAsString) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/post_string", - [](Request r) { - ASSERT_FALSE(r.body.empty()); - EXPECT_EQ("POST", r.method); - r(r.body); - }); + const auto scope = http_server.Register("/post_string", [](Request r) { + ASSERT_FALSE(r.body.empty()); + EXPECT_EQ("POST", r.method); + r(r.body); + }); EXPECT_EQ("std::string", - HTTP(POST(Printf("http://localhost:%d/post_string", port), - std::string("std::string"), - "text/plain")).body); + HTTP(POST(Printf("http://localhost:%d/post_string", port), std::string("std::string"), "text/plain")).body); } TEST(HTTPAPI, PostAStringAsConstCharPtr) { @@ -1159,17 +1082,16 @@ TEST(HTTPAPI, PostAStringAsConstCharPtr) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/post_const_char_ptr", - [](Request r) { - ASSERT_FALSE(r.body.empty()); - EXPECT_EQ("POST", r.method); - r(r.body); - }); + const auto scope = http_server.Register("/post_const_char_ptr", [](Request r) { + ASSERT_FALSE(r.body.empty()); + EXPECT_EQ("POST", r.method); + r(r.body); + }); EXPECT_EQ("const char*", HTTP(POST(Printf("http://localhost:%d/post_const_char_ptr", port), static_cast("const char*"), - "text/plain")).body); + "text/plain")) + .body); } TEST(HTTPAPI, PostWithEmptyBodyMustSetZeroContentLength) { @@ -1177,12 +1099,10 @@ TEST(HTTPAPI, PostWithEmptyBodyMustSetZeroContentLength) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/post", - [](Request r) { - ASSERT_TRUE(r.body.empty()); - r("Yo!\n"); - }); + const auto scope = http_server.Register("/post", [](Request r) { + ASSERT_TRUE(r.body.empty()); + r("Yo!\n"); + }); const auto response = HTTP(POST(Printf("http://localhost:%d/post", port), "")); EXPECT_EQ("Yo!\n", response.body); } @@ -1192,15 +1112,12 @@ TEST(HTTPAPI, RespondWithStringAsString) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/respond_with_std_string", - [](Request r) { - EXPECT_EQ("POST", r.method); - EXPECT_EQ("", r.body); - r.connection.SendHTTPResponse(std::string("std::string"), HTTPResponseCode.OK); - }); - EXPECT_EQ("std::string", - HTTP(POST(Printf("http://localhost:%d/respond_with_std_string", port), "")).body); + const auto scope = http_server.Register("/respond_with_std_string", [](Request r) { + EXPECT_EQ("POST", r.method); + EXPECT_EQ("", r.body); + r.connection.SendHTTPResponse(std::string("std::string"), HTTPResponseCode.OK); + }); + EXPECT_EQ("std::string", HTTP(POST(Printf("http://localhost:%d/respond_with_std_string", port), "")).body); } TEST(HTTPAPI, RespondWithStringAsConstCharPtr) { @@ -1208,15 +1125,11 @@ TEST(HTTPAPI, RespondWithStringAsConstCharPtr) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = - http_server - .Register("/respond_with_const_char_ptr", - [](Request r) { - EXPECT_EQ("", r.body); - r.connection.SendHTTPResponse(static_cast("const char*"), HTTPResponseCode.OK); - }); - EXPECT_EQ("const char*", - HTTP(POST(Printf("http://localhost:%d/respond_with_const_char_ptr", port), "")).body); + const auto scope = http_server.Register("/respond_with_const_char_ptr", [](Request r) { + EXPECT_EQ("", r.body); + r.connection.SendHTTPResponse(static_cast("const char*"), HTTPResponseCode.OK); + }); + EXPECT_EQ("const char*", HTTP(POST(Printf("http://localhost:%d/respond_with_const_char_ptr", port), "")).body); } TEST(HTTPAPI, RespondWithStringAsStringViaRequestDirectly) { @@ -1224,16 +1137,12 @@ TEST(HTTPAPI, RespondWithStringAsStringViaRequestDirectly) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/respond_with_std_string_via_request_directly", - [](Request r) { - EXPECT_EQ("", r.body); - r(std::string("std::string"), HTTPResponseCode.OK); - }); - EXPECT_EQ( - "std::string", - HTTP(POST(Printf("http://localhost:%d/respond_with_std_string_via_request_directly", port), - "")).body); + const auto scope = http_server.Register("/respond_with_std_string_via_request_directly", [](Request r) { + EXPECT_EQ("", r.body); + r(std::string("std::string"), HTTPResponseCode.OK); + }); + EXPECT_EQ("std::string", + HTTP(POST(Printf("http://localhost:%d/respond_with_std_string_via_request_directly", port), "")).body); } TEST(HTTPAPI, RespondWithStringAsConstCharPtrViaRequestDirectly) { @@ -1241,16 +1150,12 @@ TEST(HTTPAPI, RespondWithStringAsConstCharPtrViaRequestDirectly) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/respond_with_const_char_ptr_via_request_directly", - [](Request r) { - EXPECT_EQ("", r.body); - r(static_cast("const char*"), HTTPResponseCode.OK); - }); - EXPECT_EQ( - "const char*", - HTTP(POST(Printf("http://localhost:%d/respond_with_const_char_ptr_via_request_directly", port), - "")).body); + const auto scope = http_server.Register("/respond_with_const_char_ptr_via_request_directly", [](Request r) { + EXPECT_EQ("", r.body); + r(static_cast("const char*"), HTTPResponseCode.OK); + }); + EXPECT_EQ("const char*", + HTTP(POST(Printf("http://localhost:%d/respond_with_const_char_ptr_via_request_directly", port), "")).body); } CURRENT_STRUCT(SerializableObject) { @@ -1259,9 +1164,7 @@ CURRENT_STRUCT(SerializableObject) { std::string AsString() const { return Printf("%d:%s", static_cast(x), s.c_str()); } }; -CURRENT_STRUCT(AnotherSerializableObject) { - CURRENT_FIELD(z, uint32_t, 42u); -}; +CURRENT_STRUCT(AnotherSerializableObject) { CURRENT_FIELD(z, uint32_t, 42u); }; CURRENT_VARIANT(SerializableVariant, SerializableObject, AnotherSerializableObject); @@ -1278,8 +1181,7 @@ TEST(HTTPAPI, PostFromInvalidFile) { return port; }(); - ASSERT_THROW(HTTP(POSTFromFile( - Printf("http://localhost:%d/foo", port), non_existent_file_name, "text/plain")), + ASSERT_THROW(HTTP(POSTFromFile(Printf("http://localhost:%d/foo", port), non_existent_file_name, "text/plain")), FileException); } #endif @@ -1289,12 +1191,10 @@ TEST(HTTPAPI, PostFromFileToBuffer) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/post", - [](Request r) { - ASSERT_FALSE(r.body.empty()); - r("Voila: " + r.body); - }); + const auto scope = http_server.Register("/post", [](Request r) { + ASSERT_FALSE(r.body.empty()); + r("Voila: " + r.body); + }); current::FileSystem::MkDir(FLAGS_net_api_test_tmpdir, FileSystem::MkDirParameters::Silent); const string file_name = FLAGS_net_api_test_tmpdir + "/some_input_test_file_for_http_post"; const auto test_file_scope = FileSystem::ScopedRmFile(file_name); @@ -1312,12 +1212,10 @@ TEST(HTTPAPI, PostFromBufferToFile) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/post", - [](Request r) { - ASSERT_FALSE(r.body.empty()); - r("Meh: " + r.body); - }); + const auto scope = http_server.Register("/post", [](Request r) { + ASSERT_FALSE(r.body.empty()); + r("Meh: " + r.body); + }); current::FileSystem::MkDir(FLAGS_net_api_test_tmpdir, FileSystem::MkDirParameters::Silent); const string file_name = FLAGS_net_api_test_tmpdir + "/some_output_test_file_for_http_post"; const auto test_file_scope = FileSystem::ScopedRmFile(file_name); @@ -1334,12 +1232,10 @@ TEST(HTTPAPI, PostFromFileToFile) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/post", - [](Request r) { - ASSERT_FALSE(r.body.empty()); - r("Phew: " + r.body); - }); + const auto scope = http_server.Register("/post", [](Request r) { + ASSERT_FALSE(r.body.empty()); + r("Phew: " + r.body); + }); current::FileSystem::MkDir(FLAGS_net_api_test_tmpdir, FileSystem::MkDirParameters::Silent); const string request_file_name = FLAGS_net_api_test_tmpdir + "/some_complex_request_test_file_for_http_post"; const string response_file_name = FLAGS_net_api_test_tmpdir + "/some_complex_response_test_file_for_http_post"; @@ -1360,13 +1256,11 @@ TEST(HTTPAPI, HeadRequest) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/head", - [](Request r) { - EXPECT_EQ("HEAD", r.method); - ASSERT_TRUE(r.body.empty()); - r("", HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "text/html"); - }); + const auto scope = http_server.Register("/head", [](Request r) { + EXPECT_EQ("HEAD", r.method); + ASSERT_TRUE(r.body.empty()); + r("", HTTPResponseCode.OK, Headers({{"foo", "bar"}}), "text/html"); + }); const auto response = HTTP(HEAD(Printf("http://localhost:%d/head", port))); EXPECT_EQ(200, static_cast(response.code)); EXPECT_TRUE(response.body.empty()); @@ -1379,14 +1273,12 @@ TEST(HTTPAPI, DeleteRequest) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/delete", - [](Request r) { - EXPECT_EQ("DELETE", r.method); - ASSERT_TRUE(r.body.empty()); - SerializableObject object; - r(object); - }); + const auto scope = http_server.Register("/delete", [](Request r) { + EXPECT_EQ("DELETE", r.method); + ASSERT_TRUE(r.body.empty()); + SerializableObject object; + r(object); + }); const auto response = HTTP(DELETE(Printf("http://localhost:%d/delete", port))); EXPECT_EQ("42:foo", ParseJSON(response.body).AsString()); EXPECT_EQ(200, static_cast(response.code)); @@ -1397,13 +1289,11 @@ TEST(HTTPAPI, PatchRequest) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/patch", - [](Request r) { - EXPECT_EQ("PATCH", r.method); - EXPECT_EQ("test", r.body); - r("Patch OK."); - }); + const auto scope = http_server.Register("/patch", [](Request r) { + EXPECT_EQ("PATCH", r.method); + EXPECT_EQ("test", r.body); + r("Patch OK."); + }); const auto response = HTTP(PATCH(Printf("http://localhost:%d/patch", port), "test")); EXPECT_EQ("Patch OK.", response.body); EXPECT_EQ(200, static_cast(response.code)); @@ -1414,8 +1304,8 @@ TEST(HTTPAPI, UserAgent) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/ua", [](Request r) { r("TODO(dkorolev): Actually get passed in user agent."); }); + const auto scope = + http_server.Register("/ua", [](Request r) { r("TODO(dkorolev): Actually get passed in user agent."); }); const string url = Printf("http://localhost:%d/ua", port); const auto response = HTTP(GET(url).UserAgent("Blah")); EXPECT_EQ(url, response.url); @@ -1513,98 +1403,68 @@ TEST(HTTPAPI, ServeStaticFilesFrom) { // Redirect from directory without trailing slash to directory with trailing slash. { - ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/sub_dir", port))), - HTTPRedirectNotAllowedException); - const auto sub_dir_response = - HTTP(GET(Printf("http://localhost:%d/sub_dir", port)).AllowRedirects()); + ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/sub_dir", port))), HTTPRedirectNotAllowedException); + const auto sub_dir_response = HTTP(GET(Printf("http://localhost:%d/sub_dir", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(sub_dir_response.code)); - EXPECT_EQ(( - port == 80 - ? "http://localhost/sub_dir/" - : Printf("http://localhost:%d/sub_dir/", port) - ), sub_dir_response.url); + EXPECT_EQ((port == 80 ? "http://localhost/sub_dir/" : Printf("http://localhost:%d/sub_dir/", port)), + sub_dir_response.url); ASSERT_TRUE(sub_dir_response.headers.Has("Content-Type")); EXPECT_EQ("text/html", sub_dir_response.headers.Get("Content-Type")); EXPECT_EQ("

HTML sub_dir index

", sub_dir_response.body); } { - ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/sub_dir/sub_sub_dir", port))), - HTTPRedirectNotAllowedException); + ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/sub_dir/sub_sub_dir", port))), HTTPRedirectNotAllowedException); const auto sub_sub_dir_response = HTTP(GET(Printf("http://localhost:%d/sub_dir/sub_sub_dir", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(sub_sub_dir_response.code)); - EXPECT_EQ(( - port == 80 - ? "http://localhost/sub_dir/sub_sub_dir/" - : Printf("http://localhost:%d/sub_dir/sub_sub_dir/", port) - ), sub_sub_dir_response.url); + EXPECT_EQ((port == 80 ? "http://localhost/sub_dir/sub_sub_dir/" + : Printf("http://localhost:%d/sub_dir/sub_sub_dir/", port)), + sub_sub_dir_response.url); ASSERT_TRUE(sub_sub_dir_response.headers.Has("Content-Type")); EXPECT_EQ("text/html", sub_sub_dir_response.headers.Get("Content-Type")); EXPECT_EQ("

HTML sub_sub_dir index

", sub_sub_dir_response.body); } // Subdirectory index file. - EXPECT_EQ("

HTML sub_dir index

", - HTTP(GET(Printf("http://localhost:%d/sub_dir/", port))).body); - EXPECT_EQ("

HTML sub_dir index

", - HTTP(GET(Printf("http://localhost:%d/sub_dir/index.htm", port))).body); + EXPECT_EQ("

HTML sub_dir index

", HTTP(GET(Printf("http://localhost:%d/sub_dir/", port))).body); + EXPECT_EQ("

HTML sub_dir index

", HTTP(GET(Printf("http://localhost:%d/sub_dir/index.htm", port))).body); // File in subdirectory. - EXPECT_EQ("alert('JavaScript')", - HTTP(GET(Printf("http://localhost:%d/sub_dir/file_in_sub_dir.js", port))).body); + EXPECT_EQ("alert('JavaScript')", HTTP(GET(Printf("http://localhost:%d/sub_dir/file_in_sub_dir.js", port))).body); // Trailing slash for files should result in HTTP 404. - EXPECT_EQ(DefaultNotFoundMessage(), - HTTP(GET(Printf("http://localhost:%d/index.html/", port))).body); - EXPECT_EQ(DefaultNotFoundMessage(), - HTTP(GET(Printf("http://localhost:%d/sub_dir/index.htm/", port))).body); + EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/index.html/", port))).body); + EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/sub_dir/index.htm/", port))).body); // Hidden files should result in HTTP 404. EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/.DS_Store", port))).body); - EXPECT_EQ(DefaultNotFoundMessage(), - HTTP(GET(Printf("http://localhost:%d/sub_dir/.file_hidden", port))).body); + EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/sub_dir/.file_hidden", port))).body); // Missing index file should result in HTTP 404. - EXPECT_EQ(DefaultNotFoundMessage(), - HTTP(GET(Printf("http://localhost:%d/sub_dir_no_index", port))).body); - EXPECT_EQ(DefaultNotFoundMessage(), - HTTP(GET(Printf("http://localhost:%d/sub_dir_no_index/", port))).body); + EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/sub_dir_no_index", port))).body); + EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/sub_dir_no_index/", port))).body); // Hidden directory should result in HTTP 404. - EXPECT_EQ(DefaultNotFoundMessage(), - HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden", port))).body); - EXPECT_EQ(DefaultNotFoundMessage(), - HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden/", port))).body); - EXPECT_EQ(DefaultNotFoundMessage(), - HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden/index.html", port))).body); - EXPECT_EQ(404, - static_cast(HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden", port))).code)); - EXPECT_EQ( - 404, - static_cast( - HTTP(POST(Printf("http://localhost:%d/.sub_dir_hidden/index.html", port), "")).code)); + EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden", port))).body); + EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden/", port))).body); + EXPECT_EQ(DefaultNotFoundMessage(), HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden/index.html", port))).body); + EXPECT_EQ(404, static_cast(HTTP(GET(Printf("http://localhost:%d/.sub_dir_hidden", port))).code)); + EXPECT_EQ(404, static_cast(HTTP(POST(Printf("http://localhost:%d/.sub_dir_hidden/index.html", port), "")).code)); // POST to file URL. - EXPECT_EQ(DefaultMethodNotAllowedMessage(), - HTTP(POST(Printf("http://localhost:%d/file.html", port), "")).body); - EXPECT_EQ(405, - static_cast(HTTP(POST(Printf("http://localhost:%d/file.html", port), "")).code)); + EXPECT_EQ(DefaultMethodNotAllowedMessage(), HTTP(POST(Printf("http://localhost:%d/file.html", port), "")).body); + EXPECT_EQ(405, static_cast(HTTP(POST(Printf("http://localhost:%d/file.html", port), "")).code)); // PUT to file URL. - EXPECT_EQ(DefaultMethodNotAllowedMessage(), - HTTP(PUT(Printf("http://localhost:%d/file.html", port), "")).body); - EXPECT_EQ(405, - static_cast(HTTP(PUT(Printf("http://localhost:%d/file.html", port), "")).code)); + EXPECT_EQ(DefaultMethodNotAllowedMessage(), HTTP(PUT(Printf("http://localhost:%d/file.html", port), "")).body); + EXPECT_EQ(405, static_cast(HTTP(PUT(Printf("http://localhost:%d/file.html", port), "")).code)); // PATCH to file URL. - EXPECT_EQ(DefaultMethodNotAllowedMessage(), - HTTP(PATCH(Printf("http://localhost:%d/file.html", port), "")).body); - EXPECT_EQ(405, - static_cast(HTTP(PATCH(Printf("http://localhost:%d/file.html", port), "")).code)); + EXPECT_EQ(DefaultMethodNotAllowedMessage(), HTTP(PATCH(Printf("http://localhost:%d/file.html", port), "")).body); + EXPECT_EQ(405, static_cast(HTTP(PATCH(Printf("http://localhost:%d/file.html", port), "")).code)); // DELETE to file URL. - EXPECT_EQ(DefaultMethodNotAllowedMessage(), - HTTP(DELETE(Printf("http://localhost:%d/file.html", port))).body); + EXPECT_EQ(DefaultMethodNotAllowedMessage(), HTTP(DELETE(Printf("http://localhost:%d/file.html", port))).body); EXPECT_EQ(405, static_cast(HTTP(DELETE(Printf("http://localhost:%d/file.html", port))).code)); } @@ -1628,25 +1488,19 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefix) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = - http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/something"}); + const auto scope = http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/something"}); // Root index file. - EXPECT_EQ("

HTML index

", - HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body); + EXPECT_EQ("

HTML index

", HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body); // Redirect from directory without trailing slash to directory with trailing slash. { - ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), - HTTPRedirectNotAllowedException); - const auto dir_response = - HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects()); + ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), HTTPRedirectNotAllowedException); + const auto dir_response = HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(dir_response.code)); - EXPECT_EQ(( - port == 80 - ? "http://localhost/static/something/" - : Printf("http://localhost:%d/static/something/", port) - ), dir_response.url); + EXPECT_EQ( + (port == 80 ? "http://localhost/static/something/" : Printf("http://localhost:%d/static/something/", port)), + dir_response.url); EXPECT_EQ("

HTML index

", dir_response.body); } @@ -1661,31 +1515,26 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefix) { const auto sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(sub_dir_response.code)); - EXPECT_EQ(( - port == 80 - ? "http://localhost/static/something/sub_dir/" - : Printf("http://localhost:%d/static/something/sub_dir/", port) - ), sub_dir_response.url); + EXPECT_EQ((port == 80 ? "http://localhost/static/something/sub_dir/" + : Printf("http://localhost:%d/static/something/sub_dir/", port)), + sub_dir_response.url); EXPECT_EQ("

HTML sub_dir index

", sub_dir_response.body); } // Subsubdirectory index file. - EXPECT_EQ( - "

HTML sub_sub_dir index

", - HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body); + EXPECT_EQ("

HTML sub_sub_dir index

", + HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body); // Redirect from subsubdirectory without trailing slash to subsubdirectory with trailing slash. { ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port))), HTTPRedirectNotAllowedException); - const auto sub_sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", - port)).AllowRedirects()); + const auto sub_sub_dir_response = + HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(sub_sub_dir_response.code)); - EXPECT_EQ(( - port == 80 - ? "http://localhost/static/something/sub_dir/sub_sub_dir/" - : Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port) - ), sub_sub_dir_response.url); + EXPECT_EQ((port == 80 ? "http://localhost/static/something/sub_dir/sub_sub_dir/" + : Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port)), + sub_sub_dir_response.url); EXPECT_EQ("

HTML sub_sub_dir index

", sub_sub_dir_response.body); } } @@ -1717,25 +1566,19 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixAndPublicUrlPrefixRela const auto scope_redirect_to = http_server.Register("/anything", URLPathArgs::CountMask::Any, [](Request r) { r("Done."); }); - const auto scope = http_server - .ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/something", "/anything"}); + const auto scope = + http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/something", "/anything"}); // Root index file. - EXPECT_EQ("

HTML index

", - HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body); + EXPECT_EQ("

HTML index

", HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body); // Redirect from directory without trailing slash to directory with trailing slash. { - ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), - HTTPRedirectNotAllowedException); - const auto dir_response = - HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects()); + ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), HTTPRedirectNotAllowedException); + const auto dir_response = HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(dir_response.code)); - EXPECT_EQ(( - port == 80 - ? "http://localhost/anything/" - : Printf("http://localhost:%d/anything/", port) - ), dir_response.url); + EXPECT_EQ((port == 80 ? "http://localhost/anything/" : Printf("http://localhost:%d/anything/", port)), + dir_response.url); EXPECT_EQ("Done.", dir_response.body); } @@ -1750,31 +1593,26 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixAndPublicUrlPrefixRela const auto sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(sub_dir_response.code)); - EXPECT_EQ(( - port == 80 - ? "http://localhost/anything/sub_dir/" - : Printf("http://localhost:%d/anything/sub_dir/", port) - ), sub_dir_response.url); + EXPECT_EQ( + (port == 80 ? "http://localhost/anything/sub_dir/" : Printf("http://localhost:%d/anything/sub_dir/", port)), + sub_dir_response.url); EXPECT_EQ("Done.", sub_dir_response.body); } // Subsubdirectory index file. - EXPECT_EQ( - "

HTML sub_sub_dir index

", - HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body); + EXPECT_EQ("

HTML sub_sub_dir index

", + HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body); // Redirect from subsubdirectory without trailing slash to subsubdirectory with trailing slash. { ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port))), HTTPRedirectNotAllowedException); - const auto sub_sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", - port)).AllowRedirects()); + const auto sub_sub_dir_response = + HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(sub_sub_dir_response.code)); - EXPECT_EQ(( - port == 80 - ? "http://localhost/anything/sub_dir/sub_sub_dir/" - : Printf("http://localhost:%d/anything/sub_dir/sub_sub_dir/", port) - ), sub_sub_dir_response.url); + EXPECT_EQ((port == 80 ? "http://localhost/anything/sub_dir/sub_sub_dir/" + : Printf("http://localhost:%d/anything/sub_dir/sub_sub_dir/", port)), + sub_sub_dir_response.url); EXPECT_EQ("Done.", sub_sub_dir_response.body); } } @@ -1809,29 +1647,19 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixAndPublicUrlPrefixAbso const auto scope_redirect_to = HTTP(std::move(second_reserved_port)).Register("/", URLPathArgs::CountMask::Any, [](Request r) { r("Done."); }); - const auto scope = - http_server - .ServeStaticFilesFrom( - dir, - ServeStaticFilesFromOptions{"/static/something", - Printf("http://localhost:%d/anything", second_port)}); + const auto scope = http_server.ServeStaticFilesFrom( + dir, ServeStaticFilesFromOptions{"/static/something", Printf("http://localhost:%d/anything", second_port)}); // Root index file. - EXPECT_EQ("

HTML index

", - HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body); + EXPECT_EQ("

HTML index

", HTTP(GET(Printf("http://localhost:%d/static/something/", port))).body); // Redirect from directory without trailing slash to directory with trailing slash. { - ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), - HTTPRedirectNotAllowedException); - const auto dir_response = - HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects()); + ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something", port))), HTTPRedirectNotAllowedException); + const auto dir_response = HTTP(GET(Printf("http://localhost:%d/static/something", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(dir_response.code)); - EXPECT_EQ(( - second_port == 80 - ? "http://localhost/anything/" - : Printf("http://localhost:%d/anything/", second_port) - ), dir_response.url); + EXPECT_EQ((second_port == 80 ? "http://localhost/anything/" : Printf("http://localhost:%d/anything/", second_port)), + dir_response.url); EXPECT_EQ("Done.", dir_response.body); } @@ -1846,31 +1674,26 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixAndPublicUrlPrefixAbso const auto sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(sub_dir_response.code)); - EXPECT_EQ(( - second_port == 80 - ? "http://localhost/anything/sub_dir/" - : Printf("http://localhost:%d/anything/sub_dir/", second_port) - ), sub_dir_response.url); + EXPECT_EQ((second_port == 80 ? "http://localhost/anything/sub_dir/" + : Printf("http://localhost:%d/anything/sub_dir/", second_port)), + sub_dir_response.url); EXPECT_EQ("Done.", sub_dir_response.body); } // Subsubdirectory index file. - EXPECT_EQ( - "

HTML sub_sub_dir index

", - HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body); + EXPECT_EQ("

HTML sub_sub_dir index

", + HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir/", port))).body); // Redirect from subsubdirectory without trailing slash to subsubdirectory with trailing slash. { ASSERT_THROW(HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port))), HTTPRedirectNotAllowedException); - const auto sub_sub_dir_response = HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", - port)).AllowRedirects()); + const auto sub_sub_dir_response = + HTTP(GET(Printf("http://localhost:%d/static/something/sub_dir/sub_sub_dir", port)).AllowRedirects()); EXPECT_EQ(200, static_cast(sub_sub_dir_response.code)); - EXPECT_EQ(( - second_port == 80 - ? "http://localhost/anything/sub_dir/sub_sub_dir/" - : Printf("http://localhost:%d/anything/sub_dir/sub_sub_dir/", second_port) - ), sub_sub_dir_response.url); + EXPECT_EQ((second_port == 80 ? "http://localhost/anything/sub_dir/sub_sub_dir/" + : Printf("http://localhost:%d/anything/sub_dir/sub_sub_dir/", second_port)), + sub_sub_dir_response.url); EXPECT_EQ("Done.", sub_sub_dir_response.body); } } @@ -1882,8 +1705,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomRoutePrefixWithTrailingSlash) { auto& http_server = HTTP(std::move(reserved_port)); const std::string dir = FileSystem::JoinPath(FLAGS_net_api_test_tmpdir, "static"); - ASSERT_THROW(http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/"}), - PathEndsWithSlash); + ASSERT_THROW(http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/static/"}), PathEndsWithSlash); } TEST(HTTPAPI, ServeStaticFilesFromOptionsEmptyPublicRoutePrefix) { @@ -1893,8 +1715,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsEmptyPublicRoutePrefix) { auto& http_server = HTTP(std::move(reserved_port)); const std::string dir = FileSystem::JoinPath(FLAGS_net_api_test_tmpdir, "static"); - ASSERT_THROW(http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{""}), - PathDoesNotStartWithSlash); + ASSERT_THROW(http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{""}), PathDoesNotStartWithSlash); } TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomIndexFiles) { @@ -1909,8 +1730,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOptionsCustomIndexFiles) { const auto dir_remover = current::FileSystem::ScopedRmDir(dir); FileSystem::MkDir(dir, FileSystem::MkDirParameters::Silent); FileSystem::WriteStringToFile("TXT index", FileSystem::JoinPath(dir, "index.txt").c_str()); - const auto scope = - http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/", "", {"index.txt"}}); + const auto scope = http_server.ServeStaticFilesFrom(dir, ServeStaticFilesFromOptions{"/", "", {"index.txt"}}); EXPECT_EQ("TXT index", HTTP(GET(Printf("http://localhost:%d/", port))).body); EXPECT_EQ("TXT index", HTTP(GET(Printf("http://localhost:%d/index.txt", port))).body); } @@ -1927,8 +1747,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOnlyServesOneIndexFilePerDirectory) { FileSystem::MkDir(dir, FileSystem::MkDirParameters::Silent); FileSystem::WriteStringToFile("

HTML index 1

", FileSystem::JoinPath(dir, "index.html").c_str()); FileSystem::WriteStringToFile("

HTML index 2

", FileSystem::JoinPath(dir, "index.htm").c_str()); - ASSERT_THROW(http_server.ServeStaticFilesFrom(dir), - ServeStaticFilesFromCannotServeMoreThanOneIndexFile); + ASSERT_THROW(http_server.ServeStaticFilesFrom(dir), ServeStaticFilesFromCannotServeMoreThanOneIndexFile); } TEST(HTTPAPI, ServeStaticFilesFromOnlyServesFilesOfKnownMIMEType) { @@ -1943,8 +1762,7 @@ TEST(HTTPAPI, ServeStaticFilesFromOnlyServesFilesOfKnownMIMEType) { FileSystem::MkDir(dir, FileSystem::MkDirParameters::Silent); FileSystem::WriteStringToFile("TXT is okay.", FileSystem::JoinPath(dir, "file.txt").c_str()); FileSystem::WriteStringToFile("FOO is not! ", FileSystem::JoinPath(dir, "file.foo").c_str()); - ASSERT_THROW(http_server.ServeStaticFilesFrom(dir), - ServeStaticFilesFromCanNotServeStaticFilesOfUnknownMIMEType); + ASSERT_THROW(http_server.ServeStaticFilesFrom(dir), ServeStaticFilesFromCanNotServeStaticFilesOfUnknownMIMEType); } TEST(HTTPAPI, ResponseSmokeTest) { @@ -1954,62 +1772,34 @@ TEST(HTTPAPI, ResponseSmokeTest) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = - http_server - .Register("/response1", [send_response](Request r) { send_response(Response("foo"), std::move(r)); }) + - http_server - .Register( - "/response2", - [send_response](Request r) { send_response(Response("bar", HTTPResponseCode.Accepted), std::move(r)); }) + - http_server - .Register("/response3", - [send_response](Request r) { - send_response(Response("baz", HTTPResponseCode.NotFound, "text/blah"), std::move(r)); - }) + - http_server - .Register("/response4", - [send_response](Request r) { - send_response(Response(SerializableObject(), HTTPResponseCode.Accepted), std::move(r)); - }) + - http_server - .Register("/response5", - [send_response](Request r) { - send_response(Response(SerializableObject(), "meh").Code(HTTPResponseCode.Created), std::move(r)); - }) + - http_server - .Register("/response6", - [send_response](Request r) { - send_response(Response().Body("OK").Code(HTTPResponseCode.OK), std::move(r)); - }) + - http_server - .Register("/response7", - [send_response](Request r) { - send_response(Response().JSON(SerializableObject(), "magic").Code(HTTPResponseCode.OK), - std::move(r)); - }) + - http_server - .Register("/response8", - [send_response](Request r) { send_response(Response(HTTPResponseCode.Created), std::move(r)); }) + - http_server - .Register("/response9", - [send_response](Request r) { - send_response(Response(), std::move(r)); // Will result in a 500 "INTERNAL SERVER ERROR". - }) + - http_server - .Register("/response10", - [](Request r) { - SerializableVariant v; - v.template Construct(); - r(v); - }) + - http_server - .Register("/response11", - [send_response](Request r) { - // Test both a direct response (`Request::operator()`) and a response via `Respose`. - SerializableVariant v; - v.template Construct(); - send_response(v, std::move(r)); - }); + const auto scope = http_server.Register("/response1", [send_response](Request r) { + send_response(Response("foo"), std::move(r)); + }) + http_server.Register("/response2", [send_response](Request r) { + send_response(Response("bar", HTTPResponseCode.Accepted), std::move(r)); + }) + http_server.Register("/response3", [send_response](Request r) { + send_response(Response("baz", HTTPResponseCode.NotFound, "text/blah"), std::move(r)); + }) + http_server.Register("/response4", [send_response](Request r) { + send_response(Response(SerializableObject(), HTTPResponseCode.Accepted), std::move(r)); + }) + http_server.Register("/response5", [send_response](Request r) { + send_response(Response(SerializableObject(), "meh").Code(HTTPResponseCode.Created), std::move(r)); + }) + http_server.Register("/response6", [send_response](Request r) { + send_response(Response().Body("OK").Code(HTTPResponseCode.OK), std::move(r)); + }) + http_server.Register("/response7", [send_response](Request r) { + send_response(Response().JSON(SerializableObject(), "magic").Code(HTTPResponseCode.OK), std::move(r)); + }) + http_server.Register("/response8", [send_response](Request r) { + send_response(Response(HTTPResponseCode.Created), std::move(r)); + }) + http_server.Register("/response9", [send_response](Request r) { + send_response(Response(), std::move(r)); // Will result in a 500 "INTERNAL SERVER ERROR". + }) + http_server.Register("/response10", [](Request r) { + SerializableVariant v; + v.template Construct(); + r(v); + }) + http_server.Register("/response11", [send_response](Request r) { + // Test both a direct response (`Request::operator()`) and a response via `Respose`. + SerializableVariant v; + v.template Construct(); + send_response(v, std::move(r)); + }); const auto response1 = HTTP(GET(Printf("http://localhost:%d/response1", port))); EXPECT_EQ(200, static_cast(response1.code)); @@ -2068,20 +1858,17 @@ TEST(HTTPAPI, PayloadTooLarge) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = http_server - .Register("/enough_is_enough", - [](Request r) { - ASSERT_FALSE(r.body.empty()); - EXPECT_EQ("POST", r.method); - r("Fits.\n"); - }); + const auto scope = http_server.Register("/enough_is_enough", [](Request r) { + ASSERT_FALSE(r.body.empty()); + EXPECT_EQ("POST", r.method); + r("Fits.\n"); + }); { const size_t size_ok = 16 * 1024 * 1024; ASSERT_EQ(current::net::constants::kMaxHTTPPayloadSizeInBytes, size_ok); - const auto response = - HTTP(POST(Printf("http://localhost:%d/enough_is_enough", port), std::string(size_ok, '.'))); + const auto response = HTTP(POST(Printf("http://localhost:%d/enough_is_enough", port), std::string(size_ok, '.'))); EXPECT_EQ(200, static_cast(response.code)); EXPECT_EQ("Fits.\n", response.body); } @@ -2089,8 +1876,8 @@ TEST(HTTPAPI, PayloadTooLarge) { const size_t size_too_much = 16 * 1024 * 1024 + 1; ASSERT_GT(size_too_much, current::net::constants::kMaxHTTPPayloadSizeInBytes); - const auto response = HTTP( - POST(Printf("http://localhost:%d/enough_is_enough", port), std::string(size_too_much, '.'))); + const auto response = + HTTP(POST(Printf("http://localhost:%d/enough_is_enough", port), std::string(size_too_much, '.'))); EXPECT_EQ(413, static_cast(response.code)); EXPECT_EQ("

ENTITY TOO LARGE

\n", response.body); } @@ -2108,23 +1895,18 @@ TEST(HTTPAPI, ResponseGeneratorForSerializableAndNonSerializableTypes) { const int port = reserved_port; auto& http_server = HTTP(std::move(reserved_port)); - const auto scope = - http_server - .Register( - "/maybe_json", - [](Request r) { - if (r.url.query.has("json")) { - static_assert(current::serialization::json::IsJSONSerializable::value, ""); - r(current::http::GenerateResponseFromMaybeSerializableObject< - HTTPAPITemplatedTestObject>(HTTPAPITemplatedTestObject())); - } else { - static_assert(!current::serialization::json::IsJSONSerializable::value, - ""); - r(current::http::GenerateResponseFromMaybeSerializableObject< - HTTPAPITemplatedTestObject>( - HTTPAPITemplatedTestObject())); - } - }); + const auto scope = http_server.Register("/maybe_json", [](Request r) { + if (r.url.query.has("json")) { + static_assert(current::serialization::json::IsJSONSerializable::value, ""); + r(current::http::GenerateResponseFromMaybeSerializableObject>( + HTTPAPITemplatedTestObject())); + } else { + static_assert(!current::serialization::json::IsJSONSerializable::value, ""); + r(current::http::GenerateResponseFromMaybeSerializableObject< + HTTPAPITemplatedTestObject>( + HTTPAPITemplatedTestObject())); + } + }); { const auto response = HTTP(GET(Printf("http://localhost:%d/maybe_json?json", port))); EXPECT_EQ("{\"text\":\"OK\",\"data\":{\"number\":42,\"text\":\"text\",\"array\":[1,2,3]}}\n", response.body); @@ -2178,8 +1960,7 @@ TEST(HTTPAPI, JSONDoesHaveCORSHeaderByDefault) { auto& http_server = HTTP(std::move(reserved_port)); { - const auto scope = - http_server.Register("/json1", [](Request r) { r(Response(SerializableObject())); }); + const auto scope = http_server.Register("/json1", [](Request r) { r(Response(SerializableObject())); }); const auto response = HTTP(GET(Printf("http://localhost:%d/json1", port))); EXPECT_EQ(200, static_cast(response.code)); @@ -2188,9 +1969,8 @@ TEST(HTTPAPI, JSONDoesHaveCORSHeaderByDefault) { EXPECT_EQ("*", response.headers.Get("Access-Control-Allow-Origin")); } { - const auto scope = http_server.Register("/json2", [](Request r) { - r(Response(SerializableObject()).DisableCORS()); - }); + const auto scope = + http_server.Register("/json2", [](Request r) { r(Response(SerializableObject()).DisableCORS()); }); const auto response = HTTP(GET(Printf("http://localhost:%d/json2", port))); EXPECT_EQ(200, static_cast(response.code)); @@ -2198,9 +1978,8 @@ TEST(HTTPAPI, JSONDoesHaveCORSHeaderByDefault) { EXPECT_FALSE(response.headers.Has("Access-Control-Allow-Origin")); } { - const auto scope = http_server.Register("/json3", [](Request r) { - r(Response(SerializableObject()).DisableCORS().EnableCORS()); - }); + const auto scope = + http_server.Register("/json3", [](Request r) { r(Response(SerializableObject()).DisableCORS().EnableCORS()); }); const auto response = HTTP(GET(Printf("http://localhost:%d/json3", port))); EXPECT_EQ(200, static_cast(response.code)); diff --git a/blocks/http/types.h b/blocks/http/types.h index f6dc9ac7f..2ea97d2c4 100644 --- a/blocks/http/types.h +++ b/blocks/http/types.h @@ -103,15 +103,16 @@ struct ChunkedBase { std::function done_callback_impl; explicit ChunkedBase(std::string url) - : url(std::move(url)), - header_callback([this](const std::string& k, const std::string& v) { header_callback_wrapper(k, v); }), - chunk_callback([this](const std::string& c) { chunk_callback_wrapper(c); }), - done_callback([this]() { done_callback_wrapper(); }) {} - - explicit ChunkedBase(std::string url, - std::function header_callback, - std::function chunk_callback, - std::function done_callback = []() {}) + : url(std::move(url)), + header_callback([this](const std::string& k, const std::string& v) { header_callback_wrapper(k, v); }), + chunk_callback([this](const std::string& c) { chunk_callback_wrapper(c); }), + done_callback([this]() { done_callback_wrapper(); }) {} + + explicit ChunkedBase( + std::string url, + std::function header_callback, + std::function chunk_callback, + std::function done_callback = []() {}) : ChunkedBase(std::move(url)) { header_callback_impl = header_callback; chunk_callback_impl = chunk_callback; @@ -135,7 +136,7 @@ struct ChunkedBase { // TODO(dkorolev): Move this to `Chunk`-s if performance becomes the bottleneck. T& OnLine(std::function line_callback) { group_by_lines_.emplace_back(std::make_unique( - [line_callback](const std::string& line) { line_callback(line); })); + [line_callback](const std::string& line) { line_callback(line); })); return static_cast(*this); } @@ -168,12 +169,13 @@ struct ChunkedGET final : ChunkedBase { struct ChunkedPOST final : ChunkedBase { const std::string body; const std::string content_type; - explicit ChunkedPOST(std::string url, - std::string body, - std::string content_type, - std::function header_callback, - std::function chunk_callback, - std::function done_callback = []() {}) + explicit ChunkedPOST( + std::string url, + std::string body, + std::string content_type, + std::function header_callback, + std::function chunk_callback, + std::function done_callback = []() {}) : ChunkedBase(std::move(url), header_callback, chunk_callback, done_callback), body(std::move(body)), content_type(std::move(content_type)) {} @@ -202,8 +204,9 @@ struct FillBody { template struct FillBody { template - static std::enable_if_t)> Fill( - REQUEST& request, T&& object, const std::string& content_type) { + static std::enable_if_t)> Fill(REQUEST& request, + T&& object, + const std::string& content_type) { request.body = JSON(std::forward(object)); request.content_type = !content_type.empty() ? content_type : net::constants::kDefaultJSONContentType; } @@ -214,8 +217,7 @@ struct POST : HTTPRequestBase { std::string content_type; template - POST(const std::string& url, T&& body, const std::string& content_type = "") - : HTTPRequestBase(url) { + POST(const std::string& url, T&& body, const std::string& content_type = "") : HTTPRequestBase(url) { FillBody::value>::Fill(*this, std::forward(body), content_type); } }; @@ -233,8 +235,7 @@ struct PUT : HTTPRequestBase { std::string content_type; template - PUT(const std::string& url, T&& body, const std::string& content_type = "") - : HTTPRequestBase(url) { + PUT(const std::string& url, T&& body, const std::string& content_type = "") : HTTPRequestBase(url) { FillBody::value>::Fill(*this, std::forward(body), content_type); } }; @@ -244,8 +245,7 @@ struct PATCH : HTTPRequestBase { std::string content_type; template - PATCH(const std::string& url, T&& body, const std::string& content_type = "") - : HTTPRequestBase(url) { + PATCH(const std::string& url, T&& body, const std::string& content_type = "") : HTTPRequestBase(url) { FillBody::value>::Fill(*this, std::forward(body), content_type); } }; @@ -398,13 +398,13 @@ struct HTTPImpl { } // namespace http } // namespace current +using current::http::DELETE; using current::http::GET; using current::http::HEAD; +using current::http::PATCH; using current::http::POST; using current::http::POSTFromFile; using current::http::PUT; -using current::http::PATCH; -using current::http::DELETE; using current::http::ChunkedGET; using current::http::ChunkedPOST; diff --git a/blocks/json/json.h b/blocks/json/json.h index c282c9aec..6ad0f55fd 100644 --- a/blocks/json/json.h +++ b/blocks/json/json.h @@ -75,14 +75,14 @@ CURRENT_STRUCT(JSONString) { CURRENT_FIELD(string, std::string); CURRENT_CONSTRUCTOR(JSONString)(std::string string = "") : string(std::move(string)) {} operator std::string() const { return string; } - void DoAppendToJSON(std::ostream& os) const { os << JSON(string); } + void DoAppendToJSON(std::ostream & os) const { os << JSON(string); } }; CURRENT_STRUCT(JSONNumber) { CURRENT_FIELD(number, double); CURRENT_CONSTRUCTOR(JSONNumber)(double number = 0) : number(number) {} operator double() const { return number; } - void DoAppendToJSON(std::ostream& os) const { + void DoAppendToJSON(std::ostream & os) const { if (number == std::floor(number)) { if (number < 0) { os << JSON(static_cast(number)); @@ -99,7 +99,7 @@ CURRENT_STRUCT(JSONBoolean) { CURRENT_FIELD(boolean, bool); CURRENT_CONSTRUCTOR(JSONBoolean)(bool boolean = false) : boolean(boolean) {} operator bool() const { return boolean; } - void DoAppendToJSON(std::ostream& os) const { os << JSON(boolean); } + void DoAppendToJSON(std::ostream & os) const { os << JSON(boolean); } }; // clang-format off @@ -119,7 +119,7 @@ CURRENT_STRUCT(JSONArray) { static JSONValue null((JSONNull())); return i < elements.size() ? elements[i] : null; } - void DoAppendToJSON(std::ostream& os) const { + void DoAppendToJSON(std::ostream & os) const { os << '['; bool first = true; for (const JSONValue& element : elements) { @@ -133,19 +133,11 @@ CURRENT_STRUCT(JSONArray) { os << ']'; } using iterator = typename std::vector::iterator; - iterator begin() { - return elements.begin(); - } - iterator end() { - return elements.end(); - } + iterator begin() { return elements.begin(); } + iterator end() { return elements.end(); } using const_iterator = typename std::vector::const_iterator; - const_iterator begin() const { - return elements.begin(); - } - const_iterator end() const { - return elements.end(); - } + const_iterator begin() const { return elements.begin(); } + const_iterator end() const { return elements.end(); } }; CURRENT_STRUCT(JSONObject) { @@ -176,7 +168,7 @@ CURRENT_STRUCT(JSONObject) { fields.erase(name); return *this; } - void DoAppendToJSON(std::ostream& os) const { + void DoAppendToJSON(std::ostream & os) const { os << '{'; bool first = true; for (const std::string& key : keys) { @@ -201,19 +193,11 @@ CURRENT_STRUCT(JSONObject) { const_iterator(const JSONObject& self, std::vector::const_iterator cit) : self(self), cit(cit) {} bool operator==(const const_iterator& rhs) const { return cit == rhs.cit; } bool operator!=(const const_iterator& rhs) const { return cit != rhs.cit; } - const_element operator*() const { - return const_element(*cit, self.fields.at(*cit)); - } - void operator++() { - ++cit; - } + const_element operator*() const { return const_element(*cit, self.fields.at(*cit)); } + void operator++() { ++cit; } }; - const_iterator begin() const { - return const_iterator(*this, keys.begin()); - } - const_iterator end() const { - return const_iterator(*this, keys.end()); - } + const_iterator begin() const { return const_iterator(*this, keys.begin()); } + const_iterator end() const { return const_iterator(*this, keys.end()); } }; inline JSONValue ParseJSONUniversally(rapidjson::Value& value) { diff --git a/blocks/json/test.cc b/blocks/json/test.cc index b1eb76b3e..8402b8e52 100644 --- a/blocks/json/test.cc +++ b/blocks/json/test.cc @@ -121,9 +121,8 @@ TEST(UniversalJSON, Object) { using JO = JSONObject; using JN = JSONNumber; - EXPECT_EQ( - "{\"x\":42,\"y\":{\"a\":1,\"b\":2}}", - AsJSON(JO().push_back("x", JN(42)).push_back("y", JO().push_back("a", JN(1)).push_back("b", JN(2))))); + EXPECT_EQ("{\"x\":42,\"y\":{\"a\":1,\"b\":2}}", + AsJSON(JO().push_back("x", JN(42)).push_back("y", JO().push_back("a", JN(1)).push_back("b", JN(2))))); } TEST(UniversalJSON, FloatingPoint) { diff --git a/blocks/mmq/mmpq.h b/blocks/mmq/mmpq.h index 395110460..879ff749f 100644 --- a/blocks/mmq/mmpq.h +++ b/blocks/mmq/mmpq.h @@ -108,11 +108,9 @@ class MMPQImpl { while (true) { std::unique_lock lock(mutex_); - condition_variable_.wait(lock, - [this] { - return (!queue_.empty() && queue_.begin()->index_timestamp.us <= last_idx_ts_.us) || - destructing_; - }); + condition_variable_.wait(lock, [this] { + return (!queue_.empty() && queue_.begin()->index_timestamp.us <= last_idx_ts_.us) || destructing_; + }); if (destructing_) { return; // LCOV_EXCL_LINE diff --git a/blocks/mmq/test.cc b/blocks/mmq/test.cc index 109e9129d..7d79e58c3 100644 --- a/blocks/mmq/test.cc +++ b/blocks/mmq/test.cc @@ -37,8 +37,8 @@ SOFTWARE. #include "../../3rdparty/gtest/gtest-main.h" -using current::mmq::MMQ; using current::mmq::MMPQ; +using current::mmq::MMQ; using current::ss::EntryResponse; TEST(InMemoryMQ, SmokeTest) { diff --git a/blocks/persistence/exceptions.h b/blocks/persistence/exceptions.h index 3cd59cc84..d27d3a563 100644 --- a/blocks/persistence/exceptions.h +++ b/blocks/persistence/exceptions.h @@ -70,7 +70,7 @@ struct UnsafePublishBadIndexTimestampException : PersistenceException { "Expecting index %lld, seeing %lld.", static_cast(expected), static_cast(found))) {} }; -} // namespace peristence +} // namespace persistence } // namespace current #endif // BLOCKS_PERSISTENCE_EXCEPTIONS_H diff --git a/blocks/persistence/file.h b/blocks/persistence/file.h index b971a39bd..f74387d41 100644 --- a/blocks/persistence/file.h +++ b/blocks/persistence/file.h @@ -61,7 +61,7 @@ constexpr char kDirectiveMarker = '#'; constexpr char kSignatureDirective[] = "#signature"; constexpr char kHeadDirective[] = "#head"; constexpr char kHeadFormatString[] = "%020lld"; -} // namespace current::persistence::impl::constants +} // namespace constants typedef int64_t head_value_t; @@ -460,7 +460,8 @@ class FilePersister { // would be serialized in an unwrapped way when passed directly. file_persister_impl_->file_appender_ << JSON(idxts) << '\t' << JSON(MakeSureTheRightTypeIsSerialized>::DoIt( - std::forward(entry))) << std::endl; + std::forward(entry))) + << std::endl; ++iterator.next_index; file_persister_impl_->head_offset_ = 0; file_persister_impl_->end_.store(iterator); @@ -630,7 +631,10 @@ class FilePersister { // ">" is OK, as this call is multithreading-friendly, and more entries could have been added during this call. CURRENT_ASSERT(file_persister_impl_->record_offset_.size() >= current_size); - return ITERABLE(file_persister_impl_, static_cast(begin_index), static_cast(end_index), file_persister_impl_->record_offset_[static_cast(begin_index)]); + return ITERABLE(file_persister_impl_, + static_cast(begin_index), + static_cast(end_index), + file_persister_impl_->record_offset_[static_cast(begin_index)]); } template @@ -651,12 +655,12 @@ class FilePersister { Owned file_persister_impl_; // `Owned`, as iterators borrow it. }; -} // namespace current::persistence::impl +} // namespace impl template using File = ss::EntryPersister, ENTRY>; -} // namespace current::persistence +} // namespace persistence } // namespace current #endif // BLOCKS_PERSISTENCE_FILE_H diff --git a/blocks/persistence/memory.h b/blocks/persistence/memory.h index 735a58619..a7c45fa4f 100644 --- a/blocks/persistence/memory.h +++ b/blocks/persistence/memory.h @@ -334,12 +334,12 @@ class MemoryPersister { Owned container_; // `Owned`, as iterators borrow it. }; -} // namespace current::persistence::impl +} // namespace impl template using Memory = ss::EntryPersister, ENTRY>; -} // namespace current::persistence +} // namespace persistence } // namespace current #endif // BLOCKS_PERSISTENCE_MEMORY_H diff --git a/blocks/persistence/test.cc b/blocks/persistence/test.cc index e781c1bda..9e19dde81 100644 --- a/blocks/persistence/test.cc +++ b/blocks/persistence/test.cc @@ -845,21 +845,18 @@ void IteratorPerformanceTest(IMPL& impl, bool publish = true) { EXPECT_EQ(10ull, (*impl.Iterate(10, 11).begin()).idx_ts.index); EXPECT_EQ(10000ll, (*impl.Iterate(10, 11).begin()).idx_ts.us.count()); EXPECT_EQ("0000010 kkkkkk", (*impl.Iterate(10, 11).begin()).entry.s); - EXPECT_EQ("{\"index\":10,\"us\":10000}\t{\"s\":\"0000010 kkkkkk\"}", - (*impl.IterateUnsafe(10, 11).begin())); + EXPECT_EQ("{\"index\":10,\"us\":10000}\t{\"s\":\"0000010 kkkkkk\"}", (*impl.IterateUnsafe(10, 11).begin())); EXPECT_EQ(100ull, (*impl.Iterate(100, 101).begin()).idx_ts.index); EXPECT_EQ(100000ll, (*impl.Iterate(100, 101).begin()).idx_ts.us.count()); EXPECT_EQ("0000100 wwwww", (*impl.Iterate(100, 101).begin()).entry.s); - EXPECT_EQ("{\"index\":100,\"us\":100000}\t{\"s\":\"0000100 wwwww\"}", - (*impl.IterateUnsafe(100, 101).begin())); + EXPECT_EQ("{\"index\":100,\"us\":100000}\t{\"s\":\"0000100 wwwww\"}", (*impl.IterateUnsafe(100, 101).begin())); } { // By timestamp. EXPECT_EQ(0ull, (*impl.Iterate(us_t(0), us_t(1000)).begin()).idx_ts.index); EXPECT_EQ(0ll, (*impl.Iterate(us_t(0), us_t(1000)).begin()).idx_ts.us.count()); EXPECT_EQ("0000000 aaa", (*impl.Iterate(us_t(0), us_t(1000)).begin()).entry.s); - EXPECT_EQ("{\"index\":0,\"us\":0}\t{\"s\":\"0000000 aaa\"}", - (*impl.IterateUnsafe(us_t(0), us_t(1000)).begin())); + EXPECT_EQ("{\"index\":0,\"us\":0}\t{\"s\":\"0000000 aaa\"}", (*impl.IterateUnsafe(us_t(0), us_t(1000)).begin())); EXPECT_EQ(10ull, (*impl.Iterate(us_t(10000), us_t(11000)).begin()).idx_ts.index); EXPECT_EQ(10000ll, (*impl.Iterate(us_t(10000), us_t(11000)).begin()).idx_ts.us.count()); EXPECT_EQ("0000010 kkkkkk", (*impl.Iterate(us_t(10000), us_t(11000)).begin()).entry.s); @@ -990,10 +987,10 @@ TEST(PersistenceLayer, FileIteratorCanNotOutliveFile) { TEST(PersistenceLayer, Exceptions) { using namespace persistence_test; using IMPL = current::persistence::File; - using current::ss::IndexAndTimestamp; - using current::ss::InconsistentTimestampException; - using current::ss::InconsistentIndexException; using current::persistence::MalformedEntryException; + using current::ss::InconsistentIndexException; + using current::ss::InconsistentTimestampException; + using current::ss::IndexAndTimestamp; const auto namespace_name = current::ss::StreamNamespaceName("namespace", "entry_name"); const std::string persistence_file_name = current::FileSystem::JoinPath(FLAGS_persistence_test_tmpdir, "data"); diff --git a/blocks/self_modifying_config/test.cc b/blocks/self_modifying_config/test.cc index bc8fdc62b..a1ab04c31 100644 --- a/blocks/self_modifying_config/test.cc +++ b/blocks/self_modifying_config/test.cc @@ -88,8 +88,9 @@ TEST(SelfModifyingConfig, ReadFileException) { current::time::SetNow( current::IMFFixDateTimeStringToTimestamp("Tue, 16 Aug 1983 00:00:00 GMT")); // I was born. -- D.K. - ASSERT_THROW(static_cast(std::make_unique>(config_filename)), - current::SelfModifyingConfigReadFileException); + ASSERT_THROW( + static_cast(std::make_unique>(config_filename)), + current::SelfModifyingConfigReadFileException); try { static_cast(std::make_unique>(config_filename)); } catch (const current::SelfModifyingConfigReadFileException& e) { @@ -115,8 +116,9 @@ TEST(SelfModifyingConfig, ParseJSONException) { current::FileSystem::WriteStringToFile("De Louboutin.", config_filename.c_str()); - ASSERT_THROW(static_cast(std::make_unique>(config_filename)), - current::SelfModifyingConfigParseJSONException); + ASSERT_THROW( + static_cast(std::make_unique>(config_filename)), + current::SelfModifyingConfigParseJSONException); try { static_cast(std::make_unique>(config_filename)); } catch (const current::SelfModifyingConfigParseJSONException& e) { @@ -144,8 +146,9 @@ TEST(SelfModifyingConfig, WriteFileException) { current::FileSystem::WriteStringToFile(JSON(UnitTestSelfModifyingConfig(4)), config_filename.c_str()); - ASSERT_THROW(static_cast(std::make_unique>(config_filename)), - current::SelfModifyingConfigWriteFileException); + ASSERT_THROW( + static_cast(std::make_unique>(config_filename)), + current::SelfModifyingConfigWriteFileException); try { static_cast(std::make_unique>(config_filename)); } catch (const current::SelfModifyingConfigWriteFileException& e) { diff --git a/blocks/ss/exceptions.h b/blocks/ss/exceptions.h index a05da964e..e17bd587d 100644 --- a/blocks/ss/exceptions.h +++ b/blocks/ss/exceptions.h @@ -52,7 +52,7 @@ struct InconsistentTimestampException : InconsistentIndexOrTimestampException { static_cast(found.count()))) {} }; -} // namespace current::ss +} // namespace ss } // namespace current #endif // BLOCKS_SS_EXCEPTIONS_H diff --git a/blocks/ss/idx_ts.h b/blocks/ss/idx_ts.h index 9a9773100..ac87258bc 100644 --- a/blocks/ss/idx_ts.h +++ b/blocks/ss/idx_ts.h @@ -81,12 +81,12 @@ CURRENT_STRUCT(HeadAndOptionalIndexAndTimestamp) { CURRENT_USE_FIELD_AS_TIMESTAMP(head); CURRENT_DEFAULT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp) : head(0) {} CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp)(std::chrono::microseconds head) : head(head) {} - CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp)(std::chrono::microseconds head, IndexAndTimestamp idxts) - : head(head), idxts(idxts) { + CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp) + (std::chrono::microseconds head, IndexAndTimestamp idxts) : head(head), idxts(idxts) { CURRENT_ASSERT(head >= idxts.us); } - CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp)( - std::chrono::microseconds head, uint64_t index, std::chrono::microseconds us) + CURRENT_CONSTRUCTOR(HeadAndOptionalIndexAndTimestamp) + (std::chrono::microseconds head, uint64_t index, std::chrono::microseconds us) : head(head), idxts(IndexAndTimestamp(index, us)) { #ifndef CURRENT_BUILD_WITH_PARANOIC_RUNTIME_CHECKS CURRENT_ASSERT(head >= us); @@ -99,7 +99,7 @@ CURRENT_STRUCT(HeadAndOptionalIndexAndTimestamp) { } }; -} // namespace current::ss +} // namespace ss } // namespace current using idxts_t = current::ss::IndexAndTimestamp; diff --git a/blocks/ss/persister.h b/blocks/ss/persister.h index f1610abdc..4eb4a69c6 100644 --- a/blocks/ss/persister.h +++ b/blocks/ss/persister.h @@ -53,8 +53,7 @@ class EntryPersister : public GenericEntryPersister, public IMPL { using IterableRangeUnsafe = typename IMPL::IterableRangeUnsafe; template - explicit EntryPersister(std::mutex& mutex, ARGS&&... args) - : IMPL(mutex, std::forward(args)...) {} + explicit EntryPersister(std::mutex& mutex, ARGS&&... args) : IMPL(mutex, std::forward(args)...) {} virtual ~EntryPersister() {} template , T>; }; -} // namespace current::ss +} // namespace ss } // namespace current #endif // BLOCKS_SS_PERSISTER_H diff --git a/blocks/ss/pubsub.h b/blocks/ss/pubsub.h index 9426082ed..da250a47e 100644 --- a/blocks/ss/pubsub.h +++ b/blocks/ss/pubsub.h @@ -52,8 +52,7 @@ class EntryPublisher : public GenericEntryPublisher, public IMPL { public: template - explicit EntryPublisher(ARGS&&... args) - : IMPL(std::forward(args)...) {} + explicit EntryPublisher(ARGS&&... args) : IMPL(std::forward(args)...) {} virtual ~EntryPublisher() {} @@ -133,8 +132,7 @@ template class EntrySubscriber : public GenericEntrySubscriber, public IMPL { public: template - EntrySubscriber(ARGS&&... args) - : IMPL(std::forward(args)...) {} + EntrySubscriber(ARGS&&... args) : IMPL(std::forward(args)...) {} virtual ~EntrySubscriber() {} EntryResponse operator()(const ENTRY& e, idxts_t current, idxts_t last) { return IMPL::operator()(e, current, last); } @@ -211,7 +209,7 @@ struct PassEntryToSubscriberIfTypeMatchesImpl { } }; -} // namespace current::ss::impl +} // namespace impl template EntryResponse PassEntryToSubscriberIfTypeMatches(F&& f, G&& fallback, E&& entry, idxts_t current, idxts_t last) { @@ -219,7 +217,7 @@ EntryResponse PassEntryToSubscriberIfTypeMatches(F&& f, G&& fallback, E&& entry, std::forward(f), std::forward(fallback), std::forward(entry), current, last); } -} // namespace current::ss +} // namespace ss } // namespace current #endif // BLOCKS_SS_PUBSUB_H diff --git a/blocks/ss/signature.h b/blocks/ss/signature.h index 75d713fa4..44dc620da 100644 --- a/blocks/ss/signature.h +++ b/blocks/ss/signature.h @@ -35,17 +35,19 @@ CURRENT_STRUCT(StreamNamespaceName) { CURRENT_FIELD(namespace_name, std::string); CURRENT_FIELD(entry_name, std::string); CURRENT_DEFAULT_CONSTRUCTOR(StreamNamespaceName) {} - CURRENT_CONSTRUCTOR(StreamNamespaceName)(const std::string& namespace_name, const std::string& entry_name) + CURRENT_CONSTRUCTOR(StreamNamespaceName) + (const std::string& namespace_name, const std::string& entry_name) : namespace_name(namespace_name), entry_name(entry_name) {} }; CURRENT_STRUCT(StreamSignature, StreamNamespaceName) { CURRENT_FIELD(schema, reflection::SchemaInfo); CURRENT_DEFAULT_CONSTRUCTOR(StreamSignature) {} - CURRENT_CONSTRUCTOR(StreamSignature)( - const std::string& namespace_name, const std::string& entry_name, const reflection::SchemaInfo& schema) + CURRENT_CONSTRUCTOR(StreamSignature) + (const std::string& namespace_name, const std::string& entry_name, const reflection::SchemaInfo& schema) : SUPER(namespace_name, entry_name), schema(schema) {} - CURRENT_CONSTRUCTOR(StreamSignature)(const StreamNamespaceName& namespace_name, const reflection::SchemaInfo& schema) + CURRENT_CONSTRUCTOR(StreamSignature) + (const StreamNamespaceName& namespace_name, const reflection::SchemaInfo& schema) : SUPER(namespace_name), schema(std::move(schema)) {} }; diff --git a/blocks/ss/types.h b/blocks/ss/types.h index bafb0184c..413b92666 100644 --- a/blocks/ss/types.h +++ b/blocks/ss/types.h @@ -37,10 +37,9 @@ template #ifndef CURRENT_FOR_CPP14 inline #endif // CURRENT_FOR_CPP14 -constexpr -bool can_publish_v = std::is_constructible_v; + constexpr bool can_publish_v = std::is_constructible_v; -} // namespace current::ss +} // namespace ss } // namespace current #endif // BLOCKS_SS_TYPES_H diff --git a/blocks/url/exceptions.h b/blocks/url/exceptions.h index 15e66ee27..887e99544 100644 --- a/blocks/url/exceptions.h +++ b/blocks/url/exceptions.h @@ -64,7 +64,7 @@ struct URLParseSpecificObjectAsURLParameterException : URLParseObjectAsURLParame : URLParseObjectAsURLParameterException(key, error, DescribeT()) {} }; -} // namespace current::url +} // namespace url } // namespace current #endif // BLOCKS_URL_EXCEPTIONS_H diff --git a/blocks/url/url.h b/blocks/url/url.h index 59ba6eacf..4ca959da7 100644 --- a/blocks/url/url.h +++ b/blocks/url/url.h @@ -72,7 +72,7 @@ namespace impl { namespace { const char* const kDefaultScheme = "http"; const char* const kDefaultHost = "localhost"; -} +} // namespace struct URLWithoutParametersParser { std::string host = ""; @@ -318,7 +318,8 @@ struct URLParametersExtractor { using super_t = current::reflection::SuperType; FillObjectImpl::DoIt(parameters, static_cast(object)); QueryParametersObjectFiller parser{parameters}; - current::reflection::VisitAllFields::WithObject(object, parser); + current::reflection::VisitAllFields::WithObject(object, + parser); } }; @@ -475,10 +476,9 @@ struct URL : URLParametersExtractor, URLWithoutParametersParser { static bool IsPathValidToRegister(const std::string& path) { const std::set valid_nonalnum_chars{ '/', '-', '.', '_', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@'}; - return find_if(path.begin(), - path.end(), - [&valid_nonalnum_chars](char c) { return !(isalnum(c) || valid_nonalnum_chars.count(c)); }) == - path.end(); + return find_if(path.begin(), path.end(), [&valid_nonalnum_chars](char c) { + return !(isalnum(c) || valid_nonalnum_chars.count(c)); + }) == path.end(); } }; diff --git a/blocks/xterm/example.cc b/blocks/xterm/example.cc index b73e494fa..e86f70746 100644 --- a/blocks/xterm/example.cc +++ b/blocks/xterm/example.cc @@ -19,8 +19,7 @@ int main(int argc, char** argv) { // Basic VT100 demo. using namespace current::vt100; - std::cout << "Default, " << bold << "bold" << normal << ", " << dim << "dim" << normal << ", done." - << std::endl; + std::cout << "Default, " << bold << "bold" << normal << ", " << dim << "dim" << normal << ", done." << std::endl; #ifndef CURRENT_WINDOWS std::cout << "Default, " << italic << "italic" << noitalic << '.' << std::endl; #endif // CURRENT_WINDOWS @@ -48,10 +47,9 @@ int main(int argc, char** argv) { std::cout << "Default, " << background(red) << blue << bold << "blue on red " << reverse << " reversed " << noreverse << " back to blue on red" << reset << '.' << std::endl; - std::cout << "Default, " << strikeout << "no " << red << "red" << bold << " bold" << italic << " italic" - << noitalic << ' ' << underlined << "underlined" << nounderlined << ' ' << doubleunderlined - << "doubleunderlined" << nounderlined << normal << default_color << " style" << nostrikeout - << '.' << reset << std::endl; + std::cout << "Default, " << strikeout << "no " << red << "red" << bold << " bold" << italic << " italic" << noitalic + << ' ' << underlined << "underlined" << nounderlined << ' ' << doubleunderlined << "doubleunderlined" + << nounderlined << normal << default_color << " style" << nostrikeout << '.' << reset << std::endl; } { @@ -86,7 +84,7 @@ int main(int argc, char** argv) { } std::cout << "Done." << std::endl; } - #endif +#endif if (false) { // NOTE(dkorolev): This fails on my Linux. :/ Prints `Test3> tttesting ... OK`, then `Test3> ttDone.` at the end. diff --git a/blocks/xterm/multiline.cc b/blocks/xterm/multiline.cc index d3d723bdc..d4c8d1faa 100644 --- a/blocks/xterm/multiline.cc +++ b/blocks/xterm/multiline.cc @@ -11,18 +11,22 @@ int main() { std::vector threads; int index = 0u; do { - threads.emplace_back([&multiline_progress](int index) { - current::ProgressLine line = multiline_progress(); - const double k = current::random::RandomDouble(0.01, 0.04); - const double b = current::random::RandomDouble(0.0, 6.28); - const double a = current::random::RandomDouble(20, 45); - const auto t0 = current::time::Now(); - while (true) { - line << "Line" << index << ": " << std::string(static_cast( - 0.5 * (std::sin((current::time::Now() - t0).count() * 1e-3 * k + b) + 1.0) * a), '*'); - std::this_thread::sleep_for(std::chrono::milliseconds(current::random::RandomInt(1, 25))); - } - }, ++index); + threads.emplace_back( + [&multiline_progress](int index) { + current::ProgressLine line = multiline_progress(); + const double k = current::random::RandomDouble(0.01, 0.04); + const double b = current::random::RandomDouble(0.0, 6.28); + const double a = current::random::RandomDouble(20, 45); + const auto t0 = current::time::Now(); + while (true) { + line << "Line" << index << ": " + << std::string(static_cast( + 0.5 * (std::sin((current::time::Now() - t0).count() * 1e-3 * k + b) + 1.0) * a), + '*'); + std::this_thread::sleep_for(std::chrono::milliseconds(current::random::RandomInt(1, 25))); + } + }, + ++index); std::this_thread::sleep_for(std::chrono::milliseconds(current::random::RandomInt(500, 2500 * index))); } while (true); } diff --git a/blocks/xterm/progress.h b/blocks/xterm/progress.h index a59cf526b..f76bb603b 100644 --- a/blocks/xterm/progress.h +++ b/blocks/xterm/progress.h @@ -64,7 +64,8 @@ class ProgressLine final { ProgressLine(DoConstruct, std::ostream& os = std::cout, std::function up = nullptr, - std::mutex* maybe_mutex = nullptr) : os_(os), up_(up), maybe_mutex_(maybe_mutex) { + std::mutex* maybe_mutex = nullptr) + : os_(os), up_(up), maybe_mutex_(maybe_mutex) { if (up_) { // Move to the next line right away to "allocate" a new line for this "multiline" "progress instance". const auto maybe_lock = MaybeLock(); @@ -128,9 +129,7 @@ class ProgressLine final { return status; } - std::string GetUndecoratedString() const { - return current_undecorated_status_; - } + std::string GetUndecoratedString() const { return current_undecorated_status_; } protected: void DoUpdate(Status& status) { @@ -139,7 +138,7 @@ class ProgressLine final { if (new_status != current_status_) { const size_t new_status_length = - current::strings::UTF8StringLength(status.oss_text_with_no_vt100_escape_sequences.str()); + current::strings::UTF8StringLength(status.oss_text_with_no_vt100_escape_sequences.str()); if (!up_) { const auto maybe_lock = MaybeLock(); DoClearString(os_); @@ -153,8 +152,8 @@ class ProgressLine final { os_ << vt100::up(n + 1) << new_status << vt100::reset << '\n' << vt100::down(n) << std::flush; } else { const size_t d = current_status_length_ - new_status_length; - os_ << vt100::up(n + 1) << new_status << vt100::reset - << std::string(d, ' ') << '\n' << vt100::down(n) << std::flush; + os_ << vt100::up(n + 1) << new_status << vt100::reset << std::string(d, ' ') << '\n' + << vt100::down(n) << std::flush; } } current_status_ = new_status; @@ -172,7 +171,8 @@ class MultilineProgress final { current::ProgressLine operator()(std::ostream& os = std::cout) { ++total_; int index = total_; - return current::ProgressLine(os, [index, this]() { return total_ - index; }, mutex_); + return current::ProgressLine( + os, [index, this]() { return total_ - index; }, mutex_); } }; diff --git a/blocks/xterm/vt100.h b/blocks/xterm/vt100.h index e0b0374a1..a02cc9083 100644 --- a/blocks/xterm/vt100.h +++ b/blocks/xterm/vt100.h @@ -102,15 +102,11 @@ struct UD final { explicit UD(int by) : down(by) {} }; -inline UD up(int d) { - return UD(-d); -} +inline UD up(int d) { return UD(-d); } -inline UD down(int d) { - return UD(+d); -} +inline UD down(int d) { return UD(+d); } -} // namespace current::vt100 +} // namespace vt100 } // namespace current inline void EnableVirtualTerminalProcessing() { diff --git a/bricks/c++17/test.cc b/bricks/c++17/test.cc index f3ca48387..f44f8978d 100644 --- a/bricks/c++17/test.cc +++ b/bricks/c++17/test.cc @@ -28,7 +28,9 @@ SOFTWARE. #if __cplusplus >= 201703L TEST(CPlusPlus17, Enabled) { - auto const generic_lambda = [](auto const x) { return current::reflection::TypeName>(); }; + auto const generic_lambda = [](auto const x) { + return current::reflection::TypeName>(); + }; EXPECT_STREQ("uint32_t", generic_lambda(static_cast(42))); EXPECT_STREQ("bool", generic_lambda(true)); diff --git a/bricks/dflags/test.cc b/bricks/dflags/test.cc index 732278bed..1c7e7bcbd 100644 --- a/bricks/dflags/test.cc +++ b/bricks/dflags/test.cc @@ -276,17 +276,17 @@ TEST(DFlags, PrintsHelpDeathTest) { char p2[] = "--help"; char* pp[] = {p1, p2}; char** argv = pp; - EXPECT_DEATH(ParseDFlags(&argc, &argv), DFLAGS_TEST_REGEX( - "3 flags registered.\n" - "\t--bar , bool\n" - "\t\tBar\\.\n" - "\t\tDefault value\\: True\n" - "\t--foo , std\\:\\:string\n" - "\t\tFoo\\.\n" - "\t\tDefault value: 'TRUE THIS'\n" - "\t--meh , int32_t\n" - "\t\tMeh\\.\n" - "\t\tDefault value: 42\n")); + EXPECT_DEATH(ParseDFlags(&argc, &argv), + DFLAGS_TEST_REGEX("3 flags registered.\n" + "\t--bar , bool\n" + "\t\tBar\\.\n" + "\t\tDefault value\\: True\n" + "\t--foo , std\\:\\:string\n" + "\t\tFoo\\.\n" + "\t\tDefault value: 'TRUE THIS'\n" + "\t--meh , int32_t\n" + "\t\tMeh\\.\n" + "\t\tDefault value: 42\n")); } TEST(DFlags, UndefinedFlagDeathTest) { @@ -319,7 +319,8 @@ TEST(DFlags, TooManyDashesDeathTest) { char p2[] = "---whatever42"; char* pp[] = {p1, p2}; char** argv = pp; - EXPECT_DEATH(ParseDFlags(&argc, &argv), DFLAGS_TEST_REGEX("Parameter: '---whatever42' has too many dashes in front\\.")); + EXPECT_DEATH(ParseDFlags(&argc, &argv), + DFLAGS_TEST_REGEX("Parameter: '---whatever42' has too many dashes in front\\.")); } TEST(DFlags, NoValueDeathTest) { diff --git a/bricks/dot/graphviz.h b/bricks/dot/graphviz.h index a824b47a2..2b64e59d7 100644 --- a/bricks/dot/graphviz.h +++ b/bricks/dot/graphviz.h @@ -259,8 +259,8 @@ struct GenericGraph { const auto output_file_deleter = current::FileSystem::ScopedRmFile(output_file_name); current::FileSystem::WriteStringToFile(AsDOT(), input_file_name.c_str()); - CURRENT_ASSERT(!bricks::system::SystemCall(current::strings::Printf( - "dot -T svg %s -o %s", input_file_name.c_str(), output_file_name.c_str()).c_str())); + CURRENT_ASSERT(!bricks::system::SystemCall( + current::strings::Printf("dot -T svg %s -o %s", input_file_name.c_str(), output_file_name.c_str()).c_str())); return current::FileSystem::ReadFileAsString(output_file_name.c_str()); } }; diff --git a/bricks/file/file.h b/bricks/file/file.h index d3c832a5c..d93f7c8e0 100644 --- a/bricks/file/file.h +++ b/bricks/file/file.h @@ -326,26 +326,27 @@ struct FileSystem { // Inner lambdas have distinct types thus creating template instantiation limit, // which is fixed by casting the lambda to its canonical type. ScanDirUntil(directory, - static_cast>([&item_handler, parameters, &context]( - const ScanDirItemInfo& item_info) { - const ScanDirParameters mask = - item_info.is_directory ? ScanDirParameters::ListDirsOnly : ScanDirParameters::ListFilesOnly; - if (static_cast(parameters) & static_cast(mask)) { - if (!item_handler(item_info)) { - return false; - } - } - if (item_info.is_directory) { - context.path_components.push_back(item_info.basename); - const auto guard = current::MakeScopeGuard([&context]() { context.path_components.pop_back(); }); - ScanDirUntil(item_info.pathname, - std::forward(item_handler), - parameters, - ScanDirRecursive::Yes, - context); - } - return true; - }), + static_cast>( + [&item_handler, parameters, &context](const ScanDirItemInfo& item_info) { + const ScanDirParameters mask = item_info.is_directory ? ScanDirParameters::ListDirsOnly + : ScanDirParameters::ListFilesOnly; + if (static_cast(parameters) & static_cast(mask)) { + if (!item_handler(item_info)) { + return false; + } + } + if (item_info.is_directory) { + context.path_components.push_back(item_info.basename); + const auto guard = + current::MakeScopeGuard([&context]() { context.path_components.pop_back(); }); + ScanDirUntil(item_info.pathname, + std::forward(item_handler), + parameters, + ScanDirRecursive::Yes, + context); + } + return true; + }), ScanDirParameters::ListFilesAndDirs, ScanDirRecursive::No, context); @@ -357,13 +358,14 @@ struct FileSystem { ITEM_HANDLER&& item_handler, ScanDirParameters parameters = ScanDirParameters::ListFilesOnly, ScanDirRecursive recursive = ScanDirRecursive::No) { - ScanDirUntil(directory, - [&item_handler](const ScanDirItemInfo& item_info) { - item_handler(item_info); - return true; - }, - parameters, - recursive); + ScanDirUntil( + directory, + [&item_handler](const ScanDirItemInfo& item_info) { + item_handler(item_info); + return true; + }, + parameters, + recursive); } enum class RmFileParameters { ThrowExceptionOnError, Silent }; @@ -416,18 +418,18 @@ struct FileSystem { } } else { try { - ScanDir(directory, - [parameters](const ScanDirItemInfo& item_info) { - if (item_info.is_directory) { - RmDir(item_info.pathname, parameters, RmDirRecursive::Yes); - } else { - RmFile(item_info.pathname, - (parameters == RmDirParameters::ThrowExceptionOnError) - ? RmFileParameters::ThrowExceptionOnError - : RmFileParameters::Silent); - } - }, - ScanDirParameters::ListFilesAndDirs); + ScanDir( + directory, + [parameters](const ScanDirItemInfo& item_info) { + if (item_info.is_directory) { + RmDir(item_info.pathname, parameters, RmDirRecursive::Yes); + } else { + RmFile(item_info.pathname, + (parameters == RmDirParameters::ThrowExceptionOnError) ? RmFileParameters::ThrowExceptionOnError + : RmFileParameters::Silent); + } + }, + ScanDirParameters::ListFilesAndDirs); RmDir(directory, parameters, RmDirRecursive::No); } catch (const current::Exception&) { if (parameters == RmDirParameters::ThrowExceptionOnError) { diff --git a/bricks/file/test.cc b/bricks/file/test.cc index f81b2c33a..a5dc215d3 100644 --- a/bricks/file/test.cc +++ b/bricks/file/test.cc @@ -33,11 +33,11 @@ SOFTWARE. #include "../strings/join.h" #include "../../3rdparty/gtest/gtest-main-with-dflags.h" -using current::FileSystem; -using current::FileException; using current::DirDoesNotExistException; -using current::PathNotDirException; using current::DirNotEmptyException; +using current::FileException; +using current::FileSystem; +using current::PathNotDirException; DEFINE_string(file_test_tmpdir, ".current", "Local path for the test to create temporary files in."); @@ -302,11 +302,10 @@ TEST(File, ScanDirParameters) { { std::set names; std::map item_infos; - FileSystem::ScanDir(base_dir, - [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) { - names.insert(x.basename); - item_infos.insert(std::make_pair(x.basename, x)); - }); + FileSystem::ScanDir(base_dir, [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) { + names.insert(x.basename); + item_infos.insert(std::make_pair(x.basename, x)); + }); EXPECT_EQ("f", current::strings::Join(names, ',')); EXPECT_EQ(f, item_infos.at("f").pathname); EXPECT_EQ(base_dir, item_infos.at("f").dirname); @@ -316,12 +315,13 @@ TEST(File, ScanDirParameters) { { std::set names; std::map item_infos; - FileSystem::ScanDir(base_dir, - [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) { - names.insert(x.basename); - item_infos.insert(std::make_pair(x.basename, x)); - }, - FileSystem::ScanDirParameters::ListFilesOnly); + FileSystem::ScanDir( + base_dir, + [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) { + names.insert(x.basename); + item_infos.insert(std::make_pair(x.basename, x)); + }, + FileSystem::ScanDirParameters::ListFilesOnly); EXPECT_EQ("f", current::strings::Join(names, ',')); EXPECT_EQ(f, item_infos.at("f").pathname); EXPECT_EQ(base_dir, item_infos.at("f").dirname); @@ -331,12 +331,13 @@ TEST(File, ScanDirParameters) { { std::set names; std::map item_infos; - FileSystem::ScanDir(base_dir, - [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) { - names.insert(x.basename); - item_infos.insert(std::make_pair(x.basename, x)); - }, - FileSystem::ScanDirParameters::ListDirsOnly); + FileSystem::ScanDir( + base_dir, + [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) { + names.insert(x.basename); + item_infos.insert(std::make_pair(x.basename, x)); + }, + FileSystem::ScanDirParameters::ListDirsOnly); EXPECT_EQ("d", current::strings::Join(names, ',')); EXPECT_EQ(d, item_infos.at("d").pathname); EXPECT_EQ(base_dir, item_infos.at("d").dirname); @@ -346,12 +347,13 @@ TEST(File, ScanDirParameters) { { std::set names; std::map item_infos; - FileSystem::ScanDir(base_dir, - [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) { - names.insert(x.basename); - item_infos.insert(std::make_pair(x.basename, x)); - }, - FileSystem::ScanDirParameters::ListFilesAndDirs); + FileSystem::ScanDir( + base_dir, + [&names, &item_infos](const FileSystem::ScanDirItemInfo& x) { + names.insert(x.basename); + item_infos.insert(std::make_pair(x.basename, x)); + }, + FileSystem::ScanDirParameters::ListFilesAndDirs); EXPECT_EQ("d,f", current::strings::Join(names, ',')); EXPECT_EQ(d, item_infos.at("d").pathname); EXPECT_EQ(base_dir, item_infos.at("d").dirname); @@ -388,13 +390,14 @@ TEST(File, ScanDirRecursive) { std::set basenames; std::map item_infos; - FileSystem::ScanDir(base_dir, - [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) { - basenames.insert(x.basename); - item_infos.insert(std::make_pair(x.basename, x)); - }, - FileSystem::ScanDirParameters::ListFilesOnly, - FileSystem::ScanDirRecursive::Yes); + FileSystem::ScanDir( + base_dir, + [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) { + basenames.insert(x.basename); + item_infos.insert(std::make_pair(x.basename, x)); + }, + FileSystem::ScanDirParameters::ListFilesOnly, + FileSystem::ScanDirRecursive::Yes); EXPECT_EQ("base_dir_file,sub_dir_file,sub_sub_dir_file,sub_sub_dir_file_2", current::strings::Join(basenames, ',')); @@ -413,13 +416,14 @@ TEST(File, ScanDirRecursive) { std::set basenames; std::map item_infos; - FileSystem::ScanDir(base_dir, - [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) { - basenames.insert(x.basename); - item_infos.insert(std::make_pair(x.basename, x)); - }, - FileSystem::ScanDirParameters::ListDirsOnly, - FileSystem::ScanDirRecursive::Yes); + FileSystem::ScanDir( + base_dir, + [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) { + basenames.insert(x.basename); + item_infos.insert(std::make_pair(x.basename, x)); + }, + FileSystem::ScanDirParameters::ListDirsOnly, + FileSystem::ScanDirRecursive::Yes); EXPECT_EQ("sub_dir,sub_sub_dir,sub_sub_dir_2", current::strings::Join(basenames, ',')); @@ -436,13 +440,14 @@ TEST(File, ScanDirRecursive) { std::set basenames; std::map item_infos; - FileSystem::ScanDir(base_dir, - [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) { - basenames.insert(x.basename); - item_infos.insert(std::make_pair(x.basename, x)); - }, - FileSystem::ScanDirParameters::ListFilesAndDirs, - FileSystem::ScanDirRecursive::Yes); + FileSystem::ScanDir( + base_dir, + [&basenames, &item_infos](const FileSystem::ScanDirItemInfo& x) { + basenames.insert(x.basename); + item_infos.insert(std::make_pair(x.basename, x)); + }, + FileSystem::ScanDirParameters::ListFilesAndDirs, + FileSystem::ScanDirRecursive::Yes); EXPECT_EQ("base_dir_file,sub_dir,sub_dir_file,sub_sub_dir,sub_sub_dir_2,sub_sub_dir_file,sub_sub_dir_file_2", current::strings::Join(basenames, ',')); diff --git a/bricks/graph/gnuplot.h b/bricks/graph/gnuplot.h index b85ecfd69..8cc9f3f8d 100644 --- a/bricks/graph/gnuplot.h +++ b/bricks/graph/gnuplot.h @@ -236,7 +236,7 @@ struct GNUPlot { } if (output_format_ != "gnuplot") { CURRENT_ASSERT(!bricks::system::SystemCall( - strings::Printf("gnuplot <%s >%s", input_file_name.c_str(), output_file_name.c_str()))); + strings::Printf("gnuplot <%s >%s", input_file_name.c_str(), output_file_name.c_str()))); return current::FileSystem::ReadFileAsString(output_file_name.c_str()); } else { // For unit tests, just compare the inputs. diff --git a/bricks/net/http/headers/headers.h b/bricks/net/http/headers/headers.h index 6a310384b..dff875a94 100644 --- a/bricks/net/http/headers/headers.h +++ b/bricks/net/http/headers/headers.h @@ -193,9 +193,9 @@ struct Headers final { Headers(const std::string& header, const std::string& value) { Set(header, value); } Headers(std::initializer_list> initializer) { - std::for_each(initializer.begin(), - initializer.end(), - [this](const std::pair& h) { Set(h.first, h.second); }); + std::for_each(initializer.begin(), initializer.end(), [this](const std::pair& h) { + Set(h.first, h.second); + }); } // An instance of `Headers` can `Set()` / `Get()` / `Has()` / `Remove()` headers. diff --git a/bricks/net/http/test.cc b/bricks/net/http/test.cc index 921a9163c..489ce1894 100644 --- a/bricks/net/http/test.cc +++ b/bricks/net/http/test.cc @@ -37,19 +37,19 @@ SOFTWARE. #include "../../../3rdparty/gtest/gtest-main-with-dflags.h" -using current::net::Socket; +using current::net::AttemptedToSendHTTPResponseMoreThanOnce; +using current::net::ChunkSizeNotAValidHEXValue; using current::net::ClientSocket; using current::net::Connection; -using current::net::HTTPServerConnection; +using current::net::ConnectionResetByPeer; +using current::net::DefaultInternalServerErrorMessage; +using current::net::GetFileMimeType; using current::net::HTTPRequestData; -using current::net::HTTPResponseCodeValue; using current::net::HTTPResponseCodeAsString; -using current::net::GetFileMimeType; -using current::net::DefaultInternalServerErrorMessage; +using current::net::HTTPResponseCodeValue; +using current::net::HTTPServerConnection; +using current::net::Socket; using current::net::SocketException; -using current::net::ConnectionResetByPeer; -using current::net::ChunkSizeNotAValidHEXValue; -using current::net::AttemptedToSendHTTPResponseMoreThanOnce; static void ExpectToReceive(const std::string& golden, Connection& connection) { std::vector response(golden.length()); @@ -71,16 +71,18 @@ CURRENT_STRUCT(HTTPTestObject) { TEST(PosixHTTPServerTest, Smoke) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([port](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip); - EXPECT_EQ(port, c.LocalIPAndPort().port); - EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip); - EXPECT_LT(0, c.RemoteIPAndPort().port); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/", c.HTTPRequest().RawPath()); - c.SendHTTPResponse("Data: " + c.HTTPRequest().Body()); - }, std::move(reserved_port)); + std::thread t( + [port](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip); + EXPECT_EQ(port, c.LocalIPAndPort().port); + EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip); + EXPECT_LT(0, c.RemoteIPAndPort().port); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/", c.HTTPRequest().RawPath()); + c.SendHTTPResponse("Data: " + c.HTTPRequest().Body()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); EXPECT_EQ("127.0.0.1", connection.LocalIPAndPort().ip); EXPECT_LT(0, connection.LocalIPAndPort().port); @@ -106,16 +108,18 @@ TEST(PosixHTTPServerTest, Smoke) { TEST(PosixHTTPServerTest, SmokeWithTrailingSpaces) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([port](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip); - EXPECT_EQ(port, c.LocalIPAndPort().port); - EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip); - EXPECT_LT(0, c.RemoteIPAndPort().port); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/", c.HTTPRequest().RawPath()); - c.SendHTTPResponse("Data: " + c.HTTPRequest().Body()); - }, std::move(reserved_port)); + std::thread t( + [port](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip); + EXPECT_EQ(port, c.LocalIPAndPort().port); + EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip); + EXPECT_LT(0, c.RemoteIPAndPort().port); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/", c.HTTPRequest().RawPath()); + c.SendHTTPResponse("Data: " + c.HTTPRequest().Body()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); EXPECT_EQ("127.0.0.1", connection.LocalIPAndPort().ip); EXPECT_LT(0, connection.LocalIPAndPort().port); @@ -141,12 +145,14 @@ TEST(PosixHTTPServerTest, SmokeWithTrailingSpaces) { TEST(PosixHTTPServerTest, SmokeWithArray) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("GET", c.HTTPRequest().Method()); - EXPECT_EQ("/vector_char", c.HTTPRequest().RawPath()); - c.SendHTTPResponse(std::vector({'S', 't', 'r', 'i', 'n', 'g'})); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("GET", c.HTTPRequest().Method()); + EXPECT_EQ("/vector_char", c.HTTPRequest().RawPath()); + c.SendHTTPResponse(std::vector({'S', 't', 'r', 'i', 'n', 'g'})); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("GET /vector_char HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -166,12 +172,14 @@ TEST(PosixHTTPServerTest, SmokeWithArray) { TEST(PosixHTTPServerTest, SmokeWithObject) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("GET", c.HTTPRequest().Method()); - EXPECT_EQ("/test_object", c.HTTPRequest().RawPath()); - c.SendHTTPResponse(HTTPTestObject()); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("GET", c.HTTPRequest().Method()); + EXPECT_EQ("/test_object", c.HTTPRequest().RawPath()); + c.SendHTTPResponse(HTTPTestObject()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("GET /test_object HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -191,12 +199,14 @@ TEST(PosixHTTPServerTest, SmokeWithObject) { TEST(PosixHTTPServerTest, SmokeWithObjectWithCORSHeader) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("GET", c.HTTPRequest().Method()); - EXPECT_EQ("/test_object", c.HTTPRequest().RawPath()); - c.SendHTTPResponse(HTTPTestObject(), HTTPResponseCode.OK, current::net::http::Headers().SetCORSHeader()); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("GET", c.HTTPRequest().Method()); + EXPECT_EQ("/test_object", c.HTTPRequest().RawPath()); + c.SendHTTPResponse(HTTPTestObject(), HTTPResponseCode.OK, current::net::http::Headers().SetCORSHeader()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("GET /test_object HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -217,15 +227,17 @@ TEST(PosixHTTPServerTest, SmokeWithObjectWithCORSHeader) { TEST(PosixHTTPServerTest, SmokeChunkedResponse) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("GET", c.HTTPRequest().Method()); - EXPECT_EQ("/chunked", c.HTTPRequest().RawPath()); - auto r = c.SendChunkedHTTPResponse(); - r.Send("onetwothree"); - r.Send(std::vector({'f', 'o', 'o'})); - r.Send(HTTPTestObject()); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("GET", c.HTTPRequest().Method()); + EXPECT_EQ("/chunked", c.HTTPRequest().RawPath()); + auto r = c.SendChunkedHTTPResponse(); + r.Send("onetwothree"); + r.Send(std::vector({'f', 'o', 'o'})); + r.Send(HTTPTestObject()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("GET /chunked HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -250,15 +262,17 @@ TEST(PosixHTTPServerTest, SmokeChunkedResponse) { TEST(PosixHTTPServerTest, SmokeChunkedResponseWithCORSHeader) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("GET", c.HTTPRequest().Method()); - EXPECT_EQ("/chunked", c.HTTPRequest().RawPath()); - auto r = c.SendChunkedHTTPResponse(HTTPResponseCode.OK, current::net::http::Headers().SetCORSHeader()); - r.Send("onetwothree"); - r.Send(std::vector({'f', 'o', 'o'})); - r.Send(HTTPTestObject()); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("GET", c.HTTPRequest().Method()); + EXPECT_EQ("/chunked", c.HTTPRequest().RawPath()); + auto r = c.SendChunkedHTTPResponse(HTTPResponseCode.OK, current::net::http::Headers().SetCORSHeader()); + r.Send("onetwothree"); + r.Send(std::vector({'f', 'o', 'o'})); + r.Send(HTTPTestObject()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("GET /chunked HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -284,15 +298,17 @@ TEST(PosixHTTPServerTest, SmokeChunkedResponseWithCORSHeader) { TEST(PosixHTTPServerTest, SmokeWithHeaders) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/header", c.HTTPRequest().RawPath()); - c.SendHTTPResponse("OK", - HTTPResponseCode.OK, - current::net::http::Headers({{"foo", "bar"}, {"baz", "meh"}}), - "here_is_" + c.HTTPRequest().Body()); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/header", c.HTTPRequest().RawPath()); + c.SendHTTPResponse("OK", + HTTPResponseCode.OK, + current::net::http::Headers({{"foo", "bar"}, {"baz", "meh"}}), + "here_is_" + c.HTTPRequest().Body()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("POST /header HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -316,16 +332,18 @@ TEST(PosixHTTPServerTest, SmokeWithHeaders) { TEST(PosixHTTPServerTest, SmokeWithLowercaseContentLength) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([port](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip); - EXPECT_EQ(port, c.LocalIPAndPort().port); - EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip); - EXPECT_LT(0, c.RemoteIPAndPort().port); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/", c.HTTPRequest().RawPath()); - c.SendHTTPResponse("Data: " + c.HTTPRequest().Body()); - }, std::move(reserved_port)); + std::thread t( + [port](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("127.0.0.1", c.LocalIPAndPort().ip); + EXPECT_EQ(port, c.LocalIPAndPort().port); + EXPECT_EQ("127.0.0.1", c.RemoteIPAndPort().ip); + EXPECT_LT(0, c.RemoteIPAndPort().port); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/", c.HTTPRequest().RawPath()); + c.SendHTTPResponse("Data: " + c.HTTPRequest().Body()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); EXPECT_EQ("127.0.0.1", connection.LocalIPAndPort().ip); EXPECT_LT(0, connection.LocalIPAndPort().port); @@ -350,13 +368,15 @@ TEST(PosixHTTPServerTest, SmokeWithLowercaseContentLength) { TEST(PosixHTTPServerTest, SmokeWithMethodInHeader) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("PATCH", c.HTTPRequest().Method()); - EXPECT_EQ("/ugly", c.HTTPRequest().RawPath()); - EXPECT_EQ("YES", c.HTTPRequest().Body()); - c.SendHTTPResponse("PASS"); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("PATCH", c.HTTPRequest().Method()); + EXPECT_EQ("/ugly", c.HTTPRequest().RawPath()); + EXPECT_EQ("YES", c.HTTPRequest().Body()); + c.SendHTTPResponse("PASS"); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("POST /ugly HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -379,13 +399,15 @@ TEST(PosixHTTPServerTest, SmokeWithMethodInHeader) { TEST(PosixHTTPServerTest, SmokeWithLowercaseMethodInLowercaseHeader) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("PATCH", c.HTTPRequest().Method()); - EXPECT_EQ("/ugly2", c.HTTPRequest().RawPath()); - EXPECT_EQ("yes", c.HTTPRequest().Body()); - c.SendHTTPResponse("Pass"); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("PATCH", c.HTTPRequest().Method()); + EXPECT_EQ("/ugly2", c.HTTPRequest().RawPath()); + EXPECT_EQ("yes", c.HTTPRequest().Body()); + c.SendHTTPResponse("Pass"); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("POST /ugly2 HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -409,14 +431,16 @@ TEST(PosixHTTPServerTest, SmokeNoBodyForPOST) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; std::atomic_bool thrown(false); - std::thread t([&thrown](Socket s) { - try { - HTTPServerConnection c(s.Accept()); - ASSERT_TRUE(false); - } catch (const current::net::HTTPRequestBodyLengthNotProvided&) { - thrown = true; - } - }, std::move(reserved_port)); + std::thread t( + [&thrown](Socket s) { + try { + HTTPServerConnection c(s.Accept()); + ASSERT_TRUE(false); + } catch (const current::net::HTTPRequestBodyLengthNotProvided&) { + thrown = true; + } + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("POST / HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -438,14 +462,16 @@ TEST(PosixHTTPServerTest, SmokePOSTBodyTooLong) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; std::atomic_bool thrown(false); - std::thread t([&thrown](Socket s) { - try { - HTTPServerConnection c(s.Accept()); - ASSERT_TRUE(false); - } catch (const current::net::HTTPPayloadTooLarge&) { - thrown = true; - } - }, std::move(reserved_port)); + std::thread t( + [&thrown](Socket s) { + try { + HTTPServerConnection c(s.Accept()); + ASSERT_TRUE(false); + } catch (const current::net::HTTPPayloadTooLarge&) { + thrown = true; + } + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); try { connection.BlockingWrite("POST / HTTP/1.1\r\n", true); @@ -478,12 +504,14 @@ TEST(PosixHTTPServerTest, SmokePOSTBodyTooLong) { TEST(PosixHTTPServerTest, LargeBody) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/", c.HTTPRequest().RawPath()); - c.SendHTTPResponse(std::string("Data: ") + c.HTTPRequest().Body()); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/", c.HTTPRequest().RawPath()); + c.SendHTTPResponse(std::string("Data: ") + c.HTTPRequest().Body()); + }, + std::move(reserved_port)); std::string body(1000000, '.'); for (size_t i = 0; i < body.length(); ++i) { body[i] = 'A' + (i % 26); @@ -509,12 +537,14 @@ TEST(PosixHTTPServerTest, LargeBody) { TEST(PosixHTTPServerTest, ChunkedLargeBodyManyChunks) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/", c.HTTPRequest().RawPath()); - c.SendHTTPResponse(c.HTTPRequest().Body()); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/", c.HTTPRequest().RawPath()); + c.SendHTTPResponse(c.HTTPRequest().Body()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("POST / HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -532,13 +562,12 @@ TEST(PosixHTTPServerTest, ChunkedLargeBodyManyChunks) { connection.BlockingWrite("\r\n", true); } connection.BlockingWrite("0\r\n", false); - ExpectToReceive(current::strings::Printf( - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n" - "Content-Length: %d\r\n" - "\r\n", - static_cast(body.length())) + + ExpectToReceive(current::strings::Printf("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "Content-Length: %d\r\n" + "\r\n", + static_cast(body.length())) + body, connection); t.join(); @@ -572,8 +601,8 @@ TEST(PosixHTTPServerTest, ChunkedSmoke) for (uint64_t i = 0; i < chunks; ++i) { const uint64_t start = offset + length * i / chunks; const uint64_t end = offset + length * (i + 1) / chunks; - chunked_body += - current::strings::Printf("%llX\r\n", static_cast(end - start)) + body.substr(static_cast(start), static_cast(end - start)); + chunked_body += current::strings::Printf("%llX\r\n", static_cast(end - start)) + + body.substr(static_cast(start), static_cast(end - start)); } auto local_reserved_port = current::net::ReserveLocalPort(); @@ -586,13 +615,12 @@ TEST(PosixHTTPServerTest, ChunkedSmoke) connection.BlockingWrite("\r\n", true); connection.BlockingWrite(chunked_body, true); connection.BlockingWrite("0\r\n", false); - ExpectToReceive(current::strings::Printf( - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n" - "Content-Length: %d\r\n" - "\r\n", - static_cast(length)) + + ExpectToReceive(current::strings::Printf("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "Content-Length: %d\r\n" + "\r\n", + static_cast(length)) + body.substr(static_cast(offset)), connection); t.join(); @@ -816,13 +844,15 @@ TEST(PosixHTTPServerTest, DISABLED_InvalidHEXAsChunkSizeDoesNotKillServer) auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; std::atomic_bool wrong_chunk_size_exception_thrown(false); - std::thread t([&wrong_chunk_size_exception_thrown](Socket s) { - try { - HTTPServerConnection c(s.Accept()); - } catch (const ChunkSizeNotAValidHEXValue&) { - wrong_chunk_size_exception_thrown = true; - } - }, std::move(reserved_port)); + std::thread t( + [&wrong_chunk_size_exception_thrown](Socket s) { + try { + HTTPServerConnection c(s.Accept()); + } catch (const ChunkSizeNotAValidHEXValue&) { + wrong_chunk_size_exception_thrown = true; + } + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("POST / HTTP/1.1\r\n", true); @@ -848,12 +878,14 @@ TEST(PosixHTTPServerTest, DISABLED_InvalidHEXAsChunkSizeDoesNotKillServer) TEST(PosixHTTPServerTest, ChunkedBodyLargeFirstChunk) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/", c.HTTPRequest().RawPath()); - c.SendHTTPResponse(c.HTTPRequest().Body()); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/", c.HTTPRequest().RawPath()); + c.SendHTTPResponse(c.HTTPRequest().Body()); + }, + std::move(reserved_port)); Connection connection(ClientSocket("localhost", port)); connection.BlockingWrite("POST / HTTP/1.1\r\n", true); connection.BlockingWrite("Host: localhost\r\n", true); @@ -870,13 +902,12 @@ TEST(PosixHTTPServerTest, ChunkedBodyLargeFirstChunk) { body += chunk; } connection.BlockingWrite("0\r\n", false); - ExpectToReceive(current::strings::Printf( - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n" - "Content-Length: %d\r\n" - "\r\n", - static_cast(body.length())) + + ExpectToReceive(current::strings::Printf("HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "Content-Length: %d\r\n" + "\r\n", + static_cast(body.length())) + body, connection); t.join(); @@ -885,7 +916,7 @@ TEST(PosixHTTPServerTest, ChunkedBodyLargeFirstChunk) { #ifndef CURRENT_WINDOWS struct HTTPClientImplCURL { static std::string MakeGetRequest(std::thread& server_thread, int port, const std::string& url) { - const auto cmd = current::strings::Printf( "curl -s localhost:%d%s", port, url.c_str()); + const auto cmd = current::strings::Printf("curl -s localhost:%d%s", port, url.c_str()); const std::string result = current::bricks::system::SystemCallReadPipe(cmd).ReadLine(); server_thread.join(); return result; @@ -895,8 +926,7 @@ struct HTTPClientImplCURL { int port, const std::string& url, const std::string& data) { - const auto cmd = current::strings::Printf( - "curl -s -d '%s' localhost:%d%s", data.c_str(), port, url.c_str()); + const auto cmd = current::strings::Printf("curl -s -d '%s' localhost:%d%s", data.c_str(), port, url.c_str()); const std::string result = current::bricks::system::SystemCallReadPipe(cmd).ReadLine(); server_thread.join(); return result; @@ -955,53 +985,61 @@ TYPED_TEST_CASE(HTTPTest, HTTPClientImplsTypeList); TYPED_TEST(HTTPTest, GET) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("GET", c.HTTPRequest().Method()); - EXPECT_EQ("/unittest?foo=bar", c.HTTPRequest().RawPath()); - EXPECT_EQ("/unittest", c.HTTPRequest().URL().path); - EXPECT_EQ("bar", c.HTTPRequest().URL().query["foo"]); - c.SendHTTPResponse("PASSED"); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("GET", c.HTTPRequest().Method()); + EXPECT_EQ("/unittest?foo=bar", c.HTTPRequest().RawPath()); + EXPECT_EQ("/unittest", c.HTTPRequest().URL().path); + EXPECT_EQ("bar", c.HTTPRequest().URL().query["foo"]); + c.SendHTTPResponse("PASSED"); + }, + std::move(reserved_port)); EXPECT_EQ("PASSED", TypeParam::MakeGetRequest(t, port, "/unittest?foo=bar")); } TYPED_TEST(HTTPTest, POST) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/unittest_post", c.HTTPRequest().RawPath()); - EXPECT_EQ(7u, c.HTTPRequest().BodyLength()); - EXPECT_EQ("BAZINGA", c.HTTPRequest().Body()); - c.SendHTTPResponse("POSTED"); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/unittest_post", c.HTTPRequest().RawPath()); + EXPECT_EQ(7u, c.HTTPRequest().BodyLength()); + EXPECT_EQ("BAZINGA", c.HTTPRequest().Body()); + c.SendHTTPResponse("POSTED"); + }, + std::move(reserved_port)); EXPECT_EQ("POSTED", TypeParam::MakePostRequest(t, port, "/unittest_post", "BAZINGA")); } TYPED_TEST(HTTPTest, NoBodyPOST) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - EXPECT_EQ("POST", c.HTTPRequest().Method()); - EXPECT_EQ("/unittest_empty_post", c.HTTPRequest().RawPath()); - EXPECT_EQ(0u, c.HTTPRequest().BodyLength()); - c.SendHTTPResponse("ALMOST_POSTED"); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + EXPECT_EQ("POST", c.HTTPRequest().Method()); + EXPECT_EQ("/unittest_empty_post", c.HTTPRequest().RawPath()); + EXPECT_EQ(0u, c.HTTPRequest().BodyLength()); + c.SendHTTPResponse("ALMOST_POSTED"); + }, + std::move(reserved_port)); EXPECT_EQ("ALMOST_POSTED", TypeParam::MakePostRequest(t, port, "/unittest_empty_post", "")); } TYPED_TEST(HTTPTest, AttemptsToSendResponseTwice) { auto reserved_port = current::net::ReserveLocalPort(); const int port = reserved_port; - std::thread t([](Socket s) { - HTTPServerConnection c(s.Accept()); - c.SendHTTPResponse("one"); - ASSERT_THROW(c.SendHTTPResponse("two"), AttemptedToSendHTTPResponseMoreThanOnce); - ASSERT_THROW(c.SendChunkedHTTPResponse().Send("three"), AttemptedToSendHTTPResponseMoreThanOnce); - }, std::move(reserved_port)); + std::thread t( + [](Socket s) { + HTTPServerConnection c(s.Accept()); + c.SendHTTPResponse("one"); + ASSERT_THROW(c.SendHTTPResponse("two"), AttemptedToSendHTTPResponseMoreThanOnce); + ASSERT_THROW(c.SendChunkedHTTPResponse().Send("three"), AttemptedToSendHTTPResponseMoreThanOnce); + }, + std::move(reserved_port)); EXPECT_EQ("one", TypeParam::MakeGetRequest(t, port, "/")); } diff --git a/bricks/net/tcp/impl/posix.h b/bricks/net/tcp/impl/posix.h index 764d260ec..1c1a6bf5e 100644 --- a/bricks/net/tcp/impl/posix.h +++ b/bricks/net/tcp/impl/posix.h @@ -24,11 +24,11 @@ SOFTWARE. #if 0 -# NOTE(dkorolev): I have tested the `ReserveLocalPort` logic in the following way. -# Step one: build. +#NOTE(dkorolev) : I have tested the `ReserveLocalPort` logic in the following way. +#Step one : build. g++ -g -std=c++17 -W -Wall -Wno-strict-aliasing -o ".current/test" "test.cc" -pthread -ldl ulimit -c unlimited -# Step two: run in two terminals in parallel. +#Step two : run in two terminals in parallel. rm -f core ; while true ; do ./.current/test --gtest_throw_on_failure --gtest_catch_exceptions=0 || break ; done #endif @@ -108,9 +108,8 @@ enum class BarePort : uint16_t {}; class SocketHandle : private SocketSystemInitializer { private: struct InternalInit final {}; - explicit SocketHandle(InternalInit, - NagleAlgorithm nagle_algorithm_policy = kDefaultNagleAlgorithmPolicy) - : socket_(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) { + explicit SocketHandle(InternalInit, NagleAlgorithm nagle_algorithm_policy = kDefaultNagleAlgorithmPolicy) + : socket_(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) { if (socket_ < 0) { CURRENT_THROW(SocketCreateException()); // LCOV_EXCL_LINE -- Not covered by unit tests. } @@ -126,11 +125,7 @@ class SocketHandle : private SocketSystemInitializer { // NOTE(dkorolev): On Windows, `SO_REUSEADDR` is unnecessary. // First, local ports can be reused right away, so it doesn't win anything. // Second, on Windows this setting allows binding the second socket to the same port, which is just bad. - if (::setsockopt(socket_, - SOL_SOCKET, - SO_REUSEADDR, - &just_one, - sizeof(just_one))) { + if (::setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR, &just_one, sizeof(just_one))) { CURRENT_THROW(SocketCreateException()); // LCOV_EXCL_LINE -- Not covered by the unit tests. } #endif @@ -154,7 +149,6 @@ class SocketHandle : private SocketSystemInitializer { } } // LCOV_EXCL_STOP - } public: @@ -188,7 +182,7 @@ class SocketHandle : private SocketSystemInitializer { struct DoNotBind final {}; explicit SocketHandle(DoNotBind, NagleAlgorithm nagle_algorithm_policy = kDefaultNagleAlgorithmPolicy) - : SocketHandle(InternalInit(), nagle_algorithm_policy) {} + : SocketHandle(InternalInit(), nagle_algorithm_policy) {} struct FromAcceptedHandle final { SOCKET handle; @@ -215,9 +209,7 @@ class SocketHandle : private SocketSystemInitializer { } } - explicit SocketHandle(SocketHandle&& rhs) : socket_(static_cast(-1)) { - std::swap(socket_, rhs.socket_); - } + explicit SocketHandle(SocketHandle&& rhs) : socket_(static_cast(-1)) { std::swap(socket_, rhs.socket_); } private: friend class Socket; @@ -295,11 +287,10 @@ class ReservedLocalPort final : public current::net::SocketHandle { public: struct Construct final {}; ReservedLocalPort() = delete; - ReservedLocalPort(Construct, uint16_t port, current::net::SocketHandle&& socket) : super_t(std::move(socket)), port_(port) {} + ReservedLocalPort(Construct, uint16_t port, current::net::SocketHandle&& socket) + : super_t(std::move(socket)), port_(port) {} ReservedLocalPort(const ReservedLocalPort&) = delete; - ReservedLocalPort(ReservedLocalPort&& rhs) : super_t(std::move(rhs)), port_(rhs.port_) { - rhs.port_ = 0; - } + ReservedLocalPort(ReservedLocalPort&& rhs) : super_t(std::move(rhs)), port_(rhs.port_) { rhs.port_ = 0; } ReservedLocalPort& operator=(const ReservedLocalPort&) = delete; ReservedLocalPort& operator=(ReservedLocalPort&&) = delete; operator uint16_t() const { return port_; } @@ -323,10 +314,9 @@ class ReserveLocalPortImpl final { index_ = 0u; } - current::net::ReservedLocalPort DoIt( - uint16_t hint, - NagleAlgorithm nagle_algorithm_policy, - MaxServerQueuedConnectionsValue max_connections) { + current::net::ReservedLocalPort DoIt(uint16_t hint, + NagleAlgorithm nagle_algorithm_policy, + MaxServerQueuedConnectionsValue max_connections) { size_t save_index = index_; bool keep_searching = true; while (keep_searching) { @@ -350,13 +340,12 @@ class ReserveLocalPortImpl final { return retval; }(); try { - current::net::SocketHandle try_to_hold_port(current::net::SocketHandle::BindAndListen(), + current::net::SocketHandle try_to_hold_port(current::net::SocketHandle::BindAndListen(), BarePort(candidate_port), nagle_algorithm_policy, max_connections); - return current::net::ReservedLocalPort(current::net::ReservedLocalPort::Construct(), - candidate_port, - std::move(try_to_hold_port)); + return current::net::ReservedLocalPort( + current::net::ReservedLocalPort::Construct(), candidate_port, std::move(try_to_hold_port)); } catch (const current::net::SocketConnectException&) { // Keep trying. // std::cerr << "Failed in `connect`." << candidate_port << '\n'; @@ -374,7 +363,7 @@ class ReserveLocalPortImpl final { } }; -} // namespace current::net::impl +} // namespace impl // Pick an available local port. [[nodiscard]] inline ReservedLocalPort ReserveLocalPort( @@ -387,7 +376,8 @@ class ReserveLocalPortImpl final { uint16_t hint, NagleAlgorithm nagle_algorithm_policy = kDefaultNagleAlgorithmPolicy, MaxServerQueuedConnectionsValue max_connections = kMaxServerQueuedConnections) { - return current::ThreadLocalSingleton().DoIt(hint, nagle_algorithm_policy, max_connections); + return current::ThreadLocalSingleton().DoIt( + hint, nagle_algorithm_policy, max_connections); } class Connection : public SocketHandle { @@ -411,9 +401,7 @@ class Connection : public SocketHandle { enum BlockingReadPolicy { ReturnASAP = false, FillFullBuffer = true }; template inline std::enable_if_t BlockingRead( - T* output_buffer, - size_t max_length, - BlockingReadPolicy policy = BlockingReadPolicy::ReturnASAP) { + T* output_buffer, size_t max_length, BlockingReadPolicy policy = BlockingReadPolicy::ReturnASAP) { if (max_length == 0) { return 0; // LCOV_EXCL_LINE } else { @@ -580,8 +568,7 @@ class Socket final : public SocketHandle { explicit Socket(BarePort bare_port, NagleAlgorithm nagle_algorithm_policy = kDefaultNagleAlgorithmPolicy, MaxServerQueuedConnectionsValue max_connections = kMaxServerQueuedConnections) - : SocketHandle(SocketHandle::BindAndListen(), bare_port, nagle_algorithm_policy, max_connections) { - } + : SocketHandle(SocketHandle::BindAndListen(), bare_port, nagle_algorithm_policy, max_connections) {} explicit Socket(ReservedLocalPort&& reserved_port) : SocketHandle(std::move(reserved_port)) {} @@ -637,7 +624,7 @@ namespace addrinfo_t_impl { struct Deleter { void operator()(struct addrinfo* ptr) { ::freeaddrinfo(ptr); } }; -} +} // namespace addrinfo_t_impl using addrinfo_t = std::unique_ptr; inline addrinfo_t GetAddrInfo(const std::string& host, const std::string& serv = "") { @@ -671,7 +658,7 @@ inline Connection ClientSocket(const std::string& host, T port_or_serv) { class ClientSocket final : public SocketHandle { public: explicit ClientSocket(const std::string& host, - const std::string& serv, + const std::string& serv, NagleAlgorithm nagle_algorithm_policy = kDefaultNagleAlgorithmPolicy) : SocketHandle(SocketHandle::DoNotBind(), nagle_algorithm_policy) { CURRENT_BRICKS_NET_LOG("S%05d ", static_cast(socket)); diff --git a/bricks/net/tcp/test.cc b/bricks/net/tcp/test.cc index 55e21c895..9b9ee93d3 100644 --- a/bricks/net/tcp/test.cc +++ b/bricks/net/tcp/test.cc @@ -41,15 +41,15 @@ using std::string; using std::to_string; using std::vector; -using std::this_thread::sleep_for; using std::chrono::milliseconds; +using std::this_thread::sleep_for; -using current::strings::Printf; using current::Singleton; -using current::net::Socket; -using current::net::Connection; using current::net::ClientSocket; +using current::net::Connection; using current::net::ResolveIPFromHostname; +using current::net::Socket; +using current::strings::Printf; using current::net::AttemptedToUseMovedAwayConnection; using current::net::SocketBindException; @@ -79,44 +79,38 @@ static void ExpectFromSocket(const std::string& golden, const string& host, const uint16_t port, const string& message_to_send_from_client = "") { - ExpectFromSocket(golden, - server_thread, - host, - port, - [&message_to_send_from_client](Connection& connection) { - if (!message_to_send_from_client.empty()) { - connection.BlockingWrite(message_to_send_from_client, false); - } - }); + ExpectFromSocket(golden, server_thread, host, port, [&message_to_send_from_client](Connection& connection) { + if (!message_to_send_from_client.empty()) { + connection.BlockingWrite(message_to_send_from_client, false); + } + }); } static void ExpectFromSocket(const std::string& golden, std::thread& server_thread, const uint16_t port, const string& message_to_send_from_client = "") { - ExpectFromSocket(golden, - server_thread, - "localhost", - port, - [&message_to_send_from_client](Connection& connection) { - if (!message_to_send_from_client.empty()) { - connection.BlockingWrite(message_to_send_from_client, false); - } - }); + ExpectFromSocket(golden, server_thread, "localhost", port, [&message_to_send_from_client](Connection& connection) { + if (!message_to_send_from_client.empty()) { + connection.BlockingWrite(message_to_send_from_client, false); + } + }); } TEST(TCPTest, IPAndPort) { current::net::ReservedLocalPort port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server([port_number](Socket socket) { - Connection connection = socket.Accept(); - EXPECT_EQ("127.0.0.1", connection.LocalIPAndPort().ip); - EXPECT_EQ(port_number, connection.LocalIPAndPort().port); - EXPECT_EQ("127.0.0.1", connection.RemoteIPAndPort().ip); - EXPECT_LT(0, connection.RemoteIPAndPort().port); - connection.BlockingWrite("42", false); - }, Socket(std::move(port_reservation))); + std::thread server( + [port_number](Socket socket) { + Connection connection = socket.Accept(); + EXPECT_EQ("127.0.0.1", connection.LocalIPAndPort().ip); + EXPECT_EQ(port_number, connection.LocalIPAndPort().port); + EXPECT_EQ("127.0.0.1", connection.RemoteIPAndPort().ip); + EXPECT_LT(0, connection.RemoteIPAndPort().port); + connection.BlockingWrite("42", false); + }, + Socket(std::move(port_reservation))); Connection client(ClientSocket("127.0.0.1", port_number)); EXPECT_EQ("127.0.0.1", client.LocalIPAndPort().ip); EXPECT_LT(0, client.LocalIPAndPort().port); @@ -146,12 +140,14 @@ TEST(TCPTest, ReceiveMessageOfTwoParts) { TEST(TCPTest, ReceiveDelayedMessage) { current::net::ReservedLocalPort port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server([](Socket socket) { - Connection connection = socket.Accept(); - connection.BlockingWrite("BLA", true); - sleep_for(milliseconds(1)); - connection.BlockingWrite("H", false); - }, std::move(port_reservation)); + std::thread server( + [](Socket socket) { + Connection connection = socket.Accept(); + connection.BlockingWrite("BLA", true); + sleep_for(milliseconds(1)); + connection.BlockingWrite("H", false); + }, + std::move(port_reservation)); Connection client(ClientSocket("localhost", port_number)); char response[5] = "????"; ASSERT_EQ(4u, client.BlockingRead(response, 4, Connection::FillFullBuffer)); @@ -162,14 +158,16 @@ TEST(TCPTest, ReceiveDelayedMessage) { TEST(TCPTest, ReceiveMessageAsResponse) { current::net::ReservedLocalPort port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server([](Socket socket) { - Connection connection = socket.Accept(); - connection.BlockingWrite("{", true); - char buffer[2]; // Wait for three incoming bytes before sending data out. - ASSERT_EQ(2u, connection.BlockingRead(buffer, 2, Connection::FillFullBuffer)); - connection.BlockingWrite(buffer, 2, true); - connection.BlockingWrite("}", false); - }, std::move(port_reservation)); + std::thread server( + [](Socket socket) { + Connection connection = socket.Accept(); + connection.BlockingWrite("{", true); + char buffer[2]; // Wait for three incoming bytes before sending data out. + ASSERT_EQ(2u, connection.BlockingRead(buffer, 2, Connection::FillFullBuffer)); + connection.BlockingWrite(buffer, 2, true); + connection.BlockingWrite("}", false); + }, + std::move(port_reservation)); Connection client(ClientSocket("localhost", port_number)); client.BlockingWrite("!?", false); char response[5] = "????"; @@ -181,12 +179,14 @@ TEST(TCPTest, ReceiveMessageAsResponse) { TEST(TCPTest, CanNotUseMovedAwayConnection) { current::net::ReservedLocalPort port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server([](Socket socket) { - Connection connection = socket.Accept(); - char buffer[3]; // Wait for three incoming bytes before sending data out. - ASSERT_EQ(3u, connection.BlockingRead(buffer, 3, Connection::FillFullBuffer)); - connection.BlockingWrite("OK", false); - }, std::move(port_reservation)); + std::thread server( + [](Socket socket) { + Connection connection = socket.Accept(); + char buffer[3]; // Wait for three incoming bytes before sending data out. + ASSERT_EQ(3u, connection.BlockingRead(buffer, 3, Connection::FillFullBuffer)); + connection.BlockingWrite("OK", false); + }, + std::move(port_reservation)); Connection old_connection(ClientSocket("localhost", port_number)); old_connection.BlockingWrite("1", true); Connection new_connection(std::move(old_connection)); @@ -204,59 +204,63 @@ TEST(TCPTest, ReceiveMessageOfTwoUInt16AndTestEndianness) { // NOTE(dkorolev): This tests endianness as well. current::net::ReservedLocalPort port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server_thread([](Socket socket) { - socket.Accept().BlockingWrite(vector{0x3031, 0x3233}, false); - }, std::move(port_reservation)); + std::thread server_thread( + [](Socket socket) { + socket.Accept().BlockingWrite(vector{0x3031, 0x3233}, false); + }, + std::move(port_reservation)); ExpectFromSocket("1032", server_thread, port_number); } TEST(TCPTest, EchoMessage) { current::net::ReservedLocalPort port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server_thread([](Socket socket) { - Connection connection(socket.Accept()); - std::vector s(7); - ASSERT_EQ(s.size(), connection.BlockingRead(&s[0], s.size(), Connection::FillFullBuffer)); - connection.BlockingWrite("ECHO: " + std::string(s.begin(), s.end()), false); - }, std::move(port_reservation)); + std::thread server_thread( + [](Socket socket) { + Connection connection(socket.Accept()); + std::vector s(7); + ASSERT_EQ(s.size(), connection.BlockingRead(&s[0], s.size(), Connection::FillFullBuffer)); + connection.BlockingWrite("ECHO: " + std::string(s.begin(), s.end()), false); + }, + std::move(port_reservation)); ExpectFromSocket("ECHO: TEST OK", server_thread, port_number, std::string("TEST OK")); } TEST(TCPTest, EchoThreeMessages) { current::net::ReservedLocalPort port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server_thread([](Socket socket) { - const size_t block_length = 3; - string s(block_length, ' '); - Connection connection(socket.Accept()); - for (int i = 0; i < 3; ++i) { - ASSERT_EQ(block_length, connection.BlockingRead(&s[0], block_length, Connection::FillFullBuffer)); - connection.BlockingWrite(i > 0 ? "," : "ECHO: ", true); - connection.BlockingWrite(s, false); - } - }, std::move(port_reservation)); - ExpectFromSocket("ECHO: FOO,BAR,BAZ", - server_thread, - "localhost", - port_number, - [](Connection& connection) { - connection.BlockingWrite("FOOBARB", true); - sleep_for(milliseconds(1)); - connection.BlockingWrite("A", true); - sleep_for(milliseconds(1)); - connection.BlockingWrite("Z", false); - }); + std::thread server_thread( + [](Socket socket) { + const size_t block_length = 3; + string s(block_length, ' '); + Connection connection(socket.Accept()); + for (int i = 0; i < 3; ++i) { + ASSERT_EQ(block_length, connection.BlockingRead(&s[0], block_length, Connection::FillFullBuffer)); + connection.BlockingWrite(i > 0 ? "," : "ECHO: ", true); + connection.BlockingWrite(s, false); + } + }, + std::move(port_reservation)); + ExpectFromSocket("ECHO: FOO,BAR,BAZ", server_thread, "localhost", port_number, [](Connection& connection) { + connection.BlockingWrite("FOOBARB", true); + sleep_for(milliseconds(1)); + connection.BlockingWrite("A", true); + sleep_for(milliseconds(1)); + connection.BlockingWrite("Z", false); + }); } TEST(TCPTest, EchoLongMessageTestsDynamicBufferGrowth) { current::net::ReservedLocalPort port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server_thread([](Socket socket) { - Connection connection(socket.Accept()); - std::vector s(10000); - ASSERT_EQ(s.size(), connection.BlockingRead(&s[0], s.size(), Connection::FillFullBuffer)); - connection.BlockingWrite("ECHO: " + std::string(s.begin(), s.end()), false); - }, std::move(port_reservation)); + std::thread server_thread( + [](Socket socket) { + Connection connection(socket.Accept()); + std::vector s(10000); + ASSERT_EQ(s.size(), connection.BlockingRead(&s[0], s.size(), Connection::FillFullBuffer)); + connection.BlockingWrite("ECHO: " + std::string(s.begin(), s.end()), false); + }, + std::move(port_reservation)); std::string message; for (size_t i = 0; i < 10000; ++i) { message += '0' + (i % 10); @@ -309,12 +313,14 @@ TEST(TCPTest, CanNotBindTwoSocketsToTheSamePortSimultaneously) { TEST(TCPTest, WriteExceptionWhileWritingAVeryLongMessage) { auto port_reservation = ReserveLocalPort(); const uint16_t port_number = port_reservation; - std::thread server_thread([](Socket socket) { - Connection connection(socket.Accept()); - char buffer[3]; - connection.BlockingRead(buffer, 3, Connection::FillFullBuffer); - connection.BlockingWrite("Done, thanks.\n", false); - }, Socket(std::move(port_reservation))); + std::thread server_thread( + [](Socket socket) { + Connection connection(socket.Accept()); + char buffer[3]; + connection.BlockingRead(buffer, 3, Connection::FillFullBuffer); + connection.BlockingWrite("Done, thanks.\n", false); + }, + Socket(std::move(port_reservation))); // Attempt to send a very long message to ensure it does not fit OS buffers. Connection connection(ClientSocket("localhost", port_number)); ASSERT_THROW(connection.BlockingWrite(std::vector(100 * 1000 * 1000, '!'), true), @@ -347,12 +353,12 @@ TEST(TCPTest, PickLocalPort) { } #if 0 -# NOTE(dkorolev): This test will fail if the following command is run from two terminals concurrently. +#NOTE(dkorolev) : This test will fail if the following command is run from two terminals concurrently. while true ; do ./.current/test \ --gtest_filter=TCPTest.PickLocalPortWithHint \ --gtest_throw_on_failure \ --gtest_catch_exceptions=0 || break ; done -# The above test, `TCPTest.PickLocalPort`, would run just fine in such a scenario. +#The above test, `TCPTest.PickLocalPort`, would run just fine in such a scenario. #endif TEST(TCPTest, PickLocalPortWithHint) { diff --git a/bricks/strings/chunk.h b/bricks/strings/chunk.h index ca7c85602..ee5b4a7db 100644 --- a/bricks/strings/chunk.h +++ b/bricks/strings/chunk.h @@ -166,12 +166,8 @@ class Chunk { typedef EqualityComparator Pride; // Your favorite equality smiley here. Mine is *HAWAII*, because rainbow. // Still allow comparing `Chunk`-s to `std::string`-s, for purely code readability purposes. - bool operator==(const std::string& rhs) const { - return N == rhs.length() && ::memcmp(S, rhs.c_str(), N) == 0; - } - bool operator!=(const std::string& rhs) const { - return !operator==(rhs); - } + bool operator==(const std::string& rhs) const { return N == rhs.length() && ::memcmp(S, rhs.c_str(), N) == 0; } + bool operator!=(const std::string& rhs) const { return !operator==(rhs); } private: const char* S; diff --git a/bricks/strings/fixed_size_serializer.h b/bricks/strings/fixed_size_serializer.h index db2e35966..c667e997e 100644 --- a/bricks/strings/fixed_size_serializer.h +++ b/bricks/strings/fixed_size_serializer.h @@ -40,8 +40,9 @@ namespace strings { struct FixedSizeSerializerEnabler {}; template -struct FixedSizeSerializer : std::enable_if_t::value && std::is_integral::value && (sizeof(T) > 1), - FixedSizeSerializerEnabler> { +struct FixedSizeSerializer + : std::enable_if_t::value && std::is_integral::value && (sizeof(T) > 1), + FixedSizeSerializerEnabler> { enum { size_in_bytes = std::numeric_limits::digits10 + 1 }; static std::string PackToString(T x) { std::ostringstream os; @@ -67,7 +68,7 @@ inline const T& UnpackFromString(std::string const& s, T& x) { return x; } -} // namespace string +} // namespace strings } // namespace current #endif // BRICKS_STRINGS_FIXED_SIZE_SERIALIZER_H diff --git a/bricks/strings/group_by_lines.h b/bricks/strings/group_by_lines.h index e3bb6463b..ae25ff0c6 100644 --- a/bricks/strings/group_by_lines.h +++ b/bricks/strings/group_by_lines.h @@ -90,12 +90,10 @@ class GenericStatefulGroupByLines final { PROCESSOR::DoProcess(std::move(extracted), f_); } } - + public: explicit GenericStatefulGroupByLines(F&& f) : f_(std::move(f)) {} - void Feed(const std::string& s) { - Feed(s.c_str()); - } + void Feed(const std::string& s) { Feed(s.c_str()); } void Feed(const char* s) { if (done_called_) { CURRENT_THROW(GroupByLinesFeedCaledAfterDone()); @@ -159,82 +157,71 @@ class GenericStatefulGroupByLines final { } }; -using StatefulGroupByLines = - GenericStatefulGroupByLines, - GroupByLinesExceptions::Prohibit, - GenericStatefulGroupByLinesProcessCPPString>; -using StatefulGroupByLinesCStringProcessing = - GenericStatefulGroupByLines, - GroupByLinesExceptions::Prohibit, - GenericStatefulGroupByLinesProcessCString>; - -using ExceptionFriendlyStatefulGroupByLines = - GenericStatefulGroupByLines, - GroupByLinesExceptions::Allow, - GenericStatefulGroupByLinesProcessCPPString>; +using StatefulGroupByLines = GenericStatefulGroupByLines, + GroupByLinesExceptions::Prohibit, + GenericStatefulGroupByLinesProcessCPPString>; +using StatefulGroupByLinesCStringProcessing = GenericStatefulGroupByLines, + GroupByLinesExceptions::Prohibit, + GenericStatefulGroupByLinesProcessCString>; + +using ExceptionFriendlyStatefulGroupByLines = GenericStatefulGroupByLines, + GroupByLinesExceptions::Allow, + GenericStatefulGroupByLinesProcessCPPString>; using ExceptionFriendlyStatefulGroupByLinesCStringProcessing = - GenericStatefulGroupByLines, - GroupByLinesExceptions::Allow, - GenericStatefulGroupByLinesProcessCString>; + GenericStatefulGroupByLines, + GroupByLinesExceptions::Allow, + GenericStatefulGroupByLinesProcessCString>; template struct CreateStatefulGroupByLinesImpl; template struct CreateStatefulGroupByLinesImpl final { - using type_t = GenericStatefulGroupByLines, - E, - GenericStatefulGroupByLinesProcessCPPString>; - static type_t DoIt(F&& f) { - return type_t(std::forward(f)); - } + using type_t = + GenericStatefulGroupByLines, E, GenericStatefulGroupByLinesProcessCPPString>; + static type_t DoIt(F&& f) { return type_t(std::forward(f)); } }; template struct CreateStatefulGroupByLinesImpl final { - using type_t = GenericStatefulGroupByLines, - E, - GenericStatefulGroupByLinesProcessCString>; - static type_t DoIt(F&& f) { - return type_t(std::forward(f)); - } + using type_t = + GenericStatefulGroupByLines, E, GenericStatefulGroupByLinesProcessCString>; + static type_t DoIt(F&& f) { return type_t(std::forward(f)); } }; #ifndef CURRENT_FOR_CPP14 template auto CreateStatefulGroupByLines(F&& f) { - return CreateStatefulGroupByLinesImpl< - F, - GroupByLinesExceptions::Prohibit, - std::is_invocable::value, - std::is_invocable::value>::DoIt(std::forward(f)); + return CreateStatefulGroupByLinesImpl::value, + std::is_invocable::value>::DoIt(std::forward(f)); } template auto CreateExceptionFriendlyStatefulGroupByLines(F&& f) { - return CreateStatefulGroupByLinesImpl< - F, - GroupByLinesExceptions::Allow, - std::is_invocable::value, - std::is_invocable::value>::DoIt(std::forward(f)); + return CreateStatefulGroupByLinesImpl::value, + std::is_invocable::value>::DoIt(std::forward(f)); } #else template auto CreateStatefulGroupByLines(F&& f) { return CreateStatefulGroupByLinesImpl< - F, - GroupByLinesExceptions::Prohibit, - current::weed::call_with::implemented, - current::weed::call_with::implemented>::DoIt(std::forward(f)); + F, + GroupByLinesExceptions::Prohibit, + current::weed::call_with::implemented, + current::weed::call_with::implemented>::DoIt(std::forward(f)); } template auto CreateExceptionFriendlyStatefulGroupByLines(F&& f) { return CreateStatefulGroupByLinesImpl< - F, - GroupByLinesExceptions::Allow, - current::weed::call_with::implemented, - current::weed::call_with::implemented>::DoIt(std::forward(f)); + F, + GroupByLinesExceptions::Allow, + current::weed::call_with::implemented, + current::weed::call_with::implemented>::DoIt(std::forward(f)); } #endif // CURRENT_FOR_CPP14 diff --git a/bricks/strings/join.h b/bricks/strings/join.h index 41f747728..5d72ba304 100644 --- a/bricks/strings/join.h +++ b/bricks/strings/join.h @@ -65,9 +65,10 @@ template struct is_container : std::false_type {}; template -struct is_container().begin()), - decltype(std::declval().end()), - typename T::value_type>> : std::true_type {}; +struct is_container< + T, + std::void_t().begin()), decltype(std::declval().end()), typename T::value_type>> + : std::true_type {}; #ifndef CURRENT_FOR_CPP14 @@ -105,7 +106,7 @@ template void OptionallyReserveOutputBuffer(std::string& output, const CONTAINER& components, SEPARATOR&& separator) { #ifndef CURRENT_FOR_CPP14 // Note: this implementation does not do `reserve()` for chars, the length of which is always known to be 1. - if constexpr(sfinae::is_container_of_strings_v) { + if constexpr (sfinae::is_container_of_strings_v) { if (!components.empty()) { size_t length = 0; for (const auto& cit : components) { diff --git a/bricks/strings/printf.h b/bricks/strings/printf.h index 700f2e63b..f346ceefd 100644 --- a/bricks/strings/printf.h +++ b/bricks/strings/printf.h @@ -39,7 +39,8 @@ namespace strings { #ifdef __GNUC__ __attribute__((__format__(__printf__, 1, 2))) #endif -inline std::string Printf(const char *fmt, ...) { +inline std::string +Printf(const char *fmt, ...) { // Most of the platforms now support thread locals, so 64Kb buffer seems reasonable. constexpr int max_string_length_for_static_buffer = 64 * 1024 - 1; // Absolute limit on result size is 1Mb. @@ -67,7 +68,8 @@ inline std::string Printf(const char *fmt, ...) { } #else va_start(ap, fmt); - const int res = _vsnprintf_s(buffer, max_string_length_for_static_buffer + 1, max_string_length_for_static_buffer, fmt, ap); + const int res = + _vsnprintf_s(buffer, max_string_length_for_static_buffer + 1, max_string_length_for_static_buffer, fmt, ap); va_end(ap); if (res < 0 || errno == ERANGE) { va_start(ap, fmt); diff --git a/bricks/strings/regex.h b/bricks/strings/regex.h index 64d8ac0fe..aca81a9e0 100644 --- a/bricks/strings/regex.h +++ b/bricks/strings/regex.h @@ -43,8 +43,7 @@ struct IterateByRegexMatches { : copy_of_string_if_needed_(s), begin_(copy_of_string_if_needed_.begin(), copy_of_string_if_needed_.end(), re) {} template - IterateByRegexMatches(const std::regex& re, T&& s) - : begin_(s.begin(), s.end(), re) {} + IterateByRegexMatches(const std::regex& re, T&& s) : begin_(s.begin(), s.end(), re) {} std::sregex_iterator begin() const { return begin_; } std::sregex_iterator end() const { return end_; } @@ -106,17 +105,14 @@ class NamedRegexCapturer { std::smatch match; MatchResult(std::string input_string, std::shared_ptr data) - : owned_string(std::make_unique(std::move(input_string))), - data(std::move(data)) {} + : owned_string(std::make_unique(std::move(input_string))), data(std::move(data)) {} MatchResult() = delete; MatchResult(MatchResult const&) = delete; MatchResult& operator=(MatchResult const&) = delete; MatchResult(MatchResult&& rhs) - : owned_string(std::move(rhs.owned_string)), - data(rhs.data), - match(std::move(rhs.match)) {} + : owned_string(std::move(rhs.owned_string)), data(rhs.data), match(std::move(rhs.match)) {} MatchResult& operator=(MatchResult&& rhs) { owned_string = std::move(rhs.owned_string); @@ -180,8 +176,7 @@ class NamedRegexCapturer { Iterable(std::shared_ptr data, std::string::const_iterator begin, std::string::const_iterator end) - : data_(std::move(data)), - begin_(begin, end, data_->transformed_re) {} + : data_(std::move(data)), begin_(begin, end, data_->transformed_re) {} struct Iterator { const std::shared_ptr data_shared_ptr_; diff --git a/bricks/strings/split.h b/bricks/strings/split.h index e15a5b693..67f6df131 100644 --- a/bricks/strings/split.h +++ b/bricks/strings/split.h @@ -257,10 +257,11 @@ SplitIntoChunks(Chunk chunk, SEPARATOR&& separator = impl::DefaultSeparator::value(), EmptyFields empty_fields_strategy = EmptyFields::Skip) { std::vector result; - Split(chunk, - std::forward(separator), - [&result](Chunk chunk) { result.emplace_back(chunk); }, - empty_fields_strategy); + Split( + chunk, + std::forward(separator), + [&result](Chunk chunk) { result.emplace_back(chunk); }, + empty_fields_strategy); return result; } @@ -290,10 +291,11 @@ Split(STRING&& s, SEPARATOR&& separator = impl::DefaultSeparator::value(), EmptyFields empty_fields_strategy = EmptyFields::Skip) { std::vector result; - Split(std::forward(s), - std::forward(separator), - [&result](std::string&& chunk) { result.emplace_back(std::move(chunk)); }, - empty_fields_strategy); + Split( + std::forward(s), + std::forward(separator), + [&result](std::string&& chunk) { result.emplace_back(std::move(chunk)); }, + empty_fields_strategy); return result; } diff --git a/bricks/strings/test.cc b/bricks/strings/test.cc index 7ee584c8d..87e921360 100644 --- a/bricks/strings/test.cc +++ b/bricks/strings/test.cc @@ -32,39 +32,39 @@ SOFTWARE. #include "../../3rdparty/gtest/gtest-main.h" -using current::strings::Printf; -using current::strings::FixedSizeSerializer; -using current::strings::PackToString; -using current::strings::UnpackFromString; +using current::strings::ByLines; +using current::strings::ByWhitespace; +using current::strings::Chunk; +using current::strings::ChunkDB; using current::strings::CompileTimeStringLength; -using current::strings::Trim; -using current::strings::ToLower; -using current::strings::ToUpper; +using current::strings::CreateExceptionFriendlyStatefulGroupByLines; +using current::strings::CreateStatefulGroupByLines; +using current::strings::EmptyFields; +using current::strings::EscapeForCPlusPlus; +using current::strings::EscapeForMarkdown; +using current::strings::ExceptionFriendlyStatefulGroupByLines; +using current::strings::FastEditDistance; +using current::strings::FixedSizeSerializer; +using current::strings::is_string_type; using current::strings::Join; +using current::strings::KeyValueMultipleValuesException; +using current::strings::KeyValueNoValueException; +using current::strings::KeyValueParsing; +using current::strings::PackToString; +using current::strings::Printf; +using current::strings::RoundDoubleToString; +using current::strings::SlowEditDistance; using current::strings::Split; using current::strings::SplitIntoChunks; using current::strings::SplitIntoKeyValuePairs; using current::strings::StatefulGroupByLines; -using current::strings::CreateStatefulGroupByLines; -using current::strings::ExceptionFriendlyStatefulGroupByLines; -using current::strings::CreateExceptionFriendlyStatefulGroupByLines; -using current::strings::EmptyFields; -using current::strings::KeyValueParsing; -using current::strings::KeyValueNoValueException; -using current::strings::KeyValueMultipleValuesException; -using current::strings::ByWhitespace; -using current::strings::ByLines; -using current::strings::SlowEditDistance; -using current::strings::FastEditDistance; -using current::strings::Chunk; -using current::strings::UniqueChunk; -using current::strings::ChunkDB; -using current::strings::RoundDoubleToString; -using current::strings::TimeIntervalAsHumanReadableString; using current::strings::TimeDifferenceAsHumanReadableString; -using current::strings::EscapeForCPlusPlus; -using current::strings::EscapeForMarkdown; -using current::strings::is_string_type; +using current::strings::TimeIntervalAsHumanReadableString; +using current::strings::ToLower; +using current::strings::ToUpper; +using current::strings::Trim; +using current::strings::UniqueChunk; +using current::strings::UnpackFromString; TEST(StringPrintf, SmokeTest) { EXPECT_EQ("Test: 42, 'Hello', 0000ABBA", Printf("Test: %d, '%s', %08X", 42, "Hello", 0xabba)); @@ -880,7 +880,9 @@ TEST(Regex, SubmatchesDoTheirJobForUnnamedSuperGroups) { TEST(Regex, SimpleTokenization) { const std::vector clauses({ - "(?[A-Z]+)", "(?[a-z]+)", "(?[0-9]+)", + "(?[A-Z]+)", + "(?[a-z]+)", + "(?[0-9]+)", }); const current::strings::NamedRegexCapturer re(current::strings::Join(clauses, '|')); EXPECT_EQ("([A-Z]+)|([a-z]+)|([0-9]+)", re.GetTransformedRegexBody()); @@ -905,7 +907,8 @@ TEST(Regex, SimpleTokenization) { TEST(Regex, MemoryOwnershipSmokeTest) { const std::vector cs({ - "(?foo)", "(?bar)", + "(?foo)", + "(?bar)", }); std::vector output; for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')).Iterate("foo bar")) { @@ -922,12 +925,14 @@ TEST(Regex, MemoryOwnershipSmokeTest) { TEST(Regex, SubstringIterationSmokeTest) { const std::vector cs({ - "(?foo)", "(?bar)", + "(?foo)", + "(?bar)", }); std::string const foo_bar = "foo bar"; { std::vector output; - for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')).Iterate(foo_bar.begin(), foo_bar.end())) { + for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')) + .Iterate(foo_bar.begin(), foo_bar.end())) { if (token.Has("foo")) { output.push_back("foo@" + current::ToString(token.position())); } else if (token.Has("bar")) { @@ -940,7 +945,8 @@ TEST(Regex, SubstringIterationSmokeTest) { } { std::vector output; - for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')).Iterate(foo_bar.begin(), foo_bar.begin() + 3u)) { + for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')) + .Iterate(foo_bar.begin(), foo_bar.begin() + 3u)) { if (token.Has("foo")) { output.push_back("foo@" + current::ToString(token.position())); } else if (token.Has("bar")) { @@ -953,7 +959,8 @@ TEST(Regex, SubstringIterationSmokeTest) { } { std::vector output; - for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')).Iterate(foo_bar.begin() + 3u, foo_bar.begin() + 7u)) { + for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')) + .Iterate(foo_bar.begin() + 3u, foo_bar.begin() + 7u)) { if (token.Has("foo")) { output.push_back("foo@" + current::ToString(token.position())); } else if (token.Has("bar")) { @@ -966,7 +973,8 @@ TEST(Regex, SubstringIterationSmokeTest) { } { std::vector output; - for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')).Iterate(foo_bar.begin() + 5u, foo_bar.begin() + 7u)) { + for (const auto& token : current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')) + .Iterate(foo_bar.begin() + 5u, foo_bar.begin() + 7u)) { if (token.Has("foo")) { output.push_back("foo@" + current::ToString(token.position())); } else if (token.Has("bar")) { @@ -978,15 +986,18 @@ TEST(Regex, SubstringIterationSmokeTest) { EXPECT_TRUE(output.empty()); } { - const auto iterable = current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')).Iterate(foo_bar.begin() + 0u, foo_bar.begin() + 7u); + const auto iterable = current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')) + .Iterate(foo_bar.begin() + 0u, foo_bar.begin() + 7u); EXPECT_FALSE(iterable.begin() == iterable.end()); } { - const auto iterable = current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')).Iterate(foo_bar.begin() + 0u, foo_bar.begin() + 2u); + const auto iterable = current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')) + .Iterate(foo_bar.begin() + 0u, foo_bar.begin() + 2u); EXPECT_TRUE(iterable.begin() == iterable.end()); } { - const auto iterable = current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')).Iterate(foo_bar.begin() + 5u, foo_bar.begin() + 7u); + const auto iterable = current::strings::NamedRegexCapturer(current::strings::Join(cs, '|')) + .Iterate(foo_bar.begin() + 5u, foo_bar.begin() + 7u); EXPECT_TRUE(iterable.begin() == iterable.end()); } } @@ -998,7 +1009,8 @@ TEST(UTF8StringLength, Smoke) { TEST(StatefulGroupByLines, SmokeTrivial) { std::vector lines; - StatefulGroupByLines splitter = CreateStatefulGroupByLines([&lines](const std::string& line) { lines.push_back(line); }); + StatefulGroupByLines splitter = + CreateStatefulGroupByLines([&lines](const std::string& line) { lines.push_back(line); }); splitter.Feed("foo\n"); splitter.Feed("bar\n"); splitter.Feed("baz\n"); @@ -1091,9 +1103,7 @@ TEST(StatefulGroupByLines, DoneMustBeCalledForExceptionFriendlySplitter) { bool done_not_called_failure = false; auto& handler = current::Singleton(); handler.InjectHandler([&done_not_called_failure]() { done_not_called_failure = true; }); - { - RunTest(lines).DoRunTest(); - } + { RunTest(lines).DoRunTest(); } handler.ResetHandler(); ASSERT_TRUE(done_not_called_failure); ASSERT_EQ(2u, lines.size()); @@ -1103,9 +1113,7 @@ TEST(StatefulGroupByLines, DoneMustBeCalledForExceptionFriendlySplitter) { TEST(StatefulGroupByLines, CanNotCallDoneTwiceOnExceptionFriendlySplitter) { std::vector lines; - auto splitter = CreateExceptionFriendlyStatefulGroupByLines([&lines](const char* line) { - lines.push_back(line); - }); + auto splitter = CreateExceptionFriendlyStatefulGroupByLines([&lines](const char* line) { lines.push_back(line); }); ASSERT_EQ(0u, lines.size()); splitter.Feed("foo\nba"); ASSERT_EQ(1u, lines.size()); diff --git a/bricks/strings/util.h b/bricks/strings/util.h index dd16ea830..38bd585df 100644 --- a/bricks/strings/util.h +++ b/bricks/strings/util.h @@ -223,7 +223,6 @@ struct FromStringImpl { } }; - template struct FromStringImpl { static const std::chrono::milliseconds& Go(INPUT&& input, std::chrono::milliseconds& output) { @@ -272,7 +271,7 @@ inline OUTPUT FromString(INPUT&& input) { inline std::string FromString(const std::string& input) { return input; } template -constexpr std::enable_if_t<(N > 0), size_t> CompileTimeStringLength(char const(&)[N]) { +constexpr std::enable_if_t<(N > 0), size_t> CompileTimeStringLength(char const (&)[N]) { return N - 1; } @@ -341,8 +340,8 @@ inline const char* ConstCharPtr(const std::string& s) { return s.c_str(); } } // namespace strings -using strings::ToString; using strings::FromString; +using strings::ToString; } // namespace current diff --git a/bricks/sync/locks.h b/bricks/sync/locks.h index e1c56bebc..de7a41492 100644 --- a/bricks/sync/locks.h +++ b/bricks/sync/locks.h @@ -41,8 +41,7 @@ struct NoOpLock { }; template -using SmartMutexLockGuard = - std::conditional_t, NoOpLock>; +using SmartMutexLockGuard = std::conditional_t, NoOpLock>; static_assert(std::is_same_v, SmartMutexLockGuard>, ""); static_assert(std::is_same_v>, ""); diff --git a/bricks/sync/owned_borrowed.h b/bricks/sync/owned_borrowed.h index 29c23e8ee..0c5efe09a 100644 --- a/bricks/sync/owned_borrowed.h +++ b/bricks/sync/owned_borrowed.h @@ -153,7 +153,7 @@ struct UniqueInstance final { size_t total_borrowers_spawned_throughout_lifetime_; // A pre-increment of this value is the key in the above map. }; -} // namespace current::sync::impl +} // namespace impl template class Owned; @@ -308,7 +308,7 @@ struct UniqueInstanceContainer { UniqueInstanceContainer& operator=(const UniqueInstanceContainer&) = delete; }; -} // namespace current::sync::impl +} // namespace impl template struct ConstructOwned {}; @@ -466,7 +466,7 @@ Owned MakeOwned(ARGS&&... args) { return Owned(ConstructOwned(), std::forward(args)...); } -} // namespace current::sync +} // namespace sync template using ConstructOwned = sync::ConstructOwned; diff --git a/bricks/sync/test.cc b/bricks/sync/test.cc index 74d65ff94..56981b06a 100644 --- a/bricks/sync/test.cc +++ b/bricks/sync/test.cc @@ -194,11 +194,10 @@ TEST(OwnedBorrowed, BorrowedWithCallbackOutlivingTheOwner) { y.ExclusiveUse([](Container& container) { ++container.ref; }); } }, - std::make_unique>(x, - [&log, &terminating]() { - terminating = true; - log += "Terminating.\n"; - })); + std::make_unique>(x, [&log, &terminating]() { + terminating = true; + log += "Terminating.\n"; + })); EXPECT_EQ(1u, x.NumberOfActiveBorrowers()); EXPECT_EQ(1u, x.TotalBorrowersSpawnedThroughoutLifetime()); @@ -231,16 +230,18 @@ TEST(OwnedBorrowed, UseInternalIsDestructingGetter) { std::unique_ptr thread; { current::Owned x(current::ConstructOwned(), container); - thread = std::make_unique([](current::Borrowed y) { - // Keep incrementing until external termination request. - while (y) { - y.ExclusiveUse([](Container& container) { ++container.ref; }); - } - // And do another one thousand increments just because we can. - for (int i = 0; i < 1000; ++i) { - y.ExclusiveUse([](Container& container) { ++container.ref; }); - } - }, current::Borrowed(x)); + thread = std::make_unique( + [](current::Borrowed y) { + // Keep incrementing until external termination request. + while (y) { + y.ExclusiveUse([](Container& container) { ++container.ref; }); + } + // And do another one thousand increments just because we can. + for (int i = 0; i < 1000; ++i) { + y.ExclusiveUse([](Container& container) { ++container.ref; }); + } + }, + current::Borrowed(x)); int extracted_value; do { @@ -253,8 +254,8 @@ TEST(OwnedBorrowed, UseInternalIsDestructingGetter) { } TEST(WaitableAtomic, Smoke) { - using current::WaitableAtomic; using current::IntrusiveClient; + using current::WaitableAtomic; struct Object { size_t x = 0; @@ -269,34 +270,40 @@ TEST(WaitableAtomic, Smoke) { WaitableAtomic top_level_lock; // The `++x` thread uses mutable accessors. - std::thread([&top_level_lock, &object](IntrusiveClient top_level_client) { - // Should be able to register another client for `top_level_lock`. - ASSERT_TRUE(bool(top_level_lock.RegisterScopedClient())); - while (top_level_client) { - // This loop will be terminated as `top_level_lock` will be leaving the scope. - ++object.MutableScopedAccessor()->x; - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - // Should no longer be able to register another client for `top_level_lock`. - ASSERT_FALSE(bool(top_level_lock.RegisterScopedClient())); - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - object.MutableScopedAccessor()->x_done = true; - }, top_level_lock.RegisterScopedClient()).detach(); + std::thread( + [&top_level_lock, &object](IntrusiveClient top_level_client) { + // Should be able to register another client for `top_level_lock`. + ASSERT_TRUE(bool(top_level_lock.RegisterScopedClient())); + while (top_level_client) { + // This loop will be terminated as `top_level_lock` will be leaving the scope. + ++object.MutableScopedAccessor()->x; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + // Should no longer be able to register another client for `top_level_lock`. + ASSERT_FALSE(bool(top_level_lock.RegisterScopedClient())); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + object.MutableScopedAccessor()->x_done = true; + }, + top_level_lock.RegisterScopedClient()) + .detach(); // The `++y` thread uses the functional style. - std::thread([&top_level_lock, &object](IntrusiveClient top_level_client) { - // Should be able to register another client for `top_level_lock`. - ASSERT_TRUE(bool(top_level_lock.RegisterScopedClient())); - while (top_level_client) { - // This loop will be terminated as `top_level_lock` will be leaving the scope. - object.MutableUse([](Object& object) { ++object.y; }); - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - // Should no longer be able to register another client for `top_level_lock`. - ASSERT_FALSE(bool(top_level_lock.RegisterScopedClient())); - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - object.MutableUse([](Object& object) { object.y_done = true; }); - }, top_level_lock.RegisterScopedClient()).detach(); + std::thread( + [&top_level_lock, &object](IntrusiveClient top_level_client) { + // Should be able to register another client for `top_level_lock`. + ASSERT_TRUE(bool(top_level_lock.RegisterScopedClient())); + while (top_level_client) { + // This loop will be terminated as `top_level_lock` will be leaving the scope. + object.MutableUse([](Object& object) { ++object.y; }); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + // Should no longer be able to register another client for `top_level_lock`. + ASSERT_FALSE(bool(top_level_lock.RegisterScopedClient())); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + object.MutableUse([](Object& object) { object.y_done = true; }); + }, + top_level_lock.RegisterScopedClient()) + .detach(); // Let `++x` and `++y` threads run 25ms. std::this_thread::sleep_for(std::chrono::milliseconds(25)); @@ -348,8 +355,8 @@ TEST(WaitableAtomic, ProxyConstructor) { } TEST(WaitableAtomic, IntrusiveClientsCanBeTransferred) { - using current::WaitableAtomic; using current::IntrusiveClient; + using current::WaitableAtomic; WaitableAtomic object; auto f = [](IntrusiveClient& c) { static_cast(c); }; diff --git a/bricks/sync/waitable_atomic.h b/bricks/sync/waitable_atomic.h index dbe65110e..02bf49bc0 100644 --- a/bricks/sync/waitable_atomic.h +++ b/bricks/sync/waitable_atomic.h @@ -116,8 +116,7 @@ class WaitableAtomicImpl { enum { IS_INTRUSIVE = false }; template - BasicImpl(ARGS&&... args) - : data_(std::forward(args)...) {} + BasicImpl(ARGS&&... args) : data_(std::forward(args)...) {} BasicImpl(const DATA& data) : data_(data) {} @@ -143,9 +142,8 @@ class WaitableAtomicImpl { bool mark_as_unmodified_; }; - using impl_t = std::conditional_t::value, - ImmutableAccessorDoesNotNotify, - MutableAccessorDoesNotify>; + using impl_t = + std::conditional_t::value, ImmutableAccessorDoesNotNotify, MutableAccessorDoesNotify>; }; // A generic implementation for both mutable and immutable scoped accessors. @@ -154,9 +152,8 @@ class WaitableAtomicImpl { public: using parent_t = PARENT; using optional_notifier_t = typename NotifyIfMutable::impl_t; - using data_t = std::conditional_t::value, - const typename parent_t::data_t, - typename parent_t::data_t>; + using data_t = std:: + conditional_t::value, const typename parent_t::data_t, typename parent_t::data_t>; explicit ScopedAccessorImpl(parent_t* parent) : ScopedUniqueLock(parent->data_mutex_), optional_notifier_t(parent), pdata_(&parent->data_) {} diff --git a/bricks/system/current.inl.h b/bricks/system/current.inl.h index 21e4aea2f..261103c88 100644 --- a/bricks/system/current.inl.h +++ b/bricks/system/current.inl.h @@ -14,7 +14,7 @@ namespace inl { static const std::string bricks_system_current_inl = current::Base64Decode("Ly8gV2hlbiBgSklUQ29tcGlsZWRDUFBgIGlzIHByb3ZpZGVkIHRoZSBzZWNvbmQgcGFyYW1ldGVyLCB0aGUgcGF0aCB0byBgY3VycmVudGAsIHRoZQovLyBzeW1ib2xpYyBsaW5rIGNhbGxlZCBgY3VycmVudGAgaXMgY3JlYXRlZCBpbiB0aGUgZGlyZWN0b3J5IGluIHdoaWNoIHRoZSB1c2VyIGNvZGUgaXMgY29tcGlsZWQuCi8vCi8vIFRoaXMgaW1tZWRpYXRlbHkgYWxsb3dzIHRoZSB1c2VyIGNvZGUgdG8gYWNjZXNzIEN1cnJlbnQgaGVhZGVycyBieSBtZWFucyBvZiBgI2luY2x1ZGUgImN1cnJlbnQvLi4uImAuCi8vCi8vIE11Y2ggbGlrZSB3aXRob3V0IHRoZSBzZWNvbmQgcGFyYW1ldGVyIHByb3ZpZGVkIHRvIGBKSVRDb21waWxlZENQUGAsIHRoZSB1c2VyIGNvZGUKLy8gaXMgY29tcGlsZWQgZnJvbSB3aXRoaW4gYSBkaXJlY3Rvcnkgd2hlcmUgdGhlIGBjdXJyZW50LmhgIGhlYWRlciBmaWxlIGlzIHBsYWNlZC4KLy8KLy8gSW4gdGhlIGFic2VuY2Ugb2YgQ3VycmVudCBzeW1saW5rZWQgaW4gdGhhdCBkaXJlY3RvcnksIHRoZSBkdW1teSwgZW1wdHksIGBjdXJyZW50LmhgIGhlYWRlciBjcmVhdGVkIHRoZXJlCi8vIHNlcnZlcyB0aGUgcHVycG9zZSBvZiBhbGxvd2luZyB0aGUgdXNlciB0byBoYXZlIHRoZWlyIG93biwgZGlmZmVyZW50IGBjdXJyZW50LmhgIGZpbGUgaW4gdGhlIGRpcmVjb3J5Ci8vIGZyb20gd2hpY2ggdGhleSB3b3VsZCBiZSAiY3VybCBQT1NUIi1pbmcgdGhpcyBmaWxlIHRvIHRoZSBzZXJ2ZXIsIHRvIGRlZmluZSB0aGUgc3ltYm9scyB0aGUgInNlcnZlci1zaWRlIiBkbG9wZW4oKQovLyB3b3VsZCBjb250YWluIGluIHRoZSBib2xpZXJwbGF0ZSwgdGh1cyBtYWtpbmcgc3VyZSB0aGUgdXNlciBjb2RlIGlzIHNlbGYtc3VmZmljaWVudCBmcm9tIHRoZSBJREUgcHVycG9zZXMsCi8vIHN1Y2ggdGhhdCBmZWF0dXJlcyBzdWNoIGFzIGNvbXBsZXRpb24gYW5kIGVycm9ycyBoaWdobGlnaHRpbmcgd291bGQgd29yayBqdXN0IGZpbmUuCi8vCi8vIEluIHRoZSBwcmVzZW5jZSBvZiBDdXJyZW50LCB0aGUgYGN1cnJlbnQuaGAgaGVhZGVyIGlzIG5vIGxvbmdlciBkdW1teSwgYnV0IHNlcnZlcyBhcyBhIGJvaWxlcnBsYXRlIHRvIGluY2x1ZGUKLy8gdmFyaW91cyBDdXJyZW50LXNwZWNpZmljIHdyYXBwZXJzIHNvIHRoYXQgdGhlIHVzZXIgY29kZSBoYXMgaW1tZWRpYXRlIGFjY2VzcyB0byB0aGVtLgovLwovLyBUaGlzIGNvbnRlbnRzIG9mIHRoaXMgaGVhZGVyIGZpbGUgYXJlIHRoZW4gInR1bmVkIiB0byBkZW1vbnN0cmF0ZSB0aGUgcG93ZXIgb2YgQysrIHdpdGggQ3VycmVudCwKLy8gd2l0aG91dCBzbG93aW5nIHRoZSBjb21waWxhdGlvbiBtdWNoLgoKI2luY2x1ZGUgImN1cnJlbnQvYnJpY2tzL3N0cmluZ3MvcHJpbnRmLmgiCiNpbmNsdWRlICJjdXJyZW50L2JyaWNrcy9zdHJpbmdzL3V0aWwuaCIKI2luY2x1ZGUgImN1cnJlbnQvYnJpY2tzL3N0cmluZ3Mvc3BsaXQuaCIKI2luY2x1ZGUgImN1cnJlbnQvYnJpY2tzL3N0cmluZ3Mvam9pbi5oIgojaW5jbHVkZSAiY3VycmVudC9icmlja3Mvc3RyaW5ncy9jaHVuay5oIgoKdXNpbmcgY3VycmVudDo6c3RyaW5nczo6UHJpbnRmOwp1c2luZyBjdXJyZW50OjpzdHJpbmdzOjpGcm9tU3RyaW5nOwp1c2luZyBjdXJyZW50OjpzdHJpbmdzOjpUb1N0cmluZzsKdXNpbmcgY3VycmVudDo6c3RyaW5nczo6VG9Mb3dlcjsKdXNpbmcgY3VycmVudDo6c3RyaW5nczo6VG9VcHBlcjsKdXNpbmcgY3VycmVudDo6c3RyaW5nczo6VHJpbTsKdXNpbmcgY3VycmVudDo6c3RyaW5nczo6U3BsaXQ7CnVzaW5nIGN1cnJlbnQ6OnN0cmluZ3M6OkpvaW47CnVzaW5nIGN1cnJlbnQ6OnN0cmluZ3M6OkNodW5rOwoKI2luY2x1ZGUgImN1cnJlbnQvYnJpY2tzL3V0aWwvc2luZ2xldG9uLmgiCgp1c2luZyBjdXJyZW50OjpTaW5nbGV0b247CgojaW5jbHVkZSAiY3VycmVudC9icmlja3MvdXRpbC9yYW5kb20uaCIKdXNpbmcgbmFtZXNwYWNlIGN1cnJlbnQ6OnJhbmRvbTsKCi8vICNpbmNsdWRlICJjdXJyZW50L3R5cGVzeXN0ZW0vc2VyaWFsaXphdGlvbi9qc29uLmgiIC0tIEEgYml0IHRvbyBzbG93LCBidXQgcGVyaGFwcyBhZGQgYSBzeW1saW5rIHRvIGBqc29uLmhgIGFzIHdlbGwuCg=="); // clang-format on -} // namespace current::inl +} // namespace inl } // namespace current #endif // BRICKS_SYSTEM_CURRENT_INL_H diff --git a/bricks/system/syscalls.h b/bricks/system/syscalls.h index 7ab9a6fa3..0a24e0a1a 100644 --- a/bricks/system/syscalls.h +++ b/bricks/system/syscalls.h @@ -240,8 +240,8 @@ class JITCompiledCPP final { }; #endif // CURRENT_WINDOWS -} // namespace current::bricks::system -} // namespace current::bricks +} // namespace system +} // namespace bricks } // namespace current #endif // BRICKS_SYSTEM_SYSCALLS_H diff --git a/bricks/template/combine.h b/bricks/template/combine.h index c47fbf8e5..6ef492b9a 100644 --- a/bricks/template/combine.h +++ b/bricks/template/combine.h @@ -49,8 +49,7 @@ struct dispatch { T instance; template - dispatch(const ARGS&... args) - : instance(args...) {} + dispatch(const ARGS&... args) : instance(args...) {} template std::enable_if_t::implemented, weed::call_with_type> operator()(XS&&... params) { @@ -58,8 +57,8 @@ struct dispatch { } template - std::enable_if_t::implemented, weed::call_with_type> - operator()(XS&&... params) const { + std::enable_if_t::implemented, weed::call_with_type> operator()( + XS&&... params) const { return instance(std::forward(params)...); } @@ -83,8 +82,7 @@ struct inherit_from_both : T1, T2 { using T2::operator(); template - inherit_from_both(const ARGS&... args) - : T1(args...), T2(args...) {} + inherit_from_both(const ARGS&... args) : T1(args...), T2(args...) {} // `DispatchToAll(...)` will reach both `T1` and `T2`. template diff --git a/bricks/template/test.cc b/bricks/template/test.cc index 109797d35..dc8ff7f3f 100644 --- a/bricks/template/test.cc +++ b/bricks/template/test.cc @@ -137,8 +137,8 @@ TEST(TemplateMetaprogrammingInternalTest, Combine) { } TEST(TemplateMetaprogrammingInternalTest, VariadicIndexes) { - using current::variadic_indexes::indexes; using current::variadic_indexes::generate_indexes; + using current::variadic_indexes::indexes; static_assert(std::is_same_v, generate_indexes<0>>, ""); static_assert(std::is_same_v, generate_indexes<1>>, ""); @@ -316,8 +316,7 @@ static_assert(is_same_v>, ""); // `current::decay_t` + `std::tuple`. static_assert(is_same_v, decay_t>>, ""); -static_assert(is_same_v, decay_t>>, - ""); +static_assert(is_same_v, decay_t>>, ""); static_assert(is_same_v, decay_t>>, ""); static_assert(is_same_v, decay_t>>, ""); @@ -332,17 +331,13 @@ static_assert(is_same_v, decay_t, decay_t&>>, ""); static_assert(is_same_v, decay_t&&>>, ""); -static_assert(is_same_v>, decay_t>>>, - ""); +static_assert(is_same_v>, decay_t>>>, ""); static_assert(is_same_v>, decay_t>>>, ""); -static_assert(is_same_v>, decay_t>>>, - ""); +static_assert(is_same_v>, decay_t>>>, ""); static_assert(is_same_v>, decay_t>>>, ""); static_assert(is_same_v>, decay_t>>>, ""); -static_assert(is_same_v>, decay_t>&>>, - ""); -static_assert(is_same_v>, decay_t&>&>>, - ""); +static_assert(is_same_v>, decay_t>&>>, ""); +static_assert(is_same_v>, decay_t&>&>>, ""); static_assert(is_same_v>, decay_t&>&>>, ""); static_assert(is_same_v>, decay_t&>&>>, diff --git a/bricks/template/typelist.h b/bricks/template/typelist.h index 6eec593e8..732f8098f 100644 --- a/bricks/template/typelist.h +++ b/bricks/template/typelist.h @@ -58,7 +58,7 @@ template #ifndef CURRENT_FOR_CPP14 inline #endif // CURRENT_FOR_CPP14 -constexpr size_t TypeListSize = TypeListSizeExtractor::value; + constexpr size_t TypeListSize = TypeListSizeExtractor::value; static_assert(TypeListSize> == 0, ""); static_assert(TypeListSize> == 1, ""); @@ -138,11 +138,9 @@ static_assert(std::is_same_v, TypeListCat, TypeLis static_assert(std::is_same_v, TypeListCat, TypeListImpl<>>>, ""); static_assert(std::is_same_v, TypeListCat, TypeListImpl>>, ""); static_assert( - std::is_same_v, TypeListCat, TypeListImpl>>, - ""); + std::is_same_v, TypeListCat, TypeListImpl>>, ""); static_assert( - std::is_same_v, TypeListCat, TypeListImpl>>, - ""); + std::is_same_v, TypeListCat, TypeListImpl>>, ""); static_assert(std::is_same_v, TypeListCat<>>, ""); static_assert(std::is_same_v, TypeListCat>>, ""); static_assert(std::is_same_v, @@ -259,13 +257,13 @@ static_assert(std::is_same_v, TypeListUnion, TypeL static_assert(std::is_same_v, TypeListUnion, TypeListImpl<>>>, ""); static_assert(std::is_same_v, TypeListUnion, TypeListImpl>>, ""); static_assert(std::is_same_v, TypeListUnion, TypeListImpl>>, ""); -static_assert(std::is_same_v, - TypeListUnion, TypeListImpl>>, - ""); +static_assert( + std::is_same_v, TypeListUnion, TypeListImpl>>, + ""); static_assert(std::is_same_v, TypeListUnion<>>, ""); static_assert(std::is_same_v, TypeListUnion>>, ""); -static_assert( - std::is_same_v, TypeListUnion, TypeListImpl, TypeListImpl>>, ""); +static_assert(std::is_same_v, TypeListUnion, TypeListImpl, TypeListImpl>>, + ""); static_assert( std::is_same_v, TypeListUnion, TypeListImpl, TypeListImpl, TypeListImpl>>, @@ -312,8 +310,8 @@ static_assert(std::is_same_v, Flatten, Flatten>>>>, ""); static_assert(std::is_same_v, Flatten>>, ""); static_assert(std::is_same_v, Flatten, double>>>, ""); -static_assert( - std::is_same_v, Flatten>, double>>>, ""); +static_assert(std::is_same_v, Flatten>, double>>>, + ""); // Performance alert, @dkorolev @mzhurovich 12/5/2015. Revisited and kept the semantics same. -- D.K. 10/15/2015. // The implementation of `TypeList` deduplication+flattening is very inefficient as of now. @@ -335,8 +333,8 @@ static_assert(std::is_same_v, SlowTypeList, SlowTypeList>, ""); static_assert(std::is_same_v, SlowTypeList>>, ""); static_assert(std::is_same_v, SlowTypeList>>>, ""); -static_assert( - std::is_same_v, SlowTypeList, double>>>, ""); +static_assert(std::is_same_v, SlowTypeList, double>>>, + ""); static_assert(std::is_same_v, SlowTypeList>, ""); static_assert(std::is_same_v, SlowTypeList>, ""); static_assert(std::is_same_v, SlowTypeList>, ""); @@ -428,7 +426,7 @@ struct Q { using type = typename type_wrapper::type; }; -} // namespace crnt::tle +} // namespace tle } // namespace crnt namespace current { @@ -446,12 +444,12 @@ static_assert(std::is_same_v>> } // namespace current // Export some symbols into global scope. -using current::metaprogramming::TypeList; +using current::metaprogramming::IsTypeList; using current::metaprogramming::SlowTypeList; +using current::metaprogramming::TypeList; using current::metaprogramming::TypeListContains; -using current::metaprogramming::IsTypeList; -using current::metaprogramming::TypeListSize; using current::metaprogramming::TypeListElement; +using current::metaprogramming::TypeListSize; // Note: For equality and lack of discrimination reasons, the user may still use raw `TypeListImpl`, // if she prefers to not have flattening and deduplication take place. diff --git a/bricks/template/weed.h b/bricks/template/weed.h index bed6ba92a..5503d6878 100644 --- a/bricks/template/weed.h +++ b/bricks/template/weed.h @@ -52,7 +52,7 @@ struct call_with_impl { } }; -} // namespace current::weed::impl +} // namespace impl template struct call_with { @@ -83,7 +83,7 @@ static_assert(!call_with::implemented, ""); } // namespace smoke_test -} // namespace current::weed +} // namespace weed } // namespace current #endif // BRICKS_TEMPLATE_WEED_H diff --git a/bricks/time/chrono.h b/bricks/time/chrono.h index 031d5ec6e..0a06775c7 100644 --- a/bricks/time/chrono.h +++ b/bricks/time/chrono.h @@ -133,7 +133,7 @@ inline void SleepUntil(T moment) { #endif // CURRENT_MOCK_TIME -} // namespace current::time +} // namespace time namespace strings { @@ -153,7 +153,7 @@ struct FixedSizeSerializer { } }; -} // namespace current::strings +} // namespace strings namespace time { @@ -218,7 +218,7 @@ inline std::tm FillStructTM(std::chrono::microseconds t) { return FillStructTM(t, tm); } -} // namespace current::time +} // namespace time template inline std::string FormatDateTime(std::chrono::microseconds t, const char* format_string = "%Y/%m/%d %H:%M:%S") { @@ -257,8 +257,9 @@ inline std::chrono::microseconds DateTimeStringToTimestamp( tm.tm_isdst = 0; tt = ::timegm(&tm); } - const auto result = std::chrono::time_point_cast( - std::chrono::system_clock::from_time_t(tt)).time_since_epoch(); + const auto result = + std::chrono::time_point_cast(std::chrono::system_clock::from_time_t(tt)) + .time_since_epoch(); if (padding == time::SecondsToMicrosecondsPadding::Lower) { return result; } else { @@ -274,7 +275,8 @@ std::chrono::microseconds UTCDateTimeStringToTimestamp( STRING&& datetime, const char* format_string, time::SecondsToMicrosecondsPadding padding = time::SecondsToMicrosecondsPadding::Lower) { - return DateTimeStringToTimestamp(std::forward(datetime), format_string, padding); + return DateTimeStringToTimestamp( + std::forward(datetime), format_string, padding); } template @@ -282,21 +284,22 @@ std::chrono::microseconds LocalDateTimeStringToTimestamp( STRING&& datetime, const char* format_string, time::SecondsToMicrosecondsPadding padding = time::SecondsToMicrosecondsPadding::Lower) { - return DateTimeStringToTimestamp(std::forward(datetime), format_string, padding); + return DateTimeStringToTimestamp( + std::forward(datetime), format_string, padding); } template std::chrono::microseconds IMFFixDateTimeStringToTimestamp( - STRING&& datetime, - time::SecondsToMicrosecondsPadding padding = time::SecondsToMicrosecondsPadding::Lower) { - return DateTimeStringToTimestamp(std::forward(datetime), time::DateTimeFmts::IMFFix, padding); + STRING&& datetime, time::SecondsToMicrosecondsPadding padding = time::SecondsToMicrosecondsPadding::Lower) { + return DateTimeStringToTimestamp( + std::forward(datetime), time::DateTimeFmts::IMFFix, padding); } template std::chrono::microseconds RFC850DateTimeStringToTimestamp( - STRING&& datetime, - time::SecondsToMicrosecondsPadding padding = time::SecondsToMicrosecondsPadding::Lower) { - return DateTimeStringToTimestamp(std::forward(datetime), time::DateTimeFmts::RFC850, padding); + STRING&& datetime, time::SecondsToMicrosecondsPadding padding = time::SecondsToMicrosecondsPadding::Lower) { + return DateTimeStringToTimestamp( + std::forward(datetime), time::DateTimeFmts::RFC850, padding); } } // namespace current diff --git a/bricks/time/test.cc b/bricks/time/test.cc index 90490dcd3..1f5c03dd4 100644 --- a/bricks/time/test.cc +++ b/bricks/time/test.cc @@ -95,14 +95,17 @@ TEST(Time, DateTimeFormatFunctions) { EXPECT_EQ(1461461461000000, current::IMFFixDateTimeStringToTimestamp("Sun, 24 Apr 2016 01:31:01 GMT").count()); EXPECT_EQ(1461461461999999, current::IMFFixDateTimeStringToTimestamp("Sun, 24 Apr 2016 01:31:01 GMT", - current::time::SecondsToMicrosecondsPadding::Upper).count()); + current::time::SecondsToMicrosecondsPadding::Upper) + .count()); EXPECT_EQ(0, current::IMFFixDateTimeStringToTimestamp("Not valid string,").count()); - EXPECT_EQ(0, - current::IMFFixDateTimeStringToTimestamp("Not valid string,", - current::time::SecondsToMicrosecondsPadding::Upper).count()); + EXPECT_EQ( + 0, + current::IMFFixDateTimeStringToTimestamp("Not valid string,", current::time::SecondsToMicrosecondsPadding::Upper) + .count()); EXPECT_EQ(1461461461000000, current::RFC850DateTimeStringToTimestamp("Sunday, 24-Apr-16 01:31:01 GMT").count()); EXPECT_EQ(1461461461999999, current::RFC850DateTimeStringToTimestamp("Sunday, 24-Apr-16 01:31:01 GMT", - current::time::SecondsToMicrosecondsPadding::Upper).count()); + current::time::SecondsToMicrosecondsPadding::Upper) + .count()); EXPECT_EQ(0, current::RFC850DateTimeStringToTimestamp("Not valid string,").count()); } diff --git a/bricks/util/accumulative_scoped_deleter.h b/bricks/util/accumulative_scoped_deleter.h index aab9c5505..583363cc2 100644 --- a/bricks/util/accumulative_scoped_deleter.h +++ b/bricks/util/accumulative_scoped_deleter.h @@ -45,8 +45,7 @@ class AccumulativeScopedDeleter { AccumulativeScopedDeleter(std::function f) : captured_{f} {} template - AccumulativeScopedDeleter(AccumulativeScopedDeleter&& rhs) - : captured_(std::move(rhs.captured_)) { + AccumulativeScopedDeleter(AccumulativeScopedDeleter&& rhs) : captured_(std::move(rhs.captured_)) { rhs.captured_.clear(); } template diff --git a/bricks/util/base64.h b/bricks/util/base64.h index dd4cf38cc..a92b4e52e 100644 --- a/bricks/util/base64.h +++ b/bricks/util/base64.h @@ -152,9 +152,8 @@ inline std::string Base64Encode(const std::string& input) { } inline strings::Chunk Base64EncodeInto(strings::Chunk input, std::string& placeholder) { - base64::Impl::EncodeInto(reinterpret_cast(input.c_str()), - input.length(), - placeholder); + base64::Impl::EncodeInto( + reinterpret_cast(input.c_str()), input.length(), placeholder); return placeholder; } diff --git a/bricks/util/comparators.h b/bricks/util/comparators.h index 4b0cabeee..af7f66bc4 100644 --- a/bricks/util/comparators.h +++ b/bricks/util/comparators.h @@ -59,8 +59,7 @@ constexpr auto HasHashMethod(int) -> decltype(std::declval().Hash(), bo template struct GenericHashFunctionSelector { - typedef custom_comparator_and_hash_function::GenericHashFunctionImpl(0), std::is_enum_v> - type; + typedef custom_comparator_and_hash_function::GenericHashFunctionImpl(0), std::is_enum_v> type; }; } // namespace custom_comparator_and_hash_function diff --git a/bricks/util/iterator.h b/bricks/util/iterator.h index d8d2f9acd..817d7f7a8 100644 --- a/bricks/util/iterator.h +++ b/bricks/util/iterator.h @@ -140,7 +140,7 @@ struct is_unordered_map { constexpr static bool value = Check(0); }; -} // namespace current::stl_wrappers::sfinae +} // namespace sfinae template struct GenericMapAccessor final { @@ -178,10 +178,10 @@ struct GenericMapAccessor final { int64_t TotalElementsForHypermediaCollectionView() const { return static_cast(Size()); } }; -} // namespace current::stl_wrappers +} // namespace stl_wrappers -using stl_wrappers::GenericMapIterator; using stl_wrappers::GenericMapAccessor; +using stl_wrappers::GenericMapIterator; } // namespace current diff --git a/bricks/util/object_interface.h b/bricks/util/object_interface.h index 242203fcf..7c6f662cd 100644 --- a/bricks/util/object_interface.h +++ b/bricks/util/object_interface.h @@ -41,10 +41,10 @@ SOFTWARE. template <> \ struct CURRENT_OBJECT_INTERFACE_METHODS_WRAPPER : CURRENT_OBJECT_INTERFACE_IMPL_POINTER_CONTAINER -#define CURRENT_FORWARD_METHOD(method) \ - template \ - auto method(ARGS&&... args) { \ - return this->CURRENT_IMPLEMENTATION_POINTER->method(std::forward(args)...); \ +#define CURRENT_FORWARD_METHOD(method) \ + template \ + auto method(ARGS&&... args) { \ + return this->CURRENT_IMPLEMENTATION_POINTER->method(std::forward(args)...); \ } #endif // BRICKS_UTIL_OBJECT_INTERFACE_H diff --git a/bricks/util/random.h b/bricks/util/random.h index 0acba168d..f9d5c1001 100644 --- a/bricks/util/random.h +++ b/bricks/util/random.h @@ -135,13 +135,13 @@ inline double CSRandomDouble(const double a, const double b) { return RandomReal } // namespace random } // namespace current +using current::random::RandomDouble; +using current::random::RandomFloat; using current::random::RandomInt; -using current::random::RandomLong; -using current::random::RandomULong; using current::random::RandomInt64; +using current::random::RandomLong; using current::random::RandomUInt64; -using current::random::RandomFloat; -using current::random::RandomDouble; +using current::random::RandomULong; using current::random::SetRandomSeed; diff --git a/bricks/util/singleton.h b/bricks/util/singleton.h index 74b50a86e..170d6bd28 100644 --- a/bricks/util/singleton.h +++ b/bricks/util/singleton.h @@ -105,13 +105,13 @@ struct ThreadLocalSingletonContainer : ThreadLocalSingletonContainerBase { }; struct ThreadLocalSingletonsFactory { - std::unordered_map> instances; + std::unordered_map > instances; template T& DoGetInstance() { auto& placeholder = instances[std::type_index(typeid(T))]; if (!placeholder) { - placeholder = std::make_unique>(); + placeholder = std::make_unique >(); } return dynamic_cast&>(*placeholder).instance; } diff --git a/bricks/util/test.cc b/bricks/util/test.cc index 42f65ea14..3559b7916 100644 --- a/bricks/util/test.cc +++ b/bricks/util/test.cc @@ -196,11 +196,10 @@ TEST(Util, MakePointerScopeGuard) { EXPECT_EQ("custom_guarded_pointer\n", story); { Instance* pointer = new Instance(story); - const auto guard = current::MakePointerScopeGuard(pointer, - [&story](Instance* p) { - story += "guarded_delete\n"; - delete p; - }); + const auto guard = current::MakePointerScopeGuard(pointer, [&story](Instance* p) { + story += "guarded_delete\n"; + delete p; + }); EXPECT_EQ("custom_guarded_pointer\nconstructed\n", story); } EXPECT_EQ("custom_guarded_pointer\nconstructed\nguarded_delete\ndestructed\n", story); @@ -242,10 +241,10 @@ TEST(Util, ThreadLocalSingleton) { } TEST(Util, Base64) { - using current::Base64Encode; - using current::Base64URLEncode; using current::Base64Decode; + using current::Base64Encode; using current::Base64URLDecode; + using current::Base64URLEncode; EXPECT_EQ("", Base64Encode("")); EXPECT_EQ("Zg==", Base64Encode("f")); @@ -371,10 +370,9 @@ TEST(Util, WaitableTerminateSignalGotExternalTerminateSignal) { bool result; std::thread thread([&signal, &counter, &mutex, &result, &result_set]() { std::unique_lock lock(mutex); - result = signal.WaitUntil(lock, - [&counter]() { - return counter > 1000u; // Not going to happen in this test. - }); + result = signal.WaitUntil(lock, [&counter]() { + return counter > 1000u; // Not going to happen in this test. + }); result_set = true; }); @@ -445,11 +443,11 @@ TEST(Util, WaitableTerminateSignalScopedRegisterer) { } TEST(Util, LazyInstantiation) { - using current::LazilyInstantiated; using current::DelayedInstantiate; using current::DelayedInstantiateFromTuple; using current::DelayedInstantiateWithExtraParameter; using current::DelayedInstantiateWithExtraParameterFromTuple; + using current::LazilyInstantiated; struct Foo { int foo; @@ -785,8 +783,7 @@ template struct ObjectContainer { T object; template - ObjectContainer(ARGS&&... args) - : object(std::forward(args)...) {} + ObjectContainer(ARGS&&... args) : object(std::forward(args)...) {} }; template @@ -795,8 +792,7 @@ struct ExampleObjectInterface : private ObjectContainer, public CURRENT_OBJEC using methods_wrapper_t = CURRENT_OBJECT_INTERFACE_METHODS_WRAPPER; template - ExampleObjectInterface(ARGS&&... args) - : object_container_t(std::forward(args)...) { + ExampleObjectInterface(ARGS&&... args) : object_container_t(std::forward(args)...) { methods_wrapper_t::CURRENT_IMPLEMENTATION_POINTER = &(object_container_t::object); } }; @@ -818,8 +814,7 @@ template struct NamespacedObjectContainer { T object; template - NamespacedObjectContainer(ARGS&&... args) - : object(std::forward(args)...) {} + NamespacedObjectContainer(ARGS&&... args) : object(std::forward(args)...) {} }; template @@ -829,8 +824,7 @@ struct NamespacedExampleObjectInterface : private NamespacedObjectContainer, using methods_wrapper_t = CURRENT_OBJECT_INTERFACE_METHODS_WRAPPER; template - NamespacedExampleObjectInterface(ARGS&&... args) - : object_container_t(std::forward(args)...) { + NamespacedExampleObjectInterface(ARGS&&... args) : object_container_t(std::forward(args)...) { methods_wrapper_t::CURRENT_IMPLEMENTATION_POINTER = &(object_container_t::object); } }; @@ -861,7 +855,8 @@ TEST(ObjectInterface, Smoke) { } { object_with_interface_test_namespace::NamespacedExampleObjectInterface< - object_with_interface_test_namespace::NamespacedObjectWithInterface> o; + object_with_interface_test_namespace::NamespacedObjectWithInterface> + o; EXPECT_EQ(1, o.total_calls()); EXPECT_EQ(2, o.total_calls()); EXPECT_EQ(3, o.total_calls()); diff --git a/compact_tsv/gen.cc b/compact_tsv/gen.cc index 23c4e78fb..85157637f 100644 --- a/compact_tsv/gen.cc +++ b/compact_tsv/gen.cc @@ -40,20 +40,25 @@ DEFINE_size_t(random_seed, 42, "Random seed."); int main(int argc, char** argv) { ParseDFlags(&argc, &argv); std::unordered_map strings; - CreateTSV([&strings](const std::vector& row) { - for (size_t i = 0; i < row.size(); ++i) { - std::string& s = strings[row[i]]; - if (s.empty()) { - do { - s += 'a' + rand() % 26; - if (FLAGS_nulls) { + CreateTSV( + [&strings](const std::vector& row) { + for (size_t i = 0; i < row.size(); ++i) { + std::string& s = strings[row[i]]; + if (s.empty()) { do { - s += '\0'; - } while ((rand() & 31) == 31); + s += 'a' + rand() % 26; + if (FLAGS_nulls) { + do { + s += '\0'; + } while ((rand() & 31) == 31); + } + } while (rand() & 7); } - } while (rand() & 7); - } - std::cout << s << ((i + 1) == row.size() ? '\n' : '\t'); - } - }, FLAGS_rows, FLAGS_cols, FLAGS_scale, FLAGS_random_seed); + std::cout << s << ((i + 1) == row.size() ? '\n' : '\t'); + } + }, + FLAGS_rows, + FLAGS_cols, + FLAGS_scale, + FLAGS_random_seed); } diff --git a/compact_tsv/test.cc b/compact_tsv/test.cc index e628b72a6..6617c0794 100644 --- a/compact_tsv/test.cc +++ b/compact_tsv/test.cc @@ -47,11 +47,16 @@ TEST(CompactTSV, Smoke) { std::ostringstream os; const auto t_a_begin = current::time::Now(); - CreateTSV([&os](const std::vector &row) { - for (size_t i = 0; i < row.size(); ++i) { - os << std::setw(2) << row[i] << ((i + 1) == row.size() ? '\n' : ' '); - } - }, FLAGS_rows, FLAGS_cols, FLAGS_scale, FLAGS_random_seed); + CreateTSV( + [&os](const std::vector &row) { + for (size_t i = 0; i < row.size(); ++i) { + os << std::setw(2) << row[i] << ((i + 1) == row.size() ? '\n' : ' '); + } + }, + FLAGS_rows, + FLAGS_cols, + FLAGS_scale, + FLAGS_random_seed); const auto t_a_end = current::time::Now(); if (run_test) { @@ -74,24 +79,31 @@ TEST(CompactTSV, Smoke) { CompactTSV fast; const auto t_b_begin = current::time::Now(); - CreateTSV([&fast](const std::vector &row) { - std::vector row_of_strings(row.size()); - for (size_t i = 0; i < row.size(); ++i) { - row_of_strings[i] = current::ToString(row[i]); - } - fast(row_of_strings); - }, FLAGS_rows, FLAGS_cols, FLAGS_scale, FLAGS_random_seed); + CreateTSV( + [&fast](const std::vector &row) { + std::vector row_of_strings(row.size()); + for (size_t i = 0; i < row.size(); ++i) { + row_of_strings[i] = current::ToString(row[i]); + } + fast(row_of_strings); + }, + FLAGS_rows, + FLAGS_cols, + FLAGS_scale, + FLAGS_random_seed); const auto t_b_end = current::time::Now(); fast.Finalize(); std::ostringstream os2; const auto t_c_begin = current::time::Now(); EXPECT_EQ(FLAGS_rows, - CompactTSV::Unpack([&os2](const std::vector &row) { - for (size_t i = 0; i < row.size(); ++i) { - os2 << std::setw(2) << row[i] << ((i + 1) == row.size() ? '\n' : ' '); - } - }, fast.GetPackedString())); + CompactTSV::Unpack( + [&os2](const std::vector &row) { + for (size_t i = 0; i < row.size(); ++i) { + os2 << std::setw(2) << row[i] << ((i + 1) == row.size() ? '\n' : ' '); + } + }, + fast.GetPackedString())); EXPECT_EQ(golden, os2.str()); const auto t_c_end = current::time::Now(); @@ -116,12 +128,12 @@ TEST(CompactTSV, Smoke) { std::cerr << "Original TSV size:\t" << golden_size << "b, or\t" << golden_size / (1024u * 1024u) << "MB.\n"; std::cerr << "Packed TSV size:\t" << packed_size << "b, or\t" << packed_size / (1024u * 1024u) << "MB.\n"; const double K = 1e-3; // microseconds -> milliseconds. - std::cerr << "Generate: " << K *(t_a_end - t_a_begin).count() << "ms.\n"; - std::cerr << "Pack: " << K *(t_b_end - t_b_begin).count() << "ms.\n"; - std::cerr << "Unpack into std::ostringstream: " << K *(t_c_end - t_c_begin).count() << "ms.\n"; - std::cerr << "Unpack into std::string-s: " << K *(t_d_end - t_d_begin).count() << "ms.\n"; - std::cerr << "Unpack into std::pair: " << K *(t_e_end - t_e_begin).count() << "ms.\n"; - std::cerr << "Unpack into UniqueChunk-s: " << K *(t_f_end - t_f_begin).count() << "ms.\n"; + std::cerr << "Generate: " << K * (t_a_end - t_a_begin).count() << "ms.\n"; + std::cerr << "Pack: " << K * (t_b_end - t_b_begin).count() << "ms.\n"; + std::cerr << "Unpack into std::ostringstream: " << K * (t_c_end - t_c_begin).count() << "ms.\n"; + std::cerr << "Unpack into std::string-s: " << K * (t_d_end - t_d_begin).count() << "ms.\n"; + std::cerr << "Unpack into std::pair: " << K * (t_e_end - t_e_begin).count() << "ms.\n"; + std::cerr << "Unpack into UniqueChunk-s: " << K * (t_f_end - t_f_begin).count() << "ms.\n"; // LCOV_EXCL_STOP } } diff --git a/compact_tsv/unpack_fast.cc b/compact_tsv/unpack_fast.cc index 52267ffec..a84df6cc9 100644 --- a/compact_tsv/unpack_fast.cc +++ b/compact_tsv/unpack_fast.cc @@ -39,13 +39,15 @@ int main(int argc, char** argv) { CURRENT_ASSERT(!FLAGS_input.empty()); const auto contents = current::FileSystem::ReadFileAsString(FLAGS_input); - CompactTSV::Unpack([](const std::vector>& v) { - for (size_t i = 0; i < v.size(); ++i) { - if (i) { - fputc('\t', stdout); - } - fwrite(v[i].first, 1, v[i].second, stdout); - } - fputc('\n', stdout); - }, contents); + CompactTSV::Unpack( + [](const std::vector>& v) { + for (size_t i = 0; i < v.size(); ++i) { + if (i) { + fputc('\t', stdout); + } + fwrite(v[i].first, 1, v[i].second, stdout); + } + fputc('\n', stdout); + }, + contents); } diff --git a/examples/benchmark/generic/benchmark.h b/examples/benchmark/generic/benchmark.h index 351f8b836..b60c67794 100644 --- a/examples/benchmark/generic/benchmark.h +++ b/examples/benchmark/generic/benchmark.h @@ -55,7 +55,8 @@ struct ScenariosRegisterer { } void Synopsis() const { std::cout << "./.current/run --scenario={scenario} [--threads={threads_to_query_from}] " - "[--secons={seconds_to_run_benchmark_for}." << std::endl; + "[--secons={seconds_to_run_benchmark_for}." + << std::endl; for (const auto& scenario : map) { std::cout << "\t--scenario=" << scenario.first << " : " << scenario.second.first << std::endl; } diff --git a/examples/benchmark/generic/scenario_storage.h b/examples/benchmark/generic/scenario_storage.h index 0bcd2a05f..4722c2d08 100644 --- a/examples/benchmark/generic/scenario_storage.h +++ b/examples/benchmark/generic/scenario_storage.h @@ -54,8 +54,8 @@ CURRENT_STRUCT(UInt32KeyValuePair) { CURRENT_STRUCT(StringKeyValuePair) { CURRENT_FIELD(key, std::string); CURRENT_FIELD(value, uint32_t); - CURRENT_CONSTRUCTOR(StringKeyValuePair)(const std::string key = "", uint32_t value = 0) - : key(std::move(key)), value(value) {} + CURRENT_CONSTRUCTOR(StringKeyValuePair) + (const std::string key = "", uint32_t value = 0) : key(std::move(key)), value(value) {} }; CURRENT_STORAGE_FIELD_ENTRY(UnorderedDictionary, UInt32KeyValuePair, PersistedUInt32KeyValuePair); @@ -91,32 +91,31 @@ SCENARIO(storage, "Storage transactions test.") { {{"size"}, [this]() { db->ReadOnlyTransaction([this](ImmutableFields fields) { - if (fields.hashmap_uint32.Size() != actual_size_uint32 || - fields.hashmap_string.Size() != actual_size_string) { - std::cerr << "Test failed." << std::endl; - std::exit(-1); - } - }).Wait(); + if (fields.hashmap_uint32.Size() != actual_size_uint32 || + fields.hashmap_string.Size() != actual_size_string) { + std::cerr << "Test failed." << std::endl; + std::exit(-1); + } + }).Wait(); }}, {{"get"}, [this, testing_string]() { Value(db->ReadOnlyTransaction([this, testing_string](ImmutableFields fields) { - if (!testing_string) { - return Exists(fields.hashmap_uint32[RandomUInt32()]); - } else { - return Exists(fields.hashmap_string[RandomString()]); - } - }).Go()); + if (!testing_string) { + return Exists(fields.hashmap_uint32[RandomUInt32()]); + } else { + return Exists(fields.hashmap_string[RandomString()]); + } + }).Go()); }}, - {{"put"}, - [this, testing_string]() { + {{"put"}, [this, testing_string]() { db->ReadWriteTransaction([this, testing_string](MutableFields fields) { - if (!testing_string) { - fields.hashmap_uint32.Add(UInt32KeyValuePair(RandomUInt32(), RandomUInt32())); - } else { - fields.hashmap_string.Add(StringKeyValuePair(RandomString(), RandomUInt32())); - } - }).Wait(); + if (!testing_string) { + fields.hashmap_uint32.Add(UInt32KeyValuePair(RandomUInt32(), RandomUInt32())); + } else { + fields.hashmap_string.Add(StringKeyValuePair(RandomString(), RandomUInt32())); + } + }).Wait(); }}}; const auto cit = tests.find(FLAGS_storage_transaction); @@ -132,13 +131,14 @@ SCENARIO(storage, "Storage transactions test.") { CURRENT_ASSERT(false); } - const auto pair = Value(db->ReadWriteTransaction([](MutableFields fields) { - for (uint32_t i = 0; i < FLAGS_storage_initial_size; ++i) { - fields.hashmap_uint32.Add(UInt32KeyValuePair(RandomUInt32(), RandomUInt32())); - fields.hashmap_string.Add(StringKeyValuePair(RandomString(), RandomUInt32())); - } - return NonSerializablePairOfTwoSizeT(fields.hashmap_uint32.Size(), fields.hashmap_string.Size()); - }).Go()); + const auto pair = + Value(db->ReadWriteTransaction([](MutableFields fields) { + for (uint32_t i = 0; i < FLAGS_storage_initial_size; ++i) { + fields.hashmap_uint32.Add(UInt32KeyValuePair(RandomUInt32(), RandomUInt32())); + fields.hashmap_string.Add(StringKeyValuePair(RandomString(), RandomUInt32())); + } + return NonSerializablePairOfTwoSizeT(fields.hashmap_uint32.Size(), fields.hashmap_string.Size()); + }).Go()); actual_size_uint32 = pair.first; actual_size_string = pair.second; diff --git a/examples/benchmark/http/benchmark.cc b/examples/benchmark/http/benchmark.cc index 177ec1f17..bba1f2f07 100644 --- a/examples/benchmark/http/benchmark.cc +++ b/examples/benchmark/http/benchmark.cc @@ -55,8 +55,7 @@ int main(int argc, char** argv) { while (NowInSeconds() < timestamp_end) { const int a = current::random::RandomIntegral(-1000000, +1000000); const int b = current::random::RandomIntegral(-1000000, +1000000); - const auto r = - HTTP(GET(strings::Printf(FLAGS_url.c_str(), port) + strings::Printf("?a=%d&b=%d", a, b))); + const auto r = HTTP(GET(strings::Printf(FLAGS_url.c_str(), port) + strings::Printf("?a=%d&b=%d", a, b))); CURRENT_ASSERT(r.code == HTTPResponseCode.OK); CURRENT_ASSERT(ParseJSON(r.body).sum == a + b); ++queries_; diff --git a/examples/benchmark/http/server.h b/examples/benchmark/http/server.h index 81fae735f..3305669ca 100644 --- a/examples/benchmark/http/server.h +++ b/examples/benchmark/http/server.h @@ -37,12 +37,9 @@ class BenchmarkTestServer { BenchmarkTestServer(current::net::ReservedLocalPort reserved_port, const std::string& route) : port_(reserved_port), http_server_(HTTP(std::move(reserved_port))), - scope_(http_server_.Register(route, - [](Request r) { - r(AddResult(current::FromString(r.url.query["a"]) + - current::FromString(r.url.query["b"]))); - }) + - http_server_.Register("/perftest", [](Request r) { r("perftest ok\n"); })) {} + scope_(http_server_.Register(route, [](Request r) { + r(AddResult(current::FromString(r.url.query["a"]) + current::FromString(r.url.query["b"]))); + }) + http_server_.Register("/perftest", [](Request r) { r("perftest ok\n"); })) {} void Join() { http_server_.Join(); } diff --git a/examples/benchmark/lockfree/benchmark.cc b/examples/benchmark/lockfree/benchmark.cc index 8cd56e20b..dd0a6c82d 100644 --- a/examples/benchmark/lockfree/benchmark.cc +++ b/examples/benchmark/lockfree/benchmark.cc @@ -35,15 +35,16 @@ struct EpochClockGuaranteeingMonotonicity { inline std::chrono::microseconds Now() const { std::lock_guard lock(mutex); - const uint64_t now_us = std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count(); + const uint64_t now_us = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); monotonic_now_us = std::max(monotonic_now_us + 1, now_us); return std::chrono::microseconds(monotonic_now_us); } }; inline std::chrono::microseconds Now() { return current::Singleton().Now(); } -} +} // namespace current_time_with_mutex template std::chrono::microseconds Run() { @@ -64,16 +65,16 @@ std::chrono::microseconds Run() { }; std::vector> threads(FLAGS_threads); - const auto start = - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); + const auto start = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); for (auto& thread : threads) { thread = std::make_unique(FLAGS_iterations); } for (auto& thread : threads) { thread->Join(); } - const auto end = - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); + const auto end = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); return (end - start) / FLAGS_threads; } diff --git a/examples/benchmark/storage/replay.cc b/examples/benchmark/storage/replay.cc index ce32dab84..06c432395 100644 --- a/examples/benchmark/storage/replay.cc +++ b/examples/benchmark/storage/replay.cc @@ -21,10 +21,12 @@ inline void GenerateTestData(const std::string& file, uint32_t size) { current::FileSystem::RmFile(file, current::FileSystem::RmFileParameters::Silent); auto storage = storage_t::CreateMasterStorage(file); for (uint32_t i = 0u; i < size; ++i) { - storage->ReadWriteTransaction([i](MutableFields fields) { - Entry entry(static_cast(i), current::SHA256(current::ToString(i))); - fields.entries.Add(entry); - }).Go(); + storage + ->ReadWriteTransaction([i](MutableFields fields) { + Entry entry(static_cast(i), current::SHA256(current::ToString(i))); + fields.entries.Add(entry); + }) + .Go(); } } @@ -141,8 +143,10 @@ inline void PerformReplayBenchmark(const std::string& file, auto storage = storage_t::CreateFollowingStorageAtopExistingStream(stream); // Spin lock checking the number of imported entries. while (storage_size < stream_size) { - storage->ReadOnlyTransaction( - [&storage_size](ImmutableFields fields) { storage_size = fields.entries.Size(); }).Go(); + storage + ->ReadOnlyTransaction( + [&storage_size](ImmutableFields fields) { storage_size = fields.entries.Size(); }) + .Go(); std::this_thread::sleep_for(spin_lock_sleep); } const auto end = current::time::Now(); @@ -258,42 +262,42 @@ int main(int argc, char** argv) { .ImageSize(1000) .OutputFormat("pngcairo") .Plot(WithMeta([&report](Plotter p) { - for (size_t i = 0; i < report.subs.size(); ++i) { - p(report.subs[i], 1e-3 * report.owning_storage_replay_ms[i]); - } - }) + for (size_t i = 0; i < report.subs.size(); ++i) { + p(report.subs[i], 1e-3 * report.owning_storage_replay_ms[i]); + } + }) .LineWidth(5) .Color("rgb '#B90000'") .Name("Owning storage")) .Plot(WithMeta([&report](Plotter p) { - for (size_t i = 0; i < report.subs.size(); ++i) { - p(report.subs[i], 1e-3 * report.following_storage_replay_ms[i]); - } - }) + for (size_t i = 0; i < report.subs.size(); ++i) { + p(report.subs[i], 1e-3 * report.following_storage_replay_ms[i]); + } + }) .LineWidth(5) .Color("rgb '#0000B9'") .Name("Following storage")) .Plot(WithMeta([&report](Plotter p) { - for (size_t i = 0; i < report.subs.size(); ++i) { - p(report.subs[i], 1e-3 * report.raw_persister_replay_ms[i]); - } - }) + for (size_t i = 0; i < report.subs.size(); ++i) { + p(report.subs[i], 1e-3 * report.raw_persister_replay_ms[i]); + } + }) .LineWidth(5) .Color("rgb '#008080'") .Name("Persister iterators")) .Plot(WithMeta([&report](Plotter p) { - for (size_t i = 0; i < report.subs.size(); ++i) { - p(report.subs[i], 1e-3 * report.raw_file_scan_ms[i]); - } - }) + for (size_t i = 0; i < report.subs.size(); ++i) { + p(report.subs[i], 1e-3 * report.raw_file_scan_ms[i]); + } + }) .LineWidth(5) .Color("rgb '#404040'") .Name("File scan w/o parsing")) .Plot(WithMeta([&report](Plotter p) { - for (size_t i = 0; i < report.subs.size(); ++i) { - p(report.subs[i], 1e-3 * report.parsing_file_scan_ms[i]); - } - }) + for (size_t i = 0; i < report.subs.size(); ++i) { + p(report.subs[i], 1e-3 * report.parsing_file_scan_ms[i]); + } + }) .LineWidth(5) .Color("rgb '#00B900'") .Name("File scan with parsing")); diff --git a/examples/cookies_server/cookies.cc b/examples/cookies_server/cookies.cc index 45b8a5246..eebd1e343 100644 --- a/examples/cookies_server/cookies.cc +++ b/examples/cookies_server/cookies.cc @@ -31,15 +31,13 @@ DEFINE_int32(cookies_demo_port, 3000, "Local port to spawn the server on."); int main(int argc, char** argv) { ParseDFlags(&argc, &argv); - HTTP(FLAGS_cookies_demo_port) - .Register("/", - [](Request r) { - const auto now = current::ToString(current::time::Now().count()); - r(Response(r.headers.CookiesAsString()) - .SetCookie("Now", now) - .SetCookie("SecureNow", now, {{"secure", ""}}) - .SetCookie("LoadedAt" + now, "Yes.")); - }); + HTTP(FLAGS_cookies_demo_port).Register("/", [](Request r) { + const auto now = current::ToString(current::time::Now().count()); + r(Response(r.headers.CookiesAsString()) + .SetCookie("Now", now) + .SetCookie("SecureNow", now, {{"secure", ""}}) + .SetCookie("LoadedAt" + now, "Yes.")); + }); HTTP(FLAGS_cookies_demo_port).Join(); } diff --git a/examples/datafest_talk/tier1_cook_dataset/step2_confirm_timestamps_are_valid.cc b/examples/datafest_talk/tier1_cook_dataset/step2_confirm_timestamps_are_valid.cc index b891a237e..307f590ad 100644 --- a/examples/datafest_talk/tier1_cook_dataset/step2_confirm_timestamps_are_valid.cc +++ b/examples/datafest_talk/tier1_cook_dataset/step2_confirm_timestamps_are_valid.cc @@ -9,12 +9,17 @@ #include "../../../bricks/time/chrono.h" static std::unordered_map dow_map{ - {"Mon", 0}, {"Tue", 1}, {"Wed", 2}, {"Thu", 3}, {"Fri", 4}, {"Sat", 5}, {"Sun", 6}, + {"Mon", 0}, + {"Tue", 1}, + {"Wed", 2}, + {"Thu", 3}, + {"Fri", 4}, + {"Sat", 5}, + {"Sun", 6}, }; static const char* const one_based_month_name[13] = { - "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" -}; + "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; inline void ValidateTimestamp(std::vector const& pieces) { CURRENT_ASSERT(pieces.size() == 9); @@ -43,15 +48,14 @@ inline void ValidateTimestamp(std::vector const& pieces CURRENT_ASSERT(epoch_seconds > 0); - std::string imf_fix_date = - current::strings::Printf("%s, %2d %s %d %02d:%02d:%02d GMT", - dow_as_string.c_str(), - day, - one_based_month_name[month], - year, - hour, - minute, - second); + std::string imf_fix_date = current::strings::Printf("%s, %2d %s %d %02d:%02d:%02d GMT", + dow_as_string.c_str(), + day, + one_based_month_name[month], + year, + hour, + minute, + second); int const imf_fix_timestamp = current::IMFFixDateTimeStringToTimestamp(imf_fix_date).count() / 1000000; diff --git a/examples/datafest_talk/tier2_rides_by_months/step3_rides_by_months_unoptimized.cc b/examples/datafest_talk/tier2_rides_by_months/step3_rides_by_months_unoptimized.cc index 23f41d7a4..bb5991926 100644 --- a/examples/datafest_talk/tier2_rides_by_months/step3_rides_by_months_unoptimized.cc +++ b/examples/datafest_talk/tier2_rides_by_months/step3_rides_by_months_unoptimized.cc @@ -1,5 +1,5 @@ // To run: g++ -std=c++11 -O3 step3_rides_by_months_unoptimized.cc && time ./a.out | tee >(md5sum) -// +// // Count rides by month, print the counters in the lexicographically sorted order of keys. // The "canonical C++" implementation, with extra checks, longer, and slower. diff --git a/examples/datafest_talk/tier2_rides_by_months/step4_rides_by_months_still_unoptimized.cc b/examples/datafest_talk/tier2_rides_by_months/step4_rides_by_months_still_unoptimized.cc index db6d204ec..546d01c0b 100644 --- a/examples/datafest_talk/tier2_rides_by_months/step4_rides_by_months_still_unoptimized.cc +++ b/examples/datafest_talk/tier2_rides_by_months/step4_rides_by_months_still_unoptimized.cc @@ -1,5 +1,5 @@ // To run: g++ -std=c++11 -O3 step4_rides_by_months_still_unoptimized.cc && time ./a.out | tee >(md5sum) -// +// // Count rides by month, print the counters in the lexicographically sorted order of keys. // The "canonical C++" implementation splitting into `Chunk`-s, not `std::string`-s. diff --git a/examples/datafest_talk/tier2_rides_by_months/step6_rides_by_months_readfullfile.cc b/examples/datafest_talk/tier2_rides_by_months/step6_rides_by_months_readfullfile.cc index bad9706de..7e96403c6 100644 --- a/examples/datafest_talk/tier2_rides_by_months/step6_rides_by_months_readfullfile.cc +++ b/examples/datafest_talk/tier2_rides_by_months/step6_rides_by_months_readfullfile.cc @@ -1,5 +1,5 @@ // To run: g++ -std=c++11 -O3 step6_rides_by_months_readfullfile.cc && time ./a.out | tee >(md5sum) -// +// // Count rides by month, print the counters in the lexicographically sorted order of keys. // The "read whole file into memory and analyze it" C implementation, still unsafe in a few ways. @@ -22,7 +22,7 @@ int main(int argc, char** argv) { if (!buffer) { return -1; } - if (::fread(buffer, 1, length, f) != length) { + if (::fread(buffer, 1, length, f) != length) { return -1; } ::fclose(f); diff --git a/examples/datafest_talk/tier3_cook_binary/step1_cook.cc b/examples/datafest_talk/tier3_cook_binary/step1_cook.cc index 856136086..245ee693e 100644 --- a/examples/datafest_talk/tier3_cook_binary/step1_cook.cc +++ b/examples/datafest_talk/tier3_cook_binary/step1_cook.cc @@ -1,5 +1,5 @@ // To run: g++ -std=c++11 -O3 step1_cook.cc && time ./a.out -// +// // Cooks the CSV file into a binary format. #include @@ -10,13 +10,13 @@ #include "../../../bricks/strings/strings.h" std::unordered_map dow_map{ - { "Mon", 0 }, - { "Tue", 1 }, - { "Wed", 2 }, - { "Thu", 3 }, - { "Fri", 4 }, - { "Sat", 5 }, - { "Sun", 6 }, + {"Mon", 0}, + {"Tue", 1}, + {"Wed", 2}, + {"Thu", 3}, + {"Fri", 4}, + {"Sat", 5}, + {"Sun", 6}, }; void PackTimestamp(std::vector const& pieces, Timestamp& timestamp) { diff --git a/examples/datafest_talk/tier4_cook_binary_integers/schema_integers.h b/examples/datafest_talk/tier4_cook_binary_integers/schema_integers.h index c2ad35ce5..4bbbb5624 100644 --- a/examples/datafest_talk/tier4_cook_binary_integers/schema_integers.h +++ b/examples/datafest_talk/tier4_cook_binary_integers/schema_integers.h @@ -41,12 +41,12 @@ struct IntegerRide { int32_t tolls_amount_cents; int32_t improvement_surcharge_cents; int32_t total_amount_cents; - uint8_t vendor_id; // Same 1 or 2. - char store_and_fwd_flag; // Same 'N' or 'Y'. - uint8_t ratecode_id; // Integer, { 1, 2, 3, 4, 5, 6, 99 }. - uint8_t passenger_count; // Integer, { 0 .. 9 }. - uint8_t payment_type; // One of { 1, 2, 3, 4, 5 }. - uint8_t trip_type; // Empty = 0, '1', or '2'. + uint8_t vendor_id; // Same 1 or 2. + char store_and_fwd_flag; // Same 'N' or 'Y'. + uint8_t ratecode_id; // Integer, { 1, 2, 3, 4, 5, 6, 99 }. + uint8_t passenger_count; // Integer, { 0 .. 9 }. + uint8_t payment_type; // One of { 1, 2, 3, 4, 5 }. + uint8_t trip_type; // Empty = 0, '1', or '2'. uint16_t pu_location_id; uint16_t do_location_id; }; diff --git a/examples/datafest_talk/tier4_cook_binary_integers/step1_cook.cc b/examples/datafest_talk/tier4_cook_binary_integers/step1_cook.cc index 69adc2548..6aed9beac 100644 --- a/examples/datafest_talk/tier4_cook_binary_integers/step1_cook.cc +++ b/examples/datafest_talk/tier4_cook_binary_integers/step1_cook.cc @@ -8,13 +8,13 @@ #include "../../../bricks/strings/strings.h" std::unordered_map dow_map{ - { "Mon", 0 }, - { "Tue", 1 }, - { "Wed", 2 }, - { "Thu", 3 }, - { "Fri", 4 }, - { "Sat", 5 }, - { "Sun", 6 }, + {"Mon", 0}, + {"Tue", 1}, + {"Wed", 2}, + {"Thu", 3}, + {"Fri", 4}, + {"Sat", 5}, + {"Sun", 6}, }; void PackTimestamp(std::vector const& pieces, Timestamp& timestamp) { diff --git a/examples/datafest_talk/tier5_online_tool/nyc_taxi_dataset_service.h b/examples/datafest_talk/tier5_online_tool/nyc_taxi_dataset_service.h index 31171135e..421182abd 100644 --- a/examples/datafest_talk/tier5_online_tool/nyc_taxi_dataset_service.h +++ b/examples/datafest_talk/tier5_online_tool/nyc_taxi_dataset_service.h @@ -110,7 +110,9 @@ class NYCTaxiDatasetServiceImpl { std::unordered_map> handlers_; HTTPRoutesScope RegisterRoutes(std::string route, uint16_t port) { - return HTTP(current::net::BarePort(port)).Register(route, URLPathArgs::CountMask::Any, [this](Request r) { Serve(std::move(r)); }); + return HTTP(current::net::BarePort(port)).Register(route, URLPathArgs::CountMask::Any, [this](Request r) { + Serve(std::move(r)); + }); } std::string ConstructSource(const std::string& body, const std::string& source_name = "code.cc") const { diff --git a/examples/dump_schema/dump_schema.cc b/examples/dump_schema/dump_schema.cc index 22b6d80c4..669fc415e 100644 --- a/examples/dump_schema/dump_schema.cc +++ b/examples/dump_schema/dump_schema.cc @@ -24,17 +24,13 @@ SOFTWARE. #include "../../current.h" -template +template void DumpSchema() { current::reflection::StructSchema schema; schema.AddType(); std::cout << schema.GetSchemaInfo().Describe(); } -CURRENT_STRUCT(CurrentType) { - CURRENT_FIELD(foo, std::string); -}; +CURRENT_STRUCT(CurrentType) { CURRENT_FIELD(foo, std::string); }; -int main() { - DumpSchema(); -} +int main() { DumpSchema(); } diff --git a/examples/ejs/cpp/ejs.cc b/examples/ejs/cpp/ejs.cc index 22260624b..d4253cb8b 100644 --- a/examples/ejs/cpp/ejs.cc +++ b/examples/ejs/cpp/ejs.cc @@ -45,48 +45,47 @@ int main(int argc, char** argv) { auto& http_server = HTTP(FLAGS_ejs_server_port); - const auto http_route_scope = http_server.Register( - "/", - [](Request request) { - const PrimesResponse response = [&request]() { - PrimesResponse response; - response.a = current::FromString(request.url.query.get("a", "1")); - response.b = current::FromString(request.url.query.get("b", "100")); - for (int64_t p = response.a; p <= response.b; ++p) { - bool is_prime = (p % 2) ? true : false; - for (int64_t d = 3; d * d <= p && is_prime; d += 2) { - if ((p % d) == 0) { - is_prime = false; - } - } - if (is_prime) { - response.x.push_back(p); - } + const auto http_route_scope = http_server.Register("/", [](Request request) { + const PrimesResponse response = [&request]() { + PrimesResponse response; + response.a = current::FromString(request.url.query.get("a", "1")); + response.b = current::FromString(request.url.query.get("b", "100")); + for (int64_t p = response.a; p <= response.b; ++p) { + bool is_prime = (p % 2) ? true : false; + for (int64_t d = 3; d * d <= p && is_prime; d += 2) { + if ((p % d) == 0) { + is_prime = false; } - return response; - }(); - - const bool html = [&request]() { - const char* kAcceptHeader = "Accept"; - if (request.headers.Has(kAcceptHeader)) { - for (const auto& h : current::strings::Split(request.headers[kAcceptHeader].value, ',')) { - if (current::strings::Split(h, ';').front() == "text/html") { // Allow "text/html; charset=...", etc. - return true; - } - } + } + if (is_prime) { + response.x.push_back(p); + } + } + return response; + }(); + + const bool html = [&request]() { + const char* kAcceptHeader = "Accept"; + if (request.headers.Has(kAcceptHeader)) { + for (const auto& h : current::strings::Split(request.headers[kAcceptHeader].value, ',')) { + if (current::strings::Split(h, ';').front() == "text/html") { // Allow "text/html; charset=...", etc. + return true; } - return false; - }(); - - if (html) { - request(HTTP(POST(current::strings::Printf("http://localhost:%d", static_cast(FLAGS_ejs_renderer_port)), - response)).body, - HTTPResponseCode.OK, - current::net::constants::kDefaultHTMLContentType); - } else { - request(response); } - }); + } + return false; + }(); + + if (html) { + request(HTTP(POST(current::strings::Printf("http://localhost:%d", static_cast(FLAGS_ejs_renderer_port)), + response)) + .body, + HTTPResponseCode.OK, + current::net::constants::kDefaultHTMLContentType); + } else { + request(response); + } + }); std::cout << "c++ app listening on port " << FLAGS_ejs_server_port << std::endl; diff --git a/examples/embedded_db/db.cc b/examples/embedded_db/db.cc index 728fbd776..d8b2f96e7 100644 --- a/examples/embedded_db/db.cc +++ b/examples/embedded_db/db.cc @@ -143,56 +143,46 @@ int main(int argc, char** argv) { HTTP(port).Register("/healthz", [](Request r) { r("OK\n"); }); // Schema. + using reflection::Language; using reflection::SchemaInfo; using reflection::StructSchema; - using reflection::Language; - HTTP(port) - .Register( - "/schema.h", - [](Request r) { - StructSchema schema; - schema.AddType(); - r(schema.GetSchemaInfo().Describe(), HTTPResponseCode.OK, "text/plain; charset=us-ascii"); - }); - - HTTP(port) - .Register( - "/schema.fs", - [](Request r) { - StructSchema schema; - schema.AddType(); - r(schema.GetSchemaInfo().Describe(), HTTPResponseCode.OK, "text/plain; charset=us-ascii"); - }); - - HTTP(port) - .Register("/schema.json", - [](Request r) { - StructSchema schema; - schema.AddType(); - r(schema.GetSchemaInfo()); - }); + HTTP(port).Register("/schema.h", [](Request r) { + StructSchema schema; + schema.AddType(); + r(schema.GetSchemaInfo().Describe(), HTTPResponseCode.OK, "text/plain; charset=us-ascii"); + }); + + HTTP(port).Register("/schema.fs", [](Request r) { + StructSchema schema; + schema.AddType(); + r(schema.GetSchemaInfo().Describe(), HTTPResponseCode.OK, "text/plain; charset=us-ascii"); + }); + + HTTP(port).Register("/schema.json", [](Request r) { + StructSchema schema; + schema.AddType(); + r(schema.GetSchemaInfo()); + }); // Subscribe. HTTP(port).Register("/data", *stream); // Publish. - HTTP(port) - .Register("/publish", - [&stream](Request r) { - if (r.method == "POST") { - try { - auto event = ParseJSON(r.body); - SetMicroTimestamp(event, time::Now()); - stream->Publisher()->Publish(std::move(event)); - r("", HTTPResponseCode.NoContent); - } catch (const Exception& e) { - r(Error(e.DetailedDescription()), HTTPResponseCode.BadRequest); - } - } else { - r(Error("This request should be a POST."), HTTPResponseCode.MethodNotAllowed); - } - }); + HTTP(port).Register("/publish", [&stream](Request r) { + if (r.method == "POST") { + try { + auto event = ParseJSON(r.body); + SetMicroTimestamp(event, time::Now()); + stream->Publisher()->Publish(std::move(event)); + r("", HTTPResponseCode.NoContent); + } catch (const Exception& e) { + r(Error(e.DetailedDescription()), HTTPResponseCode.BadRequest); + } + } else { + r(Error("This request should be a POST."), HTTPResponseCode.MethodNotAllowed); + } + }); // Read model. current::ss::StreamSubscriber read_model(port); diff --git a/examples/embedded_db/schema.h b/examples/embedded_db/schema.h index 15d085734..a35b4075f 100644 --- a/examples/embedded_db/schema.h +++ b/examples/embedded_db/schema.h @@ -71,8 +71,8 @@ CURRENT_STRUCT(UserNickname) { CURRENT_FIELD(user_id, std::string); CURRENT_FIELD(nickname, std::string); - CURRENT_CONSTRUCTOR(UserNickname)(const std::string& user_id, const std::string& nickname) - : user_id(user_id), nickname(nickname) {} + CURRENT_CONSTRUCTOR(UserNickname) + (const std::string& user_id, const std::string& nickname) : user_id(user_id), nickname(nickname) {} }; CURRENT_STRUCT(UserNicknameNotFound) { diff --git a/examples/event_collector/event_collector.h b/examples/event_collector/event_collector.h index a1eb815a1..6083d22e0 100644 --- a/examples/event_collector/event_collector.h +++ b/examples/event_collector/event_collector.h @@ -80,30 +80,28 @@ class EventCollectorHTTPServer { last_event_t_(0u), events_pushed_(0u), timer_thread_(&EventCollectorHTTPServer::TimerThreadFunction, this), - http_route_scope_(HTTP(http_port_) - .Register(route_, - [this](Request r) { - LogEntryWithHeaders entry; - { - const auto now = current::time::Now(); - std::lock_guard lock(mutex_); - entry.t = now.count(); - entry.m = r.method; - entry.u = r.url.ComposeURLWithoutParameters(); - entry.q = r.url.AllQueryParameters(); - entry.h = r.headers.AsMap(); - entry.c = r.headers.CookiesAsString(); - entry.b = r.body; - entry.f = r.url.fragment; - ostream_ << JSON(entry) << std::endl; - ++events_pushed_; - last_event_t_ = now; - if (callback_) { - callback_(entry); - } - } - r(response_text_); - })) {} + http_route_scope_(HTTP(http_port_).Register(route_, [this](Request r) { + LogEntryWithHeaders entry; + { + const auto now = current::time::Now(); + std::lock_guard lock(mutex_); + entry.t = now.count(); + entry.m = r.method; + entry.u = r.url.ComposeURLWithoutParameters(); + entry.q = r.url.AllQueryParameters(); + entry.h = r.headers.AsMap(); + entry.c = r.headers.CookiesAsString(); + entry.b = r.body; + entry.f = r.url.fragment; + ostream_ << JSON(entry) << std::endl; + ++events_pushed_; + last_event_t_ = now; + if (callback_) { + callback_(entry); + } + } + r(response_text_); + })) {} EventCollectorHTTPServer(const EventCollectorHTTPServer&) = delete; EventCollectorHTTPServer(EventCollectorHTTPServer&&) = delete; diff --git a/examples/event_collector/test.cc b/examples/event_collector/test.cc index 77e068d88..9a7ec55dd 100644 --- a/examples/event_collector/test.cc +++ b/examples/event_collector/test.cc @@ -144,9 +144,7 @@ TEST(EventCollector, Headers) { std::ostringstream os; EventCollectorHTTPServer collector(port, os, std::chrono::microseconds(0), "/ctfo", "="); EXPECT_EQ("=", - HTTP(GET(Printf("http://localhost:%d/ctfo", port)) - .SetHeader("foo", "bar") - .SetHeader("baz", "meh")).body); + HTTP(GET(Printf("http://localhost:%d/ctfo", port)).SetHeader("foo", "bar").SetHeader("baz", "meh")).body); auto e = ParseJSON(os.str()); EXPECT_EQ("bar", e.h["foo"]); EXPECT_EQ("meh", e.h["baz"]); diff --git a/examples/event_store/event_store.h b/examples/event_store/event_store.h index 3dd18f7a1..9921c2eda 100644 --- a/examples/event_store/event_store.h +++ b/examples/event_store/event_store.h @@ -37,7 +37,8 @@ SOFTWARE. template