diff options
author | Sadie Powell <sadie@witchery.services> | 2024-03-11 13:53:05 +0000 |
---|---|---|
committer | Sadie Powell <sadie@witchery.services> | 2024-03-11 19:17:29 +0000 |
commit | 29e7674e56bf2b829bba22def2760d034a76e788 (patch) | |
tree | f40049ba995b03dd7c510d88f9f19db2d2e65a2e | |
parent | e2df7d4d01f8fdb41c49ce8efc462cab005e7d5c (diff) |
Replace convertTo/stringify with non-throwing alternatives.
Having these throw is terrible for ergonomics and there are loads
of places where the exception was either silently ignored or not
handled at all. Having a function which returns an optional and
another that returns a default works a lot better imo.
76 files changed, 573 insertions, 811 deletions
diff --git a/include/anope.h b/include/anope.h index fd3728d84..c4a2079aa 100644 --- a/include/anope.h +++ b/include/anope.h @@ -39,6 +39,7 @@ namespace Anope typedef std::string::reverse_iterator reverse_iterator; typedef std::string::const_reverse_iterator const_reverse_iterator; typedef std::string::size_type size_type; + typedef std::string::value_type value_type; static const size_type npos = static_cast<size_type>(-1); /** @@ -729,72 +730,6 @@ public: virtual ~ModuleException() noexcept = default; }; -class CoreExport ConvertException final - : public CoreException -{ -public: - ConvertException(const Anope::string &reason = "") : CoreException(reason) { } - - virtual ~ConvertException() noexcept = default; -}; - -/** Convert something to a string - */ -inline Anope::string stringify(const Anope::string &x) -{ - return x; -} - -template<typename T> inline Anope::string stringify(const T &x) -{ - std::ostringstream stream; - - if (!(stream << x)) - throw ConvertException("Stringify fail"); - - return stream.str(); -} - -template<typename T> inline void convert(const Anope::string &s, T &x, Anope::string &leftover, bool failIfLeftoverChars = true) -{ - leftover.clear(); - std::istringstream i(s.str()); - char c; - if (!(i >> x)) - throw ConvertException("Convert fail"); - if (failIfLeftoverChars) - { - if (i.get(c)) - throw ConvertException("Convert fail"); - } - else - { - std::string left; - getline(i, left); - leftover = left; - } -} - -template<typename T> inline void convert(const Anope::string &s, T &x, bool failIfLeftoverChars = true) -{ - Anope::string Unused; - convert(s, x, Unused, failIfLeftoverChars); -} - -template<typename T> inline T convertTo(const Anope::string &s, Anope::string &leftover, bool failIfLeftoverChars = true) -{ - T x; - convert(s, x, leftover, failIfLeftoverChars); - return x; -} - -template<typename T> inline T convertTo(const Anope::string &s, bool failIfLeftoverChars = true) -{ - T x; - convert(s, x, failIfLeftoverChars); - return x; -} - /** Casts to be used instead of dynamic_cast, this uses dynamic_cast * for debug builds and static_cast on release builds * to speed up the program because dynamic_cast relies on RTTI. @@ -814,3 +749,5 @@ template<typename T, typename O> inline T anope_dynamic_static_cast(O ptr) return static_cast<T>(ptr); } #endif + +#include "convert.h" diff --git a/include/config.h b/include/config.h index 022ee503d..652d42a7a 100644 --- a/include/config.h +++ b/include/config.h @@ -46,14 +46,7 @@ namespace Configuration template<typename T> T Get(const Anope::string &tag, const Anope::string &def = "") const { - const Anope::string &value = this->Get<const Anope::string>(tag, def); - if (!value.empty()) - try - { - return convertTo<T>(value); - } - catch (const ConvertException &) { } - return T(); + return Anope::TryConvert<T>(this->Get<const Anope::string>(tag, def)).value_or(T()); } bool Set(const Anope::string &tag, const Anope::string &value); diff --git a/include/convert.h b/include/convert.h new file mode 100644 index 000000000..3cdbcd787 --- /dev/null +++ b/include/convert.h @@ -0,0 +1,133 @@ +/* + * + * (C) 2003-2024 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + */ + +#pragma once + +#include <optional> + +namespace Anope +{ + /** Attempts to convert a string to any type. + * @param in The value to convert. + * @param leftover If non-nullptr then the location to store leftover data. + */ + template<typename T> + inline std::optional<T> TryConvert(const Anope::string &in, Anope::string *leftover = nullptr) + { + std::istringstream tmp(in.str()); + T out; + if (!(tmp >> out)) + return std::nullopt; + + if (leftover) + { + std::string extra; + std::getline(tmp, extra); + *leftover = extra; + } + else + { + char extra; + if (tmp >> extra) + return std::nullopt; + } + return out; + } + + /** Converts a string to any type. + * @param in The value to convert. + * @param def The default to use if the conversion failed. + * @param leftover If non-nullptr then the location to store leftover data. + */ + template<typename T> + inline T Convert(const Anope::string &in, T def, Anope::string *leftover = nullptr) + { + return TryConvert<T>(in, leftover).value_or(def); + } + + /** Attempts to convert any type to a string. + * @param in The value to convert. + */ + template <class T> + inline std::optional<Anope::string> TryString(const T &in) + { + std::ostringstream tmp; + if (!(tmp << in)) + return std::nullopt; + return tmp.str(); + } + + /** No-op function that returns the string that was passed to it. + * @param in The string to return. + */ + inline const string &ToString(const string &in) + { + return in; + } + + /** Converts a std::string to a string. + * @param in The value to convert. + */ + inline string ToString(const std::string &in) + { + return in; + } + + /** Converts a char array to a string. + * @param in The value to convert. + */ + inline string ToString(const char *in) + { + return string(in); + } + + /** Converts a char to a string. + * @param in The value to convert. + */ + inline string ToString(char in) + { + return string(1, static_cast<string::value_type>(in)); + } + + /** Converts an unsigned char to a string. + * @param in The value to convert. + */ + inline string ToString(unsigned char in) + { + return string(1, static_cast<string::value_type>(in)); + } + + /** Converts a bool to a string. + * @param in The value to convert. + */ + inline string ToString(bool in) + { + return (in ? "1" : "0"); + } + + /** Converts a type that std::to_string is implemented for to a string. + * @param in The value to convert. + */ + template<typename Stringable> + inline std::enable_if_t<std::is_arithmetic_v<Stringable>, string> ToString(const Stringable &in) + { + return std::to_string(in); + } + + /** Converts any type to a string. + * @param in The value to convert. + */ + template <class T> + inline std::enable_if_t<!std::is_arithmetic_v<T>, string> ToString(const T &in) + { + return TryString(in).value_or(Anope::string()); + } +} diff --git a/include/modules/sql.h b/include/modules/sql.h index 8ac03803f..4c1b7d455 100644 --- a/include/modules/sql.h +++ b/include/modules/sql.h @@ -128,13 +128,12 @@ namespace SQL template<typename T> void SetValue(const Anope::string &key, const T &value, bool escape = true) { - try - { - Anope::string string_value = stringify(value); - this->parameters[key].data = string_value; - this->parameters[key].escape = escape; - } - catch (const ConvertException &ex) { } + auto str = Anope::TryString(value); + if (!str.has_value()) + return; + + this->parameters[key].data = str.value(); + this->parameters[key].escape = escape; } }; diff --git a/include/protocol.h b/include/protocol.h index 88bb94bfc..612593c89 100644 --- a/include/protocol.h +++ b/include/protocol.h @@ -164,14 +164,14 @@ public: template <typename... Args> void SendMode(const MessageSource &source, Channel *chan, const Anope::string &modes, Args &&...args) { - SendModeInternal(source, chan, modes, { stringify(args)... }); + SendModeInternal(source, chan, modes, { Anope::ToString(args)... }); } virtual void SendModeInternal(const MessageSource &source, User *u, const Anope::string &modes, const std::vector<Anope::string> &values); template <typename... Args> void SendMode(const MessageSource &source, User *u, const Anope::string &modes, Args &&...args) { - SendModeInternal(source, u, modes, { stringify(args)... }); + SendModeInternal(source, u, modes, { Anope::ToString(args)... }); } /** Introduces a client to the rest of the network @@ -258,7 +258,7 @@ public: template <typename... Args> void SendNumeric(int numeric, const Anope::string &dest, Args &&...args) { - SendNumericInternal(numeric, dest, { stringify(args)... }); + SendNumericInternal(numeric, dest, { Anope::ToString(args)... }); } virtual void SendLogin(User *u, NickAlias *na) = 0; diff --git a/include/uplink.h b/include/uplink.h index 12365dd65..924c05cfc 100644 --- a/include/uplink.h +++ b/include/uplink.h @@ -23,25 +23,25 @@ namespace Uplink template<typename... Args> void Send(const Anope::map<Anope::string> &tags, const MessageSource &source, const Anope::string &command, Args &&...args) { - SendInternal(tags, source, command, { stringify(args)... }); + SendInternal(tags, source, command, { Anope::ToString(args)... }); } template<typename... Args> void Send(const Anope::map<Anope::string> &tags, const Anope::string &command, Args &&...args) { - SendInternal(tags, Me, command, { stringify(args)... }); + SendInternal(tags, Me, command, { Anope::ToString(args)... }); } template<typename... Args> void Send(const MessageSource &source, const Anope::string &command, Args &&...args) { - SendInternal({}, source, command, { stringify(args)... }); + SendInternal({}, source, command, { Anope::ToString(args)... }); } template<typename... Args> void Send(const Anope::string &command, Args &&...args) { - SendInternal({}, Me, command, { stringify(args)... }); + SendInternal({}, Me, command, { Anope::ToString(args)... }); } } diff --git a/modules/botserv/botserv.cpp b/modules/botserv/botserv.cpp index d2b8df4bb..706865522 100644 --- a/modules/botserv/botserv.cpp +++ b/modules/botserv/botserv.cpp @@ -67,12 +67,8 @@ public: Anope::string Limit; unsigned limit = 0; - try - { - if (c->GetParam("LIMIT", Limit)) - limit = convertTo<unsigned>(Limit); - } - catch (const ConvertException &) { } + if (c->GetParam("LIMIT", Limit)) + limit = Anope::Convert<unsigned>(Limit, limit); /* Should we be invited? */ if (c->HasMode("INVITE") || (limit && c->users.size() >= limit)) diff --git a/modules/botserv/bs_badwords.cpp b/modules/botserv/bs_badwords.cpp index 5dee8ed2c..09e96564b 100644 --- a/modules/botserv/bs_badwords.cpp +++ b/modules/botserv/bs_badwords.cpp @@ -222,7 +222,7 @@ private: const BadWord *b = bw->GetBadWord(Number - 1); ListFormatter::ListEntry entry; - entry["Number"] = stringify(Number); + entry["Number"] = Anope::ToString(Number); entry["Word"] = b->word; entry["Type"] = b->type == BW_SINGLE ? "(SINGLE)" : (b->type == BW_START ? "(START)" : (b->type == BW_END ? "(END)" : "")); this->list.AddEntry(entry); @@ -241,7 +241,7 @@ private: continue; ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Word"] = b->word; entry["Type"] = b->type == BW_SINGLE ? "(SINGLE)" : (b->type == BW_START ? "(START)" : (b->type == BW_END ? "(END)" : "")); list.AddEntry(entry); diff --git a/modules/botserv/bs_info.cpp b/modules/botserv/bs_info.cpp index c8e05577b..b4a5592b1 100644 --- a/modules/botserv/bs_info.cpp +++ b/modules/botserv/bs_info.cpp @@ -55,7 +55,7 @@ public: info[_("Real name")] = bi->realname; info[_("Created")] = Anope::strftime(bi->created, source.GetAccount()); info[_("Options")] = bi->oper_only ? _("Private") : _("None"); - info[_("Used on")] = stringify(bi->GetChannelCount()) + " channel(s)"; + info[_("Used on")] = Anope::ToString(bi->GetChannelCount()) + " channel(s)"; FOREACH_MOD(OnBotInfo, (source, bi, ci, info)); diff --git a/modules/botserv/bs_kick.cpp b/modules/botserv/bs_kick.cpp index 29c8cb598..9183eae22 100644 --- a/modules/botserv/bs_kick.cpp +++ b/modules/botserv/bs_kick.cpp @@ -106,11 +106,10 @@ struct KickerDataImpl final data["ttb"] >> ttb; spacesepstream sep(ttb); for (int i = 0; sep.GetToken(tok) && i < TTB_SIZE; ++i) - try - { - kd->ttb[i] = convertTo<int16_t>(tok); - } - catch (const ConvertException &) { } + { + if (auto n = Anope::TryConvert<int16_t>(tok)) + kd->ttb[i] = n.value(); + } kd->Check(ci); } @@ -206,21 +205,13 @@ protected: { if (!ttb.empty()) { - int16_t i; - - try - { - i = convertTo<int16_t>(ttb); - if (i < 0) - throw ConvertException(); - } - catch (const ConvertException &) + kd->ttb[ttb_idx] = Anope::Convert<int16_t>(ttb, -1); + if (kd->ttb[ttb_idx] < 0) { + kd->ttb[ttb_idx] = 0; source.Reply(_("\002%s\002 cannot be taken as times to ban."), ttb.c_str()); return; } - - kd->ttb[ttb_idx] = i; } else kd->ttb[ttb_idx] = 0; @@ -386,13 +377,8 @@ public: if (!ttb.empty()) { - try - { - kd->ttb[TTB_CAPS] = convertTo<int16_t>(ttb); - if (kd->ttb[TTB_CAPS] < 0) - throw ConvertException(); - } - catch (const ConvertException &) + kd->ttb[TTB_CAPS] = Anope::Convert<int16_t>(ttb, -1); + if (kd->ttb[TTB_CAPS] < 0) { kd->ttb[TTB_CAPS] = 0; source.Reply(_("\002%s\002 cannot be taken as times to ban."), ttb.c_str()); @@ -402,21 +388,11 @@ public: else kd->ttb[TTB_CAPS] = 0; - kd->capsmin = 10; - try - { - kd->capsmin = convertTo<int16_t>(min); - } - catch (const ConvertException &) { } + kd->capsmin = Anope::Convert(min, 0); if (kd->capsmin < 1) kd->capsmin = 10; - kd->capspercent = 25; - try - { - kd->capspercent = convertTo<int16_t>(percent); - } - catch (const ConvertException &) { } + kd->capspercent = Anope::Convert(percent, 0); if (kd->capspercent < 1 || kd->capspercent > 100) kd->capspercent = 25; @@ -518,42 +494,25 @@ public: if (!ttb.empty()) { - int16_t i; - - try - { - i = convertTo<int16_t>(ttb); - if (i < 0) - throw ConvertException(); - } - catch (const ConvertException &) + kd->ttb[TTB_FLOOD] = Anope::Convert<int16_t>(ttb, -1); + if (kd->ttb[TTB_FLOOD] < 0) { + kd->ttb[TTB_FLOOD] = 0; source.Reply(_("\002%s\002 cannot be taken as times to ban."), ttb.c_str()); return; } - - kd->ttb[TTB_FLOOD] = i; } else kd->ttb[TTB_FLOOD] = 0; - kd->floodlines = 6; - try - { - kd->floodlines = convertTo<int16_t>(lines); - } - catch (const ConvertException &) { } + kd->floodlines = Anope::Convert(lines, -1); if (kd->floodlines < 2) kd->floodlines = 6; - kd->floodsecs = 10; - try - { - kd->floodsecs = convertTo<int16_t>(secs); - } - catch (const ConvertException &) { } + kd->floodsecs = Anope::Convert(secs, -1); if (kd->floodsecs < 1) kd->floodsecs = 10; + if (kd->floodsecs > Config->GetModule(me)->Get<time_t>("keepdata")) kd->floodsecs = Config->GetModule(me)->Get<time_t>("keepdata"); @@ -651,31 +610,18 @@ public: if (!ttb.empty()) { - int16_t i; - - try - { - i = convertTo<int16_t>(ttb); - if (i < 0) - throw ConvertException(); - } - catch (const ConvertException &) + kd->ttb[TTB_REPEAT] = Anope::Convert(ttb, -1); + if (kd->ttb[TTB_REPEAT] < 0) { + kd->ttb[TTB_REPEAT] = 0; source.Reply(_("\002%s\002 cannot be taken as times to ban."), ttb.c_str()); return; } - - kd->ttb[TTB_REPEAT] = i; } else kd->ttb[TTB_REPEAT] = 0; - kd->repeattimes = 3; - try - { - kd->repeattimes = convertTo<int16_t>(times); - } - catch (const ConvertException &) { } + kd->repeattimes = Anope::Convert<int16_t>(times, -1); if (kd->repeattimes < 1) kd->repeattimes = 3; diff --git a/modules/chanserv/cs_access.cpp b/modules/chanserv/cs_access.cpp index 3d2c3c8d6..f86d9f5bc 100644 --- a/modules/chanserv/cs_access.cpp +++ b/modules/chanserv/cs_access.cpp @@ -37,18 +37,13 @@ public: Anope::string AccessSerialize() const override { - return stringify(this->level); + return Anope::ToString(this->level); } void AccessUnserialize(const Anope::string &data) override { - try - { - this->level = convertTo<int>(data); - } - catch (const ConvertException &) - { - } + if (auto l = Anope::TryConvert<int>(data)) + this->level = l.value(); } bool operator>(const ChanAccess &other) const override @@ -95,11 +90,9 @@ class CommandCSAccess final Privilege *p = NULL; int level = ACCESS_INVALID; - try - { - level = convertTo<int>(params[3]); - } - catch (const ConvertException &) + if (auto lvl = Anope::TryConvert<int>(params[3])) + level = lvl.value(); + else { p = PrivilegeManager::FindPrivilege(params[3]); if (p != NULL && defaultLevels[p->name]) @@ -402,7 +395,7 @@ class CommandCSAccess final } ListFormatter::ListEntry entry; - entry["Number"] = stringify(number); + entry["Number"] = Anope::ToString(number); entry["Level"] = access->AccessSerialize(); entry["Mask"] = access->Mask(); entry["By"] = access->creator; @@ -442,7 +435,7 @@ class CommandCSAccess final } ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Level"] = access->AccessSerialize(); entry["Mask"] = access->Mask(); entry["By"] = access->creator; @@ -652,11 +645,9 @@ class CommandCSLevels final level = ACCESS_FOUNDER; else { - try - { - level = convertTo<int>(lev); - } - catch (const ConvertException &) + if (auto lvl = Anope::TryConvert<int>(lev)) + level = lvl.value(); + else { this->OnSyntaxError(source, "SET"); return; @@ -734,7 +725,7 @@ class CommandCSLevels final else if (j == ACCESS_FOUNDER) entry["Level"] = Language::Translate(source.GetAccount(), _("(founder only)")); else - entry["Level"] = stringify(j); + entry["Level"] = Anope::ToString(j); list.AddEntry(entry); } diff --git a/modules/chanserv/cs_akick.cpp b/modules/chanserv/cs_akick.cpp index 6457f2856..35052e63d 100644 --- a/modules/chanserv/cs_akick.cpp +++ b/modules/chanserv/cs_akick.cpp @@ -311,7 +311,7 @@ class CommandCSAKick final lastused = UNKNOWN; ListFormatter::ListEntry entry; - entry["Number"] = stringify(number); + entry["Number"] = Anope::ToString(number); if (akick->nc) entry["Mask"] = akick->nc->display; else @@ -351,7 +351,7 @@ class CommandCSAKick final lastused = UNKNOWN; ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); if (akick->nc) entry["Mask"] = akick->nc->display; else diff --git a/modules/chanserv/cs_enforce.cpp b/modules/chanserv/cs_enforce.cpp index 825301cdd..3c0a464ef 100644 --- a/modules/chanserv/cs_enforce.cpp +++ b/modules/chanserv/cs_enforce.cpp @@ -166,14 +166,8 @@ private: return; } - int l; - try - { - l = convertTo<int>(l_str); - if (l < 0) - throw ConvertException(); - } - catch (const ConvertException &) + auto l = Anope::Convert<int>(l_str, -1); + if (l < 0) { source.Reply(_("The limit on %s is not valid."), ci->name.c_str()); return; diff --git a/modules/chanserv/cs_entrymsg.cpp b/modules/chanserv/cs_entrymsg.cpp index 03e4b22de..efe13d1aa 100644 --- a/modules/chanserv/cs_entrymsg.cpp +++ b/modules/chanserv/cs_entrymsg.cpp @@ -123,7 +123,7 @@ private: EntryMsg *msg = (*messages)->at(i); ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Creator"] = msg->creator; entry["Created"] = Anope::strftime(msg->when, NULL, true); entry["Message"] = msg->message; @@ -162,21 +162,16 @@ private: source.Reply(_("Entry message list for \002%s\002 is empty."), ci->name.c_str()); else { - try + auto i = Anope::Convert<unsigned>(message, 0); + if (i > 0 && i <= (*messages)->size()) { - unsigned i = convertTo<unsigned>(message); - if (i > 0 && i <= (*messages)->size()) - { - delete (*messages)->at(i - 1); - if ((*messages)->empty()) - ci->Shrink<EntryMessageList>("entrymsg"); - Log(source.AccessFor(ci).HasPriv("SET") ? LOG_COMMAND : LOG_OVERRIDE, source, this, ci) << "to remove a message"; - source.Reply(_("Entry message \002%i\002 for \002%s\002 deleted."), i, ci->name.c_str()); - } - else - throw ConvertException(); + delete (*messages)->at(i - 1); + if ((*messages)->empty()) + ci->Shrink<EntryMessageList>("entrymsg"); + Log(source.AccessFor(ci).HasPriv("SET") ? LOG_COMMAND : LOG_OVERRIDE, source, this, ci) << "to remove a message"; + source.Reply(_("Entry message \002%i\002 for \002%s\002 deleted."), i, ci->name.c_str()); } - catch (const ConvertException &) + else { source.Reply(_("Entry message \002%s\002 not found on channel \002%s\002."), message.c_str(), ci->name.c_str()); } diff --git a/modules/chanserv/cs_flags.cpp b/modules/chanserv/cs_flags.cpp index feb64aacd..7404aef57 100644 --- a/modules/chanserv/cs_flags.cpp +++ b/modules/chanserv/cs_flags.cpp @@ -331,7 +331,7 @@ class CommandCSFlags final ListFormatter::ListEntry entry; ++count; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Mask"] = access->Mask(); entry["Flags"] = flags; entry["Creator"] = access->creator; diff --git a/modules/chanserv/cs_info.cpp b/modules/chanserv/cs_info.cpp index 685538284..e02660301 100644 --- a/modules/chanserv/cs_info.cpp +++ b/modules/chanserv/cs_info.cpp @@ -58,7 +58,7 @@ public: if (show_all) { - info[_("Ban type")] = stringify(ci->bantype); + info[_("Ban type")] = Anope::ToString(ci->bantype); } FOREACH_MOD(OnChanInfo, (source, ci, info, show_all)); diff --git a/modules/chanserv/cs_list.cpp b/modules/chanserv/cs_list.cpp index 29add4596..c9589a268 100644 --- a/modules/chanserv/cs_list.cpp +++ b/modules/chanserv/cs_list.cpp @@ -36,12 +36,10 @@ public: sepstream(pattern.substr(1), '-').GetToken(n1, 0); sepstream(pattern, '-').GetToken(n2, 1); - try - { - from = convertTo<int>(n1); - to = convertTo<int>(n2); - } - catch (const ConvertException &) + auto num1 = Anope::TryConvert<int>(n1); + auto num2 = Anope::TryConvert<int>(n2); + + if (!num1.has_value() || !num2.has_value()) { source.Reply(LIST_INCORRECT_RANGE); source.Reply(_("To search for channels starting with #, search for the channel\n" @@ -49,6 +47,8 @@ public: return; } + from = num1.value(); + to = num2.value(); pattern = "*"; } diff --git a/modules/chanserv/cs_log.cpp b/modules/chanserv/cs_log.cpp index 213940a5c..8c1004eeb 100644 --- a/modules/chanserv/cs_log.cpp +++ b/modules/chanserv/cs_log.cpp @@ -135,7 +135,7 @@ public: const LogSetting *log = (*ls)->at(i); ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Service"] = log->command_service; entry["Command"] = !log->command_name.empty() ? log->command_name : log->service_name; entry["Method"] = log->method; diff --git a/modules/chanserv/cs_mode.cpp b/modules/chanserv/cs_mode.cpp index 8c7c7c1c3..8f462a3cb 100644 --- a/modules/chanserv/cs_mode.cpp +++ b/modules/chanserv/cs_mode.cpp @@ -716,7 +716,7 @@ class CommandCSMode final std::vector<Anope::string> new_params; new_params.push_back(params[0]); new_params.emplace_back("SET"); - new_params.push_back("-" + stringify(cm->mchar)); + new_params.push_back("-" + Anope::ToString(cm->mchar)); new_params.emplace_back("*"); this->DoSet(source, ci, new_params); } diff --git a/modules/chanserv/cs_set.cpp b/modules/chanserv/cs_set.cpp index d5ed4713f..c7952baba 100644 --- a/modules/chanserv/cs_set.cpp +++ b/modules/chanserv/cs_set.cpp @@ -165,19 +165,16 @@ public: return; } - try - { - int16_t new_type = convertTo<int16_t>(params[1]); - if (new_type < 0 || new_type > 3) - throw ConvertException("Invalid range"); - Log(source.AccessFor(ci).HasPriv("SET") ? LOG_COMMAND : LOG_OVERRIDE, source, this, ci) << "to change the ban type to " << new_type; - ci->bantype = new_type; - source.Reply(_("Ban type for channel %s is now #%d."), ci->name.c_str(), ci->bantype); - } - catch (const ConvertException &) + auto new_type = Anope::Convert<int16_t>(params[1], -1); + if (new_type < 0 || new_type > 3) { source.Reply(_("\002%s\002 is not a valid ban type."), params[1].c_str()); + return; } + + Log(source.AccessFor(ci).HasPriv("SET") ? LOG_COMMAND : LOG_OVERRIDE, source, this, ci) << "to change the ban type to " << new_type; + ci->bantype = new_type; + source.Reply(_("Ban type for channel %s is now #%d."), ci->name.c_str(), ci->bantype); } bool OnHelp(CommandSource &source, const Anope::string &) override diff --git a/modules/chanserv/cs_xop.cpp b/modules/chanserv/cs_xop.cpp index b47e1e988..0ec8e8d25 100644 --- a/modules/chanserv/cs_xop.cpp +++ b/modules/chanserv/cs_xop.cpp @@ -420,7 +420,7 @@ private: return; ListFormatter::ListEntry entry; - entry["Number"] = stringify(Number); + entry["Number"] = Anope::ToString(Number); entry["Mask"] = a->Mask(); entry["Description"] = a->description; this->list.AddEntry(entry); @@ -440,7 +440,7 @@ private: continue; ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Mask"] = a->Mask(); entry["Description"] = a->description; list.AddEntry(entry); diff --git a/modules/database/db_atheme.cpp b/modules/database/db_atheme.cpp index 3e613562b..3f62c29ca 100644 --- a/modules/database/db_atheme.cpp +++ b/modules/database/db_atheme.cpp @@ -56,16 +56,7 @@ public: template<typename Numeric> std::enable_if_t<std::is_arithmetic_v<Numeric>, Numeric> GetNum() { - try - { - auto token = Get(); - std::stringstream stream(token.str()); - Numeric ntoken = 0; - stream >> ntoken; - return ntoken; - } - catch (const ConvertException &) { } - return 0; + return Anope::Convert<Numeric>(Get(), 0); } // Retrieves the entire row. @@ -869,7 +860,7 @@ private: else if (key == "private:close:reason") data->suspend_reason = value; else if (key == "private:close:timestamp") - data->suspend_ts = convertTo<time_t>(value); + data->suspend_ts = Anope::Convert<time_t>(value, 0); else if (key == "private:entrymsg") { auto *eml = ci->Require<EntryMessageList>("entrymsg"); @@ -891,19 +882,19 @@ private: else if (key == "private:klinechan:reason") data->suspend_reason = value; else if (key == "private:klinechan:timestamp") - data->suspend_ts = convertTo<time_t>(value); + data->suspend_ts = Anope::Convert<time_t>(value, 0); else if (key == "private:mark:reason") data->info_message = value; else if (key == "private:mark:setter") data->info_adder = value; else if (key == "private:mark:timestamp") - data->info_ts = convertTo<time_t>(value); + data->info_ts = Anope::Convert<time_t>(value, 0); else if (key == "private:topic:setter") ci->last_topic_setter = value; else if (key == "private:topic:text") ci->last_topic = value; else if (key == "private:topic:ts") - ci->last_topic_time = convertTo<time_t>(value); + ci->last_topic_time = Anope::Convert<time_t>(value, 0); else Log(this) << "Unknown channel metadata " << key << " = " << value; @@ -953,7 +944,7 @@ private: auto kill = Config->GetModule("nickserv")->Get<time_t>("kill", "60s"); auto killquick = Config->GetModule("nickserv")->Get<time_t>("killquick", "20s"); - auto secs = convertTo<unsigned>(value); + auto secs = Anope::Convert<time_t>(value, kill); if (secs >= kill) nc->Extend<bool>("KILLPROTECT"); else if (secs >= killquick) @@ -966,7 +957,7 @@ private: else if (key == "private:freeze:reason") data->suspend_reason = value; else if (key == "private:freeze:timestamp") - data->suspend_ts = convertTo<time_t>(value); + data->suspend_ts = Anope::Convert<time_t>(value, 0); else if (key == "private:host:actual") data->last_real_mask = value; else if (key == "private:host:vhost") @@ -978,13 +969,13 @@ private: else if (key == "private:mark:setter") data->info_adder = value; else if (key == "private:mark:timestamp") - data->info_ts = convertTo<time_t>(value); + data->info_ts = Anope::Convert<time_t>(value, 0); else if (key == "private:usercloak") data->vhost = value; else if (key == "private:usercloak-assigner") data->vhost_creator = value; else if (key == "private:usercloak-timestamp") - data->vhost_ts = convertTo<time_t>(value); + data->vhost_ts = Anope::Convert<time_t>(value, 0); else if (key.compare(0, 18, "private:usercloak:", 18) == 0) data->vhost_nick[key.substr(18)] = value; else diff --git a/modules/database/db_flatfile.cpp b/modules/database/db_flatfile.cpp index d2225ce88..63c18f744 100644 --- a/modules/database/db_flatfile.cpp +++ b/modules/database/db_flatfile.cpp @@ -52,12 +52,7 @@ public: { if (token.find("ID ") == 0) { - try - { - this->id = convertTo<unsigned int>(token.substr(3)); - } - catch (const ConvertException &) { } - + this->id = Anope::Convert(token.substr(3), 0); continue; } else if (token.find("DATA ") != 0) @@ -136,7 +131,7 @@ class DBFlatFile final for (const auto &db : dbs) { const Anope::string &oldname = Anope::DataDir + "/" + db; - Anope::string newname = Anope::DataDir + "/backups/" + db + "-" + stringify(tm->tm_year + 1900) + Anope::printf("-%02i-", tm->tm_mon + 1) + Anope::printf("%02i", tm->tm_mday); + Anope::string newname = Anope::DataDir + "/backups/" + db + "-" + Anope::ToString(tm->tm_year + 1900) + Anope::printf("-%02i-", tm->tm_mon + 1) + Anope::printf("%02i", tm->tm_mday); /* Backup already exists or no database to backup */ if (Anope::IsFile(newname) || !Anope::IsFile(oldname)) diff --git a/modules/database/db_old.cpp b/modules/database/db_old.cpp index c3e82ea39..e95cc19ef 100644 --- a/modules/database/db_old.cpp +++ b/modules/database/db_old.cpp @@ -152,7 +152,7 @@ static void process_mlock(ChannelInfo *ci, uint32_t lock, bool status, uint32_t if (cm && ml) { if (limit && mlock_info.c == 'l') - ml->SetMLock(cm, status, stringify(*limit)); + ml->SetMLock(cm, status, Anope::ToString(*limit)); else if (key && mlock_info.c == 'k') ml->SetMLock(cm, status, *key); else @@ -889,7 +889,7 @@ static void LoadChannels() } } else - access->AccessUnserialize(stringify(level)); + access->AccessUnserialize(Anope::ToString(level)); } Anope::string mask; diff --git a/modules/database/db_redis.cpp b/modules/database/db_redis.cpp index b4abcab7f..413729887 100644 --- a/modules/database/db_redis.cpp +++ b/modules/database/db_redis.cpp @@ -162,7 +162,7 @@ public: std::vector<Anope::string> args; args.emplace_back("HGETALL"); - args.push_back("hash:" + t->GetName() + ":" + stringify(obj->id)); + args.push_back("hash:" + t->GetName() + ":" + Anope::ToString(obj->id)); /* Get object attrs to clear before updating */ redis->SendCommand(new Updater(this, t->GetName(), obj->id), args); @@ -248,7 +248,7 @@ public: std::vector<Anope::string> args; args.emplace_back("HGETALL"); - args.push_back("hash:" + t->GetName() + ":" + stringify(obj->id)); + args.push_back("hash:" + t->GetName() + ":" + Anope::ToString(obj->id)); /* Get all of the attributes for this object */ redis->SendCommand(new Deleter(this, t->GetName(), obj->id), args); @@ -278,19 +278,14 @@ void TypeLoader::OnResult(const Reply &r) if (reply->type != Reply::BULK) continue; - int64_t id; - try - { - id = convertTo<int64_t>(reply->bulk); - } - catch (const ConvertException &) - { + auto i = Anope::TryConvert<int64_t>(reply->bulk); + if (!i) continue; - } + auto id = i.value(); std::vector<Anope::string> args; args.emplace_back("HGETALL"); - args.push_back("hash:" + this->type + ":" + stringify(id)); + args.push_back("hash:" + this->type + ":" + Anope::ToString(id)); me->redis->SendCommand(new ObjectLoader(me, this->type, id), args); } @@ -364,7 +359,7 @@ void Deleter::OnResult(const Reply &r) std::vector<Anope::string> args; args.emplace_back("DEL"); - args.push_back("hash:" + this->type + ":" + stringify(this->id)); + args.push_back("hash:" + this->type + ":" + Anope::ToString(this->id)); /* Delete hash object */ me->redis->SendCommand(NULL, args); @@ -372,7 +367,7 @@ void Deleter::OnResult(const Reply &r) args.clear(); args.emplace_back("SREM"); args.push_back("ids:" + this->type); - args.push_back(stringify(this->id)); + args.push_back(Anope::ToString(this->id)); /* Delete id from ids set */ me->redis->SendCommand(NULL, args); @@ -385,7 +380,7 @@ void Deleter::OnResult(const Reply &r) args.clear(); args.emplace_back("SREM"); args.push_back("value:" + this->type + ":" + key->bulk + ":" + value->bulk); - args.push_back(stringify(this->id)); + args.push_back(Anope::ToString(this->id)); /* Delete value -> object id */ me->redis->SendCommand(NULL, args); @@ -428,7 +423,7 @@ void Updater::OnResult(const Reply &r) std::vector<Anope::string> args; args.emplace_back("SREM"); args.push_back("value:" + this->type + ":" + key->bulk + ":" + value->bulk); - args.push_back(stringify(this->id)); + args.push_back(Anope::ToString(this->id)); /* Delete value -> object id */ me->redis->SendCommand(NULL, args); @@ -438,12 +433,12 @@ void Updater::OnResult(const Reply &r) std::vector<Anope::string> args; args.emplace_back("SADD"); args.push_back("ids:" + this->type); - args.push_back(stringify(obj->id)); + args.push_back(Anope::ToString(obj->id)); me->redis->SendCommand(NULL, args); args.clear(); args.emplace_back("HMSET"); - args.push_back("hash:" + this->type + ":" + stringify(obj->id)); + args.push_back("hash:" + this->type + ":" + Anope::ToString(obj->id)); for (const auto &[key, value] : data.data) { @@ -454,7 +449,7 @@ void Updater::OnResult(const Reply &r) args2.emplace_back("SADD"); args2.push_back("value:" + this->type + ":" + key + ":" + value->str()); - args2.push_back(stringify(obj->id)); + args2.push_back(Anope::ToString(obj->id)); /* Add to value -> object id set */ me->redis->SendCommand(NULL, args2); @@ -505,16 +500,11 @@ void SubscriptionListener::OnResult(const Reply &r) if (s_type == NULL) return; - uint64_t obj_id; - try - { - obj_id = convertTo<uint64_t>(id); - } - catch (const ConvertException &) - { + auto oid = Anope::TryConvert<uint64_t>(id); + if (!oid.has_value()) return; - } + auto obj_id = oid.value(); if (op == "hset" || op == "hdel") { Serializable *s = s_type->objects[obj_id]; @@ -564,7 +554,7 @@ void SubscriptionListener::OnResult(const Reply &r) std::vector<Anope::string> args; args.emplace_back("SREM"); args.push_back("ids:" + type); - args.push_back(stringify(s->id)); + args.push_back(Anope::ToString(s->id)); /* Delete object from id set */ me->redis->SendCommand(NULL, args); @@ -604,7 +594,7 @@ void ModifiedObject::OnResult(const Reply &r) std::vector<Anope::string> args; args.emplace_back("SREM"); args.push_back("value:" + st->GetName() + ":" + key + ":" + value->str()); - args.push_back(stringify(this->id)); + args.push_back(Anope::ToString(this->id)); /* Delete value -> object id */ me->redis->SendCommand(NULL, args); @@ -633,7 +623,7 @@ void ModifiedObject::OnResult(const Reply &r) std::vector<Anope::string> args; args.emplace_back("SADD"); args.push_back("value:" + st->GetName() + ":" + key + ":" + value->str()); - args.push_back(stringify(obj->id)); + args.push_back(Anope::ToString(obj->id)); /* Add to value -> object id set */ me->redis->SendCommand(NULL, args); @@ -642,7 +632,7 @@ void ModifiedObject::OnResult(const Reply &r) std::vector<Anope::string> args; args.emplace_back("SADD"); args.push_back("ids:" + st->GetName()); - args.push_back(stringify(obj->id)); + args.push_back(Anope::ToString(obj->id)); /* Add to type -> id set */ me->redis->SendCommand(NULL, args); diff --git a/modules/database/db_sql.cpp b/modules/database/db_sql.cpp index 24b5c1f1f..d8fe89972 100644 --- a/modules/database/db_sql.cpp +++ b/modules/database/db_sql.cpp @@ -209,7 +209,7 @@ public: return; Serialize::Type *s_type = obj->GetSerializableType(); if (s_type && obj->id > 0) - this->RunBackground("DELETE FROM `" + this->prefix + s_type->GetName() + "` WHERE `id` = " + stringify(obj->id)); + this->RunBackground("DELETE FROM `" + this->prefix + s_type->GetName() + "` WHERE `id` = " + Anope::ToString(obj->id)); this->updated_items.erase(obj); } @@ -240,18 +240,14 @@ public: data[key] << value; Serializable *obj = sb->Unserialize(NULL, data); - try - { - if (obj) - obj->id = convertTo<unsigned int>(res.Get(j, "id")); - } - catch (const ConvertException &) - { - Log(this) << "Unable to convert id for object #" << j << " of type " << sb->GetName(); - } - if (obj) { + auto oid = Anope::TryConvert<unsigned int>(res.Get(j, "id")); + if (oid.has_value()) + obj->id = oid.value(); + else + Log(this) << "Unable to convert id for object #" << j << " of type " << sb->GetName(); + /* The Unserialize operation is destructive so rebuild the data for UpdateCache. * Also the old data may contain columns that we don't use, so we reserialize the * object to know for sure our cache is consistent diff --git a/modules/database/db_sql_live.cpp b/modules/database/db_sql_live.cpp index d97fe6683..839126d41 100644 --- a/modules/database/db_sql_live.cpp +++ b/modules/database/db_sql_live.cpp @@ -163,7 +163,7 @@ public: if (s_type) { if (obj->id > 0) - this->RunQuery("DELETE FROM `" + this->prefix + s_type->GetName() + "` WHERE `id` = " + stringify(obj->id)); + this->RunQuery("DELETE FROM `" + this->prefix + s_type->GetName() + "` WHERE `id` = " + Anope::ToString(obj->id)); s_type->objects.erase(obj->id); } this->updated_items.erase(obj); @@ -185,17 +185,16 @@ public: { const std::map<Anope::string, Anope::string> &row = res.Row(i); - unsigned int id; - try - { - id = convertTo<unsigned int>(res.Get(i, "id")); - } - catch (const ConvertException &) + + + auto oid = Anope::TryConvert<unsigned int>(res.Get(i, "id")); + if (!oid.has_value()) { Log(LOG_DEBUG) << "Unable to convert id from " << obj->GetName(); continue; } + auto id = oid.value(); if (res.Get(i, "timestamp").empty()) { clear_null = true; @@ -237,7 +236,7 @@ public: else { if (!s) - this->RunQuery("UPDATE `" + prefix + obj->GetName() + "` SET `timestamp` = " + this->SQL->FromUnixtime(obj->GetTimestamp()) + " WHERE `id` = " + stringify(id)); + this->RunQuery("UPDATE `" + prefix + obj->GetName() + "` SET `timestamp` = " + this->SQL->FromUnixtime(obj->GetTimestamp()) + " WHERE `id` = " + Anope::ToString(id)); else delete s; } diff --git a/modules/encryption/enc_bcrypt.cpp b/modules/encryption/enc_bcrypt.cpp index 7fd3864ac..0800b2d66 100644 --- a/modules/encryption/enc_bcrypt.cpp +++ b/modules/encryption/enc_bcrypt.cpp @@ -142,19 +142,15 @@ public: if (bcryptprovider.Compare(hash_value, req->GetPassword())) { unsigned long rounds = 0; - try - { - // Try to extract the rounds count to cher - pos = hash_value.find('$', 4); - if (pos == Anope::string::npos) - throw ConvertException("Malformed BCrypt hash?!"); - - rounds = convertTo<unsigned long>(hash_value.substr(4, pos - 4)); - } - catch (const ConvertException &) - { + + // Try to extract the rounds count to check if we need to + // re-encrypt the password. + pos = hash_value.find('$', 4); + if (pos != Anope::string::npos) + rounds = Anope::Convert<unsigned long>(hash_value.substr(4, pos - 4), 0); + + if (!rounds) Log(LOG_DEBUG) << "Unable to determine the rounds of a bcrypt hash: " << hash_value; - } // If we are NOT the first encryption module or the Bcrypt rounds // are different we want to re-encrypt the password with the primary diff --git a/modules/extra/mysql.cpp b/modules/extra/mysql.cpp index 49149464f..72c026dad 100644 --- a/modules/extra/mysql.cpp +++ b/modules/extra/mysql.cpp @@ -452,7 +452,7 @@ Query MySQLService::BuildInsert(const Anope::string &table, unsigned int id, Dat for (const auto &[field, _] : data.data) query_text += ",`" + field + "`"; - query_text += ") VALUES (" + stringify(id); + query_text += ") VALUES (" + Anope::ToString(id); for (const auto &[field, _] : data.data) query_text += ",@" + field + "@"; query_text += ") ON DUPLICATE KEY UPDATE "; @@ -536,7 +536,7 @@ Anope::string MySQLService::BuildQuery(const Query &q) Anope::string MySQLService::FromUnixtime(time_t t) { - return "FROM_UNIXTIME(" + stringify(t) + ")"; + return "FROM_UNIXTIME(" + Anope::ToString(t) + ")"; } void DispatcherThread::Run() diff --git a/modules/extra/regex_pcre2.cpp b/modules/extra/regex_pcre2.cpp index ef2786823..991be3f6c 100644 --- a/modules/extra/regex_pcre2.cpp +++ b/modules/extra/regex_pcre2.cpp @@ -30,7 +30,7 @@ public: { PCRE2_UCHAR error[128]; pcre2_get_error_message(errcode, error, sizeof error); - throw RegexException("Error in regex " + expr + " at offset " + stringify(erroffset) + ": " + reinterpret_cast<const char*>(error)); + throw RegexException("Error in regex " + expr + " at offset " + Anope::ToString(erroffset) + ": " + reinterpret_cast<const char*>(error)); } } diff --git a/modules/extra/sqlite.cpp b/modules/extra/sqlite.cpp index b481093ca..4968e8e0d 100644 --- a/modules/extra/sqlite.cpp +++ b/modules/extra/sqlite.cpp @@ -297,7 +297,7 @@ Query SQLiteService::BuildInsert(const Anope::string &table, unsigned int id, Da query_text.erase(query_text.length() - 1); query_text += ") VALUES ("; if (id > 0) - query_text += stringify(id) + ","; + query_text += Anope::ToString(id) + ","; for (const auto &[field, _] : data.data) query_text += "@" + field + "@,"; query_text.erase(query_text.length() - 1); @@ -339,7 +339,7 @@ Anope::string SQLiteService::BuildQuery(const Query &q) Anope::string SQLiteService::FromUnixtime(time_t t) { - return "datetime('" + stringify(t) + "', 'unixepoch')"; + return "datetime('" + Anope::ToString(t) + "', 'unixepoch')"; } MODULE_INIT(ModuleSQLite) diff --git a/modules/hostserv/hs_list.cpp b/modules/hostserv/hs_list.cpp index 7b85bead3..dd459fd78 100644 --- a/modules/hostserv/hs_list.cpp +++ b/modules/hostserv/hs_list.cpp @@ -45,12 +45,9 @@ public: source.Reply(LIST_INCORRECT_RANGE); return; } - try - { - from = convertTo<int>(key.substr(1, tmp - 1)); - to = convertTo<int>(key.substr(tmp + 1)); - } - catch (const ConvertException &) { } + + from = Anope::Convert<int>(key.substr(1, tmp - 1), 0); + to = Anope::Convert<int>(key.substr(tmp + 1), 0); } } @@ -70,7 +67,7 @@ public: ++display_counter; ListFormatter::ListEntry entry; - entry["Number"] = stringify(display_counter); + entry["Number"] = Anope::ToString(display_counter); entry["Nick"] = na->nick; entry["Vhost"] = na->GetVhostMask(); entry["Creator"] = na->GetVhostCreator(); @@ -88,7 +85,7 @@ public: { ++display_counter; ListFormatter::ListEntry entry; - entry["Number"] = stringify(display_counter); + entry["Number"] = Anope::ToString(display_counter); entry["Nick"] = na->nick; entry["Vhost"] = na->GetVhostMask(); entry["Creator"] = na->GetVhostCreator(); diff --git a/modules/hostserv/hs_request.cpp b/modules/hostserv/hs_request.cpp index 021e5f5b7..d7bc6bc34 100644 --- a/modules/hostserv/hs_request.cpp +++ b/modules/hostserv/hs_request.cpp @@ -320,7 +320,7 @@ public: ++display_counter; ListFormatter::ListEntry entry; - entry["Number"] = stringify(display_counter); + entry["Number"] = Anope::ToString(display_counter); entry["Nick"] = nick; if (!hr->ident.empty()) entry["Vhost"] = hr->ident + "@" + hr->host; diff --git a/modules/httpd.cpp b/modules/httpd.cpp index 226d750fe..f784d2d32 100644 --- a/modules/httpd.cpp +++ b/modules/httpd.cpp @@ -216,11 +216,8 @@ public: } else if (buf.find_ci("Content-Length: ") == 0) { - try - { - this->content_length = convertTo<unsigned>(buf.substr(16)); - } - catch (const ConvertException &ex) { } + if (auto len = Anope::TryConvert<unsigned>(buf.substr(16))) + this->content_length = len.value(); } else if (buf.find(':') != Anope::string::npos) { @@ -252,7 +249,7 @@ public: this->WriteClient("Content-Type: text/html"); else this->WriteClient("Content-Type: " + msg->content_type); - this->WriteClient("Content-Length: " + stringify(msg->length)); + this->WriteClient("Content-Length: " + Anope::ToString(msg->length)); for (const auto &cookie : msg->cookies) { diff --git a/modules/memoserv/memoserv.cpp b/modules/memoserv/memoserv.cpp index 45642b46d..084650542 100644 --- a/modules/memoserv/memoserv.cpp +++ b/modules/memoserv/memoserv.cpp @@ -24,13 +24,13 @@ class MemoServCore final subject = subject.replace_all_cs("%n", nc->display); subject = subject.replace_all_cs("%s", m->sender); - subject = subject.replace_all_cs("%d", stringify(mi->GetIndex(m) + 1)); + subject = subject.replace_all_cs("%d", Anope::ToString(mi->GetIndex(m) + 1)); subject = subject.replace_all_cs("%t", m->text); subject = subject.replace_all_cs("%N", Config->GetBlock("networkinfo")->Get<const Anope::string>("networkname")); message = message.replace_all_cs("%n", nc->display); message = message.replace_all_cs("%s", m->sender); - message = message.replace_all_cs("%d", stringify(mi->GetIndex(m) + 1)); + message = message.replace_all_cs("%d", Anope::ToString(mi->GetIndex(m) + 1)); message = message.replace_all_cs("%t", m->text); message = message.replace_all_cs("%N", Config->GetBlock("networkinfo")->Get<const Anope::string>("networkname")); diff --git a/modules/memoserv/ms_list.cpp b/modules/memoserv/ms_list.cpp index 127cfdaaf..a25a95ed0 100644 --- a/modules/memoserv/ms_list.cpp +++ b/modules/memoserv/ms_list.cpp @@ -85,7 +85,7 @@ public: const Memo *m = mi->GetMemo(number - 1); ListFormatter::ListEntry entry; - entry["Number"] = (m->unread ? "* " : " ") + stringify(number); + entry["Number"] = (m->unread ? "* " : " ") + Anope::ToString(number); entry["Sender"] = m->sender; entry["Date/Time"] = Anope::strftime(m->time, source.GetAccount()); this->list.AddEntry(entry); @@ -120,7 +120,7 @@ public: const Memo *m = mi->GetMemo(i); ListFormatter::ListEntry entry; - entry["Number"] = (m->unread ? "* " : " ") + stringify(i + 1); + entry["Number"] = (m->unread ? "* " : " ") + Anope::ToString(i + 1); entry["Sender"] = m->sender; entry["Date/Time"] = Anope::strftime(m->time, source.GetAccount()); list.AddEntry(entry); diff --git a/modules/memoserv/ms_set.cpp b/modules/memoserv/ms_set.cpp index 83b28fb20..54ad7c252 100644 --- a/modules/memoserv/ms_set.cpp +++ b/modules/memoserv/ms_set.cpp @@ -135,12 +135,8 @@ private: else nc->Shrink<bool>("MEMO_HARDMAX"); } - limit = -1; - try - { - limit = convertTo<int16_t>(p1); - } - catch (const ConvertException &) { } + + limit = Anope::Convert<int16_t>(p1, -1); } else { @@ -160,12 +156,8 @@ private: return; } int max_memos = Config->GetModule("memoserv")->Get<int>("maxmemos"); - limit = -1; - try - { - limit = convertTo<int16_t>(p1); - } - catch (const ConvertException &) { } + limit = Anope::Convert<int16_t>(p1, -1); + /* The first character is a digit, but we could still go negative * from overflow... watch out! */ if (limit < 0 || (max_memos > 0 && limit > max_memos)) diff --git a/modules/nickserv/nickserv.cpp b/modules/nickserv/nickserv.cpp index 541b7f0f9..f1f087163 100644 --- a/modules/nickserv/nickserv.cpp +++ b/modules/nickserv/nickserv.cpp @@ -246,7 +246,7 @@ public: int i = 0; do { - guestnick = guestprefix + stringify(static_cast<uint16_t>(Anope::RandomNumber())); + guestnick = guestprefix + Anope::ToString(static_cast<uint16_t>(Anope::RandomNumber())); if (guestnick.length() > nicklen) guestnick = guestnick.substr(0, nicklen); } diff --git a/modules/nickserv/ns_ajoin.cpp b/modules/nickserv/ns_ajoin.cpp index f6e716a36..91e700e4a 100644 --- a/modules/nickserv/ns_ajoin.cpp +++ b/modules/nickserv/ns_ajoin.cpp @@ -105,7 +105,7 @@ class CommandNSAJoin final { AJoinEntry *aj = (*channels)->at(i); ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Channel"] = aj->channel; entry["Key"] = aj->key; list.AddEntry(entry); @@ -382,13 +382,11 @@ public: Anope::string l; if (c->GetParam("LIMIT", l)) { - try + if (auto limit = Anope::TryConvert<unsigned>(l)) { - unsigned limit = convertTo<unsigned>(l); - if (c->users.size() >= limit) + if (c->users.size() >= limit.value()) need_invite = true; } - catch (const ConvertException &) { } } } } diff --git a/modules/nickserv/ns_alist.cpp b/modules/nickserv/ns_alist.cpp index e4adfb870..0d02894af 100644 --- a/modules/nickserv/ns_alist.cpp +++ b/modules/nickserv/ns_alist.cpp @@ -59,7 +59,7 @@ public: if (ci->GetFounder() == nc) { ++chan_count; - entry["Number"] = stringify(chan_count); + entry["Number"] = Anope::ToString(chan_count); entry["Channel"] = (ci->HasExt("CS_NO_EXPIRE") ? "!" : "") + ci->name; entry["Access"] = Language::Translate(source.GetAccount(), _("Founder")); entry["Description"] = ci->desc; @@ -70,7 +70,7 @@ public: if (ci->GetSuccessor() == nc) { ++chan_count; - entry["Number"] = stringify(chan_count); + entry["Number"] = Anope::ToString(chan_count); entry["Channel"] = (ci->HasExt("CS_NO_EXPIRE") ? "!" : "") + ci->name; entry["Access"] = Language::Translate(source.GetAccount(), _("Successor")); entry["Description"] = ci->desc; @@ -84,7 +84,7 @@ public: ++chan_count; - entry["Number"] = stringify(chan_count); + entry["Number"] = Anope::ToString(chan_count); entry["Channel"] = (ci->HasExt("CS_NO_EXPIRE") ? "!" : "") + ci->name; for (auto &p : access.paths) { diff --git a/modules/nickserv/ns_list.cpp b/modules/nickserv/ns_list.cpp index a1c28a28d..1bd4ea043 100644 --- a/modules/nickserv/ns_list.cpp +++ b/modules/nickserv/ns_list.cpp @@ -39,17 +39,17 @@ public: Anope::string n1, n2; sepstream(pattern.substr(1), '-').GetToken(n1, 0); sepstream(pattern, '-').GetToken(n2, 1); - try - { - from = convertTo<int>(n1); - to = convertTo<int>(n2); - } - catch (const ConvertException &) + + auto num1 = Anope::TryConvert<int>(n1); + auto num2 = Anope::TryConvert<int>(n2); + if (!num1.has_value() || !num2.has_value()) { source.Reply(LIST_INCORRECT_RANGE); return; } + from = num1.value(); + to = num2.value(); pattern = "*"; } diff --git a/modules/operserv/os_akill.cpp b/modules/operserv/os_akill.cpp index 3f5e9c7d2..7fcacd9ad 100644 --- a/modules/operserv/os_akill.cpp +++ b/modules/operserv/os_akill.cpp @@ -285,7 +285,7 @@ private: return; ListFormatter::ListEntry entry; - entry["Number"] = stringify(number); + entry["Number"] = Anope::ToString(number); entry["Mask"] = x->mask; entry["Creator"] = x->by; entry["Created"] = Anope::strftime(x->created, NULL, true); @@ -307,7 +307,7 @@ private: if (mask.empty() || mask.equals_ci(x->mask) || mask == x->id || Anope::Match(x->mask, mask, false, true)) { ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Mask"] = x->mask; entry["Creator"] = x->by; entry["Created"] = Anope::strftime(x->created, NULL, true); diff --git a/modules/operserv/os_defcon.cpp b/modules/operserv/os_defcon.cpp index dbb0edb69..564cfec50 100644 --- a/modules/operserv/os_defcon.cpp +++ b/modules/operserv/os_defcon.cpp @@ -192,13 +192,7 @@ public: return; } - int newLevel = 0; - try - { - newLevel = convertTo<int>(lvl); - } - catch (const ConvertException &) { } - + auto newLevel = Anope::Convert<int>(lvl, 0); if (newLevel < 1 || newLevel > 5) { this->OnSyntaxError(source, ""); diff --git a/modules/operserv/os_dns.cpp b/modules/operserv/os_dns.cpp index 99d01e7b7..18e53b25a 100644 --- a/modules/operserv/os_dns.cpp +++ b/modules/operserv/os_dns.cpp @@ -42,7 +42,7 @@ struct DNSZone final data["name"] << name; unsigned count = 0; for (const auto &server : servers) - data["server" + stringify(count++)] << server; + data["server" + Anope::ToString(count++)] << server; } static Serializable *Unserialize(Serializable *obj, Serialize::Data &data) @@ -64,7 +64,7 @@ struct DNSZone final for (unsigned count = 0; true; ++count) { Anope::string server_str; - data["server" + stringify(count)] >> server_str; + data["server" + Anope::ToString(count)] >> server_str; if (server_str.empty()) break; zone->servers.insert(server_str); @@ -146,12 +146,12 @@ public: { data["server_name"] << server_name; for (unsigned i = 0; i < ips.size(); ++i) - data["ip" + stringify(i)] << ips[i]; + data["ip" + Anope::ToString(i)] << ips[i]; data["limit"] << limit; data["pooled"] << pooled; unsigned count = 0; for (const auto &zone : zones) - data["zone" + stringify(count++)] << zone; + data["zone" + Anope::ToString(count++)] << zone; } static Serializable *Unserialize(Serializable *obj, Serialize::Data &data) @@ -172,7 +172,7 @@ public: for (unsigned i = 0; true; ++i) { Anope::string ip_str; - data["ip" + stringify(i)] >> ip_str; + data["ip" + Anope::ToString(i)] >> ip_str; if (ip_str.empty()) break; req->ips.push_back(ip_str); @@ -185,7 +185,7 @@ public: for (unsigned i = 0; true; ++i) { Anope::string zone_str; - data["zone" + stringify(i)] >> zone_str; + data["zone" + Anope::ToString(i)] >> zone_str; if (zone_str.empty()) break; req->zones.insert(zone_str); @@ -225,7 +225,7 @@ class CommandOSDNS final ListFormatter::ListEntry entry; entry["Server"] = s->GetName(); - entry["Limit"] = s->GetLimit() ? stringify(s->GetLimit()) : Language::Translate(source.GetAccount(), _("None")); + entry["Limit"] = s->GetLimit() ? Anope::ToString(s->GetLimit()) : Language::Translate(source.GetAccount(), _("None")); Anope::string ip_str; for (const auto &ip : s->GetIPs()) @@ -579,16 +579,15 @@ class CommandOSDNS final if (params[2].equals_ci("LIMIT")) { - try + if (auto l = Anope::TryConvert<unsigned>(params[3])) { - unsigned l = convertTo<unsigned>(params[3]); - s->SetLimit(l); - if (l) - source.Reply(_("User limit for %s set to %d."), s->GetName().c_str(), l); + s->SetLimit(l.value()); + if (s->GetLimit()) + source.Reply(_("User limit for %s set to %d."), s->GetName().c_str(), s->GetLimit()); else source.Reply(_("User limit for %s removed."), s->GetName().c_str()); } - catch (const ConvertException &ex) + else { source.Reply(_("Invalid value for LIMIT. Must be numerical.")); } diff --git a/modules/operserv/os_list.cpp b/modules/operserv/os_list.cpp index a6969dc24..ba1156967 100644 --- a/modules/operserv/os_list.cpp +++ b/modules/operserv/os_list.cpp @@ -60,7 +60,7 @@ public: ListFormatter::ListEntry entry; entry["Name"] = cc->chan->name; - entry["Users"] = stringify(cc->chan->users.size()); + entry["Users"] = Anope::ToString(cc->chan->users.size()); entry["Modes"] = cc->chan->GetModes(true, true); entry["Topic"] = cc->chan->topic; list.AddEntry(entry); @@ -87,7 +87,7 @@ public: ListFormatter::ListEntry entry; entry["Name"] = c->name; - entry["Users"] = stringify(c->users.size()); + entry["Users"] = Anope::ToString(c->users.size()); entry["Modes"] = c->GetModes(true, true); entry["Topic"] = c->topic; list.AddEntry(entry); diff --git a/modules/operserv/os_logsearch.cpp b/modules/operserv/os_logsearch.cpp index 606a74d78..0282644b2 100644 --- a/modules/operserv/os_logsearch.cpp +++ b/modules/operserv/os_logsearch.cpp @@ -47,32 +47,22 @@ public: if (params[i].length() > 2) { Anope::string dur = params[i].substr(1, params[i].length() - 2); - try - { - days = convertTo<int>(dur); - if (days <= 0) - throw ConvertException(); - } - catch (const ConvertException &) - { + auto d = Anope::Convert<int>(dur, 0); + if (d > 0) + days = d; + else source.Reply(_("Invalid duration %s, using %d days."), dur.c_str(), days); - } } break; case 'l': if (params[i].length() > 2) { Anope::string dur = params[i].substr(1, params[i].length() - 2); - try - { - replies = convertTo<int>(dur); - if (replies <= 0) - throw ConvertException(); - } - catch (const ConvertException &) - { + auto r = Anope::Convert<int>(dur, 0); + if (r > 0) + replies = r; + else source.Reply(_("Invalid limit %s, using %d."), dur.c_str(), replies); - } } break; default: diff --git a/modules/operserv/os_news.cpp b/modules/operserv/os_news.cpp index 067bfbc74..2cf011c0e 100644 --- a/modules/operserv/os_news.cpp +++ b/modules/operserv/os_news.cpp @@ -168,7 +168,7 @@ protected: for (unsigned i = 0, end = list.size(); i < end; ++i) { ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Creator"] = list[i]->who; entry["Created"] = Anope::strftime(list[i]->time, NULL, true); entry["Text"] = list[i]->text; @@ -232,18 +232,14 @@ protected: source.Reply(READ_ONLY_MODE); if (!text.equals_ci("ALL")) { - try + unsigned num = Anope::Convert<unsigned>(text, 0); + if (num > 0 && num <= list.size()) { - unsigned num = convertTo<unsigned>(text); - if (num > 0 && num <= list.size()) - { - this->ns->DelNewsItem(list[num - 1]); - source.Reply(msgs[MSG_DELETED], num); - Log(LOG_ADMIN, source, this) << "to delete a news item"; - return; - } + this->ns->DelNewsItem(list[num - 1]); + source.Reply(msgs[MSG_DELETED], num); + Log(LOG_ADMIN, source, this) << "to delete a news item"; + return; } - catch (const ConvertException &) { } source.Reply(msgs[MSG_DEL_NOT_FOUND], text.c_str()); } diff --git a/modules/operserv/os_session.cpp b/modules/operserv/os_session.cpp index 02695c55a..1e59f7d04 100644 --- a/modules/operserv/os_session.cpp +++ b/modules/operserv/os_session.cpp @@ -178,13 +178,7 @@ private: { Anope::string param = params[1]; - unsigned mincount = 0; - try - { - mincount = convertTo<unsigned>(param); - } - catch (const ConvertException &) { } - + auto mincount = Anope::Convert<unsigned>(param, 0); if (mincount <= 1) source.Reply(_("Invalid threshold value. It must be a valid integer greater than 1.")); else @@ -197,7 +191,7 @@ private: if (session->count >= mincount) { ListFormatter::ListEntry entry; - entry["Session"] = stringify(session->count); + entry["Session"] = Anope::ToString(session->count); entry["Host"] = session->addr.mask(); list.AddEntry(entry); } @@ -327,13 +321,7 @@ private: else if (expires > 0) expires += Anope::CurTime; - unsigned limit = -1; - try - { - limit = convertTo<unsigned>(limitstr); - } - catch (const ConvertException &) { } - + auto limit = Anope::Convert<unsigned>(limitstr, -1); if (limit > max_exception_limit) { source.Reply(_("Invalid session limit. It must be a valid integer greater than or equal to zero and less than \002%d\002."), max_exception_limit); @@ -453,12 +441,12 @@ private: Exception *e = session_service->GetExceptions()[Number - 1]; ListFormatter::ListEntry entry; - entry["Number"] = stringify(Number); + entry["Number"] = Anope::ToString(Number); entry["Mask"] = e->mask; entry["By"] = e->who; entry["Created"] = Anope::strftime(e->time, NULL, true); entry["Expires"] = Anope::Expires(e->expires, source.GetAccount()); - entry["Limit"] = stringify(e->limit); + entry["Limit"] = Anope::ToString(e->limit); entry["Reason"] = e->reason; this->list.AddEntry(entry); } @@ -474,12 +462,12 @@ private: if (mask.empty() || Anope::Match(e->mask, mask)) { ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Mask"] = e->mask; entry["By"] = e->who; entry["Created"] = Anope::strftime(e->time, NULL, true); entry["Expires"] = Anope::Expires(e->expires, source.GetAccount()); - entry["Limit"] = stringify(e->limit); + entry["Limit"] = Anope::ToString(e->limit); entry["Reason"] = e->reason; list.AddEntry(entry); } diff --git a/modules/operserv/os_set.cpp b/modules/operserv/os_set.cpp index a6cad4f07..b9c948e30 100644 --- a/modules/operserv/os_set.cpp +++ b/modules/operserv/os_set.cpp @@ -122,14 +122,14 @@ private: } else { - try + auto debug = Anope::TryConvert<int>(setting); + if (debug.has_value()) { - Anope::Debug = convertTo<int>(setting); + Anope::Debug = debug.value(); Log(LOG_ADMIN, source, this) << "DEBUG " << Anope::Debug; source.Reply(_("Services are now in \002debug\002 mode (level %d)."), Anope::Debug); return; } - catch (const ConvertException &) { } source.Reply(_("Setting for DEBUG must be \002ON\002, \002OFF\002, or a positive number.")); } diff --git a/modules/operserv/os_sxline.cpp b/modules/operserv/os_sxline.cpp index 769a25982..2460a5fe8 100644 --- a/modules/operserv/os_sxline.cpp +++ b/modules/operserv/os_sxline.cpp @@ -142,7 +142,7 @@ private: return; ListFormatter::ListEntry entry; - entry["Number"] = stringify(number); + entry["Number"] = Anope::ToString(number); entry["Mask"] = x->mask; entry["By"] = x->by; entry["Created"] = Anope::strftime(x->created, NULL, true); @@ -164,7 +164,7 @@ private: if (mask.empty() || mask.equals_ci(x->mask) || mask == x->id || Anope::Match(x->mask, mask, false, true)) { ListFormatter::ListEntry entry; - entry["Number"] = stringify(i + 1); + entry["Number"] = Anope::ToString(i + 1); entry["Mask"] = x->mask; entry["By"] = x->by; entry["Created"] = Anope::strftime(x->created, NULL, true); diff --git a/modules/protocol/bahamut.cpp b/modules/protocol/bahamut.cpp index 9c88b94a3..e80de36ad 100644 --- a/modules/protocol/bahamut.cpp +++ b/modules/protocol/bahamut.cpp @@ -19,15 +19,15 @@ public: bool IsValid(Anope::string &value) const override { - try - { - Anope::string rest; - if (!value.empty() && value[0] != ':' && convertTo<int>(value[0] == '*' ? value.substr(1) : value, rest, false) > 0 && rest[0] == ':' && rest.length() > 1 && convertTo<int>(rest.substr(1), rest, false) > 0 && rest.empty()) - return true; - } - catch (const ConvertException &) { } + if (value.empty() || value[0] == ':') + return false; + + Anope::string rest; + auto num1 = Anope::Convert<int>(value[0] == '*' ? value.substr(1) : value, 0, &rest); + if (num1 <= 0 || rest[0] != ':' || rest.length() <= 1) + return false; - return false; + return Anope::Convert<int>(rest.substr(1), 0, &rest) > 0 && rest.empty(); } }; @@ -52,7 +52,7 @@ public: if (Servers::Capab.count("TSMODE") > 0) { auto params = values; - params.insert(params.begin(), { chan->name, stringify(chan->creation_time), modes }); + params.insert(params.begin(), { chan->name, Anope::ToString(chan->creation_time), modes }); Uplink::SendInternal({}, source, "MODE", params); } else @@ -62,7 +62,7 @@ public: void SendModeInternal(const MessageSource &source, User *u, const Anope::string &modes, const std::vector<Anope::string> &values) override { auto params = values; - params.insert(params.begin(), { u->nick, stringify(u->timestamp), modes }); + params.insert(params.begin(), { u->nick, Anope::ToString(u->timestamp), modes }); Uplink::SendInternal({}, source, "SVSMODE", params); } @@ -323,13 +323,7 @@ struct IRCDMessageMode final if (params.size() > 2 && IRCD->IsChannelValid(params[0])) { Channel *c = Channel::Find(params[0]); - time_t ts = 0; - - try - { - ts = convertTo<time_t>(params[1]); - } - catch (const ConvertException &) { } + auto ts = Anope::Convert<time_t>(params[1], 0); Anope::string modes = params[2]; for (unsigned int i = 3; i < params.size(); ++i) @@ -382,8 +376,8 @@ struct IRCDMessageNick final } NickAlias *na = NULL; - time_t signon = params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0, - stamp = params[7].is_pos_number_only() ? convertTo<time_t>(params[7]) : 0; + auto signon = Anope::Convert<time_t>(params[2], 0); + auto stamp = Anope::Convert<time_t>(params[7], 0); if (signon && signon == stamp) na = NickAlias::Find(params[0]); @@ -406,7 +400,7 @@ struct IRCDMessageServer final void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { - unsigned int hops = Anope::string(params[1]).is_pos_number_only() ? convertTo<unsigned>(params[1]) : 0; + auto hops = Anope::Convert<unsigned>(params[1], 0); new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], hops, params[2]); } }; @@ -463,7 +457,7 @@ struct IRCDMessageSJoin final } } - time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : Anope::CurTime; + auto ts = Anope::Convert<time_t>(params[0], Anope::CurTime); Message::Join::SJoin(source, params[1], ts, modes, users); } }; @@ -477,7 +471,7 @@ struct IRCDMessageTopic final { Channel *c = Channel::Find(params[0]); if (c) - c->ChangeTopicInternal(source.GetUser(), params[1], params[3], Anope::string(params[2]).is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime); + c->ChangeTopicInternal(source.GetUser(), params[1], params[3], Anope::Convert<time_t>(params[2], Anope::CurTime)); } }; diff --git a/modules/protocol/hybrid.cpp b/modules/protocol/hybrid.cpp index 0f3f767d3..fc937d819 100644 --- a/modules/protocol/hybrid.cpp +++ b/modules/protocol/hybrid.cpp @@ -203,7 +203,7 @@ public: void SendModeInternal(const MessageSource &source, User *u, const Anope::string &modes, const std::vector<Anope::string> &values) override { auto params = values; - params.insert(params.begin(), { u->GetUID(), stringify(u->timestamp), modes }); + params.insert(params.begin(), { u->GetUID(), Anope::ToString(u->timestamp), modes }); Uplink::SendInternal({}, source, "SVSMODE", params); } @@ -468,7 +468,7 @@ struct IRCDMessageNick final /* :0MCAAAAAB NICK newnick 1350157102 */ void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { - source.GetUser()->ChangeNick(params[0], convertTo<time_t>(params[1])); + source.GetUser()->ChangeNick(params[0], Anope::Convert<time_t>(params[1], Anope::CurTime)); } }; @@ -531,7 +531,7 @@ struct IRCDMessageSID final /* :0MC SID hades.arpa 2 4XY + :ircd-hybrid test server */ void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { - unsigned int hops = params[1].is_pos_number_only() ? convertTo<unsigned>(params[1]) : 0; + auto hops = Anope::Convert(params[1], 0); new Server(source.GetServer() == NULL ? Me : source.GetServer(), params[0], hops, params.back(), params[2]); IRCD->SendPing(Me->GetName(), params[0]); @@ -581,7 +581,7 @@ struct IRCDMessageSJoin final users.push_back(sju); } - time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : Anope::CurTime; + auto ts = Anope::Convert<time_t>(params[0], Anope::CurTime); Message::Join::SJoin(source, params[1], ts, modes, users); } }; @@ -600,7 +600,7 @@ struct IRCDMessageSVSMode final if (!u) return; - if (!params[1].is_pos_number_only() || convertTo<time_t>(params[1]) != u->timestamp) + if (Anope::Convert<time_t>(params[1], 0) != u->timestamp) return; u->SetModesInternal(source, params[2]); @@ -618,7 +618,7 @@ struct IRCDMessageTBurst final { Anope::string setter; sepstream(params[3], '!').GetToken(setter, 0); - time_t topic_time = Anope::string(params[2]).is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime; + auto topic_time = Anope::Convert<time_t>(params[2], Anope::CurTime); Channel *c = Channel::Find(params[1]); if (c) @@ -635,14 +635,7 @@ struct IRCDMessageTMode final /* :0MC TMODE 1654867975 #nether +ntR */ void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { - time_t ts = 0; - - try - { - ts = convertTo<time_t>(params[0]); - } - catch (const ConvertException &) { } - + auto ts = Anope::Convert<time_t>(params[0], 0); Channel *c = Channel::Find(params[1]); Anope::string modes = params[2]; @@ -670,8 +663,7 @@ struct IRCDMessageUID final /* Source is always the server */ User::OnIntroduce(params[0], params[4], params[6], params[5], params[7], source.GetServer(), params[10], - params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0, - params[3], params[8], na ? *na->nc : NULL); + Anope::Convert<time_t>(params[2], 0), params[3], params[8], na ? *na->nc : NULL); } }; diff --git a/modules/protocol/inspircd.cpp b/modules/protocol/inspircd.cpp index fa7a509d6..72f1b1cf1 100644 --- a/modules/protocol/inspircd.cpp +++ b/modules/protocol/inspircd.cpp @@ -130,7 +130,7 @@ private: static void SendAccount(const Anope::string &uid, NickAlias *na) { - Uplink::Send("METADATA", uid, "accountid", na ? na->nc->GetId() : Anope::string()); + Uplink::Send("METADATA", uid, "accountid", na ? Anope::ToString(na->nc->GetId()) : Anope::string()); Uplink::Send("METADATA", uid, "accountname", na ? na->nc->display : Anope::string()); if (spanningtree_proto_ver >= 1206) Uplink::Send("METADATA", uid, "accountnicks", GetAccountNicks(na)); @@ -401,14 +401,14 @@ public: void SendNumericInternal(int numeric, const Anope::string &dest, const std::vector<Anope::string> ¶ms) override { auto newparams = params; - newparams.insert(newparams.begin(), { Me->GetSID(), dest, stringify(numeric) }); + newparams.insert(newparams.begin(), { Me->GetSID(), dest, Anope::ToString(numeric) }); Uplink::SendInternal({}, Me, "NUM", newparams); } void SendModeInternal(const MessageSource &source, Channel *chan, const Anope::string &modes, const std::vector<Anope::string> &values) override { auto params = values; - params.insert(params.begin(), { chan->name, stringify(chan->creation_time), modes }); + params.insert(params.begin(), { chan->name, Anope::ToString(chan->creation_time), modes }); Uplink::SendInternal({}, source, "FMODE", params); } @@ -923,32 +923,20 @@ public: return false; // no ':' or it's the first char, both are invalid Anope::string rest; - try - { - if (convertTo<int>(value, rest, false) <= 0) - return false; // negative numbers and zero are invalid - - rest = rest.substr(1); - int n; - if (historymode) - { - // For the history mode, the part after the ':' is a duration and it - // can be in the user friendly "1d3h20m" format, make sure we accept that - n = Anope::DoTime(rest); - } - else - n = convertTo<int>(rest); + if (Anope::Convert<int>(value, 0, &rest) <= 0) + return false; // negative numbers and zero are invalid - if (n <= 0) - return false; + rest = rest.substr(1); + if (historymode) + { + // For the history mode, the part after the ':' is a duration and it + // can be in the user friendly "1d3h20m" format, make sure we accept that + return Anope::DoTime(rest) <= 0; } - catch (const ConvertException &e) + else { - // conversion error, invalid - return false; + return Anope::Convert(rest, 0) <= 0; } - - return true; } }; @@ -963,18 +951,7 @@ public: if (value.empty()) return false; // empty param is never valid - try - { - if (convertTo<int>(value) <= 0) - return false; - } - catch (const ConvertException &e) - { - // conversion error, invalid - return false; - } - - return true; + return Anope::Convert<int>(value, 0) <= 0; } }; @@ -1068,15 +1045,15 @@ struct IRCDMessageCapab final static std::pair<Anope::string, size_t> ParseCapability(const Anope::string &token) { - auto sep = token.find(':'); + auto sep = token.find('='); if (sep == Anope::string::npos) return { token, 0 }; - auto value = token.substr(sep); + auto value = token.substr(sep + 1); if (!value.is_pos_number_only()) return { token, 0 }; - return { token.substr(0, sep), convertTo<size_t>(value) }; + return { token.substr(0, sep), Anope::Convert<size_t>(value, 0) }; } static bool ParseExtBan(const Anope::string &token, ExtBanInfo &extban) @@ -1117,7 +1094,7 @@ struct IRCDMessageCapab final return false; const Anope::string modelevel = token.substr(a + 1, b - a - 1); - mode.level = modelevel.is_pos_number_only() ? convertTo<unsigned>(modelevel) : 0; + mode.level = Anope::Convert<unsigned>(modelevel, 0); a = b; } @@ -1159,7 +1136,7 @@ struct IRCDMessageCapab final { spanningtree_proto_ver = 0; if (params.size() >= 2) - spanningtree_proto_ver = params[1].is_pos_number_only() ? convertTo<size_t>(params[1]) : 0; + spanningtree_proto_ver = Anope::Convert<size_t>(params[1], 0); if (spanningtree_proto_ver < 1205) { @@ -1769,18 +1746,8 @@ struct IRCDMessageSave final void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { User *targ = User::Find(params[0]); - time_t ts; - - try - { - ts = convertTo<time_t>(params[1]); - } - catch (const ConvertException &) - { - return; - } - - if (!targ || targ->timestamp != ts) + auto ts = Anope::Convert<time_t>(params[1], 0); + if (!targ || !ts || targ->timestamp != ts) return; BotInfo *bi; @@ -1847,7 +1814,7 @@ public: Anope::string modechr, modelimit; while (limitstream.GetToken(modechr) && limitstream.GetToken(modelimit)) { - limits.emplace(modechr[0], convertTo<unsigned>(modelimit)); + limits.emplace(modechr[0], Anope::Convert<unsigned>(modelimit, 0)); } maxlist.Set(c, limits); } @@ -2048,7 +2015,7 @@ struct IRCDMessageFJoin final users.push_back(sju); } - time_t ts = Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : Anope::CurTime; + auto ts = Anope::Convert<time_t>(params[0], Anope::CurTime); Message::Join::SJoin(source, params[0], ts, modes, users); } }; @@ -2067,17 +2034,7 @@ struct IRCDMessageFMode final modes += " " + params[n]; Channel *c = Channel::Find(params[0]); - time_t ts; - - try - { - ts = convertTo<time_t>(params[1]); - } - catch (const ConvertException &) - { - ts = 0; - } - + auto ts = Anope::Convert<time_t>(params[1], 0); if (c) c->SetModesInternal(source, modes, ts); } @@ -2098,7 +2055,7 @@ struct IRCDMessageFTopic final Channel *c = Channel::Find(params[0]); if (c) - c->ChangeTopicInternal(NULL, setby, topic, params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime); + c->ChangeTopicInternal(NULL, setby, topic, Anope::Convert<time_t>(params[2], Anope::CurTime)); } }; @@ -2147,7 +2104,7 @@ struct IRCDMessageIJoin final time_t chants = Anope::CurTime; if (params.size() >= 4) { - chants = params[2].is_pos_number_only() ? convertTo<unsigned>(params[2]) : 0; + chants = Anope::Convert<time_t>(params[2], 0); for (auto mode : params[3]) user.first.AddMode(mode); } @@ -2175,7 +2132,7 @@ struct IRCDMessageLMode final return; // Channel doesn't exist. // If the TS is greater than ours, we drop the mode and don't pass it anywhere. - auto chants = convertTo<time_t>(params[1]); + auto chants = Anope::Convert<time_t>(params[1], Anope::CurTime); if (chants > chan->creation_time) return; @@ -2307,7 +2264,7 @@ struct IRCDMessageServer final * 3: numeric * 4: desc */ - unsigned int hops = Anope::string(params[2]).is_pos_number_only() ? convertTo<unsigned>(params[2]) : 0; + auto hops = Anope::Convert<unsigned>(params[2], 0); new Server(Me, params[0], hops, params[4], params[3]); } else if (source.GetServer()) @@ -2380,7 +2337,7 @@ struct IRCDMessageUID final void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { size_t offset = params[9][0] == '+' ? 1 : 0; - time_t ts = convertTo<time_t>(params[1]); + time_t ts = Anope::Convert<time_t>(params[1], 0); Anope::string modes = params[8]; for (unsigned i = 9; i < params.size() - 1; ++i) @@ -2405,7 +2362,7 @@ struct IRCDMessageUID final User *u = User::OnIntroduce(params[2], params[5+offset], params[3], params[4], params[6+offset], source.GetServer(), params[params.size() - 1], ts, modes, params[0], na ? *na->nc : NULL); if (u) - u->signon = convertTo<time_t>(params[7+offset]); + u->signon = Anope::Convert<time_t>(params[7+offset], 0); } }; diff --git a/modules/protocol/ngircd.cpp b/modules/protocol/ngircd.cpp index 773fab805..ea9d92294 100644 --- a/modules/protocol/ngircd.cpp +++ b/modules/protocol/ngircd.cpp @@ -178,12 +178,11 @@ struct IRCDMessage005 final data = param.substr(pos+1, param.length()); if (parameter == "MODES") { - unsigned maxmodes = convertTo<unsigned>(data); - IRCD->MaxModes = maxmodes; + IRCD->MaxModes = Anope::Convert<unsigned>(data, IRCD->MaxModes); } else if (parameter == "NICKLEN") { - nicklen = data.is_pos_number_only() ? convertTo<size_t>(data) : 0; + nicklen = Anope::Convert<size_t>(data, 0); } } } @@ -557,7 +556,7 @@ struct IRCDMessageServer final else { // our uplink is introducing a new server - unsigned int hops = params[1].is_pos_number_only() ? convertTo<unsigned>(params[1]) : 0; + auto hops = Anope::Convert<unsigned>(params[1], 0); new Server(source.GetServer(), params[0], hops, params[3], params[2]); } /* diff --git a/modules/protocol/plexus.cpp b/modules/protocol/plexus.cpp index 1e5ae714b..a2282276a 100644 --- a/modules/protocol/plexus.cpp +++ b/modules/protocol/plexus.cpp @@ -144,7 +144,7 @@ public: void SendModeInternal(const MessageSource &source, User *u, const Anope::string &modes, const std::vector<Anope::string> &values) override { auto params = values; - params.insert(params.begin(), { "*", "SVSMODE", u->GetUID(), stringify(u->timestamp), modes }); + params.insert(params.begin(), { "*", "SVSMODE", u->GetUID(), Anope::ToString(u->timestamp), modes }); Uplink::SendInternal({}, source, "ENCAP", params); } @@ -306,23 +306,11 @@ struct IRCDMessageUID final if (ip == "0") ip.clear(); - time_t ts; - try - { - ts = convertTo<time_t>(params[2]); - } - catch (const ConvertException &) - { - ts = Anope::CurTime; - } - + auto ts = Anope::Convert<time_t>(params[2], Anope::CurTime); NickAlias *na = NULL; - try - { - if (params[8].is_pos_number_only() && convertTo<time_t>(params[8]) == ts) - na = NickAlias::Find(params[0]); - } - catch (const ConvertException &) { } + if (Anope::Convert<time_t>(params[8], 0) == ts) + na = NickAlias::Find(params[0]); + if (params[8] != "0" && !na) na = NickAlias::Find(params[8]); diff --git a/modules/protocol/ratbox.cpp b/modules/protocol/ratbox.cpp index 18dd448af..d6f7a1b3a 100644 --- a/modules/protocol/ratbox.cpp +++ b/modules/protocol/ratbox.cpp @@ -228,7 +228,7 @@ struct IRCDMessageTBurst final */ void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { - time_t topic_time = Anope::string(params[1]).is_pos_number_only() ? convertTo<time_t>(params[1]) : Anope::CurTime; + auto topic_time = Anope::Convert<time_t>(params[1], Anope::CurTime); Channel *c = Channel::Find(params[0]); if (!c) @@ -250,7 +250,7 @@ struct IRCDMessageUID final void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { /* Source is always the server */ - User::OnIntroduce(params[0], params[4], params[5], "", params[6], source.GetServer(), params[8], params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : 0, params[3], params[7], NULL); + User::OnIntroduce(params[0], params[4], params[5], "", params[6], source.GetServer(), params[8], Anope::Convert<time_t>(params[2], 0), params[3], params[7], NULL); } }; diff --git a/modules/protocol/solanum.cpp b/modules/protocol/solanum.cpp index 59d401741..6ac5cbc69 100644 --- a/modules/protocol/solanum.cpp +++ b/modules/protocol/solanum.cpp @@ -254,7 +254,7 @@ struct IRCDMessageEUID final if (params[9] != "*") na = NickAlias::Find(params[9]); - User::OnIntroduce(params[0], params[4], (params[8] != "*" ? params[8] : params[5]), params[5], params[6], source.GetServer(), params[10], params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime, params[3], params[7], na ? *na->nc : NULL); + User::OnIntroduce(params[0], params[4], (params[8] != "*" ? params[8] : params[5]), params[5], params[6], source.GetServer(), params[10], Anope::Convert<time_t>(params[2], Anope::CurTime), params[3], params[7], na ? *na->nc : NULL); } }; diff --git a/modules/protocol/unrealircd.cpp b/modules/protocol/unrealircd.cpp index c36cd10ed..d1d852d37 100644 --- a/modules/protocol/unrealircd.cpp +++ b/modules/protocol/unrealircd.cpp @@ -675,15 +675,16 @@ public: /* Borrowed part of this check from UnrealIRCd */ bool IsValid(Anope::string &value) const override { - if (value.empty()) + if (value.empty() || value[0] == ':') return false; - try - { - Anope::string rest; - if (value[0] != ':' && convertTo<unsigned>(value[0] == '*' ? value.substr(1) : value, rest, false) > 0 && rest[0] == ':' && rest.length() > 1 && convertTo<unsigned>(rest.substr(1), rest, false) > 0 && rest.empty()) - return true; - } - catch (const ConvertException &) { } + + Anope::string rest; + auto num1 = Anope::Convert<unsigned>(value[0] == '*' ? value.substr(1) : value, 0, &rest); + if (!num1 || rest[0] != ':' || rest.length() <= 1) + return false; + + if (Anope::Convert<int>(rest.substr(1), 0, &rest) > 0 && rest.empty()) + return true; /* '['<number><1 letter>[optional: '#'+1 letter],[next..]']'':'<number> */ size_t end_bracket = value.find(']', 1); @@ -702,16 +703,10 @@ public: ++p; if (p == arg.length() || (arg[p] != 'c' && arg[p] != 'j' && arg[p] != 'k' && arg[p] != 'm' && arg[p] != 'n' && arg[p] != 't')) continue; /* continue instead of break for forward compatibility. */ - try - { - int v = arg.substr(0, p).is_number_only() ? convertTo<int>(arg.substr(0, p)) : 0; - if (v < 1 || v > 999) - return false; - } - catch (const ConvertException &) - { + + auto v = Anope::Convert<int>(arg.substr(0, p), 0); + if (v < 1 || v > 999) return false; - } } return true; @@ -734,27 +729,14 @@ public: return false; // no ':' or it's the first char, both are invalid Anope::string rest; - try - { - if (convertTo<int>(value, rest, false) <= 0) - return false; // negative numbers and zero are invalid - - rest = rest.substr(1); - int n; - // The part after the ':' is a duration and it - // can be in the user friendly "1d3h20m" format, make sure we accept that - n = Anope::DoTime(rest); + if (Anope::Convert<int>(value, 0, &rest) <= 0) + return false; // negative numbers and zero are invalid - if (n <= 0) - return false; - } - catch (const ConvertException &e) - { - // conversion error, invalid + // The part after the ':' is a duration and it + // can be in the user friendly "1d3h20m" format, make sure we accept that + auto n = Anope::DoTime(rest.substr(1)); + return n <= 0; return false; - } - - return true; } }; @@ -1177,14 +1159,7 @@ struct IRCDMessageMode final if (IRCD->IsChannelValid(params[0])) { Channel *c = Channel::Find(params[0]); - time_t ts = 0; - - try - { - if (server_source) - ts = convertTo<time_t>(params[params.size() - 1]); - } - catch (const ConvertException &) { } + auto ts = Anope::Convert<time_t>(params[params.size() - 1], 0); if (c) c->SetModesInternal(source, modes, ts); @@ -1215,7 +1190,7 @@ struct IRCDMessageNetInfo final void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { - Uplink::Send("NETINFO", MaxUserCount, Anope::CurTime, convertTo<int>(params[2]), params[3], 0, 0, 0, params[7]); + Uplink::Send("NETINFO", MaxUserCount, Anope::CurTime, params[2], params[3], 0, 0, 0, params[7]); } }; @@ -1263,8 +1238,7 @@ struct IRCDMessageNick final if (vhost.equals_cs("*")) vhost.clear(); - time_t user_ts = params[2].is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime; - + auto user_ts = Anope::Convert<time_t>(params[2], Anope::CurTime); Server *s = Server::Find(params[5]); if (s == NULL) { @@ -1278,7 +1252,7 @@ struct IRCDMessageNick final ; else if (params[6].is_pos_number_only()) { - if (convertTo<time_t>(params[6]) == user_ts) + if (Anope::Convert<time_t>(params[6], 0) == user_ts) na = NickAlias::Find(params[0]); } else @@ -1398,7 +1372,7 @@ struct IRCDMessageServer final void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { - unsigned int hops = Anope::string(params[1]).is_pos_number_only() ? convertTo<unsigned>(params[1]) : 0; + auto hops = Anope::Convert<unsigned>(params[1], 0); if (params[1].equals_cs("1")) { @@ -1421,7 +1395,7 @@ struct IRCDMessageSID final void Run(MessageSource &source, const std::vector<Anope::string> ¶ms, const Anope::map<Anope::string> &tags) override { - unsigned int hops = Anope::string(params[1]).is_pos_number_only() ? convertTo<unsigned>(params[1]) : 0; + auto hops = Anope::Convert<unsigned>(params[1], 0); new Server(source.GetServer(), params[0], hops, params[3], params[2]); @@ -1503,7 +1477,7 @@ struct IRCDMessageSJoin final } } - time_t ts = Anope::string(params[0]).is_pos_number_only() ? convertTo<time_t>(params[0]) : Anope::CurTime; + auto ts = Anope::Convert<time_t>(params[0], Anope::CurTime); Message::Join::SJoin(source, params[1], ts, modes, users); if (!bans.empty() || !excepts.empty() || !invites.empty()) @@ -1582,7 +1556,7 @@ struct IRCDMessageTopic final { Channel *c = Channel::Find(params[0]); if (c) - c->ChangeTopicInternal(source.GetUser(), params[1], params[3], Anope::string(params[2]).is_pos_number_only() ? convertTo<time_t>(params[2]) : Anope::CurTime); + c->ChangeTopicInternal(source.GetUser(), params[1], params[3], Anope::Convert<time_t>(params[2], Anope::CurTime)); } }; @@ -1637,16 +1611,7 @@ struct IRCDMessageUID final if (chost == "*") chost.clear(); - time_t user_ts; - try - { - user_ts = convertTo<time_t>(timestamp); - } - catch (const ConvertException &) - { - user_ts = Anope::CurTime; - } - + auto user_ts = Anope::Convert<time_t>(timestamp, Anope::CurTime); NickAlias *na = NULL; if (account == "0") @@ -1655,7 +1620,7 @@ struct IRCDMessageUID final } else if (account.is_pos_number_only()) { - if (convertTo<time_t>(account) == user_ts) + if (Anope::Convert<time_t>(account, 0) == user_ts) na = NickAlias::Find(nickname); } else diff --git a/modules/proxyscan.cpp b/modules/proxyscan.cpp index 42beb37e5..e7c761c9f 100644 --- a/modules/proxyscan.cpp +++ b/modules/proxyscan.cpp @@ -88,7 +88,7 @@ protected: reason = reason.replace_all_cs("%t", this->GetType()); reason = reason.replace_all_cs("%i", this->conaddr.addr()); - reason = reason.replace_all_cs("%p", stringify(this->conaddr.port())); + reason = reason.replace_all_cs("%p", Anope::ToString(this->conaddr.port())); BotInfo *OperServ = Config->GetClient("OperServ"); Log(OperServ) << "PROXYSCAN: Open " << this->GetType() << " proxy found on " << this->conaddr.str() << " (" << reason << ")"; @@ -321,12 +321,8 @@ public: commasepstream sep2(block->Get<const Anope::string>("port")); while (sep2.GetToken(token)) { - try - { - unsigned short port = convertTo<unsigned short>(token); - p.ports.push_back(port); - } - catch (const ConvertException &) { } + if (auto port = Anope::TryConvert<unsigned short>(token)) + p.ports.push_back(port.value()); } if (p.ports.empty()) continue; diff --git a/modules/redis.cpp b/modules/redis.cpp index 8b333a7ff..4e006c9ff 100644 --- a/modules/redis.cpp +++ b/modules/redis.cpp @@ -127,13 +127,13 @@ private: std::vector<char> buffer; Pack(buffer, "*"); - Pack(buffer, stringify(args.size()).c_str()); + Pack(buffer, Anope::ToString(args.size()).c_str()); Pack(buffer, "\r\n"); for (const auto &[key, value] : args) { Pack(buffer, "$"); - Pack(buffer, stringify(value).c_str()); + Pack(buffer, Anope::ToString(value).c_str()); Pack(buffer, "\r\n"); Pack(buffer, key, value); @@ -278,7 +278,7 @@ void RedisSocket::OnConnect() Log() << "redis: Successfully connected to " << provider->name << (this == this->provider->sub ? " (sub)" : ""); this->provider->SendCommand(NULL, "CLIENT SETNAME Anope"); - this->provider->SendCommand(NULL, "SELECT " + stringify(provider->db)); + this->provider->SendCommand(NULL, "SELECT " + Anope::ToString(provider->db)); if (this != this->provider->sub) { @@ -333,11 +333,8 @@ size_t RedisSocket::ParseReply(Reply &r, const char *buffer, size_t l) size_t nl = ibuf.find("\r\n"); if (nl != Anope::string::npos) { - try - { - r.i = convertTo<int64_t>(ibuf.substr(0, nl)); - } - catch (const ConvertException &) { } + if (auto i = Anope::TryConvert<int64_t>(ibuf.substr(0, nl))) + r.i = i.value(); r.type = Reply::INT; used = 1 + nl + 2; @@ -351,10 +348,9 @@ size_t RedisSocket::ParseReply(Reply &r, const char *buffer, size_t l) size_t nl = reply.find("\r\n"); if (nl != Anope::string::npos) { - int len; - try + if (auto l = Anope::TryConvert<int>(reply.substr(0, nl))) { - len = convertTo<int>(reply.substr(0, nl)); + int len = l.value(); if (len >= 0) { if (1 + nl + 2 + len + 2 <= l) @@ -370,7 +366,6 @@ size_t RedisSocket::ParseReply(Reply &r, const char *buffer, size_t l) r.type = Reply::BULK; } } - catch (const ConvertException &) { } } break; } @@ -384,12 +379,8 @@ size_t RedisSocket::ParseReply(Reply &r, const char *buffer, size_t l) if (nl != Anope::string::npos) { r.type = Reply::MULTI_BULK; - try - { - r.multi_bulk_size = convertTo<int>(reply.substr(0, nl)); - } - catch (const ConvertException &) { } - + if (auto size = Anope::TryConvert<int>(reply.substr(0, nl))) + r.multi_bulk_size = size.value(); used = 1 + nl + 2; } else diff --git a/modules/rewrite.cpp b/modules/rewrite.cpp index 3911b5ddf..008e3e722 100644 --- a/modules/rewrite.cpp +++ b/modules/rewrite.cpp @@ -38,28 +38,35 @@ struct Rewrite final else { int num = -1, end = -1; - try + Anope::string num_str = token.substr(1); + size_t hy = num_str.find('-'); + if (hy == Anope::string::npos) { - Anope::string num_str = token.substr(1); - size_t hy = num_str.find('-'); - if (hy == Anope::string::npos) - { - num = convertTo<int>(num_str); - end = num + 1; - } + auto n = Anope::TryConvert<int>(num_str); + if (!n.has_value()) + continue; + + num = n.value(); + end = num + 1; + } + else + { + auto n = Anope::TryConvert<int>(num_str.substr(0, hy)); + if (!n.has_value()) + continue; + + num = n.value(); + if (hy == num_str.length() - 1) + end = params.size(); else { - num = convertTo<int>(num_str.substr(0, hy)); - if (hy == num_str.length() - 1) - end = params.size(); - else - end = convertTo<int>(num_str.substr(hy + 1)) + 1; + n = Anope::TryConvert<int>(num_str.substr(hy + 1)); + if (!n.has_value()) + continue; + + end = n.value() + 1; } } - catch (const ConvertException &) - { - continue; - } for (int i = num; i < end && static_cast<unsigned>(i) < params.size(); ++i) message += " " + params[i]; diff --git a/modules/webcpanel/pages/memoserv/memos.cpp b/modules/webcpanel/pages/memoserv/memos.cpp index 7eec4ec02..d7fb76d74 100644 --- a/modules/webcpanel/pages/memoserv/memos.cpp +++ b/modules/webcpanel/pages/memoserv/memos.cpp @@ -73,14 +73,10 @@ bool WebCPanel::MemoServ::Memos::OnRequest(HTTPProvider *server, const Anope::st std::vector<Anope::string> params; int number = -1; - try - { - number = convertTo<int>(message.get_data["number"]); - } - catch (const ConvertException &ex) - { + if (auto num = Anope::TryConvert<int>(message.get_data["number"])) + number = num.value(); + else replacements["MESSAGES"] = "ERROR - invalid parameter for NUMBER"; - } if (number > 0) { @@ -98,7 +94,7 @@ bool WebCPanel::MemoServ::Memos::OnRequest(HTTPProvider *server, const Anope::st for (unsigned i = 0; i < mi->memos->size(); ++i) { m = mi->GetMemo(i); - replacements["NUMBER"] = stringify(i+1); + replacements["NUMBER"] = Anope::ToString(i+1); replacements["SENDER"] = m->sender; replacements["TIME"] = Anope::strftime(m->time); replacements["TEXT"] = m->text; diff --git a/modules/webcpanel/pages/nickserv/alist.cpp b/modules/webcpanel/pages/nickserv/alist.cpp index ddc394962..48c61d83e 100644 --- a/modules/webcpanel/pages/nickserv/alist.cpp +++ b/modules/webcpanel/pages/nickserv/alist.cpp @@ -30,7 +30,7 @@ bool WebCPanel::NickServ::Alist::OnRequest(HTTPProvider *server, const Anope::st { ++chan_count; - replacements["NUMBERS"] = stringify(chan_count); + replacements["NUMBERS"] = Anope::ToString(chan_count); replacements["CHANNELS"] = (ci->HasExt("CS_NO_EXPIRE") ? "!" : "") + ci->name; replacements["ACCESSES"] = "Founder"; continue; @@ -42,7 +42,7 @@ bool WebCPanel::NickServ::Alist::OnRequest(HTTPProvider *server, const Anope::st ++chan_count; - replacements["NUMBERS"] = stringify(chan_count); + replacements["NUMBERS"] = Anope::ToString(chan_count); replacements["CHANNELS"] = (ci->HasExt("CS_NO_EXPIRE") ? "!" : "") + ci->name; const ChanAccess *highest = access.Highest(); diff --git a/modules/webcpanel/pages/operserv/akill.cpp b/modules/webcpanel/pages/operserv/akill.cpp index 424635f94..c7cb8ab9a 100644 --- a/modules/webcpanel/pages/operserv/akill.cpp +++ b/modules/webcpanel/pages/operserv/akill.cpp @@ -48,7 +48,7 @@ bool WebCPanel::OperServ::Akill::OnRequest(HTTPProvider *server, const Anope::st for (unsigned i = 0, end = akills->GetCount(); i < end; ++i) { const XLine *x = akills->GetEntry(i); - replacements["NUMBER"] = stringify(i + 1); + replacements["NUMBER"] = Anope::ToString(i + 1); replacements["HOST"] = x->mask; replacements["SETTER"] = x->by; replacements["TIME"] = Anope::strftime(x->created, NULL, true); diff --git a/modules/xmlrpc_main.cpp b/modules/xmlrpc_main.cpp index dedb587f9..abf648da8 100644 --- a/modules/xmlrpc_main.cpp +++ b/modules/xmlrpc_main.cpp @@ -141,7 +141,7 @@ private: static void DoStats(XMLRPCServiceInterface *iface, HTTPClient *client, XMLRPCRequest &request) { - request.reply("uptime", stringify(Anope::CurTime - Anope::StartTime)); + request.reply("uptime", Anope::ToString(Anope::CurTime - Anope::StartTime)); request.reply("uplinkname", Me->GetLinks().front()->GetName()); { Anope::string buf; @@ -151,9 +151,9 @@ private: buf.erase(buf.begin()); request.reply("uplinkcapab", buf); } - request.reply("usercount", stringify(UserListByNick.size())); - request.reply("maxusercount", stringify(MaxUserCount)); - request.reply("channelcount", stringify(ChannelList.size())); + request.reply("usercount", Anope::ToString(UserListByNick.size())); + request.reply("maxusercount", Anope::ToString(MaxUserCount)); + request.reply("channelcount", Anope::ToString(ChannelList.size())); } static void DoChannel(XMLRPCServiceInterface *iface, HTTPClient *client, XMLRPCRequest &request) @@ -167,20 +167,20 @@ private: if (c) { - request.reply("bancount", stringify(c->HasMode("BAN"))); + request.reply("bancount", Anope::ToString(c->HasMode("BAN"))); int count = 0; for (auto &ban : c->GetModeList("BAN")) - request.reply("ban" + stringify(++count), iface->Sanitize(ban)); + request.reply("ban" + Anope::ToString(++count), iface->Sanitize(ban)); - request.reply("exceptcount", stringify(c->HasMode("EXCEPT"))); + request.reply("exceptcount", Anope::ToString(c->HasMode("EXCEPT"))); count = 0; for (auto &except : c->GetModeList("EXCEPT")) - request.reply("except" + stringify(++count), iface->Sanitize(except)); + request.reply("except" + Anope::ToString(++count), iface->Sanitize(except)); - request.reply("invitecount", stringify(c->HasMode("INVITEOVERRIDE"))); + request.reply("invitecount", Anope::ToString(c->HasMode("INVITEOVERRIDE"))); count = 0; for (auto &invite : c->GetModeList("INVITEOVERRIDE")) - request.reply("invite" + stringify(++count), iface->Sanitize(invite)); + request.reply("invite" + Anope::ToString(++count), iface->Sanitize(invite)); Anope::string users; for (Channel::ChanUserList::const_iterator it = c->users.begin(); it != c->users.end(); ++it) @@ -200,8 +200,8 @@ private: if (!c->topic_setter.empty()) request.reply("topicsetter", iface->Sanitize(c->topic_setter)); - request.reply("topictime", stringify(c->topic_time)); - request.reply("topicts", stringify(c->topic_ts)); + request.reply("topictime", Anope::ToString(c->topic_time)); + request.reply("topicts", Anope::ToString(c->topic_ts)); } } @@ -224,8 +224,8 @@ private: if (!u->chost.empty()) request.reply("chost", iface->Sanitize(u->chost)); request.reply("ip", u->ip.addr()); - request.reply("timestamp", stringify(u->timestamp)); - request.reply("signon", stringify(u->signon)); + request.reply("timestamp", Anope::ToString(u->timestamp)); + request.reply("signon", Anope::ToString(u->signon)); if (u->Account()) { request.reply("account", iface->Sanitize(u->Account()->display)); diff --git a/src/config.cpp b/src/config.cpp index ca36bea7d..6a8380464 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -824,12 +824,12 @@ void Conf::LoadConf(File &file) if (block_stack.empty() || itemname.empty()) { file.Close(); - throw ConfigException("Unexpected quoted string: " + file.GetName() + ":" + stringify(linenumber)); + throw ConfigException("Unexpected quoted string: " + file.GetName() + ":" + Anope::ToString(linenumber)); } if (in_word || !wordbuffer.empty()) { file.Close(); - throw ConfigException("Unexpected quoted string (prior unhandled words): " + file.GetName() + ":" + stringify(linenumber)); + throw ConfigException("Unexpected quoted string (prior unhandled words): " + file.GetName() + ":" + Anope::ToString(linenumber)); } in_quote = in_word = true; } @@ -838,13 +838,13 @@ void Conf::LoadConf(File &file) if (block_stack.empty()) { file.Close(); - throw ConfigException("Config item outside of section (or stray '='): " + file.GetName() + ":" + stringify(linenumber)); + throw ConfigException("Config item outside of section (or stray '='): " + file.GetName() + ":" + Anope::ToString(linenumber)); } if (!itemname.empty() || wordbuffer.empty()) { file.Close(); - throw ConfigException("Stray '=' sign or item without value: " + file.GetName() + ":" + stringify(linenumber)); + throw ConfigException("Stray '=' sign or item without value: " + file.GetName() + ":" + Anope::ToString(linenumber)); } in_word = false; @@ -891,7 +891,7 @@ void Conf::LoadConf(File &file) if (!in_word && !wordbuffer.empty()) { file.Close(); - throw ConfigException("Unexpected word: " + file.GetName() + ":" + stringify(linenumber)); + throw ConfigException("Unexpected word: " + file.GetName() + ":" + Anope::ToString(linenumber)); } wordbuffer += ch; in_word = true; @@ -918,7 +918,7 @@ void Conf::LoadConf(File &file) if (block_stack.empty()) { file.Close(); - throw ConfigException("Stray ';' outside of block: " + file.GetName() + ":" + stringify(linenumber)); + throw ConfigException("Stray ';' outside of block: " + file.GetName() + ":" + Anope::ToString(linenumber)); } Block *b = block_stack.top(); @@ -949,7 +949,7 @@ void Conf::LoadConf(File &file) if (block_stack.empty()) { file.Close(); - throw ConfigException("Stray '}': " + file.GetName() + ":" + stringify(linenumber)); + throw ConfigException("Stray '}': " + file.GetName() + ":" + Anope::ToString(linenumber)); } block_stack.pop(); @@ -969,7 +969,7 @@ void Conf::LoadConf(File &file) if (!block_stack.empty()) { if (block_stack.top()) - throw ConfigException("Unterminated block at end of file: " + file.GetName() + ". Block was opened on line " + stringify(block_stack.top()->linenum)); + throw ConfigException("Unterminated block at end of file: " + file.GetName() + ". Block was opened on line " + Anope::ToString(block_stack.top()->linenum)); else throw ConfigException("Unterminated commented block at end of file: " + file.GetName()); } diff --git a/src/init.cpp b/src/init.cpp index 969263191..c6cb62428 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -148,10 +148,10 @@ void Anope::HandleSignal() case SIGINT: #ifndef _WIN32 Log() << "Received " << strsignal(Signal) << " signal (" << Signal << "), exiting."; - Anope::QuitReason = Anope::string("Services terminating via signal ") + strsignal(Signal) + " (" + stringify(Signal) + ")"; + Anope::QuitReason = Anope::string("Services terminating via signal ") + strsignal(Signal) + " (" + Anope::ToString(Signal) + ")"; #else Log() << "Received signal " << Signal << ", exiting."; - Anope::QuitReason = Anope::string("Services terminating via signal ") + stringify(Signal); + Anope::QuitReason = Anope::string("Services terminating via signal ") + Anope::ToString(Signal); #endif Anope::Quitting = true; Anope::SaveDatabases(); @@ -355,7 +355,7 @@ bool Anope::Init(int ac, char **av) { if (!arg.empty()) { - int level = arg.is_number_only() ? convertTo<int>(arg) : -1; + auto level = Anope::Convert<int>(arg, -1); if (level > 0) Anope::Debug = level; else diff --git a/src/misc.cpp b/src/misc.cpp index f7ada8f60..a64de450e 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -45,13 +45,12 @@ NumberList::NumberList(const Anope::string &list, bool descending) : desc(descen if (t == Anope::string::npos) { - try + if (auto num = Anope::TryConvert<unsigned>(token, &error)) { - unsigned num = convertTo<unsigned>(token, error, false); if (error.empty()) - numbers.insert(num); + numbers.insert(num.value()); } - catch (const ConvertException &) + else { error = "1"; } @@ -68,15 +67,17 @@ NumberList::NumberList(const Anope::string &list, bool descending) : desc(descen else { Anope::string error2; - try + auto n1 = Anope::TryConvert<unsigned>(token.substr(0, t), &error); + auto n2 = Anope::TryConvert<unsigned>(token.substr(t + 1), &error); + if (n1.has_value() && n2.has_value()) { - unsigned num1 = convertTo<unsigned>(token.substr(0, t), error, false); - unsigned num2 = convertTo<unsigned>(token.substr(t + 1), error2, false); + auto num1 = n1.value(); + auto num2 = n2.value(); if (error.empty() && error2.empty()) for (unsigned i = num1; i <= num2; ++i) numbers.insert(i); } - catch (const ConvertException &) + else { error = "1"; } @@ -271,37 +272,28 @@ time_t Anope::DoTime(const Anope::string &s) if (s.empty()) return 0; - int amount = 0; Anope::string end; - - try + auto amount = Anope::Convert<int>(s, -1, &end); + if (!end.empty()) { - amount = convertTo<int>(s, end, false); - if (!end.empty()) + switch (end[0]) { - switch (end[0]) - { - case 's': - return amount; - case 'm': - return amount * 60; - case 'h': - return amount * 3600; - case 'd': - return amount * 86400; - case 'w': - return amount * 86400 * 7; - case 'y': - return amount * 86400 * 365; - default: - break; - } + case 's': + return amount; + case 'm': + return amount * 60; + case 'h': + return amount * 3600; + case 'd': + return amount * 86400; + case 'w': + return amount * 86400 * 7; + case 'y': + return amount * 86400 * 365; + default: + break; } } - catch (const ConvertException &) - { - amount = -1; - } return amount; } @@ -316,32 +308,32 @@ Anope::string Anope::Duration(time_t t, const NickCore *nc) time_t seconds = (t) % 60; if (!years && !days && !hours && !minutes) - return stringify(seconds) + " " + (seconds != 1 ? Language::Translate(nc, _("seconds")) : Language::Translate(nc, _("second"))); + return Anope::ToString(seconds) + " " + (seconds != 1 ? Language::Translate(nc, _("seconds")) : Language::Translate(nc, _("second"))); else { bool need_comma = false; Anope::string buffer; if (years) { - buffer = stringify(years) + " " + (years != 1 ? Language::Translate(nc, _("years")) : Language::Translate(nc, _("year"))); + buffer = Anope::ToString(years) + " " + (years != 1 ? Language::Translate(nc, _("years")) : Language::Translate(nc, _("year"))); need_comma = true; } if (days) { buffer += need_comma ? ", " : ""; - buffer += stringify(days) + " " + (days != 1 ? Language::Translate(nc, _("days")) : Language::Translate(nc, _("day"))); + buffer += Anope::ToString(days) + " " + (days != 1 ? Language::Translate(nc, _("days")) : Language::Translate(nc, _("day"))); need_comma = true; } if (hours) { buffer += need_comma ? ", " : ""; - buffer += stringify(hours) + " " + (hours != 1 ? Language::Translate(nc, _("hours")) : Language::Translate(nc, _("hour"))); + buffer += Anope::ToString(hours) + " " + (hours != 1 ? Language::Translate(nc, _("hours")) : Language::Translate(nc, _("hour"))); need_comma = true; } if (minutes) { buffer += need_comma ? ", " : ""; - buffer += stringify(minutes) + " " + (minutes != 1 ? Language::Translate(nc, _("minutes")) : Language::Translate(nc, _("minute"))); + buffer += Anope::ToString(minutes) + " " + (minutes != 1 ? Language::Translate(nc, _("minutes")) : Language::Translate(nc, _("minute"))); } return buffer; } @@ -596,23 +588,23 @@ Anope::string Anope::LastError() Anope::string Anope::Version() { #ifdef VERSION_GIT - return stringify(VERSION_MAJOR) + "." + stringify(VERSION_MINOR) + "." + stringify(VERSION_PATCH) + VERSION_EXTRA + " (" + VERSION_GIT + ")"; + return Anope::ToString(VERSION_MAJOR) + "." + Anope::ToString(VERSION_MINOR) + "." + Anope::ToString(VERSION_PATCH) + VERSION_EXTRA + " (" + VERSION_GIT + ")"; #else - return stringify(VERSION_MAJOR) + "." + stringify(VERSION_MINOR) + "." + stringify(VERSION_PATCH) + VERSION_EXTRA; + return Anope::ToString(VERSION_MAJOR) + "." + Anope::ToString(VERSION_MINOR) + "." + Anope::ToString(VERSION_PATCH) + VERSION_EXTRA; #endif } Anope::string Anope::VersionShort() { - return stringify(VERSION_MAJOR) + "." + stringify(VERSION_MINOR) + "." + stringify(VERSION_PATCH); + return Anope::ToString(VERSION_MAJOR) + "." + Anope::ToString(VERSION_MINOR) + "." + Anope::ToString(VERSION_PATCH); } Anope::string Anope::VersionBuildString() { #ifdef REPRODUCIBLE_BUILD - Anope::string s = "build #" + stringify(BUILD); + Anope::string s = "build #" + Anope::ToString(BUILD); #else - Anope::string s = "build #" + stringify(BUILD) + ", compiled " + Anope::compiled; + Anope::string s = "build #" + Anope::ToString(BUILD) + ", compiled " + Anope::compiled; #endif Anope::string flags; diff --git a/src/modes.cpp b/src/modes.cpp index 9d344e153..8b2534268 100644 --- a/src/modes.cpp +++ b/src/modes.cpp @@ -398,7 +398,7 @@ bool ModeManager::AddUserMode(UserMode *um) if (um->name.empty()) { - um->name = stringify(++GenericUserModes); + um->name = Anope::ToString(++GenericUserModes); Log() << "ModeManager: Added generic support for user mode " << um->mchar; } @@ -425,7 +425,7 @@ bool ModeManager::AddChannelMode(ChannelMode *cm) if (cm->name.empty()) { - cm->name = stringify(++GenericChannelModes); + cm->name = Anope::ToString(++GenericChannelModes); Log() << "ModeManager: Added generic support for channel mode " << cm->mchar; } @@ -783,22 +783,15 @@ Entry::Entry(const Anope::string &m, const Anope::string &fh) : name(m), mask(fh &cidr_range = this->host.substr(sl + 1); sockaddrs addr(cidr_ip); - - try + auto range = Anope::TryConvert<unsigned short>(cidr_range); + if (addr.valid() && range.has_value()) { - if (addr.valid() && cidr_range.is_pos_number_only()) - { - this->cidr_len = convertTo<unsigned short>(cidr_range); - - /* If we got here, cidr_len is a valid number. */ - - this->host = cidr_ip; - this->family = addr.family(); + this->cidr_len = range.value(); + this->host = cidr_ip; + this->family = addr.family(); - Log(LOG_DEBUG) << "Ban " << mask << " has cidr " << this->cidr_len; - } + Log(LOG_DEBUG) << "Ban " << mask << " has cidr " << this->cidr_len; } - catch (const ConvertException &) { } } } @@ -822,11 +815,11 @@ Anope::string Entry::GetNUHMask() const { case AF_INET: if (cidr_len <= 32) - c = "/" + stringify(cidr_len); + c = "/" + Anope::ToString(cidr_len); break; case AF_INET6: if (cidr_len <= 128) - c = "/" + stringify(cidr_len); + c = "/" + Anope::ToString(cidr_len); break; } diff --git a/src/modulemanager.cpp b/src/modulemanager.cpp index 2da87c96f..c350f8efd 100644 --- a/src/modulemanager.cpp +++ b/src/modulemanager.cpp @@ -348,7 +348,7 @@ void ModuleManager::RequireVersion(int major, int minor, int patch) } } - throw ModuleException("This module requires version " + stringify(major) + "." + stringify(minor) + "." + stringify(patch) + " - this is " + Anope::VersionShort()); + throw ModuleException("This module requires version " + Anope::ToString(major) + "." + Anope::ToString(minor) + "." + Anope::ToString(patch) + " - this is " + Anope::VersionShort()); } ModuleReturn ModuleManager::DeleteModule(Module *m) diff --git a/src/nickcore.cpp b/src/nickcore.cpp index ae9e15334..5629b00fd 100644 --- a/src/nickcore.cpp +++ b/src/nickcore.cpp @@ -213,7 +213,7 @@ uint64_t NickCore::GetId() return 0; } - Anope::string secretid = this->display + "\0" + stringify(na->time_registered); + Anope::string secretid = this->display + "\0" + Anope::ToString(na->time_registered); // Generate the account id. This should almost always only have one // iteration but in the rare case that we generate a duplicate id we try diff --git a/src/protocol.cpp b/src/protocol.cpp index 6fb7d3398..4893173af 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -157,7 +157,7 @@ void IRCDProto::SendCTCPInternal(const MessageSource &source, const Anope::strin void IRCDProto::SendNumericInternal(int numeric, const Anope::string &dest, const std::vector<Anope::string> ¶ms) { - Anope::string n = stringify(numeric); + Anope::string n = Anope::ToString(numeric); if (numeric < 10) n = "0" + n; if (numeric < 100) diff --git a/src/regchannel.cpp b/src/regchannel.cpp index 404f55aae..6aaf02901 100644 --- a/src/regchannel.cpp +++ b/src/regchannel.cpp @@ -195,7 +195,7 @@ void ChannelInfo::Serialize(Serialize::Data &data) const { Anope::string levels_buffer; for (const auto &[name, level] : this->levels) - levels_buffer += name + " " + stringify(level) + " "; + levels_buffer += name + " " + Anope::ToString(level) + " "; data["levels"] << levels_buffer; } if (this->bi) @@ -238,11 +238,10 @@ Serializable *ChannelInfo::Unserialize(Serializable *obj, Serialize::Data &data) std::vector<Anope::string> v; spacesepstream(slevels).GetTokens(v); for (unsigned i = 0; i + 1 < v.size(); i += 2) - try - { - ci->levels[v[i]] = convertTo<int16_t>(v[i + 1]); - } - catch (const ConvertException &) { } + { + if (auto level = Anope::TryConvert<int16_t>(v[i + 1])) + ci->levels[v[i]] = level.value(); + } } BotInfo *bi = BotInfo::Find(sbi, true); if (*ci->bi != bi) diff --git a/src/socketengines/epoll.cpp b/src/socketengines/epoll.cpp index e67745096..eb70de630 100644 --- a/src/socketengines/epoll.cpp +++ b/src/socketengines/epoll.cpp @@ -67,7 +67,7 @@ void SocketEngine::Change(Socket *s, bool set, SocketFlag flag) return; if (epoll_ctl(EngineHandle, mod, ev.data.fd, &ev) == -1) - throw SocketException("Unable to epoll_ctl() fd " + stringify(ev.data.fd) + " to epoll: " + Anope::LastError()); + throw SocketException("Unable to epoll_ctl() fd " + Anope::ToString(ev.data.fd) + " to epoll: " + Anope::LastError()); } void SocketEngine::Process() diff --git a/src/socketengines/poll.cpp b/src/socketengines/poll.cpp index e9a81933b..feeac5967 100644 --- a/src/socketengines/poll.cpp +++ b/src/socketengines/poll.cpp @@ -71,7 +71,7 @@ void SocketEngine::Change(Socket *s, bool set, SocketFlag flag) { std::map<int, unsigned>::iterator pos = socket_positions.find(s->GetFD()); if (pos == socket_positions.end()) - throw SocketException("Unable to remove fd " + stringify(s->GetFD()) + " from poll, it does not exist?"); + throw SocketException("Unable to remove fd " + Anope::ToString(s->GetFD()) + " from poll, it does not exist?"); if (pos->second != events.size() - 1) { @@ -90,7 +90,7 @@ void SocketEngine::Change(Socket *s, bool set, SocketFlag flag) { std::map<int, unsigned>::iterator pos = socket_positions.find(s->GetFD()); if (pos == socket_positions.end()) - throw SocketException("Unable to modify fd " + stringify(s->GetFD()) + " in poll, it does not exist?"); + throw SocketException("Unable to modify fd " + Anope::ToString(s->GetFD()) + " in poll, it does not exist?"); pollfd &ev = events[pos->second]; ev.events = (s->flags[SF_READABLE] ? POLLIN : 0) | (s->flags[SF_WRITABLE] ? POLLOUT : 0); diff --git a/src/sockets.cpp b/src/sockets.cpp index fc2940a59..6d6718547 100644 --- a/src/sockets.cpp +++ b/src/sockets.cpp @@ -282,13 +282,7 @@ cidr::cidr(const Anope::string &ip) Anope::string cidr_range = ip.substr(sl + 1); this->cidr_ip = real_ip; - this->cidr_len = ipv6 ? 128 : 32; - try - { - if (cidr_range.is_pos_number_only()) - this->cidr_len = convertTo<unsigned int>(cidr_range); - } - catch (const ConvertException &) { } + this->cidr_len = Anope::Convert<unsigned int>(cidr_range, ipv6 ? 128 : 32); this->addr.pton(ipv6 ? AF_INET6 : AF_INET, real_ip); } } |