Skip to content

Commit 492003b

Browse files
committed
Top 10 ports - Introduce TopPorts class
1 parent 70e7cc2 commit 492003b

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

input/topPorts.hpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* \file topPorts.hpp
3+
* \brief Template class implementing the most popular ports.
4+
* \author Damir Zainullin <[email protected]>
5+
* \date 2024
6+
*/
7+
#pragma once
8+
9+
#include <array>
10+
#include <cstdint>
11+
#include <functional>
12+
#include <limits>
13+
14+
namespace ipxp {
15+
/**
16+
* \brief Top ports counter.
17+
* \tparam TopPortsCount Number of the most popular ports to store.
18+
*/
19+
template<std::size_t TopPortsCount>
20+
class TopPorts {
21+
public:
22+
/**
23+
* \brief Increments number of times given port has been seen.
24+
* \param port Port to increment its frequency.
25+
*/
26+
void increment_frequency(uint16_t port) noexcept
27+
{
28+
m_port_frequencies[port]++;
29+
}
30+
31+
/**
32+
* \brief Get the top ports.
33+
* \return Pair of the top ports array and their count.
34+
*/
35+
std::pair<std::array<std::pair<uint16_t, size_t>, TopPortsCount>, size_t>
36+
get_top_ports() const noexcept
37+
{
38+
std::array<std::pair<uint16_t, size_t>, TopPortsCount> res{};
39+
size_t ports_inserted = 0;
40+
std::for_each(m_port_frequencies.begin(), m_port_frequencies.end(),[&, port = 0](size_t count) mutable {
41+
auto port_pos = std::lower_bound(res.begin(), res.end(), count, [](const std::pair<uint16_t, size_t>& portCount, size_t count) {
42+
return portCount.second >= count;
43+
});
44+
if (port_pos != res.end()) {
45+
std::copy_backward(port_pos, std::prev(res.end()), res.end());
46+
*port_pos = std::make_pair(port, count);
47+
ports_inserted = std::min(TopPortsCount, ports_inserted + 1);
48+
}
49+
port++;
50+
});
51+
return {res, ports_inserted};
52+
}
53+
54+
private:
55+
std::array<std::size_t, std::numeric_limits<uint16_t>::max() + 1> m_port_frequencies {};
56+
};
57+
58+
} // namespace ipxp

0 commit comments

Comments
 (0)