From 3b04085b048e29411f194603abacb20eb012cf57 Mon Sep 17 00:00:00 2001 From: amass <168062547@qq.com> Date: Sun, 10 Nov 2024 20:20:34 +0800 Subject: [PATCH] add nng error code. --- Nng/ErrorCode.cpp | 22 ++++++++++++++++++++++ Nng/ErrorCode.h | 16 ++++++++++++++++ Nng/Option.h | 18 ++++++++++++++++++ Nng/Socket.h | 14 ++++++++++++-- 4 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 Nng/Option.h diff --git a/Nng/ErrorCode.cpp b/Nng/ErrorCode.cpp index e69de29..5586200 100644 --- a/Nng/ErrorCode.cpp +++ b/Nng/ErrorCode.cpp @@ -0,0 +1,22 @@ +#include "ErrorCode.h" +#include + +namespace Nng { +const char *ErrorCategory::name() const noexcept { + return "nng"; +} + +std::string ErrorCategory::message(int ev) const { + return nng_strerror(ev); +} + +static const std::error_category &errorCategory() { + static ErrorCategory instance; + return instance; +} + +std::error_code makeErrorCode(int code) { + return {code, errorCategory()}; +} + +} // namespace Nng diff --git a/Nng/ErrorCode.h b/Nng/ErrorCode.h index e69de29..9b40f73 100644 --- a/Nng/ErrorCode.h +++ b/Nng/ErrorCode.h @@ -0,0 +1,16 @@ +#ifndef __ERRORCODE_H__ +#define __ERRORCODE_H__ + +#include + +namespace Nng { +class ErrorCategory : public std::error_category { +public: + const char *name() const noexcept final; + std::string message(int ev) const final; +}; + +std::error_code makeErrorCode(int code); +} // namespace Nng + +#endif // __ERRORCODE_H__ \ No newline at end of file diff --git a/Nng/Option.h b/Nng/Option.h new file mode 100644 index 0000000..d4ad2e8 --- /dev/null +++ b/Nng/Option.h @@ -0,0 +1,18 @@ +#ifndef __OPTION_H__ +#define __OPTION_H__ + +#include +#include + +namespace Nng { + +template +struct Option { + constexpr Option(const char *opt) : option(opt) {}; + const char *option; +}; + +inline constexpr Option RecvTimeout(NNG_OPT_RECVTIMEO); +} // namespace Nng + +#endif // __OPTION_H__ \ No newline at end of file diff --git a/Nng/Socket.h b/Nng/Socket.h index ad056ee..4bfce64 100644 --- a/Nng/Socket.h +++ b/Nng/Socket.h @@ -2,6 +2,8 @@ #define __SOCKET_H__ #include "Buffer.h" +#include "ErrorCode.h" +#include "Option.h" #include "Protocol.h" #include #include @@ -22,8 +24,11 @@ public: nng_listen(m_socket, url.data(), nullptr, flags); } - void dial(const std::string_view &url, int flags = 0) { - nng_dial(m_socket, url.data(), nullptr, flags); + void dial(const std::string_view &url, std::error_code &error, int flags = 0) { + int status = nng_dial(m_socket, url.data(), nullptr, flags); + if (status != 0) { + error = makeErrorCode(status); + } } void send(const void *data, size_t size, int flags = 0) { @@ -37,6 +42,11 @@ public: return Buffer(data, size); } + template + void setOption(const Option &opt, const T &value) { + nng_socket_set_ms(m_socket, opt.option, value.count()); + } + protected: nng_socket m_socket = NNG_SOCKET_INITIALIZER; };