6 Commits

Author SHA1 Message Date
471b5b56f8 remove this commit
All checks were successful
Linux arm64 / Build (push) Successful in 58s
2025-03-15 09:33:59 +01:00
392fcb3d17 add operator<< for packets (#14)
All checks were successful
Linux arm64 / Build (push) Successful in 16s
Reviewed-on: #14
Co-authored-by: Persson-dev <sim16.prib@gmail.com>
Co-committed-by: Persson-dev <sim16.prib@gmail.com>
2025-03-13 15:20:37 +00:00
205c09a338 move SocketHandle to TcpTag
All checks were successful
Linux arm64 / Build (push) Successful in 1m3s
2025-03-12 19:07:29 +01:00
77356ce749 better print override
All checks were successful
Linux arm64 / Build (push) Successful in 15s
2025-03-04 22:45:50 +01:00
7f8d9e3f96 add msg.ToString()
All checks were successful
Linux arm64 / Build (push) Successful in 15s
2025-03-04 20:26:42 +01:00
81c9dbadd6 fix printing
All checks were successful
Linux arm64 / Build (push) Successful in 15s
2025-03-04 12:23:59 +01:00
25 changed files with 403 additions and 72 deletions

View File

@@ -15,7 +15,8 @@ using UpgradeTowerFields = std::tuple<
sp::Field<std::uint16_t, 12>, //<- m_Tower
sp::Field<std::uint8_t, 4> //<- m_Upgrade
>,
sp::VarInt //<- just for testing
sp::VarInt, //<- just for testing
std::map<std::string, std::vector<int>>
>;
DeclarePacket(UpgradeTower){

View File

@@ -6,7 +6,7 @@
namespace sp {
template <typename T>
std::string GetClassName(const T& a_Value) {
std::string GetBasicClassName(const T& a_Value) {
int status;
char* demangled = abi::__cxa_demangle(typeid(a_Value).name(), 0, 0, &status);
if (status != 0)
@@ -15,7 +15,7 @@ std::string GetClassName(const T& a_Value) {
}
template <typename T>
std::string GetClassName() {
std::string GetBasicClassName() {
int status;
char* demangled = abi::__cxa_demangle(typeid(T).name(), 0, 0, &status);
if (status != 0)
@@ -23,4 +23,38 @@ std::string GetClassName() {
return std::string(demangled);
}
template <typename T>
struct Reflector {
static std::string GetClassName() {
return GetBasicClassName<T>();
}
};
template <>
struct Reflector<std::string> {
static std::string GetClassName() {
return "std::string";
}
};
template <typename K, typename V>
struct Reflector<std::map<K, V>> {
static std::string GetClassName();
};
template <typename T>
struct Reflector<std::vector<T>> {
static std::string GetClassName();
};
template <typename T>
std::string Reflector<std::vector<T>>::GetClassName() {
return "std::vector<" + Reflector<T>::GetClassName() + ">";
}
template <typename K, typename V>
std::string Reflector<std::map<K, V>>::GetClassName() {
return "std::map<" + Reflector<K>::GetClassName() + ", " + Reflector<V>::GetClassName() + ">";
}
} // namespace sp

View File

@@ -1,6 +1,8 @@
#pragma once
#include <cstdint>
#include <string>
#include <tuple>
namespace sp {
@@ -50,4 +52,48 @@ void TupleForEach(TFunc&& func, TTuple&& tuple) {
details::TupleForEachHelper<TupleSize>::Exec(std::forward<TTuple>(tuple), std::forward<TFunc>(func));
}
namespace details {
template <typename T, typename U = void>
struct is_mappish_impl : std::false_type {};
template <typename T>
struct is_mappish_impl<T, std::void_t<typename T::key_type, typename T::mapped_type,
decltype(std::declval<T&>()[std::declval<const typename T::key_type&>()])>> : std::true_type {};
template <typename T, typename U = void>
struct is_vectish_impl : std::false_type {};
template <typename T>
struct is_vectish_impl<T,
std::void_t<typename T::value_type, decltype(std::declval<T&>()[std::declval<const typename T::value_type&>()])>>
: std::true_type {};
template <typename T, typename U = void>
struct is_pairish_impl : std::false_type {};
template <typename T>
struct is_pairish_impl<T,
std::void_t<typename T::first_type, decltype(std::declval<T&>()[std::declval<const typename T::first_type&>()])>>
: std::true_type {};
template <typename T>
using is_general_t = std::integral_constant<bool,
(std::is_same_v<T, std::string> || (!std::is_same_v<T, char> && !std::is_same_v<T, unsigned char> && !std::is_arithmetic_v<T> &&
!is_pairish_impl<T>::value && !is_mappish_impl<T>::value && !is_vectish_impl<T>::value))>;
template <typename T>
using is_primitive =
std::integral_constant<bool, std::is_same_v<T, char> || std::is_same_v<T, unsigned char> || std::is_arithmetic_v<T>>;
} // namespace details
} // namespace sp

View File

@@ -8,6 +8,7 @@
#include <cstddef>
#include <cstdint>
#include <ostream>
#include <sp/protocol/Field.h>
namespace sp {
@@ -57,10 +58,7 @@ class VarInt {
*/
friend DataBuffer& operator>>(DataBuffer& in, VarInt& var);
/**
* \brief overriding stream operator
*/
friend std::ostream& operator<<(std::ostream& a_Stream, const sp::VarInt& a_VarInt);
friend std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<VarInt>& a_VarInt);
};
} // namespace sp

View File

@@ -7,12 +7,13 @@ namespace sp {
class PacketHandler;
using PacketMessage = Message<
option::MsgIdType<std::uint8_t>, // add id() operation
option::ReadOperations, // add read() operation
option::WriteOperations, // add write() operation
option::WriteId, // write id before data
option::Handler<PacketHandler> // add dispatch() operation
>;
option::MsgIdType<std::uint8_t>, // add id() operation
option::ReadOperations, // add read() operation
option::WriteOperations, // add write() operation
option::WriteId, // write id before data
option::Handler<PacketHandler>, // add dispatch() operation
option::DebugPrint // add ToString() operator
>;
#define PacketConstructor(packetName) \
packetName##Packet() {} \
@@ -23,7 +24,8 @@ using PacketMessage = Message<
#define DeclarePacket(packetName) \
class packetName##Packet : public sp::MessageBase<sp::PacketMessage, sp::option::StaticNumIdImpl<packetName>, \
sp::option::DispatchImpl<packetName##Packet>, sp::option::FieldsImpl<packetName##Fields>>
sp::option::DispatchImpl<packetName##Packet>, sp::option::FieldsImpl<packetName##Fields>>, \
sp::option::ToStringImpl<packetName##Packet>

View File

@@ -10,6 +10,8 @@ namespace io {
*/
class TcpListener : private NonCopyable {
public:
using SocketHandle = TcpTag::SocketHandle;
/**
* \brief Starts listening for guests to connect
* \param port The port to listen to

View File

@@ -6,9 +6,9 @@
namespace sp {
namespace io {
using SocketHandle = int;
struct TcpTag {};
struct TcpTag {
using SocketHandle = int;
};
class SocketError : public std::exception {
private:
@@ -25,6 +25,8 @@ class SocketError : public std::exception {
template <>
class IOInterface<TcpTag> : private NonCopyable {
public:
using SocketHandle = TcpTag::SocketHandle;
/**
* \enum Status
* \brief Describes the state of a socket

View File

@@ -1,6 +1,5 @@
#pragma once
#include <sp/common/DataBuffer.h>
#include <sp/common/Templates.h>
namespace sp {
@@ -98,6 +97,19 @@ class Field {
StorageType m_Value;
};
template <typename T>
class PrintableField {
public:
PrintableField(const T& a_Value) : m_Value(a_Value) {}
const T& GetValue() const {
return m_Value;
}
private:
const T& m_Value;
};
namespace details {
template <typename... TFields>

View File

@@ -14,3 +14,5 @@ template <typename TBase, typename... TOptions>
class MessageBase : public details::MessageImplBuilder<TBase, TOptions...>::Type {};
} // namespace sp
#include <sp/protocol/message/MessagePrinterImpl.h>

View File

@@ -1,19 +1,61 @@
#pragma once
#include <map>
#include <ostream>
#include <sp/common/Reflection.h>
#include <sp/protocol/message/MessagePrinterImpl.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/message/OstreamFieldIterator.h>
#include <string>
#include <vector>
/**
* \brief Prints a message in a human readable string
*/
template <typename TBase, typename... TOptions>
std::ostream& operator<<(std::ostream& a_Stream, const sp::MessageBase<TBase, TOptions...>& a_Message) {
a_Stream
<< sp::GetClassName(a_Message)
<< sp::details::IdPrinter<TOptions...>::PrintMessageId()
<< "["
<< sp::details::PrintFields(a_Message.GetFields())
<< "]";
return a_Stream;
namespace sp {
template <typename T, std::enable_if_t<details::is_primitive<T>::value, bool> = true>
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<T>& a_Field) {
return a_Stream << std::to_string(a_Field.GetValue());
}
inline std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<long unsigned int>& a_Field) {
return a_Stream << a_Field.GetValue();
}
inline std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::string>& a_Field) {
return a_Stream << "\"" << a_Field.GetValue() << "\"";
}
template <typename K, typename V>
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::pair<K, V>>& a_Data);
template <typename K, typename V>
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::map<K, V>>& a_Data);
template <typename T>
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::vector<T>>& a_Data);
template <typename K, typename V>
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::pair<K, V>>& a_Data) {
return a_Stream << PrintableField<K>(a_Data.GetValue().first) << " => " << PrintableField<V>(a_Data.GetValue().second);
}
template <typename K, typename V>
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::map<K, V>>& a_Data) {
a_Stream << "{";
std::copy(a_Data.GetValue().begin(), a_Data.GetValue().end(), OstreamFieldIterator<std::pair<K, V>>(std::cout, ", "));
return a_Stream << "}";
}
template <typename T>
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<std::vector<T>>& a_Data) {
a_Stream << "{";
std::copy(a_Data.GetValue().begin(), a_Data.GetValue().end(), OstreamFieldIterator<T>(std::cout, ", "));
return a_Stream << "}";
}
} // namespace sp

