Conn/net_utils/fmt_mac: Avoid snprintf(), memcpy() and allocation

The fmt_mac() function returning a std::string means the resulting mac
is copied at least once upon returning. Then, the Assign() in GetVal()
taking a std::string internally allocates a new zeek::String which
hits a malloc (no short-string optimization for zeek::String) and then
also copies the content from the std::string into the malloced memory.

Save a few cycles by directly using the allocated memory with the
String instance. This change improves runtime for a SYN-only pcap
with just base/protocols/conn loaded by some 1-2%.
This commit is contained in:
Arne Welzel 2024-02-08 11:32:06 +01:00
parent c41977057a
commit 29f5b507b6
3 changed files with 87 additions and 16 deletions

View file

@ -207,12 +207,29 @@ extern const char* fmt_conn_id(const uint32_t* src_addr, uint32_t src_port, cons
* an empty string.
*
* @param m EUI-48 or EUI-64 MAC address to format, as a char array
* @param len Number of bytes valid starting at *n*. This must be at
* least 8 for a valid address.
* @param len Number of bytes valid starting at *m*. This must be at
* least 6 for a valid address.
* @return A string of the formatted MAC. Passes ownership to caller.
*/
extern std::string fmt_mac(const unsigned char* m, int len);
/**
* Given a MAC address, formats it in hex as 00:de:ad:be:ef.
* Supports both EUI-48 and EUI-64. If it's neither, returns
* an empty buffer.
*
* This method returns a unique pointer to a buffer that is
* null terminated. It can, for example, be directly passed
* to a zeek::String instance.
*
* @param m EUI-48 or EUI-64 MAC address to format, as a char array
* @param len Number of bytes valid starting at *m*. This must be at
* least 6 for a valid address.
* @return A pair consisting of a uint8_t buffer and its string length.
* The buffer is null terminated and its actual length is + 1.
*/
extern std::pair<std::unique_ptr<uint8_t[]>, int> fmt_mac_bytes(const unsigned char* m, int len);
// Read 4 bytes from data and return in network order.
extern uint32_t extract_uint32(const u_char* data);