SolidWallOfCode commented on a change in pull request #7918: URL: https://github.com/apache/trafficserver/pull/7918#discussion_r645734365
########## File path: proxy/http/remap/RemapHitCount.cc ########## @@ -0,0 +1,90 @@ +/** @file + + A brief file description + + @section license License + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#include "RemapHitCount.h" + +extern int num_of_net_threads; + +RemapHitCount RemapHitCount::_remapHitCountInstance; +std::vector<std::unordered_map<std::string, int>> RemapHitCount::_perThreadHits(num_of_net_threads); + +std::string +RemapHitCount::printRemapHits() +{ + std::unordered_map<std::string, int> aggregateHits; + ink_mutex_acquire(&_mutex); + for (size_t i = 0; i < _perThreadHits.size(); i++) { + for (auto &kv : _perThreadHits[i]) { + aggregateHits[kv.first] += kv.second; + } + } + ink_mutex_release(&_mutex); + + std::string text; + size_t extent = 0; + static const ts::BWFormat header_fmt{R"({{"remapRulesCount": {}, "list": [)"}; + static const ts::BWFormat item_fmt{R"( {{"fromURL": "{}", "hit_count": "{}"}},)"}; + static const std::string_view trailer{" }\n]}"}; + + static const auto printer = [](ts::BufferWriter &w, std::pair<std::string, int> &kv) -> ts::BufferWriter & { + w.print(item_fmt, kv.first, kv.second); + return w; + }; + + ts::FixedBufferWriter null_bw{nullptr}; // Empty buffer for sizing work. + + null_bw.print(header_fmt, aggregateHits.size()).extent(); + for (auto &kv : aggregateHits) { + printer(null_bw, (std::pair<std::string, int> &)kv); + } + extent = null_bw.extent() + trailer.size() - 2; // 2 for the trailing comma newline that will get clipped. + + text.resize(extent); + ts::FixedBufferWriter w(const_cast<char *>(text.data()), text.size()); + w.clip(trailer.size()); Review comment: You shouldn't need the `clip` / `restore` here because the output is already sufficient large. That is useful only in situations where the buffer could overflow and the terminator must be present. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected]