View File

@@ -37,8 +37,12 @@ struct MessageImplBuilder {
static const bool HasValidImpl = InterfaceOptions::HasValid && ImplOptions::HasFieldsImpl;
using Base6 = typename MessageImplProcessValidFields<Base5, HasValidImpl>::Type;
// Provide ToStringImpl() if possible
static const bool HasToStringImpl = InterfaceOptions::HasToString;
using Base7 = typename MessageImplProcessToString<Base6, ImplOptions, HasToStringImpl>::Type;
// The last BaseN must be taken as final type.
using Type = Base6;
using Type = Base7;
};
} // namespace details

View File

@@ -16,6 +16,11 @@ struct DispatchImpl {};
template <typename TFields>
struct FieldsImpl {};
// Print fields of the message, facilitate implementation of
// ToStringImpl()
template <typename TActual>
struct ToStringImpl {};
} // namespace option

View File

@@ -4,6 +4,20 @@ namespace sp {
namespace details {
// ToString impl
template <typename TBase, typename ParsedImplOptions, bool TImplement>
struct MessageImplProcessToString;
template <typename TBase, typename ParsedImplOptions>
struct MessageImplProcessToString<TBase, ParsedImplOptions, true> {
using Type = MessageImplToStringBase<TBase, typename ParsedImplOptions::ActualMessage>;
};
template <typename TBase, typename ParsedImplOptions>
struct MessageImplProcessToString<TBase, ParsedImplOptions, false> {
using Type = TBase;
};
// id impl
template <typename TBase, typename ParsedImplOptions, bool TImplement>

View File

@@ -33,8 +33,11 @@ struct MessageInterfaceBuilder {
// add write id functionality if write id and write was provided
using Base7 = typename MessageInterfaceProcessWriteId<Base6, ParsedOptions::HasWriteId && ParsedOptions::HasWriteOperations>::Type;
// The last Base7 must be taken as final type.
using Type = Base7;
// add ToString() if HasToString was provided
using Base8 = typename MessageInterfaceProcessToString<Base7, ParsedOptions::HasToString>::Type;
// The last Base8 must be taken as final type.
using Type = Base8;
};
} // namespace details

View File

@@ -101,5 +101,19 @@ struct MessageInterfaceProcessWriteId<TBase, false> {
using Type = TBase;
};
// Build to string
template <typename TBase, bool THasToString>
struct MessageInterfaceProcessToString;
template <typename TBase>
struct MessageInterfaceProcessToString<TBase, true> {
using Type = MessageInterfaceToStringBase<TBase>;
};
template <typename TBase>
struct MessageInterfaceProcessToString<TBase, false> {
using Type = TBase;
};
} // namespace details
} // namespace sp

