Compiles with C++17, replaces ghc::filesystem with std::filesystem,
nonstd::optional with std::optional, and llarp::string_view with
std::string_view.
pull/1250/head
Jason Rhinelander 4 years ago
parent 5a2141bae8
commit 1697bf90fe

6
.gitmodules vendored

@ -7,15 +7,9 @@
[submodule "external/cxxopts"] [submodule "external/cxxopts"]
path = external/cxxopts path = external/cxxopts
url = https://github.com/jarro2783/cxxopts.git url = https://github.com/jarro2783/cxxopts.git
[submodule "external/ghc-filesystem"]
path = external/ghc-filesystem
url = https://github.com/gulrak/filesystem.git
[submodule "test/Catch2"] [submodule "test/Catch2"]
path = test/Catch2 path = test/Catch2
url = https://github.com/catchorg/Catch2 url = https://github.com/catchorg/Catch2
[submodule "external/optional-lite"]
path = external/optional-lite
url = https://github.com/martinmoene/optional-lite.git
[submodule "external/date"] [submodule "external/date"]
path = external/date path = external/date
url = https://github.com/HowardHinnant/date.git url = https://github.com/HowardHinnant/date.git

@ -81,6 +81,14 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
include(MacroEnsureOutOfSourceBuild) include(MacroEnsureOutOfSourceBuild)
macro_ensure_out_of_source_build("${PROJECT_NAME} requires an out-of-source build. Create a build directory and run 'cmake ${CMAKE_SOURCE_DIR} [options]'.") macro_ensure_out_of_source_build("${PROJECT_NAME} requires an out-of-source build. Create a build directory and run 'cmake ${CMAKE_SOURCE_DIR} [options]'.")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
include(cmake/unix.cmake) include(cmake/unix.cmake)
if(NOT WIN32) if(NOT WIN32)
@ -97,14 +105,6 @@ if(NOT WIN32)
endif() endif()
endif() endif()
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
# this is messing with release builds # this is messing with release builds
add_compile_options(-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0) add_compile_options(-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0)
@ -276,16 +276,16 @@ if(SUBMODULE_CHECK)
check_submodule(external/nlohmann) check_submodule(external/nlohmann)
check_submodule(external/googletest) check_submodule(external/googletest)
check_submodule(external/cxxopts) check_submodule(external/cxxopts)
check_submodule(external/ghc-filesystem)
check_submodule(external/optional-lite)
check_submodule(external/date) check_submodule(external/date)
check_submodule(external/pybind11) check_submodule(external/pybind11)
endif() endif()
endif() endif()
if(WITH_HIVE) # We only actually need pybind11 with WITH_HIVE, but if we don't load it here then something further
add_subdirectory(external/pybind11 EXCLUDE_FROM_ALL) # down loads a broken PythonInterp that loads Python2, but Python2 headers are not C++17 compatible.
endif() # So load this here universally so that pybind's more intelligent python finder finds python3.x
# (which the crappier loader invoked below then respects).
add_subdirectory(external/pybind11 EXCLUDE_FROM_ALL)
if(WITH_TESTS) if(WITH_TESTS)
add_subdirectory(external/googletest EXCLUDE_FROM_ALL) add_subdirectory(external/googletest EXCLUDE_FROM_ALL)
@ -294,8 +294,6 @@ endif()
set(JSON_BuildTests OFF CACHE INTERNAL "") set(JSON_BuildTests OFF CACHE INTERNAL "")
add_subdirectory(external/nlohmann EXCLUDE_FROM_ALL) add_subdirectory(external/nlohmann EXCLUDE_FROM_ALL)
add_subdirectory(external/cxxopts EXCLUDE_FROM_ALL) add_subdirectory(external/cxxopts EXCLUDE_FROM_ALL)
add_subdirectory(external/ghc-filesystem)
add_subdirectory(external/optional-lite EXCLUDE_FROM_ALL)
add_subdirectory(external/date EXCLUDE_FROM_ALL) add_subdirectory(external/date EXCLUDE_FROM_ALL)
if(ANDROID) if(ANDROID)

@ -67,8 +67,6 @@ elseif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR ${CMAKE_SYSTEM_NAME} MATCHES "i
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-darwin.c ${TT_ROOT}/tuntap-unix-bsd.c) list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-darwin.c ${TT_ROOT}/tuntap-unix-bsd.c)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "SunOS") elseif (${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-sunos.c) list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-sunos.c)
# Apple C++ screws up name decorations in stdc++fs, causing link to fail
# Samsung does not build c++experimental or c++fs in their Apple libc++ pkgsrc build
if (LIBUV_USE_STATIC) if (LIBUV_USE_STATIC)
link_libraries(-lkstat -lsendfile) link_libraries(-lkstat -lsendfile)
endif() endif()
@ -78,6 +76,40 @@ endif()
set(EXE_LIBS ${STATIC_LIB}) set(EXE_LIBS ${STATIC_LIB})
# Figure out if we need -lstdc++fs or -lc++fs and add it to the `filesystem` interface, if needed
# (otherwise just leave it an empty interface library; linking to it will do nothing). The former
# is needed for gcc before v9, and the latter with libc++ before llvm v9. But this gets more
# complicated than just using the compiler, because clang on linux by default uses libstdc++, so
# we'll just give up and see what works.
add_library(filesystem INTERFACE)
set(filesystem_code [[
#include <filesystem>
int main() {
auto cwd = std::filesystem::current_path();
return !cwd.string().empty();
}
]])
check_cxx_source_compiles("${filesystem_code}" filesystem_compiled)
if(filesystem_compiled)
message(STATUS "No extra link flag needed for std::filesystem")
else()
foreach(fslib stdc++fs c++fs)
set(CMAKE_REQUIRED_LIBRARIES -l${fslib})
check_cxx_source_compiles("${filesystem_code}" filesystem_compiled_${fslib})
if (filesystem_compiled_${fslib})
message(STATUS "Using -l${fslib} for std::filesystem support")
target_link_libraries(filesystem INTERFACE ${fslib})
break()
endif()
endforeach()
endif()
unset(CMAKE_REQUIRED_LIBRARIES)
if(RELEASE_MOTTO) if(RELEASE_MOTTO)
add_definitions(-DLLARP_RELEASE_MOTTO="${RELEASE_MOTTO}") add_definitions(-DLLARP_RELEASE_MOTTO="${RELEASE_MOTTO}")
endif() endif()

@ -1 +0,0 @@
Subproject commit e63a58c5bac94a3a75a7083f87bb092531407a92

@ -1 +0,0 @@
Subproject commit 3b79f4ee539d8f4c709a76b95a13564b6d9ae9cb

@ -73,7 +73,7 @@ namespace llarp
HandleSignal(int sig); HandleSignal(int sig);
bool bool
Configure(bool isRelay, nonstd::optional<fs::path> dataDir); Configure(bool isRelay, std::optional<fs::path> dataDir);
bool bool
IsUp() const; IsUp() const;

@ -3,7 +3,6 @@
#include <ev/ev.h> #include <ev/ev.h>
#include <util/json.hpp> #include <util/json.hpp>
#include <util/string_view.hpp>
#include <abyss/http.hpp> #include <abyss/http.hpp>
#include <deque> #include <deque>

@ -1,9 +1,9 @@
#ifndef ABYSS_HTTP_HPP #ifndef ABYSS_HTTP_HPP
#define ABYSS_HTTP_HPP #define ABYSS_HTTP_HPP
#include <util/json.hpp> #include <util/json.hpp>
#include <util/string_view.hpp>
#include <string> #include <string>
#include <string_view>
#include <unordered_map> #include <unordered_map>
namespace abyss namespace abyss
@ -20,18 +20,16 @@ namespace abyss
struct HeaderReader struct HeaderReader
{ {
using string_view = llarp::string_view;
RequestHeader Header; RequestHeader Header;
virtual ~HeaderReader() virtual ~HeaderReader()
{ {
} }
bool bool
ProcessHeaderLine(string_view line, bool& done); ProcessHeaderLine(std::string_view line, bool& done);
virtual bool virtual bool
ShouldProcessHeader(const string_view& line) const = 0; ShouldProcessHeader(std::string_view line) const = 0;
}; };
} // namespace http } // namespace http

@ -3,12 +3,10 @@
#include <ev/ev.h> #include <ev/ev.h>
#include <util/json.hpp> #include <util/json.hpp>
#include <util/string_view.hpp>
#include <util/thread/logic.hpp> #include <util/thread/logic.hpp>
#include <util/time.hpp> #include <util/time.hpp>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <nonstd/optional.hpp>
#include <list> #include <list>
#include <memory> #include <memory>

