Extracted endianless conversion functions to separate file

This commit is contained in:
Pavel Odintsov 2020-08-23 14:29:12 +01:00
parent 8e9e782b65
commit ad5533bee2
3 changed files with 46 additions and 38 deletions

44
src/fast_endianless.hpp Normal file
View File

@ -0,0 +1,44 @@
#pragma once
#include <arpa/inet.h>
// Linux standard functions for endian conversions are ugly because there are no checks about arguments length
// And you could accidentally use ntohs (suitable only for 16 bit) for 32 or 64 bit value and nobody will warning you
// With this wrapper functions it's pretty complicated to use them for incorrect length type! :)
// Type safe versions of ntohl, ntohs with type control
inline uint16_t fast_ntoh(uint16_t value) {
return ntohs(value);
}
inline uint32_t fast_ntoh(uint32_t value) {
return ntohl(value);
}
inline int32_t fast_ntoh(int32_t value) {
return ntohl(value);
}
// network (big endian) byte order to host byte order
inline uint64_t fast_ntoh(uint64_t value) {
return be64toh(value);
}
// Type safe version of htonl, htons
inline uint16_t fast_hton(uint16_t value) {
return htons(value);
}
inline uint32_t fast_hton(uint32_t value) {
return htonl(value);
}
inline int32_t fast_hton(int32_t value) {
return htonl(value);
}
inline uint64_t fast_hton(uint64_t value) {
// host to big endian (network byte order)
return htobe64(value);
}

View File

@ -37,35 +37,6 @@ int convert_string_to_integer(std::string line) {
return atoi(line.c_str());
}
// Type safe versions of ntohl, ntohs with type control
uint16_t fast_ntoh(uint16_t value) {
return ntohs(value);
}
uint32_t fast_ntoh(uint32_t value) {
return ntohl(value);
}
// network (big endian) byte order to host byte order
uint64_t fast_ntoh(uint64_t value) {
return be64toh(value);
}
// Type safe version of htonl, htons
uint16_t fast_hton(uint16_t value) {
return htons(value);
}
uint32_t fast_hton(uint32_t value) {
return htonl(value);
}
uint64_t fast_hton(uint64_t value) {
// host to big endian (network byte order)
return htobe64(value);
}
uint32_t convert_ip_as_string_to_uint(std::string ip) {
struct in_addr ip_addr;
inet_aton(ip.c_str(), &ip_addr);

View File

@ -28,6 +28,8 @@
#include <luajit-2.0/lua.hpp>
#endif
#include "fast_endianless.hpp"
#define TCP_FIN_FLAG_SHIFT 1
#define TCP_SYN_FLAG_SHIFT 2
#define TCP_RST_FLAG_SHIFT 3
@ -81,15 +83,6 @@ void copy_networks_from_string_form_to_binary(std::vector<std::string> networks_
std::vector<subnet_t>& our_networks);
int convert_string_to_integer(std::string line);
// Byte order type safe converters
uint16_t fast_ntoh(uint16_t value);
uint32_t fast_ntoh(uint32_t value);
uint64_t fast_ntoh(uint64_t value);
uint16_t fast_hton(uint16_t value);
uint32_t fast_hton(uint32_t value);
uint64_t fast_hton(uint64_t value);
bool print_pid_to_file(pid_t pid, std::string pid_path);
bool read_pid_from_file(pid_t& pid, std::string pid_path);