diff --git a/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp b/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp index df408dee2a..a555984e02 100644 --- a/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp +++ b/cameraserver/multiCameraServer/src/main/native/cpp/main.cpp @@ -4,10 +4,12 @@ #include #include +#include #include #include -#include +#include +#include #include #include #include @@ -105,7 +107,7 @@ bool ReadConfig() { try { j = wpi::json::parse(is); } catch (const wpi::json::parse_error& e) { - ParseError() << "byte " << e.byte << ": " << e.what() << '\n'; + fmt::print(ParseError(), "byte {}: {}\n", e.byte, e.what()); return false; } @@ -127,10 +129,9 @@ bool ReadConfig() { if (j.count("ntmode") != 0) { try { auto str = j.at("ntmode").get(); - wpi::StringRef s(str); - if (s.equals_lower("client")) { + if (wpi::equals_lower(str, "client")) { server = false; - } else if (s.equals_lower("server")) { + } else if (wpi::equals_lower(str, "server")) { server = true; } else { ParseError() << "could not understand ntmode value '" << str << "'\n"; @@ -156,8 +157,7 @@ bool ReadConfig() { } void StartCamera(const CameraConfig& config) { - wpi::outs() << "Starting camera '" << config.name << "' on " << config.path - << '\n'; + fmt::print("Starting camera '{}' on {}\n", config.name, config.path); auto camera = frc::CameraServer::GetInstance()->StartAutomaticCapture( config.name, config.path); @@ -178,10 +178,10 @@ int main(int argc, char* argv[]) { // start NetworkTables auto ntinst = nt::NetworkTableInstance::GetDefault(); if (server) { - wpi::outs() << "Setting up NetworkTables server\n"; + std::puts("Setting up NetworkTables server"); ntinst.StartServer(); } else { - wpi::outs() << "Setting up NetworkTables client for team " << team << '\n'; + fmt::print("Setting up NetworkTables client for team {}\n", team); ntinst.StartClientTeam(team); } diff --git a/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp b/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp index 222753f991..19de47b9d0 100644 --- a/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp +++ b/cameraserver/src/main/native/cpp/cameraserver/CameraServer.cpp @@ -7,14 +7,15 @@ #include #include +#include #include #include #include #include #include +#include #include #include -#include #include "cameraserver/CameraServerShared.h" #include "ntcore_cpp.h" @@ -56,20 +57,20 @@ CameraServer* CameraServer::GetInstance() { return &(*instance); } -static wpi::StringRef MakeSourceValue(CS_Source source, - wpi::SmallVectorImpl& buf) { +static std::string_view MakeSourceValue(CS_Source source, + wpi::SmallVectorImpl& buf) { CS_Status status = 0; buf.clear(); switch (cs::GetSourceKind(source, &status)) { case CS_SOURCE_USB: { - wpi::StringRef prefix{"usb:"}; + std::string_view prefix{"usb:"}; buf.append(prefix.begin(), prefix.end()); auto path = cs::GetUsbCameraPath(source, &status); buf.append(path.begin(), path.end()); break; } case CS_SOURCE_HTTP: { - wpi::StringRef prefix{"ip:"}; + std::string_view prefix{"ip:"}; buf.append(prefix.begin(), prefix.end()); auto urls = cs::GetHttpCameraUrls(source, &status); if (!urls.empty()) { @@ -83,13 +84,11 @@ static wpi::StringRef MakeSourceValue(CS_Source source, return "unknown:"; } - return wpi::StringRef{buf.begin(), buf.size()}; + return {buf.begin(), buf.size()}; } -static std::string MakeStreamValue(const wpi::Twine& address, int port) { - return ("mjpg:http://" + address + wpi::Twine(':') + wpi::Twine(port) + - "/?action=stream") - .str(); +static std::string MakeStreamValue(std::string_view address, int port) { + return fmt::format("mjpg:http://{}:{}/?action=stream", address, port); } std::shared_ptr CameraServer::Impl::GetSourceTable( @@ -229,12 +228,8 @@ static std::string PixelFormatToString(int pixelFormat) { } static std::string VideoModeToString(const cs::VideoMode& mode) { - std::string rv; - wpi::raw_string_ostream oss{rv}; - oss << mode.width << "x" << mode.height; - oss << " " << PixelFormatToString(mode.pixelFormat) << " "; - oss << mode.fps << " fps"; - return oss.str(); + return fmt::format("{}x{} {} {} fps", mode.width, mode.height, + PixelFormatToString(mode.pixelFormat), mode.fps); } static std::vector GetSourceModeValues(int source) { @@ -248,23 +243,20 @@ static std::vector GetSourceModeValues(int source) { static void PutSourcePropertyValue(nt::NetworkTable* table, const cs::VideoEvent& event, bool isNew) { - wpi::SmallString<64> name; - wpi::SmallString<64> infoName; - if (wpi::StringRef{event.name}.startswith("raw_")) { - name = "RawProperty/"; - name += event.name; - infoName = "RawPropertyInfo/"; - infoName += event.name; + std::string_view namePrefix; + std::string_view infoPrefix; + if (wpi::starts_with(event.name, "raw_")) { + namePrefix = "RawProperty"; + infoPrefix = "RawPropertyInfo"; } else { - name = "Property/"; - name += event.name; - infoName = "PropertyInfo/"; - infoName += event.name; + namePrefix = "Property"; + infoPrefix = "PropertyInfo"; } wpi::SmallString<64> buf; CS_Status status = 0; - nt::NetworkTableEntry entry = table->GetEntry(name); + nt::NetworkTableEntry entry = + table->GetEntry(fmt::format("{}/{}", namePrefix, event.name)); switch (event.propertyKind) { case CS_PROP_BOOLEAN: if (isNew) { @@ -277,13 +269,13 @@ static void PutSourcePropertyValue(nt::NetworkTable* table, case CS_PROP_ENUM: if (isNew) { entry.SetDefaultDouble(event.value); - table->GetEntry(infoName + "/min") + table->GetEntry(fmt::format("{}/{}/min", infoPrefix, event.name)) .SetDouble(cs::GetPropertyMin(event.propertyHandle, &status)); - table->GetEntry(infoName + "/max") + table->GetEntry(fmt::format("{}/{}/max", infoPrefix, event.name)) .SetDouble(cs::GetPropertyMax(event.propertyHandle, &status)); - table->GetEntry(infoName + "/step") + table->GetEntry(fmt::format("{}/{}/step", infoPrefix, event.name)) .SetDouble(cs::GetPropertyStep(event.propertyHandle, &status)); - table->GetEntry(infoName + "/default") + table->GetEntry(fmt::format("{}/{}/default", infoPrefix, event.name)) .SetDouble(cs::GetPropertyDefault(event.propertyHandle, &status)); } else { entry.SetDouble(event.value); @@ -404,12 +396,11 @@ CameraServer::Impl::Impl() : m_nextPort(kBasePort) { case cs::VideoEvent::kSourcePropertyChoicesUpdated: { auto table = GetSourceTable(event.sourceHandle); if (table) { - wpi::SmallString<64> name{"PropertyInfo/"}; - name += event.name; - name += "/choices"; auto choices = cs::GetEnumPropertyChoices(event.propertyHandle, &status); - table->GetEntry(name).SetStringArray(choices); + table + ->GetEntry(fmt::format("PropertyInfo/{}/choices", event.name)) + .SetStringArray(choices); } break; } @@ -433,35 +424,35 @@ CameraServer::Impl::Impl() : m_nextPort(kBasePort) { // else tries to change it. wpi::SmallString<64> buf; m_tableListener = nt::NetworkTableInstance::GetDefault().AddEntryListener( - kPublishName + wpi::Twine('/'), + fmt::format("{}/", kPublishName), [=](const nt::EntryNotification& event) { - wpi::StringRef relativeKey = - event.name.substr(wpi::StringRef(kPublishName).size() + 1); + auto relativeKey = wpi::drop_front( + event.name, std::string_view{kPublishName}.size() + 1); // get source (sourceName/...) auto subKeyIndex = relativeKey.find('/'); - if (subKeyIndex == wpi::StringRef::npos) { + if (subKeyIndex == std::string_view::npos) { return; } - wpi::StringRef sourceName = relativeKey.slice(0, subKeyIndex); + auto sourceName = wpi::slice(relativeKey, 0, subKeyIndex); auto sourceIt = m_sources.find(sourceName); if (sourceIt == m_sources.end()) { return; } // get subkey - relativeKey = relativeKey.substr(subKeyIndex + 1); + relativeKey.remove_prefix(subKeyIndex + 1); // handle standard names - wpi::StringRef propName; + std::string_view propName; nt::NetworkTableEntry entry{event.entry}; if (relativeKey == "mode") { // reset to current mode entry.SetString(VideoModeToString(sourceIt->second.GetVideoMode())); return; - } else if (relativeKey.startswith("Property/")) { + } else if (wpi::starts_with(relativeKey, "Property/")) { propName = relativeKey.substr(9); - } else if (relativeKey.startswith("RawProperty/")) { + } else if (wpi::starts_with(relativeKey, "RawProperty/")) { propName = relativeKey.substr(12); } else { return; // ignore @@ -501,14 +492,14 @@ cs::UsbCamera CameraServer::StartAutomaticCapture() { } cs::UsbCamera CameraServer::StartAutomaticCapture(int dev) { - cs::UsbCamera camera{"USB Camera " + wpi::Twine(dev), dev}; + cs::UsbCamera camera{fmt::format("USB Camera {}", dev), dev}; StartAutomaticCapture(camera); auto csShared = GetCameraServerShared(); csShared->ReportUsbCamera(camera.GetHandle()); return camera; } -cs::UsbCamera CameraServer::StartAutomaticCapture(const wpi::Twine& name, +cs::UsbCamera CameraServer::StartAutomaticCapture(std::string_view name, int dev) { cs::UsbCamera camera{name, dev}; StartAutomaticCapture(camera); @@ -517,8 +508,8 @@ cs::UsbCamera CameraServer::StartAutomaticCapture(const wpi::Twine& name, return camera; } -cs::UsbCamera CameraServer::StartAutomaticCapture(const wpi::Twine& name, - const wpi::Twine& path) { +cs::UsbCamera CameraServer::StartAutomaticCapture(std::string_view name, + std::string_view path) { cs::UsbCamera camera{name, path}; StartAutomaticCapture(camera); auto csShared = GetCameraServerShared(); @@ -526,7 +517,7 @@ cs::UsbCamera CameraServer::StartAutomaticCapture(const wpi::Twine& name, return camera; } -cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& host) { +cs::AxisCamera CameraServer::AddAxisCamera(std::string_view host) { return AddAxisCamera("Axis Camera", host); } @@ -542,8 +533,8 @@ cs::AxisCamera CameraServer::AddAxisCamera(wpi::ArrayRef hosts) { return AddAxisCamera("Axis Camera", hosts); } -cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name, - const wpi::Twine& host) { +cs::AxisCamera CameraServer::AddAxisCamera(std::string_view name, + std::string_view host) { cs::AxisCamera camera{name, host}; StartAutomaticCapture(camera); auto csShared = GetCameraServerShared(); @@ -551,7 +542,7 @@ cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name, return camera; } -cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name, +cs::AxisCamera CameraServer::AddAxisCamera(std::string_view name, const char* host) { cs::AxisCamera camera{name, host}; StartAutomaticCapture(camera); @@ -560,7 +551,7 @@ cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name, return camera; } -cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name, +cs::AxisCamera CameraServer::AddAxisCamera(std::string_view name, const std::string& host) { cs::AxisCamera camera{name, host}; StartAutomaticCapture(camera); @@ -569,7 +560,7 @@ cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name, return camera; } -cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name, +cs::AxisCamera CameraServer::AddAxisCamera(std::string_view name, wpi::ArrayRef hosts) { cs::AxisCamera camera{name, hosts}; StartAutomaticCapture(camera); @@ -578,7 +569,7 @@ cs::AxisCamera CameraServer::AddAxisCamera(const wpi::Twine& name, return camera; } -cs::MjpegServer CameraServer::AddSwitchedCamera(const wpi::Twine& name) { +cs::MjpegServer CameraServer::AddSwitchedCamera(std::string_view name) { // create a dummy CvSource cs::CvSource source{name, cs::VideoMode::PixelFormat::kMJPEG, 160, 120, 30}; cs::MjpegServer server = StartAutomaticCapture(source); @@ -590,7 +581,7 @@ cs::MjpegServer CameraServer::AddSwitchedCamera(const wpi::Twine& name) { cs::MjpegServer CameraServer::StartAutomaticCapture( const cs::VideoSource& camera) { AddCamera(camera); - auto server = AddServer(wpi::Twine("serve_") + camera.GetName()); + auto server = AddServer(fmt::format("serve_{}", camera.GetName())); server.SetSource(camera); return server; } @@ -633,22 +624,20 @@ cs::CvSink CameraServer::GetVideo(const cs::VideoSource& camera) { } } - cs::CvSink newsink{name}; + cs::CvSink newsink{name.str()}; newsink.SetSource(camera); AddServer(newsink); return newsink; } -cs::CvSink CameraServer::GetVideo(const wpi::Twine& name) { - wpi::SmallString<64> nameBuf; - wpi::StringRef nameStr = name.toStringRef(nameBuf); +cs::CvSink CameraServer::GetVideo(std::string_view name) { cs::VideoSource source; { std::scoped_lock lock(m_impl->m_mutex); - auto it = m_impl->m_sources.find(nameStr); + auto it = m_impl->m_sources.find(name); if (it == m_impl->m_sources.end()) { auto csShared = GetCameraServerShared(); - csShared->SetCameraServerError("could not find camera {}", nameStr); + csShared->SetCameraServerError("could not find camera {}", name); return cs::CvSink{}; } source = it->second; @@ -656,14 +645,14 @@ cs::CvSink CameraServer::GetVideo(const wpi::Twine& name) { return GetVideo(source); } -cs::CvSource CameraServer::PutVideo(const wpi::Twine& name, int width, +cs::CvSource CameraServer::PutVideo(std::string_view name, int width, int height) { cs::CvSource source{name, cs::VideoMode::kMJPEG, width, height, 30}; StartAutomaticCapture(source); return source; } -cs::MjpegServer CameraServer::AddServer(const wpi::Twine& name) { +cs::MjpegServer CameraServer::AddServer(std::string_view name) { int port; { std::scoped_lock lock(m_impl->m_mutex); @@ -672,7 +661,7 @@ cs::MjpegServer CameraServer::AddServer(const wpi::Twine& name) { return AddServer(name, port); } -cs::MjpegServer CameraServer::AddServer(const wpi::Twine& name, int port) { +cs::MjpegServer CameraServer::AddServer(std::string_view name, int port) { cs::MjpegServer server{name, port}; AddServer(server); return server; @@ -683,14 +672,13 @@ void CameraServer::AddServer(const cs::VideoSink& server) { m_impl->m_sinks.try_emplace(server.GetName(), server); } -void CameraServer::RemoveServer(const wpi::Twine& name) { +void CameraServer::RemoveServer(std::string_view name) { std::scoped_lock lock(m_impl->m_mutex); - wpi::SmallString<64> nameBuf; - m_impl->m_sinks.erase(name.toStringRef(nameBuf)); + m_impl->m_sinks.erase(name); } cs::VideoSink CameraServer::GetServer() { - wpi::SmallString<64> name; + std::string name; { std::scoped_lock lock(m_impl->m_mutex); if (m_impl->m_primarySourceName.empty()) { @@ -698,20 +686,18 @@ cs::VideoSink CameraServer::GetServer() { csShared->SetCameraServerError("no camera available"); return cs::VideoSink{}; } - name = "serve_"; - name += m_impl->m_primarySourceName; + name = fmt::format("serve_{}", m_impl->m_primarySourceName); } return GetServer(name); } -cs::VideoSink CameraServer::GetServer(const wpi::Twine& name) { +cs::VideoSink CameraServer::GetServer(std::string_view name) { wpi::SmallString<64> nameBuf; - wpi::StringRef nameStr = name.toStringRef(nameBuf); std::scoped_lock lock(m_impl->m_mutex); - auto it = m_impl->m_sinks.find(nameStr); + auto it = m_impl->m_sinks.find(name); if (it == m_impl->m_sinks.end()) { auto csShared = GetCameraServerShared(); - csShared->SetCameraServerError("could not find server {}", nameStr); + csShared->SetCameraServerError("could not find server {}", name); return cs::VideoSink{}; } return it->second; @@ -726,10 +712,9 @@ void CameraServer::AddCamera(const cs::VideoSource& camera) { m_impl->m_sources.try_emplace(name, camera); } -void CameraServer::RemoveCamera(const wpi::Twine& name) { +void CameraServer::RemoveCamera(std::string_view name) { std::scoped_lock lock(m_impl->m_mutex); - wpi::SmallString<64> nameBuf; - m_impl->m_sources.erase(name.toStringRef(nameBuf)); + m_impl->m_sources.erase(name); } void CameraServer::SetSize(int size) { diff --git a/cameraserver/src/main/native/include/cameraserver/CameraServer.h b/cameraserver/src/main/native/include/cameraserver/CameraServer.h index ce620ed1b8..e5ce45766f 100644 --- a/cameraserver/src/main/native/include/cameraserver/CameraServer.h +++ b/cameraserver/src/main/native/include/cameraserver/CameraServer.h @@ -8,9 +8,9 @@ #include #include +#include #include -#include #include "cscore.h" #include "cscore_cv.h" @@ -63,7 +63,7 @@ class CameraServer { * @param name The name to give the camera * @param dev The device number of the camera interface */ - cs::UsbCamera StartAutomaticCapture(const wpi::Twine& name, int dev); + cs::UsbCamera StartAutomaticCapture(std::string_view name, int dev); /** * Start automatically capturing images to send to the dashboard. @@ -71,8 +71,8 @@ class CameraServer { * @param name The name to give the camera * @param path The device path (e.g. "/dev/video0") of the camera */ - cs::UsbCamera StartAutomaticCapture(const wpi::Twine& name, - const wpi::Twine& path); + cs::UsbCamera StartAutomaticCapture(std::string_view name, + std::string_view path); /** * Start automatically capturing images to send to the dashboard from @@ -89,7 +89,7 @@ class CameraServer { * * @param host Camera host IP or DNS name (e.g. "10.x.y.11") */ - cs::AxisCamera AddAxisCamera(const wpi::Twine& host); + cs::AxisCamera AddAxisCamera(std::string_view host); /** * Adds an Axis IP camera. @@ -134,7 +134,7 @@ class CameraServer { * @param name The name to give the camera * @param host Camera host IP or DNS name (e.g. "10.x.y.11") */ - cs::AxisCamera AddAxisCamera(const wpi::Twine& name, const wpi::Twine& host); + cs::AxisCamera AddAxisCamera(std::string_view name, std::string_view host); /** * Adds an Axis IP camera. @@ -142,7 +142,7 @@ class CameraServer { * @param name The name to give the camera * @param host Camera host IP or DNS name (e.g. "10.x.y.11") */ - cs::AxisCamera AddAxisCamera(const wpi::Twine& name, const char* host); + cs::AxisCamera AddAxisCamera(std::string_view name, const char* host); /** * Adds an Axis IP camera. @@ -150,7 +150,7 @@ class CameraServer { * @param name The name to give the camera * @param host Camera host IP or DNS name (e.g. "10.x.y.11") */ - cs::AxisCamera AddAxisCamera(const wpi::Twine& name, const std::string& host); + cs::AxisCamera AddAxisCamera(std::string_view name, const std::string& host); /** * Adds an Axis IP camera. @@ -158,7 +158,7 @@ class CameraServer { * @param name The name to give the camera * @param hosts Array of Camera host IPs/DNS names */ - cs::AxisCamera AddAxisCamera(const wpi::Twine& name, + cs::AxisCamera AddAxisCamera(std::string_view name, wpi::ArrayRef hosts); /** @@ -168,7 +168,7 @@ class CameraServer { * @param hosts Array of Camera host IPs/DNS names */ template - cs::AxisCamera AddAxisCamera(const wpi::Twine& name, + cs::AxisCamera AddAxisCamera(std::string_view name, std::initializer_list hosts); /** @@ -177,7 +177,7 @@ class CameraServer { * VideoSource. Calling SetSource() on the returned object can be used * to switch the actual source of the stream. */ - cs::MjpegServer AddSwitchedCamera(const wpi::Twine& name); + cs::MjpegServer AddSwitchedCamera(std::string_view name); /** * Get OpenCV access to the primary camera feed. This allows you to @@ -202,7 +202,7 @@ class CameraServer { * * @param name Camera name */ - cs::CvSink GetVideo(const wpi::Twine& name); + cs::CvSink GetVideo(std::string_view name); /** * Create a MJPEG stream with OpenCV input. This can be called to pass custom @@ -212,21 +212,21 @@ class CameraServer { * @param width Width of the image being sent * @param height Height of the image being sent */ - cs::CvSource PutVideo(const wpi::Twine& name, int width, int height); + cs::CvSource PutVideo(std::string_view name, int width, int height); /** * Adds a MJPEG server at the next available port. * * @param name Server name */ - cs::MjpegServer AddServer(const wpi::Twine& name); + cs::MjpegServer AddServer(std::string_view name); /** * Adds a MJPEG server. * * @param name Server name */ - cs::MjpegServer AddServer(const wpi::Twine& name, int port); + cs::MjpegServer AddServer(std::string_view name, int port); /** * Adds an already created server. @@ -240,7 +240,7 @@ class CameraServer { * * @param name Server name */ - void RemoveServer(const wpi::Twine& name); + void RemoveServer(std::string_view name); /** * Get server for the primary camera feed. @@ -255,7 +255,7 @@ class CameraServer { * * @param name Server name */ - cs::VideoSink GetServer(const wpi::Twine& name); + cs::VideoSink GetServer(std::string_view name); /** * Adds an already created camera. @@ -269,7 +269,7 @@ class CameraServer { * * @param name Camera name */ - void RemoveCamera(const wpi::Twine& name); + void RemoveCamera(std::string_view name); /** * Sets the size of the image to use. Use the public kSize constants to set diff --git a/cameraserver/src/main/native/include/cameraserver/CameraServer.inc b/cameraserver/src/main/native/include/cameraserver/CameraServer.inc index bdd35508ed..8c8ec21cf9 100644 --- a/cameraserver/src/main/native/include/cameraserver/CameraServer.inc +++ b/cameraserver/src/main/native/include/cameraserver/CameraServer.inc @@ -19,7 +19,7 @@ inline cs::AxisCamera CameraServer::AddAxisCamera( template inline cs::AxisCamera CameraServer::AddAxisCamera( - const wpi::Twine& name, std::initializer_list hosts) { + std::string_view name, std::initializer_list hosts) { std::vector vec; vec.reserve(hosts.size()); for (const auto& host : hosts) { diff --git a/cmake/scripts/GenResource.cmake b/cmake/scripts/GenResource.cmake index d28e5648e3..3c6e2515e2 100644 --- a/cmake/scripts/GenResource.cmake +++ b/cmake/scripts/GenResource.cmake @@ -7,7 +7,7 @@ GET_FILENAME_COMPONENT(inputBase ${input} NAME) STRING(REGEX REPLACE "[^a-zA-Z0-9]" "_" funcName "${inputBase}") SET(funcName "GetResource_${funcName}") -FILE(WRITE "${output}" "#include \n#include \nextern \"C\" {\nstatic const unsigned char contents[] = {") +FILE(WRITE "${output}" "#include \n#include \nextern \"C\" {\nstatic const unsigned char contents[] = {") STRING(REGEX MATCHALL ".." outputData "${fileHex}") STRING(REGEX REPLACE ";" ", 0x" outputData "${outputData}") @@ -17,7 +17,7 @@ FILE(APPEND "${output}" "const unsigned char* ${prefix}${funcName}(size_t* len) IF(NOT namespace STREQUAL "") FILE(APPEND "${output}" "namespace ${namespace} {\n") ENDIF() -FILE(APPEND "${output}" "wpi::StringRef ${funcName}() {\n return wpi::StringRef(reinterpret_cast(contents), ${fileSize});\n}\n") +FILE(APPEND "${output}" "std::string_view ${funcName}() {\n return std::string_view(reinterpret_cast(contents), ${fileSize});\n}\n") IF(NOT namespace STREQUAL "") FILE(APPEND "${output}" "}\n") ENDIF() diff --git a/cscore/.styleguide b/cscore/.styleguide index fada841611..f0732e1bf8 100644 --- a/cscore/.styleguide +++ b/cscore/.styleguide @@ -31,6 +31,7 @@ repoRootNameOverride { } includeOtherLibs { + ^fmt/ ^opencv2/ ^support/ ^tcpsockets/ diff --git a/cscore/examples/enum_usb/enum_usb.cpp b/cscore/examples/enum_usb/enum_usb.cpp index a5b7a10702..e9c1225a8c 100644 --- a/cscore/examples/enum_usb/enum_usb.cpp +++ b/cscore/examples/enum_usb/enum_usb.cpp @@ -2,83 +2,77 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. -#include -#include +#include + +#include #include "cscore.h" int main() { CS_Status status = 0; - wpi::SmallString<64> buf; for (const auto& caminfo : cs::EnumerateUsbCameras(&status)) { - wpi::outs() << caminfo.dev << ": " << caminfo.path << " (" << caminfo.name - << ")\n"; + fmt::print("{}: {} ({})\n", caminfo.dev, caminfo.path, caminfo.name); if (!caminfo.otherPaths.empty()) { - wpi::outs() << "Other device paths:\n"; + std::puts("Other device paths:"); for (auto&& path : caminfo.otherPaths) { - wpi::outs() << " " << path << '\n'; + fmt::print(" {}\n", path); } } cs::UsbCamera camera{"usbcam", caminfo.dev}; - wpi::outs() << "Properties:\n"; + std::puts("Properties:"); for (const auto& prop : camera.EnumerateProperties()) { - wpi::outs() << " " << prop.GetName(); + fmt::print(" {}", prop.GetName()); switch (prop.GetKind()) { case cs::VideoProperty::kBoolean: - wpi::outs() << " (bool): " - << "value=" << prop.Get() - << " default=" << prop.GetDefault(); + fmt::print(" (bool): value={} default={}", prop.Get(), + prop.GetDefault()); break; case cs::VideoProperty::kInteger: - wpi::outs() << " (int): " - << "value=" << prop.Get() << " min=" << prop.GetMin() - << " max=" << prop.GetMax() << " step=" << prop.GetStep() - << " default=" << prop.GetDefault(); + fmt::print(" (int): value={} min={} max={} step={} default={}", + prop.Get(), prop.GetMin(), prop.GetMax(), prop.GetStep(), + prop.GetDefault()); break; case cs::VideoProperty::kString: - wpi::outs() << " (string): " << prop.GetString(buf); + fmt::print(" (string): {}", prop.GetString()); break; case cs::VideoProperty::kEnum: { - wpi::outs() << " (enum): " - << "value=" << prop.Get(); + fmt::print(" (enum): value={}", prop.Get()); auto choices = prop.GetChoices(); for (size_t i = 0; i < choices.size(); ++i) { - if (choices[i].empty()) { - continue; + if (!choices[i].empty()) { + fmt::print("\n {}: {}", i, choices[i]); } - wpi::outs() << "\n " << i << ": " << choices[i]; } break; } default: break; } - wpi::outs() << '\n'; + std::fputc('\n', stdout); } - wpi::outs() << "Video Modes:\n"; + std::puts("Video Modes:"); for (const auto& mode : camera.EnumerateVideoModes()) { - wpi::outs() << " PixelFormat:"; + const char* pixelFormat; switch (mode.pixelFormat) { case cs::VideoMode::kMJPEG: - wpi::outs() << "MJPEG"; + pixelFormat = "MJPEG"; break; case cs::VideoMode::kYUYV: - wpi::outs() << "YUYV"; + pixelFormat = "YUYV"; break; case cs::VideoMode::kRGB565: - wpi::outs() << "RGB565"; + pixelFormat = "RGB565"; break; default: - wpi::outs() << "Unknown"; + pixelFormat = "Unknown"; break; } - wpi::outs() << " Width:" << mode.width; - wpi::outs() << " Height:" << mode.height; - wpi::outs() << " FPS:" << mode.fps << '\n'; + fmt::print(" PixelFormat:{} Width:{} Height:{} FPS:{}\n", pixelFormat, + mode.width, mode.height, mode.fps); } } } diff --git a/cscore/examples/settings/settings.cpp b/cscore/examples/settings/settings.cpp index 7681d17121..40961b45ea 100644 --- a/cscore/examples/settings/settings.cpp +++ b/cscore/examples/settings/settings.cpp @@ -3,23 +3,27 @@ // the WPILib BSD license file in the root directory of this project. #include +#include #include -#include -#include +#include +#include #include "cscore.h" int main(int argc, char** argv) { if (argc < 2) { - wpi::errs() << "Usage: settings camera [prop val] ... -- [prop val]...\n"; - wpi::errs() << " Example: settings 1 brightness 30 raw_contrast 10\n"; + std::fputs("Usage: settings camera [prop val] ... -- [prop val]...\n", + stderr); + std::fputs(" Example: settings 1 brightness 30 raw_contrast 10\n", stderr); return 1; } int id; - if (wpi::StringRef{argv[1]}.getAsInteger(10, id)) { - wpi::errs() << "Expected number for camera\n"; + if (auto v = wpi::parse_integer(argv[1], 10)) { + id = v.value(); + } else { + std::fputs("Expected number for camera\n", stderr); return 2; } @@ -27,22 +31,21 @@ int main(int argc, char** argv) { // Set prior to connect int arg = 2; - wpi::StringRef propName; - for (; arg < argc && wpi::StringRef{argv[arg]} != "--"; ++arg) { + std::string_view propName; + for (; arg < argc && std::string_view{argv[arg]} != "--"; ++arg) { if (propName.empty()) { propName = argv[arg]; } else { - wpi::StringRef propVal{argv[arg]}; - int intVal; - if (propVal.getAsInteger(10, intVal)) { - camera.GetProperty(propName).SetString(propVal); + std::string_view propVal{argv[arg]}; + if (auto v = wpi::parse_integer(propVal, 10)) { + camera.GetProperty(propName).Set(v.value()); } else { - camera.GetProperty(propName).Set(intVal); + camera.GetProperty(propName).SetString(propVal); } - propName = wpi::StringRef{}; + propName = {}; } } - if (arg < argc && wpi::StringRef{argv[arg]} == "--") { + if (arg < argc && std::string_view{argv[arg]} == "--") { ++arg; } @@ -52,57 +55,51 @@ int main(int argc, char** argv) { } // Set rest - propName = wpi::StringRef{}; + propName = {}; for (; arg < argc; ++arg) { if (propName.empty()) { propName = argv[arg]; } else { - wpi::StringRef propVal{argv[arg]}; - int intVal; - if (propVal.getAsInteger(10, intVal)) { - camera.GetProperty(propName).SetString(propVal); + std::string_view propVal{argv[arg]}; + if (auto v = wpi::parse_integer(propVal, 10)) { + camera.GetProperty(propName).Set(v.value()); } else { - camera.GetProperty(propName).Set(intVal); + camera.GetProperty(propName).SetString(propVal); } - propName = wpi::StringRef{}; + propName = {}; } } // Print settings - wpi::SmallString<64> buf; - wpi::outs() << "Properties:\n"; + std::puts("Properties:"); for (const auto& prop : camera.EnumerateProperties()) { - wpi::outs() << " " << prop.GetName(); + fmt::print(" {}", prop.GetName()); switch (prop.GetKind()) { case cs::VideoProperty::kBoolean: - wpi::outs() << " (bool): " - << "value=" << prop.Get() - << " default=" << prop.GetDefault(); + fmt::print(" (bool): value={} default={}", prop.Get(), + prop.GetDefault()); break; case cs::VideoProperty::kInteger: - wpi::outs() << " (int): " - << "value=" << prop.Get() << " min=" << prop.GetMin() - << " max=" << prop.GetMax() << " step=" << prop.GetStep() - << " default=" << prop.GetDefault(); + fmt::print(" (int): value={} min={} max={} step={} default={}", + prop.Get(), prop.GetMin(), prop.GetMax(), prop.GetStep(), + prop.GetDefault()); break; case cs::VideoProperty::kString: - wpi::outs() << " (string): " << prop.GetString(buf); + fmt::print(" (string): {}", prop.GetString()); break; case cs::VideoProperty::kEnum: { - wpi::outs() << " (enum): " - << "value=" << prop.Get(); + fmt::print(" (enum): value={}", prop.Get()); auto choices = prop.GetChoices(); for (size_t i = 0; i < choices.size(); ++i) { - if (choices[i].empty()) { - continue; + if (!choices[i].empty()) { + fmt::print("\n {}: {}", i, choices[i]); } - wpi::outs() << "\n " << i << ": " << choices[i]; } break; } default: break; } - wpi::outs() << '\n'; + std::fputc('\n', stdout); } } diff --git a/cscore/examples/usbstream/usbstream.cpp b/cscore/examples/usbstream/usbstream.cpp index f4a612e1e2..7a57e8d9a3 100644 --- a/cscore/examples/usbstream/usbstream.cpp +++ b/cscore/examples/usbstream/usbstream.cpp @@ -4,15 +4,15 @@ #include -#include +#include #include "cscore.h" int main() { - wpi::outs() << "hostname: " << cs::GetHostname() << '\n'; - wpi::outs() << "IPv4 network addresses:\n"; + fmt::print("hostname: {}\n", cs::GetHostname()); + std::puts("IPv4 network addresses:"); for (const auto& addr : cs::GetNetworkInterfaces()) { - wpi::outs() << " " << addr << '\n'; + fmt::print(" {}\n", addr); } cs::UsbCamera camera{"usbcam", 0}; camera.SetVideoMode(cs::VideoMode::kMJPEG, 320, 240, 30); @@ -22,9 +22,8 @@ int main() { CS_Status status = 0; cs::AddListener( [&](const cs::RawEvent& event) { - wpi::outs() << "FPS=" << camera.GetActualFPS() - << " MBPS=" << (camera.GetActualDataRate() / 1000000.0) - << '\n'; + fmt::print("FPS={} MBPS={}\n", camera.GetActualFPS(), + (camera.GetActualDataRate() / 1000000.0)); }, cs::RawEvent::kTelemetryUpdated, false, &status); cs::SetTelemetryPeriod(1.0); diff --git a/cscore/examples/usbviewer/usbviewer.cpp b/cscore/examples/usbviewer/usbviewer.cpp index 1b2ef5d44e..5c2e7c94c4 100644 --- a/cscore/examples/usbviewer/usbviewer.cpp +++ b/cscore/examples/usbviewer/usbviewer.cpp @@ -6,12 +6,13 @@ #include #include +#include + #define IMGUI_DEFINE_MATH_OPERATORS #include #include #include #include -#include #include #include @@ -38,7 +39,7 @@ int main() { // get frame from camera uint64_t time = cvsink.GrabFrame(frame); if (time == 0) { - wpi::outs() << "error: " << cvsink.GetError() << '\n'; + fmt::print("error: {}\n", cvsink.GetError()); continue; } diff --git a/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp b/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp index 6dedd33494..78cd988640 100644 --- a/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp +++ b/cscore/src/main/native/cpp/ConfigurableSourceImpl.cpp @@ -13,7 +13,7 @@ using namespace cs; -ConfigurableSourceImpl::ConfigurableSourceImpl(const wpi::Twine& name, +ConfigurableSourceImpl::ConfigurableSourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, @@ -50,11 +50,11 @@ void ConfigurableSourceImpl::NumSinksEnabledChanged() { // ignore } -void ConfigurableSourceImpl::NotifyError(const wpi::Twine& msg) { +void ConfigurableSourceImpl::NotifyError(std::string_view msg) { PutError(msg, wpi::Now()); } -int ConfigurableSourceImpl::CreateProperty(const wpi::Twine& name, +int ConfigurableSourceImpl::CreateProperty(std::string_view name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value) { @@ -75,12 +75,12 @@ int ConfigurableSourceImpl::CreateProperty(const wpi::Twine& name, value = prop.value; }); m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CREATED, name, ndx, - kind, value, wpi::Twine{}); + kind, value, {}); return ndx; } int ConfigurableSourceImpl::CreateProperty( - const wpi::Twine& name, CS_PropertyKind kind, int minimum, int maximum, + std::string_view name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value, std::function onChange) { // TODO @@ -102,5 +102,5 @@ void ConfigurableSourceImpl::SetEnumPropertyChoices( prop->enumChoices = choices; m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CHOICES_UPDATED, prop->name, property, CS_PROP_ENUM, - prop->value, wpi::Twine{}); + prop->value, {}); } diff --git a/cscore/src/main/native/cpp/ConfigurableSourceImpl.h b/cscore/src/main/native/cpp/ConfigurableSourceImpl.h index 9dcb3177fe..bfc07f903e 100644 --- a/cscore/src/main/native/cpp/ConfigurableSourceImpl.h +++ b/cscore/src/main/native/cpp/ConfigurableSourceImpl.h @@ -9,10 +9,10 @@ #include #include #include +#include #include #include -#include #include "SourceImpl.h" @@ -20,7 +20,7 @@ namespace cs { class ConfigurableSourceImpl : public SourceImpl { protected: - ConfigurableSourceImpl(const wpi::Twine& name, wpi::Logger& logger, + ConfigurableSourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, const VideoMode& mode); @@ -35,10 +35,10 @@ class ConfigurableSourceImpl : public SourceImpl { void NumSinksEnabledChanged() override; // OpenCV-specific functions - void NotifyError(const wpi::Twine& msg); - int CreateProperty(const wpi::Twine& name, CS_PropertyKind kind, int minimum, + void NotifyError(std::string_view msg); + int CreateProperty(std::string_view name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value); - int CreateProperty(const wpi::Twine& name, CS_PropertyKind kind, int minimum, + int CreateProperty(std::string_view name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value, std::function onChange); void SetEnumPropertyChoices(int property, wpi::ArrayRef choices, diff --git a/cscore/src/main/native/cpp/CvSinkImpl.cpp b/cscore/src/main/native/cpp/CvSinkImpl.cpp index 8154b4b4f6..dbda6c61e7 100644 --- a/cscore/src/main/native/cpp/CvSinkImpl.cpp +++ b/cscore/src/main/native/cpp/CvSinkImpl.cpp @@ -18,14 +18,14 @@ using namespace cs; -CvSinkImpl::CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger, +CvSinkImpl::CvSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry) : SinkImpl{name, logger, notifier, telemetry} { m_active = true; // m_thread = std::thread(&CvSinkImpl::ThreadMain, this); } -CvSinkImpl::CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger, +CvSinkImpl::CvSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, std::function processFrame) : SinkImpl{name, logger, notifier, telemetry} {} @@ -110,7 +110,7 @@ void CvSinkImpl::ThreadMain() { std::this_thread::sleep_for(std::chrono::seconds(1)); continue; } - SDEBUG4("waiting for frame"); + SDEBUG4("{}", "waiting for frame"); Frame frame = source->GetNextFrame(); // blocks if (!m_active) { break; @@ -127,14 +127,14 @@ void CvSinkImpl::ThreadMain() { namespace cs { -CS_Sink CreateCvSink(const wpi::Twine& name, CS_Status* status) { +CS_Sink CreateCvSink(std::string_view name, CS_Status* status) { auto& inst = Instance::GetInstance(); return inst.CreateSink( CS_SINK_CV, std::make_shared(name, inst.logger, inst.notifier, inst.telemetry)); } -CS_Sink CreateCvSinkCallback(const wpi::Twine& name, +CS_Sink CreateCvSinkCallback(std::string_view name, std::function processFrame, CS_Status* status) { auto& inst = Instance::GetInstance(); @@ -145,7 +145,7 @@ CS_Sink CreateCvSinkCallback(const wpi::Twine& name, static constexpr unsigned SinkMask = CS_SINK_CV | CS_SINK_RAW; -void SetSinkDescription(CS_Sink sink, const wpi::Twine& description, +void SetSinkDescription(CS_Sink sink, std::string_view description, CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data || (data->kind & SinkMask) == 0) { @@ -183,12 +183,12 @@ std::string GetSinkError(CS_Sink sink, CS_Status* status) { return static_cast(*data->sink).GetError(); } -wpi::StringRef GetSinkError(CS_Sink sink, wpi::SmallVectorImpl& buf, - CS_Status* status) { +std::string_view GetSinkError(CS_Sink sink, wpi::SmallVectorImpl& buf, + CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data || (data->kind & SinkMask) == 0) { *status = CS_INVALID_HANDLE; - return wpi::StringRef{}; + return {}; } return static_cast(*data->sink).GetError(buf); } diff --git a/cscore/src/main/native/cpp/CvSinkImpl.h b/cscore/src/main/native/cpp/CvSinkImpl.h index b07cf7c530..ad63a20f1a 100644 --- a/cscore/src/main/native/cpp/CvSinkImpl.h +++ b/cscore/src/main/native/cpp/CvSinkImpl.h @@ -9,10 +9,10 @@ #include #include +#include #include #include -#include #include #include "Frame.h" @@ -24,9 +24,9 @@ class SourceImpl; class CvSinkImpl : public SinkImpl { public: - CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, + CvSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry); - CvSinkImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, + CvSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, std::function processFrame); ~CvSinkImpl() override; diff --git a/cscore/src/main/native/cpp/CvSourceImpl.cpp b/cscore/src/main/native/cpp/CvSourceImpl.cpp index fa95f4400c..d05d89af70 100644 --- a/cscore/src/main/native/cpp/CvSourceImpl.cpp +++ b/cscore/src/main/native/cpp/CvSourceImpl.cpp @@ -19,7 +19,7 @@ using namespace cs; -CvSourceImpl::CvSourceImpl(const wpi::Twine& name, wpi::Logger& logger, +CvSourceImpl::CvSourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, const VideoMode& mode) : ConfigurableSourceImpl{name, logger, notifier, telemetry, mode} {} @@ -53,8 +53,7 @@ void CvSourceImpl::PutFrame(cv::Mat& image) { cv::cvtColor(finalImage, dest->AsMat(), cv::COLOR_BGRA2BGR); break; default: - SERROR("PutFrame: " << image.channels() - << "-channel images not supported"); + SERROR("PutFrame: {}-channel images not supported", image.channels()); return; } SourceImpl::PutFrame(std::move(dest), wpi::Now()); @@ -62,7 +61,7 @@ void CvSourceImpl::PutFrame(cv::Mat& image) { namespace cs { -CS_Source CreateCvSource(const wpi::Twine& name, const VideoMode& mode, +CS_Source CreateCvSource(std::string_view name, const VideoMode& mode, CS_Status* status) { auto& inst = Instance::GetInstance(); return inst.CreateSource(CS_SOURCE_CV, std::make_shared( @@ -81,7 +80,7 @@ void PutSourceFrame(CS_Source source, cv::Mat& image, CS_Status* status) { static constexpr unsigned SourceMask = CS_SINK_CV | CS_SINK_RAW; -void NotifySourceError(CS_Source source, const wpi::Twine& msg, +void NotifySourceError(CS_Source source, std::string_view msg, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data || (data->kind & SourceMask) == 0) { @@ -100,7 +99,7 @@ void SetSourceConnected(CS_Source source, bool connected, CS_Status* status) { static_cast(*data->source).SetConnected(connected); } -void SetSourceDescription(CS_Source source, const wpi::Twine& description, +void SetSourceDescription(CS_Source source, std::string_view description, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data || (data->kind & SourceMask) == 0) { @@ -110,7 +109,7 @@ void SetSourceDescription(CS_Source source, const wpi::Twine& description, static_cast(*data->source).SetDescription(description); } -CS_Property CreateSourceProperty(CS_Source source, const wpi::Twine& name, +CS_Property CreateSourceProperty(CS_Source source, std::string_view name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value, CS_Status* status) { @@ -126,7 +125,7 @@ CS_Property CreateSourceProperty(CS_Source source, const wpi::Twine& name, } CS_Property CreateSourcePropertyCallback( - CS_Source source, const wpi::Twine& name, CS_PropertyKind kind, int minimum, + CS_Source source, std::string_view name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value, std::function onChange, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); diff --git a/cscore/src/main/native/cpp/CvSourceImpl.h b/cscore/src/main/native/cpp/CvSourceImpl.h index dc9bcb3ca5..1956fbe56d 100644 --- a/cscore/src/main/native/cpp/CvSourceImpl.h +++ b/cscore/src/main/native/cpp/CvSourceImpl.h @@ -9,11 +9,11 @@ #include #include #include +#include #include #include #include -#include #include "ConfigurableSourceImpl.h" #include "SourceImpl.h" @@ -22,7 +22,7 @@ namespace cs { class CvSourceImpl : public ConfigurableSourceImpl { public: - CvSourceImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, + CvSourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, const VideoMode& mode); ~CvSourceImpl() override; diff --git a/cscore/src/main/native/cpp/Frame.cpp b/cscore/src/main/native/cpp/Frame.cpp index 71bd446206..0aa1947f00 100644 --- a/cscore/src/main/native/cpp/Frame.cpp +++ b/cscore/src/main/native/cpp/Frame.cpp @@ -16,10 +16,10 @@ using namespace cs; -Frame::Frame(SourceImpl& source, const wpi::Twine& error, Time time) +Frame::Frame(SourceImpl& source, std::string_view error, Time time) : m_impl{source.AllocFrameImpl().release()} { m_impl->refcount = 1; - m_impl->error = error.str(); + m_impl->error = error; m_impl->time = time; } @@ -522,10 +522,8 @@ Image* Frame::GetImageImpl(int width, int height, } WPI_DEBUG4(Instance::GetInstance().logger, - "converting image from " << cur->width << "x" << cur->height - << " type " << cur->pixelFormat << " to " - << width << "x" << height << " type " - << pixelFormat); + "converting image from {}x{} type {} to {}x{} type {}", cur->width, + cur->height, cur->pixelFormat, width, height, pixelFormat); // If the source image is a JPEG, we need to decode it before we can do // anything else with it. Note that if the destination format is JPEG, we diff --git a/cscore/src/main/native/cpp/Frame.h b/cscore/src/main/native/cpp/Frame.h index 3177d2625c..9a16824021 100644 --- a/cscore/src/main/native/cpp/Frame.h +++ b/cscore/src/main/native/cpp/Frame.h @@ -8,11 +8,11 @@ #include #include #include +#include #include #include #include -#include #include #include "Image.h" @@ -44,7 +44,7 @@ class Frame { public: Frame() noexcept = default; - Frame(SourceImpl& source, const wpi::Twine& error, Time time); + Frame(SourceImpl& source, std::string_view error, Time time); Frame(SourceImpl& source, std::unique_ptr image, Time time); @@ -72,7 +72,7 @@ class Frame { Time GetTime() const { return m_impl ? m_impl->time : 0; } - wpi::StringRef GetError() const { + std::string_view GetError() const { if (!m_impl) { return {}; } diff --git a/cscore/src/main/native/cpp/HttpCameraImpl.cpp b/cscore/src/main/native/cpp/HttpCameraImpl.cpp index 3d1c64883b..5cbe9436d6 100644 --- a/cscore/src/main/native/cpp/HttpCameraImpl.cpp +++ b/cscore/src/main/native/cpp/HttpCameraImpl.cpp @@ -5,6 +5,7 @@ #include "HttpCameraImpl.h" #include +#include #include #include @@ -18,7 +19,7 @@ using namespace cs; -HttpCameraImpl::HttpCameraImpl(const wpi::Twine& name, CS_HttpCameraKind kind, +HttpCameraImpl::HttpCameraImpl(std::string_view name, CS_HttpCameraKind kind, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry) : SourceImpl{name, logger, notifier, telemetry}, m_kind{kind} {} @@ -84,7 +85,7 @@ void HttpCameraImpl::MonitorThreadMain() { // (this will result in an error at the read point, and ultimately // a reconnect attempt) if (m_streamConn && m_frameCount == 0) { - SWARNING("Monitor detected stream hung, disconnecting"); + SWARNING("{}", "Monitor detected stream hung, disconnecting"); m_streamConn->stream->close(); } @@ -92,7 +93,7 @@ void HttpCameraImpl::MonitorThreadMain() { m_frameCount = 0; } - SDEBUG("Monitor Thread exiting"); + SDEBUG("{}", "Monitor Thread exiting"); } void HttpCameraImpl::StreamThreadMain() { @@ -132,14 +133,14 @@ void HttpCameraImpl::StreamThreadMain() { SetConnected(true); // stream - DeviceStream(conn->is, boundary); + DeviceStream(conn->is, boundary.str()); { std::unique_lock lock(m_mutex); m_streamConn = nullptr; } } - SDEBUG("Camera Thread exiting"); + SDEBUG("{}", "Camera Thread exiting"); SetConnected(false); } @@ -150,7 +151,7 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( { std::scoped_lock lock(m_mutex); if (m_locations.empty()) { - SERROR("locations array is empty!?"); + SERROR("{}", "locations array is empty!?"); std::this_thread::sleep_for(std::chrono::seconds(1)); return nullptr; } @@ -181,19 +182,17 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( std::string warn; if (!conn->Handshake(req, &warn)) { - SWARNING(GetName() << ": " << warn); + SWARNING("{}", warn); std::scoped_lock lock(m_mutex); m_streamConn = nullptr; return nullptr; } // Parse Content-Type header to get the boundary - wpi::StringRef mediaType, contentType; - std::tie(mediaType, contentType) = conn->contentType.str().split(';'); - mediaType = mediaType.trim(); + auto [mediaType, contentType] = wpi::split(conn->contentType.str(), ';'); + mediaType = wpi::trim(mediaType); if (mediaType != "multipart/x-mixed-replace") { - SWARNING("\"" << req.host << "\": unrecognized Content-Type \"" << mediaType - << "\""); + SWARNING("\"{}\": unrecognized Content-Type \"{}\"", req.host, mediaType); std::scoped_lock lock(m_mutex); m_streamConn = nullptr; return nullptr; @@ -202,14 +201,13 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( // media parameters boundary.clear(); while (!contentType.empty()) { - wpi::StringRef keyvalue; - std::tie(keyvalue, contentType) = contentType.split(';'); - contentType = contentType.ltrim(); - wpi::StringRef key, value; - std::tie(key, value) = keyvalue.split('='); - if (key.trim() == "boundary") { - value = value.trim().trim('"'); // value may be quoted - if (value.startswith("--")) { + std::string_view keyvalue; + std::tie(keyvalue, contentType) = wpi::split(contentType, ';'); + contentType = wpi::ltrim(contentType); + auto [key, value] = wpi::split(keyvalue, '='); + if (wpi::trim(key) == "boundary") { + value = wpi::trim(wpi::trim(value), '"'); // value may be quoted + if (wpi::starts_with(value, "--")) { value = value.substr(2); } boundary.append(value.begin(), value.end()); @@ -217,8 +215,7 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( } if (boundary.empty()) { - SWARNING("\"" << req.host - << "\": empty multi-part boundary or no Content-Type"); + SWARNING("\"{}\": empty multi-part boundary or no Content-Type", req.host); std::scoped_lock lock(m_mutex); m_streamConn = nullptr; return nullptr; @@ -228,7 +225,7 @@ wpi::HttpConnection* HttpCameraImpl::DeviceStreamConnect( } void HttpCameraImpl::DeviceStream(wpi::raw_istream& is, - wpi::StringRef boundary) { + std::string_view boundary) { // Stored here so we reuse it from frame to frame std::string imageBuf; @@ -275,28 +272,29 @@ bool HttpCameraImpl::DeviceStreamFrame(wpi::raw_istream& is, wpi::SmallString<64> contentTypeBuf; wpi::SmallString<64> contentLengthBuf; if (!ParseHttpHeaders(is, &contentTypeBuf, &contentLengthBuf)) { - SWARNING("disconnected during headers"); + SWARNING("{}", "disconnected during headers"); PutError("disconnected during headers", wpi::Now()); return false; } // Check the content type (if present) if (!contentTypeBuf.str().empty() && - !contentTypeBuf.str().startswith("image/jpeg")) { - wpi::SmallString<64> errBuf; - wpi::raw_svector_ostream errMsg{errBuf}; - errMsg << "received unknown Content-Type \"" << contentTypeBuf << "\""; - SWARNING(errMsg.str()); - PutError(errMsg.str(), wpi::Now()); + !wpi::starts_with(contentTypeBuf, "image/jpeg")) { + auto errMsg = + fmt::format("received unknown Content-Type \"{}\"", contentTypeBuf); + SWARNING("{}", errMsg); + PutError(errMsg, wpi::Now()); return false; } unsigned int contentLength = 0; - if (contentLengthBuf.str().getAsInteger(10, contentLength)) { + if (auto v = wpi::parse_integer(contentLengthBuf, 10)) { + contentLength = v.value(); + } else { // Ugh, no Content-Length? Read the blocks of the JPEG file. int width, height; if (!ReadJpeg(is, imageBuf, &width, &height)) { - SWARNING("did not receive a JPEG image"); + SWARNING("{}", "did not receive a JPEG image"); PutError("did not receive a JPEG image", wpi::Now()); return false; } @@ -315,7 +313,7 @@ bool HttpCameraImpl::DeviceStreamFrame(wpi::raw_istream& is, } int width, height; if (!GetJpegSize(image->str(), &width, &height)) { - SWARNING("did not receive a JPEG image"); + SWARNING("{}", "did not receive a JPEG image"); PutError("did not receive a JPEG image", wpi::Now()); return false; } @@ -345,7 +343,7 @@ void HttpCameraImpl::SettingsThreadMain() { DeviceSendSettings(req); } - SDEBUG("Settings Thread exiting"); + SDEBUG("{}", "Settings Thread exiting"); } void HttpCameraImpl::DeviceSendSettings(wpi::HttpRequest& req) { @@ -369,7 +367,7 @@ void HttpCameraImpl::DeviceSendSettings(wpi::HttpRequest& req) { // Just need a handshake as settings are sent via GET parameters std::string warn; if (!conn->Handshake(req, &warn)) { - SWARNING(GetName() << ": " << warn); + SWARNING("{}", warn); } conn->stream->close(); @@ -388,7 +386,7 @@ bool HttpCameraImpl::SetUrls(wpi::ArrayRef urls, std::string errorMsg; locations.emplace_back(url, &error, &errorMsg); if (error) { - SERROR(GetName() << ": " << errorMsg); + SERROR("{}", errorMsg); *status = CS_BAD_URL; return false; } @@ -410,8 +408,8 @@ std::vector HttpCameraImpl::GetUrls() const { return urls; } -void HttpCameraImpl::CreateProperty(const wpi::Twine& name, - const wpi::Twine& httpParam, +void HttpCameraImpl::CreateProperty(std::string_view name, + std::string_view httpParam, bool viaSettings, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value) const { @@ -421,13 +419,12 @@ void HttpCameraImpl::CreateProperty(const wpi::Twine& name, value)); m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CREATED, name, - m_propertyData.size() + 1, kind, value, - wpi::Twine{}); + m_propertyData.size() + 1, kind, value, {}); } template void HttpCameraImpl::CreateEnumProperty( - const wpi::Twine& name, const wpi::Twine& httpParam, bool viaSettings, + std::string_view name, std::string_view httpParam, bool viaSettings, int defaultValue, int value, std::initializer_list choices) const { std::scoped_lock lock(m_mutex); m_propertyData.emplace_back(std::make_unique( @@ -442,14 +439,14 @@ void HttpCameraImpl::CreateEnumProperty( m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CREATED, name, m_propertyData.size() + 1, CS_PROP_ENUM, - value, wpi::Twine{}); + value, {}); m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CHOICES_UPDATED, name, m_propertyData.size() + 1, CS_PROP_ENUM, - value, wpi::Twine{}); + value, {}); } std::unique_ptr HttpCameraImpl::CreateEmptyProperty( - const wpi::Twine& name) const { + std::string_view name) const { return std::make_unique(name); } @@ -474,7 +471,7 @@ void HttpCameraImpl::SetProperty(int property, int value, CS_Status* status) { // TODO } -void HttpCameraImpl::SetStringProperty(int property, const wpi::Twine& value, +void HttpCameraImpl::SetStringProperty(int property, std::string_view value, CS_Status* status) { // TODO } @@ -560,7 +557,7 @@ bool AxisCameraImpl::CacheProperties(CS_Status* status) const { namespace cs { -CS_Source CreateHttpCamera(const wpi::Twine& name, const wpi::Twine& url, +CS_Source CreateHttpCamera(std::string_view name, std::string_view url, CS_HttpCameraKind kind, CS_Status* status) { auto& inst = Instance::GetInstance(); std::shared_ptr source; @@ -574,13 +571,13 @@ CS_Source CreateHttpCamera(const wpi::Twine& name, const wpi::Twine& url, inst.notifier, inst.telemetry); break; } - if (!source->SetUrls(url.str(), status)) { + if (!source->SetUrls(std::string{url}, status)) { return 0; } return inst.CreateSource(CS_SOURCE_HTTP, source); } -CS_Source CreateHttpCamera(const wpi::Twine& name, +CS_Source CreateHttpCamera(std::string_view name, wpi::ArrayRef urls, CS_HttpCameraKind kind, CS_Status* status) { auto& inst = Instance::GetInstance(); diff --git a/cscore/src/main/native/cpp/HttpCameraImpl.h b/cscore/src/main/native/cpp/HttpCameraImpl.h index 459d8fc1a6..1d375a82df 100644 --- a/cscore/src/main/native/cpp/HttpCameraImpl.h +++ b/cscore/src/main/native/cpp/HttpCameraImpl.h @@ -10,13 +10,13 @@ #include #include #include +#include #include #include #include #include #include -#include #include #include @@ -27,7 +27,7 @@ namespace cs { class HttpCameraImpl : public SourceImpl { public: - HttpCameraImpl(const wpi::Twine& name, CS_HttpCameraKind kind, + HttpCameraImpl(std::string_view name, CS_HttpCameraKind kind, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry); ~HttpCameraImpl() override; @@ -35,7 +35,7 @@ class HttpCameraImpl : public SourceImpl { // Property functions void SetProperty(int property, int value, CS_Status* status) override; - void SetStringProperty(int property, const wpi::Twine& value, + void SetStringProperty(int property, std::string_view value, CS_Status* status) override; // Standard common camera properties @@ -61,13 +61,13 @@ class HttpCameraImpl : public SourceImpl { class PropertyData : public PropertyImpl { public: PropertyData() = default; - explicit PropertyData(const wpi::Twine& name_) : PropertyImpl{name_} {} - PropertyData(const wpi::Twine& name_, const wpi::Twine& httpParam_, + explicit PropertyData(std::string_view name_) : PropertyImpl{name_} {} + PropertyData(std::string_view name_, std::string_view httpParam_, bool viaSettings_, CS_PropertyKind kind_, int minimum_, int maximum_, int step_, int defaultValue_, int value_) : PropertyImpl(name_, kind_, step_, defaultValue_, value_), viaSettings(viaSettings_), - httpParam(httpParam_.str()) { + httpParam(httpParam_) { hasMinimum = true; minimum = minimum_; hasMaximum = true; @@ -81,16 +81,16 @@ class HttpCameraImpl : public SourceImpl { protected: std::unique_ptr CreateEmptyProperty( - const wpi::Twine& name) const override; + std::string_view name) const override; bool CacheProperties(CS_Status* status) const override; - void CreateProperty(const wpi::Twine& name, const wpi::Twine& httpParam, + void CreateProperty(std::string_view name, std::string_view httpParam, bool viaSettings, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value) const; template - void CreateEnumProperty(const wpi::Twine& name, const wpi::Twine& httpParam, + void CreateEnumProperty(std::string_view name, std::string_view httpParam, bool viaSettings, int defaultValue, int value, std::initializer_list choices) const; @@ -101,7 +101,7 @@ class HttpCameraImpl : public SourceImpl { // Functions used by StreamThreadMain() wpi::HttpConnection* DeviceStreamConnect( wpi::SmallVectorImpl& boundary); - void DeviceStream(wpi::raw_istream& is, wpi::StringRef boundary); + void DeviceStream(wpi::raw_istream& is, std::string_view boundary); bool DeviceStreamFrame(wpi::raw_istream& is, std::string& imageBuf); // The camera settings thread @@ -146,12 +146,12 @@ class HttpCameraImpl : public SourceImpl { class AxisCameraImpl : public HttpCameraImpl { public: - AxisCameraImpl(const wpi::Twine& name, wpi::Logger& logger, - Notifier& notifier, Telemetry& telemetry) + AxisCameraImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, + Telemetry& telemetry) : HttpCameraImpl{name, CS_HTTP_AXIS, logger, notifier, telemetry} {} #if 0 void SetProperty(int property, int value, CS_Status* status) override; - void SetStringProperty(int property, const wpi::Twine& value, + void SetStringProperty(int property, std::string_view value, CS_Status* status) override; #endif protected: diff --git a/cscore/src/main/native/cpp/Image.h b/cscore/src/main/native/cpp/Image.h index 110bee4994..9a1579f281 100644 --- a/cscore/src/main/native/cpp/Image.h +++ b/cscore/src/main/native/cpp/Image.h @@ -5,10 +5,10 @@ #ifndef CSCORE_IMAGE_H_ #define CSCORE_IMAGE_H_ +#include #include #include -#include #include "cscore_cpp.h" #include "default_init_allocator.h" @@ -34,8 +34,8 @@ class Image { Image& operator=(const Image&) = delete; // Getters - operator wpi::StringRef() const { return str(); } // NOLINT - wpi::StringRef str() const { return wpi::StringRef(data(), size()); } + operator std::string_view() const { return str(); } // NOLINT + std::string_view str() const { return {data(), size()}; } size_t capacity() const { return m_data.capacity(); } const char* data() const { return reinterpret_cast(m_data.data()); diff --git a/cscore/src/main/native/cpp/Instance.cpp b/cscore/src/main/native/cpp/Instance.cpp index a42f7d48f2..3b81f01658 100644 --- a/cscore/src/main/native/cpp/Instance.cpp +++ b/cscore/src/main/native/cpp/Instance.cpp @@ -4,36 +4,32 @@ #include "Instance.h" -#include -#include +#include + +#include #include -#include using namespace cs; static void def_log_func(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 << "CS: " << msg << '\n'; - wpi::errs() << oss.str(); + fmt::print(stderr, "CS: {}\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 << "CS: " << levelmsg << msg << " (" << fs::path{file}.filename().string() - << ':' << line << ")\n"; - wpi::errs() << oss.str(); + fmt::print(stderr, "CS: {}: {} ({}:{})\n", levelmsg, msg, + fs::path{file}.filename().string(), line); } Instance::Instance() diff --git a/cscore/src/main/native/cpp/JpegUtil.cpp b/cscore/src/main/native/cpp/JpegUtil.cpp index 0ec9eee375..2e66338974 100644 --- a/cscore/src/main/native/cpp/JpegUtil.cpp +++ b/cscore/src/main/native/cpp/JpegUtil.cpp @@ -46,20 +46,20 @@ static const unsigned char dhtData[] = { 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa}; -bool IsJpeg(wpi::StringRef data) { +bool IsJpeg(std::string_view data) { if (data.size() < 11) { return false; } // Check for valid SOI - auto bytes = data.bytes_begin(); + auto bytes = reinterpret_cast(data.data()); if (bytes[0] != 0xff || bytes[1] != 0xd8) { return false; } return true; } -bool GetJpegSize(wpi::StringRef data, int* width, int* height) { +bool GetJpegSize(std::string_view data, int* width, int* height) { if (!IsJpeg(data)) { return false; } @@ -69,7 +69,7 @@ bool GetJpegSize(wpi::StringRef data, int* width, int* height) { if (data.size() < 4) { return false; // EOF } - auto bytes = data.bytes_begin(); + auto bytes = reinterpret_cast(data.data()); if (bytes[0] != 0xff) { return false; // not a tag } @@ -94,7 +94,7 @@ bool GetJpegSize(wpi::StringRef data, int* width, int* height) { } bool JpegNeedsDHT(const char* data, size_t* size, size_t* locSOF) { - wpi::StringRef sdata(data, *size); + std::string_view sdata(data, *size); if (!IsJpeg(sdata)) { return false; } @@ -107,7 +107,7 @@ bool JpegNeedsDHT(const char* data, size_t* size, size_t* locSOF) { if (sdata.size() < 4) { return false; // EOF } - auto bytes = sdata.bytes_begin(); + auto bytes = reinterpret_cast(sdata.data()); if (bytes[0] != 0xff) { return false; // not a tag } @@ -132,9 +132,8 @@ bool JpegNeedsDHT(const char* data, size_t* size, size_t* locSOF) { return false; } -wpi::StringRef JpegGetDHT() { - return wpi::StringRef(reinterpret_cast(dhtData), - sizeof(dhtData)); +std::string_view JpegGetDHT() { + return {reinterpret_cast(dhtData), sizeof(dhtData)}; } static inline void ReadInto(wpi::raw_istream& is, std::string& buf, diff --git a/cscore/src/main/native/cpp/JpegUtil.h b/cscore/src/main/native/cpp/JpegUtil.h index 5d68f19659..4fe0693f59 100644 --- a/cscore/src/main/native/cpp/JpegUtil.h +++ b/cscore/src/main/native/cpp/JpegUtil.h @@ -6,8 +6,7 @@ #define CSCORE_JPEGUTIL_H_ #include - -#include +#include namespace wpi { class raw_istream; @@ -15,13 +14,13 @@ class raw_istream; namespace cs { -bool IsJpeg(wpi::StringRef data); +bool IsJpeg(std::string_view data); -bool GetJpegSize(wpi::StringRef data, int* width, int* height); +bool GetJpegSize(std::string_view data, int* width, int* height); bool JpegNeedsDHT(const char* data, size_t* size, size_t* locSOF); -wpi::StringRef JpegGetDHT(); +std::string_view JpegGetDHT(); bool ReadJpeg(wpi::raw_istream& is, std::string& buf, int* width, int* height); diff --git a/cscore/src/main/native/cpp/Log.cpp b/cscore/src/main/native/cpp/Log.cpp new file mode 100644 index 0000000000..baf2e5eb98 --- /dev/null +++ b/cscore/src/main/native/cpp/Log.cpp @@ -0,0 +1,15 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "Log.h" + +void cs::NamedLogV(wpi::Logger& logger, unsigned int level, const char* file, + unsigned int line, std::string_view name, + fmt::string_view format, fmt::format_args args) { + fmt::memory_buffer out; + fmt::format_to(out, "{}: ", name); + fmt::vformat_to(out, format, args); + out.push_back('\0'); + logger.DoLog(level, file, line, out.data()); +} diff --git a/cscore/src/main/native/cpp/Log.h b/cscore/src/main/native/cpp/Log.h index c56389c75e..21becdf357 100644 --- a/cscore/src/main/native/cpp/Log.h +++ b/cscore/src/main/native/cpp/Log.h @@ -5,29 +5,71 @@ #ifndef CSCORE_LOG_H_ #define CSCORE_LOG_H_ +#include + #include -#define LOG(level, x) WPI_LOG(m_logger, level, x) +namespace cs { + +void NamedLogV(wpi::Logger& logger, unsigned int level, const char* file, + unsigned int line, std::string_view name, + fmt::string_view format, fmt::format_args args); + +template +inline void NamedLog(wpi::Logger& logger, unsigned int level, const char* file, + unsigned int line, std::string_view name, const S& format, + Args&&... args) { + if (logger.HasLogger() && level >= logger.min_level()) { + NamedLogV(logger, level, file, line, name, format, + fmt::make_args_checked(format, args...)); + } +} + +} // namespace cs + +#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__) -#define SERROR(x) ERROR(GetName() << ": " << x) -#define SWARNING(x) WARNING(GetName() << ": " << x) -#define SINFO(x) INFO(GetName() << ": " << x) +#define SLOG(level, format, ...) \ + NamedLog(m_logger, level, __FILE__, __LINE__, GetName(), FMT_STRING(format), \ + __VA_ARGS__) -#define SDEBUG(x) DEBUG0(GetName() << ": " << x) -#define SDEBUG1(x) DEBUG1(GetName() << ": " << x) -#define SDEBUG2(x) DEBUG2(GetName() << ": " << x) -#define SDEBUG3(x) DEBUG3(GetName() << ": " << x) -#define SDEBUG4(x) DEBUG4(GetName() << ": " << x) +#define SERROR(format, ...) SLOG(::wpi::WPI_LOG_ERROR, format, __VA_ARGS__) +#define SWARNING(format, ...) SLOG(::wpi::WPI_LOG_WARNING, format, __VA_ARGS__) +#define SINFO(format, ...) SLOG(::wpi::WPI_LOG_INFO, format, __VA_ARGS__) + +#ifdef NDEBUG +#define SDEBUG(format, ...) \ + do { \ + } while (0) +#define SDEBUG1(format, ...) \ + do { \ + } while (0) +#define SDEBUG2(format, ...) \ + do { \ + } while (0) +#define SDEBUG3(format, ...) \ + do { \ + } while (0) +#define SDEBUG4(format, ...) \ + do { \ + } while (0) +#else +#define SDEBUG(format, ...) SLOG(::wpi::WPI_LOG_DEBUG, format, __VA_ARGS__) +#define SDEBUG1(format, ...) SLOG(::wpi::WPI_LOG_DEBUG1, format, __VA_ARGS__) +#define SDEBUG2(format, ...) SLOG(::wpi::WPI_LOG_DEBUG2, format, __VA_ARGS__) +#define SDEBUG3(format, ...) SLOG(::wpi::WPI_LOG_DEBUG3, format, __VA_ARGS__) +#define SDEBUG4(format, ...) SLOG(::wpi::WPI_LOG_DEBUG4, format, __VA_ARGS__) +#endif #endif // CSCORE_LOG_H_ diff --git a/cscore/src/main/native/cpp/MjpegServerImpl.cpp b/cscore/src/main/native/cpp/MjpegServerImpl.cpp index 4ffded64bc..92c23fff5e 100644 --- a/cscore/src/main/native/cpp/MjpegServerImpl.cpp +++ b/cscore/src/main/native/cpp/MjpegServerImpl.cpp @@ -6,9 +6,12 @@ #include +#include #include #include +#include #include +#include #include #include @@ -72,13 +75,13 @@ static const char* endRootPage = ""; class MjpegServerImpl::ConnThread : public wpi::SafeThread { public: - explicit ConnThread(const wpi::Twine& name, wpi::Logger& logger) - : m_name(name.str()), m_logger(logger) {} + explicit ConnThread(std::string_view name, wpi::Logger& logger) + : m_name(name), m_logger(logger) {} void Main() override; bool ProcessCommand(wpi::raw_ostream& os, SourceImpl& source, - wpi::StringRef parameters, bool respond); + std::string_view parameters, bool respond); void SendJSON(wpi::raw_ostream& os, SourceImpl& source, bool header); void SendHTMLHeadTitle(wpi::raw_ostream& os) const; void SendHTML(wpi::raw_ostream& os, SourceImpl& source, bool header); @@ -99,7 +102,7 @@ class MjpegServerImpl::ConnThread : public wpi::SafeThread { std::string m_name; wpi::Logger& m_logger; - wpi::StringRef GetName() { return m_name; } + std::string_view GetName() { return m_name; } std::shared_ptr GetSource() { std::scoped_lock lock(m_mutex); @@ -130,10 +133,9 @@ class MjpegServerImpl::ConnThread : public wpi::SafeThread { // Using cached pictures would lead to showing old/outdated pictures. // Many browsers seem to ignore, or at least not always obey, those headers. static void SendHeader(wpi::raw_ostream& os, int code, - const wpi::Twine& codeText, - const wpi::Twine& contentType, - const wpi::Twine& extra = wpi::Twine{}) { - os << "HTTP/1.0 " << code << ' ' << codeText << "\r\n"; + std::string_view codeText, std::string_view contentType, + std::string_view extra = {}) { + fmt::print(os, "HTTP/1.0 {} {}\r\n", code, codeText); os << "Connection: close\r\n" "Server: CameraServer/1.0\r\n" "Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, " @@ -142,10 +144,8 @@ static void SendHeader(wpi::raw_ostream& os, int code, "Expires: Mon, 3 Jan 2000 12:34:56 GMT\r\n"; os << "Content-Type: " << contentType << "\r\n"; os << "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: *\r\n"; - wpi::SmallString<128> extraBuf; - wpi::StringRef extraStr = extra.toStringRef(extraBuf); - if (!extraStr.empty()) { - os << extraStr << "\r\n"; + if (!extra.empty()) { + os << extra << "\r\n"; } os << "\r\n"; // header ends with a blank line } @@ -154,8 +154,8 @@ static void SendHeader(wpi::raw_ostream& os, int code, // @param code HTTP error code (e.g. 404) // @param message Additional message text static void SendError(wpi::raw_ostream& os, int code, - const wpi::Twine& message) { - wpi::StringRef codeText, extra, baseMessage; + std::string_view message) { + std::string_view codeText, extra, baseMessage; switch (code) { case 401: codeText = "Unauthorized"; @@ -195,66 +195,61 @@ static void SendError(wpi::raw_ostream& os, int code, // Perform a command specified by HTTP GET parameters. bool MjpegServerImpl::ConnThread::ProcessCommand(wpi::raw_ostream& os, SourceImpl& source, - wpi::StringRef parameters, + std::string_view parameters, bool respond) { wpi::SmallString<256> responseBuf; wpi::raw_svector_ostream response{responseBuf}; // command format: param1=value1¶m2=value2... while (!parameters.empty()) { // split out next param and value - wpi::StringRef rawParam, rawValue; - std::tie(rawParam, parameters) = parameters.split('&'); + std::string_view rawParam, rawValue; + std::tie(rawParam, parameters) = wpi::split(parameters, '&'); if (rawParam.empty()) { continue; // ignore "&&" } - std::tie(rawParam, rawValue) = rawParam.split('='); + std::tie(rawParam, rawValue) = wpi::split(rawParam, '='); if (rawParam.empty() || rawValue.empty()) { continue; // ignore "param=" } - SDEBUG4("HTTP parameter \"" << rawParam << "\" value \"" << rawValue - << "\""); + SDEBUG4("HTTP parameter \"{}\" value \"{}\"", rawParam, rawValue); // unescape param bool error = false; wpi::SmallString<64> paramBuf; - wpi::StringRef param = wpi::UnescapeURI(rawParam, paramBuf, &error); + std::string_view param = wpi::UnescapeURI(rawParam, paramBuf, &error); if (error) { - wpi::SmallString<128> error; - wpi::raw_svector_ostream oss{error}; - oss << "could not unescape parameter \"" << rawParam << "\""; - SendError(os, 500, error.str()); - SDEBUG(error.str()); + auto estr = fmt::format("could not unescape parameter \"{}\"", rawParam); + SendError(os, 500, estr); + SDEBUG("{}", estr); return false; } // unescape value wpi::SmallString<64> valueBuf; - wpi::StringRef value = wpi::UnescapeURI(rawValue, valueBuf, &error); + std::string_view value = wpi::UnescapeURI(rawValue, valueBuf, &error); if (error) { - wpi::SmallString<128> error; - wpi::raw_svector_ostream oss{error}; - oss << "could not unescape value \"" << rawValue << "\""; - SendError(os, 500, error.str()); - SDEBUG(error.str()); + auto estr = fmt::format("could not unescape value \"{}\"", rawValue); + SendError(os, 500, estr); + SDEBUG("{}", estr); return false; } // Handle resolution, compression, and FPS. These are handled locally // rather than passed to the source. if (param == "resolution") { - wpi::StringRef widthStr, heightStr; - std::tie(widthStr, heightStr) = value.split('x'); - int width, height; - if (widthStr.getAsInteger(10, width)) { + auto [widthStr, heightStr] = wpi::split(value, 'x'); + int width = wpi::parse_integer(widthStr, 10).value_or(-1); + int height = wpi::parse_integer(heightStr, 10).value_or(-1); + if (width < 0) { response << param << ": \"width is not an integer\"\r\n"; - SWARNING("HTTP parameter \"" << param << "\" width \"" << widthStr - << "\" is not an integer"); + SWARNING("HTTP parameter \"{}\" width \"{}\" is not an integer", param, + widthStr); continue; } - if (heightStr.getAsInteger(10, height)) { + if (height < 0) { response << param << ": \"height is not an integer\"\r\n"; - SWARNING("HTTP parameter \"" << param << "\" height \"" << heightStr - << "\" is not an integer"); + SWARNING("HTTP parameter \"{}\" height \"{}\" is not an integer", param, + heightStr); continue; } m_width = width; @@ -264,29 +259,25 @@ bool MjpegServerImpl::ConnThread::ProcessCommand(wpi::raw_ostream& os, } if (param == "fps") { - int fps; - if (value.getAsInteger(10, fps)) { - response << param << ": \"invalid integer\"\r\n"; - SWARNING("HTTP parameter \"" << param << "\" value \"" << value - << "\" is not an integer"); - continue; - } else { - m_fps = fps; + if (auto v = wpi::parse_integer(value, 10)) { + m_fps = v.value(); response << param << ": \"ok\"\r\n"; + } else { + response << param << ": \"invalid integer\"\r\n"; + SWARNING("HTTP parameter \"{}\" value \"{}\" is not an integer", param, + value); } continue; } if (param == "compression") { - int compression; - if (value.getAsInteger(10, compression)) { - response << param << ": \"invalid integer\"\r\n"; - SWARNING("HTTP parameter \"" << param << "\" value \"" << value - << "\" is not an integer"); - continue; - } else { - m_compression = compression; + if (auto v = wpi::parse_integer(value, 10)) { + m_compression = v.value(); response << param << ": \"ok\"\r\n"; + } else { + response << param << ": \"invalid integer\"\r\n"; + SWARNING("HTTP parameter \"{}\" value \"{}\" is not an integer", param, + value); } continue; } @@ -300,7 +291,7 @@ bool MjpegServerImpl::ConnThread::ProcessCommand(wpi::raw_ostream& os, auto prop = source.GetPropertyIndex(param); if (!prop) { response << param << ": \"ignored\"\r\n"; - SWARNING("ignoring HTTP parameter \"" << param << "\""); + SWARNING("ignoring HTTP parameter \"{}\"", param); continue; } @@ -310,21 +301,20 @@ bool MjpegServerImpl::ConnThread::ProcessCommand(wpi::raw_ostream& os, case CS_PROP_BOOLEAN: case CS_PROP_INTEGER: case CS_PROP_ENUM: { - int val = 0; - if (value.getAsInteger(10, val)) { - response << param << ": \"invalid integer\"\r\n"; - SWARNING("HTTP parameter \"" << param << "\" value \"" << value - << "\" is not an integer"); + if (auto v = wpi::parse_integer(value, 10)) { + fmt::print(response, "{}: {}\r\n", param, v.value()); + SDEBUG4("HTTP parameter \"{}\" value {}", param, value); + source.SetProperty(prop, v.value(), &status); } else { - response << param << ": " << val << "\r\n"; - SDEBUG4("HTTP parameter \"" << param << "\" value " << value); - source.SetProperty(prop, val, &status); + response << param << ": \"invalid integer\"\r\n"; + SWARNING("HTTP parameter \"{}\" value \"{}\" is not an integer", + param, value); } break; } case CS_PROP_STRING: { response << param << ": \"ok\"\r\n"; - SDEBUG4("HTTP parameter \"" << param << "\" value \"" << value << "\""); + SDEBUG4("HTTP parameter \"{}\" value \"{}\"", param, value); source.SetStringProperty(prop, value, &status); break; } @@ -362,17 +352,17 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, for (auto prop : source.EnumerateProperties(properties_vec, &status)) { wpi::SmallString<128> name_buf; auto name = source.GetPropertyName(prop, name_buf, &status); - if (name.startswith("raw_")) { + if (wpi::starts_with(name, "raw_")) { continue; } auto kind = source.GetPropertyKind(prop); - os << "

" - << "\n"; + fmt::print(os, "

\n", name); switch (kind) { case CS_PROP_BOOLEAN: - os << "\n"; } else { @@ -384,12 +374,13 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, auto min = source.GetPropertyMin(prop, &status); auto max = source.GetPropertyMax(prop, &status); auto step = source.GetPropertyStep(prop, &status); - os << "\n"; - os << "" << valI - << "\n"; + fmt::print(os, + "\n", + name, min, max, valI, step); + fmt::print(os, "{1}\n", name, + valI); break; } case CS_PROP_ENUM: { @@ -404,26 +395,30 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, // replace any non-printable characters in name with spaces wpi::SmallString<128> ch_name; for (char ch : *choice) { - ch_name.push_back(std::isprint(ch) ? ch : ' '); + ch_name.push_back(wpi::isPrint(ch) ? ch : ' '); } - os << "\n"; + fmt::print(os, " />\n", name, j, + ch_name); } break; } case CS_PROP_STRING: { wpi::SmallString<128> strval_buf; - os << "\n"; - os << "\n"; + fmt::print(os, + "\n", + name, source.GetStringProperty(prop, strval_buf, &status)); + fmt::print(os, + "\n", + name); break; } default: @@ -469,10 +464,8 @@ void MjpegServerImpl::ConnThread::SendHTML(wpi::raw_ostream& os, os << "unknown"; break; } - os << "" << mode.width; - os << "" << mode.height; - os << "" << mode.fps; - os << ""; + fmt::print(os, "{}{}{}", mode.width, + mode.height, mode.fps); } os << "\n"; os << endRootPage << "\r\n"; @@ -500,20 +493,21 @@ void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, wpi::SmallString<128> name_buf; auto name = source.GetPropertyName(prop, name_buf, &status); auto kind = source.GetPropertyKind(prop); - os << "\n\"name\": \"" << name << '"'; - os << ",\n\"id\": \"" << prop << '"'; - os << ",\n\"type\": \"" << kind << '"'; - os << ",\n\"min\": \"" << source.GetPropertyMin(prop, &status) << '"'; - os << ",\n\"max\": \"" << source.GetPropertyMax(prop, &status) << '"'; - os << ",\n\"step\": \"" << source.GetPropertyStep(prop, &status) << '"'; - os << ",\n\"default\": \"" << source.GetPropertyDefault(prop, &status) - << '"'; + fmt::print(os, "\n\"name\": \"{}\"", name); + fmt::print(os, ",\n\"id\": \"{}\"", prop); + fmt::print(os, ",\n\"type\": \"{}\"", kind); + fmt::print(os, ",\n\"min\": \"{}\"", source.GetPropertyMin(prop, &status)); + fmt::print(os, ",\n\"max\": \"{}\"", source.GetPropertyMax(prop, &status)); + fmt::print(os, ",\n\"step\": \"{}\"", + source.GetPropertyStep(prop, &status)); + fmt::print(os, ",\n\"default\": \"{}\"", + source.GetPropertyDefault(prop, &status)); os << ",\n\"value\": \""; switch (kind) { case CS_PROP_BOOLEAN: case CS_PROP_INTEGER: case CS_PROP_ENUM: - os << source.GetProperty(prop, &status); + fmt::print(os, "{}", source.GetProperty(prop, &status)); break; case CS_PROP_STRING: { wpi::SmallString<128> strval_buf; @@ -543,7 +537,7 @@ void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, for (char ch : *choice) { ch_name.push_back(std::isprint(ch) ? ch : ' '); } - os << '"' << j << "\": \"" << ch_name << '"'; + fmt::print(os, "\"{}\": \"{}\"", j, ch_name); } os << "}\n"; } @@ -579,29 +573,26 @@ void MjpegServerImpl::ConnThread::SendJSON(wpi::raw_ostream& os, os << "unknown"; break; } - os << "\",\n\"width\": \"" << mode.width << '"'; - os << ",\n\"height\": \"" << mode.height << '"'; - os << ",\n\"fps\": \"" << mode.fps << '"'; + fmt::print(os, "\",\n\"width\": \"{}\"", mode.width); + fmt::print(os, ",\n\"height\": \"{}\"", mode.height); + fmt::print(os, ",\n\"fps\": \"{}\"", mode.fps); os << '}'; } os << "\n]\n}\n"; os.flush(); } -MjpegServerImpl::MjpegServerImpl(const wpi::Twine& name, wpi::Logger& logger, +MjpegServerImpl::MjpegServerImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, - const wpi::Twine& listenAddress, int port, + std::string_view listenAddress, int port, std::unique_ptr acceptor) : SinkImpl{name, logger, notifier, telemetry}, - m_listenAddress(listenAddress.str()), + m_listenAddress(listenAddress), m_port(port), m_acceptor{std::move(acceptor)} { m_active = true; - wpi::SmallString<128> descBuf; - wpi::raw_svector_ostream desc{descBuf}; - desc << "HTTP Server on port " << port; - SetDescription(desc.str()); + SetDescription(fmt::format("HTTP Server on port {}", port)); // Create properties m_widthProp = CreateProperty("width", [] { @@ -659,7 +650,7 @@ void MjpegServerImpl::Stop() { // Send HTTP response and a stream of JPG-frames void MjpegServerImpl::ConnThread::SendStream(wpi::raw_socket_ostream& os) { if (m_noStreaming) { - SERROR("Too many simultaneous client streams"); + SERROR("{}", "Too many simultaneous client streams"); SendError(os, 503, "Too many simultaneous streams"); return; } @@ -672,7 +663,7 @@ void MjpegServerImpl::ConnThread::SendStream(wpi::raw_socket_ostream& os) { SendHeader(oss, 200, "OK", "multipart/x-mixed-replace;boundary=" BOUNDARY); os << oss.str(); - SDEBUG("Headers send, sending stream now"); + SDEBUG("{}", "Headers send, sending stream now"); Frame::Time lastFrameTime = 0; Frame::Time timePerFrame = 0; @@ -694,7 +685,7 @@ void MjpegServerImpl::ConnThread::SendStream(wpi::raw_socket_ostream& os) { std::this_thread::sleep_for(std::chrono::milliseconds(200)); continue; } - SDEBUG4("waiting for frame"); + SDEBUG4("{}", "waiting for frame"); Frame frame = source->GetNextFrame(0.225); // blocks if (!m_active) { break; @@ -757,7 +748,7 @@ void MjpegServerImpl::ConnThread::SendStream(wpi::raw_socket_ostream& os) { continue; } - SDEBUG4("sending frame size=" << size << " addDHT=" << addDHT); + SDEBUG4("sending frame size={} addDHT={}", size, addDHT); // print the individual mimetype and the length // sending the content-length fixes random stream disruption observed @@ -766,18 +757,18 @@ void MjpegServerImpl::ConnThread::SendStream(wpi::raw_socket_ostream& os) { double timestamp = lastFrameTime / 1000000.0; header.clear(); oss << "\r\n--" BOUNDARY "\r\n" - << "Content-Type: image/jpeg\r\n" - << "Content-Length: " << size << "\r\n" - << "X-Timestamp: " << timestamp << "\r\n" - << "\r\n"; + << "Content-Type: image/jpeg\r\n"; + fmt::print(oss, "Content-Length: {}\r\n", size); + fmt::print(oss, "X-Timestamp: {}\r\n", timestamp); + oss << "\r\n"; os << oss.str(); if (addDHT) { // Insert DHT data immediately before SOF - os << wpi::StringRef(data, locSOF); + os << std::string_view(data, locSOF); os << JpegGetDHT(); - os << wpi::StringRef(data + locSOF, image->size() - locSOF); + os << std::string_view(data + locSOF, image->size() - locSOF); } else { - os << wpi::StringRef(data, size); + os << std::string_view(data, size); } // os.flush(); } @@ -790,48 +781,50 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { // Read the request string from the stream wpi::SmallString<128> reqBuf; - wpi::StringRef req = is.getline(reqBuf, 4096); + std::string_view req = is.getline(reqBuf, 4096); if (is.has_error()) { - SDEBUG("error getting request string"); + SDEBUG("{}", "error getting request string"); return; } enum { kCommand, kStream, kGetSettings, kGetSourceConfig, kRootPage } kind; - wpi::StringRef parameters; + std::string_view parameters; size_t pos; - SDEBUG("HTTP request: '" << req << "'\n"); + SDEBUG("HTTP request: '{}'\n", req); // Determine request kind. Most of these are for mjpgstreamer // compatibility, others are for Axis camera compatibility. - if ((pos = req.find("POST /stream")) != wpi::StringRef::npos) { + if ((pos = req.find("POST /stream")) != std::string_view::npos) { kind = kStream; parameters = req.substr(req.find('?', pos + 12)).substr(1); - } else if ((pos = req.find("GET /?action=stream")) != wpi::StringRef::npos) { + } else if ((pos = req.find("GET /?action=stream")) != + std::string_view::npos) { kind = kStream; parameters = req.substr(req.find('&', pos + 19)).substr(1); - } else if ((pos = req.find("GET /stream.mjpg")) != wpi::StringRef::npos) { + } else if ((pos = req.find("GET /stream.mjpg")) != std::string_view::npos) { kind = kStream; parameters = req.substr(req.find('?', pos + 16)).substr(1); - } else if (req.find("GET /settings") != wpi::StringRef::npos && - req.find(".json") != wpi::StringRef::npos) { + } else if (req.find("GET /settings") != std::string_view::npos && + req.find(".json") != std::string_view::npos) { kind = kGetSettings; - } else if (req.find("GET /config") != wpi::StringRef::npos && - req.find(".json") != wpi::StringRef::npos) { + } else if (req.find("GET /config") != std::string_view::npos && + req.find(".json") != std::string_view::npos) { kind = kGetSourceConfig; - } else if (req.find("GET /input") != wpi::StringRef::npos && - req.find(".json") != wpi::StringRef::npos) { + } else if (req.find("GET /input") != std::string_view::npos && + req.find(".json") != std::string_view::npos) { kind = kGetSettings; - } else if (req.find("GET /output") != wpi::StringRef::npos && - req.find(".json") != wpi::StringRef::npos) { + } else if (req.find("GET /output") != std::string_view::npos && + req.find(".json") != std::string_view::npos) { kind = kGetSettings; - } else if ((pos = req.find("GET /?action=command")) != wpi::StringRef::npos) { + } else if ((pos = req.find("GET /?action=command")) != + std::string_view::npos) { kind = kCommand; parameters = req.substr(req.find('&', pos + 20)).substr(1); - } else if (req.find("GET / ") != wpi::StringRef::npos || req == "GET /\n") { + } else if (req.find("GET / ") != std::string_view::npos || req == "GET /\n") { kind = kRootPage; } else { - SDEBUG("HTTP request resource not found"); + SDEBUG("{}", "HTTP request resource not found"); SendError(os, 404, "Resource not found"); return; } @@ -841,13 +834,13 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_" "-=&1234567890%./"); parameters = parameters.substr(0, pos); - SDEBUG("command parameters: \"" << parameters << "\""); + SDEBUG("command parameters: \"{}\"", parameters); // Read the rest of the HTTP request. // The end of the request is marked by a single, empty line wpi::SmallString<128> lineBuf; for (;;) { - if (is.getline(lineBuf, 4096).startswith("\n")) { + if (wpi::starts_with(is.getline(lineBuf, 4096), "\n")) { break; } if (is.has_error()) { @@ -859,7 +852,7 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { switch (kind) { case kStream: if (auto source = GetSource()) { - SDEBUG("request for stream " << source->GetName()); + SDEBUG("request for stream {}", source->GetName()); if (!ProcessCommand(os, *source, parameters, false)) { return; } @@ -873,11 +866,11 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { SendHeader(os, 200, "OK", "text/plain"); os << "Ignored due to no connected source." << "\r\n"; - SDEBUG("Ignored due to no connected source."); + SDEBUG("{}", "Ignored due to no connected source."); } break; case kGetSettings: - SDEBUG("request for JSON file"); + SDEBUG("{}", "request for JSON file"); if (auto source = GetSource()) { SendJSON(os, *source, true); } else { @@ -885,7 +878,7 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { } break; case kGetSourceConfig: - SDEBUG("request for JSON file"); + SDEBUG("{}", "request for JSON file"); if (auto source = GetSource()) { SendHeader(os, 200, "OK", "application/json"); CS_Status status = CS_OK; @@ -896,7 +889,7 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { } break; case kRootPage: - SDEBUG("request for root page"); + SDEBUG("{}", "request for root page"); SendHeader(os, 200, "OK", "text/html"); if (auto source = GetSource()) { SendHTML(os, *source, false); @@ -907,7 +900,7 @@ void MjpegServerImpl::ConnThread::ProcessRequest() { break; } - SDEBUG("leaving HTTP client thread"); + SDEBUG("{}", "leaving HTTP client thread"); } // worker thread for clients that connected to this server @@ -934,7 +927,7 @@ void MjpegServerImpl::ServerThreadMain() { return; } - SDEBUG("waiting for clients to connect"); + SDEBUG("{}", "waiting for clients to connect"); while (m_active) { auto stream = m_acceptor->accept(); if (!stream) { @@ -945,7 +938,7 @@ void MjpegServerImpl::ServerThreadMain() { return; } - SDEBUG("client connection from " << stream->getPeerIP()); + SDEBUG("client connection from {}", stream->getPeerIP()); auto source = GetSource(); @@ -984,7 +977,7 @@ void MjpegServerImpl::ServerThreadMain() { thr->m_cond.notify_one(); } - SDEBUG("leaving server thread"); + SDEBUG("{}", "leaving server thread"); } void MjpegServerImpl::SetSourceImpl(std::shared_ptr source) { @@ -1007,19 +1000,15 @@ void MjpegServerImpl::SetSourceImpl(std::shared_ptr source) { namespace cs { -CS_Sink CreateMjpegServer(const wpi::Twine& name, - const wpi::Twine& listenAddress, int port, - CS_Status* status) { +CS_Sink CreateMjpegServer(std::string_view name, std::string_view listenAddress, + int port, CS_Status* status) { auto& inst = Instance::GetInstance(); - wpi::SmallString<128> listenAddressBuf; return inst.CreateSink( CS_SINK_MJPEG, std::make_shared( name, inst.logger, inst.notifier, inst.telemetry, listenAddress, port, - std::unique_ptr(new wpi::TCPAcceptor( - port, - listenAddress.toNullTerminatedStringRef(listenAddressBuf).data(), - inst.logger)))); + std::unique_ptr( + new wpi::TCPAcceptor(port, listenAddress, inst.logger)))); } std::string GetMjpegServerListenAddress(CS_Sink sink, CS_Status* status) { diff --git a/cscore/src/main/native/cpp/MjpegServerImpl.h b/cscore/src/main/native/cpp/MjpegServerImpl.h index bc4d232e62..e323e69b48 100644 --- a/cscore/src/main/native/cpp/MjpegServerImpl.h +++ b/cscore/src/main/native/cpp/MjpegServerImpl.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -15,7 +16,6 @@ #include #include #include -#include #include #include #include @@ -28,9 +28,9 @@ class SourceImpl; class MjpegServerImpl : public SinkImpl { public: - MjpegServerImpl(const wpi::Twine& name, wpi::Logger& logger, + MjpegServerImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, - const wpi::Twine& listenAddress, int port, + std::string_view listenAddress, int port, std::unique_ptr acceptor); ~MjpegServerImpl() override; diff --git a/cscore/src/main/native/cpp/Notifier.cpp b/cscore/src/main/native/cpp/Notifier.cpp index 318e1b25ff..371189634d 100644 --- a/cscore/src/main/native/cpp/Notifier.cpp +++ b/cscore/src/main/native/cpp/Notifier.cpp @@ -32,7 +32,7 @@ unsigned int Notifier::AddPolled(unsigned int pollerUid, int eventMask) { return DoAdd(pollerUid, eventMask); } -void Notifier::NotifySource(const wpi::Twine& name, CS_Source source, +void Notifier::NotifySource(std::string_view name, CS_Source source, CS_EventKind kind) { Send(UINT_MAX, name, source, static_cast(kind)); } @@ -49,9 +49,9 @@ void Notifier::NotifySourceVideoMode(const SourceImpl& source, } void Notifier::NotifySourceProperty(const SourceImpl& source, CS_EventKind kind, - const wpi::Twine& propertyName, - int property, CS_PropertyKind propertyKind, - int value, const wpi::Twine& valueStr) { + std::string_view propertyName, int property, + CS_PropertyKind propertyKind, int value, + std::string_view valueStr) { auto handleData = Instance::GetInstance().FindSource(source); Send(UINT_MAX, propertyName, handleData.first, static_cast(kind), @@ -59,7 +59,7 @@ void Notifier::NotifySourceProperty(const SourceImpl& source, CS_EventKind kind, value, valueStr); } -void Notifier::NotifySink(const wpi::Twine& name, CS_Sink sink, +void Notifier::NotifySink(std::string_view name, CS_Sink sink, CS_EventKind kind) { Send(UINT_MAX, name, sink, static_cast(kind)); } @@ -69,7 +69,7 @@ void Notifier::NotifySink(const SinkImpl& sink, CS_EventKind kind) { NotifySink(sink.GetName(), handleData.first, kind); } -void Notifier::NotifySinkSourceChanged(const wpi::Twine& name, CS_Sink sink, +void Notifier::NotifySinkSourceChanged(std::string_view name, CS_Sink sink, CS_Source source) { RawEvent event{name, sink, RawEvent::kSinkSourceChanged}; event.sourceHandle = source; @@ -77,9 +77,9 @@ void Notifier::NotifySinkSourceChanged(const wpi::Twine& name, CS_Sink sink, } void Notifier::NotifySinkProperty(const SinkImpl& sink, CS_EventKind kind, - const wpi::Twine& propertyName, int property, + std::string_view propertyName, int property, CS_PropertyKind propertyKind, int value, - const wpi::Twine& valueStr) { + std::string_view valueStr) { auto handleData = Instance::GetInstance().FindSink(sink); Send(UINT_MAX, propertyName, handleData.first, static_cast(kind), diff --git a/cscore/src/main/native/cpp/Notifier.h b/cscore/src/main/native/cpp/Notifier.h index 3a5533ac05..c0f7abcf39 100644 --- a/cscore/src/main/native/cpp/Notifier.h +++ b/cscore/src/main/native/cpp/Notifier.h @@ -65,22 +65,21 @@ class Notifier : public wpi::CallbackManager { unsigned int AddPolled(unsigned int pollerUid, int eventMask); // Notification events - void NotifySource(const wpi::Twine& name, CS_Source source, - CS_EventKind kind); + void NotifySource(std::string_view name, CS_Source source, CS_EventKind kind); void NotifySource(const SourceImpl& source, CS_EventKind kind); void NotifySourceVideoMode(const SourceImpl& source, const VideoMode& mode); void NotifySourceProperty(const SourceImpl& source, CS_EventKind kind, - const wpi::Twine& propertyName, int property, + std::string_view propertyName, int property, CS_PropertyKind propertyKind, int value, - const wpi::Twine& valueStr); - void NotifySink(const wpi::Twine& name, CS_Sink sink, CS_EventKind kind); + std::string_view valueStr); + void NotifySink(std::string_view name, CS_Sink sink, CS_EventKind kind); void NotifySink(const SinkImpl& sink, CS_EventKind kind); - void NotifySinkSourceChanged(const wpi::Twine& name, CS_Sink sink, + void NotifySinkSourceChanged(std::string_view name, CS_Sink sink, CS_Source source); void NotifySinkProperty(const SinkImpl& sink, CS_EventKind kind, - const wpi::Twine& propertyName, int property, + std::string_view propertyName, int property, CS_PropertyKind propertyKind, int value, - const wpi::Twine& valueStr); + std::string_view valueStr); void NotifyNetworkInterfacesChanged(); void NotifyTelemetryUpdated(); void NotifyUsbCamerasChanged(); diff --git a/cscore/src/main/native/cpp/PropertyContainer.cpp b/cscore/src/main/native/cpp/PropertyContainer.cpp index f86280b317..d95c06edfa 100644 --- a/cscore/src/main/native/cpp/PropertyContainer.cpp +++ b/cscore/src/main/native/cpp/PropertyContainer.cpp @@ -11,15 +11,14 @@ using namespace cs; -int PropertyContainer::GetPropertyIndex(const wpi::Twine& name) const { +int PropertyContainer::GetPropertyIndex(std::string_view name) const { // We can't fail, so instead we create a new index if caching fails. CS_Status status = 0; if (!m_properties_cached) { CacheProperties(&status); } std::scoped_lock lock(m_mutex); - wpi::SmallVector nameBuf; - int& ndx = m_properties[name.toStringRef(nameBuf)]; + int& ndx = m_properties[name]; if (ndx == 0) { // create a new index ndx = m_propertyData.size() + 1; @@ -55,7 +54,7 @@ CS_PropertyKind PropertyContainer::GetPropertyKind(int property) const { return prop->propKind; } -wpi::StringRef PropertyContainer::GetPropertyName( +std::string_view PropertyContainer::GetPropertyName( int property, wpi::SmallVectorImpl& buf, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) { return {}; @@ -108,7 +107,7 @@ void PropertyContainer::SetProperty(int property, int value, return; } - UpdatePropertyValue(property, false, value, wpi::Twine{}); + UpdatePropertyValue(property, false, value, {}); } int PropertyContainer::GetPropertyMin(int property, CS_Status* status) const { @@ -164,7 +163,7 @@ int PropertyContainer::GetPropertyDefault(int property, return prop->defaultValue; } -wpi::StringRef PropertyContainer::GetStringProperty( +std::string_view PropertyContainer::GetStringProperty( int property, wpi::SmallVectorImpl& buf, CS_Status* status) const { if (!m_properties_cached && !CacheProperties(status)) { return {}; @@ -181,10 +180,10 @@ wpi::StringRef PropertyContainer::GetStringProperty( } buf.clear(); buf.append(prop->valueStr.begin(), prop->valueStr.end()); - return wpi::StringRef(buf.data(), buf.size()); + return {buf.data(), buf.size()}; } -void PropertyContainer::SetStringProperty(int property, const wpi::Twine& value, +void PropertyContainer::SetStringProperty(int property, std::string_view value, CS_Status* status) { std::scoped_lock lock(m_mutex); auto prop = GetProperty(property); @@ -225,7 +224,7 @@ std::vector PropertyContainer::GetEnumPropertyChoices( } std::unique_ptr PropertyContainer::CreateEmptyProperty( - const wpi::Twine& name) const { + std::string_view name) const { return std::make_unique(name); } @@ -237,16 +236,15 @@ bool PropertyContainer::CacheProperties(CS_Status* status) const { bool PropertyContainer::SetPropertiesJson(const wpi::json& config, wpi::Logger& logger, - wpi::StringRef logName, + std::string_view logName, CS_Status* status) { for (auto&& prop : config) { std::string name; try { name = prop.at("name").get(); } catch (const wpi::json::exception& e) { - WPI_WARNING(logger, - logName << ": SetConfigJson: could not read property name: " - << e.what()); + WPI_WARNING(logger, "{}: SetConfigJson: could not read property name: {}", + logName, e.what()); continue; } int n = GetPropertyIndex(name); @@ -254,24 +252,24 @@ bool PropertyContainer::SetPropertiesJson(const wpi::json& config, auto& v = prop.at("value"); if (v.is_string()) { std::string val = v.get(); - WPI_INFO(logger, logName << ": SetConfigJson: setting property '" - << name << "' to '" << val << '\''); + WPI_INFO(logger, "{}: SetConfigJson: setting property '{}' to '{}'", + logName, name, val); SetStringProperty(n, val, status); } else if (v.is_boolean()) { bool val = v.get(); - WPI_INFO(logger, logName << ": SetConfigJson: setting property '" - << name << "' to " << val); + WPI_INFO(logger, "{}: SetConfigJson: setting property '{}' to {}", + logName, name, val); SetProperty(n, val, status); } else { int val = v.get(); - WPI_INFO(logger, logName << ": SetConfigJson: setting property '" - << name << "' to " << val); + WPI_INFO(logger, "{}: SetConfigJson: setting property '{}' to {}", + logName, name, val); SetProperty(n, val, status); } } catch (const wpi::json::exception& e) { WPI_WARNING(logger, - logName << ": SetConfigJson: could not read property value: " - << e.what()); + "{}: SetConfigJson: could not read property value: {}", + logName, e.what()); continue; } } diff --git a/cscore/src/main/native/cpp/PropertyContainer.h b/cscore/src/main/native/cpp/PropertyContainer.h index f1c71ea6b0..f09ea23c7b 100644 --- a/cscore/src/main/native/cpp/PropertyContainer.h +++ b/cscore/src/main/native/cpp/PropertyContainer.h @@ -9,13 +9,11 @@ #include #include #include +#include #include #include -#include #include -#include -#include #include #include "PropertyImpl.h" @@ -23,6 +21,8 @@ namespace wpi { class Logger; +template +class SmallVectorImpl; class json; } // namespace wpi @@ -32,28 +32,29 @@ class PropertyContainer { public: virtual ~PropertyContainer() = default; - int GetPropertyIndex(const wpi::Twine& name) const; + int GetPropertyIndex(std::string_view name) const; wpi::ArrayRef EnumerateProperties(wpi::SmallVectorImpl& vec, CS_Status* status) const; CS_PropertyKind GetPropertyKind(int property) const; - wpi::StringRef GetPropertyName(int property, wpi::SmallVectorImpl& buf, - CS_Status* status) const; + std::string_view GetPropertyName(int property, + wpi::SmallVectorImpl& buf, + CS_Status* status) const; int GetProperty(int property, CS_Status* status) const; virtual void SetProperty(int property, int value, CS_Status* status); int GetPropertyMin(int property, CS_Status* status) const; int GetPropertyMax(int property, CS_Status* status) const; int GetPropertyStep(int property, CS_Status* status) const; int GetPropertyDefault(int property, CS_Status* status) const; - wpi::StringRef GetStringProperty(int property, - wpi::SmallVectorImpl& buf, - CS_Status* status) const; - virtual void SetStringProperty(int property, const wpi::Twine& value, + std::string_view GetStringProperty(int property, + wpi::SmallVectorImpl& buf, + CS_Status* status) const; + virtual void SetStringProperty(int property, std::string_view value, CS_Status* status); std::vector GetEnumPropertyChoices(int property, CS_Status* status) const; bool SetPropertiesJson(const wpi::json& config, wpi::Logger& logger, - wpi::StringRef logName, CS_Status* status); + std::string_view logName, CS_Status* status); wpi::json GetPropertiesJsonObject(CS_Status* status); protected: @@ -76,10 +77,9 @@ class PropertyContainer { // @tparam NewFunc functor that returns a std::unique_ptr // @tparam UpdateFunc functor that takes a PropertyImpl&. template - int CreateOrUpdateProperty(const wpi::Twine& name, NewFunc newFunc, + int CreateOrUpdateProperty(std::string_view name, NewFunc newFunc, UpdateFunc updateFunc) { - wpi::SmallVector nameBuf; - int& ndx = m_properties[name.toStringRef(nameBuf)]; + int& ndx = m_properties[name]; if (ndx == 0) { // create a new index ndx = m_propertyData.size() + 1; @@ -91,7 +91,7 @@ class PropertyContainer { return ndx; } template - int CreateProperty(const wpi::Twine& name, NewFunc newFunc) { + int CreateProperty(std::string_view name, NewFunc newFunc) { return CreateOrUpdateProperty(name, newFunc, [](PropertyImpl&) {}); } @@ -100,7 +100,7 @@ class PropertyContainer { // Note: called with m_mutex held. // The default implementation simply creates a PropertyImpl object. virtual std::unique_ptr CreateEmptyProperty( - const wpi::Twine& name) const; + std::string_view name) const; // Cache properties. Implementations must return false and set status to // CS_SOURCE_IS_DISCONNECTED if not possible to cache. @@ -111,7 +111,7 @@ class PropertyContainer { // Update property value; must be called with m_mutex held. virtual void UpdatePropertyValue(int property, bool setString, int value, - const wpi::Twine& valueStr) = 0; + std::string_view valueStr) = 0; // Whether CacheProperties() has been successful at least once (and thus // should not be called again) diff --git a/cscore/src/main/native/cpp/PropertyImpl.cpp b/cscore/src/main/native/cpp/PropertyImpl.cpp index 68977235d1..3c3663043c 100644 --- a/cscore/src/main/native/cpp/PropertyImpl.cpp +++ b/cscore/src/main/native/cpp/PropertyImpl.cpp @@ -6,18 +6,18 @@ using namespace cs; -PropertyImpl::PropertyImpl(const wpi::Twine& name_) : name{name_.str()} {} -PropertyImpl::PropertyImpl(const wpi::Twine& name_, CS_PropertyKind kind_, +PropertyImpl::PropertyImpl(std::string_view name_) : name{name_} {} +PropertyImpl::PropertyImpl(std::string_view name_, CS_PropertyKind kind_, int step_, int defaultValue_, int value_) - : name{name_.str()}, + : name{name_}, propKind{kind_}, step{step_}, defaultValue{defaultValue_}, value{value_} {} -PropertyImpl::PropertyImpl(const wpi::Twine& name_, CS_PropertyKind kind_, +PropertyImpl::PropertyImpl(std::string_view name_, CS_PropertyKind kind_, int minimum_, int maximum_, int step_, int defaultValue_, int value_) - : name{name_.str()}, + : name{name_}, propKind{kind_}, hasMinimum{true}, hasMaximum{true}, @@ -43,11 +43,10 @@ void PropertyImpl::SetValue(int v) { } } -void PropertyImpl::SetValue(const wpi::Twine& v) { +void PropertyImpl::SetValue(std::string_view v) { bool valueChanged = false; - std::string vStr = v.str(); - if (valueStr != vStr) { - valueStr = vStr; + if (valueStr != v) { + valueStr = v; valueChanged = true; } bool wasValueSet = valueSet; diff --git a/cscore/src/main/native/cpp/PropertyImpl.h b/cscore/src/main/native/cpp/PropertyImpl.h index ea9f057b8a..77e79082d7 100644 --- a/cscore/src/main/native/cpp/PropertyImpl.h +++ b/cscore/src/main/native/cpp/PropertyImpl.h @@ -6,11 +6,10 @@ #define CSCORE_PROPERTYIMPL_H_ #include +#include #include #include -#include -#include #include "cscore_c.h" @@ -20,17 +19,17 @@ namespace cs { class PropertyImpl { public: PropertyImpl() = default; - explicit PropertyImpl(const wpi::Twine& name_); - PropertyImpl(const wpi::Twine& name_, CS_PropertyKind kind_, int step_, + explicit PropertyImpl(std::string_view name_); + PropertyImpl(std::string_view name_, CS_PropertyKind kind_, int step_, int defaultValue_, int value_); - PropertyImpl(const wpi::Twine& name_, CS_PropertyKind kind_, int minimum_, + PropertyImpl(std::string_view name_, CS_PropertyKind kind_, int minimum_, int maximum_, int step_, int defaultValue_, int value_); virtual ~PropertyImpl() = default; PropertyImpl(const PropertyImpl& oth) = delete; PropertyImpl& operator=(const PropertyImpl& oth) = delete; void SetValue(int v); - void SetValue(const wpi::Twine& v); + void SetValue(std::string_view v); void SetDefaultValue(int v); std::string name; diff --git a/cscore/src/main/native/cpp/RawSinkImpl.cpp b/cscore/src/main/native/cpp/RawSinkImpl.cpp index 4dbe7818a0..fbc1028f81 100644 --- a/cscore/src/main/native/cpp/RawSinkImpl.cpp +++ b/cscore/src/main/native/cpp/RawSinkImpl.cpp @@ -10,14 +10,14 @@ using namespace cs; -RawSinkImpl::RawSinkImpl(const wpi::Twine& name, wpi::Logger& logger, +RawSinkImpl::RawSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry) : SinkImpl{name, logger, notifier, telemetry} { m_active = true; // m_thread = std::thread(&RawSinkImpl::ThreadMain, this); } -RawSinkImpl::RawSinkImpl(const wpi::Twine& name, wpi::Logger& logger, +RawSinkImpl::RawSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, std::function processFrame) : SinkImpl{name, logger, notifier, telemetry} {} @@ -127,7 +127,7 @@ void RawSinkImpl::ThreadMain() { std::this_thread::sleep_for(std::chrono::seconds(1)); continue; } - SDEBUG4("waiting for frame"); + SDEBUG4("{}", "waiting for frame"); Frame frame = source->GetNextFrame(); // blocks if (!m_active) { break; @@ -143,14 +143,14 @@ void RawSinkImpl::ThreadMain() { } namespace cs { -CS_Sink CreateRawSink(const wpi::Twine& name, CS_Status* status) { +CS_Sink CreateRawSink(std::string_view name, CS_Status* status) { auto& inst = Instance::GetInstance(); return inst.CreateSink(CS_SINK_RAW, std::make_shared( name, inst.logger, inst.notifier, inst.telemetry)); } -CS_Sink CreateRawSinkCallback(const wpi::Twine& name, +CS_Sink CreateRawSinkCallback(std::string_view name, std::function processFrame, CS_Status* status) { auto& inst = Instance::GetInstance(); diff --git a/cscore/src/main/native/cpp/RawSinkImpl.h b/cscore/src/main/native/cpp/RawSinkImpl.h index 5fc43de36e..6e8032a101 100644 --- a/cscore/src/main/native/cpp/RawSinkImpl.h +++ b/cscore/src/main/native/cpp/RawSinkImpl.h @@ -9,9 +9,9 @@ #include #include +#include #include -#include #include #include "Frame.h" @@ -23,9 +23,9 @@ class SourceImpl; class RawSinkImpl : public SinkImpl { public: - RawSinkImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, + RawSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry); - RawSinkImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, + RawSinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, std::function processFrame); ~RawSinkImpl() override; diff --git a/cscore/src/main/native/cpp/RawSourceImpl.cpp b/cscore/src/main/native/cpp/RawSourceImpl.cpp index 87184d2534..9ce0628102 100644 --- a/cscore/src/main/native/cpp/RawSourceImpl.cpp +++ b/cscore/src/main/native/cpp/RawSourceImpl.cpp @@ -14,7 +14,7 @@ using namespace cs; -RawSourceImpl::RawSourceImpl(const wpi::Twine& name, wpi::Logger& logger, +RawSourceImpl::RawSourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, const VideoMode& mode) : ConfigurableSourceImpl{name, logger, notifier, telemetry, mode} {} @@ -47,7 +47,7 @@ void RawSourceImpl::PutFrame(const CS_RawFrame& image) { } namespace cs { -CS_Source CreateRawSource(const wpi::Twine& name, const VideoMode& mode, +CS_Source CreateRawSource(std::string_view name, const VideoMode& mode, CS_Status* status) { auto& inst = Instance::GetInstance(); return inst.CreateSource(CS_SOURCE_RAW, std::make_shared( diff --git a/cscore/src/main/native/cpp/RawSourceImpl.h b/cscore/src/main/native/cpp/RawSourceImpl.h index a15278dd4e..bb9a49fc67 100644 --- a/cscore/src/main/native/cpp/RawSourceImpl.h +++ b/cscore/src/main/native/cpp/RawSourceImpl.h @@ -9,10 +9,10 @@ #include #include #include +#include #include #include -#include #include "ConfigurableSourceImpl.h" #include "SourceImpl.h" @@ -22,7 +22,7 @@ namespace cs { class RawSourceImpl : public ConfigurableSourceImpl { public: - RawSourceImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, + RawSourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, const VideoMode& mode); ~RawSourceImpl() override; diff --git a/cscore/src/main/native/cpp/SinkImpl.cpp b/cscore/src/main/native/cpp/SinkImpl.cpp index a092cb7d59..93a625f814 100644 --- a/cscore/src/main/native/cpp/SinkImpl.cpp +++ b/cscore/src/main/native/cpp/SinkImpl.cpp @@ -12,12 +12,12 @@ using namespace cs; -SinkImpl::SinkImpl(const wpi::Twine& name, wpi::Logger& logger, +SinkImpl::SinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry) : m_logger(logger), m_notifier(notifier), m_telemetry(telemetry), - m_name{name.str()} {} + m_name{name} {} SinkImpl::~SinkImpl() { if (m_source) { @@ -28,15 +28,16 @@ SinkImpl::~SinkImpl() { } } -void SinkImpl::SetDescription(const wpi::Twine& description) { +void SinkImpl::SetDescription(std::string_view description) { std::scoped_lock lock(m_mutex); - m_description = description.str(); + m_description = description; } -wpi::StringRef SinkImpl::GetDescription(wpi::SmallVectorImpl& buf) const { +std::string_view SinkImpl::GetDescription( + wpi::SmallVectorImpl& buf) const { std::scoped_lock lock(m_mutex); buf.append(m_description.begin(), m_description.end()); - return wpi::StringRef{buf.data(), buf.size()}; + return {buf.data(), buf.size()}; } void SinkImpl::Enable() { @@ -106,28 +107,27 @@ std::string SinkImpl::GetError() const { if (!m_source) { return "no source connected"; } - return m_source->GetCurFrame().GetError(); + return std::string{m_source->GetCurFrame().GetError()}; } -wpi::StringRef SinkImpl::GetError(wpi::SmallVectorImpl& buf) const { +std::string_view SinkImpl::GetError(wpi::SmallVectorImpl& buf) const { std::scoped_lock lock(m_mutex); if (!m_source) { return "no source connected"; } // Make a copy as it's shared data - wpi::StringRef error = m_source->GetCurFrame().GetError(); + std::string_view error = m_source->GetCurFrame().GetError(); buf.clear(); buf.append(error.data(), error.data() + error.size()); - return wpi::StringRef{buf.data(), buf.size()}; + return {buf.data(), buf.size()}; } -bool SinkImpl::SetConfigJson(wpi::StringRef config, CS_Status* status) { +bool SinkImpl::SetConfigJson(std::string_view config, CS_Status* status) { wpi::json j; try { j = wpi::json::parse(config); } catch (const wpi::json::parse_error& e) { - SWARNING("SetConfigJson: parse error at byte " << e.byte << ": " - << e.what()); + SWARNING("SetConfigJson: parse error at byte {}: {}", e.byte, e.what()); *status = CS_PROPERTY_WRITE_FAILED; return false; } @@ -169,12 +169,12 @@ void SinkImpl::NotifyPropertyCreated(int propIndex, PropertyImpl& prop) { if (prop.propKind == CS_PROP_ENUM) { m_notifier.NotifySinkProperty(*this, CS_SINK_PROPERTY_CHOICES_UPDATED, prop.name, propIndex, prop.propKind, - prop.value, wpi::Twine{}); + prop.value, {}); } } void SinkImpl::UpdatePropertyValue(int property, bool setString, int value, - const wpi::Twine& valueStr) { + std::string_view valueStr) { auto prop = GetProperty(property); if (!prop) { return; diff --git a/cscore/src/main/native/cpp/SinkImpl.h b/cscore/src/main/native/cpp/SinkImpl.h index 5c8faa42e7..aa37d61230 100644 --- a/cscore/src/main/native/cpp/SinkImpl.h +++ b/cscore/src/main/native/cpp/SinkImpl.h @@ -7,10 +7,9 @@ #include #include +#include #include -#include -#include #include #include "SourceImpl.h" @@ -27,16 +26,16 @@ class Telemetry; class SinkImpl : public PropertyContainer { public: - explicit SinkImpl(const wpi::Twine& name, wpi::Logger& logger, + explicit SinkImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry); ~SinkImpl() override; SinkImpl(const SinkImpl& queue) = delete; SinkImpl& operator=(const SinkImpl& queue) = delete; - wpi::StringRef GetName() const { return m_name; } + std::string_view GetName() const { return m_name; } - void SetDescription(const wpi::Twine& description); - wpi::StringRef GetDescription(wpi::SmallVectorImpl& buf) const; + void SetDescription(std::string_view description); + std::string_view GetDescription(wpi::SmallVectorImpl& buf) const; void Enable(); void Disable(); @@ -50,9 +49,9 @@ class SinkImpl : public PropertyContainer { } std::string GetError() const; - wpi::StringRef GetError(wpi::SmallVectorImpl& buf) const; + std::string_view GetError(wpi::SmallVectorImpl& buf) const; - bool SetConfigJson(wpi::StringRef config, CS_Status* status); + bool SetConfigJson(std::string_view config, CS_Status* status); virtual bool SetConfigJson(const wpi::json& config, CS_Status* status); std::string GetConfigJson(CS_Status* status); virtual wpi::json GetConfigJsonObject(CS_Status* status); @@ -61,7 +60,7 @@ class SinkImpl : public PropertyContainer { // PropertyContainer implementation void NotifyPropertyCreated(int propIndex, PropertyImpl& prop) override; void UpdatePropertyValue(int property, bool setString, int value, - const wpi::Twine& valueStr) override; + std::string_view valueStr) override; virtual void SetSourceImpl(std::shared_ptr source); diff --git a/cscore/src/main/native/cpp/SourceImpl.cpp b/cscore/src/main/native/cpp/SourceImpl.cpp index b88a1e1a2a..da5aa1d9f5 100644 --- a/cscore/src/main/native/cpp/SourceImpl.cpp +++ b/cscore/src/main/native/cpp/SourceImpl.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -19,13 +20,13 @@ using namespace cs; static constexpr size_t kMaxImagesAvail = 32; -SourceImpl::SourceImpl(const wpi::Twine& name, wpi::Logger& logger, +SourceImpl::SourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry) : m_logger(logger), m_notifier(notifier), m_telemetry(telemetry), - m_name{name.str()} { - m_frame = Frame{*this, wpi::StringRef{}, 0}; + m_name{name} { + m_frame = Frame{*this, std::string_view{}, 0}; } SourceImpl::~SourceImpl() { @@ -41,16 +42,16 @@ SourceImpl::~SourceImpl() { // Everything else can clean up itself. } -void SourceImpl::SetDescription(const wpi::Twine& description) { +void SourceImpl::SetDescription(std::string_view description) { std::scoped_lock lock(m_mutex); - m_description = description.str(); + m_description = description; } -wpi::StringRef SourceImpl::GetDescription( +std::string_view SourceImpl::GetDescription( wpi::SmallVectorImpl& buf) const { std::scoped_lock lock(m_mutex); buf.append(m_description.begin(), m_description.end()); - return wpi::StringRef{buf.data(), buf.size()}; + return {buf.data(), buf.size()}; } void SourceImpl::SetConnected(bool connected) { @@ -93,7 +94,7 @@ Frame SourceImpl::GetNextFrame(double timeout) { void SourceImpl::Wakeup() { { std::scoped_lock lock{m_frameMutex}; - m_frame = Frame{*this, wpi::StringRef{}, 0}; + m_frame = Frame{*this, std::string_view{}, 0}; } m_frameCv.notify_all(); } @@ -168,13 +169,12 @@ bool SourceImpl::SetFPS(int fps, CS_Status* status) { return SetVideoMode(mode, status); } -bool SourceImpl::SetConfigJson(wpi::StringRef config, CS_Status* status) { +bool SourceImpl::SetConfigJson(std::string_view config, CS_Status* status) { wpi::json j; try { j = wpi::json::parse(config); } catch (const wpi::json::parse_error& e) { - SWARNING("SetConfigJson: parse error at byte " << e.byte << ": " - << e.what()); + SWARNING("SetConfigJson: parse error at byte {}: {}", e.byte, e.what()); *status = CS_PROPERTY_WRITE_FAILED; return false; } @@ -188,23 +188,22 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { if (config.count("pixel format") != 0) { try { auto str = config.at("pixel format").get(); - wpi::StringRef s(str); - if (s.equals_lower("mjpeg")) { + if (wpi::equals_lower(str, "mjpeg")) { mode.pixelFormat = cs::VideoMode::kMJPEG; - } else if (s.equals_lower("yuyv")) { + } else if (wpi::equals_lower(str, "yuyv")) { mode.pixelFormat = cs::VideoMode::kYUYV; - } else if (s.equals_lower("rgb565")) { + } else if (wpi::equals_lower(str, "rgb565")) { mode.pixelFormat = cs::VideoMode::kRGB565; - } else if (s.equals_lower("bgr")) { + } else if (wpi::equals_lower(str, "bgr")) { mode.pixelFormat = cs::VideoMode::kBGR; - } else if (s.equals_lower("gray")) { + } else if (wpi::equals_lower(str, "gray")) { mode.pixelFormat = cs::VideoMode::kGray; } else { - SWARNING("SetConfigJson: could not understand pixel format value '" - << str << '\''); + SWARNING("SetConfigJson: could not understand pixel format value '{}'", + str); } } catch (const wpi::json::exception& e) { - SWARNING("SetConfigJson: could not read pixel format: " << e.what()); + SWARNING("SetConfigJson: could not read pixel format: {}", e.what()); } } @@ -213,7 +212,7 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { try { mode.width = config.at("width").get(); } catch (const wpi::json::exception& e) { - SWARNING("SetConfigJson: could not read width: " << e.what()); + SWARNING("SetConfigJson: could not read width: {}", e.what()); } } @@ -222,7 +221,7 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { try { mode.height = config.at("height").get(); } catch (const wpi::json::exception& e) { - SWARNING("SetConfigJson: could not read height: " << e.what()); + SWARNING("SetConfigJson: could not read height: {}", e.what()); } } @@ -231,30 +230,31 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { try { mode.fps = config.at("fps").get(); } catch (const wpi::json::exception& e) { - SWARNING("SetConfigJson: could not read fps: " << e.what()); + SWARNING("SetConfigJson: could not read fps: {}", e.what()); } } // if all of video mode is set, use SetVideoMode, otherwise piecemeal it if (mode.pixelFormat != VideoMode::kUnknown && mode.width != 0 && mode.height != 0 && mode.fps != 0) { - SINFO("SetConfigJson: setting video mode to pixelFormat " - << mode.pixelFormat << ", width " << mode.width << ", height " - << mode.height << ", fps " << mode.fps); + SINFO( + "SetConfigJson: setting video mode to pixelFormat {}, width {}, height " + "{}, fps {}", + mode.pixelFormat, mode.width, mode.height, mode.fps); SetVideoMode(mode, status); } else { if (mode.pixelFormat != cs::VideoMode::kUnknown) { - SINFO("SetConfigJson: setting pixelFormat " << mode.pixelFormat); + SINFO("SetConfigJson: setting pixelFormat {}", mode.pixelFormat); SetPixelFormat(static_cast(mode.pixelFormat), status); } if (mode.width != 0 && mode.height != 0) { - SINFO("SetConfigJson: setting width " << mode.width << ", height " - << mode.height); + SINFO("SetConfigJson: setting width {}, height {}", mode.width, + mode.height); SetResolution(mode.width, mode.height, status); } if (mode.fps != 0) { - SINFO("SetConfigJson: setting fps " << mode.fps); + SINFO("SetConfigJson: setting fps {}", mode.fps); SetFPS(mode.fps, status); } } @@ -263,10 +263,10 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { if (config.count("brightness") != 0) { try { int val = config.at("brightness").get(); - SINFO("SetConfigJson: setting brightness to " << val); + SINFO("SetConfigJson: setting brightness to {}", val); SetBrightness(val, status); } catch (const wpi::json::exception& e) { - SWARNING("SetConfigJson: could not read brightness: " << e.what()); + SWARNING("SetConfigJson: could not read brightness: {}", e.what()); } } @@ -276,24 +276,24 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { auto& setting = config.at("white balance"); if (setting.is_string()) { auto str = setting.get(); - wpi::StringRef s(str); - if (s.equals_lower("auto")) { - SINFO("SetConfigJson: setting white balance to auto"); + if (wpi::equals_lower(str, "auto")) { + SINFO("SetConfigJson: setting white balance to {}", "auto"); SetWhiteBalanceAuto(status); - } else if (s.equals_lower("hold")) { - SINFO("SetConfigJson: setting white balance to hold current"); + } else if (wpi::equals_lower(str, "hold")) { + SINFO("SetConfigJson: setting white balance to {}", "hold current"); SetWhiteBalanceHoldCurrent(status); } else { - SWARNING("SetConfigJson: could not understand white balance value '" - << str << '\''); + SWARNING( + "SetConfigJson: could not understand white balance value '{}'", + str); } } else { int val = setting.get(); - SINFO("SetConfigJson: setting white balance to " << val); + SINFO("SetConfigJson: setting white balance to {}", val); SetWhiteBalanceManual(val, status); } } catch (const wpi::json::exception& e) { - SWARNING("SetConfigJson: could not read white balance: " << e.what()); + SWARNING("SetConfigJson: could not read white balance: {}", e.what()); } } @@ -303,24 +303,23 @@ bool SourceImpl::SetConfigJson(const wpi::json& config, CS_Status* status) { auto& setting = config.at("exposure"); if (setting.is_string()) { auto str = setting.get(); - wpi::StringRef s(str); - if (s.equals_lower("auto")) { - SINFO("SetConfigJson: setting exposure to auto"); + if (wpi::equals_lower(str, "auto")) { + SINFO("SetConfigJson: setting exposure to {}", "auto"); SetExposureAuto(status); - } else if (s.equals_lower("hold")) { - SINFO("SetConfigJson: setting exposure to hold current"); + } else if (wpi::equals_lower(str, "hold")) { + SINFO("SetConfigJson: setting exposure to {}", "hold current"); SetExposureHoldCurrent(status); } else { - SWARNING("SetConfigJson: could not understand exposure value '" - << str << '\''); + SWARNING("SetConfigJson: could not understand exposure value '{}'", + str); } } else { int val = setting.get(); - SINFO("SetConfigJson: setting exposure to " << val); + SINFO("SetConfigJson: setting exposure to {}", val); SetExposureManual(val, status); } } catch (const wpi::json::exception& e) { - SWARNING("SetConfigJson: could not read exposure: " << e.what()); + SWARNING("SetConfigJson: could not read exposure: {}", e.what()); } } @@ -344,7 +343,7 @@ wpi::json SourceImpl::GetConfigJsonObject(CS_Status* status) { wpi::json j; // pixel format - wpi::StringRef pixelFormat; + std::string_view pixelFormat; switch (m_mode.pixelFormat) { case VideoMode::kMJPEG: pixelFormat = "mjpeg"; @@ -440,14 +439,12 @@ std::unique_ptr SourceImpl::AllocImage( } void SourceImpl::PutFrame(VideoMode::PixelFormat pixelFormat, int width, - int height, wpi::StringRef data, Frame::Time time) { + int height, std::string_view data, Frame::Time time) { auto image = AllocImage(pixelFormat, width, height, data.size()); // Copy in image data - SDEBUG4("Copying data to " - << reinterpret_cast(image->data()) << " from " - << reinterpret_cast(data.data()) << " (" << data.size() - << " bytes)"); + SDEBUG4("Copying data to {} from {} ({} bytes)", fmt::ptr(image->data()), + fmt::ptr(data.data()), data.size()); std::memcpy(image->data(), data.data(), data.size()); PutFrame(std::move(image), time); @@ -468,7 +465,7 @@ void SourceImpl::PutFrame(std::unique_ptr image, Frame::Time time) { m_frameCv.notify_all(); } -void SourceImpl::PutError(const wpi::Twine& msg, Frame::Time time) { +void SourceImpl::PutError(std::string_view msg, Frame::Time time) { // Update frame { std::scoped_lock lock{m_frameMutex}; @@ -487,12 +484,12 @@ void SourceImpl::NotifyPropertyCreated(int propIndex, PropertyImpl& prop) { if (prop.propKind == CS_PROP_ENUM) { m_notifier.NotifySourceProperty(*this, CS_SOURCE_PROPERTY_CHOICES_UPDATED, prop.name, propIndex, prop.propKind, - prop.value, wpi::Twine{}); + prop.value, {}); } } void SourceImpl::UpdatePropertyValue(int property, bool setString, int value, - const wpi::Twine& valueStr) { + std::string_view valueStr) { auto prop = GetProperty(property); if (!prop) { return; diff --git a/cscore/src/main/native/cpp/SourceImpl.h b/cscore/src/main/native/cpp/SourceImpl.h index 9b7fae4175..0a7839e23a 100644 --- a/cscore/src/main/native/cpp/SourceImpl.h +++ b/cscore/src/main/native/cpp/SourceImpl.h @@ -9,12 +9,11 @@ #include #include #include +#include #include #include #include -#include -#include #include #include @@ -37,7 +36,7 @@ class SourceImpl : public PropertyContainer { friend class Frame; public: - SourceImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, + SourceImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry); ~SourceImpl() override; SourceImpl(const SourceImpl& oth) = delete; @@ -45,10 +44,10 @@ class SourceImpl : public PropertyContainer { virtual void Start() = 0; - wpi::StringRef GetName() const { return m_name; } + std::string_view GetName() const { return m_name; } - void SetDescription(const wpi::Twine& description); - wpi::StringRef GetDescription(wpi::SmallVectorImpl& buf) const; + void SetDescription(std::string_view description); + std::string_view GetDescription(wpi::SmallVectorImpl& buf) const; void SetConnectionStrategy(CS_ConnectionStrategy strategy) { m_strategy = static_cast(strategy); @@ -128,7 +127,7 @@ class SourceImpl : public PropertyContainer { virtual bool SetResolution(int width, int height, CS_Status* status); virtual bool SetFPS(int fps, CS_Status* status); - bool SetConfigJson(wpi::StringRef config, CS_Status* status); + bool SetConfigJson(std::string_view config, CS_Status* status); virtual bool SetConfigJson(const wpi::json& config, CS_Status* status); std::string GetConfigJson(CS_Status* status); virtual wpi::json GetConfigJsonObject(CS_Status* status); @@ -141,12 +140,12 @@ class SourceImpl : public PropertyContainer { protected: void NotifyPropertyCreated(int propIndex, PropertyImpl& prop) override; void UpdatePropertyValue(int property, bool setString, int value, - const wpi::Twine& valueStr) override; + std::string_view valueStr) override; void PutFrame(VideoMode::PixelFormat pixelFormat, int width, int height, - wpi::StringRef data, Frame::Time time); + std::string_view data, Frame::Time time); void PutFrame(std::unique_ptr image, Frame::Time time); - void PutError(const wpi::Twine& msg, Frame::Time time); + void PutError(std::string_view msg, Frame::Time time); // Notification functions for corresponding atomics virtual void NumSinksChanged() = 0; diff --git a/cscore/src/main/native/cpp/c_util.h b/cscore/src/main/native/cpp/c_util.h index 4a474df224..904d049ef6 100644 --- a/cscore/src/main/native/cpp/c_util.h +++ b/cscore/src/main/native/cpp/c_util.h @@ -7,13 +7,13 @@ #include #include +#include #include -#include namespace cs { -inline char* ConvertToC(wpi::StringRef in) { +inline char* ConvertToC(std::string_view in) { char* out = static_cast(wpi::safe_malloc(in.size() + 1)); std::memmove(out, in.data(), in.size()); out[in.size()] = '\0'; diff --git a/cscore/src/main/native/cpp/cscore_cpp.cpp b/cscore/src/main/native/cpp/cscore_cpp.cpp index cf35cec7c0..7d3828e318 100644 --- a/cscore/src/main/native/cpp/cscore_cpp.cpp +++ b/cscore/src/main/native/cpp/cscore_cpp.cpp @@ -70,12 +70,12 @@ std::string GetPropertyName(CS_Property property, CS_Status* status) { if (!container) { return {}; } - return container->GetPropertyName(propertyIndex, buf, status); + return std::string{container->GetPropertyName(propertyIndex, buf, status)}; } -wpi::StringRef GetPropertyName(CS_Property property, - wpi::SmallVectorImpl& buf, - CS_Status* status) { +std::string_view GetPropertyName(CS_Property property, + wpi::SmallVectorImpl& buf, + CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); if (!container) { @@ -145,12 +145,12 @@ std::string GetStringProperty(CS_Property property, CS_Status* status) { if (!container) { return {}; } - return container->GetStringProperty(propertyIndex, buf, status); + return std::string{container->GetStringProperty(propertyIndex, buf, status)}; } -wpi::StringRef GetStringProperty(CS_Property property, - wpi::SmallVectorImpl& buf, - CS_Status* status) { +std::string_view GetStringProperty(CS_Property property, + wpi::SmallVectorImpl& buf, + CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); if (!container) { @@ -159,7 +159,7 @@ wpi::StringRef GetStringProperty(CS_Property property, return container->GetStringProperty(propertyIndex, buf, status); } -void SetStringProperty(CS_Property property, const wpi::Twine& value, +void SetStringProperty(CS_Property property, std::string_view value, CS_Status* status) { int propertyIndex; auto container = GetPropertyContainer(property, &propertyIndex, status); @@ -196,17 +196,18 @@ std::string GetSourceName(CS_Source source, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data) { *status = CS_INVALID_HANDLE; - return std::string{}; + return {}; } - return data->source->GetName(); + return std::string{data->source->GetName()}; } -wpi::StringRef GetSourceName(CS_Source source, wpi::SmallVectorImpl& buf, - CS_Status* status) { +std::string_view GetSourceName(CS_Source source, + wpi::SmallVectorImpl& buf, + CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data) { *status = CS_INVALID_HANDLE; - return wpi::StringRef{}; + return {}; } return data->source->GetName(); } @@ -215,19 +216,19 @@ std::string GetSourceDescription(CS_Source source, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data) { *status = CS_INVALID_HANDLE; - return std::string{}; + return {}; } wpi::SmallString<128> buf; - return data->source->GetDescription(buf); + return std::string{data->source->GetDescription(buf)}; } -wpi::StringRef GetSourceDescription(CS_Source source, - wpi::SmallVectorImpl& buf, - CS_Status* status) { +std::string_view GetSourceDescription(CS_Source source, + wpi::SmallVectorImpl& buf, + CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data) { *status = CS_INVALID_HANDLE; - return wpi::StringRef{}; + return {}; } return data->source->GetDescription(buf); } @@ -270,7 +271,7 @@ bool IsSourceEnabled(CS_Source source, CS_Status* status) { return data->source->IsEnabled(); } -CS_Property GetSourceProperty(CS_Source source, const wpi::Twine& name, +CS_Property GetSourceProperty(CS_Source source, std::string_view name, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data) { @@ -349,7 +350,7 @@ bool SetSourceFPS(CS_Source source, int fps, CS_Status* status) { return data->source->SetFPS(fps, status); } -bool SetSourceConfigJson(CS_Source source, wpi::StringRef config, +bool SetSourceConfigJson(CS_Source source, std::string_view config, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data) { @@ -531,17 +532,17 @@ std::string GetSinkName(CS_Sink sink, CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data) { *status = CS_INVALID_HANDLE; - return std::string{}; + return {}; } - return data->sink->GetName(); + return std::string{data->sink->GetName()}; } -wpi::StringRef GetSinkName(CS_Sink sink, wpi::SmallVectorImpl& buf, - CS_Status* status) { +std::string_view GetSinkName(CS_Sink sink, wpi::SmallVectorImpl& buf, + CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data) { *status = CS_INVALID_HANDLE; - return wpi::StringRef{}; + return {}; } return data->sink->GetName(); } @@ -550,23 +551,24 @@ std::string GetSinkDescription(CS_Sink sink, CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data) { *status = CS_INVALID_HANDLE; - return std::string{}; + return {}; } wpi::SmallString<128> buf; - return data->sink->GetDescription(buf); + return std::string{data->sink->GetDescription(buf)}; } -wpi::StringRef GetSinkDescription(CS_Sink sink, wpi::SmallVectorImpl& buf, - CS_Status* status) { +std::string_view GetSinkDescription(CS_Sink sink, + wpi::SmallVectorImpl& buf, + CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data) { *status = CS_INVALID_HANDLE; - return wpi::StringRef{}; + return {}; } return data->sink->GetDescription(buf); } -CS_Property GetSinkProperty(CS_Sink sink, const wpi::Twine& name, +CS_Property GetSinkProperty(CS_Sink sink, std::string_view name, CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data) { @@ -596,7 +598,8 @@ wpi::ArrayRef EnumerateSinkProperties( return vec; } -bool SetSinkConfigJson(CS_Sink sink, wpi::StringRef config, CS_Status* status) { +bool SetSinkConfigJson(CS_Sink sink, std::string_view config, + CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data) { *status = CS_INVALID_HANDLE; @@ -663,7 +666,7 @@ CS_Source GetSinkSource(CS_Sink sink, CS_Status* status) { return data->sourceHandle.load(); } -CS_Property GetSinkSourceProperty(CS_Sink sink, const wpi::Twine& name, +CS_Property GetSinkSourceProperty(CS_Sink sink, std::string_view name, CS_Status* status) { auto data = Instance::GetInstance().GetSink(sink); if (!data) { diff --git a/cscore/src/main/native/cpp/cscore_oo.cpp b/cscore/src/main/native/cpp/cscore_oo.cpp index 86e549074f..cca5ba73dd 100644 --- a/cscore/src/main/native/cpp/cscore_oo.cpp +++ b/cscore/src/main/native/cpp/cscore_oo.cpp @@ -4,6 +4,7 @@ #include "cscore_oo.h" +#include #include using namespace cs; @@ -82,3 +83,7 @@ std::vector VideoSink::EnumerateSinks() { } return sinks; } + +std::string AxisCamera::HostToUrl(std::string_view host) { + return fmt::format("http://{}/mjpg/video.mjpg", host); +} diff --git a/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp b/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp index a603fbf820..afdf566787 100644 --- a/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp +++ b/cscore/src/main/native/cpp/jni/CameraServerJNI.cpp @@ -4,10 +4,10 @@ #include +#include #include #include #include -#include #include "cscore_cpp.h" #include "cscore_cv.h" @@ -197,7 +197,8 @@ static void ReportError(JNIEnv* env, CS_Status status) { if (status == CS_OK) { return; } - wpi::SmallString<64> msg; + std::string_view msg; + std::string msgBuf; switch (status) { case CS_PROPERTY_WRITE_FAILED: msg = "property write failed"; @@ -230,8 +231,8 @@ static void ReportError(JNIEnv* env, CS_Status status) { msg = "telemetry not enabled"; break; default: { - wpi::raw_svector_ostream oss{msg}; - oss << "unknown error code=" << status; + msgBuf = fmt::format("unknown error code={}", status); + msg = msgBuf; break; } } @@ -577,7 +578,7 @@ Java_edu_wpi_first_cscore_CameraServerJNI_createHttpCameraMulti // TODO return 0; } - vec.push_back(JStringRef{env, elem}.str()); + vec.emplace_back(JStringRef{env, elem}.str()); } CS_Status status = 0; auto val = @@ -1172,7 +1173,7 @@ Java_edu_wpi_first_cscore_CameraServerJNI_setHttpCameraUrls // TODO return; } - vec.push_back(JStringRef{env, elem}.str()); + vec.emplace_back(JStringRef{env, elem}.str()); } CS_Status status = 0; cs::SetHttpCameraUrls(source, vec, &status); @@ -1353,7 +1354,7 @@ Java_edu_wpi_first_cscore_CameraServerJNI_setSourceEnumPropertyChoices // TODO return; } - vec.push_back(JStringRef{env, elem}.str()); + vec.emplace_back(JStringRef{env, elem}.str()); } CS_Status status = 0; cs::SetSourceEnumPropertyChoices(source, property, vec, &status); diff --git a/cscore/src/main/native/include/cscore_cpp.h b/cscore/src/main/native/include/cscore_cpp.h index 52f6f5f93c..593ad08936 100644 --- a/cscore/src/main/native/include/cscore_cpp.h +++ b/cscore/src/main/native/include/cscore_cpp.h @@ -9,12 +9,11 @@ #include #include +#include #include #include #include -#include -#include #include "cscore_c.h" @@ -122,8 +121,8 @@ struct RawEvent { RawEvent() = default; explicit RawEvent(RawEvent::Kind kind_) : kind{kind_} {} - RawEvent(const wpi::Twine& name_, CS_Handle handle_, RawEvent::Kind kind_) - : kind{kind_}, name{name_.str()} { + RawEvent(std::string_view name_, CS_Handle handle_, RawEvent::Kind kind_) + : kind{kind_}, name{name_} { if (kind_ == kSinkCreated || kind_ == kSinkDestroyed || kind_ == kSinkEnabled || kind_ == kSinkDisabled) { sinkHandle = handle_; @@ -131,21 +130,21 @@ struct RawEvent { sourceHandle = handle_; } } - RawEvent(const wpi::Twine& name_, CS_Source source_, const VideoMode& mode_) + RawEvent(std::string_view name_, CS_Source source_, const VideoMode& mode_) : kind{kSourceVideoModeChanged}, sourceHandle{source_}, - name{name_.str()}, + name{name_}, mode{mode_} {} - RawEvent(const wpi::Twine& name_, CS_Source source_, RawEvent::Kind kind_, + RawEvent(std::string_view name_, CS_Source source_, RawEvent::Kind kind_, CS_Property property_, CS_PropertyKind propertyKind_, int value_, - const wpi::Twine& valueStr_) + std::string_view valueStr_) : kind{kind_}, sourceHandle{source_}, - name{name_.str()}, + name{name_}, propertyHandle{property_}, propertyKind{propertyKind_}, value{value_}, - valueStr{valueStr_.str()} {} + valueStr{valueStr_} {} Kind kind; @@ -175,9 +174,9 @@ struct RawEvent { */ CS_PropertyKind GetPropertyKind(CS_Property property, CS_Status* status); std::string GetPropertyName(CS_Property property, CS_Status* status); -wpi::StringRef GetPropertyName(CS_Property property, - wpi::SmallVectorImpl& buf, - CS_Status* status); +std::string_view GetPropertyName(CS_Property property, + wpi::SmallVectorImpl& buf, + CS_Status* status); int GetProperty(CS_Property property, CS_Status* status); void SetProperty(CS_Property property, int value, CS_Status* status); int GetPropertyMin(CS_Property property, CS_Status* status); @@ -185,10 +184,10 @@ int GetPropertyMax(CS_Property property, CS_Status* status); int GetPropertyStep(CS_Property property, CS_Status* status); int GetPropertyDefault(CS_Property property, CS_Status* status); std::string GetStringProperty(CS_Property property, CS_Status* status); -wpi::StringRef GetStringProperty(CS_Property property, - wpi::SmallVectorImpl& buf, - CS_Status* status); -void SetStringProperty(CS_Property property, const wpi::Twine& value, +std::string_view GetStringProperty(CS_Property property, + wpi::SmallVectorImpl& buf, + CS_Status* status); +void SetStringProperty(CS_Property property, std::string_view value, CS_Status* status); std::vector GetEnumPropertyChoices(CS_Property property, CS_Status* status); @@ -198,16 +197,15 @@ std::vector GetEnumPropertyChoices(CS_Property property, * @defgroup cscore_source_create_func Source Creation Functions * @{ */ -CS_Source CreateUsbCameraDev(const wpi::Twine& name, int dev, - CS_Status* status); -CS_Source CreateUsbCameraPath(const wpi::Twine& name, const wpi::Twine& path, +CS_Source CreateUsbCameraDev(std::string_view name, int dev, CS_Status* status); +CS_Source CreateUsbCameraPath(std::string_view name, std::string_view path, CS_Status* status); -CS_Source CreateHttpCamera(const wpi::Twine& name, const wpi::Twine& url, +CS_Source CreateHttpCamera(std::string_view name, std::string_view url, CS_HttpCameraKind kind, CS_Status* status); -CS_Source CreateHttpCamera(const wpi::Twine& name, +CS_Source CreateHttpCamera(std::string_view name, wpi::ArrayRef urls, CS_HttpCameraKind kind, CS_Status* status); -CS_Source CreateCvSource(const wpi::Twine& name, const VideoMode& mode, +CS_Source CreateCvSource(std::string_view name, const VideoMode& mode, CS_Status* status); /** @} */ @@ -217,19 +215,20 @@ CS_Source CreateCvSource(const wpi::Twine& name, const VideoMode& mode, */ CS_SourceKind GetSourceKind(CS_Source source, CS_Status* status); std::string GetSourceName(CS_Source source, CS_Status* status); -wpi::StringRef GetSourceName(CS_Source source, wpi::SmallVectorImpl& buf, - CS_Status* status); +std::string_view GetSourceName(CS_Source source, + wpi::SmallVectorImpl& buf, + CS_Status* status); std::string GetSourceDescription(CS_Source source, CS_Status* status); -wpi::StringRef GetSourceDescription(CS_Source source, - wpi::SmallVectorImpl& buf, - CS_Status* status); +std::string_view GetSourceDescription(CS_Source source, + wpi::SmallVectorImpl& buf, + CS_Status* status); uint64_t GetSourceLastFrameTime(CS_Source source, CS_Status* status); void SetSourceConnectionStrategy(CS_Source source, CS_ConnectionStrategy strategy, CS_Status* status); bool IsSourceConnected(CS_Source source, CS_Status* status); bool IsSourceEnabled(CS_Source source, CS_Status* status); -CS_Property GetSourceProperty(CS_Source source, const wpi::Twine& name, +CS_Property GetSourceProperty(CS_Source source, std::string_view name, CS_Status* status); wpi::ArrayRef EnumerateSourceProperties( CS_Source source, wpi::SmallVectorImpl& vec, @@ -242,7 +241,7 @@ bool SetSourcePixelFormat(CS_Source source, VideoMode::PixelFormat pixelFormat, bool SetSourceResolution(CS_Source source, int width, int height, CS_Status* status); bool SetSourceFPS(CS_Source source, int fps, CS_Status* status); -bool SetSourceConfigJson(CS_Source source, wpi::StringRef config, +bool SetSourceConfigJson(CS_Source source, std::string_view config, CS_Status* status); bool SetSourceConfigJson(CS_Source source, const wpi::json& config, CS_Status* status); @@ -276,7 +275,7 @@ void SetCameraExposureManual(CS_Source source, int value, CS_Status* status); * @defgroup cscore_usbcamera_func UsbCamera Source Functions * @{ */ -void SetUsbCameraPath(CS_Source, const wpi::Twine& path, CS_Status* status); +void SetUsbCameraPath(CS_Source, std::string_view path, CS_Status* status); std::string GetUsbCameraPath(CS_Source source, CS_Status* status); UsbCameraInfo GetUsbCameraInfo(CS_Source source, CS_Status* status); /** @} */ @@ -295,12 +294,12 @@ std::vector GetHttpCameraUrls(CS_Source source, CS_Status* status); * @defgroup cscore_opencv_source_func OpenCV Source Functions * @{ */ -void NotifySourceError(CS_Source source, const wpi::Twine& msg, +void NotifySourceError(CS_Source source, std::string_view msg, CS_Status* status); void SetSourceConnected(CS_Source source, bool connected, CS_Status* status); -void SetSourceDescription(CS_Source source, const wpi::Twine& description, +void SetSourceDescription(CS_Source source, std::string_view description, CS_Status* status); -CS_Property CreateSourceProperty(CS_Source source, const wpi::Twine& name, +CS_Property CreateSourceProperty(CS_Source source, std::string_view name, CS_PropertyKind kind, int minimum, int maximum, int step, int defaultValue, int value, CS_Status* status); @@ -313,11 +312,10 @@ void SetSourceEnumPropertyChoices(CS_Source source, CS_Property property, * @defgroup cscore_sink_create_func Sink Creation Functions * @{ */ -CS_Sink CreateMjpegServer(const wpi::Twine& name, - const wpi::Twine& listenAddress, int port, - CS_Status* status); -CS_Sink CreateCvSink(const wpi::Twine& name, CS_Status* status); -CS_Sink CreateCvSinkCallback(const wpi::Twine& name, +CS_Sink CreateMjpegServer(std::string_view name, std::string_view listenAddress, + int port, CS_Status* status); +CS_Sink CreateCvSink(std::string_view name, CS_Status* status); +CS_Sink CreateCvSinkCallback(std::string_view name, std::function processFrame, CS_Status* status); @@ -329,19 +327,21 @@ CS_Sink CreateCvSinkCallback(const wpi::Twine& name, */ CS_SinkKind GetSinkKind(CS_Sink sink, CS_Status* status); std::string GetSinkName(CS_Sink sink, CS_Status* status); -wpi::StringRef GetSinkName(CS_Sink sink, wpi::SmallVectorImpl& buf, - CS_Status* status); +std::string_view GetSinkName(CS_Sink sink, wpi::SmallVectorImpl& buf, + CS_Status* status); std::string GetSinkDescription(CS_Sink sink, CS_Status* status); -wpi::StringRef GetSinkDescription(CS_Sink sink, wpi::SmallVectorImpl& buf, - CS_Status* status); -CS_Property GetSinkProperty(CS_Sink sink, const wpi::Twine& name, +std::string_view GetSinkDescription(CS_Sink sink, + wpi::SmallVectorImpl& buf, + CS_Status* status); +CS_Property GetSinkProperty(CS_Sink sink, std::string_view name, CS_Status* status); wpi::ArrayRef EnumerateSinkProperties( CS_Sink sink, wpi::SmallVectorImpl& vec, CS_Status* status); void SetSinkSource(CS_Sink sink, CS_Source source, CS_Status* status); -CS_Property GetSinkSourceProperty(CS_Sink sink, const wpi::Twine& name, +CS_Property GetSinkSourceProperty(CS_Sink sink, std::string_view name, CS_Status* status); -bool SetSinkConfigJson(CS_Sink sink, wpi::StringRef config, CS_Status* status); +bool SetSinkConfigJson(CS_Sink sink, std::string_view config, + CS_Status* status); bool SetSinkConfigJson(CS_Sink sink, const wpi::json& config, CS_Status* status); std::string GetSinkConfigJson(CS_Sink sink, CS_Status* status); @@ -363,11 +363,11 @@ int GetMjpegServerPort(CS_Sink sink, CS_Status* status); * @defgroup cscore_opencv_sink_func OpenCV Sink Functions * @{ */ -void SetSinkDescription(CS_Sink sink, const wpi::Twine& description, +void SetSinkDescription(CS_Sink sink, std::string_view description, CS_Status* status); std::string GetSinkError(CS_Sink sink, CS_Status* status); -wpi::StringRef GetSinkError(CS_Sink sink, wpi::SmallVectorImpl& buf, - CS_Status* status); +std::string_view GetSinkError(CS_Sink sink, wpi::SmallVectorImpl& buf, + CS_Status* status); void SetSinkEnabled(CS_Sink sink, bool enabled, CS_Status* status); /** @} */ diff --git a/cscore/src/main/native/include/cscore_cv.h b/cscore/src/main/native/include/cscore_cv.h index 45baf08739..6911ae2fa1 100644 --- a/cscore/src/main/native/include/cscore_cv.h +++ b/cscore/src/main/native/include/cscore_cv.h @@ -82,7 +82,7 @@ class CvSource : public ImageSource { * @param name Source name (arbitrary unique identifier) * @param mode Video mode being generated */ - CvSource(const wpi::Twine& name, const VideoMode& mode); + CvSource(std::string_view name, const VideoMode& mode); /** * Create an OpenCV source. @@ -93,8 +93,8 @@ class CvSource : public ImageSource { * @param height height * @param fps fps */ - CvSource(const wpi::Twine& name, VideoMode::PixelFormat pixelFormat, - int width, int height, int fps); + CvSource(std::string_view name, VideoMode::PixelFormat pixelFormat, int width, + int height, int fps); /** * Put an OpenCV image and notify sinks. @@ -126,7 +126,7 @@ class CvSink : public ImageSink { * * @param name Source name (arbitrary unique identifier) */ - explicit CvSink(const wpi::Twine& name); + explicit CvSink(std::string_view name); /** * Create a sink for accepting OpenCV images in a separate thread. @@ -140,7 +140,7 @@ class CvSink : public ImageSink { * or GetError() as needed, but should not call (except in very * unusual circumstances) WaitForImage(). */ - CvSink(const wpi::Twine& name, + CvSink(std::string_view name, std::function processFrame); /** @@ -165,11 +165,11 @@ class CvSink : public ImageSink { uint64_t GrabFrameNoTimeout(cv::Mat& image) const; }; -inline CvSource::CvSource(const wpi::Twine& name, const VideoMode& mode) { +inline CvSource::CvSource(std::string_view name, const VideoMode& mode) { m_handle = CreateCvSource(name, mode, &m_status); } -inline CvSource::CvSource(const wpi::Twine& name, VideoMode::PixelFormat format, +inline CvSource::CvSource(std::string_view name, VideoMode::PixelFormat format, int width, int height, int fps) { m_handle = CreateCvSource(name, VideoMode{format, width, height, fps}, &m_status); @@ -180,11 +180,11 @@ inline void CvSource::PutFrame(cv::Mat& image) { PutSourceFrame(m_handle, image, &m_status); } -inline CvSink::CvSink(const wpi::Twine& name) { +inline CvSink::CvSink(std::string_view name) { m_handle = CreateCvSink(name, &m_status); } -inline CvSink::CvSink(const wpi::Twine& name, +inline CvSink::CvSink(std::string_view name, std::function processFrame) { m_handle = CreateCvSinkCallback(name, processFrame, &m_status); } diff --git a/cscore/src/main/native/include/cscore_oo.h b/cscore/src/main/native/include/cscore_oo.h index 138495d5c7..384d5230b2 100644 --- a/cscore/src/main/native/include/cscore_oo.h +++ b/cscore/src/main/native/include/cscore_oo.h @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -71,8 +72,8 @@ class VideoProperty { // String-specific functions std::string GetString() const; - wpi::StringRef GetString(wpi::SmallVectorImpl& buf) const; - void SetString(const wpi::Twine& value); + std::string_view GetString(wpi::SmallVectorImpl& buf) const; + void SetString(std::string_view value); // Enum-specific functions std::vector GetChoices() const; @@ -194,7 +195,7 @@ class VideoSource { * @return Property contents (of kind Property::kNone if no property with * the given name exists) */ - VideoProperty GetProperty(const wpi::Twine& name); + VideoProperty GetProperty(std::string_view name); /** * Enumerate all properties of this source. @@ -276,7 +277,7 @@ class VideoSource { * @param config configuration * @return True if set successfully */ - bool SetConfigJson(wpi::StringRef config); + bool SetConfigJson(std::string_view config); /** * Set video mode and properties from a JSON configuration object. @@ -424,7 +425,7 @@ class UsbCamera : public VideoCamera { * @param name Source name (arbitrary unique identifier) * @param dev Device number (e.g. 0 for /dev/video0) */ - UsbCamera(const wpi::Twine& name, int dev); + UsbCamera(std::string_view name, int dev); /** * Create a source for a USB camera based on device path. @@ -432,7 +433,7 @@ class UsbCamera : public VideoCamera { * @param name Source name (arbitrary unique identifier) * @param path Path to device (e.g. "/dev/video0" on Linux) */ - UsbCamera(const wpi::Twine& name, const wpi::Twine& path); + UsbCamera(std::string_view name, std::string_view path); /** * Enumerate USB cameras on the local system. @@ -444,7 +445,7 @@ class UsbCamera : public VideoCamera { /** * Change the path to the device. */ - void SetPath(const wpi::Twine& path); + void SetPath(std::string_view path); /** * Get the path to the device. @@ -483,7 +484,7 @@ class HttpCamera : public VideoCamera { * @param url Camera URL (e.g. "http://10.x.y.11/video/stream.mjpg") * @param kind Camera kind (e.g. kAxis) */ - HttpCamera(const wpi::Twine& name, const wpi::Twine& url, + HttpCamera(std::string_view name, std::string_view url, HttpCameraKind kind = kUnknown); /** @@ -493,7 +494,7 @@ class HttpCamera : public VideoCamera { * @param url Camera URL (e.g. "http://10.x.y.11/video/stream.mjpg") * @param kind Camera kind (e.g. kAxis) */ - HttpCamera(const wpi::Twine& name, const char* url, + HttpCamera(std::string_view name, const char* url, HttpCameraKind kind = kUnknown); /** @@ -503,7 +504,7 @@ class HttpCamera : public VideoCamera { * @param url Camera URL (e.g. "http://10.x.y.11/video/stream.mjpg") * @param kind Camera kind (e.g. kAxis) */ - HttpCamera(const wpi::Twine& name, const std::string& url, + HttpCamera(std::string_view name, const std::string& url, HttpCameraKind kind = kUnknown); /** @@ -513,7 +514,7 @@ class HttpCamera : public VideoCamera { * @param urls Array of Camera URLs * @param kind Camera kind (e.g. kAxis) */ - HttpCamera(const wpi::Twine& name, wpi::ArrayRef urls, + HttpCamera(std::string_view name, wpi::ArrayRef urls, HttpCameraKind kind = kUnknown); /** @@ -524,7 +525,7 @@ class HttpCamera : public VideoCamera { * @param kind Camera kind (e.g. kAxis) */ template - HttpCamera(const wpi::Twine& name, std::initializer_list urls, + HttpCamera(std::string_view name, std::initializer_list urls, HttpCameraKind kind = kUnknown); /** @@ -556,7 +557,7 @@ class HttpCamera : public VideoCamera { * A source that represents an Axis IP camera. */ class AxisCamera : public HttpCamera { - static std::string HostToUrl(const wpi::Twine& host); + static std::string HostToUrl(std::string_view host); static std::vector HostToUrl(wpi::ArrayRef hosts); template static std::vector HostToUrl(std::initializer_list hosts); @@ -569,7 +570,7 @@ class AxisCamera : public HttpCamera { * @param host Camera host IP or DNS name (e.g. "10.x.y.11") * @param kind Camera kind (e.g. kAxis) */ - AxisCamera(const wpi::Twine& name, const wpi::Twine& host); + AxisCamera(std::string_view name, std::string_view host); /** * Create a source for an Axis IP camera. @@ -578,7 +579,7 @@ class AxisCamera : public HttpCamera { * @param host Camera host IP or DNS name (e.g. "10.x.y.11") * @param kind Camera kind (e.g. kAxis) */ - AxisCamera(const wpi::Twine& name, const char* host); + AxisCamera(std::string_view name, const char* host); /** * Create a source for an Axis IP camera. @@ -587,16 +588,7 @@ class AxisCamera : public HttpCamera { * @param host Camera host IP or DNS name (e.g. "10.x.y.11") * @param kind Camera kind (e.g. kAxis) */ - AxisCamera(const wpi::Twine& name, const std::string& host); - - /** - * Create a source for an Axis IP camera. - * - * @param name Source name (arbitrary unique identifier) - * @param host Camera host IP or DNS name (e.g. "10.x.y.11") - * @param kind Camera kind (e.g. kAxis) - */ - AxisCamera(const wpi::Twine& name, wpi::StringRef host); + AxisCamera(std::string_view name, const std::string& host); /** * Create a source for an Axis IP camera. @@ -605,7 +597,7 @@ class AxisCamera : public HttpCamera { * @param hosts Array of Camera host IPs/DNS names * @param kind Camera kind (e.g. kAxis) */ - AxisCamera(const wpi::Twine& name, wpi::ArrayRef hosts); + AxisCamera(std::string_view name, wpi::ArrayRef hosts); /** * Create a source for an Axis IP camera. @@ -615,7 +607,7 @@ class AxisCamera : public HttpCamera { * @param kind Camera kind (e.g. kAxis) */ template - AxisCamera(const wpi::Twine& name, std::initializer_list hosts); + AxisCamera(std::string_view name, std::initializer_list hosts); }; /** @@ -630,7 +622,7 @@ class ImageSource : public VideoSource { * Signal sinks that an error has occurred. This should be called instead * of NotifyFrame when an error occurs. */ - void NotifyError(const wpi::Twine& msg); + void NotifyError(std::string_view msg); /** * Set source connection status. Defaults to true. @@ -644,7 +636,7 @@ class ImageSource : public VideoSource { * * @param description Description */ - void SetDescription(const wpi::Twine& description); + void SetDescription(std::string_view description); /** * Create a property. @@ -658,7 +650,7 @@ class ImageSource : public VideoSource { * @param value Current value * @return Property */ - VideoProperty CreateProperty(const wpi::Twine& name, VideoProperty::Kind kind, + VideoProperty CreateProperty(std::string_view name, VideoProperty::Kind kind, int minimum, int maximum, int step, int defaultValue, int value); @@ -673,7 +665,7 @@ class ImageSource : public VideoSource { * @param value Current value * @return Property */ - VideoProperty CreateIntegerProperty(const wpi::Twine& name, int minimum, + VideoProperty CreateIntegerProperty(std::string_view name, int minimum, int maximum, int step, int defaultValue, int value); @@ -685,7 +677,7 @@ class ImageSource : public VideoSource { * @param value Current value * @return Property */ - VideoProperty CreateBooleanProperty(const wpi::Twine& name, bool defaultValue, + VideoProperty CreateBooleanProperty(std::string_view name, bool defaultValue, bool value); /** @@ -696,8 +688,8 @@ class ImageSource : public VideoSource { * @param value Current value * @return Property */ - VideoProperty CreateStringProperty(const wpi::Twine& name, - const wpi::Twine& value); + VideoProperty CreateStringProperty(std::string_view name, + std::string_view value); /** * Configure enum property choices. @@ -772,7 +764,7 @@ class VideoSink { * @return Property (kind Property::kNone if no property with * the given name exists) */ - VideoProperty GetProperty(const wpi::Twine& name); + VideoProperty GetProperty(std::string_view name); /** * Enumerate all properties of this sink. @@ -798,7 +790,7 @@ class VideoSink { * @param config configuration * @return True if set successfully */ - bool SetConfigJson(wpi::StringRef config); + bool SetConfigJson(std::string_view config); /** * Set properties from a JSON configuration object. @@ -845,7 +837,7 @@ class VideoSink { * @return Property (kind Property::kNone if no property with * the given name exists or no source connected) */ - VideoProperty GetSourceProperty(const wpi::Twine& name); + VideoProperty GetSourceProperty(std::string_view name); CS_Status GetLastStatus() const { return m_status; } @@ -883,8 +875,7 @@ class MjpegServer : public VideoSink { * @param listenAddress TCP listen address (empty string for all addresses) * @param port TCP port number */ - MjpegServer(const wpi::Twine& name, const wpi::Twine& listenAddress, - int port); + MjpegServer(std::string_view name, std::string_view listenAddress, int port); /** * Create a MJPEG-over-HTTP server sink. @@ -892,7 +883,7 @@ class MjpegServer : public VideoSink { * @param name Sink name (arbitrary unique identifier) * @param port TCP port number */ - MjpegServer(const wpi::Twine& name, int port) : MjpegServer(name, "", port) {} + MjpegServer(std::string_view name, int port) : MjpegServer(name, "", port) {} /** * Get the listen address of the server. @@ -963,7 +954,7 @@ class ImageSink : public VideoSink { * * @param description Description */ - void SetDescription(const wpi::Twine& description); + void SetDescription(std::string_view description); /** * Get error string. Call this if WaitForFrame() returns 0 to determine diff --git a/cscore/src/main/native/include/cscore_oo.inc b/cscore/src/main/native/include/cscore_oo.inc index 887bd74522..878462afdb 100644 --- a/cscore/src/main/native/include/cscore_oo.inc +++ b/cscore/src/main/native/include/cscore_oo.inc @@ -6,6 +6,7 @@ #define CSCORE_CSCORE_OO_INC_ #include +#include #include #include @@ -53,13 +54,13 @@ inline std::string VideoProperty::GetString() const { return GetStringProperty(m_handle, &m_status); } -inline wpi::StringRef VideoProperty::GetString( +inline std::string_view VideoProperty::GetString( wpi::SmallVectorImpl& buf) const { m_status = 0; return GetStringProperty(m_handle, buf, &m_status); } -inline void VideoProperty::SetString(const wpi::Twine& value) { +inline void VideoProperty::SetString(std::string_view value) { m_status = 0; SetStringProperty(m_handle, value, &m_status); } @@ -139,7 +140,7 @@ inline bool VideoSource::IsEnabled() const { return IsSourceEnabled(m_handle, &m_status); } -inline VideoProperty VideoSource::GetProperty(const wpi::Twine& name) { +inline VideoProperty VideoSource::GetProperty(std::string_view name) { m_status = 0; return VideoProperty{GetSourceProperty(m_handle, name, &m_status)}; } @@ -176,7 +177,7 @@ inline bool VideoSource::SetFPS(int fps) { return SetSourceFPS(m_handle, fps, &m_status); } -inline bool VideoSource::SetConfigJson(wpi::StringRef config) { +inline bool VideoSource::SetConfigJson(std::string_view config) { m_status = 0; return SetSourceConfigJson(m_handle, config, &m_status); } @@ -248,11 +249,11 @@ inline void VideoCamera::SetExposureManual(int value) { SetCameraExposureManual(m_handle, value, &m_status); } -inline UsbCamera::UsbCamera(const wpi::Twine& name, int dev) { +inline UsbCamera::UsbCamera(std::string_view name, int dev) { m_handle = CreateUsbCameraDev(name, dev, &m_status); } -inline UsbCamera::UsbCamera(const wpi::Twine& name, const wpi::Twine& path) { +inline UsbCamera::UsbCamera(std::string_view name, std::string_view path) { m_handle = CreateUsbCameraPath(name, path, &m_status); } @@ -261,7 +262,7 @@ inline std::vector UsbCamera::EnumerateUsbCameras() { return ::cs::EnumerateUsbCameras(&status); } -inline void UsbCamera::SetPath(const wpi::Twine& path) { +inline void UsbCamera::SetPath(std::string_view path) { m_status = 0; return ::cs::SetUsbCameraPath(m_handle, path, &m_status); } @@ -282,25 +283,25 @@ inline void UsbCamera::SetConnectVerbose(int level) { &m_status); } -inline HttpCamera::HttpCamera(const wpi::Twine& name, const wpi::Twine& url, +inline HttpCamera::HttpCamera(std::string_view name, std::string_view url, HttpCameraKind kind) { m_handle = CreateHttpCamera( name, url, static_cast(static_cast(kind)), &m_status); } -inline HttpCamera::HttpCamera(const wpi::Twine& name, const char* url, +inline HttpCamera::HttpCamera(std::string_view name, const char* url, HttpCameraKind kind) { m_handle = CreateHttpCamera( name, url, static_cast(static_cast(kind)), &m_status); } -inline HttpCamera::HttpCamera(const wpi::Twine& name, const std::string& url, +inline HttpCamera::HttpCamera(std::string_view name, const std::string& url, HttpCameraKind kind) - : HttpCamera(name, wpi::Twine{url}, kind) {} + : HttpCamera(name, std::string_view{url}, kind) {} -inline HttpCamera::HttpCamera(const wpi::Twine& name, +inline HttpCamera::HttpCamera(std::string_view name, wpi::ArrayRef urls, HttpCameraKind kind) { m_handle = CreateHttpCamera( @@ -309,7 +310,7 @@ inline HttpCamera::HttpCamera(const wpi::Twine& name, } template -inline HttpCamera::HttpCamera(const wpi::Twine& name, +inline HttpCamera::HttpCamera(std::string_view name, std::initializer_list urls, HttpCameraKind kind) { std::vector vec; @@ -349,16 +350,12 @@ inline std::vector HttpCamera::GetUrls() const { return ::cs::GetHttpCameraUrls(m_handle, &m_status); } -inline std::string AxisCamera::HostToUrl(const wpi::Twine& host) { - return ("http://" + host + "/mjpg/video.mjpg").str(); -} - inline std::vector AxisCamera::HostToUrl( wpi::ArrayRef hosts) { std::vector rv; rv.reserve(hosts.size()); for (const auto& host : hosts) { - rv.emplace_back(HostToUrl(wpi::StringRef{host})); + rv.emplace_back(HostToUrl(std::string_view{host})); } return rv; } @@ -369,33 +366,30 @@ inline std::vector AxisCamera::HostToUrl( std::vector rv; rv.reserve(hosts.size()); for (const auto& host : hosts) { - rv.emplace_back(HostToUrl(wpi::StringRef{host})); + rv.emplace_back(HostToUrl(std::string_view{host})); } return rv; } -inline AxisCamera::AxisCamera(const wpi::Twine& name, const wpi::Twine& host) +inline AxisCamera::AxisCamera(std::string_view name, std::string_view host) : HttpCamera(name, HostToUrl(host), kAxis) {} -inline AxisCamera::AxisCamera(const wpi::Twine& name, const char* host) +inline AxisCamera::AxisCamera(std::string_view name, const char* host) : HttpCamera(name, HostToUrl(host), kAxis) {} -inline AxisCamera::AxisCamera(const wpi::Twine& name, const std::string& host) - : HttpCamera(name, HostToUrl(wpi::Twine{host}), kAxis) {} +inline AxisCamera::AxisCamera(std::string_view name, const std::string& host) + : HttpCamera(name, HostToUrl(std::string_view{host}), kAxis) {} -inline AxisCamera::AxisCamera(const wpi::Twine& name, wpi::StringRef host) - : HttpCamera(name, HostToUrl(host), kAxis) {} - -inline AxisCamera::AxisCamera(const wpi::Twine& name, +inline AxisCamera::AxisCamera(std::string_view name, wpi::ArrayRef hosts) : HttpCamera(name, HostToUrl(hosts), kAxis) {} template -inline AxisCamera::AxisCamera(const wpi::Twine& name, +inline AxisCamera::AxisCamera(std::string_view name, std::initializer_list hosts) : HttpCamera(name, HostToUrl(hosts), kAxis) {} -inline void ImageSource::NotifyError(const wpi::Twine& msg) { +inline void ImageSource::NotifyError(std::string_view msg) { m_status = 0; NotifySourceError(m_handle, msg, &m_status); } @@ -405,12 +399,12 @@ inline void ImageSource::SetConnected(bool connected) { SetSourceConnected(m_handle, connected, &m_status); } -inline void ImageSource::SetDescription(const wpi::Twine& description) { +inline void ImageSource::SetDescription(std::string_view description) { m_status = 0; SetSourceDescription(m_handle, description, &m_status); } -inline VideoProperty ImageSource::CreateProperty(const wpi::Twine& name, +inline VideoProperty ImageSource::CreateProperty(std::string_view name, VideoProperty::Kind kind, int minimum, int maximum, int step, int defaultValue, @@ -421,7 +415,7 @@ inline VideoProperty ImageSource::CreateProperty(const wpi::Twine& name, minimum, maximum, step, defaultValue, value, &m_status)}; } -inline VideoProperty ImageSource::CreateIntegerProperty(const wpi::Twine& name, +inline VideoProperty ImageSource::CreateIntegerProperty(std::string_view name, int minimum, int maximum, int step, int defaultValue, @@ -434,7 +428,7 @@ inline VideoProperty ImageSource::CreateIntegerProperty(const wpi::Twine& name, minimum, maximum, step, defaultValue, value, &m_status)}; } -inline VideoProperty ImageSource::CreateBooleanProperty(const wpi::Twine& name, +inline VideoProperty ImageSource::CreateBooleanProperty(std::string_view name, bool defaultValue, bool value) { m_status = 0; @@ -445,8 +439,8 @@ inline VideoProperty ImageSource::CreateBooleanProperty(const wpi::Twine& name, 0, 1, 1, defaultValue ? 1 : 0, value ? 1 : 0, &m_status)}; } -inline VideoProperty ImageSource::CreateStringProperty( - const wpi::Twine& name, const wpi::Twine& value) { +inline VideoProperty ImageSource::CreateStringProperty(std::string_view name, + std::string_view value) { m_status = 0; auto prop = VideoProperty{ CreateSourceProperty(m_handle, name, @@ -509,7 +503,7 @@ inline std::string VideoSink::GetDescription() const { return GetSinkDescription(m_handle, &m_status); } -inline VideoProperty VideoSink::GetProperty(const wpi::Twine& name) { +inline VideoProperty VideoSink::GetProperty(std::string_view name) { m_status = 0; return VideoProperty{GetSinkProperty(m_handle, name, &m_status)}; } @@ -529,12 +523,12 @@ inline VideoSource VideoSink::GetSource() const { return VideoSource{handle == 0 ? 0 : CopySource(handle, &m_status)}; } -inline VideoProperty VideoSink::GetSourceProperty(const wpi::Twine& name) { +inline VideoProperty VideoSink::GetSourceProperty(std::string_view name) { m_status = 0; return VideoProperty{GetSinkSourceProperty(m_handle, name, &m_status)}; } -inline bool VideoSink::SetConfigJson(wpi::StringRef config) { +inline bool VideoSink::SetConfigJson(std::string_view config) { m_status = 0; return SetSinkConfigJson(m_handle, config, &m_status); } @@ -549,8 +543,8 @@ inline std::string VideoSink::GetConfigJson() const { return GetSinkConfigJson(m_handle, &m_status); } -inline MjpegServer::MjpegServer(const wpi::Twine& name, - const wpi::Twine& listenAddress, int port) { +inline MjpegServer::MjpegServer(std::string_view name, + std::string_view listenAddress, int port) { m_handle = CreateMjpegServer(name, listenAddress, port, &m_status); } @@ -588,7 +582,7 @@ inline void MjpegServer::SetDefaultCompression(int quality) { quality, &m_status); } -inline void ImageSink::SetDescription(const wpi::Twine& description) { +inline void ImageSink::SetDescription(std::string_view description) { m_status = 0; SetSinkDescription(m_handle, description, &m_status); } diff --git a/cscore/src/main/native/include/cscore_raw.h b/cscore/src/main/native/include/cscore_raw.h index 5fc125d4cf..b52962855c 100644 --- a/cscore/src/main/native/include/cscore_raw.h +++ b/cscore/src/main/native/include/cscore_raw.h @@ -78,11 +78,11 @@ struct RawFrame : public CS_RawFrame { * @{ */ -CS_Source CreateRawSource(const wpi::Twine& name, const VideoMode& mode, +CS_Source CreateRawSource(std::string_view name, const VideoMode& mode, CS_Status* status); -CS_Sink CreateRawSink(const wpi::Twine& name, CS_Status* status); -CS_Sink CreateRawSinkCallback(const wpi::Twine& name, +CS_Sink CreateRawSink(std::string_view name, CS_Status* status); +CS_Sink CreateRawSinkCallback(std::string_view name, std::function processFrame, CS_Status* status); @@ -107,7 +107,7 @@ class RawSource : public ImageSource { * @param name Source name (arbitrary unique identifier) * @param mode Video mode being generated */ - RawSource(const wpi::Twine& name, const VideoMode& mode); + RawSource(std::string_view name, const VideoMode& mode); /** * Create a raw frame source. @@ -118,7 +118,7 @@ class RawSource : public ImageSource { * @param height height * @param fps fps */ - RawSource(const wpi::Twine& name, VideoMode::PixelFormat pixelFormat, + RawSource(std::string_view name, VideoMode::PixelFormat pixelFormat, int width, int height, int fps); protected: @@ -147,7 +147,7 @@ class RawSink : public ImageSink { * * @param name Source name (arbitrary unique identifier) */ - explicit RawSink(const wpi::Twine& name); + explicit RawSink(std::string_view name); /** * Create a sink for accepting raws images in a separate thread. @@ -161,7 +161,7 @@ class RawSink : public ImageSink { * or GetError() as needed, but should not call (except in very * unusual circumstances) WaitForImage(). */ - RawSink(const wpi::Twine& name, + RawSink(std::string_view name, std::function processFrame); protected: @@ -187,11 +187,11 @@ class RawSink : public ImageSink { uint64_t GrabFrameNoTimeout(RawFrame& image) const; }; -inline RawSource::RawSource(const wpi::Twine& name, const VideoMode& mode) { +inline RawSource::RawSource(std::string_view name, const VideoMode& mode) { m_handle = CreateRawSource(name, mode, &m_status); } -inline RawSource::RawSource(const wpi::Twine& name, +inline RawSource::RawSource(std::string_view name, VideoMode::PixelFormat format, int width, int height, int fps) { m_handle = @@ -203,11 +203,11 @@ inline void RawSource::PutFrame(RawFrame& image) { PutSourceFrame(m_handle, image, &m_status); } -inline RawSink::RawSink(const wpi::Twine& name) { +inline RawSink::RawSink(std::string_view name) { m_handle = CreateRawSink(name, &m_status); } -inline RawSink::RawSink(const wpi::Twine& name, +inline RawSink::RawSink(std::string_view name, std::function processFrame) { m_handle = CreateRawSinkCallback(name, processFrame, &m_status); } diff --git a/cscore/src/main/native/include/cscore_raw_cv.h b/cscore/src/main/native/include/cscore_raw_cv.h index 5a2b727e05..defd239857 100644 --- a/cscore/src/main/native/include/cscore_raw_cv.h +++ b/cscore/src/main/native/include/cscore_raw_cv.h @@ -32,7 +32,7 @@ class RawCvSource : public RawSource { * @param name Source name (arbitrary unique identifier) * @param mode Video mode being generated */ - RawCvSource(const wpi::Twine& name, const VideoMode& mode); + RawCvSource(std::string_view name, const VideoMode& mode); /** * Create a Raw OpenCV source. @@ -43,7 +43,7 @@ class RawCvSource : public RawSource { * @param height height * @param fps fps */ - RawCvSource(const wpi::Twine& name, VideoMode::PixelFormat pixelFormat, + RawCvSource(std::string_view name, VideoMode::PixelFormat pixelFormat, int width, int height, int fps); /** @@ -83,7 +83,7 @@ class RawCvSink : public RawSink { * * @param name Source name (arbitrary unique identifier) */ - explicit RawCvSink(const wpi::Twine& name); + explicit RawCvSink(std::string_view name); /** * Create a sink for accepting OpenCV images in a separate thread. @@ -97,7 +97,7 @@ class RawCvSink : public RawSink { * or GetError() as needed, but should not call (except in very * unusual circumstances) WaitForImage(). */ - RawCvSink(const wpi::Twine& name, + RawCvSink(std::string_view name, std::function processFrame); /** @@ -146,10 +146,10 @@ class RawCvSink : public RawSink { RawFrame rawFrame; }; -inline RawCvSource::RawCvSource(const wpi::Twine& name, const VideoMode& mode) +inline RawCvSource::RawCvSource(std::string_view name, const VideoMode& mode) : RawSource{name, mode} {} -inline RawCvSource::RawCvSource(const wpi::Twine& name, +inline RawCvSource::RawCvSource(std::string_view name, VideoMode::PixelFormat format, int width, int height, int fps) : RawSource{name, format, width, height, fps} {} @@ -164,9 +164,9 @@ inline void RawCvSource::PutFrame(cv::Mat& image) { PutSourceFrame(m_handle, rawFrame, &m_status); } -inline RawCvSink::RawCvSink(const wpi::Twine& name) : RawSink{name} {} +inline RawCvSink::RawCvSink(std::string_view name) : RawSink{name} {} -inline RawCvSink::RawCvSink(const wpi::Twine& name, +inline RawCvSink::RawCvSink(std::string_view name, std::function processFrame) : RawSink{name, processFrame} {} diff --git a/cscore/src/main/native/linux/NetworkListener.cpp b/cscore/src/main/native/linux/NetworkListener.cpp index bab556fb9b..1a0ac8b595 100644 --- a/cscore/src/main/native/linux/NetworkListener.cpp +++ b/cscore/src/main/native/linux/NetworkListener.cpp @@ -70,15 +70,15 @@ void NetworkListener::Impl::Thread::Main() { // Create event socket so we can be shut down m_command_fd = ::eventfd(0, 0); if (m_command_fd < 0) { - ERROR( - "NetworkListener: could not create eventfd: " << std::strerror(errno)); + ERROR("NetworkListener: could not create eventfd: {}", + std::strerror(errno)); return; } // Create netlink socket int sd = ::socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sd < 0) { - ERROR("NetworkListener: could not create socket: " << std::strerror(errno)); + ERROR("NetworkListener: could not create socket: {}", std::strerror(errno)); ::close(m_command_fd); m_command_fd = -1; return; @@ -90,7 +90,7 @@ void NetworkListener::Impl::Thread::Main() { addr.nl_family = AF_NETLINK; addr.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR; if (bind(sd, reinterpret_cast(&addr), sizeof(addr)) < 0) { - ERROR("NetworkListener: could not create socket: " << std::strerror(errno)); + ERROR("NetworkListener: could not create socket: {}", std::strerror(errno)); ::close(sd); ::close(m_command_fd); m_command_fd = -1; @@ -113,7 +113,7 @@ void NetworkListener::Impl::Thread::Main() { int nfds = std::max(m_command_fd, sd) + 1; if (::select(nfds, &readfds, nullptr, nullptr, &tv) < 0) { - ERROR("NetworkListener: select(): " << std::strerror(errno)); + ERROR("NetworkListener: select(): {}", std::strerror(errno)); break; // XXX: is this the right thing to do here? } @@ -134,8 +134,8 @@ void NetworkListener::Impl::Thread::Main() { if (errno == EWOULDBLOCK || errno == EAGAIN) { continue; } - ERROR( - "NetworkListener: could not read netlink: " << std::strerror(errno)); + ERROR("NetworkListener: could not read netlink: {}", + std::strerror(errno)); break; // XXX: is this the right thing to do here? } if (len == 0) { diff --git a/cscore/src/main/native/linux/UsbCameraImpl.cpp b/cscore/src/main/native/linux/UsbCameraImpl.cpp index 8a05bee765..3e84578d18 100644 --- a/cscore/src/main/native/linux/UsbCameraImpl.cpp +++ b/cscore/src/main/native/linux/UsbCameraImpl.cpp @@ -22,8 +22,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -95,8 +97,8 @@ static __u32 FromPixelFormat(VideoMode::PixelFormat pixelFormat) { } } -static bool IsPercentageProperty(wpi::StringRef name) { - if (name.startswith("raw_")) { +static bool IsPercentageProperty(std::string_view name) { + if (wpi::starts_with(name, "raw_")) { name = name.substr(4); } return name == "brightness" || name == "contrast" || name == "saturation" || @@ -154,11 +156,8 @@ int UsbCameraImpl::PercentageToRaw(const UsbCameraProperty& rawProp, } static bool GetVendorProduct(int dev, int* vendor, int* product) { - wpi::SmallString<64> ifpath; - { - wpi::raw_svector_ostream oss{ifpath}; - oss << "/sys/class/video4linux/video" << dev << "/device/modalias"; - } + auto ifpath = + fmt::format("/sys/class/video4linux/video{}/device/modalias", dev); int fd = open(ifpath.c_str(), O_RDONLY); if (fd < 0) { @@ -172,15 +171,17 @@ static bool GetVendorProduct(int dev, int* vendor, int* product) { if (n <= 0) { return false; } - wpi::StringRef readStr{readBuf}; - if (readStr.substr(readStr.find('v')) - .substr(1, 4) - .getAsInteger(16, *vendor)) { + std::string_view readStr{readBuf}; + if (auto v = wpi::parse_integer( + readStr.substr(readStr.find('v')).substr(1, 4), 16)) { + *vendor = v.value(); + } else { return false; } - if (readStr.substr(readStr.find('p')) - .substr(1, 4) - .getAsInteger(16, *product)) { + if (auto v = wpi::parse_integer( + readStr.substr(readStr.find('p')).substr(1, 4), 16)) { + *product = v.value(); + } else { return false; } @@ -188,11 +189,8 @@ static bool GetVendorProduct(int dev, int* vendor, int* product) { } static bool GetDescriptionSysV4L(int dev, std::string* desc) { - wpi::SmallString<64> ifpath; - { - wpi::raw_svector_ostream oss{ifpath}; - oss << "/sys/class/video4linux/video" << dev << "/device/interface"; - } + auto ifpath = + fmt::format("/sys/class/video4linux/video{}/device/interface", dev); int fd = open(ifpath.c_str(), O_RDONLY); if (fd < 0) { @@ -207,7 +205,7 @@ static bool GetDescriptionSysV4L(int dev, std::string* desc) { return false; } - *desc = wpi::StringRef(readBuf, n).rtrim(); + *desc = wpi::rtrim(std::string_view(readBuf, n)); return true; } @@ -225,17 +223,16 @@ static bool GetDescriptionIoctl(const char* cpath, std::string* desc) { } close(fd); - wpi::StringRef card{reinterpret_cast(vcap.card)}; + std::string_view card{reinterpret_cast(vcap.card)}; // try to convert "UVC Camera (0000:0000)" into a better name - int vendor = 0; - int product = 0; - if (card.startswith("UVC Camera (") && - !card.substr(12, 4).getAsInteger(16, vendor) && - !card.substr(17, 4).getAsInteger(16, product)) { - wpi::SmallString<64> card2Buf; - wpi::StringRef card2 = GetUsbNameFromId(vendor, product, card2Buf); + std::optional vendor; + std::optional product; + if (wpi::starts_with(card, "UVC Camera (") && + (vendor = wpi::parse_integer(card.substr(12, 4), 16)) && + (product = wpi::parse_integer(card.substr(17, 4), 16))) { + std::string card2 = GetUsbNameFromId(vendor.value(), product.value()); if (!card2.empty()) { - *desc = card2; + *desc = std::move(card2); return true; } } @@ -274,15 +271,14 @@ static int GetDeviceNum(const char* cpath) { path = fs::canonical(path); } - auto fn = path.filename(); - if (!wpi::StringRef{fn}.startswith("video")) { + std::string fn = path.filename(); + if (!wpi::starts_with(fn, "video")) { return -1; } - int dev = -1; - if (wpi::StringRef{fn}.substr(5).getAsInteger(10, dev)) { - return -1; + if (auto dev = wpi::parse_integer(fn.substr(5), 10)) { + return dev.value(); } - return dev; + return -1; } static std::string GetDescriptionImpl(const char* cpath) { @@ -304,14 +300,14 @@ static std::string GetDescriptionImpl(const char* cpath) { return std::string{}; } -UsbCameraImpl::UsbCameraImpl(const wpi::Twine& name, wpi::Logger& logger, +UsbCameraImpl::UsbCameraImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, - const wpi::Twine& path) + std::string_view path) : SourceImpl{name, logger, notifier, telemetry}, m_fd{-1}, m_command_fd{eventfd(0, 0)}, m_active{true}, - m_path{path.str()} { + m_path{path} { SetDescription(GetDescriptionImpl(m_path.c_str())); SetQuirks(); @@ -439,7 +435,7 @@ void UsbCameraImpl::CameraThreadMain() { DoFdSet(notify_fd, &readfds, &nfds); if (select(nfds, &readfds, nullptr, nullptr, &tv) < 0) { - SERROR("select(): " << std::strerror(errno)); + SERROR("select(): {}", std::strerror(errno)); break; // XXX: is this the right thing to do here? } @@ -450,7 +446,7 @@ void UsbCameraImpl::CameraThreadMain() { // Handle notify events if (notify_fd >= 0 && FD_ISSET(notify_fd, &readfds)) { - SDEBUG4("notify event"); + SDEBUG4("{}", "notify event"); struct inotify_event event; do { // Read the event structure @@ -460,10 +456,9 @@ void UsbCameraImpl::CameraThreadMain() { raw_name.resize(event.len); notify_is->read(raw_name.data(), event.len); // If the name is what we expect... - wpi::StringRef name{raw_name.c_str()}; - SDEBUG4("got event on '" << name << "' (" << name.size() - << ") compare to '" << base << "' (" - << base.size() << ") mask " << event.mask); + std::string_view name{raw_name.c_str()}; + SDEBUG4("got event on '{}' ({}) compare to '{}' ({}) mask {}", name, + name.size(), base, base.size(), event.mask); if (name == base) { if ((event.mask & IN_DELETE) != 0) { wasStreaming = m_streaming; @@ -480,7 +475,7 @@ void UsbCameraImpl::CameraThreadMain() { // Handle commands if (command_fd >= 0 && FD_ISSET(command_fd, &readfds)) { - SDEBUG4("got command"); + SDEBUG4("{}", "got command"); // Read it to clear eventfd_t val; eventfd_read(command_fd, &val); @@ -490,7 +485,7 @@ void UsbCameraImpl::CameraThreadMain() { // Handle frames if (m_streaming && fd >= 0 && FD_ISSET(fd, &readfds)) { - SDEBUG4("grabbing image"); + SDEBUG4("{}", "grabbing image"); // Dequeue buffer struct v4l2_buffer buf; @@ -498,7 +493,7 @@ void UsbCameraImpl::CameraThreadMain() { buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; if (DoIoctl(fd, VIDIOC_DQBUF, &buf) != 0) { - SWARNING("could not dequeue buffer"); + SWARNING("{}", "could not dequeue buffer"); wasStreaming = m_streaming; DeviceStreamOff(); DeviceDisconnect(); @@ -507,14 +502,14 @@ void UsbCameraImpl::CameraThreadMain() { } if ((buf.flags & V4L2_BUF_FLAG_ERROR) == 0) { - SDEBUG4("got image size=" << buf.bytesused << " index=" << buf.index); + SDEBUG4("got image size={} index={}", buf.bytesused, buf.index); if (buf.index >= kNumBuffers || !m_buffers[buf.index].m_data) { - SWARNING("invalid buffer" << buf.index); + SWARNING("invalid buffer {}", buf.index); continue; } - wpi::StringRef image{ + std::string_view image{ static_cast(m_buffers[buf.index].m_data), static_cast(buf.bytesused)}; int width = m_mode.width; @@ -522,7 +517,7 @@ void UsbCameraImpl::CameraThreadMain() { bool good = true; if (m_mode.pixelFormat == VideoMode::kMJPEG && !GetJpegSize(image, &width, &height)) { - SWARNING("invalid JPEG image received from camera"); + SWARNING("{}", "invalid JPEG image received from camera"); good = false; } if (good) { @@ -533,7 +528,7 @@ void UsbCameraImpl::CameraThreadMain() { // Requeue buffer if (DoIoctl(fd, VIDIOC_QBUF, &buf) != 0) { - SWARNING("could not requeue buffer"); + SWARNING("{}", "could not requeue buffer"); wasStreaming = m_streaming; DeviceStreamOff(); DeviceDisconnect(); @@ -572,11 +567,11 @@ void UsbCameraImpl::DeviceConnect() { } if (m_connectVerbose) { - SINFO("Connecting to USB camera on " << m_path); + SINFO("Connecting to USB camera on {}", m_path); } // Try to open the device - SDEBUG3("opening device"); + SDEBUG3("{}", "opening device"); int fd = open(m_path.c_str(), O_RDWR); if (fd < 0) { return; @@ -584,7 +579,7 @@ void UsbCameraImpl::DeviceConnect() { m_fd = fd; // Get capabilities - SDEBUG3("getting capabilities"); + SDEBUG3("{}", "getting capabilities"); struct v4l2_capability vcap; std::memset(&vcap, 0, sizeof(vcap)); if (DoIoctl(fd, VIDIOC_QUERYCAP, &vcap) >= 0) { @@ -596,18 +591,18 @@ void UsbCameraImpl::DeviceConnect() { // Get or restore video mode if (!m_properties_cached) { - SDEBUG3("caching properties"); + SDEBUG3("{}", "caching properties"); DeviceCacheProperties(); DeviceCacheVideoModes(); DeviceCacheMode(); m_properties_cached = true; } else { - SDEBUG3("restoring video mode"); + SDEBUG3("{}", "restoring video mode"); DeviceSetMode(); DeviceSetFPS(); // Restore settings - SDEBUG3("restoring settings"); + SDEBUG3("{}", "restoring settings"); std::unique_lock lock2(m_mutex); for (size_t i = 0; i < m_propertyData.size(); ++i) { const auto prop = @@ -616,27 +611,27 @@ void UsbCameraImpl::DeviceConnect() { continue; } if (!prop->DeviceSet(lock2, m_fd)) { - SWARNING("failed to set property " << prop->name); + SWARNING("failed to set property {}", prop->name); } } } // Request buffers - SDEBUG3("allocating buffers"); + SDEBUG3("{}", "allocating buffers"); struct v4l2_requestbuffers rb; std::memset(&rb, 0, sizeof(rb)); rb.count = kNumBuffers; rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; rb.memory = V4L2_MEMORY_MMAP; if (DoIoctl(fd, VIDIOC_REQBUFS, &rb) != 0) { - SWARNING("could not allocate buffers"); + SWARNING("{}", "could not allocate buffers"); close(fd); m_fd = -1; return; } // Map buffers - SDEBUG3("mapping buffers"); + SDEBUG3("{}", "mapping buffers"); for (int i = 0; i < kNumBuffers; ++i) { struct v4l2_buffer buf; std::memset(&buf, 0, sizeof(buf)); @@ -644,17 +639,16 @@ void UsbCameraImpl::DeviceConnect() { buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; if (DoIoctl(fd, VIDIOC_QUERYBUF, &buf) != 0) { - SWARNING("could not query buffer " << i); + SWARNING("could not query buffer {}", i); close(fd); m_fd = -1; return; } - SDEBUG4("buf " << i << " length=" << buf.length - << " offset=" << buf.m.offset); + SDEBUG4("buf {} length={} offset={}", i, buf.length, buf.m.offset); m_buffers[i] = UsbCameraBuffer(fd, buf.length, buf.m.offset); if (!m_buffers[i].m_data) { - SWARNING("could not map buffer " << i); + SWARNING("could not map buffer {}", i); // release other buffers for (int j = 0; j < i; ++j) { m_buffers[j] = UsbCameraBuffer{}; @@ -664,7 +658,7 @@ void UsbCameraImpl::DeviceConnect() { return; } - SDEBUG4("buf " << i << " address=" << m_buffers[i].m_data); + SDEBUG4("buf {} address={}", i, m_buffers[i].m_data); } // Update description (as it may have changed) @@ -687,7 +681,7 @@ bool UsbCameraImpl::DeviceStreamOn() { } // Queue buffers - SDEBUG3("queuing buffers"); + SDEBUG3("{}", "queuing buffers"); for (int i = 0; i < kNumBuffers; ++i) { struct v4l2_buffer buf; std::memset(&buf, 0, sizeof(buf)); @@ -695,7 +689,7 @@ bool UsbCameraImpl::DeviceStreamOn() { buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; if (DoIoctl(fd, VIDIOC_QBUF, &buf) != 0) { - SWARNING("could not queue buffer " << i); + SWARNING("could not queue buffer {}", i); return false; } } @@ -706,16 +700,17 @@ bool UsbCameraImpl::DeviceStreamOn() { if (errno == ENOSPC) { // indicates too much USB bandwidth requested SERROR( + "{}", "could not start streaming due to USB bandwidth limitations; try a " "lower resolution or a different pixel format (VIDIOC_STREAMON: " "No space left on device)"); } else { // some other error - SERROR("ioctl VIDIOC_STREAMON failed: " << std::strerror(errno)); + SERROR("ioctl VIDIOC_STREAMON failed: {}", std::strerror(errno)); } return false; } - SDEBUG4("enabled streaming"); + SDEBUG4("{}", "enabled streaming"); m_streaming = true; return true; } @@ -732,7 +727,7 @@ bool UsbCameraImpl::DeviceStreamOff() { if (DoIoctl(fd, VIDIOC_STREAMOFF, &type) != 0) { return false; } - SDEBUG4("disabled streaming"); + SDEBUG4("{}", "disabled streaming"); m_streaming = false; return true; } @@ -806,7 +801,7 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetProperty( bool setString = (msg.kind == Message::kCmdSetPropertyStr); int property = msg.data[0]; int value = msg.data[1]; - wpi::StringRef valueStr = msg.dataStr; + std::string_view valueStr = msg.dataStr; // Look up auto prop = static_cast(GetProperty(property)); @@ -940,19 +935,19 @@ void UsbCameraImpl::DeviceSetMode() { vfmt.fmt.pix.pixelformat = FromPixelFormat(static_cast(m_mode.pixelFormat)); if (vfmt.fmt.pix.pixelformat == 0) { - SWARNING("could not set format " << m_mode.pixelFormat - << ", defaulting to MJPEG"); + SWARNING("could not set format {}, defaulting to MJPEG", + m_mode.pixelFormat); vfmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG; } vfmt.fmt.pix.width = m_mode.width; vfmt.fmt.pix.height = m_mode.height; vfmt.fmt.pix.field = V4L2_FIELD_ANY; if (DoIoctl(fd, VIDIOC_S_FMT, &vfmt) != 0) { - SWARNING("could not set format " << m_mode.pixelFormat << " res " - << m_mode.width << "x" << m_mode.height); + SWARNING("could not set format {} res {}x{}", m_mode.pixelFormat, + m_mode.width, m_mode.height); } else { - SINFO("set format " << m_mode.pixelFormat << " res " << m_mode.width << "x" - << m_mode.height); + SINFO("set format {} res {}x{}", m_mode.pixelFormat, m_mode.width, + m_mode.height); } } @@ -975,9 +970,9 @@ void UsbCameraImpl::DeviceSetFPS() { parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; parm.parm.capture.timeperframe = FPSToFract(m_mode.fps); if (DoIoctl(fd, VIDIOC_S_PARM, &parm) != 0) { - SWARNING("could not set FPS to " << m_mode.fps); + SWARNING("could not set FPS to {}", m_mode.fps); } else { - SINFO("set FPS to " << m_mode.fps); + SINFO("set FPS to {}", m_mode.fps); } } @@ -997,7 +992,7 @@ void UsbCameraImpl::DeviceCacheMode() { #endif vfmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (DoIoctl(fd, VIDIOC_G_FMT, &vfmt) != 0) { - SERROR("could not read current video mode"); + SERROR("{}", "could not read current video mode"); std::scoped_lock lock(m_mutex); m_mode = VideoMode{VideoMode::kMJPEG, 320, 240, 30}; return; @@ -1133,7 +1128,7 @@ void UsbCameraImpl::DeviceCacheProperty( } else { // Read current raw value and set percentage from it if (!rawProp->DeviceGet(lock, m_fd)) { - SWARNING("failed to get property " << rawProp->name); + SWARNING("failed to get property {}", rawProp->name); } if (perProp) { @@ -1145,7 +1140,7 @@ void UsbCameraImpl::DeviceCacheProperty( // Set value on device if user-configured if (rawProp->valueSet) { if (!rawProp->DeviceSet(lock, m_fd)) { - SWARNING("failed to set property " << rawProp->name); + SWARNING("failed to set property {}", rawProp->name); } } @@ -1360,7 +1355,7 @@ void UsbCameraImpl::Send(Message&& msg) const { } std::unique_ptr UsbCameraImpl::CreateEmptyProperty( - const wpi::Twine& name) const { + std::string_view name) const { return std::make_unique(name); } @@ -1379,10 +1374,10 @@ bool UsbCameraImpl::CacheProperties(CS_Status* status) const { void UsbCameraImpl::SetQuirks() { wpi::SmallString<128> descbuf; - wpi::StringRef desc = GetDescription(descbuf); - m_lifecam_exposure = - desc.endswith("LifeCam HD-3000") || desc.endswith("LifeCam Cinema (TM)"); - m_picamera = desc.startswith("mmal service"); + std::string_view desc = GetDescription(descbuf); + m_lifecam_exposure = wpi::ends_with(desc, "LifeCam HD-3000") || + wpi::ends_with(desc, "LifeCam Cinema (TM)"); + m_picamera = wpi::ends_with(desc, "mmal service"); int deviceNum = GetDeviceNum(m_path.c_str()); if (deviceNum >= 0) { @@ -1400,11 +1395,11 @@ void UsbCameraImpl::SetProperty(int property, int value, CS_Status* status) { *status = SendAndWait(std::move(msg)); } -void UsbCameraImpl::SetStringProperty(int property, const wpi::Twine& value, +void UsbCameraImpl::SetStringProperty(int property, std::string_view value, CS_Status* status) { Message msg{Message::kCmdSetPropertyStr}; msg.data[0] = property; - msg.dataStr = value.str(); + msg.dataStr = value; *status = SendAndWait(std::move(msg)); } @@ -1524,9 +1519,9 @@ void UsbCameraImpl::NumSinksEnabledChanged() { Send(Message{Message::kNumSinksEnabledChanged}); } -void UsbCameraImpl::SetPath(const wpi::Twine& path, CS_Status* status) { +void UsbCameraImpl::SetPath(std::string_view path, CS_Status* status) { Message msg{Message::kCmdSetPath}; - msg.dataStr = path.str(); + msg.dataStr = path; *status = SendAndWait(std::move(msg)); } @@ -1537,15 +1532,12 @@ std::string UsbCameraImpl::GetPath() const { namespace cs { -CS_Source CreateUsbCameraDev(const wpi::Twine& name, int dev, +CS_Source CreateUsbCameraDev(std::string_view name, int dev, CS_Status* status) { - wpi::SmallString<32> path; - wpi::raw_svector_ostream oss{path}; - oss << "/dev/video" << dev; - return CreateUsbCameraPath(name, oss.str(), status); + return CreateUsbCameraPath(name, fmt::format("/dev/video{}", dev), status); } -CS_Source CreateUsbCameraPath(const wpi::Twine& name, const wpi::Twine& path, +CS_Source CreateUsbCameraPath(std::string_view name, std::string_view path, CS_Status* status) { auto& inst = Instance::GetInstance(); return inst.CreateSource(CS_SOURCE_USB, std::make_shared( @@ -1553,7 +1545,7 @@ CS_Source CreateUsbCameraPath(const wpi::Twine& name, const wpi::Twine& path, inst.telemetry, path)); } -void SetUsbCameraPath(CS_Source source, const wpi::Twine& path, +void SetUsbCameraPath(CS_Source source, std::string_view path, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data || data->kind != CS_SOURCE_USB) { @@ -1629,13 +1621,15 @@ std::vector EnumerateUsbCameras(CS_Status* status) { if (DIR* dp = ::opendir("/dev")) { while (struct dirent* ep = ::readdir(dp)) { - wpi::StringRef fname{ep->d_name}; - if (!fname.startswith("video")) { + std::string_view fname{ep->d_name}; + if (!wpi::starts_with(fname, "video")) { continue; } unsigned int dev = 0; - if (fname.substr(5).getAsInteger(10, dev)) { + if (auto v = wpi::parse_integer(fname.substr(5), 10)) { + dev = v.value(); + } else { continue; } @@ -1665,7 +1659,7 @@ std::vector EnumerateUsbCameras(CS_Status* status) { ::closedir(dp); } else { // *status = ; - WPI_ERROR(Instance::GetInstance().logger, "Could not open /dev"); + WPI_ERROR(Instance::GetInstance().logger, "{}", "Could not open /dev"); return retval; } @@ -1682,11 +1676,11 @@ std::vector EnumerateUsbCameras(CS_Status* status) { char* target = ::realpath(path.c_str(), nullptr); if (target) { std::string fname = fs::path{target}.filename(); - unsigned int dev = 0; - if (wpi::StringRef{fname}.startswith("video") && - !wpi::StringRef{fname}.substr(5).getAsInteger(10, dev) && - dev < retval.size()) { - retval[dev].otherPaths.emplace_back(path.str()); + std::optional dev; + if (wpi::starts_with(fname, "video") && + (dev = wpi::parse_integer(fname.substr(5), 10)) && + dev.value() < retval.size()) { + retval[dev.value()].otherPaths.emplace_back(path.str()); } std::free(target); } diff --git a/cscore/src/main/native/linux/UsbCameraImpl.h b/cscore/src/main/native/linux/UsbCameraImpl.h index edfd2d5bad..c0273431ee 100644 --- a/cscore/src/main/native/linux/UsbCameraImpl.h +++ b/cscore/src/main/native/linux/UsbCameraImpl.h @@ -10,13 +10,13 @@ #include #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -33,15 +33,15 @@ class Telemetry; class UsbCameraImpl : public SourceImpl { public: - UsbCameraImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, - Telemetry& telemetry, const wpi::Twine& path); + UsbCameraImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, + Telemetry& telemetry, std::string_view path); ~UsbCameraImpl() override; void Start() override; // Property functions void SetProperty(int property, int value, CS_Status* status) override; - void SetStringProperty(int property, const wpi::Twine& value, + void SetStringProperty(int property, std::string_view value, CS_Status* status) override; // Standard common camera properties @@ -63,7 +63,7 @@ class UsbCameraImpl : public SourceImpl { void NumSinksChanged() override; void NumSinksEnabledChanged() override; - void SetPath(const wpi::Twine& path, CS_Status* status); + void SetPath(std::string_view path, CS_Status* status); std::string GetPath() const; // Messages passed to/from camera thread @@ -95,7 +95,7 @@ class UsbCameraImpl : public SourceImpl { protected: std::unique_ptr CreateEmptyProperty( - const wpi::Twine& name) const override; + std::string_view name) const override; // Cache properties. Immediately successful if properties are already cached. // If they are not, tries to connect to the camera to do so; returns false and diff --git a/cscore/src/main/native/linux/UsbCameraListener.cpp b/cscore/src/main/native/linux/UsbCameraListener.cpp index 7c73b79876..40e84c5daf 100644 --- a/cscore/src/main/native/linux/UsbCameraListener.cpp +++ b/cscore/src/main/native/linux/UsbCameraListener.cpp @@ -5,6 +5,7 @@ #include "UsbCameraListener.h" #include +#include #include #include @@ -38,7 +39,7 @@ void UsbCameraListener::Start() { auto devEvents = wpi::uv::FsEvent::Create(loop); devEvents->fsEvent.connect([refreshTimer](const char* fn, int flags) { - if (wpi::StringRef(fn).startswith("video")) { + if (wpi::starts_with(fn, "video")) { refreshTimer->Start(wpi::uv::Timer::Time(200)); } }); diff --git a/cscore/src/main/native/linux/UsbCameraProperty.cpp b/cscore/src/main/native/linux/UsbCameraProperty.cpp index f2ec84839d..149ca1b979 100644 --- a/cscore/src/main/native/linux/UsbCameraProperty.cpp +++ b/cscore/src/main/native/linux/UsbCameraProperty.cpp @@ -4,8 +4,8 @@ #include "UsbCameraProperty.h" +#include #include -#include #include "UsbUtil.h" @@ -92,15 +92,8 @@ static int GetStringCtrlIoctl(int fd, int id, int maximum, std::string* value) { } static int SetStringCtrlIoctl(int fd, int id, int maximum, - const wpi::Twine& value) { - wpi::SmallString<64> strBuf, strBuf2; - wpi::StringRef str = value.toNullTerminatedStringRef(strBuf); - if (str.size() > static_cast(maximum)) { - // don't know if strBuf was used, just recopy - strBuf2 = str.take_front(maximum); - str = strBuf2; - strBuf2.push_back('\0'); // null terminate - } + std::string_view value) { + wpi::SmallString<64> str{value.substr(0, maximum)}; struct v4l2_ext_control ctrl; struct v4l2_ext_controls ctrls; @@ -108,7 +101,7 @@ static int SetStringCtrlIoctl(int fd, int id, int maximum, std::memset(&ctrls, 0, sizeof(ctrls)); ctrl.id = id; ctrl.size = str.size(); - ctrl.string = const_cast(str.data()); + ctrl.string = const_cast(str.c_str()); ctrls.ctrl_class = V4L2_CTRL_ID2CLASS(id); ctrls.count = 1; ctrls.controls = &ctrl; @@ -117,8 +110,8 @@ static int SetStringCtrlIoctl(int fd, int id, int maximum, // Removes non-alphanumeric characters and replaces spaces with underscores. // e.g. "Zoom, Absolute" -> "zoom_absolute", "Pan (Absolute)" -> "pan_absolute" -static wpi::StringRef NormalizeName(wpi::StringRef name, - wpi::SmallVectorImpl& buf) { +static std::string_view NormalizeName(std::string_view name, + wpi::SmallVectorImpl& buf) { bool newWord = false; for (auto ch : name) { if (std::isalnum(ch)) { @@ -131,13 +124,12 @@ static wpi::StringRef NormalizeName(wpi::StringRef name, newWord = true; } } - return wpi::StringRef(buf.data(), buf.size()); + return {buf.data(), buf.size()}; } #ifdef VIDIOC_QUERY_EXT_CTRL UsbCameraProperty::UsbCameraProperty(const struct v4l2_query_ext_ctrl& ctrl) - : PropertyImpl(wpi::StringRef{}, CS_PROP_NONE, ctrl.step, - ctrl.default_value, 0), + : PropertyImpl({}, CS_PROP_NONE, ctrl.step, ctrl.default_value, 0), id(ctrl.id & V4L2_CTRL_ID_MASK), type(ctrl.type) { hasMinimum = true; @@ -174,13 +166,12 @@ UsbCameraProperty::UsbCameraProperty(const struct v4l2_query_ext_ctrl& ctrl) ++len; } wpi::SmallString<64> name_buf; - name = NormalizeName(wpi::StringRef(ctrl.name, len), name_buf); + name = NormalizeName({ctrl.name, len}, name_buf); } #endif UsbCameraProperty::UsbCameraProperty(const struct v4l2_queryctrl& ctrl) - : PropertyImpl(wpi::StringRef{}, CS_PROP_NONE, ctrl.step, - ctrl.default_value, 0), + : PropertyImpl({}, CS_PROP_NONE, ctrl.step, ctrl.default_value, 0), id(ctrl.id & V4L2_CTRL_ID_MASK), type(ctrl.type) { hasMinimum = true; @@ -214,8 +205,8 @@ UsbCameraProperty::UsbCameraProperty(const struct v4l2_queryctrl& ctrl) ++len; } wpi::SmallString<64> name_buf; - name = NormalizeName( - wpi::StringRef(reinterpret_cast(ctrl.name), len), name_buf); + name = + NormalizeName({reinterpret_cast(ctrl.name), len}, name_buf); } std::unique_ptr UsbCameraProperty::DeviceQuery(int fd, @@ -261,8 +252,7 @@ std::unique_ptr UsbCameraProperty::DeviceQuery(int fd, continue; } if (prop->intMenu) { - wpi::raw_string_ostream os(prop->enumChoices[i]); - os << qmenu.value; + prop->enumChoices[i] = fmt::to_string(qmenu.value); } else { prop->enumChoices[i] = reinterpret_cast(qmenu.name); } @@ -315,12 +305,12 @@ bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, int fd) const { // Make a copy of the string as we're about to release the lock wpi::SmallString<128> valueStrCopy{valueStr}; - return DeviceSet(lock, fd, value, valueStrCopy); + return DeviceSet(lock, fd, value, valueStrCopy.str()); } bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, int fd, int newValue, - const wpi::Twine& newValueStr) const { + std::string_view newValueStr) const { if (!device || fd < 0) { return true; } diff --git a/cscore/src/main/native/linux/UsbCameraProperty.h b/cscore/src/main/native/linux/UsbCameraProperty.h index c608e00fd6..b0291a17eb 100644 --- a/cscore/src/main/native/linux/UsbCameraProperty.h +++ b/cscore/src/main/native/linux/UsbCameraProperty.h @@ -8,6 +8,7 @@ #include #include +#include #include @@ -19,19 +20,19 @@ namespace cs { class UsbCameraProperty : public PropertyImpl { public: UsbCameraProperty() = default; - explicit UsbCameraProperty(const wpi::Twine& name_) : PropertyImpl{name_} {} + explicit UsbCameraProperty(std::string_view name_) : PropertyImpl{name_} {} // Software property constructor - UsbCameraProperty(const wpi::Twine& name_, unsigned id_, - CS_PropertyKind kind_, int minimum_, int maximum_, - int step_, int defaultValue_, int value_) + UsbCameraProperty(std::string_view name_, unsigned id_, CS_PropertyKind kind_, + int minimum_, int maximum_, int step_, int defaultValue_, + int value_) : PropertyImpl(name_, kind_, minimum_, maximum_, step_, defaultValue_, value_), device{false}, id{id_} {} // Normalized property constructor - UsbCameraProperty(const wpi::Twine& name_, int rawIndex_, + UsbCameraProperty(std::string_view name_, int rawIndex_, const UsbCameraProperty& rawProp, int defaultValue_, int value_) : PropertyImpl(name_, rawProp.propKind, 1, defaultValue_, value_), @@ -55,7 +56,7 @@ class UsbCameraProperty : public PropertyImpl { bool DeviceGet(std::unique_lock& lock, int fd); bool DeviceSet(std::unique_lock& lock, int fd) const; bool DeviceSet(std::unique_lock& lock, int fd, int newValue, - const wpi::Twine& newValueStr) const; + std::string_view newValueStr) const; // If this is a device (rather than software) property bool device{true}; diff --git a/cscore/src/main/native/linux/UsbUtil.cpp b/cscore/src/main/native/linux/UsbUtil.cpp index c2aff2972b..afe3e4218d 100644 --- a/cscore/src/main/native/linux/UsbUtil.cpp +++ b/cscore/src/main/native/linux/UsbUtil.cpp @@ -8,8 +8,10 @@ #include #include -#include +#include #include +#include +#include #include #include @@ -18,21 +20,18 @@ namespace cs { -static wpi::StringRef GetUsbNameFromFile(int vendor, int product, - wpi::SmallVectorImpl& buf) { +static std::string GetUsbNameFromFile(int vendor, int product) { int fd = open("/var/lib/usbutils/usb.ids", O_RDONLY); if (fd < 0) { return {}; } - wpi::raw_svector_ostream os{buf}; + wpi::SmallString<128> buf; wpi::raw_fd_istream is{fd, true}; // build vendor and product 4-char hex strings - wpi::SmallString<16> vendorStr, productStr; - wpi::raw_svector_ostream vendorOs{vendorStr}, productOs{productStr}; - vendorOs << wpi::format_hex_no_prefix(vendor, 4); - productOs << wpi::format_hex_no_prefix(product, 4); + auto vendorStr = fmt::format("{:04x}", vendor); + auto productStr = fmt::format("{:04x}", product); // scan file wpi::SmallString<128> lineBuf; @@ -48,23 +47,24 @@ static wpi::StringRef GetUsbNameFromFile(int vendor, int product, } // look for vendor at start of line - if (line.startswith(vendorStr)) { + if (wpi::starts_with(line, vendorStr)) { foundVendor = true; - os << line.substr(5).trim() << ' '; + buf += wpi::trim(line.substr(5)); + buf += ' '; continue; } if (foundVendor) { // next vendor, but didn't match product? if (line[0] != '\t') { - os << "Unknown"; - return os.str(); + buf += "Unknown"; + return buf; } // look for product - if (line.substr(1).startswith(productStr)) { - os << line.substr(6).trim(); - return os.str(); + if (wpi::starts_with(line.substr(1), productStr)) { + buf += wpi::trim(line.substr(6)); + return buf; } } } @@ -72,93 +72,90 @@ static wpi::StringRef GetUsbNameFromFile(int vendor, int product, return {}; } -wpi::StringRef GetUsbNameFromId(int vendor, int product, - wpi::SmallVectorImpl& buf) { +std::string GetUsbNameFromId(int vendor, int product) { // try reading usb.ids - wpi::StringRef rv = GetUsbNameFromFile(vendor, product, buf); + std::string rv = GetUsbNameFromFile(vendor, product); if (!rv.empty()) { return rv; } // Fall back to internal database - wpi::raw_svector_ostream os{buf}; switch (vendor) { - case 0x046d: - os << "Logitech, Inc. "; + case 0x046d: { + std::string_view productStr; switch (product) { case 0x0802: - os << "Webcam C200"; + productStr = "Webcam C200"; break; case 0x0804: - os << "Webcam C250"; + productStr = "Webcam C250"; break; case 0x0805: - os << "Webcam C300"; + productStr = "Webcam C300"; break; case 0x0807: - os << "Webcam B500"; + productStr = "Webcam B500"; break; case 0x0808: - os << "Webcam C600"; + productStr = "Webcam C600"; break; case 0x0809: - os << "Webcam Pro 9000"; + productStr = "Webcam Pro 9000"; break; case 0x080a: - os << "Portable Webcam C905"; + productStr = "Portable Webcam C905"; break; case 0x080f: - os << "Webcam C120"; + productStr = "Webcam C120"; break; case 0x0819: - os << "Webcam C210"; + productStr = "Webcam C210"; break; case 0x081b: - os << "Webcam C310"; + productStr = "Webcam C310"; break; case 0x081d: - os << "HD Webcam C510"; + productStr = "HD Webcam C510"; break; case 0x0821: - os << "HD Webcam C910"; + productStr = "HD Webcam C910"; break; case 0x0825: - os << "Webcam C270"; + productStr = "Webcam C270"; break; case 0x0826: - os << "HD Webcam C525"; + productStr = "HD Webcam C525"; break; case 0x0828: - os << "HD Webcam B990"; + productStr = "HD Webcam B990"; break; case 0x082b: - os << "Webcam C170"; + productStr = "Webcam C170"; break; case 0x082d: - os << "HD Pro Webcam C920"; + productStr = "HD Pro Webcam C920"; break; case 0x0836: - os << "B525 HD Webcam"; + productStr = "B525 HD Webcam"; break; case 0x0843: - os << "Webcam C930e"; + productStr = "Webcam C930e"; break; } - break; + return fmt::format("Logitech, Inc. {}", productStr); + } } - return os.str(); + return {}; } int CheckedIoctl(int fd, unsigned long req, void* data, // NOLINT(runtime/int) const char* name, const char* file, int line, bool quiet) { int retval = ioctl(fd, req, data); if (!quiet && retval < 0) { - wpi::SmallString<64> localfile{file}; - localfile.push_back('\0'); - WPI_ERROR(Instance::GetInstance().logger, - "ioctl " << name << " failed at " << basename(localfile.data()) - << ":" << line << ": " << std::strerror(errno)); + WPI_ERROR(Instance::GetInstance().logger, "ioctl {} failed at {}:{}: {}", + name, fs::path{file}.filename().string(), line, + std::strerror(errno)); } return retval; } diff --git a/cscore/src/main/native/linux/UsbUtil.h b/cscore/src/main/native/linux/UsbUtil.h index 3d038a8bfb..9f6f8f5376 100644 --- a/cscore/src/main/native/linux/UsbUtil.h +++ b/cscore/src/main/native/linux/UsbUtil.h @@ -5,15 +5,11 @@ #ifndef CSCORE_USBUTIL_H_ #define CSCORE_USBUTIL_H_ -#include - -#include -#include +#include namespace cs { -wpi::StringRef GetUsbNameFromId(int vendor, int product, - wpi::SmallVectorImpl& buf); +std::string GetUsbNameFromId(int vendor, int product); int CheckedIoctl(int fd, unsigned long req, void* data, // NOLINT(runtime/int) const char* name, const char* file, int line, bool quiet); diff --git a/cscore/src/main/native/osx/UsbCameraImpl.cpp b/cscore/src/main/native/osx/UsbCameraImpl.cpp index ab491426d1..3b5d82185c 100644 --- a/cscore/src/main/native/osx/UsbCameraImpl.cpp +++ b/cscore/src/main/native/osx/UsbCameraImpl.cpp @@ -6,19 +6,19 @@ namespace cs { -CS_Source CreateUsbCameraDev(const wpi::Twine& name, int dev, +CS_Source CreateUsbCameraDev(std::string_view name, int dev, CS_Status* status) { *status = CS_INVALID_HANDLE; return 0; } -CS_Source CreateUsbCameraPath(const wpi::Twine& name, const wpi::Twine& path, +CS_Source CreateUsbCameraPath(std::string_view name, std::string_view path, CS_Status* status) { *status = CS_INVALID_HANDLE; return 0; } -void SetUsbCameraPath(CS_Source source, const wpi::Twine& path, +void SetUsbCameraPath(CS_Source source, std::string_view path, CS_Status* status) { *status = CS_INVALID_HANDLE; } diff --git a/cscore/src/main/native/windows/UsbCameraImpl.cpp b/cscore/src/main/native/windows/UsbCameraImpl.cpp index 10ce8d982a..082057ccc7 100644 --- a/cscore/src/main/native/windows/UsbCameraImpl.cpp +++ b/cscore/src/main/native/windows/UsbCameraImpl.cpp @@ -26,8 +26,7 @@ #include #include #include -#include -#include +#include #include #include "COMCreators.h" @@ -69,17 +68,17 @@ using namespace cs; namespace cs { -UsbCameraImpl::UsbCameraImpl(const wpi::Twine& name, wpi::Logger& logger, +UsbCameraImpl::UsbCameraImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, - const wpi::Twine& path) - : SourceImpl{name, logger, notifier, telemetry}, m_path{path.str()} { + std::string_view path) + : SourceImpl{name, logger, notifier, telemetry}, m_path{path} { std::wstring_convert> utf8_conv; m_widePath = utf8_conv.from_bytes(m_path.c_str()); m_deviceId = -1; StartMessagePump(); } -UsbCameraImpl::UsbCameraImpl(const wpi::Twine& name, wpi::Logger& logger, +UsbCameraImpl::UsbCameraImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, int deviceId) : SourceImpl{name, logger, notifier, telemetry}, m_deviceId(deviceId) { @@ -99,11 +98,11 @@ void UsbCameraImpl::SetProperty(int property, int value, CS_Status* status) { SetCameraMessage, msg.kind, &msg); *status = result; } -void UsbCameraImpl::SetStringProperty(int property, const wpi::Twine& value, +void UsbCameraImpl::SetStringProperty(int property, std::string_view value, CS_Status* status) { Message msg{Message::kCmdSetPropertyStr}; msg.data[0] = property; - msg.dataStr = value.str(); + msg.dataStr = value; auto result = m_messagePump->SendWindowMessage( SetCameraMessage, msg.kind, &msg); @@ -197,9 +196,9 @@ void UsbCameraImpl::NumSinksEnabledChanged() { SetCameraMessage, Message::kNumSinksEnabledChanged, nullptr); } -void UsbCameraImpl::SetPath(const wpi::Twine& path, CS_Status* status) { +void UsbCameraImpl::SetPath(std::string_view path, CS_Status* status) { Message msg{Message::kCmdSetPath}; - msg.dataStr = path.str(); + msg.dataStr = path; auto result = m_messagePump->SendWindowMessage( SetCameraMessage, msg.kind, &msg); @@ -257,7 +256,7 @@ bool UsbCameraImpl::CheckDeviceChange(WPARAM wParam, DEV_BROADCAST_HDR* pHdr, void UsbCameraImpl::DeviceDisconnect() { if (m_connectVerbose) - SINFO("Disconnected from " << m_path); + SINFO("Disconnected from {}", m_path); m_sourceReader.Reset(); m_mediaSource.Reset(); if (m_imageCallback) { @@ -268,8 +267,8 @@ void UsbCameraImpl::DeviceDisconnect() { SetConnected(false); } -static bool IsPercentageProperty(wpi::StringRef name) { - if (name.startswith("raw_")) +static bool IsPercentageProperty(std::string_view name) { + if (wpi::starts_with(name, "raw_")) name = name.substr(4); return name == "Brightness" || name == "Contrast" || name == "Saturation" || name == "Hue" || name == "Sharpness" || name == "Gain" || @@ -341,8 +340,7 @@ void UsbCameraImpl::ProcessFrame(IMFSample* videoSample, case cs::VideoMode::PixelFormat::kMJPEG: { // Special case PutFrame(VideoMode::kMJPEG, mode.width, mode.height, - wpi::StringRef(reinterpret_cast(ptr), length), - wpi::Now()); + {reinterpret_cast(ptr), length}, wpi::Now()); doFinalSet = false; break; } @@ -477,9 +475,9 @@ bool UsbCameraImpl::DeviceConnect() { return true; if (m_connectVerbose) - SINFO("Connecting to USB camera on " << m_path); + SINFO("Connecting to USB camera on {}", m_path); - SDEBUG3("opening device"); + SDEBUG3("{}", "opening device"); const wchar_t* path = m_widePath.c_str(); m_mediaSource = CreateVideoCaptureDevice(path); @@ -506,13 +504,13 @@ bool UsbCameraImpl::DeviceConnect() { } if (!m_properties_cached) { - SDEBUG3("caching properties"); + SDEBUG3("{}", "caching properties"); DeviceCacheProperties(); DeviceCacheVideoModes(); DeviceCacheMode(); m_properties_cached = true; } else { - SDEBUG3("restoring video mode"); + SDEBUG3("{}", "restoring video mode"); DeviceSetMode(); } @@ -526,7 +524,7 @@ bool UsbCameraImpl::DeviceConnect() { } std::unique_ptr UsbCameraImpl::CreateEmptyProperty( - const wpi::Twine& name) const { + std::string_view name) const { return nullptr; } @@ -545,7 +543,7 @@ bool UsbCameraImpl::CacheProperties(CS_Status* status) const { } template -void UsbCameraImpl::DeviceAddProperty(const wpi::Twine& name_, TagProperty tag, +void UsbCameraImpl::DeviceAddProperty(std::string_view name_, TagProperty tag, IAM* pProcAmp) { // First see if properties exist bool isValid = false; @@ -556,11 +554,11 @@ void UsbCameraImpl::DeviceAddProperty(const wpi::Twine& name_, TagProperty tag, } } -template void UsbCameraImpl::DeviceAddProperty(const wpi::Twine& name_, +template void UsbCameraImpl::DeviceAddProperty(std::string_view name_, tagVideoProcAmpProperty tag, IAMVideoProcAmp* pProcAmp); -template void UsbCameraImpl::DeviceAddProperty(const wpi::Twine& name_, +template void UsbCameraImpl::DeviceAddProperty(std::string_view name_, tagCameraControlProperty tag, IAMCameraControl* pProcAmp); @@ -669,7 +667,7 @@ void UsbCameraImpl::DeviceCacheProperty( } else { // Read current raw value and set percentage from it if (!rawProp->DeviceGet(lock, pProcAmp)) - SWARNING("failed to get property " << rawProp->name); + SWARNING("failed to get property {}", rawProp->name); if (perProp) { perProp->SetValue(RawToPercentage(*rawProp, rawProp->value)); @@ -680,7 +678,7 @@ void UsbCameraImpl::DeviceCacheProperty( // Set value on device if user-configured if (rawProp->valueSet) { if (!rawProp->DeviceSet(lock, pProcAmp)) - SWARNING("failed to set property " << rawProp->name); + SWARNING("failed to set property {}", rawProp->name); } // Update pointers since we released the lock @@ -764,7 +762,7 @@ CS_StatusValue UsbCameraImpl::DeviceCmdSetProperty( bool setString = (msg.kind == Message::kCmdSetPropertyStr); int property = msg.data[0]; int value = msg.data[1]; - wpi::StringRef valueStr = msg.dataStr; + std::string_view valueStr = msg.dataStr; // Look up auto prop = static_cast(GetProperty(property)); @@ -1022,23 +1020,21 @@ void UsbCameraImpl::DeviceCacheVideoModes() { m_notifier.NotifySource(*this, CS_SOURCE_VIDEOMODES_UPDATED); } -static void ParseVidAndPid(wpi::StringRef path, int* pid, int* vid) { - auto vidIndex = path.find_lower("vid_"); - auto pidIndex = path.find_lower("pid_"); +static void ParseVidAndPid(std::string_view path, int* pid, int* vid) { + auto vidIndex = wpi::find_lower(path, "vid_"); + auto pidIndex = wpi::find_lower(path, "pid_"); - if (vidIndex != wpi::StringRef::npos) { - auto vidSlice = path.slice(vidIndex + 4, vidIndex + 8); - uint16_t val = 0; - if (!vidSlice.getAsInteger(16, val)) { - *vid = val; + if (vidIndex != std::string_view::npos) { + auto vidSlice = wpi::slice(path, vidIndex + 4, vidIndex + 8); + if (auto v = wpi::parse_integer(vidSlice, 16)) { + *vid = v.value(); } } - if (pidIndex != wpi::StringRef::npos) { - auto pidSlice = path.slice(pidIndex + 4, pidIndex + 8); - uint16_t val = 0; - if (!pidSlice.getAsInteger(16, val)) { - *pid = val; + if (pidIndex != std::string_view::npos) { + auto pidSlice = wpi::slice(path, pidIndex + 4, pidIndex + 8); + if (auto v = wpi::parse_integer(pidSlice, 16)) { + *pid = v.value(); } } } @@ -1112,7 +1108,7 @@ done: return retval; } -CS_Source CreateUsbCameraDev(const wpi::Twine& name, int dev, +CS_Source CreateUsbCameraDev(std::string_view name, int dev, CS_Status* status) { // First check if device exists auto devices = cs::EnumerateUsbCameras(status); @@ -1125,7 +1121,7 @@ CS_Source CreateUsbCameraDev(const wpi::Twine& name, int dev, return inst.CreateSource(CS_SOURCE_USB, source); } -CS_Source CreateUsbCameraPath(const wpi::Twine& name, const wpi::Twine& path, +CS_Source CreateUsbCameraPath(std::string_view name, std::string_view path, CS_Status* status) { auto& inst = Instance::GetInstance(); auto source = std::make_shared( @@ -1133,7 +1129,7 @@ CS_Source CreateUsbCameraPath(const wpi::Twine& name, const wpi::Twine& path, return inst.CreateSource(CS_SOURCE_USB, source); } -void SetUsbCameraPath(CS_Source source, const wpi::Twine& path, +void SetUsbCameraPath(CS_Source source, std::string_view path, CS_Status* status) { auto data = Instance::GetInstance().GetSource(source); if (!data || data->kind != CS_SOURCE_USB) { diff --git a/cscore/src/main/native/windows/UsbCameraImpl.h b/cscore/src/main/native/windows/UsbCameraImpl.h index 285da2c16b..05ee359bfc 100644 --- a/cscore/src/main/native/windows/UsbCameraImpl.h +++ b/cscore/src/main/native/windows/UsbCameraImpl.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -23,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -40,9 +40,9 @@ namespace cs { class UsbCameraImpl : public SourceImpl, public std::enable_shared_from_this { public: - UsbCameraImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, - Telemetry& telemetry, const wpi::Twine& path); - UsbCameraImpl(const wpi::Twine& name, wpi::Logger& logger, Notifier& notifier, + UsbCameraImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, + Telemetry& telemetry, std::string_view path); + UsbCameraImpl(std::string_view name, wpi::Logger& logger, Notifier& notifier, Telemetry& telemetry, int deviceId); ~UsbCameraImpl() override; @@ -50,7 +50,7 @@ class UsbCameraImpl : public SourceImpl, // Property functions void SetProperty(int property, int value, CS_Status* status) override; - void SetStringProperty(int property, const wpi::Twine& value, + void SetStringProperty(int property, std::string_view value, CS_Status* status) override; // Standard common camera properties @@ -75,7 +75,7 @@ class UsbCameraImpl : public SourceImpl, void ProcessFrame(IMFSample* sample, const VideoMode& mode); void PostRequestNewFrame(); - void SetPath(const wpi::Twine& path, CS_Status* status); + void SetPath(std::string_view path, CS_Status* status); std::string GetPath() const; // Messages passed to/from camera thread @@ -107,7 +107,7 @@ class UsbCameraImpl : public SourceImpl, protected: std::unique_ptr CreateEmptyProperty( - const wpi::Twine& name) const override; + std::string_view name) const override; // Cache properties. Immediately successful if properties are already cached. // If they are not, tries to connect to the camera to do so; returns false and @@ -132,7 +132,7 @@ class UsbCameraImpl : public SourceImpl, void DeviceCacheProperties(); void DeviceCacheVideoModes(); template - void DeviceAddProperty(const wpi::Twine& name_, TagProperty tag, + void DeviceAddProperty(std::string_view name_, TagProperty tag, IAM* pProcAmp); ComPtr DeviceCheckModeValid(const VideoMode& toCheck); diff --git a/cscore/src/main/native/windows/UsbCameraProperty.cpp b/cscore/src/main/native/windows/UsbCameraProperty.cpp index ebd8967e48..5ddeebf8cd 100644 --- a/cscore/src/main/native/windows/UsbCameraProperty.cpp +++ b/cscore/src/main/native/windows/UsbCameraProperty.cpp @@ -4,14 +4,16 @@ #include "UsbCameraProperty.h" +#include + #include "ComPtr.h" using namespace cs; -UsbCameraProperty::UsbCameraProperty(const wpi::Twine& name_, +UsbCameraProperty::UsbCameraProperty(std::string_view name_, tagVideoProcAmpProperty tag, bool autoProp, IAMVideoProcAmp* pProcAmp, bool* isValid) - : PropertyImpl{autoProp ? name_ + "_auto" : name_} { + : PropertyImpl{autoProp ? fmt::format("{}_auto", name_) : name_} { this->tagVideoProc = tag; this->isControlProperty = false; this->isAutoProp = autoProp; @@ -71,11 +73,11 @@ bool UsbCameraProperty::DeviceSet(std::unique_lock& lock, return false; } -UsbCameraProperty::UsbCameraProperty(const wpi::Twine& name_, +UsbCameraProperty::UsbCameraProperty(std::string_view name_, tagCameraControlProperty tag, bool autoProp, IAMCameraControl* pProcAmp, bool* isValid) - : PropertyImpl{autoProp ? name_ + "_auto" : name_} { + : PropertyImpl{autoProp ? fmt::format("{}_auto", name_) : name_} { this->tagCameraControl = tag; this->isControlProperty = true; this->isAutoProp = autoProp; diff --git a/cscore/src/main/native/windows/UsbCameraProperty.h b/cscore/src/main/native/windows/UsbCameraProperty.h index 7dc52f120d..03cd375393 100644 --- a/cscore/src/main/native/windows/UsbCameraProperty.h +++ b/cscore/src/main/native/windows/UsbCameraProperty.h @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -21,19 +22,19 @@ namespace cs { class UsbCameraProperty : public PropertyImpl { public: UsbCameraProperty() = default; - explicit UsbCameraProperty(const wpi::Twine& name_) : PropertyImpl{name_} {} + explicit UsbCameraProperty(std::string_view name_) : PropertyImpl{name_} {} // Software property constructor - UsbCameraProperty(const wpi::Twine& name_, unsigned id_, - CS_PropertyKind kind_, int minimum_, int maximum_, - int step_, int defaultValue_, int value_) + UsbCameraProperty(std::string_view name_, unsigned id_, CS_PropertyKind kind_, + int minimum_, int maximum_, int step_, int defaultValue_, + int value_) : PropertyImpl(name_, kind_, minimum_, maximum_, step_, defaultValue_, value_), device{false}, id{id_} {} // Normalized property constructor - UsbCameraProperty(const wpi::Twine& name_, int rawIndex_, + UsbCameraProperty(std::string_view name_, int rawIndex_, const UsbCameraProperty& rawProp, int defaultValue_, int value_) : PropertyImpl(name_, rawProp.propKind, 1, defaultValue_, value_), @@ -47,10 +48,10 @@ class UsbCameraProperty : public PropertyImpl { maximum = 100; } - UsbCameraProperty(const wpi::Twine& name_, tagVideoProcAmpProperty tag, + UsbCameraProperty(std::string_view name_, tagVideoProcAmpProperty tag, bool autoProp, IAMVideoProcAmp* pProcAmp, bool* isValid); - UsbCameraProperty(const wpi::Twine& name_, tagCameraControlProperty tag, + UsbCameraProperty(std::string_view name_, tagCameraControlProperty tag, bool autoProp, IAMCameraControl* pProcAmp, bool* isValid); bool DeviceGet(std::unique_lock& lock, diff --git a/glass/.styleguide b/glass/.styleguide index cf7a487147..d555d5af8a 100644 --- a/glass/.styleguide +++ b/glass/.styleguide @@ -21,6 +21,7 @@ repoRootNameOverride { includeOtherLibs { ^GLFW ^cscore + ^fmt/ ^frc/ ^imgui ^ntcore diff --git a/glass/src/app/native/cpp/main.cpp b/glass/src/app/native/cpp/main.cpp index 62821538bf..3e0adf197d 100644 --- a/glass/src/app/native/cpp/main.cpp +++ b/glass/src/app/native/cpp/main.cpp @@ -5,9 +5,9 @@ #include #include +#include #include #include -#include #include #include "glass/Context.h" @@ -24,13 +24,13 @@ namespace gui = wpi::gui; const char* GetWPILibVersion(); namespace glass { -wpi::StringRef GetResource_glass_16_png(); -wpi::StringRef GetResource_glass_32_png(); -wpi::StringRef GetResource_glass_48_png(); -wpi::StringRef GetResource_glass_64_png(); -wpi::StringRef GetResource_glass_128_png(); -wpi::StringRef GetResource_glass_256_png(); -wpi::StringRef GetResource_glass_512_png(); +std::string_view GetResource_glass_16_png(); +std::string_view GetResource_glass_32_png(); +std::string_view GetResource_glass_48_png(); +std::string_view GetResource_glass_64_png(); +std::string_view GetResource_glass_128_png(); +std::string_view GetResource_glass_256_png(); +std::string_view GetResource_glass_512_png(); } // namespace glass static std::unique_ptr gPlotProvider; @@ -56,11 +56,9 @@ static void NtInitialize() { bool timedOut; for (auto&& event : nt::PollConnectionListener(poller, 0, &timedOut)) { if (event.connected) { - wpi::SmallString<64> title; - title = "Glass - Connected ("; - title += event.conn.remote_ip; - title += ')'; - glfwSetWindowTitle(win, title.c_str()); + glfwSetWindowTitle( + win, fmt::format("Glass - Connected ({})", event.conn.remote_ip) + .c_str()); } else { glfwSetWindowTitle(win, "Glass - DISCONNECTED"); } @@ -81,9 +79,8 @@ static void NtInitialize() { } else if (msg.level >= NT_LOG_WARNING) { level = "WARNING: "; } - gNetworkTablesLog.Append( - wpi::Twine{level} + msg.message + wpi::Twine{" ("} + msg.filename + - wpi::Twine{':'} + wpi::Twine{msg.line} + wpi::Twine{")\n"}); + gNetworkTablesLog.Append(fmt::format("{}{} ({}:{})\n", level, msg.message, + msg.filename, msg.line)); } }); diff --git a/glass/src/lib/native/cpp/Context.cpp b/glass/src/lib/native/cpp/Context.cpp index 031170fbe5..936acb2d95 100644 --- a/glass/src/lib/native/cpp/Context.cpp +++ b/glass/src/lib/native/cpp/Context.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include @@ -23,64 +23,47 @@ Context* glass::gContext; static bool ConvertInt(Storage::Value* value) { value->type = Storage::Value::kInt; - if (value->stringVal.empty()) { - return false; - } else { - if (wpi::StringRef{value->stringVal}.getAsInteger(10, value->intVal)) { - return false; - } + if (auto val = wpi::parse_integer(value->stringVal, 10)) { + value->intVal = val.value(); + return true; } - return true; + return false; } static bool ConvertInt64(Storage::Value* value) { value->type = Storage::Value::kInt64; - if (value->stringVal.empty()) { - return false; - } else { - if (wpi::StringRef{value->stringVal}.getAsInteger(10, value->int64Val)) { - return false; - } + if (auto val = wpi::parse_integer(value->stringVal, 10)) { + value->int64Val = val.value(); + return true; } - return true; + return false; } static bool ConvertBool(Storage::Value* value) { value->type = Storage::Value::kBool; - if (value->stringVal.empty()) { - return false; - } else { - int val; - if (wpi::StringRef{value->stringVal}.getAsInteger(10, val)) { - return false; - } - value->boolVal = (val != 0); + if (auto val = wpi::parse_integer(value->stringVal, 10)) { + value->intVal = (val.value() != 0); + return true; } - return true; + return false; } static bool ConvertFloat(Storage::Value* value) { value->type = Storage::Value::kFloat; - if (value->stringVal.empty()) { - return false; - } else { - if (std::sscanf(value->stringVal.c_str(), "%f", &value->floatVal) != 1) { - return false; - } + if (auto val = wpi::parse_float(value->stringVal)) { + value->floatVal = val.value(); + return true; } - return true; + return false; } static bool ConvertDouble(Storage::Value* value) { value->type = Storage::Value::kDouble; - if (value->stringVal.empty()) { - return false; - } else { - if (std::sscanf(value->stringVal.c_str(), "%lf", &value->doubleVal) != 1) { - return false; - } + if (auto val = wpi::parse_float(value->stringVal)) { + value->doubleVal = val.value(); + return true; } - return true; + return false; } static void* GlassStorageReadOpen(ImGuiContext*, ImGuiSettingsHandler* handler, @@ -96,7 +79,7 @@ static void* GlassStorageReadOpen(ImGuiContext*, ImGuiSettingsHandler* handler, static void GlassStorageReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) { auto storage = static_cast(entry); - auto [key, val] = wpi::StringRef{line}.split('='); + auto [key, val] = wpi::split(line, '='); auto& keys = storage->GetKeys(); auto& values = storage->GetValues(); auto it = std::find(keys.begin(), keys.end(), key); @@ -144,7 +127,8 @@ static void GlassStorageWriteAll(ImGuiContext*, ImGuiSettingsHandler* handler, for (auto&& entryIt : sorted) { auto& entry = *entryIt; out_buf->append("[GlassStorage]["); - out_buf->append(entry.first().begin(), entry.first().end()); + out_buf->append(entry.first().data(), + entry.first().data() + entry.first().size()); out_buf->append("]\n"); auto& keys = entry.second->GetKeys(); auto& values = entry.second->GetValues(); @@ -233,7 +217,7 @@ uint64_t glass::GetZeroTime() { return gContext->zeroTime; } -Storage::Value& Storage::GetValue(wpi::StringRef key) { +Storage::Value& Storage::GetValue(std::string_view key) { auto it = std::find(m_keys.begin(), m_keys.end(), key); if (it == m_keys.end()) { m_keys.emplace_back(key); @@ -244,49 +228,49 @@ Storage::Value& Storage::GetValue(wpi::StringRef key) { } } -#define DEFUN(CapsName, LowerName, CType) \ - CType Storage::Get##CapsName(wpi::StringRef key, CType defaultVal) const { \ - auto it = std::find(m_keys.begin(), m_keys.end(), key); \ - if (it == m_keys.end()) \ - return defaultVal; \ - Value& value = *m_values[it - m_keys.begin()]; \ - if (value.type != Value::k##CapsName) { \ - if (!Convert##CapsName(&value)) \ - value.LowerName##Val = defaultVal; \ - } \ - return value.LowerName##Val; \ - } \ - \ - void Storage::Set##CapsName(wpi::StringRef key, CType val) { \ - auto it = std::find(m_keys.begin(), m_keys.end(), key); \ - if (it == m_keys.end()) { \ - m_keys.emplace_back(key); \ - m_values.emplace_back(std::make_unique()); \ - m_values.back()->type = Value::k##CapsName; \ - m_values.back()->LowerName##Val = val; \ - } else { \ - Value& value = *m_values[it - m_keys.begin()]; \ - value.type = Value::k##CapsName; \ - value.LowerName##Val = val; \ - } \ - } \ - \ - CType* Storage::Get##CapsName##Ref(wpi::StringRef key, CType defaultVal) { \ - auto it = std::find(m_keys.begin(), m_keys.end(), key); \ - if (it == m_keys.end()) { \ - m_keys.emplace_back(key); \ - m_values.emplace_back(std::make_unique()); \ - m_values.back()->type = Value::k##CapsName; \ - m_values.back()->LowerName##Val = defaultVal; \ - return &m_values.back()->LowerName##Val; \ - } else { \ - Value& value = *m_values[it - m_keys.begin()]; \ - if (value.type != Value::k##CapsName) { \ - if (!Convert##CapsName(&value)) \ - value.LowerName##Val = defaultVal; \ - } \ - return &value.LowerName##Val; \ - } \ +#define DEFUN(CapsName, LowerName, CType) \ + CType Storage::Get##CapsName(std::string_view key, CType defaultVal) const { \ + auto it = std::find(m_keys.begin(), m_keys.end(), key); \ + if (it == m_keys.end()) \ + return defaultVal; \ + Value& value = *m_values[it - m_keys.begin()]; \ + if (value.type != Value::k##CapsName) { \ + if (!Convert##CapsName(&value)) \ + value.LowerName##Val = defaultVal; \ + } \ + return value.LowerName##Val; \ + } \ + \ + void Storage::Set##CapsName(std::string_view key, CType val) { \ + auto it = std::find(m_keys.begin(), m_keys.end(), key); \ + if (it == m_keys.end()) { \ + m_keys.emplace_back(key); \ + m_values.emplace_back(std::make_unique()); \ + m_values.back()->type = Value::k##CapsName; \ + m_values.back()->LowerName##Val = val; \ + } else { \ + Value& value = *m_values[it - m_keys.begin()]; \ + value.type = Value::k##CapsName; \ + value.LowerName##Val = val; \ + } \ + } \ + \ + CType* Storage::Get##CapsName##Ref(std::string_view key, CType defaultVal) { \ + auto it = std::find(m_keys.begin(), m_keys.end(), key); \ + if (it == m_keys.end()) { \ + m_keys.emplace_back(key); \ + m_values.emplace_back(std::make_unique()); \ + m_values.back()->type = Value::k##CapsName; \ + m_values.back()->LowerName##Val = defaultVal; \ + return &m_values.back()->LowerName##Val; \ + } else { \ + Value& value = *m_values[it - m_keys.begin()]; \ + if (value.type != Value::k##CapsName) { \ + if (!Convert##CapsName(&value)) \ + value.LowerName##Val = defaultVal; \ + } \ + return &value.LowerName##Val; \ + } \ } DEFUN(Int, int, int) @@ -295,18 +279,18 @@ DEFUN(Bool, bool, bool) DEFUN(Float, float, float) DEFUN(Double, double, double) -std::string Storage::GetString(wpi::StringRef key, - const std::string& defaultVal) const { +std::string Storage::GetString(std::string_view key, + std::string_view defaultVal) const { auto it = std::find(m_keys.begin(), m_keys.end(), key); if (it == m_keys.end()) { - return defaultVal; + return std::string{defaultVal}; } Value& value = *m_values[it - m_keys.begin()]; value.type = Value::kString; return value.stringVal; } -void Storage::SetString(wpi::StringRef key, const wpi::Twine& val) { +void Storage::SetString(std::string_view key, std::string_view val) { auto it = std::find(m_keys.begin(), m_keys.end(), key); if (it == m_keys.end()) { m_keys.emplace_back(key); @@ -315,12 +299,12 @@ void Storage::SetString(wpi::StringRef key, const wpi::Twine& val) { } else { Value& value = *m_values[it - m_keys.begin()]; value.type = Value::kString; - value.stringVal = val.str(); + value.stringVal = val; } } -std::string* Storage::GetStringRef(wpi::StringRef key, - wpi::StringRef defaultVal) { +std::string* Storage::GetStringRef(std::string_view key, + std::string_view defaultVal) { auto it = std::find(m_keys.begin(), m_keys.end(), key); if (it == m_keys.end()) { m_keys.emplace_back(key); @@ -342,7 +326,7 @@ Storage& glass::GetStorage() { return *storage; } -Storage& glass::GetStorage(wpi::StringRef id) { +Storage& glass::GetStorage(std::string_view id) { auto& storage = gContext->storage[id]; if (!storage) { storage = std::make_unique(); @@ -350,10 +334,10 @@ Storage& glass::GetStorage(wpi::StringRef id) { return *storage; } -static void PushIDStack(wpi::StringRef label_id) { +static void PushIDStack(std::string_view label_id) { gContext->idStack.emplace_back(gContext->curId.size()); - auto [label, id] = wpi::StringRef{label_id}.split("###"); + auto [label, id] = wpi::split(label_id, "###"); // if no ###id, use label as id if (id.empty()) { id = label; @@ -392,7 +376,7 @@ void glass::EndChild() { bool glass::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { wpi::SmallString<64> openKey; - auto [name, id] = wpi::StringRef{label}.split("###"); + auto [name, id] = wpi::split(label, "###"); // if no ###id, use name as id if (id.empty()) { id = name; @@ -400,7 +384,7 @@ bool glass::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { openKey = id; openKey += "###open"; - bool* open = GetStorage().GetBoolRef(openKey); + bool* open = GetStorage().GetBoolRef(openKey.str()); *open = ImGui::CollapsingHeader( label, flags | (*open ? ImGuiTreeNodeFlags_DefaultOpen : 0)); return *open; @@ -428,7 +412,7 @@ void glass::PushID(const char* str_id) { } void glass::PushID(const char* str_id_begin, const char* str_id_end) { - PushIDStack(wpi::StringRef(str_id_begin, str_id_end - str_id_begin)); + PushIDStack(std::string_view(str_id_begin, str_id_end - str_id_begin)); ImGui::PushID(str_id_begin, str_id_end); } diff --git a/glass/src/lib/native/cpp/DataSource.cpp b/glass/src/lib/native/cpp/DataSource.cpp index ab304fe63d..adab6e75a3 100644 --- a/glass/src/lib/native/cpp/DataSource.cpp +++ b/glass/src/lib/native/cpp/DataSource.cpp @@ -4,13 +4,15 @@ #include "glass/DataSource.h" +#include + #include "glass/ContextInternal.h" using namespace glass; wpi::sig::Signal DataSource::sourceCreated; -DataSource::DataSource(const wpi::Twine& id) : m_id{id.str()} { +DataSource::DataSource(std::string_view id) : m_id{id} { auto it = gContext->sources.try_emplace(m_id, this); auto& srcName = it.first->getValue(); m_name = srcName.name.get(); @@ -20,12 +22,11 @@ DataSource::DataSource(const wpi::Twine& id) : m_id{id.str()} { sourceCreated(m_id.c_str(), this); } -DataSource::DataSource(const wpi::Twine& id, int index) - : DataSource{id + wpi::Twine('[') + wpi::Twine(index) + wpi::Twine(']')} {} +DataSource::DataSource(std::string_view id, int index) + : DataSource{fmt::format("{}[{}]", id, index)} {} -DataSource::DataSource(const wpi::Twine& id, int index, int index2) - : DataSource{id + wpi::Twine('[') + wpi::Twine(index) + wpi::Twine(',') + - wpi::Twine(index2) + wpi::Twine(']')} {} +DataSource::DataSource(std::string_view id, int index, int index2) + : DataSource{fmt::format("{}[{},{}]", id, index, index2)} {} DataSource::~DataSource() { if (!gContext) { @@ -41,7 +42,7 @@ DataSource::~DataSource() { } } -void DataSource::SetName(const wpi::Twine& name) { +void DataSource::SetName(std::string_view name) { m_name->SetName(name); } @@ -146,7 +147,7 @@ void DataSource::EmitDrag(ImGuiDragDropFlags flags) const { } } -DataSource* DataSource::Find(wpi::StringRef id) { +DataSource* DataSource::Find(std::string_view id) { auto it = gContext->sources.find(id); if (it == gContext->sources.end()) { return nullptr; diff --git a/glass/src/lib/native/cpp/Window.cpp b/glass/src/lib/native/cpp/Window.cpp index 83e59aa79f..5c014eb7b1 100644 --- a/glass/src/lib/native/cpp/Window.cpp +++ b/glass/src/lib/native/cpp/Window.cpp @@ -5,7 +5,7 @@ #include "glass/Window.h" #include -#include +#include #include "glass/Context.h" @@ -86,26 +86,21 @@ void Window::ScaleDefault(float scale) { } } -void Window::IniReadLine(const char* lineStr) { - wpi::StringRef line{lineStr}; - auto [name, value] = line.split('='); - name = name.trim(); - value = value.trim(); +void Window::IniReadLine(const char* line) { + auto [name, value] = wpi::split(line, '='); + name = wpi::trim(name); + value = wpi::trim(value); if (name == "name") { m_name = value; } else if (name == "visible") { - int num; - if (value.getAsInteger(10, num)) { - return; + if (auto num = wpi::parse_integer(value, 10)) { + m_visible = num.value(); } - m_visible = num; } else if (name == "enabled") { - int num; - if (value.getAsInteger(10, num)) { - return; + if (auto num = wpi::parse_integer(value, 10)) { + m_enabled = num.value(); } - m_enabled = num; } } diff --git a/glass/src/lib/native/cpp/WindowManager.cpp b/glass/src/lib/native/cpp/WindowManager.cpp index 8e7f971274..037b9bdd2b 100644 --- a/glass/src/lib/native/cpp/WindowManager.cpp +++ b/glass/src/lib/native/cpp/WindowManager.cpp @@ -5,14 +5,14 @@ #include "glass/WindowManager.h" #include +#include -#include -#include +#include #include using namespace glass; -WindowManager::WindowManager(const wpi::Twine& iniName) +WindowManager::WindowManager(std::string_view iniName) : m_iniSaver{iniName, this} {} // read/write open state to ini file @@ -31,42 +31,42 @@ void WindowManager::IniSaver::IniWriteAll(ImGuiTextBuffer* out_buf) { } } -Window* WindowManager::AddWindow(wpi::StringRef id, +Window* WindowManager::AddWindow(std::string_view id, wpi::unique_function display) { auto win = GetOrAddWindow(id, false); if (!win) { return nullptr; } if (win->HasView()) { - wpi::errs() << "GUI: ignoring duplicate window '" << id << "'\n"; + fmt::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); return nullptr; } win->SetView(MakeFunctionView(std::move(display))); return win; } -Window* WindowManager::AddWindow(wpi::StringRef id, +Window* WindowManager::AddWindow(std::string_view id, std::unique_ptr view) { auto win = GetOrAddWindow(id, false); if (!win) { return nullptr; } if (win->HasView()) { - wpi::errs() << "GUI: ignoring duplicate window '" << id << "'\n"; + fmt::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); return nullptr; } win->SetView(std::move(view)); return win; } -Window* WindowManager::GetOrAddWindow(wpi::StringRef id, bool duplicateOk) { +Window* WindowManager::GetOrAddWindow(std::string_view id, bool duplicateOk) { // binary search auto it = std::lower_bound( m_windows.begin(), m_windows.end(), id, - [](const auto& elem, wpi::StringRef s) { return elem->GetId() < s; }); + [](const auto& elem, std::string_view s) { return elem->GetId() < s; }); if (it != m_windows.end() && (*it)->GetId() == id) { if (!duplicateOk) { - wpi::errs() << "GUI: ignoring duplicate window '" << id << "'\n"; + fmt::print(stderr, "GUI: ignoring duplicate window '{}'\n", id); return nullptr; } return it->get(); @@ -75,11 +75,11 @@ Window* WindowManager::GetOrAddWindow(wpi::StringRef id, bool duplicateOk) { return m_windows.emplace(it, std::make_unique(id))->get(); } -Window* WindowManager::GetWindow(wpi::StringRef id) { +Window* WindowManager::GetWindow(std::string_view id) { // binary search auto it = std::lower_bound( m_windows.begin(), m_windows.end(), id, - [](const auto& elem, wpi::StringRef s) { return elem->GetId() < s; }); + [](const auto& elem, std::string_view s) { return elem->GetId() < s; }); if (it == m_windows.end() || (*it)->GetId() != id) { return nullptr; } diff --git a/glass/src/lib/native/cpp/hardware/AnalogInput.cpp b/glass/src/lib/native/cpp/hardware/AnalogInput.cpp index c0f9780361..b9699a4797 100644 --- a/glass/src/lib/native/cpp/hardware/AnalogInput.cpp +++ b/glass/src/lib/native/cpp/hardware/AnalogInput.cpp @@ -48,7 +48,7 @@ void glass::DisplayAnalogInput(AnalogInputModel* model, int index) { } void glass::DisplayAnalogInputs(AnalogInputsModel* model, - wpi::StringRef noneMsg) { + std::string_view noneMsg) { ImGui::Text("(Use Ctrl+Click to edit value)"); bool hasAny = false; bool first = true; @@ -65,6 +65,6 @@ void glass::DisplayAnalogInputs(AnalogInputsModel* model, hasAny = true; }); if (!hasAny && !noneMsg.empty()) { - ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + ImGui::TextUnformatted(noneMsg.data(), noneMsg.data() + noneMsg.size()); } } diff --git a/glass/src/lib/native/cpp/hardware/DIO.cpp b/glass/src/lib/native/cpp/hardware/DIO.cpp index 4d8cdf2a73..59d71f892e 100644 --- a/glass/src/lib/native/cpp/hardware/DIO.cpp +++ b/glass/src/lib/native/cpp/hardware/DIO.cpp @@ -104,7 +104,7 @@ void glass::DisplayDIO(DIOModel* model, int index, bool outputsEnabled) { } void glass::DisplayDIOs(DIOsModel* model, bool outputsEnabled, - wpi::StringRef noneMsg) { + std::string_view noneMsg) { bool hasAny = false; ImGui::PushItemWidth(ImGui::GetFontSize() * 8); @@ -116,6 +116,6 @@ void glass::DisplayDIOs(DIOsModel* model, bool outputsEnabled, }); ImGui::PopItemWidth(); if (!hasAny && !noneMsg.empty()) { - ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + ImGui::TextUnformatted(noneMsg.data(), noneMsg.data() + noneMsg.size()); } } diff --git a/glass/src/lib/native/cpp/hardware/Encoder.cpp b/glass/src/lib/native/cpp/hardware/Encoder.cpp index eca2840e5d..599a5b8a50 100644 --- a/glass/src/lib/native/cpp/hardware/Encoder.cpp +++ b/glass/src/lib/native/cpp/hardware/Encoder.cpp @@ -4,6 +4,7 @@ #include "glass/hardware/Encoder.h" +#include #include #include "glass/Context.h" @@ -11,8 +12,8 @@ using namespace glass; -void EncoderModel::SetName(const wpi::Twine& name) { - if (name.str().empty()) { +void EncoderModel::SetName(std::string_view name) { + if (name.empty()) { if (auto distancePerPulse = GetDistancePerPulseData()) { distancePerPulse->SetName(""); } @@ -33,22 +34,22 @@ void EncoderModel::SetName(const wpi::Twine& name) { } } else { if (auto distancePerPulse = GetDistancePerPulseData()) { - distancePerPulse->SetName(name + " Distance/Count"); + distancePerPulse->SetName(fmt::format("{} Distance/Count", name)); } if (auto count = GetCountData()) { - count->SetName(name + " Count"); + count->SetName(fmt::format("{} Count", name)); } if (auto period = GetPeriodData()) { - period->SetName(name + " Period"); + period->SetName(fmt::format("{} Period", name)); } if (auto direction = GetDirectionData()) { - direction->SetName(name + " Direction"); + direction->SetName(fmt::format("{} Direction", name)); } if (auto distance = GetDistanceData()) { - distance->SetName(name + " Distance"); + distance->SetName(fmt::format("{} Distance", name)); } if (auto rate = GetRateData()) { - rate->SetName(name + " Rate"); + rate->SetName(fmt::format("{} Rate", name)); } } } @@ -153,7 +154,7 @@ void glass::DisplayEncoder(EncoderModel* model) { ImGui::PopItemWidth(); } -void glass::DisplayEncoders(EncodersModel* model, wpi::StringRef noneMsg) { +void glass::DisplayEncoders(EncodersModel* model, std::string_view noneMsg) { bool hasAny = false; model->ForEachEncoder([&](EncoderModel& encoder, int i) { hasAny = true; @@ -162,6 +163,6 @@ void glass::DisplayEncoders(EncodersModel* model, wpi::StringRef noneMsg) { PopID(); }); if (!hasAny && !noneMsg.empty()) { - ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + ImGui::TextUnformatted(noneMsg.data(), noneMsg.data() + noneMsg.size()); } } diff --git a/glass/src/lib/native/cpp/hardware/PCM.cpp b/glass/src/lib/native/cpp/hardware/PCM.cpp index 400df689ba..23746be142 100644 --- a/glass/src/lib/native/cpp/hardware/PCM.cpp +++ b/glass/src/lib/native/cpp/hardware/PCM.cpp @@ -83,7 +83,7 @@ bool glass::DisplayPCMSolenoids(PCMModel* model, int index, } void glass::DisplayPCMsSolenoids(PCMsModel* model, bool outputsEnabled, - wpi::StringRef noneMsg) { + std::string_view noneMsg) { bool hasAny = false; model->ForEachPCM([&](PCMModel& pcm, int i) { PushID(i); @@ -93,7 +93,7 @@ void glass::DisplayPCMsSolenoids(PCMsModel* model, bool outputsEnabled, PopID(); }); if (!hasAny && !noneMsg.empty()) { - ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + ImGui::TextUnformatted(noneMsg.data(), noneMsg.data() + noneMsg.size()); } } diff --git a/glass/src/lib/native/cpp/hardware/PDP.cpp b/glass/src/lib/native/cpp/hardware/PDP.cpp index 23871cabc2..af70116989 100644 --- a/glass/src/lib/native/cpp/hardware/PDP.cpp +++ b/glass/src/lib/native/cpp/hardware/PDP.cpp @@ -79,7 +79,7 @@ void glass::DisplayPDP(PDPModel* model, int index) { } } -void glass::DisplayPDPs(PDPsModel* model, wpi::StringRef noneMsg) { +void glass::DisplayPDPs(PDPsModel* model, std::string_view noneMsg) { bool hasAny = false; model->ForEachPDP([&](PDPModel& pdp, int i) { hasAny = true; @@ -88,6 +88,6 @@ void glass::DisplayPDPs(PDPsModel* model, wpi::StringRef noneMsg) { PopID(); }); if (!hasAny && !noneMsg.empty()) { - ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + ImGui::TextUnformatted(noneMsg.data(), noneMsg.data() + noneMsg.size()); } } diff --git a/glass/src/lib/native/cpp/hardware/PWM.cpp b/glass/src/lib/native/cpp/hardware/PWM.cpp index 6fbc6243b5..3ff8e5273b 100644 --- a/glass/src/lib/native/cpp/hardware/PWM.cpp +++ b/glass/src/lib/native/cpp/hardware/PWM.cpp @@ -41,7 +41,7 @@ void glass::DisplayPWM(PWMModel* model, int index, bool outputsEnabled) { } void glass::DisplayPWMs(PWMsModel* model, bool outputsEnabled, - wpi::StringRef noneMsg) { + std::string_view noneMsg) { bool hasAny = false; bool first = true; model->ForEachPWM([&](PWMModel& pwm, int i) { @@ -58,6 +58,6 @@ void glass::DisplayPWMs(PWMsModel* model, bool outputsEnabled, PopID(); }); if (!hasAny && !noneMsg.empty()) { - ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + ImGui::TextUnformatted(noneMsg.data(), noneMsg.data() + noneMsg.size()); } } diff --git a/glass/src/lib/native/cpp/hardware/Relay.cpp b/glass/src/lib/native/cpp/hardware/Relay.cpp index f0dbbf7209..59bbc51b64 100644 --- a/glass/src/lib/native/cpp/hardware/Relay.cpp +++ b/glass/src/lib/native/cpp/hardware/Relay.cpp @@ -60,7 +60,7 @@ void glass::DisplayRelay(RelayModel* model, int index, bool outputsEnabled) { } void glass::DisplayRelays(RelaysModel* model, bool outputsEnabled, - wpi::StringRef noneMsg) { + std::string_view noneMsg) { bool hasAny = false; bool first = true; model->ForEachRelay([&](RelayModel& relay, int i) { @@ -77,6 +77,6 @@ void glass::DisplayRelays(RelaysModel* model, bool outputsEnabled, PopID(); }); if (!hasAny && !noneMsg.empty()) { - ImGui::TextUnformatted(noneMsg.begin(), noneMsg.end()); + ImGui::TextUnformatted(noneMsg.data(), noneMsg.data() + noneMsg.size()); } } diff --git a/glass/src/lib/native/cpp/other/Field2D.cpp b/glass/src/lib/native/cpp/other/Field2D.cpp index 0fda587ee7..e926019674 100644 --- a/glass/src/lib/native/cpp/other/Field2D.cpp +++ b/glass/src/lib/native/cpp/other/Field2D.cpp @@ -6,9 +6,12 @@ #include #include +#include #include +#include #include +#include #include #include #include @@ -21,11 +24,11 @@ #include #include #include +#include #include #include #include #include -#include #include #include "glass/Context.h" @@ -229,7 +232,7 @@ class FieldInfo { private: void Reset(); bool LoadImageImpl(const char* fn); - void LoadJson(const wpi::Twine& jsonfile); + void LoadJson(std::string_view jsonfile); std::unique_ptr m_fileOpener; @@ -377,7 +380,7 @@ void FieldInfo::LoadImage() { if (m_fileOpener && m_fileOpener->ready(0)) { auto result = m_fileOpener->result(); if (!result.empty()) { - if (wpi::StringRef(result[0]).endswith(".json")) { + if (wpi::ends_with(result[0], ".json")) { LoadJson(result[0]); } else { LoadImageImpl(result[0].c_str()); @@ -396,11 +399,11 @@ void FieldInfo::LoadImage() { } } -void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { +void FieldInfo::LoadJson(std::string_view jsonfile) { std::error_code ec; wpi::raw_fd_istream f(jsonfile, ec); if (ec) { - wpi::errs() << "GUI: could not open field JSON file\n"; + std::fputs("GUI: could not open field JSON file\n", stderr); return; } @@ -409,12 +412,12 @@ void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { try { j = wpi::json::parse(f); } catch (const wpi::json::parse_error& e) { - wpi::errs() << "GUI: JSON: could not parse: " << e.what() << '\n'; + fmt::print(stderr, "GUI: JSON: could not parse: {}\n", e.what()); } // top level must be an object if (!j.is_object()) { - wpi::errs() << "GUI: JSON: does not contain a top object\n"; + std::fputs("GUI: JSON: does not contain a top object\n", stderr); return; } @@ -423,8 +426,7 @@ void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { try { image = j.at("field-image").get(); } catch (const wpi::json::exception& e) { - wpi::errs() << "GUI: JSON: could not read field-image: " << e.what() - << '\n'; + fmt::print(stderr, "GUI: JSON: could not read field-image: {}\n", e.what()); return; } @@ -436,8 +438,8 @@ void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { bottom = j.at("field-corners").at("bottom-right").at(1).get(); right = j.at("field-corners").at("bottom-right").at(0).get(); } catch (const wpi::json::exception& e) { - wpi::errs() << "GUI: JSON: could not read field-corners: " << e.what() - << '\n'; + fmt::print(stderr, "GUI: JSON: could not read field-corners: {}\n", + e.what()); return; } @@ -448,7 +450,7 @@ void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { width = j.at("field-size").at(0).get(); height = j.at("field-size").at(1).get(); } catch (const wpi::json::exception& e) { - wpi::errs() << "GUI: JSON: could not read field-size: " << e.what() << '\n'; + fmt::print(stderr, "GUI: JSON: could not read field-size: {}\n", e.what()); return; } @@ -457,7 +459,7 @@ void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { try { unit = j.at("field-unit").get(); } catch (const wpi::json::exception& e) { - wpi::errs() << "GUI: JSON: could not read field-unit: " << e.what() << '\n'; + fmt::print(stderr, "GUI: JSON: could not read field-unit: {}\n", e.what()); return; } @@ -468,7 +470,7 @@ void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { } // the image filename is relative to the json file - auto pathname = fs::path{jsonfile.str()}.replace_filename(image).string(); + auto pathname = fs::path{jsonfile}.replace_filename(image).string(); // load field image if (!LoadImageImpl(pathname.c_str())) { @@ -486,10 +488,10 @@ void FieldInfo::LoadJson(const wpi::Twine& jsonfile) { } bool FieldInfo::LoadImageImpl(const char* fn) { - wpi::outs() << "GUI: loading field image '" << fn << "'\n"; + fmt::print("GUI: loading field image '{}'\n", fn); auto texture = gui::Texture::CreateFromFile(fn); if (!texture) { - wpi::errs() << "GUI: could not read field image\n"; + std::puts("GUI: could not read field image"); return false; } m_texture = std::move(texture); @@ -679,10 +681,10 @@ void ObjectInfo::LoadImage() { } bool ObjectInfo::LoadImageImpl(const char* fn) { - wpi::outs() << "GUI: loading object image '" << fn << "'\n"; + fmt::print("GUI: loading object image '{}'\n", fn); auto texture = gui::Texture::CreateFromFile(fn); if (!texture) { - wpi::errs() << "GUI: could not read object image\n"; + std::fputs("GUI: could not read object image\n", stderr); return false; } m_texture = std::move(texture); @@ -883,7 +885,7 @@ void glass::DisplayField2DSettings(Field2DModel* model) { } auto obj = objRef.get(); - wpi::SmallString<64> nameBuf = name; + wpi::SmallString<64> nameBuf{name}; if (ImGui::CollapsingHeader(nameBuf.c_str())) { obj->DisplaySettings(); } @@ -899,7 +901,7 @@ class FieldDisplay { const ImVec2& contentSize); private: - void DisplayObject(FieldObjectModel& model, wpi::StringRef name); + void DisplayObject(FieldObjectModel& model, std::string_view name); FieldInfo* m_field; ImVec2 m_mousePos; @@ -1018,7 +1020,8 @@ void FieldDisplay::Display(FieldInfo* field, Field2DModel* model, } } -void FieldDisplay::DisplayObject(FieldObjectModel& model, wpi::StringRef name) { +void FieldDisplay::DisplayObject(FieldObjectModel& model, + std::string_view name) { PushID(name); auto& objRef = m_field->m_objects[name]; if (!objRef) { diff --git a/glass/src/lib/native/cpp/other/Log.cpp b/glass/src/lib/native/cpp/other/Log.cpp index 8e6db5d4aa..9a1d2c5cc2 100644 --- a/glass/src/lib/native/cpp/other/Log.cpp +++ b/glass/src/lib/native/cpp/other/Log.cpp @@ -5,7 +5,6 @@ #include "glass/other/Log.h" #include -#include using namespace glass; @@ -17,14 +16,13 @@ void LogData::Clear() { m_lineOffsets.push_back(0); } -void LogData::Append(const wpi::Twine& msg) { +void LogData::Append(std::string_view msg) { if (m_lineOffsets.size() >= m_maxLines) { Clear(); } size_t oldSize = m_buf.size(); - wpi::raw_string_ostream os{m_buf}; - msg.print(os); + m_buf.append(msg); for (size_t newSize = m_buf.size(); oldSize < newSize; ++oldSize) { if (m_buf[oldSize] == '\n') { m_lineOffsets.push_back(oldSize + 1); diff --git a/glass/src/lib/native/cpp/other/Mechanism2D.cpp b/glass/src/lib/native/cpp/other/Mechanism2D.cpp index 86e7d898a8..07e83e2f86 100644 --- a/glass/src/lib/native/cpp/other/Mechanism2D.cpp +++ b/glass/src/lib/native/cpp/other/Mechanism2D.cpp @@ -6,9 +6,12 @@ #include #include +#include #include +#include #include +#include #include #include #include @@ -21,7 +24,6 @@ #include #include #include -#include #include #include "glass/Context.h" @@ -125,10 +127,10 @@ void BackgroundInfo::LoadImage() { } bool BackgroundInfo::LoadImageImpl(const char* fn) { - wpi::outs() << "GUI: loading background image '" << fn << "'\n"; + fmt::print("GUI: loading background image '{}'\n", fn); auto texture = gui::Texture::CreateFromFile(fn); if (!texture) { - wpi::errs() << "GUI: could not read background image\n"; + std::puts("GUI: could not read background image"); return false; } m_texture = std::move(texture); @@ -182,7 +184,7 @@ void glass::DisplayMechanism2DSettings(Mechanism2DModel* model) { void FrameData::DrawObject(ImDrawList* drawList, MechanismObjectModel& objModel, const frc::Pose2d& pose) const { const char* type = objModel.GetType(); - if (wpi::StringRef{type} == "line") { + if (std::string_view{type} == "line") { auto startPose = pose + frc::Transform2d{frc::Translation2d{}, objModel.GetAngle()}; auto endPose = diff --git a/glass/src/lib/native/cpp/other/Plot.cpp b/glass/src/lib/native/cpp/other/Plot.cpp index 7faa54ad11..372f8c959b 100644 --- a/glass/src/lib/native/cpp/other/Plot.cpp +++ b/glass/src/lib/native/cpp/other/Plot.cpp @@ -12,8 +12,11 @@ #include #include #include +#include #include +#include + #define IMGUI_DEFINE_MATH_OPERATORS #include #include @@ -23,6 +26,7 @@ #include #include #include +#include #include #include "glass/Context.h" @@ -42,7 +46,7 @@ struct PlotSeriesRef { class PlotSeries { public: - explicit PlotSeries(wpi::StringRef id); + explicit PlotSeries(std::string_view id); explicit PlotSeries(DataSource* source, int yAxis = 0); const std::string& GetId() const { return m_id; } @@ -52,7 +56,7 @@ class PlotSeries { void SetSource(DataSource* source); DataSource* GetSource() const { return m_source; } - bool ReadIni(wpi::StringRef name, wpi::StringRef value); + bool ReadIni(std::string_view name, std::string_view value); void WriteIni(ImGuiTextBuffer* out); enum Action { kNone, kMoveUp, kMoveDown, kDelete }; @@ -102,7 +106,7 @@ class Plot { public: Plot(); - bool ReadIni(wpi::StringRef name, wpi::StringRef value); + bool ReadIni(std::string_view name, std::string_view value); void WriteIni(ImGuiTextBuffer* out); void DragDropTarget(PlotView& view, size_t i, bool inPlot); @@ -164,7 +168,7 @@ class PlotView : public View { } // namespace -PlotSeries::PlotSeries(wpi::StringRef id) : m_id(id) { +PlotSeries::PlotSeries(std::string_view id) : m_id(id) { if (DataSource* source = DataSource::Find(id)) { SetSource(source); return; @@ -241,55 +245,45 @@ void PlotSeries::AppendValue(double value, uint64_t timeUs) { } } -bool PlotSeries::ReadIni(wpi::StringRef name, wpi::StringRef value) { +bool PlotSeries::ReadIni(std::string_view name, std::string_view value) { if (name == "name") { m_name = value; return true; } if (name == "yAxis") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_yAxis = num.value(); } - m_yAxis = num; return true; } else if (name == "color") { - unsigned int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_color = ImColor(num.value()); } - m_color = ImColor(num); return true; } else if (name == "marker") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_marker = num.value(); } - m_marker = num; return true; } else if (name == "weight") { - std::sscanf(value.data(), "%f", &m_weight); + if (auto num = wpi::parse_float(value)) { + m_weight = num.value(); + } return true; } else if (name == "digital") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_digital = num.value(); } - m_digital = num; return true; } else if (name == "digitalBitHeight") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_digitalBitHeight = num.value(); } - m_digitalBitHeight = num; return true; } else if (name == "digitalBitGap") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_digitalBitGap = num.value(); } - m_digitalBitGap = num; return true; } return false; @@ -478,121 +472,93 @@ Plot::Plot() { } } -bool Plot::ReadIni(wpi::StringRef name, wpi::StringRef value) { +bool Plot::ReadIni(std::string_view name, std::string_view value) { if (name == "name") { m_name = value; return true; } else if (name == "visible") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_visible = num.value() != 0; } - m_visible = num != 0; return true; } else if (name == "showPause") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_showPause = num.value() != 0; } - m_showPause = num != 0; return true; } else if (name == "lockPrevX") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_lockPrevX = num.value() != 0; } - m_lockPrevX = num != 0; return true; } else if (name == "legend") { - int num; - if (value.getAsInteger(10, num)) { - return true; - } - if (num == 0) { - m_plotFlags |= ImPlotFlags_NoLegend; - } else { - m_plotFlags &= ~ImPlotFlags_NoLegend; + if (auto num = wpi::parse_integer(value, 10)) { + if (num.value() == 0) { + m_plotFlags |= ImPlotFlags_NoLegend; + } else { + m_plotFlags &= ~ImPlotFlags_NoLegend; + } } return true; } else if (name == "yaxis2") { - int num; - if (value.getAsInteger(10, num)) { - return true; - } - if (num == 0) { - m_plotFlags &= ~ImPlotFlags_YAxis2; - } else { - m_plotFlags |= ImPlotFlags_YAxis2; + if (auto num = wpi::parse_integer(value, 10)) { + if (num.value() == 0) { + m_plotFlags &= ~ImPlotFlags_YAxis2; + } else { + m_plotFlags |= ImPlotFlags_YAxis2; + } } return true; } else if (name == "yaxis3") { - int num; - if (value.getAsInteger(10, num)) { - return true; - } - if (num == 0) { - m_plotFlags &= ~ImPlotFlags_YAxis3; - } else { - m_plotFlags |= ImPlotFlags_YAxis3; + if (auto num = wpi::parse_integer(value, 10)) { + if (num.value() == 0) { + m_plotFlags &= ~ImPlotFlags_YAxis3; + } else { + m_plotFlags |= ImPlotFlags_YAxis3; + } } return true; } else if (name == "viewTime") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_viewTime = num.value() / 1000.0; } - m_viewTime = num / 1000.0; return true; } else if (name == "autoHeight") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_autoHeight = num.value() != 0; } - m_autoHeight = num != 0; return true; } else if (name == "height") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_height = num.value(); } - m_height = num; return true; - } else if (name.startswith("y")) { - auto [yAxisStr, yName] = name.split('_'); - int yAxis; - if (yAxisStr.substr(1).getAsInteger(10, yAxis)) { - return false; - } + } else if (wpi::starts_with(name, 'y')) { + auto [yAxisStr, yName] = wpi::split(name, '_'); + int yAxis = + wpi::parse_integer(wpi::drop_front(yAxisStr), 10).value_or(-1); if (yAxis < 0 || yAxis > 3) { return false; } if (yName == "min") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_axisRange[yAxis].min = num.value() / 1000.0; } - m_axisRange[yAxis].min = num / 1000.0; return true; } else if (yName == "max") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_axisRange[yAxis].max = num.value() / 1000.0; } - m_axisRange[yAxis].max = num / 1000.0; return true; } else if (yName == "lockMin") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_axisRange[yAxis].lockMin = num.value() != 0; } - m_axisRange[yAxis].lockMin = num != 0; return true; } else if (yName == "lockMax") { - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_axisRange[yAxis].lockMax = num.value() != 0; } - m_axisRange[yAxis].lockMax = num != 0; return true; } else if (yName == "label") { m_axisLabel[yAxis] = value; @@ -960,10 +926,10 @@ void PlotView::MovePlotSeries(PlotView* fromView, size_t fromPlotIndex, } } -PlotProvider::PlotProvider(const wpi::Twine& iniName) - : WindowManager{iniName + "Window"}, +PlotProvider::PlotProvider(std::string_view iniName) + : WindowManager{fmt::format("{}Window", iniName)}, m_plotSaver{iniName, this, false}, - m_seriesSaver{iniName + "Series", this, true} {} + m_seriesSaver{fmt::format("{}Series", iniName), this, true} {} PlotProvider::~PlotProvider() = default; @@ -1021,21 +987,23 @@ void PlotProvider::DisplayWindows() { WindowManager::DisplayWindows(); } -PlotProvider::IniSaver::IniSaver(const wpi::Twine& typeName, +PlotProvider::IniSaver::IniSaver(std::string_view typeName, PlotProvider* provider, bool forSeries) : IniSaverBase{typeName}, m_provider{provider}, m_forSeries{forSeries} {} void* PlotProvider::IniSaver::IniReadOpen(const char* name) { - auto [viewId, plotNumStr] = wpi::StringRef{name}.split('#'); - wpi::StringRef seriesId; + auto [viewId, plotNumStr] = wpi::split(name, '#'); + std::string_view seriesId; if (m_forSeries) { - std::tie(plotNumStr, seriesId) = plotNumStr.split('#'); + std::tie(plotNumStr, seriesId) = wpi::split(plotNumStr, '#'); if (seriesId.empty()) { return nullptr; } } unsigned int plotNum; - if (plotNumStr.getAsInteger(10, plotNum)) { + if (auto plotNumOpt = wpi::parse_integer(plotNumStr, 10)) { + plotNum = plotNumOpt.value(); + } else { return nullptr; } @@ -1071,10 +1039,10 @@ void* PlotProvider::IniSaver::IniReadOpen(const char* name) { .get(); } -void PlotProvider::IniSaver::IniReadLine(void* entry, const char* lineStr) { - auto [name, value] = wpi::StringRef{lineStr}.split('='); - name = name.trim(); - value = value.trim(); +void PlotProvider::IniSaver::IniReadLine(void* entry, const char* line) { + auto [name, value] = wpi::split(line, '='); + name = wpi::trim(name); + value = wpi::trim(value); if (m_forSeries) { static_cast(entry)->ReadIni(name, value); } else { diff --git a/glass/src/lib/native/cpp/support/IniSaverBase.cpp b/glass/src/lib/native/cpp/support/IniSaverBase.cpp index e222818d03..ae8d811d41 100644 --- a/glass/src/lib/native/cpp/support/IniSaverBase.cpp +++ b/glass/src/lib/native/cpp/support/IniSaverBase.cpp @@ -54,9 +54,8 @@ static ImGuiSaver* GetSaverInstance() { return inst; } -IniSaverBase::IniSaverBase(const wpi::Twine& typeName, IniSaverBackend* backend) - : m_typeName(typeName.str()), - m_backend{backend ? backend : GetSaverInstance()} {} +IniSaverBase::IniSaverBase(std::string_view typeName, IniSaverBackend* backend) + : m_typeName(typeName), m_backend{backend ? backend : GetSaverInstance()} {} IniSaverBase::~IniSaverBase() { m_backend->Unregister(this); diff --git a/glass/src/lib/native/cpp/support/IniSaverInfo.cpp b/glass/src/lib/native/cpp/support/IniSaverInfo.cpp index 32911da255..6525e8e69d 100644 --- a/glass/src/lib/native/cpp/support/IniSaverInfo.cpp +++ b/glass/src/lib/native/cpp/support/IniSaverInfo.cpp @@ -8,15 +8,13 @@ #include #include -#include +#include using namespace glass; -void NameInfo::SetName(const wpi::Twine& name) { - wpi::SmallString<64> nameBuf; - auto nameStr = name.toStringRef(nameBuf); - size_t len = (std::min)(nameStr.size(), sizeof(m_name) - 1); - std::memcpy(m_name, nameStr.data(), len); +void NameInfo::SetName(std::string_view name) { + size_t len = (std::min)(name.size(), sizeof(m_name) - 1); + std::memcpy(m_name, name.data(), len); m_name[len] = '\0'; } @@ -74,7 +72,7 @@ void NameInfo::GetLabel(char* buf, size_t size, const char* defaultName, } } -bool NameInfo::ReadIni(wpi::StringRef name, wpi::StringRef value) { +bool NameInfo::ReadIni(std::string_view name, std::string_view value) { if (name != "name") { return false; } @@ -140,15 +138,13 @@ bool NameInfo::InputTextName(const char* label_id, ImGuiInputTextFlags flags) { return ImGui::InputText(label_id, m_name, sizeof(m_name), flags); } -bool OpenInfo::ReadIni(wpi::StringRef name, wpi::StringRef value) { +bool OpenInfo::ReadIni(std::string_view name, std::string_view value) { if (name != "open") { return false; } - int num; - if (value.getAsInteger(10, num)) { - return true; + if (auto num = wpi::parse_integer(value, 10)) { + m_open = num.value(); } - m_open = num; return true; } @@ -156,7 +152,7 @@ void OpenInfo::WriteIni(ImGuiTextBuffer* out) { out->appendf("open=%d\n", m_open ? 1 : 0); } -bool NameOpenInfo::ReadIni(wpi::StringRef name, wpi::StringRef value) { +bool NameOpenInfo::ReadIni(std::string_view name, std::string_view value) { if (NameInfo::ReadIni(name, value)) { return true; } diff --git a/glass/src/lib/native/include/glass/Context.h b/glass/src/lib/native/include/glass/Context.h index bb3c0209e2..62b0a33470 100644 --- a/glass/src/lib/native/include/glass/Context.h +++ b/glass/src/lib/native/include/glass/Context.h @@ -6,12 +6,11 @@ #include #include +#include #include #include #include -#include -#include namespace glass { @@ -48,7 +47,7 @@ class Storage { public: struct Value { Value() = default; - explicit Value(const wpi::Twine& str) : stringVal{str.str()} {} + explicit Value(std::string_view str) : stringVal{str} {} enum Type { kNone, kInt, kInt64, kBool, kFloat, kDouble, kString }; Type type = kNone; @@ -62,29 +61,30 @@ class Storage { std::string stringVal; }; - int GetInt(wpi::StringRef key, int defaultVal = 0) const; - int64_t GetInt64(wpi::StringRef key, int64_t defaultVal = 0) const; - bool GetBool(wpi::StringRef key, bool defaultVal = false) const; - float GetFloat(wpi::StringRef key, float defaultVal = 0.0f) const; - double GetDouble(wpi::StringRef key, double defaultVal = 0.0) const; - std::string GetString(wpi::StringRef key, - const std::string& defaultVal = {}) const; + int GetInt(std::string_view key, int defaultVal = 0) const; + int64_t GetInt64(std::string_view key, int64_t defaultVal = 0) const; + bool GetBool(std::string_view key, bool defaultVal = false) const; + float GetFloat(std::string_view key, float defaultVal = 0.0f) const; + double GetDouble(std::string_view key, double defaultVal = 0.0) const; + std::string GetString(std::string_view key, + std::string_view defaultVal = {}) const; - void SetInt(wpi::StringRef key, int val); - void SetInt64(wpi::StringRef key, int64_t val); - void SetBool(wpi::StringRef key, bool val); - void SetFloat(wpi::StringRef key, float val); - void SetDouble(wpi::StringRef key, double val); - void SetString(wpi::StringRef key, const wpi::Twine& val); + void SetInt(std::string_view key, int val); + void SetInt64(std::string_view key, int64_t val); + void SetBool(std::string_view key, bool val); + void SetFloat(std::string_view key, float val); + void SetDouble(std::string_view key, double val); + void SetString(std::string_view key, std::string_view val); - int* GetIntRef(wpi::StringRef key, int defaultVal = 0); - int64_t* GetInt64Ref(wpi::StringRef key, int64_t defaultVal = 0); - bool* GetBoolRef(wpi::StringRef key, bool defaultVal = false); - float* GetFloatRef(wpi::StringRef key, float defaultVal = 0.0f); - double* GetDoubleRef(wpi::StringRef key, double defaultVal = 0.0); - std::string* GetStringRef(wpi::StringRef key, wpi::StringRef defaultVal = {}); + int* GetIntRef(std::string_view key, int defaultVal = 0); + int64_t* GetInt64Ref(std::string_view key, int64_t defaultVal = 0); + bool* GetBoolRef(std::string_view key, bool defaultVal = false); + float* GetFloatRef(std::string_view key, float defaultVal = 0.0f); + double* GetDoubleRef(std::string_view key, double defaultVal = 0.0); + std::string* GetStringRef(std::string_view key, + std::string_view defaultVal = {}); - Value& GetValue(wpi::StringRef key); + Value& GetValue(std::string_view key); void SetData(std::shared_ptr&& data) { m_data = std::move(data); } @@ -111,7 +111,7 @@ class Storage { }; Storage& GetStorage(); -Storage& GetStorage(wpi::StringRef id); +Storage& GetStorage(std::string_view id); bool Begin(const char* name, bool* p_open = nullptr, ImGuiWindowFlags flags = 0); @@ -141,8 +141,8 @@ void PushID(const char* str_id); void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string). -inline void PushID(wpi::StringRef str) { - PushID(str.begin(), str.end()); +inline void PushID(std::string_view str) { + PushID(str.data(), str.data() + str.size()); } // push integer into the ID stack (will hash integer). diff --git a/glass/src/lib/native/include/glass/ContextInternal.h b/glass/src/lib/native/include/glass/ContextInternal.h index 58f1e21776..39e54f3925 100644 --- a/glass/src/lib/native/include/glass/ContextInternal.h +++ b/glass/src/lib/native/include/glass/ContextInternal.h @@ -26,7 +26,7 @@ class DataSourceName { DataSourceName() = default; explicit DataSourceName(DataSource* source) : source{source} {} - bool ReadIni(wpi::StringRef name_, wpi::StringRef value) { + bool ReadIni(std::string_view name_, std::string_view value) { return name->ReadIni(name_, value); } void WriteIni(ImGuiTextBuffer* out) { name->WriteIni(out); } diff --git a/glass/src/lib/native/include/glass/DataSource.h b/glass/src/lib/native/include/glass/DataSource.h index 657dbf7870..1d5c37b0d8 100644 --- a/glass/src/lib/native/include/glass/DataSource.h +++ b/glass/src/lib/native/include/glass/DataSource.h @@ -8,11 +8,10 @@ #include #include +#include #include #include -#include -#include #include namespace glass { @@ -24,9 +23,9 @@ class NameInfo; */ class DataSource { public: - explicit DataSource(const wpi::Twine& id); - DataSource(const wpi::Twine& id, int index); - DataSource(const wpi::Twine& id, int index, int index2); + explicit DataSource(std::string_view id); + DataSource(std::string_view id, int index); + DataSource(std::string_view id, int index, int index2); virtual ~DataSource(); DataSource(const DataSource&) = delete; @@ -34,7 +33,7 @@ class DataSource { const char* GetId() const { return m_id.c_str(); } - void SetName(const wpi::Twine& name); + void SetName(std::string_view name); const char* GetName() const; NameInfo& GetNameInfo() { return *m_name; } @@ -69,7 +68,7 @@ class DataSource { wpi::sig::SignalBase valueChanged; - static DataSource* Find(wpi::StringRef id); + static DataSource* Find(std::string_view id); static wpi::sig::Signal sourceCreated; diff --git a/glass/src/lib/native/include/glass/Provider.h b/glass/src/lib/native/include/glass/Provider.h index 9eafbeefea..53b1e75f2d 100644 --- a/glass/src/lib/native/include/glass/Provider.h +++ b/glass/src/lib/native/include/glass/Provider.h @@ -8,11 +8,10 @@ #include #include #include +#include #include #include -#include -#include #include #include "glass/Model.h" @@ -52,7 +51,7 @@ class Provider : public WindowManager { * * @param iniName Group name to use in ini file */ - explicit Provider(const wpi::Twine& iniName) : WindowManager{iniName} {} + explicit Provider(std::string_view iniName) : WindowManager{iniName} {} Provider(const Provider&) = delete; Provider& operator=(const Provider&) = delete; @@ -69,7 +68,7 @@ class Provider : public WindowManager { * * @param name View name */ - void ShowDefault(wpi::StringRef name); + void ShowDefault(std::string_view name); /** * Register a model and view combination. Equivalent to calling both @@ -80,7 +79,7 @@ class Provider : public WindowManager { * @param createModel Functor for creating model * @param createView Functor for creating view */ - void Register(wpi::StringRef name, ExistsFunc exists, + void Register(std::string_view name, ExistsFunc exists, CreateModelFunc createModel, CreateViewFunc createView); /** @@ -90,7 +89,7 @@ class Provider : public WindowManager { * @param exists Functor, returns true if model can be created * @param createModel Functor for creating model */ - void RegisterModel(wpi::StringRef name, ExistsFunc exists, + void RegisterModel(std::string_view name, ExistsFunc exists, CreateModelFunc createModel); /** @@ -101,14 +100,14 @@ class Provider : public WindowManager { * @param exists Functor, returns true if view can be created * @param createView Functor for creating view */ - void RegisterView(wpi::StringRef name, wpi::StringRef modelName, + void RegisterView(std::string_view name, std::string_view modelName, ViewExistsFunc exists, CreateViewFunc createView); protected: virtual void Update(); struct ModelEntry { - ModelEntry(wpi::StringRef name, ExistsFunc exists, + ModelEntry(std::string_view name, ExistsFunc exists, CreateModelFunc createModel) : name{name}, exists{std::move(exists)}, @@ -122,7 +121,7 @@ class Provider : public WindowManager { }; struct ViewEntry { - ViewEntry(wpi::StringRef name, ModelEntry* modelEntry, + ViewEntry(std::string_view name, ModelEntry* modelEntry, ViewExistsFunc exists, CreateViewFunc createView) : name{name}, modelEntry{modelEntry}, @@ -143,16 +142,16 @@ class Provider : public WindowManager { using ViewEntries = std::vector>; ViewEntries m_viewEntries; - typename ModelEntries::iterator FindModelEntry(wpi::StringRef name); - typename ViewEntries::iterator FindViewEntry(wpi::StringRef name); + typename ModelEntries::iterator FindModelEntry(std::string_view name); + typename ViewEntries::iterator FindViewEntry(std::string_view name); virtual std::unique_ptr MakeModelEntry( - wpi::StringRef name, ExistsFunc exists, CreateModelFunc createModel) { + std::string_view name, ExistsFunc exists, CreateModelFunc createModel) { return std::make_unique(name, std::move(exists), std::move(createModel)); } - virtual std::unique_ptr MakeViewEntry(wpi::StringRef name, + virtual std::unique_ptr MakeViewEntry(std::string_view name, ModelEntry* modelEntry, ViewExistsFunc exists, CreateViewFunc createView) { diff --git a/glass/src/lib/native/include/glass/Provider.inc b/glass/src/lib/native/include/glass/Provider.inc index 357812c659..33bb6e031d 100644 --- a/glass/src/lib/native/include/glass/Provider.inc +++ b/glass/src/lib/native/include/glass/Provider.inc @@ -17,7 +17,7 @@ void Provider::GlobalInit() { } template -void Provider::ShowDefault(wpi::StringRef name) { +void Provider::ShowDefault(std::string_view name) { auto win = GetWindow(name); if (win) { return; @@ -30,7 +30,7 @@ void Provider::ShowDefault(wpi::StringRef name) { } template -void Provider::Register(wpi::StringRef name, ExistsFunc exists, +void Provider::Register(std::string_view name, ExistsFunc exists, CreateModelFunc createModel, CreateViewFunc createView) { RegisterModel(name, std::move(exists), std::move(createModel)); @@ -38,7 +38,8 @@ void Provider::Register(wpi::StringRef name, ExistsFunc exists, } template -void Provider::RegisterModel(wpi::StringRef name, ExistsFunc exists, +void Provider::RegisterModel(std::string_view name, + ExistsFunc exists, CreateModelFunc createModel) { auto it = FindModelEntry(name); // ignore if exists @@ -51,8 +52,8 @@ void Provider::RegisterModel(wpi::StringRef name, ExistsFunc exists, } template -void Provider::RegisterView(wpi::StringRef name, - wpi::StringRef modelName, +void Provider::RegisterView(std::string_view name, + std::string_view modelName, ViewExistsFunc exists, CreateViewFunc createView) { // find model; if model doesn't exist, ignore @@ -84,18 +85,18 @@ void Provider::Update() { template typename Provider::ModelEntries::iterator -Provider::FindModelEntry(wpi::StringRef name) { +Provider::FindModelEntry(std::string_view name) { return std::lower_bound( m_modelEntries.begin(), m_modelEntries.end(), name, - [](const auto& elem, wpi::StringRef s) { return elem->name < s; }); + [](const auto& elem, std::string_view s) { return elem->name < s; }); } template typename Provider::ViewEntries::iterator -Provider::FindViewEntry(wpi::StringRef name) { +Provider::FindViewEntry(std::string_view name) { return std::lower_bound( m_viewEntries.begin(), m_viewEntries.end(), name, - [](const auto& elem, wpi::StringRef s) { return elem->name < s; }); + [](const auto& elem, std::string_view s) { return elem->name < s; }); } } // namespace glass diff --git a/glass/src/lib/native/include/glass/Window.h b/glass/src/lib/native/include/glass/Window.h index 504b53e11a..780479a105 100644 --- a/glass/src/lib/native/include/glass/Window.h +++ b/glass/src/lib/native/include/glass/Window.h @@ -6,11 +6,10 @@ #include #include +#include #include #include -#include -#include #include "glass/View.h" @@ -23,9 +22,9 @@ namespace glass { class Window { public: Window() = default; - explicit Window(wpi::StringRef id) : m_id{id}, m_defaultName{id} {} + explicit Window(std::string_view id) : m_id{id}, m_defaultName{id} {} - wpi::StringRef GetId() const { return m_id; } + std::string_view GetId() const { return m_id; } enum Visibility { kHide = 0, kShow, kDisabled }; @@ -43,8 +42,8 @@ class Window { void SetFlags(ImGuiWindowFlags flags) { m_flags = flags; } - void SetName(const wpi::Twine& name) { m_name = name.str(); } - void SetDefaultName(const wpi::Twine& name) { m_defaultName = name.str(); } + void SetName(std::string_view name) { m_name = name; } + void SetDefaultName(std::string_view name) { m_defaultName = name; } /** * Normally windows provide a right-click popup menu on the title bar to diff --git a/glass/src/lib/native/include/glass/WindowManager.h b/glass/src/lib/native/include/glass/WindowManager.h index 384dd918bc..4024e1561f 100644 --- a/glass/src/lib/native/include/glass/WindowManager.h +++ b/glass/src/lib/native/include/glass/WindowManager.h @@ -6,13 +6,12 @@ #include #include +#include #include #include #include #include -#include -#include #include "glass/Window.h" #include "glass/support/IniSaverBase.h" @@ -34,7 +33,7 @@ class WindowManager { * * @param iniName Group name to use in ini file */ - explicit WindowManager(const wpi::Twine& iniName); + explicit WindowManager(std::string_view iniName); virtual ~WindowManager() = default; WindowManager(const WindowManager&) = delete; @@ -67,7 +66,7 @@ class WindowManager { * @param id unique identifier of the window (title bar) * @param display window contents display function */ - Window* AddWindow(wpi::StringRef id, wpi::unique_function display); + Window* AddWindow(std::string_view id, wpi::unique_function display); /** * Adds window to GUI. The view's display function is called from within a @@ -85,7 +84,7 @@ class WindowManager { * @param view view object * @return Window, or nullptr on duplicate window */ - Window* AddWindow(wpi::StringRef id, std::unique_ptr view); + Window* AddWindow(std::string_view id, std::unique_ptr view); /** * Adds window to GUI. A View must be assigned to the returned Window @@ -102,7 +101,7 @@ class WindowManager { * @param id unique identifier of the window (default title bar) * @return Window, or nullptr on duplicate window */ - Window* GetOrAddWindow(wpi::StringRef id, bool duplicateOk = false); + Window* GetOrAddWindow(std::string_view id, bool duplicateOk = false); /** * Gets existing window. If none exists, returns nullptr. @@ -110,7 +109,7 @@ class WindowManager { * @param id unique identifier of the window (default title bar) * @return Window, or nullptr if window does not exist */ - Window* GetWindow(wpi::StringRef id); + Window* GetWindow(std::string_view id); protected: virtual void DisplayWindows(); @@ -121,7 +120,7 @@ class WindowManager { private: class IniSaver : public IniSaverBase { public: - explicit IniSaver(const wpi::Twine& typeName, WindowManager* manager) + explicit IniSaver(std::string_view typeName, WindowManager* manager) : IniSaverBase{typeName}, m_manager{manager} {} void* IniReadOpen(const char* name) override; diff --git a/glass/src/lib/native/include/glass/hardware/AnalogInput.h b/glass/src/lib/native/include/glass/hardware/AnalogInput.h index 3ddbd9c3fa..10f4b40b79 100644 --- a/glass/src/lib/native/include/glass/hardware/AnalogInput.h +++ b/glass/src/lib/native/include/glass/hardware/AnalogInput.h @@ -4,8 +4,9 @@ #pragma once +#include + #include -#include #include "glass/Model.h" @@ -31,6 +32,6 @@ class AnalogInputsModel : public Model { void DisplayAnalogInput(AnalogInputModel* model, int index); void DisplayAnalogInputs(AnalogInputsModel* model, - wpi::StringRef noneMsg = "No analog inputs"); + std::string_view noneMsg = "No analog inputs"); } // namespace glass diff --git a/glass/src/lib/native/include/glass/hardware/DIO.h b/glass/src/lib/native/include/glass/hardware/DIO.h index 830edb10f5..a8236f3487 100644 --- a/glass/src/lib/native/include/glass/hardware/DIO.h +++ b/glass/src/lib/native/include/glass/hardware/DIO.h @@ -4,8 +4,9 @@ #pragma once +#include + #include -#include #include "glass/Model.h" @@ -57,6 +58,6 @@ class DIOsModel : public Model { void DisplayDIO(DIOModel* model, int index, bool outputsEnabled); void DisplayDIOs(DIOsModel* model, bool outputsEnabled, - wpi::StringRef noneMsg = "No Digital I/O"); + std::string_view noneMsg = "No Digital I/O"); } // namespace glass diff --git a/glass/src/lib/native/include/glass/hardware/Encoder.h b/glass/src/lib/native/include/glass/hardware/Encoder.h index 31ac8bfcf6..d553ef10fa 100644 --- a/glass/src/lib/native/include/glass/hardware/Encoder.h +++ b/glass/src/lib/native/include/glass/hardware/Encoder.h @@ -4,8 +4,9 @@ #pragma once +#include + #include -#include #include "glass/Model.h" @@ -15,7 +16,7 @@ class DataSource; class EncoderModel : public Model { public: - virtual void SetName(const wpi::Twine& name); + virtual void SetName(std::string_view name); virtual const char* GetSimDevice() const = 0; @@ -51,6 +52,6 @@ class EncodersModel : public Model { void DisplayEncoder(EncoderModel* model); void DisplayEncoders(EncodersModel* model, - wpi::StringRef noneMsg = "No encoders"); + std::string_view noneMsg = "No encoders"); } // namespace glass diff --git a/glass/src/lib/native/include/glass/hardware/Gyro.h b/glass/src/lib/native/include/glass/hardware/Gyro.h index b60f340acf..d2bb09d2ac 100644 --- a/glass/src/lib/native/include/glass/hardware/Gyro.h +++ b/glass/src/lib/native/include/glass/hardware/Gyro.h @@ -4,9 +4,6 @@ #pragma once -#include -#include - #include "glass/Model.h" namespace glass { diff --git a/glass/src/lib/native/include/glass/hardware/PCM.h b/glass/src/lib/native/include/glass/hardware/PCM.h index a825ada889..af8bde892e 100644 --- a/glass/src/lib/native/include/glass/hardware/PCM.h +++ b/glass/src/lib/native/include/glass/hardware/PCM.h @@ -4,8 +4,9 @@ #pragma once +#include + #include -#include #include "glass/Model.h" @@ -49,7 +50,7 @@ class PCMsModel : public Model { bool DisplayPCMSolenoids(PCMModel* model, int index, bool outputsEnabled); void DisplayPCMsSolenoids(PCMsModel* model, bool outputsEnabled, - wpi::StringRef noneMsg = "No solenoids"); + std::string_view noneMsg = "No solenoids"); void DisplayCompressorDevice(PCMModel* model, int index, bool outputsEnabled); void DisplayCompressorDevice(CompressorModel* model, int index, diff --git a/glass/src/lib/native/include/glass/hardware/PDP.h b/glass/src/lib/native/include/glass/hardware/PDP.h index 8b4f38def4..c0d5c3f487 100644 --- a/glass/src/lib/native/include/glass/hardware/PDP.h +++ b/glass/src/lib/native/include/glass/hardware/PDP.h @@ -4,8 +4,9 @@ #pragma once +#include + #include -#include #include "glass/Model.h" @@ -33,6 +34,6 @@ class PDPsModel : public Model { }; void DisplayPDP(PDPModel* model, int index); -void DisplayPDPs(PDPsModel* model, wpi::StringRef noneMsg = "No PDPs"); +void DisplayPDPs(PDPsModel* model, std::string_view noneMsg = "No PDPs"); } // namespace glass diff --git a/glass/src/lib/native/include/glass/hardware/PWM.h b/glass/src/lib/native/include/glass/hardware/PWM.h index 229e75172c..d8a6a4ed47 100644 --- a/glass/src/lib/native/include/glass/hardware/PWM.h +++ b/glass/src/lib/native/include/glass/hardware/PWM.h @@ -4,8 +4,9 @@ #pragma once +#include + #include -#include #include "glass/Model.h" @@ -31,6 +32,6 @@ class PWMsModel : public Model { void DisplayPWM(PWMModel* model, int index, bool outputsEnabled); void DisplayPWMs(PWMsModel* model, bool outputsEnabled, - wpi::StringRef noneMsg = "No PWM outputs"); + std::string_view noneMsg = "No PWM outputs"); } // namespace glass diff --git a/glass/src/lib/native/include/glass/hardware/Relay.h b/glass/src/lib/native/include/glass/hardware/Relay.h index 55d26a77ae..287c42b71b 100644 --- a/glass/src/lib/native/include/glass/hardware/Relay.h +++ b/glass/src/lib/native/include/glass/hardware/Relay.h @@ -4,8 +4,9 @@ #pragma once +#include + #include -#include #include "glass/Model.h" @@ -30,6 +31,6 @@ class RelaysModel : public Model { void DisplayRelay(RelayModel* model, int index, bool outputsEnabled); void DisplayRelays(RelaysModel* model, bool outputsEnabled, - wpi::StringRef noneMsg = "No relays"); + std::string_view noneMsg = "No relays"); } // namespace glass diff --git a/glass/src/lib/native/include/glass/hardware/SpeedController.h b/glass/src/lib/native/include/glass/hardware/SpeedController.h index 6151b65511..033f27dcd3 100644 --- a/glass/src/lib/native/include/glass/hardware/SpeedController.h +++ b/glass/src/lib/native/include/glass/hardware/SpeedController.h @@ -4,9 +4,6 @@ #pragma once -#include -#include - #include "glass/Model.h" namespace glass { diff --git a/glass/src/lib/native/include/glass/other/CommandScheduler.h b/glass/src/lib/native/include/glass/other/CommandScheduler.h index 94dcd3205f..66b92b2e45 100644 --- a/glass/src/lib/native/include/glass/other/CommandScheduler.h +++ b/glass/src/lib/native/include/glass/other/CommandScheduler.h @@ -7,9 +7,6 @@ #include #include -#include -#include - #include "glass/Model.h" namespace glass { diff --git a/glass/src/lib/native/include/glass/other/CommandSelector.h b/glass/src/lib/native/include/glass/other/CommandSelector.h index 456817786a..e5126f2ad6 100644 --- a/glass/src/lib/native/include/glass/other/CommandSelector.h +++ b/glass/src/lib/native/include/glass/other/CommandSelector.h @@ -4,9 +4,6 @@ #pragma once -#include -#include - #include "glass/Model.h" namespace glass { diff --git a/glass/src/lib/native/include/glass/other/Drive.h b/glass/src/lib/native/include/glass/other/Drive.h index 33f8687362..c9695829f2 100644 --- a/glass/src/lib/native/include/glass/other/Drive.h +++ b/glass/src/lib/native/include/glass/other/Drive.h @@ -6,11 +6,10 @@ #include #include +#include #include #include -#include - #include "glass/Model.h" struct ImVec2; @@ -24,7 +23,7 @@ class DriveModel : public Model { DataSource* percent; std::function setter; - WheelInfo(wpi::StringRef name, DataSource* percent, + WheelInfo(std::string_view name, DataSource* percent, std::function setter) : name(name), percent(percent), setter(std::move(setter)) {} }; diff --git a/glass/src/lib/native/include/glass/other/FMS.h b/glass/src/lib/native/include/glass/other/FMS.h index 2d19c3f4c2..1e0f8efcfc 100644 --- a/glass/src/lib/native/include/glass/other/FMS.h +++ b/glass/src/lib/native/include/glass/other/FMS.h @@ -4,7 +4,7 @@ #pragma once -#include +#include #include "glass/Model.h" @@ -27,7 +27,7 @@ class FMSModel : public Model { virtual DataSource* GetEnabledData() = 0; virtual DataSource* GetTestData() = 0; virtual DataSource* GetAutonomousData() = 0; - virtual wpi::StringRef GetGameSpecificMessage( + virtual std::string_view GetGameSpecificMessage( wpi::SmallVectorImpl& buf) = 0; virtual void SetFmsAttached(bool val) = 0; diff --git a/glass/src/lib/native/include/glass/other/Field2D.h b/glass/src/lib/native/include/glass/other/Field2D.h index 35d188a97d..c9944deff3 100644 --- a/glass/src/lib/native/include/glass/other/Field2D.h +++ b/glass/src/lib/native/include/glass/other/Field2D.h @@ -4,14 +4,14 @@ #pragma once +#include + #include #include #include #include #include #include -#include -#include #include "glass/Model.h" #include "glass/View.h" @@ -31,10 +31,10 @@ class FieldObjectModel : public Model { class Field2DModel : public Model { public: - virtual FieldObjectModel* AddFieldObject(const wpi::Twine& name) = 0; - virtual void RemoveFieldObject(const wpi::Twine& name) = 0; + virtual FieldObjectModel* AddFieldObject(std::string_view name) = 0; + virtual void RemoveFieldObject(std::string_view name) = 0; virtual void ForEachFieldObject( - wpi::function_ref + wpi::function_ref func) = 0; }; diff --git a/glass/src/lib/native/include/glass/other/Log.h b/glass/src/lib/native/include/glass/other/Log.h index ddaadaf918..3d9c59b669 100644 --- a/glass/src/lib/native/include/glass/other/Log.h +++ b/glass/src/lib/native/include/glass/other/Log.h @@ -5,10 +5,9 @@ #pragma once #include +#include #include -#include - #include "glass/View.h" namespace glass { @@ -20,7 +19,7 @@ class LogData { explicit LogData(size_t maxLines = 10000); void Clear(); - void Append(const wpi::Twine& msg); + void Append(std::string_view msg); const std::string& GetBuffer(); private: diff --git a/glass/src/lib/native/include/glass/other/Plot.h b/glass/src/lib/native/include/glass/other/Plot.h index 2ffc3da9c0..f7b196dcc2 100644 --- a/glass/src/lib/native/include/glass/other/Plot.h +++ b/glass/src/lib/native/include/glass/other/Plot.h @@ -4,6 +4,8 @@ #pragma once +#include + #include "glass/WindowManager.h" #include "glass/support/IniSaverBase.h" @@ -11,7 +13,7 @@ namespace glass { class PlotProvider : private WindowManager { public: - explicit PlotProvider(const wpi::Twine& iniName); + explicit PlotProvider(std::string_view iniName); ~PlotProvider() override; void GlobalInit() override; @@ -35,7 +37,7 @@ class PlotProvider : private WindowManager { class IniSaver : public IniSaverBase { public: - explicit IniSaver(const wpi::Twine& typeName, PlotProvider* provider, + explicit IniSaver(std::string_view typeName, PlotProvider* provider, bool forSeries); void* IniReadOpen(const char* name) override; diff --git a/glass/src/lib/native/include/glass/other/StringChooser.h b/glass/src/lib/native/include/glass/other/StringChooser.h index 6f0aa26dea..692eb7ca43 100644 --- a/glass/src/lib/native/include/glass/other/StringChooser.h +++ b/glass/src/lib/native/include/glass/other/StringChooser.h @@ -5,10 +5,10 @@ #pragma once #include +#include #include #include -#include #include "glass/Model.h" @@ -21,9 +21,9 @@ class StringChooserModel : public Model { virtual const std::string& GetActive() = 0; virtual const std::vector& GetOptions() = 0; - virtual void SetDefault(wpi::StringRef val) = 0; - virtual void SetSelected(wpi::StringRef val) = 0; - virtual void SetActive(wpi::StringRef val) = 0; + virtual void SetDefault(std::string_view val) = 0; + virtual void SetSelected(std::string_view val) = 0; + virtual void SetActive(std::string_view val) = 0; virtual void SetOptions(wpi::ArrayRef val) = 0; }; diff --git a/glass/src/lib/native/include/glass/other/Subsystem.h b/glass/src/lib/native/include/glass/other/Subsystem.h index 89f06178cb..db79db583b 100644 --- a/glass/src/lib/native/include/glass/other/Subsystem.h +++ b/glass/src/lib/native/include/glass/other/Subsystem.h @@ -4,9 +4,6 @@ #pragma once -#include -#include - #include "glass/Model.h" namespace glass { diff --git a/glass/src/lib/native/include/glass/support/IniSaver.h b/glass/src/lib/native/include/glass/support/IniSaver.h index 1312c0d517..a3aa3d0997 100644 --- a/glass/src/lib/native/include/glass/support/IniSaver.h +++ b/glass/src/lib/native/include/glass/support/IniSaver.h @@ -4,9 +4,10 @@ #pragma once +#include + #include #include -#include #include "glass/support/IniSaverBase.h" @@ -15,7 +16,7 @@ namespace glass { template class IniSaver : public IniSaverBase { public: - explicit IniSaver(const wpi::Twine& typeName, + explicit IniSaver(std::string_view typeName, IniSaverBackend* backend = nullptr) : IniSaverBase(typeName, backend) {} diff --git a/glass/src/lib/native/include/glass/support/IniSaver.inc b/glass/src/lib/native/include/glass/support/IniSaver.inc index 48f43973af..42efb85ba2 100644 --- a/glass/src/lib/native/include/glass/support/IniSaver.inc +++ b/glass/src/lib/native/include/glass/support/IniSaver.inc @@ -4,7 +4,9 @@ #pragma once -#include +#include + +#include #include "glass/support/IniSaver.h" @@ -12,21 +14,18 @@ namespace glass { template void* IniSaver::IniReadOpen(const char* name) { - int num; - if (wpi::StringRef{name}.getAsInteger(10, num)) { + if (auto num = wpi::parse_integer(name, 10)) { + return &m_map[num.value()]; + } else { return nullptr; } - return &m_map[num]; } template -void IniSaver::IniReadLine(void* entry, const char* lineStr) { +void IniSaver::IniReadLine(void* entry, const char* line) { auto element = static_cast(entry); - wpi::StringRef line{lineStr}; - auto [name, value] = line.split('='); - name = name.trim(); - value = value.trim(); - element->ReadIni(name, value); + auto [name, value] = wpi::split(line, '='); + element->ReadIni(wpi::trim(name), wpi::trim(value)); } template diff --git a/glass/src/lib/native/include/glass/support/IniSaverBase.h b/glass/src/lib/native/include/glass/support/IniSaverBase.h index e713ffc288..85ae1e3973 100644 --- a/glass/src/lib/native/include/glass/support/IniSaverBase.h +++ b/glass/src/lib/native/include/glass/support/IniSaverBase.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include namespace glass { @@ -22,7 +22,7 @@ class IniSaverBackend { class IniSaverBase { public: - explicit IniSaverBase(const wpi::Twine& typeName, + explicit IniSaverBase(std::string_view typeName, IniSaverBackend* backend = nullptr); virtual ~IniSaverBase(); diff --git a/glass/src/lib/native/include/glass/support/IniSaverInfo.h b/glass/src/lib/native/include/glass/support/IniSaverInfo.h index 957655ec75..2014e9d28b 100644 --- a/glass/src/lib/native/include/glass/support/IniSaverInfo.h +++ b/glass/src/lib/native/include/glass/support/IniSaverInfo.h @@ -4,9 +4,9 @@ #pragma once +#include + #include -#include -#include namespace glass { @@ -15,7 +15,7 @@ class NameInfo { NameInfo() { m_name[0] = '\0'; } bool HasName() const { return m_name[0] != '\0'; } - void SetName(const wpi::Twine& name); + void SetName(std::string_view name); const char* GetName() const { return m_name; } void GetName(char* buf, size_t size, const char* defaultName) const; void GetName(char* buf, size_t size, const char* defaultName, @@ -28,7 +28,7 @@ class NameInfo { void GetLabel(char* buf, size_t size, const char* defaultName, int index, int index2) const; - bool ReadIni(wpi::StringRef name, wpi::StringRef value); + bool ReadIni(std::string_view name, std::string_view value); void WriteIni(ImGuiTextBuffer* out); void PushEditNameId(int index); void PushEditNameId(const char* name); @@ -47,7 +47,7 @@ class OpenInfo { bool IsOpen() const { return m_open; } void SetOpen(bool open) { m_open = open; } - bool ReadIni(wpi::StringRef name, wpi::StringRef value); + bool ReadIni(std::string_view name, std::string_view value); void WriteIni(ImGuiTextBuffer* out); private: @@ -56,7 +56,7 @@ class OpenInfo { class NameOpenInfo : public NameInfo, public OpenInfo { public: - bool ReadIni(wpi::StringRef name, wpi::StringRef value); + bool ReadIni(std::string_view name, std::string_view value); void WriteIni(ImGuiTextBuffer* out); }; diff --git a/glass/src/lib/native/include/glass/support/IniSaverString.h b/glass/src/lib/native/include/glass/support/IniSaverString.h index 9ac3d70d55..4134219433 100644 --- a/glass/src/lib/native/include/glass/support/IniSaverString.h +++ b/glass/src/lib/native/include/glass/support/IniSaverString.h @@ -4,12 +4,11 @@ #pragma once +#include #include #include #include -#include -#include #include "glass/support/IniSaverBase.h" @@ -18,28 +17,28 @@ namespace glass { template class IniSaverString : public IniSaverBase { public: - explicit IniSaverString(const wpi::Twine& typeName, + explicit IniSaverString(std::string_view typeName, IniSaverBackend* backend = nullptr) : IniSaverBase(typeName, backend) {} // pass through useful functions to map - Info& operator[](wpi::StringRef key) { return m_map[key]; } + Info& operator[](std::string_view key) { return m_map[key]; } template - auto try_emplace(wpi::StringRef key, ArgsTy&&... args) { + auto try_emplace(std::string_view key, ArgsTy&&... args) { return m_map.try_emplace(key, std::forward(args)...); } void erase(typename wpi::StringMap::iterator it) { m_map.erase(it); } - auto erase(wpi::StringRef key) { return m_map.erase(key); } + auto erase(std::string_view key) { return m_map.erase(key); } auto begin() { return m_map.begin(); } auto end() { return m_map.end(); } - auto find(wpi::StringRef key) { return m_map.find(key); } + auto find(std::string_view key) { return m_map.find(key); } auto begin() const { return m_map.begin(); } auto end() const { return m_map.end(); } - auto find(wpi::StringRef key) const { return m_map.find(key); } + auto find(std::string_view key) const { return m_map.find(key); } bool empty() const { return m_map.empty(); } diff --git a/glass/src/lib/native/include/glass/support/IniSaverString.inc b/glass/src/lib/native/include/glass/support/IniSaverString.inc index 6ca76dde8e..0d18d29011 100644 --- a/glass/src/lib/native/include/glass/support/IniSaverString.inc +++ b/glass/src/lib/native/include/glass/support/IniSaverString.inc @@ -4,7 +4,9 @@ #pragma once -#include +#include + +#include #include "glass/support/IniSaverString.h" @@ -16,13 +18,10 @@ void* IniSaverString::IniReadOpen(const char* name) { } template -void IniSaverString::IniReadLine(void* entry, const char* lineStr) { +void IniSaverString::IniReadLine(void* entry, const char* line) { auto element = static_cast(entry); - wpi::StringRef line{lineStr}; - auto [name, value] = line.split('='); - name = name.trim(); - value = value.trim(); - element->ReadIni(name, value); + auto [name, value] = wpi::split(line, '='); + element->ReadIni(wpi::trim(name), wpi::trim(value)); } template diff --git a/glass/src/lib/native/include/glass/support/IniSaverVector.h b/glass/src/lib/native/include/glass/support/IniSaverVector.h index 86b2bbc1ff..e2e57cec39 100644 --- a/glass/src/lib/native/include/glass/support/IniSaverVector.h +++ b/glass/src/lib/native/include/glass/support/IniSaverVector.h @@ -4,10 +4,10 @@ #pragma once +#include #include #include -#include #include "glass/support/IniSaverBase.h" @@ -16,7 +16,7 @@ namespace glass { template class IniSaverVector : public std::vector, public IniSaverBase { public: - explicit IniSaverVector(const wpi::Twine& typeName, + explicit IniSaverVector(std::string_view typeName, IniSaverBackend* backend = nullptr) : IniSaverBase(typeName, backend) {} diff --git a/glass/src/lib/native/include/glass/support/IniSaverVector.inc b/glass/src/lib/native/include/glass/support/IniSaverVector.inc index 0b48ab5781..a86b1161d2 100644 --- a/glass/src/lib/native/include/glass/support/IniSaverVector.inc +++ b/glass/src/lib/native/include/glass/support/IniSaverVector.inc @@ -4,7 +4,9 @@ #pragma once -#include +#include + +#include #include "glass/support/IniSaverVector.h" @@ -12,24 +14,21 @@ namespace glass { template void* IniSaverVector::IniReadOpen(const char* name) { - unsigned int num; - if (wpi::StringRef{name}.getAsInteger(10, num)) { + if (auto num = wpi::parse_integer(name, 10)) { + if (num.value() >= this->size()) { + this->resize(num.value() + 1); + } + return &(*this)[num.value()]; + } else { return nullptr; } - if (num >= this->size()) { - this->resize(num + 1); - } - return &(*this)[num]; } template -void IniSaverVector::IniReadLine(void* entry, const char* lineStr) { +void IniSaverVector::IniReadLine(void* entry, const char* line) { auto element = static_cast(entry); - wpi::StringRef line{lineStr}; - auto [name, value] = line.split('='); - name = name.trim(); - value = value.trim(); - element->ReadIni(name, value); + auto [name, value] = wpi::split(line, '='); + element->ReadIni(wpi::trim(name), wpi::trim(value)); } template diff --git a/glass/src/libnt/native/cpp/NTCommandScheduler.cpp b/glass/src/libnt/native/cpp/NTCommandScheduler.cpp index 857e0df16d..4d4e39394e 100644 --- a/glass/src/libnt/native/cpp/NTCommandScheduler.cpp +++ b/glass/src/libnt/native/cpp/NTCommandScheduler.cpp @@ -4,21 +4,22 @@ #include "glass/networktables/NTCommandScheduler.h" -#include +#include +#include using namespace glass; -NTCommandSchedulerModel::NTCommandSchedulerModel(wpi::StringRef path) +NTCommandSchedulerModel::NTCommandSchedulerModel(std::string_view path) : NTCommandSchedulerModel(nt::GetDefaultInstance(), path) {} NTCommandSchedulerModel::NTCommandSchedulerModel(NT_Inst instance, - wpi::StringRef path) + std::string_view path) : m_nt(instance), - m_name(m_nt.GetEntry(path + "/.name")), - m_commands(m_nt.GetEntry(path + "/Names")), - m_ids(m_nt.GetEntry(path + "/Ids")), - m_cancel(m_nt.GetEntry(path + "/Cancel")), - m_nameValue(path.rsplit('/').second) { + m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), + m_commands(m_nt.GetEntry(fmt::format("{}/Names", path))), + m_ids(m_nt.GetEntry(fmt::format("{}/Ids", path))), + m_cancel(m_nt.GetEntry(fmt::format("{}/Cancel", path))), + m_nameValue(wpi::rsplit(path, '/').second) { m_nt.AddListener(m_name); m_nt.AddListener(m_commands); m_nt.AddListener(m_ids); diff --git a/glass/src/libnt/native/cpp/NTCommandSelector.cpp b/glass/src/libnt/native/cpp/NTCommandSelector.cpp index bf9a399a35..efcbac2046 100644 --- a/glass/src/libnt/native/cpp/NTCommandSelector.cpp +++ b/glass/src/libnt/native/cpp/NTCommandSelector.cpp @@ -4,18 +4,21 @@ #include "glass/networktables/NTCommandSelector.h" +#include +#include + using namespace glass; -NTCommandSelectorModel::NTCommandSelectorModel(wpi::StringRef path) +NTCommandSelectorModel::NTCommandSelectorModel(std::string_view path) : NTCommandSelectorModel(nt::GetDefaultInstance(), path) {} NTCommandSelectorModel::NTCommandSelectorModel(NT_Inst instance, - wpi::StringRef path) + std::string_view path) : m_nt(instance), - m_running(m_nt.GetEntry(path + "/running")), - m_name(m_nt.GetEntry(path + "/.name")), - m_runningData("NTCmd:" + path), - m_nameValue(path.rsplit('/').second) { + m_running(m_nt.GetEntry(fmt::format("{}/running", path))), + m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), + m_runningData(fmt::format("NTCmd:{}", path)), + m_nameValue(wpi::rsplit(path, '/').second) { m_runningData.SetDigital(true); m_nt.AddListener(m_running); m_nt.AddListener(m_name); diff --git a/glass/src/libnt/native/cpp/NTDifferentialDrive.cpp b/glass/src/libnt/native/cpp/NTDifferentialDrive.cpp index 39fe335064..b44ea07d7d 100644 --- a/glass/src/libnt/native/cpp/NTDifferentialDrive.cpp +++ b/glass/src/libnt/native/cpp/NTDifferentialDrive.cpp @@ -4,24 +4,26 @@ #include "glass/networktables/NTDifferentialDrive.h" +#include #include #include +#include using namespace glass; -NTDifferentialDriveModel::NTDifferentialDriveModel(wpi::StringRef path) +NTDifferentialDriveModel::NTDifferentialDriveModel(std::string_view path) : NTDifferentialDriveModel(nt::GetDefaultInstance(), path) {} NTDifferentialDriveModel::NTDifferentialDriveModel(NT_Inst instance, - wpi::StringRef path) + std::string_view path) : m_nt(instance), - m_name(m_nt.GetEntry(path + "/.name")), - m_controllable(m_nt.GetEntry(path + "/.controllable")), - m_lPercent(m_nt.GetEntry(path + "/Left Motor Speed")), - m_rPercent(m_nt.GetEntry(path + "/Right Motor Speed")), - m_nameValue(path.rsplit('/').second), - m_lPercentData("NTDiffDriveL:" + path), - m_rPercentData("NTDiffDriveR:" + path) { + m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), + m_controllable(m_nt.GetEntry(fmt::format("{}/.controllable", path))), + m_lPercent(m_nt.GetEntry(fmt::format("{}/Left Motor Speed", path))), + m_rPercent(m_nt.GetEntry(fmt::format("{}/Right Motor Speed", path))), + m_nameValue(wpi::rsplit(path, '/').second), + m_lPercentData(fmt::format("NTDiffDriveL:{}", path)), + m_rPercentData(fmt::format("NTDiffDriveR:{}", path)) { m_nt.AddListener(m_name); m_nt.AddListener(m_controllable); m_nt.AddListener(m_lPercent); diff --git a/glass/src/libnt/native/cpp/NTDigitalInput.cpp b/glass/src/libnt/native/cpp/NTDigitalInput.cpp index a823dbbd25..5de6c2954e 100644 --- a/glass/src/libnt/native/cpp/NTDigitalInput.cpp +++ b/glass/src/libnt/native/cpp/NTDigitalInput.cpp @@ -4,19 +4,20 @@ #include "glass/networktables/NTDigitalInput.h" -#include +#include +#include using namespace glass; -NTDigitalInputModel::NTDigitalInputModel(wpi::StringRef path) +NTDigitalInputModel::NTDigitalInputModel(std::string_view path) : NTDigitalInputModel{nt::GetDefaultInstance(), path} {} -NTDigitalInputModel::NTDigitalInputModel(NT_Inst inst, wpi::StringRef path) +NTDigitalInputModel::NTDigitalInputModel(NT_Inst inst, std::string_view path) : m_nt{inst}, - m_value{m_nt.GetEntry(path + "/Value")}, - m_name{m_nt.GetEntry(path + "/.name")}, - m_valueData{"NT_DIn:" + path}, - m_nameValue{path.rsplit('/').second} { + m_value{m_nt.GetEntry(fmt::format("{}/Value", path))}, + m_name{m_nt.GetEntry(fmt::format("{}/.name", path))}, + m_valueData{fmt::format("NT_DIn:{}", path)}, + m_nameValue{wpi::rsplit(path, '/').second} { m_nt.AddListener(m_value); m_nt.AddListener(m_name); diff --git a/glass/src/libnt/native/cpp/NTDigitalOutput.cpp b/glass/src/libnt/native/cpp/NTDigitalOutput.cpp index ca260b548d..a09d424446 100644 --- a/glass/src/libnt/native/cpp/NTDigitalOutput.cpp +++ b/glass/src/libnt/native/cpp/NTDigitalOutput.cpp @@ -4,19 +4,19 @@ #include "glass/networktables/NTDigitalOutput.h" -#include +#include using namespace glass; -NTDigitalOutputModel::NTDigitalOutputModel(wpi::StringRef path) +NTDigitalOutputModel::NTDigitalOutputModel(std::string_view path) : NTDigitalOutputModel{nt::GetDefaultInstance(), path} {} -NTDigitalOutputModel::NTDigitalOutputModel(NT_Inst inst, wpi::StringRef path) +NTDigitalOutputModel::NTDigitalOutputModel(NT_Inst inst, std::string_view path) : m_nt{inst}, - m_value{m_nt.GetEntry(path + "/Value")}, - m_name{m_nt.GetEntry(path + "/.name")}, - m_controllable{m_nt.GetEntry(path + "/.controllable")}, - m_valueData{"NT_DOut:" + path} { + m_value{m_nt.GetEntry(fmt::format("{}/Value", path))}, + m_name{m_nt.GetEntry(fmt::format("{}/.name", path))}, + m_controllable{m_nt.GetEntry(fmt::format("{}/.controllable", path))}, + m_valueData{fmt::format("NT_DOut:{}", path)} { m_nt.AddListener(m_value); m_nt.AddListener(m_name); m_nt.AddListener(m_controllable); diff --git a/glass/src/libnt/native/cpp/NTFMS.cpp b/glass/src/libnt/native/cpp/NTFMS.cpp index f1dc2eede9..1f54803fc7 100644 --- a/glass/src/libnt/native/cpp/NTFMS.cpp +++ b/glass/src/libnt/native/cpp/NTFMS.cpp @@ -6,27 +6,28 @@ #include -#include +#include #include using namespace glass; -NTFMSModel::NTFMSModel(wpi::StringRef path) +NTFMSModel::NTFMSModel(std::string_view path) : NTFMSModel{nt::GetDefaultInstance(), path} {} -NTFMSModel::NTFMSModel(NT_Inst inst, wpi::StringRef path) +NTFMSModel::NTFMSModel(NT_Inst inst, std::string_view path) : m_nt{inst}, - m_gameSpecificMessage{m_nt.GetEntry(path + "/GameSpecificMessage")}, - m_alliance{m_nt.GetEntry(path + "/IsRedAlliance")}, - m_station{m_nt.GetEntry(path + "/StationNumber")}, - m_controlWord{m_nt.GetEntry(path + "/FMSControlData")}, - m_fmsAttached{"NT_FMS:FMSAttached:" + path}, - m_dsAttached{"NT_FMS:DSAttached:" + path}, - m_allianceStationId{"NT_FMS:AllianceStationID:" + path}, - m_estop{"NT_FMS:EStop:" + path}, - m_enabled{"NT_FMS:RobotEnabled:" + path}, - m_test{"NT_FMS:TestMode:" + path}, - m_autonomous{"NT_FMS:AutonomousMode:" + path} { + m_gameSpecificMessage{ + m_nt.GetEntry(fmt::format("{}/GameSpecificMessage", path))}, + m_alliance{m_nt.GetEntry(fmt::format("{}/IsRedAlliance", path))}, + m_station{m_nt.GetEntry(fmt::format("{}/StationNumber", path))}, + m_controlWord{m_nt.GetEntry(fmt::format("{}/FMSControlData", path))}, + m_fmsAttached{fmt::format("NT_FMS:FMSAttached:{}", path)}, + m_dsAttached{fmt::format("NT_FMS:DSAttached:{}", path)}, + m_allianceStationId{fmt::format("NT_FMS:AllianceStationID:{}", path)}, + m_estop{fmt::format("NT_FMS:EStop:{}", path)}, + m_enabled{fmt::format("NT_FMS:RobotEnabled:{}", path)}, + m_test{fmt::format("NT_FMS:TestMode:{}", path)}, + m_autonomous{fmt::format("NT_FMS:AutonomousMode:{}", path)} { m_nt.AddListener(m_alliance); m_nt.AddListener(m_station); m_nt.AddListener(m_controlWord); @@ -39,7 +40,7 @@ NTFMSModel::NTFMSModel(NT_Inst inst, wpi::StringRef path) m_autonomous.SetDigital(true); } -wpi::StringRef NTFMSModel::GetGameSpecificMessage( +std::string_view NTFMSModel::GetGameSpecificMessage( wpi::SmallVectorImpl& buf) { buf.clear(); auto value = nt::GetEntryValue(m_gameSpecificMessage); @@ -47,7 +48,7 @@ wpi::StringRef NTFMSModel::GetGameSpecificMessage( auto str = value->GetString(); buf.append(str.begin(), str.end()); } - return wpi::StringRef{buf.data(), buf.size()}; + return std::string_view{buf.data(), buf.size()}; } void NTFMSModel::Update() { diff --git a/glass/src/libnt/native/cpp/NTField2D.cpp b/glass/src/libnt/native/cpp/NTField2D.cpp index 89f6a639e5..5c0c9542f5 100644 --- a/glass/src/libnt/native/cpp/NTField2D.cpp +++ b/glass/src/libnt/native/cpp/NTField2D.cpp @@ -7,17 +7,18 @@ #include #include +#include #include #include #include -#include #include +#include using namespace glass; class NTField2DModel::ObjectModel : public FieldObjectModel { public: - ObjectModel(wpi::StringRef name, NT_Entry entry) + ObjectModel(std::string_view name, NT_Entry entry) : m_name{name}, m_entry{entry} {} const char* GetName() const override { return m_name.c_str(); } @@ -63,7 +64,7 @@ void NTField2DModel::ObjectModel::NTUpdate(const nt::Value& value) { } } else if (value.IsRaw()) { // treat it simply as an array of doubles - wpi::StringRef data = value.GetRaw(); + std::string_view data = value.GetRaw(); // must be triples of doubles auto size = data.size(); @@ -71,7 +72,7 @@ void NTField2DModel::ObjectModel::NTUpdate(const nt::Value& value) { return; } m_poses.resize(size / (3 * 8)); - const char* p = data.begin(); + const char* p = data.data(); for (size_t i = 0; i < size / (3 * 8); ++i) { double x = wpi::BitsToDouble( wpi::support::endian::readNext())); p += 8; } - nt::SetEntryTypeValue( - m_entry, nt::Value::MakeRaw(wpi::StringRef{arr.data(), arr.size()})); + nt::SetEntryTypeValue(m_entry, + nt::Value::MakeRaw({arr.data(), arr.size()})); } } @@ -147,13 +148,13 @@ void NTField2DModel::ObjectModel::SetRotation(size_t i, frc::Rotation2d rot) { } } -NTField2DModel::NTField2DModel(wpi::StringRef path) +NTField2DModel::NTField2DModel(std::string_view path) : NTField2DModel{nt::GetDefaultInstance(), path} {} -NTField2DModel::NTField2DModel(NT_Inst inst, wpi::StringRef path) +NTField2DModel::NTField2DModel(NT_Inst inst, std::string_view path) : m_nt{inst}, - m_path{(path + "/").str()}, - m_name{m_nt.GetEntry(path + "/.name")} { + m_path{fmt::format("{}/", path)}, + m_name{m_nt.GetEntry(fmt::format("{}/.name", path))} { m_nt.AddListener(m_path, NT_NOTIFY_LOCAL | NT_NOTIFY_NEW | NT_NOTIFY_DELETE | NT_NOTIFY_UPDATE | NT_NOTIFY_IMMEDIATE); } @@ -182,8 +183,9 @@ void NTField2DModel::Update() { } // handle create/delete - if (wpi::StringRef{event.name}.startswith(m_path)) { - auto name = wpi::StringRef{event.name}.drop_front(m_path.size()); + std::string_view name = event.name; + if (wpi::starts_with(name, m_path)) { + name.remove_prefix(m_path.size()); if (name.empty() || name[0] == '.') { continue; } @@ -216,9 +218,8 @@ bool NTField2DModel::IsReadOnly() { return false; } -FieldObjectModel* NTField2DModel::AddFieldObject(const wpi::Twine& name) { - wpi::SmallString<128> fullNameBuf; - wpi::StringRef fullName = (m_path + name).toStringRef(fullNameBuf); +FieldObjectModel* NTField2DModel::AddFieldObject(std::string_view name) { + auto fullName = fmt::format("{}{}", m_path, name); auto [it, match] = Find(fullName); if (!match) { it = m_objects.emplace( @@ -227,9 +228,8 @@ FieldObjectModel* NTField2DModel::AddFieldObject(const wpi::Twine& name) { return it->get(); } -void NTField2DModel::RemoveFieldObject(const wpi::Twine& name) { - wpi::SmallString<128> fullNameBuf; - auto [it, match] = Find((m_path + name).toStringRef(fullNameBuf)); +void NTField2DModel::RemoveFieldObject(std::string_view name) { + auto [it, match] = Find(fmt::format("{}{}", m_path, name)); if (match) { nt::DeleteEntry((*it)->GetEntry()); m_objects.erase(it); @@ -237,19 +237,19 @@ void NTField2DModel::RemoveFieldObject(const wpi::Twine& name) { } void NTField2DModel::ForEachFieldObject( - wpi::function_ref + wpi::function_ref func) { for (auto&& obj : m_objects) { if (obj->Exists()) { - func(*obj, wpi::StringRef{obj->GetName()}.drop_front(m_path.size())); + func(*obj, wpi::drop_front(obj->GetName(), m_path.size())); } } } std::pair NTField2DModel::Find( - wpi::StringRef fullName) { + std::string_view fullName) { auto it = std::lower_bound( m_objects.begin(), m_objects.end(), fullName, - [](const auto& e, wpi::StringRef name) { return e->GetName() < name; }); + [](const auto& e, std::string_view name) { return e->GetName() < name; }); return {it, it != m_objects.end() && (*it)->GetName() == fullName}; } diff --git a/glass/src/libnt/native/cpp/NTGyro.cpp b/glass/src/libnt/native/cpp/NTGyro.cpp index e0af6a0480..7651d2c1ff 100644 --- a/glass/src/libnt/native/cpp/NTGyro.cpp +++ b/glass/src/libnt/native/cpp/NTGyro.cpp @@ -4,17 +4,20 @@ #include "glass/networktables/NTGyro.h" +#include +#include + using namespace glass; -NTGyroModel::NTGyroModel(wpi::StringRef path) +NTGyroModel::NTGyroModel(std::string_view path) : NTGyroModel(nt::GetDefaultInstance(), path) {} -NTGyroModel::NTGyroModel(NT_Inst instance, wpi::StringRef path) +NTGyroModel::NTGyroModel(NT_Inst instance, std::string_view path) : m_nt(instance), - m_angle(m_nt.GetEntry(path + "/Value")), - m_name(m_nt.GetEntry(path + "/.name")), - m_angleData("NT_Gyro:" + path), - m_nameValue(path.rsplit('/').second) { + m_angle(m_nt.GetEntry(fmt::format("{}/Value", path))), + m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), + m_angleData(fmt::format("NT_Gyro:{}", path)), + m_nameValue(wpi::rsplit(path, '/').second) { m_nt.AddListener(m_angle); m_nt.AddListener(m_name); } diff --git a/glass/src/libnt/native/cpp/NTMecanumDrive.cpp b/glass/src/libnt/native/cpp/NTMecanumDrive.cpp index a071e5d517..28c0a6745c 100644 --- a/glass/src/libnt/native/cpp/NTMecanumDrive.cpp +++ b/glass/src/libnt/native/cpp/NTMecanumDrive.cpp @@ -4,27 +4,33 @@ #include "glass/networktables/NTMecanumDrive.h" +#include #include #include +#include using namespace glass; -NTMecanumDriveModel::NTMecanumDriveModel(wpi::StringRef path) +NTMecanumDriveModel::NTMecanumDriveModel(std::string_view path) : NTMecanumDriveModel(nt::GetDefaultInstance(), path) {} -NTMecanumDriveModel::NTMecanumDriveModel(NT_Inst instance, wpi::StringRef path) +NTMecanumDriveModel::NTMecanumDriveModel(NT_Inst instance, + std::string_view path) : m_nt(instance), - m_name(m_nt.GetEntry(path + "/.name")), - m_controllable(m_nt.GetEntry(path + "/.controllable")), - m_flPercent(m_nt.GetEntry(path + "/Front Left Motor Speed")), - m_frPercent(m_nt.GetEntry(path + "/Front Right Motor Speed")), - m_rlPercent(m_nt.GetEntry(path + "/Rear Left Motor Speed")), - m_rrPercent(m_nt.GetEntry(path + "/Rear Right Motor Speed")), - m_nameValue(path.rsplit('/').second), - m_flPercentData("NTMcnmDriveFL:" + path), - m_frPercentData("NTMcnmDriveFR:" + path), - m_rlPercentData("NTMcnmDriveRL:" + path), - m_rrPercentData("NTMcnmDriveRR:" + path) { + m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), + m_controllable(m_nt.GetEntry(fmt::format("{}/.controllable", path))), + m_flPercent( + m_nt.GetEntry(fmt::format("{}/Front Left Motor Speed", path))), + m_frPercent( + m_nt.GetEntry(fmt::format("{}/Front Right Motor Speed", path))), + m_rlPercent(m_nt.GetEntry(fmt::format("{}/Rear Left Motor Speed", path))), + m_rrPercent( + m_nt.GetEntry(fmt::format("{}/Rear Right Motor Speed", path))), + m_nameValue(wpi::rsplit(path, '/').second), + m_flPercentData(fmt::format("NTMcnmDriveFL:{}", path)), + m_frPercentData(fmt::format("NTMcnmDriveFR:{}", path)), + m_rlPercentData(fmt::format("NTMcnmDriveRL:{}", path)), + m_rrPercentData(fmt::format("NTMcnmDriveRR:{}", path)) { m_nt.AddListener(m_name); m_nt.AddListener(m_controllable); m_nt.AddListener(m_flPercent); diff --git a/glass/src/libnt/native/cpp/NTMechanism2D.cpp b/glass/src/libnt/native/cpp/NTMechanism2D.cpp index 99a17e3ef3..9c73af2532 100644 --- a/glass/src/libnt/native/cpp/NTMechanism2D.cpp +++ b/glass/src/libnt/native/cpp/NTMechanism2D.cpp @@ -5,25 +5,27 @@ #include "glass/networktables/NTMechanism2D.h" #include +#include #include +#include #include #include +#include #include "glass/other/Mechanism2D.h" using namespace glass; // Convert "#RRGGBB" hex color to ImU32 color -static void ConvertColor(wpi::StringRef in, ImU32* out) { +static void ConvertColor(std::string_view in, ImU32* out) { if (in.size() != 7 || in[0] != '#') { return; } - ImU32 val = 0; - if (in.drop_front().getAsInteger(16, val)) { - return; + if (auto v = wpi::parse_integer(wpi::drop_front(in), 16)) { + ImU32 val = v.value(); + *out = IM_COL32((val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff, 255); } - *out = IM_COL32((val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff, 255); } namespace { @@ -32,13 +34,13 @@ class NTMechanismObjectModel; class NTMechanismGroupImpl final { public: - NTMechanismGroupImpl(NT_Inst inst, const wpi::Twine& path, - wpi::StringRef name) - : m_inst{inst}, m_path{path.str()}, m_name{name} {} + NTMechanismGroupImpl(NT_Inst inst, std::string_view path, + std::string_view name) + : m_inst{inst}, m_path{path}, m_name{name} {} const char* GetName() const { return m_name.c_str(); } void ForEachObject(wpi::function_ref func); - void NTUpdate(const nt::EntryNotification& event, wpi::StringRef name); + void NTUpdate(const nt::EntryNotification& event, std::string_view name); protected: NT_Inst m_inst; @@ -49,14 +51,14 @@ class NTMechanismGroupImpl final { class NTMechanismObjectModel final : public MechanismObjectModel { public: - NTMechanismObjectModel(NT_Inst inst, const wpi::Twine& path, - wpi::StringRef name) + NTMechanismObjectModel(NT_Inst inst, std::string_view path, + std::string_view name) : m_group{inst, path, name}, - m_type{nt::GetEntry(inst, path + "/.type")}, - m_color{nt::GetEntry(inst, path + "/color")}, - m_weight{nt::GetEntry(inst, path + "/weight")}, - m_angle{nt::GetEntry(inst, path + "/angle")}, - m_length{nt::GetEntry(inst, path + "/length")} {} + m_type{nt::GetEntry(inst, fmt::format("{}/.type", path))}, + m_color{nt::GetEntry(inst, fmt::format("{}/color", path))}, + m_weight{nt::GetEntry(inst, fmt::format("{}/weight", path))}, + m_angle{nt::GetEntry(inst, fmt::format("{}/angle", path))}, + m_length{nt::GetEntry(inst, fmt::format("{}/length", path))} {} const char* GetName() const final { return m_group.GetName(); } void ForEachObject( @@ -70,7 +72,7 @@ class NTMechanismObjectModel final : public MechanismObjectModel { frc::Rotation2d GetAngle() const final { return m_angleValue; } units::meter_t GetLength() const final { return m_lengthValue; } - bool NTUpdate(const nt::EntryNotification& event, wpi::StringRef childName); + bool NTUpdate(const nt::EntryNotification& event, std::string_view childName); private: NTMechanismGroupImpl m_group; @@ -98,25 +100,26 @@ void NTMechanismGroupImpl::ForEachObject( } void NTMechanismGroupImpl::NTUpdate(const nt::EntryNotification& event, - wpi::StringRef name) { + std::string_view name) { if (name.empty()) { return; } - wpi::StringRef childName; - std::tie(name, childName) = name.split('/'); + std::string_view childName; + std::tie(name, childName) = wpi::split(name, '/'); if (childName.empty()) { return; } auto it = std::lower_bound( m_objects.begin(), m_objects.end(), name, - [](const auto& e, wpi::StringRef name) { return e->GetName() < name; }); + [](const auto& e, std::string_view name) { return e->GetName() < name; }); bool match = it != m_objects.end() && (*it)->GetName() == name; if (event.flags & NT_NOTIFY_NEW) { if (!match) { - it = m_objects.emplace(it, std::make_unique( - m_inst, m_path + "/" + name, name)); + it = m_objects.emplace( + it, std::make_unique( + m_inst, fmt::format("{}/{}", m_path, name), name)); match = true; } } @@ -128,7 +131,7 @@ void NTMechanismGroupImpl::NTUpdate(const nt::EntryNotification& event, } bool NTMechanismObjectModel::NTUpdate(const nt::EntryNotification& event, - wpi::StringRef childName) { + std::string_view childName) { if (event.entry == m_type) { if ((event.flags & NT_NOTIFY_DELETE) != 0) { return true; @@ -160,10 +163,10 @@ bool NTMechanismObjectModel::NTUpdate(const nt::EntryNotification& event, class NTMechanism2DModel::RootModel final : public MechanismRootModel { public: - RootModel(NT_Inst inst, const wpi::Twine& path, wpi::StringRef name) + RootModel(NT_Inst inst, std::string_view path, std::string_view name) : m_group{inst, path, name}, - m_x{nt::GetEntry(inst, path + "/x")}, - m_y{nt::GetEntry(inst, path + "/y")} {} + m_x{nt::GetEntry(inst, fmt::format("{}/x", path))}, + m_y{nt::GetEntry(inst, fmt::format("{}/y", path))} {} const char* GetName() const final { return m_group.GetName(); } void ForEachObject( @@ -171,7 +174,7 @@ class NTMechanism2DModel::RootModel final : public MechanismRootModel { m_group.ForEachObject(func); } - bool NTUpdate(const nt::EntryNotification& event, wpi::StringRef childName); + bool NTUpdate(const nt::EntryNotification& event, std::string_view childName); frc::Translation2d GetPosition() const override { return m_pos; }; @@ -183,7 +186,7 @@ class NTMechanism2DModel::RootModel final : public MechanismRootModel { }; bool NTMechanism2DModel::RootModel::NTUpdate(const nt::EntryNotification& event, - wpi::StringRef childName) { + std::string_view childName) { if ((event.flags & NT_NOTIFY_DELETE) != 0 && (event.entry == m_x || event.entry == m_y)) { return true; @@ -203,15 +206,15 @@ bool NTMechanism2DModel::RootModel::NTUpdate(const nt::EntryNotification& event, return false; } -NTMechanism2DModel::NTMechanism2DModel(wpi::StringRef path) +NTMechanism2DModel::NTMechanism2DModel(std::string_view path) : NTMechanism2DModel{nt::GetDefaultInstance(), path} {} -NTMechanism2DModel::NTMechanism2DModel(NT_Inst inst, wpi::StringRef path) +NTMechanism2DModel::NTMechanism2DModel(NT_Inst inst, std::string_view path) : m_nt{inst}, - m_path{(path + "/").str()}, - m_name{m_nt.GetEntry(path + "/.name")}, - m_dimensions{m_nt.GetEntry(path + "/dims")}, - m_bgColor{m_nt.GetEntry(path + "/backgroundColor")}, + m_path{fmt::format("{}/", path)}, + m_name{m_nt.GetEntry(fmt::format("{}/.name", path))}, + m_dimensions{m_nt.GetEntry(fmt::format("{}/dims", path))}, + m_bgColor{m_nt.GetEntry(fmt::format("{}/backgroundColor", path))}, m_dimensionsValue{1_m, 1_m} { m_nt.AddListener(m_path, NT_NOTIFY_LOCAL | NT_NOTIFY_NEW | NT_NOTIFY_DELETE | NT_NOTIFY_UPDATE | NT_NOTIFY_IMMEDIATE); @@ -247,28 +250,30 @@ void NTMechanism2DModel::Update() { } } - if (wpi::StringRef{event.name}.startswith(m_path)) { - auto name = wpi::StringRef{event.name}.drop_front(m_path.size()); + std::string_view name = event.name; + if (wpi::starts_with(name, m_path)) { + name.remove_prefix(m_path.size()); if (name.empty() || name[0] == '.') { continue; } - wpi::StringRef childName; - std::tie(name, childName) = name.split('/'); + std::string_view childName; + std::tie(name, childName) = wpi::split(name, '/'); if (childName.empty()) { continue; } auto it = std::lower_bound(m_roots.begin(), m_roots.end(), name, - [](const auto& e, wpi::StringRef name) { + [](const auto& e, std::string_view name) { return e->GetName() < name; }); bool match = it != m_roots.end() && (*it)->GetName() == name; if (event.flags & NT_NOTIFY_NEW) { if (!match) { - it = - m_roots.emplace(it, std::make_unique( - m_nt.GetInstance(), m_path + name, name)); + it = m_roots.emplace( + it, + std::make_unique( + m_nt.GetInstance(), fmt::format("{}{}", m_path, name), name)); match = true; } } diff --git a/glass/src/libnt/native/cpp/NTPIDController.cpp b/glass/src/libnt/native/cpp/NTPIDController.cpp index fdea4fb451..7936057fab 100644 --- a/glass/src/libnt/native/cpp/NTPIDController.cpp +++ b/glass/src/libnt/native/cpp/NTPIDController.cpp @@ -4,25 +4,28 @@ #include "glass/networktables/NTPIDController.h" +#include +#include + using namespace glass; -NTPIDControllerModel::NTPIDControllerModel(wpi::StringRef path) +NTPIDControllerModel::NTPIDControllerModel(std::string_view path) : NTPIDControllerModel(nt::GetDefaultInstance(), path) {} NTPIDControllerModel::NTPIDControllerModel(NT_Inst instance, - wpi::StringRef path) + std::string_view path) : m_nt(instance), - m_name(m_nt.GetEntry(path + "/.name")), - m_controllable(m_nt.GetEntry(path + "/.controllable")), - m_p(m_nt.GetEntry(path + "/p")), - m_i(m_nt.GetEntry(path + "/i")), - m_d(m_nt.GetEntry(path + "/d")), - m_setpoint(m_nt.GetEntry(path + "/setpoint")), - m_pData("NTPIDCtrlP:" + path), - m_iData("NTPIDCtrlI:" + path), - m_dData("NTPIDCtrlD:" + path), - m_setpointData("NTPIDCtrlStpt:" + path), - m_nameValue(path.rsplit('/').second) { + m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), + m_controllable(m_nt.GetEntry(fmt::format("{}/.controllable", path))), + m_p(m_nt.GetEntry(fmt::format("{}/p", path))), + m_i(m_nt.GetEntry(fmt::format("{}/i", path))), + m_d(m_nt.GetEntry(fmt::format("{}/d", path))), + m_setpoint(m_nt.GetEntry(fmt::format("{}/setpoint", path))), + m_pData(fmt::format("NTPIDCtrlP:{}", path)), + m_iData(fmt::format("NTPIDCtrlI:{}", path)), + m_dData(fmt::format("NTPIDCtrlD:{}", path)), + m_setpointData(fmt::format("NTPIDCtrlStpt:{}", path)), + m_nameValue(wpi::rsplit(path, '/').second) { m_nt.AddListener(m_name); m_nt.AddListener(m_controllable); m_nt.AddListener(m_p); diff --git a/glass/src/libnt/native/cpp/NTSpeedController.cpp b/glass/src/libnt/native/cpp/NTSpeedController.cpp index 8dd9142cc6..a4fc1cab2f 100644 --- a/glass/src/libnt/native/cpp/NTSpeedController.cpp +++ b/glass/src/libnt/native/cpp/NTSpeedController.cpp @@ -4,19 +4,22 @@ #include "glass/networktables/NTSpeedController.h" +#include +#include + using namespace glass; -NTSpeedControllerModel::NTSpeedControllerModel(wpi::StringRef path) +NTSpeedControllerModel::NTSpeedControllerModel(std::string_view path) : NTSpeedControllerModel(nt::GetDefaultInstance(), path) {} NTSpeedControllerModel::NTSpeedControllerModel(NT_Inst instance, - wpi::StringRef path) + std::string_view path) : m_nt(instance), - m_value(m_nt.GetEntry(path + "/Value")), - m_name(m_nt.GetEntry(path + "/.name")), - m_controllable(m_nt.GetEntry(path + "/.controllable")), - m_valueData("NT_SpdCtrl:" + path), - m_nameValue(path.rsplit('/').second) { + m_value(m_nt.GetEntry(fmt::format("{}/Value", path))), + m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), + m_controllable(m_nt.GetEntry(fmt::format("{}/.controllable"))), + m_valueData(fmt::format("NT_SpdCtrl:{}", path)), + m_nameValue(wpi::rsplit(path, '/').second) { m_nt.AddListener(m_value); m_nt.AddListener(m_name); m_nt.AddListener(m_controllable); diff --git a/glass/src/libnt/native/cpp/NTStringChooser.cpp b/glass/src/libnt/native/cpp/NTStringChooser.cpp index e1c8d3bf18..47eb787ea5 100644 --- a/glass/src/libnt/native/cpp/NTStringChooser.cpp +++ b/glass/src/libnt/native/cpp/NTStringChooser.cpp @@ -4,32 +4,34 @@ #include "glass/networktables/NTStringChooser.h" +#include + using namespace glass; -NTStringChooserModel::NTStringChooserModel(wpi::StringRef path) +NTStringChooserModel::NTStringChooserModel(std::string_view path) : NTStringChooserModel{nt::GetDefaultInstance(), path} {} -NTStringChooserModel::NTStringChooserModel(NT_Inst inst, wpi::StringRef path) +NTStringChooserModel::NTStringChooserModel(NT_Inst inst, std::string_view path) : m_nt{inst}, - m_default{m_nt.GetEntry(path + "/default")}, - m_selected{m_nt.GetEntry(path + "/selected")}, - m_active{m_nt.GetEntry(path + "/active")}, - m_options{m_nt.GetEntry(path + "/options")} { + m_default{m_nt.GetEntry(fmt::format("{}/default", path))}, + m_selected{m_nt.GetEntry(fmt::format("{}/selected", path))}, + m_active{m_nt.GetEntry(fmt::format("{}/active", path))}, + m_options{m_nt.GetEntry(fmt::format("{}/options", path))} { m_nt.AddListener(m_default); m_nt.AddListener(m_selected); m_nt.AddListener(m_active); m_nt.AddListener(m_options); } -void NTStringChooserModel::SetDefault(wpi::StringRef val) { +void NTStringChooserModel::SetDefault(std::string_view val) { nt::SetEntryValue(m_default, nt::Value::MakeString(val)); } -void NTStringChooserModel::SetSelected(wpi::StringRef val) { +void NTStringChooserModel::SetSelected(std::string_view val) { nt::SetEntryValue(m_selected, nt::Value::MakeString(val)); } -void NTStringChooserModel::SetActive(wpi::StringRef val) { +void NTStringChooserModel::SetActive(std::string_view val) { nt::SetEntryValue(m_active, nt::Value::MakeString(val)); } diff --git a/glass/src/libnt/native/cpp/NTSubsystem.cpp b/glass/src/libnt/native/cpp/NTSubsystem.cpp index e7976ec958..b2bdf8c837 100644 --- a/glass/src/libnt/native/cpp/NTSubsystem.cpp +++ b/glass/src/libnt/native/cpp/NTSubsystem.cpp @@ -4,16 +4,18 @@ #include "glass/networktables/NTSubsystem.h" +#include + using namespace glass; -NTSubsystemModel::NTSubsystemModel(wpi::StringRef path) +NTSubsystemModel::NTSubsystemModel(std::string_view path) : NTSubsystemModel(nt::GetDefaultInstance(), path) {} -NTSubsystemModel::NTSubsystemModel(NT_Inst instance, wpi::StringRef path) +NTSubsystemModel::NTSubsystemModel(NT_Inst instance, std::string_view path) : m_nt(instance), - m_name(m_nt.GetEntry(path + "/.name")), - m_defaultCommand(m_nt.GetEntry(path + "/.default")), - m_currentCommand(m_nt.GetEntry(path + "/.command")) { + m_name(m_nt.GetEntry(fmt::format("{}/.name", path))), + m_defaultCommand(m_nt.GetEntry(fmt::format("{}/.default", path))), + m_currentCommand(m_nt.GetEntry(fmt::format("{}/.command", path))) { m_nt.AddListener(m_name); m_nt.AddListener(m_defaultCommand); m_nt.AddListener(m_currentCommand); diff --git a/glass/src/libnt/native/cpp/NetworkTables.cpp b/glass/src/libnt/native/cpp/NetworkTables.cpp index cea8be538f..0e0955d3ce 100644 --- a/glass/src/libnt/native/cpp/NetworkTables.cpp +++ b/glass/src/libnt/native/cpp/NetworkTables.cpp @@ -11,14 +11,15 @@ #include #include #include +#include #include +#include #include #include #include -#include #include -#include +#include #include #include "glass/Context.h" @@ -47,19 +48,7 @@ static std::string BooleanArrayToString(wpi::ArrayRef in) { } static std::string DoubleArrayToString(wpi::ArrayRef in) { - std::string rv; - wpi::raw_string_ostream os{rv}; - os << '['; - bool first = true; - for (auto v : in) { - if (!first) { - os << ','; - } - first = false; - os << wpi::format("%.6f", v); - } - os << ']'; - return rv; + return fmt::format("[{:.6f}]", fmt::join(in, ",")); } static std::string StringArrayToString(wpi::ArrayRef in) { @@ -107,14 +96,14 @@ void NetworkTablesModel::Entry::UpdateValue() { switch (value->type()) { case NT_BOOLEAN: if (!source) { - source = std::make_unique(wpi::Twine{"NT:"} + name); + source = std::make_unique(fmt::format("NT:{}", name)); } source->SetValue(value->GetBoolean() ? 1 : 0); source->SetDigital(true); break; case NT_DOUBLE: if (!source) { - source = std::make_unique(wpi::Twine{"NT:"} + name); + source = std::make_unique(fmt::format("NT:{}", name)); } source->SetValue(value->GetDouble()); source->SetDigital(false); @@ -185,10 +174,10 @@ void NetworkTablesModel::Update() { // rebuild tree m_root.clear(); - wpi::SmallVector parts; + wpi::SmallVector parts; for (auto& entry : m_sortedEntries) { parts.clear(); - wpi::StringRef{entry->name}.split(parts, '/', -1, false); + wpi::split(entry->name, parts, '/', -1, false); // ignore a raw "/" key if (parts.empty()) { @@ -206,8 +195,8 @@ void NetworkTablesModel::Update() { // path is from the beginning of the string to the end of the current // part; this works because part is a reference to the internals of // entry->name - nodes->back().path.assign(entry->name.data(), - part.end() - entry->name.data()); + nodes->back().path.assign( + entry->name.data(), part.data() + part.size() - entry->name.data()); it = nodes->end() - 1; } nodes = &it->children; @@ -229,33 +218,33 @@ bool NetworkTablesModel::Exists() { return nt::IsConnected(m_inst); } -static std::shared_ptr StringToBooleanArray(wpi::StringRef in) { - in = in.trim(); +static std::shared_ptr StringToBooleanArray(std::string_view in) { + in = wpi::trim(in); if (in.empty()) { return nt::NetworkTableValue::MakeBooleanArray( std::initializer_list{}); } if (in.front() == '[') { - in = in.drop_front(); + in.remove_prefix(1); } if (in.back() == ']') { - in = in.drop_back(); + in.remove_suffix(1); } - in = in.trim(); + in = wpi::trim(in); - wpi::SmallVector inSplit; + wpi::SmallVector inSplit; wpi::SmallVector out; - in.split(inSplit, ',', -1, false); + wpi::split(in, inSplit, ',', -1, false); for (auto val : inSplit) { - val = val.trim(); - if (val.equals_lower("true")) { + val = wpi::trim(val); + if (wpi::equals_lower(val, "true")) { out.emplace_back(1); - } else if (val.equals_lower("false")) { + } else if (wpi::equals_lower(val, "false")) { out.emplace_back(0); } else { - wpi::errs() << "GUI: NetworkTables: Could not understand value '" << val - << "'\n"; + fmt::print(stderr, + "GUI: NetworkTables: Could not understand value '{}'\n", val); return nullptr; } } @@ -263,33 +252,30 @@ static std::shared_ptr StringToBooleanArray(wpi::StringRef in) { return nt::NetworkTableValue::MakeBooleanArray(out); } -static std::shared_ptr StringToDoubleArray(wpi::StringRef in) { - in = in.trim(); +static std::shared_ptr StringToDoubleArray(std::string_view in) { + in = wpi::trim(in); if (in.empty()) { return nt::NetworkTableValue::MakeDoubleArray( std::initializer_list{}); } if (in.front() == '[') { - in = in.drop_front(); + in.remove_prefix(1); } if (in.back() == ']') { - in = in.drop_back(); + in.remove_suffix(1); } - in = in.trim(); + in = wpi::trim(in); - wpi::SmallVector inSplit; + wpi::SmallVector inSplit; wpi::SmallVector out; - in.split(inSplit, ',', -1, false); + wpi::split(in, inSplit, ',', -1, false); for (auto val : inSplit) { - val = val.trim(); - wpi::SmallString<32> valStr = val; - double d; - if (std::sscanf(valStr.c_str(), "%lf", &d) == 1) { - out.emplace_back(d); + if (auto num = wpi::parse_float(wpi::trim(val))) { + out.emplace_back(num.value()); } else { - wpi::errs() << "GUI: NetworkTables: Could not understand value '" << val - << "'\n"; + fmt::print(stderr, + "GUI: NetworkTables: Could not understand value '{}'\n", val); return nullptr; } } @@ -307,8 +293,8 @@ static int fromxdigit(char ch) { } } -static wpi::StringRef UnescapeString(wpi::StringRef source, - wpi::SmallVectorImpl& buf) { +static std::string_view UnescapeString(std::string_view source, + wpi::SmallVectorImpl& buf) { assert(source.size() >= 2 && source.front() == '"' && source.back() == '"'); buf.clear(); buf.reserve(source.size() - 2); @@ -342,36 +328,36 @@ static wpi::StringRef UnescapeString(wpi::StringRef source, break; } } - return wpi::StringRef{buf.data(), buf.size()}; + return {buf.data(), buf.size()}; } -static std::shared_ptr StringToStringArray(wpi::StringRef in) { - in = in.trim(); +static std::shared_ptr StringToStringArray(std::string_view in) { + in = wpi::trim(in); if (in.empty()) { return nt::NetworkTableValue::MakeStringArray( std::initializer_list{}); } if (in.front() == '[') { - in = in.drop_front(); + in.remove_prefix(1); } if (in.back() == ']') { - in = in.drop_back(); + in.remove_suffix(1); } - in = in.trim(); + in = wpi::trim(in); - wpi::SmallVector inSplit; + wpi::SmallVector inSplit; std::vector out; wpi::SmallString<32> buf; - in.split(inSplit, ',', -1, false); + wpi::split(in, inSplit, ',', -1, false); for (auto val : inSplit) { - val = val.trim(); + val = wpi::trim(val); if (val.empty()) { continue; } if (val.front() != '"' || val.back() != '"') { - wpi::errs() << "GUI: NetworkTables: Could not understand value '" << val - << "'\n"; + fmt::print(stderr, + "GUI: NetworkTables: Could not understand value '{}'\n", val); return nullptr; } out.emplace_back(UnescapeString(val, buf)); @@ -421,7 +407,7 @@ static void EmitEntryValueReadonly(NetworkTablesModel::Entry& entry) { static constexpr size_t kTextBufferSize = 4096; -static char* GetTextBuffer(wpi::StringRef in) { +static char* GetTextBuffer(std::string_view in) { static char textBuffer[kTextBufferSize]; size_t len = (std::min)(in.size(), kTextBufferSize - 1); std::memcpy(textBuffer, in.data(), len); @@ -524,7 +510,7 @@ static void EmitParentContextMenu(const std::string& path, if (path == "/") { fullNewPath = path + nameBuffer; } else { - fullNewPath = (path + wpi::Twine('/') + nameBuffer).str(); + fullNewPath = fmt::format("{}/{}", path, nameBuffer); } ImGui::Text("Adding: %s", fullNewPath.c_str()); diff --git a/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp b/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp index 7431380752..8d991cb78d 100644 --- a/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp +++ b/glass/src/libnt/native/cpp/NetworkTablesProvider.cpp @@ -6,18 +6,22 @@ #include +#include #include #include +#include #include using namespace glass; -NetworkTablesProvider::NetworkTablesProvider(const wpi::Twine& iniName) +NetworkTablesProvider::NetworkTablesProvider(std::string_view iniName) : NetworkTablesProvider{iniName, nt::GetDefaultInstance()} {} -NetworkTablesProvider::NetworkTablesProvider(const wpi::Twine& iniName, +NetworkTablesProvider::NetworkTablesProvider(std::string_view iniName, NT_Inst inst) - : Provider{iniName + "Window"}, m_nt{inst}, m_typeCache{iniName} { + : Provider{fmt::format("{}Window", iniName)}, + m_nt{inst}, + m_typeCache{iniName} { m_nt.AddListener("", NT_NOTIFY_LOCAL | NT_NOTIFY_NEW | NT_NOTIFY_DELETE | NT_NOTIFY_IMMEDIATE); } @@ -28,11 +32,11 @@ void NetworkTablesProvider::GlobalInit() { } void NetworkTablesProvider::DisplayMenu() { - wpi::SmallVector path; + wpi::SmallVector path; wpi::SmallString<64> name; for (auto&& entry : m_viewEntries) { path.clear(); - wpi::StringRef{entry->name}.split(path, '/', -1, false); + wpi::split(entry->name, path, '/', -1, false); bool fullDepth = true; int depth = 0; @@ -69,12 +73,12 @@ void NetworkTablesProvider::Update() { // add/remove entries from NT changes for (auto&& event : m_nt.PollListener()) { // look for .type fields - wpi::StringRef eventName{event.name}; - if (!eventName.endswith("/.type") || !event.value || + std::string_view eventName{event.name}; + if (!wpi::ends_with(eventName, "/.type") || !event.value || !event.value->IsString()) { continue; } - auto tableName = eventName.drop_back(6); + auto tableName = wpi::drop_back(eventName, 6); // only handle ones where we have a builder auto builderIt = m_typeMap.find(event.value->GetString()); @@ -117,14 +121,15 @@ void NetworkTablesProvider::Update() { } auto entry = GetOrCreateView( - builderIt->second, nt::GetEntry(m_nt.GetInstance(), id + "/.type"), id); + builderIt->second, + nt::GetEntry(m_nt.GetInstance(), fmt::format("{}/.type", id)), id); if (entry) { Show(entry, window.get()); } } } -void NetworkTablesProvider::Register(wpi::StringRef typeName, +void NetworkTablesProvider::Register(std::string_view typeName, CreateModelFunc createModel, CreateViewFunc createView) { m_typeMap[typeName] = Builder{std::move(createModel), std::move(createView)}; @@ -153,9 +158,9 @@ void NetworkTablesProvider::Show(ViewEntry* entry, Window* window) { if (!window) { return; } - if (wpi::StringRef{entry->name}.startswith("/SmartDashboard/")) { - window->SetDefaultName(wpi::StringRef{entry->name}.drop_front(16) + - " (SmartDashboard)"); + if (wpi::starts_with(entry->name, "/SmartDashboard/")) { + window->SetDefaultName( + fmt::format("{} (SmartDashboard)", wpi::drop_front(entry->name, 16))); } entry->window = window; @@ -171,7 +176,7 @@ void NetworkTablesProvider::Show(ViewEntry* entry, Window* window) { } NetworkTablesProvider::ViewEntry* NetworkTablesProvider::GetOrCreateView( - const Builder& builder, NT_Entry typeEntry, wpi::StringRef name) { + const Builder& builder, NT_Entry typeEntry, std::string_view name) { // get view entry if it already exists auto viewIt = FindViewEntry(name); if (viewIt != m_viewEntries.end() && (*viewIt)->name == name) { diff --git a/glass/src/libnt/native/cpp/NetworkTablesSettings.cpp b/glass/src/libnt/native/cpp/NetworkTablesSettings.cpp index 2a603b6eae..28f4de4bcd 100644 --- a/glass/src/libnt/native/cpp/NetworkTablesSettings.cpp +++ b/glass/src/libnt/native/cpp/NetworkTablesSettings.cpp @@ -4,14 +4,15 @@ #include "glass/networktables/NetworkTablesSettings.h" +#include +#include #include #include #include #include #include -#include -#include +#include #include "glass/Context.h" @@ -55,14 +56,15 @@ void NetworkTablesSettings::Thread::Main() { } while (mode != m_mode || dsClient != m_dsClient); if (m_mode == 1) { - wpi::StringRef serverTeam{m_serverTeam}; - unsigned int team; - if (!serverTeam.contains('.') && !serverTeam.getAsInteger(10, team)) { - nt::StartClientTeam(m_inst, team, NT_DEFAULT_PORT); + std::string_view serverTeam{m_serverTeam}; + std::optional team; + if (!wpi::contains(serverTeam, '.') && + (team = wpi::parse_integer(serverTeam, 10))) { + nt::StartClientTeam(m_inst, team.value(), NT_DEFAULT_PORT); } else { - wpi::SmallVector serverNames; - wpi::SmallVector, 4> servers; - serverTeam.split(serverNames, ',', -1, false); + wpi::SmallVector serverNames; + wpi::SmallVector, 4> servers; + wpi::split(serverTeam, serverNames, ',', -1, false); for (auto&& serverName : serverNames) { servers.emplace_back(serverName, NT_DEFAULT_PORT); } diff --git a/glass/src/libnt/native/include/glass/networktables/NTCommandScheduler.h b/glass/src/libnt/native/include/glass/networktables/NTCommandScheduler.h index a9aad0f2f5..54dc778841 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTCommandScheduler.h +++ b/glass/src/libnt/native/include/glass/networktables/NTCommandScheduler.h @@ -5,10 +5,10 @@ #pragma once #include +#include #include #include -#include #include "glass/DataSource.h" #include "glass/networktables/NetworkTablesHelper.h" @@ -19,8 +19,8 @@ class NTCommandSchedulerModel : public CommandSchedulerModel { public: static constexpr const char* kType = "Scheduler"; - explicit NTCommandSchedulerModel(wpi::StringRef path); - NTCommandSchedulerModel(NT_Inst instance, wpi::StringRef path); + explicit NTCommandSchedulerModel(std::string_view path); + NTCommandSchedulerModel(NT_Inst instance, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } const std::vector& GetCurrentCommands() override { diff --git a/glass/src/libnt/native/include/glass/networktables/NTCommandSelector.h b/glass/src/libnt/native/include/glass/networktables/NTCommandSelector.h index 002a1eb34a..c936665915 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTCommandSelector.h +++ b/glass/src/libnt/native/include/glass/networktables/NTCommandSelector.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include #include "glass/DataSource.h" #include "glass/networktables/NetworkTablesHelper.h" @@ -18,8 +18,8 @@ class NTCommandSelectorModel : public CommandSelectorModel { public: static constexpr const char* kType = "Command"; - explicit NTCommandSelectorModel(wpi::StringRef path); - NTCommandSelectorModel(NT_Inst instance, wpi::StringRef path); + explicit NTCommandSelectorModel(std::string_view path); + NTCommandSelectorModel(NT_Inst instance, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } DataSource* GetRunningData() override { return &m_runningData; } diff --git a/glass/src/libnt/native/include/glass/networktables/NTDifferentialDrive.h b/glass/src/libnt/native/include/glass/networktables/NTDifferentialDrive.h index b6e741b636..3dcf72106d 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTDifferentialDrive.h +++ b/glass/src/libnt/native/include/glass/networktables/NTDifferentialDrive.h @@ -5,11 +5,11 @@ #pragma once #include +#include #include #include #include -#include #include "glass/DataSource.h" #include "glass/networktables/NetworkTablesHelper.h" @@ -20,8 +20,8 @@ class NTDifferentialDriveModel : public DriveModel { public: static constexpr const char* kType = "DifferentialDrive"; - explicit NTDifferentialDriveModel(wpi::StringRef path); - NTDifferentialDriveModel(NT_Inst instance, wpi::StringRef path); + explicit NTDifferentialDriveModel(std::string_view path); + NTDifferentialDriveModel(NT_Inst instance, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } const std::vector& GetWheels() const override { diff --git a/glass/src/libnt/native/include/glass/networktables/NTDigitalInput.h b/glass/src/libnt/native/include/glass/networktables/NTDigitalInput.h index f3b4155a87..cd3dfebc1c 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTDigitalInput.h +++ b/glass/src/libnt/native/include/glass/networktables/NTDigitalInput.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include #include "glass/DataSource.h" #include "glass/hardware/DIO.h" @@ -20,8 +20,8 @@ class NTDigitalInputModel : public DIOModel { static constexpr const char* kType = "Digital Input"; // path is to the table containing ".type", excluding the trailing / - explicit NTDigitalInputModel(wpi::StringRef path); - NTDigitalInputModel(NT_Inst inst, wpi::StringRef path); + explicit NTDigitalInputModel(std::string_view path); + NTDigitalInputModel(NT_Inst inst, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } diff --git a/glass/src/libnt/native/include/glass/networktables/NTDigitalOutput.h b/glass/src/libnt/native/include/glass/networktables/NTDigitalOutput.h index 0f1604d880..8ed1ee7207 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTDigitalOutput.h +++ b/glass/src/libnt/native/include/glass/networktables/NTDigitalOutput.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include #include "glass/DataSource.h" #include "glass/hardware/DIO.h" @@ -20,8 +20,8 @@ class NTDigitalOutputModel : public DIOModel { static constexpr const char* kType = "Digital Output"; // path is to the table containing ".type", excluding the trailing / - explicit NTDigitalOutputModel(wpi::StringRef path); - NTDigitalOutputModel(NT_Inst inst, wpi::StringRef path); + explicit NTDigitalOutputModel(std::string_view path); + NTDigitalOutputModel(NT_Inst inst, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } diff --git a/glass/src/libnt/native/include/glass/networktables/NTFMS.h b/glass/src/libnt/native/include/glass/networktables/NTFMS.h index 1aa0193eca..b19a9f02da 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTFMS.h +++ b/glass/src/libnt/native/include/glass/networktables/NTFMS.h @@ -4,8 +4,9 @@ #pragma once +#include + #include -#include #include "glass/DataSource.h" #include "glass/networktables/NetworkTablesHelper.h" @@ -18,8 +19,8 @@ class NTFMSModel : public FMSModel { static constexpr const char* kType = "FMSInfo"; // path is to the table containing ".type", excluding the trailing / - explicit NTFMSModel(wpi::StringRef path); - NTFMSModel(NT_Inst inst, wpi::StringRef path); + explicit NTFMSModel(std::string_view path); + NTFMSModel(NT_Inst inst, std::string_view path); DataSource* GetFmsAttachedData() override { return &m_fmsAttached; } DataSource* GetDsAttachedData() override { return &m_dsAttached; } @@ -32,7 +33,7 @@ class NTFMSModel : public FMSModel { DataSource* GetEnabledData() override { return &m_enabled; } DataSource* GetTestData() override { return &m_test; } DataSource* GetAutonomousData() override { return &m_autonomous; } - wpi::StringRef GetGameSpecificMessage( + std::string_view GetGameSpecificMessage( wpi::SmallVectorImpl& buf) override; // NT is read-only (it's continually set by robot code) diff --git a/glass/src/libnt/native/include/glass/networktables/NTField2D.h b/glass/src/libnt/native/include/glass/networktables/NTField2D.h index c44b2a13a9..f966e0f01d 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTField2D.h +++ b/glass/src/libnt/native/include/glass/networktables/NTField2D.h @@ -6,11 +6,11 @@ #include #include +#include #include #include #include -#include #include "glass/networktables/NetworkTablesHelper.h" #include "glass/other/Field2D.h" @@ -22,8 +22,8 @@ class NTField2DModel : public Field2DModel { static constexpr const char* kType = "Field2d"; // path is to the table containing ".type", excluding the trailing / - explicit NTField2DModel(wpi::StringRef path); - NTField2DModel(NT_Inst inst, wpi::StringRef path); + explicit NTField2DModel(std::string_view path); + NTField2DModel(NT_Inst inst, std::string_view path); ~NTField2DModel() override; const char* GetPath() const { return m_path.c_str(); } @@ -33,10 +33,10 @@ class NTField2DModel : public Field2DModel { bool Exists() override; bool IsReadOnly() override; - FieldObjectModel* AddFieldObject(const wpi::Twine& name) override; - void RemoveFieldObject(const wpi::Twine& name) override; + FieldObjectModel* AddFieldObject(std::string_view name) override; + void RemoveFieldObject(std::string_view name) override; void ForEachFieldObject( - wpi::function_ref + wpi::function_ref func) override; private: @@ -49,7 +49,7 @@ class NTField2DModel : public Field2DModel { using Objects = std::vector>; Objects m_objects; - std::pair Find(wpi::StringRef fullName); + std::pair Find(std::string_view fullName); }; } // namespace glass diff --git a/glass/src/libnt/native/include/glass/networktables/NTGyro.h b/glass/src/libnt/native/include/glass/networktables/NTGyro.h index 48d6fffef2..db303a569a 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTGyro.h +++ b/glass/src/libnt/native/include/glass/networktables/NTGyro.h @@ -3,10 +3,11 @@ // the WPILib BSD license file in the root directory of this project. #pragma once + #include +#include #include -#include #include "glass/DataSource.h" #include "glass/hardware/Gyro.h" @@ -17,8 +18,8 @@ class NTGyroModel : public GyroModel { public: static constexpr const char* kType = "Gyro"; - explicit NTGyroModel(wpi::StringRef path); - NTGyroModel(NT_Inst instance, wpi::StringRef path); + explicit NTGyroModel(std::string_view path); + NTGyroModel(NT_Inst instance, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } const char* GetSimDevice() const override { return nullptr; } diff --git a/glass/src/libnt/native/include/glass/networktables/NTMecanumDrive.h b/glass/src/libnt/native/include/glass/networktables/NTMecanumDrive.h index f002a47b2c..3d4718a207 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTMecanumDrive.h +++ b/glass/src/libnt/native/include/glass/networktables/NTMecanumDrive.h @@ -5,11 +5,11 @@ #pragma once #include +#include #include #include #include -#include #include "glass/DataSource.h" #include "glass/networktables/NetworkTablesHelper.h" @@ -20,8 +20,8 @@ class NTMecanumDriveModel : public DriveModel { public: static constexpr const char* kType = "MecanumDrive"; - explicit NTMecanumDriveModel(wpi::StringRef path); - NTMecanumDriveModel(NT_Inst instance, wpi::StringRef path); + explicit NTMecanumDriveModel(std::string_view path); + NTMecanumDriveModel(NT_Inst instance, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } const std::vector& GetWheels() const override { diff --git a/glass/src/libnt/native/include/glass/networktables/NTMechanism2D.h b/glass/src/libnt/native/include/glass/networktables/NTMechanism2D.h index 5157b08345..81f7df1cb4 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTMechanism2D.h +++ b/glass/src/libnt/native/include/glass/networktables/NTMechanism2D.h @@ -6,12 +6,12 @@ #include #include +#include #include #include #include #include -#include #include "glass/networktables/NetworkTablesHelper.h" #include "glass/other/Mechanism2D.h" @@ -23,8 +23,8 @@ class NTMechanism2DModel : public Mechanism2DModel { static constexpr const char* kType = "Mechanism2d"; // path is to the table containing ".type", excluding the trailing / - explicit NTMechanism2DModel(wpi::StringRef path); - NTMechanism2DModel(NT_Inst inst, wpi::StringRef path); + explicit NTMechanism2DModel(std::string_view path); + NTMechanism2DModel(NT_Inst inst, std::string_view path); ~NTMechanism2DModel() override; const char* GetPath() const { return m_path.c_str(); } diff --git a/glass/src/libnt/native/include/glass/networktables/NTPIDController.h b/glass/src/libnt/native/include/glass/networktables/NTPIDController.h index 930ef54dab..b975641f55 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTPIDController.h +++ b/glass/src/libnt/native/include/glass/networktables/NTPIDController.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include #include "glass/DataSource.h" #include "glass/networktables/NetworkTablesHelper.h" @@ -18,8 +18,8 @@ class NTPIDControllerModel : public PIDControllerModel { public: static constexpr const char* kType = "PIDController"; - explicit NTPIDControllerModel(wpi::StringRef path); - NTPIDControllerModel(NT_Inst instance, wpi::StringRef path); + explicit NTPIDControllerModel(std::string_view path); + NTPIDControllerModel(NT_Inst instance, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } diff --git a/glass/src/libnt/native/include/glass/networktables/NTSpeedController.h b/glass/src/libnt/native/include/glass/networktables/NTSpeedController.h index 1a30d9ffce..756d94744e 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTSpeedController.h +++ b/glass/src/libnt/native/include/glass/networktables/NTSpeedController.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include #include "glass/DataSource.h" #include "glass/hardware/SpeedController.h" @@ -18,8 +18,8 @@ class NTSpeedControllerModel : public SpeedControllerModel { public: static constexpr const char* kType = "Speed Controller"; - explicit NTSpeedControllerModel(wpi::StringRef path); - NTSpeedControllerModel(NT_Inst instance, wpi::StringRef path); + explicit NTSpeedControllerModel(std::string_view path); + NTSpeedControllerModel(NT_Inst instance, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } const char* GetSimDevice() const override { return nullptr; } diff --git a/glass/src/libnt/native/include/glass/networktables/NTStringChooser.h b/glass/src/libnt/native/include/glass/networktables/NTStringChooser.h index 2262708647..fac9f7c53a 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTStringChooser.h +++ b/glass/src/libnt/native/include/glass/networktables/NTStringChooser.h @@ -19,8 +19,8 @@ class NTStringChooserModel : public StringChooserModel { static constexpr const char* kType = "String Chooser"; // path is to the table containing ".type", excluding the trailing / - explicit NTStringChooserModel(wpi::StringRef path); - NTStringChooserModel(NT_Inst inst, wpi::StringRef path); + explicit NTStringChooserModel(std::string_view path); + NTStringChooserModel(NT_Inst inst, std::string_view path); const std::string& GetDefault() override { return m_defaultValue; } const std::string& GetSelected() override { return m_selectedValue; } @@ -29,9 +29,9 @@ class NTStringChooserModel : public StringChooserModel { return m_optionsValue; } - void SetDefault(wpi::StringRef val) override; - void SetSelected(wpi::StringRef val) override; - void SetActive(wpi::StringRef val) override; + void SetDefault(std::string_view val) override; + void SetSelected(std::string_view val) override; + void SetActive(std::string_view val) override; void SetOptions(wpi::ArrayRef val) override; void Update() override; diff --git a/glass/src/libnt/native/include/glass/networktables/NTSubsystem.h b/glass/src/libnt/native/include/glass/networktables/NTSubsystem.h index b134e95497..c5862cfbd9 100644 --- a/glass/src/libnt/native/include/glass/networktables/NTSubsystem.h +++ b/glass/src/libnt/native/include/glass/networktables/NTSubsystem.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include #include "glass/DataSource.h" #include "glass/networktables/NetworkTablesHelper.h" @@ -18,8 +18,8 @@ class NTSubsystemModel : public SubsystemModel { public: static constexpr const char* kType = "Subsystem"; - explicit NTSubsystemModel(wpi::StringRef path); - NTSubsystemModel(NT_Inst instance, wpi::StringRef path); + explicit NTSubsystemModel(std::string_view path); + NTSubsystemModel(NT_Inst instance, std::string_view path); const char* GetName() const override { return m_nameValue.c_str(); } const char* GetDefaultCommand() const override { diff --git a/glass/src/libnt/native/include/glass/networktables/NetworkTables.h b/glass/src/libnt/native/include/glass/networktables/NetworkTables.h index e7dbbece83..e16ac3ad14 100644 --- a/glass/src/libnt/native/include/glass/networktables/NetworkTables.h +++ b/glass/src/libnt/native/include/glass/networktables/NetworkTables.h @@ -6,12 +6,12 @@ #include #include +#include #include #include #include #include -#include #include "glass/Model.h" #include "glass/View.h" @@ -47,7 +47,7 @@ class NetworkTablesModel : public Model { }; struct TreeNode { - explicit TreeNode(wpi::StringRef name) : name{name} {} + explicit TreeNode(std::string_view name) : name{name} {} /** Short name (e.g. of just this node) */ std::string name; diff --git a/glass/src/libnt/native/include/glass/networktables/NetworkTablesHelper.h b/glass/src/libnt/native/include/glass/networktables/NetworkTablesHelper.h index b241c6efb8..aba32525c8 100644 --- a/glass/src/libnt/native/include/glass/networktables/NetworkTablesHelper.h +++ b/glass/src/libnt/native/include/glass/networktables/NetworkTablesHelper.h @@ -4,11 +4,10 @@ #pragma once +#include #include #include -#include -#include namespace glass { @@ -23,7 +22,7 @@ class NetworkTablesHelper { NT_Inst GetInstance() const { return m_inst; } NT_EntryListenerPoller GetPoller() const { return m_poller; } - NT_Entry GetEntry(const wpi::Twine& name) const { + NT_Entry GetEntry(std::string_view name) const { return nt::GetEntry(m_inst, name); } @@ -36,7 +35,7 @@ class NetworkTablesHelper { return nt::AddPolledEntryListener(m_poller, entry, flags); } - NT_EntryListener AddListener(const wpi::Twine& prefix, + NT_EntryListener AddListener(std::string_view prefix, unsigned int flags = kDefaultListenerFlags) { return nt::AddPolledEntryListener(m_poller, prefix, flags); } diff --git a/glass/src/libnt/native/include/glass/networktables/NetworkTablesProvider.h b/glass/src/libnt/native/include/glass/networktables/NetworkTablesProvider.h index cf97e6cf1a..17374cae9e 100644 --- a/glass/src/libnt/native/include/glass/networktables/NetworkTablesProvider.h +++ b/glass/src/libnt/native/include/glass/networktables/NetworkTablesProvider.h @@ -6,12 +6,11 @@ #include #include +#include #include #include #include -#include -#include #include "glass/Model.h" #include "glass/Provider.h" @@ -42,8 +41,8 @@ class NetworkTablesProvider : private Provider { using Provider::CreateModelFunc; using Provider::CreateViewFunc; - explicit NetworkTablesProvider(const wpi::Twine& iniName); - NetworkTablesProvider(const wpi::Twine& iniName, NT_Inst inst); + explicit NetworkTablesProvider(std::string_view iniName); + NetworkTablesProvider(std::string_view iniName, NT_Inst inst); /** * Get the NetworkTables instance being used for this provider. @@ -70,7 +69,7 @@ class NetworkTablesProvider : private Provider { * @param createModel functor to create model * @param createView functor to create view */ - void Register(wpi::StringRef typeName, CreateModelFunc createModel, + void Register(std::string_view typeName, CreateModelFunc createModel, CreateViewFunc createView); using WindowManager::AddWindow; @@ -92,7 +91,7 @@ class NetworkTablesProvider : private Provider { wpi::StringMap m_typeMap; struct Entry : public ModelEntry { - Entry(NT_Entry typeEntry, wpi::StringRef name, const Builder& builder) + Entry(NT_Entry typeEntry, std::string_view name, const Builder& builder) : ModelEntry{name, [](NT_Inst, const char*) { return true; }, builder.createModel}, typeEntry{typeEntry} {} @@ -102,7 +101,7 @@ class NetworkTablesProvider : private Provider { void Show(ViewEntry* entry, Window* window) override; ViewEntry* GetOrCreateView(const Builder& builder, NT_Entry typeEntry, - wpi::StringRef name); + std::string_view name); }; /** diff --git a/hal/.styleguide b/hal/.styleguide index 49d4e29e24..5f7d6e3d7a 100644 --- a/hal/.styleguide +++ b/hal/.styleguide @@ -30,6 +30,7 @@ repoRootNameOverride { includeOtherLibs { ^FRC_FPGA_ChipObject/ ^FRC_NetworkCommunication/ + ^fmt/ ^i2clib/ ^llvm/ ^opencv2/ diff --git a/hal/src/main/native/athena/AddressableLED.cpp b/hal/src/main/native/athena/AddressableLED.cpp index 864c08ce07..74a323a46d 100644 --- a/hal/src/main/native/athena/AddressableLED.cpp +++ b/hal/src/main/native/athena/AddressableLED.cpp @@ -7,6 +7,7 @@ #include #include +#include #include "ConstantsInternal.h" #include "DigitalInternal.h" @@ -145,9 +146,11 @@ void HAL_SetAddressableLEDLength(HAL_AddressableLEDHandle handle, if (length > HAL_kAddressableLEDMaxLength || length < 0) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "LED length must be less than or equal to " + - wpi::Twine(HAL_kAddressableLEDMaxLength) + - ". " + wpi::Twine(length) + " was requested"); + hal::SetLastError( + status, + fmt::format( + "LED length must be less than or equal to {}. {} was requested", + HAL_kAddressableLEDMaxLength, length)); return; } @@ -179,9 +182,11 @@ void HAL_WriteAddressableLEDData(HAL_AddressableLEDHandle handle, if (length > led->stringLength || length < 0) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Data length must be less than or equal to " + - wpi::Twine(led->stringLength) + ". " + - wpi::Twine(length) + " was requested"); + hal::SetLastError( + status, + fmt::format( + "Data length must be less than or equal to {}. {} was requested", + led->stringLength, length)); return; } diff --git a/hal/src/main/native/athena/AnalogGyro.cpp b/hal/src/main/native/athena/AnalogGyro.cpp index 83bc42f0be..19f26ddd7b 100644 --- a/hal/src/main/native/athena/AnalogGyro.cpp +++ b/hal/src/main/native/athena/AnalogGyro.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include #include "AnalogInternal.h" #include "HALInitializer.h" @@ -193,8 +193,8 @@ void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) { if (*status != 0) { return; } - wpi::outs() << "Calibrating analog gyro for " << kCalibrationSampleTime - << " seconds." << '\n'; + fmt::print("Calibrating analog gyro for {} seconds.\n", + kCalibrationSampleTime); Wait(kCalibrationSampleTime); int64_t value; diff --git a/hal/src/main/native/athena/CTREPCM.cpp b/hal/src/main/native/athena/CTREPCM.cpp index fc079011e3..07aa48e1cc 100644 --- a/hal/src/main/native/athena/CTREPCM.cpp +++ b/hal/src/main/native/athena/CTREPCM.cpp @@ -4,6 +4,8 @@ #include "hal/CTREPCM.h" +#include + #include "HALInitializer.h" #include "HALInternal.h" #include "PortsInternal.h" @@ -342,8 +344,9 @@ void HAL_FireCTREPCMOneShot(HAL_CTREPCMHandle handle, int32_t index, int32_t* status) { if (index > 7 || index < 0) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Only [0-7] are valid index values. Requested " + - wpi::Twine(index)); + hal::SetLastError( + status, + fmt::format("Only [0-7] are valid index values. Requested {}", index)); return; } @@ -373,8 +376,9 @@ void HAL_SetCTREPCMOneShotDuration(HAL_CTREPCMHandle handle, int32_t index, int32_t durMs, int32_t* status) { if (index > 7 || index < 0) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Only [0-7] are valid index values. Requested " + - wpi::Twine(index)); + hal::SetLastError( + status, + fmt::format("Only [0-7] are valid index values. Requested {}", index)); return; } diff --git a/hal/src/main/native/athena/Counter.cpp b/hal/src/main/native/athena/Counter.cpp index d6a278ce74..7f84df88ff 100644 --- a/hal/src/main/native/athena/Counter.cpp +++ b/hal/src/main/native/athena/Counter.cpp @@ -4,6 +4,8 @@ #include "hal/Counter.h" +#include + #include "ConstantsInternal.h" #include "DigitalInternal.h" #include "HALInitializer.h" @@ -264,10 +266,9 @@ void HAL_SetCounterSamplesToAverage(HAL_CounterHandle counterHandle, } if (samplesToAverage < 1 || samplesToAverage > 127) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError( - status, - "Samples to average must be between 1 and 127 inclusive. Requested " + - wpi::Twine(samplesToAverage)); + hal::SetLastError(status, fmt::format("Samples to average must be between " + "1 and 127 inclusive. Requested {}", + samplesToAverage)); return; } counter->counter->writeTimerConfig_AverageSize(samplesToAverage, status); diff --git a/hal/src/main/native/athena/DIO.cpp b/hal/src/main/native/athena/DIO.cpp index 75909a0702..45723597a8 100644 --- a/hal/src/main/native/athena/DIO.cpp +++ b/hal/src/main/native/athena/DIO.cpp @@ -5,10 +5,9 @@ #include "hal/DIO.h" #include +#include #include -#include - #include "DigitalInternal.h" #include "HALInitializer.h" #include "HALInternal.h" @@ -143,8 +142,8 @@ void HAL_FreeDIOPort(HAL_DigitalHandle dioPortHandle) { while (port.use_count() != 1) { auto current = hal::fpga_clock::now(); if (start + std::chrono::seconds(1) < current) { - wpi::outs() << "DIO handle free timeout\n"; - wpi::outs().flush(); + std::puts("DIO handle free timeout"); + std::fflush(stdout); break; } std::this_thread::yield(); diff --git a/hal/src/main/native/athena/Encoder.cpp b/hal/src/main/native/athena/Encoder.cpp index 10556844f6..d5a3d38c94 100644 --- a/hal/src/main/native/athena/Encoder.cpp +++ b/hal/src/main/native/athena/Encoder.cpp @@ -4,6 +4,8 @@ #include "hal/Encoder.h" +#include + #include "EncoderInternal.h" #include "FPGAEncoder.h" #include "HALInitializer.h" @@ -47,9 +49,8 @@ Encoder::Encoder(HAL_Handle digitalSourceHandleA, } default: *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Encoding type " + - wpi::Twine(static_cast(encodingType)) + - " invalid."); + hal::SetLastError(status, fmt::format("Encoding type {} invalid.", + static_cast(encodingType))); return; } } @@ -185,10 +186,9 @@ void Encoder::SetReverseDirection(bool reverseDirection, int32_t* status) { void Encoder::SetSamplesToAverage(int32_t samplesToAverage, int32_t* status) { if (samplesToAverage < 1 || samplesToAverage > 127) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError( - status, - "Samples to average must be between 1 and 127 inclusive. Requested " + - wpi::Twine(samplesToAverage)); + hal::SetLastError(status, fmt::format("Samples to average must be between " + "1 and 127 inclusive. Requested {}", + samplesToAverage)); return; } if (m_counter) { diff --git a/hal/src/main/native/athena/FPGAEncoder.cpp b/hal/src/main/native/athena/FPGAEncoder.cpp index 3bfe9d9a41..9965d43cb0 100644 --- a/hal/src/main/native/athena/FPGAEncoder.cpp +++ b/hal/src/main/native/athena/FPGAEncoder.cpp @@ -6,6 +6,8 @@ #include +#include + #include "DigitalInternal.h" #include "HALInitializer.h" #include "HALInternal.h" @@ -194,10 +196,9 @@ void HAL_SetFPGAEncoderSamplesToAverage(HAL_FPGAEncoderHandle fpgaEncoderHandle, } if (samplesToAverage < 1 || samplesToAverage > 127) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError( - status, - "Samples to average must be between 1 and 127 inclusive. Requested " + - wpi::Twine(samplesToAverage)); + hal::SetLastError(status, fmt::format("Samples to average must be between " + "1 and 127 inclusive. Requested {}", + samplesToAverage)); return; } encoder->encoder->writeTimerConfig_AverageSize(samplesToAverage, status); diff --git a/hal/src/main/native/athena/FRCDriverStation.cpp b/hal/src/main/native/athena/FRCDriverStation.cpp index 40c2f24baa..55b86e7bc8 100644 --- a/hal/src/main/native/athena/FRCDriverStation.cpp +++ b/hal/src/main/native/athena/FRCDriverStation.cpp @@ -7,13 +7,15 @@ #include #include #include +#include +#include #include #include +#include #include #include #include -#include #include "hal/DriverStation.h" @@ -161,9 +163,9 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, } int retval = 0; if (i == KEEP_MSGS || (curTime - prevMsgTime[i]) >= std::chrono::seconds(1)) { - wpi::StringRef detailsRef{details}; - wpi::StringRef locationRef{location}; - wpi::StringRef callStackRef{callStack}; + std::string_view detailsRef{details}; + std::string_view locationRef{location}; + std::string_view callStackRef{callStack}; // 1 tag, 4 timestamp, 2 seqnum // 2 numOccur, 4 error code, 1 flags, 6 strlen @@ -199,14 +201,16 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, newCallStack.c_str()); } if (printMsg) { + fmt::memory_buffer buf; if (location && location[0] != '\0') { - wpi::errs() << (isError ? "Error" : "Warning") << " at " << location - << ": "; + fmt::format_to(buf, "{} at {}: ", isError ? "Error" : "Warning", + location); } - wpi::errs() << details << "\n"; + fmt::format_to(buf, "{}\n", details); if (callStack && callStack[0] != '\0') { - wpi::errs() << callStack << "\n"; + fmt::format_to(buf, "{}\n", callStack); } + std::fwrite(buf.data(), buf.size(), 1, stderr); } if (i == KEEP_MSGS) { // replace the oldest one @@ -226,7 +230,7 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, } int32_t HAL_SendConsoleLine(const char* line) { - wpi::StringRef lineRef{line}; + std::string_view lineRef{line}; if (lineRef.size() <= 65535) { // Send directly return FRC_NetworkCommunication_sendConsoleLine(line); diff --git a/hal/src/main/native/athena/HAL.cpp b/hal/src/main/native/athena/HAL.cpp index 386953669d..e99aa0f6a7 100644 --- a/hal/src/main/native/athena/HAL.cpp +++ b/hal/src/main/native/athena/HAL.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -16,8 +17,8 @@ #include #include #include +#include #include -#include #include #include "HALInitializer.h" @@ -330,18 +331,19 @@ static bool killExistingProgram(int timeout, int mode) { // see if the pid is around, but we don't want to mess with init id=1, or // ourselves if (pid >= 2 && kill(pid, 0) == 0 && pid != getpid()) { - wpi::outs() << "Killing previously running FRC program...\n"; + std::puts("Killing previously running FRC program..."); kill(pid, SIGTERM); // try to kill it std::this_thread::sleep_for(std::chrono::milliseconds(timeout)); if (kill(pid, 0) == 0) { // still not successful - wpi::outs() << "FRC pid " << pid << " did not die within " << timeout - << "ms. Force killing with kill -9\n"; + fmt::print( + "FRC pid {} did not die within {} ms. Force killing with kill -9\n", + pid, timeout); // Force kill -9 auto forceKill = kill(pid, SIGKILL); if (forceKill != 0) { auto errorMsg = std::strerror(forceKill); - wpi::outs() << "Kill -9 error: " << errorMsg << "\n"; + fmt::print("Kill -9 error: {}\n", errorMsg); } // Give a bit of time for the kill to take place std::this_thread::sleep_for(std::chrono::milliseconds(250)); @@ -378,7 +380,6 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { setlinebuf(stdin); setlinebuf(stdout); - wpi::outs().SetUnbuffered(); prctl(PR_SET_PDEATHSIG, SIGTERM); @@ -412,11 +413,11 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { int32_t status = 0; uint64_t rv = HAL_GetFPGATime(&status); if (status != 0) { - wpi::errs() - << "Call to HAL_GetFPGATime failed in wpi::Now() with status " - << status - << ". Initialization might have failed. Time will not be correct\n"; - wpi::errs().flush(); + fmt::print(stderr, + "Call to HAL_GetFPGATime failed in wpi::Now() with status {}. " + "Initialization might have failed. Time will not be correct\n", + status); + std::fflush(stderr); return 0u; } return rv; diff --git a/hal/src/main/native/athena/HALInternal.h b/hal/src/main/native/athena/HALInternal.h index b1a2d1dfd5..64a0dca368 100644 --- a/hal/src/main/native/athena/HALInternal.h +++ b/hal/src/main/native/athena/HALInternal.h @@ -6,15 +6,15 @@ #include -#include +#include namespace hal { void ReleaseFPGAInterrupt(int32_t interruptNumber); -void SetLastError(int32_t* status, const wpi::Twine& value); -void SetLastErrorIndexOutOfRange(int32_t* status, const wpi::Twine& message, +void SetLastError(int32_t* status, std::string_view value); +void SetLastErrorIndexOutOfRange(int32_t* status, std::string_view message, int32_t minimum, int32_t maximum, int32_t channel); -void SetLastErrorPreviouslyAllocated(int32_t* status, const wpi::Twine& message, +void SetLastErrorPreviouslyAllocated(int32_t* status, std::string_view message, int32_t channel, - const wpi::Twine& previousAllocation); + std::string_view previousAllocation); } // namespace hal diff --git a/hal/src/main/native/athena/I2C.cpp b/hal/src/main/native/athena/I2C.cpp index 9af13ed46f..6e7f89bead 100644 --- a/hal/src/main/native/athena/I2C.cpp +++ b/hal/src/main/native/athena/I2C.cpp @@ -12,6 +12,8 @@ #include +#include + #include "DigitalInternal.h" #include "HALInitializer.h" #include "hal/DIO.h" @@ -56,7 +58,7 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { } int handle = open("/dev/i2c-2", O_RDWR); if (handle < 0) { - std::printf("Failed to open onboard i2c bus: %s\n", std::strerror(errno)); + fmt::print("Failed to open onboard i2c bus: {}\n", std::strerror(errno)); return; } i2COnBoardHandle = handle; @@ -79,7 +81,7 @@ void HAL_InitializeI2C(HAL_I2CPort port, int32_t* status) { digitalSystem->readEnableMXPSpecialFunction(status) | 0xC000, status); int handle = open("/dev/i2c-1", O_RDWR); if (handle < 0) { - std::printf("Failed to open MXP i2c bus: %s\n", std::strerror(errno)); + fmt::print("Failed to open MXP i2c bus: {}\n", std::strerror(errno)); return; } i2CMXPHandle = handle; diff --git a/hal/src/main/native/athena/PDP.cpp b/hal/src/main/native/athena/PDP.cpp index 0cdf30f831..3771bcef9b 100644 --- a/hal/src/main/native/athena/PDP.cpp +++ b/hal/src/main/native/athena/PDP.cpp @@ -4,6 +4,7 @@ #include "hal/PDP.h" +#include #include #include "HALInitializer.h" @@ -118,7 +119,7 @@ HAL_PDPHandle HAL_InitializePDP(int32_t module, int32_t* status) { hal::init::CheckInit(); if (!HAL_CheckPDPModule(module)) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Invalid pdp module " + wpi::Twine(module)); + hal::SetLastError(status, fmt::format("Invalid pdp module {}", module)); return HAL_kInvalidHandle; } @@ -194,7 +195,7 @@ double HAL_GetPDPChannelCurrent(HAL_PDPHandle handle, int32_t channel, int32_t* status) { if (!HAL_CheckPDPChannel(channel)) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Invalid pdp channel " + wpi::Twine(channel)); + hal::SetLastError(status, fmt::format("Invalid pdp channel {}", channel)); return 0; } diff --git a/hal/src/main/native/athena/PWM.cpp b/hal/src/main/native/athena/PWM.cpp index bf9773a6a2..6bb0fce09c 100644 --- a/hal/src/main/native/athena/PWM.cpp +++ b/hal/src/main/native/athena/PWM.cpp @@ -4,11 +4,11 @@ #include "hal/PWM.h" +#include #include +#include #include -#include - #include "ConstantsInternal.h" #include "DigitalInternal.h" #include "HALInitializer.h" @@ -138,8 +138,8 @@ void HAL_FreePWMPort(HAL_DigitalHandle pwmPortHandle, int32_t* status) { while (port.use_count() != 1) { auto current = hal::fpga_clock::now(); if (start + std::chrono::seconds(1) < current) { - wpi::outs() << "PWM handle free timeout\n"; - wpi::outs().flush(); + std::puts("PWM handle free timeout"); + std::fflush(stdout); break; } std::this_thread::yield(); diff --git a/hal/src/main/native/athena/SPI.cpp b/hal/src/main/native/athena/SPI.cpp index 090c53378e..1121fd88dd 100644 --- a/hal/src/main/native/athena/SPI.cpp +++ b/hal/src/main/native/athena/SPI.cpp @@ -11,10 +11,11 @@ #include #include +#include #include +#include #include -#include #include "DigitalInternal.h" #include "HALInitializer.h" @@ -78,14 +79,14 @@ static void CommonSPIPortInit(int32_t* status) { if ((digitalHandles[3] = HAL_InitializeDIOPort(createPortHandleForSPI(29), false, nullptr, status)) == HAL_kInvalidHandle) { - std::printf("Failed to allocate DIO 29 (MISO)\n"); + std::puts("Failed to allocate DIO 29 (MISO)"); return; } // MOSI if ((digitalHandles[4] = HAL_InitializeDIOPort(createPortHandleForSPI(30), false, nullptr, status)) == HAL_kInvalidHandle) { - std::printf("Failed to allocate DIO 30 (MOSI)\n"); + std::puts("Failed to allocate DIO 30 (MOSI)"); HAL_FreeDIOPort(digitalHandles[3]); // free the first port allocated return; } @@ -104,9 +105,10 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { hal::init::CheckInit(); if (port < 0 || port >= kSpiMaxHandles) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Serial port must be between 0 and " + - wpi::Twine(kSpiMaxHandles) + ". Requested " + - wpi::Twine(static_cast(port))); + hal::SetLastError( + status, + fmt::format("Serial port must be between 0 and {}. Requested {}", + kSpiMaxHandles, static_cast(port))); return; } @@ -123,8 +125,8 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { // CS0 is not a DIO port, so nothing to allocate handle = open("/dev/spidev0.0", O_RDWR); if (handle < 0) { - std::printf("Failed to open SPI port %d: %s\n", port, - std::strerror(errno)); + fmt::print("Failed to open SPI port {}: {}\n", port, + std::strerror(errno)); CommonSPIPortFree(); return; } @@ -139,14 +141,14 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { if ((digitalHandles[0] = HAL_InitializeDIOPort(createPortHandleForSPI(26), false, nullptr, status)) == HAL_kInvalidHandle) { - std::printf("Failed to allocate DIO 26 (CS1)\n"); + std::puts("Failed to allocate DIO 26 (CS1)"); CommonSPIPortFree(); return; } handle = open("/dev/spidev0.1", O_RDWR); if (handle < 0) { - std::printf("Failed to open SPI port %d: %s\n", port, - std::strerror(errno)); + fmt::print("Failed to open SPI port {}: {}\n", port, + std::strerror(errno)); CommonSPIPortFree(); HAL_FreeDIOPort(digitalHandles[0]); return; @@ -162,14 +164,14 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { if ((digitalHandles[1] = HAL_InitializeDIOPort(createPortHandleForSPI(27), false, nullptr, status)) == HAL_kInvalidHandle) { - std::printf("Failed to allocate DIO 27 (CS2)\n"); + std::puts("Failed to allocate DIO 27 (CS2)"); CommonSPIPortFree(); return; } handle = open("/dev/spidev0.2", O_RDWR); if (handle < 0) { - std::printf("Failed to open SPI port %d: %s\n", port, - std::strerror(errno)); + fmt::print("Failed to open SPI port {}: {}\n", port, + std::strerror(errno)); CommonSPIPortFree(); HAL_FreeDIOPort(digitalHandles[1]); return; @@ -185,14 +187,14 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { if ((digitalHandles[2] = HAL_InitializeDIOPort(createPortHandleForSPI(28), false, nullptr, status)) == HAL_kInvalidHandle) { - std::printf("Failed to allocate DIO 28 (CS3)\n"); + std::puts("Failed to allocate DIO 28 (CS3)"); CommonSPIPortFree(); return; } handle = open("/dev/spidev0.3", O_RDWR); if (handle < 0) { - std::printf("Failed to open SPI port %d: %s\n", port, - std::strerror(errno)); + fmt::print("Failed to open SPI port {}: {}\n", port, + std::strerror(errno)); CommonSPIPortFree(); HAL_FreeDIOPort(digitalHandles[2]); return; @@ -207,20 +209,20 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { if ((digitalHandles[5] = HAL_InitializeDIOPort(createPortHandleForSPI(14), false, nullptr, status)) == HAL_kInvalidHandle) { - wpi::outs() << "Failed to allocate DIO 14\n"; + std::puts("Failed to allocate DIO 14"); return; } if ((digitalHandles[6] = HAL_InitializeDIOPort(createPortHandleForSPI(15), false, nullptr, status)) == HAL_kInvalidHandle) { - wpi::outs() << "Failed to allocate DIO 15\n"; + std::puts("Failed to allocate DIO 15"); HAL_FreeDIOPort(digitalHandles[5]); // free the first port allocated return; } if ((digitalHandles[7] = HAL_InitializeDIOPort(createPortHandleForSPI(16), false, nullptr, status)) == HAL_kInvalidHandle) { - wpi::outs() << "Failed to allocate DIO 16\n"; + std::puts("Failed to allocate DIO 16"); HAL_FreeDIOPort(digitalHandles[5]); // free the first port allocated HAL_FreeDIOPort(digitalHandles[6]); // free the second port allocated return; @@ -228,7 +230,7 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { if ((digitalHandles[8] = HAL_InitializeDIOPort(createPortHandleForSPI(17), false, nullptr, status)) == HAL_kInvalidHandle) { - wpi::outs() << "Failed to allocate DIO 17\n"; + std::puts("Failed to allocate DIO 17"); HAL_FreeDIOPort(digitalHandles[5]); // free the first port allocated HAL_FreeDIOPort(digitalHandles[6]); // free the second port allocated HAL_FreeDIOPort(digitalHandles[7]); // free the third port allocated @@ -238,8 +240,8 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { digitalSystem->readEnableMXPSpecialFunction(status) | 0x00F0, status); handle = open("/dev/spidev1.0", O_RDWR); if (handle < 0) { - std::printf("Failed to open SPI port %d: %s\n", port, - std::strerror(errno)); + fmt::print("Failed to open SPI port {}: {}\n", port, + std::strerror(errno)); HAL_FreeDIOPort(digitalHandles[5]); // free the first port allocated HAL_FreeDIOPort(digitalHandles[6]); // free the second port allocated HAL_FreeDIOPort(digitalHandles[7]); // free the third port allocated @@ -251,7 +253,7 @@ void HAL_InitializeSPI(HAL_SPIPort port, int32_t* status) { default: *status = PARAMETER_OUT_OF_RANGE; hal::SetLastError( - status, "Invalid SPI port " + wpi::Twine(static_cast(port))); + status, fmt::format("Invalid SPI port {}", static_cast(port))); break; } } @@ -380,9 +382,10 @@ void HAL_SetSPIOpts(HAL_SPIPort port, HAL_Bool msbFirst, void HAL_SetSPIChipSelectActiveHigh(HAL_SPIPort port, int32_t* status) { if (port < 0 || port >= kSpiMaxHandles) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Serial port must be between 0 and " + - wpi::Twine(kSpiMaxHandles) + ". Requested " + - wpi::Twine(static_cast(port))); + hal::SetLastError( + status, + fmt::format("Serial port must be between 0 and {}. Requested {}", + kSpiMaxHandles, static_cast(port))); return; } @@ -398,9 +401,10 @@ void HAL_SetSPIChipSelectActiveHigh(HAL_SPIPort port, int32_t* status) { void HAL_SetSPIChipSelectActiveLow(HAL_SPIPort port, int32_t* status) { if (port < 0 || port >= kSpiMaxHandles) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Serial port must be between 0 and " + - wpi::Twine(kSpiMaxHandles) + ". Requested " + - wpi::Twine(static_cast(port))); + hal::SetLastError( + status, + fmt::format("Serial port must be between 0 and {}. Requested {}", + kSpiMaxHandles, static_cast(port))); return; } @@ -465,9 +469,10 @@ void HAL_SetSPIHandle(HAL_SPIPort port, int32_t handle) { void HAL_InitSPIAuto(HAL_SPIPort port, int32_t bufferSize, int32_t* status) { if (port < 0 || port >= kSpiMaxHandles) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Serial port must be between 0 and " + - wpi::Twine(kSpiMaxHandles) + ". Requested " + - wpi::Twine(static_cast(port))); + hal::SetLastError( + status, + fmt::format("Serial port must be between 0 and {}. Requested {}", + kSpiMaxHandles, static_cast(port))); return; } @@ -499,9 +504,10 @@ void HAL_InitSPIAuto(HAL_SPIPort port, int32_t bufferSize, int32_t* status) { void HAL_FreeSPIAuto(HAL_SPIPort port, int32_t* status) { if (port < 0 || port >= kSpiMaxHandles) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Serial port must be between 0 and " + - wpi::Twine(kSpiMaxHandles) + ". Requested " + - wpi::Twine(static_cast(port))); + hal::SetLastError( + status, + fmt::format("Serial port must be between 0 and {}. Requested {}", + kSpiMaxHandles, static_cast(port))); return; } @@ -605,16 +611,20 @@ void HAL_SetSPIAutoTransmitData(HAL_SPIPort port, const uint8_t* dataToSend, if (dataSize < 0 || dataSize > 32) { *status = PARAMETER_OUT_OF_RANGE; hal::SetLastError( - status, "Data size must be between 0 and 32 inclusive. Requested " + - wpi::Twine(dataSize)); + status, + fmt::format( + "Data size must be between 0 and 32 inclusive. Requested {}", + dataSize)); return; } if (zeroSize < 0 || zeroSize > 127) { *status = PARAMETER_OUT_OF_RANGE; hal::SetLastError( - status, "Zero size must be between 0 and 127 inclusive. Requested " + - wpi::Twine(zeroSize)); + status, + fmt::format( + "Zero size must be between 0 and 127 inclusive. Requested {}", + zeroSize)); return; } diff --git a/hal/src/main/native/athena/SerialPort.cpp b/hal/src/main/native/athena/SerialPort.cpp index dfacbecc7c..0163f6e48f 100644 --- a/hal/src/main/native/athena/SerialPort.cpp +++ b/hal/src/main/native/athena/SerialPort.cpp @@ -19,6 +19,8 @@ #include #include +#include + #include "HALInternal.h" #include "hal/cpp/SerialHelper.h" #include "hal/handles/HandlesInternal.h" @@ -184,7 +186,7 @@ void HAL_SetSerialBaudRate(HAL_SerialPortHandle handle, int32_t baud, BAUDCASE(4000000) default: *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Invalid BaudRate: " + wpi::Twine(baud)); + hal::SetLastError(status, fmt::format("Invalid BaudRate: {}", baud)); return; } int err = cfsetospeed(&port->tty, static_cast(port->baudRate)); @@ -227,7 +229,7 @@ void HAL_SetSerialDataBits(HAL_SerialPortHandle handle, int32_t bits, break; default: *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Invalid data bits: " + wpi::Twine(bits)); + hal::SetLastError(status, fmt::format("Invalid data bits: {}", bits)); return; } @@ -275,7 +277,7 @@ void HAL_SetSerialParity(HAL_SerialPortHandle handle, int32_t parity, break; default: *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Invalid parity bits: " + wpi::Twine(parity)); + hal::SetLastError(status, fmt::format("Invalid parity bits: {}", parity)); return; } @@ -303,7 +305,7 @@ void HAL_SetSerialStopBits(HAL_SerialPortHandle handle, int32_t stopBits, break; default: *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Invalid stop bits: " + wpi::Twine(stopBits)); + hal::SetLastError(status, fmt::format("Invalid stop bits: {}", stopBits)); return; } @@ -339,7 +341,7 @@ void HAL_SetSerialFlowControl(HAL_SerialPortHandle handle, int32_t flow, break; default: *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Invalid fc bits: " + wpi::Twine(flow)); + hal::SetLastError(status, fmt::format("Invalid fc bits: {}", flow)); return; } diff --git a/hal/src/main/native/athena/cpp/SerialHelper.cpp b/hal/src/main/native/athena/cpp/SerialHelper.cpp index 361a0ea1a0..3831769a2e 100644 --- a/hal/src/main/native/athena/cpp/SerialHelper.cpp +++ b/hal/src/main/native/athena/cpp/SerialHelper.cpp @@ -7,8 +7,9 @@ #include #include #include +#include -#include +#include #include #include "hal/Errors.h" @@ -53,7 +54,7 @@ std::string SerialHelper::GetVISASerialPortName(HAL_SerialPort port, return ""; // Error } else { - return m_visaResource[visaIndex].str(); + return std::string{m_visaResource[visaIndex].str()}; } } @@ -80,7 +81,7 @@ std::string SerialHelper::GetOSSerialPortName(HAL_SerialPort port, return ""; // Error } else { - return m_osResource[osIndex].str(); + return std::string{m_osResource[osIndex].str()}; } } @@ -136,8 +137,8 @@ void SerialHelper::SortHubPathVector() { std::sort(m_sortedHubPath.begin(), m_sortedHubPath.end(), [](const wpi::SmallVectorImpl& lhs, const wpi::SmallVectorImpl& rhs) -> int { - wpi::StringRef lhsRef(lhs.begin(), lhs.size()); - wpi::StringRef rhsRef(rhs.begin(), rhs.size()); + std::string_view lhsRef(lhs.begin(), lhs.size()); + std::string_view rhsRef(rhs.begin(), rhs.size()); return lhsRef.compare(rhsRef); }); } @@ -147,9 +148,9 @@ void SerialHelper::CoiteratedSort( wpi::SmallVector, 4> sortedVec; for (auto& str : m_sortedHubPath) { for (size_t i = 0; i < m_unsortedHubPath.size(); i++) { - if (wpi::StringRef{m_unsortedHubPath[i].begin(), - m_unsortedHubPath[i].size()} - .equals(wpi::StringRef{str.begin(), str.size()})) { + if (wpi::equals(std::string_view{m_unsortedHubPath[i].begin(), + m_unsortedHubPath[i].size()}, + std::string_view{str.begin(), str.size()})) { sortedVec.push_back(vec[i]); break; } @@ -206,14 +207,14 @@ void SerialHelper::QueryHubPaths(int32_t* status) { *status = 0; // split until (/dev/ - wpi::StringRef devNameRef = wpi::StringRef{osName}.split("(/dev/").second; + std::string_view devNameRef = wpi::split(osName, "(/dev/").second; // String not found, continue - if (devNameRef.equals("")) + if (wpi::equals(devNameRef, "")) continue; // Split at ) - wpi::StringRef matchString = devNameRef.split(')').first; - if (matchString.equals(devNameRef)) + std::string_view matchString = wpi::split(devNameRef, ')').first; + if (wpi::equals(matchString, devNameRef)) continue; // Search directories to get a list of system accessors @@ -223,7 +224,7 @@ void SerialHelper::QueryHubPaths(int32_t* status) { for (auto& p : fs::recursive_directory_iterator("/sys/devices/soc0", ec)) { if (ec) break; - std::string path = p.path().string(); + std::string path = p.path(); if (path.find("amba") == std::string::npos) continue; if (path.find("usb") == std::string::npos) @@ -231,22 +232,22 @@ void SerialHelper::QueryHubPaths(int32_t* status) { if (path.find(matchString) == std::string::npos) continue; - wpi::SmallVector pathSplitVec; + wpi::SmallVector pathSplitVec; // Split path into individual directories - wpi::StringRef{path}.split(pathSplitVec, '/', -1, false); + wpi::split(path, pathSplitVec, '/', -1, false); // Find each individual item index int findusb = -1; int findtty = -1; int findregex = -1; for (size_t i = 0; i < pathSplitVec.size(); i++) { - if (findusb == -1 && pathSplitVec[i].equals("usb1")) { + if (findusb == -1 && wpi::equals(pathSplitVec[i], "usb1")) { findusb = i; } - if (findtty == -1 && pathSplitVec[i].equals("tty")) { + if (findtty == -1 && wpi::equals(pathSplitVec[i], "tty")) { findtty = i; } - if (findregex == -1 && pathSplitVec[i].equals(matchString)) { + if (findregex == -1 && wpi::equals(pathSplitVec[i], matchString)) { findregex = i; } } @@ -263,10 +264,10 @@ void SerialHelper::QueryHubPaths(int32_t* status) { // Add our devices to our list m_unsortedHubPath.emplace_back( - wpi::StringRef{pathSplitVec[hubIndex - 2]}); + std::string_view{pathSplitVec[hubIndex - 2]}); m_visaResource.emplace_back(desc); m_osResource.emplace_back( - wpi::StringRef{osName}.split("(").second.split(")").first); + wpi::split(wpi::split(osName, "(").second, ")").first); break; } } @@ -291,8 +292,9 @@ int32_t SerialHelper::GetIndexForPort(HAL_SerialPort port, int32_t* status) { if (portString.empty()) { for (size_t i = 0; i < 2; i++) { // Remove all used ports - auto idx = std::find(m_sortedHubPath.begin(), m_sortedHubPath.end(), - m_usbNames[i]); + auto idx = std::find_if( + m_sortedHubPath.begin(), m_sortedHubPath.end(), + [&](const auto& s) { return wpi::equals(s, m_usbNames[i]); }); if (idx != m_sortedHubPath.end()) { // found m_sortedHubPath.erase(idx); @@ -327,7 +329,7 @@ int32_t SerialHelper::GetIndexForPort(HAL_SerialPort port, int32_t* status) { int retIndex = -1; for (size_t i = 0; i < m_sortedHubPath.size(); i++) { - if (m_sortedHubPath[i].equals(portString)) { + if (wpi::equals(m_sortedHubPath[i], portString)) { retIndex = i; break; } diff --git a/hal/src/main/native/cpp/ErrorHandling.cpp b/hal/src/main/native/cpp/ErrorHandling.cpp index fa54e4676e..ad1b40b5bd 100644 --- a/hal/src/main/native/cpp/ErrorHandling.cpp +++ b/hal/src/main/native/cpp/ErrorHandling.cpp @@ -2,8 +2,8 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include #include -#include #include "hal/Errors.h" #include "hal/HALBase.h" @@ -21,31 +21,30 @@ static LastErrorStorage& GetThreadLastError() { } namespace hal { -void SetLastError(int32_t* status, const wpi::Twine& value) { +void SetLastError(int32_t* status, std::string_view value) { LastErrorStorage& lastError = GetThreadLastError(); - lastError.message.clear(); - value.toVector(lastError.message); + lastError.message = value; lastError.status = *status; *status = HAL_USE_LAST_ERROR; } -void SetLastErrorIndexOutOfRange(int32_t* status, const wpi::Twine& message, +void SetLastErrorIndexOutOfRange(int32_t* status, std::string_view message, int32_t minimum, int32_t maximum, int32_t requested) { - SetLastError(status, message + "\n Status: " + wpi::Twine(*status) + - "\n Minimum: " + wpi::Twine(minimum) + - " Maximum: " + wpi::Twine(maximum) + - " Reequested: " + wpi::Twine(requested)); + SetLastError( + status, + fmt::format("{}\n Status: {}\n Minimum: {} Maximum: {} Requested: {}", + message, *status, minimum, maximum, requested)); } -void SetLastErrorPreviouslyAllocated(int32_t* status, const wpi::Twine& message, +void SetLastErrorPreviouslyAllocated(int32_t* status, std::string_view message, int32_t channel, - const wpi::Twine& previousAllocation) { - hal::SetLastError( - status, - message + " " + wpi::Twine(channel) + - " previously allocated.\nLocation of the previous allocation:\n" + - previousAllocation + "\nLocation of the current allocation:"); + std::string_view previousAllocation) { + hal::SetLastError(status, + fmt::format("{} {} previously allocated.\n" + "Location of the previous allocation:\n{}\n" + "Location of the current allocation:", + message, channel, previousAllocation)); } } // namespace hal diff --git a/hal/src/main/native/cpp/cpp/fpga_clock.cpp b/hal/src/main/native/cpp/cpp/fpga_clock.cpp index 6ca623c257..550596a8ac 100644 --- a/hal/src/main/native/cpp/cpp/fpga_clock.cpp +++ b/hal/src/main/native/cpp/cpp/fpga_clock.cpp @@ -4,9 +4,10 @@ #include "hal/cpp/fpga_clock.h" +#include #include -#include +#include #include "hal/HALBase.h" @@ -19,11 +20,12 @@ fpga_clock::time_point fpga_clock::now() noexcept { int32_t status = 0; uint64_t currentTime = HAL_GetFPGATime(&status); if (status != 0) { - wpi::errs() - << "Call to HAL_GetFPGATime failed in fpga_clock::now() with status " - << status - << ". Initialization might have failed. Time will not be correct\n"; - wpi::errs().flush(); + fmt::print( + stderr, + "Call to HAL_GetFPGATime failed in fpga_clock::now() with status {}. " + "Initialization might have failed. Time will not be correct\n", + status); + std::fflush(stderr); return epoch(); } return time_point(std::chrono::microseconds(currentTime)); diff --git a/hal/src/main/native/cpp/jni/CANAPIJNI.cpp b/hal/src/main/native/cpp/jni/CANAPIJNI.cpp index 71804afa0c..106167abf0 100644 --- a/hal/src/main/native/cpp/jni/CANAPIJNI.cpp +++ b/hal/src/main/native/cpp/jni/CANAPIJNI.cpp @@ -6,9 +6,7 @@ #include -#include #include -#include #include "HALUtil.h" #include "edu_wpi_first_hal_CANAPIJNI.h" diff --git a/hal/src/main/native/cpp/jni/CANJNI.cpp b/hal/src/main/native/cpp/jni/CANJNI.cpp index b430012753..3eeedc6425 100644 --- a/hal/src/main/native/cpp/jni/CANJNI.cpp +++ b/hal/src/main/native/cpp/jni/CANJNI.cpp @@ -6,9 +6,7 @@ #include -#include #include -#include #include "HALUtil.h" #include "edu_wpi_first_hal_can_CANJNI.h" @@ -65,8 +63,8 @@ Java_edu_wpi_first_hal_can_CANJNI_FRCNetCommCANSessionMuxReceiveMessage return nullptr; } return MakeJByteArray(env, - wpi::StringRef{reinterpret_cast(buffer), - static_cast(dataSize)}); + std::string_view{reinterpret_cast(buffer), + static_cast(dataSize)}); } /* diff --git a/hal/src/main/native/cpp/jni/HAL.cpp b/hal/src/main/native/cpp/jni/HAL.cpp index 4787ca85d6..4e260324c9 100644 --- a/hal/src/main/native/cpp/jni/HAL.cpp +++ b/hal/src/main/native/cpp/jni/HAL.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include "HALUtil.h" @@ -227,13 +228,11 @@ Java_edu_wpi_first_hal_HAL_getJoystickAxes jsize javaSize = env->GetArrayLength(axesArray); if (axes.count > javaSize) { - wpi::SmallString<128> errStr; - wpi::raw_svector_ostream oss{errStr}; - oss << "Native array size larger then passed in java array size " - << "Native Size: " << static_cast(axes.count) - << " Java Size: " << static_cast(javaSize); - - ThrowIllegalArgumentException(env, errStr.str()); + ThrowIllegalArgumentException( + env, + fmt::format("Native array size larger then passed in java array " + "size\nNative Size: {} Java Size: {}", + static_cast(axes.count), static_cast(javaSize))); return 0; } @@ -256,13 +255,11 @@ Java_edu_wpi_first_hal_HAL_getJoystickPOVs jsize javaSize = env->GetArrayLength(povsArray); if (povs.count > javaSize) { - wpi::SmallString<128> errStr; - wpi::raw_svector_ostream oss{errStr}; - oss << "Native array size larger then passed in java array size " - << "Native Size: " << static_cast(povs.count) - << " Java Size: " << static_cast(javaSize); - - ThrowIllegalArgumentException(env, errStr.str()); + ThrowIllegalArgumentException( + env, + fmt::format("Native array size larger then passed in java array " + "size\nNative Size: {} Java Size: {}", + static_cast(povs.count), static_cast(javaSize))); return 0; } diff --git a/hal/src/main/native/cpp/jni/HALUtil.cpp b/hal/src/main/native/cpp/jni/HALUtil.cpp index 9894942f12..1cf7cbb3d0 100644 --- a/hal/src/main/native/cpp/jni/HALUtil.cpp +++ b/hal/src/main/native/cpp/jni/HALUtil.cpp @@ -12,9 +12,8 @@ #include #include -#include +#include #include -#include #include "edu_wpi_first_hal_HALUtil.h" #include "hal/CAN.h" @@ -72,7 +71,7 @@ static const JExceptionInit exceptions[] = { namespace hal { -void ThrowUncleanStatusException(JNIEnv* env, wpi::StringRef msg, +void ThrowUncleanStatusException(JNIEnv* env, std::string_view msg, int32_t status) { static jmethodID func = env->GetMethodID(uncleanStatusExCls, "", "(ILjava/lang/String;)V"); @@ -85,20 +84,14 @@ void ThrowUncleanStatusException(JNIEnv* env, wpi::StringRef msg, void ThrowAllocationException(JNIEnv* env, const char* lastError, int32_t status) { - wpi::SmallString<1024> buf; - wpi::raw_svector_ostream oss(buf); - - oss << "Code: " << status << '\n' << lastError; - - allocationExCls.Throw(env, buf.c_str()); + allocationExCls.Throw(env, + fmt::format("Code: {}\n{}", status, lastError).c_str()); } void ThrowHalHandleException(JNIEnv* env, int32_t status) { const char* message = HAL_GetLastError(&status); - wpi::SmallString<1024> buf; - wpi::raw_svector_ostream oss(buf); - oss << " Code: " << status << ". " << message; - halHandleExCls.Throw(env, buf.c_str()); + halHandleExCls.Throw(env, + fmt::format(" Code: {}. {}", status, message).c_str()); } void ReportError(JNIEnv* env, int32_t status, bool doThrow) { @@ -111,16 +104,14 @@ void ReportError(JNIEnv* env, int32_t status, bool doThrow) { return; } if (doThrow && status < 0) { - wpi::SmallString<1024> buf; - wpi::raw_svector_ostream oss(buf); - oss << " Code: " << status << ". " << message; - ThrowUncleanStatusException(env, buf.c_str(), status); + ThrowUncleanStatusException( + env, fmt::format(" Code: {}. {}", status, message).c_str(), status); } else { std::string func; auto stack = GetJavaStackTrace(env, &func, "edu.wpi.first"); // Make a copy of message for safety, calling back into the HAL might // invalidate the string. - wpi::SmallString<256> lastMessage{wpi::StringRef{message}}; + std::string lastMessage{message}; HAL_SendError(1, status, 0, lastMessage.c_str(), func.c_str(), stack.c_str(), 1); } @@ -141,10 +132,8 @@ void ThrowError(JNIEnv* env, int32_t status, int32_t minRange, int32_t maxRange, ThrowHalHandleException(env, status); return; } - wpi::SmallString<1024> buf; - wpi::raw_svector_ostream oss(buf); - oss << " Code: " << status << ". " << lastError; - ThrowUncleanStatusException(env, buf.c_str(), status); + ThrowUncleanStatusException( + env, fmt::format(" Code: {}. {}", status, lastError).c_str(), status); } void ReportCANError(JNIEnv* env, int32_t status, int message_id) { @@ -181,10 +170,8 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) { } case HAL_ERR_CANSessionMux_NotAllowed: case kRIOStatusFeatureNotSupported: { - wpi::SmallString<100> buf; - wpi::raw_svector_ostream oss(buf); - oss << "MessageID = " << message_id; - canMessageNotAllowedExCls.Throw(env, buf.c_str()); + canMessageNotAllowedExCls.Throw( + env, fmt::format("MessageID = {}", message_id).c_str()); break; } case HAL_ERR_CANSessionMux_NotInitialized: @@ -200,16 +187,14 @@ void ReportCANError(JNIEnv* env, int32_t status, int message_id) { break; } default: { - wpi::SmallString<100> buf; - wpi::raw_svector_ostream oss(buf); - oss << "Fatal status code detected: " << status; - uncleanStatusExCls.Throw(env, buf.c_str()); + uncleanStatusExCls.Throw( + env, fmt::format("Fatal status code detected: {}", status).c_str()); break; } } } -void ThrowIllegalArgumentException(JNIEnv* env, wpi::StringRef msg) { +void ThrowIllegalArgumentException(JNIEnv* env, std::string_view msg) { illegalArgExCls.Throw(env, msg); } @@ -266,9 +251,9 @@ void SetMatchInfoObject(JNIEnv* env, jobject matchStatus, env->CallVoidMethod( matchStatus, func, MakeJString(env, matchInfo.eventName), - MakeJString(env, wpi::StringRef{reinterpret_cast( - matchInfo.gameSpecificMessage), - matchInfo.gameSpecificMessageSize}), + MakeJString(env, + {reinterpret_cast(matchInfo.gameSpecificMessage), + matchInfo.gameSpecificMessageSize}), static_cast(matchInfo.matchNumber), static_cast(matchInfo.replayNumber), static_cast(matchInfo.matchType)); diff --git a/hal/src/main/native/cpp/jni/HALUtil.h b/hal/src/main/native/cpp/jni/HALUtil.h index c56c36d5d1..56faa88f1c 100644 --- a/hal/src/main/native/cpp/jni/HALUtil.h +++ b/hal/src/main/native/cpp/jni/HALUtil.h @@ -8,7 +8,7 @@ #include #include -#include +#include struct HAL_MatchInfo; struct HAL_Value; @@ -51,7 +51,7 @@ inline bool CheckCANStatus(JNIEnv* env, int32_t status, int32_t message_id) { return status == 0; } -void ThrowIllegalArgumentException(JNIEnv* env, wpi::StringRef msg); +void ThrowIllegalArgumentException(JNIEnv* env, std::string_view msg); void ThrowBoundaryException(JNIEnv* env, double value, double lower, double upper); diff --git a/hal/src/main/native/cpp/jni/SimDeviceJNI.cpp b/hal/src/main/native/cpp/jni/SimDeviceJNI.cpp index e036174eb4..f681e71009 100644 --- a/hal/src/main/native/cpp/jni/SimDeviceJNI.cpp +++ b/hal/src/main/native/cpp/jni/SimDeviceJNI.cpp @@ -96,7 +96,7 @@ Java_edu_wpi_first_hal_SimDeviceJNI_createSimValueEnum if (!elem) { return 0; } - arr.push_back(JStringRef{env, elem}.str()); + arr.emplace_back(JStringRef{env, elem}.str()); } wpi::SmallVector carr; for (auto&& val : arr) { @@ -129,7 +129,7 @@ Java_edu_wpi_first_hal_SimDeviceJNI_createSimValueEnumDouble if (!elem) { return 0; } - arr.push_back(JStringRef{env, elem}.str()); + arr.emplace_back(JStringRef{env, elem}.str()); } wpi::SmallVector carr; diff --git a/hal/src/main/native/cpp/jni/simulation/BufferCallbackStore.cpp b/hal/src/main/native/cpp/jni/simulation/BufferCallbackStore.cpp index 8f4c141d2b..265b363e17 100644 --- a/hal/src/main/native/cpp/jni/simulation/BufferCallbackStore.cpp +++ b/hal/src/main/native/cpp/jni/simulation/BufferCallbackStore.cpp @@ -6,6 +6,8 @@ #include +#include + #include #include "SimulatorJNI.h" @@ -46,18 +48,18 @@ void BufferCallbackStore::performCallback(const char* name, uint8_t* buffer, didAttachThread = true; if (vm->AttachCurrentThread(reinterpret_cast(&env), nullptr) != 0) { // Failed to attach, log and return - wpi::outs() << "Failed to attach\n"; - wpi::outs().flush(); + std::puts("Failed to attach"); + std::fflush(stdout); return; } } else if (tryGetEnv == JNI_EVERSION) { - wpi::outs() << "Invalid JVM Version requested\n"; - wpi::outs().flush(); + std::puts("Invalid JVM Version requested"); + std::fflush(stdout); } - auto toCallbackArr = - MakeJByteArray(env, wpi::StringRef{reinterpret_cast(buffer), - static_cast(length)}); + auto toCallbackArr = MakeJByteArray( + env, std::string_view{reinterpret_cast(buffer), + static_cast(length)}); env->CallVoidMethod(m_call, sim::GetBufferCallback(), MakeJString(env, name), toCallbackArr, static_cast(length)); diff --git a/hal/src/main/native/cpp/jni/simulation/CallbackStore.cpp b/hal/src/main/native/cpp/jni/simulation/CallbackStore.cpp index 24426957d5..46e032015d 100644 --- a/hal/src/main/native/cpp/jni/simulation/CallbackStore.cpp +++ b/hal/src/main/native/cpp/jni/simulation/CallbackStore.cpp @@ -6,6 +6,8 @@ #include +#include + #include #include "SimulatorJNI.h" @@ -45,13 +47,13 @@ void CallbackStore::performCallback(const char* name, const HAL_Value* value) { didAttachThread = true; if (vm->AttachCurrentThread(reinterpret_cast(&env), nullptr) != 0) { // Failed to attach, log and return - wpi::outs() << "Failed to attach\n"; - wpi::outs().flush(); + std::puts("Failed to attach"); + std::fflush(stdout); return; } } else if (tryGetEnv == JNI_EVERSION) { - wpi::outs() << "Invalid JVM Version requested\n"; - wpi::outs().flush(); + std::puts("Invalid JVM Version requested"); + std::fflush(stdout); } env->CallVoidMethod(m_call, sim::GetNotifyCallback(), MakeJString(env, name), diff --git a/hal/src/main/native/cpp/jni/simulation/ConstBufferCallbackStore.cpp b/hal/src/main/native/cpp/jni/simulation/ConstBufferCallbackStore.cpp index 1172c649e8..cba0a5b196 100644 --- a/hal/src/main/native/cpp/jni/simulation/ConstBufferCallbackStore.cpp +++ b/hal/src/main/native/cpp/jni/simulation/ConstBufferCallbackStore.cpp @@ -6,6 +6,8 @@ #include +#include + #include #include "SimulatorJNI.h" @@ -47,18 +49,18 @@ void ConstBufferCallbackStore::performCallback(const char* name, didAttachThread = true; if (vm->AttachCurrentThread(reinterpret_cast(&env), nullptr) != 0) { // Failed to attach, log and return - wpi::outs() << "Failed to attach\n"; - wpi::outs().flush(); + std::puts("Failed to attach"); + std::fflush(stdout); return; } } else if (tryGetEnv == JNI_EVERSION) { - wpi::outs() << "Invalid JVM Version requested\n"; - wpi::outs().flush(); + std::puts("Invalid JVM Version requested"); + std::fflush(stdout); } - auto toCallbackArr = - MakeJByteArray(env, wpi::StringRef{reinterpret_cast(buffer), - static_cast(length)}); + auto toCallbackArr = MakeJByteArray( + env, std::string_view{reinterpret_cast(buffer), + static_cast(length)}); env->CallVoidMethod(m_call, sim::GetConstBufferCallback(), MakeJString(env, name), toCallbackArr, diff --git a/hal/src/main/native/cpp/jni/simulation/SimDeviceDataJNI.cpp b/hal/src/main/native/cpp/jni/simulation/SimDeviceDataJNI.cpp index a07e8af15c..51a3f0746c 100644 --- a/hal/src/main/native/cpp/jni/simulation/SimDeviceDataJNI.cpp +++ b/hal/src/main/native/cpp/jni/simulation/SimDeviceDataJNI.cpp @@ -6,6 +6,7 @@ #include +#include #include #include @@ -134,13 +135,13 @@ void DeviceCallbackStore::performCallback(const char* name, didAttachThread = true; if (vm->AttachCurrentThread(reinterpret_cast(&env), nullptr) != 0) { // Failed to attach, log and return - wpi::outs() << "Failed to attach\n"; - wpi::outs().flush(); + std::puts("Failed to attach"); + std::fflush(stdout); return; } } else if (tryGetEnv == JNI_EVERSION) { - wpi::outs() << "Invalid JVM Version requested\n"; - wpi::outs().flush(); + std::puts("Invalid JVM Version requested"); + std::fflush(stdout); } env->CallVoidMethod(m_call, simDeviceCallbackCallback, MakeJString(env, name), @@ -168,13 +169,13 @@ void ValueCallbackStore::performCallback(const char* name, didAttachThread = true; if (vm->AttachCurrentThread(reinterpret_cast(&env), nullptr) != 0) { // Failed to attach, log and return - wpi::outs() << "Failed to attach\n"; - wpi::outs().flush(); + std::puts("Failed to attach"); + std::fflush(stdout); return; } } else if (tryGetEnv == JNI_EVERSION) { - wpi::outs() << "Invalid JVM Version requested\n"; - wpi::outs().flush(); + std::puts("Invalid JVM Version requested"); + std::fflush(stdout); } auto [value1, value2] = ToValue12(value); diff --git a/hal/src/main/native/cpp/jni/simulation/SpiReadAutoReceiveBufferCallbackStore.cpp b/hal/src/main/native/cpp/jni/simulation/SpiReadAutoReceiveBufferCallbackStore.cpp index 67121345cd..8d43e6fa2f 100644 --- a/hal/src/main/native/cpp/jni/simulation/SpiReadAutoReceiveBufferCallbackStore.cpp +++ b/hal/src/main/native/cpp/jni/simulation/SpiReadAutoReceiveBufferCallbackStore.cpp @@ -6,6 +6,8 @@ #include +#include + #include #include "SimulatorJNI.h" @@ -47,13 +49,13 @@ int32_t SpiReadAutoReceiveBufferCallbackStore::performCallback( didAttachThread = true; if (vm->AttachCurrentThread(reinterpret_cast(&env), nullptr) != 0) { // Failed to attach, log and return - wpi::outs() << "Failed to attach\n"; - wpi::outs().flush(); + std::puts("Failed to attach"); + std::fflush(stdout); return -1; } } else if (tryGetEnv == JNI_EVERSION) { - wpi::outs() << "Invalid JVM Version requested\n"; - wpi::outs().flush(); + std::puts("Invalid JVM Version requested"); + std::fflush(stdout); } auto toCallbackArr = MakeJIntArray( diff --git a/hal/src/main/native/include/hal/.clang-tidy b/hal/src/main/native/include/hal/.clang-tidy index a7388ad83d..4f4edda0f0 100644 --- a/hal/src/main/native/include/hal/.clang-tidy +++ b/hal/src/main/native/include/hal/.clang-tidy @@ -72,4 +72,4 @@ Checks: FormatStyle: file CheckOptions: - key: bugprone-dangling-handle - value: 'wpi::StringRef;wpi::Twine' + value: 'std::string_view' diff --git a/hal/src/main/native/sim/AddressableLED.cpp b/hal/src/main/native/sim/AddressableLED.cpp index 2ddc38271a..75a09fbb17 100644 --- a/hal/src/main/native/sim/AddressableLED.cpp +++ b/hal/src/main/native/sim/AddressableLED.cpp @@ -4,6 +4,8 @@ #include "hal/AddressableLED.h" +#include + #include "DigitalInternal.h" #include "HALInitializer.h" #include "HALInternal.h" @@ -113,9 +115,11 @@ void HAL_SetAddressableLEDLength(HAL_AddressableLEDHandle handle, } if (length > HAL_kAddressableLEDMaxLength || length < 0) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "LED length must be less than or equal to " + - wpi::Twine(HAL_kAddressableLEDMaxLength) + - ". " + wpi::Twine(length) + " was requested"); + hal::SetLastError( + status, + fmt::format( + "LED length must be less than or equal to {}. {} was requested", + HAL_kAddressableLEDMaxLength, length)); return; } SimAddressableLEDData[led->index].length = length; @@ -131,10 +135,11 @@ void HAL_WriteAddressableLEDData(HAL_AddressableLEDHandle handle, } if (length > SimAddressableLEDData[led->index].length) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, - "Data length must be less than or equal to " + - wpi::Twine(SimAddressableLEDData[led->index].length) + - ". " + wpi::Twine(length) + " was requested"); + hal::SetLastError( + status, + fmt::format( + "Data length must be less than or equal to {}. {} was requested", + SimAddressableLEDData[led->index].length, length)); return; } SimAddressableLEDData[led->index].SetData(data, length); diff --git a/hal/src/main/native/sim/DriverStation.cpp b/hal/src/main/native/sim/DriverStation.cpp index e4a491327a..d02319f93f 100644 --- a/hal/src/main/native/sim/DriverStation.cpp +++ b/hal/src/main/native/sim/DriverStation.cpp @@ -13,9 +13,9 @@ #include #include +#include #include #include -#include #include "HALInitializer.h" #include "hal/cpp/fpga_clock.h" @@ -83,14 +83,16 @@ int32_t HAL_SendError(HAL_Bool isError, int32_t errorCode, HAL_Bool isLVCode, if (i == KEEP_MSGS || (curTime - prevMsgTime[i]) >= std::chrono::seconds(1)) { printMsg = true; if (printMsg) { + fmt::memory_buffer buf; if (location && location[0] != '\0') { - std::fprintf(stderr, "%s at %s: ", isError ? "Error" : "Warning", - location); + fmt::format_to(buf, "{} at {}: ", isError ? "Error" : "Warning", + location); } - std::fprintf(stderr, "%s\n", details); + fmt::format_to(buf, "{}\n", details); if (callStack && callStack[0] != '\0') { - std::fprintf(stderr, "%s\n", callStack); + fmt::format_to(buf, "{}\n", callStack); } + std::fwrite(buf.data(), buf.size(), 1, stderr); } if (i == KEEP_MSGS) { // replace the oldest one @@ -114,8 +116,8 @@ int32_t HAL_SendConsoleLine(const char* line) { if (handler) { return handler(line); } - wpi::outs() << line << "\n"; - wpi::outs().flush(); + std::puts(line); + std::fflush(stdout); return 0; } diff --git a/hal/src/main/native/sim/Extensions.cpp b/hal/src/main/native/sim/Extensions.cpp index ce9dcbfbea..9131bcb809 100644 --- a/hal/src/main/native/sim/Extensions.cpp +++ b/hal/src/main/native/sim/Extensions.cpp @@ -4,12 +4,14 @@ #include "hal/Extensions.h" +#include +#include #include -#include -#include +#include +#include +#include #include -#include #include #if defined(WIN32) || defined(_WIN32) @@ -24,7 +26,7 @@ #define DLOPEN(a) LoadLibraryA(a) #define DLSYM GetProcAddress #define DLCLOSE FreeLibrary -#define DLERROR "error #" << GetLastError() +#define DLERROR fmt::format("error #{}", GetLastError()) #else #define DELIM ':' #define HTYPE void* @@ -53,30 +55,26 @@ extern "C" { int HAL_LoadOneExtension(const char* library) { int rc = 1; // It is expected and reasonable not to find an extra simulation - wpi::outs() << "HAL Extensions: Attempting to load: " - << fs::path{library}.stem().string() << "\n"; - wpi::outs().flush(); + fmt::print("HAL Extensions: Attempting to load: {}\n", + fs::path{library}.stem().string()); + std::fflush(stdout); HTYPE handle = DLOPEN(library); #if !defined(WIN32) && !defined(_WIN32) if (!handle) { - wpi::SmallString<128> libraryName("lib"); - libraryName += library; #if defined(__APPLE__) - libraryName += ".dylib"; + auto libraryName = fmt::format("lib{}.dylib", library); #else - libraryName += ".so"; + auto libraryName = fmt::format("lib{}.so", library); #endif - wpi::outs() << "HAL Extensions: Load failed: " << DLERROR - << "\nTrying modified name: " - << fs::path{libraryName.str()}.stem() << "\n"; - wpi::outs().flush(); + fmt::print("HAL Extensions: Load failed: {}\nTrying modified name: {}\n", + DLERROR, fs::path{libraryName}.stem().string()); + std::fflush(stdout); handle = DLOPEN(libraryName.c_str()); } #endif if (!handle) { - wpi::outs() << "HAL Extensions: Failed to load library: " << DLERROR - << '\n'; - wpi::outs().flush(); + fmt::print("HAL Extensions: Failed to load library: {}\n", DLERROR); + std::fflush(stdout); return rc; } @@ -88,32 +86,30 @@ int HAL_LoadOneExtension(const char* library) { } if (rc != 0) { - wpi::outs() << "HAL Extensions: Failed to load extension\n"; - wpi::outs().flush(); + std::puts("HAL Extensions: Failed to load extension"); + std::fflush(stdout); DLCLOSE(handle); } else { - wpi::outs() << "HAL Extensions: Successfully loaded extension\n"; - wpi::outs().flush(); + std::puts("HAL Extensions: Successfully loaded extension"); + std::fflush(stdout); } return rc; } int HAL_LoadExtensions(void) { int rc = 1; - wpi::SmallVector libraries; + wpi::SmallVector libraries; const char* e = std::getenv("HALSIM_EXTENSIONS"); if (!e) { if (GetShowNotFoundMessage()) { - wpi::outs() << "HAL Extensions: No extensions found\n"; - wpi::outs().flush(); + std::puts("HAL Extensions: No extensions found"); + std::fflush(stdout); } return rc; } - wpi::StringRef env{e}; - env.split(libraries, DELIM, -1, false); - for (auto& libref : libraries) { - wpi::SmallString<128> library(libref); - rc = HAL_LoadOneExtension(library.c_str()); + wpi::split(e, libraries, DELIM, -1, false); + for (auto& library : libraries) { + rc = HAL_LoadOneExtension(std::string(library).c_str()); if (rc < 0) { break; } diff --git a/hal/src/main/native/sim/HAL.cpp b/hal/src/main/native/sim/HAL.cpp index b6f9b4379d..0df981ad2e 100644 --- a/hal/src/main/native/sim/HAL.cpp +++ b/hal/src/main/native/sim/HAL.cpp @@ -4,10 +4,10 @@ #include "hal/HAL.h" +#include #include #include -#include #include #ifdef _WIN32 @@ -351,7 +351,11 @@ HAL_Bool HAL_Initialize(int32_t timeout, int32_t mode) { } #endif // _WIN32 - wpi::outs().SetUnbuffered(); +#ifndef _WIN32 + setlinebuf(stdin); + setlinebuf(stdout); +#endif + if (HAL_LoadExtensions() < 0) { return false; } diff --git a/hal/src/main/native/sim/HALInternal.h b/hal/src/main/native/sim/HALInternal.h index 28dcdc293a..7a7863a474 100644 --- a/hal/src/main/native/sim/HALInternal.h +++ b/hal/src/main/native/sim/HALInternal.h @@ -6,14 +6,14 @@ #include -#include +#include namespace hal { -void SetLastError(int32_t* status, const wpi::Twine& value); -void SetLastErrorIndexOutOfRange(int32_t* status, const wpi::Twine& message, +void SetLastError(int32_t* status, std::string_view value); +void SetLastErrorIndexOutOfRange(int32_t* status, std::string_view message, int32_t minimum, int32_t maximum, int32_t channel); -void SetLastErrorPreviouslyAllocated(int32_t* status, const wpi::Twine& message, +void SetLastErrorPreviouslyAllocated(int32_t* status, std::string_view message, int32_t channel, - const wpi::Twine& previousAllocation); + std::string_view previousAllocation); } // namespace hal diff --git a/hal/src/main/native/sim/MockHooks.cpp b/hal/src/main/native/sim/MockHooks.cpp index e4751f7d76..4e20c6acf5 100644 --- a/hal/src/main/native/sim/MockHooks.cpp +++ b/hal/src/main/native/sim/MockHooks.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include "MockHooksInternal.h" @@ -83,7 +84,7 @@ void HALSIM_WaitForProgramStart(void) { int count = 0; while (!programStarted) { count++; - std::printf("Waiting for program start signal: %d\n", count); + fmt::print("Waiting for program start signal: {}\n", count); std::this_thread::sleep_for(std::chrono::milliseconds(500)); } } diff --git a/hal/src/main/native/sim/PDP.cpp b/hal/src/main/native/sim/PDP.cpp index aa08ca0dfa..f6c6bcb380 100644 --- a/hal/src/main/native/sim/PDP.cpp +++ b/hal/src/main/native/sim/PDP.cpp @@ -4,6 +4,8 @@ #include "hal/PDP.h" +#include + #include "CANAPIInternal.h" #include "HALInitializer.h" #include "HALInternal.h" @@ -28,7 +30,7 @@ extern "C" { HAL_PDPHandle HAL_InitializePDP(int32_t module, int32_t* status) { if (!HAL_CheckPDPModule(module)) { *status = PARAMETER_OUT_OF_RANGE; - hal::SetLastError(status, "Invalid pdp module " + wpi::Twine(module)); + hal::SetLastError(status, fmt::format("Invalid pdp module {}", module)); return HAL_kInvalidHandle; } hal::init::CheckInit(); diff --git a/hal/src/main/native/sim/SimDevice.cpp b/hal/src/main/native/sim/SimDevice.cpp index 3b95555c26..b6c637cedc 100644 --- a/hal/src/main/native/sim/SimDevice.cpp +++ b/hal/src/main/native/sim/SimDevice.cpp @@ -4,8 +4,7 @@ #include "hal/SimDevice.h" -#include -#include +#include #include "HALInitializer.h" #include "mockdata/SimDeviceDataInternal.h" @@ -66,19 +65,12 @@ void HAL_ResetSimValue(HAL_SimValueHandle handle) { } hal::SimDevice::SimDevice(const char* name, int index) { - wpi::SmallString<128> fullname; - wpi::raw_svector_ostream os(fullname); - os << name << '[' << index << ']'; - - m_handle = HAL_CreateSimDevice(fullname.c_str()); + m_handle = HAL_CreateSimDevice(fmt::format("{}[{}]", name, index).c_str()); } hal::SimDevice::SimDevice(const char* name, int index, int channel) { - wpi::SmallString<128> fullname; - wpi::raw_svector_ostream os(fullname); - os << name << '[' << index << ',' << channel << ']'; - - m_handle = HAL_CreateSimDevice(fullname.c_str()); + m_handle = HAL_CreateSimDevice( + fmt::format("{}[{},{}]", name, index, channel).c_str()); } } // extern "C" diff --git a/hal/src/main/native/sim/mockdata/SimDeviceData.cpp b/hal/src/main/native/sim/mockdata/SimDeviceData.cpp index df7e12f542..9c7fdbc202 100644 --- a/hal/src/main/native/sim/mockdata/SimDeviceData.cpp +++ b/hal/src/main/native/sim/mockdata/SimDeviceData.cpp @@ -6,6 +6,8 @@ #include +#include + #include "SimDeviceDataInternal.h" using namespace hal; @@ -71,7 +73,7 @@ void SimDeviceData::SetDeviceEnabled(const char* prefix, bool enabled) { bool SimDeviceData::IsDeviceEnabled(const char* name) { std::scoped_lock lock(m_mutex); for (const auto& elem : m_prefixEnabled) { - if (wpi::StringRef{name}.startswith(elem.first)) { + if (wpi::starts_with(name, elem.first)) { return elem.second; } } @@ -83,7 +85,7 @@ HAL_SimDeviceHandle SimDeviceData::CreateDevice(const char* name) { // don't create if disabled for (const auto& elem : m_prefixEnabled) { - if (wpi::StringRef{name}.startswith(elem.first)) { + if (wpi::starts_with(name, elem.first)) { if (elem.second) { break; // enabled } @@ -272,7 +274,7 @@ int32_t SimDeviceData::RegisterDeviceCreatedCallback( // initial notifications if (initialNotify) { for (auto&& device : m_devices) { - if (wpi::StringRef{device->name}.startswith(prefix)) { + if (wpi::starts_with(device->name, prefix)) { callback(device->name.c_str(), param, device->handle); } } @@ -332,7 +334,7 @@ void SimDeviceData::EnumerateDevices(const char* prefix, void* param, HALSIM_SimDeviceCallback callback) { std::scoped_lock lock(m_mutex); for (auto&& device : m_devices) { - if (wpi::StringRef{device->name}.startswith(prefix)) { + if (wpi::starts_with(device->name, prefix)) { callback(device->name.c_str(), param, device->handle); } } diff --git a/hal/src/main/native/sim/mockdata/SimDeviceDataInternal.h b/hal/src/main/native/sim/mockdata/SimDeviceDataInternal.h index 18ac645a4a..deff6ed282 100644 --- a/hal/src/main/native/sim/mockdata/SimDeviceDataInternal.h +++ b/hal/src/main/native/sim/mockdata/SimDeviceDataInternal.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -118,7 +119,7 @@ class SimPrefixCallbackRegistry { void Invoke(const char* name, U&&... u) const { if (m_callbacks) { for (auto&& cb : *m_callbacks) { - if (wpi::StringRef{name}.startswith(cb.prefix)) { + if (wpi::starts_with(name, cb.prefix)) { cb.callback(name, cb.param, std::forward(u)...); } } diff --git a/ntcore/.styleguide b/ntcore/.styleguide index 67befdb7dd..8cf3a512f0 100644 --- a/ntcore/.styleguide +++ b/ntcore/.styleguide @@ -27,6 +27,7 @@ includeGuardRoots { } includeOtherLibs { + ^fmt/ ^support/ ^wpi/ } diff --git a/ntcore/src/main/native/cpp/Dispatcher.cpp b/ntcore/src/main/native/cpp/Dispatcher.cpp index 839faeb1f2..f0416f54ed 100644 --- a/ntcore/src/main/native/cpp/Dispatcher.cpp +++ b/ntcore/src/main/native/cpp/Dispatcher.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -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(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 { return wpi::TCPConnector::connect(server_name_copy.c_str(), static_cast(port), m_logger, 1); @@ -36,10 +37,10 @@ void Dispatcher::SetServer(const char* server_name, unsigned int port) { } void Dispatcher::SetServer( - wpi::ArrayRef> servers) { + wpi::ArrayRef> servers) { wpi::SmallVector, 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(server.second)); } @@ -53,49 +54,33 @@ void Dispatcher::SetServer( } void Dispatcher::SetServerTeam(unsigned int team, unsigned int port) { - std::pair servers[5]; + std::pair servers[5]; // 10.te.am.2 - wpi::SmallString<32> fixed; - { - wpi::raw_svector_ostream oss{fixed}; - oss << "10." << static_cast(team / 100) << '.' - << static_cast(team % 100) << ".2"; - servers[0] = std::make_pair(oss.str(), port); - } + auto fixed = fmt::format("10.{}.{}.2", static_cast(team / 100), + static_cast(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--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--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--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 { return wpi::TCPConnector::connect(server_name_copy.c_str(), static_cast(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 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(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; } diff --git a/ntcore/src/main/native/cpp/Dispatcher.h b/ntcore/src/main/native/cpp/Dispatcher.h index 020f737a17..c18b0b4caf 100644 --- a/ntcore/src/main/native/cpp/Dispatcher.h +++ b/ntcore/src/main/native/cpp/Dispatcher.h @@ -9,12 +9,11 @@ #include #include #include +#include #include #include #include -#include -#include #include #include @@ -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 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 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> servers); + wpi::ArrayRef> servers); void SetServerTeam(unsigned int team, unsigned int port); void SetServerOverride(const char* server_name, unsigned int port); diff --git a/ntcore/src/main/native/cpp/DsClient.cpp b/ntcore/src/main/native/cpp/DsClient.cpp index 073be143fa..9ed185041c 100644 --- a/ntcore/src/main/native/cpp/DsClient.cpp +++ b/ntcore/src/main/native/cpp/DsClient.cpp @@ -5,6 +5,7 @@ #include "DsClient.h" #include +#include #include #include #include @@ -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( + 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 diff --git a/ntcore/src/main/native/cpp/EntryNotifier.cpp b/ntcore/src/main/native/cpp/EntryNotifier.cpp index fb05cd9470..6f251a3df5 100644 --- a/ntcore/src/main/native/cpp/EntryNotifier.cpp +++ b/ntcore/src/main/native/cpp/EntryNotifier.cpp @@ -4,6 +4,8 @@ #include "EntryNotifier.h" +#include + #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 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, 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); } diff --git a/ntcore/src/main/native/cpp/EntryNotifier.h b/ntcore/src/main/native/cpp/EntryNotifier.h index bfc77f7025..087d39321d 100644 --- a/ntcore/src/main/native/cpp/EntryNotifier.h +++ b/ntcore/src/main/native/cpp/EntryNotifier.h @@ -8,6 +8,7 @@ #include #include #include +#include #include @@ -29,13 +30,13 @@ struct EntryListenerData EntryListenerData() = default; EntryListenerData( std::function callback_, - wpi::StringRef prefix_, unsigned int flags_) + std::string_view prefix_, unsigned int flags_) : CallbackListenerData(callback_), prefix(prefix_), flags(flags_) {} EntryListenerData( std::function 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 callback, - wpi::StringRef prefix, unsigned int flags) override; + std::string_view prefix, unsigned int flags) override; unsigned int Add(std::function 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, unsigned int flags, unsigned int only_listener = UINT_MAX) override; diff --git a/ntcore/src/main/native/cpp/IEntryNotifier.h b/ntcore/src/main/native/cpp/IEntryNotifier.h index bfc6da34b9..b3f91b2efa 100644 --- a/ntcore/src/main/native/cpp/IEntryNotifier.h +++ b/ntcore/src/main/native/cpp/IEntryNotifier.h @@ -7,6 +7,7 @@ #include #include +#include #include "ntcore_cpp.h" @@ -22,16 +23,17 @@ class IEntryNotifier { virtual unsigned int Add( std::function callback, - wpi::StringRef prefix, unsigned int flags) = 0; + std::string_view prefix, unsigned int flags) = 0; virtual unsigned int Add( std::function 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, unsigned int flags, unsigned int only_listener = UINT_MAX) = 0; }; diff --git a/ntcore/src/main/native/cpp/IRpcServer.h b/ntcore/src/main/native/cpp/IRpcServer.h index 1abce862f4..aa16084ed1 100644 --- a/ntcore/src/main/native/cpp/IRpcServer.h +++ b/ntcore/src/main/native/cpp/IRpcServer.h @@ -6,6 +6,7 @@ #define NTCORE_IRPCSERVER_H_ #include +#include #include "Message.h" #include "ntcore_cpp.h" @@ -14,7 +15,7 @@ namespace nt { class IRpcServer { public: - typedef std::function SendResponseFunc; + using SendResponseFunc = std::function; 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; diff --git a/ntcore/src/main/native/cpp/IStorage.h b/ntcore/src/main/native/cpp/IStorage.h index 47b3b50b01..d547d51dff 100644 --- a/ntcore/src/main/native/cpp/IStorage.h +++ b/ntcore/src/main/native/cpp/IStorage.h @@ -7,10 +7,10 @@ #include #include +#include #include #include -#include #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 warn) = 0; }; diff --git a/ntcore/src/main/native/cpp/Log.h b/ntcore/src/main/native/cpp/Log.h index 112f17190c..d3066d7414 100644 --- a/ntcore/src/main/native/cpp/Log.h +++ b/ntcore/src/main/native/cpp/Log.h @@ -7,17 +7,17 @@ #include -#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_ diff --git a/ntcore/src/main/native/cpp/LoggerImpl.cpp b/ntcore/src/main/native/cpp/LoggerImpl.cpp index 504b3cd1ad..28c9204ec1 100644 --- a/ntcore/src/main/native/cpp/LoggerImpl.cpp +++ b/ntcore/src/main/native/cpp/LoggerImpl.cpp @@ -4,35 +4,29 @@ #include "LoggerImpl.h" -#include -#include +#include #include -#include 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) {} diff --git a/ntcore/src/main/native/cpp/Message.cpp b/ntcore/src/main/native/cpp/Message.cpp index cf42651019..61efed16c9 100644 --- a/ntcore/src/main/native/cpp/Message.cpp +++ b/ntcore/src/main/native/cpp/Message.cpp @@ -106,7 +106,7 @@ std::shared_ptr 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::Read(WireDecoder& decoder, if (!decoder.Read(¶ms, 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::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::ClientHello(wpi::StringRef self_id) { +std::shared_ptr Message::ClientHello(std::string_view self_id) { auto msg = std::make_shared(kClientHello, private_init()); msg->m_str = self_id; return msg; } std::shared_ptr Message::ServerHello(unsigned int flags, - wpi::StringRef self_id) { + std::string_view self_id) { auto msg = std::make_shared(kServerHello, private_init()); msg->m_str = self_id; msg->m_flags = flags; return msg; } -std::shared_ptr Message::EntryAssign(wpi::StringRef name, +std::shared_ptr Message::EntryAssign(std::string_view name, unsigned int id, unsigned int seq_num, std::shared_ptr value, @@ -257,7 +257,7 @@ std::shared_ptr Message::EntryDelete(unsigned int id) { } std::shared_ptr Message::ExecuteRpc(unsigned int id, unsigned int uid, - wpi::StringRef params) { + std::string_view params) { auto msg = std::make_shared(kExecuteRpc, private_init()); msg->m_str = params; msg->m_id = id; @@ -266,7 +266,7 @@ std::shared_ptr Message::ExecuteRpc(unsigned int id, unsigned int uid, } std::shared_ptr Message::RpcResponse(unsigned int id, unsigned int uid, - wpi::StringRef result) { + std::string_view result) { auto msg = std::make_shared(kRpcResponse, private_init()); msg->m_str = result; msg->m_id = id; diff --git a/ntcore/src/main/native/cpp/Message.h b/ntcore/src/main/native/cpp/Message.h index 7754bb584c..53e8aac487 100644 --- a/ntcore/src/main/native/cpp/Message.h +++ b/ntcore/src/main/native/cpp/Message.h @@ -8,6 +8,7 @@ #include #include #include +#include #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() 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 ClientHello(wpi::StringRef self_id); + static std::shared_ptr ClientHello(std::string_view self_id); static std::shared_ptr ServerHello(unsigned int flags, - wpi::StringRef self_id); - static std::shared_ptr EntryAssign(wpi::StringRef name, + std::string_view self_id); + static std::shared_ptr EntryAssign(std::string_view name, unsigned int id, unsigned int seq_num, std::shared_ptr value, @@ -90,9 +91,9 @@ class Message { unsigned int flags); static std::shared_ptr EntryDelete(unsigned int id); static std::shared_ptr ExecuteRpc(unsigned int id, unsigned int uid, - wpi::StringRef params); + std::string_view params); static std::shared_ptr RpcResponse(unsigned int id, unsigned int uid, - wpi::StringRef result); + std::string_view result); Message(const Message&) = delete; Message& operator=(const Message&) = delete; diff --git a/ntcore/src/main/native/cpp/NetworkConnection.cpp b/ntcore/src/main/native/cpp/NetworkConnection.cpp index 84c8d981e8..ffc45c5b65 100644 --- a/ntcore/src/main/native/cpp/NetworkConnection.cpp +++ b/ntcore/src/main/native/cpp/NetworkConnection.cpp @@ -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(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) { diff --git a/ntcore/src/main/native/cpp/NetworkConnection.h b/ntcore/src/main/native/cpp/NetworkConnection.h index 69015054c0..412b91702f 100644 --- a/ntcore/src/main/native/cpp/NetworkConnection.h +++ b/ntcore/src/main/native/cpp/NetworkConnection.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -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; } diff --git a/ntcore/src/main/native/cpp/RpcServer.cpp b/ntcore/src/main/native/cpp/RpcServer.cpp index 88a53b796d..b4bf96a006 100644 --- a/ntcore/src/main/native/cpp/RpcServer.cpp +++ b/ntcore/src/main/native/cpp/RpcServer.cpp @@ -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); diff --git a/ntcore/src/main/native/cpp/RpcServer.h b/ntcore/src/main/native/cpp/RpcServer.h index e4d1b1d63d..4b830620f4 100644 --- a/ntcore/src/main/native/cpp/RpcServer.h +++ b/ntcore/src/main/native/cpp/RpcServer.h @@ -22,8 +22,8 @@ namespace impl { typedef std::pair 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 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; diff --git a/ntcore/src/main/native/cpp/Storage.cpp b/ntcore/src/main/native/cpp/Storage.cpp index f666976053..9e8bd83c06 100644 --- a/ntcore/src/main/native/cpp/Storage.cpp +++ b/ntcore/src/main/native/cpp/Storage.cpp @@ -4,6 +4,7 @@ #include "Storage.h" +#include #include #include "Handle.h" @@ -91,7 +92,7 @@ void Storage::ProcessIncomingEntryAssign(std::shared_ptr 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 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 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 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 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 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 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 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 Storage::GetEntryValue(wpi::StringRef name) const { +std::shared_ptr 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 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) { 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) { +bool Storage::SetEntryValue(std::string_view name, + std::shared_ptr value) { if (name.empty()) { return true; } @@ -664,7 +666,7 @@ void Storage::SetEntryValueImpl(Entry* entry, std::shared_ptr value, } } -void Storage::SetEntryTypeValue(wpi::StringRef name, +void Storage::SetEntryTypeValue(std::string_view name, std::shared_ptr 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 Storage::GetEntries(const wpi::Twine& prefix, +std::vector 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 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 Storage::GetEntryInfo(int inst, const wpi::Twine& prefix, +std::vector 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 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 Storage::GetEntryInfo(int inst, const wpi::Twine& prefix, } unsigned int Storage::AddListener( - const wpi::Twine& prefix, + std::string_view prefix, std::function 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>>* 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); diff --git a/ntcore/src/main/native/cpp/Storage.h b/ntcore/src/main/native/cpp/Storage.h index 96968b4573..3ca834cdb2 100644 --- a/ntcore/src/main/native/cpp/Storage.h +++ b/ntcore/src/main/native/cpp/Storage.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -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 GetEntryValue(wpi::StringRef name) const; + std::shared_ptr GetEntryValue(std::string_view name) const; std::shared_ptr GetEntryValue(unsigned int local_id) const; - bool SetDefaultEntryValue(wpi::StringRef name, std::shared_ptr value); + bool SetDefaultEntryValue(std::string_view name, + std::shared_ptr value); bool SetDefaultEntryValue(unsigned int local_id, std::shared_ptr value); - bool SetEntryValue(wpi::StringRef name, std::shared_ptr value); + bool SetEntryValue(std::string_view name, std::shared_ptr value); bool SetEntryValue(unsigned int local_id, std::shared_ptr value); - void SetEntryTypeValue(wpi::StringRef name, std::shared_ptr value); + void SetEntryTypeValue(std::string_view name, std::shared_ptr value); void SetEntryTypeValue(unsigned int local_id, std::shared_ptr 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 GetEntryInfo(int inst, const wpi::Twine& prefix, + std::vector GetEntryInfo(int inst, std::string_view prefix, unsigned int types); unsigned int AddListener( - const wpi::Twine& prefix, + std::string_view prefix, std::function 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 GetEntries(const wpi::Twine& prefix, + unsigned int GetEntry(std::string_view name); + std::vector 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 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 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 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>>* entries) const; - bool GetEntries(const wpi::Twine& prefix, + bool GetEntries(std::string_view prefix, std::vector>>* entries) const; void SetEntryValueImpl(Entry* entry, std::shared_ptr value, @@ -256,7 +258,7 @@ class Storage : public IStorage { template 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 diff --git a/ntcore/src/main/native/cpp/Storage_load.cpp b/ntcore/src/main/native/cpp/Storage_load.cpp index 04904aaa03..fdc80a4334 100644 --- a/ntcore/src/main/native/cpp/Storage_load.cpp +++ b/ntcore/src/main/native/cpp/Storage_load.cpp @@ -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* entries); + bool Load(std::string_view prefix, std::vector* entries); private: bool ReadLine(); bool ReadHeader(); NT_Type ReadType(); - wpi::StringRef ReadName(wpi::SmallVectorImpl& buf); + std::string_view ReadName(wpi::SmallVectorImpl& buf); std::shared_ptr ReadValue(NT_Type type); std::shared_ptr ReadBooleanValue(); std::shared_ptr 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 ReadStringToken( - wpi::StringRef source) { +static std::pair 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 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& buf) { +static std::string_view UnescapeString(std::string_view source, + wpi::SmallVectorImpl& 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* 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& buf) { - wpi::StringRef tok; +std::string_view LoadPersistentImpl::ReadName(wpi::SmallVectorImpl& 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 LoadPersistentImpl::ReadBooleanValue() { std::shared_ptr 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 LoadPersistentImpl::ReadDoubleValue() { } std::shared_ptr 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 LoadPersistentImpl::ReadRawValue() { std::shared_ptr 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 LoadPersistentImpl::ReadBooleanArrayValue() { std::shared_ptr 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 LoadPersistentImpl::ReadDoubleArrayValue() { std::shared_ptr 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 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 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 warn) { - wpi::SmallString<128> prefixBuf; - wpi::StringRef prefixStr = prefix.toStringRef(prefixBuf); - // entries to add std::vector 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 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 warn) { std::error_code ec; wpi::raw_fd_istream is(filename, ec); diff --git a/ntcore/src/main/native/cpp/Storage_save.cpp b/ntcore/src/main/native/cpp/Storage_save.cpp index 8cd6f9910c..26e0cad983 100644 --- a/ntcore/src/main/native/cpp/Storage_save.cpp +++ b/ntcore/src/main/native/cpp/Storage_save.cpp @@ -5,8 +5,8 @@ #include #include +#include #include -#include #include #include #include @@ -21,17 +21,17 @@ namespace { class SavePersistentImpl { public: - typedef std::pair> Entry; + using Entry = std::pair>; explicit SavePersistentImpl(wpi::raw_ostream& os) : m_os(os) {} void Save(wpi::ArrayRef entries); private: - void WriteString(wpi::StringRef str); + void WriteString(std::string_view str); void WriteHeader(); void WriteEntries(wpi::ArrayRef 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 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 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 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 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()) { diff --git a/ntcore/src/main/native/cpp/Value.cpp b/ntcore/src/main/native/cpp/Value.cpp index ff7fcb7c0b..96af67a551 100644 --- a/ntcore/src/main/native/cpp/Value.cpp +++ b/ntcore/src/main/native/cpp/Value.cpp @@ -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(wpi::safe_malloc(in.size() + 1)); std::memcpy(out->str, in.data(), in.size()); @@ -184,7 +184,7 @@ std::shared_ptr nt::ConvertFromC(const NT_Value& value) { std::vector 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)); } diff --git a/ntcore/src/main/native/cpp/Value_internal.h b/ntcore/src/main/native/cpp/Value_internal.h index 328f4aa87d..54850ab2c1 100644 --- a/ntcore/src/main/native/cpp/Value_internal.h +++ b/ntcore/src/main/native/cpp/Value_internal.h @@ -7,8 +7,7 @@ #include #include - -#include +#include #include "ntcore_c.h" @@ -18,9 +17,9 @@ class Value; void ConvertToC(const Value& in, NT_Value* out); std::shared_ptr 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 diff --git a/ntcore/src/main/native/cpp/WireDecoder.cpp b/ntcore/src/main/native/cpp/WireDecoder.cpp index e0bd01daf5..c0647dc048 100644 --- a/ntcore/src/main/native/cpp/WireDecoder.cpp +++ b/ntcore/src/main/native/cpp/WireDecoder.cpp @@ -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; } diff --git a/ntcore/src/main/native/cpp/WireEncoder.cpp b/ntcore/src/main/native/cpp/WireEncoder.cpp index ca6bd332d0..b35b7808f0 100644 --- a/ntcore/src/main/native/cpp/WireEncoder.cpp +++ b/ntcore/src/main/native/cpp/WireEncoder.cpp @@ -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) { diff --git a/ntcore/src/main/native/cpp/WireEncoder.h b/ntcore/src/main/native/cpp/WireEncoder.h index 3111f8f1ed..84edc39ebd 100644 --- a/ntcore/src/main/native/cpp/WireEncoder.h +++ b/ntcore/src/main/native/cpp/WireEncoder.h @@ -9,9 +9,9 @@ #include #include +#include #include -#include #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. */ diff --git a/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp b/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp index 75f9c713eb..b3f943c0fa 100644 --- a/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp +++ b/ntcore/src/main/native/cpp/jni/NetworkTablesJNI.cpp @@ -6,10 +6,9 @@ #include +#include #include -#include #include -#include #include "edu_wpi_first_networktables_NetworkTablesJNI.h" #include "ntcore.h" @@ -113,7 +112,7 @@ inline std::shared_ptr 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 FromJavaRawBB(JNIEnv* env, jobject jbb, @@ -170,7 +169,7 @@ std::shared_ptr 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 names; - std::vector> servers; + std::vector> 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 names; - std::vector> servers; + std::vector> 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 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 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; diff --git a/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp b/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp index d4839009ee..25bd809f02 100644 --- a/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp +++ b/ntcore/src/main/native/cpp/networktables/NetworkTable.cpp @@ -6,61 +6,59 @@ #include +#include +#include #include +#include #include -#include #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& buf, - bool withLeadingSlash) { +std::string_view NetworkTable::NormalizeKey(std::string_view key, + wpi::SmallVectorImpl& 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 parts; - keyStr.split(parts, PATH_SEPARATOR_CHAR, -1, false); + wpi::SmallVector 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 NetworkTable::GetHierarchy(const wpi::Twine& key) { +std::vector NetworkTable::GetHierarchy(std::string_view key) { std::vector 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 parts; - keyStr.split(parts, PATH_SEPARATOR_CHAR, -1, false); + wpi::SmallVector 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 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 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(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(this), event.name.substr(prefix_len), - entry, event.value, event.flags); + listener(const_cast(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::GetSubTable( - const wpi::Twine& key) const { + std::string_view key) const { return std::make_shared( - 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 NetworkTable::GetKeys(int types) const { std::vector 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 NetworkTable::GetKeys(int types) const { std::vector NetworkTable::GetSubTables() const { std::vector 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 value) { return GetEntry(key).SetBooleanArray(value); } -bool NetworkTable::SetDefaultBooleanArray(wpi::StringRef key, +bool NetworkTable::SetDefaultBooleanArray(std::string_view key, wpi::ArrayRef defaultValue) { return GetEntry(key).SetDefaultBooleanArray(defaultValue); } std::vector NetworkTable::GetBooleanArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) const { + std::string_view key, wpi::ArrayRef defaultValue) const { return GetEntry(key).GetBooleanArray(defaultValue); } -bool NetworkTable::PutNumberArray(wpi::StringRef key, +bool NetworkTable::PutNumberArray(std::string_view key, wpi::ArrayRef value) { return GetEntry(key).SetDoubleArray(value); } -bool NetworkTable::SetDefaultNumberArray(wpi::StringRef key, +bool NetworkTable::SetDefaultNumberArray(std::string_view key, wpi::ArrayRef defaultValue) { return GetEntry(key).SetDefaultDoubleArray(defaultValue); } std::vector NetworkTable::GetNumberArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) const { + std::string_view key, wpi::ArrayRef defaultValue) const { return GetEntry(key).GetDoubleArray(defaultValue); } -bool NetworkTable::PutStringArray(wpi::StringRef key, +bool NetworkTable::PutStringArray(std::string_view key, wpi::ArrayRef value) { return GetEntry(key).SetStringArray(value); } bool NetworkTable::SetDefaultStringArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) { + std::string_view key, wpi::ArrayRef defaultValue) { return GetEntry(key).SetDefaultStringArray(defaultValue); } std::vector NetworkTable::GetStringArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) const { + std::string_view key, wpi::ArrayRef 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) { return GetEntry(key).SetValue(value); } -bool NetworkTable::SetDefaultValue(const wpi::Twine& key, +bool NetworkTable::SetDefaultValue(std::string_view key, std::shared_ptr defaultValue) { return GetEntry(key).SetDefaultValue(defaultValue); } -std::shared_ptr NetworkTable::GetValue(const wpi::Twine& key) const { +std::shared_ptr 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 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); } diff --git a/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp b/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp index 8a3d985dc6..4ff8f7551b 100644 --- a/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp +++ b/ntcore/src/main/native/cpp/networktables/NetworkTableInstance.cpp @@ -4,42 +4,37 @@ #include "networktables/NetworkTableInstance.h" -#include +#include +#include using namespace nt; std::shared_ptr 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(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(m_handle, key, NetworkTable::private_init{}); } else { - return std::make_shared( - m_handle, wpi::Twine(NetworkTable::PATH_SEPARATOR_CHAR) + key, - NetworkTable::private_init{}); + return std::make_shared(m_handle, fmt::format("/{}", key), + NetworkTable::private_init{}); } } -void NetworkTableInstance::StartClient(wpi::ArrayRef servers, +void NetworkTableInstance::StartClient(wpi::ArrayRef servers, unsigned int port) { - wpi::SmallVector, 8> server_ports; + wpi::SmallVector, 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 servers, +void NetworkTableInstance::SetServer(wpi::ArrayRef servers, unsigned int port) { - wpi::SmallVector, 8> server_ports; + wpi::SmallVector, 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 servers, } NT_EntryListener NetworkTableInstance::AddEntryListener( - const wpi::Twine& prefix, + std::string_view prefix, std::function callback, unsigned int flags) const { return ::nt::AddEntryListener(m_handle, prefix, callback, flags); diff --git a/ntcore/src/main/native/cpp/ntcore_c.cpp b/ntcore/src/main/native/cpp/ntcore_c.cpp index d41fc9774c..ae48b1cce6 100644 --- a/ntcore/src/main/native/cpp/ntcore_c.cpp +++ b/ntcore/src/main/native/cpp/ntcore_c.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -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(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(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(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> servers; + std::vector> 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> servers; + std::vector> 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 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 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, diff --git a/ntcore/src/main/native/cpp/ntcore_cpp.cpp b/ntcore/src/main/native/cpp/ntcore_cpp.cpp index cf1a7d5c16..619e996941 100644 --- a/ntcore/src/main/native/cpp/ntcore_cpp.cpp +++ b/ntcore/src/main/native/cpp/ntcore_cpp.cpp @@ -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 GetEntries(NT_Inst inst, const wpi::Twine& prefix, +std::vector 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 GetEntryInfo(NT_Inst inst, const wpi::Twine& prefix, +std::vector 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 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 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> values) { for (auto& value : values) { enc.WriteValue(*value); } - return enc.ToStringRef(); + return std::string{enc.ToStringView()}; } std::vector> UnpackRpcValues( - wpi::StringRef packed, wpi::ArrayRef types) { + std::string_view packed, wpi::ArrayRef 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> servers) { + wpi::ArrayRef> 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> servers) { +void SetServer( + NT_Inst inst, + wpi::ArrayRef> 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 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 warn) { auto ii = InstanceImpl::Get(Handle{inst}.GetTypedInst(Handle::kInstance)); if (!ii) { diff --git a/ntcore/src/main/native/cpp/ntcore_test.cpp b/ntcore/src/main/native/cpp/ntcore_test.cpp index 08ebec75ab..00d07f7b27 100644 --- a/ntcore/src/main/native/cpp/ntcore_test.cpp +++ b/ntcore/src/main/native/cpp/ntcore_test.cpp @@ -12,7 +12,7 @@ extern "C" { struct NT_String* NT_GetStringForTesting(const char* string, int* struct_size) { struct NT_String* str = static_cast(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(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( 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(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(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(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( 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( 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( wpi::safe_malloc(num_params * sizeof(NT_RpcParamDef))); @@ -234,8 +234,8 @@ struct NT_RpcAnswer* NT_GetRpcAnswerForTesting( static_cast(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; } diff --git a/ntcore/src/main/native/include/networktables/NetworkTable.h b/ntcore/src/main/native/include/networktables/NetworkTable.h index 664c98b563..7ac4e7eb14 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTable.h +++ b/ntcore/src/main/native/include/networktables/NetworkTable.h @@ -8,12 +8,12 @@ #include #include #include +#include #include #include #include #include -#include #include #include "networktables/NetworkTableEntry.h" @@ -54,7 +54,7 @@ class NetworkTable final { * @param key key * @return base name */ - static wpi::StringRef BasenameKey(wpi::StringRef key); + static std::string_view BasenameKey(std::string_view key); /** * Normalizes an network table key to contain no consecutive slashes and @@ -72,12 +72,12 @@ class NetworkTable final { * with a leading slash * @return normalized key */ - static std::string NormalizeKey(const wpi::Twine& key, + static std::string NormalizeKey(std::string_view key, bool withLeadingSlash = true); - static wpi::StringRef NormalizeKey(const wpi::Twine& key, - wpi::SmallVectorImpl& buf, - bool withLeadingSlash = true); + static std::string_view NormalizeKey(std::string_view key, + wpi::SmallVectorImpl& buf, + bool withLeadingSlash = true); /** * Gets a list of the names of all the super tables of a given key. For @@ -87,13 +87,13 @@ class NetworkTable final { * @param key the key * @return List of super tables */ - static std::vector GetHierarchy(const wpi::Twine& key); + static std::vector GetHierarchy(std::string_view key); /** * Constructor. Use NetworkTableInstance::GetTable() or GetSubTable() * instead. */ - NetworkTable(NT_Inst inst, const wpi::Twine& path, const private_init&); + NetworkTable(NT_Inst inst, std::string_view path, const private_init&); virtual ~NetworkTable(); /** @@ -114,7 +114,7 @@ class NetworkTable final { * @param key the key name * @return Network table entry. */ - NetworkTableEntry GetEntry(const wpi::Twine& key) const; + NetworkTableEntry GetEntry(std::string_view key) const; /** * Listen to keys only within this table. @@ -134,7 +134,7 @@ class NetworkTable final { * @param flags EntryListenerFlags bitmask * @return Listener handle */ - NT_EntryListener AddEntryListener(const wpi::Twine& key, + NT_EntryListener AddEntryListener(std::string_view key, TableEntryListener listener, unsigned int flags) const; @@ -171,7 +171,7 @@ class NetworkTable final { * @param key the key name * @return the networktable to be returned */ - std::shared_ptr GetSubTable(const wpi::Twine& key) const; + std::shared_ptr GetSubTable(std::string_view key) const; /** * Determines whether the given key is in this table. @@ -179,7 +179,7 @@ class NetworkTable final { * @param key the key to search for * @return true if the table as a value assigned to the given key */ - bool ContainsKey(const wpi::Twine& key) const; + bool ContainsKey(std::string_view key) const; /** * Determines whether there exists a non-empty subtable for this key @@ -189,7 +189,7 @@ class NetworkTable final { * @return true if there is a subtable with the key which contains at least * one key/subtable of its own */ - bool ContainsSubTable(const wpi::Twine& key) const; + bool ContainsSubTable(std::string_view key) const; /** * Gets all keys in the table (not including sub-tables). @@ -211,7 +211,7 @@ class NetworkTable final { * * @param key the key to make persistent */ - void SetPersistent(wpi::StringRef key); + void SetPersistent(std::string_view key); /** * Stop making a key's value persistent through program restarts. @@ -219,7 +219,7 @@ class NetworkTable final { * * @param key the key name */ - void ClearPersistent(wpi::StringRef key); + void ClearPersistent(std::string_view key); /** * Returns whether the value is persistent through program restarts. @@ -227,7 +227,7 @@ class NetworkTable final { * * @param key the key name */ - bool IsPersistent(wpi::StringRef key) const; + bool IsPersistent(std::string_view key) const; /** * Sets flags on the specified key in this table. The key can @@ -236,7 +236,7 @@ class NetworkTable final { * @param key the key name * @param flags the flags to set (bitmask) */ - void SetFlags(wpi::StringRef key, unsigned int flags); + void SetFlags(std::string_view key, unsigned int flags); /** * Clears flags on the specified key in this table. The key can @@ -245,7 +245,7 @@ class NetworkTable final { * @param key the key name * @param flags the flags to clear (bitmask) */ - void ClearFlags(wpi::StringRef key, unsigned int flags); + void ClearFlags(std::string_view key, unsigned int flags); /** * Returns the flags for the specified key. @@ -253,14 +253,14 @@ class NetworkTable final { * @param key the key name * @return the flags, or 0 if the key is not defined */ - unsigned int GetFlags(wpi::StringRef key) const; + unsigned int GetFlags(std::string_view key) const; /** * Deletes the specified key in this table. * * @param key the key name */ - void Delete(const wpi::Twine& key); + void Delete(std::string_view key); /** * Put a number in the table @@ -269,7 +269,7 @@ class NetworkTable final { * @param value the value that will be assigned * @return False if the table key already exists with a different type */ - bool PutNumber(wpi::StringRef key, double value); + bool PutNumber(std::string_view key, double value); /** * Gets the current value in the table, setting it if it does not exist. @@ -278,7 +278,7 @@ class NetworkTable final { * @param defaultValue the default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - bool SetDefaultNumber(wpi::StringRef key, double defaultValue); + bool SetDefaultNumber(std::string_view key, double defaultValue); /** * Gets the number associated with the given name. @@ -288,7 +288,7 @@ class NetworkTable final { * @return the value associated with the given key or the given default value * if there is no value associated with the key */ - double GetNumber(wpi::StringRef key, double defaultValue) const; + double GetNumber(std::string_view key, double defaultValue) const; /** * Put a string in the table @@ -297,7 +297,7 @@ class NetworkTable final { * @param value the value that will be assigned * @return False if the table key already exists with a different type */ - bool PutString(wpi::StringRef key, wpi::StringRef value); + bool PutString(std::string_view key, std::string_view value); /** * Gets the current value in the table, setting it if it does not exist. @@ -306,7 +306,7 @@ class NetworkTable final { * @param defaultValue the default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - bool SetDefaultString(wpi::StringRef key, wpi::StringRef defaultValue); + bool SetDefaultString(std::string_view key, std::string_view defaultValue); /** * Gets the string associated with the given name. If the key does not @@ -317,7 +317,8 @@ class NetworkTable final { * @return the value associated with the given key or the given default value * if there is no value associated with the key */ - std::string GetString(wpi::StringRef key, wpi::StringRef defaultValue) const; + std::string GetString(std::string_view key, + std::string_view defaultValue) const; /** * Put a boolean in the table @@ -326,7 +327,7 @@ class NetworkTable final { * @param value the value that will be assigned * @return False if the table key already exists with a different type */ - bool PutBoolean(wpi::StringRef key, bool value); + bool PutBoolean(std::string_view key, bool value); /** * Gets the current value in the table, setting it if it does not exist. @@ -335,7 +336,7 @@ class NetworkTable final { * @param defaultValue the default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - bool SetDefaultBoolean(wpi::StringRef key, bool defaultValue); + bool SetDefaultBoolean(std::string_view key, bool defaultValue); /** * Gets the boolean associated with the given name. If the key does not @@ -346,7 +347,7 @@ class NetworkTable final { * @return the value associated with the given key or the given default value * if there is no value associated with the key */ - bool GetBoolean(wpi::StringRef key, bool defaultValue) const; + bool GetBoolean(std::string_view key, bool defaultValue) const; /** * Put a boolean array in the table @@ -359,7 +360,7 @@ class NetworkTable final { * std::vector is special-cased in C++. 0 is false, any * non-zero value is true. */ - bool PutBooleanArray(wpi::StringRef key, wpi::ArrayRef value); + bool PutBooleanArray(std::string_view key, wpi::ArrayRef value); /** * Gets the current value in the table, setting it if it does not exist. @@ -368,7 +369,7 @@ class NetworkTable final { * @param defaultValue the default value to set if key doesn't exist. * @return False if the table key exists with a different type */ - bool SetDefaultBooleanArray(wpi::StringRef key, + bool SetDefaultBooleanArray(std::string_view key, wpi::ArrayRef defaultValue); /** @@ -387,7 +388,7 @@ class NetworkTable final { * because std::vector is special-cased in C++. 0 is false, any * non-zero value is true. */ - std::vector GetBooleanArray(wpi::StringRef key, + std::vector GetBooleanArray(std::string_view key, wpi::ArrayRef defaultValue) const; /** @@ -397,7 +398,7 @@ class NetworkTable final { * @param value the value that will be assigned * @return False if the table key already exists with a different type */ - bool PutNumberArray(wpi::StringRef key, wpi::ArrayRef value); + bool PutNumberArray(std::string_view key, wpi::ArrayRef value); /** * Gets the current value in the table, setting it if it does not exist. @@ -406,7 +407,7 @@ class NetworkTable final { * @param defaultValue the default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - bool SetDefaultNumberArray(wpi::StringRef key, + bool SetDefaultNumberArray(std::string_view key, wpi::ArrayRef defaultValue); /** @@ -421,7 +422,7 @@ class NetworkTable final { * @note This makes a copy of the array. If the overhead of this is a * concern, use GetValue() instead. */ - std::vector GetNumberArray(wpi::StringRef key, + std::vector GetNumberArray(std::string_view key, wpi::ArrayRef defaultValue) const; /** @@ -431,7 +432,7 @@ class NetworkTable final { * @param value the value that will be assigned * @return False if the table key already exists with a different type */ - bool PutStringArray(wpi::StringRef key, wpi::ArrayRef value); + bool PutStringArray(std::string_view key, wpi::ArrayRef value); /** * Gets the current value in the table, setting it if it does not exist. @@ -440,7 +441,7 @@ class NetworkTable final { * @param defaultValue the default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - bool SetDefaultStringArray(wpi::StringRef key, + bool SetDefaultStringArray(std::string_view key, wpi::ArrayRef defaultValue); /** @@ -456,7 +457,7 @@ class NetworkTable final { * concern, use GetValue() instead. */ std::vector GetStringArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) const; + std::string_view key, wpi::ArrayRef defaultValue) const; /** * Put a raw value (byte array) in the table @@ -465,7 +466,7 @@ class NetworkTable final { * @param value the value that will be assigned * @return False if the table key already exists with a different type */ - bool PutRaw(wpi::StringRef key, wpi::StringRef value); + bool PutRaw(std::string_view key, std::string_view value); /** * Gets the current value in the table, setting it if it does not exist. @@ -474,7 +475,7 @@ class NetworkTable final { * @param defaultValue the default value to set if key doesn't exist. * @return False if the table key exists with a different type */ - bool SetDefaultRaw(wpi::StringRef key, wpi::StringRef defaultValue); + bool SetDefaultRaw(std::string_view key, std::string_view defaultValue); /** * Returns the raw value (byte array) the key maps to. If the key does not @@ -488,7 +489,7 @@ class NetworkTable final { * @note This makes a copy of the raw contents. If the overhead of this is a * concern, use GetValue() instead. */ - std::string GetRaw(wpi::StringRef key, wpi::StringRef defaultValue) const; + std::string GetRaw(std::string_view key, std::string_view defaultValue) const; /** * Put a value in the table @@ -497,7 +498,7 @@ class NetworkTable final { * @param value the value that will be assigned * @return False if the table key already exists with a different type */ - bool PutValue(const wpi::Twine& key, std::shared_ptr value); + bool PutValue(std::string_view key, std::shared_ptr value); /** * Gets the current value in the table, setting it if it does not exist. @@ -506,7 +507,7 @@ class NetworkTable final { * @param defaultValue the default value to set if key doesn't exist. * @return False if the table key exists with a different type */ - bool SetDefaultValue(const wpi::Twine& key, + bool SetDefaultValue(std::string_view key, std::shared_ptr defaultValue); /** @@ -516,14 +517,14 @@ class NetworkTable final { * @return the value associated with the given key, or nullptr if the key * does not exist */ - std::shared_ptr GetValue(const wpi::Twine& key) const; + std::shared_ptr GetValue(std::string_view key) const; /** * Gets the full path of this table. Does not include the trailing "/". * * @return The path (e.g "", "/foo"). */ - wpi::StringRef GetPath() const; + std::string_view GetPath() const; /** * Save table values to a file. The file format used is identical to @@ -532,7 +533,7 @@ class NetworkTable final { * @param filename filename * @return error string, or nullptr if successful */ - const char* SaveEntries(const wpi::Twine& filename) const; + const char* SaveEntries(std::string_view filename) const; /** * Load table values from a file. The file format used is identical to @@ -543,7 +544,7 @@ class NetworkTable final { * @return error string, or nullptr if successful */ const char* LoadEntries( - const wpi::Twine& filename, + std::string_view filename, std::function warn); }; diff --git a/ntcore/src/main/native/include/networktables/NetworkTableEntry.h b/ntcore/src/main/native/include/networktables/NetworkTableEntry.h index 92c1f352f1..7774fa2157 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableEntry.h +++ b/ntcore/src/main/native/include/networktables/NetworkTableEntry.h @@ -10,11 +10,9 @@ #include #include #include +#include #include -#include -#include - #include "networktables/NetworkTableType.h" #include "networktables/NetworkTableValue.h" #include "networktables/RpcCall.h" @@ -143,7 +141,7 @@ class NetworkTableEntry final { * @param defaultValue the value to be returned if no value is found * @return the entry's value or the given default value */ - std::string GetString(wpi::StringRef defaultValue) const; + std::string GetString(std::string_view defaultValue) const; /** * Gets the entry's value as a raw. If the entry does not exist or is of @@ -152,7 +150,7 @@ class NetworkTableEntry final { * @param defaultValue the value to be returned if no value is found * @return the entry's value or the given default value */ - std::string GetRaw(wpi::StringRef defaultValue) const; + std::string GetRaw(std::string_view defaultValue) const; /** * Gets the entry's value as a boolean array. If the entry does not exist @@ -268,7 +266,7 @@ class NetworkTableEntry final { * @param defaultValue the default value to set * @return False if the entry exists with a different type */ - bool SetDefaultString(const wpi::Twine& defaultValue); + bool SetDefaultString(std::string_view defaultValue); /** * Sets the entry's value if it does not exist. @@ -276,7 +274,7 @@ class NetworkTableEntry final { * @param defaultValue the default value to set * @return False if the entry exists with a different type */ - bool SetDefaultRaw(wpi::StringRef defaultValue); + bool SetDefaultRaw(std::string_view defaultValue); /** * Sets the entry's value if it does not exist. @@ -356,7 +354,7 @@ class NetworkTableEntry final { * @param value the value to set * @return False if the entry exists with a different type */ - bool SetString(const wpi::Twine& value); + bool SetString(std::string_view value); /** * Sets the entry's value. @@ -364,7 +362,7 @@ class NetworkTableEntry final { * @param value the value to set * @return False if the entry exists with a different type */ - bool SetRaw(wpi::StringRef value); + bool SetRaw(std::string_view value); /** * Sets the entry's value. @@ -460,7 +458,7 @@ class NetworkTableEntry final { * * @param value the value to set */ - void ForceSetString(const wpi::Twine& value); + void ForceSetString(std::string_view value); /** * Sets the entry's value. If the value is of different type, the type is @@ -468,7 +466,7 @@ class NetworkTableEntry final { * * @param value the value to set */ - void ForceSetRaw(wpi::StringRef value); + void ForceSetRaw(std::string_view value); /** * Sets the entry's value. If the value is of different type, the type is @@ -596,7 +594,7 @@ class NetworkTableEntry final { * @param params parameter * @return RPC call object. */ - RpcCall CallRpc(wpi::StringRef params); + RpcCall CallRpc(std::string_view params); /** * Add a listener for changes to this entry. diff --git a/ntcore/src/main/native/include/networktables/NetworkTableEntry.inc b/ntcore/src/main/native/include/networktables/NetworkTableEntry.inc index ba1628e4d6..00082b3961 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableEntry.inc +++ b/ntcore/src/main/native/include/networktables/NetworkTableEntry.inc @@ -7,6 +7,7 @@ #include #include +#include #include #include "networktables/NetworkTableEntry.h" @@ -67,21 +68,21 @@ inline double NetworkTableEntry::GetDouble(double defaultValue) const { } inline std::string NetworkTableEntry::GetString( - wpi::StringRef defaultValue) const { + std::string_view defaultValue) const { auto value = GetEntryValue(m_handle); if (!value || value->type() != NT_STRING) { - return defaultValue; + return std::string{defaultValue}; } - return value->GetString(); + return std::string{value->GetString()}; } inline std::string NetworkTableEntry::GetRaw( - wpi::StringRef defaultValue) const { + std::string_view defaultValue) const { auto value = GetEntryValue(m_handle); if (!value || value->type() != NT_RAW) { - return defaultValue; + return std::string{defaultValue}; } - return value->GetRaw(); + return std::string{value->GetRaw()}; } inline std::vector NetworkTableEntry::GetBooleanArray( @@ -141,12 +142,11 @@ inline bool NetworkTableEntry::SetDefaultDouble(double defaultValue) { return SetDefaultEntryValue(m_handle, Value::MakeDouble(defaultValue)); } -inline bool NetworkTableEntry::SetDefaultString( - const wpi::Twine& defaultValue) { +inline bool NetworkTableEntry::SetDefaultString(std::string_view defaultValue) { return SetDefaultEntryValue(m_handle, Value::MakeString(defaultValue)); } -inline bool NetworkTableEntry::SetDefaultRaw(wpi::StringRef defaultValue) { +inline bool NetworkTableEntry::SetDefaultRaw(std::string_view defaultValue) { return SetDefaultEntryValue(m_handle, Value::MakeRaw(defaultValue)); } @@ -192,11 +192,11 @@ inline bool NetworkTableEntry::SetDouble(double value) { return SetEntryValue(m_handle, Value::MakeDouble(value)); } -inline bool NetworkTableEntry::SetString(const wpi::Twine& value) { +inline bool NetworkTableEntry::SetString(std::string_view value) { return SetEntryValue(m_handle, Value::MakeString(value)); } -inline bool NetworkTableEntry::SetRaw(wpi::StringRef value) { +inline bool NetworkTableEntry::SetRaw(std::string_view value) { return SetEntryValue(m_handle, Value::MakeRaw(value)); } @@ -249,11 +249,11 @@ inline void NetworkTableEntry::ForceSetDouble(double value) { SetEntryTypeValue(m_handle, Value::MakeDouble(value)); } -inline void NetworkTableEntry::ForceSetString(const wpi::Twine& value) { +inline void NetworkTableEntry::ForceSetString(std::string_view value) { SetEntryTypeValue(m_handle, Value::MakeString(value)); } -inline void NetworkTableEntry::ForceSetRaw(wpi::StringRef value) { +inline void NetworkTableEntry::ForceSetRaw(std::string_view value) { SetEntryTypeValue(m_handle, Value::MakeRaw(value)); } @@ -321,10 +321,10 @@ inline void NetworkTableEntry::Delete() { inline void NetworkTableEntry::CreateRpc( std::function callback) { - ::nt::CreateRpc(m_handle, wpi::StringRef("\0", 1), callback); + ::nt::CreateRpc(m_handle, std::string_view("\0", 1), callback); } -inline RpcCall NetworkTableEntry::CallRpc(wpi::StringRef params) { +inline RpcCall NetworkTableEntry::CallRpc(std::string_view params) { return RpcCall{m_handle, ::nt::CallRpc(m_handle, params)}; } diff --git a/ntcore/src/main/native/include/networktables/NetworkTableInstance.h b/ntcore/src/main/native/include/networktables/NetworkTableInstance.h index 89c4fe038e..3f7f247ac7 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableInstance.h +++ b/ntcore/src/main/native/include/networktables/NetworkTableInstance.h @@ -8,12 +8,11 @@ #include #include #include +#include #include #include #include -#include -#include #include "networktables/NetworkTable.h" #include "networktables/NetworkTableEntry.h" @@ -131,7 +130,7 @@ class NetworkTableInstance final { * @param name Key * @return Network table entry. */ - NetworkTableEntry GetEntry(const wpi::Twine& name); + NetworkTableEntry GetEntry(std::string_view name); /** * Get entries starting with the given prefix. @@ -144,7 +143,7 @@ class NetworkTableInstance final { * @param types bitmask of types; 0 is treated as a "don't care" * @return Array of entries. */ - std::vector GetEntries(const wpi::Twine& prefix, + std::vector GetEntries(std::string_view prefix, unsigned int types); /** @@ -158,7 +157,7 @@ class NetworkTableInstance final { * @param types bitmask of types; 0 is treated as a "don't care" * @return Array of entry information. */ - std::vector GetEntryInfo(const wpi::Twine& prefix, + std::vector GetEntryInfo(std::string_view prefix, unsigned int types) const; /** @@ -167,7 +166,7 @@ class NetworkTableInstance final { * @param key the key name * @return The network table */ - std::shared_ptr GetTable(const wpi::Twine& key) const; + std::shared_ptr GetTable(std::string_view key) const; /** * Deletes ALL keys in ALL subtables (except persistent values). @@ -189,7 +188,7 @@ class NetworkTableInstance final { * @return Listener handle */ NT_EntryListener AddEntryListener( - const wpi::Twine& prefix, + std::string_view prefix, std::function callback, unsigned int flags) const; @@ -283,7 +282,7 @@ class NetworkTableInstance final { * * @param name identity to advertise */ - void SetNetworkIdentity(const wpi::Twine& name); + void SetNetworkIdentity(std::string_view name); /** * Get the current network mode. @@ -314,7 +313,7 @@ class NetworkTableInstance final { * address (UTF-8 string, null terminated) * @param port port to communicate over */ - void StartServer(const wpi::Twine& persist_filename = "networktables.ini", + void StartServer(std::string_view persist_filename = "networktables.ini", const char* listen_address = "", unsigned int port = kDefaultPort); @@ -343,7 +342,7 @@ class NetworkTableInstance final { * @param servers array of server name and port pairs */ void StartClient( - wpi::ArrayRef> servers); + wpi::ArrayRef> servers); /** * Starts a client using the specified servers and port. The @@ -352,7 +351,7 @@ class NetworkTableInstance final { * @param servers array of server names * @param port port to communicate over */ - void StartClient(wpi::ArrayRef servers, + void StartClient(wpi::ArrayRef servers, unsigned int port = kDefaultPort); /** @@ -384,7 +383,7 @@ class NetworkTableInstance final { * @param servers array of server name and port pairs */ void SetServer( - wpi::ArrayRef> servers); + wpi::ArrayRef> servers); /** * Sets server addresses and port for client (without restarting client). @@ -393,7 +392,7 @@ class NetworkTableInstance final { * @param servers array of server names * @param port port to communicate over */ - void SetServer(wpi::ArrayRef servers, + void SetServer(wpi::ArrayRef servers, unsigned int port = kDefaultPort); /** @@ -465,7 +464,7 @@ class NetworkTableInstance final { * @param filename filename * @return error string, or nullptr if successful */ - const char* SavePersistent(const wpi::Twine& filename) const; + const char* SavePersistent(std::string_view filename) const; /** * Load persistent values from a file. The server automatically does this @@ -477,7 +476,7 @@ class NetworkTableInstance final { * @return error string, or nullptr if successful */ const char* LoadPersistent( - const wpi::Twine& filename, + std::string_view filename, std::function warn); /** @@ -488,8 +487,8 @@ class NetworkTableInstance final { * @param prefix save only keys starting with this prefix * @return error string, or nullptr if successful */ - const char* SaveEntries(const wpi::Twine& filename, - const wpi::Twine& prefix) const; + const char* SaveEntries(std::string_view filename, + std::string_view prefix) const; /** * Load table values from a file. The file format used is identical to @@ -501,7 +500,7 @@ class NetworkTableInstance final { * @return error string, or nullptr if successful */ const char* LoadEntries( - const wpi::Twine& filename, const wpi::Twine& prefix, + std::string_view filename, std::string_view prefix, std::function warn); /** @} */ diff --git a/ntcore/src/main/native/include/networktables/NetworkTableInstance.inc b/ntcore/src/main/native/include/networktables/NetworkTableInstance.inc index ea8e74f447..9bb5399d8a 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableInstance.inc +++ b/ntcore/src/main/native/include/networktables/NetworkTableInstance.inc @@ -5,6 +5,7 @@ #ifndef NTCORE_NETWORKTABLES_NETWORKTABLEINSTANCE_INC_ #define NTCORE_NETWORKTABLES_NETWORKTABLEINSTANCE_INC_ +#include #include #include @@ -35,13 +36,12 @@ inline NT_Inst NetworkTableInstance::GetHandle() const { return m_handle; } -inline NetworkTableEntry NetworkTableInstance::GetEntry( - const wpi::Twine& name) { +inline NetworkTableEntry NetworkTableInstance::GetEntry(std::string_view name) { return NetworkTableEntry{::nt::GetEntry(m_handle, name)}; } inline std::vector NetworkTableInstance::GetEntries( - const wpi::Twine& prefix, unsigned int types) { + std::string_view prefix, unsigned int types) { std::vector entries; for (auto entry : ::nt::GetEntries(m_handle, prefix, types)) { entries.emplace_back(entry); @@ -50,7 +50,7 @@ inline std::vector NetworkTableInstance::GetEntries( } inline std::vector NetworkTableInstance::GetEntryInfo( - const wpi::Twine& prefix, unsigned int types) const { + std::string_view prefix, unsigned int types) const { return ::nt::GetEntryInfo(m_handle, prefix, types); } @@ -81,7 +81,7 @@ inline bool NetworkTableInstance::WaitForRpcCallQueue(double timeout) { return ::nt::WaitForRpcCallQueue(m_handle, timeout); } -inline void NetworkTableInstance::SetNetworkIdentity(const wpi::Twine& name) { +inline void NetworkTableInstance::SetNetworkIdentity(std::string_view name) { ::nt::SetNetworkIdentity(m_handle, name); } @@ -97,9 +97,9 @@ inline void NetworkTableInstance::StopLocal() { ::nt::StopLocal(m_handle); } -inline void NetworkTableInstance::StartServer( - const wpi::Twine& persist_filename, const char* listen_address, - unsigned int port) { +inline void NetworkTableInstance::StartServer(std::string_view persist_filename, + const char* listen_address, + unsigned int port) { ::nt::StartServer(m_handle, persist_filename, listen_address, port); } @@ -117,7 +117,7 @@ inline void NetworkTableInstance::StartClient(const char* server_name, } inline void NetworkTableInstance::StartClient( - wpi::ArrayRef> servers) { + wpi::ArrayRef> servers) { ::nt::StartClient(m_handle, servers); } @@ -136,7 +136,7 @@ inline void NetworkTableInstance::SetServer(const char* server_name, } inline void NetworkTableInstance::SetServer( - wpi::ArrayRef> servers) { + wpi::ArrayRef> servers) { ::nt::SetServer(m_handle, servers); } @@ -171,23 +171,23 @@ inline bool NetworkTableInstance::IsConnected() const { } inline const char* NetworkTableInstance::SavePersistent( - const wpi::Twine& filename) const { + std::string_view filename) const { return ::nt::SavePersistent(m_handle, filename); } inline const char* NetworkTableInstance::LoadPersistent( - const wpi::Twine& filename, + std::string_view filename, std::function warn) { return ::nt::LoadPersistent(m_handle, filename, warn); } inline const char* NetworkTableInstance::SaveEntries( - const wpi::Twine& filename, const wpi::Twine& prefix) const { + std::string_view filename, std::string_view prefix) const { return ::nt::SaveEntries(m_handle, filename, prefix); } inline const char* NetworkTableInstance::LoadEntries( - const wpi::Twine& filename, const wpi::Twine& prefix, + std::string_view filename, std::string_view prefix, std::function warn) { return ::nt::LoadEntries(m_handle, filename, prefix, warn); } diff --git a/ntcore/src/main/native/include/networktables/NetworkTableValue.h b/ntcore/src/main/native/include/networktables/NetworkTableValue.h index 014bc326cd..acc51ad2b9 100644 --- a/ntcore/src/main/native/include/networktables/NetworkTableValue.h +++ b/ntcore/src/main/native/include/networktables/NetworkTableValue.h @@ -11,13 +11,12 @@ #include #include #include +#include #include #include #include #include -#include -#include #include "ntcore_c.h" @@ -163,7 +162,7 @@ class Value final { * * @return The string value. */ - wpi::StringRef GetString() const { + std::string_view GetString() const { assert(m_val.type == NT_STRING); return m_string; } @@ -173,7 +172,7 @@ class Value final { * * @return The raw value. */ - wpi::StringRef GetRaw() const { + std::string_view GetRaw() const { assert(m_val.type == NT_RAW); return m_string; } @@ -183,7 +182,7 @@ class Value final { * * @return The rpc definition value. */ - wpi::StringRef GetRpc() const { + std::string_view GetRpc() const { assert(m_val.type == NT_RPC); return m_string; } @@ -263,10 +262,10 @@ class Value final { * time) * @return The entry value */ - static std::shared_ptr MakeString(const wpi::Twine& value, + static std::shared_ptr MakeString(std::string_view value, uint64_t time = 0) { auto val = std::make_shared(NT_STRING, time, private_init()); - val->m_string = value.str(); + val->m_string = value; val->m_val.data.v_string.str = const_cast(val->m_string.c_str()); val->m_val.data.v_string.len = val->m_string.size(); return val; @@ -298,7 +297,7 @@ class Value final { * time) * @return The entry value */ - static std::shared_ptr MakeRaw(wpi::StringRef value, + static std::shared_ptr MakeRaw(std::string_view value, uint64_t time = 0) { auto val = std::make_shared(NT_RAW, time, private_init()); val->m_string = value; @@ -333,7 +332,7 @@ class Value final { * time) * @return The entry value */ - static std::shared_ptr MakeRpc(wpi::StringRef value, + static std::shared_ptr MakeRpc(std::string_view value, uint64_t time = 0) { auto val = std::make_shared(NT_RPC, time, private_init()); val->m_string = value; diff --git a/ntcore/src/main/native/include/networktables/TableEntryListener.h b/ntcore/src/main/native/include/networktables/TableEntryListener.h index 4930bf0056..180234f386 100644 --- a/ntcore/src/main/native/include/networktables/TableEntryListener.h +++ b/ntcore/src/main/native/include/networktables/TableEntryListener.h @@ -7,8 +7,7 @@ #include #include - -#include +#include namespace nt { @@ -30,10 +29,9 @@ class Value; * * @ingroup ntcore_cpp_api */ -typedef std::function value, int flags)> - TableEntryListener; +using TableEntryListener = std::function value, int flags)>; } // namespace nt diff --git a/ntcore/src/main/native/include/networktables/TableListener.h b/ntcore/src/main/native/include/networktables/TableListener.h index 3e8f8c70cd..cc1113ea61 100644 --- a/ntcore/src/main/native/include/networktables/TableListener.h +++ b/ntcore/src/main/native/include/networktables/TableListener.h @@ -7,8 +7,7 @@ #include #include - -#include +#include namespace nt { @@ -25,9 +24,9 @@ class NetworkTable; * * @ingroup ntcore_cpp_api */ -typedef std::function table)> - TableListener; +using TableListener = + std::function table)>; } // namespace nt diff --git a/ntcore/src/main/native/include/ntcore_cpp.h b/ntcore/src/main/native/include/ntcore_cpp.h index 74bc1e8ac6..2bc517a6d7 100644 --- a/ntcore/src/main/native/include/ntcore_cpp.h +++ b/ntcore/src/main/native/include/ntcore_cpp.h @@ -11,13 +11,12 @@ #include #include #include +#include #include #include #include #include -#include -#include #include "networktables/NetworkTableValue.h" @@ -98,7 +97,7 @@ struct ConnectionInfo { /** NetworkTables RPC Version 1 Definition Parameter */ struct RpcParamDef { RpcParamDef() = default; - RpcParamDef(wpi::StringRef name_, std::shared_ptr def_value_) + RpcParamDef(std::string_view name_, std::shared_ptr def_value_) : name(name_), def_value(std::move(def_value_)) {} std::string name; @@ -108,7 +107,7 @@ struct RpcParamDef { /** NetworkTables RPC Version 1 Definition Result */ struct RpcResultDef { RpcResultDef() = default; - RpcResultDef(wpi::StringRef name_, NT_Type type_) + RpcResultDef(std::string_view name_, NT_Type type_) : name(name_), type(type_) {} std::string name; @@ -127,8 +126,8 @@ struct RpcDefinition { class RpcAnswer { public: RpcAnswer() = default; - RpcAnswer(NT_Entry entry_, NT_RpcCall call_, wpi::StringRef name_, - wpi::StringRef params_, ConnectionInfo conn_) + RpcAnswer(NT_Entry entry_, NT_RpcCall call_, std::string_view name_, + std::string_view params_, ConnectionInfo conn_) : entry(entry_), call(call_), name(name_), @@ -161,7 +160,7 @@ class RpcAnswer { * @param result result raw data that will be provided to remote caller * @return True if posting the response is valid, otherwise false */ - bool PostResponse(wpi::StringRef result) const; + bool PostResponse(std::string_view result) const; friend void swap(RpcAnswer& first, RpcAnswer& second) { using std::swap; @@ -178,7 +177,7 @@ class EntryNotification { public: EntryNotification() = default; EntryNotification(NT_EntryListener listener_, NT_Entry entry_, - wpi::StringRef name_, std::shared_ptr value_, + std::string_view name_, std::shared_ptr value_, unsigned int flags_) : listener(listener_), entry(entry_), @@ -245,7 +244,7 @@ class LogMessage { public: LogMessage() = default; LogMessage(NT_Logger logger_, unsigned int level_, const char* filename_, - unsigned int line_, wpi::StringRef message_) + unsigned int line_, std::string_view message_) : logger(logger_), level(level_), filename(filename_), @@ -327,7 +326,7 @@ NT_Inst GetInstanceFromHandle(NT_Handle handle); * @param name entry name (UTF-8 string) * @return entry handle */ -NT_Entry GetEntry(NT_Inst inst, const wpi::Twine& name); +NT_Entry GetEntry(NT_Inst inst, std::string_view name); /** * Get Entry Handles. @@ -343,7 +342,7 @@ NT_Entry GetEntry(NT_Inst inst, const wpi::Twine& name); * as a "don't care" * @return Array of entry handles. */ -std::vector GetEntries(NT_Inst inst, const wpi::Twine& prefix, +std::vector GetEntries(NT_Inst inst, std::string_view prefix, unsigned int types); /** @@ -484,7 +483,7 @@ void DeleteAllEntries(NT_Inst inst); * as a "don't care" * @return Array of entry information. */ -std::vector GetEntryInfo(NT_Inst inst, const wpi::Twine& prefix, +std::vector GetEntryInfo(NT_Inst inst, std::string_view prefix, unsigned int types); /** @@ -516,9 +515,9 @@ EntryInfo GetEntryInfo(NT_Entry entry); * @param flags update flags; for example, NT_NOTIFY_NEW if the key * did not previously exist */ -typedef std::function value, unsigned int flags)> - EntryListenerCallback; +using EntryListenerCallback = + std::function value, unsigned int flags)>; /** * Add a listener for all entries starting with a certain prefix. @@ -530,7 +529,7 @@ typedef std::function callback, unsigned int flags); @@ -578,7 +577,7 @@ void DestroyEntryListenerPoller(NT_EntryListenerPoller poller); * @return Listener handle */ NT_EntryListener AddPolledEntryListener(NT_EntryListenerPoller poller, - const wpi::Twine& prefix, + std::string_view prefix, unsigned int flags); /** @@ -787,7 +786,7 @@ bool WaitForConnectionListenerQueue(NT_Inst inst, double timeout); * @param callback callback function; note the callback function must call * PostRpcResponse() to provide a response to the call */ -void CreateRpc(NT_Entry entry, wpi::StringRef def, +void CreateRpc(NT_Entry entry, std::string_view def, std::function callback); /** @@ -820,7 +819,7 @@ void DestroyRpcCallPoller(NT_RpcCallPoller poller); * @param def RPC definition * @param poller poller handle */ -void CreatePolledRpc(NT_Entry entry, wpi::StringRef def, +void CreatePolledRpc(NT_Entry entry, std::string_view def, NT_RpcCallPoller poller); /** @@ -884,7 +883,7 @@ bool WaitForRpcCallQueue(NT_Inst inst, double timeout); * @param result result raw data that will be provided to remote caller * @return true if the response was posted, otherwise false */ -bool PostRpcResponse(NT_Entry entry, NT_RpcCall call, wpi::StringRef result); +bool PostRpcResponse(NT_Entry entry, NT_RpcCall call, std::string_view result); /** * Call a RPC function. May be used on either the client or server. @@ -897,7 +896,7 @@ bool PostRpcResponse(NT_Entry entry, NT_RpcCall call, wpi::StringRef result); * @return RPC call handle (for use with GetRpcResult() or * CancelRpcResult()). */ -NT_RpcCall CallRpc(NT_Entry entry, wpi::StringRef params); +NT_RpcCall CallRpc(NT_Entry entry, std::string_view params); /** * Get the result (return value) of a RPC call. This function blocks until @@ -948,7 +947,7 @@ std::string PackRpcDefinition(const RpcDefinition& def); * @param def RPC version 1 definition (output) * @return True if successfully unpacked, false otherwise. */ -bool UnpackRpcDefinition(wpi::StringRef packed, RpcDefinition* def); +bool UnpackRpcDefinition(std::string_view packed, RpcDefinition* def); /** * Pack RPC values as required for RPC version 1 definition messages. @@ -966,7 +965,7 @@ std::string PackRpcValues(wpi::ArrayRef> values); * @return Array of values. */ std::vector> UnpackRpcValues( - wpi::StringRef packed, wpi::ArrayRef types); + std::string_view packed, wpi::ArrayRef types); /** @} */ @@ -983,7 +982,7 @@ std::vector> UnpackRpcValues( * @param inst instance handle * @param name identity to advertise */ -void SetNetworkIdentity(NT_Inst inst, const wpi::Twine& name); +void SetNetworkIdentity(NT_Inst inst, std::string_view name); /** * Get the current network mode. @@ -1016,7 +1015,7 @@ void StopLocal(NT_Inst inst); * address. (UTF-8 string, null terminated) * @param port port to communicate over. */ -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); /** @@ -1051,7 +1050,7 @@ void StartClient(NT_Inst inst, const char* server_name, unsigned int port); */ void StartClient( NT_Inst inst, - wpi::ArrayRef> servers); + wpi::ArrayRef> servers); /** * Starts a client using commonly known robot addresses for the specified @@ -1086,8 +1085,9 @@ void SetServer(NT_Inst inst, const char* server_name, unsigned int port); * @param inst instance handle * @param servers array of server name and port pairs */ -void SetServer(NT_Inst inst, - wpi::ArrayRef> servers); +void SetServer( + NT_Inst inst, + wpi::ArrayRef> servers); /** * Sets server addresses and port for client (without restarting client). @@ -1173,7 +1173,7 @@ bool IsConnected(NT_Inst inst); * @param filename filename * @return error string, or nullptr if successful */ -const char* SavePersistent(NT_Inst inst, const wpi::Twine& filename); +const char* SavePersistent(NT_Inst inst, std::string_view filename); /** * Load persistent values from a file. The server automatically does this @@ -1186,7 +1186,7 @@ const char* SavePersistent(NT_Inst inst, const wpi::Twine& filename); * @return error string, or nullptr if successful */ const char* LoadPersistent( - NT_Inst inst, const wpi::Twine& filename, + NT_Inst inst, std::string_view filename, std::function warn); /** @@ -1198,8 +1198,8 @@ const char* LoadPersistent( * @param prefix save only keys starting with this prefix * @return error string, or nullptr if successful */ -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); /** * Load table values from a file. The file format used is identical to @@ -1211,8 +1211,8 @@ const char* SaveEntries(NT_Inst inst, const wpi::Twine& filename, * @param warn callback function for warnings * @return error string, or nullptr if successful */ -const char* LoadEntries(NT_Inst inst, const wpi::Twine& filename, - const wpi::Twine& prefix, +const char* LoadEntries(NT_Inst inst, std::string_view filename, + std::string_view prefix, std::function warn); /** @} */ @@ -1339,7 +1339,7 @@ bool WaitForLoggerQueue(NT_Inst inst, double timeout); /** @} */ /** @} */ -inline bool RpcAnswer::PostResponse(wpi::StringRef result) const { +inline bool RpcAnswer::PostResponse(std::string_view result) const { auto ret = PostRpcResponse(entry, call, result); call = 0; return ret; diff --git a/ntcore/src/test/native/cpp/EntryNotifierTest.cpp b/ntcore/src/test/native/cpp/EntryNotifierTest.cpp index 54285dc873..e781b49b8c 100644 --- a/ntcore/src/test/native/cpp/EntryNotifierTest.cpp +++ b/ntcore/src/test/native/cpp/EntryNotifierTest.cpp @@ -3,6 +3,7 @@ // the WPILib BSD license file in the root directory of this project. #include +#include #include "EntryNotifier.h" #include "TestPrinters.h" @@ -245,7 +246,7 @@ TEST_F(EntryNotifierTest, PollPrefixBasic) { int g4count = 0; for (const auto& result : results) { SCOPED_TRACE(::testing::PrintToString(result)); - EXPECT_TRUE(wpi::StringRef(result.name).startswith("/foo")); + EXPECT_TRUE(wpi::starts_with(result.name, "/foo")); EXPECT_THAT(result.value, ValueEq(Value::MakeDouble(1))); EXPECT_EQ(Handle{result.entry}.GetType(), Handle::kEntry); EXPECT_EQ(Handle{result.entry}.GetInst(), 1); diff --git a/ntcore/src/test/native/cpp/MockEntryNotifier.h b/ntcore/src/test/native/cpp/MockEntryNotifier.h index 75e5cc3830..58518c687e 100644 --- a/ntcore/src/test/native/cpp/MockEntryNotifier.h +++ b/ntcore/src/test/native/cpp/MockEntryNotifier.h @@ -18,19 +18,19 @@ class MockEntryNotifier : public IEntryNotifier { MOCK_METHOD3( Add, unsigned int(std::function callback, - wpi::StringRef prefix, unsigned int flags)); + std::string_view prefix, unsigned int flags)); MOCK_METHOD3( Add, unsigned int(std::function callback, unsigned int local_id, unsigned int flags)); MOCK_METHOD3(AddPolled, - unsigned int(unsigned int poller_uid, wpi::StringRef prefix, + unsigned int(unsigned int poller_uid, std::string_view prefix, unsigned int flags)); MOCK_METHOD3(AddPolled, unsigned int(unsigned int poller_uid, unsigned int local_id, unsigned int flags)); MOCK_METHOD5(NotifyEntry, - void(unsigned int local_id, wpi::StringRef name, + void(unsigned int local_id, std::string_view name, std::shared_ptr value, unsigned int flags, unsigned int only_listener)); }; diff --git a/ntcore/src/test/native/cpp/MockRpcServer.h b/ntcore/src/test/native/cpp/MockRpcServer.h index 4196008381..be9e5129cf 100644 --- a/ntcore/src/test/native/cpp/MockRpcServer.h +++ b/ntcore/src/test/native/cpp/MockRpcServer.h @@ -16,7 +16,7 @@ class MockRpcServer : public IRpcServer { MOCK_METHOD1(RemoveRpc, void(unsigned int rpc_uid)); MOCK_METHOD7(ProcessRpc, void(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)); }; diff --git a/ntcore/src/test/native/cpp/StorageTest.cpp b/ntcore/src/test/native/cpp/StorageTest.cpp index e8c80539ce..9294be4e87 100644 --- a/ntcore/src/test/native/cpp/StorageTest.cpp +++ b/ntcore/src/test/native/cpp/StorageTest.cpp @@ -4,6 +4,8 @@ #include "StorageTest.h" +#include +#include #include #include @@ -19,7 +21,6 @@ using ::testing::_; using ::testing::AnyNumber; using ::testing::IsNull; using ::testing::Return; -using wpi::StringRef; namespace nt { @@ -86,13 +87,13 @@ class StorageTestPersistent : public StorageTestEmpty { storage.SetEntryTypeValue("double/big", Value::MakeDouble(1.3e8)); storage.SetEntryTypeValue("string/empty", Value::MakeString("")); storage.SetEntryTypeValue("string/normal", Value::MakeString("hello")); - storage.SetEntryTypeValue("string/special", - Value::MakeString(StringRef("\0\3\5\n", 4))); + storage.SetEntryTypeValue( + "string/special", Value::MakeString(std::string_view("\0\3\5\n", 4))); storage.SetEntryTypeValue("string/quoted", Value::MakeString("\"a\"")); storage.SetEntryTypeValue("raw/empty", Value::MakeRaw("")); storage.SetEntryTypeValue("raw/normal", Value::MakeRaw("hello")); storage.SetEntryTypeValue("raw/special", - Value::MakeRaw(StringRef("\0\3\5\n", 4))); + Value::MakeRaw(std::string_view("\0\3\5\n", 4))); storage.SetEntryTypeValue("booleanarr/empty", Value::MakeBooleanArray(std::vector{})); storage.SetEntryTypeValue("booleanarr/one", @@ -114,7 +115,7 @@ class StorageTestPersistent : public StorageTestEmpty { storage.SetEntryTypeValue( "stringarr/two", Value::MakeStringArray(std::vector{"hello", "world\n"})); - storage.SetEntryTypeValue(StringRef("\0\3\5\n", 4), + storage.SetEntryTypeValue(std::string_view("\0\3\5\n", 4), Value::MakeBoolean(true)); storage.SetEntryTypeValue("=", Value::MakeBoolean(true)); ::testing::Mock::VerifyAndClearExpectations(&dispatcher); @@ -127,7 +128,7 @@ class StorageTestPersistent : public StorageTestEmpty { class MockLoadWarn { public: - MOCK_METHOD2(Warn, void(size_t line, wpi::StringRef msg)); + MOCK_METHOD2(Warn, void(size_t line, std::string_view msg)); }; TEST_P(StorageTestEmpty, Construct) { @@ -166,7 +167,7 @@ TEST_P(StorageTestEmpty, SetEntryTypeValueAssignNew) { QueueOutgoing(MessageEq(Message::EntryAssign( "foo", GetParam() ? 0 : 0xffff, 1, value, 0)), IsNull(), IsNull())); - EXPECT_CALL(notifier, NotifyEntry(0, StringRef("foo"), value, + EXPECT_CALL(notifier, NotifyEntry(0, std::string_view("foo"), value, NT_NOTIFY_NEW | NT_NOTIFY_LOCAL, UINT_MAX)); storage.SetEntryTypeValue("foo", value); @@ -189,7 +190,7 @@ TEST_P(StorageTestPopulateOne, SetEntryTypeValueAssignTypeChange) { "foo", GetParam() ? 0 : 0xffff, 2, value, 0)), IsNull(), IsNull())); EXPECT_CALL(notifier, - NotifyEntry(0, StringRef("foo"), value, + NotifyEntry(0, std::string_view("foo"), value, NT_NOTIFY_UPDATE | NT_NOTIFY_LOCAL, UINT_MAX)); storage.SetEntryTypeValue("foo", value); @@ -216,7 +217,7 @@ TEST_P(StorageTestPopulated, SetEntryTypeValueDifferentValue) { IsNull(), IsNull())); } EXPECT_CALL(notifier, - NotifyEntry(1, StringRef("foo2"), value, + NotifyEntry(1, std::string_view("foo2"), value, NT_NOTIFY_UPDATE | NT_NOTIFY_LOCAL, UINT_MAX)); storage.SetEntryTypeValue("foo2", value); EXPECT_EQ(value, GetEntry("foo2")->value); @@ -249,7 +250,7 @@ TEST_P(StorageTestEmpty, SetEntryValueAssignNew) { QueueOutgoing(MessageEq(Message::EntryAssign( "foo", GetParam() ? 0 : 0xffff, 1, value, 0)), IsNull(), IsNull())); - EXPECT_CALL(notifier, NotifyEntry(0, StringRef("foo"), value, + EXPECT_CALL(notifier, NotifyEntry(0, std::string_view("foo"), value, NT_NOTIFY_NEW | NT_NOTIFY_LOCAL, UINT_MAX)); EXPECT_TRUE(storage.SetEntryValue("foo", value)); @@ -285,7 +286,7 @@ TEST_P(StorageTestPopulated, SetEntryValueDifferentValue) { IsNull(), IsNull())); } EXPECT_CALL(notifier, - NotifyEntry(1, StringRef("foo2"), value, + NotifyEntry(1, std::string_view("foo2"), value, NT_NOTIFY_UPDATE | NT_NOTIFY_LOCAL, UINT_MAX)); EXPECT_TRUE(storage.SetEntryValue("foo2", value)); @@ -320,7 +321,7 @@ TEST_P(StorageTestEmpty, SetDefaultEntryAssignNew) { QueueOutgoing(MessageEq(Message::EntryAssign( "foo", GetParam() ? 0 : 0xffff, 1, value, 0)), IsNull(), IsNull())); - EXPECT_CALL(notifier, NotifyEntry(0, StringRef("foo"), value, + EXPECT_CALL(notifier, NotifyEntry(0, std::string_view("foo"), value, NT_NOTIFY_NEW | NT_NOTIFY_LOCAL, UINT_MAX)); auto ret_val = storage.SetDefaultEntryValue("foo", value); @@ -423,7 +424,7 @@ TEST_P(StorageTestPopulated, SetEntryFlagsDifferentValue) { IsNull(), IsNull())); } EXPECT_CALL(notifier, - NotifyEntry(1, StringRef("foo2"), _, + NotifyEntry(1, std::string_view("foo2"), _, NT_NOTIFY_FLAGS | NT_NOTIFY_LOCAL, UINT_MAX)); storage.SetEntryFlags("foo2", 1u); EXPECT_EQ(1u, GetEntry("foo2")->flags); @@ -460,9 +461,10 @@ TEST_P(StorageTestPopulated, DeleteEntryExist) { EXPECT_CALL(dispatcher, QueueOutgoing(MessageEq(Message::EntryDelete(1)), IsNull(), IsNull())); } - EXPECT_CALL(notifier, - NotifyEntry(1, StringRef("foo2"), ValueEq(Value::MakeDouble(0)), - NT_NOTIFY_DELETE | NT_NOTIFY_LOCAL, UINT_MAX)); + EXPECT_CALL( + notifier, + NotifyEntry(1, std::string_view("foo2"), ValueEq(Value::MakeDouble(0)), + NT_NOTIFY_DELETE | NT_NOTIFY_LOCAL, UINT_MAX)); storage.DeleteEntry("foo2"); ASSERT_EQ(1u, entries().count("foo2")); @@ -562,58 +564,58 @@ TEST_P(StorageTestPersistent, SavePersistent) { wpi::SmallString<256> buf; wpi::raw_svector_ostream oss(buf); storage.SavePersistent(oss, false); - wpi::StringRef out = oss.str(); + std::string_view out = oss.str(); // std::fputs(out.c_str(), stderr); - wpi::StringRef line, rem = out; - std::tie(line, rem) = rem.split('\n'); + std::string_view line, rem = out; + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("[NetworkTables Storage 3.0]", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("boolean \"\\x00\\x03\\x05\\n\"=true", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("boolean \"\\x3D\"=true", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("boolean \"boolean/false\"=false", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("boolean \"boolean/true\"=true", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array boolean \"booleanarr/empty\"=", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array boolean \"booleanarr/one\"=true", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array boolean \"booleanarr/two\"=true,false", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("double \"double/big\"=1.3e+08", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("double \"double/neg\"=-1.5", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("double \"double/zero\"=0", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array double \"doublearr/empty\"=", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array double \"doublearr/one\"=0.5", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array double \"doublearr/two\"=0.5,-0.25", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("raw \"raw/empty\"=", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("raw \"raw/normal\"=aGVsbG8=", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("raw \"raw/special\"=AAMFCg==", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("string \"string/empty\"=\"\"", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("string \"string/normal\"=\"hello\"", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("string \"string/quoted\"=\"\\\"a\\\"\"", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("string \"string/special\"=\"\\x00\\x03\\x05\\n\"", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array string \"stringarr/empty\"=", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array string \"stringarr/one\"=\"hello\"", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("array string \"stringarr/two\"=\"hello\",\"world\\n\"", line); - std::tie(line, rem) = rem.split('\n'); + std::tie(line, rem) = wpi::split(rem, '\n'); ASSERT_EQ("", line); } @@ -624,13 +626,13 @@ TEST_P(StorageTestEmpty, LoadPersistentBadHeader) { wpi::raw_mem_istream iss(""); EXPECT_CALL( warn, - Warn(1, wpi::StringRef("header line mismatch, ignoring rest of file"))); + Warn(1, std::string_view("header line mismatch, ignoring rest of file"))); EXPECT_FALSE(storage.LoadEntries(iss, "", true, warn_func)); wpi::raw_mem_istream iss2("[NetworkTables"); EXPECT_CALL( warn, - Warn(1, wpi::StringRef("header line mismatch, ignoring rest of file"))); + Warn(1, std::string_view("header line mismatch, ignoring rest of file"))); EXPECT_FALSE(storage.LoadEntries(iss2, "", true, warn_func)); EXPECT_TRUE(entries().empty()); @@ -669,7 +671,7 @@ TEST_P(StorageTestEmpty, LoadPersistentAssign) { "foo", GetParam() ? 0 : 0xffff, 1, value, NT_PERSISTENT)), IsNull(), IsNull())); - EXPECT_CALL(notifier, NotifyEntry(0, StringRef("foo"), + EXPECT_CALL(notifier, NotifyEntry(0, std::string_view("foo"), ValueEq(Value::MakeBoolean(true)), NT_NOTIFY_NEW | NT_NOTIFY_LOCAL, UINT_MAX)); @@ -692,9 +694,10 @@ TEST_P(StorageTestPopulated, LoadPersistentUpdateFlags) { QueueOutgoing(MessageEq(Message::FlagsUpdate(1, NT_PERSISTENT)), IsNull(), IsNull())); } - EXPECT_CALL(notifier, - NotifyEntry(1, StringRef("foo2"), ValueEq(Value::MakeDouble(0)), - NT_NOTIFY_FLAGS | NT_NOTIFY_LOCAL, UINT_MAX)); + EXPECT_CALL( + notifier, + NotifyEntry(1, std::string_view("foo2"), ValueEq(Value::MakeDouble(0)), + NT_NOTIFY_FLAGS | NT_NOTIFY_LOCAL, UINT_MAX)); wpi::raw_mem_istream iss( "[NetworkTables Storage 3.0]\ndouble \"foo2\"=0.0\n"); @@ -719,9 +722,10 @@ TEST_P(StorageTestPopulated, LoadPersistentUpdateValue) { QueueOutgoing(MessageEq(Message::EntryUpdate(1, 2, value)), IsNull(), IsNull())); } - EXPECT_CALL(notifier, - NotifyEntry(1, StringRef("foo2"), ValueEq(Value::MakeDouble(1)), - NT_NOTIFY_UPDATE | NT_NOTIFY_LOCAL, UINT_MAX)); + EXPECT_CALL( + notifier, + NotifyEntry(1, std::string_view("foo2"), ValueEq(Value::MakeDouble(1)), + NT_NOTIFY_UPDATE | NT_NOTIFY_LOCAL, UINT_MAX)); wpi::raw_mem_istream iss( "[NetworkTables Storage 3.0]\ndouble \"foo2\"=1.0\n"); @@ -752,10 +756,11 @@ TEST_P(StorageTestPopulated, LoadPersistentUpdateValueFlags) { QueueOutgoing(MessageEq(Message::FlagsUpdate(1, NT_PERSISTENT)), IsNull(), IsNull())); } - EXPECT_CALL(notifier, - NotifyEntry(1, StringRef("foo2"), ValueEq(Value::MakeDouble(1)), - NT_NOTIFY_FLAGS | NT_NOTIFY_UPDATE | NT_NOTIFY_LOCAL, - UINT_MAX)); + EXPECT_CALL( + notifier, + NotifyEntry(1, std::string_view("foo2"), ValueEq(Value::MakeDouble(1)), + NT_NOTIFY_FLAGS | NT_NOTIFY_UPDATE | NT_NOTIFY_LOCAL, + UINT_MAX)); wpi::raw_mem_istream iss( "[NetworkTables Storage 3.0]\ndouble \"foo2\"=1.0\n"); @@ -817,13 +822,13 @@ TEST_P(StorageTestEmpty, LoadPersistent) { EXPECT_EQ(*Value::MakeString(""), *storage.GetEntryValue("string/empty")); EXPECT_EQ(*Value::MakeString("hello"), *storage.GetEntryValue("string/normal")); - EXPECT_EQ(*Value::MakeString(StringRef("\0\3\5\n", 4)), + EXPECT_EQ(*Value::MakeString(std::string_view("\0\3\5\n", 4)), *storage.GetEntryValue("string/special")); EXPECT_EQ(*Value::MakeString("\"a\""), *storage.GetEntryValue("string/quoted")); EXPECT_EQ(*Value::MakeRaw(""), *storage.GetEntryValue("raw/empty")); EXPECT_EQ(*Value::MakeRaw("hello"), *storage.GetEntryValue("raw/normal")); - EXPECT_EQ(*Value::MakeRaw(StringRef("\0\3\5\n", 4)), + EXPECT_EQ(*Value::MakeRaw(std::string_view("\0\3\5\n", 4)), *storage.GetEntryValue("raw/special")); EXPECT_EQ(*Value::MakeBooleanArray(std::vector{}), *storage.GetEntryValue("booleanarr/empty")); @@ -845,7 +850,7 @@ TEST_P(StorageTestEmpty, LoadPersistent) { *Value::MakeStringArray(std::vector{"hello", "world\n"}), *storage.GetEntryValue("stringarr/two")); EXPECT_EQ(*Value::MakeBoolean(true), - *storage.GetEntryValue(StringRef("\0\3\5\n", 4))); + *storage.GetEntryValue(std::string_view("\0\3\5\n", 4))); EXPECT_EQ(*Value::MakeBoolean(true), *storage.GetEntryValue("=")); } @@ -856,7 +861,7 @@ TEST_P(StorageTestEmpty, LoadPersistentWarn) { wpi::raw_mem_istream iss( "[NetworkTables Storage 3.0]\nboolean \"foo\"=foo\n"); EXPECT_CALL( - warn, Warn(2, wpi::StringRef( + warn, Warn(2, std::string_view( "unrecognized boolean value, not 'true' or 'false'"))); EXPECT_TRUE(storage.LoadEntries(iss, "", true, warn_func)); @@ -874,7 +879,7 @@ TEST_P(StorageTestEmpty, ProcessIncomingEntryAssign) { QueueOutgoing(MessageEq(Message::EntryAssign("foo", 0, 0, value, 0)), IsNull(), IsNull())); } - EXPECT_CALL(notifier, NotifyEntry(0, StringRef("foo"), ValueEq(value), + EXPECT_CALL(notifier, NotifyEntry(0, std::string_view("foo"), ValueEq(value), NT_NOTIFY_NEW, UINT_MAX)); storage.ProcessIncoming( @@ -893,7 +898,7 @@ TEST_P(StorageTestPopulateOne, ProcessIncomingEntryAssign) { QueueOutgoing(MessageEq(Message::EntryAssign("foo", 0, 1, value, 0)), IsNull(), conn.get())); } - EXPECT_CALL(notifier, NotifyEntry(0, StringRef("foo"), ValueEq(value), + EXPECT_CALL(notifier, NotifyEntry(0, std::string_view("foo"), ValueEq(value), NT_NOTIFY_UPDATE, UINT_MAX)); storage.ProcessIncoming(Message::EntryAssign("foo", 0, 1, value, 0), @@ -918,15 +923,16 @@ TEST_P(StorageTestPopulateOne, ProcessIncomingEntryAssignWithFlags) { QueueOutgoing(MessageEq(Message::EntryAssign("foo", 0, 1, value, 0x2)), IsNull(), conn.get())); EXPECT_CALL(notifier, - NotifyEntry(0, StringRef("foo"), ValueEq(value), + NotifyEntry(0, std::string_view("foo"), ValueEq(value), NT_NOTIFY_UPDATE | NT_NOTIFY_FLAGS, UINT_MAX)); } else { // client forces flags back when an assign message is received for an // existing entry with different flags EXPECT_CALL(dispatcher, QueueOutgoing(MessageEq(Message::FlagsUpdate(0, 0)), IsNull(), IsNull())); - EXPECT_CALL(notifier, NotifyEntry(0, StringRef("foo"), ValueEq(value), - NT_NOTIFY_UPDATE, UINT_MAX)); + EXPECT_CALL(notifier, + NotifyEntry(0, std::string_view("foo"), ValueEq(value), + NT_NOTIFY_UPDATE, UINT_MAX)); } storage.ProcessIncoming(Message::EntryAssign("foo", 0, 1, value, 0x2), diff --git a/ntcore/src/test/native/cpp/StorageTest.h b/ntcore/src/test/native/cpp/StorageTest.h index 782a9f1edb..3a1755f048 100644 --- a/ntcore/src/test/native/cpp/StorageTest.h +++ b/ntcore/src/test/native/cpp/StorageTest.h @@ -24,7 +24,7 @@ class StorageTest { Storage::EntriesMap& entries() { return storage.m_entries; } Storage::IdMap& idmap() { return storage.m_idmap; } - Storage::Entry* GetEntry(wpi::StringRef name) { + Storage::Entry* GetEntry(std::string_view name) { auto i = storage.m_entries.find(name); return i == storage.m_entries.end() ? &tmp_entry : i->getValue(); } diff --git a/ntcore/src/test/native/cpp/TestPrinters.cpp b/ntcore/src/test/native/cpp/TestPrinters.cpp index f99529e210..49b407ba24 100644 --- a/ntcore/src/test/native/cpp/TestPrinters.cpp +++ b/ntcore/src/test/native/cpp/TestPrinters.cpp @@ -126,7 +126,7 @@ void PrintTo(const Value& value, std::ostream* os) { *os << value.GetDouble(); break; case NT_STRING: - *os << '"' << value.GetString().str() << '"'; + *os << '"' << value.GetString() << '"'; break; case NT_RAW: *os << ::testing::PrintToString(value.GetRaw()); diff --git a/ntcore/src/test/native/cpp/TestPrinters.h b/ntcore/src/test/native/cpp/TestPrinters.h index 9c9ae0140a..47c9eb4955 100644 --- a/ntcore/src/test/native/cpp/TestPrinters.h +++ b/ntcore/src/test/native/cpp/TestPrinters.h @@ -7,15 +7,15 @@ #include #include - -#include +#include +#include #include "gtest/gtest.h" namespace wpi { -inline void PrintTo(StringRef str, ::std::ostream* os) { - ::testing::internal::PrintStringTo(str.str(), os); +inline void PrintTo(std::string_view str, ::std::ostream* os) { + ::testing::internal::PrintStringTo(std::string{str}, os); } } // namespace wpi diff --git a/ntcore/src/test/native/cpp/ValueTest.cpp b/ntcore/src/test/native/cpp/ValueTest.cpp index 10ae2353ac..271f7b67ae 100644 --- a/ntcore/src/test/native/cpp/ValueTest.cpp +++ b/ntcore/src/test/native/cpp/ValueTest.cpp @@ -2,11 +2,15 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include + #include "TestPrinters.h" #include "Value_internal.h" #include "gtest/gtest.h" #include "networktables/NetworkTableValue.h" +using namespace std::string_view_literals; + namespace nt { class ValueTest : public ::testing::Test {}; @@ -66,7 +70,7 @@ TEST_F(ValueTest, String) { NT_InitValue(&cv); ConvertToC(*v, &cv); ASSERT_EQ(NT_STRING, cv.type); - ASSERT_EQ(wpi::StringRef("hello"), cv.data.v_string.str); + ASSERT_EQ("hello"sv, cv.data.v_string.str); ASSERT_EQ(5u, cv.data.v_string.len); v = Value::MakeString("goodbye"); @@ -74,7 +78,7 @@ TEST_F(ValueTest, String) { ASSERT_EQ("goodbye", v->GetString()); ConvertToC(*v, &cv); ASSERT_EQ(NT_STRING, cv.type); - ASSERT_EQ(wpi::StringRef("goodbye"), cv.data.v_string.str); + ASSERT_EQ("goodbye"sv, cv.data.v_string.str); ASSERT_EQ(7u, cv.data.v_string.len); NT_DisposeValue(&cv); @@ -88,7 +92,7 @@ TEST_F(ValueTest, Raw) { NT_InitValue(&cv); ConvertToC(*v, &cv); ASSERT_EQ(NT_RAW, cv.type); - ASSERT_EQ(wpi::StringRef("hello"), cv.data.v_string.str); + ASSERT_EQ("hello"sv, cv.data.v_string.str); ASSERT_EQ(5u, cv.data.v_string.len); v = Value::MakeRaw("goodbye"); @@ -96,7 +100,7 @@ TEST_F(ValueTest, Raw) { ASSERT_EQ("goodbye", v->GetRaw()); ConvertToC(*v, &cv); ASSERT_EQ(NT_RAW, cv.type); - ASSERT_EQ(wpi::StringRef("goodbye"), cv.data.v_string.str); + ASSERT_EQ("goodbye"sv, cv.data.v_string.str); ASSERT_EQ(7u, cv.data.v_string.len); NT_DisposeValue(&cv); @@ -190,17 +194,17 @@ TEST_F(ValueTest, StringArray) { auto v = Value::MakeStringArray(std::move(vec)); ASSERT_EQ(NT_STRING_ARRAY, v->type()); ASSERT_EQ(3u, v->GetStringArray().size()); - ASSERT_EQ(wpi::StringRef("hello"), v->GetStringArray()[0]); - ASSERT_EQ(wpi::StringRef("goodbye"), v->GetStringArray()[1]); - ASSERT_EQ(wpi::StringRef("string"), v->GetStringArray()[2]); + ASSERT_EQ("hello"sv, v->GetStringArray()[0]); + ASSERT_EQ("goodbye"sv, v->GetStringArray()[1]); + ASSERT_EQ("string"sv, v->GetStringArray()[2]); NT_Value cv; NT_InitValue(&cv); ConvertToC(*v, &cv); ASSERT_EQ(NT_STRING_ARRAY, cv.type); ASSERT_EQ(3u, cv.data.arr_string.size); - ASSERT_EQ(wpi::StringRef("hello"), cv.data.arr_string.arr[0].str); - ASSERT_EQ(wpi::StringRef("goodbye"), cv.data.arr_string.arr[1].str); - ASSERT_EQ(wpi::StringRef("string"), cv.data.arr_string.arr[2].str); + ASSERT_EQ("hello"sv, cv.data.arr_string.arr[0].str); + ASSERT_EQ("goodbye"sv, cv.data.arr_string.arr[1].str); + ASSERT_EQ("string"sv, cv.data.arr_string.arr[2].str); // assign with same size vec.clear(); @@ -210,15 +214,15 @@ TEST_F(ValueTest, StringArray) { v = Value::MakeStringArray(vec); ASSERT_EQ(NT_STRING_ARRAY, v->type()); ASSERT_EQ(3u, v->GetStringArray().size()); - ASSERT_EQ(wpi::StringRef("s1"), v->GetStringArray()[0]); - ASSERT_EQ(wpi::StringRef("str2"), v->GetStringArray()[1]); - ASSERT_EQ(wpi::StringRef("string3"), v->GetStringArray()[2]); + ASSERT_EQ("s1"sv, v->GetStringArray()[0]); + ASSERT_EQ("str2"sv, v->GetStringArray()[1]); + ASSERT_EQ("string3"sv, v->GetStringArray()[2]); ConvertToC(*v, &cv); ASSERT_EQ(NT_STRING_ARRAY, cv.type); ASSERT_EQ(3u, cv.data.arr_string.size); - ASSERT_EQ(wpi::StringRef("s1"), cv.data.arr_string.arr[0].str); - ASSERT_EQ(wpi::StringRef("str2"), cv.data.arr_string.arr[1].str); - ASSERT_EQ(wpi::StringRef("string3"), cv.data.arr_string.arr[2].str); + ASSERT_EQ("s1"sv, cv.data.arr_string.arr[0].str); + ASSERT_EQ("str2"sv, cv.data.arr_string.arr[1].str); + ASSERT_EQ("string3"sv, cv.data.arr_string.arr[2].str); // assign with different size vec.clear(); @@ -227,13 +231,13 @@ TEST_F(ValueTest, StringArray) { v = Value::MakeStringArray(std::move(vec)); ASSERT_EQ(NT_STRING_ARRAY, v->type()); ASSERT_EQ(2u, v->GetStringArray().size()); - ASSERT_EQ(wpi::StringRef("short"), v->GetStringArray()[0]); - ASSERT_EQ(wpi::StringRef("er"), v->GetStringArray()[1]); + ASSERT_EQ("short"sv, v->GetStringArray()[0]); + ASSERT_EQ("er"sv, v->GetStringArray()[1]); ConvertToC(*v, &cv); ASSERT_EQ(NT_STRING_ARRAY, cv.type); ASSERT_EQ(2u, cv.data.arr_string.size); - ASSERT_EQ(wpi::StringRef("short"), cv.data.arr_string.arr[0].str); - ASSERT_EQ(wpi::StringRef("er"), cv.data.arr_string.arr[1].str); + ASSERT_EQ("short"sv, cv.data.arr_string.arr[0].str); + ASSERT_EQ("er"sv, cv.data.arr_string.arr[1].str); NT_DisposeValue(&cv); } diff --git a/ntcore/src/test/native/cpp/WireDecoderTest.cpp b/ntcore/src/test/native/cpp/WireDecoderTest.cpp index b2c87b458f..313fd989c7 100644 --- a/ntcore/src/test/native/cpp/WireDecoderTest.cpp +++ b/ntcore/src/test/native/cpp/WireDecoderTest.cpp @@ -7,13 +7,14 @@ #include #include #include - -#include +#include #include "TestPrinters.h" #include "WireDecoder.h" #include "gtest/gtest.h" +using namespace std::string_view_literals; + namespace nt { class WireDecoderTest : public ::testing::Test { @@ -21,8 +22,8 @@ class WireDecoderTest : public ::testing::Test { WireDecoderTest() { v_boolean = Value::MakeBoolean(true); v_double = Value::MakeDouble(1.0); - v_string = Value::MakeString(wpi::StringRef("hello")); - v_raw = Value::MakeRaw(wpi::StringRef("hello")); + v_string = Value::MakeString("hello"sv); + v_raw = Value::MakeRaw("hello"sv); v_boolean_array = Value::MakeBooleanArray(std::vector{0, 1, 0}); v_boolean_array_big = Value::MakeBooleanArray(std::vector(255)); v_double_array = Value::MakeDoubleArray(std::vector{0.5, 0.25}); @@ -268,7 +269,7 @@ TEST_F(WireDecoderTest, ReadStringValue2) { ASSERT_TRUE(static_cast(val)); EXPECT_EQ(*v_string, *val); - auto v_bye = Value::MakeString(wpi::StringRef("bye")); + auto v_bye = Value::MakeString("bye"sv); val = d.ReadValue(NT_STRING); ASSERT_TRUE(static_cast(val)); EXPECT_EQ(*v_bye, *val); @@ -443,7 +444,7 @@ TEST_F(WireDecoderTest, ReadStringValue3) { ASSERT_TRUE(static_cast(val)); EXPECT_EQ(*v_string, *val); - auto v_bye = Value::MakeString(wpi::StringRef("bye")); + auto v_bye = Value::MakeString("bye"sv); val = d.ReadValue(NT_STRING); ASSERT_TRUE(static_cast(val)); EXPECT_EQ(*v_bye, *val); @@ -467,7 +468,7 @@ TEST_F(WireDecoderTest, ReadRawValue3) { ASSERT_TRUE(static_cast(val)); EXPECT_EQ(*v_raw, *val); - auto v_bye = Value::MakeRaw(wpi::StringRef("bye")); + auto v_bye = Value::MakeRaw("bye"sv); val = d.ReadValue(NT_RAW); ASSERT_TRUE(static_cast(val)); EXPECT_EQ(*v_bye, *val); diff --git a/ntcore/src/test/native/cpp/WireEncoderTest.cpp b/ntcore/src/test/native/cpp/WireEncoderTest.cpp index 46e362281c..b7141127d1 100644 --- a/ntcore/src/test/native/cpp/WireEncoderTest.cpp +++ b/ntcore/src/test/native/cpp/WireEncoderTest.cpp @@ -5,8 +5,7 @@ #include #include #include - -#include +#include #include "TestPrinters.h" #include "WireEncoder.h" @@ -14,6 +13,8 @@ #define BUFSIZE 1024 +using namespace std::string_view_literals; + namespace nt { class WireEncoderTest : public ::testing::Test { @@ -22,8 +23,8 @@ class WireEncoderTest : public ::testing::Test { v_empty = std::make_shared(); v_boolean = Value::MakeBoolean(true); v_double = Value::MakeDouble(1.0); - v_string = Value::MakeString(wpi::StringRef("hello")); - v_raw = Value::MakeRaw(wpi::StringRef("hello")); + v_string = Value::MakeString("hello"sv); + v_raw = Value::MakeRaw("hello"sv); v_boolean_array = Value::MakeBooleanArray(std::vector{0, 1, 0}); v_boolean_array_big = Value::MakeBooleanArray(std::vector(256)); v_double_array = Value::MakeDoubleArray(std::vector{0.5, 0.25}); @@ -83,8 +84,7 @@ TEST_F(WireEncoderTest, Write8) { e.Write8(0x101u); // should be truncated e.Write8(0u); ASSERT_EQ(3u, e.size() - off); - ASSERT_EQ(wpi::StringRef("\x05\x01\x00", 3), - wpi::StringRef(e.data(), e.size()).substr(off)); + ASSERT_EQ("\x05\x01\x00"sv, std::string_view(e.data(), e.size()).substr(off)); } TEST_F(WireEncoderTest, Write16) { @@ -98,8 +98,8 @@ TEST_F(WireEncoderTest, Write16) { e.Write16(0x4567u); e.Write16(0u); ASSERT_EQ(8u, e.size() - off); - ASSERT_EQ(wpi::StringRef("\x00\x05\x00\x01\x45\x67\x00\x00", 8), - wpi::StringRef(e.data(), e.size()).substr(off)); + ASSERT_EQ("\x00\x05\x00\x01\x45\x67\x00\x00"sv, + std::string_view(e.data(), e.size()).substr(off)); } TEST_F(WireEncoderTest, Write32) { @@ -114,10 +114,10 @@ TEST_F(WireEncoderTest, Write32) { e.Write32(0x12345678ul); e.Write32(0ul); ASSERT_EQ(20u, e.size() - off); - ASSERT_EQ(wpi::StringRef("\x00\x00\x00\x05\x00\x00\x00\x01\x00\x00\xab\xcd" - "\x12\x34\x56\x78\x00\x00\x00\x00", - 20), - wpi::StringRef(e.data(), e.size()).substr(off)); + ASSERT_EQ(std::string_view("\x00\x00\x00\x05\x00\x00\x00\x01\x00\x00\xab\xcd" + "\x12\x34\x56\x78\x00\x00\x00\x00", + 20), + std::string_view(e.data(), e.size()).substr(off)); } TEST_F(WireEncoderTest, WriteDouble) { @@ -134,13 +134,13 @@ TEST_F(WireEncoderTest, WriteDouble) { ASSERT_EQ(40u, e.size() - off); // golden values except min and max from // http://www.binaryconvert.com/result_double.html - ASSERT_EQ(wpi::StringRef("\x00\x00\x00\x00\x00\x00\x00\x00" - "\x41\x0c\x13\x80\x00\x00\x00\x00" - "\x7f\xf0\x00\x00\x00\x00\x00\x00" - "\x00\x10\x00\x00\x00\x00\x00\x00" - "\x7f\xef\xff\xff\xff\xff\xff\xff", - 40), - wpi::StringRef(e.data(), e.size()).substr(off)); + ASSERT_EQ(std::string_view("\x00\x00\x00\x00\x00\x00\x00\x00" + "\x41\x0c\x13\x80\x00\x00\x00\x00" + "\x7f\xf0\x00\x00\x00\x00\x00\x00" + "\x00\x10\x00\x00\x00\x00\x00\x00" + "\x7f\xef\xff\xff\xff\xff\xff\xff", + 40), + std::string_view(e.data(), e.size()).substr(off)); } TEST_F(WireEncoderTest, WriteUleb128) { @@ -153,8 +153,8 @@ TEST_F(WireEncoderTest, WriteUleb128) { e.WriteUleb128(0x7ful); e.WriteUleb128(0x80ul); ASSERT_EQ(4u, e.size() - off); - ASSERT_EQ(wpi::StringRef("\x00\x7f\x80\x01", 4), - wpi::StringRef(e.data(), e.size()).substr(off)); + ASSERT_EQ("\x00\x7f\x80\x01"sv, + std::string_view(e.data(), e.size()).substr(off)); } TEST_F(WireEncoderTest, WriteType) { @@ -173,8 +173,8 @@ TEST_F(WireEncoderTest, WriteType) { e.WriteType(NT_RPC); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(8u, e.size() - off); - ASSERT_EQ(wpi::StringRef("\x00\x01\x02\x03\x10\x11\x12\x20", 8), - wpi::StringRef(e.data(), e.size()).substr(off)); + ASSERT_EQ("\x00\x01\x02\x03\x10\x11\x12\x20"sv, + std::string_view(e.data(), e.size()).substr(off)); } TEST_F(WireEncoderTest, WriteTypeError) { @@ -235,7 +235,7 @@ TEST_F(WireEncoderTest, WriteBooleanValue2) { e.WriteValue(*v_false); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(2u, e.size()); - ASSERT_EQ(wpi::StringRef("\x01\x00", 2), wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x01\x00"sv, std::string_view(e.data(), e.size())); } TEST_F(WireEncoderTest, WriteDoubleValue2) { @@ -243,8 +243,8 @@ TEST_F(WireEncoderTest, WriteDoubleValue2) { e.WriteValue(*v_double); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(8u, e.size()); - ASSERT_EQ(wpi::StringRef("\x3f\xf0\x00\x00\x00\x00\x00\x00", 8), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x3f\xf0\x00\x00\x00\x00\x00\x00"sv, + std::string_view(e.data(), e.size())); } TEST_F(WireEncoderTest, WriteStringValue2) { @@ -252,8 +252,7 @@ TEST_F(WireEncoderTest, WriteStringValue2) { e.WriteValue(*v_string); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(7u, e.size()); - ASSERT_EQ(wpi::StringRef("\x00\x05hello", 7), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x00\x05hello"sv, std::string_view(e.data(), e.size())); } TEST_F(WireEncoderTest, WriteBooleanArrayValue2) { @@ -261,15 +260,14 @@ TEST_F(WireEncoderTest, WriteBooleanArrayValue2) { e.WriteValue(*v_boolean_array); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 3u, e.size()); - ASSERT_EQ(wpi::StringRef("\x03\x00\x01\x00", 4), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x03\x00\x01\x00"sv, std::string_view(e.data(), e.size())); // truncated e.Reset(); e.WriteValue(*v_boolean_array_big); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 255u, e.size()); - ASSERT_EQ(wpi::StringRef("\xff\x00", 2), wpi::StringRef(e.data(), 2)); + ASSERT_EQ("\xff\x00"sv, std::string_view(e.data(), 2)); } TEST_F(WireEncoderTest, WriteDoubleArrayValue2) { @@ -277,17 +275,17 @@ TEST_F(WireEncoderTest, WriteDoubleArrayValue2) { e.WriteValue(*v_double_array); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 2u * 8u, e.size()); - ASSERT_EQ(wpi::StringRef("\x02\x3f\xe0\x00\x00\x00\x00\x00\x00" - "\x3f\xd0\x00\x00\x00\x00\x00\x00", - 17), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ(std::string_view("\x02\x3f\xe0\x00\x00\x00\x00\x00\x00" + "\x3f\xd0\x00\x00\x00\x00\x00\x00", + 17), + std::string_view(e.data(), e.size())); // truncated e.Reset(); e.WriteValue(*v_double_array_big); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 255u * 8u, e.size()); - ASSERT_EQ(wpi::StringRef("\xff\x00", 2), wpi::StringRef(e.data(), 2)); + ASSERT_EQ("\xff\x00"sv, std::string_view(e.data(), 2)); } TEST_F(WireEncoderTest, WriteStringArrayValue2) { @@ -295,15 +293,15 @@ TEST_F(WireEncoderTest, WriteStringArrayValue2) { e.WriteValue(*v_string_array); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 7u + 9u, e.size()); - ASSERT_EQ(wpi::StringRef("\x02\x00\x05hello\x00\x07goodbye", 17), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x02\x00\x05hello\x00\x07goodbye"sv, + std::string_view(e.data(), e.size())); // truncated e.Reset(); e.WriteValue(*v_string_array_big); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 255u * 3u, e.size()); - ASSERT_EQ(wpi::StringRef("\xff\x00\x01", 3), wpi::StringRef(e.data(), 3)); + ASSERT_EQ("\xff\x00\x01"sv, std::string_view(e.data(), 3)); } TEST_F(WireEncoderTest, WriteValueError2) { @@ -346,7 +344,7 @@ TEST_F(WireEncoderTest, WriteBooleanValue3) { e.WriteValue(*v_false); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(2u, e.size()); - ASSERT_EQ(wpi::StringRef("\x01\x00", 2), wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x01\x00"sv, std::string_view(e.data(), e.size())); } TEST_F(WireEncoderTest, WriteDoubleValue3) { @@ -354,8 +352,8 @@ TEST_F(WireEncoderTest, WriteDoubleValue3) { e.WriteValue(*v_double); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(8u, e.size()); - ASSERT_EQ(wpi::StringRef("\x3f\xf0\x00\x00\x00\x00\x00\x00", 8), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x3f\xf0\x00\x00\x00\x00\x00\x00"sv, + std::string_view(e.data(), e.size())); } TEST_F(WireEncoderTest, WriteStringValue3) { @@ -363,7 +361,7 @@ TEST_F(WireEncoderTest, WriteStringValue3) { e.WriteValue(*v_string); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(6u, e.size()); - ASSERT_EQ(wpi::StringRef("\x05hello", 6), wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x05hello"sv, std::string_view(e.data(), e.size())); } TEST_F(WireEncoderTest, WriteRawValue3) { @@ -371,7 +369,7 @@ TEST_F(WireEncoderTest, WriteRawValue3) { e.WriteValue(*v_raw); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(6u, e.size()); - ASSERT_EQ(wpi::StringRef("\x05hello", 6), wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x05hello"sv, std::string_view(e.data(), e.size())); } TEST_F(WireEncoderTest, WriteBooleanArrayValue3) { @@ -379,15 +377,14 @@ TEST_F(WireEncoderTest, WriteBooleanArrayValue3) { e.WriteValue(*v_boolean_array); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 3u, e.size()); - ASSERT_EQ(wpi::StringRef("\x03\x00\x01\x00", 4), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x03\x00\x01\x00"sv, std::string_view(e.data(), e.size())); // truncated e.Reset(); e.WriteValue(*v_boolean_array_big); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 255u, e.size()); - ASSERT_EQ(wpi::StringRef("\xff\x00", 2), wpi::StringRef(e.data(), 2)); + ASSERT_EQ("\xff\x00"sv, std::string_view(e.data(), 2)); } TEST_F(WireEncoderTest, WriteDoubleArrayValue3) { @@ -395,17 +392,17 @@ TEST_F(WireEncoderTest, WriteDoubleArrayValue3) { e.WriteValue(*v_double_array); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 2u * 8u, e.size()); - ASSERT_EQ(wpi::StringRef("\x02\x3f\xe0\x00\x00\x00\x00\x00\x00" - "\x3f\xd0\x00\x00\x00\x00\x00\x00", - 17), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ(std::string_view("\x02\x3f\xe0\x00\x00\x00\x00\x00\x00" + "\x3f\xd0\x00\x00\x00\x00\x00\x00", + 17), + std::string_view(e.data(), e.size())); // truncated e.Reset(); e.WriteValue(*v_double_array_big); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 255u * 8u, e.size()); - ASSERT_EQ(wpi::StringRef("\xff\x00", 2), wpi::StringRef(e.data(), 2)); + ASSERT_EQ("\xff\x00"sv, std::string_view(e.data(), 2)); } TEST_F(WireEncoderTest, WriteStringArrayValue3) { @@ -413,15 +410,14 @@ TEST_F(WireEncoderTest, WriteStringArrayValue3) { e.WriteValue(*v_string_array); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 6u + 8u, e.size()); - ASSERT_EQ(wpi::StringRef("\x02\x05hello\x07goodbye", 15), - wpi::StringRef(e.data(), e.size())); + ASSERT_EQ("\x02\x05hello\x07goodbye"sv, std::string_view(e.data(), e.size())); // truncated e.Reset(); e.WriteValue(*v_string_array_big); ASSERT_EQ(nullptr, e.error()); ASSERT_EQ(1u + 255u * 2u, e.size()); - ASSERT_EQ(wpi::StringRef("\xff\x01", 2), wpi::StringRef(e.data(), 2)); + ASSERT_EQ("\xff\x01"sv, std::string_view(e.data(), 2)); } TEST_F(WireEncoderTest, WriteValueError3) { @@ -445,14 +441,13 @@ TEST_F(WireEncoderTest, WriteString2) { e.WriteString(s_normal); EXPECT_EQ(nullptr, e.error()); EXPECT_EQ(7u, e.size()); - EXPECT_EQ(wpi::StringRef("\x00\x05hello", 7), - wpi::StringRef(e.data(), e.size())); + EXPECT_EQ("\x00\x05hello"sv, std::string_view(e.data(), e.size())); e.Reset(); e.WriteString(s_long); EXPECT_EQ(nullptr, e.error()); ASSERT_EQ(130u, e.size()); - EXPECT_EQ(wpi::StringRef("\x00\x80**", 4), wpi::StringRef(e.data(), 4)); + EXPECT_EQ("\x00\x80**"sv, std::string_view(e.data(), 4)); EXPECT_EQ('*', e.data()[128]); EXPECT_EQ('x', e.data()[129]); @@ -461,7 +456,7 @@ TEST_F(WireEncoderTest, WriteString2) { e.WriteString(s_big); EXPECT_EQ(nullptr, e.error()); ASSERT_EQ(65537u, e.size()); - EXPECT_EQ(wpi::StringRef("\xff\xff**", 4), wpi::StringRef(e.data(), 4)); + EXPECT_EQ("\xff\xff**"sv, std::string_view(e.data(), 4)); EXPECT_EQ('*', e.data()[65535]); EXPECT_EQ('x', e.data()[65536]); } @@ -479,13 +474,13 @@ TEST_F(WireEncoderTest, WriteString3) { e.WriteString(s_normal); EXPECT_EQ(nullptr, e.error()); EXPECT_EQ(6u, e.size()); - EXPECT_EQ(wpi::StringRef("\x05hello", 6), wpi::StringRef(e.data(), e.size())); + EXPECT_EQ("\x05hello"sv, std::string_view(e.data(), e.size())); e.Reset(); e.WriteString(s_long); EXPECT_EQ(nullptr, e.error()); ASSERT_EQ(130u, e.size()); - EXPECT_EQ(wpi::StringRef("\x80\x01**", 4), wpi::StringRef(e.data(), 4)); + EXPECT_EQ("\x80\x01**"sv, std::string_view(e.data(), 4)); EXPECT_EQ('*', e.data()[128]); EXPECT_EQ('x', e.data()[129]); @@ -494,7 +489,7 @@ TEST_F(WireEncoderTest, WriteString3) { e.WriteString(s_big); EXPECT_EQ(nullptr, e.error()); ASSERT_EQ(65540u, e.size()); - EXPECT_EQ(wpi::StringRef("\x81\x80\x04*", 4), wpi::StringRef(e.data(), 4)); + EXPECT_EQ("\x81\x80\x04*"sv, std::string_view(e.data(), 4)); EXPECT_EQ('*', e.data()[65536]); EXPECT_EQ('x', e.data()[65537]); EXPECT_EQ('x', e.data()[65538]); diff --git a/outlineviewer/.styleguide b/outlineviewer/.styleguide index c8e055a4ca..d4917bfc9c 100644 --- a/outlineviewer/.styleguide +++ b/outlineviewer/.styleguide @@ -20,6 +20,7 @@ repoRootNameOverride { includeOtherLibs { ^GLFW + ^fmt/ ^imgui ^ntcore ^wpi/ diff --git a/outlineviewer/src/main/native/cpp/main.cpp b/outlineviewer/src/main/native/cpp/main.cpp index 061c9045bc..11428f5e68 100644 --- a/outlineviewer/src/main/native/cpp/main.cpp +++ b/outlineviewer/src/main/native/cpp/main.cpp @@ -5,9 +5,9 @@ #include #include +#include #include #include -#include #include #include "glass/Context.h" @@ -21,13 +21,13 @@ namespace gui = wpi::gui; const char* GetWPILibVersion(); namespace ov { -wpi::StringRef GetResource_ov_16_png(); -wpi::StringRef GetResource_ov_32_png(); -wpi::StringRef GetResource_ov_48_png(); -wpi::StringRef GetResource_ov_64_png(); -wpi::StringRef GetResource_ov_128_png(); -wpi::StringRef GetResource_ov_256_png(); -wpi::StringRef GetResource_ov_512_png(); +std::string_view GetResource_ov_16_png(); +std::string_view GetResource_ov_32_png(); +std::string_view GetResource_ov_48_png(); +std::string_view GetResource_ov_64_png(); +std::string_view GetResource_ov_128_png(); +std::string_view GetResource_ov_256_png(); +std::string_view GetResource_ov_512_png(); } // namespace ov static std::unique_ptr gModel; @@ -49,18 +49,14 @@ static void NtInitialize() { for (auto&& event : nt::PollConnectionListener(poller, 0, &timedOut)) { if ((nt::GetNetworkMode(inst) & NT_NET_MODE_SERVER) != 0) { // for server mode, just print number of clients connected - wpi::SmallString<64> title; - glfwSetWindowTitle(win, ("OutlineViewer - " + - wpi::Twine{nt::GetConnections(inst).size()} + - " Clients Connected") - .toNullTerminatedStringRef(title) - .data()); + glfwSetWindowTitle(win, + fmt::format("OutlineViewer - {} Clients Connected", + nt::GetConnections(inst).size()) + .c_str()); } else if (event.connected) { - wpi::SmallString<64> title; - title = "OutlineViewer - Connected ("; - title += event.conn.remote_ip; - title += ')'; - glfwSetWindowTitle(win, title.c_str()); + glfwSetWindowTitle(win, fmt::format("OutlineViewer - Connected ({})", + event.conn.remote_ip) + .c_str()); } else { glfwSetWindowTitle(win, "OutlineViewer - DISCONNECTED"); } @@ -81,9 +77,8 @@ static void NtInitialize() { } else if (msg.level >= NT_LOG_WARNING) { level = "WARNING: "; } - gLog.Append(wpi::Twine{level} + msg.message + wpi::Twine{" ("} + - msg.filename + wpi::Twine{':'} + wpi::Twine{msg.line} + - wpi::Twine{")\n"}); + gLog.Append(fmt::format("{}{} ({}:{})\n", level, msg.message, + msg.filename, msg.line)); } }); diff --git a/shared/resources.gradle b/shared/resources.gradle index 50879e14b1..f5aa19f241 100644 --- a/shared/resources.gradle +++ b/shared/resources.gradle @@ -19,7 +19,7 @@ ext.createGenerateResourcesTask = { name, prefix, namespace, project -> outputFile.withWriter { out -> def inputBytes = inputFile.bytes out.print '''#include -#include +#include extern "C" { static const unsigned char contents[] = { ''' @@ -36,8 +36,8 @@ const unsigned char* ${prefix}${funcName}(size_t* len) { if (!namespace.isEmpty()) { out.println "namespace ${namespace} {" } - out.println """wpi::StringRef ${funcName}() { - return wpi::StringRef(reinterpret_cast(contents), ${fileBytes.size()}); + out.println """std::string_view ${funcName}() { + return std::string_view(reinterpret_cast(contents), ${fileBytes.size()}); }""" if (!namespace.isEmpty()) { out.println '}' diff --git a/simulation/halsim_ds_socket/src/dev/native/cpp/main.cpp b/simulation/halsim_ds_socket/src/dev/native/cpp/main.cpp index 0989409966..cf3adc6c7e 100644 --- a/simulation/halsim_ds_socket/src/dev/native/cpp/main.cpp +++ b/simulation/halsim_ds_socket/src/dev/native/cpp/main.cpp @@ -6,8 +6,6 @@ #include #include -#include -#include extern "C" int HALSIM_InitExtension(void); diff --git a/simulation/halsim_ds_socket/src/main/native/cpp/DSCommPacket.cpp b/simulation/halsim_ds_socket/src/main/native/cpp/DSCommPacket.cpp index 0aad44faa4..aeaf5e1101 100644 --- a/simulation/halsim_ds_socket/src/main/native/cpp/DSCommPacket.cpp +++ b/simulation/halsim_ds_socket/src/main/native/cpp/DSCommPacket.cpp @@ -13,7 +13,6 @@ #include #include #include -#include using namespace halsim; diff --git a/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp b/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp index bac36b4334..c9fa585334 100644 --- a/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp +++ b/simulation/halsim_ds_socket/src/main/native/cpp/main.cpp @@ -14,13 +14,14 @@ #include #include +#include #include +#include #include +#include #include #include -#include -#include #include #include #include @@ -50,13 +51,13 @@ static SimpleBufferPool<4>& GetBufferPool() { } static void HandleTcpDataStream(Buffer& buf, size_t size, DataStore& store) { - wpi::StringRef data{buf.base, size}; + std::string_view data{buf.base, size}; while (!data.empty()) { if (store.m_frameSize == (std::numeric_limits::max)()) { if (store.m_frame.size() < 2u) { size_t toCopy = (std::min)(2u - store.m_frame.size(), data.size()); - store.m_frame.append(data.bytes_begin(), data.bytes_begin() + toCopy); - data = data.drop_front(toCopy); + store.m_frame.append(data.data(), data.data() + toCopy); + data.remove_prefix(toCopy); if (store.m_frame.size() < 2u) { return; // need more data } @@ -67,8 +68,8 @@ static void HandleTcpDataStream(Buffer& buf, size_t size, DataStore& store) { if (store.m_frameSize != (std::numeric_limits::max)()) { size_t need = store.m_frameSize - (store.m_frame.size() - 2); size_t toCopy = (std::min)(need, data.size()); - store.m_frame.append(data.bytes_begin(), data.bytes_begin() + toCopy); - data = data.drop_front(toCopy); + store.m_frame.append(data.data(), data.data() + toCopy); + data.remove_prefix(toCopy); need -= toCopy; if (need == 0) { auto ds = store.dsPacket; @@ -118,8 +119,8 @@ static void SetupUdp(wpi::uv::Loop& loop) { udpLocal->Send(simAddr, wpi::ArrayRef{singleByte.get(), 1}, [](auto buf, Error err) { if (err) { - wpi::errs() << err.str() << "\n"; - wpi::errs().flush(); + fmt::print(stderr, "{}\n", err.str()); + std::fflush(stderr); } }); }); @@ -146,8 +147,8 @@ static void SetupUdp(wpi::uv::Loop& loop) { udpLocal->Send(outAddr, sendBufs, [](auto bufs, Error err) { GetBufferPool().Release(bufs); if (err) { - wpi::errs() << err.str() << "\n"; - wpi::errs().flush(); + fmt::print(stderr, "{}\n", err.str()); + std::fflush(stderr); } }); ds->SendUDPToHALSim(); @@ -177,12 +178,12 @@ __declspec(dllexport) static bool once = false; if (once) { - wpi::errs() << "Error: cannot invoke HALSIM_InitExtension twice.\n"; + std::fputs("Error: cannot invoke HALSIM_InitExtension twice.\n", stderr); return -1; } once = true; - wpi::outs() << "DriverStationSocket Initializing.\n"; + std::puts("DriverStationSocket Initializing."); HAL_RegisterExtension("ds_socket", &gDSConnected); @@ -192,7 +193,7 @@ __declspec(dllexport) eventLoopRunner->ExecAsync(SetupEventLoop); - wpi::outs() << "DriverStationSocket Initialized!\n"; + std::puts("DriverStationSocket Initialized!"); return 0; } } // extern "C" diff --git a/simulation/halsim_gui/src/main/native/cpp/AddressableLEDGui.cpp b/simulation/halsim_gui/src/main/native/cpp/AddressableLEDGui.cpp index 37f2005245..586bbd8841 100644 --- a/simulation/halsim_gui/src/main/native/cpp/AddressableLEDGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/AddressableLEDGui.cpp @@ -9,7 +9,6 @@ #include #include #include -#include #include "HALSimGui.h" diff --git a/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp b/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp index 8394a8ddb0..42ec8a35b7 100644 --- a/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.cpp @@ -13,15 +13,18 @@ #include #include #include +#include #include #include +#include +#include #include #include #include #include #include -#include +#include #include #include "HALDataSource.h" @@ -104,7 +107,7 @@ class KeyboardJoystick : public SystemJoystick { void ClearKey(int key); virtual const char* GetKeyName(int key) const = 0; - void ReadIni(wpi::StringRef name, wpi::StringRef value); + void ReadIni(std::string_view name, std::string_view value); void WriteIni(ImGuiTextBuffer* out_buf) const; protected: @@ -210,14 +213,14 @@ class FMSSimModel : public glass::FMSModel { glass::DataSource* GetEnabledData() override { return &m_enabled; } glass::DataSource* GetTestData() override { return &m_test; } glass::DataSource* GetAutonomousData() override { return &m_autonomous; } - wpi::StringRef GetGameSpecificMessage( + std::string_view GetGameSpecificMessage( wpi::SmallVectorImpl& buf) override { HAL_MatchInfo info; HALSIM_GetMatchInfo(&info); buf.clear(); buf.append(info.gameSpecificMessage, info.gameSpecificMessage + info.gameSpecificMessageSize); - return wpi::StringRef(buf.begin(), buf.size()); + return std::string_view(buf.begin(), buf.size()); } void SetFmsAttached(bool val) override { @@ -299,17 +302,15 @@ JoystickModel::JoystickModel(int index) : m_index{index} { axisCount = halAxes.count; for (int i = 0; i < axisCount; ++i) { axes[i] = std::make_unique( - "Joystick[" + wpi::Twine{index} + "] Axis[" + wpi::Twine{i} + - wpi::Twine{']'}); + fmt::format("Joystick[{}] Axis[{}]", index, i)); } HAL_JoystickButtons halButtons; HALSIM_GetJoystickButtons(index, &halButtons); buttonCount = halButtons.count; for (int i = 0; i < buttonCount; ++i) { - buttons[i] = - new glass::DataSource("Joystick[" + wpi::Twine{index} + "] Button[" + - wpi::Twine{i + 1} + wpi::Twine{']'}); + buttons[i] = new glass::DataSource( + fmt::format("Joystick[{}] Button[{}]", index, i + 1)); buttons[i]->SetDigital(true); } for (int i = buttonCount; i < 32; ++i) { @@ -321,8 +322,7 @@ JoystickModel::JoystickModel(int index) : m_index{index} { povCount = halPOVs.count; for (int i = 0; i < povCount; ++i) { povs[i] = std::make_unique( - "Joystick[" + wpi::Twine{index} + "] POV[" + wpi::Twine{i} + - wpi::Twine{']'}); + fmt::format("Joystick[{}] POV [{}]", index, i)); } m_callback = @@ -360,10 +360,7 @@ void JoystickModel::CallbackFunc(const char*, void* param, const HAL_Value*) { // read/write joystick mapping to ini file static void* JoystickReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name) { - int num; - if (wpi::StringRef{name}.getAsInteger(10, num)) { - return nullptr; - } + int num = wpi::parse_integer(name, 10).value_or(-1); if (num < 0 || num >= HAL_kMaxJoysticks) { return nullptr; } @@ -371,21 +368,18 @@ static void* JoystickReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, } static void JoystickReadLine(ImGuiContext* ctx, ImGuiSettingsHandler* handler, - void* entry, const char* lineStr) { + void* entry, const char* line) { RobotJoystick* joy = static_cast(entry); // format: guid=guid or useGamepad=0/1 - wpi::StringRef line{lineStr}; - auto [name, value] = line.split('='); - name = name.trim(); - value = value.trim(); + auto [name, value] = wpi::split(line, '='); + name = wpi::trim(name); + value = wpi::trim(value); if (name == "guid") { joy->guid = value; } else if (name == "useGamepad") { - int num; - if (value.getAsInteger(10, num)) { - return; + if (auto num = wpi::parse_integer(value, 10)) { + joy->useGamepad = num.value(); } - joy->useGamepad = num; } else { joy->name.ReadIni(name, value); } @@ -417,10 +411,7 @@ static void JoystickWriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, static void* KeyboardJoystickReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name) { - int num; - if (wpi::StringRef{name}.getAsInteger(10, num)) { - return nullptr; - } + int num = wpi::parse_integer(name, 10).value_or(-1); if (num < 0 || num >= static_cast(gKeyboardJoysticks.size())) { return nullptr; } @@ -431,12 +422,11 @@ static void* KeyboardJoystickReadOpen(ImGuiContext* ctx, static void KeyboardJoystickReadLine(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, - const char* lineStr) { + const char* line) { auto joy = static_cast(entry); // format: guid=guid or useGamepad=0/1 - wpi::StringRef line{lineStr}; - auto [name, value] = line.split('='); - joy->ReadIni(name.trim(), value.trim()); + auto [name, value] = wpi::split(line, '='); + joy->ReadIni(wpi::trim(name), wpi::trim(value)); } static void KeyboardJoystickWriteAll(ImGuiContext* ctx, @@ -453,7 +443,7 @@ static void KeyboardJoystickWriteAll(ImGuiContext* ctx, static void* DriverStationReadOpen(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name) { - if (name == wpi::StringRef{"Main"}) { + if (name == std::string_view{"Main"}) { return &gDisableDS; } return nullptr; @@ -461,35 +451,26 @@ static void* DriverStationReadOpen(ImGuiContext* ctx, static void DriverStationReadLine(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, - const char* lineStr) { - wpi::StringRef line{lineStr}; - auto [name, value] = line.split('='); - name = name.trim(); - value = value.trim(); + const char* line) { + auto [name, value] = wpi::split(line, '='); + name = wpi::trim(name); + value = wpi::trim(value); if (name == "disable") { - int num; - if (value.getAsInteger(10, num)) { - return; + if (auto num = wpi::parse_integer(value, 10)) { + gDisableDS = num.value(); } - gDisableDS = num; } else if (name == "zeroDisconnectedJoysticks") { - int num; - if (value.getAsInteger(10, num)) { - return; + if (auto num = wpi::parse_integer(value, 10)) { + gZeroDisconnectedJoysticks = num.value(); } - gZeroDisconnectedJoysticks = num; } else if (name == "enableDisableKeys") { - int num; - if (value.getAsInteger(10, num)) { - return; + if (auto num = wpi::parse_integer(value, 10)) { + gUseEnableDisableHotkeys = num.value(); } - gUseEnableDisableHotkeys = num; } else if (name == "estopKey") { - int num; - if (value.getAsInteger(10, num)) { - return; + if (auto num = wpi::parse_integer(value, 10)) { + gUseEstopHotkey = num.value(); } - gUseEstopHotkey = num; } } @@ -914,92 +895,76 @@ void KeyboardJoystick::ClearKey(int key) { } } -void KeyboardJoystick::ReadIni(wpi::StringRef name, wpi::StringRef value) { - if (name.startswith("axis")) { - name = name.drop_front(4); +void KeyboardJoystick::ReadIni(std::string_view name, std::string_view value) { + if (wpi::starts_with(name, "axis")) { + name.remove_prefix(4); if (name == "Count") { - int v; - if (value.getAsInteger(10, v)) { - return; + if (auto v = wpi::parse_integer(value, 10)) { + m_data.axes.count = (std::min)(v.value(), HAL_kMaxJoystickAxes); } - m_data.axes.count = (std::min)(v, HAL_kMaxJoystickAxes); return; } - unsigned int index; - if (name.consumeInteger(10, index)) { - return; - } + auto index = wpi::consume_integer(&name, 10).value_or( + HAL_kMaxJoystickAxes); if (index >= HAL_kMaxJoystickAxes) { return; } if (name == "incKey") { - int v; - if (value.getAsInteger(10, v)) { - return; + if (auto v = wpi::parse_integer(value, 10)) { + m_axisConfig[index].incKey = v.value(); } - m_axisConfig[index].incKey = v; } else if (name == "decKey") { - int v; - if (value.getAsInteger(10, v)) { - return; + if (auto v = wpi::parse_integer(value, 10)) { + m_axisConfig[index].decKey = v.value(); } - m_axisConfig[index].decKey = v; } else if (name == "keyRate") { - std::sscanf(value.data(), "%f", &m_axisConfig[index].keyRate); - } else if (name == "decayRate") { - std::sscanf(value.data(), "%f", &m_axisConfig[index].decayRate); - } else if (name == "maxAbsValue") { - std::sscanf(value.data(), "%f", &m_axisConfig[index].maxAbsValue); - } - } else if (name.startswith("button")) { - name = name.drop_front(6); - if (name == "Count") { - int v; - if (value.getAsInteger(10, v)) { - return; + if (auto v = wpi::parse_float(value)) { + m_axisConfig[index].keyRate = v.value(); + } + } else if (name == "decayRate") { + if (auto v = wpi::parse_float(value)) { + m_axisConfig[index].decayRate = v.value(); + } + } else if (name == "maxAbsValue") { + if (auto v = wpi::parse_float(value)) { + m_axisConfig[index].maxAbsValue = v.value(); + } + } + } else if (wpi::starts_with(name, "button")) { + name.remove_prefix(6); + if (name == "Count") { + if (auto v = wpi::parse_integer(value, 10)) { + m_data.buttons.count = (std::min)(v.value(), kMaxButtonCount); } - m_data.buttons.count = (std::min)(v, kMaxButtonCount); return; } - unsigned int index; - if (name.getAsInteger(10, index)) { - return; - } + auto index = + wpi::parse_integer(name, 10).value_or(kMaxButtonCount); if (index >= kMaxButtonCount) { return; } - int v; - if (value.getAsInteger(10, v)) { - return; - } + int v = wpi::parse_integer(value, 10).value_or(-1); if (v < 0 || v >= IM_ARRAYSIZE(ImGuiIO::KeysDown)) { return; } m_buttonKey[index] = v; - } else if (name.startswith("pov")) { - name = name.drop_front(3); + } else if (wpi::starts_with(name, "pov")) { + name.remove_prefix(3); if (name == "Count") { - int v; - if (value.getAsInteger(10, v)) { - return; + if (auto v = wpi::parse_integer(value, 10)) { + m_data.povs.count = (std::min)(v.value(), HAL_kMaxJoystickPOVs); } - m_data.povs.count = (std::min)(v, HAL_kMaxJoystickPOVs); return; } - unsigned int index; - if (name.consumeInteger(10, index)) { - return; - } + auto index = wpi::consume_integer(&name, 10).value_or( + HAL_kMaxJoystickPOVs); if (index >= HAL_kMaxJoystickPOVs) { return; } - int v; - if (value.getAsInteger(10, v)) { - return; - } + int v = wpi::parse_integer(value, 10).value_or(-1); if (v < 0 || v >= IM_ARRAYSIZE(ImGuiIO::KeysDown)) { return; } @@ -1409,8 +1374,9 @@ static void DisplayJoysticks() { } joy.sys = payload_sys; joy.guid.clear(); - wpi::StringRef name{payload_sys->GetName()}; - joy.useGamepad = name.startswith("Xbox") || name.contains("pad"); + std::string_view name{payload_sys->GetName()}; + joy.useGamepad = + wpi::starts_with(name, "Xbox") || wpi::contains(name, "pad"); } ImGui::EndDragDropTarget(); } diff --git a/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.h b/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.h index 80a7a73a81..51f7554620 100644 --- a/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.h +++ b/simulation/halsim_gui/src/main/native/cpp/DriverStationGui.h @@ -6,11 +6,13 @@ #include +#include + namespace halsimgui { class DSManager : public glass::WindowManager { public: - explicit DSManager(const wpi::Twine& iniName) : WindowManager{iniName} {} + explicit DSManager(std::string_view iniName) : WindowManager{iniName} {} void DisplayMenu() override; }; diff --git a/simulation/halsim_gui/src/main/native/cpp/EncoderSimGui.cpp b/simulation/halsim_gui/src/main/native/cpp/EncoderSimGui.cpp index d5bf569a41..56e8ea2334 100644 --- a/simulation/halsim_gui/src/main/native/cpp/EncoderSimGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/EncoderSimGui.cpp @@ -9,8 +9,10 @@ #include #include +#include #include +#include #include #include #include @@ -24,14 +26,14 @@ namespace { class EncoderSimModel : public glass::EncoderModel { public: - EncoderSimModel(const wpi::Twine& id, int32_t index, int channelA, + EncoderSimModel(std::string_view id, int32_t index, int channelA, int channelB) - : m_distancePerPulse(id + " Dist/Count"), - m_count(id + " Count"), - m_period(id + " Period"), - m_direction(id + " Direction"), - m_distance(id + " Distance"), - m_rate(id + " Rate"), + : m_distancePerPulse(fmt::format("{} Dist/Count", id)), + m_count(fmt::format("{} Count", id)), + m_period(fmt::format("{} Period", id)), + m_direction(fmt::format("{} Direction", id)), + m_distance(fmt::format("{} Distance", id)), + m_rate(fmt::format("{} Rate", id)), m_index{index}, m_channelA{channelA}, m_channelB{channelB}, @@ -48,8 +50,7 @@ class EncoderSimModel : public glass::EncoderModel { } EncoderSimModel(int32_t index, int channelA, int channelB) - : EncoderSimModel("Encoder[" + wpi::Twine(channelA) + wpi::Twine(',') + - wpi::Twine(channelB) + wpi::Twine(']'), + : EncoderSimModel(fmt::format("Encoder[{},{}]", channelA, channelB), index, channelA, channelB) {} explicit EncoderSimModel(int32_t index) diff --git a/simulation/halsim_gui/src/main/native/cpp/HALProvider.cpp b/simulation/halsim_gui/src/main/native/cpp/HALProvider.cpp index 0f2a2f8cfa..72b9c29db4 100644 --- a/simulation/halsim_gui/src/main/native/cpp/HALProvider.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/HALProvider.cpp @@ -56,7 +56,7 @@ void HALProvider::Update() { } } -glass::Model* HALProvider::GetModel(wpi::StringRef name) { +glass::Model* HALProvider::GetModel(std::string_view name) { auto it = FindModelEntry(name); if (it == m_modelEntries.end() || (*it)->name != name) { return nullptr; diff --git a/simulation/halsim_gui/src/main/native/cpp/SimDeviceGui.cpp b/simulation/halsim_gui/src/main/native/cpp/SimDeviceGui.cpp index 4a4de4bb23..62e289632f 100644 --- a/simulation/halsim_gui/src/main/native/cpp/SimDeviceGui.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/SimDeviceGui.cpp @@ -7,9 +7,11 @@ #include #include +#include #include #include #include +#include #include "HALDataSource.h" #include "HALSimGui.h" @@ -21,7 +23,7 @@ class SimValueSource : public glass::DataSource { public: explicit SimValueSource(HAL_SimValueHandle handle, const char* device, const char* name) - : DataSource(wpi::Twine{device} + wpi::Twine{'-'} + name), + : DataSource(fmt::format("{}-{}", device, name)), m_callback{HALSIM_RegisterSimValueChangedCallback( handle, this, CallbackFunc, true)} {} ~SimValueSource() override { @@ -137,11 +139,11 @@ static void DisplaySimValue(const char* name, void* data, static void DisplaySimDevice(const char* name, void* data, HAL_SimDeviceHandle handle) { - wpi::StringRef id{name}; + std::string_view id{name}; if (!gSimDevicesShowPrefix) { // only show "Foo" portion of "Accel:Foo" - wpi::StringRef type; - std::tie(type, id) = id.split(':'); + std::string_view type; + std::tie(type, id) = wpi::split(id, ':'); if (id.empty()) { id = type; } diff --git a/simulation/halsim_gui/src/main/native/cpp/main.cpp b/simulation/halsim_gui/src/main/native/cpp/main.cpp index 2950b4d6df..a0db3d0a2c 100644 --- a/simulation/halsim_gui/src/main/native/cpp/main.cpp +++ b/simulation/halsim_gui/src/main/native/cpp/main.cpp @@ -5,11 +5,12 @@ #include #include +#include +#include + #include #include #include -#include -#include #include #include "AccelerometerSimGui.h" @@ -41,7 +42,7 @@ extern "C" { __declspec(dllexport) #endif int HALSIM_InitExtension(void) { - wpi::outs() << "Simulator GUI Initializing.\n"; + std::puts("Simulator GUI Initializing."); gui::CreateContext(); glass::CreateContext(); @@ -102,7 +103,7 @@ __declspec(dllexport) } HAL_RegisterExtensionListener( nullptr, [](void*, const char* name, void* data) { - if (wpi::StringRef{name} == "ds_socket") { + if (std::string_view{name} == "ds_socket") { DriverStationGui::SetDSSocketExtension(data); } }); @@ -114,7 +115,7 @@ __declspec(dllexport) gui::DestroyContext(); }, [](void*) { gui::Exit(); }); - wpi::outs() << "Simulator GUI Initialized!\n"; + std::puts("Simulator GUI Initialized!"); return 0; } diff --git a/simulation/halsim_gui/src/main/native/include/HALProvider.h b/simulation/halsim_gui/src/main/native/include/HALProvider.h index 2dcbc0d632..e3098db416 100644 --- a/simulation/halsim_gui/src/main/native/include/HALProvider.h +++ b/simulation/halsim_gui/src/main/native/include/HALProvider.h @@ -10,19 +10,18 @@ #include #include #include +#include #include -#include - namespace halsimgui { class HALProvider : public glass::Provider<> { public: - explicit HALProvider(const wpi::Twine& iniName) : Provider{iniName} {} + explicit HALProvider(std::string_view iniName) : Provider{iniName} {} void DisplayMenu() override; - glass::Model* GetModel(wpi::StringRef name); + glass::Model* GetModel(std::string_view name); /** * Returns true if outputs are disabled. diff --git a/simulation/halsim_ws_client/src/main/native/cpp/HALSimWS.cpp b/simulation/halsim_ws_client/src/main/native/cpp/HALSimWS.cpp index da6253d589..9c23885843 100644 --- a/simulation/halsim_ws_client/src/main/native/cpp/HALSimWS.cpp +++ b/simulation/halsim_ws_client/src/main/native/cpp/HALSimWS.cpp @@ -4,8 +4,10 @@ #include "HALSimWS.h" +#include + +#include #include -#include #include #include "HALSimWSClientConnection.h" @@ -22,7 +24,7 @@ HALSimWS::HALSimWS(wpi::uv::Loop& loop, ProviderContainer& providers, m_providers(providers), m_simDevicesProvider(simDevicesProvider) { m_loop.error.connect([](uv::Error err) { - wpi::errs() << "HALSim WS Client libuv Error: " << err.str() << "\n"; + fmt::print(stderr, "HALSim WS Client libuv Error: {}\n", err.str()); }); m_tcp_client = uv::Tcp::Create(m_loop); @@ -50,7 +52,7 @@ bool HALSimWS::Initialize() { try { m_port = std::stoi(port); } catch (const std::invalid_argument& err) { - wpi::errs() << "Error decoding HALSIMWS_PORT (" << err.what() << ")\n"; + fmt::print(stderr, "Error decoding HALSIMWS_PORT ({})\n", err.what()); return false; } } else { @@ -83,13 +85,12 @@ void HALSimWS::Start() { m_connect_timer->Start(uv::Timer::Time(kTcpConnectAttemptTimeout)); }); - m_tcp_client->closed.connect( - []() { wpi::outs() << "TCP connection closed\n"; }); + m_tcp_client->closed.connect([]() { std::puts("TCP connection closed"); }); // Set up the connection timer - wpi::outs() << "HALSimWS Initialized\n"; - wpi::outs() << "Will attempt to connect to ws://" << m_host << ":" << m_port - << m_uri << "\n"; + std::puts("HALSimWS Initialized"); + fmt::print("Will attempt to connect to ws://{}:{}{}\n", m_host, m_port, + m_uri); // Set up the timer to attempt connection m_connect_timer->timeout.connect([this] { AttemptConnect(); }); @@ -102,7 +103,7 @@ void HALSimWS::Start() { void HALSimWS::AttemptConnect() { m_connect_attempts++; - wpi::outs() << "Connection Attempt " << m_connect_attempts << "\n"; + fmt::print("Connection Attempt {}\n", m_connect_attempts); struct sockaddr_in dest; uv::NameToAddr(m_host, m_port, &dest); @@ -167,6 +168,6 @@ void HALSimWS::OnNetValueChanged(const wpi::json& msg) { provider->OnNetValueChanged(msg.at("data")); } } catch (wpi::json::exception& e) { - wpi::errs() << "Error with incoming message: " << e.what() << "\n"; + fmt::print(stderr, "Error with incoming message: {}\n", e.what()); } } diff --git a/simulation/halsim_ws_client/src/main/native/cpp/HALSimWSClientConnection.cpp b/simulation/halsim_ws_client/src/main/native/cpp/HALSimWSClientConnection.cpp index 4ebaf1d225..22dadb1245 100644 --- a/simulation/halsim_ws_client/src/main/native/cpp/HALSimWSClientConnection.cpp +++ b/simulation/halsim_ws_client/src/main/native/cpp/HALSimWSClientConnection.cpp @@ -4,7 +4,9 @@ #include "HALSimWSClientConnection.h" -#include +#include + +#include #include #include "HALSimWS.h" @@ -17,29 +19,29 @@ void HALSimWSClientConnection::Initialize() { // Get a shared pointer to ourselves auto self = this->shared_from_this(); - auto ws = - wpi::WebSocket::CreateClient(*m_stream, m_client->GetTargetUri(), - wpi::Twine{m_client->GetTargetHost()} + ":" + - wpi::Twine{m_client->GetTargetPort()}); + auto ws = wpi::WebSocket::CreateClient( + *m_stream, m_client->GetTargetUri(), + fmt::format("{}:{}", m_client->GetTargetHost(), + m_client->GetTargetPort())); ws->SetData(self); m_websocket = ws.get(); // Hook up events - m_websocket->open.connect_extended([this](auto conn, wpi::StringRef) { + m_websocket->open.connect_extended([this](auto conn, auto) { conn.disconnect(); if (!m_client->RegisterWebsocket(shared_from_this())) { - wpi::errs() << "Unable to register websocket\n"; + std::fputs("Unable to register websocket\n", stderr); return; } m_ws_connected = true; - wpi::outs() << "HALSimWS: WebSocket Connected\n"; + std::puts("HALSimWS: WebSocket Connected"); }); - m_websocket->text.connect([this](wpi::StringRef msg, bool) { + m_websocket->text.connect([this](auto msg, bool) { if (!m_ws_connected) { return; } @@ -50,7 +52,7 @@ void HALSimWSClientConnection::Initialize() { } catch (const wpi::json::parse_error& e) { std::string err("JSON parse failed: "); err += e.what(); - wpi::errs() << err << "\n"; + fmt::print(stderr, "{}\n", err); m_websocket->Fail(1003, err); return; } @@ -58,9 +60,9 @@ void HALSimWSClientConnection::Initialize() { m_client->OnNetValueChanged(j); }); - m_websocket->closed.connect([this](uint16_t, wpi::StringRef) { + m_websocket->closed.connect([this](uint16_t, auto) { if (m_ws_connected) { - wpi::outs() << "HALSimWS: Websocket Disconnected\n"; + std::puts("HALSimWS: Websocket Disconnected"); m_ws_connected = false; m_client->CloseWebsocket(shared_from_this()); @@ -90,8 +92,8 @@ void HALSimWSClientConnection::OnSimValueChanged(const wpi::json& msg) { } if (err) { - wpi::errs() << err.str() << "\n"; - wpi::errs().flush(); + fmt::print(stderr, "{}\n", err.str()); + std::fflush(stderr); } }); }); diff --git a/simulation/halsim_ws_client/src/main/native/cpp/main.cpp b/simulation/halsim_ws_client/src/main/native/cpp/main.cpp index c5493713d6..8e2e2fa569 100644 --- a/simulation/halsim_ws_client/src/main/native/cpp/main.cpp +++ b/simulation/halsim_ws_client/src/main/native/cpp/main.cpp @@ -2,10 +2,10 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include #include #include -#include #include "HALSimWSClient.h" @@ -19,7 +19,7 @@ __declspec(dllexport) #endif int HALSIM_InitExtension(void) { - wpi::outs() << "HALSim WS Client Extension Initializing\n"; + std::puts("HALSim WS Client Extension Initializing"); HAL_OnShutdown(nullptr, [](void*) { gClient.reset(); }); @@ -28,7 +28,7 @@ __declspec(dllexport) return -1; } - wpi::outs() << "HALSim WS Client Extension Initialized\n"; + std::puts("HALSim WS Client Extension Initialized"); return 0; } diff --git a/simulation/halsim_ws_client/src/main/native/include/HALSimWS.h b/simulation/halsim_ws_client/src/main/native/include/HALSimWS.h index d2595470ce..9563482032 100644 --- a/simulation/halsim_ws_client/src/main/native/include/HALSimWS.h +++ b/simulation/halsim_ws_client/src/main/native/include/HALSimWS.h @@ -41,8 +41,8 @@ class HALSimWS : public std::enable_shared_from_this { void OnNetValueChanged(const wpi::json& msg); - wpi::StringRef GetTargetHost() const { return m_host; } - wpi::StringRef GetTargetUri() const { return m_uri; } + const std::string& GetTargetHost() const { return m_host; } + const std::string& GetTargetUri() const { return m_uri; } int GetTargetPort() const { return m_port; } wpi::uv::Loop& GetLoop() { return m_loop; } diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSBaseProvider.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSBaseProvider.cpp index 2e93f96ff1..16d92fa371 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSBaseProvider.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSBaseProvider.cpp @@ -8,8 +8,9 @@ namespace wpilibws { -HALSimWSBaseProvider::HALSimWSBaseProvider(std::string key, std::string type) - : m_key(std::move(key)), m_type(std::move(type)) {} +HALSimWSBaseProvider::HALSimWSBaseProvider(std::string_view key, + std::string_view type) + : m_key(key), m_type(type) {} void HALSimWSBaseProvider::OnNetValueChanged(const wpi::json& json) { // empty diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSHalProviders.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSHalProviders.cpp index e9576aeea8..4d6c024558 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSHalProviders.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSHalProviders.cpp @@ -4,6 +4,8 @@ #include "WSHalProviders.h" +#include + namespace wpilibws { void HALSimWSHalProvider::OnNetworkConnected( @@ -30,10 +32,10 @@ void HALSimWSHalProvider::ProcessHalCallback(const wpi::json& payload) { } HALSimWSHalChanProvider::HALSimWSHalChanProvider(int32_t channel, - const std::string& key, - const std::string& type) + std::string_view key, + std::string_view type) : HALSimWSHalProvider(key, type), m_channel(channel) { - m_deviceId = std::to_string(channel); + m_deviceId = fmt::format("{}", channel); } } // namespace wpilibws diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_DriverStation.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_DriverStation.cpp index 44bca99eee..6fbc3d7a3c 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_DriverStation.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_DriverStation.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -32,7 +33,7 @@ void HALSimWSProviderDriverStation::Initialize(WSRegisterFunc webRegisterFunc) { registered = true; HAL_RegisterExtensionListener( nullptr, [](void*, const char* name, void* data) { - if (wpi::StringRef{name} == "ds_socket") { + if (std::string_view{name} == "ds_socket") { gDSSocketConnected = static_cast*>(data); } }); diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_SimDevice.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_SimDevice.cpp index a296c06291..93852b6703 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_SimDevice.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_SimDevice.cpp @@ -7,7 +7,9 @@ #include #include +#include #include +#include namespace wpilibws { @@ -140,7 +142,7 @@ void HALSimWSProviderSimDevice::OnValueCreated(const char* name, break; } } - std::string key = (wpi::Twine(prefix) + name).str(); + std::string key = fmt::format("{}{}", prefix, name); auto data = std::make_unique(); data->device = this; data->handle = handle; @@ -258,15 +260,15 @@ HALSimWSProviderSimDevices::~HALSimWSProviderSimDevices() { void HALSimWSProviderSimDevices::DeviceCreatedCallback( const char* name, HAL_SimDeviceHandle handle) { // Map "Accel:Foo" -> type=Accel, device=Foo - auto [type, id] = wpi::StringRef{name}.split(':'); + auto [type, id] = wpi::split(name, ':'); std::shared_ptr dev; if (id.empty()) { - auto key = ("SimDevice/" + type).str(); + auto key = fmt::format("SimDevice/{}", type); dev = std::make_shared(handle, key, "SimDevice", type); m_providers.Add(key, dev); } else { - auto key = (type + "/" + id).str(); + auto key = fmt::format("{}/{}", type, id); dev = std::make_shared(handle, key, type, id); m_providers.Add(key, dev); } diff --git a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Solenoid.cpp b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Solenoid.cpp index c87cb82a40..c376d3a59d 100644 --- a/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Solenoid.cpp +++ b/simulation/halsim_ws_core/src/main/native/cpp/WSProvider_Solenoid.cpp @@ -4,6 +4,7 @@ #include "WSProvider_Solenoid.h" +#include #include #include @@ -22,9 +23,7 @@ void HALSimWSProviderSolenoid::Initialize(WSRegisterFunc webRegisterFunc) { ++CTREPCMIndex) { for (int32_t solenoidIndex = 0; solenoidIndex < HAL_GetNumSolenoidChannels(); ++solenoidIndex) { - auto key = ("Solenoid/" + wpi::Twine(CTREPCMIndex) + "," + - wpi::Twine(solenoidIndex)) - .str(); + auto key = fmt::format("Solenoid/{},{}", CTREPCMIndex, solenoidIndex); auto ptr = std::make_unique( CTREPCMIndex, solenoidIndex, key, "Solenoid"); webRegisterFunc(key, std::move(ptr)); @@ -39,8 +38,7 @@ HALSimWSProviderSolenoid::HALSimWSProviderSolenoid(int32_t CTREPCMChannel, : HALSimWSHalProvider(key, type), m_pcmIndex(CTREPCMChannel), m_solenoidIndex(solenoidChannel) { - m_deviceId = - std::to_string(m_pcmIndex) + "," + std::to_string(solenoidChannel); + m_deviceId = fmt::format("{},{}", m_pcmIndex, solenoidChannel); } HALSimWSProviderSolenoid::~HALSimWSProviderSolenoid() { diff --git a/simulation/halsim_ws_core/src/main/native/include/WSBaseProvider.h b/simulation/halsim_ws_core/src/main/native/include/WSBaseProvider.h index 39fadb6708..268c47af4e 100644 --- a/simulation/halsim_ws_core/src/main/native/include/WSBaseProvider.h +++ b/simulation/halsim_ws_core/src/main/native/include/WSBaseProvider.h @@ -7,6 +7,7 @@ #include #include #include +#include #include @@ -16,7 +17,8 @@ namespace wpilibws { class HALSimWSBaseProvider { public: - explicit HALSimWSBaseProvider(std::string key, std::string type = ""); + explicit HALSimWSBaseProvider(std::string_view key, + std::string_view type = ""); virtual ~HALSimWSBaseProvider() = default; HALSimWSBaseProvider(const HALSimWSBaseProvider&) = delete; @@ -34,8 +36,8 @@ class HALSimWSBaseProvider { // network -> sim virtual void OnNetValueChanged(const wpi::json& json); - const std::string GetDeviceType() { return m_type; } - const std::string GetDeviceId() { return m_deviceId; } + const std::string& GetDeviceType() { return m_type; } + const std::string& GetDeviceId() { return m_deviceId; } protected: // sim -> network diff --git a/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.h b/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.h index ce12c59495..e1bc1f85ac 100644 --- a/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.h +++ b/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -41,8 +42,8 @@ class HALSimWSHalProvider : public HALSimWSBaseProvider { // provider generates per-channel diffs class HALSimWSHalChanProvider : public HALSimWSHalProvider { public: - explicit HALSimWSHalChanProvider(int32_t channel, const std::string& key, - const std::string& type); + explicit HALSimWSHalChanProvider(int32_t channel, std::string_view key, + std::string_view type); int32_t GetChannel() { return m_channel; } @@ -51,15 +52,14 @@ class HALSimWSHalChanProvider : public HALSimWSHalProvider { }; using WSRegisterFunc = std::function)>; + std::string_view, std::shared_ptr)>; template -void CreateProviders(const std::string& prefix, int32_t numChannels, +void CreateProviders(std::string_view prefix, int32_t numChannels, WSRegisterFunc webRegisterFunc); template -void CreateSingleProvider(const std::string& key, - WSRegisterFunc webRegisterFunc); +void CreateSingleProvider(std::string_view key, WSRegisterFunc webRegisterFunc); } // namespace wpilibws diff --git a/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.inc b/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.inc index df67764104..c9ce9d14d8 100644 --- a/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.inc +++ b/simulation/halsim_ws_core/src/main/native/include/WSHalProviders.inc @@ -5,25 +5,27 @@ #pragma once #include -#include +#include #include +#include + #include "WSHalProviders.h" namespace wpilibws { template -void CreateProviders(const std::string& prefix, int numChannels, +void CreateProviders(std::string_view prefix, int numChannels, WSRegisterFunc webRegisterFunc) { for (int32_t i = 0; i < numChannels; i++) { - auto key = (prefix + "/" + wpi::Twine(i)).str(); + auto key = fmt::format("{}/{}", prefix, i); auto ptr = std::make_unique(i, key, prefix); webRegisterFunc(key, std::move(ptr)); } } template -void CreateSingleProvider(const std::string& key, +void CreateSingleProvider(std::string_view key, WSRegisterFunc webRegisterFunc) { auto ptr = std::make_unique(key, key); webRegisterFunc(key, std::move(ptr)); diff --git a/simulation/halsim_ws_core/src/main/native/include/WSProviderContainer.h b/simulation/halsim_ws_core/src/main/native/include/WSProviderContainer.h index 6c51b46940..7c8f8617b5 100644 --- a/simulation/halsim_ws_core/src/main/native/include/WSProviderContainer.h +++ b/simulation/halsim_ws_core/src/main/native/include/WSProviderContainer.h @@ -8,6 +8,7 @@ #include #include #include +#include #include @@ -25,12 +26,13 @@ class ProviderContainer { ProviderContainer(const ProviderContainer&) = delete; ProviderContainer& operator=(const ProviderContainer&) = delete; - void Add(wpi::StringRef key, std::shared_ptr provider) { + void Add(std::string_view key, + std::shared_ptr provider) { std::unique_lock lock(m_mutex); m_providers[key] = provider; } - void Delete(wpi::StringRef key) { + void Delete(std::string_view key) { std::unique_lock lock(m_mutex); m_providers.erase(key); } @@ -42,7 +44,7 @@ class ProviderContainer { } } - ProviderPtr Get(wpi::StringRef key) { + ProviderPtr Get(std::string_view key) { std::shared_lock lock(m_mutex); auto fiter = m_providers.find(key); return fiter != m_providers.end() ? fiter->second : ProviderPtr(); diff --git a/simulation/halsim_ws_core/src/main/native/include/WSProvider_SimDevice.h b/simulation/halsim_ws_core/src/main/native/include/WSProvider_SimDevice.h index 6d80467caf..c4d4347635 100644 --- a/simulation/halsim_ws_core/src/main/native/include/WSProvider_SimDevice.h +++ b/simulation/halsim_ws_core/src/main/native/include/WSProvider_SimDevice.h @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -34,9 +35,8 @@ struct SimDeviceValueData { class HALSimWSProviderSimDevice : public HALSimWSBaseProvider { public: - HALSimWSProviderSimDevice(HAL_SimDeviceHandle handle, const std::string& key, - const std::string& type, - const std::string& deviceId) + HALSimWSProviderSimDevice(HAL_SimDeviceHandle handle, std::string_view key, + std::string_view type, std::string_view deviceId) : HALSimWSBaseProvider(key, type), m_handle(handle) { m_deviceId = deviceId; } diff --git a/simulation/halsim_ws_server/src/dev/native/cpp/main.cpp b/simulation/halsim_ws_server/src/dev/native/cpp/main.cpp index 4b03d40acb..d215df6837 100644 --- a/simulation/halsim_ws_server/src/dev/native/cpp/main.cpp +++ b/simulation/halsim_ws_server/src/dev/native/cpp/main.cpp @@ -2,14 +2,14 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include #include #include +#include #include #include #include -#include -#include extern "C" int HALSIM_InitExtension(void); @@ -25,9 +25,9 @@ int main() { while (cycleCount < 1000) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); cycleCount++; - std::cout << "Count: " << cycleCount << std::endl; + fmt::print("Count: {}\n", cycleCount); } - std::cout << "DONE" << std::endl; + std::puts("DONE"); HAL_ExitMain(); } diff --git a/simulation/halsim_ws_server/src/main/native/cpp/HALSimHttpConnection.cpp b/simulation/halsim_ws_server/src/main/native/cpp/HALSimHttpConnection.cpp index d6967b47e9..3a2e3b2d24 100644 --- a/simulation/halsim_ws_server/src/main/native/cpp/HALSimHttpConnection.cpp +++ b/simulation/halsim_ws_server/src/main/native/cpp/HALSimHttpConnection.cpp @@ -6,12 +6,15 @@ #include +#include + +#include #include #include +#include #include #include #include -#include #include #include @@ -19,7 +22,7 @@ namespace uv = wpi::uv; using namespace wpilibws; -bool HALSimHttpConnection::IsValidWsUpgrade(wpi::StringRef protocol) { +bool HALSimHttpConnection::IsValidWsUpgrade(std::string_view protocol) { if (m_request.GetUrl() != m_server->GetServerUri()) { MySendError(404, "invalid websocket address"); return false; @@ -29,7 +32,7 @@ bool HALSimHttpConnection::IsValidWsUpgrade(wpi::StringRef protocol) { } void HALSimHttpConnection::ProcessWsUpgrade() { - m_websocket->open.connect_extended([this](auto conn, wpi::StringRef) { + m_websocket->open.connect_extended([this](auto conn, auto) { conn.disconnect(); // one-shot if (!m_server->RegisterWebsocket(shared_from_this())) { @@ -40,11 +43,11 @@ void HALSimHttpConnection::ProcessWsUpgrade() { Log(200); m_isWsConnected = true; - wpi::errs() << "HALWebSim: websocket connected\n"; + std::fputs("HALWebSim: websocket connected\n", stderr); }); // parse incoming JSON, dispatch to parent - m_websocket->text.connect([this](wpi::StringRef msg, bool) { + m_websocket->text.connect([this](auto msg, bool) { if (!m_isWsConnected) { return; } @@ -61,10 +64,10 @@ void HALSimHttpConnection::ProcessWsUpgrade() { m_server->OnNetValueChanged(j); }); - m_websocket->closed.connect([this](uint16_t, wpi::StringRef) { + m_websocket->closed.connect([this](uint16_t, auto) { // unset the global, allow another websocket to connect if (m_isWsConnected) { - wpi::errs() << "HALWebSim: websocket disconnected\n"; + std::fputs("HALWebSim: websocket disconnected\n", stderr); m_isWsConnected = false; m_server->CloseWebsocket(shared_from_this()); @@ -91,30 +94,28 @@ void HALSimHttpConnection::OnSimValueChanged(const wpi::json& msg) { } if (err) { - wpi::errs() << err.str() << "\n"; - wpi::errs().flush(); + fmt::print(stderr, "{}\n", err.str()); + std::fflush(stderr); } }); }); } -void HALSimHttpConnection::SendFileResponse(int code, - const wpi::Twine& codeText, - const wpi::Twine& contentType, - const wpi::Twine& filename, - const wpi::Twine& extraHeader) { - std::string fn = filename.str(); +void HALSimHttpConnection::SendFileResponse(int code, std::string_view codeText, + std::string_view contentType, + std::string_view filename, + std::string_view extraHeader) { std::error_code ec; // get file size - auto size = fs::file_size(fn, ec); + auto size = fs::file_size(filename, ec); if (ec) { MySendError(404, "error getting file size"); return; } // open file - wpi::raw_fd_istream is{fn, ec, true}; + wpi::raw_fd_istream is{filename, ec, true}; if (ec) { MySendError(404, "error opening file"); return; @@ -157,23 +158,23 @@ void HALSimHttpConnection::ProcessRequest() { return; } - wpi::StringRef path; + std::string_view path; if (url.HasPath()) { path = url.GetPath(); } - if (m_request.GetMethod() == wpi::HTTP_GET && path.startswith("/") && - !path.contains("..") && !path.contains("//")) { + if (m_request.GetMethod() == wpi::HTTP_GET && wpi::starts_with(path, '/') && + !wpi::contains(path, "..") && !wpi::contains(path, "//")) { // convert to fs native representation fs::path nativePath; - if (path.startswith("/user/")) { - nativePath = fs::path{std::string{m_server->GetWebrootSys()}} / - fs::path{std::string{path.drop_front(6)}, - fs::path::format::generic_format}; + if (wpi::starts_with(path, "/user/")) { + nativePath = + fs::path{m_server->GetWebrootSys()} / + fs::path{wpi::drop_front(path, 6), fs::path::format::generic_format}; } else { - nativePath = fs::path{std::string{m_server->GetWebrootSys()}} / - fs::path{std::string{path.drop_front(1)}, - fs::path::format::generic_format}; + nativePath = + fs::path{m_server->GetWebrootSys()} / + fs::path{wpi::drop_front(path, 1), fs::path::format::generic_format}; } if (fs::is_directory(nativePath)) { @@ -181,7 +182,7 @@ void HALSimHttpConnection::ProcessRequest() { } if (!fs::exists(nativePath) || fs::is_directory(nativePath)) { - MySendError(404, "Resource '" + path + "' not found"); + MySendError(404, fmt::format("Resource '{}' not found", path)); } else { auto contentType = wpi::MimeTypeFromPath(nativePath.string()); SendFileResponse(200, "OK", contentType, nativePath.string()); @@ -191,14 +192,13 @@ void HALSimHttpConnection::ProcessRequest() { } } -void HALSimHttpConnection::MySendError(int code, const wpi::Twine& message) { +void HALSimHttpConnection::MySendError(int code, std::string_view message) { Log(code); SendError(code, message); } void HALSimHttpConnection::Log(int code) { auto method = wpi::http_method_str(m_request.GetMethod()); - wpi::errs() << method << " " << m_request.GetUrl() << " HTTP/" - << m_request.GetMajor() << "." << m_request.GetMinor() << " " - << code << "\n"; + fmt::print(stderr, "{} {} HTTP/{}.{} {}\n", method, m_request.GetUrl(), + m_request.GetMajor(), m_request.GetMinor(), code); } diff --git a/simulation/halsim_ws_server/src/main/native/cpp/HALSimWeb.cpp b/simulation/halsim_ws_server/src/main/native/cpp/HALSimWeb.cpp index 902916ef52..43e3b08962 100644 --- a/simulation/halsim_ws_server/src/main/native/cpp/HALSimWeb.cpp +++ b/simulation/halsim_ws_server/src/main/native/cpp/HALSimWeb.cpp @@ -4,8 +4,8 @@ #include "HALSimWeb.h" +#include #include -#include #include #include #include @@ -25,7 +25,7 @@ HALSimWeb::HALSimWeb(wpi::uv::Loop& loop, ProviderContainer& providers, m_providers(providers), m_simDevicesProvider(simDevicesProvider) { m_loop.error.connect([](uv::Error err) { - wpi::errs() << "HALSim WS Server libuv ERROR: " << err.str() << '\n'; + fmt::print(stderr, "HALSim WS Server libuv ERROR: {}\n", err.str()); }); m_server = uv::Tcp::Create(m_loop); @@ -70,7 +70,7 @@ bool HALSimWeb::Initialize() { try { m_port = std::stoi(port); } catch (const std::invalid_argument& err) { - wpi::errs() << "Error decoding HALSIMWS_PORT (" << err.what() << ")\n"; + fmt::print(stderr, "Error decoding HALSIMWS_PORT ({})\n", err.what()); return false; } } else { @@ -98,8 +98,8 @@ void HALSimWeb::Start() { // start listening for incoming connections m_server->Listen(); - wpi::outs() << "Listening at http://localhost:" << m_port << "\n"; - wpi::outs() << "WebSocket URI: " << m_uri << "\n"; + fmt::print("Listening at http://localhost:{}\n", m_port); + fmt::print("WebSocket URI: {}\n", m_uri); } bool HALSimWeb::RegisterWebsocket( @@ -154,6 +154,6 @@ void HALSimWeb::OnNetValueChanged(const wpi::json& msg) { provider->OnNetValueChanged(msg.at("data")); } } catch (wpi::json::exception& e) { - wpi::errs() << "Error with incoming message: " << e.what() << "\n"; + fmt::print(stderr, "Error with incoming message: {}\n", e.what()); } } diff --git a/simulation/halsim_ws_server/src/main/native/cpp/main.cpp b/simulation/halsim_ws_server/src/main/native/cpp/main.cpp index 6cc5be813e..1ee0ae8bba 100644 --- a/simulation/halsim_ws_server/src/main/native/cpp/main.cpp +++ b/simulation/halsim_ws_server/src/main/native/cpp/main.cpp @@ -2,10 +2,10 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include #include #include -#include #include "HALSimWSServer.h" @@ -19,7 +19,7 @@ extern "C" { __declspec(dllexport) #endif int HALSIM_InitExtension(void) { - wpi::outs() << "Websocket WS Server Initializing.\n"; + std::puts("Websocket WS Server Initializing."); HAL_OnShutdown(nullptr, [](void*) { gServer.reset(); }); @@ -28,7 +28,7 @@ __declspec(dllexport) return -1; } - wpi::outs() << "Websocket WS Server Initialized!\n"; + std::puts("Websocket WS Server Initialized!"); return 0; } } // extern "C" diff --git a/simulation/halsim_ws_server/src/main/native/include/HALSimHttpConnection.h b/simulation/halsim_ws_server/src/main/native/include/HALSimHttpConnection.h index d6f65e5ad4..217e2ba4bb 100644 --- a/simulation/halsim_ws_server/src/main/native/include/HALSimHttpConnection.h +++ b/simulation/halsim_ws_server/src/main/native/include/HALSimHttpConnection.h @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -38,14 +39,13 @@ class HALSimHttpConnection protected: void ProcessRequest() override; - bool IsValidWsUpgrade(wpi::StringRef protocol) override; + bool IsValidWsUpgrade(std::string_view protocol) override; void ProcessWsUpgrade() override; - void SendFileResponse(int code, const wpi::Twine& codeText, - const wpi::Twine& contentType, - const wpi::Twine& filename, - const wpi::Twine& extraHeader = wpi::Twine{}); + void SendFileResponse(int code, std::string_view codeText, + std::string_view contentType, std::string_view filename, + std::string_view extraHeader = {}); - void MySendError(int code, const wpi::Twine& message); + void MySendError(int code, std::string_view message); void Log(int code); private: diff --git a/simulation/halsim_ws_server/src/main/native/include/HALSimWeb.h b/simulation/halsim_ws_server/src/main/native/include/HALSimWeb.h index 3026b368bf..83a680e74f 100644 --- a/simulation/halsim_ws_server/src/main/native/include/HALSimWeb.h +++ b/simulation/halsim_ws_server/src/main/native/include/HALSimWeb.h @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -42,9 +41,9 @@ class HALSimWeb : public std::enable_shared_from_this { // network -> sim void OnNetValueChanged(const wpi::json& msg); - wpi::StringRef GetWebrootSys() const { return m_webroot_sys; } - wpi::StringRef GetWebrootUser() const { return m_webroot_user; } - wpi::StringRef GetServerUri() const { return m_uri; } + const std::string& GetWebrootSys() const { return m_webroot_sys; } + const std::string& GetWebrootUser() const { return m_webroot_user; } + const std::string& GetServerUri() const { return m_uri; } int GetServerPort() const { return m_port; } wpi::uv::Loop& GetLoop() { return m_loop; } diff --git a/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp b/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp index 03469f3360..f13a0c65b3 100644 --- a/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp +++ b/simulation/halsim_ws_server/src/test/native/cpp/WebServerClientTest.cpp @@ -4,10 +4,10 @@ #include "WebServerClientTest.h" -#include +#include +#include #include -#include #include #include @@ -20,14 +20,12 @@ namespace wpilibws { // Create Web Socket and specify event callbacks void WebServerClientTest::InitializeWebSocket(const std::string& host, int port, const std::string& uri) { - std::stringstream ss; - ss << host << ":" << port; - wpi::outs() << "Will attempt to connect to: " << ss.str() << uri << "\n"; - m_websocket = - wpi::WebSocket::CreateClient(*m_tcp_client.get(), uri, ss.str()); + fmt::print("Will attempt to connect to: {}:{}{}\n", host, port, uri); + m_websocket = wpi::WebSocket::CreateClient(*m_tcp_client.get(), uri, + fmt::format("{}:{}", host, port)); // Hook up events - m_websocket->open.connect_extended([this](auto conn, wpi::StringRef) { + m_websocket->open.connect_extended([this](auto conn, auto) { conn.disconnect(); m_buffers = std::make_unique(); @@ -38,17 +36,17 @@ void WebServerClientTest::InitializeWebSocket(const std::string& host, int port, }); m_ws_connected = true; - wpi::errs() << "WebServerClientTest: WebSocket Connected\n"; + std::fputs("WebServerClientTest: WebSocket Connected\n", stderr); }); - m_websocket->text.connect([this](wpi::StringRef msg, bool) { + m_websocket->text.connect([this](auto msg, bool) { wpi::json j; try { j = wpi::json::parse(msg); } catch (const wpi::json::parse_error& e) { std::string err("JSON parse failed: "); err += e.what(); - wpi::errs() << err << "\n"; + fmt::print(stderr, "{}\n", err); m_websocket->Fail(1003, err); return; } @@ -56,9 +54,9 @@ void WebServerClientTest::InitializeWebSocket(const std::string& host, int port, m_json = j; }); - m_websocket->closed.connect([this](uint16_t, wpi::StringRef) { + m_websocket->closed.connect([this](uint16_t, auto) { if (m_ws_connected) { - wpi::errs() << "WebServerClientTest: Websocket Disconnected\n"; + std::fputs("WebServerClientTest: Websocket Disconnected\n", stderr); m_ws_connected = false; } }); @@ -67,11 +65,11 @@ void WebServerClientTest::InitializeWebSocket(const std::string& host, int port, // Create tcp client, specify callbacks, and create timers for loop bool WebServerClientTest::Initialize() { m_loop.error.connect( - [](uv::Error err) { wpi::errs() << "uv Error: " << err.str() << "\n"; }); + [](uv::Error err) { fmt::print(stderr, "uv Error: {}\n", err.str()); }); m_tcp_client = uv::Tcp::Create(m_loop); if (!m_tcp_client) { - wpi::errs() << "ERROR: Could not create TCP Client\n"; + std::fputs("ERROR: Could not create TCP Client\n", stderr); return false; } @@ -90,7 +88,7 @@ bool WebServerClientTest::Initialize() { }); m_tcp_client->closed.connect( - []() { wpi::errs() << "TCP connection closed\n"; }); + []() { std::fputs("TCP connection closed\n", stderr); }); // Set up the connection timer m_connect_timer = uv::Timer::Create(m_loop); @@ -101,18 +99,17 @@ bool WebServerClientTest::Initialize() { m_connect_timer->timeout.connect([this] { AttemptConnect(); }); m_connect_timer->Start(uv::Timer::Time(0)); - wpi::outs() << "WebServerClientTest Initialized\n"; + std::puts("WebServerClientTest Initialized"); return true; } void WebServerClientTest::AttemptConnect() { m_connect_attempts++; - wpi::outs() << "Test Client Connection Attempt " << m_connect_attempts - << "\n"; + fmt::print("Test Client Connection Attempt {}\n", m_connect_attempts); if (m_connect_attempts >= 5) { - wpi::errs() << "Test Client Timeout. Unable to connect\n"; + std::fputs("Test Client Timeout. Unable to connect\n", stderr); m_loop.Stop(); return; } @@ -127,7 +124,7 @@ void WebServerClientTest::AttemptConnect() { void WebServerClientTest::SendMessage(const wpi::json& msg) { if (msg.empty()) { - wpi::errs() << "Message to send is empty\n"; + std::fputs("Message to send is empty\n", stderr); return; } @@ -147,8 +144,8 @@ void WebServerClientTest::SendMessage(const wpi::json& msg) { m_buffers->Release(bufs); } if (err) { - wpi::errs() << err.str() << "\n"; - wpi::errs().flush(); + fmt::print(stderr, "{}\n", err.str()); + std::fflush(stderr); } }); }); diff --git a/simulation/halsim_ws_server/src/test/native/cpp/main.cpp b/simulation/halsim_ws_server/src/test/native/cpp/main.cpp index 0b4628e462..ef31ba1fb8 100644 --- a/simulation/halsim_ws_server/src/test/native/cpp/main.cpp +++ b/simulation/halsim_ws_server/src/test/native/cpp/main.cpp @@ -4,11 +4,11 @@ #include +#include #include #include #include #include -#include #include #include "HALSimWSServer.h" @@ -55,8 +55,8 @@ TEST_F(WebServerIntegrationTest, DISABLED_DigitalOutput) { return; } if (IsConnectedClientWS()) { - wpi::outs() << "***** Setting DIO value for pin " << PIN << " to " - << (EXPECTED_VALUE ? "true" : "false") << "\n"; + fmt::print("***** Setting DIO value for pin {} to {}\n", PIN, + (EXPECTED_VALUE ? "true" : "false")); HALSIM_SetDIOValue(PIN, EXPECTED_VALUE); done = true; } @@ -83,7 +83,7 @@ TEST_F(WebServerIntegrationTest, DISABLED_DigitalOutput) { test_value = it.value(); } } catch (wpi::json::exception& e) { - wpi::errs() << "Error with incoming message: " << e.what() << "\n"; + fmt::print(stderr, "Error with incoming message: {}\n", e.what()); } // Compare results @@ -109,7 +109,7 @@ TEST_F(WebServerIntegrationTest, DISABLED_DigitalInput) { wpi::json msg = {{"type", "DIO"}, {"device", std::to_string(PIN)}, {"data", {{"<>value", EXPECTED_VALUE}}}}; - wpi::outs() << "***** Input JSON: " << msg.dump() << "\n"; + fmt::print("***** Input JSON: {}\n", msg.dump()); m_webserverClient->SendMessage(msg); done = true; } @@ -144,7 +144,7 @@ TEST_F(WebServerIntegrationTest, DriverStation) { {"type", "DriverStation"}, {"device", ""}, {"data", {{">enabled", EXPECTED_VALUE}, {">new_data", true}}}}; - wpi::outs() << "***** Input JSON: " << msg.dump() << "\n"; + fmt::print("***** Input JSON: {}\n", msg.dump()); m_webserverClient->SendMessage(msg); done = true; } diff --git a/wpigui/src/main/native/include/wpigui.h b/wpigui/src/main/native/include/wpigui.h index 228f89d3ed..7860f0debd 100644 --- a/wpigui/src/main/native/include/wpigui.h +++ b/wpigui/src/main/native/include/wpigui.h @@ -6,14 +6,10 @@ #include #include +#include #include -#if __has_include() -#include -#define WPIGUI_HAS_STRINGREF -#endif - extern "C" struct GLFWwindow; namespace wpi::gui { @@ -98,11 +94,10 @@ GLFWwindow* GetSystemWindow(); */ bool AddIcon(const unsigned char* data, int len); -#ifdef WPIGUI_HAS_STRINGREF -inline bool AddIcon(wpi::StringRef data) { - return AddIcon(data.bytes_begin(), data.size()); +inline bool AddIcon(std::string_view data) { + return AddIcon(reinterpret_cast(data.data()), + data.size()); } -#endif /** * Adds a font to the GUI. The passed function is called during diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp index c51ad2ed2b..f269698dfe 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandScheduler.cpp @@ -4,6 +4,8 @@ #include "frc2/command/CommandScheduler.h" +#include + #include #include #include @@ -15,7 +17,6 @@ #include #include #include -#include #include "frc2/command/CommandGroupBase.h" #include "frc2/command/CommandState.h" @@ -65,7 +66,7 @@ static bool ContainsKey(const TMap& map, TKey keyToCheck) { CommandScheduler::CommandScheduler() : m_impl(new Impl), m_watchdog(frc::TimedRobot::kDefaultPeriod, [] { - wpi::outs() << "CommandScheduler loop time overrun.\n"; + std::puts("CommandScheduler loop time overrun."); }) { HAL_Report(HALUsageReporting::kResourceType_Command, HALUsageReporting::kCommand2_Scheduler); diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp index af711aadc1..8d7c855602 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/PrintCommand.cpp @@ -4,13 +4,13 @@ #include "frc2/command/PrintCommand.h" -#include +#include using namespace frc2; PrintCommand::PrintCommand(std::string_view message) - : CommandHelper{ - [str = std::string(message)] { wpi::outs() << str << "\n"; }, {}} {} + : CommandHelper{[str = std::string(message)] { fmt::print("{}\n", str); }, + {}} {} bool PrintCommand::RunsWhenDisabled() const { return true; diff --git a/wpilibOldCommands/src/main/native/cpp/commands/PrintCommand.cpp b/wpilibOldCommands/src/main/native/cpp/commands/PrintCommand.cpp index 3589feea2d..ca8f49a84a 100644 --- a/wpilibOldCommands/src/main/native/cpp/commands/PrintCommand.cpp +++ b/wpilibOldCommands/src/main/native/cpp/commands/PrintCommand.cpp @@ -5,7 +5,6 @@ #include "frc/commands/PrintCommand.h" #include -#include using namespace frc; @@ -15,5 +14,5 @@ PrintCommand::PrintCommand(std::string_view message) } void PrintCommand::Initialize() { - wpi::outs() << m_message << '\n'; + fmt::print("{}\n", m_message); } diff --git a/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp b/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp index 12fda75d1c..bae03c7d02 100644 --- a/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp +++ b/wpilibc/src/main/native/cpp/DoubleSolenoid.cpp @@ -121,7 +121,7 @@ void DoubleSolenoid::InitSendable(SendableBuilder& builder) { builder.SetSafeState([=]() { Set(kOff); }); builder.AddSmallStringProperty( "Value", - [=](wpi::SmallVectorImpl& buf) -> wpi::StringRef { + [=](wpi::SmallVectorImpl& buf) -> std::string_view { switch (Get()) { case kForward: return "Forward"; @@ -131,7 +131,7 @@ void DoubleSolenoid::InitSendable(SendableBuilder& builder) { return "Off"; } }, - [=](wpi::StringRef value) { + [=](std::string_view value) { Value lvalue = kOff; if (value == "Forward") { lvalue = kForward; diff --git a/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp b/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp index 6202e5bff0..2033745c60 100644 --- a/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp +++ b/wpilibc/src/main/native/cpp/IterativeRobotBase.cpp @@ -4,9 +4,9 @@ #include "frc/IterativeRobotBase.h" +#include #include #include -#include #include "frc/Errors.h" #include "frc/livewindow/LiveWindow.h" @@ -23,33 +23,33 @@ IterativeRobotBase::IterativeRobotBase(units::second_t period) m_watchdog(period, [this] { PrintLoopOverrunMessage(); }) {} void IterativeRobotBase::RobotInit() { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); } void IterativeRobotBase::SimulationInit() { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); } void IterativeRobotBase::DisabledInit() { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); } void IterativeRobotBase::AutonomousInit() { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); } void IterativeRobotBase::TeleopInit() { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); } void IterativeRobotBase::TestInit() { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); } void IterativeRobotBase::RobotPeriodic() { static bool firstRun = true; if (firstRun) { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -57,7 +57,7 @@ void IterativeRobotBase::RobotPeriodic() { void IterativeRobotBase::SimulationPeriodic() { static bool firstRun = true; if (firstRun) { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -65,7 +65,7 @@ void IterativeRobotBase::SimulationPeriodic() { void IterativeRobotBase::DisabledPeriodic() { static bool firstRun = true; if (firstRun) { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -73,7 +73,7 @@ void IterativeRobotBase::DisabledPeriodic() { void IterativeRobotBase::AutonomousPeriodic() { static bool firstRun = true; if (firstRun) { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -81,7 +81,7 @@ void IterativeRobotBase::AutonomousPeriodic() { void IterativeRobotBase::TeleopPeriodic() { static bool firstRun = true; if (firstRun) { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } @@ -89,7 +89,7 @@ void IterativeRobotBase::TeleopPeriodic() { void IterativeRobotBase::TestPeriodic() { static bool firstRun = true; if (firstRun) { - wpi::outs() << "Default " << __FUNCTION__ << "() method... Override me!\n"; + fmt::print("Default {}() method... Override me!\n", __FUNCTION__); firstRun = false; } } diff --git a/wpilibc/src/main/native/cpp/Preferences.cpp b/wpilibc/src/main/native/cpp/Preferences.cpp index ca38900733..ae8c578514 100644 --- a/wpilibc/src/main/native/cpp/Preferences.cpp +++ b/wpilibc/src/main/native/cpp/Preferences.cpp @@ -8,12 +8,11 @@ #include #include -#include using namespace frc; // The Preferences table name -static wpi::StringRef kTableName{"Preferences"}; +static constexpr std::string_view kTableName{"Preferences"}; Preferences* Preferences::GetInstance() { static Preferences instance; @@ -24,126 +23,126 @@ std::vector Preferences::GetKeys() { return m_table->GetKeys(); } -std::string Preferences::GetString(wpi::StringRef key, - wpi::StringRef defaultValue) { +std::string Preferences::GetString(std::string_view key, + std::string_view defaultValue) { return m_table->GetString(key, defaultValue); } -int Preferences::GetInt(wpi::StringRef key, int defaultValue) { +int Preferences::GetInt(std::string_view key, int defaultValue) { return static_cast(m_table->GetNumber(key, defaultValue)); } -double Preferences::GetDouble(wpi::StringRef key, double defaultValue) { +double Preferences::GetDouble(std::string_view key, double defaultValue) { return m_table->GetNumber(key, defaultValue); } -float Preferences::GetFloat(wpi::StringRef key, float defaultValue) { +float Preferences::GetFloat(std::string_view key, float defaultValue) { return m_table->GetNumber(key, defaultValue); } -bool Preferences::GetBoolean(wpi::StringRef key, bool defaultValue) { +bool Preferences::GetBoolean(std::string_view key, bool defaultValue) { return m_table->GetBoolean(key, defaultValue); } -int64_t Preferences::GetLong(wpi::StringRef key, int64_t defaultValue) { +int64_t Preferences::GetLong(std::string_view key, int64_t defaultValue) { return static_cast(m_table->GetNumber(key, defaultValue)); } -void Preferences::SetString(wpi::StringRef key, wpi::StringRef value) { +void Preferences::SetString(std::string_view key, std::string_view value) { auto entry = m_table->GetEntry(key); entry.SetString(value); entry.SetPersistent(); } -void Preferences::PutString(wpi::StringRef key, wpi::StringRef value) { +void Preferences::PutString(std::string_view key, std::string_view value) { SetString(key, value); } -void Preferences::InitString(wpi::StringRef key, wpi::StringRef value) { +void Preferences::InitString(std::string_view key, std::string_view value) { auto entry = m_table->GetEntry(key); entry.SetDefaultString(value); } -void Preferences::SetInt(wpi::StringRef key, int value) { +void Preferences::SetInt(std::string_view key, int value) { auto entry = m_table->GetEntry(key); entry.SetDouble(value); entry.SetPersistent(); } -void Preferences::PutInt(wpi::StringRef key, int value) { +void Preferences::PutInt(std::string_view key, int value) { SetInt(key, value); } -void Preferences::InitInt(wpi::StringRef key, int value) { +void Preferences::InitInt(std::string_view key, int value) { auto entry = m_table->GetEntry(key); entry.SetDefaultDouble(value); } -void Preferences::SetDouble(wpi::StringRef key, double value) { +void Preferences::SetDouble(std::string_view key, double value) { auto entry = m_table->GetEntry(key); entry.SetDouble(value); entry.SetPersistent(); } -void Preferences::PutDouble(wpi::StringRef key, double value) { +void Preferences::PutDouble(std::string_view key, double value) { SetDouble(key, value); } -void Preferences::InitDouble(wpi::StringRef key, double value) { +void Preferences::InitDouble(std::string_view key, double value) { auto entry = m_table->GetEntry(key); entry.SetDefaultDouble(value); } -void Preferences::SetFloat(wpi::StringRef key, float value) { +void Preferences::SetFloat(std::string_view key, float value) { auto entry = m_table->GetEntry(key); entry.SetDouble(value); entry.SetPersistent(); } -void Preferences::PutFloat(wpi::StringRef key, float value) { +void Preferences::PutFloat(std::string_view key, float value) { SetFloat(key, value); } -void Preferences::InitFloat(wpi::StringRef key, float value) { +void Preferences::InitFloat(std::string_view key, float value) { auto entry = m_table->GetEntry(key); entry.SetDefaultDouble(value); } -void Preferences::SetBoolean(wpi::StringRef key, bool value) { +void Preferences::SetBoolean(std::string_view key, bool value) { auto entry = m_table->GetEntry(key); entry.SetBoolean(value); entry.SetPersistent(); } -void Preferences::PutBoolean(wpi::StringRef key, bool value) { +void Preferences::PutBoolean(std::string_view key, bool value) { SetBoolean(key, value); } -void Preferences::InitBoolean(wpi::StringRef key, bool value) { +void Preferences::InitBoolean(std::string_view key, bool value) { auto entry = m_table->GetEntry(key); entry.SetDefaultBoolean(value); } -void Preferences::SetLong(wpi::StringRef key, int64_t value) { +void Preferences::SetLong(std::string_view key, int64_t value) { auto entry = m_table->GetEntry(key); entry.SetDouble(value); entry.SetPersistent(); } -void Preferences::PutLong(wpi::StringRef key, int64_t value) { +void Preferences::PutLong(std::string_view key, int64_t value) { SetLong(key, value); } -void Preferences::InitLong(wpi::StringRef key, int64_t value) { +void Preferences::InitLong(std::string_view key, int64_t value) { auto entry = m_table->GetEntry(key); entry.SetDefaultDouble(value); } -bool Preferences::ContainsKey(wpi::StringRef key) { +bool Preferences::ContainsKey(std::string_view key) { return m_table->ContainsKey(key); } -void Preferences::Remove(wpi::StringRef key) { +void Preferences::Remove(std::string_view key) { m_table->Delete(key); } @@ -159,7 +158,7 @@ Preferences::Preferences() : m_table(nt::NetworkTableInstance::GetDefault().GetTable(kTableName)) { m_table->GetEntry(".type").SetString("RobotPreferences"); m_listener = m_table->AddEntryListener( - [=](nt::NetworkTable* table, wpi::StringRef name, + [=](nt::NetworkTable* table, std::string_view name, nt::NetworkTableEntry entry, std::shared_ptr value, int flags) { entry.SetPersistent(); }, NT_NOTIFY_NEW | NT_NOTIFY_IMMEDIATE); diff --git a/wpilibc/src/main/native/cpp/Relay.cpp b/wpilibc/src/main/native/cpp/Relay.cpp index b925f7d384..887be6fee3 100644 --- a/wpilibc/src/main/native/cpp/Relay.cpp +++ b/wpilibc/src/main/native/cpp/Relay.cpp @@ -178,7 +178,7 @@ void Relay::InitSendable(SendableBuilder& builder) { builder.SetSafeState([=]() { Set(kOff); }); builder.AddSmallStringProperty( "Value", - [=](wpi::SmallVectorImpl& buf) -> wpi::StringRef { + [=](wpi::SmallVectorImpl& buf) -> std::string_view { switch (Get()) { case kOn: return "On"; @@ -190,7 +190,7 @@ void Relay::InitSendable(SendableBuilder& builder) { return "Off"; } }, - [=](wpi::StringRef value) { + [=](std::string_view value) { if (value == "Off") { Set(kOff); } else if (value == "Forward") { diff --git a/wpilibc/src/main/native/cpp/Tracer.cpp b/wpilibc/src/main/native/cpp/Tracer.cpp index 9aa0116f16..1375411ff1 100644 --- a/wpilibc/src/main/native/cpp/Tracer.cpp +++ b/wpilibc/src/main/native/cpp/Tracer.cpp @@ -4,7 +4,7 @@ #include "frc/Tracer.h" -#include +#include #include #include @@ -25,7 +25,7 @@ void Tracer::ClearEpochs() { m_epochs.clear(); } -void Tracer::AddEpoch(wpi::StringRef epochName) { +void Tracer::AddEpoch(std::string_view epochName) { auto currentTime = hal::fpga_clock::now(); m_epochs[epochName] = currentTime - m_startTime; m_startTime = currentTime; @@ -48,11 +48,9 @@ void Tracer::PrintEpochs(wpi::raw_ostream& os) { if (now - m_lastEpochsPrintTime > kMinPrintPeriod) { m_lastEpochsPrintTime = now; for (const auto& epoch : m_epochs) { - os << '\t' << epoch.getKey() << ": " - << wpi::format( - "%.6f", - duration_cast(epoch.getValue()).count() / 1.0e6) - << "s\n"; + os << fmt::format( + "\t{}: {:.6f}s\n", epoch.getKey(), + duration_cast(epoch.getValue()).count() / 1.0e6); } } } diff --git a/wpilibc/src/main/native/cpp/Watchdog.cpp b/wpilibc/src/main/native/cpp/Watchdog.cpp index e6eac6a8cf..8fbfe81f71 100644 --- a/wpilibc/src/main/native/cpp/Watchdog.cpp +++ b/wpilibc/src/main/native/cpp/Watchdog.cpp @@ -192,7 +192,7 @@ bool Watchdog::IsExpired() const { return m_isExpired; } -void Watchdog::AddEpoch(wpi::StringRef epochName) { +void Watchdog::AddEpoch(std::string_view epochName) { m_tracer.AddEpoch(epochName); } diff --git a/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp b/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp index 9b812d41e5..9c47efb8e9 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/LayoutType.cpp @@ -6,6 +6,6 @@ using namespace frc; -wpi::StringRef LayoutType::GetLayoutName() const { +std::string_view LayoutType::GetLayoutName() const { return m_layoutName; } diff --git a/wpilibc/src/main/native/cpp/shuffleboard/RecordingController.cpp b/wpilibc/src/main/native/cpp/shuffleboard/RecordingController.cpp index ecdf977d72..834c4be88d 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/RecordingController.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/RecordingController.cpp @@ -26,7 +26,7 @@ void RecordingController::StopRecording() { m_recordingControlEntry.SetBoolean(false); } -void RecordingController::SetRecordingFileNameFormat(wpi::StringRef format) { +void RecordingController::SetRecordingFileNameFormat(std::string_view format) { m_recordingFileNameFormatEntry.SetString(format); } @@ -35,7 +35,7 @@ void RecordingController::ClearRecordingFileNameFormat() { } void RecordingController::AddEventMarker( - wpi::StringRef name, wpi::StringRef description, + std::string_view name, std::string_view description, ShuffleboardEventImportance importance) { if (name.empty()) { FRC_ReportError(err::Error, "{}", @@ -43,5 +43,6 @@ void RecordingController::AddEventMarker( return; } m_eventsTable->GetSubTable(name)->GetEntry("Info").SetStringArray( - {description, ShuffleboardEventImportanceName(importance)}); + {std::string{description}, + std::string{ShuffleboardEventImportanceName(importance)}}); } diff --git a/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp b/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp index 7c7e535151..16b404c255 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/Shuffleboard.cpp @@ -14,7 +14,7 @@ void Shuffleboard::Update() { GetInstance().Update(); } -ShuffleboardTab& Shuffleboard::GetTab(wpi::StringRef title) { +ShuffleboardTab& Shuffleboard::GetTab(std::string_view title) { return GetInstance().GetTab(title); } @@ -22,7 +22,7 @@ void Shuffleboard::SelectTab(int index) { GetInstance().SelectTab(index); } -void Shuffleboard::SelectTab(wpi::StringRef title) { +void Shuffleboard::SelectTab(std::string_view title) { GetInstance().SelectTab(title); } @@ -44,7 +44,7 @@ void Shuffleboard::StopRecording() { GetRecordingController().StopRecording(); } -void Shuffleboard::SetRecordingFileNameFormat(wpi::StringRef format) { +void Shuffleboard::SetRecordingFileNameFormat(std::string_view format) { GetRecordingController().SetRecordingFileNameFormat(format); } @@ -52,13 +52,13 @@ void Shuffleboard::ClearRecordingFileNameFormat() { GetRecordingController().ClearRecordingFileNameFormat(); } -void Shuffleboard::AddEventMarker(wpi::StringRef name, - wpi::StringRef description, +void Shuffleboard::AddEventMarker(std::string_view name, + std::string_view description, ShuffleboardEventImportance importance) { GetRecordingController().AddEventMarker(name, description, importance); } -void Shuffleboard::AddEventMarker(wpi::StringRef name, +void Shuffleboard::AddEventMarker(std::string_view name, ShuffleboardEventImportance importance) { AddEventMarker(name, "", importance); } diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardContainer.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardContainer.cpp index d1d49b889c..bf36ea66fb 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardContainer.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardContainer.cpp @@ -4,8 +4,6 @@ #include "frc/shuffleboard/ShuffleboardContainer.h" -#include - #include "frc/Errors.h" #include "frc/shuffleboard/ComplexWidget.h" #include "frc/shuffleboard/ShuffleboardComponent.h" @@ -70,7 +68,7 @@ ComplexWidget& ShuffleboardContainer::Add(std::string_view title, ComplexWidget& ShuffleboardContainer::Add(Sendable& sendable) { auto name = SendableRegistry::GetInstance().GetName(&sendable); if (name.empty()) { - wpi::outs() << "Sendable must have a name\n"; + FRC_ReportError(err::Error, "{}", "Sendable must have a name"); } return Add(name, sendable); } @@ -285,7 +283,7 @@ void ShuffleboardContainer::DisableIfActuator() { void ShuffleboardContainer::CheckTitle(std::string_view title) { std::string titleStr{title}; if (m_usedTitles.count(titleStr) > 0) { - wpi::errs() << "Title is already in use: " << title << "\n"; + FRC_ReportError(err::Error, "Title is already in use: {}", title); return; } m_usedTitles.insert(titleStr); diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp index 25daba291f..fb4485b269 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardInstance.cpp @@ -31,7 +31,7 @@ ShuffleboardInstance::ShuffleboardInstance(nt::NetworkTableInstance ntInstance) ShuffleboardInstance::~ShuffleboardInstance() = default; -frc::ShuffleboardTab& ShuffleboardInstance::GetTab(wpi::StringRef title) { +frc::ShuffleboardTab& ShuffleboardInstance::GetTab(std::string_view title) { if (m_impl->tabs.find(title) == m_impl->tabs.end()) { m_impl->tabs.try_emplace(title, ShuffleboardTab(*this, title)); m_impl->tabsChanged = true; @@ -77,6 +77,6 @@ void ShuffleboardInstance::SelectTab(int index) { m_impl->rootMetaTable->GetEntry("Selected").ForceSetDouble(index); } -void ShuffleboardInstance::SelectTab(wpi::StringRef title) { +void ShuffleboardInstance::SelectTab(std::string_view title) { m_impl->rootMetaTable->GetEntry("Selected").ForceSetString(title); } diff --git a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp index 1c91ca72e7..61e0e4541a 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/ShuffleboardTab.cpp @@ -6,7 +6,7 @@ using namespace frc; -ShuffleboardTab::ShuffleboardTab(ShuffleboardRoot& root, wpi::StringRef title) +ShuffleboardTab::ShuffleboardTab(ShuffleboardRoot& root, std::string_view title) : ShuffleboardValue(title), ShuffleboardContainer(title), m_root(root) {} ShuffleboardRoot& ShuffleboardTab::GetRoot() { diff --git a/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp b/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp index 79f7d1440d..3062cba9ad 100644 --- a/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp +++ b/wpilibc/src/main/native/cpp/shuffleboard/WidgetType.cpp @@ -6,6 +6,6 @@ using namespace frc; -wpi::StringRef WidgetType::GetWidgetName() const { +std::string_view WidgetType::GetWidgetName() const { return m_widgetName; } diff --git a/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp index 2ea8237234..1483716da6 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/FieldObject2d.cpp @@ -114,9 +114,9 @@ void FieldObject2d::UpdateEntry(bool setDefault) { p += 8; } if (setDefault) { - m_entry.SetDefaultRaw(wpi::StringRef{arr.data(), arr.size()}); + m_entry.SetDefaultRaw({arr.data(), arr.size()}); } else { - m_entry.ForceSetRaw(wpi::StringRef{arr.data(), arr.size()}); + m_entry.ForceSetRaw({arr.data(), arr.size()}); } } } @@ -144,7 +144,7 @@ void FieldObject2d::UpdateFromEntry() const { } } else if (val->IsRaw()) { // treat it simply as an array of doubles - wpi::StringRef data = val->GetRaw(); + std::string_view data = val->GetRaw(); // must be triples of doubles auto size = data.size(); @@ -152,7 +152,7 @@ void FieldObject2d::UpdateFromEntry() const { return; } m_poses.resize(size / (3 * 8)); - const char* p = data.begin(); + const char* p = data.data(); for (size_t i = 0; i < size / (3 * 8); ++i) { double x = wpi::BitsToDouble( wpi::support::endian::readNext getter, - std::function setter) { + std::function setter) { m_properties.emplace_back(*m_table, key); if (getter) { m_properties.back().update = [=](nt::NetworkTableEntry entry, @@ -255,7 +255,7 @@ void SendableBuilderImpl::AddStringArrayProperty( void SendableBuilderImpl::AddRawProperty( std::string_view key, std::function getter, - std::function setter) { + std::function setter) { m_properties.emplace_back(*m_table, key); if (getter) { m_properties.back().update = [=](nt::NetworkTableEntry entry, @@ -303,8 +303,8 @@ void SendableBuilderImpl::AddValueProperty( void SendableBuilderImpl::AddSmallStringProperty( std::string_view key, - std::function& buf)> getter, - std::function setter) { + std::function& buf)> getter, + std::function setter) { m_properties.emplace_back(*m_table, key); if (getter) { m_properties.back().update = [=](nt::NetworkTableEntry entry, @@ -418,8 +418,8 @@ void SendableBuilderImpl::AddSmallStringArrayProperty( void SendableBuilderImpl::AddSmallRawProperty( std::string_view key, - std::function& buf)> getter, - std::function setter) { + std::function& buf)> getter, + std::function setter) { m_properties.emplace_back(*m_table, key); if (getter) { m_properties.back().update = [=](nt::NetworkTableEntry entry, diff --git a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp index 53ef7f382e..d7794707f2 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/SmartDashboard.cpp @@ -44,7 +44,7 @@ void SmartDashboard::init() { Singleton::GetInstance(); } -bool SmartDashboard::ContainsKey(wpi::StringRef key) { +bool SmartDashboard::ContainsKey(std::string_view key) { return Singleton::GetInstance().table->ContainsKey(key); } @@ -52,39 +52,39 @@ std::vector SmartDashboard::GetKeys(int types) { return Singleton::GetInstance().table->GetKeys(types); } -void SmartDashboard::SetPersistent(wpi::StringRef key) { +void SmartDashboard::SetPersistent(std::string_view key) { Singleton::GetInstance().table->GetEntry(key).SetPersistent(); } -void SmartDashboard::ClearPersistent(wpi::StringRef key) { +void SmartDashboard::ClearPersistent(std::string_view key) { Singleton::GetInstance().table->GetEntry(key).ClearPersistent(); } -bool SmartDashboard::IsPersistent(wpi::StringRef key) { +bool SmartDashboard::IsPersistent(std::string_view key) { return Singleton::GetInstance().table->GetEntry(key).IsPersistent(); } -void SmartDashboard::SetFlags(wpi::StringRef key, unsigned int flags) { +void SmartDashboard::SetFlags(std::string_view key, unsigned int flags) { Singleton::GetInstance().table->GetEntry(key).SetFlags(flags); } -void SmartDashboard::ClearFlags(wpi::StringRef key, unsigned int flags) { +void SmartDashboard::ClearFlags(std::string_view key, unsigned int flags) { Singleton::GetInstance().table->GetEntry(key).ClearFlags(flags); } -unsigned int SmartDashboard::GetFlags(wpi::StringRef key) { +unsigned int SmartDashboard::GetFlags(std::string_view key) { return Singleton::GetInstance().table->GetEntry(key).GetFlags(); } -void SmartDashboard::Delete(wpi::StringRef key) { +void SmartDashboard::Delete(std::string_view key) { Singleton::GetInstance().table->Delete(key); } -nt::NetworkTableEntry SmartDashboard::GetEntry(wpi::StringRef key) { +nt::NetworkTableEntry SmartDashboard::GetEntry(std::string_view key) { return Singleton::GetInstance().table->GetEntry(key); } -void SmartDashboard::PutData(wpi::StringRef key, Sendable* data) { +void SmartDashboard::PutData(std::string_view key, Sendable* data) { if (!data) { throw FRC_MakeError(err::NullParameter, "{}", "value"); } @@ -111,7 +111,7 @@ void SmartDashboard::PutData(Sendable* value) { } } -Sendable* SmartDashboard::GetData(wpi::StringRef key) { +Sendable* SmartDashboard::GetData(std::string_view key) { auto& inst = Singleton::GetInstance(); std::scoped_lock lock(inst.tablesToDataMutex); auto it = inst.tablesToData.find(key); @@ -121,128 +121,132 @@ Sendable* SmartDashboard::GetData(wpi::StringRef key) { return SendableRegistry::GetInstance().GetSendable(it->getValue()); } -bool SmartDashboard::PutBoolean(wpi::StringRef keyName, bool value) { +bool SmartDashboard::PutBoolean(std::string_view keyName, bool value) { return Singleton::GetInstance().table->GetEntry(keyName).SetBoolean(value); } -bool SmartDashboard::SetDefaultBoolean(wpi::StringRef key, bool defaultValue) { +bool SmartDashboard::SetDefaultBoolean(std::string_view key, + bool defaultValue) { return Singleton::GetInstance().table->GetEntry(key).SetDefaultBoolean( defaultValue); } -bool SmartDashboard::GetBoolean(wpi::StringRef keyName, bool defaultValue) { +bool SmartDashboard::GetBoolean(std::string_view keyName, bool defaultValue) { return Singleton::GetInstance().table->GetEntry(keyName).GetBoolean( defaultValue); } -bool SmartDashboard::PutNumber(wpi::StringRef keyName, double value) { +bool SmartDashboard::PutNumber(std::string_view keyName, double value) { return Singleton::GetInstance().table->GetEntry(keyName).SetDouble(value); } -bool SmartDashboard::SetDefaultNumber(wpi::StringRef key, double defaultValue) { +bool SmartDashboard::SetDefaultNumber(std::string_view key, + double defaultValue) { return Singleton::GetInstance().table->GetEntry(key).SetDefaultDouble( defaultValue); } -double SmartDashboard::GetNumber(wpi::StringRef keyName, double defaultValue) { +double SmartDashboard::GetNumber(std::string_view keyName, + double defaultValue) { return Singleton::GetInstance().table->GetEntry(keyName).GetDouble( defaultValue); } -bool SmartDashboard::PutString(wpi::StringRef keyName, wpi::StringRef value) { +bool SmartDashboard::PutString(std::string_view keyName, + std::string_view value) { return Singleton::GetInstance().table->GetEntry(keyName).SetString(value); } -bool SmartDashboard::SetDefaultString(wpi::StringRef key, - wpi::StringRef defaultValue) { +bool SmartDashboard::SetDefaultString(std::string_view key, + std::string_view defaultValue) { return Singleton::GetInstance().table->GetEntry(key).SetDefaultString( defaultValue); } -std::string SmartDashboard::GetString(wpi::StringRef keyName, - wpi::StringRef defaultValue) { +std::string SmartDashboard::GetString(std::string_view keyName, + std::string_view defaultValue) { return Singleton::GetInstance().table->GetEntry(keyName).GetString( defaultValue); } -bool SmartDashboard::PutBooleanArray(wpi::StringRef key, +bool SmartDashboard::PutBooleanArray(std::string_view key, wpi::ArrayRef value) { return Singleton::GetInstance().table->GetEntry(key).SetBooleanArray(value); } -bool SmartDashboard::SetDefaultBooleanArray(wpi::StringRef key, +bool SmartDashboard::SetDefaultBooleanArray(std::string_view key, wpi::ArrayRef defaultValue) { return Singleton::GetInstance().table->GetEntry(key).SetDefaultBooleanArray( defaultValue); } std::vector SmartDashboard::GetBooleanArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) { + std::string_view key, wpi::ArrayRef defaultValue) { return Singleton::GetInstance().table->GetEntry(key).GetBooleanArray( defaultValue); } -bool SmartDashboard::PutNumberArray(wpi::StringRef key, +bool SmartDashboard::PutNumberArray(std::string_view key, wpi::ArrayRef value) { return Singleton::GetInstance().table->GetEntry(key).SetDoubleArray(value); } -bool SmartDashboard::SetDefaultNumberArray(wpi::StringRef key, +bool SmartDashboard::SetDefaultNumberArray(std::string_view key, wpi::ArrayRef defaultValue) { return Singleton::GetInstance().table->GetEntry(key).SetDefaultDoubleArray( defaultValue); } std::vector SmartDashboard::GetNumberArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) { + std::string_view key, wpi::ArrayRef defaultValue) { return Singleton::GetInstance().table->GetEntry(key).GetDoubleArray( defaultValue); } -bool SmartDashboard::PutStringArray(wpi::StringRef key, +bool SmartDashboard::PutStringArray(std::string_view key, wpi::ArrayRef value) { return Singleton::GetInstance().table->GetEntry(key).SetStringArray(value); } bool SmartDashboard::SetDefaultStringArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) { + std::string_view key, wpi::ArrayRef defaultValue) { return Singleton::GetInstance().table->GetEntry(key).SetDefaultStringArray( defaultValue); } std::vector SmartDashboard::GetStringArray( - wpi::StringRef key, wpi::ArrayRef defaultValue) { + std::string_view key, wpi::ArrayRef defaultValue) { return Singleton::GetInstance().table->GetEntry(key).GetStringArray( defaultValue); } -bool SmartDashboard::PutRaw(wpi::StringRef key, wpi::StringRef value) { +bool SmartDashboard::PutRaw(std::string_view key, std::string_view value) { return Singleton::GetInstance().table->GetEntry(key).SetRaw(value); } -bool SmartDashboard::SetDefaultRaw(wpi::StringRef key, - wpi::StringRef defaultValue) { +bool SmartDashboard::SetDefaultRaw(std::string_view key, + std::string_view defaultValue) { return Singleton::GetInstance().table->GetEntry(key).SetDefaultRaw( defaultValue); } -std::string SmartDashboard::GetRaw(wpi::StringRef key, - wpi::StringRef defaultValue) { +std::string SmartDashboard::GetRaw(std::string_view key, + std::string_view defaultValue) { return Singleton::GetInstance().table->GetEntry(key).GetRaw(defaultValue); } -bool SmartDashboard::PutValue(wpi::StringRef keyName, +bool SmartDashboard::PutValue(std::string_view keyName, std::shared_ptr value) { return Singleton::GetInstance().table->GetEntry(keyName).SetValue(value); } -bool SmartDashboard::SetDefaultValue(wpi::StringRef key, +bool SmartDashboard::SetDefaultValue(std::string_view key, std::shared_ptr defaultValue) { return Singleton::GetInstance().table->GetEntry(key).SetDefaultValue( defaultValue); } -std::shared_ptr SmartDashboard::GetValue(wpi::StringRef keyName) { +std::shared_ptr SmartDashboard::GetValue(std::string_view keyName) { return Singleton::GetInstance().table->GetEntry(keyName).GetValue(); } diff --git a/wpilibc/src/main/native/cppcs/RobotBase.cpp b/wpilibc/src/main/native/cppcs/RobotBase.cpp index f0fab4ddce..ab8bf896e1 100644 --- a/wpilibc/src/main/native/cppcs/RobotBase.cpp +++ b/wpilibc/src/main/native/cppcs/RobotBase.cpp @@ -30,12 +30,12 @@ using namespace frc; int frc::RunHALInitialization() { if (!HAL_Initialize(500, 0)) { - wpi::errs() << "FATAL ERROR: HAL could not be initialized\n"; + std::puts("FATAL ERROR: HAL could not be initialized"); return -1; } HAL_Report(HALUsageReporting::kResourceType_Language, HALUsageReporting::kLanguage_CPlusPlus, 0, GetWPILibVersion()); - wpi::outs() << "\n********** Robot program starting **********\n"; + std::puts("\n********** Robot program starting **********"); return 0; } @@ -124,8 +124,8 @@ static void SetupCameraServerShared() { #endif if (!cameraServerLib) { - wpi::outs() << "Camera Server Library Not Found\n"; - wpi::outs().flush(); + std::puts("Camera Server Library Not Found"); + std::fflush(stdout); return; } auto symbol = dlsym(cameraServerLib, "CameraServer_SetCameraServerShared"); @@ -133,15 +133,15 @@ static void SetupCameraServerShared() { auto setCameraServerShared = (SetCameraServerSharedFP)symbol; setCameraServerShared(new WPILibCameraServerShared{}); } else { - wpi::outs() << "Camera Server Shared Symbol Missing\n"; - wpi::outs().flush(); + std::puts("Camera Server Shared Symbol Missing"); + std::fflush(stdout); } #else CameraServer_SetCameraServerShared(new WPILibCameraServerShared{}); #endif #else - wpi::outs() << "Not loading CameraServerShared\n"; - wpi::outs().flush(); + std::puts("Not loading CameraServerShared"); + std::fflush(stdout); #endif } diff --git a/wpilibc/src/main/native/include/frc/Preferences.h b/wpilibc/src/main/native/include/frc/Preferences.h index 3a6d597646..0df03bce77 100644 --- a/wpilibc/src/main/native/include/frc/Preferences.h +++ b/wpilibc/src/main/native/include/frc/Preferences.h @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -53,7 +54,8 @@ class Preferences { * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ - std::string GetString(wpi::StringRef key, wpi::StringRef defaultValue = ""); + std::string GetString(std::string_view key, + std::string_view defaultValue = ""); /** * Returns the int at the given key. If this table does not have a value for @@ -63,7 +65,7 @@ class Preferences { * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ - int GetInt(wpi::StringRef key, int defaultValue = 0); + int GetInt(std::string_view key, int defaultValue = 0); /** * Returns the double at the given key. If this table does not have a value @@ -73,7 +75,7 @@ class Preferences { * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ - double GetDouble(wpi::StringRef key, double defaultValue = 0.0); + double GetDouble(std::string_view key, double defaultValue = 0.0); /** * Returns the float at the given key. If this table does not have a value @@ -83,7 +85,7 @@ class Preferences { * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ - float GetFloat(wpi::StringRef key, float defaultValue = 0.0); + float GetFloat(std::string_view key, float defaultValue = 0.0); /** * Returns the boolean at the given key. If this table does not have a value @@ -93,7 +95,7 @@ class Preferences { * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ - bool GetBoolean(wpi::StringRef key, bool defaultValue = false); + bool GetBoolean(std::string_view key, bool defaultValue = false); /** * Returns the long (int64_t) at the given key. If this table does not have a @@ -104,7 +106,7 @@ class Preferences { * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ - int64_t GetLong(wpi::StringRef key, int64_t defaultValue = 0); + int64_t GetLong(std::string_view key, int64_t defaultValue = 0); /** * Puts the given string into the preferences table. @@ -115,7 +117,7 @@ class Preferences { * @param key the key * @param value the value */ - void SetString(wpi::StringRef key, wpi::StringRef value); + void SetString(std::string_view key, std::string_view value); /** * Puts the given string into the preferences table. @@ -127,13 +129,13 @@ class Preferences { * @param value the value */ WPI_DEPRECATED("Use SetString instead.") - void PutString(wpi::StringRef key, wpi::StringRef value); + void PutString(std::string_view key, std::string_view value); /** * Puts the given string into the preferences table if it doesn't * already exist. */ - void InitString(wpi::StringRef key, wpi::StringRef value); + void InitString(std::string_view key, std::string_view value); /** * Puts the given int into the preferences table. @@ -143,7 +145,7 @@ class Preferences { * @param key the key * @param value the value */ - void SetInt(wpi::StringRef key, int value); + void SetInt(std::string_view key, int value); /** * Puts the given int into the preferences table. @@ -154,13 +156,13 @@ class Preferences { * @param value the value */ WPI_DEPRECATED("Use SetInt instead.") - void PutInt(wpi::StringRef key, int value); + void PutInt(std::string_view key, int value); /** * Puts the given int into the preferences table if it doesn't * already exist. */ - void InitInt(wpi::StringRef key, int value); + void InitInt(std::string_view key, int value); /** * Puts the given double into the preferences table. @@ -170,7 +172,7 @@ class Preferences { * @param key the key * @param value the value */ - void SetDouble(wpi::StringRef key, double value); + void SetDouble(std::string_view key, double value); /** * Puts the given double into the preferences table. @@ -181,13 +183,13 @@ class Preferences { * @param value the value */ WPI_DEPRECATED("Use SetDouble instead.") - void PutDouble(wpi::StringRef key, double value); + void PutDouble(std::string_view key, double value); /** * Puts the given double into the preferences table if it doesn't * already exist. */ - void InitDouble(wpi::StringRef key, double value); + void InitDouble(std::string_view key, double value); /** * Puts the given float into the preferences table. @@ -197,7 +199,7 @@ class Preferences { * @param key the key * @param value the value */ - void SetFloat(wpi::StringRef key, float value); + void SetFloat(std::string_view key, float value); /** * Puts the given float into the preferences table. @@ -208,13 +210,13 @@ class Preferences { * @param value the value */ WPI_DEPRECATED("Use SetFloat instead.") - void PutFloat(wpi::StringRef key, float value); + void PutFloat(std::string_view key, float value); /** * Puts the given float into the preferences table if it doesn't * already exist. */ - void InitFloat(wpi::StringRef key, float value); + void InitFloat(std::string_view key, float value); /** * Puts the given boolean into the preferences table. @@ -224,7 +226,7 @@ class Preferences { * @param key the key * @param value the value */ - void SetBoolean(wpi::StringRef key, bool value); + void SetBoolean(std::string_view key, bool value); /** * Puts the given boolean into the preferences table. @@ -235,13 +237,13 @@ class Preferences { * @param value the value */ WPI_DEPRECATED("Use SetBoolean instead.") - void PutBoolean(wpi::StringRef key, bool value); + void PutBoolean(std::string_view key, bool value); /** * Puts the given boolean into the preferences table if it doesn't * already exist. */ - void InitBoolean(wpi::StringRef key, bool value); + void InitBoolean(std::string_view key, bool value); /** * Puts the given long (int64_t) into the preferences table. @@ -251,7 +253,7 @@ class Preferences { * @param key the key * @param value the value */ - void SetLong(wpi::StringRef key, int64_t value); + void SetLong(std::string_view key, int64_t value); /** * Puts the given long (int64_t) into the preferences table. @@ -262,13 +264,13 @@ class Preferences { * @param value the value */ WPI_DEPRECATED("Use SetLong instead.") - void PutLong(wpi::StringRef key, int64_t value); + void PutLong(std::string_view key, int64_t value); /** * Puts the given long into the preferences table if it doesn't * already exist. */ - void InitLong(wpi::StringRef key, int64_t value); + void InitLong(std::string_view key, int64_t value); /** * Returns whether or not there is a key with the given name. @@ -276,14 +278,14 @@ class Preferences { * @param key the key * @return if there is a value at the given key */ - bool ContainsKey(wpi::StringRef key); + bool ContainsKey(std::string_view key); /** * Remove a preference. * * @param key the key */ - void Remove(wpi::StringRef key); + void Remove(std::string_view key); /** * Remove all preferences. diff --git a/wpilibc/src/main/native/include/frc/RobotBase.h b/wpilibc/src/main/native/include/frc/RobotBase.h index e0c1592fef..6e5d3b5137 100644 --- a/wpilibc/src/main/native/include/frc/RobotBase.h +++ b/wpilibc/src/main/native/include/frc/RobotBase.h @@ -11,7 +11,6 @@ #include #include #include -#include #include "frc/Errors.h" diff --git a/wpilibc/src/main/native/include/frc/SerialPort.h b/wpilibc/src/main/native/include/frc/SerialPort.h index f26d53cc3b..7fff14acaf 100644 --- a/wpilibc/src/main/native/include/frc/SerialPort.h +++ b/wpilibc/src/main/native/include/frc/SerialPort.h @@ -144,7 +144,7 @@ class SerialPort { * Use Write({data, len}) to get a buffer that is shorter than the length of * the string. * - * @param buffer StringRef to the buffer to read the bytes from. + * @param buffer the buffer to read the bytes from. * @return The number of bytes actually written into the port. */ int Write(std::string_view buffer); diff --git a/wpilibc/src/main/native/include/frc/Tracer.h b/wpilibc/src/main/native/include/frc/Tracer.h index 7c36f58fdd..2acb017cb3 100644 --- a/wpilibc/src/main/native/include/frc/Tracer.h +++ b/wpilibc/src/main/native/include/frc/Tracer.h @@ -5,10 +5,10 @@ #pragma once #include +#include #include #include -#include namespace wpi { class raw_ostream; @@ -48,7 +48,7 @@ class Tracer { * * @param epochName The name to associate with the epoch. */ - void AddEpoch(wpi::StringRef epochName); + void AddEpoch(std::string_view epochName); /** * Prints list of epochs added so far and their times to the DriverStation. diff --git a/wpilibc/src/main/native/include/frc/Watchdog.h b/wpilibc/src/main/native/include/frc/Watchdog.h index 9bb15630aa..d85674d8c6 100644 --- a/wpilibc/src/main/native/include/frc/Watchdog.h +++ b/wpilibc/src/main/native/include/frc/Watchdog.h @@ -5,10 +5,10 @@ #pragma once #include +#include #include #include -#include #include "frc/Tracer.h" @@ -76,7 +76,7 @@ class Watchdog { * * @param epochName The name to associate with the epoch. */ - void AddEpoch(wpi::StringRef epochName); + void AddEpoch(std::string_view epochName); /** * Prints list of epochs added so far and their times. diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/LayoutType.h b/wpilibc/src/main/native/include/frc/shuffleboard/LayoutType.h index 413af06034..5fa5ca4ad0 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/LayoutType.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/LayoutType.h @@ -4,7 +4,7 @@ #pragma once -#include +#include namespace frc { @@ -25,7 +25,7 @@ class LayoutType { * Gets the string type of the layout as defined by that layout in * Shuffleboard. */ - wpi::StringRef GetLayoutName() const; + std::string_view GetLayoutName() const; private: const char* m_layoutName; diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/RecordingController.h b/wpilibc/src/main/native/include/frc/shuffleboard/RecordingController.h index 716597c7bb..83b23a424b 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/RecordingController.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/RecordingController.h @@ -6,11 +6,11 @@ #include #include +#include #include #include #include -#include #include "frc/shuffleboard/ShuffleboardEventImportance.h" @@ -23,10 +23,10 @@ class RecordingController final { void StartRecording(); void StopRecording(); - void SetRecordingFileNameFormat(wpi::StringRef format); + void SetRecordingFileNameFormat(std::string_view format); void ClearRecordingFileNameFormat(); - void AddEventMarker(wpi::StringRef name, wpi::StringRef description, + void AddEventMarker(std::string_view name, std::string_view description, ShuffleboardEventImportance importance); private: diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/Shuffleboard.h b/wpilibc/src/main/native/include/frc/shuffleboard/Shuffleboard.h index 6952295a0d..9b691fd7ea 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/Shuffleboard.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/Shuffleboard.h @@ -4,7 +4,7 @@ #pragma once -#include +#include #include "frc/shuffleboard/RecordingController.h" #include "frc/shuffleboard/ShuffleboardEventImportance.h" @@ -77,7 +77,7 @@ class Shuffleboard final { * @param title the title of the tab * @return the tab with the given title */ - static ShuffleboardTab& GetTab(wpi::StringRef title); + static ShuffleboardTab& GetTab(std::string_view title); /** * Selects the tab in the dashboard with the given index in the range @@ -93,7 +93,7 @@ class Shuffleboard final { * * @param title the title of the tab to select */ - static void SelectTab(wpi::StringRef title); + static void SelectTab(std::string_view title); /** * Enables user control of widgets containing actuators: speed controllers, @@ -141,7 +141,7 @@ class Shuffleboard final { * * @param format the format for the */ - static void SetRecordingFileNameFormat(wpi::StringRef format); + static void SetRecordingFileNameFormat(std::string_view format); /** * Clears the custom name format for recording files. New recordings will use @@ -163,7 +163,8 @@ class Shuffleboard final { * @param description a description of the event * @param importance the importance of the event */ - static void AddEventMarker(wpi::StringRef name, wpi::StringRef description, + static void AddEventMarker(std::string_view name, + std::string_view description, ShuffleboardEventImportance importance); /** @@ -177,7 +178,7 @@ class Shuffleboard final { * @param name the name of the event * @param importance the importance of the event */ - static void AddEventMarker(wpi::StringRef name, + static void AddEventMarker(std::string_view name, ShuffleboardEventImportance importance); private: diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h index f989fb3915..1fa9c91f3d 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardEventImportance.h @@ -4,7 +4,7 @@ #pragma once -#include +#include namespace frc { @@ -14,7 +14,7 @@ namespace frc { enum ShuffleboardEventImportance { kTrivial, kLow, kNormal, kHigh, kCritical }; -inline wpi::StringRef ShuffleboardEventImportanceName( +inline std::string_view ShuffleboardEventImportanceName( ShuffleboardEventImportance importance) { switch (importance) { case kTrivial: diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardInstance.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardInstance.h index 20ddc6bfb3..2885af7b8a 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardInstance.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardInstance.h @@ -5,6 +5,7 @@ #pragma once #include +#include #include "frc/shuffleboard/ShuffleboardRoot.h" #include "frc/shuffleboard/ShuffleboardTab.h" @@ -19,7 +20,7 @@ class ShuffleboardInstance final : public ShuffleboardRoot { ShuffleboardInstance(ShuffleboardInstance&&) = default; ShuffleboardInstance& operator=(ShuffleboardInstance&&) = default; - frc::ShuffleboardTab& GetTab(wpi::StringRef title) override; + frc::ShuffleboardTab& GetTab(std::string_view title) override; void Update() override; @@ -29,7 +30,7 @@ class ShuffleboardInstance final : public ShuffleboardRoot { void SelectTab(int index) override; - void SelectTab(wpi::StringRef) override; + void SelectTab(std::string_view) override; private: struct Impl; diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardRoot.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardRoot.h index f8d98f753f..1e766a84e4 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardRoot.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardRoot.h @@ -4,7 +4,7 @@ #pragma once -#include +#include namespace frc { @@ -25,7 +25,7 @@ class ShuffleboardRoot { * @param title the title of the tab * @return the tab with the given title */ - virtual ShuffleboardTab& GetTab(wpi::StringRef title) = 0; + virtual ShuffleboardTab& GetTab(std::string_view title) = 0; /** * Updates all tabs. @@ -57,7 +57,7 @@ class ShuffleboardRoot { * * @param title the title of the tab to select */ - virtual void SelectTab(wpi::StringRef title) = 0; + virtual void SelectTab(std::string_view title) = 0; }; } // namespace frc diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardTab.h b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardTab.h index a23890bdd7..1dd1aac311 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardTab.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/ShuffleboardTab.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include #include "frc/shuffleboard/ShuffleboardContainer.h" @@ -24,7 +24,7 @@ class ShuffleboardRoot; */ class ShuffleboardTab final : public ShuffleboardContainer { public: - ShuffleboardTab(ShuffleboardRoot& root, wpi::StringRef title); + ShuffleboardTab(ShuffleboardRoot& root, std::string_view title); ShuffleboardRoot& GetRoot(); diff --git a/wpilibc/src/main/native/include/frc/shuffleboard/WidgetType.h b/wpilibc/src/main/native/include/frc/shuffleboard/WidgetType.h index 6dd30b5f02..13805bb85e 100644 --- a/wpilibc/src/main/native/include/frc/shuffleboard/WidgetType.h +++ b/wpilibc/src/main/native/include/frc/shuffleboard/WidgetType.h @@ -4,7 +4,7 @@ #pragma once -#include +#include namespace frc { @@ -25,7 +25,7 @@ class WidgetType { * Gets the string type of the widget as defined by that widget in * Shuffleboard. */ - wpi::StringRef GetWidgetName() const; + std::string_view GetWidgetName() const; private: const char* m_widgetName; diff --git a/wpilibc/src/main/native/include/frc/simulation/CallbackStore.h b/wpilibc/src/main/native/include/frc/simulation/CallbackStore.h index 0a13a4ff10..61cc6b291b 100644 --- a/wpilibc/src/main/native/include/frc/simulation/CallbackStore.h +++ b/wpilibc/src/main/native/include/frc/simulation/CallbackStore.h @@ -5,15 +5,15 @@ #pragma once #include +#include #include -#include namespace frc::sim { -using NotifyCallback = std::function; +using NotifyCallback = std::function; using ConstBufferCallback = std::function; + std::string_view, const unsigned char* buffer, unsigned int count)>; using CancelCallbackFunc = void (*)(int32_t index, int32_t uid); using CancelCallbackNoIndexFunc = void (*)(int32_t uid); using CancelCallbackChannelFunc = void (*)(int32_t index, int32_t channel, diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h index 9311b54641..7ddc976c36 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h @@ -59,7 +59,7 @@ class Mechanism2d : public Sendable, public SendableHelper { * @param y the root y coordinate * @return a new root object, or the existing one with the given name. */ - MechanismRoot2d* GetRoot(wpi::StringRef name, double x, double y); + MechanismRoot2d* GetRoot(std::string_view name, double x, double y); /** * Set the Mechanism2d background color. diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/MechanismObject2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/MechanismObject2d.h index 3821f617c2..c4185e7f88 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/MechanismObject2d.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/MechanismObject2d.h @@ -14,6 +14,8 @@ #include #include +#include "frc/Errors.h" + namespace frc { /** @@ -63,13 +65,14 @@ class MechanismObject2d { template >> - T* Append(wpi::StringRef name, Args&&... args) { + T* Append(std::string_view name, Args&&... args) { std::scoped_lock lock(m_mutex); auto& obj = m_objects[name]; if (obj) { - throw std::runtime_error(("MechanismObject names must be unique! `" + - name + "` was inserted twice!") - .str()); + throw FRC_MakeError( + err::Error, + "MechanismObject names must be unique! `{}` was inserted twice!", + name); } obj = std::make_unique(name, std::forward(args)...); T* ex = static_cast(obj.get()); diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilder.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilder.h index 432854f1b4..3ec3831cef 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilder.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilder.h @@ -96,7 +96,7 @@ class SendableBuilder { */ virtual void AddStringProperty( std::string_view key, std::function getter, - std::function setter) = 0; + std::function setter) = 0; /** * Add a boolean array property. @@ -140,7 +140,7 @@ class SendableBuilder { */ virtual void AddRawProperty(std::string_view key, std::function getter, - std::function setter) = 0; + std::function setter) = 0; /** * Add a NetworkTableValue property. @@ -162,8 +162,8 @@ class SendableBuilder { */ virtual void AddSmallStringProperty( std::string_view key, - std::function& buf)> getter, - std::function setter) = 0; + std::function& buf)> getter, + std::function setter) = 0; /** * Add a boolean array property (SmallVector form). @@ -213,8 +213,8 @@ class SendableBuilder { */ virtual void AddSmallRawProperty( std::string_view key, - std::function& buf)> getter, - std::function setter) = 0; + std::function& buf)> getter, + std::function setter) = 0; /** * Get the network table. diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h index 34eeb668ab..34b9d59673 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableBuilderImpl.h @@ -100,7 +100,7 @@ class SendableBuilderImpl : public SendableBuilder { void AddStringProperty(std::string_view key, std::function getter, - std::function setter) override; + std::function setter) override; void AddBooleanArrayProperty( std::string_view key, std::function()> getter, @@ -115,7 +115,7 @@ class SendableBuilderImpl : public SendableBuilder { std::function)> setter) override; void AddRawProperty(std::string_view key, std::function getter, - std::function setter) override; + std::function setter) override; void AddValueProperty( std::string_view key, std::function()> getter, @@ -123,8 +123,8 @@ class SendableBuilderImpl : public SendableBuilder { void AddSmallStringProperty( std::string_view key, - std::function& buf)> getter, - std::function setter) override; + std::function& buf)> getter, + std::function setter) override; void AddSmallBooleanArrayProperty( std::string_view key, @@ -146,8 +146,8 @@ class SendableBuilderImpl : public SendableBuilder { void AddSmallRawProperty( std::string_view key, - std::function& buf)> getter, - std::function setter) override; + std::function& buf)> getter, + std::function setter) override; private: struct Property { diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h index 4f55576c91..26a1671ab6 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.h @@ -5,9 +5,9 @@ #pragma once #include +#include #include -#include #include #include "frc/smartdashboard/SendableBuilder.h" @@ -56,7 +56,7 @@ class SendableChooser : public SendableChooserBase { * @param name the name of the option * @param object the option */ - void AddOption(wpi::StringRef name, T object); + void AddOption(std::string_view name, T object); /** * Add the given object to the list of options and marks it as the default. @@ -67,7 +67,7 @@ class SendableChooser : public SendableChooserBase { * @param name the name of the option * @param object the option */ - void SetDefaultOption(wpi::StringRef name, T object); + void SetDefaultOption(std::string_view name, T object); /** * Adds the given object to the list of options. @@ -75,13 +75,13 @@ class SendableChooser : public SendableChooserBase { * On the SmartDashboard on the desktop, the object will appear as the given * name. * - * @deprecated use AddOption(wpi::StringRef name, T object) instead. + * @deprecated use AddOption(std::string_view name, T object) instead. * * @param name the name of the option * @param object the option */ WPI_DEPRECATED("use AddOption() instead") - void AddObject(wpi::StringRef name, T object) { AddOption(name, object); } + void AddObject(std::string_view name, T object) { AddOption(name, object); } /** * Add the given object to the list of options and marks it as the default. @@ -89,13 +89,13 @@ class SendableChooser : public SendableChooserBase { * Functionally, this is very close to AddOption() except that it will use * this as the default option if none other is explicitly selected. * - * @deprecated use SetDefaultOption(wpi::StringRef name, T object) instead. + * @deprecated use SetDefaultOption(std::string_view name, T object) instead. * * @param name the name of the option * @param object the option */ WPI_DEPRECATED("use SetDefaultOption() instead") - void AddDefault(wpi::StringRef name, T object) { + void AddDefault(std::string_view name, T object) { SetDefaultOption(name, object); } diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc index 2e160bcf32..d556ea3aad 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableChooser.inc @@ -7,22 +7,21 @@ #include #include #include +#include #include #include -#include - #include "frc/smartdashboard/SendableChooser.h" namespace frc { template -void SendableChooser::AddOption(wpi::StringRef name, T object) { +void SendableChooser::AddOption(std::string_view name, T object) { m_choices[name] = std::move(object); } template -void SendableChooser::SetDefaultOption(wpi::StringRef name, T object) { +void SendableChooser::SetDefaultOption(std::string_view name, T object) { m_defaultChoice = name; AddOption(name, std::move(object)); } @@ -53,7 +52,7 @@ void SendableChooser::InitSendable(SendableBuilder& builder) { [=]() { std::vector keys; for (const auto& choice : m_choices) { - keys.push_back(choice.first()); + keys.emplace_back(choice.first()); } // Unlike std::map, wpi::StringMap elements @@ -65,17 +64,17 @@ void SendableChooser::InitSendable(SendableBuilder& builder) { nullptr); builder.AddSmallStringProperty( kDefault, - [=](wpi::SmallVectorImpl&) -> wpi::StringRef { + [=](wpi::SmallVectorImpl&) -> std::string_view { return m_defaultChoice; }, nullptr); builder.AddSmallStringProperty( kActive, - [=](wpi::SmallVectorImpl& buf) -> wpi::StringRef { + [=](wpi::SmallVectorImpl& buf) -> std::string_view { std::scoped_lock lock(m_mutex); if (m_haveSelected) { buf.assign(m_selected.begin(), m_selected.end()); - return wpi::StringRef(buf.data(), buf.size()); + return {buf.data(), buf.size()}; } else { return m_defaultChoice; } @@ -85,7 +84,7 @@ void SendableChooser::InitSendable(SendableBuilder& builder) { std::scoped_lock lock(m_mutex); m_activeEntries.emplace_back(builder.GetEntry(kActive)); } - builder.AddStringProperty(kSelected, nullptr, [=](wpi::StringRef val) { + builder.AddStringProperty(kSelected, nullptr, [=](std::string_view val) { std::scoped_lock lock(m_mutex); m_haveSelected = true; m_selected = val; diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SendableRegistry.h b/wpilibc/src/main/native/include/frc/smartdashboard/SendableRegistry.h index b1c9b35f32..e93d77a613 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SendableRegistry.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SendableRegistry.h @@ -298,8 +298,8 @@ class SendableRegistry { * Data passed to ForeachLiveWindow() callback function */ struct CallbackData { - CallbackData(Sendable* sendable_, wpi::StringRef name_, - wpi::StringRef subsystem_, Sendable* parent_, + CallbackData(Sendable* sendable_, std::string_view name_, + std::string_view subsystem_, Sendable* parent_, std::shared_ptr& data_, SendableBuilderImpl& builder_) : sendable(sendable_), name(name_), @@ -309,8 +309,8 @@ class SendableRegistry { builder(builder_) {} Sendable* sendable; - wpi::StringRef name; - wpi::StringRef subsystem; + std::string_view name; + std::string_view subsystem; Sendable* parent; std::shared_ptr& data; SendableBuilderImpl& builder; diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/SmartDashboard.h b/wpilibc/src/main/native/include/frc/smartdashboard/SmartDashboard.h index 6a6ee299cf..1ce7762392 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/SmartDashboard.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/SmartDashboard.h @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -27,7 +28,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param key the key to search for * @return true if the table as a value assigned to the given key */ - static bool ContainsKey(wpi::StringRef key); + static bool ContainsKey(std::string_view key); /** * @param types bitmask of types; 0 is treated as a "don't care". @@ -40,7 +41,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * * @param key the key to make persistent */ - static void SetPersistent(wpi::StringRef key); + static void SetPersistent(std::string_view key); /** * Stop making a key's value persistent through program restarts. @@ -48,7 +49,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * * @param key the key name */ - static void ClearPersistent(wpi::StringRef key); + static void ClearPersistent(std::string_view key); /** * Returns whether the value is persistent through program restarts. @@ -56,7 +57,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * * @param key the key name */ - static bool IsPersistent(wpi::StringRef key); + static bool IsPersistent(std::string_view key); /** * Sets flags on the specified key in this table. The key can @@ -65,7 +66,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param key the key name * @param flags the flags to set (bitmask) */ - static void SetFlags(wpi::StringRef key, unsigned int flags); + static void SetFlags(std::string_view key, unsigned int flags); /** * Clears flags on the specified key in this table. The key can @@ -74,7 +75,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param key the key name * @param flags the flags to clear (bitmask) */ - static void ClearFlags(wpi::StringRef key, unsigned int flags); + static void ClearFlags(std::string_view key, unsigned int flags); /** * Returns the flags for the specified key. @@ -82,14 +83,14 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param key the key name * @return the flags, or 0 if the key is not defined */ - static unsigned int GetFlags(wpi::StringRef key); + static unsigned int GetFlags(std::string_view key); /** * Deletes the specified key in this table. * * @param key the key name */ - static void Delete(wpi::StringRef key); + static void Delete(std::string_view key); /** * Returns an NT Entry mapping to the specified key @@ -99,7 +100,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param key the key * @return the entry for the key */ - static nt::NetworkTableEntry GetEntry(wpi::StringRef key); + static nt::NetworkTableEntry GetEntry(std::string_view key); /** * Maps the specified key to the specified value in this table. @@ -113,7 +114,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param keyName the key * @param value the value */ - static void PutData(wpi::StringRef key, Sendable* data); + static void PutData(std::string_view key, Sendable* data); /** * Maps the specified key (where the key is the name of the Sendable) @@ -135,7 +136,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param keyName the key * @return the value */ - static Sendable* GetData(wpi::StringRef keyName); + static Sendable* GetData(std::string_view keyName); /** * Maps the specified key to the specified value in this table. @@ -147,7 +148,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param value the value * @return False if the table key already exists with a different type */ - static bool PutBoolean(wpi::StringRef keyName, bool value); + static bool PutBoolean(std::string_view keyName, bool value); /** * Gets the current value in the table, setting it if it does not exist. @@ -155,7 +156,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param defaultValue the default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - static bool SetDefaultBoolean(wpi::StringRef key, bool defaultValue); + static bool SetDefaultBoolean(std::string_view key, bool defaultValue); /** * Returns the value at the specified key. @@ -165,7 +166,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param keyName the key * @return the value */ - static bool GetBoolean(wpi::StringRef keyName, bool defaultValue); + static bool GetBoolean(std::string_view keyName, bool defaultValue); /** * Maps the specified key to the specified value in this table. @@ -177,7 +178,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param value the value * @return False if the table key already exists with a different type */ - static bool PutNumber(wpi::StringRef keyName, double value); + static bool PutNumber(std::string_view keyName, double value); /** * Gets the current value in the table, setting it if it does not exist. @@ -186,7 +187,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param defaultValue The default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - static bool SetDefaultNumber(wpi::StringRef key, double defaultValue); + static bool SetDefaultNumber(std::string_view key, double defaultValue); /** * Returns the value at the specified key. @@ -196,7 +197,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param keyName the key * @return the value */ - static double GetNumber(wpi::StringRef keyName, double defaultValue); + static double GetNumber(std::string_view keyName, double defaultValue); /** * Maps the specified key to the specified value in this table. @@ -208,7 +209,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param value the value * @return False if the table key already exists with a different type */ - static bool PutString(wpi::StringRef keyName, wpi::StringRef value); + static bool PutString(std::string_view keyName, std::string_view value); /** * Gets the current value in the table, setting it if it does not exist. @@ -217,7 +218,8 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param defaultValue the default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - static bool SetDefaultString(wpi::StringRef key, wpi::StringRef defaultValue); + static bool SetDefaultString(std::string_view key, + std::string_view defaultValue); /** * Returns the value at the specified key. @@ -227,8 +229,8 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param keyName the key * @return the value */ - static std::string GetString(wpi::StringRef keyName, - wpi::StringRef defaultValue); + static std::string GetString(std::string_view keyName, + std::string_view defaultValue); /** * Put a boolean array in the table. @@ -241,7 +243,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * std::vector is special-cased in C++. 0 is false, any * non-zero value is true. */ - static bool PutBooleanArray(wpi::StringRef key, wpi::ArrayRef value); + static bool PutBooleanArray(std::string_view key, wpi::ArrayRef value); /** * Gets the current value in the table, setting it if it does not exist. @@ -250,7 +252,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param defaultValue the default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - static bool SetDefaultBooleanArray(wpi::StringRef key, + static bool SetDefaultBooleanArray(std::string_view key, wpi::ArrayRef defaultValue); /** @@ -271,7 +273,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * because std::vector is special-cased in C++. 0 is false, any * non-zero value is true. */ - static std::vector GetBooleanArray(wpi::StringRef key, + static std::vector GetBooleanArray(std::string_view key, wpi::ArrayRef defaultValue); /** @@ -281,7 +283,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param value The value that will be assigned. * @return False if the table key already exists with a different type */ - static bool PutNumberArray(wpi::StringRef key, wpi::ArrayRef value); + static bool PutNumberArray(std::string_view key, wpi::ArrayRef value); /** * Gets the current value in the table, setting it if it does not exist. @@ -290,7 +292,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param defaultValue The default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - static bool SetDefaultNumberArray(wpi::StringRef key, + static bool SetDefaultNumberArray(std::string_view key, wpi::ArrayRef defaultValue); /** @@ -307,7 +309,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @note This makes a copy of the array. If the overhead of this is a concern, * use GetValue() instead. */ - static std::vector GetNumberArray(wpi::StringRef key, + static std::vector GetNumberArray(std::string_view key, wpi::ArrayRef defaultValue); /** @@ -317,7 +319,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param value The value that will be assigned. * @return False if the table key already exists with a different type */ - static bool PutStringArray(wpi::StringRef key, + static bool PutStringArray(std::string_view key, wpi::ArrayRef value); /** @@ -327,7 +329,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param defaultValue The default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - static bool SetDefaultStringArray(wpi::StringRef key, + static bool SetDefaultStringArray(std::string_view key, wpi::ArrayRef defaultValue); /** @@ -345,7 +347,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * use GetValue() instead. */ static std::vector GetStringArray( - wpi::StringRef key, wpi::ArrayRef defaultValue); + std::string_view key, wpi::ArrayRef defaultValue); /** * Put a raw value (byte array) in the table. @@ -354,7 +356,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param value The value that will be assigned. * @return False if the table key already exists with a different type */ - static bool PutRaw(wpi::StringRef key, wpi::StringRef value); + static bool PutRaw(std::string_view key, std::string_view value); /** * Gets the current value in the table, setting it if it does not exist. @@ -363,7 +365,8 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param defaultValue The default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - static bool SetDefaultRaw(wpi::StringRef key, wpi::StringRef defaultValue); + static bool SetDefaultRaw(std::string_view key, + std::string_view defaultValue); /** * Returns the raw value (byte array) the key maps to. @@ -379,7 +382,8 @@ class SmartDashboard : public Sendable, public SendableHelper { * @note This makes a copy of the raw contents. If the overhead of this is a * concern, use GetValue() instead. */ - static std::string GetRaw(wpi::StringRef key, wpi::StringRef defaultValue); + static std::string GetRaw(std::string_view key, + std::string_view defaultValue); /** * Maps the specified key to the specified complex value (such as an array) in @@ -392,7 +396,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param value the value * @return False if the table key already exists with a different type */ - static bool PutValue(wpi::StringRef keyName, + static bool PutValue(std::string_view keyName, std::shared_ptr value); /** @@ -402,7 +406,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param defaultValue The default value to set if key doesn't exist. * @returns False if the table key exists with a different type */ - static bool SetDefaultValue(wpi::StringRef key, + static bool SetDefaultValue(std::string_view key, std::shared_ptr defaultValue); /** @@ -412,7 +416,7 @@ class SmartDashboard : public Sendable, public SendableHelper { * @param keyName the key * @param value the object to retrieve the value into */ - static std::shared_ptr GetValue(wpi::StringRef keyName); + static std::shared_ptr GetValue(std::string_view keyName); /** * Posts a task from a listener to the ListenerExecutor, so that it can be run diff --git a/wpilibc/src/test/native/cpp/ScopedTracerTest.cpp b/wpilibc/src/test/native/cpp/ScopedTracerTest.cpp index 8ffb51e587..c4ef317404 100644 --- a/wpilibc/src/test/native/cpp/ScopedTracerTest.cpp +++ b/wpilibc/src/test/native/cpp/ScopedTracerTest.cpp @@ -2,18 +2,20 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include + #include -#include +#include #include #include "frc/ScopedTracer.h" #include "frc/simulation/SimHooks.h" #include "gtest/gtest.h" -wpi::SmallString<128> buf; -wpi::raw_svector_ostream os(buf); - TEST(ScopedTracerTest, Timing) { + wpi::SmallString<128> buf; + wpi::raw_svector_ostream os(buf); + frc::sim::PauseTiming(); { frc::ScopedTracer tracer("timing_test", os); @@ -21,6 +23,6 @@ TEST(ScopedTracerTest, Timing) { } frc::sim::ResumeTiming(); - wpi::StringRef out = os.str(); - EXPECT_TRUE(out.startswith(" timing_test: 1.5")); + std::string_view out = os.str(); + EXPECT_TRUE(wpi::starts_with(out, " timing_test: 1.5")); } diff --git a/wpilibc/src/test/native/cpp/shuffleboard/MockActuatorSendable.cpp b/wpilibc/src/test/native/cpp/shuffleboard/MockActuatorSendable.cpp index 51b2193d1c..6d7897eb5e 100644 --- a/wpilibc/src/test/native/cpp/shuffleboard/MockActuatorSendable.cpp +++ b/wpilibc/src/test/native/cpp/shuffleboard/MockActuatorSendable.cpp @@ -6,10 +6,12 @@ #include "frc/smartdashboard/SendableRegistry.h" +using namespace frc; + MockActuatorSendable::MockActuatorSendable(std::string_view name) { - frc::SendableRegistry::GetInstance().Add(this, name); + SendableRegistry::GetInstance().Add(this, name); } -void MockActuatorSendable::InitSendable(frc::SendableBuilder& builder) { +void MockActuatorSendable::InitSendable(SendableBuilder& builder) { builder.SetActuator(true); } diff --git a/wpilibc/src/test/native/cpp/shuffleboard/SuppliedValueWidgetTest.cpp b/wpilibc/src/test/native/cpp/shuffleboard/SuppliedValueWidgetTest.cpp index 94aa5caf16..c8449e5be7 100644 --- a/wpilibc/src/test/native/cpp/shuffleboard/SuppliedValueWidgetTest.cpp +++ b/wpilibc/src/test/native/cpp/shuffleboard/SuppliedValueWidgetTest.cpp @@ -97,7 +97,7 @@ TEST_F(SuppliedValueWidgetTest, AddBooleanArray) { } TEST_F(SuppliedValueWidgetTest, AddRaw) { - wpi::StringRef bytes = "\1\2\3"; + std::string_view bytes = "\1\2\3"; m_tab->AddRaw("Raw", [&bytes]() { return bytes; }); auto entry = m_ntInst.inst.GetEntry("/Shuffleboard/Tab/Raw"); diff --git a/wpilibc/src/test/native/cpp/simulation/AccelerometerSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/AccelerometerSimTest.cpp index 4534ff3294..1a59604b1e 100644 --- a/wpilibc/src/test/native/cpp/simulation/AccelerometerSimTest.cpp +++ b/wpilibc/src/test/native/cpp/simulation/AccelerometerSimTest.cpp @@ -22,7 +22,7 @@ TEST(AcclerometerSimTests, TestActiveCallback) { bool lastValue = false; auto cb = sim.RegisterActiveCallback( - [&](wpi::StringRef name, const HAL_Value* value) { + [&](std::string_view name, const HAL_Value* value) { wasTriggered = true; lastValue = value->data.v_boolean; }, diff --git a/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp b/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp index 90420c6f7e..d195ee7d56 100644 --- a/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp +++ b/wpilibc/src/test/native/cpp/simulation/SimDeviceSimTest.cpp @@ -2,8 +2,9 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include + #include -#include #include "frc/simulation/SimDeviceSim.h" #include "gtest/gtest.h" @@ -27,7 +28,7 @@ TEST(SimDeviceSimTests, TestEnumerateDevices) { bool foundit = false; SimDeviceSim::EnumerateDevices( "te", [&](const char* name, HAL_SimDeviceHandle handle) { - if (wpi::StringRef(name) == "test") { + if (std::string_view(name) == "test") { foundit = true; } }); diff --git a/wpilibcExamples/src/main/cpp/examples/IntermediateVision/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/IntermediateVision/cpp/Robot.cpp index 923b4253cc..f8a01e84d7 100644 --- a/wpilibcExamples/src/main/cpp/examples/IntermediateVision/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/IntermediateVision/cpp/Robot.cpp @@ -2,6 +2,7 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include #include #include @@ -9,7 +10,6 @@ #include #include #include -#include /** * This is a demo program showing the use of OpenCV to do vision processing. The @@ -18,7 +18,7 @@ * processing. */ class Robot : public frc::TimedRobot { -#if defined(__linux__) +#if defined(__linux__) || defined(_WIN32) private: static void VisionThread() { @@ -60,12 +60,12 @@ class Robot : public frc::TimedRobot { void RobotInit() override { // We need to run our vision program in a separate thread. If not, our robot // program will not run. -#if defined(__linux__) +#if defined(__linux__) || defined(_WIN32) std::thread visionThread(VisionThread); visionThread.detach(); #else - wpi::errs() << "Vision only available on Linux.\n"; - wpi::errs().flush(); + std::fputs("Vision only available on Linux or Windows.\n", stderr); + std::fflush(stderr); #endif } }; diff --git a/wpilibcExamples/src/main/cpp/examples/QuickVision/cpp/Robot.cpp b/wpilibcExamples/src/main/cpp/examples/QuickVision/cpp/Robot.cpp index b754deb277..c1d7c10fea 100644 --- a/wpilibcExamples/src/main/cpp/examples/QuickVision/cpp/Robot.cpp +++ b/wpilibcExamples/src/main/cpp/examples/QuickVision/cpp/Robot.cpp @@ -2,9 +2,10 @@ // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. +#include + #include #include -#include /** * Uses the CameraServer class to automatically capture video from a USB webcam @@ -15,11 +16,11 @@ class Robot : public frc::TimedRobot { public: void RobotInit() override { -#if defined(__linux__) +#if defined(__linux__) || defined(_WIN32) frc::CameraServer::GetInstance()->StartAutomaticCapture(); #else - wpi::errs() << "Vision only available on Linux.\n"; - wpi::errs().flush(); + std::fputs("Vision only available on Linux or Windows.\n", stderr); + std::fflush(stderr); #endif } }; diff --git a/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp b/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp index 73d23dcb9d..2e2771daca 100644 --- a/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp +++ b/wpimath/src/main/native/cpp/trajectory/TrajectoryGenerator.cpp @@ -6,7 +6,7 @@ #include -#include +#include #include "frc/spline/SplineHelper.h" #include "frc/spline/SplineParameterizer.h" @@ -22,7 +22,7 @@ void TrajectoryGenerator::ReportError(const char* error) { if (s_errorFunc) { s_errorFunc(error); } else { - wpi::errs() << "TrajectoryGenerator error: " << error << "\n"; + fmt::print(stderr, "TrajectoryGenerator error: {}\n", error); } } diff --git a/wpimath/src/main/native/cpp/trajectory/TrajectoryUtil.cpp b/wpimath/src/main/native/cpp/trajectory/TrajectoryUtil.cpp index 3a1f3170cd..29e27ec430 100644 --- a/wpimath/src/main/native/cpp/trajectory/TrajectoryUtil.cpp +++ b/wpimath/src/main/native/cpp/trajectory/TrajectoryUtil.cpp @@ -6,6 +6,7 @@ #include +#include #include #include #include @@ -14,13 +15,12 @@ using namespace frc; void TrajectoryUtil::ToPathweaverJson(const Trajectory& trajectory, - const wpi::Twine& path) { + std::string_view path) { std::error_code error_code; - wpi::SmallString<128> buf; - wpi::raw_fd_ostream output{path.toStringRef(buf), error_code}; + wpi::raw_fd_ostream output{path, error_code}; if (error_code) { - throw std::runtime_error(("Cannot open file: " + path).str()); + throw std::runtime_error(fmt::format("Cannot open file: {}", path)); } wpi::json json = trajectory.States(); @@ -28,13 +28,12 @@ void TrajectoryUtil::ToPathweaverJson(const Trajectory& trajectory, output.flush(); } -Trajectory TrajectoryUtil::FromPathweaverJson(const wpi::Twine& path) { +Trajectory TrajectoryUtil::FromPathweaverJson(std::string_view path) { std::error_code error_code; - wpi::SmallString<128> buf; - wpi::raw_fd_istream input{path.toStringRef(buf), error_code}; + wpi::raw_fd_istream input{path, error_code}; if (error_code) { - throw std::runtime_error(("Cannot open file: " + path).str()); + throw std::runtime_error(fmt::format("Cannot open file: {}", path)); } wpi::json json; @@ -48,8 +47,7 @@ std::string TrajectoryUtil::SerializeTrajectory(const Trajectory& trajectory) { return json.dump(); } -Trajectory TrajectoryUtil::DeserializeTrajectory( - const wpi::StringRef json_str) { +Trajectory TrajectoryUtil::DeserializeTrajectory(std::string_view json_str) { wpi::json json = wpi::json::parse(json_str); return Trajectory{json.get>()}; } diff --git a/wpimath/src/main/native/include/frc/spline/SplineParameterizer.h b/wpimath/src/main/native/include/frc/spline/SplineParameterizer.h index efbf989932..b174b53748 100644 --- a/wpimath/src/main/native/include/frc/spline/SplineParameterizer.h +++ b/wpimath/src/main/native/include/frc/spline/SplineParameterizer.h @@ -33,8 +33,6 @@ #include #include -#include - #include "frc/spline/Spline.h" #include "units/angle.h" #include "units/curvature.h" diff --git a/wpimath/src/main/native/include/frc/trajectory/TrajectoryUtil.h b/wpimath/src/main/native/include/frc/trajectory/TrajectoryUtil.h index 69482b8f73..612e8b2b6e 100644 --- a/wpimath/src/main/native/include/frc/trajectory/TrajectoryUtil.h +++ b/wpimath/src/main/native/include/frc/trajectory/TrajectoryUtil.h @@ -5,9 +5,7 @@ #pragma once #include - -#include -#include +#include #include "frc/trajectory/Trajectory.h" @@ -25,7 +23,7 @@ class TrajectoryUtil { * @return The interpolated state. */ static void ToPathweaverJson(const Trajectory& trajectory, - const wpi::Twine& path); + std::string_view path); /** * Imports a Trajectory from a PathWeaver-style JSON file. * @@ -33,7 +31,7 @@ class TrajectoryUtil { * * @return The trajectory represented by the file. */ - static Trajectory FromPathweaverJson(const wpi::Twine& path); + static Trajectory FromPathweaverJson(std::string_view path); /** * Deserializes a Trajectory from PathWeaver-style JSON. @@ -51,6 +49,6 @@ class TrajectoryUtil { * * @return the string containing the serialized JSON */ - static Trajectory DeserializeTrajectory(wpi::StringRef json_str); + static Trajectory DeserializeTrajectory(std::string_view json_str); }; } // namespace frc diff --git a/wpiutil/examples/webserver/webserver.cpp b/wpiutil/examples/webserver/webserver.cpp index 1147c686f3..503405f208 100644 --- a/wpiutil/examples/webserver/webserver.cpp +++ b/wpiutil/examples/webserver/webserver.cpp @@ -4,10 +4,10 @@ #include +#include "fmt/format.h" #include "wpi/EventLoopRunner.h" #include "wpi/HttpServerConnection.h" #include "wpi/UrlParser.h" -#include "wpi/raw_ostream.h" #include "wpi/uv/Loop.h" #include "wpi/uv/Tcp.h" @@ -23,7 +23,7 @@ class MyHttpServerConnection : public wpi::HttpServerConnection { }; void MyHttpServerConnection::ProcessRequest() { - wpi::errs() << "HTTP request: '" << m_request.GetUrl() << "'\n"; + fmt::print(stderr, "HTTP request: '{}'\n", m_request.GetUrl()); wpi::UrlParser url{m_request.GetUrl(), m_request.GetMethod() == wpi::HTTP_CONNECT}; if (!url.IsValid()) { @@ -32,27 +32,25 @@ void MyHttpServerConnection::ProcessRequest() { return; } - wpi::StringRef path; + std::string_view path; if (url.HasPath()) { path = url.GetPath(); } - wpi::errs() << "path: \"" << path << "\"\n"; + fmt::print(stderr, "path: \"{}\"\n", path); - wpi::StringRef query; + std::string_view query; if (url.HasQuery()) { query = url.GetQuery(); } - wpi::errs() << "query: \"" << query << "\"\n"; + fmt::print(stderr, "query: \"{}\"\n", query); const bool isGET = m_request.GetMethod() == wpi::HTTP_GET; - if (isGET && path.equals("/")) { + if (isGET && path == "/") { // build HTML root page - wpi::SmallString<256> buf; - wpi::raw_svector_ostream os{buf}; - os << "WebServer Example"; - os << "

This is an example root page from the webserver."; - os << ""; - SendResponse(200, "OK", "text/html", os.str()); + SendResponse(200, "OK", "text/html", + "WebServer Example" + "

This is an example root page from the webserver." + ""); } else { SendError(404, "Resource not found"); } @@ -73,7 +71,7 @@ int main() { if (!tcp) { return; } - wpi::errs() << "Got a connection\n"; + std::fputs("Got a connection\n", stderr); auto conn = std::make_shared(tcp); tcp->SetData(conn); }); @@ -81,7 +79,7 @@ int main() { // start listening for incoming connections tcp->Listen(); - wpi::errs() << "Listening on port 8080\n"; + std::fputs("Listening on port 8080\n", stderr); }); // wait for a keypress to terminate diff --git a/wpiutil/src/dev/native/cpp/main.cpp b/wpiutil/src/dev/native/cpp/main.cpp index fd3686cd6f..ede6910134 100644 --- a/wpiutil/src/dev/native/cpp/main.cpp +++ b/wpiutil/src/dev/native/cpp/main.cpp @@ -4,11 +4,10 @@ #include -#include "wpi/SmallVector.h" -#include "wpi/StringRef.h" +#include "wpi/SmallString.h" #include "wpi/hostname.h" int main() { - wpi::StringRef v1("Hello"); - std::cout << v1.lower() << std::endl; + wpi::SmallString<128> v1("Hello"); + std::cout << v1.str() << std::endl; } diff --git a/wpiutil/src/main/native/cpp/Base64.cpp b/wpiutil/src/main/native/cpp/Base64.cpp index 4d13b1a613..08c9fce9ce 100644 --- a/wpiutil/src/main/native/cpp/Base64.cpp +++ b/wpiutil/src/main/native/cpp/Base64.cpp @@ -80,17 +80,19 @@ static const unsigned char pr2six[256] = { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64}; -size_t Base64Decode(raw_ostream& os, StringRef encoded) { - const unsigned char* end = encoded.bytes_begin(); - while (pr2six[*end] <= 63 && end != encoded.bytes_end()) { +size_t Base64Decode(raw_ostream& os, std::string_view encoded) { + auto bytes_begin = reinterpret_cast(encoded.data()); + auto bytes_end = bytes_begin + encoded.size(); + const unsigned char* end = bytes_begin; + while (pr2six[*end] <= 63 && end != bytes_end) { ++end; } - size_t nprbytes = end - encoded.bytes_begin(); + size_t nprbytes = end - bytes_begin; if (nprbytes == 0) { return 0; } - const unsigned char* cur = encoded.bytes_begin(); + const unsigned char* cur = bytes_begin; while (nprbytes > 4) { os << static_cast(pr2six[cur[0]] << 2 | pr2six[cur[1]] >> 4); @@ -111,10 +113,10 @@ size_t Base64Decode(raw_ostream& os, StringRef encoded) { os << static_cast(pr2six[cur[2]] << 6 | pr2six[cur[3]]); } - return (end - encoded.bytes_begin()) + ((4 - nprbytes) & 3); + return (end - bytes_begin) + ((4 - nprbytes) & 3); } -size_t Base64Decode(StringRef encoded, std::string* plain) { +size_t Base64Decode(std::string_view encoded, std::string* plain) { plain->resize(0); raw_string_ostream os(*plain); size_t rv = Base64Decode(os, encoded); @@ -122,8 +124,8 @@ size_t Base64Decode(StringRef encoded, std::string* plain) { return rv; } -StringRef Base64Decode(StringRef encoded, size_t* num_read, - SmallVectorImpl& buf) { +std::string_view Base64Decode(std::string_view encoded, size_t* num_read, + SmallVectorImpl& buf) { buf.clear(); raw_svector_ostream os(buf); *num_read = Base64Decode(os, encoded); @@ -133,7 +135,7 @@ StringRef Base64Decode(StringRef encoded, size_t* num_read, static const char basis_64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -void Base64Encode(raw_ostream& os, StringRef plain) { +void Base64Encode(raw_ostream& os, std::string_view plain) { if (plain.empty()) { return; } @@ -162,14 +164,15 @@ void Base64Encode(raw_ostream& os, StringRef plain) { } } -void Base64Encode(StringRef plain, std::string* encoded) { +void Base64Encode(std::string_view plain, std::string* encoded) { encoded->resize(0); raw_string_ostream os(*encoded); Base64Encode(os, plain); os.flush(); } -StringRef Base64Encode(StringRef plain, SmallVectorImpl& buf) { +std::string_view Base64Encode(std::string_view plain, + SmallVectorImpl& buf) { buf.clear(); raw_svector_ostream os(buf); Base64Encode(os, plain); diff --git a/wpiutil/src/main/native/cpp/HttpParser.cpp b/wpiutil/src/main/native/cpp/HttpParser.cpp index 4733befb48..3c18e0f6f8 100644 --- a/wpiutil/src/main/native/cpp/HttpParser.cpp +++ b/wpiutil/src/main/native/cpp/HttpParser.cpp @@ -37,7 +37,7 @@ HttpParser::HttpParser(Type type) { if ((self.m_urlBuf.size() + length) > self.m_maxLength) { return 1; } - self.m_urlBuf += StringRef{at, length}; + self.m_urlBuf += std::string_view{at, length}; self.m_state = kUrl; return 0; }; @@ -50,7 +50,7 @@ HttpParser::HttpParser(Type type) { if ((self.m_valueBuf.size() + length) > self.m_maxLength) { return 1; } - self.m_valueBuf += StringRef{at, length}; + self.m_valueBuf += std::string_view{at, length}; self.m_state = kStatus; return 0; }; @@ -95,7 +95,7 @@ HttpParser::HttpParser(Type type) { if ((self.m_fieldBuf.size() + length) > self.m_maxLength) { return 1; } - self.m_fieldBuf += StringRef{at, length}; + self.m_fieldBuf += std::string_view{at, length}; return 0; }; @@ -114,7 +114,7 @@ HttpParser::HttpParser(Type type) { if ((self.m_valueBuf.size() + length) > self.m_maxLength) { return 1; } - self.m_valueBuf += StringRef{at, length}; + self.m_valueBuf += std::string_view{at, length}; return 0; }; @@ -154,7 +154,7 @@ HttpParser::HttpParser(Type type) { m_settings.on_body = [](http_parser* p, const char* at, size_t length) -> int { auto& self = *static_cast(p->data); - self.body(StringRef{at, length}, self.IsBodyFinal()); + self.body(std::string_view{at, length}, self.IsBodyFinal()); return self.m_aborted; }; diff --git a/wpiutil/src/main/native/cpp/HttpServerConnection.cpp b/wpiutil/src/main/native/cpp/HttpServerConnection.cpp index b7352abbcc..7ef52273e8 100644 --- a/wpiutil/src/main/native/cpp/HttpServerConnection.cpp +++ b/wpiutil/src/main/native/cpp/HttpServerConnection.cpp @@ -4,8 +4,11 @@ #include "wpi/HttpServerConnection.h" +#include "fmt/format.h" #include "wpi/SmallString.h" #include "wpi/SmallVector.h" +#include "wpi/StringExtras.h" +#include "wpi/fmt/raw_ostream.h" #include "wpi/raw_uv_ostream.h" using namespace wpi; @@ -21,16 +24,18 @@ HttpServerConnection::HttpServerConnection(std::shared_ptr stream) // look for Accept-Encoding headers to determine if gzip is acceptable m_request.messageBegin.connect([this] { m_acceptGzip = false; }); - m_request.header.connect([this](StringRef name, StringRef value) { - if (name.equals_lower("accept-encoding") && value.contains("gzip")) { - m_acceptGzip = true; - } - }); + m_request.header.connect( + [this](std::string_view name, std::string_view value) { + if (wpi::equals_lower(name, "accept-encoding") && + wpi::contains(value, "gzip")) { + m_acceptGzip = true; + } + }); // pass incoming data to HTTP parser m_dataConn = stream->data.connect_connection([this](uv::Buffer& buf, size_t size) { - m_request.Execute(StringRef{buf.base, size}); + m_request.Execute({buf.base, size}); if (m_request.HasError()) { // could not parse; just close the connection m_stream.Close(); @@ -54,12 +59,12 @@ void HttpServerConnection::BuildCommonHeaders(raw_ostream& os) { } void HttpServerConnection::BuildHeader(raw_ostream& os, int code, - const Twine& codeText, - const Twine& contentType, + std::string_view codeText, + std::string_view contentType, uint64_t contentLength, - const Twine& extra) { - os << "HTTP/" << m_request.GetMajor() << '.' << m_request.GetMinor() << ' ' - << code << ' ' << codeText << "\r\n"; + std::string_view extra) { + fmt::print(os, "HTTP/{}.{} {} {}\r\n", m_request.GetMajor(), + m_request.GetMinor(), code, codeText); if (contentLength == 0) { m_keepAlive = false; } @@ -69,13 +74,11 @@ void HttpServerConnection::BuildHeader(raw_ostream& os, int code, BuildCommonHeaders(os); os << "Content-Type: " << contentType << "\r\n"; if (contentLength != 0) { - os << "Content-Length: " << contentLength << "\r\n"; + fmt::print(os, "Content-Length: {}\r\n", contentLength); } os << "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: *\r\n"; - SmallString<128> extraBuf; - StringRef extraStr = extra.toStringRef(extraBuf); - if (!extraStr.empty()) { - os << extraStr; + if (!extra.empty()) { + os << extra; } os << "\r\n"; // header ends with a blank line } @@ -93,10 +96,10 @@ void HttpServerConnection::SendData(ArrayRef bufs, }); } -void HttpServerConnection::SendResponse(int code, const Twine& codeText, - const Twine& contentType, - StringRef content, - const Twine& extraHeader) { +void HttpServerConnection::SendResponse(int code, std::string_view codeText, + std::string_view contentType, + std::string_view content, + std::string_view extraHeader) { SmallVector toSend; raw_uv_ostream os{toSend, 4096}; BuildHeader(os, code, codeText, contentType, content.size(), extraHeader); @@ -105,13 +108,12 @@ void HttpServerConnection::SendResponse(int code, const Twine& codeText, SendData(os.bufs(), !m_keepAlive); } -void HttpServerConnection::SendStaticResponse(int code, const Twine& codeText, - const Twine& contentType, - StringRef content, bool gzipped, - const Twine& extraHeader) { +void HttpServerConnection::SendStaticResponse( + int code, std::string_view codeText, std::string_view contentType, + std::string_view content, bool gzipped, std::string_view extraHeader) { // TODO: handle remote side not accepting gzip (very rare) - StringRef contentEncodingHeader; + std::string_view contentEncodingHeader; if (gzipped /* && m_acceptGzip*/) { contentEncodingHeader = "Content-Encoding: gzip\r\n"; } @@ -119,7 +121,7 @@ void HttpServerConnection::SendStaticResponse(int code, const Twine& codeText, SmallVector bufs; raw_uv_ostream os{bufs, 4096}; BuildHeader(os, code, codeText, contentType, content.size(), - extraHeader + contentEncodingHeader); + fmt::format("{}{}", extraHeader, contentEncodingHeader)); // can send content without copying bufs.emplace_back(content); @@ -135,8 +137,8 @@ void HttpServerConnection::SendStaticResponse(int code, const Twine& codeText, }); } -void HttpServerConnection::SendError(int code, const Twine& message) { - StringRef codeText, extra, baseMessage; +void HttpServerConnection::SendError(int code, std::string_view message) { + std::string_view codeText, extra, baseMessage; switch (code) { case 401: codeText = "Unauthorized"; @@ -169,8 +171,8 @@ void HttpServerConnection::SendError(int code, const Twine& message) { baseMessage = "501: Not Implemented!"; break; } - SmallString<256> content = baseMessage; + SmallString<256> content{baseMessage}; content += "\r\n"; - message.toVector(content); - SendResponse(code, codeText, "text/plain", content, extra); + content += message; + SendResponse(code, codeText, "text/plain", content.str(), extra); } diff --git a/wpiutil/src/main/native/cpp/HttpUtil.cpp b/wpiutil/src/main/native/cpp/HttpUtil.cpp index 086fdc87b7..802432e31e 100644 --- a/wpiutil/src/main/native/cpp/HttpUtil.cpp +++ b/wpiutil/src/main/native/cpp/HttpUtil.cpp @@ -6,6 +6,7 @@ #include +#include "fmt/format.h" #include "wpi/Base64.h" #include "wpi/STLExtras.h" #include "wpi/StringExtras.h" @@ -14,12 +15,10 @@ namespace wpi { -StringRef UnescapeURI(const Twine& str, SmallVectorImpl& buf, - bool* error) { - SmallString<128> strBuf; - StringRef strStr = str.toStringRef(strBuf); +std::string_view UnescapeURI(std::string_view str, SmallVectorImpl& buf, + bool* error) { buf.clear(); - for (auto i = strStr.begin(), end = strStr.end(); i != end; ++i) { + for (auto i = str.begin(), end = str.end(); i != end; ++i) { // pass non-escaped characters to output if (*i != '%') { // decode + to space @@ -34,35 +33,33 @@ StringRef UnescapeURI(const Twine& str, SmallVectorImpl& buf, // are there enough characters left? if (i + 2 >= end) { *error = true; - return StringRef{}; + return {}; } // replace %xx with the corresponding character unsigned val1 = hexDigitValue(*++i); if (val1 == -1U) { *error = true; - return StringRef{}; + return {}; } unsigned val2 = hexDigitValue(*++i); if (val2 == -1U) { *error = true; - return StringRef{}; + return {}; } buf.push_back((val1 << 4) | val2); } *error = false; - return StringRef{buf.data(), buf.size()}; + return {buf.data(), buf.size()}; } -StringRef EscapeURI(const Twine& str, SmallVectorImpl& buf, - bool spacePlus) { +std::string_view EscapeURI(std::string_view str, SmallVectorImpl& buf, + bool spacePlus) { static const char* const hexLut = "0123456789ABCDEF"; - SmallString<128> strBuf; - StringRef strStr = str.toStringRef(strBuf); buf.clear(); - for (auto i = strStr.begin(), end = strStr.end(); i != end; ++i) { + for (auto i = str.begin(), end = str.end(); i != end; ++i) { // pass unreserved characters to output if (std::isalnum(*i) || *i == '-' || *i == '_' || *i == '.' || *i == '~') { buf.push_back(*i); @@ -81,15 +78,15 @@ StringRef EscapeURI(const Twine& str, SmallVectorImpl& buf, buf.push_back(hexLut[(*i) & 0x0f]); } - return StringRef{buf.data(), buf.size()}; + return {buf.data(), buf.size()}; } -HttpQueryMap::HttpQueryMap(wpi::StringRef query) { - wpi::SmallVector queryElems; - query.split(queryElems, '&', 100, false); +HttpQueryMap::HttpQueryMap(std::string_view query) { + SmallVector queryElems; + split(query, queryElems, '&', 100, false); for (auto elem : queryElems) { - auto [nameEsc, valueEsc] = elem.split('='); - wpi::SmallString<64> nameBuf; + auto [nameEsc, valueEsc] = split(elem, '='); + SmallString<64> nameBuf; bool err = false; auto name = wpi::UnescapeURI(nameEsc, nameBuf, &err); // note: ignores duplicates @@ -99,8 +96,8 @@ HttpQueryMap::HttpQueryMap(wpi::StringRef query) { } } -std::optional HttpQueryMap::Get( - wpi::StringRef name, wpi::SmallVectorImpl& buf) const { +std::optional HttpQueryMap::Get( + std::string_view name, wpi::SmallVectorImpl& buf) const { auto it = m_elems.find(name); if (it == m_elems.end()) { return {}; @@ -113,16 +110,16 @@ std::optional HttpQueryMap::Get( return val; } -HttpPath::HttpPath(wpi::StringRef path) { +HttpPath::HttpPath(std::string_view path) { // special-case root path to be a single empty element if (path == "/") { m_pathEnds.emplace_back(0); return; } - wpi::SmallVector pathElems; - path.split(pathElems, '/', 100, false); + wpi::SmallVector pathElems; + split(path, pathElems, '/', 100, false); for (auto elem : pathElems) { - wpi::SmallString<64> buf; + SmallString<64> buf; bool err = false; auto val = wpi::UnescapeURI(elem, buf, &err); if (err) { @@ -134,14 +131,15 @@ HttpPath::HttpPath(wpi::StringRef path) { } } -bool HttpPath::startswith(size_t start, ArrayRef match) const { +bool HttpPath::startswith(size_t start, + ArrayRef match) const { if (m_pathEnds.size() < (start + match.size())) { return false; } bool first = start == 0; auto p = m_pathEnds.begin() + start; for (auto m : match) { - auto val = m_pathBuf.slice(first ? 0 : *(p - 1), *p); + auto val = slice(m_pathBuf, first ? 0 : *(p - 1), *p); if (val != m) { return false; } @@ -151,6 +149,10 @@ bool HttpPath::startswith(size_t start, ArrayRef match) const { return true; } +std::string_view HttpPath::operator[](size_t n) const { + return slice(m_pathBuf, n == 0 ? 0 : m_pathEnds[n - 1], m_pathEnds[n]); +} + bool ParseHttpHeaders(raw_istream& is, SmallVectorImpl* contentType, SmallVectorImpl* contentLength) { if (contentType) { @@ -164,7 +166,7 @@ bool ParseHttpHeaders(raw_istream& is, SmallVectorImpl* contentType, bool inContentLength = false; SmallString<64> lineBuf; for (;;) { - StringRef line = is.getline(lineBuf, 1024).rtrim(); + std::string_view line = rtrim(is.getline(lineBuf, 1024)); if (is.has_error()) { return false; } @@ -176,12 +178,12 @@ bool ParseHttpHeaders(raw_istream& is, SmallVectorImpl* contentType, if (!std::isspace(line[0])) { inContentType = false; inContentLength = false; - StringRef field; - std::tie(field, line) = line.split(':'); - field = field.rtrim(); - if (field.equals_lower("content-type")) { + std::string_view field; + std::tie(field, line) = split(line, ':'); + field = rtrim(field); + if (equals_lower(field, "content-type")) { inContentType = true; - } else if (field.equals_lower("content-length")) { + } else if (equals_lower(field, "content-length")) { inContentLength = true; } else { continue; // ignore other fields @@ -189,7 +191,7 @@ bool ParseHttpHeaders(raw_istream& is, SmallVectorImpl* contentType, } // collapse whitespace - line = line.ltrim(); + line = ltrim(line); // save field data if (inContentType && contentType) { @@ -200,7 +202,7 @@ bool ParseHttpHeaders(raw_istream& is, SmallVectorImpl* contentType, } } -bool FindMultipartBoundary(raw_istream& is, StringRef boundary, +bool FindMultipartBoundary(raw_istream& is, std::string_view boundary, std::string* saveBuf) { SmallString<64> searchBuf; searchBuf.resize(boundary.size() + 2); @@ -237,7 +239,7 @@ bool FindMultipartBoundary(raw_istream& is, StringRef boundary, // Fast-scan for '-' size_t pos = searchBuf.find('-', searchBuf[0] == '-' ? 1 : 0); - if (pos == StringRef::npos) { + if (pos == std::string_view::npos) { if (saveBuf) { saveBuf->append(searchBuf.data(), searchBuf.size()); } @@ -254,63 +256,58 @@ bool FindMultipartBoundary(raw_istream& is, StringRef boundary, } } -HttpLocation::HttpLocation(const Twine& url_, bool* error, +HttpLocation::HttpLocation(std::string_view url_, bool* error, std::string* errorMsg) - : url{url_.str()} { + : url{url_} { // Split apart into components - StringRef query{url}; + std::string_view query{url}; // scheme: - StringRef scheme; - std::tie(scheme, query) = query.split(':'); - if (!scheme.equals_lower("http")) { + std::string_view scheme; + std::tie(scheme, query) = split(query, ':'); + if (!equals_lower(scheme, "http")) { *errorMsg = "only supports http URLs"; *error = true; return; } // "//" - if (!query.startswith("//")) { + if (!starts_with(query, "//")) { *errorMsg = "expected http://..."; *error = true; return; } - query = query.drop_front(2); + query.remove_prefix(2); // user:password@host:port/ - StringRef authority; - std::tie(authority, query) = query.split('/'); + std::string_view authority; + std::tie(authority, query) = split(query, '/'); - StringRef userpass, hostport; - std::tie(userpass, hostport) = authority.split('@'); + auto [userpass, hostport] = split(authority, '@'); // split leaves the RHS empty if the split char isn't present... if (hostport.empty()) { hostport = userpass; - userpass = StringRef{}; + userpass = {}; } if (!userpass.empty()) { - StringRef rawUser, rawPassword; - std::tie(rawUser, rawPassword) = userpass.split(':'); + auto [rawUser, rawPassword] = split(userpass, ':'); SmallString<64> userBuf, passBuf; user = UnescapeURI(rawUser, userBuf, error); if (*error) { - raw_string_ostream oss(*errorMsg); - oss << "could not unescape user \"" << rawUser << "\""; - oss.flush(); + *errorMsg = fmt::format("could not unescape user \"{}\"", rawUser); return; } password = UnescapeURI(rawPassword, passBuf, error); if (*error) { - raw_string_ostream oss(*errorMsg); - oss << "could not unescape password \"" << rawPassword << "\""; - oss.flush(); + *errorMsg = + fmt::format("could not unescape password \"{}\"", rawPassword); return; } } - StringRef portStr; - std::tie(host, portStr) = hostport.rsplit(':'); + std::string_view portStr; + std::tie(host, portStr) = rsplit(hostport, ':'); if (host.empty()) { *errorMsg = "host is empty"; *error = true; @@ -318,46 +315,42 @@ HttpLocation::HttpLocation(const Twine& url_, bool* error, } if (portStr.empty()) { port = 80; - } else if (portStr.getAsInteger(10, port)) { - raw_string_ostream oss(*errorMsg); - oss << "port \"" << portStr << "\" is not an integer"; - oss.flush(); + } else if (auto p = parse_integer(portStr, 10)) { + port = p.value(); + } else { + *errorMsg = fmt::format("port \"{}\" is not an integer", portStr); *error = true; return; } // path?query#fragment - std::tie(query, fragment) = query.split('#'); - std::tie(path, query) = query.split('?'); + std::tie(query, fragment) = split(query, '#'); + std::tie(path, query) = split(query, '?'); // Split query string into parameters while (!query.empty()) { // split out next param and value - StringRef rawParam, rawValue; - std::tie(rawParam, query) = query.split('&'); + std::string_view rawParam, rawValue; + std::tie(rawParam, query) = split(query, '&'); if (rawParam.empty()) { continue; // ignore "&&" } - std::tie(rawParam, rawValue) = rawParam.split('='); + std::tie(rawParam, rawValue) = split(rawParam, '='); // unescape param *error = false; SmallString<64> paramBuf; - StringRef param = UnescapeURI(rawParam, paramBuf, error); + std::string_view param = UnescapeURI(rawParam, paramBuf, error); if (*error) { - raw_string_ostream oss(*errorMsg); - oss << "could not unescape parameter \"" << rawParam << "\""; - oss.flush(); + *errorMsg = fmt::format("could not unescape parameter \"{}\"", rawParam); return; } // unescape value SmallString<64> valueBuf; - StringRef value = UnescapeURI(rawValue, valueBuf, error); + std::string_view value = UnescapeURI(rawValue, valueBuf, error); if (*error) { - raw_string_ostream oss(*errorMsg); - oss << "could not unescape value \"" << rawValue << "\""; - oss.flush(); + *errorMsg = fmt::format("could not unescape value \"{}\"", rawValue); return; } @@ -373,7 +366,7 @@ void HttpRequest::SetAuth(const HttpLocation& loc) { userpass += loc.user; userpass += ':'; userpass += loc.password; - Base64Encode(userpass, &auth); + Base64Encode(userpass.str(), &auth); } } @@ -390,24 +383,22 @@ bool HttpConnection::Handshake(const HttpRequest& request, // read first line of response SmallString<64> lineBuf; - StringRef line = is.getline(lineBuf, 1024).rtrim(); + std::string_view line = rtrim(is.getline(lineBuf, 1024)); if (is.has_error()) { *warnMsg = "disconnected before response"; return false; } // see if we got a HTTP 200 response - StringRef httpver, code, codeText; - std::tie(httpver, line) = line.split(' '); - std::tie(code, codeText) = line.split(' '); - if (!httpver.startswith("HTTP")) { + std::string_view httpver, code, codeText; + std::tie(httpver, line) = split(line, ' '); + std::tie(code, codeText) = split(line, ' '); + if (!starts_with(httpver, "HTTP")) { *warnMsg = "did not receive HTTP response"; return false; } if (code != "200") { - raw_string_ostream oss(*warnMsg); - oss << "received " << code << " " << codeText << " response"; - oss.flush(); + *warnMsg = fmt::format("received {} {} response", code, codeText); return false; } @@ -420,7 +411,7 @@ bool HttpConnection::Handshake(const HttpRequest& request, return true; } -void HttpMultipartScanner::SetBoundary(StringRef boundary) { +void HttpMultipartScanner::SetBoundary(std::string_view boundary) { m_boundaryWith = "\n--"; m_boundaryWith += boundary; m_boundaryWithout = "\n"; @@ -436,7 +427,7 @@ void HttpMultipartScanner::Reset(bool saveSkipped) { m_buf.resize(0); } -StringRef HttpMultipartScanner::Execute(StringRef in) { +std::string_view HttpMultipartScanner::Execute(std::string_view in) { if (m_state == kDone) { Reset(m_saveSkipped); } @@ -483,7 +474,7 @@ StringRef HttpMultipartScanner::Execute(StringRef in) { } if (m_state == kPadding) { - for (char ch : in.drop_front(pos)) { + for (char ch : drop_front(in, pos)) { ++pos; if (ch == '\n') { // Found the LF; return remaining input buffer (following it) @@ -491,13 +482,13 @@ StringRef HttpMultipartScanner::Execute(StringRef in) { if (m_saveSkipped) { m_buf.resize(m_buf.size() - in.size() + pos); } - return in.drop_front(pos); + return drop_front(in, pos); } } } // We consumed the entire input - return StringRef{}; + return {}; } } // namespace wpi diff --git a/wpiutil/src/main/native/cpp/Logger.cpp b/wpiutil/src/main/native/cpp/Logger.cpp new file mode 100644 index 0000000000..629c14a60d --- /dev/null +++ b/wpiutil/src/main/native/cpp/Logger.cpp @@ -0,0 +1,26 @@ +// Copyright (c) FIRST and other WPILib contributors. +// Open Source Software; you can modify and/or share it under the terms of +// the WPILib BSD license file in the root directory of this project. + +#include "wpi/Logger.h" + +using namespace wpi; + +void Logger::DoLog(unsigned int level, const char* file, unsigned int line, + const char* msg) { + if (!m_func || level < m_min_level) { + return; + } + m_func(level, file, line, msg); +} + +void Logger::LogV(unsigned int level, const char* file, unsigned int line, + fmt::string_view format, fmt::format_args args) { + if (!m_func || level < m_min_level) { + return; + } + fmt::memory_buffer out; + fmt::vformat_to(out, format, args); + out.push_back('\0'); + m_func(level, file, line, out.data()); +} diff --git a/wpiutil/src/main/native/cpp/MimeTypes.cpp b/wpiutil/src/main/native/cpp/MimeTypes.cpp index 664122a408..082dab140c 100644 --- a/wpiutil/src/main/native/cpp/MimeTypes.cpp +++ b/wpiutil/src/main/native/cpp/MimeTypes.cpp @@ -10,7 +10,7 @@ namespace wpi { // derived partially from // https://github.com/DEGoodmanWilson/libmime/blob/stable/0.1.2/mime/mime.cpp -StringRef MimeTypeFromPath(StringRef path) { +std::string_view MimeTypeFromPath(std::string_view path) { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types static StringMap mimeTypes{ // text @@ -52,11 +52,11 @@ StringRef MimeTypeFromPath(StringRef path) { static const char* defaultType = "application/octet-stream"; auto pos = path.find_last_of("/"); - if (pos != StringRef::npos) { + if (pos != std::string_view::npos) { path = path.substr(pos + 1); } auto dot_pos = path.find_last_of("."); - if (dot_pos > 0 && dot_pos != StringRef::npos) { + if (dot_pos > 0 && dot_pos != std::string_view::npos) { auto type = mimeTypes.find(path.substr(dot_pos + 1)); if (type != mimeTypes.end()) { return type->getValue(); diff --git a/wpiutil/src/main/native/cpp/PortForwarder.cpp b/wpiutil/src/main/native/cpp/PortForwarder.cpp index d2b80b14a9..797c7c7fdb 100644 --- a/wpiutil/src/main/native/cpp/PortForwarder.cpp +++ b/wpiutil/src/main/native/cpp/PortForwarder.cpp @@ -4,10 +4,9 @@ #include "wpi/PortForwarder.h" +#include "fmt/format.h" #include "wpi/DenseMap.h" #include "wpi/EventLoopRunner.h" -#include "wpi/SmallString.h" -#include "wpi/raw_ostream.h" #include "wpi/uv/GetAddrInfo.h" #include "wpi/uv/Tcp.h" #include "wpi/uv/Timer.h" @@ -45,7 +44,7 @@ static void CopyStream(uv::Stream& in, std::weak_ptr outWeak) { }); } -void PortForwarder::Add(unsigned int port, const Twine& remoteHost, +void PortForwarder::Add(unsigned int port, std::string_view remoteHost, unsigned int remotePort) { m_impl->runner.ExecSync([&](uv::Loop& loop) { auto server = uv::Tcp::Create(loop); @@ -55,7 +54,7 @@ void PortForwarder::Add(unsigned int port, const Twine& remoteHost, // when we get a connection, accept it server->connection.connect([serverPtr = server.get(), - host = remoteHost.str(), remotePort] { + host = std::string{remoteHost}, remotePort] { auto& loop = serverPtr->GetLoopRef(); auto client = serverPtr->Accept(); if (!client) { @@ -80,10 +79,6 @@ void PortForwarder::Add(unsigned int port, const Twine& remoteHost, } }); - // convert port to string - SmallString<16> remotePortStr; - raw_svector_ostream(remotePortStr) << remotePort; - // resolve address uv::GetAddrInfo( loop, @@ -125,7 +120,7 @@ void PortForwarder::Add(unsigned int port, const Twine& remoteHost, CopyStream(*remotePtr, clientWeak); }); }, - host, remotePortStr); + host, fmt::to_string(remotePort)); // time out for connection uv::Timer::SingleShot(loop, uv::Timer::Time{500}, diff --git a/wpiutil/src/main/native/cpp/StringExtras.cpp b/wpiutil/src/main/native/cpp/StringExtras.cpp index 2fbf21346a..45d23ea1b7 100644 --- a/wpiutil/src/main/native/cpp/StringExtras.cpp +++ b/wpiutil/src/main/native/cpp/StringExtras.cpp @@ -23,7 +23,6 @@ #include "wpi/SmallString.h" #include "wpi/SmallVector.h" -#include "wpi/StringRef.h" // strncasecmp() is not available on non-POSIX systems, so define an // alternative function here. @@ -178,34 +177,143 @@ void wpi::split(std::string_view str, SmallVectorImpl& arr, } } -bool wpi::detail::GetAsUnsignedInteger( - std::string_view str, unsigned radix, - unsigned long long& result) noexcept { // NOLINT(runtime/int) - return wpi::getAsUnsignedInteger(str, radix, result); -} +static unsigned GetAutoSenseRadix(std::string_view& str) noexcept { + if (str.empty()) { + return 10; + } -bool wpi::detail::GetAsSignedInteger( - std::string_view str, unsigned radix, - long long& result) noexcept { // NOLINT(runtime/int) - return wpi::getAsSignedInteger(str, radix, result); + if (wpi::starts_with(str, "0x") || wpi::starts_with(str, "0X")) { + str.remove_prefix(2); + return 16; + } + + if (wpi::starts_with(str, "0b") || wpi::starts_with(str, "0B")) { + str.remove_prefix(2); + return 2; + } + + if (wpi::starts_with(str, "0o")) { + str.remove_prefix(2); + return 8; + } + + if (str[0] == '0' && str.size() > 1 && wpi::isDigit(str[1])) { + str.remove_prefix(1); + return 8; + } + + return 10; } bool wpi::detail::ConsumeUnsignedInteger( std::string_view& str, unsigned radix, unsigned long long& result) noexcept { // NOLINT(runtime/int) - wpi::StringRef sref = str; - bool rv = wpi::consumeUnsignedInteger(sref, radix, result); - str = sref; - return rv; + // Autosense radix if not specified. + if (radix == 0) { + radix = GetAutoSenseRadix(str); + } + + // Empty strings (after the radix autosense) are invalid. + if (str.empty()) { + return true; + } + + // Parse all the bytes of the string given this radix. Watch for overflow. + std::string_view str2 = str; + result = 0; + while (!str2.empty()) { + unsigned charVal; + if (str2[0] >= '0' && str2[0] <= '9') { + charVal = str2[0] - '0'; + } else if (str2[0] >= 'a' && str2[0] <= 'z') { + charVal = str2[0] - 'a' + 10; + } else if (str2[0] >= 'A' && str2[0] <= 'Z') { + charVal = str2[0] - 'A' + 10; + } else { + break; + } + + // If the parsed value is larger than the integer radix, we cannot + // consume any more characters. + if (charVal >= radix) { + break; + } + + // Add in this character. + unsigned long long prevResult = result; // NOLINT(runtime/int) + result = result * radix + charVal; + + // Check for overflow by shifting back and seeing if bits were lost. + if (result / radix < prevResult) { + return true; + } + + str2.remove_prefix(1); + } + + // We consider the operation a failure if no characters were consumed + // successfully. + if (str.size() == str2.size()) { + return true; + } + + str = str2; + return false; } bool wpi::detail::ConsumeSignedInteger( std::string_view& str, unsigned radix, long long& result) noexcept { // NOLINT(runtime/int) - wpi::StringRef sref = str; - bool rv = wpi::consumeSignedInteger(sref, radix, result); - str = sref; - return rv; + unsigned long long ullVal; // NOLINT(runtime/int) + + // Handle positive strings first. + if (str.empty() || str.front() != '-') { + if (wpi::detail::ConsumeUnsignedInteger(str, radix, ullVal) || + // Check for value so large it overflows a signed value. + static_cast(ullVal) < 0) { // NOLINT(runtime/int) + return true; + } + result = ullVal; + return false; + } + + // Get the positive part of the value. + std::string_view str2 = wpi::drop_front(str, 1); + if (wpi::detail::ConsumeUnsignedInteger(str2, radix, ullVal) || + // Reject values so large they'd overflow as negative signed, but allow + // "-0". This negates the unsigned so that the negative isn't undefined + // on signed overflow. + static_cast(-ullVal) > 0) { // NOLINT(runtime/int) + return true; + } + + str = str2; + result = -ullVal; + return false; +} + +bool wpi::detail::GetAsUnsignedInteger( + std::string_view str, unsigned radix, + unsigned long long& result) noexcept { // NOLINT(runtime/int) + if (wpi::detail::ConsumeUnsignedInteger(str, radix, result)) { + return true; + } + + // For getAsUnsignedInteger, we require the whole string to be consumed or + // else we consider it a failure. + return !str.empty(); +} + +bool wpi::detail::GetAsSignedInteger( + std::string_view str, unsigned radix, + long long& result) noexcept { // NOLINT(runtime/int) + if (wpi::detail::ConsumeSignedInteger(str, radix, result)) { + return true; + } + + // For getAsSignedInteger, we require the whole string to be consumed or else + // we consider it a failure. + return !str.empty(); } template <> diff --git a/wpiutil/src/main/native/cpp/TCPAcceptor.cpp b/wpiutil/src/main/native/cpp/TCPAcceptor.cpp index de4bfcf1d7..8d12ac3a12 100644 --- a/wpiutil/src/main/native/cpp/TCPAcceptor.cpp +++ b/wpiutil/src/main/native/cpp/TCPAcceptor.cpp @@ -44,7 +44,7 @@ using namespace wpi; -TCPAcceptor::TCPAcceptor(int port, const char* address, Logger& logger) +TCPAcceptor::TCPAcceptor(int port, std::string_view address, Logger& logger) : m_lsd(0), m_port(port), m_address(address), @@ -79,7 +79,7 @@ int TCPAcceptor::start() { m_lsd = socket(PF_INET, SOCK_STREAM, 0); if (m_lsd < 0) { - WPI_ERROR(m_logger, "could not create socket"); + WPI_ERROR(m_logger, "{}", "could not create socket"); return -1; } struct sockaddr_in address; @@ -95,7 +95,7 @@ int TCPAcceptor::start() { int res = inet_pton(PF_INET, m_address.c_str(), &(address.sin_addr)); #endif if (res != 1) { - WPI_ERROR(m_logger, "could not resolve " << m_address << " address"); + WPI_ERROR(m_logger, "could not resolve {} address", m_address); return -1; } } else { @@ -116,15 +116,15 @@ int TCPAcceptor::start() { int result = bind(m_lsd, reinterpret_cast(&address), sizeof(address)); if (result != 0) { - WPI_ERROR(m_logger, - "bind() to port " << m_port << " failed: " << SocketStrerror()); + WPI_ERROR(m_logger, "bind() to port {} failed: {}", m_port, + SocketStrerror()); return result; } result = listen(m_lsd, 5); if (result != 0) { - WPI_ERROR(m_logger, - "listen() on port " << m_port << " failed: " << SocketStrerror()); + WPI_ERROR(m_logger, "listen() on port {} failed: {}", m_port, + SocketStrerror()); return result; } m_listening = true; @@ -193,8 +193,8 @@ std::unique_ptr TCPAcceptor::accept() { int sd = ::accept(m_lsd, reinterpret_cast(&address), &len); if (sd < 0) { if (!m_shutdown) { - WPI_ERROR(m_logger, "accept() on port " - << m_port << " failed: " << SocketStrerror()); + WPI_ERROR(m_logger, "accept() on port {} failed: {}", m_port, + SocketStrerror()); } return nullptr; } diff --git a/wpiutil/src/main/native/cpp/TCPConnector.cpp b/wpiutil/src/main/native/cpp/TCPConnector.cpp index 20fdbc9369..ed97962463 100644 --- a/wpiutil/src/main/native/cpp/TCPConnector.cpp +++ b/wpiutil/src/main/native/cpp/TCPConnector.cpp @@ -96,7 +96,7 @@ std::unique_ptr TCPConnector::connect(const char* server, int res = inet_pton(PF_INET, server, &(address.sin_addr)); #endif if (res != 1) { - WPI_ERROR(logger, "could not resolve " << server << " address"); + WPI_ERROR(logger, "could not resolve {} address", server); return nullptr; } } @@ -105,13 +105,13 @@ std::unique_ptr TCPConnector::connect(const char* server, if (timeout == 0) { int sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { - WPI_ERROR(logger, "could not create socket"); + WPI_ERROR(logger, "{}", "could not create socket"); return nullptr; } if (::connect(sd, reinterpret_cast(&address), sizeof(address)) != 0) { - WPI_ERROR(logger, "connect() to " << server << " port " << port - << " failed: " << SocketStrerror()); + WPI_ERROR(logger, "connect() to {} port {} failed: {}", server, port, + SocketStrerror()); #ifdef _WIN32 closesocket(sd); #else @@ -127,7 +127,7 @@ std::unique_ptr TCPConnector::connect(const char* server, socklen_t len; int result = -1, valopt, sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { - WPI_ERROR(logger, "could not create socket"); + WPI_ERROR(logger, "{}", "could not create socket"); return nullptr; } @@ -135,19 +135,19 @@ std::unique_ptr TCPConnector::connect(const char* server, #ifdef _WIN32 u_long mode = 1; if (ioctlsocket(sd, FIONBIO, &mode) == SOCKET_ERROR) - WPI_WARNING(logger, - "could not set socket to non-blocking: " << SocketStrerror()); + WPI_WARNING(logger, "could not set socket to non-blocking: {}", + SocketStrerror()); #else int arg; arg = fcntl(sd, F_GETFL, nullptr); if (arg < 0) { - WPI_WARNING(logger, - "could not set socket to non-blocking: " << SocketStrerror()); + WPI_WARNING(logger, "could not set socket to non-blocking: {}", + SocketStrerror()); } else { arg |= O_NONBLOCK; if (fcntl(sd, F_SETFL, arg) < 0) { - WPI_WARNING(logger, - "could not set socket to non-blocking: " << SocketStrerror()); + WPI_WARNING(logger, "could not set socket to non-blocking: {}", + SocketStrerror()); } } #endif @@ -170,21 +170,18 @@ std::unique_ptr TCPConnector::connect(const char* server, getsockopt(sd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&valopt), &len); if (valopt) { - WPI_ERROR(logger, "select() to " << server << " port " << port - << " error " << valopt << " - " - << SocketStrerror(valopt)); + WPI_ERROR(logger, "select() to {} port {} error {} - {}", server, + port, valopt, SocketStrerror(valopt)); } else { // connection established result = 0; } } else { - WPI_INFO(logger, - "connect() to " << server << " port " << port << " timed out"); + WPI_INFO(logger, "connect() to {} port {} timed out", server, port); } } else { - WPI_ERROR(logger, "connect() to " << server << " port " << port - << " error " << SocketErrno() << " - " - << SocketStrerror()); + WPI_ERROR(logger, "connect() to {} port {} error {} - {}", server, port, + SocketErrno(), SocketStrerror()); } } @@ -192,18 +189,18 @@ std::unique_ptr TCPConnector::connect(const char* server, #ifdef _WIN32 mode = 0; if (ioctlsocket(sd, FIONBIO, &mode) == SOCKET_ERROR) - WPI_WARNING(logger, - "could not set socket to blocking: " << SocketStrerror()); + WPI_WARNING(logger, "could not set socket to blocking: {}", + SocketStrerror()); #else arg = fcntl(sd, F_GETFL, nullptr); if (arg < 0) { - WPI_WARNING(logger, - "could not set socket to blocking: " << SocketStrerror()); + WPI_WARNING(logger, "could not set socket to blocking: {}", + SocketStrerror()); } else { arg &= (~O_NONBLOCK); if (fcntl(sd, F_SETFL, arg) < 0) { - WPI_WARNING(logger, - "could not set socket to blocking: " << SocketStrerror()); + WPI_WARNING(logger, "could not set socket to blocking: {}", + SocketStrerror()); } } #endif diff --git a/wpiutil/src/main/native/cpp/TCPStream.cpp b/wpiutil/src/main/native/cpp/TCPStream.cpp index 7a0ead1dac..45671611d4 100644 --- a/wpiutil/src/main/native/cpp/TCPStream.cpp +++ b/wpiutil/src/main/native/cpp/TCPStream.cpp @@ -168,7 +168,7 @@ void TCPStream::close() { m_sd = -1; } -StringRef TCPStream::getPeerIP() const { +std::string_view TCPStream::getPeerIP() const { return m_peerIP; } diff --git a/wpiutil/src/main/native/cpp/UDPClient.cpp b/wpiutil/src/main/native/cpp/UDPClient.cpp index afaad9fec9..3e90d47dca 100644 --- a/wpiutil/src/main/native/cpp/UDPClient.cpp +++ b/wpiutil/src/main/native/cpp/UDPClient.cpp @@ -16,14 +16,15 @@ #endif #include "wpi/Logger.h" +#include "wpi/SmallString.h" #include "wpi/SocketError.h" using namespace wpi; UDPClient::UDPClient(Logger& logger) : UDPClient("", logger) {} -UDPClient::UDPClient(const Twine& address, Logger& logger) - : m_lsd(0), m_port(0), m_address(address.str()), m_logger(logger) {} +UDPClient::UDPClient(std::string_view address, Logger& logger) + : m_lsd(0), m_port(0), m_address(address), m_logger(logger) {} UDPClient::UDPClient(UDPClient&& other) : m_lsd(other.m_lsd), @@ -72,7 +73,7 @@ int UDPClient::start(int port) { m_lsd = socket(AF_INET, SOCK_DGRAM, 0); if (m_lsd < 0) { - WPI_ERROR(m_logger, "could not create socket"); + WPI_ERROR(m_logger, "{}", "could not create socket"); return -1; } @@ -88,7 +89,7 @@ int UDPClient::start(int port) { int res = inet_pton(PF_INET, m_address.c_str(), &(addr.sin_addr)); #endif if (res != 1) { - WPI_ERROR(m_logger, "could not resolve " << m_address << " address"); + WPI_ERROR(m_logger, "could not resolve {} address", m_address); return -1; } } else { @@ -110,7 +111,7 @@ int UDPClient::start(int port) { int result = bind(m_lsd, reinterpret_cast(&addr), sizeof(addr)); if (result != 0) { - WPI_ERROR(m_logger, "bind() failed: " << SocketStrerror()); + WPI_ERROR(m_logger, "bind() failed: {}", SocketStrerror()); return result; } m_port = port; @@ -132,25 +133,24 @@ void UDPClient::shutdown() { } } -int UDPClient::send(ArrayRef data, const Twine& server, int port) { +int UDPClient::send(ArrayRef data, std::string_view server, int port) { // server must be a resolvable IP address struct sockaddr_in addr; std::memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; - SmallVector addr_store; - StringRef remoteAddr = server.toNullTerminatedStringRef(addr_store); + SmallString<128> remoteAddr{server}; if (remoteAddr.empty()) { - WPI_ERROR(m_logger, "server must be passed"); + WPI_ERROR(m_logger, "{}", "server must be passed"); return -1; } #ifdef _WIN32 - int res = InetPton(AF_INET, remoteAddr.data(), &(addr.sin_addr)); + int res = InetPton(AF_INET, remoteAddr.c_str(), &(addr.sin_addr)); #else - int res = inet_pton(AF_INET, remoteAddr.data(), &(addr.sin_addr)); + int res = inet_pton(AF_INET, remoteAddr.c_str(), &(addr.sin_addr)); #endif if (res != 1) { - WPI_ERROR(m_logger, "could not resolve " << server << " address"); + WPI_ERROR(m_logger, "could not resolve {} address", server); return -1; } addr.sin_port = htons(port); @@ -162,25 +162,24 @@ int UDPClient::send(ArrayRef data, const Twine& server, int port) { return result; } -int UDPClient::send(StringRef data, const Twine& server, int port) { +int UDPClient::send(std::string_view data, std::string_view server, int port) { // server must be a resolvable IP address struct sockaddr_in addr; std::memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; - SmallVector addr_store; - StringRef remoteAddr = server.toNullTerminatedStringRef(addr_store); + SmallString<128> remoteAddr{server}; if (remoteAddr.empty()) { - WPI_ERROR(m_logger, "server must be passed"); + WPI_ERROR(m_logger, "{}", "server must be passed"); return -1; } #ifdef _WIN32 - int res = InetPton(AF_INET, remoteAddr.data(), &(addr.sin_addr)); + int res = InetPton(AF_INET, remoteAddr.c_str(), &(addr.sin_addr)); #else - int res = inet_pton(AF_INET, remoteAddr.data(), &(addr.sin_addr)); + int res = inet_pton(AF_INET, remoteAddr.c_str(), &(addr.sin_addr)); #endif if (res != 1) { - WPI_ERROR(m_logger, "could not resolve " << server << " address"); + WPI_ERROR(m_logger, "could not resolve {} address", server); return -1; } addr.sin_port = htons(port); @@ -242,7 +241,7 @@ int UDPClient::set_timeout(double timeout) { int ret = setsockopt(m_lsd, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&tv), sizeof(tv)); if (ret < 0) { - WPI_ERROR(m_logger, "set timeout failed"); + WPI_ERROR(m_logger, "{}", "set timeout failed"); } return ret; } diff --git a/wpiutil/src/main/native/cpp/WebSocket.cpp b/wpiutil/src/main/native/cpp/WebSocket.cpp index 11e3391687..e7a38736c7 100644 --- a/wpiutil/src/main/native/cpp/WebSocket.cpp +++ b/wpiutil/src/main/native/cpp/WebSocket.cpp @@ -6,10 +6,12 @@ #include +#include "fmt/format.h" #include "wpi/Base64.h" #include "wpi/HttpParser.h" #include "wpi/SmallString.h" #include "wpi/SmallVector.h" +#include "wpi/StringExtras.h" #include "wpi/raw_uv_ostream.h" #include "wpi/sha1.h" #include "wpi/uv/Stream.h" @@ -47,7 +49,7 @@ class WebSocket::ClientHandshakeData { v = static_cast(dist(gen)); } raw_svector_ostream os(key); - Base64Encode(os, StringRef{nonce, 16}); + Base64Encode(os, {nonce, 16}); } ~ClientHandshakeData() { if (auto t = timer.lock()) { @@ -67,7 +69,8 @@ class WebSocket::ClientHandshakeData { std::weak_ptr timer; }; -static StringRef AcceptHash(StringRef key, SmallVectorImpl& buf) { +static std::string_view AcceptHash(std::string_view key, + SmallVectorImpl& buf) { SHA1 hash; hash.Update(key); hash.Update("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); @@ -80,7 +83,7 @@ WebSocket::WebSocket(uv::Stream& stream, bool server, const private_init&) // Connect closed and error signals to ourselves m_stream.closed.connect([this]() { SetClosed(1006, "handle closed"); }); m_stream.error.connect([this](uv::Error err) { - Terminate(1006, "stream error: " + Twine(err.name())); + Terminate(1006, fmt::format("stream error: {}", err.name())); }); // Start reading @@ -95,8 +98,8 @@ WebSocket::WebSocket(uv::Stream& stream, bool server, const private_init&) WebSocket::~WebSocket() = default; std::shared_ptr WebSocket::CreateClient( - uv::Stream& stream, const Twine& uri, const Twine& host, - ArrayRef protocols, const ClientOptions& options) { + uv::Stream& stream, std::string_view uri, std::string_view host, + ArrayRef protocols, const ClientOptions& options) { auto ws = std::make_shared(stream, false, private_init{}); stream.SetData(ws); ws->StartClient(uri, host, protocols, options); @@ -104,23 +107,23 @@ std::shared_ptr WebSocket::CreateClient( } std::shared_ptr WebSocket::CreateServer(uv::Stream& stream, - StringRef key, - StringRef version, - StringRef protocol) { + std::string_view key, + std::string_view version, + std::string_view protocol) { auto ws = std::make_shared(stream, true, private_init{}); stream.SetData(ws); ws->StartServer(key, version, protocol); return ws; } -void WebSocket::Close(uint16_t code, const Twine& reason) { +void WebSocket::Close(uint16_t code, std::string_view reason) { SendClose(code, reason); if (m_state != FAILED && m_state != CLOSED) { m_state = CLOSING; } } -void WebSocket::Fail(uint16_t code, const Twine& reason) { +void WebSocket::Fail(uint16_t code, std::string_view reason) { if (m_state == FAILED || m_state == CLOSED) { return; } @@ -129,7 +132,7 @@ void WebSocket::Fail(uint16_t code, const Twine& reason) { Shutdown(); } -void WebSocket::Terminate(uint16_t code, const Twine& reason) { +void WebSocket::Terminate(uint16_t code, std::string_view reason) { if (m_state == FAILED || m_state == CLOSED) { return; } @@ -137,8 +140,8 @@ void WebSocket::Terminate(uint16_t code, const Twine& reason) { Shutdown(); } -void WebSocket::StartClient(const Twine& uri, const Twine& host, - ArrayRef protocols, +void WebSocket::StartClient(std::string_view uri, std::string_view host, + ArrayRef protocols, const ClientOptions& options) { // Create client handshake data m_clientHandshake = std::make_unique(); @@ -187,42 +190,42 @@ void WebSocket::StartClient(const Twine& uri, const Twine& host, }); // Set up client response handling - m_clientHandshake->parser.status.connect([this](StringRef status) { + m_clientHandshake->parser.status.connect([this](std::string_view status) { unsigned int code = m_clientHandshake->parser.GetStatusCode(); if (code != 101) { Terminate(code, status); } }); m_clientHandshake->parser.header.connect( - [this](StringRef name, StringRef value) { - value = value.trim(); - if (name.equals_lower("upgrade")) { - if (!value.equals_lower("websocket")) { + [this](std::string_view name, std::string_view value) { + value = trim(value); + if (equals_lower(name, "upgrade")) { + if (!equals_lower(value, "websocket")) { return Terminate(1002, "invalid upgrade response value"); } m_clientHandshake->hasUpgrade = true; - } else if (name.equals_lower("connection")) { - if (!value.equals_lower("upgrade")) { + } else if (equals_lower(name, "connection")) { + if (!equals_lower(value, "upgrade")) { return Terminate(1002, "invalid connection response value"); } m_clientHandshake->hasConnection = true; - } else if (name.equals_lower("sec-websocket-accept")) { + } else if (equals_lower(name, "sec-websocket-accept")) { // Check against expected response SmallString<64> acceptBuf; - if (!value.equals(AcceptHash(m_clientHandshake->key, acceptBuf))) { + if (!equals(value, AcceptHash(m_clientHandshake->key, acceptBuf))) { return Terminate(1002, "invalid accept key"); } m_clientHandshake->hasAccept = true; - } else if (name.equals_lower("sec-websocket-extensions")) { + } else if (equals_lower(name, "sec-websocket-extensions")) { // No extensions are supported if (!value.empty()) { return Terminate(1010, "unsupported extension"); } - } else if (name.equals_lower("sec-websocket-protocol")) { + } else if (equals_lower(name, "sec-websocket-protocol")) { // Make sure it was one of the provided protocols bool match = false; for (auto&& protocol : m_clientHandshake->protocols) { - if (value.equals_lower(protocol)) { + if (equals_lower(value, protocol)) { match = true; break; } @@ -257,8 +260,8 @@ void WebSocket::StartClient(const Twine& uri, const Twine& host, } } -void WebSocket::StartServer(StringRef key, StringRef version, - StringRef protocol) { +void WebSocket::StartServer(std::string_view key, std::string_view version, + std::string_view protocol) { m_protocol = protocol; // Build server response @@ -308,14 +311,14 @@ void WebSocket::StartServer(StringRef key, StringRef version, }); } -void WebSocket::SendClose(uint16_t code, const Twine& reason) { +void WebSocket::SendClose(uint16_t code, std::string_view reason) { SmallVector bufs; if (code != 1005) { raw_uv_ostream os{bufs, 4096}; const uint8_t codeMsb[] = {static_cast((code >> 8) & 0xff), static_cast(code & 0xff)}; os << ArrayRef(codeMsb); - reason.print(os); + os << reason; } Send(kFlagFin | kOpClose, bufs, [](auto bufs, uv::Error) { for (auto&& buf : bufs) { @@ -324,13 +327,12 @@ void WebSocket::SendClose(uint16_t code, const Twine& reason) { }); } -void WebSocket::SetClosed(uint16_t code, const Twine& reason, bool failed) { +void WebSocket::SetClosed(uint16_t code, std::string_view reason, bool failed) { if (m_state == FAILED || m_state == CLOSED) { return; } m_state = failed ? FAILED : CLOSED; - SmallString<64> reasonBuf; - closed(code, reason.toStringRef(reasonBuf)); + closed(code, reason); } void WebSocket::Shutdown() { @@ -343,7 +345,7 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { return; } - StringRef data{buf.base, size}; + std::string_view data{buf.base, size}; // Handle connecting state (mainly on client) if (m_state == CONNECTING) { @@ -372,8 +374,8 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { // Need at least two bytes to determine header length if (m_header.size() < 2u) { size_t toCopy = (std::min)(2u - m_header.size(), data.size()); - m_header.append(data.bytes_begin(), data.bytes_begin() + toCopy); - data = data.drop_front(toCopy); + m_header.append(data.data(), data.data() + toCopy); + data.remove_prefix(toCopy); if (m_header.size() < 2u) { return; // need more data } @@ -410,8 +412,8 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { // Need to complete header to calculate message size if (m_header.size() < m_headerSize) { size_t toCopy = (std::min)(m_headerSize - m_header.size(), data.size()); - m_header.append(data.bytes_begin(), data.bytes_begin() + toCopy); - data = data.drop_front(toCopy); + m_header.append(data.data(), data.data() + toCopy); + data.remove_prefix(toCopy); if (m_header.size() < m_headerSize) { return; // need more data } @@ -446,8 +448,8 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { if (m_frameSize != UINT64_MAX) { size_t need = m_frameStart + m_frameSize - m_payload.size(); size_t toCopy = (std::min)(need, data.size()); - m_payload.append(data.bytes_begin(), data.bytes_begin() + toCopy); - data = data.drop_front(toCopy); + m_payload.append(data.data(), data.data() + toCopy); + data.remove_prefix(toCopy); need -= toCopy; if (need == 0) { // We have a complete frame @@ -474,8 +476,9 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { switch (m_fragmentOpcode) { case kOpText: if (!m_combineFragments || fin) { - text(StringRef{reinterpret_cast(m_payload.data()), - m_payload.size()}, + text(std::string_view{reinterpret_cast( + m_payload.data()), + m_payload.size()}, fin); } break; @@ -497,8 +500,8 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { return Fail(1002, "incomplete fragment"); } if (!m_combineFragments || fin) { - text(StringRef{reinterpret_cast(m_payload.data()), - m_payload.size()}, + text(std::string_view{reinterpret_cast(m_payload.data()), + m_payload.size()}, fin); } if (!fin) { @@ -518,7 +521,7 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { break; case kOpClose: { uint16_t code; - StringRef reason; + std::string_view reason; if (!fin) { code = 1002; reason = "cannot fragment control frames"; @@ -527,9 +530,9 @@ void WebSocket::HandleIncoming(uv::Buffer& buf, size_t size) { } else { code = (static_cast(m_payload[0]) << 8) | static_cast(m_payload[1]); - reason = StringRef{reinterpret_cast(m_payload.data()), - m_payload.size()} - .drop_front(2); + reason = drop_front( + {reinterpret_cast(m_payload.data()), m_payload.size()}, + 2); } // Echo the close if we didn't previously send it if (m_state != CLOSING) { diff --git a/wpiutil/src/main/native/cpp/WebSocketServer.cpp b/wpiutil/src/main/native/cpp/WebSocketServer.cpp index 637ceff104..45b9fda7b2 100644 --- a/wpiutil/src/main/native/cpp/WebSocketServer.cpp +++ b/wpiutil/src/main/native/cpp/WebSocketServer.cpp @@ -6,6 +6,8 @@ #include +#include "wpi/StringExtras.h" +#include "wpi/fmt/raw_ostream.h" #include "wpi/raw_uv_ostream.h" #include "wpi/uv/Buffer.h" #include "wpi/uv/Stream.h" @@ -13,23 +15,23 @@ using namespace wpi; WebSocketServerHelper::WebSocketServerHelper(HttpParser& req) { - req.header.connect([this](StringRef name, StringRef value) { - if (name.equals_lower("host")) { + req.header.connect([this](std::string_view name, std::string_view value) { + if (equals_lower(name, "host")) { m_gotHost = true; - } else if (name.equals_lower("upgrade")) { - if (value.equals_lower("websocket")) { + } else if (equals_lower(name, "upgrade")) { + if (equals_lower(value, "websocket")) { m_websocket = true; } - } else if (name.equals_lower("sec-websocket-key")) { + } else if (equals_lower(name, "sec-websocket-key")) { m_key = value; - } else if (name.equals_lower("sec-websocket-version")) { + } else if (equals_lower(name, "sec-websocket-version")) { m_version = value; - } else if (name.equals_lower("sec-websocket-protocol")) { + } else if (equals_lower(name, "sec-websocket-protocol")) { // Protocols are comma delimited, repeated headers add to list - SmallVector protocols; - value.split(protocols, ",", -1, false); + SmallVector protocols; + split(value, protocols, ",", -1, false); for (auto protocol : protocols) { - protocol = protocol.trim(); + protocol = trim(protocol); if (!protocol.empty()) { m_protocols.emplace_back(protocol); } @@ -43,31 +45,31 @@ WebSocketServerHelper::WebSocketServerHelper(HttpParser& req) { }); } -std::pair WebSocketServerHelper::MatchProtocol( - ArrayRef protocols) { +std::pair WebSocketServerHelper::MatchProtocol( + ArrayRef protocols) { if (protocols.empty() && m_protocols.empty()) { - return std::make_pair(true, StringRef{}); + return {true, {}}; } for (auto protocol : protocols) { for (auto&& clientProto : m_protocols) { if (protocol == clientProto) { - return std::make_pair(true, protocol); + return {true, protocol}; } } } - return std::make_pair(false, StringRef{}); + return {false, {}}; } WebSocketServer::WebSocketServer(uv::Stream& stream, - ArrayRef protocols, + ArrayRef protocols, ServerOptions options, const private_init&) : m_stream{stream}, m_helper{m_req}, m_protocols{protocols.begin(), protocols.end()}, m_options{std::move(options)} { // Header handling - m_req.header.connect([this](StringRef name, StringRef value) { - if (name.equals_lower("host")) { + m_req.header.connect([this](std::string_view name, std::string_view value) { + if (equals_lower(name, "host")) { if (m_options.checkHost) { if (!m_options.checkHost(value)) { Abort(401, "Unrecognized Host"); @@ -75,7 +77,7 @@ WebSocketServer::WebSocketServer(uv::Stream& stream, } } }); - m_req.url.connect([this](StringRef name) { + m_req.url.connect([this](std::string_view name) { if (m_options.checkUrl) { if (!m_options.checkUrl(name)) { Abort(404, "Not Found"); @@ -96,8 +98,9 @@ WebSocketServer::WebSocketServer(uv::Stream& stream, } // Negotiate sub-protocol - SmallVector protocols{m_protocols.begin(), m_protocols.end()}; - StringRef protocol = m_helper.MatchProtocol(protocols).second; + SmallVector protocols{m_protocols.begin(), + m_protocols.end()}; + std::string_view protocol = m_helper.MatchProtocol(protocols).second; // Disconnect our header reader m_dataConn.disconnect(); @@ -110,10 +113,11 @@ WebSocketServer::WebSocketServer(uv::Stream& stream, auto ws = m_helper.Accept(m_stream, protocol); // Connect the websocket open event to our connected event. - ws->open.connect_extended([self, s = ws.get()](auto conn, StringRef) { - self->connected(self->m_req.GetUrl(), *s); - conn.disconnect(); // one-shot - }); + ws->open.connect_extended( + [self, s = ws.get()](auto conn, std::string_view) { + self->connected(self->m_req.GetUrl(), *s); + conn.disconnect(); // one-shot + }); }); // Set up stream @@ -123,7 +127,7 @@ WebSocketServer::WebSocketServer(uv::Stream& stream, if (m_aborted) { return; } - m_req.Execute(StringRef{buf.base, size}); + m_req.Execute(std::string_view{buf.base, size}); if (m_req.HasError()) { Abort(400, "Bad Request"); } @@ -134,7 +138,7 @@ WebSocketServer::WebSocketServer(uv::Stream& stream, } std::shared_ptr WebSocketServer::Create( - uv::Stream& stream, ArrayRef protocols, + uv::Stream& stream, ArrayRef protocols, const ServerOptions& options) { auto server = std::make_shared(stream, protocols, options, private_init{}); @@ -142,7 +146,7 @@ std::shared_ptr WebSocketServer::Create( return server; } -void WebSocketServer::Abort(uint16_t code, StringRef reason) { +void WebSocketServer::Abort(uint16_t code, std::string_view reason) { if (m_aborted) { return; } @@ -153,7 +157,7 @@ void WebSocketServer::Abort(uint16_t code, StringRef reason) { raw_uv_ostream os{bufs, 1024}; // Handle unsupported version - os << "HTTP/1.1 " << code << ' ' << reason << "\r\n"; + fmt::print(os, "HTTP/1.1 {} {}\r\n", code, reason); if (code == 426) { os << "Upgrade: WebSocket\r\n"; } diff --git a/wpiutil/src/main/native/cpp/hostname.cpp b/wpiutil/src/main/native/cpp/hostname.cpp index 939ed223e7..d907023ff4 100644 --- a/wpiutil/src/main/native/cpp/hostname.cpp +++ b/wpiutil/src/main/native/cpp/hostname.cpp @@ -6,10 +6,10 @@ #include #include +#include #include "uv.h" #include "wpi/SmallVector.h" -#include "wpi/StringRef.h" namespace wpi { @@ -33,7 +33,7 @@ std::string GetHostname() { return rv; } -StringRef GetHostname(SmallVectorImpl& name) { +std::string_view GetHostname(SmallVectorImpl& name) { // Use a tmp array to not require the SmallVector to be too large. char tmpName[256]; size_t size = sizeof(tmpName); @@ -51,7 +51,7 @@ StringRef GetHostname(SmallVectorImpl& name) { } } - return StringRef{name.data(), size}; + return {name.data(), size}; } } // namespace wpi diff --git a/wpiutil/src/main/native/cpp/json.cpp b/wpiutil/src/main/native/cpp/json.cpp index ba9cd8ef7a..f1cfb14ca2 100644 --- a/wpiutil/src/main/native/cpp/json.cpp +++ b/wpiutil/src/main/native/cpp/json.cpp @@ -34,39 +34,51 @@ SOFTWARE. #define WPI_JSON_IMPLEMENTATION #include "wpi/json.h" +#include "fmt/format.h" #include "wpi/raw_ostream.h" namespace wpi { namespace detail { -exception::exception(int id_, const Twine& what_arg) - : id(id_), m(what_arg.str()) {} +exception::exception(int id_, std::string_view what_arg) + : id(id_), m(std::string{what_arg}) {} -parse_error parse_error::create(int id_, std::size_t byte_, const Twine& what_arg) +parse_error parse_error::create(int id_, std::size_t byte_, std::string_view what_arg) { - return parse_error(id_, byte_, "[json.exception.parse_error." + Twine(id_) + "] parse error" + - (byte_ != 0 ? (" at " + Twine(byte_)) : Twine("")) + - ": " + what_arg); + if (byte_ != 0) + return parse_error(id_, byte_, fmt::format("[json.exception.parse_error.{}] parse error at {}: {}", id_, byte_, what_arg)); + else + return parse_error(id_, byte_, fmt::format("[json.exception.parse_error.{}] parse error: {}", id_, what_arg)); } -invalid_iterator invalid_iterator::create(int id_, const Twine& what_arg) +invalid_iterator invalid_iterator::create(int id_, std::string_view what_arg) { - return invalid_iterator(id_, "[json.exception.invalid_iterator." + Twine(id_) + "] " + what_arg); + return invalid_iterator(id_, fmt::format("[json.exception.invalid_iterator.{}] {}", id_, what_arg)); } -type_error type_error::create(int id_, const Twine& what_arg) +invalid_iterator invalid_iterator::create(int id_, std::string_view what_arg, std::string_view type_info) { - return type_error(id_, "[json.exception.type_error." + Twine(id_) + "] " + what_arg); + return invalid_iterator(id_, fmt::format("[json.exception.invalid_iterator.{}] {} {}", id_, what_arg, type_info)); } -out_of_range out_of_range::create(int id_, const Twine& what_arg) +type_error type_error::create(int id_, std::string_view what_arg) { - return out_of_range(id_, "[json.exception.out_of_range." + Twine(id_) + "] " + what_arg); + return type_error(id_, fmt::format("[json.exception.type_error.{}] {}", id_, what_arg)); } -other_error other_error::create(int id_, const Twine& what_arg) +type_error type_error::create(int id_, std::string_view what_arg, std::string_view type_info) { - return other_error(id_, "[json.exception.other_error." + Twine(id_) + "] " + what_arg); + return type_error(id_, fmt::format("[json.exception.type_error.{}] {} {}", id_, what_arg, type_info)); +} + +out_of_range out_of_range::create(int id_, std::string_view what_arg) +{ + return out_of_range(id_, fmt::format("[json.exception.out_of_range.{}] {}", id_, what_arg)); +} + +other_error other_error::create(int id_, std::string_view what_arg) +{ + return other_error(id_, fmt::format("[json.exception.other_error.{}] {}", id_, what_arg)); } } // namespace detail @@ -353,12 +365,12 @@ json::reference json::at(size_type idx) JSON_CATCH (std::out_of_range&) { // create better exception explanation - JSON_THROW(out_of_range::create(401, "array index " + Twine(idx) + " is out of range")); + JSON_THROW(out_of_range::create(401, fmt::format("array index {} is out of range", idx))); } } else { - JSON_THROW(type_error::create(304, "cannot use at() with " + Twine(type_name()))); + JSON_THROW(type_error::create(304, "cannot use at() with", type_name())); } } @@ -374,16 +386,16 @@ json::const_reference json::at(size_type idx) const JSON_CATCH (std::out_of_range&) { // create better exception explanation - JSON_THROW(out_of_range::create(401, "array index " + Twine(idx) + " is out of range")); + JSON_THROW(out_of_range::create(401, fmt::format("array index {} is out of range", idx))); } } else { - JSON_THROW(type_error::create(304, "cannot use at() with " + Twine(type_name()))); + JSON_THROW(type_error::create(304, "cannot use at() with", type_name())); } } -json::reference json::at(StringRef key) +json::reference json::at(std::string_view key) { // at only works for objects if (JSON_LIKELY(is_object())) @@ -392,17 +404,17 @@ json::reference json::at(StringRef key) if (it == m_value.object->end()) { // create better exception explanation - JSON_THROW(out_of_range::create(403, "key '" + Twine(key) + "' not found")); + JSON_THROW(out_of_range::create(403, fmt::format("key '{}' not found", key))); } return it->second; } else { - JSON_THROW(type_error::create(304, "cannot use at() with " + Twine(type_name()))); + JSON_THROW(type_error::create(304, "cannot use at() with", type_name())); } } -json::const_reference json::at(StringRef key) const +json::const_reference json::at(std::string_view key) const { // at only works for objects if (JSON_LIKELY(is_object())) @@ -411,13 +423,13 @@ json::const_reference json::at(StringRef key) const if (it == m_value.object->end()) { // create better exception explanation - JSON_THROW(out_of_range::create(403, "key '" + Twine(key) + "' not found")); + JSON_THROW(out_of_range::create(403, fmt::format("key '{}' not found", key))); } return it->second; } else { - JSON_THROW(type_error::create(304, "cannot use at() with " + Twine(type_name()))); + JSON_THROW(type_error::create(304, "cannot use at() with", type_name())); } } @@ -445,7 +457,7 @@ json::reference json::operator[](size_type idx) return m_value.array->operator[](idx); } - JSON_THROW(type_error::create(305, "cannot use operator[] with " + Twine(type_name()))); + JSON_THROW(type_error::create(305, "cannot use operator[] with", type_name())); } json::const_reference json::operator[](size_type idx) const @@ -456,10 +468,10 @@ json::const_reference json::operator[](size_type idx) const return m_value.array->operator[](idx); } - JSON_THROW(type_error::create(305, "cannot use operator[] with " + Twine(type_name()))); + JSON_THROW(type_error::create(305, "cannot use operator[] with", type_name())); } -json::reference json::operator[](StringRef key) +json::reference json::operator[](std::string_view key) { // implicitly convert null value to an empty object if (is_null()) @@ -475,10 +487,10 @@ json::reference json::operator[](StringRef key) return m_value.object->operator[](key); } - JSON_THROW(type_error::create(305, "cannot use operator[] with " + Twine(type_name()))); + JSON_THROW(type_error::create(305, "cannot use operator[] with", type_name())); } -json::const_reference json::operator[](StringRef key) const +json::const_reference json::operator[](std::string_view key) const { // const operator[] only works for objects if (JSON_LIKELY(is_object())) @@ -487,10 +499,10 @@ json::const_reference json::operator[](StringRef key) const return m_value.object->find(key)->second; } - JSON_THROW(type_error::create(305, "cannot use operator[] with " + Twine(type_name()))); + JSON_THROW(type_error::create(305, "cannot use operator[] with", type_name())); } -json::size_type json::erase(StringRef key) +json::size_type json::erase(std::string_view key) { // this erase only works for objects if (JSON_LIKELY(is_object())) @@ -498,7 +510,7 @@ json::size_type json::erase(StringRef key) return m_value.object->erase(key); } - JSON_THROW(type_error::create(307, "cannot use erase() with " + Twine(type_name()))); + JSON_THROW(type_error::create(307, "cannot use erase() with", type_name())); } void json::erase(const size_type idx) @@ -508,18 +520,18 @@ void json::erase(const size_type idx) { if (JSON_UNLIKELY(idx >= size())) { - JSON_THROW(out_of_range::create(401, "array index " + Twine(idx) + " is out of range")); + JSON_THROW(out_of_range::create(401, fmt::format("array index {} is out of range", idx))); } m_value.array->erase(m_value.array->begin() + static_cast(idx)); } else { - JSON_THROW(type_error::create(307, "cannot use erase() with " + Twine(type_name()))); + JSON_THROW(type_error::create(307, "cannot use erase() with", type_name())); } } -json::iterator json::find(StringRef key) +json::iterator json::find(std::string_view key) { auto result = end(); @@ -531,7 +543,7 @@ json::iterator json::find(StringRef key) return result; } -json::const_iterator json::find(StringRef key) const +json::const_iterator json::find(std::string_view key) const { auto result = cend(); @@ -543,7 +555,7 @@ json::const_iterator json::find(StringRef key) const return result; } -json::size_type json::count(StringRef key) const +json::size_type json::count(std::string_view key) const { // return 0 for all nonobject types return is_object() ? m_value.object->count(key) : 0; @@ -689,7 +701,7 @@ void json::push_back(json&& val) // push_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + Twine(type_name()))); + JSON_THROW(type_error::create(308, "cannot use push_back() with", type_name())); } // transform null object into an array @@ -711,7 +723,7 @@ void json::push_back(const json& val) // push_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + Twine(type_name()))); + JSON_THROW(type_error::create(308, "cannot use push_back() with", type_name())); } // transform null object into an array @@ -731,7 +743,7 @@ void json::push_back(initializer_list_t init) if (is_object() and init.size() == 2 and (*init.begin())->is_string()) { std::string key = init.begin()->moved_or_copied(); - push_back(std::pair(key, (init.begin() + 1)->moved_or_copied())); + push_back(std::pair(key, (init.begin() + 1)->moved_or_copied())); } else { @@ -756,7 +768,7 @@ json::iterator json::insert(const_iterator pos, const json& val) return result; } - JSON_THROW(type_error::create(309, "cannot use insert() with " + Twine(type_name()))); + JSON_THROW(type_error::create(309, "cannot use insert() with", type_name())); } json::iterator json::insert(const_iterator pos, size_type cnt, const json& val) @@ -776,7 +788,7 @@ json::iterator json::insert(const_iterator pos, size_type cnt, const json& val) return result; } - JSON_THROW(type_error::create(309, "cannot use insert() with " + Twine(type_name()))); + JSON_THROW(type_error::create(309, "cannot use insert() with", type_name())); } json::iterator json::insert(const_iterator pos, const_iterator first, const_iterator last) @@ -784,7 +796,7 @@ json::iterator json::insert(const_iterator pos, const_iterator first, const_iter // insert only works for arrays if (JSON_UNLIKELY(not is_array())) { - JSON_THROW(type_error::create(309, "cannot use insert() with " + Twine(type_name()))); + JSON_THROW(type_error::create(309, "cannot use insert() with", type_name())); } // check if iterator pos fits to this JSON value @@ -818,7 +830,7 @@ json::iterator json::insert(const_iterator pos, initializer_list_t ilist) // insert only works for arrays if (JSON_UNLIKELY(not is_array())) { - JSON_THROW(type_error::create(309, "cannot use insert() with " + Twine(type_name()))); + JSON_THROW(type_error::create(309, "cannot use insert() with", type_name())); } // check if iterator pos fits to this JSON value @@ -838,7 +850,7 @@ void json::insert(const_iterator first, const_iterator last) // insert only works for objects if (JSON_UNLIKELY(not is_object())) { - JSON_THROW(type_error::create(309, "cannot use insert() with " + Twine(type_name()))); + JSON_THROW(type_error::create(309, "cannot use insert() with", type_name())); } // check if range iterators belong to the same JSON object @@ -871,11 +883,11 @@ void json::update(const_reference j) if (JSON_UNLIKELY(not is_object())) { - JSON_THROW(type_error::create(312, "cannot use update() with " + Twine(type_name()))); + JSON_THROW(type_error::create(312, "cannot use update() with", type_name())); } if (JSON_UNLIKELY(not j.is_object())) { - JSON_THROW(type_error::create(312, "cannot use update() with " + Twine(j.type_name()))); + JSON_THROW(type_error::create(312, "cannot use update() with", j.type_name())); } for (auto it = j.cbegin(); it != j.cend(); ++it) @@ -896,7 +908,7 @@ void json::update(const_iterator first, const_iterator last) if (JSON_UNLIKELY(not is_object())) { - JSON_THROW(type_error::create(312, "cannot use update() with " + Twine(type_name()))); + JSON_THROW(type_error::create(312, "cannot use update() with", type_name())); } // check if range iterators belong to the same JSON object @@ -1156,7 +1168,7 @@ json json::patch(const json& json_patch) const if (JSON_UNLIKELY(static_cast(idx) > parent.size())) { // avoid undefined behavior - JSON_THROW(out_of_range::create(401, "array index " + Twine(idx) + " is out of range")); + JSON_THROW(out_of_range::create(401, fmt::format("array index {} is out of range", idx))); } else { @@ -1194,7 +1206,7 @@ json json::patch(const json& json_patch) const } else { - JSON_THROW(out_of_range::create(403, "key '" + Twine(last_path) + "' not found")); + JSON_THROW(out_of_range::create(403, fmt::format("key '{}' not found", last_path))); } } else if (parent.is_array()) @@ -1227,13 +1239,13 @@ json json::patch(const json& json_patch) const // check if desired value is present if (JSON_UNLIKELY(it == val.m_value.object->end())) { - JSON_THROW(parse_error::create(105, 0, Twine(error_msg) + " must have member '" + Twine(member) + "'")); + JSON_THROW(parse_error::create(105, 0, fmt::format("{} must have member '{}'", error_msg, member))); } // check if result is of type string if (JSON_UNLIKELY(string_type and not it->second.is_string())) { - JSON_THROW(parse_error::create(105, 0, Twine(error_msg) + " must have string member '" + Twine(member) + "'")); + JSON_THROW(parse_error::create(105, 0, fmt::format("{} must have string member '{}'", error_msg, member))); } // no error: return value @@ -1321,7 +1333,7 @@ json json::patch(const json& json_patch) const // throw an exception if test fails if (JSON_UNLIKELY(not success)) { - JSON_THROW(other_error::create(501, "unsuccessful: " + Twine(val.dump()))); + JSON_THROW(other_error::create(501, fmt::format("unsuccessful: {}", val.dump()))); } break; @@ -1331,7 +1343,7 @@ json json::patch(const json& json_patch) const { // op must be "add", "remove", "replace", "move", "copy", or // "test" - JSON_THROW(parse_error::create(105, 0, "operation value '" + Twine(op) + "' is invalid")); + JSON_THROW(parse_error::create(105, 0, fmt::format("operation value '{}' is invalid", op))); } } } @@ -1413,7 +1425,7 @@ json json::diff(const json& source, const json& target, for (auto it = source.cbegin(); it != source.cend(); ++it) { // escape the key name to be used in a JSON patch - const auto key = json_pointer::escape(it.key()); + const auto key = json_pointer::escape(std::string{it.key()}); if (target.find(it.key()) != target.end()) { @@ -1437,7 +1449,7 @@ json json::diff(const json& source, const json& target, if (source.find(it.key()) == source.end()) { // found a key that is not in this -> add it - const auto key = json_pointer::escape(it.key()); + const auto key = json_pointer::escape(std::string{it.key()}); result.push_back( { {"op", "add"}, {"path", path + "/" + key}, diff --git a/wpiutil/src/main/native/cpp/json_binary_reader.cpp b/wpiutil/src/main/native/cpp/json_binary_reader.cpp index 9298e924f0..86d28332cf 100644 --- a/wpiutil/src/main/native/cpp/json_binary_reader.cpp +++ b/wpiutil/src/main/native/cpp/json_binary_reader.cpp @@ -36,6 +36,7 @@ SOFTWARE. #include // ldexp +#include "fmt/format.h" #include "wpi/raw_istream.h" namespace wpi { @@ -711,7 +712,7 @@ json json::binary_reader::parse_cbor_internal(const bool get_char) default: // anything else (0xFF is handled inside the other types) { - JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + Twine::utohexstr(current))); + JSON_THROW(parse_error::create(112, chars_read, fmt::format("error reading CBOR; last byte: {:#02x}", current))); } } } @@ -1034,7 +1035,7 @@ json json::binary_reader::parse_msgpack_internal() default: // anything else { JSON_THROW(parse_error::create(112, chars_read, - "error reading MessagePack; last byte: 0x" + Twine::utohexstr(current))); + fmt::format("error reading MessagePack; last byte: {:#02x}", current))); } } } @@ -1106,7 +1107,8 @@ std::string json::binary_reader::get_cbor_string() default: { - JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + Twine::utohexstr(current))); + JSON_THROW(parse_error::create(113, chars_read, + fmt::format("expected a CBOR string; last byte: {:#02x}", current))); } } } @@ -1172,7 +1174,7 @@ std::string json::binary_reader::get_msgpack_string() default: { JSON_THROW(parse_error::create(113, chars_read, - "expected a MessagePack string; last byte: 0x" + Twine::utohexstr(current))); + fmt::format("expected a MessagePack string; last byte: {:#02x}", current))); } } } @@ -1200,7 +1202,7 @@ std::string json::binary_reader::get_ubjson_string(const bool get_char) return get_string(get_number()); default: JSON_THROW(parse_error::create(113, chars_read, - "expected a UBJSON string; last byte: 0x" + Twine::utohexstr(current))); + fmt::format("expected a UBJSON string; last byte: {:#02x}", current))); } } @@ -1220,7 +1222,7 @@ std::pair json::binary_reader::get_ubjson_size_type() if (current != '#') { JSON_THROW(parse_error::create(112, chars_read, - "expected '#' after UBJSON type information; last byte: 0x" + Twine::utohexstr(current))); + fmt::format("expected '#' after UBJSON type information; last byte: {:#02x}", current))); } sz = parse_ubjson_internal(); } @@ -1269,7 +1271,7 @@ json json::binary_reader::get_ubjson_value(const int prefix) if (JSON_UNLIKELY(current > 127)) { JSON_THROW(parse_error::create(113, chars_read, - "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + Twine::utohexstr(current))); + fmt::format("byte after 'C' must be in range 0x00..0x7F; last byte: {:#02x}", current))); } return std::string(1, static_cast(current)); } @@ -1285,7 +1287,7 @@ json json::binary_reader::get_ubjson_value(const int prefix) default: // anything else JSON_THROW(parse_error::create(112, chars_read, - "error reading UBJSON; last byte: 0x" + Twine::utohexstr(current))); + fmt::format("error reading UBJSON; last byte: {:#02x}", current))); } } @@ -1299,7 +1301,7 @@ json json::binary_reader::get_ubjson_array() if (JSON_UNLIKELY(size_and_type.first > result.max_size())) { JSON_THROW(out_of_range::create(408, - "excessive array size: " + Twine(size_and_type.first))); + fmt::format("excessive array size: {}", size_and_type.first))); } if (size_and_type.second != 0) @@ -1344,7 +1346,7 @@ json json::binary_reader::get_ubjson_object() if (JSON_UNLIKELY(size_and_type.first > result.max_size())) { JSON_THROW(out_of_range::create(408, - "excessive object size: " + Twine(size_and_type.first))); + fmt::format("excessive object size: {}", size_and_type.first))); } if (size_and_type.second != 0) diff --git a/wpiutil/src/main/native/cpp/json_binary_writer.cpp b/wpiutil/src/main/native/cpp/json_binary_writer.cpp index 2c0bbeea70..0b6e6b7a16 100644 --- a/wpiutil/src/main/native/cpp/json_binary_writer.cpp +++ b/wpiutil/src/main/native/cpp/json_binary_writer.cpp @@ -34,6 +34,7 @@ SOFTWARE. #define WPI_JSON_IMPLEMENTATION #include "wpi/json.h" +#include "fmt/format.h" #include "wpi/raw_ostream.h" namespace wpi { @@ -75,9 +76,9 @@ class json::binary_writer const bool use_type, const bool add_prefix = true); private: - void write_cbor_string(StringRef str); + void write_cbor_string(std::string_view str); - void write_msgpack_string(StringRef str); + void write_msgpack_string(std::string_view str); /* @brief write a number to output input @@ -630,7 +631,7 @@ void json::binary_writer::write_ubjson(const json& j, const bool use_count, o << static_cast('S'); } write_number_with_ubjson_prefix(j.m_value.string->size(), true); - o << j.m_value.string; + o << *j.m_value.string; break; } @@ -731,7 +732,7 @@ void json::binary_writer::write_ubjson(const json& j, const bool use_count, } } -void json::binary_writer::write_cbor_string(StringRef str) +void json::binary_writer::write_cbor_string(std::string_view str) { // step 1: write control byte and the string length const auto N = str.size(); @@ -766,7 +767,7 @@ void json::binary_writer::write_cbor_string(StringRef str) o << str; } -void json::binary_writer::write_msgpack_string(StringRef str) +void json::binary_writer::write_msgpack_string(std::string_view str) { // step 1: write control byte and the string length const auto N = str.size(); @@ -862,7 +863,7 @@ void json::binary_writer::write_number_with_ubjson_prefix(const NumberType n, } else { - JSON_THROW(out_of_range::create(407, "number overflow serializing " + Twine(n))); + JSON_THROW(out_of_range::create(407, fmt::format("number overflow serializing {}", n))); } } @@ -915,7 +916,7 @@ void json::binary_writer::write_number_with_ubjson_prefix(const NumberType n, // LCOV_EXCL_START else { - JSON_THROW(out_of_range::create(407, "number overflow serializing " + Twine(n))); + JSON_THROW(out_of_range::create(407, fmt::format("number overflow serializing {}", n))); } // LCOV_EXCL_STOP } diff --git a/wpiutil/src/main/native/cpp/json_parser.cpp b/wpiutil/src/main/native/cpp/json_parser.cpp index e0d7db36c4..bae8c118b6 100644 --- a/wpiutil/src/main/native/cpp/json_parser.cpp +++ b/wpiutil/src/main/native/cpp/json_parser.cpp @@ -38,7 +38,7 @@ SOFTWARE. #include #include -#include "wpi/Format.h" +#include "fmt/format.h" #include "wpi/SmallString.h" #include "wpi/raw_istream.h" #include "wpi/raw_ostream.h" @@ -336,7 +336,7 @@ class json::lexer } /// return current string value - StringRef get_string() + std::string_view get_string() { return token_buffer; } @@ -1407,7 +1407,7 @@ std::string json::lexer::get_token_string() const if (c <= '\x1F') { // escape control characters - ss << "'; + ss << fmt::format("", c); } else { @@ -1605,7 +1605,7 @@ void json::parser::parse_internal(bool keep, json& result) if (keep and keep_tag and not value.is_discarded()) { - result.m_value.object->try_emplace(StringRef(key.data(), key.size()), std::move(value)); + result.m_value.object->try_emplace(std::string_view(key.data(), key.size()), std::move(value)); } // comma -> next value @@ -1757,8 +1757,8 @@ void json::parser::parse_internal(bool keep, json& result) { if (allow_exceptions) { - JSON_THROW(out_of_range::create(406, "number overflow parsing '" + - Twine(m_lexer.get_token_string()) + "'")); + JSON_THROW(out_of_range::create(406, + fmt::format("number overflow parsing '{}'", m_lexer.get_token_string()))); } expect(token_type::uninitialized); } @@ -1917,7 +1917,7 @@ void json::parser::throw_exception() const JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg)); } -json json::parse(StringRef s, +json json::parse(std::string_view s, const parser_callback_t cb, const bool allow_exceptions) { @@ -1942,7 +1942,7 @@ json json::parse(raw_istream& i, return result; } -bool json::accept(StringRef s) +bool json::accept(std::string_view s) { raw_mem_istream is(makeArrayRef(s.data(), s.size())); return parser(is).accept(true); diff --git a/wpiutil/src/main/native/cpp/json_pointer.cpp b/wpiutil/src/main/native/cpp/json_pointer.cpp index 9cb1ec4fc3..51548b39c6 100644 --- a/wpiutil/src/main/native/cpp/json_pointer.cpp +++ b/wpiutil/src/main/native/cpp/json_pointer.cpp @@ -36,7 +36,9 @@ SOFTWARE. #include // accumulate +#include "fmt/format.h" #include "wpi/SmallString.h" +#include "wpi/StringExtras.h" namespace wpi { @@ -50,17 +52,16 @@ std::string json_pointer::to_string() const noexcept }); } -int json_pointer::array_index(const Twine& s) +int json_pointer::array_index(std::string_view s) { - SmallString<128> buf; - StringRef str = s.toNullTerminatedStringRef(buf); + SmallString<128> str{s}; std::size_t processed_chars = 0; - const int res = std::stoi(str, &processed_chars); + const int res = std::stoi(str.c_str(), &processed_chars); // check if the string was completely read if (JSON_UNLIKELY(processed_chars != str.size())) { - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + Twine(s) + "'")); + JSON_THROW(detail::out_of_range::create(404, fmt::format("unresolved reference token '{}'", s))); } return res; @@ -108,7 +109,7 @@ json& json_pointer::get_and_create(json& j) const } JSON_CATCH(std::invalid_argument&) { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + Twine(reference_token) + "' is not a number")); + JSON_THROW(detail::parse_error::create(109, 0, fmt::format("array index '{}' is not a number", reference_token))); } break; } @@ -164,8 +165,7 @@ json& json_pointer::get_unchecked(json* ptr) const if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, - "array index '" + Twine(reference_token) + - "' must not begin with '0'")); + fmt::format("array index '{}' must not begin with '0'", reference_token))); } if (reference_token == "-") @@ -183,14 +183,16 @@ json& json_pointer::get_unchecked(json* ptr) const } JSON_CATCH(std::invalid_argument&) { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + Twine(reference_token) + "' is not a number")); + JSON_THROW(detail::parse_error::create(109, 0, + fmt::format("array index '{}' is not a number", reference_token))); } } break; } default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + Twine(reference_token) + "'")); + JSON_THROW(detail::out_of_range::create(404, + fmt::format("unresolved reference token '{}'", reference_token))); } } @@ -217,16 +219,14 @@ json& json_pointer::get_checked(json* ptr) const { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + Twine(ptr->m_value.array->size()) + - ") is out of range")); + fmt::format("array index '-' ({}) is out of range", ptr->m_value.array->size()))); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, - "array index '" + Twine(reference_token) + - "' must not begin with '0'")); + fmt::format("array index '{}' must not begin with '0'", reference_token))); } // note: at performs range check @@ -236,13 +236,15 @@ json& json_pointer::get_checked(json* ptr) const } JSON_CATCH(std::invalid_argument&) { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + Twine(reference_token) + "' is not a number")); + JSON_THROW(detail::parse_error::create(109, 0, + fmt::format("array index '{}' is not a number", reference_token))); } break; } default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + Twine(reference_token) + "'")); + JSON_THROW(detail::out_of_range::create(404, + fmt::format("unresolved reference token '{}'", reference_token))); } } @@ -269,16 +271,14 @@ const json& json_pointer::get_unchecked(const json* ptr) const { // "-" cannot be used for const access JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + Twine(ptr->m_value.array->size()) + - ") is out of range")); + fmt::format("array index '-' ({}) is out of range", ptr->m_value.array->size()))); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, - "array index '" + Twine(reference_token) + - "' must not begin with '0'")); + fmt::format("array index '{}' must not begin with '0'", reference_token))); } // use unchecked array access @@ -289,13 +289,15 @@ const json& json_pointer::get_unchecked(const json* ptr) const } JSON_CATCH(std::invalid_argument&) { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + Twine(reference_token) + "' is not a number")); + JSON_THROW(detail::parse_error::create(109, 0, + fmt::format("array index '{}' is not a number", reference_token))); } break; } default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + Twine(reference_token) + "'")); + JSON_THROW(detail::out_of_range::create(404, + fmt::format("unresolved reference token '{}'", reference_token))); } } @@ -322,16 +324,14 @@ const json& json_pointer::get_checked(const json* ptr) const { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + Twine(ptr->m_value.array->size()) + - ") is out of range")); + fmt::format("array index '-' ({}) is out of range", ptr->m_value.array->size()))); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, - "array index '" + Twine(reference_token) + - "' must not begin with '0'")); + fmt::format("array index '{}' must not begin with '0'", reference_token))); } // note: at performs range check @@ -341,23 +341,23 @@ const json& json_pointer::get_checked(const json* ptr) const } JSON_CATCH(std::invalid_argument&) { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + Twine(reference_token) + "' is not a number")); + JSON_THROW(detail::parse_error::create(109, 0, + fmt::format("array index '{}' is not a number", reference_token))); } break; } default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + Twine(reference_token) + "'")); + JSON_THROW(detail::out_of_range::create(404, + fmt::format("unresolved reference token '{}'", reference_token))); } } return *ptr; } -std::vector json_pointer::split(const Twine& reference_string) +std::vector json_pointer::split(std::string_view ref_str) { - SmallString<128> ref_str_buf; - StringRef ref_str = reference_string.toStringRef(ref_str_buf); std::vector result; // special case: empty reference string -> no reference tokens @@ -370,8 +370,7 @@ std::vector json_pointer::split(const Twine& reference_string) if (JSON_UNLIKELY(ref_str[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, - "JSON pointer must be empty or begin with '/' - was: '" + - Twine(ref_str) + "'")); + fmt::format("JSON pointer must be empty or begin with '/' - was: '{}'", ref_str))); } // extract the reference tokens: @@ -392,11 +391,11 @@ std::vector json_pointer::split(const Twine& reference_string) { // use the text between the beginning of the reference token // (start) and the last slash (slash). - auto reference_token = ref_str.slice(start, slash); + auto reference_token = slice(ref_str, start, slash); // check reference tokens are properly escaped for (std::size_t pos = reference_token.find_first_of('~'); - pos != StringRef::npos; + pos != std::string_view::npos; pos = reference_token.find_first_of('~', pos + 1)) { assert(reference_token[pos] == '~'); @@ -411,7 +410,7 @@ std::vector json_pointer::split(const Twine& reference_string) } // finally, store the reference token - std::string ref_tok = reference_token; + std::string ref_tok{reference_token}; unescape(ref_tok); result.emplace_back(std::move(ref_tok)); } @@ -444,7 +443,7 @@ void json_pointer::unescape(std::string& s) replace_substring(s, "~0", "~"); } -void json_pointer::flatten(const Twine& reference_string, +void json_pointer::flatten(std::string_view reference_string, const json& value, json& result) { @@ -455,15 +454,14 @@ void json_pointer::flatten(const Twine& reference_string, if (value.m_value.array->empty()) { // flatten empty array as null - SmallString<64> buf; - result[reference_string.toStringRef(buf)] = nullptr; + result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_value.array->size(); ++i) { - flatten(reference_string + "/" + Twine(i), + flatten(fmt::format("{}/{}", reference_string, i), value.m_value.array->operator[](i), result); } } @@ -475,15 +473,14 @@ void json_pointer::flatten(const Twine& reference_string, if (value.m_value.object->empty()) { // flatten empty object as null - SmallString<64> buf; - result[reference_string.toStringRef(buf)] = nullptr; + result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_value.object) { - flatten(reference_string + "/" + Twine(escape(element.first())), element.second, result); + flatten(fmt::format("{}/{}", reference_string, escape(std::string{element.first()})), element.second, result); } } break; @@ -492,8 +489,7 @@ void json_pointer::flatten(const Twine& reference_string, default: { // add primitive value with its reference string - SmallString<64> buf; - result[reference_string.toStringRef(buf)] = value; + result[reference_string] = value; break; } } diff --git a/wpiutil/src/main/native/cpp/json_serializer.cpp b/wpiutil/src/main/native/cpp/json_serializer.cpp index 8ab92b12cc..4f71bc817e 100644 --- a/wpiutil/src/main/native/cpp/json_serializer.cpp +++ b/wpiutil/src/main/native/cpp/json_serializer.cpp @@ -34,9 +34,8 @@ SOFTWARE. #define WPI_JSON_IMPLEMENTATION #include "wpi/json.h" -#include "wpi/Format.h" +#include "fmt/format.h" #include "wpi/SmallString.h" -#include "wpi/StringExtras.h" #include "wpi/raw_os_ostream.h" #include "json_serializer.h" @@ -1332,7 +1331,7 @@ void json::serializer::dump(const json& val, const bool pretty_print, } } -void json::serializer::dump_escaped(StringRef s, const bool ensure_ascii) +void json::serializer::dump_escaped(std::string_view s, const bool ensure_ascii) { uint32_t codepoint; uint8_t state = UTF8_ACCEPT; @@ -1397,12 +1396,12 @@ void json::serializer::dump_escaped(StringRef s, const bool ensure_ascii) { if (codepoint <= 0xFFFF) { - o << '\\' << 'u' << format_hex_no_prefix(codepoint, 4); + o << fmt::format("\\u{:04x}", codepoint); } else { - o << '\\' << 'u' << format_hex_no_prefix(0xD7C0 + (codepoint >> 10), 4); - o << '\\' << 'u' << format_hex_no_prefix(0xDC00 + (codepoint & 0x3FF), 4); + o << fmt::format("\\u{:04x}", 0xD7C0 + (codepoint >> 10)); + o << fmt::format("\\u{:04x}", 0xDC00 + (codepoint & 0x3FF)); } } else @@ -1419,7 +1418,7 @@ void json::serializer::dump_escaped(StringRef s, const bool ensure_ascii) case UTF8_REJECT: // decode found invalid UTF-8 byte { - JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + Twine(i) + ": 0x" + Twine::utohexstr(byte))); + JSON_THROW(type_error::create(316, fmt::format("invalid UTF-8 byte at index {}: {:#02x}", i, byte))); } default: // decode found yet incomplete multi-byte code point @@ -1437,7 +1436,7 @@ void json::serializer::dump_escaped(StringRef s, const bool ensure_ascii) if (JSON_UNLIKELY(state != UTF8_ACCEPT)) { // we finish reading, but do not accept: string was incomplete - JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + Twine::utohexstr(static_cast(s.back())))); + JSON_THROW(type_error::create(316, fmt::format("incomplete UTF-8 string; last byte: {:#02x}", s.back()))); } } diff --git a/wpiutil/src/main/native/cpp/json_serializer.h b/wpiutil/src/main/native/cpp/json_serializer.h index 6c5ffbe477..35907a24a9 100644 --- a/wpiutil/src/main/native/cpp/json_serializer.h +++ b/wpiutil/src/main/native/cpp/json_serializer.h @@ -98,7 +98,7 @@ class json::serializer @complexity Linear in the length of string @a s. */ - void dump_escaped(StringRef s, const bool ensure_ascii); + void dump_escaped(std::string_view s, const bool ensure_ascii); template , int> = 0> diff --git a/wpiutil/src/main/native/cpp/llvm/ConvertUTF.cpp b/wpiutil/src/main/native/cpp/llvm/ConvertUTF.cpp index 2594d9a8de..3050e631f2 100644 --- a/wpiutil/src/main/native/cpp/llvm/ConvertUTF.cpp +++ b/wpiutil/src/main/native/cpp/llvm/ConvertUTF.cpp @@ -744,10 +744,10 @@ ConversionResult ConvertUTF8toUTF32(const UTF8 **sourceStart, namespace sys { namespace windows { std::error_code CodePageToUTF16(unsigned codepage, - wpi::StringRef original, + std::string_view original, wpi::SmallVectorImpl &utf16) { if (!original.empty()) { - int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(), + int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.data(), original.size(), utf16.begin(), 0); if (len == 0) { @@ -757,7 +757,7 @@ std::error_code CodePageToUTF16(unsigned codepage, utf16.reserve(len + 1); utf16.set_size(len); - len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(), + len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.data(), original.size(), utf16.begin(), utf16.size()); if (len == 0) { @@ -772,12 +772,12 @@ std::error_code CodePageToUTF16(unsigned codepage, return std::error_code(); } -std::error_code UTF8ToUTF16(wpi::StringRef utf8, +std::error_code UTF8ToUTF16(std::string_view utf8, wpi::SmallVectorImpl &utf16) { return CodePageToUTF16(CP_UTF8, utf8, utf16); } -std::error_code CurCPToUTF16(wpi::StringRef curcp, +std::error_code CurCPToUTF16(std::string_view curcp, wpi::SmallVectorImpl &utf16) { return CodePageToUTF16(CP_ACP, curcp, utf16); } diff --git a/wpiutil/src/main/native/cpp/llvm/ConvertUTFWrapper.cpp b/wpiutil/src/main/native/cpp/llvm/ConvertUTFWrapper.cpp index 3402988d4e..bf9b1ad745 100644 --- a/wpiutil/src/main/native/cpp/llvm/ConvertUTFWrapper.cpp +++ b/wpiutil/src/main/native/cpp/llvm/ConvertUTFWrapper.cpp @@ -80,7 +80,7 @@ bool convertUTF16ToUTF8String(ArrayRef SrcUTF16, return true; } -bool convertUTF8ToUTF16String(StringRef SrcUTF8, +bool convertUTF8ToUTF16String(std::string_view SrcUTF8, SmallVectorImpl &DstUTF16) { assert(DstUTF16.empty()); @@ -91,8 +91,8 @@ bool convertUTF8ToUTF16String(StringRef SrcUTF8, return true; } - const UTF8 *Src = reinterpret_cast(SrcUTF8.begin()); - const UTF8 *SrcEnd = reinterpret_cast(SrcUTF8.end()); + const UTF8 *Src = reinterpret_cast(SrcUTF8.data()); + const UTF8 *SrcEnd = reinterpret_cast(SrcUTF8.data() + SrcUTF8.size()); // Allocate the same number of UTF-16 code units as UTF-8 code units. Encoding // as UTF-16 should always require the same amount or less code units than the diff --git a/wpiutil/src/main/native/cpp/llvm/Error.cpp b/wpiutil/src/main/native/cpp/llvm/Error.cpp deleted file mode 100644 index 7bf9c5f4de..0000000000 --- a/wpiutil/src/main/native/cpp/llvm/Error.cpp +++ /dev/null @@ -1,138 +0,0 @@ -//===----- lib/Support/Error.cpp - Error and associated utilities ---------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "wpi/Error.h" -#include "wpi/Twine.h" -#include "wpi/ErrorHandling.h" -#include "wpi/ManagedStatic.h" -#include - -using namespace wpi; - -namespace { - - enum class ErrorErrorCode : int { - MultipleErrors = 1, - FileError, - InconvertibleError - }; - - // FIXME: This class is only here to support the transition to wpi::Error. It - // will be removed once this transition is complete. Clients should prefer to - // deal with the Error value directly, rather than converting to error_code. - class ErrorErrorCategory : public std::error_category { - public: - const char *name() const noexcept override { return "Error"; } - - std::string message(int condition) const override { - switch (static_cast(condition)) { - case ErrorErrorCode::MultipleErrors: - return "Multiple errors"; - case ErrorErrorCode::InconvertibleError: - return "Inconvertible error value. An error has occurred that could " - "not be converted to a known std::error_code. Please file a " - "bug."; - case ErrorErrorCode::FileError: - return "A file error occurred."; - } - wpi_unreachable("Unhandled error code"); - } - }; - -} - -static ManagedStatic ErrorErrorCat; - -namespace wpi { - -void ErrorInfoBase::anchor() {} -char ErrorInfoBase::ID = 0; -char ErrorList::ID = 0; -void ECError::anchor() {} -char ECError::ID = 0; -char StringError::ID = 0; -char FileError::ID = 0; - -void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner) { - if (!E) - return; - OS << ErrorBanner; - handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { - EI.log(OS); - OS << "\n"; - }); -} - - -std::error_code ErrorList::convertToErrorCode() const { - return std::error_code(static_cast(ErrorErrorCode::MultipleErrors), - *ErrorErrorCat); -} - -std::error_code inconvertibleErrorCode() { - return std::error_code(static_cast(ErrorErrorCode::InconvertibleError), - *ErrorErrorCat); -} - -std::error_code FileError::convertToErrorCode() const { - return std::error_code(static_cast(ErrorErrorCode::FileError), - *ErrorErrorCat); -} - -Error errorCodeToError(std::error_code EC) { - if (!EC) - return Error::success(); - return Error(std::make_unique(ECError(EC))); -} - -std::error_code errorToErrorCode(Error Err) { - std::error_code EC; - handleAllErrors(std::move(Err), [&](const ErrorInfoBase &EI) { - EC = EI.convertToErrorCode(); - }); - if (EC == inconvertibleErrorCode()) - report_fatal_error(EC.message()); - return EC; -} - -StringError::StringError(std::error_code EC, const Twine &S) - : Msg(S.str()), EC(EC) {} - -StringError::StringError(const Twine &S, std::error_code EC) - : Msg(S.str()), EC(EC), PrintMsgOnly(true) {} - -void StringError::log(raw_ostream &OS) const { - if (PrintMsgOnly) { - OS << Msg; - } else { - OS << EC.message(); - if (!Msg.empty()) - OS << (" " + Msg); - } -} - -std::error_code StringError::convertToErrorCode() const { - return EC; -} - -Error createStringError(std::error_code EC, char const *Msg) { - return make_error(Msg, EC); -} - -void report_fatal_error(Error Err, bool GenCrashDiag) { - assert(Err && "report_fatal_error called with success value"); - std::string ErrMsg; - { - raw_string_ostream ErrStream(ErrMsg); - logAllUnhandledErrors(std::move(Err), ErrStream); - } - report_fatal_error(ErrMsg); -} - -} // end namespace wpi diff --git a/wpiutil/src/main/native/cpp/llvm/ErrorHandling.cpp b/wpiutil/src/main/native/cpp/llvm/ErrorHandling.cpp index ef79456779..8e522c4193 100644 --- a/wpiutil/src/main/native/cpp/llvm/ErrorHandling.cpp +++ b/wpiutil/src/main/native/cpp/llvm/ErrorHandling.cpp @@ -14,11 +14,10 @@ #include "wpi/ErrorHandling.h" #include "wpi/SmallVector.h" -#include "wpi/Twine.h" -#include "wpi/Error.h" #include "wpi/WindowsError.h" -#include "wpi/raw_ostream.h" +#include "fmt/format.h" #include +#include #include #include #include @@ -68,18 +67,14 @@ void wpi::remove_fatal_error_handler() { } void wpi::report_fatal_error(const char *Reason, bool GenCrashDiag) { - report_fatal_error(Twine(Reason), GenCrashDiag); + report_fatal_error(std::string_view(Reason), GenCrashDiag); } void wpi::report_fatal_error(const std::string &Reason, bool GenCrashDiag) { - report_fatal_error(Twine(Reason), GenCrashDiag); + report_fatal_error(std::string_view(Reason), GenCrashDiag); } -void wpi::report_fatal_error(StringRef Reason, bool GenCrashDiag) { - report_fatal_error(Twine(Reason), GenCrashDiag); -} - -void wpi::report_fatal_error(const Twine &Reason, bool GenCrashDiag) { +void wpi::report_fatal_error(std::string_view Reason, bool GenCrashDiag) { wpi::fatal_error_handler_t handler = nullptr; void* handlerData = nullptr; { @@ -91,21 +86,9 @@ void wpi::report_fatal_error(const Twine &Reason, bool GenCrashDiag) { } if (handler) { - handler(handlerData, Reason.str(), GenCrashDiag); + handler(handlerData, std::string{Reason}, GenCrashDiag); } else { - // Blast the result out to stderr. We don't try hard to make sure this - // succeeds (e.g. handling EINTR) and we can't use errs() here because - // raw ostreams can call report_fatal_error. - SmallVector Buffer; - raw_svector_ostream OS(Buffer); - OS << "LLVM ERROR: " << Reason << "\n"; - StringRef MessageStr = OS.str(); -#ifdef _WIN32 - int written = ::_write(2, MessageStr.data(), MessageStr.size()); -#else - ssize_t written = ::write(2, MessageStr.data(), MessageStr.size()); -#endif - (void)written; // If something went wrong, we deliberately just give up. + fmt::print(stderr, "LLVM ERROR: {}\n"); } exit(1); @@ -185,11 +168,11 @@ void wpi::wpi_unreachable_internal(const char *msg, const char *file, // wpi_unreachable is intended to be used to indicate "impossible" // situations, and not legitimate runtime errors. if (msg) - errs() << msg << "\n"; - errs() << "UNREACHABLE executed"; + fmt::print(stderr, "{}\n", msg); + std::fputs("UNREACHABLE executed", stderr); if (file) - errs() << " at " << file << ":" << line; - errs() << "!\n"; + fmt::print(stderr, " at {}:{}", file, line); + fmt::print(stderr, "{}", "!\n"); abort(); #ifdef LLVM_BUILTIN_UNREACHABLE // Windows systems and possibly others don't declare abort() to be noreturn, diff --git a/wpiutil/src/main/native/cpp/llvm/NativeFormatting.cpp b/wpiutil/src/main/native/cpp/llvm/NativeFormatting.cpp deleted file mode 100644 index 985e269d58..0000000000 --- a/wpiutil/src/main/native/cpp/llvm/NativeFormatting.cpp +++ /dev/null @@ -1,264 +0,0 @@ -//===- NativeFormatting.cpp - Low level formatting helpers -------*- C++-*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "wpi/NativeFormatting.h" - -#include "wpi/ArrayRef.h" -#include "wpi/SmallString.h" -#include "wpi/StringExtras.h" -#include "wpi/Format.h" - -#include - -using namespace wpi; - -template -static int format_to_buffer(T Value, char (&Buffer)[N]) { - char *EndPtr = std::end(Buffer); - char *CurPtr = EndPtr; - - do { - *--CurPtr = '0' + char(Value % 10); - Value /= 10; - } while (Value); - return EndPtr - CurPtr; -} - -static void writeWithCommas(raw_ostream &S, ArrayRef Buffer) { - assert(!Buffer.empty()); - - ArrayRef ThisGroup; - int InitialDigits = ((Buffer.size() - 1) % 3) + 1; - ThisGroup = Buffer.take_front(InitialDigits); - S.write(ThisGroup.data(), ThisGroup.size()); - - Buffer = Buffer.drop_front(InitialDigits); - assert(Buffer.size() % 3 == 0); - while (!Buffer.empty()) { - S << ','; - ThisGroup = Buffer.take_front(3); - S.write(ThisGroup.data(), 3); - Buffer = Buffer.drop_front(3); - } -} - -template -static void write_unsigned_impl(raw_ostream &S, T N, size_t MinDigits, - IntegerStyle Style, bool IsNegative) { - static_assert(std::is_unsigned::value, "Value is not unsigned!"); - - char NumberBuffer[128]; - std::memset(NumberBuffer, '0', sizeof(NumberBuffer)); - - size_t Len = 0; - Len = format_to_buffer(N, NumberBuffer); - - if (IsNegative) - S << '-'; - - if (Len < MinDigits && Style != IntegerStyle::Number) { - for (size_t I = Len; I < MinDigits; ++I) - S << '0'; - } - - if (Style == IntegerStyle::Number) { - writeWithCommas(S, ArrayRef(std::end(NumberBuffer) - Len, Len)); - } else { - S.write(std::end(NumberBuffer) - Len, Len); - } -} - -template -static void write_unsigned(raw_ostream &S, T N, size_t MinDigits, - IntegerStyle Style, bool IsNegative = false) { - // Output using 32-bit div/mod if possible. - if (N == static_cast(N)) - write_unsigned_impl(S, static_cast(N), MinDigits, Style, - IsNegative); - else - write_unsigned_impl(S, N, MinDigits, Style, IsNegative); -} - -template -static void write_signed(raw_ostream &S, T N, size_t MinDigits, - IntegerStyle Style) { - static_assert(std::is_signed::value, "Value is not signed!"); - - using UnsignedT = typename std::make_unsigned::type; - - if (N >= 0) { - write_unsigned(S, static_cast(N), MinDigits, Style); - return; - } - - UnsignedT UN = -(UnsignedT)N; - write_unsigned(S, UN, MinDigits, Style, true); -} - -void wpi::write_integer(raw_ostream &S, unsigned int N, size_t MinDigits, - IntegerStyle Style) { - write_unsigned(S, N, MinDigits, Style); -} - -void wpi::write_integer(raw_ostream &S, int N, size_t MinDigits, - IntegerStyle Style) { - write_signed(S, N, MinDigits, Style); -} - -void wpi::write_integer(raw_ostream &S, unsigned long N, size_t MinDigits, - IntegerStyle Style) { - write_unsigned(S, N, MinDigits, Style); -} - -void wpi::write_integer(raw_ostream &S, long N, size_t MinDigits, - IntegerStyle Style) { - write_signed(S, N, MinDigits, Style); -} - -void wpi::write_integer(raw_ostream &S, unsigned long long N, size_t MinDigits, - IntegerStyle Style) { - write_unsigned(S, N, MinDigits, Style); -} - -void wpi::write_integer(raw_ostream &S, long long N, size_t MinDigits, - IntegerStyle Style) { - write_signed(S, N, MinDigits, Style); -} - -void wpi::write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, - std::optional Width) { - const size_t kMaxWidth = 128u; - - size_t W = std::min(kMaxWidth, Width.value_or(0u)); - - unsigned Nibbles = (64 - countLeadingZeros(N) + 3) / 4; - bool Prefix = (Style == HexPrintStyle::PrefixLower || - Style == HexPrintStyle::PrefixUpper); - bool Upper = - (Style == HexPrintStyle::Upper || Style == HexPrintStyle::PrefixUpper); - unsigned PrefixChars = Prefix ? 2 : 0; - unsigned NumChars = - std::max(static_cast(W), std::max(1u, Nibbles) + PrefixChars); - - char NumberBuffer[kMaxWidth]; - ::memset(NumberBuffer, '0', wpi::array_lengthof(NumberBuffer)); - if (Prefix) - NumberBuffer[1] = 'x'; - char *EndPtr = NumberBuffer + NumChars; - char *CurPtr = EndPtr; - while (N) { - unsigned char x = static_cast(N) % 16; - *--CurPtr = hexdigit(x, !Upper); - N /= 16; - } - - S.write(NumberBuffer, NumChars); -} - -void wpi::write_double(raw_ostream &S, double N, FloatStyle Style, - std::optional Precision) { - size_t Prec = Precision.value_or(getDefaultPrecision(Style)); - - if (std::isnan(N)) { - S << "nan"; - return; - } else if (std::isinf(N)) { - S << "INF"; - return; - } - - char Letter; - if (Style == FloatStyle::Exponent) - Letter = 'e'; - else if (Style == FloatStyle::ExponentUpper) - Letter = 'E'; - else - Letter = 'f'; - - SmallString<8> Spec; - wpi::raw_svector_ostream Out(Spec); - Out << "%." << Prec << Letter; - - if (Style == FloatStyle::Exponent || Style == FloatStyle::ExponentUpper) { -#ifdef _WIN32 -// On MSVCRT and compatible, output of %e is incompatible to Posix -// by default. Number of exponent digits should be at least 2. "%+03d" -// FIXME: Implement our formatter to here or Support/Format.h! -#if defined(__MINGW32__) - // FIXME: It should be generic to C++11. - if (N == 0.0 && std::signbit(N)) { - char NegativeZero[] = "-0.000000e+00"; - if (Style == FloatStyle::ExponentUpper) - NegativeZero[strlen(NegativeZero) - 4] = 'E'; - S << NegativeZero; - return; - } -#else - int fpcl = _fpclass(N); - - // negative zero - if (fpcl == _FPCLASS_NZ) { - char NegativeZero[] = "-0.000000e+00"; - if (Style == FloatStyle::ExponentUpper) - NegativeZero[strlen(NegativeZero) - 4] = 'E'; - S << NegativeZero; - return; - } -#endif - - char buf[32]; - unsigned len; - len = format(Spec.c_str(), N).snprint(buf, sizeof(buf)); - if (len <= sizeof(buf) - 2) { - if (len >= 5 && (buf[len - 5] == 'e' || buf[len - 5] == 'E') && - buf[len - 3] == '0') { - int cs = buf[len - 4]; - if (cs == '+' || cs == '-') { - int c1 = buf[len - 2]; - int c0 = buf[len - 1]; - if (isdigit(static_cast(c1)) && - isdigit(static_cast(c0))) { - // Trim leading '0': "...e+012" -> "...e+12\0" - buf[len - 3] = c1; - buf[len - 2] = c0; - buf[--len] = 0; - } - } - } - S << buf; - return; - } -#endif - } - - if (Style == FloatStyle::Percent) - N *= 100.0; - - char Buf[32]; - format(Spec.c_str(), N).snprint(Buf, sizeof(Buf)); - S << Buf; - if (Style == FloatStyle::Percent) - S << '%'; -} - -bool wpi::isPrefixedHexStyle(HexPrintStyle S) { - return (S == HexPrintStyle::PrefixLower || S == HexPrintStyle::PrefixUpper); -} - -size_t wpi::getDefaultPrecision(FloatStyle Style) { - switch (Style) { - case FloatStyle::Exponent: - case FloatStyle::ExponentUpper: - return 6; // Number of decimal places. - case FloatStyle::Fixed: - case FloatStyle::Percent: - return 2; // Number of decimal places. - } - LLVM_BUILTIN_UNREACHABLE; -} diff --git a/wpiutil/src/main/native/cpp/llvm/StringMap.cpp b/wpiutil/src/main/native/cpp/llvm/StringMap.cpp index f89a8aebea..768801d848 100644 --- a/wpiutil/src/main/native/cpp/llvm/StringMap.cpp +++ b/wpiutil/src/main/native/cpp/llvm/StringMap.cpp @@ -89,7 +89,7 @@ void StringMapImpl::init(unsigned InitSize) { /// specified bucket will be non-null. Otherwise, it will be null. In either /// case, the FullHashValue field of the bucket will be set to the hash value /// of the string. -unsigned StringMapImpl::LookupBucketFor(StringRef Name) { +unsigned StringMapImpl::LookupBucketFor(std::string_view Name) { unsigned HTSize = NumBuckets; if (HTSize == 0) { // Hash table unallocated so far? init(16); @@ -128,7 +128,7 @@ unsigned StringMapImpl::LookupBucketFor(StringRef Name) { // Do the comparison like this because Name isn't necessarily // null-terminated! char *ItemStr = (char*)BucketItem+ItemSize; - if (Name == StringRef(ItemStr, BucketItem->getKeyLength())) { + if (Name == std::string_view(ItemStr, BucketItem->getKeyLength())) { // We found a match! return BucketNo; } @@ -146,7 +146,7 @@ unsigned StringMapImpl::LookupBucketFor(StringRef Name) { /// FindKey - Look up the bucket that contains the specified key. If it exists /// in the map, return the bucket number of the key. Otherwise return -1. /// This does not modify the map. -int StringMapImpl::FindKey(StringRef Key) const { +int StringMapImpl::FindKey(std::string_view Key) const { unsigned HTSize = NumBuckets; if (HTSize == 0) return -1; // Really empty table? unsigned FullHashValue = HashString(Key); @@ -171,7 +171,7 @@ int StringMapImpl::FindKey(StringRef Key) const { // Do the comparison like this because NameStart isn't necessarily // null-terminated! char *ItemStr = (char*)BucketItem+ItemSize; - if (Key == StringRef(ItemStr, BucketItem->getKeyLength())) { + if (Key == std::string_view(ItemStr, BucketItem->getKeyLength())) { // We found a match! return BucketNo; } @@ -190,14 +190,14 @@ int StringMapImpl::FindKey(StringRef Key) const { /// delete it. This aborts if the value isn't in the table. void StringMapImpl::RemoveKey(StringMapEntryBase *V) { const char *VStr = (char*)V + ItemSize; - StringMapEntryBase *V2 = RemoveKey(StringRef(VStr, V->getKeyLength())); + StringMapEntryBase *V2 = RemoveKey(std::string_view(VStr, V->getKeyLength())); (void)V2; assert(V == V2 && "Didn't find key?"); } /// RemoveKey - Remove the StringMapEntry for the specified key from the /// table, returning it. If the key is not in the table, this returns null. -StringMapEntryBase *StringMapImpl::RemoveKey(StringRef Key) { +StringMapEntryBase *StringMapImpl::RemoveKey(std::string_view Key) { int Bucket = FindKey(Key); if (Bucket == -1) return nullptr; diff --git a/wpiutil/src/main/native/cpp/llvm/StringRef.cpp b/wpiutil/src/main/native/cpp/llvm/StringRef.cpp deleted file mode 100644 index ea44bead79..0000000000 --- a/wpiutil/src/main/native/cpp/llvm/StringRef.cpp +++ /dev/null @@ -1,507 +0,0 @@ -//===-- StringRef.cpp - Lightweight String References ---------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "wpi/StringRef.h" -#include "wpi/Hashing.h" -#include "wpi/StringExtras.h" -#include "wpi/SmallVector.h" -#include -#include -#include - -using namespace wpi; - -// MSVC emits references to this into the translation units which reference it. -#ifndef _MSC_VER -const size_t StringRef::npos; -#endif - -// strncasecmp() is not available on non-POSIX systems, so define an -// alternative function here. -static int ascii_strncasecmp(const char *LHS, const char *RHS, size_t Length) noexcept { - for (size_t I = 0; I < Length; ++I) { - unsigned char LHC = toLower(LHS[I]); - unsigned char RHC = toLower(RHS[I]); - if (LHC != RHC) - return LHC < RHC ? -1 : 1; - } - return 0; -} - -/// compare_lower - Compare strings, ignoring case. -int StringRef::compare_lower(StringRef RHS) const noexcept { - if (int Res = ascii_strncasecmp(Data, RHS.Data, std::min(Length, RHS.Length))) - return Res; - if (Length == RHS.Length) - return 0; - return Length < RHS.Length ? -1 : 1; -} - -/// Check if this string starts with the given \p Prefix, ignoring case. -bool StringRef::startswith_lower(StringRef Prefix) const noexcept { - return Length >= Prefix.Length && - ascii_strncasecmp(Data, Prefix.Data, Prefix.Length) == 0; -} - -/// Check if this string ends with the given \p Suffix, ignoring case. -bool StringRef::endswith_lower(StringRef Suffix) const noexcept { - return Length >= Suffix.Length && - ascii_strncasecmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0; -} - -size_t StringRef::find_lower(char C, size_t From) const noexcept { - char L = toLower(C); - return find_if([L](char D) { return toLower(D) == L; }, From); -} - -/// compare_numeric - Compare strings, handle embedded numbers. -int StringRef::compare_numeric(StringRef RHS) const noexcept { - for (size_t I = 0, E = std::min(Length, RHS.Length); I != E; ++I) { - // Check for sequences of digits. - if (isDigit(Data[I]) && isDigit(RHS.Data[I])) { - // The longer sequence of numbers is considered larger. - // This doesn't really handle prefixed zeros well. - size_t J; - for (J = I + 1; J != E + 1; ++J) { - bool ld = J < Length && isDigit(Data[J]); - bool rd = J < RHS.Length && isDigit(RHS.Data[J]); - if (ld != rd) - return rd ? -1 : 1; - if (!rd) - break; - } - // The two number sequences have the same length (J-I), just memcmp them. - if (int Res = compareMemory(Data + I, RHS.Data + I, J - I)) - return Res < 0 ? -1 : 1; - // Identical number sequences, continue search after the numbers. - I = J - 1; - continue; - } - if (Data[I] != RHS.Data[I]) - return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1; - } - if (Length == RHS.Length) - return 0; - return Length < RHS.Length ? -1 : 1; -} - -//===----------------------------------------------------------------------===// -// String Operations -//===----------------------------------------------------------------------===// - -std::string StringRef::lower() const { - std::string Result(size(), char()); - for (size_type i = 0, e = size(); i != e; ++i) { - Result[i] = toLower(Data[i]); - } - return Result; -} - -std::string StringRef::upper() const { - std::string Result(size(), char()); - for (size_type i = 0, e = size(); i != e; ++i) { - Result[i] = toUpper(Data[i]); - } - return Result; -} - -//===----------------------------------------------------------------------===// -// String Searching -//===----------------------------------------------------------------------===// - - -/// find - Search for the first string \arg Str in the string. -/// -/// \return - The index of the first occurrence of \arg Str, or npos if not -/// found. -size_t StringRef::find(StringRef Str, size_t From) const noexcept { - if (From > Length) - return npos; - - const char *Start = Data + From; - size_t Size = Length - From; - - const char *Needle = Str.data(); - size_t N = Str.size(); - if (N == 0) - return From; - if (Size < N) - return npos; - if (N == 1) { - const char *Ptr = (const char *)::memchr(Start, Needle[0], Size); - return Ptr == nullptr ? npos : Ptr - Data; - } - - const char *Stop = Start + (Size - N + 1); - - // For short haystacks or unsupported needles fall back to the naive algorithm - if (Size < 16 || N > 255) { - do { - if (std::memcmp(Start, Needle, N) == 0) - return Start - Data; - ++Start; - } while (Start < Stop); - return npos; - } - - // Build the bad char heuristic table, with uint8_t to reduce cache thrashing. - uint8_t BadCharSkip[256]; - std::memset(BadCharSkip, N, 256); - for (unsigned i = 0; i != N-1; ++i) - BadCharSkip[(uint8_t)Str[i]] = N-1-i; - - do { - uint8_t Last = Start[N - 1]; - if (LLVM_UNLIKELY(Last == (uint8_t)Needle[N - 1])) - if (std::memcmp(Start, Needle, N - 1) == 0) - return Start - Data; - - // Otherwise skip the appropriate number of bytes. - Start += BadCharSkip[Last]; - } while (Start < Stop); - - return npos; -} - -size_t StringRef::find_lower(StringRef Str, size_t From) const noexcept { - StringRef This = substr(From); - while (This.size() >= Str.size()) { - if (This.startswith_lower(Str)) - return From; - This = This.drop_front(); - ++From; - } - return npos; -} - -size_t StringRef::rfind_lower(char C, size_t From) const noexcept { - From = std::min(From, Length); - size_t i = From; - while (i != 0) { - --i; - if (toLower(Data[i]) == toLower(C)) - return i; - } - return npos; -} - -/// rfind - Search for the last string \arg Str in the string. -/// -/// \return - The index of the last occurrence of \arg Str, or npos if not -/// found. -size_t StringRef::rfind(StringRef Str) const noexcept { - size_t N = Str.size(); - if (N > Length) - return npos; - for (size_t i = Length - N + 1, e = 0; i != e;) { - --i; - if (substr(i, N).equals(Str)) - return i; - } - return npos; -} - -size_t StringRef::rfind_lower(StringRef Str) const noexcept { - size_t N = Str.size(); - if (N > Length) - return npos; - for (size_t i = Length - N + 1, e = 0; i != e;) { - --i; - if (substr(i, N).equals_lower(Str)) - return i; - } - return npos; -} - -/// find_first_of - Find the first character in the string that is in \arg -/// Chars, or npos if not found. -/// -/// Note: O(size() + Chars.size()) -StringRef::size_type StringRef::find_first_of(StringRef Chars, - size_t From) const noexcept { - std::bitset<1 << CHAR_BIT> CharBits; - for (size_type i = 0; i != Chars.size(); ++i) - CharBits.set((unsigned char)Chars[i]); - - for (size_type i = std::min(From, Length), e = Length; i != e; ++i) - if (CharBits.test((unsigned char)Data[i])) - return i; - return npos; -} - -/// find_first_not_of - Find the first character in the string that is not -/// \arg C or npos if not found. -StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const noexcept { - for (size_type i = std::min(From, Length), e = Length; i != e; ++i) - if (Data[i] != C) - return i; - return npos; -} - -/// find_first_not_of - Find the first character in the string that is not -/// in the string \arg Chars, or npos if not found. -/// -/// Note: O(size() + Chars.size()) -StringRef::size_type StringRef::find_first_not_of(StringRef Chars, - size_t From) const noexcept { - std::bitset<1 << CHAR_BIT> CharBits; - for (size_type i = 0; i != Chars.size(); ++i) - CharBits.set((unsigned char)Chars[i]); - - for (size_type i = std::min(From, Length), e = Length; i != e; ++i) - if (!CharBits.test((unsigned char)Data[i])) - return i; - return npos; -} - -/// find_last_of - Find the last character in the string that is in \arg C, -/// or npos if not found. -/// -/// Note: O(size() + Chars.size()) -StringRef::size_type StringRef::find_last_of(StringRef Chars, - size_t From) const noexcept { - std::bitset<1 << CHAR_BIT> CharBits; - for (size_type i = 0; i != Chars.size(); ++i) - CharBits.set((unsigned char)Chars[i]); - - for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i) - if (CharBits.test((unsigned char)Data[i])) - return i; - return npos; -} - -/// find_last_not_of - Find the last character in the string that is not -/// \arg C, or npos if not found. -StringRef::size_type StringRef::find_last_not_of(char C, size_t From) const noexcept { - for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i) - if (Data[i] != C) - return i; - return npos; -} - -/// find_last_not_of - Find the last character in the string that is not in -/// \arg Chars, or npos if not found. -/// -/// Note: O(size() + Chars.size()) -StringRef::size_type StringRef::find_last_not_of(StringRef Chars, - size_t From) const noexcept { - std::bitset<1 << CHAR_BIT> CharBits; - for (size_type i = 0, e = Chars.size(); i != e; ++i) - CharBits.set((unsigned char)Chars[i]); - - for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i) - if (!CharBits.test((unsigned char)Data[i])) - return i; - return npos; -} - -void StringRef::split(SmallVectorImpl &A, - StringRef Separator, int MaxSplit, - bool KeepEmpty) const { - StringRef S = *this; - - // Count down from MaxSplit. When MaxSplit is -1, this will just split - // "forever". This doesn't support splitting more than 2^31 times - // intentionally; if we ever want that we can make MaxSplit a 64-bit integer - // but that seems unlikely to be useful. - while (MaxSplit-- != 0) { - size_t Idx = S.find(Separator); - if (Idx == npos) - break; - - // Push this split. - if (KeepEmpty || Idx > 0) - A.push_back(S.slice(0, Idx)); - - // Jump forward. - S = S.slice(Idx + Separator.size(), npos); - } - - // Push the tail. - if (KeepEmpty || !S.empty()) - A.push_back(S); -} - -void StringRef::split(SmallVectorImpl &A, char Separator, - int MaxSplit, bool KeepEmpty) const { - StringRef S = *this; - - // Count down from MaxSplit. When MaxSplit is -1, this will just split - // "forever". This doesn't support splitting more than 2^31 times - // intentionally; if we ever want that we can make MaxSplit a 64-bit integer - // but that seems unlikely to be useful. - while (MaxSplit-- != 0) { - size_t Idx = S.find(Separator); - if (Idx == npos) - break; - - // Push this split. - if (KeepEmpty || Idx > 0) - A.push_back(S.slice(0, Idx)); - - // Jump forward. - S = S.slice(Idx + 1, npos); - } - - // Push the tail. - if (KeepEmpty || !S.empty()) - A.push_back(S); -} - -//===----------------------------------------------------------------------===// -// Helpful Algorithms -//===----------------------------------------------------------------------===// - -/// count - Return the number of non-overlapped occurrences of \arg Str in -/// the string. -size_t StringRef::count(StringRef Str) const noexcept { - size_t Count = 0; - size_t N = Str.size(); - if (N > Length) - return 0; - for (size_t i = 0, e = Length - N + 1; i != e; ++i) - if (substr(i, N).equals(Str)) - ++Count; - return Count; -} - -static unsigned GetAutoSenseRadix(StringRef &Str) noexcept { - if (Str.empty()) - return 10; - - if (Str.startswith("0x") || Str.startswith("0X")) { - Str = Str.substr(2); - return 16; - } - - if (Str.startswith("0b") || Str.startswith("0B")) { - Str = Str.substr(2); - return 2; - } - - if (Str.startswith("0o")) { - Str = Str.substr(2); - return 8; - } - - if (Str[0] == '0' && Str.size() > 1 && isDigit(Str[1])) { - Str = Str.substr(1); - return 8; - } - - return 10; -} - -bool wpi::consumeUnsignedInteger(StringRef &Str, unsigned Radix, - unsigned long long &Result) noexcept { - // Autosense radix if not specified. - if (Radix == 0) - Radix = GetAutoSenseRadix(Str); - - // Empty strings (after the radix autosense) are invalid. - if (Str.empty()) return true; - - // Parse all the bytes of the string given this radix. Watch for overflow. - StringRef Str2 = Str; - Result = 0; - while (!Str2.empty()) { - unsigned CharVal; - if (Str2[0] >= '0' && Str2[0] <= '9') - CharVal = Str2[0] - '0'; - else if (Str2[0] >= 'a' && Str2[0] <= 'z') - CharVal = Str2[0] - 'a' + 10; - else if (Str2[0] >= 'A' && Str2[0] <= 'Z') - CharVal = Str2[0] - 'A' + 10; - else - break; - - // If the parsed value is larger than the integer radix, we cannot - // consume any more characters. - if (CharVal >= Radix) - break; - - // Add in this character. - unsigned long long PrevResult = Result; - Result = Result * Radix + CharVal; - - // Check for overflow by shifting back and seeing if bits were lost. - if (Result / Radix < PrevResult) - return true; - - Str2 = Str2.substr(1); - } - - // We consider the operation a failure if no characters were consumed - // successfully. - if (Str.size() == Str2.size()) - return true; - - Str = Str2; - return false; -} - -bool wpi::consumeSignedInteger(StringRef &Str, unsigned Radix, - long long &Result) noexcept { - unsigned long long ULLVal; - - // Handle positive strings first. - if (Str.empty() || Str.front() != '-') { - if (consumeUnsignedInteger(Str, Radix, ULLVal) || - // Check for value so large it overflows a signed value. - (long long)ULLVal < 0) - return true; - Result = ULLVal; - return false; - } - - // Get the positive part of the value. - StringRef Str2 = Str.drop_front(1); - if (consumeUnsignedInteger(Str2, Radix, ULLVal) || - // Reject values so large they'd overflow as negative signed, but allow - // "-0". This negates the unsigned so that the negative isn't undefined - // on signed overflow. - (long long)-ULLVal > 0) - return true; - - Str = Str2; - Result = -ULLVal; - return false; -} - -/// GetAsUnsignedInteger - Workhorse method that converts a integer character -/// sequence of radix up to 36 to an unsigned long long value. -bool wpi::getAsUnsignedInteger(StringRef Str, unsigned Radix, - unsigned long long &Result) noexcept { - if (consumeUnsignedInteger(Str, Radix, Result)) - return true; - - // For getAsUnsignedInteger, we require the whole string to be consumed or - // else we consider it a failure. - return !Str.empty(); -} - -bool wpi::getAsSignedInteger(StringRef Str, unsigned Radix, - long long &Result) noexcept { - if (consumeSignedInteger(Str, Radix, Result)) - return true; - - // For getAsSignedInteger, we require the whole string to be consumed or else - // we consider it a failure. - return !Str.empty(); -} - -std::ostream &wpi::operator<<(std::ostream &os, StringRef string) { - os.write(string.data(), string.size()); - return os; -} - -// Implementation of StringRef hashing. -hash_code wpi::hash_value(StringRef S) { - return hash_combine_range(S.begin(), S.end()); -} diff --git a/wpiutil/src/main/native/cpp/llvm/Twine.cpp b/wpiutil/src/main/native/cpp/llvm/Twine.cpp deleted file mode 100644 index b8dd7c308e..0000000000 --- a/wpiutil/src/main/native/cpp/llvm/Twine.cpp +++ /dev/null @@ -1,176 +0,0 @@ -//===-- Twine.cpp - Fast Temporary String Concatenation -------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "wpi/Twine.h" -#include "wpi/SmallString.h" -#include "wpi/raw_ostream.h" -using namespace wpi; - -std::string Twine::str() const { - // If we're storing only a std::string, just return it. - if (LHSKind == StdStringKind && RHSKind == EmptyKind) - return *LHS.stdString; - - // Otherwise, flatten and copy the contents first. - SmallString<256> Vec; - return toStringRef(Vec).str(); -} - -void Twine::toVector(SmallVectorImpl &Out) const { - raw_svector_ostream OS(Out); - print(OS); -} - -StringRef Twine::toNullTerminatedStringRef(SmallVectorImpl &Out) const { - if (isUnary()) { - switch (getLHSKind()) { - case CStringKind: - // Already null terminated, yay! - return StringRef(LHS.cString); - case StdStringKind: { - const std::string *str = LHS.stdString; - return StringRef(str->c_str(), str->size()); - } - default: - break; - } - } - toVector(Out); - Out.push_back(0); - Out.pop_back(); - return StringRef(Out.data(), Out.size()); -} - -void Twine::printOneChild(raw_ostream &OS, Child Ptr, - NodeKind Kind) const { - switch (Kind) { - case Twine::NullKind: break; - case Twine::EmptyKind: break; - case Twine::TwineKind: - Ptr.twine->print(OS); - break; - case Twine::CStringKind: - OS << Ptr.cString; - break; - case Twine::StdStringKind: - OS << *Ptr.stdString; - break; - case Twine::StringRefKind: - OS << *Ptr.stringRef; - break; - case Twine::StringViewKind: - OS << *Ptr.stringView; - break; - case Twine::SmallStringKind: - OS << *Ptr.smallString; - break; - case Twine::CharKind: - OS << Ptr.character; - break; - case Twine::DecUIKind: - OS << Ptr.decUI; - break; - case Twine::DecIKind: - OS << Ptr.decI; - break; - case Twine::DecULKind: - OS << *Ptr.decUL; - break; - case Twine::DecLKind: - OS << *Ptr.decL; - break; - case Twine::DecULLKind: - OS << *Ptr.decULL; - break; - case Twine::DecLLKind: - OS << *Ptr.decLL; - break; - case Twine::UHexKind: - OS.write_hex(*Ptr.uHex); - break; - } -} - -void Twine::printOneChildRepr(raw_ostream &OS, Child Ptr, - NodeKind Kind) const { - switch (Kind) { - case Twine::NullKind: - OS << "null"; break; - case Twine::EmptyKind: - OS << "empty"; break; - case Twine::TwineKind: - OS << "rope:"; - Ptr.twine->printRepr(OS); - break; - case Twine::CStringKind: - OS << "cstring:\"" - << Ptr.cString << "\""; - break; - case Twine::StdStringKind: - OS << "std::string:\"" - << Ptr.stdString << "\""; - break; - case Twine::StringRefKind: - OS << "stringref:\"" - << Ptr.stringRef << "\""; - break; - case Twine::StringViewKind: - OS << "std::string_view:\"" - << Ptr.stringView << "\""; - break; - case Twine::SmallStringKind: - OS << "smallstring:\"" << *Ptr.smallString << "\""; - break; - case Twine::CharKind: - OS << "char:\"" << Ptr.character << "\""; - break; - case Twine::DecUIKind: - OS << "decUI:\"" << Ptr.decUI << "\""; - break; - case Twine::DecIKind: - OS << "decI:\"" << Ptr.decI << "\""; - break; - case Twine::DecULKind: - OS << "decUL:\"" << *Ptr.decUL << "\""; - break; - case Twine::DecLKind: - OS << "decL:\"" << *Ptr.decL << "\""; - break; - case Twine::DecULLKind: - OS << "decULL:\"" << *Ptr.decULL << "\""; - break; - case Twine::DecLLKind: - OS << "decLL:\"" << *Ptr.decLL << "\""; - break; - case Twine::UHexKind: - OS << "uhex:\"" << Ptr.uHex << "\""; - break; - } -} - -void Twine::print(raw_ostream &OS) const { - printOneChild(OS, LHS, getLHSKind()); - printOneChild(OS, RHS, getRHSKind()); -} - -void Twine::printRepr(raw_ostream &OS) const { - OS << "(Twine "; - printOneChildRepr(OS, LHS, getLHSKind()); - OS << " "; - printOneChildRepr(OS, RHS, getRHSKind()); - OS << ")"; -} - -LLVM_DUMP_METHOD void Twine::dump() const { - print(errs()); -} - -LLVM_DUMP_METHOD void Twine::dumpRepr() const { - printRepr(errs()); -} diff --git a/wpiutil/src/main/native/cpp/llvm/Windows/WindowsSupport.h b/wpiutil/src/main/native/cpp/llvm/Windows/WindowsSupport.h index d830e330ec..7307337977 100644 --- a/wpiutil/src/main/native/cpp/llvm/Windows/WindowsSupport.h +++ b/wpiutil/src/main/native/cpp/llvm/Windows/WindowsSupport.h @@ -36,13 +36,12 @@ #include "wpi/SmallVector.h" #include "wpi/StringExtras.h" -#include "wpi/StringRef.h" -#include "wpi/Twine.h" #include "wpi/Chrono.h" #include "wpi/Compiler.h" #include "wpi/VersionTuple.h" #include #include +#include #include #define WIN32_NO_STATUS #include diff --git a/wpiutil/src/main/native/cpp/llvm/raw_ostream.cpp b/wpiutil/src/main/native/cpp/llvm/raw_ostream.cpp index 9c7e72dd64..b33df58266 100644 --- a/wpiutil/src/main/native/cpp/llvm/raw_ostream.cpp +++ b/wpiutil/src/main/native/cpp/llvm/raw_ostream.cpp @@ -22,9 +22,7 @@ #include "wpi/StringExtras.h" #include "wpi/Compiler.h" #include "wpi/ErrorHandling.h" -#include "wpi/Format.h" #include "wpi/MathExtras.h" -#include "wpi/NativeFormatting.h" #include "wpi/WindowsError.h" #include "wpi/fs.h" #include @@ -113,32 +111,7 @@ void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, assert(OutBufStart <= OutBufEnd && "Invalid size!"); } -raw_ostream &raw_ostream::operator<<(unsigned long N) { - write_integer(*this, static_cast(N), 0, IntegerStyle::Integer); - return *this; -} - -raw_ostream &raw_ostream::operator<<(long N) { - write_integer(*this, static_cast(N), 0, IntegerStyle::Integer); - return *this; -} - -raw_ostream &raw_ostream::operator<<(unsigned long long N) { - write_integer(*this, static_cast(N), 0, IntegerStyle::Integer); - return *this; -} - -raw_ostream &raw_ostream::operator<<(long long N) { - write_integer(*this, static_cast(N), 0, IntegerStyle::Integer); - return *this; -} - -raw_ostream &raw_ostream::write_hex(unsigned long long N) { - wpi::write_hex(*this, N, HexPrintStyle::Lower); - return *this; -} - -raw_ostream &raw_ostream::write_escaped(StringRef Str, +raw_ostream &raw_ostream::write_escaped(std::string_view Str, bool UseHexEscapes) { for (unsigned char c : Str) { switch (c) { @@ -178,16 +151,6 @@ raw_ostream &raw_ostream::write_escaped(StringRef Str, return *this; } -raw_ostream &raw_ostream::operator<<(const void *P) { - wpi::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower); - return *this; -} - -raw_ostream &raw_ostream::operator<<(double N) { - wpi::write_double(*this, N, FloatStyle::Exponent); - return *this; -} - void raw_ostream::flush_nonempty() { assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty."); size_t Length = OutBufCur - OutBufStart; @@ -277,170 +240,6 @@ void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) { OutBufCur += Size; } -// Formatted output. -raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) { - // If we have more than a few bytes left in our output buffer, try - // formatting directly onto its end. - size_t NextBufferSize = 127; - size_t BufferBytesLeft = OutBufEnd - OutBufCur; - if (BufferBytesLeft > 3) { - size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft); - - // Common case is that we have plenty of space. - if (BytesUsed <= BufferBytesLeft) { - OutBufCur += BytesUsed; - return *this; - } - - // Otherwise, we overflowed and the return value tells us the size to try - // again with. - NextBufferSize = BytesUsed; - } - - // If we got here, we didn't have enough space in the output buffer for the - // string. Try printing into a SmallVector that is resized to have enough - // space. Iterate until we win. - SmallVector V; - - while (true) { - V.resize(NextBufferSize); - - // Try formatting into the SmallVector. - size_t BytesUsed = Fmt.print(V.data(), NextBufferSize); - - // If BytesUsed fit into the vector, we win. - if (BytesUsed <= NextBufferSize) - return write(V.data(), BytesUsed); - - // Otherwise, try again with a new size. - assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?"); - NextBufferSize = BytesUsed; - } -} - -raw_ostream &raw_ostream::operator<<(const FormattedString &FS) { - if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) { - this->operator<<(FS.Str); - return *this; - } - const size_t Difference = FS.Width - FS.Str.size(); - switch (FS.Justify) { - case FormattedString::JustifyLeft: - this->operator<<(FS.Str); - this->indent(Difference); - break; - case FormattedString::JustifyRight: - this->indent(Difference); - this->operator<<(FS.Str); - break; - case FormattedString::JustifyCenter: { - int PadAmount = Difference / 2; - this->indent(PadAmount); - this->operator<<(FS.Str); - this->indent(Difference - PadAmount); - break; - } - default: - wpi_unreachable("Bad Justification"); - } - return *this; -} - -raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) { - if (FN.Hex) { - HexPrintStyle Style; - if (FN.Upper && FN.HexPrefix) - Style = HexPrintStyle::PrefixUpper; - else if (FN.Upper && !FN.HexPrefix) - Style = HexPrintStyle::Upper; - else if (!FN.Upper && FN.HexPrefix) - Style = HexPrintStyle::PrefixLower; - else - Style = HexPrintStyle::Lower; - wpi::write_hex(*this, FN.HexValue, Style, FN.Width); - } else { - wpi::SmallString<16> Buffer; - wpi::raw_svector_ostream Stream(Buffer); - wpi::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer); - if (Buffer.size() < FN.Width) - indent(FN.Width - Buffer.size()); - (*this) << Buffer; - } - return *this; -} - -raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) { - if (FB.Bytes.empty()) - return *this; - - size_t LineIndex = 0; - auto Bytes = FB.Bytes; - const size_t Size = Bytes.size(); - HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower; - uint64_t OffsetWidth = 0; - if (FB.FirstByteOffset.has_value()) { - // Figure out how many nibbles are needed to print the largest offset - // represented by this data set, so that we can align the offset field - // to the right width. - size_t Lines = Size / FB.NumPerLine; - uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine; - unsigned Power = 0; - if (MaxOffset > 0) - Power = wpi::Log2_64_Ceil(MaxOffset); - OffsetWidth = std::max(4, wpi::alignTo(Power, 4) / 4); - } - - // The width of a block of data including all spaces for group separators. - unsigned NumByteGroups = - alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize; - unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1; - - while (!Bytes.empty()) { - indent(FB.IndentLevel); - - if (FB.FirstByteOffset.has_value()) { - uint64_t Offset = FB.FirstByteOffset.value(); - wpi::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth); - *this << ": "; - } - - auto Line = Bytes.take_front(FB.NumPerLine); - - size_t CharsPrinted = 0; - // Print the hex bytes for this line in groups - for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) { - if (I && (I % FB.ByteGroupSize) == 0) { - ++CharsPrinted; - *this << " "; - } - wpi::write_hex(*this, Line[I], HPS, 2); - } - - if (FB.ASCII) { - // Print any spaces needed for any bytes that we didn't print on this - // line so that the ASCII bytes are correctly aligned. - assert(BlockCharWidth >= CharsPrinted); - indent(BlockCharWidth - CharsPrinted + 2); - *this << "|"; - - // Print the ASCII char values for each byte on this line - for (uint8_t Byte : Line) { - if (isPrint(Byte)) - *this << static_cast(Byte); - else - *this << '.'; - } - *this << '|'; - } - - Bytes = Bytes.drop_front(Line.size()); - LineIndex += Line.size(); - if (LineIndex < Size) - *this << '\n'; - } - return *this; -} - template static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) { static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, @@ -474,19 +273,11 @@ raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) { void raw_ostream::anchor() {} -//===----------------------------------------------------------------------===// -// Formatted Output -//===----------------------------------------------------------------------===// - -// Out of line virtual method. -void format_object_base::home() { -} - //===----------------------------------------------------------------------===// // raw_fd_ostream //===----------------------------------------------------------------------===// -static int getFD(StringRef Filename, std::error_code &EC, +static int getFD(std::string_view Filename, std::error_code &EC, fs::CreationDisposition Disp, fs::FileAccess Access, fs::OpenFlags Flags) { assert((Access & fs::FA_Write) && @@ -521,25 +312,25 @@ static int getFD(StringRef Filename, std::error_code &EC, return FD; } -raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC) +raw_fd_ostream::raw_fd_ostream(std::string_view Filename, std::error_code &EC) : raw_fd_ostream(Filename, EC, fs::CD_CreateAlways, fs::FA_Write, fs::OF_None) {} -raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, +raw_fd_ostream::raw_fd_ostream(std::string_view Filename, std::error_code &EC, fs::CreationDisposition Disp) : raw_fd_ostream(Filename, EC, Disp, fs::FA_Write, fs::OF_None) {} -raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, +raw_fd_ostream::raw_fd_ostream(std::string_view Filename, std::error_code &EC, fs::FileAccess Access) : raw_fd_ostream(Filename, EC, fs::CD_CreateAlways, Access, fs::OF_None) {} -raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, +raw_fd_ostream::raw_fd_ostream(std::string_view Filename, std::error_code &EC, fs::OpenFlags Flags) : raw_fd_ostream(Filename, EC, fs::CD_CreateAlways, fs::FA_Write, Flags) {} -raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, +raw_fd_ostream::raw_fd_ostream(std::string_view Filename, std::error_code &EC, fs::CreationDisposition Disp, fs::FileAccess Access, fs::OpenFlags Flags) @@ -622,7 +413,7 @@ raw_fd_ostream::~raw_fd_ostream() { // the input is UTF-8 or transcode from the local codepage to UTF-8 before // quoting it. If they don't, this may mess up the encoding, but this is still // probably the best compromise we can make. -static bool write_console_impl(int FD, StringRef Data) { +static bool write_console_impl(int FD, std::string_view Data) { SmallVector WideText; // Fall back to ::write if it wasn't valid UTF-8. @@ -665,7 +456,7 @@ void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { // If this is a Windows console device, try re-encoding from UTF-8 to UTF-16 // and using WriteConsoleW. If that fails, fall back to plain write(). if (IsWindowsConsole) - if (write_console_impl(FD, StringRef(Ptr, Size))) + if (write_console_impl(FD, std::string_view(Ptr, Size))) return; #endif diff --git a/wpiutil/src/main/native/cpp/raw_istream.cpp b/wpiutil/src/main/native/cpp/raw_istream.cpp index 4cf4dfab28..a179b982ba 100644 --- a/wpiutil/src/main/native/cpp/raw_istream.cpp +++ b/wpiutil/src/main/native/cpp/raw_istream.cpp @@ -14,9 +14,9 @@ #include #include +#include #include "wpi/SmallVector.h" -#include "wpi/StringRef.h" #include "wpi/fs.h" #if defined(_MSC_VER) @@ -33,13 +33,13 @@ using namespace wpi; -StringRef raw_istream::getline(SmallVectorImpl& buf, int maxLen) { +std::string_view raw_istream::getline(SmallVectorImpl& buf, int maxLen) { buf.clear(); for (int i = 0; i < maxLen; ++i) { char c; read(c); if (has_error()) { - return StringRef{buf.data(), buf.size()}; + return {buf.data(), buf.size()}; } if (c == '\r') { continue; @@ -49,7 +49,7 @@ StringRef raw_istream::getline(SmallVectorImpl& buf, int maxLen) { break; } } - return StringRef{buf.data(), buf.size()}; + return {buf.data(), buf.size()}; } void raw_mem_istream::close() {} @@ -69,16 +69,16 @@ void raw_mem_istream::read_impl(void* data, size_t len) { set_read_count(len); } -static int getFD(const Twine& Filename, std::error_code& EC) { +static int getFD(std::string_view Filename, std::error_code& EC) { // Handle "-" as stdin. Note that when we do this, we consider ourself // the owner of stdin. This means that we can do things like close the // file descriptor when we're done and set the "binary" flag globally. - if (Filename.isSingleStringRef() && Filename.getSingleStringRef() == "-") { + if (Filename == "-") { EC = std::error_code(); return STDIN_FILENO; } - fs::file_t F = fs::OpenFileForRead(Filename.str(), EC); + fs::file_t F = fs::OpenFileForRead(Filename, EC); if (EC) { return -1; } @@ -89,7 +89,7 @@ static int getFD(const Twine& Filename, std::error_code& EC) { return FD; } -raw_fd_istream::raw_fd_istream(const Twine& filename, std::error_code& ec, +raw_fd_istream::raw_fd_istream(std::string_view filename, std::error_code& ec, size_t bufSize) : raw_fd_istream(getFD(filename, ec), true, bufSize) {} diff --git a/wpiutil/src/main/native/cpp/sha1.cpp b/wpiutil/src/main/native/cpp/sha1.cpp index 3ad297a4dc..5319afb1db 100644 --- a/wpiutil/src/main/native/cpp/sha1.cpp +++ b/wpiutil/src/main/native/cpp/sha1.cpp @@ -216,7 +216,7 @@ SHA1::SHA1() { reset(digest, buf_size, transforms); } -void SHA1::Update(StringRef s) { +void SHA1::Update(std::string_view s) { raw_mem_istream is(makeArrayRef(s.data(), s.size())); Update(is); } @@ -293,7 +293,7 @@ std::string SHA1::Final() { return os.str(); } -StringRef SHA1::Final(SmallVectorImpl& buf) { +std::string_view SHA1::Final(SmallVectorImpl& buf) { raw_svector_ostream os(buf); finalize(digest, buffer, buf_size, transforms, os, true); @@ -301,7 +301,7 @@ StringRef SHA1::Final(SmallVectorImpl& buf) { return os.str(); } -StringRef SHA1::RawFinal(SmallVectorImpl& buf) { +std::string_view SHA1::RawFinal(SmallVectorImpl& buf) { raw_svector_ostream os(buf); finalize(digest, buffer, buf_size, transforms, os, false); @@ -309,7 +309,7 @@ StringRef SHA1::RawFinal(SmallVectorImpl& buf) { return os.str(); } -std::string SHA1::FromFile(StringRef filename) { +std::string SHA1::FromFile(std::string_view filename) { std::error_code ec; raw_fd_istream stream(filename, ec); SHA1 checksum; diff --git a/wpiutil/src/main/native/cpp/uv/FsEvent.cpp b/wpiutil/src/main/native/cpp/uv/FsEvent.cpp index 0b9dfe85ef..3c83d1d00a 100644 --- a/wpiutil/src/main/native/cpp/uv/FsEvent.cpp +++ b/wpiutil/src/main/native/cpp/uv/FsEvent.cpp @@ -22,8 +22,8 @@ std::shared_ptr FsEvent::Create(Loop& loop) { return h; } -void FsEvent::Start(const Twine& path, unsigned int flags) { - SmallString<128> pathBuf; +void FsEvent::Start(std::string_view path, unsigned int flags) { + SmallString<128> pathBuf{path}; Invoke( &uv_fs_event_start, GetRaw(), [](uv_fs_event_t* handle, const char* filename, int events, int status) { @@ -34,7 +34,7 @@ void FsEvent::Start(const Twine& path, unsigned int flags) { h.fsEvent(filename, events); } }, - path.toNullTerminatedStringRef(pathBuf).data(), flags); + pathBuf.c_str(), flags); } std::string FsEvent::GetPath() { diff --git a/wpiutil/src/main/native/cpp/uv/GetAddrInfo.cpp b/wpiutil/src/main/native/cpp/uv/GetAddrInfo.cpp index cb0a679e61..e4f7aa4f53 100644 --- a/wpiutil/src/main/native/cpp/uv/GetAddrInfo.cpp +++ b/wpiutil/src/main/native/cpp/uv/GetAddrInfo.cpp @@ -4,6 +4,7 @@ #include "wpi/uv/GetAddrInfo.h" +#include "wpi/SmallString.h" #include "wpi/uv/Loop.h" #include "wpi/uv/util.h" @@ -14,10 +15,10 @@ GetAddrInfoReq::GetAddrInfoReq() { } void GetAddrInfo(Loop& loop, const std::shared_ptr& req, - const Twine& node, const Twine& service, + std::string_view node, std::string_view service, const addrinfo* hints) { - SmallVector nodeStr; - SmallVector serviceStr; + SmallString<128> nodeStr{node}; + SmallString<128> serviceStr{service}; int err = uv_getaddrinfo( loop.GetRaw(), req->GetRaw(), [](uv_getaddrinfo_t* req, int status, addrinfo* res) { @@ -30,10 +31,8 @@ void GetAddrInfo(Loop& loop, const std::shared_ptr& req, uv_freeaddrinfo(res); h.Release(); // this is always a one-shot }, - node.isNull() ? nullptr : node.toNullTerminatedStringRef(nodeStr).data(), - service.isNull() ? nullptr - : service.toNullTerminatedStringRef(serviceStr).data(), - hints); + node.empty() ? nullptr : nodeStr.c_str(), + service.empty() ? nullptr : serviceStr.c_str(), hints); if (err < 0) { loop.ReportError(err); } else { @@ -42,7 +41,7 @@ void GetAddrInfo(Loop& loop, const std::shared_ptr& req, } void GetAddrInfo(Loop& loop, std::function callback, - const Twine& node, const Twine& service, + std::string_view node, std::string_view service, const addrinfo* hints) { auto req = std::make_shared(); req->resolved.connect(callback); diff --git a/wpiutil/src/main/native/cpp/uv/GetNameInfo.cpp b/wpiutil/src/main/native/cpp/uv/GetNameInfo.cpp index 701fc77fb7..7bc412d6ff 100644 --- a/wpiutil/src/main/native/cpp/uv/GetNameInfo.cpp +++ b/wpiutil/src/main/native/cpp/uv/GetNameInfo.cpp @@ -44,7 +44,7 @@ void GetNameInfo(Loop& loop, } void GetNameInfo4(Loop& loop, const std::shared_ptr& req, - const Twine& ip, unsigned int port, int flags) { + std::string_view ip, unsigned int port, int flags) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); if (err < 0) { @@ -56,7 +56,7 @@ void GetNameInfo4(Loop& loop, const std::shared_ptr& req, void GetNameInfo4(Loop& loop, std::function callback, - const Twine& ip, unsigned int port, int flags) { + std::string_view ip, unsigned int port, int flags) { sockaddr_in addr; int err = NameToAddr(ip, port, &addr); if (err < 0) { @@ -67,7 +67,7 @@ void GetNameInfo4(Loop& loop, } void GetNameInfo6(Loop& loop, const std::shared_ptr& req, - const Twine& ip, unsigned int port, int flags) { + std::string_view ip, unsigned int port, int flags) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); if (err < 0) { @@ -79,7 +79,7 @@ void GetNameInfo6(Loop& loop, const std::shared_ptr& req, void GetNameInfo6(Loop& loop, std::function callback, - const Twine& ip, unsigned int port, int flags) { + std::string_view ip, unsigned int port, int flags) { sockaddr_in6 addr; int err = NameToAddr(ip, port, &addr); if (err < 0) { diff --git a/wpiutil/src/main/native/cpp/uv/NameToAddr.cpp b/wpiutil/src/main/native/cpp/uv/NameToAddr.cpp index 55ec9c14fe..23ec6da6fa 100644 --- a/wpiutil/src/main/native/cpp/uv/NameToAddr.cpp +++ b/wpiutil/src/main/native/cpp/uv/NameToAddr.cpp @@ -10,53 +10,49 @@ namespace wpi::uv { -int NameToAddr(const Twine& ip, unsigned int port, sockaddr_in* addr) { - SmallString<128> tmp; - StringRef ipStr = ip.toNullTerminatedStringRef(tmp); - if (ipStr.empty()) { +int NameToAddr(std::string_view ip, unsigned int port, sockaddr_in* addr) { + if (ip.empty()) { std::memset(addr, 0, sizeof(sockaddr_in)); addr->sin_family = PF_INET; addr->sin_addr.s_addr = INADDR_ANY; addr->sin_port = htons(port); return 0; } else { - return uv_ip4_addr(ipStr.data(), port, addr); + SmallString<128> ipBuf{ip}; + return uv_ip4_addr(ipBuf.c_str(), port, addr); } } -int NameToAddr(const Twine& ip, unsigned int port, sockaddr_in6* addr) { - SmallString<128> tmp; - StringRef ipStr = ip.toNullTerminatedStringRef(tmp); - if (ipStr.empty()) { +int NameToAddr(std::string_view ip, unsigned int port, sockaddr_in6* addr) { + if (ip.empty()) { std::memset(addr, 0, sizeof(sockaddr_in6)); addr->sin6_family = PF_INET6; addr->sin6_addr = in6addr_any; addr->sin6_port = htons(port); return 0; } else { - return uv_ip6_addr(ipStr.data(), port, addr); + SmallString<128> ipBuf{ip}; + return uv_ip6_addr(ipBuf.c_str(), port, addr); } } -int NameToAddr(const Twine& ip, in_addr* addr) { - SmallString<128> tmp; - StringRef ipStr = ip.toNullTerminatedStringRef(tmp); - if (ipStr.empty()) { +int NameToAddr(std::string_view ip, in_addr* addr) { + if (ip.empty()) { addr->s_addr = INADDR_ANY; return 0; } else { - return uv_inet_pton(AF_INET, ipStr.data(), addr); + SmallString<128> ipBuf{ip}; + return uv_inet_pton(AF_INET, ipBuf.c_str(), addr); } } -int NameToAddr(const Twine& ip, in6_addr* addr) { - SmallString<128> tmp; - StringRef ipStr = ip.toNullTerminatedStringRef(tmp); - if (ipStr.empty()) { +int NameToAddr(std::string_view ip, in6_addr* addr) { + if (ip.empty()) { *addr = in6addr_any; return 0; } else { - return uv_inet_pton(AF_INET6, ipStr.data(), addr); + SmallString<128> ipBuf{ip}; + return uv_inet_pton(AF_INET6, ipBuf.c_str(), addr); } } diff --git a/wpiutil/src/main/native/cpp/uv/Pipe.cpp b/wpiutil/src/main/native/cpp/uv/Pipe.cpp index 4834d69988..ae4f6ef842 100644 --- a/wpiutil/src/main/native/cpp/uv/Pipe.cpp +++ b/wpiutil/src/main/native/cpp/uv/Pipe.cpp @@ -62,17 +62,15 @@ Pipe* Pipe::DoAccept() { return Accept().get(); } -void Pipe::Bind(const Twine& name) { - SmallString<128> nameBuf; - Invoke(&uv_pipe_bind, GetRaw(), - name.toNullTerminatedStringRef(nameBuf).data()); +void Pipe::Bind(std::string_view name) { + SmallString<128> nameBuf{name}; + Invoke(&uv_pipe_bind, GetRaw(), nameBuf.c_str()); } -void Pipe::Connect(const Twine& name, +void Pipe::Connect(std::string_view name, const std::shared_ptr& req) { - SmallString<128> nameBuf; - uv_pipe_connect(req->GetRaw(), GetRaw(), - name.toNullTerminatedStringRef(nameBuf).data(), + SmallString<128> nameBuf{name}; + uv_pipe_connect(req->GetRaw(), GetRaw(), nameBuf.c_str(), [](uv_connect_t* req, int status) { auto& h = *static_cast(req->data); if (status < 0) { @@ -85,7 +83,7 @@ void Pipe::Connect(const Twine& name, req->Keep(); } -void Pipe::Connect(const Twine& name, std::function callback) { +void Pipe::Connect(std::string_view name, std::function callback) { auto req = std::make_shared(); req->connected.connect(callback); Connect(name, req); diff --git a/wpiutil/src/main/native/cpp/uv/Process.cpp b/wpiutil/src/main/native/cpp/uv/Process.cpp index 90be6d5bed..f41f492a6c 100644 --- a/wpiutil/src/main/native/cpp/uv/Process.cpp +++ b/wpiutil/src/main/native/cpp/uv/Process.cpp @@ -10,7 +10,7 @@ namespace wpi::uv { -std::shared_ptr Process::SpawnArray(Loop& loop, const Twine& file, +std::shared_ptr Process::SpawnArray(Loop& loop, std::string_view file, ArrayRef