@ -9,6 +9,7 @@ namespace abyss
{ {
namespace http namespace http
{ {
using namespace std::literals;
namespace json = llarp::json; namespace json = llarp::json;
struct ConnImpl : HeaderReader struct ConnImpl : HeaderReader
{ {
@ -85,35 +86,35 @@ namespace abyss
} }
bool bool
ProcessStatusLine(string_view line) ProcessStatusLine(std::string_view line)
{ {
auto idx = line.find_first_of(' '); auto idx = line.find_first_of(' ');
if (idx == string_view::npos) if (idx == std::string_view::npos)
return false; return false;
string_view codePart = line.substr(1 + idx); std::string_view codePart = line.substr(1 + idx);
idx = codePart.find_first_of(' '); idx = codePart.find_first_of(' ');
if (idx == string_view::npos) if (idx == std::string_view::npos)
return false; return false;
return HandleStatusCode(codePart.substr(0, idx)); return HandleStatusCode(codePart.substr(0, idx));
} }
bool bool
ShouldProcessHeader(const llarp::string_view& name) const ShouldProcessHeader(std::string_view name) const
{ {
return name == llarp::string_view("content-length") return name == "content-length"sv
|| name == llarp::string_view("content-type") || name == "content-type"sv
|| name == llarp::string_view("www-authenticate"); || name == "www-authenticate"sv;
} }
/// return true if we get a 200 status code /// return true if we get a 200 status code
bool bool
HandleStatusCode(string_view code) HandleStatusCode(std::string_view code)
{ {
if (code == string_view("200")) if (code == "200"sv)
return true; return true;
if (code == string_view("401")) if (code == "401"sv)
{ {
m_ShouldAuth = true; m_ShouldAuth = true;
return true; return true;
@ -259,7 +260,7 @@ namespace abyss
const char* end = strstr(buf, "\r\n"); const char* end = strstr(buf, "\r\n");
if (!end) if (!end)
return false; return false;
string_view line(buf, end - buf); std::string_view line(buf, end - buf);
switch (state) switch (state)
{ {
case eReadStatusLine: case eReadStatusLine:

@ -1,11 +1,14 @@
#include <abyss/http.hpp> #include <abyss/http.hpp>
#include <util/str.hpp>
#include <algorithm> #include <algorithm>
namespace abyss namespace abyss
{ {
namespace http namespace http
{ {
bool bool
HeaderReader::ProcessHeaderLine(string_view line, bool& done) HeaderReader::ProcessHeaderLine(std::string_view line, bool& done)
{ {
if (line.size() == 0) if (line.size() == 0)
{ {
@ -13,10 +16,10 @@ namespace abyss
return true; return true;
} }
auto idx = line.find_first_of(':'); auto idx = line.find_first_of(':');
if (idx == string_view::npos) if (idx == std::string_view::npos)
return false; return false;
string_view header = line.substr(0, idx); std::string_view header = line.substr(0, idx);
string_view val = line.substr(1 + idx); std::string_view val = line.substr(1 + idx);
// to lowercase // to lowercase
std::string lowerHeader; std::string lowerHeader;
lowerHeader.reserve(header.size()); lowerHeader.reserve(header.size());

@ -8,12 +8,14 @@
#include <algorithm> #include <algorithm>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <string_view>
#include <unordered_map> #include <unordered_map>
namespace abyss namespace abyss
{ {
namespace httpd namespace httpd
{ {
using namespace std::literals;
namespace json = llarp::json; namespace json = llarp::json;
struct ConnImpl : abyss::http::HeaderReader struct ConnImpl : abyss::http::HeaderReader
{ {
@ -76,15 +78,15 @@ namespace abyss
} }
bool bool
ProcessMethodLine(string_view line) ProcessMethodLine(std::string_view line)
{ {
auto idx = line.find_first_of(' '); auto idx = line.find_first_of(' ');
if (idx == string_view::npos) if (idx == std::string_view::npos)
return false; return false;
Header.Method = std::string(line.substr(0, idx)); Header.Method = std::string(line.substr(0, idx));
line = line.substr(idx + 1); line = line.substr(idx + 1);
idx = line.find_first_of(' '); idx = line.find_first_of(' ');
if (idx == string_view::npos) if (idx == std::string_view::npos)
return false; return false;
Header.Path = std::string(line.substr(0, idx)); Header.Path = std::string(line.substr(0, idx));
m_State = eReadHTTPHeaders; m_State = eReadHTTPHeaders;
@ -92,11 +94,10 @@ namespace abyss
} }
bool bool
ShouldProcessHeader(const string_view& name) const ShouldProcessHeader(std::string_view name) const
{ {
// TODO: header whitelist // TODO: header whitelist
return name == string_view("content-type") || name == string_view("content-length") return name == "content-type"sv || name == "content-length"sv || name == "host"sv;
|| name == string_view("host");
} }
bool bool
@ -138,7 +139,7 @@ namespace abyss
return WriteResponseSimple( return WriteResponseSimple(
415, "Unsupported Media Type", "text/plain", "no content type provided"); 415, "Unsupported Media Type", "text/plain", "no content type provided");
} }
else if (itr->second != string_view("application/json")) else if (itr->second != "application/json"sv)
{ {
return WriteResponseSimple( return WriteResponseSimple(
415, "Unsupported Media Type", "text/plain", "this does not look like jsonrpc 2.0"); 415, "Unsupported Media Type", "text/plain", "this does not look like jsonrpc 2.0");
@ -231,7 +232,7 @@ namespace abyss
const char* end = strstr(buf, "\r\n"); const char* end = strstr(buf, "\r\n");
while (end) while (end)
{ {
string_view line(buf, end - buf); std::string_view line(buf, end - buf);
switch (m_State) switch (m_State)
{ {
case eReadHTTPMethodLine: case eReadHTTPMethodLine:

@ -44,8 +44,7 @@ endif()
target_link_libraries(${UTIL_LIB} PUBLIC ${CRYPTOGRAPHY_LIB} ${LOG_LIB} ${CURL_LIBRARIES}) target_link_libraries(${UTIL_LIB} PUBLIC ${CRYPTOGRAPHY_LIB} ${LOG_LIB} ${CURL_LIBRARIES})
target_link_libraries(${UTIL_LIB} PUBLIC target_link_libraries(${UTIL_LIB} PUBLIC
nlohmann_json::nlohmann_json nlohmann_json::nlohmann_json
ghc_filesystem filesystem
optional-lite
date::date date::date
) )

@ -16,7 +16,7 @@
#include <fstream> #include <fstream>
#include <ios> #include <ios>
#include <iostream> #include <iostream>
#include "ghc/filesystem.hpp" #include <filesystem>
namespace llarp namespace llarp
{ {
@ -164,7 +164,7 @@ namespace llarp
"network", "strict-connect", false, "", AssignmentAcceptor(m_strictConnect)); "network", "strict-connect", false, "", AssignmentAcceptor(m_strictConnect));
// TODO: make sure this is documented... what does it mean though? // TODO: make sure this is documented... what does it mean though?
conf.addUndeclaredHandler("network", [&](string_view, string_view name, string_view value) { conf.addUndeclaredHandler("network", [&](std::string_view, std::string_view name, std::string_view value) {
m_options.emplace(name, value); m_options.emplace(name, value);
return true; return true;
}); });
@ -199,7 +199,7 @@ namespace llarp
} }
LinksConfig::LinkInfo LinksConfig::LinkInfo
LinksConfig::LinkInfoFromINIValues(string_view name, string_view value) LinksConfig::LinkInfoFromINIValues(std::string_view name, std::string_view value)
{ {
// we treat the INI k:v pair as: // we treat the INI k:v pair as:
// k: interface name, * indicating outbound // k: interface name, * indicating outbound
@ -211,8 +211,8 @@ namespace llarp
info.addressFamily = AF_INET; info.addressFamily = AF_INET;
info.interface = str(name); info.interface = str(name);
std::vector<string_view> splits = split(value, ','); std::vector<std::string_view> splits = split(value, ',');
for (string_view str : splits) for (std::string_view str : splits)
{ {
int asNum = std::atoi(str.data()); int asNum = std::atoi(str.data());
if (asNum > 0) if (asNum > 0)
@ -233,10 +233,10 @@ namespace llarp
conf.defineOption<std::string>( conf.defineOption<std::string>(
"bind", "*", false, false, DefaultOutboundLinkValue, [this](std::string arg) { "bind", "*", false, false, DefaultOutboundLinkValue, [this](std::string arg) {
m_OutboundLink = std::move(LinkInfoFromINIValues("*", arg)); m_OutboundLink = LinkInfoFromINIValues("*", arg);
}); });
conf.addUndeclaredHandler("bind", [&](string_view, string_view name, string_view value) { conf.addUndeclaredHandler("bind", [&](std::string_view, std::string_view name, std::string_view value) {
LinkInfo info = LinkInfoFromINIValues(name, value); LinkInfo info = LinkInfoFromINIValues(name, value);
if (info.port <= 0) if (info.port <= 0)
@ -254,7 +254,7 @@ namespace llarp
(void)params; (void)params;
conf.addUndeclaredHandler( conf.addUndeclaredHandler(
"connect", [this](string_view section, string_view name, string_view value) { "connect", [this](std::string_view section, std::string_view name, std::string_view value) {
fs::path file = str(value); fs::path file = str(value);
if (not fs::exists(file)) if (not fs::exists(file))
throw std::runtime_error(stringify( throw std::runtime_error(stringify(
@ -277,7 +277,7 @@ namespace llarp
(void)params; (void)params;
conf.addUndeclaredHandler( conf.addUndeclaredHandler(
"services", [this](string_view section, string_view name, string_view value) { "services", [this](std::string_view section, std::string_view name, std::string_view value) {
(void)section; (void)section;
services.emplace_back(name, value); services.emplace_back(name, value);
return true; return true;
@ -364,7 +364,7 @@ namespace llarp
conf.defineOption<std::string>( conf.defineOption<std::string>(
"logging", "level", false, DefaultLogLevel, [this](std::string arg) { "logging", "level", false, DefaultLogLevel, [this](std::string arg) {
nonstd::optional<LogLevel> level = LogLevelFromString(arg); std::optional<LogLevel> level = LogLevelFromString(arg);
if (not level.has_value()) if (not level.has_value())
throw std::invalid_argument(stringify("invalid log level value: ", arg)); throw std::invalid_argument(stringify("invalid log level value: ", arg));
@ -422,7 +422,7 @@ namespace llarp
m_mapAddr = arg; m_mapAddr = arg;
}); });
conf.addUndeclaredHandler("snapp", [&](string_view, string_view name, string_view value) { conf.addUndeclaredHandler("snapp", [&](std::string_view, std::string_view name, std::string_view value) {
if (name == "blacklist-snode") if (name == "blacklist-snode")
{ {
m_snodeBlacklist.push_back(str(value)); m_snodeBlacklist.push_back(str(value));
@ -452,7 +452,7 @@ namespace llarp
return false; return false;
} }
parser.IterAll([&](string_view section, const SectionValues_t& values) { parser.IterAll([&](std::string_view section, const SectionValues_t& values) {
for (const auto& pair : values) for (const auto& pair : values)
{ {
conf.addConfigValue(section, pair.first, pair.second); conf.addConfigValue(section, pair.first, pair.second);

@ -66,7 +66,7 @@ namespace llarp
struct NetworkConfig struct NetworkConfig
{ {
nonstd::optional<bool> m_enableProfiling; std::optional<bool> m_enableProfiling;
std::string m_routerProfilesFile; std::string m_routerProfilesFile;
std::string m_strictConnect; std::string m_strictConnect;
FreehandOptions m_options; FreehandOptions m_options;
@ -94,7 +94,7 @@ namespace llarp
/// Create a LinkInfo from the given string. /// Create a LinkInfo from the given string.
/// @throws if str does not represent a LinkInfo. /// @throws if str does not represent a LinkInfo.
LinkInfo LinkInfo
LinkInfoFromINIValues(string_view name, string_view value); LinkInfoFromINIValues(std::string_view name, std::string_view value);
LinkInfo m_OutboundLink; LinkInfo m_OutboundLink;
std::vector<LinkInfo> m_InboundLinks; std::vector<LinkInfo> m_InboundLinks;

@ -2,6 +2,7 @@
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
#include <cassert>
namespace llarp namespace llarp
{ {
@ -47,7 +48,7 @@ namespace llarp
} }
ConfigDefinition& ConfigDefinition&
ConfigDefinition::addConfigValue(string_view section, string_view name, string_view value) ConfigDefinition::addConfigValue(std::string_view section, std::string_view name, std::string_view value)
{ {
// see if we have an undeclared handler to fall back to in case section or section:name is // see if we have an undeclared handler to fall back to in case section or section:name is
// absent // absent
@ -207,7 +208,7 @@ namespace llarp
} }
const OptionDefinition_ptr& const OptionDefinition_ptr&
ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name) const ConfigDefinition::lookupDefinitionOrThrow(std::string_view section, std::string_view name) const
{ {
const auto sectionItr = m_definitions.find(std::string(section)); const auto sectionItr = m_definitions.find(std::string(section));
if (sectionItr == m_definitions.end()) if (sectionItr == m_definitions.end())
@ -222,7 +223,7 @@ namespace llarp
} }
OptionDefinition_ptr& OptionDefinition_ptr&
ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name) ConfigDefinition::lookupDefinitionOrThrow(std::string_view section, std::string_view name)
{ {
return const_cast<OptionDefinition_ptr&>( return const_cast<OptionDefinition_ptr&>(
const_cast<const ConfigDefinition*>(this)->lookupDefinitionOrThrow(section, name)); const_cast<const ConfigDefinition*>(this)->lookupDefinitionOrThrow(section, name));

@ -1,7 +1,6 @@
#pragma once #pragma once
#include <util/str.hpp> #include <util/str.hpp>
#include <nonstd/optional.hpp>
#include <memory> #include <memory>
#include <set> #include <set>
@ -9,6 +8,9 @@
#include <stdexcept> #include <stdexcept>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <functional>
#include <optional>
#include <cassert>
namespace llarp namespace llarp
{ {
@ -88,7 +90,7 @@ namespace llarp
std::string section_, std::string section_,
std::string name_, std::string name_,
bool required_, bool required_,
nonstd::optional<T> defaultValue_, std::optional<T> defaultValue_,
std::function<void(T)> acceptor_ = nullptr) std::function<void(T)> acceptor_ = nullptr)
: OptionDefinitionBase(section_, name_, required_) : OptionDefinitionBase(section_, name_, required_)
, defaultValue(defaultValue_) , defaultValue(defaultValue_)
@ -102,7 +104,7 @@ namespace llarp
std::string name_, std::string name_,
bool required_, bool required_,
bool multiValued_, bool multiValued_,
nonstd::optional<T> defaultValue_, std::optional<T> defaultValue_,
std::function<void(T)> acceptor_ = nullptr) std::function<void(T)> acceptor_ = nullptr)
: OptionDefinitionBase(section_, name_, required_, multiValued_) : OptionDefinitionBase(section_, name_, required_, multiValued_)
, defaultValue(defaultValue_) , defaultValue(defaultValue_)
@ -114,7 +116,7 @@ namespace llarp
/// option is not required. Otherwise, returns an empty optional. /// option is not required. Otherwise, returns an empty optional.
/// ///
/// @return an optional with the parsed value, the default value, or no value. /// @return an optional with the parsed value, the default value, or no value.
nonstd::optional<T> std::optional<T>
getValue() const getValue() const
{ {
if (parsedValues.size()) if (parsedValues.size())
@ -236,7 +238,7 @@ namespace llarp
} }
} }
nonstd::optional<T> defaultValue; std::optional<T> defaultValue;
std::vector<T> parsedValues; std::vector<T> parsedValues;
std::function<void(T)> acceptor; std::function<void(T)> acceptor;
}; };
@ -248,7 +250,7 @@ namespace llarp
OptionDefinition<bool>::fromString(const std::string& input); OptionDefinition<bool>::fromString(const std::string& input);
using UndeclaredValueHandler = using UndeclaredValueHandler =
std::function<void(string_view section, string_view name, string_view value)>; std::function<void(std::string_view section, std::string_view name, std::string_view value)>;
using OptionDefinition_ptr = std::unique_ptr<OptionDefinitionBase>; using OptionDefinition_ptr = std::unique_ptr<OptionDefinitionBase>;
@ -307,7 +309,7 @@ namespace llarp
/// @return `*this` for chaining calls /// @return `*this` for chaining calls
/// @throws if the option doesn't exist or the provided string isn't parseable /// @throws if the option doesn't exist or the provided string isn't parseable
ConfigDefinition& ConfigDefinition&
addConfigValue(string_view section, string_view name, string_view value); addConfigValue(std::string_view section, std::string_view name, std::string_view value);
/// Get a config value. If the value hasn't been provided but a default has, the default will /// Get a config value. If the value hasn't been provided but a default has, the default will
/// be returned. If no value and no default is provided, an empty optional will be returned. /// be returned. If no value and no default is provided, an empty optional will be returned.
@ -321,8 +323,8 @@ namespace llarp
/// @throws std::invalid_argument if there is no such config option or the wrong type T was /// @throws std::invalid_argument if there is no such config option or the wrong type T was
// provided // provided
template <typename T> template <typename T>
nonstd::optional<T> std::optional<T>
getConfigValue(string_view section, string_view name) getConfigValue(std::string_view section, std::string_view name)
{ {
OptionDefinition_ptr& definition = lookupDefinitionOrThrow(section, name); OptionDefinition_ptr& definition = lookupDefinitionOrThrow(section, name);
@ -402,9 +404,9 @@ namespace llarp
private: private:
OptionDefinition_ptr& OptionDefinition_ptr&
lookupDefinitionOrThrow(string_view section, string_view name); lookupDefinitionOrThrow(std::string_view section, std::string_view name);
const OptionDefinition_ptr& const OptionDefinition_ptr&
lookupDefinitionOrThrow(string_view section, string_view name) const; lookupDefinitionOrThrow(std::string_view section, std::string_view name) const;
using SectionVisitor = std::function<void(const std::string&, const DefinitionMap&)>; using SectionVisitor = std::function<void(const std::string&, const DefinitionMap&)>;
void void

@ -12,7 +12,7 @@
namespace llarp namespace llarp
{ {
bool bool
ConfigParser::LoadFile(string_view fname) ConfigParser::LoadFile(std::string_view fname)
{ {
std::string name{fname}; std::string name{fname};
{ {
@ -31,7 +31,7 @@ namespace llarp
} }
bool bool
ConfigParser::LoadFromStr(string_view str) ConfigParser::LoadFromStr(std::string_view str)
{ {
m_Data.resize(str.size()); m_Data.resize(str.size());
std::copy(str.begin(), str.end(), m_Data.begin()); std::copy(str.begin(), str.end(), m_Data.begin());
@ -55,7 +55,7 @@ namespace llarp
bool bool
ConfigParser::Parse() ConfigParser::Parse()
{ {
std::list<string_view> lines; std::list<std::string_view> lines;
{ {
auto itr = m_Data.begin(); auto itr = m_Data.begin();
// split into lines // split into lines
@ -71,16 +71,16 @@ namespace llarp
} }
} }
string_view sectName; std::string_view sectName;
size_t lineno = 0; size_t lineno = 0;
for (const auto& line : lines) for (const auto& line : lines)
{ {
lineno++; lineno++;
string_view realLine; std::string_view realLine;
auto comment = line.find_first_of(';'); auto comment = line.find_first_of(';');
if (comment == string_view::npos) if (comment == std::string_view::npos)
comment = line.find_first_of('#'); comment = line.find_first_of('#');
if (comment == string_view::npos) if (comment == std::string_view::npos)
realLine = line; realLine = line;
else else
realLine = line.substr(0, comment); realLine = line.substr(0, comment);
@ -91,8 +91,8 @@ namespace llarp
auto sectOpenPos = realLine.find_first_of('['); auto sectOpenPos = realLine.find_first_of('[');
auto sectClosPos = realLine.find_first_of(']'); auto sectClosPos = realLine.find_first_of(']');
auto kvDelim = realLine.find_first_of('='); auto kvDelim = realLine.find_first_of('=');
if (sectOpenPos != string_view::npos && sectClosPos != string_view::npos if (sectOpenPos != std::string_view::npos && sectClosPos != std::string_view::npos
&& kvDelim == string_view::npos) && kvDelim == std::string_view::npos)
{ {
// section header // section header
@ -106,13 +106,13 @@ namespace llarp
// set section name // set section name
sectName = realLine.substr(sectOpenPos, sectClosPos); sectName = realLine.substr(sectOpenPos, sectClosPos);
} }
else if (kvDelim != string_view::npos) else if (kvDelim != std::string_view::npos)
{ {
// key value pair // key value pair
string_view::size_type k_start = 0; std::string_view::size_type k_start = 0;
string_view::size_type k_end = kvDelim; std::string_view::size_type k_end = kvDelim;
string_view::size_type v_start = kvDelim + 1; std::string_view::size_type v_start = kvDelim + 1;
string_view::size_type v_end = realLine.size() - 1; std::string_view::size_type v_end = realLine.size() - 1;
// clamp whitespaces // clamp whitespaces
while (whitespace(realLine[k_start]) && k_start != kvDelim) while (whitespace(realLine[k_start]) && k_start != kvDelim)
++k_start; ++k_start;
@ -124,8 +124,8 @@ namespace llarp
--v_end; --v_end;
// sect.k = v // sect.k = v
string_view k = realLine.substr(k_start, k_end - k_start); std::string_view k = realLine.substr(k_start, k_end - k_start);
string_view v = realLine.substr(v_start, 1 + (v_end - v_start)); std::string_view v = realLine.substr(v_start, 1 + (v_end - v_start));
if (k.size() == 0 || v.size() == 0) if (k.size() == 0 || v.size() == 0)
{ {
LogError(m_FileName, " invalid line (", lineno, "): '", line, "'"); LogError(m_FileName, " invalid line (", lineno, "): '", line, "'");
@ -145,7 +145,7 @@ namespace llarp
} }
void void
ConfigParser::IterAll(std::function<void(string_view, const SectionValues_t&)> visit) ConfigParser::IterAll(std::function<void(std::string_view, const SectionValues_t&)> visit)
{ {
for (const auto& item : m_Config) for (const auto& item : m_Config)
visit(item.first, item.second); visit(item.first, item.second);

@ -1,8 +1,7 @@
#ifndef LOKINET_BOOTSERV_CONFIG_HPP #ifndef LOKINET_BOOTSERV_CONFIG_HPP
#define LOKINET_BOOTSERV_CONFIG_HPP #define LOKINET_BOOTSERV_CONFIG_HPP
#include <util/string_view.hpp> #include <string_view>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <unordered_map> #include <unordered_map>
@ -22,17 +21,17 @@ namespace llarp
/// return true on success /// return true on success
/// return false on error /// return false on error
bool bool
LoadFile(string_view fname); LoadFile(std::string_view fname);
/// load from string /// load from string
/// return true on success /// return true on success
/// return false on error /// return false on error
bool bool
LoadFromStr(string_view str); LoadFromStr(std::string_view str);
/// iterate all sections and thier values /// iterate all sections and thier values
void void
IterAll(std::function<void(string_view, const SectionValues_t&)> visit); IterAll(std::function<void(std::string_view, const SectionValues_t&)> visit);
/// visit a section in config read only by name /// visit a section in config read only by name
/// return false if no section or value propagated from visitor /// return false if no section or value propagated from visitor

@ -28,7 +28,7 @@ namespace llarp
} }
bool bool
Context::Configure(bool isRelay, nonstd::optional<fs::path> dataDir) Context::Configure(bool isRelay, std::optional<fs::path> dataDir)
{ {
fs::path defaultDataDir = dataDir.has_value() ? dataDir.value() : GetDefaultDataDir(); fs::path defaultDataDir = dataDir.has_value() ? dataDir.value() : GetDefaultDataDir();

@ -157,7 +157,7 @@ namespace llarp
Init(const Key_t& us, AbstractRouter* router) override; Init(const Key_t& us, AbstractRouter* router) override;
/// get localally stored introset by service address /// get localally stored introset by service address
nonstd::optional<llarp::service::EncryptedIntroSet> std::optional<llarp::service::EncryptedIntroSet>
GetIntroSetByLocation(const Key_t& location) const override; GetIntroSetByLocation(const Key_t& location) const override;
void void
@ -412,7 +412,7 @@ namespace llarp
} }
} }
nonstd::optional<llarp::service::EncryptedIntroSet> std::optional<llarp::service::EncryptedIntroSet>
Context::GetIntroSetByLocation(const Key_t& key) const Context::GetIntroSetByLocation(const Key_t& key) const
{ {
auto itr = _services->nodes.find(key); auto itr = _services->nodes.find(key);

@ -132,7 +132,7 @@ namespace llarp
virtual void virtual void
Init(const Key_t& us, AbstractRouter* router) = 0; Init(const Key_t& us, AbstractRouter* router) = 0;
virtual nonstd::optional<llarp::service::EncryptedIntroSet> virtual std::optional<llarp::service::EncryptedIntroSet>
GetIntroSetByLocation(const Key_t& location) const = 0; GetIntroSetByLocation(const Key_t& location) const = 0;
virtual llarp_time_t virtual llarp_time_t

@ -6,7 +6,7 @@
#include <util/copy_or_nullptr.hpp> #include <util/copy_or_nullptr.hpp>
#include <vector> #include <vector>
#include <nonstd/optional.hpp> #include <optional>
namespace llarp namespace llarp
{ {
@ -20,7 +20,7 @@ namespace llarp
/// txid /// txid
uint64_t txid = 0; uint64_t txid = 0;
/// the key of a router closer in keyspace if iterative lookup /// the key of a router closer in keyspace if iterative lookup
nonstd::optional<Key_t> closer; std::optional<Key_t> closer;
GotIntroMessage(const Key_t& from) : IMessage(from) GotIntroMessage(const Key_t& from) : IMessage(from)
{ {

@ -4,7 +4,6 @@
#include <dns/message.hpp> #include <dns/message.hpp>
#include <ev/ev.h> #include <ev/ev.h>
#include <net/net.hpp> #include <net/net.hpp>
#include <util/string_view.hpp>
#include <util/thread/logic.hpp> #include <util/thread/logic.hpp>
#include <unordered_map> #include <unordered_map>

@ -1,11 +1,11 @@
#include <ev/ev.h> #include <ev/ev.h>
#include <util/mem.hpp> #include <util/mem.hpp>
#include <util/string_view.hpp>
#include <util/thread/logic.hpp> #include <util/thread/logic.hpp>
#include <net/net_addr.hpp> #include <net/net_addr.hpp>
#include <cstddef> #include <cstddef>
#include <cstring> #include <cstring>
#include <string_view>
// We libuv now // We libuv now
#include <ev/ev_libuv.hpp> #include <ev/ev_libuv.hpp>
@ -144,7 +144,7 @@ void
llarp_tcp_async_try_connect(struct llarp_ev_loop* loop, struct llarp_tcp_connecter* tcp) llarp_tcp_async_try_connect(struct llarp_ev_loop* loop, struct llarp_tcp_connecter* tcp)
{ {
tcp->loop = loop; tcp->loop = loop;
llarp::string_view addr_str, port_str; std::string_view addr_str, port_str;
// try parsing address // try parsing address
const char* begin = tcp->remote; const char* begin = tcp->remote;
const char* ptr = strstr(tcp->remote, ":"); const char* ptr = strstr(tcp->remote, ":");
@ -162,9 +162,9 @@ llarp_tcp_async_try_connect(struct llarp_ev_loop* loop, struct llarp_tcp_connect
{ {
++end; ++end;
} }
addr_str = llarp::string_view(begin, ptr - begin); addr_str = std::string_view(begin, ptr - begin);
++ptr; ++ptr;
port_str = llarp::string_view(ptr, end - ptr); port_str = std::string_view(ptr, end - ptr);
// actually parse address // actually parse address
llarp::Addr addr(addr_str, port_str); llarp::Addr addr(addr_str, port_str);

@ -4,7 +4,7 @@
namespace llarp namespace llarp
{ {
LinkFactory::LinkType LinkFactory::LinkType
LinkFactory::TypeFromName(string_view str) LinkFactory::TypeFromName(std::string_view str)
{ {
if (str == "iwp") if (str == "iwp")
return LinkType::eLinkIWP; return LinkType::eLinkIWP;
@ -40,4 +40,4 @@ namespace llarp
return nullptr; return nullptr;
} }
} }
} // namespace llarp } // namespace llarp

@ -1,7 +1,7 @@
#ifndef LLARP_LINK_FACTORY_HPP #ifndef LLARP_LINK_FACTORY_HPP
#define LLARP_LINK_FACTORY_HPP #define LLARP_LINK_FACTORY_HPP
#include <util/string_view.hpp>
#include <config/key_manager.hpp> #include <config/key_manager.hpp>
#include <string_view>
#include <functional> #include <functional>
#include <memory> #include <memory>
@ -35,7 +35,7 @@ namespace llarp
/// get link type by name string /// get link type by name string
/// if invalid returns eLinkUnspec /// if invalid returns eLinkUnspec
static LinkType static LinkType
TypeFromName(string_view name); TypeFromName(std::string_view name);
/// turns a link type into a string representation /// turns a link type into a string representation
static std::string static std::string
@ -48,4 +48,4 @@ namespace llarp
} // namespace llarp } // namespace llarp
#endif #endif

@ -16,7 +16,7 @@
#include <tooling/path_event.hpp> #include <tooling/path_event.hpp>
#include <functional> #include <functional>
#include <nonstd/optional.hpp> #include <optional>
namespace llarp namespace llarp
{ {
@ -185,7 +185,7 @@ namespace llarp
// the actual hop // the actual hop
std::shared_ptr<Hop> hop; std::shared_ptr<Hop> hop;
const nonstd::optional<llarp::Addr> fromAddr; const std::optional<llarp::Addr> fromAddr;
LRCMFrameDecrypt(Context* ctx, Decrypter_ptr dec, const LR_CommitMessage* commit) LRCMFrameDecrypt(Context* ctx, Decrypter_ptr dec, const LR_CommitMessage* commit)
: decrypter(std::move(dec)) : decrypter(std::move(dec))
@ -194,7 +194,7 @@ namespace llarp
, hop(std::make_shared<Hop>()) , hop(std::make_shared<Hop>())
, fromAddr( , fromAddr(
commit->session->GetRemoteRC().IsPublicRouter() commit->session->GetRemoteRC().IsPublicRouter()
? nonstd::optional<llarp::Addr>{} ? std::optional<llarp::Addr>{}
: commit->session->GetRemoteEndpoint()) : commit->session->GetRemoteEndpoint())
{ {
hop->info.downstream = commit->session->GetPubKey(); hop->info.downstream = commit->session->GetPubKey();

@ -6,7 +6,6 @@
#include <net/net_int.hpp> #include <net/net_int.hpp>
#include <net/net.h> #include <net/net.h>
#include <util/mem.hpp> #include <util/mem.hpp>
#include <util/string_view.hpp>
#include <util/bits.hpp> #include <util/bits.hpp>
#include <functional> #include <functional>

@ -1,6 +1,6 @@
#include <net/net.hpp> #include <net/net.hpp>
#include <net/net_addr.hpp> #include <net/net_addr.hpp>
#include <util/string_view.hpp> #include <string_view>
// for addrinfo // for addrinfo
#ifndef _WIN32 #ifndef _WIN32
@ -59,26 +59,26 @@ namespace llarp
return (const in_addr*)&_addr.sin6_addr.s6_addr[12]; return (const in_addr*)&_addr.sin6_addr.s6_addr[12];
} }
Addr::Addr(string_view str) : Addr() Addr::Addr(std::string_view str) : Addr()
{ {
this->from_char_array(str); this->from_char_array(str);
} }
Addr::Addr(string_view str, const uint16_t p_port) : Addr(str) Addr::Addr(std::string_view str, const uint16_t p_port) : Addr(str)
{ {
this->port(p_port); this->port(p_port);
} }
Addr::Addr(string_view addr_str, string_view port_str) Addr::Addr(std::string_view addr_str, std::string_view port_str)
: Addr(addr_str, std::strtoul(port_str.data(), nullptr, 10)) : Addr(addr_str, std::strtoul(port_str.data(), nullptr, 10))
{ {
} }
bool bool
Addr::from_char_array(string_view in) Addr::from_char_array(std::string_view in)
{ {
auto pPosition = in.find(':'); auto pPosition = in.find(':');
if (pPosition != string_view::npos) if (pPosition != std::string_view::npos)
{ {
// parse port // parse port
uint16_t port = std::atoi(std::string(in.begin() + pPosition + 1, in.end()).c_str()); uint16_t port = std::atoi(std::string(in.begin() + pPosition + 1, in.end()).c_str());
@ -94,7 +94,7 @@ namespace llarp
hint.ai_family = PF_UNSPEC; hint.ai_family = PF_UNSPEC;
hint.ai_flags = AI_NUMERICHOST; hint.ai_flags = AI_NUMERICHOST;
if (pPosition != string_view::npos) if (pPosition != std::string_view::npos)
{ {
ret = getaddrinfo( ret = getaddrinfo(
std::string(in.begin(), in.begin() + pPosition).c_str(), nullptr, &hint, &res); std::string(in.begin(), in.begin() + pPosition).c_str(), nullptr, &hint, &res);

@ -4,9 +4,9 @@
#include <net/address_info.hpp> #include <net/address_info.hpp>
#include <net/net.h> #include <net/net.h>
#include <net/net.hpp> #include <net/net.hpp>
#include <util/string_view.hpp>
#include <net/net_int.hpp> #include <net/net_int.hpp>
#include <string_view>
#include <string> #include <string>
namespace llarp namespace llarp
@ -21,11 +21,11 @@ namespace llarp
Addr(); Addr();
Addr(string_view str); Addr(std::string_view str);
Addr(string_view str, const uint16_t p_port); Addr(std::string_view str, const uint16_t p_port);
Addr(string_view addr_str, string_view port_str); Addr(std::string_view addr_str, std::string_view port_str);
void void
port(uint16_t port); port(uint16_t port);
@ -43,7 +43,7 @@ namespace llarp
addr4() const; addr4() const;
bool bool
from_char_array(string_view str); from_char_array(std::string_view str);
bool bool
from_4int(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four); from_4int(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four);

@ -142,7 +142,7 @@ namespace llarp
uint64_t currentStatus = status; uint64_t currentStatus = status;
size_t index = 0; size_t index = 0;
nonstd::optional<RouterID> failedAt; std::optional<RouterID> failedAt;
while (index < hops.size()) while (index < hops.size())
{ {
if (!frames[index].DoDecrypt(hops[index].shared)) if (!frames[index].DoDecrypt(hops[index].shared))

@ -1259,7 +1259,7 @@ namespace llarp
} }
bool bool
Router::LoadHiddenServiceConfig(string_view fname) Router::LoadHiddenServiceConfig(std::string_view fname)
{ {
LogDebug("opening hidden service config ", fname); LogDebug("opening hidden service config ", fname);
service::Config conf; service::Config conf;

@ -334,7 +334,7 @@ namespace llarp
Close(); Close();
bool bool
LoadHiddenServiceConfig(string_view fname); LoadHiddenServiceConfig(std::string_view fname);
bool bool
AddHiddenService(const service::Config::section_t& config); AddHiddenService(const service::Config::section_t& config);

@ -163,7 +163,7 @@ namespace llarp
nickname.Zero(); nickname.Zero();
enckey.Zero(); enckey.Zero();
pubkey.Zero(); pubkey.Zero();
routerVersion = nonstd::optional<RouterVersion>{}; routerVersion = std::optional<RouterVersion>{};
last_updated = 0s; last_updated = 0s;
} }
@ -258,7 +258,7 @@ namespace llarp
} }
void void
RouterContact::SetNick(string_view nick) RouterContact::SetNick(std::string_view nick)
{ {
nickname.Zero(); nickname.Zero();
std::copy( std::copy(

@ -105,7 +105,7 @@ namespace llarp
llarp_time_t last_updated = 0s; llarp_time_t last_updated = 0s;
uint64_t version = LLARP_PROTO_VERSION; uint64_t version = LLARP_PROTO_VERSION;
nonstd::optional<RouterVersion> routerVersion; std::optional<RouterVersion> routerVersion;
util::StatusObject util::StatusObject
ExtractStatus() const; ExtractStatus() const;
@ -174,7 +174,7 @@ namespace llarp
IsPublicRouter() const; IsPublicRouter() const;
void void
SetNick(string_view nick); SetNick(std::string_view nick);
bool bool
Verify(llarp_time_t now, bool allowExpired = true) const; Verify(llarp_time_t now, bool allowExpired = true) const;

@ -7,12 +7,12 @@ namespace llarp
namespace service namespace service
{ {
bool bool
Config::Load(string_view fname) Config::Load(std::string_view fname)
{ {
ConfigParser parser; ConfigParser parser;
if (!parser.LoadFile(fname)) if (!parser.LoadFile(fname))
return false; return false;
parser.IterAll([&](string_view name, const ConfigParser::SectionValues_t& section) { parser.IterAll([&](std::string_view name, const ConfigParser::SectionValues_t& section) {
Config::section_t values; Config::section_t values;
values.first.assign(name.begin(), name.end()); values.first.assign(name.begin(), name.end());
for (const auto& item : section) for (const auto& item : section)

@ -1,10 +1,9 @@
#ifndef LLARP_SERVICE_CONFIG_HPP #ifndef LLARP_SERVICE_CONFIG_HPP
#define LLARP_SERVICE_CONFIG_HPP #define LLARP_SERVICE_CONFIG_HPP
#include <util/string_view.hpp>
#include <list> #include <list>
#include <string> #include <string>
#include <string_view>
namespace llarp namespace llarp
{ {
@ -18,7 +17,7 @@ namespace llarp
std::list<section_t> services; std::list<section_t> services;
bool bool
Load(string_view fname); Load(std::string_view fname);
}; };
} // namespace service } // namespace service
} // namespace llarp } // namespace llarp

@ -941,7 +941,7 @@ namespace llarp
bool bool
Endpoint::OnLookup( Endpoint::OnLookup(
const Address& addr, nonstd::optional<IntroSet> introset, const RouterID& endpoint) const Address& addr, std::optional<IntroSet> introset, const RouterID& endpoint)
{ {
const auto now = Router()->Now(); const auto now = Router()->Now();
auto& fails = m_state->m_ServiceLookupFails; auto& fails = m_state->m_ServiceLookupFails;

@ -402,7 +402,7 @@ namespace llarp
bool bool
OnLookup( OnLookup(
const service::Address& addr, const service::Address& addr,
nonstd::optional<IntroSet> i, std::optional<IntroSet> i,
const RouterID& endpoint); /* */ const RouterID& endpoint); /* */
bool bool

@ -26,7 +26,7 @@ namespace llarp
bool bool
HiddenServiceAddressLookup::HandleResponse(const std::set<EncryptedIntroSet>& results) HiddenServiceAddressLookup::HandleResponse(const std::set<EncryptedIntroSet>& results)
{ {
nonstd::optional<IntroSet> found; std::optional<IntroSet> found;
const Address remote(rootkey); const Address remote(rootkey);
LogInfo("found ", results.size(), " for ", remote.ToString()); LogInfo("found ", results.size(), " for ", remote.ToString());
if (results.size() > 0) if (results.size() > 0)

@ -16,7 +16,7 @@ namespace llarp
uint64_t relayOrder; uint64_t relayOrder;
const dht::Key_t location; const dht::Key_t location;
using HandlerFunc = using HandlerFunc =
std::function<bool(const Address&, nonstd::optional<IntroSet>, const RouterID&)>; std::function<bool(const Address&, std::optional<IntroSet>, const RouterID&)>;
HandlerFunc handle; HandlerFunc handle;
HiddenServiceAddressLookup( HiddenServiceAddressLookup(

@ -152,7 +152,7 @@ namespace llarp
return crypto->derive_subkey_private(derivedSignKey, signkey, 1); return crypto->derive_subkey_private(derivedSignKey, signkey, 1);
} }
nonstd::optional<EncryptedIntroSet> std::optional<EncryptedIntroSet>
Identity::EncryptAndSignIntroSet(const IntroSet& other_i, llarp_time_t now) const Identity::EncryptAndSignIntroSet(const IntroSet& other_i, llarp_time_t now) const
{ {
EncryptedIntroSet encrypted; EncryptedIntroSet encrypted;

@ -50,7 +50,7 @@ namespace llarp
bool bool
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf); DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf);
nonstd::optional<EncryptedIntroSet> std::optional<EncryptedIntroSet>
EncryptAndSignIntroSet(const IntroSet& i, llarp_time_t now) const; EncryptAndSignIntroSet(const IntroSet& i, llarp_time_t now) const;
bool bool

@ -6,7 +6,7 @@
#include <service/vanity.hpp> #include <service/vanity.hpp>
#include <util/bencode.hpp> #include <util/bencode.hpp>
#include <nonstd/optional.hpp> #include <optional>
namespace llarp namespace llarp
{ {
@ -23,7 +23,7 @@ namespace llarp
VanityNonce vanity; VanityNonce vanity;
uint64_t version = LLARP_PROTO_VERSION; uint64_t version = LLARP_PROTO_VERSION;
using OptNonce = nonstd::optional<VanityNonce>; using OptNonce = std::optional<VanityNonce>;
void void
RandomizeVanity() RandomizeVanity()

@ -82,7 +82,7 @@ namespace llarp
return out; return out;
} }
nonstd::optional<IntroSet> std::optional<IntroSet>
EncryptedIntroSet::MaybeDecrypt(const PubKey& root) const EncryptedIntroSet::MaybeDecrypt(const PubKey& root) const
{ {
SharedSecret k(root); SharedSecret k(root);

@ -10,7 +10,7 @@
#include <util/time.hpp> #include <util/time.hpp>
#include <util/status.hpp> #include <util/status.hpp>
#include <nonstd/optional.hpp> #include <optional>
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
@ -31,7 +31,7 @@ namespace llarp
PQPubKey K; PQPubKey K;
Tag topic; Tag topic;
llarp_time_t T = 0s; llarp_time_t T = 0s;
nonstd::optional<PoW> W; std::optional<PoW> W;
Signature Z; Signature Z;
uint64_t version = LLARP_PROTO_VERSION; uint64_t version = LLARP_PROTO_VERSION;
@ -109,7 +109,7 @@ namespace llarp
llarp_time_t signedAt = 0s; llarp_time_t signedAt = 0s;
Payload_t introsetPayload; Payload_t introsetPayload;
TunnelNonce nounce; TunnelNonce nounce;
nonstd::optional<Tag> topic; std::optional<Tag> topic;
Signature sig; Signature sig;
bool bool
@ -143,7 +143,7 @@ namespace llarp
util::StatusObject util::StatusObject
ExtractStatus() const; ExtractStatus() const;
nonstd::optional<IntroSet> std::optional<IntroSet>
MaybeDecrypt(const PubKey& rootKey) const; MaybeDecrypt(const PubKey& rootKey) const;
}; };

@ -85,7 +85,7 @@ namespace llarp
bool bool
OutboundContext::OnIntroSetUpdate( OutboundContext::OnIntroSetUpdate(
const Address&, nonstd::optional<IntroSet> foundIntro, const RouterID& endpoint) const Address&, std::optional<IntroSet> foundIntro, const RouterID& endpoint)
{ {
if (markedBad) if (markedBad)
return true; return true;

@ -118,7 +118,7 @@ namespace llarp
OnGeneratedIntroFrame(AsyncKeyExchange* k, PathID_t p); OnGeneratedIntroFrame(AsyncKeyExchange* k, PathID_t p);
bool bool
OnIntroSetUpdate(const Address& addr, nonstd::optional<IntroSet> i, const RouterID& endpoint); OnIntroSetUpdate(const Address& addr, std::optional<IntroSet> i, const RouterID& endpoint);
const dht::Key_t location; const dht::Key_t location;
uint64_t m_UpdateIntrosetTX = 0; uint64_t m_UpdateIntrosetTX = 0;

@ -9,14 +9,14 @@
#define PATH_SEP "/" #define PATH_SEP "/"
#endif #endif
#include <ghc/filesystem.hpp> #include <filesystem>
namespace fs = ghc::filesystem; namespace fs = std::filesystem;
#ifndef _MSC_VER #ifndef _MSC_VER
#include <dirent.h> #include <dirent.h>
#endif #endif
#include <nonstd/optional.hpp> #include <optional>
namespace llarp namespace llarp
{ {
@ -32,7 +32,7 @@ namespace llarp
/// open a stream to a file and ensure it exists before open /// open a stream to a file and ensure it exists before open
/// sets any permissions on creation /// sets any permissions on creation
template <typename T> template <typename T>
nonstd::optional<T> std::optional<T>
OpenFileStream(fs::path pathname, std::ios::openmode mode) OpenFileStream(fs::path pathname, std::ios::openmode mode)
{ {
if (EnsurePrivateFile(pathname)) if (EnsurePrivateFile(pathname))

@ -1,5 +1,4 @@
#include <util/json.hpp> #include <util/json.hpp>
#include <util/string_view.hpp>
#include <cstring> #include <cstring>
#include <string> #include <string>

@ -1,8 +1,6 @@
#ifndef LLARP_UTIL_JSON_HPP #ifndef LLARP_UTIL_JSON_HPP
#define LLARP_UTIL_JSON_HPP #define LLARP_UTIL_JSON_HPP
#include <util/string_view.hpp>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <memory> #include <memory>

@ -46,7 +46,7 @@ namespace llarp
} }
} }
nonstd::optional<LogLevel> std::optional<LogLevel>
LogLevelFromString(std::string level) LogLevelFromString(std::string level)
{ {
std::transform(level.begin(), level.end(), level.begin(), [](const unsigned char ch) -> char { std::transform(level.begin(), level.end(), level.begin(), [](const unsigned char ch) -> char {

@ -1,7 +1,7 @@
#ifndef LLARP_UTIL_LOG_LEVEL_HPP #ifndef LLARP_UTIL_LOG_LEVEL_HPP
#define LLARP_UTIL_LOG_LEVEL_HPP #define LLARP_UTIL_LOG_LEVEL_HPP
#include <string> #include <string>
#include <nonstd/optional.hpp> #include <optional>
namespace llarp namespace llarp
{ {
@ -22,7 +22,7 @@ namespace llarp
std::string std::string
LogLevelToName(LogLevel lvl); LogLevelToName(LogLevel lvl);
nonstd::optional<LogLevel> std::optional<LogLevel>
LogLevelFromString(std::string level); LogLevelFromString(std::string level);
} // namespace llarp } // namespace llarp

@ -59,7 +59,7 @@ namespace llarp
} }
void void
Printer::printHexAddr(string_view name, const void* address) const Printer::printHexAddr(std::string_view name, const void* address) const
{ {
printIndent(); printIndent();
m_stream << name << " = "; m_stream << name << " = ";
@ -182,7 +182,7 @@ namespace llarp
void void
PrintHelper::printType( PrintHelper::printType(
std::ostream& stream, std::ostream& stream,
const string_view& value, const std::string_view& value,
int, int,
int spacesPerLevel, int spacesPerLevel,
traits::select::Case<traits::is_container>) traits::select::Case<traits::is_container>)

@ -1,13 +1,13 @@
#ifndef LLARP_PRINTER_HPP #ifndef LLARP_PRINTER_HPP
#define LLARP_PRINTER_HPP #define LLARP_PRINTER_HPP
#include <util/string_view.hpp>
#include <util/meta/traits.hpp> #include <util/meta/traits.hpp>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <cassert> #include <cassert>
#include <algorithm> #include <algorithm>
#include <string_view>
namespace llarp namespace llarp
{ {
@ -57,7 +57,7 @@ namespace llarp
/// - If `Type` is a `void *`, `const void *` or function pointer, and not /// - If `Type` is a `void *`, `const void *` or function pointer, and not
/// null, print in hex format or print "null". /// null, print in hex format or print "null".
/// - If `Type` is a `char *`, a `const char *`, a C-style char array, a /// - If `Type` is a `char *`, a `const char *`, a C-style char array, a
/// `std::string` or `llarp::string_view` print the string wrapped in `"`. /// `std::string` or `std::string_view` print the string wrapped in `"`.
/// - If `Type` is a pointer type, print the pointer, followed by the value /// - If `Type` is a pointer type, print the pointer, followed by the value
/// if not-null. /// if not-null.
/// - If `Type` is a pair/tuple type, print the elements of the tuple. /// - If `Type` is a pair/tuple type, print the elements of the tuple.
@ -66,15 +66,15 @@ namespace llarp
/// - If `Type` is any other type, call the `print` method on that type. /// - If `Type` is any other type, call the `print` method on that type.
template <typename Type> template <typename Type>
void void
printAttribute(string_view name, const Type& value) const; printAttribute(std::string_view name, const Type& value) const;
template <typename Type> template <typename Type>
void void
printAttributeAsHex(string_view name, const Type& value) const; printAttributeAsHex(std::string_view name, const Type& value) const;
template <typename InputIt> template <typename InputIt>
void void
printAttribute(string_view name, const InputIt& begin, const InputIt& end) const; printAttribute(std::string_view name, const InputIt& begin, const InputIt& end) const;
template <typename Type> template <typename Type>
void void
@ -87,20 +87,20 @@ namespace llarp
template <typename Type> template <typename Type>
void void
printForeignAttribute( printForeignAttribute(
string_view name, const Type& value, const PrintFunction<Type>& printFunction) const; std::string_view name, const Type& value, const PrintFunction<Type>& printFunction) const;
template <typename Type> template <typename Type>
void void
printForeignValue(const Type& value, const PrintFunction<Type>& printFunction) const; printForeignValue(const Type& value, const PrintFunction<Type>& printFunction) const;
void void
printHexAddr(string_view name, const void* address) const; printHexAddr(std::string_view name, const void* address) const;
void void
printHexAddr(const void* address) const; printHexAddr(const void* address) const;
template <class Type> template <class Type>
void void
printOrNull(string_view name, const Type& address) const; printOrNull(std::string_view name, const Type& address) const;
template <class Type> template <class Type>
void void
printOrNull(const Type& address) const; printOrNull(const Type& address) const;
@ -215,7 +215,7 @@ namespace llarp
static void static void
printType( printType(
std::ostream& stream, std::ostream& stream,
const string_view& value, const std::string_view& value,
int level, int level,
int spaces, int spaces,
traits::select::Case<traits::is_container>); traits::select::Case<traits::is_container>);
@ -257,7 +257,7 @@ namespace llarp
template <typename Type> template <typename Type>
inline void inline void
Printer::printAttribute(string_view name, const Type& value) const Printer::printAttribute(std::string_view name, const Type& value) const
{ {
assert(!name.empty()); assert(!name.empty());
printIndent(); printIndent();
@ -269,7 +269,7 @@ namespace llarp
template <typename Type> template <typename Type>
inline void inline void
Printer::printAttributeAsHex(string_view name, const Type& value) const Printer::printAttributeAsHex(std::string_view name, const Type& value) const
{ {
static_assert(std::is_integral<Type>::value, "type should be integral"); static_assert(std::is_integral<Type>::value, "type should be integral");
assert(!name.empty()); assert(!name.empty());
@ -289,7 +289,7 @@ namespace llarp
template <typename InputIt> template <typename InputIt>
inline void inline void
Printer::printAttribute(string_view name, const InputIt& begin, const InputIt& end) const Printer::printAttribute(std::string_view name, const InputIt& begin, const InputIt& end) const
{ {
assert(!name.empty()); assert(!name.empty());
printIndent(); printIndent();
@ -320,7 +320,7 @@ namespace llarp
template <typename Type> template <typename Type>
inline void inline void
Printer::printForeignAttribute( Printer::printForeignAttribute(
string_view name, const Type& value, const PrintFunction<Type>& printFunction) const std::string_view name, const Type& value, const PrintFunction<Type>& printFunction) const
{ {
assert(!name.empty()); assert(!name.empty());
printIndent(); printIndent();
@ -341,7 +341,7 @@ namespace llarp
template <typename Type> template <typename Type>
inline void inline void
Printer::printOrNull(string_view name, const Type& address) const Printer::printOrNull(std::string_view name, const Type& address) const
{ {
assert(!name.empty()); assert(!name.empty());
printIndent(); printIndent();
@ -385,7 +385,7 @@ namespace llarp
template <> template <>
inline void inline void
Printer::printOrNull<const void*>(string_view name, const void* const& address) const Printer::printOrNull<const void*>(std::string_view name, const void* const& address) const
{ {
assert(!name.empty()); assert(!name.empty());
printIndent(); printIndent();
@ -397,7 +397,7 @@ namespace llarp
} }
template <> template <>
inline void inline void
Printer::printOrNull<void*>(string_view name, void* const& address) const Printer::printOrNull<void*>(std::string_view name, void* const& address) const
{ {
const void* const& temp = address; const void* const& temp = address;

@ -1,14 +1,8 @@
#ifndef LLARP_UTIL_STATUS_HPP #ifndef LLARP_UTIL_STATUS_HPP
#define LLARP_UTIL_STATUS_HPP #define LLARP_UTIL_STATUS_HPP
#include <util/string_view.hpp>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <vector>
#include <string>
#include <algorithm>
namespace llarp namespace llarp
{ {
namespace util namespace util

@ -9,7 +9,7 @@
namespace llarp namespace llarp
{ {
bool bool
CaselessLessThan::operator()(string_view lhs, string_view rhs) const CaselessLessThan::operator()(std::string_view lhs, std::string_view rhs) const
{ {
const size_t s = std::min(lhs.size(), rhs.size()); const size_t s = std::min(lhs.size(), rhs.size());
for (size_t i = 0; i < s; ++i) for (size_t i = 0; i < s; ++i)
@ -31,17 +31,17 @@ namespace llarp
} }
bool bool
IsFalseValue(string_view str) IsFalseValue(std::string_view str)
{ {
static const std::set<string_view, CaselessLessThan> vals{"no", "false", "0", "off"}; static const std::set<std::string_view, CaselessLessThan> vals{"no", "false", "0", "off"};
return vals.count(str) > 0; return vals.count(str) > 0;
} }
bool bool
IsTrueValue(string_view str) IsTrueValue(std::string_view str)
{ {
static const std::set<string_view, CaselessLessThan> vals{"yes", "true", "1", "on"}; static const std::set<std::string_view, CaselessLessThan> vals{"yes", "true", "1", "on"};
return vals.count(str) > 0; return vals.count(str) > 0;
} }
@ -61,11 +61,11 @@ namespace llarp
constexpr static char whitespace[] = " \t\n\r\f\v"; constexpr static char whitespace[] = " \t\n\r\f\v";
string_view std::string_view
TrimWhitespace(string_view str) TrimWhitespace(std::string_view str)
{ {
size_t begin = str.find_first_not_of(whitespace); size_t begin = str.find_first_not_of(whitespace);
if (begin == string_view::npos) if (begin == std::string_view::npos)
{ {
str.remove_prefix(str.size()); str.remove_prefix(str.size());
return str; return str;
@ -73,20 +73,20 @@ namespace llarp
str.remove_prefix(begin); str.remove_prefix(begin);
size_t end = str.find_last_not_of(whitespace); size_t end = str.find_last_not_of(whitespace);
if (end != string_view::npos) if (end != std::string_view::npos)
str.remove_suffix(str.size() - end - 1); str.remove_suffix(str.size() - end - 1);
return str; return str;
} }
std::vector<string_view> std::vector<std::string_view>
split(string_view str, char delimiter) split(std::string_view str, char delimiter)
{ {
std::vector<string_view> splits; std::vector<std::string_view> splits;
size_t last = 0; size_t last = 0;
size_t next = 0; size_t next = 0;
while (last < str.size() and next < string_view::npos) while (last < str.size() and next < std::string_view::npos)
{ {
next = str.find_first_of(delimiter, last); next = str.find_first_of(delimiter, last);
if (next > last) if (next > last)

@ -1,7 +1,7 @@
#ifndef LLARP_STR_HPP #ifndef LLARP_STR_HPP
#define LLARP_STR_HPP #define LLARP_STR_HPP
#include <util/string_view.hpp> #include <string_view>
#include <sstream> #include <sstream>
#include <vector> #include <vector>
@ -11,24 +11,24 @@ namespace llarp
StrEq(const char* s1, const char* s2); StrEq(const char* s1, const char* s2);
bool bool
IsFalseValue(string_view str); IsFalseValue(std::string_view str);
struct CaselessLessThan struct CaselessLessThan
{ {
bool bool
operator()(string_view lhs, string_view rhs) const; operator()(std::string_view lhs, std::string_view rhs) const;
}; };
bool bool
IsTrueValue(string_view str); IsTrueValue(std::string_view str);
/// Trim leading and trailing (ascii) whitespace from the given string; /// Trim leading and trailing (ascii) whitespace from the given string;
/// returns a string_view of the trimmed part of the string. /// returns a std::string_view of the trimmed part of the string.
#ifdef __GNUG__ #ifdef __GNUG__
[[gnu::warn_unused_result]] [[gnu::warn_unused_result]]
#endif #endif
string_view std::string_view
TrimWhitespace(string_view str); TrimWhitespace(std::string_view str);
template <typename... T> template <typename... T>
std::string std::string
@ -43,13 +43,19 @@ namespace llarp
return o.str(); return o.str();
} }
// Shortcut for explicitly casting a string_view to a string. Saves 8 characters compared to
// `std::string(view)`.
inline std::string str(std::string_view s) {
return std::string{s};
}
/// Split a string on a given delimiter /// Split a string on a given delimiter
// //
/// @param str is the string to split /// @param str is the string to split
/// @param delimiter is the character to split on /// @param delimiter is the character to split on
/// @return a vector of string_views with the split words, excluding the delimeter /// @return a vector of std::string_views with the split words, excluding the delimeter
std::vector<string_view> std::vector<std::string_view>
split(string_view str, char delimiter); split(std::string_view str, char delimiter);
} // namespace llarp } // namespace llarp

@ -1,231 +0,0 @@
#ifndef LLARP_STRING_VIEW_HPP
#define LLARP_STRING_VIEW_HPP
// Copied from loki-mq (with namespaces modified); when we fully import loki-mq
// we can just use it directly.
// To keep this identical to loki-mq's copy (e.g. to be able to diff it):
//
// clang-format off
#include <string>
#ifdef __cpp_lib_string_view
#include <string_view>
namespace llarp { using string_view = std::string_view; }
#else
#include <ostream>
#include <limits>
namespace llarp {
/// Basic implementation of std::string_view (except for std::hash support).
class simple_string_view {
const char *data_;
size_t size_;
public:
using traits_type = std::char_traits<char>;
using value_type = char;
using pointer = char*;
using const_pointer = const char*;
using reference = char&;
using const_reference = const char&;
using const_iterator = const_pointer;
using iterator = const_iterator;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using reverse_iterator = const_reverse_iterator;
using size_type = std::size_t;
using different_type = std::ptrdiff_t;
static constexpr auto& npos = std::string::npos;
constexpr simple_string_view() noexcept : data_{nullptr}, size_{0} {}
constexpr simple_string_view(const simple_string_view&) noexcept = default;
simple_string_view(const std::string& str) : data_{str.data()}, size_{str.size()} {}
constexpr simple_string_view(const char* data, size_t size) noexcept : data_{data}, size_{size} {}
simple_string_view(const char* data) : data_{data}, size_{traits_type::length(data)} {}
simple_string_view& operator=(const simple_string_view&) = default;
constexpr const char* data() const noexcept { return data_; }
constexpr size_t size() const noexcept { return size_; }
constexpr size_t length() const noexcept { return size_; }
constexpr size_t max_size() const noexcept { return std::numeric_limits<size_t>::max(); }
constexpr bool empty() const noexcept { return size_ == 0; }
explicit operator std::string() const { return {data_, size_}; }
constexpr const char* begin() const noexcept { return data_; }
constexpr const char* cbegin() const noexcept { return data_; }
constexpr const char* end() const noexcept { return data_ + size_; }
constexpr const char* cend() const noexcept { return data_ + size_; }
reverse_iterator rbegin() const { return reverse_iterator{end()}; }
reverse_iterator crbegin() const { return reverse_iterator{end()}; }
reverse_iterator rend() const { return reverse_iterator{begin()}; }
reverse_iterator crend() const { return reverse_iterator{begin()}; }
constexpr const char& operator[](size_t pos) const { return data_[pos]; }
constexpr const char& front() const { return *data_; }
constexpr const char& back() const { return data_[size_ - 1]; }
int compare(simple_string_view s) const;
constexpr void remove_prefix(size_t n) { data_ += n; size_ -= n; }
constexpr void remove_suffix(size_t n) { size_ -= n; }
void swap(simple_string_view &s) noexcept { std::swap(data_, s.data_); std::swap(size_, s.size_); }
#if defined(__clang__) || !defined(__GNUG__) || __GNUC__ >= 6
constexpr // GCC 5.x is buggy wrt constexpr throwing
#endif
const char& at(size_t pos) const {
if (pos >= size())
throw std::out_of_range{"invalid string_view index"};
return data_[pos];
};
size_t copy(char* dest, size_t count, size_t pos = 0) const {
if (pos > size()) throw std::out_of_range{"invalid copy pos"};
size_t rcount = std::min(count, size_ - pos);
traits_type::copy(dest, data_ + pos, rcount);
return rcount;
}
#if defined(__clang__) || !defined(__GNUG__) || __GNUC__ >= 6
constexpr // GCC 5.x is buggy wrt constexpr throwing
#endif
simple_string_view substr(size_t pos = 0, size_t count = npos) const {
if (pos > size()) throw std::out_of_range{"invalid substr range"};
simple_string_view result = *this;
if (pos > 0) result.remove_prefix(pos);
if (count < result.size()) result.remove_suffix(result.size() - count);
return result;
}
size_t find(simple_string_view v, size_t pos = 0) const {
if (pos > size_ || v.size_ > size_) return npos;
for (const size_t max_pos = size_ - v.size_; pos <= max_pos; ++pos) {
if (0 == traits_type::compare(v.data_, data_ + pos, v.size_))
return pos;
}
return npos;
}
size_t find(char c, size_t pos = 0) const { return find({&c, 1}, pos); }
size_t find(const char* c, size_t pos, size_t count) const { return find({c, count}, pos); }
size_t find(const char* c, size_t pos = 0) const { return find(simple_string_view(c), pos); }
size_t rfind(simple_string_view v, size_t pos = npos) const {
if (v.size_ > size_) return npos;
const size_t max_pos = size_ - v.size_;
for (pos = std::min(pos, max_pos); pos <= max_pos; --pos) {
if (0 == traits_type::compare(v.data_, data_ + pos, v.size_))
return pos;
}
return npos;
}
size_t rfind(char c, size_t pos = npos) const { return rfind({&c, 1}, pos); }
size_t rfind(const char* c, size_t pos, size_t count) const { return rfind({c, count}, pos); }
size_t rfind(const char* c, size_t pos = npos) const { return rfind(simple_string_view(c), pos); }
constexpr size_t find_first_of(simple_string_view v, size_t pos = 0) const noexcept {
for (; pos < size_; ++pos)
for (char c : v)
if (data_[pos] == c)
return pos;
return npos;
}
constexpr size_t find_first_of(char c, size_t pos = 0) const noexcept { return find_first_of({&c, 1}, pos); }
constexpr size_t find_first_of(const char* c, size_t pos, size_t count) const { return find_first_of({c, count}, pos); }
size_t find_first_of(const char* c, size_t pos = 0) const { return find_first_of(simple_string_view(c), pos); }
constexpr size_t find_last_of(simple_string_view v, const size_t pos = npos) const noexcept {
if (size_ == 0) return npos;
const size_t last_pos = std::min(pos, size_-1);
for (size_t i = last_pos; i <= last_pos; --i)
for (char c : v)
if (data_[i] == c)
return i;
return npos;
}
constexpr size_t find_last_of(char c, size_t pos = npos) const noexcept { return find_last_of({&c, 1}, pos); }
constexpr size_t find_last_of(const char* c, size_t pos, size_t count) const { return find_last_of({c, count}, pos); }
size_t find_last_of(const char* c, size_t pos = npos) const { return find_last_of(simple_string_view(c), pos); }
constexpr size_t find_first_not_of(simple_string_view v, size_t pos = 0) const noexcept {
for (; pos < size_; ++pos) {
bool none = true;
for (char c : v) {
if (data_[pos] == c) {
none = false;
break;
}
}
if (none) return pos;
}
return npos;
}
constexpr size_t find_first_not_of(char c, size_t pos = 0) const noexcept { return find_first_not_of({&c, 1}, pos); }
constexpr size_t find_first_not_of(const char* c, size_t pos, size_t count) const { return find_first_not_of({c, count}, pos); }
size_t find_first_not_of(const char* c, size_t pos = 0) const { return find_first_not_of(simple_string_view(c), pos); }
constexpr size_t find_last_not_of(simple_string_view v, const size_t pos = npos) const noexcept {
if (size_ == 0) return npos;
const size_t last_pos = std::min(pos, size_-1);
for (size_t i = last_pos; i <= last_pos; --i) {
bool none = true;
for (char c : v) {
if (data_[i] == c) {
none = false;
break;
}
}
if (none) return i;
}
return npos;
}
constexpr size_t find_last_not_of(char c, size_t pos = npos) const noexcept { return find_last_not_of({&c, 1}, pos); }
constexpr size_t find_last_not_of(const char* c, size_t pos, size_t count) const { return find_last_not_of({c, count}, pos); }
size_t find_last_not_of(const char* c, size_t pos = npos) const { return find_last_not_of(simple_string_view(c), pos); }
};
inline bool operator==(simple_string_view lhs, simple_string_view rhs) {
return lhs.size() == rhs.size() && 0 == std::char_traits<char>::compare(lhs.data(), rhs.data(), lhs.size());
};
inline bool operator!=(simple_string_view lhs, simple_string_view rhs) {
return !(lhs == rhs);
}
inline int simple_string_view::compare(simple_string_view s) const {
int cmp = std::char_traits<char>::compare(data_, s.data(), std::min(size_, s.size()));
if (cmp) return cmp;
if (size_ < s.size()) return -1;
else if (size_ > s.size()) return 1;
return 0;
}
inline bool operator<(simple_string_view lhs, simple_string_view rhs) {
return lhs.compare(rhs) < 0;
};
inline bool operator<=(simple_string_view lhs, simple_string_view rhs) {
return lhs.compare(rhs) <= 0;
};
inline bool operator>(simple_string_view lhs, simple_string_view rhs) {
return lhs.compare(rhs) > 0;
};
inline bool operator>=(simple_string_view lhs, simple_string_view rhs) {
return lhs.compare(rhs) >= 0;
};
inline std::ostream& operator<<(std::ostream& os, const simple_string_view& s) {
os.write(s.data(), s.size());
return os;
}
using string_view = simple_string_view;
}
#endif
namespace llarp {
// Shortcut for explicitly casting a string_view to a string. Saves 8
// characters compared to `std::string(view)`.
inline std::string str(string_view s) {
return std::string{s};
}
}
#endif

@ -4,7 +4,7 @@
#include <ev/ev.hpp> #include <ev/ev.hpp>
#include <util/mem.h> #include <util/mem.h>
#include <util/thread/threadpool.h> #include <util/thread/threadpool.h>
#include <nonstd/optional.hpp> #include <optional>
namespace llarp namespace llarp
{ {
@ -53,7 +53,7 @@ namespace llarp
using ID_t = std::thread::id; using ID_t = std::thread::id;
llarp_threadpool* const m_Thread; llarp_threadpool* const m_Thread;
llarp_ev_loop* m_Loop = nullptr; llarp_ev_loop* m_Loop = nullptr;
nonstd::optional<ID_t> m_ID; std::optional<ID_t> m_ID;
util::ContentionKiller m_Killer; util::ContentionKiller m_Killer;
std::function<void(std::function<void(void)>)> m_Queue; std::function<void(std::function<void(void)>)> m_Queue;
}; };

@ -4,7 +4,7 @@
#include <util/thread/queue_manager.hpp> #include <util/thread/queue_manager.hpp>
#include <util/thread/threading.hpp> #include <util/thread/threading.hpp>
#include <nonstd/optional.hpp> #include <optional>
#include <atomic> #include <atomic>
#include <tuple> #include <tuple>
@ -73,10 +73,10 @@ namespace llarp
// Remove an element from the queue. Block until an element is available // Remove an element from the queue. Block until an element is available
// or until <timeout> microseconds have elapsed // or until <timeout> microseconds have elapsed
nonstd::optional<Type> std::optional<Type>
popFrontWithTimeout(std::chrono::microseconds timeout); popFrontWithTimeout(std::chrono::microseconds timeout);
nonstd::optional<Type> std::optional<Type>
tryPopFront(); tryPopFront();
// Remove all elements from the queue. Note this is not atomic, and if // Remove all elements from the queue. Note this is not atomic, and if
@ -263,7 +263,7 @@ namespace llarp
} }
template <typename Type> template <typename Type>
nonstd::optional<Type> std::optional<Type>
Queue<Type>::tryPopFront() Queue<Type>::tryPopFront()
{ {
uint32_t generation; uint32_t generation;
@ -288,7 +288,7 @@ namespace llarp
// - notify any waiting pushers // - notify any waiting pushers
QueuePopGuard<Type> popGuard(*this, generation, index); QueuePopGuard<Type> popGuard(*this, generation, index);
return nonstd::optional<Type>(std::move(m_data[index])); return std::optional<Type>(std::move(m_data[index]));
} }
template <typename Type> template <typename Type>
@ -388,7 +388,7 @@ namespace llarp
} }
template <typename Type> template <typename Type>
nonstd::optional<Type> std::optional<Type>
Queue<Type>::popFrontWithTimeout(std::chrono::microseconds timeout) Queue<Type>::popFrontWithTimeout(std::chrono::microseconds timeout)
{ {
uint32_t generation = 0; uint32_t generation = 0;

@ -153,7 +153,7 @@ namespace llarp
} }
} }
ThreadPool::ThreadPool(size_t numThreads, size_t maxJobs, string_view name) ThreadPool::ThreadPool(size_t numThreads, size_t maxJobs, std::string_view name)
: m_queue(maxJobs) : m_queue(maxJobs)
, m_semaphore(0) , m_semaphore(0)
, m_idleThreads(0) , m_idleThreads(0)

@ -1,7 +1,6 @@
#ifndef LLARP_THREAD_POOL_HPP #ifndef LLARP_THREAD_POOL_HPP
#define LLARP_THREAD_POOL_HPP #define LLARP_THREAD_POOL_HPP
#include <util/string_view.hpp>
#include <util/thread/queue.hpp> #include <util/thread/queue.hpp>
#include <util/thread/threading.hpp> #include <util/thread/threading.hpp>
@ -9,6 +8,7 @@
#include <functional> #include <functional>
#include <thread> #include <thread>
#include <vector> #include <vector>
#include <string_view>
namespace llarp namespace llarp
{ {
@ -84,7 +84,7 @@ namespace llarp
} }
public: public:
ThreadPool(size_t numThreads, size_t maxJobs, string_view name); ThreadPool(size_t numThreads, size_t maxJobs, std::string_view name);
~ThreadPool(); ~ThreadPool();

@ -4,7 +4,7 @@
#include <thread> #include <thread>
#include <shared_mutex> #include <shared_mutex>
#include <mutex> #include <mutex>
#include <nonstd/optional.hpp> #include <optional>
#include "annotations.hpp" #include "annotations.hpp"
@ -45,7 +45,7 @@ namespace llarp
/// in debug mode, we implement lock() to enforce that any lock is only /// in debug mode, we implement lock() to enforce that any lock is only
/// used from a single thread. the point of this is to identify locks that /// used from a single thread. the point of this is to identify locks that
/// are actually needed by dying a painful death when used across threads /// are actually needed by dying a painful death when used across threads
mutable nonstd::optional<std::thread::id> m_id; mutable std::optional<std::thread::id> m_id;
void void
lock() const lock() const
{ {

@ -1,7 +1,6 @@
#ifndef LLARP_THREADPOOL_H #ifndef LLARP_THREADPOOL_H
#define LLARP_THREADPOOL_H #define LLARP_THREADPOOL_H
#include <util/string_view.hpp>
#include <util/thread/queue.hpp> #include <util/thread/queue.hpp>
#include <util/thread/thread_pool.hpp> #include <util/thread/thread_pool.hpp>
#include <util/thread/threading.hpp> #include <util/thread/threading.hpp>
@ -10,6 +9,7 @@
#include <memory> #include <memory>
#include <queue> #include <queue>
#include <string_view>
struct llarp_threadpool; struct llarp_threadpool;
@ -18,7 +18,7 @@ struct llarp_threadpool
{ {
std::unique_ptr<llarp::thread::ThreadPool> impl; std::unique_ptr<llarp::thread::ThreadPool> impl;
llarp_threadpool(int workers, llarp::string_view name, size_t queueLength = size_t{1024 * 8}) llarp_threadpool(int workers, std::string_view name, size_t queueLength = size_t{1024 * 8})
: impl(std::make_unique<llarp::thread::ThreadPool>( : impl(std::make_unique<llarp::thread::ThreadPool>(
workers, std::max(queueLength, size_t{32}), name)) workers, std::max(queueLength, size_t{32}), name))
{ {

@ -1,10 +1,7 @@
#include <config/definition.hpp> #include <config/definition.hpp>
#include <util/string_view.hpp>
#include <catch2/catch.hpp> #include <catch2/catch.hpp>
using llarp::string_view;
TEST_CASE("OptionDefinition int parse test", "[config]") TEST_CASE("OptionDefinition int parse test", "[config]")
{ {
llarp::OptionDefinition<int> def("foo", "bar", false, 42); llarp::OptionDefinition<int> def("foo", "bar", false, 42);
@ -225,7 +222,7 @@ TEST_CASE("ConfigDefinition undeclared definition basic test", "[config]")
bool invoked = false; bool invoked = false;
config.addUndeclaredHandler("foo", [&](string_view section, string_view name, string_view value) { config.addUndeclaredHandler("foo", [&](std::string_view section, std::string_view name, std::string_view value) {
CHECK(section == "foo"); CHECK(section == "foo");
CHECK(name == "bar"); CHECK(name == "bar");
CHECK(value == "val"); CHECK(value == "val");
@ -244,11 +241,11 @@ TEST_CASE("ConfigDefinition undeclared add more than once test", "[config]")
std::string calledBy = ""; std::string calledBy = "";
config.addUndeclaredHandler("foo", [&](string_view, string_view, string_view) { config.addUndeclaredHandler("foo", [&](std::string_view, std::string_view, std::string_view) {
calledBy = "a"; calledBy = "a";
}); });
REQUIRE_THROWS_WITH( REQUIRE_THROWS_WITH(
config.addUndeclaredHandler("foo", [&](string_view, string_view, string_view) { config.addUndeclaredHandler("foo", [&](std::string_view, std::string_view, std::string_view) {
calledBy = "b"; calledBy = "b";
}), }),
"section foo already has a handler"); "section foo already has a handler");
@ -265,7 +262,7 @@ TEST_CASE("ConfigDefinition undeclared add/remove test", "[config]")
std::string calledBy = ""; std::string calledBy = "";
// add... // add...
REQUIRE_NOTHROW(config.addUndeclaredHandler("foo", [&](string_view, string_view, string_view) { REQUIRE_NOTHROW(config.addUndeclaredHandler("foo", [&](std::string_view, std::string_view, std::string_view) {
calledBy = "a"; calledBy = "a";
})); }));
@ -283,7 +280,7 @@ TEST_CASE("ConfigDefinition undeclared add/remove test", "[config]")
"no declared section [foo]"); "no declared section [foo]");
// ...then add again // ...then add again
REQUIRE_NOTHROW(config.addUndeclaredHandler("foo", [&](string_view, string_view, string_view) { REQUIRE_NOTHROW(config.addUndeclaredHandler("foo", [&](std::string_view, std::string_view, std::string_view) {
calledBy = "b"; calledBy = "b";
})); }));
@ -296,7 +293,7 @@ TEST_CASE("ConfigDefinition undeclared handler exception propagation test", "[co
{ {
llarp::ConfigDefinition config; llarp::ConfigDefinition config;
config.addUndeclaredHandler("foo", [](string_view, string_view, string_view) { config.addUndeclaredHandler("foo", [](std::string_view, std::string_view, std::string_view) {
throw std::runtime_error("FAIL"); throw std::runtime_error("FAIL");
}); });
@ -307,7 +304,7 @@ TEST_CASE("ConfigDefinition undeclared handler wrong section", "[config]")
{ {
llarp::ConfigDefinition config; llarp::ConfigDefinition config;
config.addUndeclaredHandler("foo", [](string_view, string_view, string_view) { config.addUndeclaredHandler("foo", [](std::string_view, std::string_view, std::string_view) {
throw std::runtime_error("FAIL"); throw std::runtime_error("FAIL");
}); });
@ -320,7 +317,7 @@ TEST_CASE("ConfigDefinition undeclared handler duplicate names", "[config]")
int count = 0; int count = 0;
config.addUndeclaredHandler("foo", [&](string_view, string_view, string_view) { config.addUndeclaredHandler("foo", [&](std::string_view, std::string_view, std::string_view) {
count++; count++;
}); });
@ -375,7 +372,7 @@ TEST_CASE("ConfigDefinition [bind]iface regression", "[config regression]")
config.defineOption<std::string>( config.defineOption<std::string>(
"bind", "*", false, false, "1090", [&](std::string arg) { val1 = arg; }); "bind", "*", false, false, "1090", [&](std::string arg) { val1 = arg; });
config.addUndeclaredHandler("bind", [&](string_view, string_view name, string_view value) { config.addUndeclaredHandler("bind", [&](std::string_view, std::string_view name, std::string_view value) {
undeclaredName = std::string(name); undeclaredName = std::string(name);
undeclaredValue = std::string(value); undeclaredValue = std::string(value);
}); });

@ -72,7 +72,7 @@ namespace llarp
void(const dht::Key_t&, AbstractRouter*)); void(const dht::Key_t&, AbstractRouter*));
MOCK_CONST_METHOD1(GetIntroSetByLocation, MOCK_CONST_METHOD1(GetIntroSetByLocation,
nonstd::optional< llarp::service::EncryptedIntroSet >( std::optional< llarp::service::EncryptedIntroSet >(
const llarp::dht::Key_t&)); const llarp::dht::Key_t&));
MOCK_CONST_METHOD0(ExtractStatus, util::StatusObject()); MOCK_CONST_METHOD0(ExtractStatus, util::StatusObject());

@ -8,7 +8,7 @@ using TestString = std::string;
struct TestParseLog struct TestParseLog
{ {
TestString input; TestString input;
nonstd::optional< llarp::LogLevel > level; std::optional< llarp::LogLevel > level;
}; };
struct LogLevelTest : public ::testing::TestWithParam< TestParseLog > struct LogLevelTest : public ::testing::TestWithParam< TestParseLog >

@ -575,7 +575,7 @@ TEST(TestQueue, moveIt)
ASSERT_EQ(5u, counter); ASSERT_EQ(5u, counter);
nonstd::optional< MoveTester > optPopped = queue.tryPopFront(); std::optional< MoveTester > optPopped = queue.tryPopFront();
ASSERT_TRUE(optPopped.has_value()); ASSERT_TRUE(optPopped.has_value());

@ -1,6 +1,6 @@
#include <util/thread/queue_manager.hpp> #include <util/thread/queue_manager.hpp>
#include <nonstd/optional.hpp> #include <optional>
#include <vector> #include <vector>
#include <gtest/gtest.h> #include <gtest/gtest.h>
@ -75,7 +75,7 @@ class IntQueue
} }
} }
nonstd::optional< int > std::optional< int >
tryPopFront() tryPopFront()
{ {
uint32_t gen = 0; uint32_t gen = 0;

Loading…
Cancel
Save