View File

@@ -129,5 +129,17 @@ class MessageInterfaceWriteIdBase : public TBase {
}
};
// Debug print functionality chunk
template <typename TBase>
class MessageInterfaceToStringBase : public TBase {
public:
friend std::ostream& operator<<(std::ostream& a_Stream, const MessageInterfaceToStringBase& a_Message) {
return a_Message.OpOutImpl(a_Stream);
}
protected:
virtual std::ostream& OpOutImpl(std::ostream& a_Stream) const = 0;
};
} // namespace details
} // namespace sp

View File

@@ -16,6 +16,7 @@ struct MessageInterfaceParsedOptions<> {
static const bool HasWriteId = false;
static const bool HasHandler = false;
static const bool HasValid = false;
static const bool HasToString = false;
};
@@ -59,5 +60,10 @@ struct MessageInterfaceParsedOptions<option::ValidCheckInterface, TOptions...> :
static const bool HasValid = true;
};
template <typename... TOptions>
struct MessageInterfaceParsedOptions<option::DebugPrint, TOptions...> : public MessageInterfaceParsedOptions<TOptions...> {
static const bool HasToString = true;
};
} // namespace details
} // namespace sp

View File

@@ -24,6 +24,9 @@ struct LittleEndian {};
// Include validity check in public interface
struct ValidCheckInterface {};
// Add a ToString() method containing fields
struct DebugPrint {};
// Define handler class
template <typename T>
struct Handler {

View File

@@ -1,7 +1,8 @@
#pragma once
#include <sstream>
#include <sp/protocol/MessageBase.h>
#include <sp/common/Reflection.h>
#include <sp/common/Templates.h>
#include <sp/protocol/MessagePrinter.h>
namespace sp {
namespace details {
@@ -30,52 +31,49 @@ struct IdPrinter<option::StaticNumIdImpl<TId>, TOptions...> {
}
};
template <typename T>
std::string PrintData(const T& a_Data) {
std::stringstream sStream;
sStream << a_Data;
return sStream.str();
}
template <>
std::string PrintData<char>(const char& a_Data) {
return std::to_string(a_Data);
}
template <>
std::string PrintData<unsigned char>(const unsigned char& a_Data) {
return std::to_string(a_Data);
}
} // namespace details
template <typename... TFields>
std::string PrintFields(const std::tuple<TFields...>& a_Fields);
std::ostream& operator<<(std::ostream& a_Stream, const std::tuple<TFields...>& a_Fields);
template <typename TField, unsigned int IAlignment>
struct FieldPrinter {
static std::string PrintField(const sp::Field<TField, IAlignment>& a_Field) {
return GetClassName<TField>() + "=" + PrintData(a_Field.GetValue());
static std::ostream& PrintField(std::ostream& a_Stream, const sp::Field<TField, IAlignment>& a_Field) {
return a_Stream << sp::Reflector<TField>::GetClassName() << "=" << PrintableField<TField>(a_Field.GetValue());
}
};
template <unsigned int IAlignment, typename TContainer, typename... TFields>
struct FieldPrinter<sp::BitField<TContainer, TFields...>, IAlignment> {
static std::string PrintField(const sp::Field<sp::BitField<TContainer, TFields...>, IAlignment>& a_Field) {
return "BitField<" + GetClassName<TContainer>() + ">[" + PrintFields(a_Field.GetValue().GetFields()) + "]";
static std::ostream& PrintField(
std::ostream& a_Stream, const sp::Field<sp::BitField<TContainer, TFields...>, IAlignment>& a_Field) {
a_Stream << "BitField<" << sp::Reflector<TContainer>::GetClassName() << ">[";
a_Stream << a_Field.GetValue().GetFields() << "]";
return a_Stream;
}
};
template <typename... TFields>
std::string PrintFields(const std::tuple<TFields...>& a_Fields) {
std::string concat;
std::ostream& operator<<(std::ostream& a_Stream, const std::tuple<TFields...>& a_Fields) {
bool first = true;
TupleForEach(
[&concat](const auto& a_Field) {
[&a_Stream, &first](const auto& a_Field) {
if (!first)
a_Stream << ", ";
using TField = typename std::decay<decltype(a_Field)>::type;
constexpr std::size_t alignment = TField::AlignmentValue;
concat += FieldPrinter<typename TField::StorageType, alignment>::PrintField(a_Field) + ", ";
FieldPrinter<typename TField::StorageType, alignment>::PrintField(a_Stream, a_Field);
first = false;
},
a_Fields);
return concat.substr(0, concat.size() - 2);
return a_Stream;
}
template <typename TBase, typename... TOptions>
std::ostream& operator<<(std::ostream& a_Stream, const sp::MessageBase<TBase, TOptions...>& a_Message) {
a_Stream << sp::GetBasicClassName(a_Message) << sp::details::IdPrinter<TOptions...>::PrintMessageId() << "["
<< a_Message.GetFields() << "]";
return a_Stream;
}
} // namespace details
} // namespace sp

View File

@@ -1,8 +1,24 @@
#pragma once
namespace sp {
template <typename TBase, typename... TOptions>
class MessageBase;
namespace details {
template <typename TBase, typename... TOptions>
std::string PrintMessage(const MessageBase<TBase, TOptions...>& a_Message);
// ID information chunk
template <typename TBase, typename TActual>
class MessageImplToStringBase : public TBase {
protected:
virtual std::ostream& OpOutImpl(std::ostream& a_Stream) const override{
return a_Stream << static_cast<const TActual&>(*this);
}
};
// ID information chunk
@@ -18,6 +34,8 @@ class MessageImplStaticNumIdBase : public TBase {
}
};
// Dispatch implementation chunk
template <typename TBase, typename TActual>
class MessageImplDispatchBase : public TBase {

View File

@@ -0,0 +1,56 @@
// infix_iterator.h
//
// Lifted from Jerry Coffin's 's prefix_ostream_iterator
#pragma once
#include <ostream>
#include <sp/protocol/Field.h>
namespace sp {
template <class T, class charT = char, class traits = std::char_traits<charT>>
class OstreamFieldIterator {
private:
std::basic_ostream<charT, traits>* m_Os;
std::string m_Delimiter;
bool m_FirstElem;
public:
using iterator_category = std::output_iterator_tag;
using value_type = void;
using difference_type = void;
using pointer = void;
using reference = void;
using char_type = charT;
using traits_type = traits;
using ostream_type = std::basic_ostream<charT, traits>;
OstreamFieldIterator(ostream_type& a_Stream) : m_Os(&a_Stream), m_Delimiter(0), m_FirstElem(true) {}
OstreamFieldIterator(ostream_type& a_Stream, std::string&& a_Delimiter) :
m_Os(&a_Stream), m_Delimiter(std::move(a_Delimiter)), m_FirstElem(true) {}
auto& operator=(const T& item) {
// Here's the only real change from ostream_iterator:
// Normally, the '*m_Os << item;' would come before the 'if'.
if (!m_FirstElem && !m_Delimiter.empty())
*m_Os << m_Delimiter;
*m_Os << sp::PrintableField<T>(item);
m_FirstElem = false;
return *this;
}
auto& operator*() {
return *this;
}
auto& operator++() {
return *this;
}
auto& operator++(int) {
return *this;
}
};
} // namespace sp

View File

@@ -49,9 +49,8 @@ DataBuffer& operator>>(DataBuffer& in, VarInt& var) {
return in;
}
std::ostream& operator<<(std::ostream& a_Stream, const sp::VarInt& a_VarInt) {
a_Stream << a_VarInt.GetValue();
return a_Stream;
std::ostream& operator<<(std::ostream& a_Stream, const PrintableField<VarInt>& a_VarInt) {
return a_Stream << a_VarInt.GetValue().GetValue();
}
} // namespace sp

View File

@@ -0,0 +1,52 @@
#include <cstring>
#include <iostream>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/entropy.h>
#include <mbedtls/x509_crt.h>
#include <sp/common/DataBuffer.h>
#include <sp/common/NonCopyable.h>
namespace sp {
class SslContext : private NonCopyable {
public:
SslContext(unsigned int a_KeySizeBits) {
mbedtls_rsa_context rsaContext;
mbedtls_rsa_init(&rsaContext);
mbedtls_rsa_gen_key(&rsaContext, mbedtls_ctr_drbg_random, &m_CtrCrbg, a_KeySizeBits, 65537);
mbedtls_rsa_free(&rsaContext);
}
SslContext(const DataBuffer& a_Data) {
mbedtls_x509_crt_parse(&m_CaCert, (const unsigned char*)a_Data.data(), a_Data.GetSize()) == 0;
}
SslContext(const std::string& a_CertFilePath) {
mbedtls_x509_crt_parse_file(&m_CaCert, a_CertFilePath.c_str());
}
~SslContext() {
mbedtls_ctr_drbg_free(&m_CtrCrbg);
mbedtls_entropy_free(&m_Entropy);
mbedtls_x509_crt_free(&m_CaCert);
}
private:
void InitContext() {
int error = 0;
mbedtls_x509_crt_init(&m_CaCert);
mbedtls_ctr_drbg_init(&m_CtrCrbg);
mbedtls_entropy_init(&m_Entropy);
if ((error = mbedtls_ctr_drbg_seed(&m_CtrCrbg, mbedtls_entropy_func, &m_Entropy, nullptr, 0)) != 0) {
throw std::runtime_error("Failed to initialise random number generator. Returned error: " + std::to_string(error));
}
}
mbedtls_entropy_context m_Entropy;
mbedtls_ctr_drbg_context m_CtrCrbg;
mbedtls_x509_crt m_CaCert;
};
} // namespace sp

View File

@@ -5,7 +5,6 @@
#include <sp/default/DefaultPacketDispatcher.h>
#include <sp/extensions/Extensions.h>
#include <sp/protocol/MessagePrinter.h>
class KeepAliveHandler : public sp::PacketHandler {
void Handle(const KeepAlivePacket& packet) {
@@ -23,7 +22,8 @@ class KeepAliveHandler : public sp::PacketHandler {
};
int main() {
auto upgradeTower = std::make_unique<UpgradeTowerPacket>(std::make_tuple(666, 9), 789);
std::map<std::string, std::vector<int>> yes = {{"woa", {5, 8}}, {"insane", {6, 9}}};
auto upgradeTower = std::make_unique<UpgradeTowerPacket>(std::make_tuple(666, 9), 789, yes);
auto keepAlive = std::make_unique<KeepAlivePacket>(6969);
sp::PacketMessage* msg = upgradeTower.get();
@@ -40,7 +40,7 @@ int main() {
auto upgradeTower2 = std::make_unique<UpgradeTowerPacket>();
upgradeTower2->Read(buffer);
std::cout << "Test : " << *upgradeTower2 << "\n";
std::cout << "Test : " << *msg << "\n";
sp::PacketFactory factory;
auto packet = factory.CreateMessage(msgId);

View File

@@ -14,6 +14,12 @@ local modules = {
Deps = {},
Includes = {"include/(sp/extensions/Tcp.h)", "include/(sp/extensions/tcp/*.h)"},
Sources = {"src/sp/extensions/Tcp*.cpp"}
},
MbedTls = {
Option = "tls",
Deps = {"mbedtls"},
Includes = {"include/(sp/extensions/Ssl.h)", "include/(sp/extensions/Ssl/*.h)"},
Sources = {"src/sp/extensions/Ssl*.cpp"}
}
}