Use std::string_view and fmtlib across all libraries (#3402)

- Twine, StringRef, Format, and NativeFormatting have been removed
- Logging now uses fmtlib style formatting
- Nearly all uses of wpi::outs/errs have been replaced with fmt::print() or
std::puts()/std::fputs() (for unformatted strings).
- A wpi/fmt/raw_ostream.h header has been added to enable
fmt::print() with wpi::raw_ostream
This commit is contained in:
Peter Johnson
2021-06-06 16:13:58 -07:00
committed by GitHub
parent 4f1cecb8e7
commit b2c3b2dd8e
441 changed files with 5061 additions and 9749 deletions

View File

@@ -7,6 +7,7 @@
#include <algorithm>
#include <iterator>
#include <wpi/StringExtras.h>
#include <wpi/TCPAcceptor.h>
#include <wpi/TCPConnector.h>
#include <wpi/timestamp.h>
@@ -18,9 +19,9 @@
using namespace nt;
void Dispatcher::StartServer(const wpi::Twine& persist_filename,
void Dispatcher::StartServer(std::string_view persist_filename,
const char* listen_address, unsigned int port) {
std::string listen_address_copy(wpi::StringRef(listen_address).trim());
std::string listen_address_copy(wpi::trim(listen_address));
DispatcherBase::StartServer(
persist_filename,
std::unique_ptr<wpi::NetworkAcceptor>(new wpi::TCPAcceptor(
@@ -28,7 +29,7 @@ void Dispatcher::StartServer(const wpi::Twine& persist_filename,
}
void Dispatcher::SetServer(const char* server_name, unsigned int port) {
std::string server_name_copy(wpi::StringRef(server_name).trim());
std::string server_name_copy(wpi::trim(server_name));
SetConnector([=]() -> std::unique_ptr<wpi::NetworkStream> {
return wpi::TCPConnector::connect(server_name_copy.c_str(),
static_cast<int>(port), m_logger, 1);
@@ -36,10 +37,10 @@ void Dispatcher::SetServer(const char* server_name, unsigned int port) {
}
void Dispatcher::SetServer(
wpi::ArrayRef<std::pair<wpi::StringRef, unsigned int>> servers) {
wpi::ArrayRef<std::pair<std::string_view, unsigned int>> servers) {
wpi::SmallVector<std::pair<std::string, int>, 16> servers_copy;
for (const auto& server : servers) {
servers_copy.emplace_back(std::string{server.first.trim()},
servers_copy.emplace_back(std::string{wpi::trim(server.first)},
static_cast<int>(server.second));
}
@@ -53,49 +54,33 @@ void Dispatcher::SetServer(
}
void Dispatcher::SetServerTeam(unsigned int team, unsigned int port) {
std::pair<wpi::StringRef, unsigned int> servers[5];
std::pair<std::string_view, unsigned int> servers[5];
// 10.te.am.2
wpi::SmallString<32> fixed;
{
wpi::raw_svector_ostream oss{fixed};
oss << "10." << static_cast<int>(team / 100) << '.'
<< static_cast<int>(team % 100) << ".2";
servers[0] = std::make_pair(oss.str(), port);
}
auto fixed = fmt::format("10.{}.{}.2", static_cast<int>(team / 100),
static_cast<int>(team % 100));
servers[0] = {fixed, port};
// 172.22.11.2
servers[1] = std::make_pair("172.22.11.2", port);
servers[1] = {"172.22.11.2", port};
// roboRIO-<team>-FRC.local
wpi::SmallString<32> mdns;
{
wpi::raw_svector_ostream oss{mdns};
oss << "roboRIO-" << team << "-FRC.local";
servers[2] = std::make_pair(oss.str(), port);
}
auto mdns = fmt::format("roboRIO-{}-FRC.local", team);
servers[2] = {mdns, port};
// roboRIO-<team>-FRC.lan
wpi::SmallString<32> mdns_lan;
{
wpi::raw_svector_ostream oss{mdns_lan};
oss << "roboRIO-" << team << "-FRC.lan";
servers[3] = std::make_pair(oss.str(), port);
}
auto mdns_lan = fmt::format("roboRIO-{}-FRC.lan", team);
servers[3] = {mdns_lan, port};
// roboRIO-<team>-FRC.frc-field.local
wpi::SmallString<64> field_local;
{
wpi::raw_svector_ostream oss{field_local};
oss << "roboRIO-" << team << "-FRC.frc-field.local";
servers[4] = std::make_pair(oss.str(), port);
}
auto field_local = fmt::format("roboRIO-{}-FRC.frc-field.local", team);
servers[4] = {field_local, port};
SetServer(servers);
}
void Dispatcher::SetServerOverride(const char* server_name, unsigned int port) {
std::string server_name_copy(wpi::StringRef(server_name).trim());
std::string server_name_copy(wpi::trim(server_name));
SetConnectorOverride([=]() -> std::unique_ptr<wpi::NetworkStream> {
return wpi::TCPConnector::connect(server_name_copy.c_str(),
static_cast<int>(port), m_logger, 1);
@@ -134,7 +119,7 @@ void DispatcherBase::StartLocal() {
}
void DispatcherBase::StartServer(
const wpi::Twine& persist_filename,
std::string_view persist_filename,
std::unique_ptr<wpi::NetworkAcceptor> acceptor) {
{
std::scoped_lock lock(m_user_mutex);
@@ -144,22 +129,20 @@ void DispatcherBase::StartServer(
m_active = true;
}
m_networkMode = NT_NET_MODE_SERVER | NT_NET_MODE_STARTING;
m_persist_filename = persist_filename.str();
m_persist_filename = persist_filename;
m_server_acceptor = std::move(acceptor);
// Load persistent file. Ignore errors, but pass along warnings.
if (!persist_filename.isTriviallyEmpty() &&
(!persist_filename.isSingleStringRef() ||
!persist_filename.getSingleStringRef().empty())) {
if (!persist_filename.empty()) {
bool first = true;
m_storage.LoadPersistent(
persist_filename, [&](size_t line, const char* msg) {
if (first) {
first = false;
WARNING("When reading initial persistent values from '"
<< persist_filename << "':");
WARNING("When reading initial persistent values from '{}':",
persist_filename);
}
WARNING(persist_filename << ":" << line << ": " << msg);
WARNING("{}:{}: {}", persist_filename, line, msg);
});
}
@@ -230,9 +213,9 @@ void DispatcherBase::SetUpdateRate(double interval) {
m_update_rate = static_cast<unsigned int>(interval * 1000);
}
void DispatcherBase::SetIdentity(const wpi::Twine& name) {
void DispatcherBase::SetIdentity(std::string_view name) {
std::scoped_lock lock(m_user_mutex);
m_identity = name.str();
m_identity = name;
}
void DispatcherBase::Flush() {
@@ -369,7 +352,7 @@ void DispatcherBase::DispatchThreadMain() {
}
const char* err = m_storage.SavePersistent(m_persist_filename, true);
if (err) {
WARNING("periodic persistent save: " << err);
WARNING("periodic persistent save: {}", err);
}
}
@@ -378,7 +361,7 @@ void DispatcherBase::DispatchThreadMain() {
bool reconnect = false;
if (++count > 10) {
DEBUG0("dispatch running " << m_connections.size() << " connections");
DEBUG0("dispatch running {} connections", m_connections.size());
count = 0;
}
@@ -441,8 +424,8 @@ void DispatcherBase::ServerThreadMain() {
m_networkMode = NT_NET_MODE_NONE;
return;
}
DEBUG0("server: client connection from " << stream->getPeerIP() << " port "
<< stream->getPeerPort());
DEBUG0("server: client connection from {} port {}", stream->getPeerIP(),
stream->getPeerPort());
// add to connections list
using namespace std::placeholders;
@@ -494,13 +477,13 @@ void DispatcherBase::ClientThreadMain() {
}
// try to connect (with timeout)
DEBUG0("client trying to connect");
DEBUG0("{}", "client trying to connect");
auto stream = connect();
if (!stream) {
m_networkMode = NT_NET_MODE_CLIENT | NT_NET_MODE_FAILURE;
continue; // keep retrying
}
DEBUG0("client connected");
DEBUG0("{}", "client connected");
m_networkMode = NT_NET_MODE_CLIENT;
std::unique_lock lock(m_user_mutex);
@@ -538,14 +521,14 @@ bool DispatcherBase::ClientHandshake(
}
// send client hello
DEBUG0("client: sending hello");
DEBUG0("{}", "client: sending hello");
send_msgs(Message::ClientHello(self_id));
// wait for response
auto msg = get_msg();
if (!msg) {
// disconnected, retry
DEBUG0("client: server disconnected before first response");
DEBUG0("{}", "client: server disconnected before first response");
return false;
}
@@ -575,11 +558,11 @@ bool DispatcherBase::ClientHandshake(
for (;;) {
if (!msg) {
// disconnected, retry
DEBUG0("client: server disconnected during initial entries");
DEBUG0("{}", "client: server disconnected during initial entries");
return false;
}
DEBUG4("received init str=" << msg->str() << " id=" << msg->id()
<< " seq_num=" << msg->seq_num_uid());
DEBUG4("received init str={} id={} seq_num={}", msg->str(), msg->id(),
msg->seq_num_uid());
if (msg->Is(Message::kServerHelloDone)) {
break;
}
@@ -590,9 +573,10 @@ bool DispatcherBase::ClientHandshake(
}
if (!msg->Is(Message::kEntryAssign)) {
// unexpected message
DEBUG0("client: received message ("
<< msg->type()
<< ") other than entry assignment during initial handshake");
DEBUG0(
"client: received message ({}) other than entry assignment during "
"initial handshake",
msg->type());
return false;
}
incoming.emplace_back(std::move(msg));
@@ -613,8 +597,8 @@ bool DispatcherBase::ClientHandshake(
send_msgs(outgoing);
}
INFO("client: CONNECTED to server " << conn.stream().getPeerIP() << " port "
<< conn.stream().getPeerPort());
INFO("client: CONNECTED to server {} port {}", conn.stream().getPeerIP(),
conn.stream().getPeerPort());
return true;
}
@@ -624,18 +608,18 @@ bool DispatcherBase::ServerHandshake(
// Wait for the client to send us a hello.
auto msg = get_msg();
if (!msg) {
DEBUG0("server: client disconnected before sending hello");
DEBUG0("{}", "server: client disconnected before sending hello");
return false;
}
if (!msg->Is(Message::kClientHello)) {
DEBUG0("server: client initial message was not client hello");
DEBUG0("{}", "server: client initial message was not client hello");
return false;
}
// Check that the client requested version is not too high.
unsigned int proto_rev = msg->id();
if (proto_rev > 0x0300) {
DEBUG0("server: client requested proto > 0x0300");
DEBUG0("{}", "server: client requested proto > 0x0300");
send_msgs(Message::ProtoUnsup());
return false;
}
@@ -645,7 +629,7 @@ bool DispatcherBase::ServerHandshake(
}
// Set the proto version to the client requested version
DEBUG0("server: client protocol " << proto_rev);
DEBUG0("server: client protocol {}", proto_rev);
conn.set_proto_rev(proto_rev);
// Send initial set of assignments
@@ -664,7 +648,7 @@ bool DispatcherBase::ServerHandshake(
outgoing.emplace_back(Message::ServerHelloDone());
// Batch transmit
DEBUG0("server: sending initial assignments");
DEBUG0("{}", "server: sending initial assignments");
send_msgs(outgoing);
// In proto rev 3.0 and later, the handshake concludes with a client hello
@@ -678,7 +662,7 @@ bool DispatcherBase::ServerHandshake(
for (;;) {
if (!msg) {
// disconnected, retry
DEBUG0("server: disconnected waiting for initial entries");
DEBUG0("{}", "server: disconnected waiting for initial entries");
return false;
}
if (msg->Is(Message::kClientHelloDone)) {
@@ -691,9 +675,10 @@ bool DispatcherBase::ServerHandshake(
}
if (!msg->Is(Message::kEntryAssign)) {
// unexpected message
DEBUG0("server: received message ("
<< msg->type()
<< ") other than entry assignment during initial handshake");
DEBUG0(
"server: received message ({}) other than entry assignment during "
"initial handshake",
msg->type());
return false;
}
incoming.push_back(msg);
@@ -705,8 +690,8 @@ bool DispatcherBase::ServerHandshake(
}
}
INFO("server: client CONNECTED: " << conn.stream().getPeerIP() << " port "
<< conn.stream().getPeerPort());
INFO("server: client CONNECTED: {} port {}", conn.stream().getPeerIP(),
conn.stream().getPeerPort());
return true;
}

View File

@@ -9,12 +9,11 @@
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
#include <wpi/StringRef.h>
#include <wpi/Twine.h>
#include <wpi/condition_variable.h>
#include <wpi/mutex.h>
@@ -45,12 +44,12 @@ class DispatcherBase : public IDispatcher {
unsigned int GetNetworkMode() const;
void StartLocal();
void StartServer(const wpi::Twine& persist_filename,
void StartServer(std::string_view persist_filename,
std::unique_ptr<wpi::NetworkAcceptor> acceptor);
void StartClient();
void Stop();
void SetUpdateRate(double interval);
void SetIdentity(const wpi::Twine& name);
void SetIdentity(std::string_view name);
void Flush();
std::vector<ConnectionInfo> GetConnections() const;
bool IsConnected() const;
@@ -132,12 +131,12 @@ class Dispatcher : public DispatcherBase {
wpi::Logger& logger)
: DispatcherBase(storage, notifier, logger) {}
void StartServer(const wpi::Twine& persist_filename,
void StartServer(std::string_view persist_filename,
const char* listen_address, unsigned int port);
void SetServer(const char* server_name, unsigned int port);
void SetServer(
wpi::ArrayRef<std::pair<wpi::StringRef, unsigned int>> servers);
wpi::ArrayRef<std::pair<std::string_view, unsigned int>> servers);
void SetServerTeam(unsigned int team, unsigned int port);
void SetServerOverride(const char* server_name, unsigned int port);

View File

@@ -5,6 +5,7 @@
#include "DsClient.h"
#include <wpi/SmallString.h>
#include <wpi/StringExtras.h>
#include <wpi/TCPConnector.h>
#include <wpi/raw_ostream.h>
#include <wpi/raw_socket_istream.h>
@@ -80,7 +81,7 @@ void DsClient::Thread::Main() {
continue;
}
DEBUG3("connected to DS");
DEBUG3("{}", "connected to DS");
wpi::raw_socket_istream is(*m_stream);
while (m_active && !is.has_error()) {
@@ -122,24 +123,27 @@ void DsClient::Thread::Main() {
m_stream = nullptr;
break;
}
DEBUG3("json=" << json);
DEBUG3("json={}", json);
// Look for "robotIP":12345, and get 12345 portion
size_t pos = json.find("\"robotIP\"");
if (pos == wpi::StringRef::npos) {
if (pos == std::string_view::npos) {
continue; // could not find?
}
pos += 9;
pos = json.find(':', pos);
if (pos == wpi::StringRef::npos) {
if (pos == std::string_view::npos) {
continue; // could not find?
}
size_t endpos = json.find_first_not_of("0123456789", pos + 1);
DEBUG3("found robotIP=" << json.slice(pos + 1, endpos));
DEBUG3("found robotIP={}", wpi::slice(json, pos + 1, endpos));
// Parse into number
unsigned int ip = 0;
if (json.slice(pos + 1, endpos).getAsInteger(10, ip)) {
if (auto v = wpi::parse_integer<unsigned int>(
wpi::slice(json, pos + 1, endpos), 10)) {
ip = v.value();
} else {
continue; // error
}
@@ -157,12 +161,10 @@ void DsClient::Thread::Main() {
oldip = ip;
// Convert number into dotted quad
json.clear();
wpi::raw_svector_ostream os{json};
os << ((ip >> 24) & 0xff) << "." << ((ip >> 16) & 0xff) << "."
<< ((ip >> 8) & 0xff) << "." << (ip & 0xff);
INFO("client: DS overriding server IP to " << os.str());
m_dispatcher.SetServerOverride(json.c_str(), port);
auto newip = fmt::format("{}.{}.{}.{}", (ip >> 24) & 0xff,
(ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
INFO("client: DS overriding server IP to {}", newip);
m_dispatcher.SetServerOverride(newip.c_str(), port);
}
// We disconnected from the DS, clear the server override

View File

@@ -4,6 +4,8 @@
#include "EntryNotifier.h"
#include <wpi/StringExtras.h>
#include "Log.h"
using namespace nt;
@@ -49,8 +51,7 @@ bool impl::EntryNotifierThread::Matches(const EntryListenerData& listener,
if (listener.entry != 0 && data.entry != listener.entry) {
return false;
}
if (listener.entry == 0 &&
!wpi::StringRef(data.name).startswith(listener.prefix)) {
if (listener.entry == 0 && !wpi::starts_with(data.name, listener.prefix)) {
return false;
}
@@ -59,7 +60,7 @@ bool impl::EntryNotifierThread::Matches(const EntryListenerData& listener,
unsigned int EntryNotifier::Add(
std::function<void(const EntryNotification& event)> callback,
wpi::StringRef prefix, unsigned int flags) {
std::string_view prefix, unsigned int flags) {
if ((flags & NT_NOTIFY_LOCAL) != 0) {
m_local_notifiers = true;
}
@@ -76,7 +77,7 @@ unsigned int EntryNotifier::Add(
}
unsigned int EntryNotifier::AddPolled(unsigned int poller_uid,
wpi::StringRef prefix,
std::string_view prefix,
unsigned int flags) {
if ((flags & NT_NOTIFY_LOCAL) != 0) {
m_local_notifiers = true;
@@ -93,7 +94,7 @@ unsigned int EntryNotifier::AddPolled(unsigned int poller_uid,
return DoAdd(poller_uid, Handle(m_inst, local_id, Handle::kEntry), flags);
}
void EntryNotifier::NotifyEntry(unsigned int local_id, wpi::StringRef name,
void EntryNotifier::NotifyEntry(unsigned int local_id, std::string_view name,
std::shared_ptr<Value> value,
unsigned int flags,
unsigned int only_listener) {
@@ -102,8 +103,7 @@ void EntryNotifier::NotifyEntry(unsigned int local_id, wpi::StringRef name,
if ((flags & NT_NOTIFY_LOCAL) != 0 && !m_local_notifiers) {
return;
}
DEBUG0("notifying '" << name << "' (local=" << local_id
<< "), flags=" << flags);
DEBUG0("notifying '{}' (local={}), flags={}", name, local_id, flags);
Send(only_listener, 0, Handle(m_inst, local_id, Handle::kEntry).handle(),
name, value, flags);
}

View File

@@ -8,6 +8,7 @@
#include <atomic>
#include <memory>
#include <string>
#include <string_view>
#include <wpi/CallbackManager.h>
@@ -29,13 +30,13 @@ struct EntryListenerData
EntryListenerData() = default;
EntryListenerData(
std::function<void(const EntryNotification& event)> callback_,
wpi::StringRef prefix_, unsigned int flags_)
std::string_view prefix_, unsigned int flags_)
: CallbackListenerData(callback_), prefix(prefix_), flags(flags_) {}
EntryListenerData(
std::function<void(const EntryNotification& event)> callback_,
NT_Entry entry_, unsigned int flags_)
: CallbackListenerData(callback_), entry(entry_), flags(flags_) {}
EntryListenerData(unsigned int poller_uid_, wpi::StringRef prefix_,
EntryListenerData(unsigned int poller_uid_, std::string_view prefix_,
unsigned int flags_)
: CallbackListenerData(poller_uid_), prefix(prefix_), flags(flags_) {}
EntryListenerData(unsigned int poller_uid_, NT_Entry entry_,
@@ -85,15 +86,15 @@ class EntryNotifier
bool local_notifiers() const override;
unsigned int Add(std::function<void(const EntryNotification& event)> callback,
wpi::StringRef prefix, unsigned int flags) override;
std::string_view prefix, unsigned int flags) override;
unsigned int Add(std::function<void(const EntryNotification& event)> callback,
unsigned int local_id, unsigned int flags) override;
unsigned int AddPolled(unsigned int poller_uid, wpi::StringRef prefix,
unsigned int AddPolled(unsigned int poller_uid, std::string_view prefix,
unsigned int flags) override;
unsigned int AddPolled(unsigned int poller_uid, unsigned int local_id,
unsigned int flags) override;
void NotifyEntry(unsigned int local_id, wpi::StringRef name,
void NotifyEntry(unsigned int local_id, std::string_view name,
std::shared_ptr<Value> value, unsigned int flags,
unsigned int only_listener = UINT_MAX) override;

View File

@@ -7,6 +7,7 @@
#include <climits>
#include <memory>
#include <string_view>
#include "ntcore_cpp.h"
@@ -22,16 +23,17 @@ class IEntryNotifier {
virtual unsigned int Add(
std::function<void(const EntryNotification& event)> callback,
wpi::StringRef prefix, unsigned int flags) = 0;
std::string_view prefix, unsigned int flags) = 0;
virtual unsigned int Add(
std::function<void(const EntryNotification& event)> callback,
unsigned int local_id, unsigned int flags) = 0;
virtual unsigned int AddPolled(unsigned int poller_uid, wpi::StringRef prefix,
virtual unsigned int AddPolled(unsigned int poller_uid,
std::string_view prefix,
unsigned int flags) = 0;
virtual unsigned int AddPolled(unsigned int poller_uid, unsigned int local_id,
unsigned int flags) = 0;
virtual void NotifyEntry(unsigned int local_id, wpi::StringRef name,
virtual void NotifyEntry(unsigned int local_id, std::string_view name,
std::shared_ptr<Value> value, unsigned int flags,
unsigned int only_listener = UINT_MAX) = 0;
};

View File

@@ -6,6 +6,7 @@
#define NTCORE_IRPCSERVER_H_
#include <memory>
#include <string_view>
#include "Message.h"
#include "ntcore_cpp.h"
@@ -14,7 +15,7 @@ namespace nt {
class IRpcServer {
public:
typedef std::function<void(wpi::StringRef result)> SendResponseFunc;
using SendResponseFunc = std::function<void(std::string_view result)>;
IRpcServer() = default;
IRpcServer(const IRpcServer&) = delete;
@@ -24,7 +25,7 @@ class IRpcServer {
virtual void RemoveRpc(unsigned int rpc_uid) = 0;
virtual void ProcessRpc(unsigned int local_id, unsigned int call_uid,
wpi::StringRef name, wpi::StringRef params,
std::string_view name, std::string_view params,
const ConnectionInfo& conn,
SendResponseFunc send_response,
unsigned int rpc_uid) = 0;

View File

@@ -7,10 +7,10 @@
#include <functional>
#include <memory>
#include <string_view>
#include <vector>
#include <wpi/ArrayRef.h>
#include <wpi/Twine.h>
#include "Message.h"
#include "ntcore_cpp.h"
@@ -50,10 +50,10 @@ class IStorage {
// Filename-based save/load functions. Used both by periodic saves and
// accessible directly via the user API.
virtual const char* SavePersistent(const wpi::Twine& filename,
virtual const char* SavePersistent(std::string_view filename,
bool periodic) const = 0;
virtual const char* LoadPersistent(
const wpi::Twine& filename,
std::string_view filename,
std::function<void(size_t line, const char* msg)> warn) = 0;
};

View File

@@ -7,17 +7,17 @@
#include <wpi/Logger.h>
#define LOG(level, x) WPI_LOG(m_logger, level, x)
#define LOG(level, format, ...) WPI_LOG(m_logger, level, format, __VA_ARGS__)
#undef ERROR
#define ERROR(x) WPI_ERROR(m_logger, x)
#define WARNING(x) WPI_WARNING(m_logger, x)
#define INFO(x) WPI_INFO(m_logger, x)
#define ERROR(format, ...) WPI_ERROR(m_logger, format, __VA_ARGS__)
#define WARNING(format, ...) WPI_WARNING(m_logger, format, __VA_ARGS__)
#define INFO(format, ...) WPI_INFO(m_logger, format, __VA_ARGS__)
#define DEBUG0(x) WPI_DEBUG(m_logger, x)
#define DEBUG1(x) WPI_DEBUG1(m_logger, x)
#define DEBUG2(x) WPI_DEBUG2(m_logger, x)
#define DEBUG3(x) WPI_DEBUG3(m_logger, x)
#define DEBUG4(x) WPI_DEBUG4(m_logger, x)
#define DEBUG0(format, ...) WPI_DEBUG(m_logger, format, __VA_ARGS__)
#define DEBUG1(format, ...) WPI_DEBUG1(m_logger, format, __VA_ARGS__)
#define DEBUG2(format, ...) WPI_DEBUG2(m_logger, format, __VA_ARGS__)
#define DEBUG3(format, ...) WPI_DEBUG3(m_logger, format, __VA_ARGS__)
#define DEBUG4(format, ...) WPI_DEBUG4(m_logger, format, __VA_ARGS__)
#endif // NTCORE_LOG_H_

View File

@@ -4,35 +4,29 @@
#include "LoggerImpl.h"
#include <wpi/SmallString.h>
#include <wpi/StringRef.h>
#include <fmt/format.h>
#include <wpi/fs.h>
#include <wpi/raw_ostream.h>
using namespace nt;
static void DefaultLogger(unsigned int level, const char* file,
unsigned int line, const char* msg) {
wpi::SmallString<128> buf;
wpi::raw_svector_ostream oss(buf);
if (level == 20) {
oss << "NT: " << msg << '\n';
wpi::errs() << oss.str();
fmt::print(stderr, "NT: {}\n", msg);
return;
}
wpi::StringRef levelmsg;
std::string_view levelmsg;
if (level >= 50) {
levelmsg = "CRITICAL: ";
levelmsg = "CRITICAL";
} else if (level >= 40) {
levelmsg = "ERROR: ";
levelmsg = "ERROR";
} else if (level >= 30) {
levelmsg = "WARNING: ";
levelmsg = "WARNING";
} else {
return;
}
oss << "NT: " << levelmsg << msg << " (" << file << ':' << line << ")\n";
wpi::errs() << oss.str();
fmt::print(stderr, "NT: {}: {} ({}:{})\n", levelmsg, msg, file, line);
}
LoggerImpl::LoggerImpl(int inst) : m_inst(inst) {}

View File

@@ -106,7 +106,7 @@ std::shared_ptr<Message> Message::Read(WireDecoder& decoder,
} else {
type = get_entry_type(msg->m_id);
}
WPI_DEBUG4(decoder.logger(), "update message data type: " << type);
WPI_DEBUG4(decoder.logger(), "update message data type: {}", type);
msg->m_value = decoder.ReadValue(type);
if (!msg->m_value) {
return nullptr;
@@ -171,7 +171,7 @@ std::shared_ptr<Message> Message::Read(WireDecoder& decoder,
if (!decoder.Read(&params, size)) {
return nullptr;
}
msg->m_str = wpi::StringRef(params, size);
msg->m_str.assign(params, size);
break;
}
case kRpcResponse: {
@@ -193,32 +193,32 @@ std::shared_ptr<Message> Message::Read(WireDecoder& decoder,
if (!decoder.Read(&results, size)) {
return nullptr;
}
msg->m_str = wpi::StringRef(results, size);
msg->m_str.assign(results, size);
break;
}
default:
decoder.set_error("unrecognized message type");
WPI_INFO(decoder.logger(), "unrecognized message type: " << msg_type);
WPI_INFO(decoder.logger(), "unrecognized message type: {}", msg_type);
return nullptr;
}
return msg;
}
std::shared_ptr<Message> Message::ClientHello(wpi::StringRef self_id) {
std::shared_ptr<Message> Message::ClientHello(std::string_view self_id) {
auto msg = std::make_shared<Message>(kClientHello, private_init());
msg->m_str = self_id;
return msg;
}
std::shared_ptr<Message> Message::ServerHello(unsigned int flags,
wpi::StringRef self_id) {
std::string_view self_id) {
auto msg = std::make_shared<Message>(kServerHello, private_init());
msg->m_str = self_id;
msg->m_flags = flags;
return msg;
}
std::shared_ptr<Message> Message::EntryAssign(wpi::StringRef name,
std::shared_ptr<Message> Message::EntryAssign(std::string_view name,
unsigned int id,
unsigned int seq_num,
std::shared_ptr<Value> value,
@@ -257,7 +257,7 @@ std::shared_ptr<Message> Message::EntryDelete(unsigned int id) {
}
std::shared_ptr<Message> Message::ExecuteRpc(unsigned int id, unsigned int uid,
wpi::StringRef params) {
std::string_view params) {
auto msg = std::make_shared<Message>(kExecuteRpc, private_init());
msg->m_str = params;
msg->m_id = id;
@@ -266,7 +266,7 @@ std::shared_ptr<Message> Message::ExecuteRpc(unsigned int id, unsigned int uid,
}
std::shared_ptr<Message> Message::RpcResponse(unsigned int id, unsigned int uid,
wpi::StringRef result) {
std::string_view result) {
auto msg = std::make_shared<Message>(kRpcResponse, private_init());
msg->m_str = result;
msg->m_id = id;

View File

@@ -8,6 +8,7 @@
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include "networktables/NetworkTableValue.h"
@@ -46,7 +47,7 @@ class Message {
// Message data accessors. Callers are responsible for knowing what data is
// actually provided for a particular message.
wpi::StringRef str() const { return m_str; }
std::string_view str() const { return m_str; }
std::shared_ptr<Value> value() const { return m_value; }
unsigned int id() const { return m_id; }
unsigned int flags() const { return m_flags; }
@@ -75,10 +76,10 @@ class Message {
}
// Create messages with data
static std::shared_ptr<Message> ClientHello(wpi::StringRef self_id);
static std::shared_ptr<Message> ClientHello(std::string_view self_id);
static std::shared_ptr<Message> ServerHello(unsigned int flags,
wpi::StringRef self_id);
static std::shared_ptr<Message> EntryAssign(wpi::StringRef name,
std::string_view self_id);
static std::shared_ptr<Message> EntryAssign(std::string_view name,
unsigned int id,
unsigned int seq_num,
std::shared_ptr<Value> value,
@@ -90,9 +91,9 @@ class Message {
unsigned int flags);
static std::shared_ptr<Message> EntryDelete(unsigned int id);
static std::shared_ptr<Message> ExecuteRpc(unsigned int id, unsigned int uid,
wpi::StringRef params);
std::string_view params);
static std::shared_ptr<Message> RpcResponse(unsigned int id, unsigned int uid,
wpi::StringRef result);
std::string_view result);
Message(const Message&) = delete;
Message& operator=(const Message&) = delete;

View File

@@ -64,7 +64,7 @@ void NetworkConnection::Start() {
}
void NetworkConnection::Stop() {
DEBUG2("NetworkConnection stopping (" << this << ")");
DEBUG2("NetworkConnection stopping ({})", fmt::ptr(this));
set_state(kDead);
m_active = false;
// closing the stream so the read thread terminates
@@ -103,7 +103,7 @@ void NetworkConnection::Stop() {
}
ConnectionInfo NetworkConnection::info() const {
return ConnectionInfo{remote_id(), m_stream->getPeerIP(),
return ConnectionInfo{remote_id(), std::string{m_stream->getPeerIP()},
static_cast<unsigned int>(m_stream->getPeerPort()),
m_last_update, m_proto_rev};
}
@@ -142,7 +142,7 @@ std::string NetworkConnection::remote_id() const {
return m_remote_id;
}
void NetworkConnection::set_remote_id(wpi::StringRef remote_id) {
void NetworkConnection::set_remote_id(std::string_view remote_id) {
std::scoped_lock lock(m_remote_id_mutex);
m_remote_id = remote_id;
}
@@ -158,7 +158,7 @@ void NetworkConnection::ReadThreadMain() {
decoder.set_proto_rev(m_proto_rev);
auto msg = Message::Read(decoder, m_get_entry_type);
if (!msg && decoder.error()) {
DEBUG0("error reading in handshake: " << decoder.error());
DEBUG0("error reading in handshake: {}", decoder.error());
}
return msg;
},
@@ -180,7 +180,7 @@ void NetworkConnection::ReadThreadMain() {
auto msg = Message::Read(decoder, m_get_entry_type);
if (!msg) {
if (decoder.error()) {
INFO("read error: " << decoder.error());
INFO("read error: {}", decoder.error());
}
// terminate connection on bad message
if (m_stream) {
@@ -188,13 +188,12 @@ void NetworkConnection::ReadThreadMain() {
}
break;
}
DEBUG3("received type=" << msg->type() << " with str=" << msg->str()
<< " id=" << msg->id()
<< " seq_num=" << msg->seq_num_uid());
DEBUG3("received type={} with str={} id={} seq_num={}", msg->type(),
msg->str(), msg->id(), msg->seq_num_uid());
m_last_update = Now();
m_process_incoming(std::move(msg), this);
}
DEBUG2("read thread died (" << this << ")");
DEBUG2("read thread died ({})", fmt::ptr(this));
set_state(kDead);
m_active = false;
m_outgoing.push(Outgoing()); // also kill write thread
@@ -213,18 +212,17 @@ void NetworkConnection::WriteThreadMain() {
while (m_active) {
auto msgs = m_outgoing.pop();
DEBUG4("write thread woke up");
DEBUG4("{}", "write thread woke up");
if (msgs.empty()) {
continue;
}
encoder.set_proto_rev(m_proto_rev);
encoder.Reset();
DEBUG3("sending " << msgs.size() << " messages");
DEBUG3("sending {} messages", msgs.size());
for (auto& msg : msgs) {
if (msg) {
DEBUG3("sending type=" << msg->type() << " with str=" << msg->str()
<< " id=" << msg->id()
<< " seq_num=" << msg->seq_num_uid());
DEBUG3("sending type={} with str={} id={} seq_num={}", msg->type(),
msg->str(), msg->id(), msg->seq_num_uid());
msg->Write(encoder);
}
}
@@ -238,9 +236,9 @@ void NetworkConnection::WriteThreadMain() {
if (m_stream->send(encoder.data(), encoder.size(), &err) == 0) {
break;
}
DEBUG4("sent " << encoder.size() << " bytes");
DEBUG4("sent {} bytes", encoder.size());
}
DEBUG2("write thread died (" << this << ")");
DEBUG2("write thread died ({})", fmt::ptr(this));
set_state(kDead);
m_active = false;
if (m_stream) {

View File

@@ -11,6 +11,7 @@
#include <chrono>
#include <memory>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
@@ -76,7 +77,7 @@ class NetworkConnection : public INetworkConnection {
void set_state(State state) final;
std::string remote_id() const;
void set_remote_id(wpi::StringRef remote_id);
void set_remote_id(std::string_view remote_id);
uint64_t last_update() const { return m_last_update; }

View File

@@ -27,7 +27,7 @@ void RpcServer::RemoveRpc(unsigned int rpc_uid) {
}
void RpcServer::ProcessRpc(unsigned int local_id, unsigned int call_uid,
wpi::StringRef name, wpi::StringRef params,
std::string_view name, std::string_view params,
const ConnectionInfo& conn,
SendResponseFunc send_response,
unsigned int rpc_uid) {
@@ -37,11 +37,12 @@ void RpcServer::ProcessRpc(unsigned int local_id, unsigned int call_uid,
}
bool RpcServer::PostRpcResponse(unsigned int local_id, unsigned int call_uid,
wpi::StringRef result) {
std::string_view result) {
auto thr = GetThread();
auto i = thr->m_response_map.find(impl::RpcIdPair{local_id, call_uid});
if (i == thr->m_response_map.end()) {
WARNING("posting RPC response to nonexistent call (or duplicate response)");
WARNING("{}",
"posting RPC response to nonexistent call (or duplicate response)");
return false;
}
(i->getSecond())(result);

View File

@@ -22,8 +22,8 @@ namespace impl {
typedef std::pair<unsigned int, unsigned int> RpcIdPair;
struct RpcNotifierData : public RpcAnswer {
RpcNotifierData(NT_Entry entry_, NT_RpcCall call_, wpi::StringRef name_,
wpi::StringRef params_, const ConnectionInfo& conn_,
RpcNotifierData(NT_Entry entry_, NT_RpcCall call_, std::string_view name_,
std::string_view params_, const ConnectionInfo& conn_,
IRpcServer::SendResponseFunc send_response_)
: RpcAnswer{entry_, call_, name_, params_, conn_},
send_response{std::move(send_response_)} {}
@@ -55,7 +55,7 @@ class RpcServerThread
void DoCallback(std::function<void(const RpcAnswer& call)> callback,
const RpcNotifierData& data) {
DEBUG4("rpc calling " << data.name);
DEBUG4("rpc calling {}", data.name);
unsigned int local_id = Handle{data.entry}.GetIndex();
unsigned int call_uid = Handle{data.call}.GetIndex();
RpcIdPair lookup_uid{local_id, call_uid};
@@ -94,12 +94,12 @@ class RpcServer
void RemoveRpc(unsigned int rpc_uid) override;
void ProcessRpc(unsigned int local_id, unsigned int call_uid,
wpi::StringRef name, wpi::StringRef params,
std::string_view name, std::string_view params,
const ConnectionInfo& conn, SendResponseFunc send_response,
unsigned int rpc_uid) override;
bool PostRpcResponse(unsigned int local_id, unsigned int call_uid,
wpi::StringRef result);
std::string_view result);
private:
int m_inst;

View File

@@ -4,6 +4,7 @@
#include "Storage.h"
#include <wpi/StringExtras.h>
#include <wpi/timestamp.h>
#include "Handle.h"
@@ -91,7 +92,7 @@ void Storage::ProcessIncomingEntryAssign(std::shared_ptr<Message> msg,
INetworkConnection* conn) {
std::unique_lock lock(m_mutex);
unsigned int id = msg->id();
wpi::StringRef name = msg->str();
std::string_view name = msg->str();
Entry* entry;
bool may_need_update = false;
SequenceNumber seq_num(msg->seq_num_uid());
@@ -115,7 +116,7 @@ void Storage::ProcessIncomingEntryAssign(std::shared_ptr<Message> msg,
// ignore arbitrary entry assignments
// this can happen due to e.g. assignment to deleted entry
lock.unlock();
DEBUG0("server: received assignment to unknown entry");
DEBUG0("{}", "server: received assignment to unknown entry");
return;
}
entry = m_idmap[id];
@@ -123,7 +124,7 @@ void Storage::ProcessIncomingEntryAssign(std::shared_ptr<Message> msg,
// clients simply accept new assignments
if (id == 0xffff) {
lock.unlock();
DEBUG0("client: received entry assignment request?");
DEBUG0("{}", "client: received entry assignment request?");
return;
}
if (id >= m_idmap.size()) {
@@ -178,7 +179,7 @@ void Storage::ProcessIncomingEntryAssign(std::shared_ptr<Message> msg,
// sanity check: name should match id
if (msg->str() != entry->name) {
lock.unlock();
DEBUG0("entry assignment for same id with different name?");
DEBUG0("{}", "entry assignment for same id with different name?");
return;
}
@@ -228,7 +229,7 @@ void Storage::ProcessIncomingEntryUpdate(std::shared_ptr<Message> msg,
// ignore arbitrary entry updates;
// this can happen due to deleted entries
lock.unlock();
DEBUG0("received update to unknown entry");
DEBUG0("{}", "received update to unknown entry");
return;
}
Entry* entry = m_idmap[id];
@@ -269,7 +270,7 @@ void Storage::ProcessIncomingFlagsUpdate(std::shared_ptr<Message> msg,
// ignore arbitrary entry updates;
// this can happen due to deleted entries
lock.unlock();
DEBUG0("received flags update to unknown entry");
DEBUG0("{}", "received flags update to unknown entry");
return;
}
@@ -293,7 +294,7 @@ void Storage::ProcessIncomingEntryDelete(std::shared_ptr<Message> msg,
// ignore arbitrary entry updates;
// this can happen due to deleted entries
lock.unlock();
DEBUG0("received delete to unknown entry");
DEBUG0("{}", "received delete to unknown entry");
return;
}
@@ -336,13 +337,13 @@ void Storage::ProcessIncomingExecuteRpc(
// ignore call to non-existent RPC
// this can happen due to deleted entries
lock.unlock();
DEBUG0("received RPC call to unknown entry");
DEBUG0("{}", "received RPC call to unknown entry");
return;
}
Entry* entry = m_idmap[id];
if (!entry->value || !entry->value->IsRpc()) {
lock.unlock();
DEBUG0("received RPC call to non-RPC entry");
DEBUG0("{}", "received RPC call to non-RPC entry");
return;
}
ConnectionInfo conn_info;
@@ -359,7 +360,7 @@ void Storage::ProcessIncomingExecuteRpc(
unsigned int call_uid = msg->seq_num_uid();
m_rpc_server.ProcessRpc(
entry->local_id, call_uid, entry->name, msg->str(), conn_info,
[=](wpi::StringRef result) {
[=](std::string_view result) {
auto c = conn_weak.lock();
if (c) {
c->QueueOutgoing(Message::RpcResponse(id, call_uid, result));
@@ -379,17 +380,17 @@ void Storage::ProcessIncomingRpcResponse(std::shared_ptr<Message> msg,
// ignore response to non-existent RPC
// this can happen due to deleted entries
lock.unlock();
DEBUG0("received rpc response to unknown entry");
DEBUG0("{}", "received rpc response to unknown entry");
return;
}
Entry* entry = m_idmap[id];
if (!entry->value || !entry->value->IsRpc()) {
lock.unlock();
DEBUG0("received RPC response to non-RPC entry");
DEBUG0("{}", "received RPC response to non-RPC entry");
return;
}
m_rpc_results.insert(std::make_pair(
RpcIdPair{entry->local_id, msg->seq_num_uid()}, msg->str()));
m_rpc_results.insert({RpcIdPair{entry->local_id, msg->seq_num_uid()},
std::string{msg->str()}});
m_rpc_results_cond.notify_all();
}
@@ -431,18 +432,18 @@ void Storage::ApplyInitialAssignments(
// apply assignments
for (auto& msg : msgs) {
if (!msg->Is(Message::kEntryAssign)) {
DEBUG0("client: received non-entry assignment request?");
DEBUG0("{}", "client: received non-entry assignment request?");
continue;
}
unsigned int id = msg->id();
if (id == 0xffff) {
DEBUG0("client: received entry assignment request?");
DEBUG0("{}", "client: received entry assignment request?");
continue;
}
SequenceNumber seq_num(msg->seq_num_uid());
wpi::StringRef name = msg->str();
std::string_view name = msg->str();
Entry* entry = GetOrNew(name);
entry->seq_num = seq_num;
@@ -509,7 +510,7 @@ void Storage::ApplyInitialAssignments(
}
}
std::shared_ptr<Value> Storage::GetEntryValue(wpi::StringRef name) const {
std::shared_ptr<Value> Storage::GetEntryValue(std::string_view name) const {
std::scoped_lock lock(m_mutex);
auto i = m_entries.find(name);
if (i == m_entries.end()) {
@@ -526,7 +527,7 @@ std::shared_ptr<Value> Storage::GetEntryValue(unsigned int local_id) const {
return m_localmap[local_id]->value;
}
bool Storage::SetDefaultEntryValue(wpi::StringRef name,
bool Storage::SetDefaultEntryValue(std::string_view name,
std::shared_ptr<Value> value) {
if (name.empty()) {
return false;
@@ -566,7 +567,8 @@ bool Storage::SetDefaultEntryValue(unsigned int local_id,
return true;
}
bool Storage::SetEntryValue(wpi::StringRef name, std::shared_ptr<Value> value) {
bool Storage::SetEntryValue(std::string_view name,
std::shared_ptr<Value> value) {
if (name.empty()) {
return true;
}
@@ -664,7 +666,7 @@ void Storage::SetEntryValueImpl(Entry* entry, std::shared_ptr<Value> value,
}
}
void Storage::SetEntryTypeValue(wpi::StringRef name,
void Storage::SetEntryTypeValue(std::string_view name,
std::shared_ptr<Value> value) {
if (name.empty()) {
return;
@@ -695,7 +697,7 @@ void Storage::SetEntryTypeValue(unsigned int local_id,
SetEntryValueImpl(entry, value, lock, true);
}
void Storage::SetEntryFlags(wpi::StringRef name, unsigned int flags) {
void Storage::SetEntryFlags(std::string_view name, unsigned int flags) {
if (name.empty()) {
return;
}
@@ -747,7 +749,7 @@ void Storage::SetEntryFlagsImpl(Entry* entry, unsigned int flags,
}
}
unsigned int Storage::GetEntryFlags(wpi::StringRef name) const {
unsigned int Storage::GetEntryFlags(std::string_view name) const {
std::scoped_lock lock(m_mutex);
auto i = m_entries.find(name);
if (i == m_entries.end()) {
@@ -764,7 +766,7 @@ unsigned int Storage::GetEntryFlags(unsigned int local_id) const {
return m_localmap[local_id]->flags;
}
void Storage::DeleteEntry(wpi::StringRef name) {
void Storage::DeleteEntry(std::string_view name) {
std::unique_lock lock(m_mutex);
auto i = m_entries.find(name);
if (i == m_entries.end()) {
@@ -873,37 +875,32 @@ void Storage::DeleteAllEntries() {
dispatcher->QueueOutgoing(Message::ClearEntries(), nullptr, nullptr);
}
Storage::Entry* Storage::GetOrNew(const wpi::Twine& name) {
wpi::SmallString<128> nameBuf;
wpi::StringRef nameStr = name.toStringRef(nameBuf);
auto& entry = m_entries[nameStr];
Storage::Entry* Storage::GetOrNew(std::string_view name) {
auto& entry = m_entries[name];
if (!entry) {
m_localmap.emplace_back(new Entry(nameStr));
m_localmap.emplace_back(new Entry(name));
entry = m_localmap.back().get();
entry->local_id = m_localmap.size() - 1;
}
return entry;
}
unsigned int Storage::GetEntry(const wpi::Twine& name) {
if (name.isTriviallyEmpty() ||
(name.isSingleStringRef() && name.getSingleStringRef().empty())) {
unsigned int Storage::GetEntry(std::string_view name) {
if (name.empty()) {
return UINT_MAX;
}
std::unique_lock lock(m_mutex);
return GetOrNew(name)->local_id;
}
std::vector<unsigned int> Storage::GetEntries(const wpi::Twine& prefix,
std::vector<unsigned int> Storage::GetEntries(std::string_view prefix,
unsigned int types) {
wpi::SmallString<128> prefixBuf;
wpi::StringRef prefixStr = prefix.toStringRef(prefixBuf);
std::scoped_lock lock(m_mutex);
std::vector<unsigned int> ids;
for (auto& i : m_entries) {
Entry* entry = i.getValue();
auto value = entry->value.get();
if (!value || !i.getKey().startswith(prefixStr)) {
if (!value || !wpi::starts_with(i.getKey(), prefix)) {
continue;
}
if (types != 0 && (types & value->type()) == 0) {
@@ -970,16 +967,14 @@ uint64_t Storage::GetEntryLastChange(unsigned int local_id) const {
return entry->value->last_change();
}
std::vector<EntryInfo> Storage::GetEntryInfo(int inst, const wpi::Twine& prefix,
std::vector<EntryInfo> Storage::GetEntryInfo(int inst, std::string_view prefix,
unsigned int types) {
wpi::SmallString<128> prefixBuf;
wpi::StringRef prefixStr = prefix.toStringRef(prefixBuf);
std::scoped_lock lock(m_mutex);
std::vector<EntryInfo> infos;
for (auto& i : m_entries) {
Entry* entry = i.getValue();
auto value = entry->value.get();
if (!value || !i.getKey().startswith(prefixStr)) {
if (!value || !wpi::starts_with(i.getKey(), prefix)) {
continue;
}
if (types != 0 && (types & value->type()) == 0) {
@@ -997,18 +992,16 @@ std::vector<EntryInfo> Storage::GetEntryInfo(int inst, const wpi::Twine& prefix,
}
unsigned int Storage::AddListener(
const wpi::Twine& prefix,
std::string_view prefix,
std::function<void(const EntryNotification& event)> callback,
unsigned int flags) const {
wpi::SmallString<128> prefixBuf;
wpi::StringRef prefixStr = prefix.toStringRef(prefixBuf);
std::scoped_lock lock(m_mutex);
unsigned int uid = m_notifier.Add(callback, prefixStr, flags);
unsigned int uid = m_notifier.Add(callback, prefix, flags);
// perform immediate notifications
if ((flags & NT_NOTIFY_IMMEDIATE) != 0 && (flags & NT_NOTIFY_NEW) != 0) {
for (auto& i : m_entries) {
Entry* entry = i.getValue();
if (!entry->value || !i.getKey().startswith(prefixStr)) {
if (!entry->value || !wpi::starts_with(i.getKey(), prefix)) {
continue;
}
m_notifier.NotifyEntry(entry->local_id, i.getKey(), entry->value,
@@ -1037,16 +1030,14 @@ unsigned int Storage::AddListener(
}
unsigned int Storage::AddPolledListener(unsigned int poller,
const wpi::Twine& prefix,
std::string_view prefix,
unsigned int flags) const {
wpi::SmallString<128> prefixBuf;
wpi::StringRef prefixStr = prefix.toStringRef(prefixBuf);
std::scoped_lock lock(m_mutex);
unsigned int uid = m_notifier.AddPolled(poller, prefixStr, flags);
unsigned int uid = m_notifier.AddPolled(poller, prefix, flags);
// perform immediate notifications
if ((flags & NT_NOTIFY_IMMEDIATE) != 0 && (flags & NT_NOTIFY_NEW) != 0) {
for (auto& i : m_entries) {
if (!i.getKey().startswith(prefixStr)) {
if (!wpi::starts_with(i.getKey(), prefix)) {
continue;
}
Entry* entry = i.getValue();
@@ -1111,11 +1102,9 @@ bool Storage::GetPersistentEntries(
}
bool Storage::GetEntries(
const wpi::Twine& prefix,
std::string_view prefix,
std::vector<std::pair<std::string, std::shared_ptr<Value>>>* entries)
const {
wpi::SmallString<128> prefixBuf;
wpi::StringRef prefixStr = prefix.toStringRef(prefixBuf);
// copy values out of storage as quickly as possible so lock isn't held
{
std::scoped_lock lock(m_mutex);
@@ -1123,7 +1112,7 @@ bool Storage::GetEntries(
for (auto& i : m_entries) {
Entry* entry = i.getValue();
// only write values with given prefix
if (!entry->value || !i.getKey().startswith(prefixStr)) {
if (!entry->value || !wpi::starts_with(i.getKey(), prefix)) {
continue;
}
entries->emplace_back(i.getKey(), entry->value);
@@ -1139,7 +1128,7 @@ bool Storage::GetEntries(
return true;
}
void Storage::CreateRpc(unsigned int local_id, wpi::StringRef def,
void Storage::CreateRpc(unsigned int local_id, std::string_view def,
unsigned int rpc_uid) {
std::unique_lock lock(m_mutex);
if (local_id >= m_localmap.size()) {
@@ -1184,7 +1173,7 @@ void Storage::CreateRpc(unsigned int local_id, wpi::StringRef def,
}
}
unsigned int Storage::CallRpc(unsigned int local_id, wpi::StringRef params) {
unsigned int Storage::CallRpc(unsigned int local_id, std::string_view params) {
std::unique_lock lock(m_mutex);
if (local_id >= m_localmap.size()) {
return 0;
@@ -1202,7 +1191,7 @@ unsigned int Storage::CallRpc(unsigned int local_id, wpi::StringRef params) {
unsigned int call_uid = entry->rpc_call_uid;
auto msg = Message::ExecuteRpc(entry->id, call_uid, params);
wpi::StringRef name{entry->name};
std::string_view name{entry->name};
if (m_server) {
// RPCs are unlikely to be used locally on the server, but handle it
@@ -1218,10 +1207,10 @@ unsigned int Storage::CallRpc(unsigned int local_id, wpi::StringRef params) {
unsigned int call_uid = msg->seq_num_uid();
m_rpc_server.ProcessRpc(
local_id, call_uid, name, msg->str(), conn_info,
[=](wpi::StringRef result) {
[=](std::string_view result) {
std::scoped_lock lock(m_mutex);
m_rpc_results.insert(
std::make_pair(RpcIdPair{local_id, call_uid}, result));
m_rpc_results.insert(std::make_pair(RpcIdPair{local_id, call_uid},
std::string{result}));
m_rpc_results_cond.notify_all();
},
rpc_uid);

View File

@@ -12,6 +12,7 @@
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -72,35 +73,36 @@ class Storage : public IStorage {
// User functions. These are the actual implementations of the corresponding
// user API functions in ntcore_cpp.
std::shared_ptr<Value> GetEntryValue(wpi::StringRef name) const;
std::shared_ptr<Value> GetEntryValue(std::string_view name) const;
std::shared_ptr<Value> GetEntryValue(unsigned int local_id) const;
bool SetDefaultEntryValue(wpi::StringRef name, std::shared_ptr<Value> value);
bool SetDefaultEntryValue(std::string_view name,
std::shared_ptr<Value> value);
bool SetDefaultEntryValue(unsigned int local_id,
std::shared_ptr<Value> value);
bool SetEntryValue(wpi::StringRef name, std::shared_ptr<Value> value);
bool SetEntryValue(std::string_view name, std::shared_ptr<Value> value);
bool SetEntryValue(unsigned int local_id, std::shared_ptr<Value> value);
void SetEntryTypeValue(wpi::StringRef name, std::shared_ptr<Value> value);
void SetEntryTypeValue(std::string_view name, std::shared_ptr<Value> value);
void SetEntryTypeValue(unsigned int local_id, std::shared_ptr<Value> value);
void SetEntryFlags(wpi::StringRef name, unsigned int flags);
void SetEntryFlags(std::string_view name, unsigned int flags);
void SetEntryFlags(unsigned int local_id, unsigned int flags);
unsigned int GetEntryFlags(wpi::StringRef name) const;
unsigned int GetEntryFlags(std::string_view name) const;
unsigned int GetEntryFlags(unsigned int local_id) const;
void DeleteEntry(wpi::StringRef name);
void DeleteEntry(std::string_view name);
void DeleteEntry(unsigned int local_id);
void DeleteAllEntries();
std::vector<EntryInfo> GetEntryInfo(int inst, const wpi::Twine& prefix,
std::vector<EntryInfo> GetEntryInfo(int inst, std::string_view prefix,
unsigned int types);
unsigned int AddListener(
const wpi::Twine& prefix,
std::string_view prefix,
std::function<void(const EntryNotification& event)> callback,
unsigned int flags) const;
unsigned int AddListener(
@@ -109,14 +111,14 @@ class Storage : public IStorage {
unsigned int flags) const;
unsigned int AddPolledListener(unsigned int poller_uid,
const wpi::Twine& prefix,
std::string_view prefix,
unsigned int flags) const;
unsigned int AddPolledListener(unsigned int poller_uid, unsigned int local_id,
unsigned int flags) const;
// Index-only
unsigned int GetEntry(const wpi::Twine& name);
std::vector<unsigned int> GetEntries(const wpi::Twine& prefix,
unsigned int GetEntry(std::string_view name);
std::vector<unsigned int> GetEntries(std::string_view prefix,
unsigned int types);
EntryInfo GetEntryInfo(int inst, unsigned int local_id) const;
std::string GetEntryName(unsigned int local_id) const;
@@ -125,32 +127,32 @@ class Storage : public IStorage {
// Filename-based save/load functions. Used both by periodic saves and
// accessible directly via the user API.
const char* SavePersistent(const wpi::Twine& filename,
const char* SavePersistent(std::string_view filename,
bool periodic) const override;
const char* LoadPersistent(
const wpi::Twine& filename,
std::string_view filename,
std::function<void(size_t line, const char* msg)> warn) override;
const char* SaveEntries(const wpi::Twine& filename,
const wpi::Twine& prefix) const;
const char* SaveEntries(std::string_view filename,
std::string_view prefix) const;
const char* LoadEntries(
const wpi::Twine& filename, const wpi::Twine& prefix,
std::string_view filename, std::string_view prefix,
std::function<void(size_t line, const char* msg)> warn);
// Stream-based save/load functions (exposed for testing purposes). These
// implement the guts of the filename-based functions.
void SavePersistent(wpi::raw_ostream& os, bool periodic) const;
bool LoadEntries(wpi::raw_istream& is, const wpi::Twine& prefix,
bool LoadEntries(wpi::raw_istream& is, std::string_view prefix,
bool persistent,
std::function<void(size_t line, const char* msg)> warn);
void SaveEntries(wpi::raw_ostream& os, const wpi::Twine& prefix) const;
void SaveEntries(wpi::raw_ostream& os, std::string_view prefix) const;
// RPC configuration needs to come through here as RPC definitions are
// actually special Storage value types.
void CreateRpc(unsigned int local_id, wpi::StringRef def,
void CreateRpc(unsigned int local_id, std::string_view def,
unsigned int rpc_uid);
unsigned int CallRpc(unsigned int local_id, wpi::StringRef params);
unsigned int CallRpc(unsigned int local_id, std::string_view params);
bool GetRpcResult(unsigned int local_id, unsigned int call_uid,
std::string* result);
bool GetRpcResult(unsigned int local_id, unsigned int call_uid,
@@ -160,7 +162,7 @@ class Storage : public IStorage {
private:
// Data for each table entry.
struct Entry {
explicit Entry(wpi::StringRef name_) : name(name_) {}
explicit Entry(std::string_view name_) : name(name_) {}
bool IsPersistent() const { return (flags & NT_PERSISTENT) != 0; }
// We redundantly store the name so that it's available when accessing the
@@ -242,7 +244,7 @@ class Storage : public IStorage {
bool periodic,
std::vector<std::pair<std::string, std::shared_ptr<Value>>>* entries)
const;
bool GetEntries(const wpi::Twine& prefix,
bool GetEntries(std::string_view prefix,
std::vector<std::pair<std::string, std::shared_ptr<Value>>>*
entries) const;
void SetEntryValueImpl(Entry* entry, std::shared_ptr<Value> value,
@@ -256,7 +258,7 @@ class Storage : public IStorage {
template <typename F>
void DeleteAllEntriesImpl(bool local, F should_delete);
void DeleteAllEntriesImpl(bool local);
Entry* GetOrNew(const wpi::Twine& name);
Entry* GetOrNew(std::string_view name);
};
} // namespace nt

View File

@@ -27,13 +27,13 @@ class LoadPersistentImpl {
LoadPersistentImpl(wpi::raw_istream& is, WarnFunc warn)
: m_is(is), m_warn(std::move(warn)) {}
bool Load(wpi::StringRef prefix, std::vector<Entry>* entries);
bool Load(std::string_view prefix, std::vector<Entry>* entries);
private:
bool ReadLine();
bool ReadHeader();
NT_Type ReadType();
wpi::StringRef ReadName(wpi::SmallVectorImpl<char>& buf);
std::string_view ReadName(wpi::SmallVectorImpl<char>& buf);
std::shared_ptr<Value> ReadValue(NT_Type type);
std::shared_ptr<Value> ReadBooleanValue();
std::shared_ptr<Value> ReadDoubleValue();
@@ -52,7 +52,7 @@ class LoadPersistentImpl {
wpi::raw_istream& m_is;
WarnFunc m_warn;
wpi::StringRef m_line;
std::string_view m_line;
wpi::SmallString<128> m_line_buf;
size_t m_line_num = 0;
@@ -71,11 +71,11 @@ class LoadPersistentImpl {
* Returns a pair containing the extracted token (if any) and the remaining
* tail string.
*/
static std::pair<wpi::StringRef, wpi::StringRef> ReadStringToken(
wpi::StringRef source) {
static std::pair<std::string_view, std::string_view> ReadStringToken(
std::string_view source) {
// Match opening quote
if (source.empty() || source.front() != '"') {
return std::make_pair(wpi::StringRef(), source);
return {{}, source};
}
// Scan for ending double quote, checking for escaped as we go.
@@ -87,7 +87,7 @@ static std::pair<wpi::StringRef, wpi::StringRef> ReadStringToken(
break;
}
}
return std::make_pair(source.slice(0, pos), source.substr(pos));
return {wpi::slice(source, 0, pos), source.substr(pos)};
}
static int fromxdigit(char ch) {
@@ -100,8 +100,8 @@ static int fromxdigit(char ch) {
}
}
static wpi::StringRef UnescapeString(wpi::StringRef source,
wpi::SmallVectorImpl<char>& buf) {
static std::string_view UnescapeString(std::string_view source,
wpi::SmallVectorImpl<char>& buf) {
assert(source.size() >= 2 && source.front() == '"' && source.back() == '"');
buf.clear();
buf.reserve(source.size() - 2);
@@ -135,10 +135,10 @@ static wpi::StringRef UnescapeString(wpi::StringRef source,
break;
}
}
return wpi::StringRef{buf.data(), buf.size()};
return {buf.data(), buf.size()};
}
bool LoadPersistentImpl::Load(wpi::StringRef prefix,
bool LoadPersistentImpl::Load(std::string_view prefix,
std::vector<Entry>* entries) {
if (!ReadHeader()) {
return false; // header
@@ -154,18 +154,19 @@ bool LoadPersistentImpl::Load(wpi::StringRef prefix,
// name
wpi::SmallString<128> buf;
wpi::StringRef name = ReadName(buf);
if (name.empty() || !name.startswith(prefix)) {
std::string_view name = ReadName(buf);
if (name.empty() || !wpi::starts_with(name, prefix)) {
continue;
}
// =
m_line = m_line.ltrim(" \t");
m_line = wpi::ltrim(m_line, " \t");
if (m_line.empty() || m_line.front() != '=') {
Warn("expected = after name");
continue;
}
m_line = m_line.drop_front().ltrim(" \t");
m_line.remove_prefix(1);
m_line = wpi::ltrim(m_line, " \t");
// value
auto value = ReadValue(type);
@@ -182,7 +183,7 @@ bool LoadPersistentImpl::ReadLine() {
// ignore blank lines and lines that start with ; or # (comments)
while (!m_is.has_error()) {
++m_line_num;
m_line = m_is.getline(m_line_buf, INT_MAX).trim();
m_line = wpi::trim(m_is.getline(m_line_buf, INT_MAX));
if (!m_line.empty() && m_line.front() != ';' && m_line.front() != '#') {
return true;
}
@@ -200,8 +201,8 @@ bool LoadPersistentImpl::ReadHeader() {
}
NT_Type LoadPersistentImpl::ReadType() {
wpi::StringRef tok;
std::tie(tok, m_line) = m_line.split(' ');
std::string_view tok;
std::tie(tok, m_line) = wpi::split(m_line, ' ');
if (tok == "boolean") {
return NT_BOOLEAN;
} else if (tok == "double") {
@@ -211,8 +212,8 @@ NT_Type LoadPersistentImpl::ReadType() {
} else if (tok == "raw") {
return NT_RAW;
} else if (tok == "array") {
wpi::StringRef array_tok;
std::tie(array_tok, m_line) = m_line.split(' ');
std::string_view array_tok;
std::tie(array_tok, m_line) = wpi::split(m_line, ' ');
if (array_tok == "boolean") {
return NT_BOOLEAN_ARRAY;
} else if (array_tok == "double") {
@@ -224,16 +225,16 @@ NT_Type LoadPersistentImpl::ReadType() {
return NT_UNASSIGNED;
}
wpi::StringRef LoadPersistentImpl::ReadName(wpi::SmallVectorImpl<char>& buf) {
wpi::StringRef tok;
std::string_view LoadPersistentImpl::ReadName(wpi::SmallVectorImpl<char>& buf) {
std::string_view tok;
std::tie(tok, m_line) = ReadStringToken(m_line);
if (tok.empty()) {
Warn("missing name");
return wpi::StringRef{};
return {};
}
if (tok.back() != '"') {
Warn("unterminated name string");
return wpi::StringRef{};
return {};
}
return UnescapeString(tok, buf);
}
@@ -273,7 +274,7 @@ std::shared_ptr<Value> LoadPersistentImpl::ReadBooleanValue() {
std::shared_ptr<Value> LoadPersistentImpl::ReadDoubleValue() {
// need to convert to null-terminated string for std::strtod()
wpi::SmallString<64> buf = m_line;
wpi::SmallString<64> buf{m_line};
char* end;
double v = std::strtod(buf.c_str(), &end);
if (*end != '\0') {
@@ -284,7 +285,7 @@ std::shared_ptr<Value> LoadPersistentImpl::ReadDoubleValue() {
}
std::shared_ptr<Value> LoadPersistentImpl::ReadStringValue() {
wpi::StringRef tok;
std::string_view tok;
std::tie(tok, m_line) = ReadStringToken(m_line);
if (tok.empty()) {
Warn("missing string value");
@@ -307,9 +308,9 @@ std::shared_ptr<Value> LoadPersistentImpl::ReadRawValue() {
std::shared_ptr<Value> LoadPersistentImpl::ReadBooleanArrayValue() {
m_buf_boolean_array.clear();
while (!m_line.empty()) {
wpi::StringRef tok;
std::tie(tok, m_line) = m_line.split(',');
tok = tok.trim(" \t");
std::string_view tok;
std::tie(tok, m_line) = wpi::split(m_line, ',');
tok = wpi::trim(tok, " \t");
if (tok == "true") {
m_buf_boolean_array.push_back(1);
} else if (tok == "false") {
@@ -325,11 +326,11 @@ std::shared_ptr<Value> LoadPersistentImpl::ReadBooleanArrayValue() {
std::shared_ptr<Value> LoadPersistentImpl::ReadDoubleArrayValue() {
m_buf_double_array.clear();
while (!m_line.empty()) {
wpi::StringRef tok;
std::tie(tok, m_line) = m_line.split(',');
tok = tok.trim(" \t");
std::string_view tok;
std::tie(tok, m_line) = wpi::split(m_line, ',');
tok = wpi::trim(tok, " \t");
// need to convert to null-terminated string for std::strtod()
wpi::SmallString<64> buf = tok;
wpi::SmallString<64> buf{tok};
char* end;
double v = std::strtod(buf.c_str(), &end);
if (*end != '\0') {
@@ -345,7 +346,7 @@ std::shared_ptr<Value> LoadPersistentImpl::ReadDoubleArrayValue() {
std::shared_ptr<Value> LoadPersistentImpl::ReadStringArrayValue() {
m_buf_string_array.clear();
while (!m_line.empty()) {
wpi::StringRef tok;
std::string_view tok;
std::tie(tok, m_line) = ReadStringToken(m_line);
if (tok.empty()) {
Warn("missing string value");
@@ -357,9 +358,9 @@ std::shared_ptr<Value> LoadPersistentImpl::ReadStringArrayValue() {
}
wpi::SmallString<128> buf;
m_buf_string_array.push_back(UnescapeString(tok, buf));
m_buf_string_array.emplace_back(UnescapeString(tok, buf));
m_line = m_line.ltrim(" \t");
m_line = wpi::ltrim(m_line, " \t");
if (m_line.empty()) {
break;
}
@@ -367,23 +368,21 @@ std::shared_ptr<Value> LoadPersistentImpl::ReadStringArrayValue() {
Warn("expected comma between strings");
return nullptr;
}
m_line = m_line.drop_front().ltrim(" \t");
m_line.remove_prefix(1);
m_line = wpi::ltrim(m_line, " \t");
}
return Value::MakeStringArray(std::move(m_buf_string_array));
}
bool Storage::LoadEntries(
wpi::raw_istream& is, const wpi::Twine& prefix, bool persistent,
wpi::raw_istream& is, std::string_view prefix, bool persistent,
std::function<void(size_t line, const char* msg)> warn) {
wpi::SmallString<128> prefixBuf;
wpi::StringRef prefixStr = prefix.toStringRef(prefixBuf);
// entries to add
std::vector<LoadPersistentImpl::Entry> entries;
// load file
if (!LoadPersistentImpl(is, warn).Load(prefixStr, &entries)) {
if (!LoadPersistentImpl(is, warn).Load(prefix, &entries)) {
return false;
}
@@ -457,7 +456,7 @@ bool Storage::LoadEntries(
}
const char* Storage::LoadPersistent(
const wpi::Twine& filename,
std::string_view filename,
std::function<void(size_t line, const char* msg)> warn) {
std::error_code ec;
wpi::raw_fd_istream is(filename, ec);
@@ -471,7 +470,7 @@ const char* Storage::LoadPersistent(
}
const char* Storage::LoadEntries(
const wpi::Twine& filename, const wpi::Twine& prefix,
std::string_view filename, std::string_view prefix,
std::function<void(size_t line, const char* msg)> warn) {
std::error_code ec;
wpi::raw_fd_istream is(filename, ec);

View File

@@ -5,8 +5,8 @@
#include <cctype>
#include <string>
#include <fmt/format.h>
#include <wpi/Base64.h>
#include <wpi/Format.h>
#include <wpi/SmallString.h>
#include <wpi/StringExtras.h>
#include <wpi/fs.h>
@@ -21,17 +21,17 @@ namespace {
class SavePersistentImpl {
public:
typedef std::pair<std::string, std::shared_ptr<Value>> Entry;
using Entry = std::pair<std::string, std::shared_ptr<Value>>;
explicit SavePersistentImpl(wpi::raw_ostream& os) : m_os(os) {}
void Save(wpi::ArrayRef<Entry> entries);
private:
void WriteString(wpi::StringRef str);
void WriteString(std::string_view str);
void WriteHeader();
void WriteEntries(wpi::ArrayRef<Entry> entries);
void WriteEntry(wpi::StringRef name, const Value& value);
void WriteEntry(std::string_view name, const Value& value);
bool WriteType(NT_Type type);
void WriteValue(const Value& value);
@@ -41,7 +41,7 @@ class SavePersistentImpl {
} // namespace
/* Escapes and writes a string, including start and end double quotes */
void SavePersistentImpl::WriteString(wpi::StringRef str) {
void SavePersistentImpl::WriteString(std::string_view str) {
m_os << '"';
for (auto c : str) {
switch (c) {
@@ -90,7 +90,7 @@ void SavePersistentImpl::WriteEntries(wpi::ArrayRef<Entry> entries) {
}
}
void SavePersistentImpl::WriteEntry(wpi::StringRef name, const Value& value) {
void SavePersistentImpl::WriteEntry(std::string_view name, const Value& value) {
if (!WriteType(value.type())) {
return; // type
}
@@ -135,7 +135,7 @@ void SavePersistentImpl::WriteValue(const Value& value) {
m_os << (value.GetBoolean() ? "true" : "false");
break;
case NT_DOUBLE:
m_os << wpi::format("%g", value.GetDouble());
m_os << fmt::format("{:g}", value.GetDouble());
break;
case NT_STRING:
WriteString(value.GetString());
@@ -162,7 +162,7 @@ void SavePersistentImpl::WriteValue(const Value& value) {
m_os << ',';
}
first = false;
m_os << wpi::format("%g", elem);
m_os << fmt::format("{:g}", elem);
}
break;
}
@@ -190,14 +190,11 @@ void Storage::SavePersistent(wpi::raw_ostream& os, bool periodic) const {
SavePersistentImpl(os).Save(entries);
}
const char* Storage::SavePersistent(const wpi::Twine& filename,
const char* Storage::SavePersistent(std::string_view filename,
bool periodic) const {
wpi::SmallString<128> fn;
filename.toVector(fn);
wpi::SmallString<128> tmp = fn;
tmp += ".tmp";
wpi::SmallString<128> bak = fn;
bak += ".bak";
std::string fn{filename};
auto tmp = fmt::format("{}.tmp", filename);
auto bak = fmt::format("{}.bak", filename);
// Get entries before creating file
std::vector<SavePersistentImpl::Entry> entries;
@@ -214,7 +211,7 @@ const char* Storage::SavePersistent(const wpi::Twine& filename,
err = "could not open file";
goto done;
}
DEBUG0("saving persistent file '" << filename << "'");
DEBUG0("saving persistent file '{}'", filename);
SavePersistentImpl(os).Save(entries);
os.close();
if (os.has_error()) {
@@ -240,8 +237,7 @@ done:
return err;
}
void Storage::SaveEntries(wpi::raw_ostream& os,
const wpi::Twine& prefix) const {
void Storage::SaveEntries(wpi::raw_ostream& os, std::string_view prefix) const {
std::vector<SavePersistentImpl::Entry> entries;
if (!GetEntries(prefix, &entries)) {
return;
@@ -249,14 +245,11 @@ void Storage::SaveEntries(wpi::raw_ostream& os,
SavePersistentImpl(os).Save(entries);
}
const char* Storage::SaveEntries(const wpi::Twine& filename,
const wpi::Twine& prefix) const {
wpi::SmallString<128> fn;
filename.toVector(fn);
wpi::SmallString<128> tmp = fn;
tmp += ".tmp";
wpi::SmallString<128> bak = fn;
bak += ".bak";
const char* Storage::SaveEntries(std::string_view filename,
std::string_view prefix) const {
std::string fn{filename};
auto tmp = fmt::format("{}.tmp", filename);
auto bak = fmt::format("{}.bak", filename);
// Get entries before creating file
std::vector<SavePersistentImpl::Entry> entries;
@@ -270,7 +263,7 @@ const char* Storage::SaveEntries(const wpi::Twine& filename,
if (ec.value() != 0) {
return "could not open file";
}
DEBUG0("saving file '" << filename << "'");
DEBUG0("saving file '{}'", filename);
SavePersistentImpl(os).Save(entries);
os.close();
if (os.has_error()) {

View File

@@ -153,7 +153,7 @@ void nt::ConvertToC(const Value& in, NT_Value* out) {
out->type = in.type();
}
void nt::ConvertToC(wpi::StringRef in, NT_String* out) {
void nt::ConvertToC(std::string_view in, NT_String* out) {
out->len = in.size();
out->str = static_cast<char*>(wpi::safe_malloc(in.size() + 1));
std::memcpy(out->str, in.data(), in.size());
@@ -184,7 +184,7 @@ std::shared_ptr<Value> nt::ConvertFromC(const NT_Value& value) {
std::vector<std::string> v;
v.reserve(value.data.arr_string.size);
for (size_t i = 0; i < value.data.arr_string.size; ++i) {
v.push_back(ConvertFromC(value.data.arr_string.arr[i]));
v.emplace_back(ConvertFromC(value.data.arr_string.arr[i]));
}
return Value::MakeStringArray(std::move(v));
}

View File

@@ -7,8 +7,7 @@
#include <memory>
#include <string>
#include <wpi/StringRef.h>
#include <string_view>
#include "ntcore_c.h"
@@ -18,9 +17,9 @@ class Value;
void ConvertToC(const Value& in, NT_Value* out);
std::shared_ptr<Value> ConvertFromC(const NT_Value& value);
void ConvertToC(wpi::StringRef in, NT_String* out);
inline wpi::StringRef ConvertFromC(const NT_String& str) {
return wpi::StringRef(str.str, str.len);
void ConvertToC(std::string_view in, NT_String* out);
inline std::string_view ConvertFromC(const NT_String& str) {
return {str.str, str.len};
}
} // namespace nt

View File

@@ -242,6 +242,6 @@ bool WireDecoder::ReadString(std::string* str) {
if (!Read(&buf, len)) {
return false;
}
*str = wpi::StringRef(buf, len);
str->assign(buf, len);
return true;
}

View File

@@ -198,7 +198,7 @@ void WireEncoder::WriteValue(const Value& value) {
}
}
size_t WireEncoder::GetStringSize(wpi::StringRef str) const {
size_t WireEncoder::GetStringSize(std::string_view str) const {
if (m_proto_rev < 0x0300u) {
size_t len = str.size();
if (len > 0xffff) {
@@ -209,7 +209,7 @@ size_t WireEncoder::GetStringSize(wpi::StringRef str) const {
return wpi::SizeUleb128(str.size()) + str.size();
}
void WireEncoder::WriteString(wpi::StringRef str) {
void WireEncoder::WriteString(std::string_view str) {
// length
size_t len = str.size();
if (m_proto_rev < 0x0300u) {

View File

@@ -9,9 +9,9 @@
#include <cassert>
#include <cstddef>
#include <string_view>
#include <wpi/SmallVector.h>
#include <wpi/StringRef.h>
#include "networktables/NetworkTableValue.h"
@@ -49,8 +49,8 @@ class WireEncoder {
/* Returns number of bytes written to memory buffer. */
size_t size() const { return m_data.size(); }
wpi::StringRef ToStringRef() const {
return wpi::StringRef(m_data.data(), m_data.size());
std::string_view ToStringView() const {
return {m_data.data(), m_data.size()};
}
/* Writes a single byte. */
@@ -80,7 +80,7 @@ class WireEncoder {
void WriteType(NT_Type type);
void WriteValue(const Value& value);
void WriteString(wpi::StringRef str);
void WriteString(std::string_view str);
/* Utility function to get the written size of a value (without actually
* writing it).
@@ -90,7 +90,7 @@ class WireEncoder {
/* Utility function to get the written size of a string (without actually
* writing it).
*/
size_t GetStringSize(wpi::StringRef str) const;
size_t GetStringSize(std::string_view str) const;
protected:
/* The protocol revision. E.g. 0x0200 for version 2.0. */

View File

@@ -6,10 +6,9 @@
#include <cassert>
#include <fmt/format.h>
#include <wpi/ConvertUTF.h>
#include <wpi/SmallString.h>
#include <wpi/jni_util.h>
#include <wpi/raw_ostream.h>
#include "edu_wpi_first_networktables_NetworkTablesJNI.h"
#include "ntcore.h"
@@ -113,7 +112,7 @@ inline std::shared_ptr<nt::Value> FromJavaRaw(JNIEnv* env, jbyteArray jarr,
if (!ref) {
return nullptr;
}
return nt::Value::MakeRaw(ref, time);
return nt::Value::MakeRaw(ref.str(), time);
}
inline std::shared_ptr<nt::Value> FromJavaRawBB(JNIEnv* env, jobject jbb,
@@ -170,7 +169,7 @@ std::shared_ptr<nt::Value> FromJavaStringArray(JNIEnv* env, jobjectArray jarr,
if (!elem) {
return nullptr;
}
arr.push_back(JStringRef{env, elem}.str());
arr.emplace_back(JStringRef{env, elem}.str());
}
return nt::Value::MakeStringArray(std::move(arr), time);
}
@@ -1251,7 +1250,7 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_createPolledRpc
nullPointerEx.Throw(env, "def cannot be null");
return;
}
nt::CreatePolledRpc(entry, JByteArrayRef{env, def}, poller);
nt::CreatePolledRpc(entry, JByteArrayRef{env, def}.str(), poller);
}
/*
@@ -1326,7 +1325,7 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_postRpcResponse
nullPointerEx.Throw(env, "result cannot be null");
return false;
}
return nt::PostRpcResponse(entry, call, JByteArrayRef{env, result});
return nt::PostRpcResponse(entry, call, JByteArrayRef{env, result}.str());
}
/*
@@ -1342,7 +1341,7 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_callRpc
nullPointerEx.Throw(env, "params cannot be null");
return 0;
}
return nt::CallRpc(entry, JByteArrayRef{env, params});
return nt::CallRpc(entry, JByteArrayRef{env, params}.str());
}
/*
@@ -1549,7 +1548,7 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_startClient__I_3Ljava_lang_Str
}
std::vector<std::string> names;
std::vector<std::pair<wpi::StringRef, unsigned int>> servers;
std::vector<std::pair<std::string_view, unsigned int>> servers;
names.reserve(len);
servers.reserve(len);
for (int i = 0; i < len; ++i) {
@@ -1561,7 +1560,7 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_startClient__I_3Ljava_lang_Str
}
names.emplace_back(JStringRef{env, elem}.str());
servers.emplace_back(
std::make_pair(wpi::StringRef(names.back()), portInts[i]));
std::make_pair(std::string_view{names.back()}, portInts[i]));
}
env->ReleaseIntArrayElements(ports, portInts, JNI_ABORT);
nt::StartClient(inst, servers);
@@ -1636,7 +1635,7 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setServer__I_3Ljava_lang_Strin
}
std::vector<std::string> names;
std::vector<std::pair<wpi::StringRef, unsigned int>> servers;
std::vector<std::pair<std::string_view, unsigned int>> servers;
names.reserve(len);
servers.reserve(len);
for (int i = 0; i < len; ++i) {
@@ -1648,7 +1647,7 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_setServer__I_3Ljava_lang_Strin
}
names.emplace_back(JStringRef{env, elem}.str());
servers.emplace_back(
std::make_pair(wpi::StringRef(names.back()), portInts[i]));
std::make_pair(std::string_view{names.back()}, portInts[i]));
}
env->ReleaseIntArrayElements(ports, portInts, JNI_ABORT);
nt::SetServer(inst, servers);
@@ -1781,13 +1780,10 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_loadPersistent
return nullptr;
}
std::vector<std::string> warns;
const char* err = nt::LoadPersistent(inst, JStringRef{env, filename}.str(),
[&](size_t line, const char* msg) {
wpi::SmallString<128> warn;
wpi::raw_svector_ostream oss(warn);
oss << line << ": " << msg;
warns.emplace_back(oss.str());
});
const char* err = nt::LoadPersistent(
inst, JStringRef{env, filename}.str(), [&](size_t line, const char* msg) {
warns.emplace_back(fmt::format("{}: {}", line, msg));
});
if (err) {
persistentEx.Throw(env, err);
return nullptr;
@@ -1837,14 +1833,11 @@ Java_edu_wpi_first_networktables_NetworkTablesJNI_loadEntries
return nullptr;
}
std::vector<std::string> warns;
const char* err = nt::LoadEntries(inst, JStringRef{env, filename}.str(),
JStringRef{env, prefix}.str(),
[&](size_t line, const char* msg) {
wpi::SmallString<128> warn;
wpi::raw_svector_ostream oss(warn);
oss << line << ": " << msg;
warns.emplace_back(oss.str());
});
const char* err = nt::LoadEntries(
inst, JStringRef{env, filename}.str(), JStringRef{env, prefix}.str(),
[&](size_t line, const char* msg) {
warns.emplace_back(fmt::format("{}: {}", line, msg));
});
if (err) {
persistentEx.Throw(env, err);
return nullptr;

View File

@@ -6,61 +6,59 @@
#include <algorithm>
#include <fmt/core.h>
#include <fmt/format.h>
#include <wpi/SmallString.h>
#include <wpi/StringExtras.h>
#include <wpi/StringMap.h>
#include <wpi/raw_ostream.h>
#include "networktables/NetworkTableInstance.h"
#include "ntcore.h"
using namespace nt;
wpi::StringRef NetworkTable::BasenameKey(wpi::StringRef key) {
std::string_view NetworkTable::BasenameKey(std::string_view key) {
size_t slash = key.rfind(PATH_SEPARATOR_CHAR);
if (slash == wpi::StringRef::npos) {
if (slash == std::string_view::npos) {
return key;
}
return key.substr(slash + 1);
}
std::string NetworkTable::NormalizeKey(const wpi::Twine& key,
std::string NetworkTable::NormalizeKey(std::string_view key,
bool withLeadingSlash) {
wpi::SmallString<128> buf;
return NormalizeKey(key, buf, withLeadingSlash);
return std::string{NormalizeKey(key, buf, withLeadingSlash)};
}
wpi::StringRef NetworkTable::NormalizeKey(const wpi::Twine& key,
wpi::SmallVectorImpl<char>& buf,
bool withLeadingSlash) {
std::string_view NetworkTable::NormalizeKey(std::string_view key,
wpi::SmallVectorImpl<char>& buf,
bool withLeadingSlash) {
buf.clear();
if (withLeadingSlash) {
buf.push_back(PATH_SEPARATOR_CHAR);
}
// for each path element, add it with a slash following
wpi::SmallString<128> keyBuf;
wpi::StringRef keyStr = key.toStringRef(keyBuf);
wpi::SmallVector<wpi::StringRef, 16> parts;
keyStr.split(parts, PATH_SEPARATOR_CHAR, -1, false);
wpi::SmallVector<std::string_view, 16> parts;
wpi::split(key, parts, PATH_SEPARATOR_CHAR, -1, false);
for (auto i = parts.begin(); i != parts.end(); ++i) {
buf.append(i->begin(), i->end());
buf.push_back(PATH_SEPARATOR_CHAR);
}
// remove trailing slash if the input key didn't have one
if (!keyStr.empty() && keyStr.back() != PATH_SEPARATOR_CHAR) {
if (!key.empty() && key.back() != PATH_SEPARATOR_CHAR) {
buf.pop_back();
}
return wpi::StringRef(buf.data(), buf.size());
return {buf.data(), buf.size()};
}
std::vector<std::string> NetworkTable::GetHierarchy(const wpi::Twine& key) {
std::vector<std::string> NetworkTable::GetHierarchy(std::string_view key) {
std::vector<std::string> hierarchy;
hierarchy.emplace_back(1, PATH_SEPARATOR_CHAR);
// for each path element, add it to the end of what we built previously
wpi::SmallString<128> keyBuf;
wpi::StringRef keyStr = key.toStringRef(keyBuf);
wpi::SmallString<128> path;
wpi::SmallVector<wpi::StringRef, 16> parts;
keyStr.split(parts, PATH_SEPARATOR_CHAR, -1, false);
wpi::SmallVector<std::string_view, 16> parts;
wpi::split(key, parts, PATH_SEPARATOR_CHAR, -1, false);
if (!parts.empty()) {
for (auto i = parts.begin(); i != parts.end(); ++i) {
path += PATH_SEPARATOR_CHAR;
@@ -68,7 +66,7 @@ std::vector<std::string> NetworkTable::GetHierarchy(const wpi::Twine& key) {
hierarchy.emplace_back(path.str());
}
// handle trailing slash
if (keyStr.back() == PATH_SEPARATOR_CHAR) {
if (key.back() == PATH_SEPARATOR_CHAR) {
path += PATH_SEPARATOR_CHAR;
hierarchy.emplace_back(path.str());
}
@@ -76,9 +74,9 @@ std::vector<std::string> NetworkTable::GetHierarchy(const wpi::Twine& key) {
return hierarchy;
}
NetworkTable::NetworkTable(NT_Inst inst, const wpi::Twine& path,
NetworkTable::NetworkTable(NT_Inst inst, std::string_view path,
const private_init&)
: m_inst(inst), m_path(path.str()) {}
: m_inst(inst), m_path(path) {}
NetworkTable::~NetworkTable() {
for (auto i : m_listeners) {
@@ -90,14 +88,13 @@ NetworkTableInstance NetworkTable::GetInstance() const {
return NetworkTableInstance{m_inst};
}
NetworkTableEntry NetworkTable::GetEntry(const wpi::Twine& key) const {
wpi::SmallString<128> keyBuf;
wpi::StringRef keyStr = key.toStringRef(keyBuf);
NetworkTableEntry NetworkTable::GetEntry(std::string_view key) const {
std::scoped_lock lock(m_mutex);
NT_Entry& entry = m_entries[keyStr];
NT_Entry& entry = m_entries[key];
if (entry == 0) {
entry =
nt::GetEntry(m_inst, m_path + wpi::Twine(PATH_SEPARATOR_CHAR) + keyStr);
fmt::memory_buffer buf;
fmt::format_to(buf, "{}/{}", m_path, key);
entry = nt::GetEntry(m_inst, {buf.data(), buf.size()});
}
return NetworkTableEntry{entry};
}
@@ -106,10 +103,10 @@ NT_EntryListener NetworkTable::AddEntryListener(TableEntryListener listener,
unsigned int flags) const {
size_t prefix_len = m_path.size() + 1;
return nt::AddEntryListener(
m_inst, m_path + wpi::Twine(PATH_SEPARATOR_CHAR),
m_inst, fmt::format("{}/", m_path),
[=](const EntryNotification& event) {
wpi::StringRef relative_key = event.name.substr(prefix_len);
if (relative_key.find(PATH_SEPARATOR_CHAR) != wpi::StringRef::npos) {
auto relative_key = std::string_view{event.name}.substr(prefix_len);
if (relative_key.find(PATH_SEPARATOR_CHAR) != std::string_view::npos) {
return;
}
listener(const_cast<NetworkTable*>(this), relative_key,
@@ -118,7 +115,7 @@ NT_EntryListener NetworkTable::AddEntryListener(TableEntryListener listener,
flags);
}
NT_EntryListener NetworkTable::AddEntryListener(const wpi::Twine& key,
NT_EntryListener NetworkTable::AddEntryListener(std::string_view key,
TableEntryListener listener,
unsigned int flags) const {
size_t prefix_len = m_path.size() + 1;
@@ -126,8 +123,9 @@ NT_EntryListener NetworkTable::AddEntryListener(const wpi::Twine& key,
return nt::AddEntryListener(
entry.GetHandle(),
[=](const EntryNotification& event) {
listener(const_cast<NetworkTable*>(this), event.name.substr(prefix_len),
entry, event.value, event.flags);
listener(const_cast<NetworkTable*>(this),
std::string_view{event.name}.substr(prefix_len), entry,
event.value, event.flags);
},
flags);
}
@@ -149,14 +147,14 @@ NT_EntryListener NetworkTable::AddSubTableListener(TableListener listener,
flags |= NT_NOTIFY_LOCAL;
}
NT_EntryListener id = nt::AddEntryListener(
m_inst, m_path + wpi::Twine(PATH_SEPARATOR_CHAR),
m_inst, fmt::format("{}/", m_path),
[=](const EntryNotification& event) {
wpi::StringRef relative_key = event.name.substr(prefix_len);
auto relative_key = std::string_view{event.name}.substr(prefix_len);
auto end_sub_table = relative_key.find(PATH_SEPARATOR_CHAR);
if (end_sub_table == wpi::StringRef::npos) {
if (end_sub_table == std::string_view::npos) {
return;
}
wpi::StringRef sub_table_key = relative_key.substr(0, end_sub_table);
auto sub_table_key = relative_key.substr(0, end_sub_table);
if (notified_tables->find(sub_table_key) == notified_tables->end()) {
return;
}
@@ -176,39 +174,33 @@ void NetworkTable::RemoveTableListener(NT_EntryListener listener) {
}
std::shared_ptr<NetworkTable> NetworkTable::GetSubTable(
const wpi::Twine& key) const {
std::string_view key) const {
return std::make_shared<NetworkTable>(
m_inst, m_path + wpi::Twine(PATH_SEPARATOR_CHAR) + key, private_init{});
m_inst, fmt::format("{}/{}", m_path, key), private_init{});
}
bool NetworkTable::ContainsKey(const wpi::Twine& key) const {
if (key.isTriviallyEmpty() ||
(key.isSingleStringRef() && key.getSingleStringRef().empty())) {
bool NetworkTable::ContainsKey(std::string_view key) const {
if (key.empty()) {
return false;
}
return GetEntry(key).Exists();
}
bool NetworkTable::ContainsSubTable(const wpi::Twine& key) const {
return !GetEntryInfo(m_inst,
m_path + wpi::Twine(PATH_SEPARATOR_CHAR) + key +
wpi::Twine(PATH_SEPARATOR_CHAR),
0)
.empty();
bool NetworkTable::ContainsSubTable(std::string_view key) const {
return !GetEntryInfo(m_inst, fmt::format("{}/{}/", m_path, key), 0).empty();
}
std::vector<std::string> NetworkTable::GetKeys(int types) const {
std::vector<std::string> keys;
size_t prefix_len = m_path.size() + 1;
auto infos =
GetEntryInfo(m_inst, m_path + wpi::Twine(PATH_SEPARATOR_CHAR), types);
auto infos = GetEntryInfo(m_inst, fmt::format("{}/", m_path), types);
std::scoped_lock lock(m_mutex);
for (auto& info : infos) {
auto relative_key = wpi::StringRef(info.name).substr(prefix_len);
if (relative_key.find(PATH_SEPARATOR_CHAR) != wpi::StringRef::npos) {
auto relative_key = std::string_view{info.name}.substr(prefix_len);
if (relative_key.find(PATH_SEPARATOR_CHAR) != std::string_view::npos) {
continue;
}
keys.push_back(relative_key);
keys.emplace_back(relative_key);
m_entries[relative_key] = info.entry;
}
return keys;
@@ -217,169 +209,167 @@ std::vector<std::string> NetworkTable::GetKeys(int types) const {
std::vector<std::string> NetworkTable::GetSubTables() const {
std::vector<std::string> keys;
size_t prefix_len = m_path.size() + 1;
for (auto& entry :
GetEntryInfo(m_inst, m_path + wpi::Twine(PATH_SEPARATOR_CHAR), 0)) {
auto relative_key = wpi::StringRef(entry.name).substr(prefix_len);
for (auto& entry : GetEntryInfo(m_inst, fmt::format("{}/", m_path), 0)) {
auto relative_key = std::string_view{entry.name}.substr(prefix_len);
size_t end_subtable = relative_key.find(PATH_SEPARATOR_CHAR);
if (end_subtable == wpi::StringRef::npos) {
if (end_subtable == std::string_view::npos) {
continue;
}
keys.push_back(relative_key.substr(0, end_subtable));
keys.emplace_back(relative_key.substr(0, end_subtable));
}
return keys;
}
void NetworkTable::SetPersistent(wpi::StringRef key) {
void NetworkTable::SetPersistent(std::string_view key) {
GetEntry(key).SetPersistent();
}
void NetworkTable::ClearPersistent(wpi::StringRef key) {
void NetworkTable::ClearPersistent(std::string_view key) {
GetEntry(key).ClearPersistent();
}
bool NetworkTable::IsPersistent(wpi::StringRef key) const {
bool NetworkTable::IsPersistent(std::string_view key) const {
return GetEntry(key).IsPersistent();
}
void NetworkTable::SetFlags(wpi::StringRef key, unsigned int flags) {
void NetworkTable::SetFlags(std::string_view key, unsigned int flags) {
GetEntry(key).SetFlags(flags);
}
void NetworkTable::ClearFlags(wpi::StringRef key, unsigned int flags) {
void NetworkTable::ClearFlags(std::string_view key, unsigned int flags) {
GetEntry(key).ClearFlags(flags);
}
unsigned int NetworkTable::GetFlags(wpi::StringRef key) const {
unsigned int NetworkTable::GetFlags(std::string_view key) const {
return GetEntry(key).GetFlags();
}
void NetworkTable::Delete(const wpi::Twine& key) {
void NetworkTable::Delete(std::string_view key) {
GetEntry(key).Delete();
}
bool NetworkTable::PutNumber(wpi::StringRef key, double value) {
bool NetworkTable::PutNumber(std::string_view key, double value) {
return GetEntry(key).SetDouble(value);
}
bool NetworkTable::SetDefaultNumber(wpi::StringRef key, double defaultValue) {
bool NetworkTable::SetDefaultNumber(std::string_view key, double defaultValue) {
return GetEntry(key).SetDefaultDouble(defaultValue);
}
double NetworkTable::GetNumber(wpi::StringRef key, double defaultValue) const {
double NetworkTable::GetNumber(std::string_view key,
double defaultValue) const {
return GetEntry(key).GetDouble(defaultValue);
}
bool NetworkTable::PutString(wpi::StringRef key, wpi::StringRef value) {
bool NetworkTable::PutString(std::string_view key, std::string_view value) {
return GetEntry(key).SetString(value);
}
bool NetworkTable::SetDefaultString(wpi::StringRef key,
wpi::StringRef defaultValue) {
bool NetworkTable::SetDefaultString(std::string_view key,
std::string_view defaultValue) {
return GetEntry(key).SetDefaultString(defaultValue);
}
std::string NetworkTable::GetString(wpi::StringRef key,
wpi::StringRef defaultValue) const {
std::string NetworkTable::GetString(std::string_view key,
std::string_view defaultValue) const {
return GetEntry(key).GetString(defaultValue);
}
bool NetworkTable::PutBoolean(wpi::StringRef key, bool value) {
bool NetworkTable::PutBoolean(std::string_view key, bool value) {
return GetEntry(key).SetBoolean(value);
}
bool NetworkTable::SetDefaultBoolean(wpi::StringRef key, bool defaultValue) {
bool NetworkTable::SetDefaultBoolean(std::string_view key, bool defaultValue) {
return GetEntry(key).SetDefaultBoolean(defaultValue);
}
bool NetworkTable::GetBoolean(wpi::StringRef key, bool defaultValue) const {
bool NetworkTable::GetBoolean(std::string_view key, bool defaultValue) const {
return GetEntry(key).GetBoolean(defaultValue);
}
bool NetworkTable::PutBooleanArray(wpi::StringRef key,
bool NetworkTable::PutBooleanArray(std::string_view key,
wpi::ArrayRef<int> value) {
return GetEntry(key).SetBooleanArray(value);
}
bool NetworkTable::SetDefaultBooleanArray(wpi::StringRef key,
bool NetworkTable::SetDefaultBooleanArray(std::string_view key,
wpi::ArrayRef<int> defaultValue) {
return GetEntry(key).SetDefaultBooleanArray(defaultValue);
}
std::vector<int> NetworkTable::GetBooleanArray(
wpi::StringRef key, wpi::ArrayRef<int> defaultValue) const {
std::string_view key, wpi::ArrayRef<int> defaultValue) const {
return GetEntry(key).GetBooleanArray(defaultValue);
}
bool NetworkTable::PutNumberArray(wpi::StringRef key,
bool NetworkTable::PutNumberArray(std::string_view key,
wpi::ArrayRef<double> value) {
return GetEntry(key).SetDoubleArray(value);
}
bool NetworkTable::SetDefaultNumberArray(wpi::StringRef key,
bool NetworkTable::SetDefaultNumberArray(std::string_view key,
wpi::ArrayRef<double> defaultValue) {
return GetEntry(key).SetDefaultDoubleArray(defaultValue);
}
std::vector<double> NetworkTable::GetNumberArray(
wpi::StringRef key, wpi::ArrayRef<double> defaultValue) const {
std::string_view key, wpi::ArrayRef<double> defaultValue) const {
return GetEntry(key).GetDoubleArray(defaultValue);
}
bool NetworkTable::PutStringArray(wpi::StringRef key,
bool NetworkTable::PutStringArray(std::string_view key,
wpi::ArrayRef<std::string> value) {
return GetEntry(key).SetStringArray(value);
}
bool NetworkTable::SetDefaultStringArray(
wpi::StringRef key, wpi::ArrayRef<std::string> defaultValue) {
std::string_view key, wpi::ArrayRef<std::string> defaultValue) {
return GetEntry(key).SetDefaultStringArray(defaultValue);
}
std::vector<std::string> NetworkTable::GetStringArray(
wpi::StringRef key, wpi::ArrayRef<std::string> defaultValue) const {
std::string_view key, wpi::ArrayRef<std::string> defaultValue) const {
return GetEntry(key).GetStringArray(defaultValue);
}
bool NetworkTable::PutRaw(wpi::StringRef key, wpi::StringRef value) {
bool NetworkTable::PutRaw(std::string_view key, std::string_view value) {
return GetEntry(key).SetRaw(value);
}
bool NetworkTable::SetDefaultRaw(wpi::StringRef key,
wpi::StringRef defaultValue) {
bool NetworkTable::SetDefaultRaw(std::string_view key,
std::string_view defaultValue) {
return GetEntry(key).SetDefaultRaw(defaultValue);
}
std::string NetworkTable::GetRaw(wpi::StringRef key,
wpi::StringRef defaultValue) const {
std::string NetworkTable::GetRaw(std::string_view key,
std::string_view defaultValue) const {
return GetEntry(key).GetRaw(defaultValue);
}
bool NetworkTable::PutValue(const wpi::Twine& key,
bool NetworkTable::PutValue(std::string_view key,
std::shared_ptr<Value> value) {
return GetEntry(key).SetValue(value);
}
bool NetworkTable::SetDefaultValue(const wpi::Twine& key,
bool NetworkTable::SetDefaultValue(std::string_view key,
std::shared_ptr<Value> defaultValue) {
return GetEntry(key).SetDefaultValue(defaultValue);
}
std::shared_ptr<Value> NetworkTable::GetValue(const wpi::Twine& key) const {
std::shared_ptr<Value> NetworkTable::GetValue(std::string_view key) const {
return GetEntry(key).GetValue();
}
wpi::StringRef NetworkTable::GetPath() const {
std::string_view NetworkTable::GetPath() const {
return m_path;
}
const char* NetworkTable::SaveEntries(const wpi::Twine& filename) const {
return nt::SaveEntries(m_inst, filename,
m_path + wpi::Twine(PATH_SEPARATOR_CHAR));
const char* NetworkTable::SaveEntries(std::string_view filename) const {
return nt::SaveEntries(m_inst, filename, fmt::format("{}/", m_path));
}
const char* NetworkTable::LoadEntries(
const wpi::Twine& filename,
std::string_view filename,
std::function<void(size_t line, const char* msg)> warn) {
return nt::LoadEntries(m_inst, filename,
m_path + wpi::Twine(PATH_SEPARATOR_CHAR), warn);
return nt::LoadEntries(m_inst, filename, fmt::format("{}/", m_path), warn);
}

View File

@@ -4,42 +4,37 @@
#include "networktables/NetworkTableInstance.h"
#include <wpi/SmallString.h>
#include <fmt/format.h>
#include <wpi/SmallVector.h>
using namespace nt;
std::shared_ptr<NetworkTable> NetworkTableInstance::GetTable(
const wpi::Twine& key) const {
wpi::StringRef simple;
bool isSimple = key.isSingleStringRef();
if (isSimple) {
simple = key.getSingleStringRef();
}
if (isSimple && (simple.empty() || simple == "/")) {
std::string_view key) const {
if (key.empty() || key == "/") {
return std::make_shared<NetworkTable>(m_handle, "",
NetworkTable::private_init{});
} else if (isSimple && simple[0] == NetworkTable::PATH_SEPARATOR_CHAR) {
} else if (key.front() == NetworkTable::PATH_SEPARATOR_CHAR) {
return std::make_shared<NetworkTable>(m_handle, key,
NetworkTable::private_init{});
} else {
return std::make_shared<NetworkTable>(
m_handle, wpi::Twine(NetworkTable::PATH_SEPARATOR_CHAR) + key,
NetworkTable::private_init{});
return std::make_shared<NetworkTable>(m_handle, fmt::format("/{}", key),
NetworkTable::private_init{});
}
}
void NetworkTableInstance::StartClient(wpi::ArrayRef<wpi::StringRef> servers,
void NetworkTableInstance::StartClient(wpi::ArrayRef<std::string_view> servers,
unsigned int port) {
wpi::SmallVector<std::pair<wpi::StringRef, unsigned int>, 8> server_ports;
wpi::SmallVector<std::pair<std::string_view, unsigned int>, 8> server_ports;
for (const auto& server : servers) {
server_ports.emplace_back(std::make_pair(server, port));
}
StartClient(server_ports);
}
void NetworkTableInstance::SetServer(wpi::ArrayRef<wpi::StringRef> servers,
void NetworkTableInstance::SetServer(wpi::ArrayRef<std::string_view> servers,
unsigned int port) {
wpi::SmallVector<std::pair<wpi::StringRef, unsigned int>, 8> server_ports;
wpi::SmallVector<std::pair<std::string_view, unsigned int>, 8> server_ports;
for (const auto& server : servers) {
server_ports.emplace_back(std::make_pair(server, port));
}
@@ -47,7 +42,7 @@ void NetworkTableInstance::SetServer(wpi::ArrayRef<wpi::StringRef> servers,
}
NT_EntryListener NetworkTableInstance::AddEntryListener(
const wpi::Twine& prefix,
std::string_view prefix,
std::function<void(const EntryNotification& event)> callback,
unsigned int flags) const {
return ::nt::AddEntryListener(m_handle, prefix, callback, flags);

View File

@@ -6,6 +6,7 @@
#include <cassert>
#include <cstdlib>
#include <string_view>
#include <wpi/MemAlloc.h>
#include <wpi/timestamp.h>
@@ -17,7 +18,7 @@ using namespace nt;
// Conversion helpers
static void ConvertToC(wpi::StringRef in, char** out) {
static void ConvertToC(std::string_view in, char** out) {
*out = static_cast<char*>(wpi::safe_malloc(in.size() + 1));
std::memmove(*out, in.data(), in.size()); // NOLINT
(*out)[in.size()] = '\0';
@@ -192,12 +193,12 @@ NT_Inst NT_GetInstanceFromHandle(NT_Handle handle) {
*/
NT_Entry NT_GetEntry(NT_Inst inst, const char* name, size_t name_len) {
return nt::GetEntry(inst, wpi::StringRef(name, name_len));
return nt::GetEntry(inst, {name, name_len});
}
NT_Entry* NT_GetEntries(NT_Inst inst, const char* prefix, size_t prefix_len,
unsigned int types, size_t* count) {
auto info_v = nt::GetEntries(inst, wpi::StringRef(prefix, prefix_len), types);
auto info_v = nt::GetEntries(inst, {prefix, prefix_len}, types);
*count = info_v.size();
if (info_v.size() == 0) {
return nullptr;
@@ -266,8 +267,7 @@ void NT_DeleteAllEntries(NT_Inst inst) {
struct NT_EntryInfo* NT_GetEntryInfo(NT_Inst inst, const char* prefix,
size_t prefix_len, unsigned int types,
size_t* count) {
auto info_v =
nt::GetEntryInfo(inst, wpi::StringRef(prefix, prefix_len), types);
auto info_v = nt::GetEntryInfo(inst, {prefix, prefix_len}, types);
return ConvertToC<NT_EntryInfo>(info_v, count);
}
@@ -289,7 +289,7 @@ NT_EntryListener NT_AddEntryListener(NT_Inst inst, const char* prefix,
NT_EntryListenerCallback callback,
unsigned int flags) {
return nt::AddEntryListener(
inst, wpi::StringRef(prefix, prefix_len),
inst, {prefix, prefix_len},
[=](const EntryNotification& event) {
NT_EntryNotification c_event;
ConvertToC(event, &c_event);
@@ -325,8 +325,7 @@ NT_EntryListener NT_AddPolledEntryListener(NT_EntryListenerPoller poller,
const char* prefix,
size_t prefix_len,
unsigned int flags) {
return nt::AddPolledEntryListener(poller, wpi::StringRef(prefix, prefix_len),
flags);
return nt::AddPolledEntryListener(poller, {prefix, prefix_len}, flags);
}
NT_EntryListener NT_AddPolledEntryListenerSingle(NT_EntryListenerPoller poller,
@@ -422,13 +421,12 @@ NT_Bool NT_WaitForConnectionListenerQueue(NT_Inst inst, double timeout) {
void NT_CreateRpc(NT_Entry entry, const char* def, size_t def_len, void* data,
NT_RpcCallback callback) {
nt::CreateRpc(entry, wpi::StringRef(def, def_len),
[=](const RpcAnswer& answer) {
NT_RpcAnswer answer_c;
ConvertToC(answer, &answer_c);
callback(data, &answer_c);
NT_DisposeRpcAnswer(&answer_c);
});
nt::CreateRpc(entry, {def, def_len}, [=](const RpcAnswer& answer) {
NT_RpcAnswer answer_c;
ConvertToC(answer, &answer_c);
callback(data, &answer_c);
NT_DisposeRpcAnswer(&answer_c);
});
}
NT_RpcCallPoller NT_CreateRpcCallPoller(NT_Inst inst) {
@@ -441,7 +439,7 @@ void NT_DestroyRpcCallPoller(NT_RpcCallPoller poller) {
void NT_CreatePolledRpc(NT_Entry entry, const char* def, size_t def_len,
NT_RpcCallPoller poller) {
nt::CreatePolledRpc(entry, wpi::StringRef(def, def_len), poller);
nt::CreatePolledRpc(entry, {def, def_len}, poller);
}
NT_RpcAnswer* NT_PollRpc(NT_RpcCallPoller poller, size_t* len) {
@@ -467,11 +465,11 @@ NT_Bool NT_WaitForRpcCallQueue(NT_Inst inst, double timeout) {
NT_Bool NT_PostRpcResponse(NT_Entry entry, NT_RpcCall call, const char* result,
size_t result_len) {
return nt::PostRpcResponse(entry, call, wpi::StringRef(result, result_len));
return nt::PostRpcResponse(entry, call, {result, result_len});
}
NT_RpcCall NT_CallRpc(NT_Entry entry, const char* params, size_t params_len) {
return nt::CallRpc(entry, wpi::StringRef(params, params_len));
return nt::CallRpc(entry, {params, params_len});
}
char* NT_GetRpcResult(NT_Entry entry, NT_RpcCall call, size_t* result_len) {
@@ -522,7 +520,7 @@ char* NT_PackRpcDefinition(const NT_RpcDefinition* def, size_t* packed_len) {
NT_Bool NT_UnpackRpcDefinition(const char* packed, size_t packed_len,
NT_RpcDefinition* def) {
nt::RpcDefinition def_v;
if (!nt::UnpackRpcDefinition(wpi::StringRef(packed, packed_len), &def_v)) {
if (!nt::UnpackRpcDefinition({packed, packed_len}, &def_v)) {
return 0;
}
@@ -552,7 +550,7 @@ char* NT_PackRpcValues(const NT_Value** values, size_t values_len,
NT_Value** NT_UnpackRpcValues(const char* packed, size_t packed_len,
const NT_Type* types, size_t types_len) {
auto values_v = nt::UnpackRpcValues(wpi::StringRef(packed, packed_len),
auto values_v = nt::UnpackRpcValues({packed, packed_len},
wpi::ArrayRef<NT_Type>(types, types_len));
if (values_v.size() == 0) {
return nullptr;
@@ -573,7 +571,7 @@ NT_Value** NT_UnpackRpcValues(const char* packed, size_t packed_len,
*/
void NT_SetNetworkIdentity(NT_Inst inst, const char* name, size_t name_len) {
nt::SetNetworkIdentity(inst, wpi::StringRef(name, name_len));
nt::SetNetworkIdentity(inst, {name, name_len});
}
unsigned int NT_GetNetworkMode(NT_Inst inst) {
@@ -607,7 +605,7 @@ void NT_StartClient(NT_Inst inst, const char* server_name, unsigned int port) {
void NT_StartClientMulti(NT_Inst inst, size_t count, const char** server_names,
const unsigned int* ports) {
std::vector<std::pair<wpi::StringRef, unsigned int>> servers;
std::vector<std::pair<std::string_view, unsigned int>> servers;
servers.reserve(count);
for (size_t i = 0; i < count; ++i) {
servers.emplace_back(std::make_pair(server_names[i], ports[i]));
@@ -629,7 +627,7 @@ void NT_SetServer(NT_Inst inst, const char* server_name, unsigned int port) {
void NT_SetServerMulti(NT_Inst inst, size_t count, const char** server_names,
const unsigned int* ports) {
std::vector<std::pair<wpi::StringRef, unsigned int>> servers;
std::vector<std::pair<std::string_view, unsigned int>> servers;
servers.reserve(count);
for (size_t i = 0; i < count; ++i) {
servers.emplace_back(std::make_pair(server_names[i], ports[i]));
@@ -681,14 +679,13 @@ const char* NT_LoadPersistent(NT_Inst inst, const char* filename,
const char* NT_SaveEntries(NT_Inst inst, const char* filename,
const char* prefix, size_t prefix_len) {
return nt::SaveEntries(inst, filename, wpi::StringRef(prefix, prefix_len));
return nt::SaveEntries(inst, filename, {prefix, prefix_len});
}
const char* NT_LoadEntries(NT_Inst inst, const char* filename,
const char* prefix, size_t prefix_len,
void (*warn)(size_t line, const char* msg)) {
return nt::LoadEntries(inst, filename, wpi::StringRef(prefix, prefix_len),
warn);
return nt::LoadEntries(inst, filename, {prefix, prefix_len}, warn);
}
/*
@@ -954,24 +951,20 @@ NT_Bool NT_SetEntryBoolean(NT_Entry entry, uint64_t time, NT_Bool v_boolean,
NT_Bool NT_SetEntryString(NT_Entry entry, uint64_t time, const char* str,
size_t str_len, NT_Bool force) {
if (force != 0) {
nt::SetEntryTypeValue(
entry, Value::MakeString(wpi::StringRef(str, str_len), time));
nt::SetEntryTypeValue(entry, Value::MakeString({str, str_len}, time));
return 1;
} else {
return nt::SetEntryValue(
entry, Value::MakeString(wpi::StringRef(str, str_len), time));
return nt::SetEntryValue(entry, Value::MakeString({str, str_len}, time));
}
}
NT_Bool NT_SetEntryRaw(NT_Entry entry, uint64_t time, const char* raw,
size_t raw_len, NT_Bool force) {
if (force != 0) {
nt::SetEntryTypeValue(entry,
Value::MakeRaw(wpi::StringRef(raw, raw_len), time));
nt::SetEntryTypeValue(entry, Value::MakeRaw({raw, raw_len}, time));
return 1;
} else {
return nt::SetEntryValue(
entry, Value::MakeRaw(wpi::StringRef(raw, raw_len), time));
return nt::SetEntryValue(entry, Value::MakeRaw({raw, raw_len}, time));
}
}
@@ -1006,7 +999,7 @@ NT_Bool NT_SetEntryStringArray(NT_Entry entry, uint64_t time,
std::vector<std::string> v;
v.reserve(size);
for (size_t i = 0; i < size; ++i) {
v.push_back(ConvertFromC(arr[i]));
v.emplace_back(ConvertFromC(arr[i]));
}
if (force != 0) {
@@ -1132,14 +1125,13 @@ NT_Bool NT_SetDefaultEntryString(NT_Entry entry, uint64_t time,
const char* default_value,
size_t default_len) {
return nt::SetDefaultEntryValue(
entry,
Value::MakeString(wpi::StringRef(default_value, default_len), time));
entry, Value::MakeString({default_value, default_len}, time));
}
NT_Bool NT_SetDefaultEntryRaw(NT_Entry entry, uint64_t time,
const char* default_value, size_t default_len) {
return nt::SetDefaultEntryValue(
entry, Value::MakeRaw(wpi::StringRef(default_value, default_len), time));
entry, Value::MakeRaw({default_value, default_len}, time));
}
NT_Bool NT_SetDefaultEntryBooleanArray(NT_Entry entry, uint64_t time,
@@ -1164,7 +1156,7 @@ NT_Bool NT_SetDefaultEntryStringArray(NT_Entry entry, uint64_t time,
std::vector<std::string> vec;
vec.reserve(default_size);
for (size_t i = 0; i < default_size; ++i) {
vec.push_back(ConvertFromC(default_value[i]));
vec.emplace_back(ConvertFromC(default_value[i]));
}
return nt::SetDefaultEntryValue(entry,

View File

@@ -53,7 +53,7 @@ NT_Inst GetInstanceFromHandle(NT_Handle handle) {
* Table Functions
*/
NT_Entry GetEntry(NT_Inst inst, const wpi::Twine& name) {
NT_Entry GetEntry(NT_Inst inst, std::string_view name) {
int i = Handle{inst}.GetTypedInst(Handle::kInstance);
auto ii = InstanceImpl::Get(i);
if (!ii) {
@@ -67,7 +67,7 @@ NT_Entry GetEntry(NT_Inst inst, const wpi::Twine& name) {
return Handle(i, id, Handle::kEntry);
}
std::vector<NT_Entry> GetEntries(NT_Inst inst, const wpi::Twine& prefix,
std::vector<NT_Entry> GetEntries(NT_Inst inst, std::string_view prefix,
unsigned int types) {
int i = Handle{inst}.GetTypedInst(Handle::kInstance);
auto ii = InstanceImpl::Get(i);
@@ -203,7 +203,7 @@ void DeleteAllEntries(NT_Inst inst) {
ii->storage.DeleteAllEntries();
}
std::vector<EntryInfo> GetEntryInfo(NT_Inst inst, const wpi::Twine& prefix,
std::vector<EntryInfo> GetEntryInfo(NT_Inst inst, std::string_view prefix,
unsigned int types) {
int i = Handle{inst}.GetTypedInst(Handle::kInstance);
auto ii = InstanceImpl::Get(i);
@@ -236,7 +236,7 @@ EntryInfo GetEntryInfo(NT_Entry entry) {
*/
NT_EntryListener AddEntryListener(
NT_Inst inst, const wpi::Twine& prefix,
NT_Inst inst, std::string_view prefix,
std::function<void(const EntryNotification& event)> callback,
unsigned int flags) {
int i = Handle{inst}.GetTypedInst(Handle::kInstance);
@@ -288,7 +288,7 @@ void DestroyEntryListenerPoller(NT_EntryListenerPoller poller) {
}
NT_EntryListener AddPolledEntryListener(NT_EntryListenerPoller poller,
const wpi::Twine& prefix,
std::string_view prefix,
unsigned int flags) {
Handle handle{poller};
int id = handle.GetTypedIndex(Handle::kEntryListenerPoller);
@@ -494,7 +494,7 @@ bool WaitForConnectionListenerQueue(NT_Inst inst, double timeout) {
* Remote Procedure Call Functions
*/
void CreateRpc(NT_Entry entry, wpi::StringRef def,
void CreateRpc(NT_Entry entry, std::string_view def,
std::function<void(const RpcAnswer& answer)> callback) {
Handle handle{entry};
int id = handle.GetTypedIndex(Handle::kEntry);
@@ -535,7 +535,7 @@ void DestroyRpcCallPoller(NT_RpcCallPoller poller) {
ii->rpc_server.RemovePoller(id);
}
void CreatePolledRpc(NT_Entry entry, wpi::StringRef def,
void CreatePolledRpc(NT_Entry entry, std::string_view def,
NT_RpcCallPoller poller) {
Handle handle{entry};
int id = handle.GetTypedIndex(Handle::kEntry);
@@ -608,7 +608,7 @@ bool WaitForRpcCallQueue(NT_Inst inst, double timeout) {
return ii->rpc_server.WaitForQueue(timeout);
}
bool PostRpcResponse(NT_Entry entry, NT_RpcCall call, wpi::StringRef result) {
bool PostRpcResponse(NT_Entry entry, NT_RpcCall call, std::string_view result) {
Handle handle{entry};
int id = handle.GetTypedIndex(Handle::kEntry);
auto ii = InstanceImpl::Get(handle.GetInst());
@@ -628,7 +628,7 @@ bool PostRpcResponse(NT_Entry entry, NT_RpcCall call, wpi::StringRef result) {
return ii->rpc_server.PostRpcResponse(id, call_uid, result);
}
NT_RpcCall CallRpc(NT_Entry entry, wpi::StringRef params) {
NT_RpcCall CallRpc(NT_Entry entry, std::string_view params) {
Handle handle{entry};
int id = handle.GetTypedIndex(Handle::kEntry);
int i = handle.GetInst();
@@ -734,10 +734,10 @@ std::string PackRpcDefinition(const RpcDefinition& def) {
enc.WriteString(def.results[i].name);
}
return enc.ToStringRef();
return std::string{enc.ToStringView()};
}
bool UnpackRpcDefinition(wpi::StringRef packed, RpcDefinition* def) {
bool UnpackRpcDefinition(std::string_view packed, RpcDefinition* def) {
wpi::raw_mem_istream is(packed.data(), packed.size());
wpi::Logger logger;
WireDecoder dec(is, 0x0300, logger);
@@ -797,11 +797,11 @@ std::string PackRpcValues(wpi::ArrayRef<std::shared_ptr<Value>> values) {
for (auto& value : values) {
enc.WriteValue(*value);
}
return enc.ToStringRef();
return std::string{enc.ToStringView()};
}
std::vector<std::shared_ptr<Value>> UnpackRpcValues(
wpi::StringRef packed, wpi::ArrayRef<NT_Type> types) {
std::string_view packed, wpi::ArrayRef<NT_Type> types) {
wpi::raw_mem_istream is(packed.data(), packed.size());
wpi::Logger logger;
WireDecoder dec(is, 0x0300, logger);
@@ -824,7 +824,7 @@ uint64_t Now() {
* Client/Server Functions
*/
void SetNetworkIdentity(NT_Inst inst, const wpi::Twine& name) {
void SetNetworkIdentity(NT_Inst inst, std::string_view name) {
auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance));
if (!ii) {
return;
@@ -860,7 +860,7 @@ void StopLocal(NT_Inst inst) {
ii->dispatcher.Stop();
}
void StartServer(NT_Inst inst, const wpi::Twine& persist_filename,
void StartServer(NT_Inst inst, std::string_view persist_filename,
const char* listen_address, unsigned int port) {
auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance));
if (!ii) {
@@ -900,7 +900,7 @@ void StartClient(NT_Inst inst, const char* server_name, unsigned int port) {
void StartClient(
NT_Inst inst,
wpi::ArrayRef<std::pair<wpi::StringRef, unsigned int>> servers) {
wpi::ArrayRef<std::pair<std::string_view, unsigned int>> servers) {
auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance));
if (!ii) {
return;
@@ -938,8 +938,9 @@ void SetServer(NT_Inst inst, const char* server_name, unsigned int port) {
ii->dispatcher.SetServer(server_name, port);
}
void SetServer(NT_Inst inst,
wpi::ArrayRef<std::pair<wpi::StringRef, unsigned int>> servers) {
void SetServer(
NT_Inst inst,
wpi::ArrayRef<std::pair<std::string_view, unsigned int>> servers) {
auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance));
if (!ii) {
return;
@@ -1015,7 +1016,7 @@ bool IsConnected(NT_Inst inst) {
* Persistent Functions
*/
const char* SavePersistent(NT_Inst inst, const wpi::Twine& filename) {
const char* SavePersistent(NT_Inst inst, std::string_view filename) {
auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance));
if (!ii) {
return "invalid instance handle";
@@ -1025,7 +1026,7 @@ const char* SavePersistent(NT_Inst inst, const wpi::Twine& filename) {
}
const char* LoadPersistent(
NT_Inst inst, const wpi::Twine& filename,
NT_Inst inst, std::string_view filename,
std::function<void(size_t line, const char* msg)> warn) {
auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance));
if (!ii) {
@@ -1035,8 +1036,8 @@ const char* LoadPersistent(
return ii->storage.LoadPersistent(filename, warn);
}
const char* SaveEntries(NT_Inst inst, const wpi::Twine& filename,
const wpi::Twine& prefix) {
const char* SaveEntries(NT_Inst inst, std::string_view filename,
std::string_view prefix) {
auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance));
if (!ii) {
return "invalid instance handle";
@@ -1046,7 +1047,7 @@ const char* SaveEntries(NT_Inst inst, const wpi::Twine& filename,
}
const char* LoadEntries(
NT_Inst inst, const wpi::Twine& filename, const wpi::Twine& prefix,
NT_Inst inst, std::string_view filename, std::string_view prefix,
std::function<void(size_t line, const char* msg)> warn) {
auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance));
if (!ii) {

View File

@@ -12,7 +12,7 @@ extern "C" {
struct NT_String* NT_GetStringForTesting(const char* string, int* struct_size) {
struct NT_String* str =
static_cast<NT_String*>(wpi::safe_calloc(1, sizeof(NT_String)));
nt::ConvertToC(wpi::StringRef(string), str);
nt::ConvertToC(string, str);
*struct_size = sizeof(NT_String);
return str;
}
@@ -24,7 +24,7 @@ struct NT_EntryInfo* NT_GetEntryInfoForTesting(const char* name,
int* struct_size) {
struct NT_EntryInfo* entry_info =
static_cast<NT_EntryInfo*>(wpi::safe_calloc(1, sizeof(NT_EntryInfo)));
nt::ConvertToC(wpi::StringRef(name), &entry_info->name);
nt::ConvertToC(name, &entry_info->name);
entry_info->type = type;
entry_info->flags = flags;
entry_info->last_change = last_change;
@@ -42,8 +42,8 @@ struct NT_ConnectionInfo* NT_GetConnectionInfoForTesting(
uint64_t last_update, unsigned int protocol_version, int* struct_size) {
struct NT_ConnectionInfo* conn_info = static_cast<NT_ConnectionInfo*>(
wpi::safe_calloc(1, sizeof(NT_ConnectionInfo)));
nt::ConvertToC(wpi::StringRef(remote_id), &conn_info->remote_id);
nt::ConvertToC(wpi::StringRef(remote_ip), &conn_info->remote_ip);
nt::ConvertToC(remote_id, &conn_info->remote_id);
nt::ConvertToC(remote_ip, &conn_info->remote_ip);
conn_info->remote_port = remote_port;
conn_info->last_update = last_update;
conn_info->protocol_version = protocol_version;
@@ -86,7 +86,7 @@ struct NT_Value* NT_GetValueStringForTesting(uint64_t last_change,
static_cast<NT_Value*>(wpi::safe_calloc(1, sizeof(NT_Value)));
value->type = NT_STRING;
value->last_change = last_change;
nt::ConvertToC(wpi::StringRef(str), &value->data.v_string);
nt::ConvertToC(str, &value->data.v_string);
*struct_size = sizeof(NT_Value);
return value;
}
@@ -97,7 +97,7 @@ struct NT_Value* NT_GetValueRawForTesting(uint64_t last_change, const char* raw,
static_cast<NT_Value*>(wpi::safe_calloc(1, sizeof(NT_Value)));
value->type = NT_RAW;
value->last_change = last_change;
nt::ConvertToC(wpi::StringRef(raw, raw_len), &value->data.v_string);
nt::ConvertToC(std::string_view(raw, raw_len), &value->data.v_string);
*struct_size = sizeof(NT_Value);
return value;
}
@@ -164,7 +164,7 @@ static void CopyNtValue(const struct NT_Value* copy_from,
static void CopyNtString(const struct NT_String* copy_from,
struct NT_String* copy_to) {
nt::ConvertToC(wpi::StringRef(copy_from->str, copy_from->len), copy_to);
nt::ConvertToC({copy_from->str, copy_from->len}, copy_to);
}
struct NT_RpcParamDef* NT_GetRpcParamDefForTesting(const char* name,
@@ -172,7 +172,7 @@ struct NT_RpcParamDef* NT_GetRpcParamDefForTesting(const char* name,
int* struct_size) {
struct NT_RpcParamDef* def =
static_cast<NT_RpcParamDef*>(wpi::safe_calloc(1, sizeof(NT_RpcParamDef)));
nt::ConvertToC(wpi::StringRef(name), &def->name);
nt::ConvertToC(name, &def->name);
CopyNtValue(val, &def->def_value);
*struct_size = sizeof(NT_RpcParamDef);
return def;
@@ -189,7 +189,7 @@ struct NT_RpcResultDef* NT_GetRpcResultsDefForTesting(const char* name,
int* struct_size) {
struct NT_RpcResultDef* def = static_cast<NT_RpcResultDef*>(
wpi::safe_calloc(1, sizeof(NT_RpcResultDef)));
nt::ConvertToC(wpi::StringRef(name), &def->name);
nt::ConvertToC(name, &def->name);
def->type = type;
*struct_size = sizeof(NT_RpcResultDef);
return def;
@@ -207,7 +207,7 @@ struct NT_RpcDefinition* NT_GetRpcDefinitionForTesting(
struct NT_RpcDefinition* def = static_cast<NT_RpcDefinition*>(
wpi::safe_calloc(1, sizeof(NT_RpcDefinition)));
def->version = version;
nt::ConvertToC(wpi::StringRef(name), &def->name);
nt::ConvertToC(name, &def->name);
def->num_params = num_params;
def->params = static_cast<NT_RpcParamDef*>(
wpi::safe_malloc(num_params * sizeof(NT_RpcParamDef)));
@@ -234,8 +234,8 @@ struct NT_RpcAnswer* NT_GetRpcAnswerForTesting(
static_cast<NT_RpcAnswer*>(wpi::safe_calloc(1, sizeof(NT_RpcAnswer)));
info->entry = rpc_id;
info->call = call_uid;
nt::ConvertToC(wpi::StringRef(name), &info->name);
nt::ConvertToC(wpi::StringRef(params, params_len), &info->params);
nt::ConvertToC(name, &info->name);
nt::ConvertToC({params, params_len}, &info->params);
*struct_size = sizeof(NT_RpcAnswer);
return info;
}