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

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

View File

@@ -7,6 +7,7 @@
#include <cstring>
#include <FRC_FPGA_ChipObject/fpgainterfacecapi/NiFpga_HMB.h>
#include <fmt/format.h>
#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;
}

View File

@@ -7,7 +7,7 @@
#include <string>
#include <thread>
#include <wpi/raw_ostream.h>
#include <fmt/format.h>
#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;

View File

@@ -4,6 +4,8 @@
#include "hal/CTREPCM.h"
#include <fmt/format.h>
#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;
}

View File

@@ -4,6 +4,8 @@
#include "hal/Counter.h"
#include <fmt/format.h>
#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);

View File

@@ -5,10 +5,9 @@
#include "hal/DIO.h"
#include <cmath>
#include <cstdio>
#include <thread>
#include <wpi/raw_ostream.h>
#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();

View File

@@ -4,6 +4,8 @@
#include "hal/Encoder.h"
#include <fmt/format.h>
#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<int>(encodingType)) +
" invalid.");
hal::SetLastError(status, fmt::format("Encoding type {} invalid.",
static_cast<int>(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) {

View File

@@ -6,6 +6,8 @@
#include <memory>
#include <fmt/format.h>
#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);

View File

@@ -7,13 +7,15 @@
#include <cstdlib>
#include <cstring>
#include <limits>
#include <string>
#include <string_view>
#include <FRC_NetworkCommunication/FRCComm.h>
#include <FRC_NetworkCommunication/NetCommRPCProxy_Occur.h>
#include <fmt/format.h>
#include <wpi/SafeThread.h>
#include <wpi/condition_variable.h>
#include <wpi/mutex.h>
#include <wpi/raw_ostream.h>
#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);

View File

@@ -9,6 +9,7 @@
#include <unistd.h>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <thread>
@@ -16,8 +17,8 @@
#include <FRC_NetworkCommunication/FRCComm.h>
#include <FRC_NetworkCommunication/LoadOut.h>
#include <FRC_NetworkCommunication/UsageReporting.h>
#include <fmt/format.h>
#include <wpi/mutex.h>
#include <wpi/raw_ostream.h>
#include <wpi/timestamp.h>
#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;

View File

@@ -6,15 +6,15 @@
#include <stdint.h>
#include <wpi/Twine.h>
#include <string_view>
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

View File

@@ -12,6 +12,8 @@
#include <cstring>
#include <fmt/format.h>
#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;

View File

@@ -4,6 +4,7 @@
#include "hal/PDP.h"
#include <fmt/format.h>
#include <wpi/mutex.h>
#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;
}

View File

@@ -4,11 +4,11 @@
#include "hal/PWM.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <thread>
#include <wpi/raw_ostream.h>
#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();

View File

@@ -11,10 +11,11 @@
#include <array>
#include <atomic>
#include <cstdio>
#include <cstring>
#include <fmt/format.h>
#include <wpi/mutex.h>
#include <wpi/raw_ostream.h>
#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<int>(port)));
hal::SetLastError(
status,
fmt::format("Serial port must be between 0 and {}. Requested {}",
kSpiMaxHandles, static_cast<int>(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<int>(port)));
status, fmt::format("Invalid SPI port {}", static_cast<int>(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<int>(port)));
hal::SetLastError(
status,
fmt::format("Serial port must be between 0 and {}. Requested {}",
kSpiMaxHandles, static_cast<int>(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<int>(port)));
hal::SetLastError(
status,
fmt::format("Serial port must be between 0 and {}. Requested {}",
kSpiMaxHandles, static_cast<int>(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<int>(port)));
hal::SetLastError(
status,
fmt::format("Serial port must be between 0 and {}. Requested {}",
kSpiMaxHandles, static_cast<int>(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<int>(port)));
hal::SetLastError(
status,
fmt::format("Serial port must be between 0 and {}. Requested {}",
kSpiMaxHandles, static_cast<int>(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;
}

View File

@@ -19,6 +19,8 @@
#include <string>
#include <thread>
#include <fmt/format.h>
#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<speed_t>(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;
}

View File

@@ -7,8 +7,9 @@
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string_view>
#include <wpi/StringRef.h>
#include <wpi/StringExtras.h>
#include <wpi/fs.h>
#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<char>& lhs,
const wpi::SmallVectorImpl<char>& 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<wpi::SmallString<16>, 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<wpi::StringRef, 16> pathSplitVec;
wpi::SmallVector<std::string_view, 16> 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;
}

View File

@@ -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 <fmt/format.h>
#include <wpi/SmallString.h>
#include <wpi/Twine.h>
#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

View File

@@ -4,9 +4,10 @@
#include "hal/cpp/fpga_clock.h"
#include <cstdio>
#include <limits>
#include <wpi/raw_ostream.h>
#include <fmt/format.h>
#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));

View File

@@ -6,9 +6,7 @@
#include <cassert>
#include <wpi/SmallString.h>
#include <wpi/jni_util.h>
#include <wpi/raw_ostream.h>
#include "HALUtil.h"
#include "edu_wpi_first_hal_CANAPIJNI.h"

View File

@@ -6,9 +6,7 @@
#include <cassert>
#include <wpi/SmallString.h>
#include <wpi/jni_util.h>
#include <wpi/raw_ostream.h>
#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<const char*>(buffer),
static_cast<size_t>(dataSize)});
std::string_view{reinterpret_cast<const char*>(buffer),
static_cast<size_t>(dataSize)});
}
/*

View File

@@ -9,6 +9,7 @@
#include <cassert>
#include <cstring>
#include <fmt/format.h>
#include <wpi/jni_util.h>
#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<int>(axes.count)
<< " Java Size: " << static_cast<int>(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<int>(axes.count), static_cast<int>(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<int>(povs.count)
<< " Java Size: " << static_cast<int>(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<int>(povs.count), static_cast<int>(javaSize)));
return 0;
}

View File

@@ -12,9 +12,8 @@
#include <cstring>
#include <string>
#include <wpi/SmallString.h>
#include <fmt/format.h>
#include <wpi/jni_util.h>
#include <wpi/raw_ostream.h>
#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, "<init>", "(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<const char*>(
matchInfo.gameSpecificMessage),
matchInfo.gameSpecificMessageSize}),
MakeJString(env,
{reinterpret_cast<const char*>(matchInfo.gameSpecificMessage),
matchInfo.gameSpecificMessageSize}),
static_cast<jint>(matchInfo.matchNumber),
static_cast<jint>(matchInfo.replayNumber),
static_cast<jint>(matchInfo.matchType));

View File

@@ -8,7 +8,7 @@
#include <jni.h>
#include <stdint.h>
#include <wpi/StringRef.h>
#include <string_view>
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);

View File

@@ -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<const char*, 8> 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<const char*, 8> carr;

View File

@@ -6,6 +6,8 @@
#include <jni.h>
#include <cstdio>
#include <wpi/jni_util.h>
#include "SimulatorJNI.h"
@@ -46,18 +48,18 @@ void BufferCallbackStore::performCallback(const char* name, uint8_t* buffer,
didAttachThread = true;
if (vm->AttachCurrentThread(reinterpret_cast<void**>(&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<const char*>(buffer),
static_cast<size_t>(length)});
auto toCallbackArr = MakeJByteArray(
env, std::string_view{reinterpret_cast<const char*>(buffer),
static_cast<size_t>(length)});
env->CallVoidMethod(m_call, sim::GetBufferCallback(), MakeJString(env, name),
toCallbackArr, static_cast<jint>(length));

View File

@@ -6,6 +6,8 @@
#include <jni.h>
#include <cstdio>
#include <wpi/jni_util.h>
#include "SimulatorJNI.h"
@@ -45,13 +47,13 @@ void CallbackStore::performCallback(const char* name, const HAL_Value* value) {
didAttachThread = true;
if (vm->AttachCurrentThread(reinterpret_cast<void**>(&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),

View File

@@ -6,6 +6,8 @@
#include <jni.h>
#include <cstdio>
#include <wpi/jni_util.h>
#include "SimulatorJNI.h"
@@ -47,18 +49,18 @@ void ConstBufferCallbackStore::performCallback(const char* name,
didAttachThread = true;
if (vm->AttachCurrentThread(reinterpret_cast<void**>(&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<const char*>(buffer),
static_cast<size_t>(length)});
auto toCallbackArr = MakeJByteArray(
env, std::string_view{reinterpret_cast<const char*>(buffer),
static_cast<size_t>(length)});
env->CallVoidMethod(m_call, sim::GetConstBufferCallback(),
MakeJString(env, name), toCallbackArr,

View File

@@ -6,6 +6,7 @@
#include <jni.h>
#include <cstdio>
#include <utility>
#include <wpi/jni_util.h>
@@ -134,13 +135,13 @@ void DeviceCallbackStore::performCallback(const char* name,
didAttachThread = true;
if (vm->AttachCurrentThread(reinterpret_cast<void**>(&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<void**>(&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);

View File

@@ -6,6 +6,8 @@
#include <jni.h>
#include <cstdio>
#include <wpi/jni_util.h>
#include "SimulatorJNI.h"
@@ -47,13 +49,13 @@ int32_t SpiReadAutoReceiveBufferCallbackStore::performCallback(
didAttachThread = true;
if (vm->AttachCurrentThread(reinterpret_cast<void**>(&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(

View File

@@ -72,4 +72,4 @@ Checks:
FormatStyle: file
CheckOptions:
- key: bugprone-dangling-handle
value: 'wpi::StringRef;wpi::Twine'
value: 'std::string_view'

View File

@@ -4,6 +4,8 @@
#include "hal/AddressableLED.h"
#include <fmt/format.h>
#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);

View File

@@ -13,9 +13,9 @@
#include <cstring>
#include <string>
#include <fmt/format.h>
#include <wpi/condition_variable.h>
#include <wpi/mutex.h>
#include <wpi/raw_ostream.h>
#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;
}

View File

@@ -4,12 +4,14 @@
#include "hal/Extensions.h"
#include <cstdio>
#include <string_view>
#include <vector>
#include <wpi/SmallString.h>
#include <wpi/StringRef.h>
#include <fmt/format.h>
#include <wpi/SmallVector.h>
#include <wpi/StringExtras.h>
#include <wpi/fs.h>
#include <wpi/raw_ostream.h>
#include <wpi/spinlock.h>
#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<wpi::StringRef, 2> libraries;
wpi::SmallVector<std::string_view, 2> 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;
}

View File

@@ -4,10 +4,10 @@
#include "hal/HAL.h"
#include <cstdio>
#include <vector>
#include <wpi/mutex.h>
#include <wpi/raw_ostream.h>
#include <wpi/spinlock.h>
#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;
}

View File

@@ -6,14 +6,14 @@
#include <stdint.h>
#include <wpi/Twine.h>
#include <string_view>
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

View File

@@ -8,6 +8,7 @@
#include <cstdio>
#include <thread>
#include <fmt/format.h>
#include <wpi/timestamp.h>
#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));
}
}

View File

@@ -4,6 +4,8 @@
#include "hal/PDP.h"
#include <fmt/format.h>
#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();

View File

@@ -4,8 +4,7 @@
#include "hal/SimDevice.h"
#include <wpi/SmallString.h>
#include <wpi/raw_ostream.h>
#include <fmt/format.h>
#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"

View File

@@ -6,6 +6,8 @@
#include <algorithm>
#include <wpi/StringExtras.h>
#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);
}
}

View File

@@ -11,6 +11,7 @@
#include <utility>
#include <vector>
#include <wpi/StringExtras.h>
#include <wpi/StringMap.h>
#include <wpi/UidVector.h>
#include <wpi/spinlock.h>
@@ -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>(u)...);
}
}