diff --git a/common/buffer_view.hpp b/common/buffer_view.hpp index f17c1be0..374e2487 100644 --- a/common/buffer_view.hpp +++ b/common/buffer_view.hpp @@ -43,9 +43,9 @@ namespace moon } template - typename std::enable_if< - !std::is_same::value && - !std::is_same::value, T>::type + std::enable_if_t< + !std::is_same_v && + !std::is_same_v, T> read() { static_assert(std::is_trivially_copyable::value, "type T must be trivially copyable."); @@ -53,15 +53,15 @@ namespace moon } template - typename std::enable_if< - std::is_same::value, T>::type read() + std::enable_if_t< + std::is_same_v, T> read() { return (_read() != 0) ? true : false; } template - typename std::enable_if< - std::is_same::value, T>::type read() + std::enable_if_t< + std::is_same_v, T> read() { std::string tmp; while (readpos_ < size_) @@ -76,7 +76,7 @@ namespace moon std::string to_string() const { - return std::string((const char*)data(), size()); + return std::string(data(), size()); } template @@ -141,8 +141,7 @@ namespace moon std::string_view read_delim(char c) { std::string_view strref(data_ + readpos_, size()); - size_t pos = strref.find(c); - if (pos != std::string_view::npos) + if (size_t pos = strref.find(c); pos != std::string_view::npos) { readpos_ += (pos + sizeof(c)); return std::string_view(strref.data(), pos); diff --git a/common/exception.hpp b/common/exception.hpp index 6a2b0253..784fdb09 100644 --- a/common/exception.hpp +++ b/common/exception.hpp @@ -29,7 +29,7 @@ namespace moon logic_error& operator=(const logic_error& e) = default; logic_error& operator=(logic_error&& e) = default; - virtual const char* what() const noexcept override { + const char* what() const noexcept override { return w.c_str(); } }; @@ -44,7 +44,7 @@ namespace moon #define MOON_CHECK(cnd,msg) {if(!(cnd)) throw moon::logic_error{(msg),__FILENAME__,__LINE__};} #ifdef DEBUG -#define MOON_ASSERT(cnd,msg) assert(cnd && msg); +#define MOON_ASSERT(cnd,msg) assert(cnd && msg) #else #define MOON_ASSERT(cnd,msg) #endif \ No newline at end of file diff --git a/common/http_utility.hpp b/common/http_utility.hpp index f79c3ccc..3e6e8f0a 100644 --- a/common/http_utility.hpp +++ b/common/http_utility.hpp @@ -4,10 +4,8 @@ #include "string.hpp" #include "buffer_view.hpp" -namespace moon +namespace moon::http { - namespace http - { using case_insensitive_multimap = std::unordered_multimap; using case_insensitive_multimap_view = std::unordered_multimap; @@ -22,7 +20,7 @@ namespace moon for (const auto &chr : value) { if (!((chr >= '0' && chr <= '9') || (chr >= 'A' && chr <= 'Z') || (chr >= 'a' && chr <= 'z') || chr == '-' || chr == '.' || chr == '_' || chr == '~')) - result += std::string("%") + hex_chars[static_cast(chr) >> 4] + hex_chars[static_cast(chr) & 15]; + result += std::string("%") + hex_chars[static_cast(chr) >> 4] + hex_chars[static_cast(chr) & 15]; else result += chr; } @@ -61,8 +59,8 @@ namespace moon std::string result; bool first = true; - for (auto &field : fields) { - result += (!first ? "&" : "") + field.first + '=' + percent::encode(field.second); + for (const auto &[k,v] : fields) { + result += (!first ? "&" : "") + k + '=' + percent::encode(v); first = false; } @@ -81,10 +79,9 @@ namespace moon auto value_pos = std::string_view::npos; for (std::size_t c = 0; c < query_string.size(); ++c) { if (query_string[c] == '&') { - auto name = query_string.substr(name_pos, (name_end_pos == std::string_view::npos ? c : name_end_pos) - name_pos); - if (!name.empty()) { + if (auto name = query_string.substr(name_pos, (name_end_pos == std::string_view::npos ? c : name_end_pos) - name_pos); !name.empty()) { auto value = value_pos == std::string_view::npos ? std::string_view{} : query_string.substr(value_pos, c - value_pos); - result.emplace(std::move(name), percent::decode(value)); + result.emplace(name, percent::decode(value)); } name_pos = c + 1; name_end_pos = std::string_view::npos; @@ -99,7 +96,7 @@ namespace moon auto name = query_string.substr(name_pos, name_end_pos - name_pos); if (!name.empty()) { auto value = value_pos >= query_string.size() ? std::string_view{} : query_string.substr(value_pos); - result.emplace(std::move(name), percent::decode(value)); + result.emplace(name, percent::decode(value)); } } @@ -116,8 +113,7 @@ namespace moon std::string_view line = br.readline(); size_t param_end = 0; while ((param_end = line.find(':')) != std::string_view::npos) { - size_t value_start = param_end + 1; - if (value_start < line.size()) { + if (size_t value_start = param_end + 1; value_start < line.size()) { if (line[value_start] == ' ') value_start++; if (value_start < line.size()) @@ -138,8 +134,7 @@ namespace moon buffer_view br(sv.data(), sv.size()); auto line = br.readline(); - size_t method_end; - if ((method_end = line.find(' ')) != std::string_view::npos) + if (size_t method_end; (method_end = line.find(' ')) != std::string_view::npos) { method = line.substr(0, method_end); size_t query_start = std::string_view::npos; @@ -164,8 +159,7 @@ namespace moon } else path = line.substr(method_end + 1, path_and_query_string_end - method_end - 1); - size_t protocol_end; - if ((protocol_end = line.find('/', path_and_query_string_end + 1)) != std::string_view::npos) { + if (size_t protocol_end; (protocol_end = line.find('/', path_and_query_string_end + 1)) != std::string_view::npos) { if (line.compare(path_and_query_string_end + 1, protocol_end - path_and_query_string_end - 1, "HTTP") != 0) return false; http_version = line.substr(protocol_end + 1, line.size() - protocol_end - 1); @@ -192,8 +186,12 @@ namespace moon { buffer_view br(sv.data(), sv.size()); auto line = br.readline(); - std::size_t version_end; - if (!line.empty() && (version_end = line.find(' ')) != std::string_view::npos) { + if(line.empty()){ + return false; + } + + + if (std::size_t version_end = line.find(' '); version_end != std::string_view::npos) { if (5 < line.size()) version = line.substr(5, version_end - 5); else @@ -210,7 +208,6 @@ namespace moon return true; } }; - } } diff --git a/common/lua_utility.hpp b/common/lua_utility.hpp index ab2f81ac..eadc3d93 100644 --- a/common/lua_utility.hpp +++ b/common/lua_utility.hpp @@ -9,14 +9,14 @@ #define luaL_rawsetfield(L, tbindex, kname, valueexp)\ lua_pushliteral(L, kname);\ (valueexp);\ - lua_rawset(L, tbindex);\ + lua_rawset(L, tbindex)\ namespace moon { struct lua_scope_pop { lua_State* lua; - lua_scope_pop(lua_State* L) + explicit lua_scope_pop(lua_State* L) :lua(L) { } @@ -213,8 +213,7 @@ namespace moon }; inline int traceback(lua_State* L) { - const char* msg = lua_tostring(L, 1); - if (msg) + if (const char* msg = lua_tostring(L, 1)) luaL_traceback(L, L, msg, 1); else { lua_pushliteral(L, "(no error message)"); diff --git a/common/string.hpp b/common/string.hpp index dfced491..2a863f07 100644 --- a/common/string.hpp +++ b/common/string.hpp @@ -192,7 +192,6 @@ namespace moon return r; } - //format string inline std::string format(const char* fmt, ...) { if (!fmt) return std::string(""); @@ -255,8 +254,7 @@ namespace moon //" /t/n/r" inline std::string_view trim_right(std::string_view v) { - const auto words_end(v.find_last_not_of(" \t\n\r")); - if (words_end != std::string_view::npos) { + if (const auto words_end(v.find_last_not_of(" \t\n\r")); words_end != std::string_view::npos) { v.remove_suffix(v.size() - words_end - 1); } return v; @@ -271,8 +269,7 @@ namespace moon inline std::string_view trim(std::string_view v) { - const auto words_end(v.find_last_not_of(" \t\n\r")); - if (words_end != std::string_view::npos) { + if (const auto words_end(v.find_last_not_of(" \t\n\r")); words_end != std::string_view::npos) { v.remove_suffix(v.size() - words_end - 1); } const auto words_begin(v.find_first_not_of(" \t\n\r")); @@ -282,11 +279,14 @@ namespace moon inline void replace(std::string& src, std::string_view old, std::string_view strnew) { - for (std::string::size_type pos(0); pos != std::string::npos; pos += strnew.size()) { - if ((pos = src.find(old, pos)) != std::string::npos) - src.replace(pos, old.size(), strnew); - else - break; + if (old.empty()) { + return; + } + + std::string::size_type pos = 0; + while ((pos = src.find(old, pos)) != std::string::npos) { + src.replace(pos, old.size(), strnew); + pos += strnew.size(); } } @@ -316,7 +316,7 @@ namespace moon } //! case insensitive - inline bool iequal_string_locale(const std::string&str1, const std::string& str2, const std::locale& Loc = std::locale()) + inline bool iequal_string_locale(std::string_view str1, std::string_view str2, const std::locale& Loc = std::locale()) { if (str1.size() != str2.size()) return false; @@ -373,6 +373,22 @@ namespace moon return res; } + inline std::string escape_non_printable(std::string_view input) { + static constexpr std::string_view hex = "0123456789abcdef"; + std::string res; + for (char ch : input) { + if (isprint(static_cast(ch))) { + res.push_back(ch); + } else { + res.push_back('\\'); + res.push_back('x'); + res.push_back(hex[ch >> 4]); + res.push_back(hex[ch & 0xf]); + } + } + return res; + } + template struct ihash_string_functor { diff --git a/common/zset.hpp b/common/zset.hpp index 73a0e4f1..20b04446 100644 --- a/common/zset.hpp +++ b/common/zset.hpp @@ -45,12 +45,12 @@ namespace moon return *this; } - bool operator!=(const skip_list_iterator_sentinel) const { - return node_ != nullptr; + friend bool operator!=(skip_list_iterator self, skip_list_iterator_sentinel) { + return self.node_ != nullptr; } - bool operator==(const skip_list_iterator_sentinel) const { - return node_ == nullptr; + friend bool operator==(skip_list_iterator self, skip_list_iterator_sentinel) { + return self.node_ == nullptr; } }; @@ -161,7 +161,7 @@ namespace moon friend class skip_list_iterator< skip_list>; using const_iterator = skip_list_iterator< skip_list>; - skip_list(const allocator_type& alloc = allocator_type()) + explicit skip_list(const allocator_type& alloc = allocator_type()) :alloc_(alloc) , gen_(std::random_device{}()) { @@ -409,42 +409,42 @@ namespace moon int64_t score = 0; int64_t timestamp = 0; - bool operator==(const context& val) const + friend bool operator==(const context& self, const context& val) { - return key == val.key; + return self.key == val.key; } - bool operator<(const context& val) const + friend bool operator<(const context& self, const context& val) { - if (score == val.score) + if (self.score == val.score) { - if (timestamp == val.timestamp) + if (self.timestamp == val.timestamp) { - return key < val.key; + return self.key < val.key; } - return timestamp < val.timestamp; + return self.timestamp < val.timestamp; } - return score > val.score; + return self.score > val.score; } - bool operator<=(const context& val) const + friend bool operator<=(const context& self, const context& val) { - if (key == val.key) + if (self.key == val.key) return true; - return operator<(val); + return operator<(self, val); } - bool operator>(const context& val) const + friend bool operator>(const context& self, const context& val) { - if (score == val.score) + if (self.score == val.score) { - if (timestamp == val.timestamp) + if (self.timestamp == val.timestamp) { - return key > val.key; + return self.key > val.key; } - return timestamp > val.timestamp; + return self.timestamp > val.timestamp; } - return score < val.score; + return self.score < val.score; } }; public: diff --git a/lualib-src/lua_http.cpp b/lualib-src/lua_http.cpp index 145241f7..2a1b9a03 100644 --- a/lualib-src/lua_http.cpp +++ b/lualib-src/lua_http.cpp @@ -12,8 +12,7 @@ static int lhttp_parse_request(lua_State* L) std::string_view query_string; std::string_view version; http::case_insensitive_multimap_view header; - bool ok = http::request_parser::parse(data, method, path, query_string, version, header); - if(!ok){ + if(bool ok = http::request_parser::parse(data, method, path, query_string, version, header); !ok){ lua_pushboolean(L, 0); lua_pushstring(L, "Parse http request failed"); return 2; @@ -28,12 +27,12 @@ static int lhttp_parse_request(lua_State* L) lua_pushliteral(L, "header"); lua_createtable(L, 0, (int)header.size()); std::string tmp; - for (const auto& v : header) + for (const auto&[k,v] : header) { - tmp.assign(v.first.data(), v.first.size()); + tmp.assign(k.data(), k.size()); moon::lower(tmp); lua_pushlstring(L, tmp.data(), tmp.size()); - lua_pushlstring(L, v.second.data(), v.second.size()); + lua_pushlstring(L, v.data(), v.size()); lua_rawset(L, -3); } lua_rawset(L, -3); @@ -46,8 +45,7 @@ static int lhttp_parse_response(lua_State* L) std::string_view version; std::string_view status_code; http::case_insensitive_multimap_view header; - bool ok = http::response_parser::parse(data, version, status_code, header); - if(!ok){ + if(bool ok = http::response_parser::parse(data, version, status_code, header); !ok){ lua_pushboolean(L, 0); lua_pushstring(L, "Parse http response failed"); return 2; @@ -59,12 +57,12 @@ static int lhttp_parse_response(lua_State* L) lua_pushliteral(L, "header"); lua_createtable(L, 0, (int)header.size()); std::string tmp; - for (const auto& v : header) + for (const auto& [k,v] : header) { - tmp.assign(v.first.data(), v.first.size()); + tmp.assign(k.data(), k.size()); moon::lower(tmp); lua_pushlstring(L, tmp.data(), tmp.size()); - lua_pushlstring(L, v.second.data(), v.second.size()); + lua_pushlstring(L, v.data(), v.size()); lua_rawset(L, -3); } lua_rawset(L, -3); @@ -76,10 +74,10 @@ static int lhttp_parse_query_string(lua_State* L) std::string_view data = lua_check(L, 1); http::case_insensitive_multimap cim = http::query_string::parse(data); lua_createtable(L, 0, (int)cim.size()); - for (const auto& v : cim) + for (const auto& [k,v] : cim) { - lua_pushlstring(L, v.first.data(), v.first.size()); - lua_pushlstring(L, v.second.data(), v.second.size()); + lua_pushlstring(L, k.data(), k.size()); + lua_pushlstring(L, v.data(), v.size()); lua_rawset(L, -3); } return 1; diff --git a/lualib-src/lua_moon.cpp b/lualib-src/lua_moon.cpp index 38940fbc..753e2fc1 100644 --- a/lualib-src/lua_moon.cpp +++ b/lualib-src/lua_moon.cpp @@ -74,28 +74,28 @@ static int lmoon_md5(lua_State* L) { size_t size; const char* s = luaL_checklstring(L, 1, &size); - uint8_t buf[md5::DIGEST_BYTES] = { 0 }; + std::array bytes{}; md5::md5_context ctx; md5::init(ctx); md5::update(ctx, s, size); - md5::finish(ctx, buf); + md5::finish(ctx, bytes.data()); - char res[md5::DIGEST_BYTES * 2]; + std::array str{}; for (size_t i = 0; i < 16; i++) { - int t = buf[i]; + int t = bytes[i]; int a = t / 16; int b = t % 16; - res[i * 2] = md5::HEX[a]; - res[i * 2 + 1] = md5::HEX[b]; + str[i * 2] = md5::HEX[a]; + str[i * 2 + 1] = md5::HEX[b]; } - lua_pushlstring(L, res, sizeof(res)); + lua_pushlstring(L, str.data(), str.size()); return 1; } static int lmoon_tostring(lua_State* L) { luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); - const char* data = (const char*)lua_touserdata(L, 1); + auto* data = (const char*)lua_touserdata(L, 1); size_t len = luaL_checkinteger(L, 2); lua_pushlstring(L, data, len); return 1; @@ -113,7 +113,7 @@ static int lmoon_timeout(lua_State* L) static int lmoon_log(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto level = (moon::LogLevel)luaL_checkinteger(L, 1); if (log::instance().get_level() < level) return 0; @@ -121,8 +121,7 @@ static int lmoon_log(lua_State* L) moon::buffer line = log::instance().make_line(true, level, S->id()); int n = lua_gettop(L); /* number of arguments */ - int i; - for (i = 2; i <= n; i++) { /* for each argument */ + for (int i = 2; i <= n; i++) { /* for each argument */ size_t l; const char* s = luaL_tolstring(L, i, &l); /* convert it to string */ if (i > 2) /* not the first element? */ @@ -131,19 +130,15 @@ static int lmoon_log(lua_State* L) lua_pop(L, 1); /* pop result */ } - lua_Debug ar; - if (lua_getstack(L, 2, &ar)) + if (lua_Debug ar; lua_getstack(L, 2, &ar) && lua_getinfo(L, "Sl", &ar)) { - if (lua_getinfo(L, "Sl", &ar)) - { - line.write_back(" ", 4); - line.write_back('('); - if (ar.srclen>1) - line.write_back(ar.source + 1, ar.srclen - 1); - line.write_back(':'); - line.write_chars(ar.currentline); - line.write_back(')'); - } + line.write_back(" ", 4); + line.write_back('('); + if (ar.srclen>1) + line.write_back(ar.source + 1, ar.srclen - 1); + line.write_back(':'); + line.write_chars(ar.currentline); + line.write_back(')'); } log::instance().push_line(std::move(line)); return 0; @@ -189,7 +184,7 @@ static void table_tostring(std::string& res, lua_State* L, int index) index = lua_gettop(L) + index + 1; } - luaL_checkstack(L, LUA_MINSTACK, NULL); + luaL_checkstack(L, LUA_MINSTACK, nullptr); res.append("{"); lua_pushnil(L); while (lua_next(L, index)) @@ -238,7 +233,7 @@ static int lmoon_new_service(lua_State* L) luaL_checktype(L, 1, LUA_TTABLE); lua_service* S = lua_service::get(L); - std::unique_ptr conf = std::make_unique(); + auto conf = std::make_unique(); conf->creator = S->id(); int64_t session = S->next_sequence(); @@ -250,8 +245,7 @@ static int lmoon_new_service(lua_State* L) conf->unique = lua_opt_field(L, 1, "unique", false); conf->threadid = lua_opt_field(L, 1, "threadid", 0); - auto path = S->get_server()->get_env("PATH"); - if(path) + if(auto path = S->get_server()->get_env("PATH"); path) conf->params.append(*path); conf->params.append("return "); table_tostring(conf->params, L, 1); @@ -264,7 +258,7 @@ static int lmoon_new_service(lua_State* L) static int lmoon_kill(lua_State* L) { lua_service* S = lua_service::get(L); - uint32_t serviceid = (uint32_t)luaL_checkinteger(L, 1); + auto serviceid = (uint32_t)luaL_checkinteger(L, 1); if (S->id() == serviceid) S->ok(false); S->get_server()->remove_service(serviceid, S->id(), 0); @@ -274,7 +268,7 @@ static int lmoon_kill(lua_State* L) static int lmoon_scan_services(lua_State* L) { lua_service* S = lua_service::get(L); - uint32_t workerid = (uint32_t)luaL_checkinteger(L, 1); + auto workerid = (uint32_t)luaL_checkinteger(L, 1); int64_t sessionid = S->next_sequence(); S->get_server()->scan_services(S->id(), workerid, sessionid); lua_pushinteger(L, sessionid); @@ -283,7 +277,7 @@ static int lmoon_scan_services(lua_State* L) static int lmoon_queryservice(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); std::string_view name = lua_check(L, 1); uint32_t id = S->get_server()->get_unique_service(std::string{ name }); lua_pushinteger(L, id); @@ -299,7 +293,7 @@ static int lmoon_next_sequence(lua_State* L) static int lmoon_env(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); if(lua_gettop(L) == 2) { S->get_server()->set_env(lua_check(L, 1), lua_check(L, 2)); @@ -317,9 +311,8 @@ static int lmoon_env(lua_State* L) static int lmoon_server_stats(lua_State* L) { - lua_service* S = lua_service::get(L); - std::string_view opt = luaL_optstring(L, 1, ""); - if(opt == "service.count") + const lua_service* S = lua_service::get(L); + if(std::string_view opt = luaL_optstring(L, 1, ""); opt == "service.count") lua_pushinteger(L, S->get_server()->service_count()); else if(opt == "log.error") lua_pushinteger(L, log::instance().error_count()); @@ -332,15 +325,15 @@ static int lmoon_server_stats(lua_State* L) static int lmoon_exit(lua_State* L) { - lua_service* S = lua_service::get(L); - int32_t code = (int32_t)luaL_checkinteger(L, 1); + const lua_service* S = lua_service::get(L); + auto code = (int32_t)luaL_checkinteger(L, 1); S->get_server()->stop(code); return 0; } static int lmoon_now(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto ratio = luaL_optinteger(L, 1, 1); luaL_argcheck(L, ratio > 0, 1, "must >0"); time_t t = (S->get_server()->now()/ratio); @@ -350,7 +343,7 @@ static int lmoon_now(lua_State* L) static int lmoon_adjtime(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); time_t t = luaL_checkinteger(L, 1); bool ok = time::offset(t); S->get_server()->now(true); @@ -360,7 +353,7 @@ static int lmoon_adjtime(lua_State* L) static int message_decode(lua_State* L) { - message* m = (message*)lua_touserdata(L, 1); + auto* m = (message*)lua_touserdata(L, 1); if (nullptr == m) return luaL_argerror(L, 1, "lightuserdata(message*) expected"); size_t len = 0; @@ -403,8 +396,7 @@ static int message_decode(lua_State* L) } case 'C': { - buffer* buf = m->as_buffer(); - if (nullptr == buf) + if (buffer* buf = m->as_buffer();nullptr == buf) { lua_pushlightuserdata(L, nullptr); lua_pushinteger(L, 0); @@ -426,7 +418,7 @@ static int message_decode(lua_State* L) static int message_redirect(lua_State* L) { int top = lua_gettop(L); - message* m = (message*)lua_touserdata(L, 1); + auto* m = (message*)lua_touserdata(L, 1); if (nullptr == m) return luaL_argerror(L, 1, "lightuserdata(message*) expected"); m->set_receiver((uint32_t)luaL_checkinteger(L, 2)); @@ -483,7 +475,7 @@ extern "C" { }; luaL_newlib(L, l); - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); lua_pushinteger(L, S->id()); lua_setfield(L, -2, "id"); lua_pushlstring(L, S->name().data(), S->name().size()); @@ -496,10 +488,10 @@ extern "C" { static int lasio_try_open(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); std::string_view host = lua_check(L, 1); - uint16_t port = (uint16_t)luaL_checkinteger(L, 2); + auto port = (uint16_t)luaL_checkinteger(L, 2); bool is_connect = luaL_optboolean(L, 3, false); bool ok = sock.try_open(std::string{host}, port, is_connect); lua_pushboolean(L, ok ? 1 : 0); @@ -508,17 +500,17 @@ static int lasio_try_open(lua_State* L) static int lasio_listen(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); std::string_view host = lua_check(L, 1); - uint16_t port = (uint16_t)luaL_checkinteger(L, 2); - uint8_t type = (uint8_t)luaL_checkinteger(L, 3); - auto res = sock.listen(std::string{ host }, port, S->id(), type); - lua_pushinteger(L, res.first); - if (res.first > 0) + auto port = (uint16_t)luaL_checkinteger(L, 2); + auto type = (uint8_t)luaL_checkinteger(L, 3); + auto [k,v] = sock.listen(std::string{ host }, port, S->id(), type); + lua_pushinteger(L, k); + if (k > 0) { - lua_pushstring(L, res.second.address().to_string().data()); - lua_pushinteger(L, res.second.port()); + lua_pushstring(L, v.address().to_string().data()); + lua_pushinteger(L, v.port()); return 3; } return 1; @@ -528,8 +520,8 @@ static int lasio_accept(lua_State* L) { lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); - uint32_t owner = (uint32_t)luaL_checkinteger(L, 2); + auto fd = (uint32_t)luaL_checkinteger(L, 1); + auto owner = (uint32_t)luaL_checkinteger(L, 2); int64_t session = luaL_opt(L, luaL_checkinteger, 3, S->next_sequence()); if(!sock.accept(fd, session, owner)){ lua_pushboolean(L, 0); @@ -560,17 +552,17 @@ static int lasio_read(lua_State* L) lua_service* S = lua_service::get(L); int64_t session = S->next_sequence(); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); int64_t size = 0; std::string_view delim; if (lua_type(L, 2) == LUA_TNUMBER) { - size = (int64_t)luaL_checkinteger(L, 2); + size = luaL_checkinteger(L, 2); } else { delim = lua_check(L, 2); - size = (int64_t)luaL_optinteger(L, 3, 0); + size = luaL_optinteger(L, 3, 0); } auto res = sock.read(fd, size, delim, session); @@ -586,9 +578,9 @@ static int lasio_read(lua_State* L) static int lasio_write(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); auto n = static_cast(luaL_optinteger(L, 3, 0)); luaL_argcheck(L, n >= 0 && n < static_cast(moon::socket_send_mask::max_mask), 3, "invalid mask"); auto mask = static_cast(n); @@ -608,10 +600,10 @@ static int lasio_write(lua_State* L) static int lasio_write_message(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); - moon::message* m =(moon::message*)lua_touserdata(L, 2); + auto fd = (uint32_t)luaL_checkinteger(L, 1); + auto* m =(message*)lua_touserdata(L, 2); if (nullptr == m) return luaL_argerror(L, 2, "lightuserdata(message*) expected"); bool ok = sock.write(fd, m->into_buffer()); @@ -621,9 +613,9 @@ static int lasio_write_message(lua_State* L) static int lasio_close(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); bool ok = sock.close(fd); lua_pushboolean(L, ok ? 1 : 0); return 1; @@ -631,11 +623,11 @@ static int lasio_close(lua_State* L) static int lasio_switch_type(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); - uint8_t type = (uint8_t)luaL_checkinteger(L, 2); + auto fd = (uint32_t)luaL_checkinteger(L, 1); + auto type = (uint8_t)luaL_checkinteger(L, 2); bool ok = sock.switch_type(fd, type); lua_pushboolean(L, ok ? 1 : 0); return 1; @@ -643,10 +635,10 @@ static int lasio_switch_type(lua_State* L) static int lasio_settimeout(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); - uint32_t seconds = (uint32_t)luaL_checkinteger(L, 2); + auto fd = (uint32_t)luaL_checkinteger(L, 1); + auto seconds = (uint32_t)luaL_checkinteger(L, 2); bool ok = sock.settimeout(fd, seconds); lua_pushboolean(L, ok ? 1 : 0); return 1; @@ -654,9 +646,9 @@ static int lasio_settimeout(lua_State* L) static int lasio_setnodelay(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); bool ok = sock.setnodelay(fd); lua_pushboolean(L, ok ? 1 : 0); return 1; @@ -664,9 +656,9 @@ static int lasio_setnodelay(lua_State* L) static int lasio_set_enable_chunked(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); std::string_view flag = lua_check(L, 2); bool ok = sock.set_enable_chunked(fd, flag); lua_pushboolean(L, ok ? 1 : 0); @@ -675,9 +667,9 @@ static int lasio_set_enable_chunked(lua_State* L) static int lasio_set_send_queue_limit(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); uint16_t warnsize = moon::lua_check(L, 2); uint16_t errorsize = moon::lua_check(L, 3); bool ok = sock.set_send_queue_limit(fd, warnsize, errorsize); @@ -687,9 +679,9 @@ static int lasio_set_send_queue_limit(lua_State* L) static int lasio_address(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); std::string addr = sock.getaddress(fd); lua_pushlstring(L, addr.data(), addr.size()); return 1; @@ -697,7 +689,7 @@ static int lasio_address(lua_State* L) static int lasio_udp(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); size_t size = 0; const char* addr = lua_tolstring(L, 1, &size); @@ -715,9 +707,9 @@ static int lasio_udp(lua_State* L) static int lasio_udp_connect(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); auto ok = sock.udp_connect(fd, lua_check(L, 2), (asio::ip::port_type)luaL_checkinteger(L, 3)); lua_pushboolean(L, ok ? 1 : 0); return 1; @@ -725,9 +717,9 @@ static int lasio_udp_connect(lua_State* L) static int lasio_sendto(lua_State* L) { - lua_service* S = lua_service::get(L); + const lua_service* S = lua_service::get(L); auto& sock = S->get_worker()->socket_server(); - uint32_t fd = (uint32_t)luaL_checkinteger(L, 1); + auto fd = (uint32_t)luaL_checkinteger(L, 1); std::string_view address = lua_check(L, 2); bool ok = sock.send_to(fd, address, moon_to_shr_buffer(L, 3)); lua_pushboolean(L, ok ? 1 : 0); @@ -750,9 +742,9 @@ static int lasio_make_endpoint(lua_State* L) lua_pushlstring(L, message.data(), message.size()); return 2; } - char arr[moon::socket_server::addr_v6_size]; - size = moon::socket_server::encode_endpoint(arr, addr, port); - lua_pushlstring(L, arr, size); + + auto bytes = moon::socket_server::encode_endpoint(addr, port); + lua_pushlstring(L, bytes.data(), bytes.size()); return 1; } diff --git a/moon-src/core/network/base_connection.hpp b/moon-src/core/network/base_connection.hpp index 1fcb3e51..a064c1f6 100644 --- a/moon-src/core/network/base_connection.hpp +++ b/moon-src/core/network/base_connection.hpp @@ -34,9 +34,7 @@ namespace moon base_connection& operator=(const base_connection&) = delete; - virtual ~base_connection() - { - } + virtual ~base_connection() = default; virtual void start(role r) { @@ -52,7 +50,7 @@ namespace moon return direct_read_result{false, { "Unsupported read operation" } }; }; - virtual bool send(buffer_shr_ptr_t&& data) + virtual bool send(buffer_shr_ptr_t data) { if (!socket_.is_open()) { @@ -239,7 +237,7 @@ namespace moon str.append(")"); } std::string content = - moon::format("{\"addr\":\"%s\",\"code\":%d,\"message\":\"%s\"}", address().data(), e.value(), str.data()); + moon::format(R"({"addr":"%s","code":%d,"message":"%s"})", address().data(), e.value(), str.data()); message msg{}; msg.set_type(type_); diff --git a/moon-src/core/network/error.hpp b/moon-src/core/network/error.hpp index df95ddcb..5658e998 100644 --- a/moon-src/core/network/error.hpp +++ b/moon-src/core/network/error.hpp @@ -192,7 +192,7 @@ namespace moon { static detail::error_codes const cat{}; return std::error_code{ static_cast< - std::underlying_type::type>(e), cat }; + std::underlying_type_t>(e), cat }; } inline std::error_condition @@ -200,6 +200,6 @@ namespace moon { static detail::error_conditions const cat{}; return std::error_condition{ static_cast< - std::underlying_type::type>(c), cat }; + std::underlying_type_t>(c), cat }; } } \ No newline at end of file diff --git a/moon-src/core/network/moon_connection.hpp b/moon-src/core/network/moon_connection.hpp index 6e59b337..923357a6 100644 --- a/moon-src/core/network/moon_connection.hpp +++ b/moon-src/core/network/moon_connection.hpp @@ -32,7 +32,7 @@ namespace moon read_header(); } - bool send(buffer_shr_ptr_t&& data) override + bool send(buffer_shr_ptr_t data) override { if (data->size() >= MESSAGE_CONTINUED_FLAG && !enum_has_any_bitmask(flag_, enable_chunked::send)) { @@ -171,7 +171,7 @@ namespace moon read_header(); } - protected: + private: enable_chunked flag_; buffer cache_; buffer_ptr_t data_; diff --git a/moon-src/core/network/socket_server.cpp b/moon-src/core/network/socket_server.cpp index 733b4235..8a1f593e 100644 --- a/moon-src/core/network/socket_server.cpp +++ b/moon-src/core/network/socket_server.cpp @@ -66,7 +66,7 @@ std::pair socket_server::listen(const std::string & hos ctx->reset_reserve(); auto id = server_->nextfd(); ctx->fd = id; - acceptors_.emplace(id, ctx); + acceptors_.try_emplace(id, ctx); return std::make_pair(id, ctx->acceptor.local_endpoint()); } catch (const asio::system_error& e) @@ -94,7 +94,7 @@ uint32_t socket_server::udp_open(uint32_t owner, std::string_view host, uint16_t auto id = server_->nextfd(); ctx->fd = id; do_receive(ctx); - udp_.emplace(id, std::move(ctx)); + udp_.try_emplace(id, std::move(ctx)); return id; } catch (const asio::system_error& e) @@ -132,7 +132,7 @@ bool socket_server::accept(uint32_t fd, int64_t sessionid, uint32_t owner) return false; } - auto& ctx = iter->second; + auto const& ctx = iter->second; if (!ctx->acceptor.is_open()) { return false; @@ -166,12 +166,9 @@ bool socket_server::accept(uint32_t fd, int64_t sessionid, uint32_t owner) if (e == asio::error::operation_aborted) return; - if (e == asio::error::no_descriptors) + if (e == asio::error::no_descriptors && ctx->reserve.is_open()) { - if (ctx->reserve.is_open()) - { - ctx->reserve.close(); - } + ctx->reserve.close(); } response(ctx->fd, ctx->owner, moon::format("socket_server::accept %s(%d)", e.message().data(), e.value()), @@ -186,64 +183,67 @@ bool socket_server::accept(uint32_t fd, int64_t sessionid, uint32_t owner) return true; } -void socket_server::connect(const std::string& host, uint16_t port, uint32_t owner, uint8_t type, int64_t sessionid, uint32_t millseconds) +void socket_server::connect(const std::string &host, uint16_t port, uint32_t owner, uint8_t type, int64_t sessionid, uint32_t millseconds) { - std::shared_ptr resolver = std::make_shared(context_); + struct connect_params + { + uint16_t port; + uint32_t owner; + int64_t millseconds; + int64_t sessionid; + std::string host; + }; + + auto params = std::make_shared(connect_params{port, owner, millseconds, sessionid, host}); + + auto conn = make_connection(owner, type, tcp::socket(context_)); + + if (millseconds > 0) + { + auto timer = std::make_unique(context_); + timer->expires_after(std::chrono::milliseconds(millseconds)); + timer->async_wait([this, params, conn, _ = std::move(timer)](const asio::error_code &ec) + { + if (ec) + return; + if(conn->fd() == 0){ + conn->close(); + response(0, params->owner, moon::format("connect %s:%d timeout", params->host.data(), params->port), params->sessionid, PTYPE_ERROR); + } }); + } + + auto resolver = std::make_unique(context_); resolver->async_resolve(host, std::to_string(port), - [this, millseconds, type, owner, sessionid, host, port, resolver](const asio::error_code& ec, tcp::resolver::results_type results) + [this, params, resolver = std::move(resolver), conn = std::move(conn)](const asio::error_code &ec, tcp::resolver::results_type results) mutable { + if (params->millseconds > 0 && conn.use_count() == 1) // has timeout timer + return; + if (!ec) { - auto c = make_connection(owner, type, tcp::socket(context_)); - std::shared_ptr timer; - if (millseconds > 0) - { - timer = std::make_shared(context_); - timer->expires_after(std::chrono::milliseconds(millseconds)); - timer->async_wait([this, c, owner, sessionid, host, port, timer](const asio::error_code& ec) { - if (!ec) - { - // The timer may have expired, but the callback function has not yet been called(asio's complete-queue).(0 == timer->cancel()). - // Only trigger error code when socket not connected : - if (c->fd() == 0) - { - c->close(); - response(0, owner, moon::format("connect %s:%d timeout", host.data(), port), sessionid, PTYPE_ERROR); - } - } - }); - } - - asio::async_connect(c->socket(), results, - [this, c, host, port, owner, sessionid, timer](const asio::error_code& ec, const tcp::endpoint&) + auto &socket = conn->socket(); + asio::async_connect(socket, results, + [this, params, conn = std::move(conn)](const asio::error_code &ec, const tcp::endpoint &) { - size_t cancelled_timer = 1; - if (timer) - { - try { - cancelled_timer = timer->cancel(); - } - catch (...) { - } - } + if (params->millseconds > 0 && conn.use_count() == 1) // has timeout timer + return; if (!ec) { - c->fd(server_->nextfd()); - connections_.emplace(c->fd(), c); - c->start(base_connection::role::client); - response(0, owner, std::to_string(c->fd()), sessionid, PTYPE_INTEGER); + conn->fd(server_->nextfd()); + connections_.try_emplace(conn->fd(), conn); + conn->start(base_connection::role::client); + response(0, params->owner, std::to_string(conn->fd()), params->sessionid, PTYPE_INTEGER); } else { - if(cancelled_timer>0) - response(0, owner, moon::format("connect %s:%d %s(%d)", host.data(), port, ec.message().data(), ec.value()), sessionid, PTYPE_ERROR); + response(0, params->owner, moon::format("connect %s:%d %s(%d)", params->host.data(), params->port, ec.message().data(), ec.value()), params->sessionid, PTYPE_ERROR); } }); } else { - response(0, owner, moon::format("resolve %s:%d %s(%d)", host.data(), port, ec.message().data(), ec.value()), sessionid, PTYPE_ERROR); + response(0, params->owner, moon::format("resolve %s:%d %s(%d)", params->host.data(), params->port, ec.message().data(), ec.value()), params->sessionid, PTYPE_ERROR); } }); } @@ -257,7 +257,7 @@ direct_read_result socket_server::read(uint32_t fd, size_t n, std::string_view d return direct_read_result{ false, { "socket.read: closed" } }; } -bool socket_server::write(uint32_t fd, buffer_shr_ptr_t&& data, socket_send_mask mask) +bool socket_server::write(uint32_t fd, buffer_shr_ptr_t data, socket_send_mask mask) { if (nullptr == data || 0 == data->size()) return false; @@ -270,10 +270,12 @@ bool socket_server::write(uint32_t fd, buffer_shr_ptr_t&& data, socket_send_mask if (auto iter = udp_.find(fd); iter != udp_.end()) { + auto buf = asio::buffer(data->data(), data->size()); iter->second->sock.async_send( - asio::buffer(data->data(), data->size()), - [data, ctx = iter->second](std::error_code /*ec*/, std::size_t /*bytes_sent*/) + buf, + [_ = std::move(data), ctx = iter->second](std::error_code /*ec*/, std::size_t /*bytes_sent*/) { + //do nothing }); return true; } @@ -309,21 +311,21 @@ bool socket_server::close(uint32_t fd) return false; } -void socket_server::close_all() +void socket_server::close_all() const { - for (auto& c : connections_) + for (const auto& [_, v] : connections_) { - c.second->close(); + v->close(); } - for (auto& c : udp_) + for (const auto& [_, v] : udp_) { - c.second->sock.close(); + v->sock.close(); } - for (auto& ac : acceptors_) + for (const auto& [_, v] : acceptors_) { - ac.second->close(); + v->close(); } } @@ -417,7 +419,7 @@ static bool decode_endpoint(std::string_view address, udp::endpoint& ep) return true; } -bool socket_server::send_to(uint32_t host, std::string_view address, buffer_shr_ptr_t&& data) +bool socket_server::send_to(uint32_t host, std::string_view address, buffer_shr_ptr_t data) { if (address.empty()) return false; @@ -426,10 +428,13 @@ bool socket_server::send_to(uint32_t host, std::string_view address, buffer_shr_ udp::endpoint ep; if (!decode_endpoint(address, ep)) return false; + + auto buf = asio::buffer(data->data(), data->size()); iter->second->sock.async_send_to( - asio::buffer(data->data(), data->size()), ep, - [data, ctx = iter->second](std::error_code /*ec*/, std::size_t /*bytes_sent*/) + buf, ep, + [_ = std::move(data), ctx = iter->second](std::error_code /*ec*/, std::size_t /*bytes_sent*/) { + //do nothing }); return true; } @@ -461,15 +466,17 @@ bool moon::socket_server::switch_type(uint32_t fd, uint8_t new_type) return false; } -size_t socket_server::encode_endpoint(char* buf, const address& addr, port_type port) +std::array +socket_server::encode_endpoint(const address& addr, port_type port) { + std::array buf{}; size_t size = 0; if (addr.is_v4()) { buf[0] = '4'; size+=1; auto bytes = addr.to_v4().to_bytes(); - memcpy(buf + size, bytes.data(), bytes.size()); + memcpy(buf.data() + size, bytes.data(), bytes.size()); size += bytes.size(); } else if (addr.is_v6()) @@ -477,12 +484,11 @@ size_t socket_server::encode_endpoint(char* buf, const address& addr, port_type buf[0] = '6'; size += 1; auto bytes = addr.to_v6().to_bytes(); - memcpy(buf + size, bytes.data(), bytes.size()); + memcpy(buf.data() + size, bytes.data(), bytes.size()); size += bytes.size(); } - memcpy(buf + size, &port, sizeof(port)); - size += sizeof(port); - return size; + memcpy(buf.data() + size, &port, sizeof(port)); + return buf; } connection_ptr_t socket_server::make_connection(uint32_t serviceid, uint8_t type, tcp::socket&& sock) @@ -532,7 +538,7 @@ void socket_server::response(uint32_t sender, uint32_t receiver, std::string_vie void socket_server::add_connection(socket_server* from, const acceptor_context_ptr_t& ctx, const connection_ptr_t & c, int64_t sessionid) { asio::dispatch(context_, [this, from, ctx, c, sessionid] { - connections_.emplace(c->fd(), c); + connections_.try_emplace(c->fd(), c); c->start(base_connection::role::server); if (sessionid != 0) @@ -546,7 +552,7 @@ void socket_server::add_connection(socket_server* from, const acceptor_context_p service* socket_server::find_service(uint32_t serviceid) { - return worker_->find_service(serviceid);; + return worker_->find_service(serviceid); } void socket_server::timeout() @@ -559,9 +565,9 @@ void socket_server::timeout() } auto now = base_connection::now(); - for (auto& connection : connections_) + for (const auto& [_, v] : connections_) { - connection.second->timeout(now); + v->timeout(now); } timeout(); }); @@ -578,18 +584,17 @@ void socket_server::do_receive(const udp_context_ptr_t& ctx) buf->commit(addr_v6_size); buf->seek(addr_v6_size, buffer::seek_origin::Begin); - auto space = buf->writeable(); + auto [k,v] = buf->writeable(); ctx->sock.async_receive_from( - asio::buffer(space.first, space.second), ctx->from_ep, + asio::buffer(k, v), ctx->from_ep, [this, ctx](std::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd >0) { - auto buf = ctx->msg.as_buffer(); - buf->commit(bytes_recvd); - char arr[32]; - size_t size = encode_endpoint(arr, ctx->from_ep.address(), ctx->from_ep.port()); - buf->write_front(arr, size); + auto b = ctx->msg.as_buffer(); + b->commit(bytes_recvd); + auto bytes = encode_endpoint(ctx->from_ep.address(), ctx->from_ep.port()); + b->write_front(bytes.data(), bytes.size()); ctx->msg.set_sender(ctx->fd); ctx->msg.set_receiver(0); ctx->msg.set_type(PTYPE_SOCKET_UDP); diff --git a/moon-src/core/network/socket_server.h b/moon-src/core/network/socket_server.h index af3841e6..b48dbea9 100644 --- a/moon-src/core/network/socket_server.h +++ b/moon-src/core/network/socket_server.h @@ -57,14 +57,12 @@ namespace moon static constexpr size_t READ_BUFFER_SIZE = 2048; udp_context(uint32_t o, asio::io_context& ioc, udp::endpoint ep) :owner(o) - , msg(READ_BUFFER_SIZE) , sock(ioc, ep) { } udp_context(uint32_t o, asio::io_context& ioc) :owner(o) - , msg(READ_BUFFER_SIZE) , sock(ioc, udp::endpoint(udp::v4(), 0)) { } @@ -72,7 +70,7 @@ namespace moon bool closed = false; uint32_t owner; uint32_t fd = 0; - message msg; + message msg{READ_BUFFER_SIZE}; udp::socket sock; udp::endpoint from_ep; }; @@ -102,11 +100,11 @@ namespace moon direct_read_result read(uint32_t fd, size_t n, std::string_view delim, int64_t sessionid); - bool write(uint32_t fd, buffer_shr_ptr_t&& data, socket_send_mask mask = socket_send_mask::none); + bool write(uint32_t fd, buffer_shr_ptr_t data, socket_send_mask mask = socket_send_mask::none); bool close(uint32_t fd); - void close_all(); + void close_all() const; bool settimeout(uint32_t fd, uint32_t seconds); @@ -116,13 +114,14 @@ namespace moon bool set_send_queue_limit(uint32_t fd, uint16_t warnsize, uint16_t errorsize); - bool send_to(uint32_t host, std::string_view address, buffer_shr_ptr_t&& data); + bool send_to(uint32_t host, std::string_view address, buffer_shr_ptr_t data); std::string getaddress(uint32_t fd); bool switch_type(uint32_t fd, uint8_t new_type); - static size_t encode_endpoint(char* buf, const address& addr, port_type port); + static std::array + encode_endpoint(const address& addr, port_type port); private: connection_ptr_t make_connection(uint32_t serviceid, uint8_t type, tcp::socket&& sock); diff --git a/moon-src/core/network/streambuf.hpp b/moon-src/core/network/streambuf.hpp index b7f81db7..adaf6a46 100644 --- a/moon-src/core/network/streambuf.hpp +++ b/moon-src/core/network/streambuf.hpp @@ -8,35 +8,13 @@ namespace moon class streambuf { public: - typedef asio::const_buffer const_buffers_type; - typedef asio::mutable_buffer mutable_buffers_type; + using const_buffers_type = asio::const_buffer; + using mutable_buffers_type = asio::mutable_buffer; - streambuf(buffer_t* buf, std::size_t maxsize = (std::numeric_limits::max)()) + streambuf(buffer_t* buf, std::size_t maxsize = std::numeric_limits::max()) :buffer_(buf) , max_size_(maxsize) { - - } - - streambuf(const streambuf&) = delete; - - streambuf& operator=(const streambuf&) = delete; - - streambuf(streambuf&& other) noexcept - :buffer_(other.buffer_) - , max_size_(other.max_size_) - { - other.buffer_ = nullptr; - other.max_size_ = 0; - } - - streambuf& operator=(streambuf&& other) noexcept - { - buffer_ = other.buffer_; - max_size_ = other.max_size_; - other.buffer_ = nullptr; - other.max_size_ = 0; - return *this; } std::size_t size() const noexcept @@ -65,8 +43,8 @@ namespace moon mutable_buffers_type prepare(std::size_t n) { if (nullptr == buffer_) return asio::mutable_buffer{nullptr, 0}; - auto space = buffer_->prepare(n); - return asio::mutable_buffer{space.first, space.second}; + auto [k, v] = buffer_->prepare(n); + return asio::mutable_buffer{k, v}; } void commit(std::size_t n) diff --git a/moon-src/core/network/ws_connection.hpp b/moon-src/core/network/ws_connection.hpp index 3980beba..5865c828 100644 --- a/moon-src/core/network/ws_connection.hpp +++ b/moon-src/core/network/ws_connection.hpp @@ -264,7 +264,7 @@ namespace moon T result = 0; for (size_t i = 0; i < sizeof(T); ++i) { - result = (result << 8) | data[i]; + result = (result << 8) | static_cast(data[i]); } return result; } @@ -282,7 +282,7 @@ namespace moon return read_payload(2); } - const uint8_t* frame_data = (const uint8_t*)(cache_.data()); + auto frame_data = (const uint8_t*)(cache_.data()); size_t header_size = 2; ws::frame_header fh{}; @@ -438,7 +438,7 @@ namespace moon if (fh.mask) { // unmask data: - uint8_t* d = (uint8_t*)data_->data(); + auto d = (uint8_t*)data_->data(); size_t size = data_->size(); for (size_t i = 0; i < size; ++i) { @@ -451,7 +451,7 @@ namespace moon return error(make_error_code(moon::error::ws_closed), std::string{data_->data(), data_->size()}); } - message msg = message{ std::move(data_) }; + auto msg = message{ std::move(data_) }; msg.set_type(type_); switch (fh.op) diff --git a/moon-src/core/server.cpp b/moon-src/core/server.cpp index f467ac66..dd08865c 100644 --- a/moon-src/core/server.cpp +++ b/moon-src/core/server.cpp @@ -26,7 +26,7 @@ namespace moon timer_.emplace_back(std::make_unique()); } - for (auto& w : workers_) + for (const auto& w : workers_) { w->run(); } @@ -46,15 +46,15 @@ namespace moon { now_ = time::now(); - if (exitcode_ < 0 ) + if (exitcode_.load(std::memory_order_acquire) < 0 ) { break; } - if (exitcode_ != std::numeric_limits::max() && !stop_once) + if (exitcode_.load(std::memory_order_acquire) != std::numeric_limits::max() && !stop_once) { stop_once = true; - CONSOLE_WARN("Received signal code %d", exitcode_); + CONSOLE_WARN("Received signal code %d", exitcode_.load(std::memory_order_acquire)); for (auto iter = workers_.rbegin(); iter != workers_.rend(); ++iter) { (*iter)->stop(); @@ -78,7 +78,7 @@ namespace moon } } - for (auto& t : timer_) + for (const auto& t : timer_) { t->update(now_); } @@ -86,14 +86,14 @@ namespace moon timer.wait(ignore); } wait(); - if(exitcode_ == std::numeric_limits::max()) - exitcode_ = 0; - return exitcode_; + if(exitcode_.load(std::memory_order_acquire) == std::numeric_limits::max()) + exitcode_.store(0, std::memory_order_release); + return exitcode_.load(); } void server::stop(int exitcode) { - exitcode_ = exitcode; + exitcode_.store(exitcode, std::memory_order_release); } void server::wait() @@ -173,7 +173,7 @@ namespace moon worker* server::get_worker(uint32_t workerid, uint32_t serviceid) const { workerid = workerid? workerid: worker_id(serviceid); - if ((workerid == 0 || workerid > static_cast(workers_.size()))) + if (workerid == 0 || workerid > static_cast(workers_.size())) { return nullptr; } @@ -192,7 +192,7 @@ namespace moon timer_[workerid-1]->add(now_+ interval, serviceid, timerid, this); } - void server::on_timer(uint32_t serviceid, int64_t timerid) + void server::on_timer(uint32_t serviceid, int64_t timerid) const { auto msg = message::with_empty(); msg.set_type(PTYPE_TIMER); @@ -215,7 +215,7 @@ namespace moon w->new_service(std::move(conf)); } - void server::remove_service(uint32_t serviceid, uint32_t sender, int64_t sessionid) + void server::remove_service(uint32_t serviceid, uint32_t sender, int64_t sessionid) const { worker* w = get_worker(0, serviceid); if (nullptr != w) @@ -254,7 +254,7 @@ namespace moon bool server::send(uint32_t sender, uint32_t receiver, buffer_ptr_t data, int64_t sessionid, uint8_t type) const { sessionid = -sessionid; - message m = message{ std::move(data) }; + message m{std::move(data)}; m.set_sender(sender); m.set_receiver(receiver); m.set_type(type); @@ -275,7 +275,7 @@ namespace moon bool server::register_service(const std::string& type, register_func f) { - auto ret = regservices_.emplace(type, f); + auto ret = regservices_.try_emplace(type, f); MOON_ASSERT(ret.second , moon::format("already registed service type[%s].", type.data()).data()); return ret.second; @@ -283,8 +283,7 @@ namespace moon service_ptr_t server::make_service(const std::string& type) { - auto iter = regservices_.find(type); - if (iter != regservices_.end()) + if (auto iter = regservices_.find(type); iter != regservices_.end()) { return iter->second(); } @@ -293,8 +292,7 @@ namespace moon std::shared_ptr server::get_env(const std::string& name) const { - std::shared_ptr value; - if (env_.try_get_value(name, value)) + if (std::shared_ptr value; env_.try_get_value(name, value)) { return value; } diff --git a/moon-src/core/server.h b/moon-src/core/server.h index 802ad7ca..e7c60886 100644 --- a/moon-src/core/server.h +++ b/moon-src/core/server.h @@ -17,7 +17,7 @@ namespace moon timer_expire_policy(uint32_t serviceid, int64_t timerid, server* srv) : serviceid_(serviceid), timerid_(timerid), server_(srv) {} - void operator()() + void operator()() const { server_->on_timer(serviceid_, timerid_); } @@ -69,7 +69,7 @@ namespace moon void new_service(std::unique_ptr conf); - void remove_service(uint32_t serviceid, uint32_t sender, int64_t sessionid); + void remove_service(uint32_t serviceid, uint32_t sender, int64_t sessionid) const; void scan_services(uint32_t sender, uint32_t workerid, int64_t sessionid) const; @@ -104,11 +104,11 @@ namespace moon size_t socket_num() const; private: - void on_timer(uint32_t serviceid, int64_t timerid); + void on_timer(uint32_t serviceid, int64_t timerid) const; void wait(); private: - volatile int exitcode_ = std::numeric_limits::max(); + std::atomic_int32_t exitcode_ = std::numeric_limits::max(); std::atomic state_ = state::unknown; std::atomic fd_seq_ = 1; std::time_t now_ = 0; diff --git a/moon-src/core/worker.cpp b/moon-src/core/worker.cpp index 6a7aa2dd..bc46e5f5 100644 --- a/moon-src/core/worker.cpp +++ b/moon-src/core/worker.cpp @@ -255,12 +255,12 @@ namespace moon CONSOLE_DEBUG("Dead service [%08X] recv message from [%08X]: %s.", receiver, sender, - moon::hex_string({ msg.data(),msg.size() }).data() + moon::escape_non_printable({ msg.data(),msg.size() }).data() ); }else{ std::string str = moon::format("Attemp call dead service [%08X]: %s." , receiver - , moon::hex_string({ msg.data(),msg.size() }).data()); + , moon::escape_non_printable({ msg.data(),msg.size() }).data()); msg.set_sessionid(-msg.sessionid()); server_->response(sender, str, msg.sessionid(), PTYPE_ERROR); }