Skip to content

Commit cb509c8

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

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

input/topPorts.hpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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 frequency) mutable {
41+
auto port_pos = std::lower_bound(res.begin(), res.end(), frequency,
42+
[](const std::pair<uint16_t, size_t>& port_frequency, size_t count) {
43+
return port_frequency.second >= count;
44+
});
45+
46+
if (port_pos != res.end()) {
47+
std::copy_backward(port_pos, std::prev(res.end()), res.end());
48+
*port_pos = std::make_pair(port, frequency);
49+
ports_inserted = std::min(TopPortsCount, ports_inserted + 1);
50+
}
51+
port++;
52+
});
53+
return {res, ports_inserted};
54+
}
55+
56+
private:
57+
std::array<std::size_t, std::numeric_limits<uint16_t>::max() + 1> m_port_frequencies {};
58+
};
59+
60+
} // namespace ipxp

0 commit comments

Comments
 (0)